4 Commits

Author SHA1 Message Date
Mathias Bergqvist
f63605bdd0 fix(mcp): downgrade protocolVersion to 2025-03-26
Some checks failed
CD / Lint / Test / Vet (push) Failing after 3s
CD / Build & Import (push) Has been skipped
CD / Deploy via GitOps (push) Has been skipped
Claude Code CLI rejects 2025-06-18 and silently drops the connection;
2025-03-26 is the highest version it supports. Fixes #4.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 07:53:18 +02:00
Mathias Bergqvist
c4d3735272 fix(mcp): allow GET/SSE without session ID for claude.ai compatibility
Some checks failed
CD / Lint / Test / Vet (push) Failing after 3s
CD / Build & Import (push) Has been skipped
CD / Deploy via GitOps (push) Has been skipped
2026-05-07 23:22:21 +02:00
Mathias Bergqvist
d8db786e27 ci: add environment: staging gate to deploy job
Some checks failed
CD / Lint / Test / Vet (push) Failing after 2s
CD / Build & Import (push) Has been skipped
CD / Deploy via GitOps (push) Has been skipped
Aligns with cobalt-dingo reference — the deploy job was missing the
Gitea Actions environment protection so staging approvals/secrets were
not enforced.
2026-05-07 21:52:40 +02:00
Mathias Bergqvist
923689afa5 feat: replace static API token with per-request Gitea PAT pass-through
Callers now supply their own Gitea PAT as a Bearer token; the server validates
it against GET /api/v1/user and threads it through context to all downstream
Gitea API calls. GITEA_API_TOKEN env var and the GiteaAPIToken config field are
removed.
2026-05-07 21:04:47 +02:00
9 changed files with 155 additions and 18 deletions

View File

@@ -95,6 +95,7 @@ jobs:
needs: build
runs-on: self-hosted
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
environment: staging
steps:
- name: Update image tag in infra repo
env:

View File

@@ -23,7 +23,7 @@ func main() {
os.Exit(1)
}
giteaClient := gitea.NewClient(cfg.GiteaBaseURL, cfg.GiteaAPIToken)
giteaClient := gitea.NewClient(cfg.GiteaBaseURL, "")
ownerAllow := allowlist.New(cfg.AllowedOwners)
reg := registry.New()
@@ -58,7 +58,11 @@ func main() {
})
mux := http.NewServeMux()
mux.Handle("/mcp", mcp.OriginAllowlist(cfg.OriginAllowlist)(auth.CallerMiddleware(mcpSrv)))
mux.Handle("/mcp", mcp.OriginAllowlist(cfg.OriginAllowlist)(
auth.BearerMiddleware(cfg.GiteaBaseURL,
auth.CallerMiddleware(mcpSrv),
),
))
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))

49
internal/auth/bearer.go Normal file
View File

@@ -0,0 +1,49 @@
package auth
import (
"context"
"net/http"
"strings"
"time"
)
type tokenKey struct{}
// BearerMiddleware validates the incoming bearer token as a Gitea PAT by
// calling GET /api/v1/user. The validated token is stored in context for
// downstream use by the Gitea client.
func BearerMiddleware(giteaBaseURL string, next http.Handler) http.Handler {
hc := &http.Client{Timeout: 5 * time.Second}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || token == "" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, giteaBaseURL+"/api/v1/user", nil)
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
req.Header.Set("Authorization", "token "+token)
resp, err := hc.Do(req)
if err != nil || resp.StatusCode != http.StatusOK {
if resp != nil {
_ = resp.Body.Close()
}
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
_ = resp.Body.Close()
ctx := context.WithValue(r.Context(), tokenKey{}, token)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// TokenFromContext returns the validated Gitea PAT stored by BearerMiddleware.
func TokenFromContext(ctx context.Context) string {
if v, ok := ctx.Value(tokenKey{}).(string); ok {
return v
}
return ""
}

View File

@@ -0,0 +1,82 @@
package auth_test
import (
"net/http"
"net/http/httptest"
"testing"
"gitea.d-ma.be/mathias/gitea-mcp/internal/auth"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBearerMiddleware_NoAuthHeader(t *testing.T) {
srv := httptest.NewServer(auth.BearerMiddleware("https://gitea.example.com",
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}),
))
defer srv.Close()
resp, err := http.Post(srv.URL+"/mcp", "application/json", nil)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
}
func TestBearerMiddleware_InvalidToken(t *testing.T) {
// Mock Gitea that rejects the token
giteaMock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}))
defer giteaMock.Close()
srv := httptest.NewServer(auth.BearerMiddleware(giteaMock.URL,
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}),
))
defer srv.Close()
req, _ := http.NewRequest(http.MethodPost, srv.URL+"/mcp", nil)
req.Header.Set("Authorization", "Bearer bad-token")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
}
func TestBearerMiddleware_ValidToken(t *testing.T) {
const token = "valid-pat"
// Mock Gitea that accepts the token and returns a user
giteaMock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "token "+token, r.Header.Get("Authorization"))
w.WriteHeader(http.StatusOK)
}))
defer giteaMock.Close()
called := false
srv := httptest.NewServer(auth.BearerMiddleware(giteaMock.URL,
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
// Token must be available in context for downstream Gitea client
assert.Equal(t, token, auth.TokenFromContext(r.Context()))
w.WriteHeader(http.StatusOK)
}),
))
defer srv.Close()
req, _ := http.NewRequest(http.MethodPost, srv.URL+"/mcp", nil)
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.True(t, called)
}
func TestTokenFromContext_Empty(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
assert.Equal(t, "", auth.TokenFromContext(req.Context()))
}

View File

@@ -8,7 +8,6 @@ import (
type Config struct {
Port string // GITEA_MCP_PORT, default 8080
GiteaBaseURL string // GITEA_BASE_URL, e.g. https://gitea.d-ma.be
GiteaAPIToken string // GITEA_API_TOKEN — bot user token
AllowedOwners []string // GITEA_MCP_ALLOWED_OWNERS, comma-separated, default "mathias"
OriginAllowlist []string // GITEA_MCP_ORIGIN_ALLOWLIST, comma-separated
}
@@ -17,7 +16,6 @@ func Load() (Config, error) {
cfg := Config{
Port: envOr("GITEA_MCP_PORT", "8080"),
GiteaBaseURL: os.Getenv("GITEA_BASE_URL"),
GiteaAPIToken: os.Getenv("GITEA_API_TOKEN"),
AllowedOwners: splitCSV(envOr("GITEA_MCP_ALLOWED_OWNERS", "mathias")),
OriginAllowlist: splitCSV(os.Getenv("GITEA_MCP_ORIGIN_ALLOWLIST")),
}

View File

@@ -10,7 +10,6 @@ import (
func TestLoadDefaults(t *testing.T) {
t.Setenv("GITEA_BASE_URL", "")
t.Setenv("GITEA_API_TOKEN", "")
t.Setenv("GITEA_MCP_ALLOWED_OWNERS", "")
t.Setenv("GITEA_MCP_ORIGIN_ALLOWLIST", "")
t.Setenv("GITEA_MCP_PORT", "")
@@ -23,7 +22,6 @@ func TestLoadDefaults(t *testing.T) {
func TestLoadFromEnv(t *testing.T) {
t.Setenv("GITEA_BASE_URL", "https://gitea.d-ma.be")
t.Setenv("GITEA_API_TOKEN", "test-token")
t.Setenv("GITEA_MCP_ALLOWED_OWNERS", "mathias,acme")
t.Setenv("GITEA_MCP_ORIGIN_ALLOWLIST", "https://claude.ai,https://api.anthropic.com")
t.Setenv("GITEA_MCP_PORT", "9000")
@@ -31,7 +29,6 @@ func TestLoadFromEnv(t *testing.T) {
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "https://gitea.d-ma.be", cfg.GiteaBaseURL)
assert.Equal(t, "test-token", cfg.GiteaAPIToken)
assert.Equal(t, []string{"mathias", "acme"}, cfg.AllowedOwners)
assert.Equal(t, []string{"https://claude.ai", "https://api.anthropic.com"}, cfg.OriginAllowlist)
assert.Equal(t, "9000", cfg.Port)

View File

@@ -7,6 +7,7 @@ import (
"net/http"
"time"
"gitea.d-ma.be/mathias/gitea-mcp/internal/auth"
"github.com/hashicorp/golang-lru/v2/expirable"
)
@@ -49,8 +50,12 @@ func (c *Client) doOnce(ctx context.Context, method, path string, body []byte) (
if err != nil {
return nil, 0, err
}
if c.token != "" {
req.Header.Set("Authorization", "token "+c.token)
token := auth.TokenFromContext(ctx)
if token == "" {
token = c.token
}
if token != "" {
req.Header.Set("Authorization", "token "+token)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
@@ -114,8 +119,12 @@ func (c *Client) doRaw(ctx context.Context, method, path string, body []byte) (*
if err != nil {
return nil, err
}
if c.token != "" {
req.Header.Set("Authorization", "token "+c.token)
token := auth.TokenFromContext(ctx)
if token == "" {
token = c.token
}
if token != "" {
req.Header.Set("Authorization", "token "+token)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")

View File

@@ -9,7 +9,7 @@ import (
)
const (
ProtocolVersion = "2025-06-18"
ProtocolVersion = "2025-03-26"
maxRequestBodyBytes = 1 << 20 // 1 MiB
)
@@ -111,11 +111,8 @@ func (s *Server) handlePOST(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) handleGET(w http.ResponseWriter, r *http.Request) {
sid := r.Header.Get("Mcp-Session-Id")
if !s.opts.Sessions.Valid(sid) {
http.Error(w, "missing or invalid Mcp-Session-Id", http.StatusBadRequest)
return
}
// Session ID is optional for GET: clients may open the SSE stream before
// calling initialize (e.g. claude.ai probes on add). Accept with or without.
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")

View File

@@ -52,7 +52,7 @@ func TestInitialize(t *testing.T) {
var resp map[string]any
require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &resp))
result := resp["result"].(map[string]any)
assert.Equal(t, "2025-06-18", result["protocolVersion"])
assert.Equal(t, mcp.ProtocolVersion, result["protocolVersion"])
si := result["serverInfo"].(map[string]any)
assert.Equal(t, "gitea-mcp", si["name"])
}