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>
284 lines
8.5 KiB
Go
284 lines
8.5 KiB
Go
package repo
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
"gitea.com/gitea/gitea-mcp/pkg/annotation"
|
|
"gitea.com/gitea/gitea-mcp/pkg/gitea"
|
|
"gitea.com/gitea/gitea-mcp/pkg/params"
|
|
"gitea.com/gitea/gitea-mcp/pkg/to"
|
|
|
|
gitea_sdk "code.gitea.io/sdk/gitea"
|
|
"github.com/mark3labs/mcp-go/mcp"
|
|
"github.com/mark3labs/mcp-go/server"
|
|
)
|
|
|
|
const (
|
|
GetFileToolName = "get_file_contents"
|
|
GetDirToolName = "get_dir_contents"
|
|
CreateOrUpdateFileToolName = "create_or_update_file"
|
|
DeleteFileToolName = "delete_file"
|
|
)
|
|
|
|
var (
|
|
GetFileContentTool = mcp.NewTool(
|
|
GetFileToolName,
|
|
mcp.WithDescription("Get file content and metadata"),
|
|
mcp.WithToolAnnotation(annotation.ReadOnly("Get file content")),
|
|
mcp.WithString("owner", mcp.Required(), mcp.Description(params.OwnerDesc)),
|
|
mcp.WithString("repo", mcp.Required(), mcp.Description(params.RepoDesc)),
|
|
mcp.WithString("ref", mcp.Required(), mcp.Description("branch, tag, or commit SHA")),
|
|
mcp.WithString("path", mcp.Required()),
|
|
mcp.WithBoolean("withLines", mcp.Description("return numbered lines")),
|
|
)
|
|
|
|
GetDirContentTool = mcp.NewTool(
|
|
GetDirToolName,
|
|
mcp.WithToolAnnotation(annotation.ReadOnly("Get directory contents")),
|
|
mcp.WithString("owner", mcp.Required(), mcp.Description(params.OwnerDesc)),
|
|
mcp.WithString("repo", mcp.Required(), mcp.Description(params.RepoDesc)),
|
|
mcp.WithString("ref", mcp.Required(), mcp.Description("branch, tag, or commit SHA")),
|
|
mcp.WithString("path", mcp.Required()),
|
|
)
|
|
|
|
CreateOrUpdateFileTool = mcp.NewTool(
|
|
CreateOrUpdateFileToolName,
|
|
mcp.WithDescription("Create or update a file (provide sha to update an existing file)."),
|
|
mcp.WithToolAnnotation(annotation.Write("Create or update a file")),
|
|
mcp.WithString("owner", mcp.Required(), mcp.Description(params.OwnerDesc)),
|
|
mcp.WithString("repo", mcp.Required(), mcp.Description(params.RepoDesc)),
|
|
mcp.WithString("path", mcp.Required()),
|
|
mcp.WithString("content", mcp.Required()),
|
|
mcp.WithString("message", mcp.Required(), mcp.Description("commit message")),
|
|
mcp.WithString("branch_name", mcp.Required()),
|
|
mcp.WithString("sha", mcp.Description("existing file SHA (omit to create)")),
|
|
mcp.WithString("new_branch_name", mcp.Description("new branch (create only)")),
|
|
)
|
|
|
|
DeleteFileTool = mcp.NewTool(
|
|
DeleteFileToolName,
|
|
mcp.WithToolAnnotation(annotation.Destructive("Delete a file")),
|
|
mcp.WithString("owner", mcp.Required(), mcp.Description(params.OwnerDesc)),
|
|
mcp.WithString("repo", mcp.Required(), mcp.Description(params.RepoDesc)),
|
|
mcp.WithString("path", mcp.Required()),
|
|
mcp.WithString("message", mcp.Required(), mcp.Description("commit message")),
|
|
mcp.WithString("branch_name", mcp.Required()),
|
|
mcp.WithString("sha", mcp.Required()),
|
|
)
|
|
)
|
|
|
|
func init() {
|
|
Tool.RegisterRead(server.ServerTool{
|
|
Tool: GetFileContentTool,
|
|
Handler: GetFileContentFn,
|
|
})
|
|
Tool.RegisterRead(server.ServerTool{
|
|
Tool: GetDirContentTool,
|
|
Handler: GetDirContentFn,
|
|
})
|
|
Tool.RegisterWrite(server.ServerTool{
|
|
Tool: CreateOrUpdateFileTool,
|
|
Handler: CreateOrUpdateFileFn,
|
|
})
|
|
Tool.RegisterWrite(server.ServerTool{
|
|
Tool: DeleteFileTool,
|
|
Handler: DeleteFileFn,
|
|
})
|
|
}
|
|
|
|
type ContentLine struct {
|
|
LineNumber int `json:"line"`
|
|
Content string `json:"content"`
|
|
}
|
|
|
|
func GetFileContentFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
|
args := req.GetArguments()
|
|
owner, err := params.GetString(args, "owner")
|
|
if err != nil {
|
|
return to.ErrorResult(err)
|
|
}
|
|
repo, err := params.GetString(args, "repo")
|
|
if err != nil {
|
|
return to.ErrorResult(err)
|
|
}
|
|
ref, _ := args["ref"].(string)
|
|
filePath, err := params.GetString(args, "path")
|
|
if err != nil {
|
|
return to.ErrorResult(err)
|
|
}
|
|
client, err := gitea.ClientFromContext(ctx)
|
|
if err != nil {
|
|
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
|
|
}
|
|
content, _, err := client.GetContents(owner, repo, ref, filePath)
|
|
if err != nil {
|
|
return to.ErrorResult(fmt.Errorf("get file err: %v", err))
|
|
}
|
|
withLines, _ := args["withLines"].(bool)
|
|
if withLines {
|
|
rawContent, err := base64.StdEncoding.DecodeString(*content.Content)
|
|
if err != nil {
|
|
return to.ErrorResult(fmt.Errorf("decode base64 content err: %v", err))
|
|
}
|
|
|
|
contentLines := make([]ContentLine, 0)
|
|
line := 0
|
|
|
|
scanner := bufio.NewScanner(bytes.NewReader(rawContent))
|
|
|
|
for scanner.Scan() {
|
|
line++
|
|
|
|
contentLines = append(contentLines, ContentLine{
|
|
LineNumber: line,
|
|
Content: scanner.Text(),
|
|
})
|
|
}
|
|
if err := scanner.Err(); err != nil {
|
|
return to.ErrorResult(fmt.Errorf("scan content err: %v", err))
|
|
}
|
|
|
|
// remove the last blank line if exists
|
|
// git does not consider the last line as a new line
|
|
if len(contentLines) > 0 && contentLines[len(contentLines)-1].Content == "" {
|
|
contentLines = contentLines[:len(contentLines)-1]
|
|
}
|
|
|
|
contentBytes, err := json.MarshalIndent(contentLines, "", " ")
|
|
if err != nil {
|
|
return to.ErrorResult(fmt.Errorf("marshal content lines err: %v", err))
|
|
}
|
|
contentStr := string(contentBytes)
|
|
content.Content = &contentStr
|
|
}
|
|
return to.TextResult(slimContents(content))
|
|
}
|
|
|
|
func GetDirContentFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
|
args := req.GetArguments()
|
|
owner, err := params.GetString(args, "owner")
|
|
if err != nil {
|
|
return to.ErrorResult(err)
|
|
}
|
|
repo, err := params.GetString(args, "repo")
|
|
if err != nil {
|
|
return to.ErrorResult(err)
|
|
}
|
|
ref, _ := args["ref"].(string)
|
|
filePath, err := params.GetString(args, "path")
|
|
if err != nil {
|
|
return to.ErrorResult(err)
|
|
}
|
|
client, err := gitea.ClientFromContext(ctx)
|
|
if err != nil {
|
|
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
|
|
}
|
|
content, _, err := client.ListContents(owner, repo, ref, filePath)
|
|
if err != nil {
|
|
return to.ErrorResult(fmt.Errorf("get dir content err: %v", err))
|
|
}
|
|
return to.TextResult(slimDirEntries(content))
|
|
}
|
|
|
|
func CreateOrUpdateFileFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
|
args := req.GetArguments()
|
|
owner, err := params.GetString(args, "owner")
|
|
if err != nil {
|
|
return to.ErrorResult(err)
|
|
}
|
|
repo, err := params.GetString(args, "repo")
|
|
if err != nil {
|
|
return to.ErrorResult(err)
|
|
}
|
|
filePath, err := params.GetString(args, "path")
|
|
if err != nil {
|
|
return to.ErrorResult(err)
|
|
}
|
|
content, _ := args["content"].(string)
|
|
message, _ := args["message"].(string)
|
|
branchName, _ := args["branch_name"].(string)
|
|
sha, _ := args["sha"].(string)
|
|
|
|
client, err := gitea.ClientFromContext(ctx)
|
|
if err != nil {
|
|
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
|
|
}
|
|
|
|
if sha != "" {
|
|
// Update existing file
|
|
opt := gitea_sdk.UpdateFileOptions{
|
|
SHA: sha,
|
|
Content: base64.StdEncoding.EncodeToString([]byte(content)),
|
|
FileOptions: gitea_sdk.FileOptions{
|
|
Message: message,
|
|
BranchName: branchName,
|
|
},
|
|
}
|
|
_, _, err = client.UpdateFile(owner, repo, filePath, opt)
|
|
if err != nil {
|
|
return to.ErrorResult(fmt.Errorf("update file err: %v", err))
|
|
}
|
|
return to.TextResult("Update file success")
|
|
}
|
|
|
|
// Create new file
|
|
opt := gitea_sdk.CreateFileOptions{
|
|
Content: base64.StdEncoding.EncodeToString([]byte(content)),
|
|
FileOptions: gitea_sdk.FileOptions{
|
|
Message: message,
|
|
BranchName: branchName,
|
|
},
|
|
}
|
|
if newBranch, ok := args["new_branch_name"].(string); ok && newBranch != "" {
|
|
opt.NewBranchName = newBranch
|
|
}
|
|
_, _, err = client.CreateFile(owner, repo, filePath, opt)
|
|
if err != nil {
|
|
return to.ErrorResult(fmt.Errorf("create file err: %v", err))
|
|
}
|
|
return to.TextResult("Create file success")
|
|
}
|
|
|
|
func DeleteFileFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
|
args := req.GetArguments()
|
|
owner, err := params.GetString(args, "owner")
|
|
if err != nil {
|
|
return to.ErrorResult(err)
|
|
}
|
|
repo, err := params.GetString(args, "repo")
|
|
if err != nil {
|
|
return to.ErrorResult(err)
|
|
}
|
|
filePath, err := params.GetString(args, "path")
|
|
if err != nil {
|
|
return to.ErrorResult(err)
|
|
}
|
|
message, _ := args["message"].(string)
|
|
branchName, _ := args["branch_name"].(string)
|
|
sha, err := params.GetString(args, "sha")
|
|
if err != nil {
|
|
return to.ErrorResult(err)
|
|
}
|
|
opt := gitea_sdk.DeleteFileOptions{
|
|
FileOptions: gitea_sdk.FileOptions{
|
|
Message: message,
|
|
BranchName: branchName,
|
|
},
|
|
SHA: sha,
|
|
}
|
|
client, err := gitea.ClientFromContext(ctx)
|
|
if err != nil {
|
|
return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err))
|
|
}
|
|
_, err = client.DeleteFile(owner, repo, filePath, opt)
|
|
if err != nil {
|
|
return to.ErrorResult(fmt.Errorf("delete file err: %v", err))
|
|
}
|
|
return to.TextResult("Delete file success")
|
|
}
|