371a06403a
Net **-650 LOC** by removing duplication and dead noise. All tests pass.
### Duplication & helpers
- Extracted shared slim helpers (`UserLogin`, `UserLogins`, `LabelNames`, `BodyWithAttachments`, `UserDetail`, `Repo`/`Repos`, `Label`/`Labels`) into `pkg/slim`. Deleted the 4 copies that lived in `issue/`, `pull/`, `search/`, `repo/` (plus duplicate `slimUserDetail`/`slimRepo`/`slimLabels` across packages).
- Added `params.GetOptionalBoolPtr` and `params.GetOptionalStringPtr`. Replaced 18 awkward `new(localVar); if !ok { = nil }` patterns across `repo/`, `pull/`, `issue/`, `label/`, `milestone/`, `search/`.
- Extracted `pullRequestReviewerFn` for the 99%-identical `createPullRequestReviewerFn`/`deletePullRequestReviewerFn` pair.
### Dead code & noise
- Deleted **122** `log.Debugf("Called X")` narration lines (`zap.AddCaller` already records the caller) and pruned 19 unused `log` imports.
- Removed the unused `log.Logger` wrapper; the mcp-go server now uses `log.Default().Sugar()` directly (matches `util.Logger`).
- Deleted dead `s.DeleteTools("")` — confirmed no-op in mcp-go.
- Stripped WHAT-narration comments per project guidance.
### Correctness & consistency
- Fixed `log.Errorf(err.Error())` format-string bug in `pkg/to/to.go` — a `%` in the error would have been interpreted as a directive.
- Standardized `to.TextResult`/`to.ErrorResult` usage; `release.go`, `tag.go`, `branch.go` were bypassing the helpers in 9 sites (skipping the wrapper's debug/error logging).
- Made `params.GetString` reject empty strings; dropped 21 redundant `err != nil || x == ""` checks in `operation/actions/`.
- Replaced raw `args["org"].(string)` in `ListOrgReposFn` with `params.GetString` to match the rest of the codebase.
### Performance
- **Cached `*gitea.Client` by host+token via `sync.Map`** + shared `*http.Transport` via `sync.Once` for both SDK and raw REST paths. Eliminates the SDK's `/api/v1/version` preflight on every tool call and enables connection keep-alive across requests.
- Gated `to.TextResult` debug log behind `flag.Debug` to skip the `string(bytes)` allocation when debug is off.
- Hoisted `8192` and `60s` magic numbers in `pkg/gitea/rest.go` into named constants.
---
This PR was written with the help of Claude Opus 4.7
---------
Co-authored-by: silverwind <silv3rwind@gmail.com>
Reviewed-on: https://gitea.com/gitea/gitea-mcp/pulls/195
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
Co-committed-by: silverwind <me@silverwind.io>
140 lines
3.7 KiB
Go
140 lines
3.7 KiB
Go
package operation
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"gitea.com/gitea/gitea-mcp/operation/actions"
|
|
"gitea.com/gitea/gitea-mcp/operation/issue"
|
|
"gitea.com/gitea/gitea-mcp/operation/label"
|
|
"gitea.com/gitea/gitea-mcp/operation/milestone"
|
|
"gitea.com/gitea/gitea-mcp/operation/notification"
|
|
"gitea.com/gitea/gitea-mcp/operation/packages"
|
|
"gitea.com/gitea/gitea-mcp/operation/pull"
|
|
"gitea.com/gitea/gitea-mcp/operation/repo"
|
|
"gitea.com/gitea/gitea-mcp/operation/search"
|
|
"gitea.com/gitea/gitea-mcp/operation/timetracking"
|
|
"gitea.com/gitea/gitea-mcp/operation/user"
|
|
"gitea.com/gitea/gitea-mcp/operation/version"
|
|
"gitea.com/gitea/gitea-mcp/operation/wiki"
|
|
mcpContext "gitea.com/gitea/gitea-mcp/pkg/context"
|
|
"gitea.com/gitea/gitea-mcp/pkg/flag"
|
|
"gitea.com/gitea/gitea-mcp/pkg/log"
|
|
"gitea.com/gitea/gitea-mcp/pkg/tool"
|
|
|
|
"github.com/mark3labs/mcp-go/server"
|
|
)
|
|
|
|
var (
|
|
mcpServer *server.MCPServer
|
|
|
|
domainTools = []*tool.Tool{
|
|
user.Tool, actions.Tool, repo.Tool, notification.Tool, issue.Tool,
|
|
label.Tool, milestone.Tool, packages.Tool, pull.Tool, search.Tool,
|
|
version.Tool, wiki.Tool, timetracking.Tool,
|
|
}
|
|
)
|
|
|
|
func RegisterTool(s *server.MCPServer) {
|
|
for _, t := range domainTools {
|
|
s.AddTools(t.Tools()...)
|
|
}
|
|
tool.WarnUnmatchedAllowedTools(domainTools...)
|
|
}
|
|
|
|
// parseAuthToken extracts the token from an Authorization header.
|
|
// Supports "Bearer <token>" (case-insensitive per RFC 7235) and
|
|
// Gitea-style "token <token>" formats.
|
|
// Returns the token and true if valid, empty string and false otherwise.
|
|
func parseAuthToken(authHeader string) (string, bool) {
|
|
if len(authHeader) > 7 && strings.EqualFold(authHeader[:7], "Bearer ") {
|
|
token := strings.TrimSpace(authHeader[7:])
|
|
if token != "" {
|
|
return token, true
|
|
}
|
|
}
|
|
if len(authHeader) > 6 && strings.EqualFold(authHeader[:6], "token ") {
|
|
token := strings.TrimSpace(authHeader[6:])
|
|
if token != "" {
|
|
return token, true
|
|
}
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
func getContextWithToken(ctx context.Context, r *http.Request) context.Context {
|
|
authHeader := r.Header.Get("Authorization")
|
|
if authHeader == "" {
|
|
return ctx
|
|
}
|
|
|
|
token, ok := parseAuthToken(authHeader)
|
|
if !ok {
|
|
return ctx
|
|
}
|
|
|
|
return context.WithValue(ctx, mcpContext.TokenContextKey, token)
|
|
}
|
|
|
|
func Run() error {
|
|
mcpServer = newMCPServer(flag.Version)
|
|
RegisterTool(mcpServer)
|
|
switch flag.Mode {
|
|
case "stdio":
|
|
if err := server.ServeStdio(
|
|
mcpServer,
|
|
); err != nil {
|
|
return err
|
|
}
|
|
case "http":
|
|
httpServer := server.NewStreamableHTTPServer(
|
|
mcpServer,
|
|
server.WithLogger(log.Default().Sugar()),
|
|
server.WithHeartbeatInterval(30*time.Second),
|
|
server.WithHTTPContextFunc(getContextWithToken),
|
|
)
|
|
log.Infof("Gitea MCP HTTP server listening on :%d", flag.Port)
|
|
|
|
// Graceful shutdown setup
|
|
sigCh := make(chan os.Signal, 1)
|
|
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
|
|
shutdownDone := make(chan struct{})
|
|
|
|
go func() {
|
|
<-sigCh
|
|
log.Infof("Shutdown signal received, gracefully stopping HTTP server...")
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
if err := httpServer.Shutdown(shutdownCtx); err != nil {
|
|
log.Errorf("HTTP server shutdown error: %v", err)
|
|
}
|
|
close(shutdownDone)
|
|
}()
|
|
|
|
if err := httpServer.Start(fmt.Sprintf(":%d", flag.Port)); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
return err
|
|
}
|
|
<-shutdownDone // Wait for shutdown to finish
|
|
default:
|
|
return fmt.Errorf("invalid transport type: %s. Must be 'stdio' or 'http'", flag.Mode)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func newMCPServer(version string) *server.MCPServer {
|
|
return server.NewMCPServer(
|
|
"Gitea MCP Server",
|
|
version,
|
|
server.WithToolCapabilities(true),
|
|
server.WithLogging(),
|
|
server.WithRecovery(),
|
|
)
|
|
}
|