Files
gitea-mcp/internal/tools/file_read.go
T
mathiasandClaude Opus 4.8 4c1f36f9eb
CD / Lint / Test / Vet (push) Successful in 7s
CD / Build & Import (push) Successful in 23s
CD / Deploy via GitOps (push) Has been skipped
chore(rename): module gitea.d-ma.be → git.d-ma.be/mathias/gitea-mcp (#39)
Gitea host renamed (infra ADR-0004); the mcp-chassis dep already migrated
(3329ff3), so the sequencing gate is clear. `go mod edit -module` + bulk import
rewrite across all .go files. gitea-mcp is a server binary (not an imported
library), so no downstream consumers break. build + task check green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 22:48:26 +02:00

89 lines
2.0 KiB
Go

package tools
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"git.d-ma.be/mathias/gitea-mcp/internal/allowlist"
"git.d-ma.be/mathias/gitea-mcp/internal/gitea"
"git.d-ma.be/mathias/gitea-mcp/internal/registry"
)
const fileReadMaxBytes = 1 << 20 // 1 MiB
type FileRead struct {
c *gitea.Client
a *allowlist.Allowlist
}
func NewFileRead(c *gitea.Client, a *allowlist.Allowlist) *FileRead {
return &FileRead{c: c, a: a}
}
func (t *FileRead) Descriptor() registry.ToolDescriptor {
return registry.ToolDescriptor{
Name: "file_read",
Description: "Read a file from a repo at a given ref. Defaults to the repo's default branch.",
InputSchema: json.RawMessage(`{
"type":"object",
"properties":{
"owner":{"type":"string"},
"repo":{"type":"string"},
"path":{"type":"string"},
"ref":{"type":"string"}
},
"required":["owner","repo","path"]
}`),
}
}
type fileReadArgs struct {
Owner string `json:"owner"`
Repo string `json:"repo"`
Path string `json:"path"`
Ref string `json:"ref"`
}
func (t *FileRead) Call(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) {
var args fileReadArgs
if err := parseArgs(raw, &args); err != nil {
return nil, err
}
if err := t.a.Check(args.Owner); err != nil {
return nil, err
}
ref := args.Ref
if ref == "" {
var err error
ref, err = t.c.DefaultBranch(ctx, args.Owner, args.Repo)
if err != nil {
return nil, err
}
}
fc, err := t.c.GetFileContents(ctx, args.Owner, args.Repo, args.Path, ref)
if err != nil {
return nil, err
}
if fc.Size > fileReadMaxBytes {
return nil, fmt.Errorf("file %q size %d exceeds 1MiB cap: %w", args.Path, fc.Size, gitea.ErrValidation)
}
decoded, err := base64.StdEncoding.DecodeString(fc.Content)
if err != nil {
return nil, fmt.Errorf("decode base64 content: %w", err)
}
return textOK(map[string]any{
"path": fc.Path,
"ref": ref,
"sha": fc.Sha,
"size": fc.Size,
"content": string(decoded),
})
}