mirror of
https://gitea.com/gitea/gitea-mcp.git
synced 2026-08-27 02:27:45 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 72bbfabf00 |
@@ -0,0 +1,193 @@
|
||||
package label
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"sort"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"gitea.com/gitea/gitea-mcp/pkg/flag"
|
||||
"gitea.com/gitea/gitea-mcp/pkg/tool"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
func Test_Tool_Registration(t *testing.T) {
|
||||
if got := Tool.Scope(); got != "label" {
|
||||
t.Fatalf("Scope() = %q, want %q", got, "label")
|
||||
}
|
||||
|
||||
readTools := Tool.ReadTools()
|
||||
if len(readTools) != 1 || readTools[0].Tool.Name != LabelReadToolName {
|
||||
t.Fatalf("ReadTools() = %v, want exactly [%s]", toolNames(readTools), LabelReadToolName)
|
||||
}
|
||||
if !readTools[0].Tool.Annotations.ReadOnlyHint {
|
||||
t.Fatalf("%s must be marked read-only", LabelReadToolName)
|
||||
}
|
||||
|
||||
writeTools := Tool.WriteTools()
|
||||
if len(writeTools) != 1 || writeTools[0].Tool.Name != LabelWriteToolName {
|
||||
t.Fatalf("WriteTools() = %v, want exactly [%s]", toolNames(writeTools), LabelWriteToolName)
|
||||
}
|
||||
if writeTools[0].Tool.Annotations.ReadOnlyHint {
|
||||
t.Fatalf("%s must not be marked read-only", LabelWriteToolName)
|
||||
}
|
||||
|
||||
assertMethodEnum(t, LabelReadTool, []string{"list_repo_labels", "get_repo_label", "list_org_labels"})
|
||||
assertMethodEnum(t, LabelWriteTool, []string{
|
||||
"create_repo_label", "edit_repo_label", "delete_repo_label",
|
||||
"create_org_label", "edit_org_label", "delete_org_label",
|
||||
})
|
||||
}
|
||||
|
||||
func toolNames(tools []tool.ServerTool) []string {
|
||||
names := make([]string, len(tools))
|
||||
for i, serverTool := range tools {
|
||||
names[i] = serverTool.Tool.Name
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func assertMethodEnum(t *testing.T, definition *mcp.Tool, want []string) {
|
||||
t.Helper()
|
||||
|
||||
schema, ok := definition.InputSchema.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("%s: input schema = %T, want map[string]any", definition.Name, definition.InputSchema)
|
||||
}
|
||||
properties, ok := schema["properties"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("%s: properties = %T, want map[string]any", definition.Name, schema["properties"])
|
||||
}
|
||||
method, ok := properties["method"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("%s: method property = %T, want map[string]any", definition.Name, properties["method"])
|
||||
}
|
||||
enum, ok := method["enum"].([]string)
|
||||
if !ok {
|
||||
t.Fatalf("%s: method enum = %T, want []string", definition.Name, method["enum"])
|
||||
}
|
||||
|
||||
got := append([]string{}, enum...)
|
||||
sort.Strings(got)
|
||||
wantSorted := append([]string{}, want...)
|
||||
sort.Strings(wantSorted)
|
||||
if !reflect.DeepEqual(got, wantSorted) {
|
||||
t.Fatalf("%s: method enum = %v, want %v", definition.Name, enum, want)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_labelReadFn_listRepoLabels(t *testing.T) {
|
||||
const (
|
||||
owner = "octo"
|
||||
repo = "demo"
|
||||
)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/version":
|
||||
_, _ = w.Write([]byte(`{"version":"1.12.0"}`))
|
||||
case fmt.Sprintf("/api/v1/repos/%s/%s/labels", owner, repo):
|
||||
_, _ = w.Write([]byte(`[{"id":1,"name":"bug","color":"ff0000","description":"a bug"}]`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
withTestFlags(t, server.URL)
|
||||
|
||||
result, err := labelReadFn(context.Background(), map[string]any{
|
||||
"method": "list_repo_labels",
|
||||
"owner": owner,
|
||||
"repo": repo,
|
||||
})
|
||||
if err != nil || result.IsError {
|
||||
t.Fatalf("list_repo_labels err=%v result=%v", err, result)
|
||||
}
|
||||
|
||||
var labels []map[string]any
|
||||
decodeResult(t, result, &labels)
|
||||
if len(labels) != 1 || labels[0]["name"] != "bug" {
|
||||
t.Fatalf("unexpected labels: %v", labels)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_labelWriteFn_createRepoLabel(t *testing.T) {
|
||||
const (
|
||||
owner = "octo"
|
||||
repo = "demo"
|
||||
)
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
body map[string]any
|
||||
)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/api/v1/version":
|
||||
_, _ = w.Write([]byte(`{"version":"1.12.0"}`))
|
||||
case r.URL.Path == fmt.Sprintf("/api/v1/repos/%s/%s/labels", owner, repo) && r.Method == http.MethodPost:
|
||||
mu.Lock()
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
mu.Unlock()
|
||||
_, _ = w.Write([]byte(`{"id":7,"name":"bug","color":"ff0000","description":"a bug"}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
withTestFlags(t, server.URL)
|
||||
|
||||
result, err := labelWriteFn(context.Background(), map[string]any{
|
||||
"method": "create_repo_label",
|
||||
"owner": owner,
|
||||
"repo": repo,
|
||||
"name": "bug",
|
||||
"color": "ff0000",
|
||||
"description": "a bug",
|
||||
})
|
||||
if err != nil || result.IsError {
|
||||
t.Fatalf("create_repo_label err=%v result=%v", err, result)
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if body["name"] != "bug" || body["color"] != "ff0000" {
|
||||
t.Fatalf("unexpected request body: %v", body)
|
||||
}
|
||||
|
||||
var label map[string]any
|
||||
decodeResult(t, result, &label)
|
||||
if label["name"] != "bug" {
|
||||
t.Fatalf("unexpected label: %v", label)
|
||||
}
|
||||
}
|
||||
|
||||
func withTestFlags(t *testing.T, host string) {
|
||||
t.Helper()
|
||||
origHost, origToken, origVersion := flag.Host, flag.Token, flag.Version
|
||||
flag.Host, flag.Token, flag.Version = host, "", "test"
|
||||
t.Cleanup(func() { flag.Host, flag.Token, flag.Version = origHost, origToken, origVersion })
|
||||
}
|
||||
|
||||
func decodeResult(t *testing.T, result *mcp.CallToolResult, out any) {
|
||||
t.Helper()
|
||||
if len(result.Content) != 1 {
|
||||
t.Fatalf("result content = %v, want exactly one item", result.Content)
|
||||
}
|
||||
text, ok := result.Content[0].(*mcp.TextContent)
|
||||
if !ok {
|
||||
t.Fatalf("result content = %T, want *mcp.TextContent", result.Content[0])
|
||||
}
|
||||
if err := json.Unmarshal([]byte(text.Text), out); err != nil {
|
||||
t.Fatalf("decode result: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -7,14 +7,122 @@ import (
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"sort"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"gitea.com/gitea/gitea-mcp/pkg/flag"
|
||||
"gitea.com/gitea/gitea-mcp/pkg/tool"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
func Test_Tool_Registration(t *testing.T) {
|
||||
if got := Tool.Scope(); got != "milestone" {
|
||||
t.Fatalf("Scope() = %q, want %q", got, "milestone")
|
||||
}
|
||||
|
||||
readTools := Tool.ReadTools()
|
||||
if len(readTools) != 1 || readTools[0].Tool.Name != MilestoneReadToolName {
|
||||
t.Fatalf("ReadTools() = %v, want exactly [%s]", toolNames(readTools), MilestoneReadToolName)
|
||||
}
|
||||
if !readTools[0].Tool.Annotations.ReadOnlyHint {
|
||||
t.Fatalf("%s must be marked read-only", MilestoneReadToolName)
|
||||
}
|
||||
|
||||
writeTools := Tool.WriteTools()
|
||||
if len(writeTools) != 1 || writeTools[0].Tool.Name != MilestoneWriteToolName {
|
||||
t.Fatalf("WriteTools() = %v, want exactly [%s]", toolNames(writeTools), MilestoneWriteToolName)
|
||||
}
|
||||
if writeTools[0].Tool.Annotations.ReadOnlyHint {
|
||||
t.Fatalf("%s must not be marked read-only", MilestoneWriteToolName)
|
||||
}
|
||||
|
||||
assertMethodEnum(t, MilestoneReadTool, []string{"get", "list"})
|
||||
assertMethodEnum(t, MilestoneWriteTool, []string{"create", "update", "edit", "delete"})
|
||||
}
|
||||
|
||||
func toolNames(tools []tool.ServerTool) []string {
|
||||
names := make([]string, len(tools))
|
||||
for i, serverTool := range tools {
|
||||
names[i] = serverTool.Tool.Name
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func assertMethodEnum(t *testing.T, definition *mcp.Tool, want []string) {
|
||||
t.Helper()
|
||||
|
||||
schema, ok := definition.InputSchema.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("%s: input schema = %T, want map[string]any", definition.Name, definition.InputSchema)
|
||||
}
|
||||
properties, ok := schema["properties"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("%s: properties = %T, want map[string]any", definition.Name, schema["properties"])
|
||||
}
|
||||
method, ok := properties["method"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("%s: method property = %T, want map[string]any", definition.Name, properties["method"])
|
||||
}
|
||||
enum, ok := method["enum"].([]string)
|
||||
if !ok {
|
||||
t.Fatalf("%s: method enum = %T, want []string", definition.Name, method["enum"])
|
||||
}
|
||||
|
||||
got := append([]string{}, enum...)
|
||||
sort.Strings(got)
|
||||
wantSorted := append([]string{}, want...)
|
||||
sort.Strings(wantSorted)
|
||||
if !reflect.DeepEqual(got, wantSorted) {
|
||||
t.Fatalf("%s: method enum = %v, want %v", definition.Name, enum, want)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_listMilestonesFn(t *testing.T) {
|
||||
const (
|
||||
owner = "octo"
|
||||
repo = "demo"
|
||||
)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/version":
|
||||
_, _ = w.Write([]byte(`{"version":"1.12.0"}`))
|
||||
case fmt.Sprintf("/api/v1/repos/%s/%s/milestones", owner, repo):
|
||||
_, _ = w.Write([]byte(`[{"id":1,"title":"v1","state":"open"}]`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
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 }()
|
||||
|
||||
result, err := listMilestonesFn(context.Background(), map[string]any{
|
||||
"owner": owner,
|
||||
"repo": repo,
|
||||
})
|
||||
if err != nil || result.IsError {
|
||||
t.Fatalf("list err=%v result=%v", err, result)
|
||||
}
|
||||
|
||||
text, ok := result.Content[0].(*mcp.TextContent)
|
||||
if !ok {
|
||||
t.Fatalf("result content = %T, want *mcp.TextContent", result.Content[0])
|
||||
}
|
||||
var milestones []map[string]any
|
||||
if err := json.Unmarshal([]byte(text.Text), &milestones); err != nil {
|
||||
t.Fatalf("decode result: %v", err)
|
||||
}
|
||||
if len(milestones) != 1 || milestones[0]["title"] != "v1" {
|
||||
t.Fatalf("unexpected milestones: %v", milestones)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_milestoneWriteFn_dueOn(t *testing.T) {
|
||||
const (
|
||||
owner = "octo"
|
||||
|
||||
+2
-41
@@ -20,13 +20,6 @@ import (
|
||||
|
||||
var Tool = tool.New("pull_request")
|
||||
|
||||
// commentWithAssets wraps the SDK Comment to capture the `assets` field that
|
||||
// the SDK currently drops on the issue comments endpoint.
|
||||
type commentWithAssets struct {
|
||||
gitea_sdk.Comment
|
||||
Assets []*gitea_sdk.Attachment `json:"assets"`
|
||||
}
|
||||
|
||||
const (
|
||||
ListRepoPullRequestsToolName = "list_pull_requests"
|
||||
PullRequestReadToolName = "pull_request_read"
|
||||
@@ -50,9 +43,9 @@ var (
|
||||
|
||||
PullRequestReadTool = tool.NewDefinition(
|
||||
PullRequestReadToolName,
|
||||
"Read pull request: details, diff, changed files, head commit status, reviews, review comments, discussion comments.",
|
||||
"Read pull request: details, diff, changed files, head commit status, reviews, review comments.",
|
||||
annotation.ReadOnly("Read pull request details"),
|
||||
tool.String("method", tool.Required(), tool.Enum("get", "get_diff", "get_files", "get_status", "get_reviews", "get_review", "get_review_comments", "get_comments")),
|
||||
tool.String("method", tool.Required(), tool.Enum("get", "get_diff", "get_files", "get_status", "get_reviews", "get_review", "get_review_comments")),
|
||||
tool.String("owner", tool.Required(), tool.Description(params.OwnerDesc)),
|
||||
tool.String("repo", tool.Required(), tool.Description(params.RepoDesc)),
|
||||
tool.Number("pull_number", tool.Required()),
|
||||
@@ -158,8 +151,6 @@ func pullRequestReadFn(ctx context.Context, args map[string]any) (*mcp.CallToolR
|
||||
return getPullRequestReviewFn(ctx, args)
|
||||
case "get_review_comments":
|
||||
return listPullRequestReviewCommentsFn(ctx, args)
|
||||
case "get_comments":
|
||||
return listPullRequestCommentsFn(ctx, args)
|
||||
default:
|
||||
return to.ErrorResult(fmt.Errorf("unknown method: %s", method))
|
||||
}
|
||||
@@ -612,36 +603,6 @@ func listPullRequestReviewCommentsFn(ctx context.Context, args map[string]any) (
|
||||
return to.TextResult(slimReviewComments(comments))
|
||||
}
|
||||
|
||||
func listPullRequestCommentsFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
|
||||
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)
|
||||
}
|
||||
index, err := params.GetIndex(args, "pull_number")
|
||||
if err != nil {
|
||||
return to.ErrorResult(err)
|
||||
}
|
||||
|
||||
// PRs are issues internally, so the regular discussion comments live on
|
||||
// the issue comments endpoint rather than a pull-specific one.
|
||||
var comments []commentWithAssets
|
||||
path := fmt.Sprintf("repos/%s/%s/issues/%d/comments", url.PathEscape(owner), url.PathEscape(repo), index)
|
||||
if _, err := gitea.DoJSON(ctx, "GET", path, nil, nil, &comments); err != nil {
|
||||
return to.ErrorResult(fmt.Errorf("get %v/%v/pr/%v comments err: %v", owner, repo, index, err))
|
||||
}
|
||||
out := make([]map[string]any, 0, len(comments))
|
||||
for i := range comments {
|
||||
m := slimComment(&comments[i].Comment)
|
||||
m["body"] = slim.BodyWithAttachments(comments[i].Body, comments[i].Assets)
|
||||
out = append(out, m)
|
||||
}
|
||||
return to.TextResult(out)
|
||||
}
|
||||
|
||||
func createPullRequestReviewFn(ctx context.Context, args map[string]any) (*mcp.CallToolResult, error) {
|
||||
owner, err := params.GetString(args, "owner")
|
||||
if err != nil {
|
||||
|
||||
@@ -943,91 +943,6 @@ func Test_closePullRequestFn(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func Test_listPullRequestCommentsFn_missingArgs(t *testing.T) {
|
||||
result, err := listPullRequestCommentsFn(context.Background(), map[string]any{
|
||||
"owner": "octo",
|
||||
"repo": "demo",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("listPullRequestCommentsFn() error = %v", err)
|
||||
}
|
||||
if result == nil || !result.IsError {
|
||||
t.Fatalf("listPullRequestCommentsFn() result = %#v, want an error result for missing pull_number", result)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_listPullRequestCommentsFn_apiError(t *testing.T) {
|
||||
const (
|
||||
owner = "octo"
|
||||
repo = "demo"
|
||||
index = 7
|
||||
)
|
||||
|
||||
serveStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/comments", owner, repo, index) {
|
||||
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
http.Error(w, "boom", http.StatusInternalServerError)
|
||||
})
|
||||
|
||||
args := map[string]any{
|
||||
"owner": owner, "repo": repo, "pull_number": float64(index),
|
||||
}
|
||||
result, err := listPullRequestCommentsFn(context.Background(), args)
|
||||
if err != nil {
|
||||
t.Fatalf("listPullRequestCommentsFn() error = %v", err)
|
||||
}
|
||||
if result == nil || !result.IsError {
|
||||
t.Fatalf("listPullRequestCommentsFn() result = %#v, want an error result on API failure", result)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_listPullRequestCommentsFn_decodesComments(t *testing.T) {
|
||||
const (
|
||||
owner = "octo"
|
||||
repo = "demo"
|
||||
index = 7
|
||||
)
|
||||
|
||||
serveStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/comments", owner, repo, index) {
|
||||
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`[
|
||||
{"id": 1, "body": "see this", "assets": [
|
||||
{"id": 9, "name": "log.txt", "size": 200, "browser_download_url": "https://example/log.txt"}
|
||||
]},
|
||||
{"id": 2, "body": "no attachment", "assets": []}
|
||||
]`))
|
||||
})
|
||||
|
||||
args := map[string]any{
|
||||
"method": "get_comments", "owner": owner, "repo": repo, "pull_number": float64(index),
|
||||
}
|
||||
result, err := pullRequestReadFn(context.Background(), args)
|
||||
if err != nil {
|
||||
t.Fatalf("pullRequestReadFn() error = %v", err)
|
||||
}
|
||||
if result.IsError {
|
||||
t.Fatalf("unexpected error result: %v", result.Content)
|
||||
}
|
||||
body := result.Content[0].(*mcp.TextContent).Text
|
||||
if !strings.Contains(body, `[log.txt](https://example/log.txt)`) {
|
||||
t.Fatalf("expected attachment markdown inlined in body, got: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, `"no attachment"`) {
|
||||
t.Fatalf("expected second comment body preserved, got: %s", body)
|
||||
}
|
||||
if strings.Contains(body, `"assets"`) {
|
||||
t.Fatalf("assets should be inlined into body, not a separate field: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_reopenPullRequestFn(t *testing.T) {
|
||||
const (
|
||||
owner = "octo"
|
||||
|
||||
@@ -164,17 +164,3 @@ func slimReviewComments(comments []*gitea_sdk.PullReviewComment) []map[string]an
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func slimComment(c *gitea_sdk.Comment) map[string]any {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return map[string]any{
|
||||
"id": c.ID,
|
||||
"body": c.Body,
|
||||
"user": slim.UserLogin(c.Poster),
|
||||
"html_url": c.HTMLURL,
|
||||
"created_at": c.Created,
|
||||
"updated_at": c.Updated,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user