diff --git a/Dockerfile b/Dockerfile index 787b981..e3f1843 100644 --- a/Dockerfile +++ b/Dockerfile @@ -32,4 +32,7 @@ USER nonroot:nonroot LABEL org.opencontainers.image.version="${VERSION}" 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"] diff --git a/README.md b/README.md index 4e49f81..d31566f 100644 --- a/README.md +++ b/README.md @@ -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 ` and `Authorization: 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:/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 Runs the server through `go run` and requires [Go](https://go.dev): diff --git a/README.zh-cn.md b/README.zh-cn.md index 7d442f8..3bf0e33 100644 --- a/README.zh-cn.md +++ b/README.zh-cn.md @@ -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 模式还提供 `/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 通过 `go run` 运行服务器,需要安装 [Go](https://go.dev): diff --git a/README.zh-tw.md b/README.zh-tw.md index 05cf494..6aa1868 100644 --- a/README.zh-tw.md +++ b/README.zh-tw.md @@ -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 模式也會提供 `/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 透過 `go run` 執行伺服器,需要安裝 [Go](https://go.dev): diff --git a/cmd/cmd.go b/cmd/cmd.go index 70566c4..ba5ce9f 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -5,6 +5,7 @@ import ( "flag" "fmt" "io" + "net/http" "os" "strconv" "strings" @@ -23,9 +24,11 @@ var ( tools string scopes string version bool + healthcheck bool maxInlineAttachmentBytes int maxInlineAttachmentBytesFlagSet bool 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) { @@ -53,6 +56,7 @@ func initFlagSet(fs *flag.FlagSet, args []string, getenv func(string) string, re fs.BoolVar(&flagPkg.Insecure, "insecure", false, "") fs.BoolVar(&version, "v", false, "") fs.BoolVar(&version, "version", false, "") + fs.BoolVar(&healthcheck, "healthcheck", false, "") maxInlineAttachmentBytes = 5 * 1024 * 1024 fs.Func("max-inline-attachment-bytes", "", func(val string) error { 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, " -max-inline-attachment-bytes \tInline image attachments up to this size (default: 5242880)\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, "Environment variables:") fmt.Fprintf(w, " GITEA_ACCESS_TOKEN\tProvide access token\n") @@ -183,6 +188,14 @@ func Execute() { fmt.Fprintln(os.Stdout, flagPkg.Version) 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 == context.Canceled { log.Info("Server shutdown due to context cancellation") diff --git a/cmd/cmd_test.go b/cmd/cmd_test.go index 24ed0fb..df383b1 100644 --- a/cmd/cmd_test.go +++ b/cmd/cmd_test.go @@ -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") + } +} diff --git a/cmd/healthcheck.go b/cmd/healthcheck.go new file mode 100644 index 0000000..fd8aa12 --- /dev/null +++ b/cmd/healthcheck.go @@ -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 +} diff --git a/cmd/healthcheck_test.go b/cmd/healthcheck_test.go new file mode 100644 index 0000000..d517d07 --- /dev/null +++ b/cmd/healthcheck_test.go @@ -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 +} diff --git a/operation/operation.go b/operation/operation.go index 610d081..e610e98 100644 --- a/operation/operation.go +++ b/operation/operation.go @@ -133,6 +133,7 @@ func newHTTPServer(addr string, s *mcp.Server) *http.Server { PropagateRequestCancellation: true, }, ))) + mux.HandleFunc("/healthz", handleHealthz) return &http.Server{ Addr: addr, 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 { mcpServer = newMCPServer(flag.Version) RegisterTool(mcpServer) diff --git a/operation/operation_test.go b/operation/operation_test.go index c0fceb4..ee8eb67 100644 --- a/operation/operation_test.go +++ b/operation/operation_test.go @@ -1,6 +1,10 @@ package operation -import "testing" +import ( + "net/http" + "net/http/httptest" + "testing" +) func TestNewHTTPServerConfig(t *testing.T) { 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) { tests := []struct { name string