Files
gitea-mcp/cmd/cmd.go
Klaus 316c2c4275
check-and-test / check-and-test (pull_request) Has been cancelled
debug: structured tool/HTTP logging, request IDs, config dump
Closes #13.

Today GITEA_DEBUG=true only flips the zap level to debug, dumps a
contextless `Text Result:` blob per tool call, and enables the gitea
SDK's own debug stream (which doesn't merge with our log file). That is
not enough to diagnose a misbehaving tool call in production.

This change introduces:

- A `pkg/middleware.ToolLogging` ToolHandlerMiddleware that logs each
  tool invocation on entry and exit with structured fields: tool name,
  redacted args, request_id, token source, duration_ms, and status. The
  request_id is stashed in the context so downstream layers can
  correlate.
- A `loggingRoundTripper` in `pkg/gitea` that wraps the shared HTTP
  transport and emits one structured line per upstream Gitea API call
  (method, token-stripped URL, status, duration_ms, bytes). This
  replaces — and is far more useful than — `gitea.SetDebugMode()`.
- An effective-config dump at startup (`logEffectiveConfig`) when
  debug+config scope is on, so "did my env var get picked up?" becomes
  answerable from the log file.
- Token source tracking. CLI flag / GITEA_ACCESS_TOKEN /
  GITEA_ACCESS_TOKEN_FILE / per-request Authorization header are now
  distinguished in logs as flag/env/env-file/header.
- A baseline redactor in `pkg/debug` that masks args / query params
  whose keys look like secrets (token, password, secret, api_key,
  authorization, …). This is the placeholder for issue #5's shared
  redactor; once that lands, callers here should defer to it.
- `GITEA_DEBUG_SCOPES` env var to scope debug output to any subset of
  `tools,http,config`. Default (unset) is "everything".

Test coverage was added for the redactor, scope flag, request-id
helpers, preview truncation (multibyte-safe), and the middleware's
context wiring + error propagation.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-23 19:04:28 +00:00

164 lines
5.0 KiB
Go

package cmd
import (
"context"
"flag"
"fmt"
"os"
"strings"
"text/tabwriter"
"gitea.com/gitea/gitea-mcp/operation"
flagPkg "gitea.com/gitea/gitea-mcp/pkg/flag"
"gitea.com/gitea/gitea-mcp/pkg/log"
)
var (
host string
port int
token string
tools string
version bool
)
func init() {
flag.StringVar(&flagPkg.Mode, "t", "stdio", "")
flag.StringVar(&flagPkg.Mode, "transport", "stdio", "")
flag.StringVar(&host, "H", os.Getenv("GITEA_HOST"), "")
flag.StringVar(&host, "host", os.Getenv("GITEA_HOST"), "")
flag.IntVar(&port, "p", 8080, "")
flag.IntVar(&port, "port", 8080, "")
flag.StringVar(&token, "T", "", "")
flag.StringVar(&token, "token", "", "")
flag.BoolVar(&flagPkg.ReadOnly, "r", false, "")
flag.BoolVar(&flagPkg.ReadOnly, "read-only", false, "")
defaultTools := os.Getenv("GITEA_TOOLS")
flag.StringVar(&tools, "O", defaultTools, "")
flag.StringVar(&tools, "tools", defaultTools, "")
flag.BoolVar(&flagPkg.Debug, "d", false, "")
flag.BoolVar(&flagPkg.Debug, "debug", false, "")
flag.BoolVar(&flagPkg.Insecure, "k", false, "")
flag.BoolVar(&flagPkg.Insecure, "insecure", false, "")
flag.BoolVar(&version, "v", false, "")
flag.BoolVar(&version, "version", false, "")
flag.Usage = func() {
w := tabwriter.NewWriter(os.Stderr, 0, 0, 3, ' ', 0)
fmt.Fprintln(os.Stderr, "Usage: gitea-mcp [options]")
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "Options:")
fmt.Fprintf(w, " -t, -transport <type>\tTransport type: stdio or http (default: stdio)\n")
fmt.Fprintf(w, " -H, -host <url>\tGitea host URL (default: https://gitea.com)\n")
fmt.Fprintf(w, " -p, -port <number>\tHTTP server port (default: 8080)\n")
fmt.Fprintf(w, " -T, -token <token>\tPersonal access token\n")
fmt.Fprintf(w, " -r, -read-only\tExpose only read-only tools\n")
fmt.Fprintf(w, " -O, -tools <names>\tComma-separated list of tool names to expose\n")
fmt.Fprintf(w, " -d, -debug\tEnable debug mode\n")
fmt.Fprintf(w, " -k, -insecure\tIgnore TLS certificate errors\n")
fmt.Fprintf(w, " -v, -version\tPrint version and exit\n")
fmt.Fprintln(w)
fmt.Fprintln(w, "Environment variables:")
fmt.Fprintf(w, " GITEA_ACCESS_TOKEN\tProvide access token\n")
fmt.Fprintf(w, " GITEA_ACCESS_TOKEN_FILE\tPath to a file containing the access token (e.g. a Docker secret)\n")
fmt.Fprintf(w, " GITEA_DEBUG\tSet to 'true' for debug mode\n")
fmt.Fprintf(w, " GITEA_DEBUG_SCOPES\tComma-separated debug scopes: tools, http, config (default: all)\n")
fmt.Fprintf(w, " GITEA_HOST\tOverride Gitea host URL\n")
fmt.Fprintf(w, " GITEA_INSECURE\tSet to 'true' to ignore TLS errors\n")
fmt.Fprintf(w, " GITEA_READONLY\tSet to 'true' for read-only mode\n")
fmt.Fprintf(w, " GITEA_TOOLS\tComma-separated list of tool names to expose\n")
fmt.Fprintf(w, " MCP_MODE\tOverride transport mode\n")
w.Flush()
}
flag.Parse()
flagPkg.Host = host
if flagPkg.Host == "" {
flagPkg.Host = "https://gitea.com"
}
flagPkg.Port = port
flagPkg.Token = token
if flagPkg.Token != "" {
flagPkg.TokenSource = "flag"
}
if flagPkg.Token == "" {
if v := os.Getenv("GITEA_ACCESS_TOKEN"); v != "" {
flagPkg.Token = v
flagPkg.TokenSource = "env"
}
}
if flagPkg.Token == "" {
if tokenFile := os.Getenv("GITEA_ACCESS_TOKEN_FILE"); tokenFile != "" {
data, err := os.ReadFile(tokenFile)
if err != nil {
fmt.Fprintf(os.Stderr, "error reading GITEA_ACCESS_TOKEN_FILE: %v\n", err)
os.Exit(1)
}
flagPkg.Token = strings.TrimRight(string(data), "\r\n")
if flagPkg.Token != "" {
flagPkg.TokenSource = "env-file"
}
}
}
if os.Getenv("MCP_MODE") != "" {
flagPkg.Mode = os.Getenv("MCP_MODE")
}
if os.Getenv("GITEA_READONLY") == "true" {
flagPkg.ReadOnly = true
}
allowed := map[string]struct{}{}
for t := range strings.SplitSeq(tools, ",") {
if t = strings.TrimSpace(t); t != "" {
allowed[t] = struct{}{}
}
}
if len(allowed) > 0 {
flagPkg.AllowedTools = allowed
}
if os.Getenv("GITEA_DEBUG") == "true" {
flagPkg.Debug = true
}
// GITEA_DEBUG_SCOPES restricts what categories of debug output are
// emitted. Empty (the default) means "everything". Known scopes:
// "tools" (per-tool-call entry/exit), "http" (upstream Gitea API
// requests), "config" (effective config dump at startup).
if scopes := os.Getenv("GITEA_DEBUG_SCOPES"); scopes != "" {
set := map[string]struct{}{}
for s := range strings.SplitSeq(scopes, ",") {
if s = strings.TrimSpace(s); s != "" {
set[s] = struct{}{}
}
}
if len(set) > 0 {
flagPkg.DebugScopes = set
}
}
// Set insecure mode based on environment variable
if os.Getenv("GITEA_INSECURE") == "true" {
flagPkg.Insecure = true
}
}
func Execute() {
if version {
fmt.Fprintln(os.Stdout, flagPkg.Version)
return
}
defer log.Default().Sync() //nolint:errcheck // best-effort flush
if err := operation.Run(); err != nil {
if err == context.Canceled {
log.Info("Server shutdown due to context cancellation")
return
}
log.Fatalf("Run Gitea MCP Server Error: %v", err) //nolint:gocritic // intentional exit after defer
}
}