mirror of
https://gitea.com/gitea/gitea-mcp.git
synced 2026-08-03 07:39:22 +02:00
21aa4684d9
`-O` / `--tools` can already narrow the exposed tool set, but it needs every tool spelled out by name. `-S` / `--scope` (`GITEA_SCOPES`) complements it by selecting whole scopes, using the same names the `Scope` column of the tool tables documents. ```bash gitea-mcp -S issue,pull_request # only those scopes gitea-mcp --scope repository,branch --tools get_me # those scopes plus one extra tool ``` ## What changed - Each scope is one `tool.Tool` registry carrying a canonical name, so `operation/repo` is split into the six scopes its files already imply: `repository` (`repo.go` + `tree.go`), `file`, `branch`, `tag`, `commit`, `release`. The other twelve packages map 1:1, giving 18 scopes. - The two allowlists combine as a **union**: with neither set every tool loads; with only `--tools` set behaviour is unchanged; with both set, the selected scopes' tools plus the individually named tools load. `-r` / `GITEA_READONLY` still hides write tools on top. - Scope names are normalized on input (case, spaces, hyphens), so `Pull Request`, `pull-request` and `PULL_REQUEST` all resolve to `pull_request`. Unknown names only warn and list the valid scopes, mirroring how `--tools` treats unknown tool names. - The `Scope` column of all three READMEs now uses the canonical names verbatim, so it doubles as the reference for `--scope`, and `TestReadmeToolTables` compares that column against the registry in both directions — no translation table needed. - Flag parsing moves from `cmd.init()` into `Execute()`. `main()` only ever calls `Execute()`, so this is behaviourally equivalent, and it makes the `cmd` package testable at all: previously the `init()` parse of `os.Args` hit `flag.CommandLine`'s `ExitOnError` on `go test`'s own `-test.*` flags. ## Verification `make fmt`, `make lint-go` (0 issues) and `go test ./...` all pass. New tests cover the filter matrix (no filters / scope-only / tools-only regression / union / read-only interaction / unknown scope), scope-name uniqueness across `domainTools`, and the flag+env parsing and normalization. Smoke-tested `tools/list` over stdio against the built binary: | flags | tools exposed | | :-- | :-- | | _none_ | 54 (identical to `main`) | | `-S branch` | `create_branch`, `delete_branch`, `list_branches` | | `--scope 'Pull Request,TAG'` | the 4 `pull_request` + 4 `tag` tools | | `-O get_me` | `get_me` (unchanged) | | `-S commit -O get_me` | `get_commit`, `list_commits`, `get_me` | | `-S file -r` | `get_dir_contents`, `get_file_contents` | | `-S bogus,issue` | the 4 `issue` tools, plus a warning naming the valid scopes | Reviewed-on: https://gitea.com/gitea/gitea-mcp/pulls/219 Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com> Co-authored-by: yp05327 <576951401@qq.com>
142 lines
3.8 KiB
Go
142 lines
3.8 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,
|
|
repo.FileTool, repo.BranchTool, repo.TagTool, repo.CommitTool, repo.ReleaseTool,
|
|
}
|
|
)
|
|
|
|
func RegisterTool(s *server.MCPServer) {
|
|
for _, t := range domainTools {
|
|
s.AddTools(t.Tools()...)
|
|
}
|
|
tool.WarnUnmatchedAllowedTools(domainTools...)
|
|
tool.WarnUnmatchedAllowedScopes(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.WithStreamableHTTPLogger(log.Slog()),
|
|
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(),
|
|
)
|
|
}
|