Files
sherlock/cmd/gitea-mcp/main.go
T
amacocian f5109abfad
CI / build (push) Successful in 19s
Gitea mcp pre-release
2026-05-25 15:22:30 +02:00

180 lines
5.9 KiB
Go

// Command gitea-mcp is sherlock's MCP server for Gitea. It exposes a
// read-mostly slice of the Gitea REST API (whoami, list_repos,
// get_file, file_history, list_workflow_runs / _jobs, get_job_logs,
// list_packages), all authenticated as the operator via Gitea's own
// OAuth2 / OIDC server with PKCE.
//
// Two modes:
//
// gitea-mcp start the stdio MCP server (this is what agents spawn)
// gitea-mcp --probe run the auth flow + one API call, print result, exit
//
// `--probe` is for end-to-end verification without an agent in the
// loop. The first invocation (or after `sherlock logout gitea`) opens
// a browser; subsequent invocations are silent until the refresh
// window opens.
//
// Configuration is compile-time. The Charlie defaults are baked in
// via gitea_clientid_charlie.go (drop with `-tags noembed` to retarget).
package main
import (
"context"
"errors"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"gitea.alexandru.macocian.me/Charlie/sherlock/internal/agent"
"gitea.alexandru.macocian.me/Charlie/sherlock/internal/authn"
"gitea.alexandru.macocian.me/Charlie/sherlock/internal/browser"
"gitea.alexandru.macocian.me/Charlie/sherlock/internal/keyring"
"gitea.alexandru.macocian.me/Charlie/sherlock/internal/xdg"
)
// serviceName is the wallet key under which gitea tokens live. The
// sherlock CLI's `logout gitea` clears the same entry.
const serviceName = "gitea"
// Compile-time configuration. The default values target the Charlie
// homelab and are populated by gitea_clientid_charlie.go (the
// `charlie` build tag is on by default — see go:build line there).
//
// To target a different deployment, build with `-tags noembed` to
// drop the Charlie constants and supply your own via -ldflags:
//
// go build -tags noembed \
// -ldflags "-X main.giteaIssuer=https://gitea.example.com \
// -X main.giteaClientID=... \
// -X main.giteaClientSecret=... \
// -X main.giteaBaseURL=https://gitea.example.com" \
// ./cmd/gitea-mcp
//
// giteaClientID must be set to the OAuth2 application ID the operator
// created in Gitea (Settings → Applications → OAuth2 Applications →
// New Application, redirect URI `http://127.0.0.1:6990/callback`).
//
// giteaClientSecret is the secret Gitea generates for the same
// application. Some Gitea versions require it on the token-exchange
// step even for native/desktop apps that primarily use PKCE; leave it
// empty if your Gitea accepts PKCE alone.
var (
giteaIssuer string
giteaClientID string
giteaClientSecret string
giteaBaseURL string
)
// Version is overwritten at build time via -ldflags "-X main.Version=...".
var Version = "0.0.0-dev"
// scopes asked from Gitea's OAuth2 server. We pull every read scope
// the tools surface needs — `read:issue` covers issues, PRs, and
// comments; `read:organization` covers orgs, members, teams, and
// org-level actions; `read:package` keeps list_packages honest even
// when Gitea tightens defaults; `read:user` lets the token hit
// /api/v1/user for whoami.
//
// Changing this list invalidates older wallet entries (they were
// granted a narrower scope). Operators must `sherlock logout gitea`
// and let the next gitea-mcp invocation re-auth.
var scopes = []string{
"openid", "profile", "email",
"read:user",
"read:repository",
"read:issue",
"read:organization",
"read:package",
}
func main() {
probe := flag.Bool("probe", false, "run auth + one API call, print result, exit")
showVersion := flag.Bool("version", false, "print version and exit")
flag.Parse()
if *showVersion {
fmt.Println(Version)
return
}
if giteaClientID == "" {
fmt.Fprintln(os.Stderr, "gitea-mcp: giteaClientID not configured.")
fmt.Fprintln(os.Stderr, "Build with -ldflags \"-X main.giteaClientID=...\" (and -tags noembed if you don't want the Charlie default) after creating an OAuth2 Application in Gitea (redirect URI http://127.0.0.1:6990/callback).")
os.Exit(2)
}
store, err := keyring.Open()
if err != nil {
fmt.Fprintln(os.Stderr, "gitea-mcp:", err)
os.Exit(3)
}
// If gitea-mcp ever shells out to siblings (today it doesn't),
// this keeps the "no manual setup" promise.
agent.EnsurePathContainsSiblings()
lockPath, err := xdg.RefreshLockPath()
if err != nil {
fmt.Fprintln(os.Stderr, "gitea-mcp:", err)
os.Exit(1)
}
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
cfg := authn.Config{
Issuer: giteaIssuer,
ClientID: giteaClientID,
ClientSecret: giteaClientSecret,
Scopes: scopes,
}
ts, err := authn.Ensure(ctx, store, serviceName, cfg, authn.EnsureOptions{
LockPath: lockPath,
OnAuthURL: func(u string) {
fmt.Fprintln(os.Stderr, "gitea-mcp: opening browser for Gitea OAuth login:")
fmt.Fprintln(os.Stderr, " ", u)
if err := browser.Open(u); err != nil {
fmt.Fprintln(os.Stderr, "gitea-mcp: open browser:", err)
fmt.Fprintln(os.Stderr, "(visit the URL above manually)")
}
},
})
if err != nil {
fmt.Fprintln(os.Stderr, "gitea-mcp: auth:", err)
os.Exit(5)
}
api := &giteaAPI{
baseURL: strings.TrimRight(giteaBaseURL, "/"),
token: ts.AccessToken,
client: &http.Client{Timeout: 30 * time.Second},
}
if *probe {
var u struct {
Login string `json:"login"`
Email string `json:"email"`
}
if err := api.get(ctx, "/api/v1/user", nil, &u); err != nil {
fmt.Fprintln(os.Stderr, "gitea-mcp: whoami:", err)
os.Exit(5)
}
fmt.Printf("OK: logged in to %s as %s <%s>\n", giteaBaseURL, u.Login, u.Email)
return
}
server := mcp.NewServer(&mcp.Implementation{Name: "gitea-mcp", Version: Version}, nil)
registerTools(server, api)
if err := server.Run(ctx, &mcp.StdioTransport{}); err != nil && !errors.Is(err, context.Canceled) {
fmt.Fprintln(os.Stderr, "gitea-mcp:", err)
os.Exit(1)
}
}