feat(issue): add attachment read downloads (#218)

- Add a read-only `attachment_read` tool for issue and issue comment attachments.
- Use the existing Gitea SDK attachment metadata APIs for `list` and `get`.
- Add authenticated `/attachments/{uuid}` downloads in the MCP server for `download`, with small image inline results and streamed file downloads for larger content.
- Add `-max-inline-attachment-bytes` / `GITEA_MAX_INLINE_ATTACHMENT_BYTES` to configure inline image limits.
- Update the tool tables in all README variants.

Refs: #209

Reviewed-on: https://gitea.com/gitea/gitea-mcp/pulls/218
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: yp05327 <576951401@qq.com>
This commit is contained in:
yp05327
2026-07-26 11:53:02 +00:00
committed by bircni
parent 18fcd663e0
commit c97c38996c
10 changed files with 968 additions and 62 deletions
+311
View File
@@ -0,0 +1,311 @@
package issue
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"mime"
"os"
"path/filepath"
"strings"
"gitea.com/gitea/gitea-mcp/pkg/annotation"
"gitea.com/gitea/gitea-mcp/pkg/flag"
"gitea.com/gitea/gitea-mcp/pkg/gitea"
"gitea.com/gitea/gitea-mcp/pkg/params"
"gitea.com/gitea/gitea-mcp/pkg/to"
gitea_sdk "gitea.dev/sdk"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
const AttachmentReadToolName = "attachment_read"
var AttachmentReadTool = mcp.NewTool(
AttachmentReadToolName,
mcp.WithDescription("Read issue/comment attachments: list metadata, get metadata, or download content."),
mcp.WithToolAnnotation(annotation.ReadOnly("Read issue or comment attachments")),
mcp.WithString("method", mcp.Required(), mcp.Enum("list", "get", "download")),
mcp.WithString("owner", mcp.Required(), mcp.Description(params.OwnerDesc)),
mcp.WithString("repo", mcp.Required(), mcp.Description(params.RepoDesc)),
mcp.WithNumber("issue_number", mcp.Description("required for issue attachment list/get or issue-scoped metadata lookup")),
mcp.WithNumber("comment_id", mcp.Description("required for comment attachment list/get or comment-scoped metadata lookup")),
mcp.WithNumber("attachment_id", mcp.Description("required for get and for download when attachment_uuid is not provided")),
mcp.WithString("attachment_uuid", mcp.Description("attachment UUID for direct download path lookup")),
mcp.WithString("output_path", mcp.Description("write the attachment to this exact path")),
)
func init() {
Tool.RegisterRead(server.ServerTool{Tool: AttachmentReadTool, Handler: attachmentReadFn})
}
func attachmentReadFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
method, err := params.GetString(req.GetArguments(), "method")
if err != nil {
return to.ErrorResult(err)
}
switch method {
case "list":
return listAttachmentsFn(ctx, req)
case "get":
return getAttachmentFn(ctx, req)
case "download":
return downloadAttachmentFn(ctx, req)
default:
return to.ErrorResult(fmt.Errorf("unknown method: %s", method))
}
}
func listAttachmentsFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
owner, repo, issueNumber, commentID, err := attachmentScopeArgs(req)
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))
}
var attachments []*gitea_sdk.Attachment
if issueNumber > 0 {
attachments, _, err = client.Issues.ListIssueAttachments(ctx, owner, repo, issueNumber)
} else {
attachments, _, err = client.Issues.ListIssueCommentAttachments(ctx, owner, repo, commentID)
}
if err != nil {
return to.ErrorResult(fmt.Errorf("list attachments err: %v", err))
}
return to.TextResult(slimAttachments(attachments))
}
func getAttachmentFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
att, err := lookupAttachment(ctx, req)
if err != nil {
return to.ErrorResult(err)
}
return to.TextResult(slimAttachment(att))
}
func downloadAttachmentFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
owner, err := params.GetString(req.GetArguments(), "owner")
if err != nil {
return to.ErrorResult(err)
}
repo, err := params.GetString(req.GetArguments(), "repo")
if err != nil {
return to.ErrorResult(err)
}
explicitOutputPath := params.GetOptionalString(req.GetArguments(), "output_path", "")
attachmentUUID := strings.TrimSpace(params.GetOptionalString(req.GetArguments(), "attachment_uuid", ""))
var att *gitea_sdk.Attachment
if attachmentUUID == "" {
att, err = lookupAttachment(ctx, req)
if err != nil {
return to.ErrorResult(err)
}
attachmentUUID = strings.TrimSpace(att.UUID)
}
if attachmentUUID == "" {
return to.ErrorResult(errors.New("attachment_uuid or attachment metadata with uuid is required"))
}
name := attachmentUUID
if att != nil && strings.TrimSpace(att.Name) != "" {
name = strings.TrimSpace(att.Name)
}
resp, err := gitea.OpenAttachment(ctx, "/attachments/"+attachmentUUID, "*/*")
if err != nil {
return to.ErrorResult(fmt.Errorf("download attachment err: %v", err))
}
defer resp.Body.Close()
mimeType := normalizeAttachmentContentType(resp.ContentType, name)
if explicitOutputPath == "" && shouldInlineAttachment(att, mimeType) {
limited, readErr := io.ReadAll(io.LimitReader(resp.Body, int64(flag.MaxInlineAttachmentBytes)+1))
if readErr != nil {
return to.ErrorResult(fmt.Errorf("read attachment err: %v", readErr))
}
if len(limited) <= flag.MaxInlineAttachmentBytes {
text := fmt.Sprintf("attachment %s (%s, %d bytes, %s)", name, attachmentUUID, len(limited), mimeType)
return mcp.NewToolResultImage(text, base64.StdEncoding.EncodeToString(limited), mimeType), nil
}
outputPath := defaultAttachmentPath(owner, repo, name, attachmentUUID)
if err := os.MkdirAll(filepath.Dir(outputPath), 0o700); err != nil {
return to.ErrorResult(fmt.Errorf("create output dir err: %v", err))
}
reader := io.MultiReader(bytes.NewReader(limited), resp.Body)
written, err := gitea.WriteAttachment(reader, outputPath)
if err != nil {
return to.ErrorResult(fmt.Errorf("write attachment file err: %v", err))
}
return attachmentFileResult(att, outputPath, written, name, attachmentUUID, mimeType)
}
outputPath := explicitOutputPath
if outputPath == "" {
outputPath = defaultAttachmentPath(owner, repo, name, attachmentUUID)
}
if err := os.MkdirAll(filepath.Dir(outputPath), 0o700); err != nil {
return to.ErrorResult(fmt.Errorf("create output dir err: %v", err))
}
written, err := gitea.WriteAttachment(resp.Body, outputPath)
if err != nil {
return to.ErrorResult(fmt.Errorf("write attachment file err: %v", err))
}
return attachmentFileResult(att, outputPath, written, name, attachmentUUID, mimeType)
}
func shouldInlineAttachment(att *gitea_sdk.Attachment, mimeType string) bool {
if !strings.HasPrefix(mimeType, "image/") || flag.MaxInlineAttachmentBytes <= 0 {
return false
}
if att == nil || att.Size <= 0 {
return true
}
return att.Size <= int64(flag.MaxInlineAttachmentBytes)
}
func attachmentFileResult(att *gitea_sdk.Attachment, outputPath string, written int64, name, attachmentUUID, mimeType string) (*mcp.CallToolResult, error) {
res := map[string]any{
"path": outputPath,
"bytes": written,
"name": name,
"uuid": attachmentUUID,
"mime_type": mimeType,
"content_type": mimeType,
}
if att != nil {
res["attachment_id"] = att.ID
}
return to.TextResult(res)
}
func attachmentScopeArgs(req mcp.CallToolRequest) (owner, repo string, issueNumber, commentID int64, err error) {
owner, err = params.GetString(req.GetArguments(), "owner")
if err != nil {
return "", "", 0, 0, err
}
repo, err = params.GetString(req.GetArguments(), "repo")
if err != nil {
return "", "", 0, 0, err
}
issueNumber = params.GetOptionalInt(req.GetArguments(), "issue_number", 0)
commentID = params.GetOptionalInt(req.GetArguments(), "comment_id", 0)
if (issueNumber > 0) == (commentID > 0) {
return "", "", 0, 0, errors.New("exactly one of issue_number or comment_id is required")
}
return owner, repo, issueNumber, commentID, nil
}
func lookupAttachment(ctx context.Context, req mcp.CallToolRequest) (*gitea_sdk.Attachment, error) {
owner, repo, issueNumber, commentID, err := attachmentScopeArgs(req)
if err != nil {
return nil, err
}
attachmentID := params.GetOptionalInt(req.GetArguments(), "attachment_id", 0)
if attachmentID <= 0 {
return nil, errors.New("attachment_id is required")
}
client, err := gitea.ClientFromContext(ctx)
if err != nil {
return nil, fmt.Errorf("get gitea client err: %v", err)
}
if issueNumber > 0 {
att, _, err := client.Issues.GetIssueAttachment(ctx, owner, repo, issueNumber, attachmentID)
if err != nil {
return nil, fmt.Errorf("get issue attachment err: %v", err)
}
return att, nil
}
att, _, err := client.Issues.GetIssueCommentAttachment(ctx, owner, repo, commentID, attachmentID)
if err != nil {
return nil, fmt.Errorf("get issue comment attachment err: %v", err)
}
return att, nil
}
func slimAttachments(atts []*gitea_sdk.Attachment) []map[string]any {
out := make([]map[string]any, 0, len(atts))
for _, att := range atts {
out = append(out, slimAttachment(att))
}
return out
}
func slimAttachment(att *gitea_sdk.Attachment) map[string]any {
if att == nil {
return nil
}
m := map[string]any{
"id": att.ID,
"name": att.Name,
"uuid": att.UUID,
"size": att.Size,
"download_count": att.DownloadCount,
"created_at": att.Created,
"mime_type": inferAttachmentMimeType(att.Name),
}
if att.DownloadURL != "" {
m["browser_download_url"] = att.DownloadURL
}
return m
}
func inferAttachmentMimeType(name string) string {
if ext := strings.ToLower(filepath.Ext(strings.TrimSpace(name))); ext != "" {
if mimeType := mime.TypeByExtension(ext); mimeType != "" {
return strings.Split(mimeType, ";")[0]
}
}
return "application/octet-stream"
}
func normalizeAttachmentContentType(contentType, name string) string {
mediaType, _, err := mime.ParseMediaType(contentType)
if err == nil && mediaType != "" && mediaType != "application/octet-stream" {
return mediaType
}
return inferAttachmentMimeType(name)
}
func defaultAttachmentPath(owner, repo, name, uuid string) string {
home, _ := os.UserHomeDir()
if home == "" {
home = os.TempDir()
}
filename := attachmentFilename(name, uuid)
ext := filepath.Ext(filename)
base := strings.TrimSuffix(filename, ext)
if uuid != "" {
filename = uuid
if base != "" && base != "attachment" {
filename = base + "-" + uuid
}
filename += ext
}
return filepath.Join(home, ".gitea-mcp", "attachments", safePathPart(owner), safePathPart(repo), filename)
}
func attachmentFilename(name, uuid string) string {
name = strings.TrimSpace(name)
if name != "" && !strings.ContainsAny(name, `/\\`) && name != "." && name != ".." {
return name
}
if uuid != "" {
return uuid + ".bin"
}
return "attachment.bin"
}
func safePathPart(name string) string {
name = strings.TrimSpace(name)
if name != "" && !strings.ContainsAny(name, `/\\`) && name != "." && name != ".." {
return name
}
return "unknown"
}
+182
View File
@@ -0,0 +1,182 @@
package issue
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"gitea.com/gitea/gitea-mcp/pkg/flag"
"gitea.com/gitea/gitea-mcp/pkg/gitea"
"github.com/mark3labs/mcp-go/mcp"
)
func TestAttachmentFilename(t *testing.T) {
tests := []struct {
name string
file string
uuid string
want string
}{
{"uses attachment name", "screenshot.png", "abc", "screenshot.png"},
{"falls back for traversal", "../etc/passwd", "abc", "abc.bin"},
{"falls back for empty name", "", "abc", "abc.bin"},
{"uses generic fallback", "", "", "attachment.bin"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := attachmentFilename(tt.file, tt.uuid); got != tt.want {
t.Fatalf("attachmentFilename() = %q, want %q", got, tt.want)
}
})
}
}
func TestInferAttachmentMimeType(t *testing.T) {
if got := inferAttachmentMimeType("shot.png"); got != "image/png" {
t.Fatalf("inferAttachmentMimeType() = %q, want image/png", got)
}
if got := inferAttachmentMimeType("archive.unknownext"); got != "application/octet-stream" {
t.Fatalf("inferAttachmentMimeType() = %q, want application/octet-stream", got)
}
}
func TestDefaultAttachmentPath(t *testing.T) {
got := defaultAttachmentPath("octo", "demo", "shot.png", "uuid-1")
want := filepath.Join(".gitea-mcp", "attachments", "octo", "demo", "shot-uuid-1.png")
if !strings.HasSuffix(got, want) {
t.Fatalf("defaultAttachmentPath() = %q, want suffix %q", got, want)
}
}
func TestAttachmentReadListIssueAttachments(t *testing.T) {
const owner = "octo"
const repo = "demo"
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/version":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"version":"1.12.0"}`))
case fmt.Sprintf("/api/v1/repos/%s/%s", owner, repo):
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"private":false}`))
case fmt.Sprintf("/api/v1/repos/%s/%s/issues/42/assets", owner, repo):
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[{"id":1,"name":"shot.png","uuid":"uuid-1","size":10,"download_count":2}]`))
default:
http.NotFound(w, r)
}
})
server := httptest.NewServer(handler)
defer server.Close()
origHost, origToken, origVersion := flag.Host, flag.Token, flag.Version
flag.Host, flag.Token, flag.Version = server.URL, "", "test"
defer func() { flag.Host, flag.Token, flag.Version = origHost, origToken, origVersion }()
res, err := attachmentReadFn(context.Background(), mcp.CallToolRequest{Params: mcp.CallToolParams{Arguments: map[string]any{
"method": "list", "owner": owner, "repo": repo, "issue_number": float64(42),
}}})
if err != nil {
t.Fatalf("attachmentReadFn() error = %v", err)
}
body := res.Content[0].(mcp.TextContent).Text
if !strings.Contains(body, `"mime_type":"image/png"`) || !strings.Contains(body, `"uuid":"uuid-1"`) {
t.Fatalf("unexpected body: %s", body)
}
}
func TestDownloadAttachmentRejectsRedirectLoopAtHopLimit(t *testing.T) {
var serverURL string
redirects := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/attachments/uuid-1" {
t.Fatalf("path = %s", r.URL.Path)
}
redirects++
http.Redirect(w, r, serverURL+"/attachments/uuid-1", http.StatusFound)
}))
defer server.Close()
serverURL = server.URL
origHost := flag.Host
flag.Host = server.URL
defer func() { flag.Host = origHost }()
_, _, _, err := gitea.DownloadAttachment(context.Background(), "/attachments/uuid-1", "*/*")
if err == nil {
t.Fatal("expected redirect limit error")
}
if !strings.Contains(err.Error(), "stopped after 10 redirects") {
t.Fatalf("unexpected error: %v", err)
}
if redirects != 10 {
t.Fatalf("redirects = %d, want 10", redirects)
}
}
func TestAttachmentReadDownloadSavesLargeAttachmentToDefaultFile(t *testing.T) {
const owner = "octo"
const repo = "demo"
const uuid = "uuid-1"
const name = "large.bin"
payload := strings.Repeat("a", 32)
home := t.TempDir()
t.Setenv("HOME", home)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/version":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"version":"1.12.0"}`))
case fmt.Sprintf("/api/v1/repos/%s/%s", owner, repo):
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"private":false}`))
case fmt.Sprintf("/api/v1/repos/%s/%s/issues/42/assets/1", owner, repo):
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"id": 1, "name": name, "uuid": uuid, "size": len(payload)})
case "/attachments/" + uuid:
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write([]byte(payload))
default:
http.NotFound(w, r)
}
})
server := httptest.NewServer(handler)
defer server.Close()
origHost, origToken, origVersion, origInline := flag.Host, flag.Token, flag.Version, flag.MaxInlineAttachmentBytes
flag.Host, flag.Token, flag.Version = server.URL, "", "test"
flag.MaxInlineAttachmentBytes = 8
defer func() {
flag.Host, flag.Token, flag.Version, flag.MaxInlineAttachmentBytes = origHost, origToken, origVersion, origInline
}()
res, err := attachmentReadFn(context.Background(), mcp.CallToolRequest{Params: mcp.CallToolParams{Arguments: map[string]any{
"method": "download", "owner": owner, "repo": repo, "issue_number": float64(42), "attachment_id": float64(1),
}}})
if err != nil {
t.Fatalf("attachmentReadFn() error = %v", err)
}
body := res.Content[0].(mcp.TextContent).Text
wantPath := filepath.Join(home, ".gitea-mcp", "attachments", owner, repo, "large-uuid-1.bin")
if !strings.Contains(body, wantPath) {
t.Fatalf("result missing path %q: %s", wantPath, body)
}
data, err := os.ReadFile(wantPath)
if err != nil {
t.Fatalf("ReadFile(%q): %v", wantPath, err)
}
if string(data) != payload {
t.Fatalf("saved payload mismatch")
}
if !strings.Contains(body, `"bytes":32`) {
t.Fatalf("result missing bytes: %s", body)
}
}