mirror of
https://gitea.com/gitea/gitea-mcp.git
synced 2026-08-30 03:57:45 +00:00
feat(docker): add /healthz endpoint and -healthcheck flag (#254)
Adds a Docker healthcheck and the small HTTP/CLI plumbing it needs. - Expose `GET /healthz` on the HTTP-mode server. - Add `-healthcheck` to dial `http://127.0.0.1:<port>/healthz` and exit with status. - Add a Dockerfile `HEALTHCHECK` instruction using `-healthcheck`. - Document HTTP-mode usage and stdio override guidance. Closes https://gitea.com/gitea/gitea-mcp/issues/146 Assisted by Codet. Reviewed-on: https://gitea.com/gitea/gitea-mcp/pulls/254 Reviewed-by: silverwind <2021+silverwind@noreply.gitea.com>
This commit is contained in:
@@ -32,4 +32,7 @@ USER nonroot:nonroot
|
|||||||
LABEL org.opencontainers.image.version="${VERSION}"
|
LABEL org.opencontainers.image.version="${VERSION}"
|
||||||
LABEL org.opencontainers.image.source="https://gitea.com/gitea/gitea-mcp"
|
LABEL org.opencontainers.image.source="https://gitea.com/gitea/gitea-mcp"
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||||
|
CMD ["/app/gitea-mcp", "-healthcheck"] || exit 1
|
||||||
|
|
||||||
CMD ["/app/gitea-mcp"]
|
CMD ["/app/gitea-mcp"]
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ The server supports MCP up to `2026-07-28` and negotiates down to the client's v
|
|||||||
|
|
||||||
HTTP is always stateless: `/mcp` accepts POST only, without `Mcp-Session-Id`, standalone SSE or `Last-Event-ID` resumability. Origins are validated, and reverse proxies must forward `Mcp-Protocol-Version`, `Mcp-Method` and `Mcp-Name` unchanged. `Authorization: Bearer <token>` and `Authorization: token <token>` pass a Gitea credential per request, which is credential passthrough rather than MCP OAuth.
|
HTTP is always stateless: `/mcp` accepts POST only, without `Mcp-Session-Id`, standalone SSE or `Last-Event-ID` resumability. Origins are validated, and reverse proxies must forward `Mcp-Protocol-Version`, `Mcp-Method` and `Mcp-Name` unchanged. `Authorization: Bearer <token>` and `Authorization: token <token>` pass a Gitea credential per request, which is credential passthrough rather than MCP OAuth.
|
||||||
|
|
||||||
|
HTTP mode also serves `/healthz`, which returns `200 OK` when the server is up. The Docker image's built-in `HEALTHCHECK` runs `gitea-mcp -healthcheck`, which dials `http://127.0.0.1:<port>/healthz` using the same `-p`/`-port` value (or `8080` by default) and exits `0` on success or `1` on failure. Stdio deployments do not serve `/healthz`, so override or disable the image's `HEALTHCHECK` when running in stdio mode.
|
||||||
|
|
||||||
### Claude Code
|
### Claude Code
|
||||||
|
|
||||||
Runs the server through `go run` and requires [Go](https://go.dev):
|
Runs the server through `go run` and requires [Go](https://go.dev):
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ Gitea 主机和访问令牌可通过命令行参数或环境变量提供,命
|
|||||||
|
|
||||||
HTTP 传输固定为无状态:`/mcp` 仅接受 POST,没有 `Mcp-Session-Id`、独立 SSE 和 `Last-Event-ID` 断点续传。服务器会验证来源,反向代理必须原样转发 `Mcp-Protocol-Version`、`Mcp-Method` 和 `Mcp-Name`。`Authorization: Bearer <令牌>` 和 `Authorization: token <令牌>` 会在每个请求中传递 Gitea 凭据,这是凭据透传,而不是 MCP OAuth。
|
HTTP 传输固定为无状态:`/mcp` 仅接受 POST,没有 `Mcp-Session-Id`、独立 SSE 和 `Last-Event-ID` 断点续传。服务器会验证来源,反向代理必须原样转发 `Mcp-Protocol-Version`、`Mcp-Method` 和 `Mcp-Name`。`Authorization: Bearer <令牌>` 和 `Authorization: token <令牌>` 会在每个请求中传递 Gitea 凭据,这是凭据透传,而不是 MCP OAuth。
|
||||||
|
|
||||||
|
HTTP 模式还提供 `/healthz` 端点,服务器正常运行时返回 `200 OK`。Docker 镜像内置的 `HEALTHCHECK` 会运行 `gitea-mcp -healthcheck`,它使用与 `-p`/`-port` 相同的端口(默认 `8080`)请求 `http://127.0.0.1:<端口>/healthz`,成功时退出码为 `0`,失败时为 `1`。stdio 部署不提供 `/healthz`,因此在 stdio 模式下运行时应覆盖或禁用镜像自带的 `HEALTHCHECK`。
|
||||||
|
|
||||||
### Claude Code
|
### Claude Code
|
||||||
|
|
||||||
通过 `go run` 运行服务器,需要安装 [Go](https://go.dev):
|
通过 `go run` 运行服务器,需要安装 [Go](https://go.dev):
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ Gitea 主機與存取令牌可透過命令列參數或環境變數提供,命
|
|||||||
|
|
||||||
HTTP 傳輸固定為無狀態:`/mcp` 只接受 POST,沒有 `Mcp-Session-Id`、獨立 SSE 與 `Last-Event-ID` 斷點續傳。伺服器會驗證來源,反向代理必須原樣轉發 `Mcp-Protocol-Version`、`Mcp-Method` 與 `Mcp-Name`。`Authorization: Bearer <令牌>` 與 `Authorization: token <令牌>` 會在每次請求中傳遞 Gitea 憑證,這是憑證透傳,而不是 MCP OAuth。
|
HTTP 傳輸固定為無狀態:`/mcp` 只接受 POST,沒有 `Mcp-Session-Id`、獨立 SSE 與 `Last-Event-ID` 斷點續傳。伺服器會驗證來源,反向代理必須原樣轉發 `Mcp-Protocol-Version`、`Mcp-Method` 與 `Mcp-Name`。`Authorization: Bearer <令牌>` 與 `Authorization: token <令牌>` 會在每次請求中傳遞 Gitea 憑證,這是憑證透傳,而不是 MCP OAuth。
|
||||||
|
|
||||||
|
HTTP 模式也會提供 `/healthz` 端點,伺服器正常運作時回傳 `200 OK`。Docker 映像內建的 `HEALTHCHECK` 會執行 `gitea-mcp -healthcheck`,它使用與 `-p`/`-port` 相同的連接埠(預設 `8080`)連線 `http://127.0.0.1:<連接埠>/healthz`,成功時結束碼為 `0`,失敗時為 `1`。stdio 部署不會提供 `/healthz`,因此在 stdio 模式下運作時應覆寫或停用映像內建的 `HEALTHCHECK`。
|
||||||
|
|
||||||
### Claude Code
|
### Claude Code
|
||||||
|
|
||||||
透過 `go run` 執行伺服器,需要安裝 [Go](https://go.dev):
|
透過 `go run` 執行伺服器,需要安裝 [Go](https://go.dev):
|
||||||
|
|||||||
+13
@@ -5,6 +5,7 @@ import (
|
|||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -23,9 +24,11 @@ var (
|
|||||||
tools string
|
tools string
|
||||||
scopes string
|
scopes string
|
||||||
version bool
|
version bool
|
||||||
|
healthcheck bool
|
||||||
maxInlineAttachmentBytes int
|
maxInlineAttachmentBytes int
|
||||||
maxInlineAttachmentBytesFlagSet bool
|
maxInlineAttachmentBytesFlagSet bool
|
||||||
osExit = os.Exit
|
osExit = os.Exit
|
||||||
|
healthcheckClient = http.DefaultClient
|
||||||
)
|
)
|
||||||
|
|
||||||
func initFlagSet(fs *flag.FlagSet, args []string, getenv func(string) string, readFile func(string) ([]byte, error), stderr io.Writer) {
|
func initFlagSet(fs *flag.FlagSet, args []string, getenv func(string) string, readFile func(string) ([]byte, error), stderr io.Writer) {
|
||||||
@@ -53,6 +56,7 @@ func initFlagSet(fs *flag.FlagSet, args []string, getenv func(string) string, re
|
|||||||
fs.BoolVar(&flagPkg.Insecure, "insecure", false, "")
|
fs.BoolVar(&flagPkg.Insecure, "insecure", false, "")
|
||||||
fs.BoolVar(&version, "v", false, "")
|
fs.BoolVar(&version, "v", false, "")
|
||||||
fs.BoolVar(&version, "version", false, "")
|
fs.BoolVar(&version, "version", false, "")
|
||||||
|
fs.BoolVar(&healthcheck, "healthcheck", false, "")
|
||||||
maxInlineAttachmentBytes = 5 * 1024 * 1024
|
maxInlineAttachmentBytes = 5 * 1024 * 1024
|
||||||
fs.Func("max-inline-attachment-bytes", "", func(val string) error {
|
fs.Func("max-inline-attachment-bytes", "", func(val string) error {
|
||||||
parsed, err := strconv.Atoi(val)
|
parsed, err := strconv.Atoi(val)
|
||||||
@@ -81,6 +85,7 @@ func initFlagSet(fs *flag.FlagSet, args []string, getenv func(string) string, re
|
|||||||
fmt.Fprintf(w, " -k, -insecure\tIgnore TLS certificate errors\n")
|
fmt.Fprintf(w, " -k, -insecure\tIgnore TLS certificate errors\n")
|
||||||
fmt.Fprintf(w, " -max-inline-attachment-bytes <bytes>\tInline image attachments up to this size (default: 5242880)\n")
|
fmt.Fprintf(w, " -max-inline-attachment-bytes <bytes>\tInline image attachments up to this size (default: 5242880)\n")
|
||||||
fmt.Fprintf(w, " -v, -version\tPrint version and exit\n")
|
fmt.Fprintf(w, " -v, -version\tPrint version and exit\n")
|
||||||
|
fmt.Fprintf(w, " -healthcheck\tCheck a running HTTP server's /healthz endpoint and exit\n")
|
||||||
fmt.Fprintln(w)
|
fmt.Fprintln(w)
|
||||||
fmt.Fprintln(w, "Environment variables:")
|
fmt.Fprintln(w, "Environment variables:")
|
||||||
fmt.Fprintf(w, " GITEA_ACCESS_TOKEN\tProvide access token\n")
|
fmt.Fprintf(w, " GITEA_ACCESS_TOKEN\tProvide access token\n")
|
||||||
@@ -183,6 +188,14 @@ func Execute() {
|
|||||||
fmt.Fprintln(os.Stdout, flagPkg.Version)
|
fmt.Fprintln(os.Stdout, flagPkg.Version)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if healthcheck {
|
||||||
|
if runHealthcheck(healthcheckClient, flagPkg.Port, os.Stdout, os.Stderr) {
|
||||||
|
osExit(0)
|
||||||
|
} else {
|
||||||
|
osExit(1)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
if err := operation.Run(); err != nil {
|
if err := operation.Run(); err != nil {
|
||||||
if err == context.Canceled {
|
if err == context.Canceled {
|
||||||
log.Info("Server shutdown due to context cancellation")
|
log.Info("Server shutdown due to context cancellation")
|
||||||
|
|||||||
@@ -95,3 +95,12 @@ func TestInitFlagSetScopes(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestInitFlagSetHealthcheck(t *testing.T) {
|
||||||
|
t.Cleanup(func() { healthcheck = false })
|
||||||
|
fs := flag.NewFlagSet("test", flag.ContinueOnError)
|
||||||
|
initFlagSet(fs, []string{"-healthcheck"}, func(string) string { return "" }, func(string) ([]byte, error) { return nil, nil }, &bytes.Buffer{})
|
||||||
|
if !healthcheck {
|
||||||
|
t.Error("healthcheck = false, want true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// runHealthcheck dials the /healthz endpoint on 127.0.0.1:port and reports
|
||||||
|
// success or failure. It returns true when the server responds with a 2xx
|
||||||
|
// status.
|
||||||
|
func runHealthcheck(client *http.Client, port int, stdout, stderr io.Writer) bool {
|
||||||
|
url := fmt.Sprintf("http://127.0.0.1:%d/healthz", port)
|
||||||
|
|
||||||
|
resp, err := client.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(stderr, "healthcheck failed: %v\n", err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||||
|
fmt.Fprintf(stderr, "healthcheck failed: unexpected status %s\n", resp.Status)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintln(stdout, "healthy")
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRunHealthcheck(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
handler http.HandlerFunc
|
||||||
|
port func(server *httptest.Server) int
|
||||||
|
wantOK bool
|
||||||
|
wantStdout string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "server responds 200 OK",
|
||||||
|
handler: func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
},
|
||||||
|
port: serverPort,
|
||||||
|
wantOK: true,
|
||||||
|
wantStdout: "healthy",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "server responds with an error status",
|
||||||
|
handler: func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
},
|
||||||
|
port: serverPort,
|
||||||
|
wantOK: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "nothing listening on the port",
|
||||||
|
port: func(*httptest.Server) int { return 1 },
|
||||||
|
wantOK: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
var server *httptest.Server
|
||||||
|
if tt.handler != nil {
|
||||||
|
server = httptest.NewServer(tt.handler)
|
||||||
|
defer server.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
ok := runHealthcheck(http.DefaultClient, tt.port(server), &stdout, &stderr)
|
||||||
|
|
||||||
|
if ok != tt.wantOK {
|
||||||
|
t.Errorf("runHealthcheck() = %v, want %v", ok, tt.wantOK)
|
||||||
|
}
|
||||||
|
if tt.wantStdout != "" && !strings.Contains(stdout.String(), tt.wantStdout) {
|
||||||
|
t.Errorf("stdout = %q, want it to contain %q", stdout.String(), tt.wantStdout)
|
||||||
|
}
|
||||||
|
if tt.wantOK && stderr.Len() != 0 {
|
||||||
|
t.Errorf("stderr = %q, want empty on success", stderr.String())
|
||||||
|
}
|
||||||
|
if !tt.wantOK && stderr.Len() == 0 {
|
||||||
|
t.Error("stderr is empty, want a failure message")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func serverPort(server *httptest.Server) int {
|
||||||
|
_, portStr, err := net.SplitHostPort(server.Listener.Addr().String())
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
port, err := strconv.Atoi(portStr)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return port
|
||||||
|
}
|
||||||
@@ -133,6 +133,7 @@ func newHTTPServer(addr string, s *mcp.Server) *http.Server {
|
|||||||
PropagateRequestCancellation: true,
|
PropagateRequestCancellation: true,
|
||||||
},
|
},
|
||||||
)))
|
)))
|
||||||
|
mux.HandleFunc("/healthz", handleHealthz)
|
||||||
return &http.Server{
|
return &http.Server{
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
Handler: mux,
|
Handler: mux,
|
||||||
@@ -140,6 +141,12 @@ func newHTTPServer(addr string, s *mcp.Server) *http.Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func handleHealthz(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = w.Write([]byte("ok\n"))
|
||||||
|
}
|
||||||
|
|
||||||
func Run() error {
|
func Run() error {
|
||||||
mcpServer = newMCPServer(flag.Version)
|
mcpServer = newMCPServer(flag.Version)
|
||||||
RegisterTool(mcpServer)
|
RegisterTool(mcpServer)
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
package operation
|
package operation
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
func TestNewHTTPServerConfig(t *testing.T) {
|
func TestNewHTTPServerConfig(t *testing.T) {
|
||||||
server := newHTTPServer(":12345", newMCPServer("test"))
|
server := newHTTPServer(":12345", newMCPServer("test"))
|
||||||
@@ -18,6 +22,21 @@ func TestNewHTTPServerConfig(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestHealthzEndpoint(t *testing.T) {
|
||||||
|
server := newHTTPServer(":0", newMCPServer("test"))
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
server.Handler.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Errorf("status = %d, want %d", rec.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
if body := rec.Body.String(); body == "" {
|
||||||
|
t.Error("body is empty, want a non-empty health message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestParseAuthToken(t *testing.T) {
|
func TestParseAuthToken(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
|
|||||||
Reference in New Issue
Block a user