refactor: replace mcp-go with the official MCP Go SDK (#223)

## Summary

Replace `github.com/mark3labs/mcp-go` with the official
`github.com/modelcontextprotocol/go-sdk v1.7.0`.

All 54 existing tools, scopes, CLI, `stdio` and HTTP (`/mcp`) modes, and
per-request authentication remain supported. This PR is limited to the SDK
equivalence migration; the stateless 2026 HTTP transport is deferred to a
follow-up PR.

## Verification

- Tool definitions were compared with `main` and matched for all 54 tools.
- `make lint`, `make fmt`, `go test -count=1 -race ./...`, `make build`, and
  `make tidy` pass.

---------

Co-authored-by: bircni <bircni@icloud.com>
Co-authored-by: silverwind <me@silverwind.io>
Reviewed-on: https://gitea.com/gitea/gitea-mcp/pulls/223
Reviewed-by: silverwind <2021+silverwind@noreply.gitea.com>
Reviewed-by: bircni <bircni@icloud.com>
Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>
This commit is contained in:
Bo-Yi Wu
2026-08-06 05:36:21 +00:00
committed by Bo-Yi Wu (吳柏毅)
parent 8b236c2e26
commit efcbdbb17f
48 changed files with 2465 additions and 1570 deletions
+11 -13
View File
@@ -1,18 +1,16 @@
package annotation
import "github.com/mark3labs/mcp-go/mcp"
import "github.com/modelcontextprotocol/go-sdk/mcp"
func ReadOnly(title string) mcp.ToolAnnotation {
func ReadOnly(title string) *mcp.ToolAnnotations {
return &mcp.ToolAnnotations{Title: title, ReadOnlyHint: true}
}
func Write(title string) *mcp.ToolAnnotations {
return &mcp.ToolAnnotations{Title: title}
}
func Destructive(title string) *mcp.ToolAnnotations {
t := true
return mcp.ToolAnnotation{Title: title, ReadOnlyHint: &t}
}
func Write(title string) mcp.ToolAnnotation {
f := false
return mcp.ToolAnnotation{Title: title, ReadOnlyHint: &f}
}
func Destructive(title string) mcp.ToolAnnotation {
f, t := false, true
return mcp.ToolAnnotation{Title: title, ReadOnlyHint: &f, DestructiveHint: &t}
return &mcp.ToolAnnotations{Title: title, DestructiveHint: &t}
}
+50
View File
@@ -0,0 +1,50 @@
package annotation
import (
"encoding/json"
"maps"
"testing"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// The hints are what clients use to decide whether a tool needs confirmation, so
// assert the encoded form: an omitted readOnlyHint reads as false either way, but
// only the explicit form survives a client that checks for the key.
func TestAnnotations(t *testing.T) {
for _, test := range []struct {
name string
annotations *mcp.ToolAnnotations
want map[string]any
}{
{
name: "ReadOnly",
annotations: ReadOnly("Read"),
want: map[string]any{"title": "Read", "readOnlyHint": true, "idempotentHint": false},
},
{
name: "Write",
annotations: Write("Write"),
want: map[string]any{"title": "Write", "readOnlyHint": false, "idempotentHint": false},
},
{
name: "Destructive",
annotations: Destructive("Delete"),
want: map[string]any{"title": "Delete", "readOnlyHint": false, "idempotentHint": false, "destructiveHint": true},
},
} {
t.Run(test.name, func(t *testing.T) {
encoded, err := json.Marshal(test.annotations)
if err != nil {
t.Fatalf("json.Marshal() error = %v", err)
}
var got map[string]any
if err := json.Unmarshal(encoded, &got); err != nil {
t.Fatalf("json.Unmarshal() error = %v", err)
}
if !maps.Equal(got, test.want) {
t.Errorf("annotations = %s, want %v", encoded, test.want)
}
})
}
}
+4 -2
View File
@@ -7,7 +7,7 @@ import (
"gitea.com/gitea/gitea-mcp/pkg/flag"
"gitea.com/gitea/gitea-mcp/pkg/log"
"github.com/mark3labs/mcp-go/mcp"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func TextResult(v any) (*mcp.CallToolResult, error) {
@@ -18,7 +18,9 @@ func TextResult(v any) (*mcp.CallToolResult, error) {
if flag.Debug {
log.Debugf("Text Result: %s", string(resultBytes))
}
return mcp.NewToolResultText(string(resultBytes)), nil
return &mcp.CallToolResult{
Content: []mcp.Content{&mcp.TextContent{Text: string(resultBytes)}},
}, nil
}
func ErrorResult(err error) (*mcp.CallToolResult, error) {
+33
View File
@@ -0,0 +1,33 @@
package to
import (
"errors"
"testing"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func TestTextResult(t *testing.T) {
result, err := TextResult(map[string]any{"name": "gitea"})
if err != nil {
t.Fatalf("TextResult() error = %v", err)
}
if len(result.Content) != 1 {
t.Fatalf("len(Content) = %d, want 1", len(result.Content))
}
content, ok := result.Content[0].(*mcp.TextContent)
if !ok {
t.Fatalf("Content[0] type = %T, want *mcp.TextContent", result.Content[0])
}
if content.Text != `{"name":"gitea"}` {
t.Errorf("Text = %q, want JSON object", content.Text)
}
}
func TestErrorResult(t *testing.T) {
want := errors.New("failed")
result, err := ErrorResult(want)
if result != nil || !errors.Is(err, want) {
t.Errorf("ErrorResult() = (%#v, %v), want (nil, %v)", result, err, want)
}
}
+106
View File
@@ -0,0 +1,106 @@
package tool
import "github.com/modelcontextprotocol/go-sdk/mcp"
// Property describes one property in a tool's input schema.
type Property struct {
name string
schema map[string]any
required bool
}
// PropertyOption configures one property in a tool's input schema.
type PropertyOption func(*Property)
// NewDefinition builds a tool definition without enabling SDK-side validation.
func NewDefinition(name, description string, annotations *mcp.ToolAnnotations, properties ...Property) *mcp.Tool {
inputProperties := make(map[string]any, len(properties))
required := make([]string, 0, len(properties))
for _, property := range properties {
inputProperties[property.name] = property.schema
if property.required {
required = append(required, property.name)
}
}
inputSchema := map[string]any{
"type": "object",
"properties": inputProperties,
}
if len(required) > 0 {
inputSchema["required"] = required
}
return &mcp.Tool{
Name: name,
Description: description,
Annotations: annotations,
InputSchema: inputSchema,
}
}
func String(name string, options ...PropertyOption) Property {
return newProperty(name, map[string]any{"type": "string"}, options...)
}
func Number(name string, options ...PropertyOption) Property {
return newProperty(name, map[string]any{"type": "number"}, options...)
}
func Boolean(name string, options ...PropertyOption) Property {
return newProperty(name, map[string]any{"type": "boolean"}, options...)
}
func Array(name string, options ...PropertyOption) Property {
return newProperty(name, map[string]any{"type": "array"}, options...)
}
func Object(name string, options ...PropertyOption) Property {
return newProperty(name, map[string]any{"type": "object", "properties": map[string]any{}}, options...)
}
func newProperty(name string, schema map[string]any, options ...PropertyOption) Property {
property := Property{name: name, schema: schema}
for _, option := range options {
option(&property)
}
return property
}
// Required marks the property as required on the parent schema. It is not a
// property-level keyword, so it never touches the emitted property schema.
func Required() PropertyOption {
return func(property *Property) {
property.required = true
}
}
func Description(description string) PropertyOption {
return func(property *Property) {
property.schema["description"] = description
}
}
func Enum(values ...string) PropertyOption {
return func(property *Property) {
property.schema["enum"] = values
}
}
func Default(value any) PropertyOption {
return func(property *Property) {
property.schema["default"] = value
}
}
func Minimum(value float64) PropertyOption {
return func(property *Property) {
property.schema["minimum"] = value
}
}
func Items(schema any) PropertyOption {
return func(property *Property) {
property.schema["items"] = schema
}
}
+71
View File
@@ -0,0 +1,71 @@
package tool
import (
"reflect"
"testing"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func TestNewDefinition(t *testing.T) {
annotations := &mcp.ToolAnnotations{Title: "Example", ReadOnlyHint: true}
definition := NewDefinition(
"example",
"Example tool",
annotations,
String("owner", Required(), Description("repository owner"), Enum("one", "two"), Default("one")),
Number("page", Required(), Default(1), Minimum(1)),
Boolean("draft"),
Array("labels", Items(map[string]any{"type": "string"})),
Object("inputs", Description("workflow inputs")),
)
if definition.Name != "example" || definition.Description != "Example tool" {
t.Fatalf("definition = %#v", definition)
}
if definition.Annotations != annotations {
t.Fatal("NewDefinition did not preserve annotations")
}
want := map[string]any{
"type": "object",
"properties": map[string]any{
"owner": map[string]any{
"type": "string",
"description": "repository owner",
"enum": []string{"one", "two"},
"default": "one",
},
"page": map[string]any{
"type": "number",
"default": 1,
"minimum": float64(1),
},
"draft": map[string]any{"type": "boolean"},
"labels": map[string]any{
"type": "array",
"items": map[string]any{"type": "string"},
},
"inputs": map[string]any{
"type": "object",
"properties": map[string]any{},
"description": "workflow inputs",
},
},
"required": []string{"owner", "page"},
}
if !reflect.DeepEqual(definition.InputSchema, want) {
t.Errorf("InputSchema = %#v, want %#v", definition.InputSchema, want)
}
}
func TestNewDefinitionWithoutRequiredProperties(t *testing.T) {
definition := NewDefinition("empty", "", nil)
schema := definition.InputSchema.(map[string]any)
if _, ok := schema["required"]; ok {
t.Errorf("InputSchema unexpectedly contains required: %#v", schema)
}
if got := schema["properties"]; !reflect.DeepEqual(got, map[string]any{}) {
t.Errorf("properties = %#v, want empty map", got)
}
}
+105
View File
@@ -0,0 +1,105 @@
package tool
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/modelcontextprotocol/go-sdk/jsonrpc"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func callTool(handler Handler, arguments json.RawMessage) (*mcp.CallToolResult, error) {
serverTool := ServerTool{Tool: &mcp.Tool{Name: "example"}, Handler: handler}
return serverTool.MCPHandler()(context.Background(), &mcp.CallToolRequest{
Params: &mcp.CallToolParamsRaw{Arguments: arguments},
})
}
func captureArguments(into *map[string]any) Handler {
return func(_ context.Context, arguments map[string]any) (*mcp.CallToolResult, error) {
*into = arguments
return &mcp.CallToolResult{}, nil
}
}
func TestMCPHandler(t *testing.T) {
var got map[string]any
result, err := callTool(captureArguments(&got), json.RawMessage(`{"count":2,"nested":{"enabled":true}}`))
if err != nil {
t.Fatalf("MCPHandler() error = %v", err)
}
if result == nil {
t.Fatal("MCPHandler() result is nil")
}
if got["count"] != float64(2) {
t.Errorf("count type/value = %T(%v), want float64(2)", got["count"], got["count"])
}
}
func TestMCPHandlerRejectsInvalidArguments(t *testing.T) {
called := false
handler := func(context.Context, map[string]any) (*mcp.CallToolResult, error) {
called = true
return &mcp.CallToolResult{}, nil
}
for _, arguments := range []json.RawMessage{json.RawMessage(`[]`), json.RawMessage(`"text"`), json.RawMessage(`{"broken"`)} {
_, err := callTool(handler, arguments)
assertProtocolErrorCode(t, err, jsonrpc.CodeInvalidParams)
}
if called {
t.Fatal("handler was called with invalid arguments")
}
}
// Tools without parameters are callable with an omitted or null "arguments",
// which is what clients send and what mcp-go accepted before the SDK migration.
func TestMCPHandlerAcceptsAbsentArguments(t *testing.T) {
for _, arguments := range []json.RawMessage{nil, json.RawMessage(`null`)} {
var got map[string]any
if _, err := callTool(captureArguments(&got), arguments); err != nil {
t.Fatalf("MCPHandler() with arguments %s error = %v", arguments, err)
}
if got == nil || len(got) != 0 {
t.Errorf("arguments = %#v, want an empty map", got)
}
}
}
func TestMCPHandlerConvertsErrorsAndRecoversPanics(t *testing.T) {
for _, test := range []struct {
name string
handler Handler
}{
{
name: "handler error",
handler: func(context.Context, map[string]any) (*mcp.CallToolResult, error) {
return nil, errors.New("failed")
},
},
{
name: "panic",
handler: func(context.Context, map[string]any) (*mcp.CallToolResult, error) {
panic("failed")
},
},
} {
t.Run(test.name, func(t *testing.T) {
_, err := callTool(test.handler, nil)
assertProtocolErrorCode(t, err, jsonrpc.CodeInternalError)
})
}
}
func assertProtocolErrorCode(t *testing.T, err error, want int64) {
t.Helper()
var protocolErr *jsonrpc.Error
if !errors.As(err, &protocolErr) {
t.Fatalf("error = %v, want *jsonrpc.Error", err)
}
if protocolErr.Code != want {
t.Errorf("error code = %d, want %d", protocolErr.Code, want)
}
}
+73 -12
View File
@@ -1,26 +1,38 @@
package tool
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"gitea.com/gitea/gitea-mcp/pkg/flag"
"gitea.com/gitea/gitea-mcp/pkg/log"
"github.com/mark3labs/mcp-go/server"
"github.com/modelcontextprotocol/go-sdk/jsonrpc"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
type Handler func(context.Context, map[string]any) (*mcp.CallToolResult, error)
type ServerTool struct {
Tool *mcp.Tool
Handler Handler
}
type Tool struct {
scope string
write []server.ServerTool
read []server.ServerTool
write []ServerTool
read []ServerTool
}
func New(scope string) *Tool {
return &Tool{
scope: scope,
write: make([]server.ServerTool, 0, 100),
read: make([]server.ServerTool, 0, 100),
write: make([]ServerTool, 0, 100),
read: make([]ServerTool, 0, 100),
}
}
@@ -29,23 +41,23 @@ func (t *Tool) Scope() string {
return t.scope
}
func (t *Tool) RegisterWrite(s server.ServerTool) {
func (t *Tool) RegisterWrite(s ServerTool) {
t.write = append(t.write, s)
}
func (t *Tool) RegisterRead(s server.ServerTool) {
func (t *Tool) RegisterRead(s ServerTool) {
t.read = append(t.read, s)
}
// ReadTools returns the read-only tools registered on this domain, ignoring
// the read-only and allowlist flags that Tools applies.
func (t *Tool) ReadTools() []server.ServerTool {
func (t *Tool) ReadTools() []ServerTool {
return t.read
}
// WriteTools returns the write tools registered on this domain, ignoring the
// read-only and allowlist flags that Tools applies.
func (t *Tool) WriteTools() []server.ServerTool {
func (t *Tool) WriteTools() []ServerTool {
return t.write
}
@@ -53,8 +65,8 @@ func (t *Tool) WriteTools() []server.ServerTool {
// read-only filter and the scope/tool allowlists (union semantics: a tool is
// kept if its domain's scope is in AllowedScopes OR its name is in
// AllowedTools). With no allowlists set, all tools pass through unchanged.
func (t *Tool) Tools() []server.ServerTool {
all := make([]server.ServerTool, 0, len(t.write)+len(t.read))
func (t *Tool) Tools() []ServerTool {
all := make([]ServerTool, 0, len(t.write)+len(t.read))
if !flag.ReadOnly {
all = append(all, t.write...)
}
@@ -63,7 +75,7 @@ func (t *Tool) Tools() []server.ServerTool {
return all
}
_, scopeAllowed := flag.AllowedScopes[t.scope]
filtered := make([]server.ServerTool, 0, len(all))
filtered := make([]ServerTool, 0, len(all))
for _, st := range all {
_, toolAllowed := flag.AllowedTools[st.Tool.Name]
if scopeAllowed || toolAllowed {
@@ -73,6 +85,55 @@ func (t *Tool) Tools() []server.ServerTool {
return filtered
}
// MCPHandler adapts a project handler to the official SDK's low-level handler.
func (s ServerTool) MCPHandler() mcp.ToolHandler {
return func(ctx context.Context, req *mcp.CallToolRequest) (result *mcp.CallToolResult, err error) {
defer func() {
if recovered := recover(); recovered != nil {
panicErr := fmt.Errorf("panic recovered in %s tool handler: %v", s.Tool.Name, recovered)
log.Errorf("%s", panicErr)
err = internalError(panicErr)
}
}()
arguments, err := decodeArguments(req.Params.Arguments)
if err != nil {
return nil, err
}
result, err = s.Handler(ctx, arguments)
if err != nil {
var protocolErr *jsonrpc.Error
if errors.As(err, &protocolErr) {
return nil, err
}
// Preserve mcp-go behavior; tool-result errors are a separate change.
return nil, internalError(err)
}
return result, nil
}
}
func decodeArguments(raw json.RawMessage) (map[string]any, error) {
// An omitted and a null "arguments" both mean the tool was called without any.
if len(raw) == 0 || string(raw) == "null" {
return map[string]any{}, nil
}
var arguments map[string]any
if err := json.Unmarshal(raw, &arguments); err != nil {
return nil, &jsonrpc.Error{
Code: jsonrpc.CodeInvalidParams,
Message: fmt.Sprintf("invalid tool arguments: %v", err),
}
}
return arguments, nil
}
func internalError(err error) error {
return &jsonrpc.Error{Code: jsonrpc.CodeInternalError, Message: err.Error()}
}
// warnUnmatched logs the names present in allowlist but absent from known,
// via logUnmatched, so WarnUnmatchedAllowedTools and WarnUnmatchedAllowedScopes
// share the same "collect, sort, no-op when empty" logic and can't drift.
+4 -5
View File
@@ -6,15 +6,14 @@ import (
"gitea.com/gitea/gitea-mcp/pkg/flag"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func makeTool(name string) server.ServerTool {
return server.ServerTool{Tool: mcp.NewTool(name)}
func makeTool(name string) ServerTool {
return ServerTool{Tool: &mcp.Tool{Name: name}}
}
func names(sts []server.ServerTool) []string {
func names(sts []ServerTool) []string {
out := make([]string, len(sts))
for i, st := range sts {
out[i] = st.Tool.Name