package tools import ( "context" "encoding/json" "fmt" "gitea.d-ma.be/mathias/gitea-mcp/internal/allowlist" "gitea.d-ma.be/mathias/gitea-mcp/internal/gitea" "gitea.d-ma.be/mathias/gitea-mcp/internal/registry" ) type CodeSearch struct { c *gitea.Client a *allowlist.Allowlist } func NewCodeSearch(c *gitea.Client, a *allowlist.Allowlist) *CodeSearch { return &CodeSearch{c: c, a: a} } func (t *CodeSearch) Descriptor() registry.ToolDescriptor { return registry.ToolDescriptor{ Name: "code_search", Description: "Search code across one repo or fan out across an owner's repos.", InputSchema: json.RawMessage(`{ "type":"object", "properties":{ "q":{"type":"string"}, "owner":{"type":"string"}, "repo":{"type":"string"}, "page":{"type":"integer","minimum":1}, "limit":{"type":"integer","minimum":1,"maximum":50} }, "required":["q","owner"] }`), } } type codeSearchArgs struct { Q string `json:"q"` Owner string `json:"owner"` Repo string `json:"repo"` Page int `json:"page"` Limit int `json:"limit"` } type codeSearchResult struct { Repo string `json:"repo"` Path string `json:"path"` Snippet string `json:"snippet"` Score float64 `json:"score"` HTMLURL string `json:"html_url"` } func (t *CodeSearch) Call(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) { var args codeSearchArgs if err := parseArgs(raw, &args); err != nil { return nil, err } if args.Q == "" { return nil, fmt.Errorf("q is required: %w", gitea.ErrValidation) } if err := t.a.Check(args.Owner); err != nil { return nil, err } if args.Page < 1 { args.Page = 1 } if args.Limit < 1 || args.Limit > 50 { args.Limit = 30 } if args.Repo == "" { // Phase 7.2: leave fan-out unimplemented — just error out for now. return nil, fmt.Errorf("repo is required for single-repo search (org-wide fan-out lands in 7.3): %w", gitea.ErrValidation) } hits, err := t.c.SearchCode(ctx, args.Owner, args.Repo, args.Q, args.Page, args.Limit) if err != nil { return nil, err } results := make([]codeSearchResult, 0, len(hits)) repoFull := args.Owner + "/" + args.Repo for _, h := range hits { score := h.Score if score == 0 { score = 1.0 } results = append(results, codeSearchResult{ Repo: repoFull, Path: h.Path, Snippet: h.Snippet, Score: score, HTMLURL: h.HTMLURL, }) } out := map[string]any{"results": results} if len(hits) == args.Limit { out["next_page"] = args.Page + 1 } return textOK(out) }