feat(tools): pr_create with identity footer

This commit is contained in:
Mathias Bergqvist
2026-05-04 22:20:33 +02:00
parent 5af8addc26
commit 9972dcd94e
5 changed files with 360 additions and 0 deletions

View File

@@ -31,6 +31,7 @@ func main() {
reg.Register(tools.NewRepoGet(giteaClient, ownerAllow)) reg.Register(tools.NewRepoGet(giteaClient, ownerAllow))
reg.Register(tools.NewFileRead(giteaClient, ownerAllow)) reg.Register(tools.NewFileRead(giteaClient, ownerAllow))
reg.Register(tools.NewFileWriteBranch(giteaClient, ownerAllow)) reg.Register(tools.NewFileWriteBranch(giteaClient, ownerAllow))
reg.Register(tools.NewPRCreate(giteaClient, ownerAllow))
mcpSrv := mcp.NewServer(mcp.ServerOptions{ mcpSrv := mcp.NewServer(mcp.ServerOptions{
Registry: reg, Registry: reg,

66
internal/gitea/pulls.go Normal file
View File

@@ -0,0 +1,66 @@
package gitea
import (
"context"
"encoding/json"
"fmt"
)
type PullRequest struct {
Number int `json:"number"`
Title string `json:"title"`
Body string `json:"body"`
HTMLURL string `json:"html_url"`
State string `json:"state"`
Draft bool `json:"draft"`
Head struct {
Ref string `json:"ref"`
} `json:"head"`
Base struct {
Ref string `json:"ref"`
} `json:"base"`
}
type CreatePullRequestArgs struct {
Title string `json:"title"`
Body string `json:"body"`
Head string `json:"head"`
Base string `json:"base"`
Draft bool `json:"draft"`
}
func (c *Client) CreatePullRequest(ctx context.Context, owner, repo string, args CreatePullRequestArgs) (*PullRequest, error) {
p := fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner, repo)
payload, err := json.Marshal(args)
if err != nil {
return nil, err
}
body, status, err := c.PostJSON(ctx, p, payload)
if err != nil {
return nil, err
}
if err := MapStatus(status, body); err != nil {
return nil, err
}
var pr PullRequest
if err := json.Unmarshal(body, &pr); err != nil {
return nil, err
}
return &pr, nil
}
func (c *Client) GetPullRequest(ctx context.Context, owner, repo string, index int) (*PullRequest, error) {
p := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d", owner, repo, index)
body, status, err := c.GetJSON(ctx, p)
if err != nil {
return nil, err
}
if err := MapStatus(status, body); err != nil {
return nil, err
}
var pr PullRequest
if err := json.Unmarshal(body, &pr); err != nil {
return nil, err
}
return &pr, nil
}

View File

@@ -0,0 +1,95 @@
package gitea_test
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"gitea.d-ma.be/mathias/gitea-mcp/internal/gitea"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const pullFixture = `{
"number": 7,
"title": "Add feature X",
"body": "This PR adds feature X",
"html_url": "http://example.com/pulls/7",
"state": "open",
"draft": false,
"head": {"ref": "feat/x"},
"base": {"ref": "main"}
}`
func TestCreatePullRequestSendsPayload(t *testing.T) {
var captured []byte
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v1/repos/o/r/pulls", r.URL.Path)
assert.Equal(t, http.MethodPost, r.Method)
var err error
captured, err = io.ReadAll(r.Body)
require.NoError(t, err)
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(pullFixture))
}))
defer srv.Close()
c := gitea.NewClient(srv.URL, "tok")
pr, err := c.CreatePullRequest(context.Background(), "o", "r", gitea.CreatePullRequestArgs{
Title: "Add feature X",
Body: "This PR adds feature X",
Head: "feat/x",
Base: "main",
Draft: false,
})
require.NoError(t, err)
var payload map[string]any
require.NoError(t, json.Unmarshal(captured, &payload))
assert.Equal(t, "Add feature X", payload["title"])
assert.Equal(t, "This PR adds feature X", payload["body"])
assert.Equal(t, "feat/x", payload["head"])
assert.Equal(t, "main", payload["base"])
assert.Equal(t, false, payload["draft"])
assert.Equal(t, 7, pr.Number)
assert.Equal(t, "Add feature X", pr.Title)
assert.Equal(t, "http://example.com/pulls/7", pr.HTMLURL)
assert.Equal(t, "feat/x", pr.Head.Ref)
assert.Equal(t, "main", pr.Base.Ref)
assert.Equal(t, "open", pr.State)
assert.False(t, pr.Draft)
}
func TestGetPullRequest(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v1/repos/o/r/pulls/42", r.URL.Path)
assert.Equal(t, http.MethodGet, r.Method)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{
"number": 42,
"title": "Fix bug Y",
"body": "Fixes Y",
"html_url": "http://example.com/pulls/42",
"state": "open",
"draft": true,
"head": {"ref": "fix/y"},
"base": {"ref": "main"}
}`))
}))
defer srv.Close()
c := gitea.NewClient(srv.URL, "tok")
pr, err := c.GetPullRequest(context.Background(), "o", "r", 42)
require.NoError(t, err)
assert.Equal(t, 42, pr.Number)
assert.Equal(t, "Fix bug Y", pr.Title)
assert.Equal(t, "http://example.com/pulls/42", pr.HTMLURL)
assert.Equal(t, "fix/y", pr.Head.Ref)
assert.Equal(t, "main", pr.Base.Ref)
assert.Equal(t, "open", pr.State)
assert.True(t, pr.Draft)
}

View File

@@ -0,0 +1,91 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"gitea.d-ma.be/mathias/gitea-mcp/internal/allowlist"
"gitea.d-ma.be/mathias/gitea-mcp/internal/auth"
"gitea.d-ma.be/mathias/gitea-mcp/internal/gitea"
"gitea.d-ma.be/mathias/gitea-mcp/internal/identity"
"gitea.d-ma.be/mathias/gitea-mcp/internal/registry"
)
type PRCreate struct {
c *gitea.Client
a *allowlist.Allowlist
}
func NewPRCreate(c *gitea.Client, a *allowlist.Allowlist) *PRCreate {
return &PRCreate{c: c, a: a}
}
func (t *PRCreate) Descriptor() registry.ToolDescriptor {
return registry.ToolDescriptor{
Name: "pr_create",
Description: "Create a pull request. Applies an identity footer to the PR body.",
InputSchema: json.RawMessage(`{
"type":"object",
"properties":{
"owner":{"type":"string"},
"name":{"type":"string"},
"title":{"type":"string"},
"body":{"type":"string"},
"head":{"type":"string"},
"base":{"type":"string"},
"draft":{"type":"boolean"}
},
"required":["owner","name","title","head","base"]
}`),
}
}
type prCreateArgs struct {
Owner string `json:"owner"`
Name string `json:"name"`
Title string `json:"title"`
Body string `json:"body"`
Head string `json:"head"`
Base string `json:"base"`
Draft bool `json:"draft"`
}
func (t *PRCreate) Call(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) {
var args prCreateArgs
if err := parseArgs(raw, &args); err != nil {
return nil, err
}
if err := t.a.Check(args.Owner); err != nil {
return nil, err
}
if args.Title == "" {
return nil, fmt.Errorf("title is required: %w", gitea.ErrValidation)
}
if args.Head == "" || args.Base == "" {
return nil, fmt.Errorf("head and base are required: %w", gitea.ErrValidation)
}
body := identity.ApplyFooter(args.Body, auth.Caller(ctx))
pr, err := t.c.CreatePullRequest(ctx, args.Owner, args.Name, gitea.CreatePullRequestArgs{
Title: args.Title,
Body: body,
Head: args.Head,
Base: args.Base,
Draft: args.Draft,
})
if err != nil {
return nil, err
}
return textOK(map[string]any{
"number": pr.Number,
"title": pr.Title,
"html_url": pr.HTMLURL,
"head": pr.Head.Ref,
"base": pr.Base.Ref,
"state": pr.State,
"draft": pr.Draft,
})
}

View File

@@ -0,0 +1,107 @@
package tools_test
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"gitea.d-ma.be/mathias/gitea-mcp/internal/allowlist"
"gitea.d-ma.be/mathias/gitea-mcp/internal/auth"
"gitea.d-ma.be/mathias/gitea-mcp/internal/gitea"
"gitea.d-ma.be/mathias/gitea-mcp/internal/tools"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const prFixture = `{
"number": 3,
"title": "My PR",
"body": "description",
"html_url": "http://example.com/pulls/3",
"state": "open",
"draft": false,
"head": {"ref": "feat/new"},
"base": {"ref": "main"}
}`
func callerContext(user string) context.Context {
var capturedCtx context.Context
h := auth.CallerMiddleware(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
capturedCtx = r.Context()
}))
req := httptest.NewRequest("POST", "/", nil)
if user != "" {
req.Header.Set("X-Auth-Request-User", user)
}
h.ServeHTTP(httptest.NewRecorder(), req)
return capturedCtx
}
func TestPRCreateAppliesIdentityFooter(t *testing.T) {
var captured []byte
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v1/repos/o/r/pulls", r.URL.Path)
var err error
captured, err = io.ReadAll(r.Body)
require.NoError(t, err)
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(prFixture))
}))
defer srv.Close()
tool := tools.NewPRCreate(gitea.NewClient(srv.URL, "tok"), allowlist.New([]string{"o"}))
ctx := callerContext("mathiasbq")
_, err := tool.Call(ctx, json.RawMessage(`{
"owner":"o","name":"r","title":"My PR","body":"description","head":"feat/new","base":"main"
}`))
require.NoError(t, err)
var payload map[string]any
require.NoError(t, json.Unmarshal(captured, &payload))
body, _ := payload["body"].(string)
assert.Contains(t, body, "_Created via git-mcp on behalf of @mathiasbq_")
}
func TestPRCreateNoFooterWhenCallerEmpty(t *testing.T) {
var captured []byte
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var err error
captured, err = io.ReadAll(r.Body)
require.NoError(t, err)
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(prFixture))
}))
defer srv.Close()
tool := tools.NewPRCreate(gitea.NewClient(srv.URL, "tok"), allowlist.New([]string{"o"}))
_, err := tool.Call(context.Background(), json.RawMessage(`{
"owner":"o","name":"r","title":"My PR","body":"description","head":"feat/new","base":"main"
}`))
require.NoError(t, err)
var payload map[string]any
require.NoError(t, json.Unmarshal(captured, &payload))
body, _ := payload["body"].(string)
assert.False(t, strings.Contains(body, "_Created via git-mcp on behalf of"), "footer should not be present when caller is empty")
}
func TestPRCreateAllowlistRejects(t *testing.T) {
tool := tools.NewPRCreate(gitea.NewClient("http://unused", ""), allowlist.New([]string{"allowed"}))
_, err := tool.Call(context.Background(), json.RawMessage(`{
"owner":"evil","name":"r","title":"T","head":"feat/x","base":"main"
}`))
require.Error(t, err)
}
func TestPRCreateRequiresTitle(t *testing.T) {
tool := tools.NewPRCreate(gitea.NewClient("http://unused", ""), allowlist.New([]string{"o"}))
_, err := tool.Call(context.Background(), json.RawMessage(`{
"owner":"o","name":"r","title":"","head":"feat/x","base":"main"
}`))
require.Error(t, err)
assert.ErrorIs(t, err, gitea.ErrValidation)
}