refactor!: replace mcp-go with the official MCP Go SDK

- Swap the mark3labs MCP dependency for modelcontextprotocol/go-sdk v1.7.0
- Add a declarative tool definition and JSON Schema builder to the tool package
- Adapt registered tools to the official low-level handler, recovering panics and mapping failures to JSON-RPC errors
- Narrow tool handlers to take a plain argument map instead of an SDK request type
- Rewire stdio and HTTP transports onto the official server, moving Authorization parsing into receiving middleware
- Add a golden contract test that locks the exposed tool schemas, plus SDK integration and helper tests
- Add a test target and run it in the pull request workflow

BREAKING CHANGE: The exported helpers change signature. Tool.RegisterRead and
Tool.RegisterWrite now take tool.ServerTool instead of server.ServerTool, and the
annotation constructors return *mcp.ToolAnnotations from the official SDK. Callers
must build tool definitions with tool.NewDefinition and handlers with the
func(context.Context, map[string]any) signature.

The 30-second SSE heartbeat is removed because the official SDK has no equivalent.
ServerOptions.KeepAlive is deliberately not used as a substitute, since it sends MCP
ping requests and ping is removed in protocol 2026. HTTP stays stateless=false, so
new clients negotiate at most 2025-11-25.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Bo-Yi Wu
2026-08-02 21:30:19 +08:00
parent 290d06b40b
commit 80c8b25d6e
49 changed files with 5277 additions and 1528 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}
}
+20
View File
@@ -0,0 +1,20 @@
package annotation
import "testing"
func TestAnnotations(t *testing.T) {
readOnly := ReadOnly("Read")
if readOnly.Title != "Read" || !readOnly.ReadOnlyHint || readOnly.DestructiveHint != nil {
t.Errorf("ReadOnly() = %#v", readOnly)
}
write := Write("Write")
if write.Title != "Write" || write.ReadOnlyHint || write.DestructiveHint != nil {
t.Errorf("Write() = %#v", write)
}
destructive := Destructive("Delete")
if destructive.Title != "Delete" || destructive.ReadOnlyHint || destructive.DestructiveHint == nil || !*destructive.DestructiveHint {
t.Errorf("Destructive() = %#v", destructive)
}
}
+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)
}
}
+110
View File
@@ -0,0 +1,110 @@
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(map[string]any)
// 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, "string", false, options...)
}
func Number(name string, options ...PropertyOption) Property {
return newProperty(name, "number", false, options...)
}
func Boolean(name string, options ...PropertyOption) Property {
return newProperty(name, "boolean", false, options...)
}
func Array(name string, options ...PropertyOption) Property {
return newProperty(name, "array", false, options...)
}
func Object(name string, options ...PropertyOption) Property {
return newProperty(name, "object", true, options...)
}
func newProperty(name, propertyType string, object bool, options ...PropertyOption) Property {
schema := map[string]any{"type": propertyType}
if object {
schema["properties"] = map[string]any{}
}
for _, option := range options {
option(schema)
}
required, _ := schema["required"].(bool)
delete(schema, "required")
return Property{name: name, schema: schema, required: required}
}
func Required() PropertyOption {
return func(schema map[string]any) {
schema["required"] = true
}
}
func Description(description string) PropertyOption {
return func(schema map[string]any) {
schema["description"] = description
}
}
func Enum(values ...string) PropertyOption {
return func(schema map[string]any) {
schema["enum"] = values
}
}
func Default(value any) PropertyOption {
return func(schema map[string]any) {
schema["default"] = value
}
}
func Minimum(value float64) PropertyOption {
return func(schema map[string]any) {
schema["minimum"] = value
}
}
func Items(schema any) PropertyOption {
return func(propertySchema map[string]any) {
propertySchema["items"] = schema
}
}
+80
View File
@@ -0,0 +1,80 @@
package tool
import (
"encoding/json"
"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)
}
data, err := json.Marshal(definition)
if err != nil {
t.Fatalf("json.Marshal() error = %v", err)
}
if !json.Valid(data) {
t.Fatalf("json.Marshal() returned invalid JSON: %s", data)
}
}
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)
}
}
+100
View File
@@ -0,0 +1,100 @@
package tool
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/modelcontextprotocol/go-sdk/jsonrpc"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func TestMCPHandler(t *testing.T) {
var got map[string]any
serverTool := ServerTool{
Tool: &mcp.Tool{Name: "example"},
Handler: func(_ context.Context, arguments map[string]any) (*mcp.CallToolResult, error) {
got = arguments
return &mcp.CallToolResult{}, nil
},
}
result, err := serverTool.MCPHandler()(context.Background(), &mcp.CallToolRequest{
Params: &mcp.CallToolParamsRaw{Arguments: 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
serverTool := ServerTool{
Tool: &mcp.Tool{Name: "example"},
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(`null`), json.RawMessage(`{"broken"`)} {
_, err := serverTool.MCPHandler()(context.Background(), &mcp.CallToolRequest{
Params: &mcp.CallToolParamsRaw{Arguments: arguments},
})
assertProtocolErrorCode(t, err, jsonrpc.CodeInvalidParams)
}
if called {
t.Fatal("handler was called with invalid arguments")
}
}
func TestMCPHandlerConvertsErrorsAndRecoversPanics(t *testing.T) {
t.Run("handler error", func(t *testing.T) {
serverTool := ServerTool{
Tool: &mcp.Tool{Name: "example"},
Handler: func(context.Context, map[string]any) (*mcp.CallToolResult, error) {
return nil, errors.New("failed")
},
}
_, err := serverTool.MCPHandler()(context.Background(), &mcp.CallToolRequest{Params: &mcp.CallToolParamsRaw{}})
assertProtocolErrorCode(t, err, jsonrpc.CodeInternalError)
})
t.Run("panic", func(t *testing.T) {
calls := 0
serverTool := ServerTool{
Tool: &mcp.Tool{Name: "example"},
Handler: func(context.Context, map[string]any) (*mcp.CallToolResult, error) {
calls++
if calls == 1 {
panic("failed")
}
return &mcp.CallToolResult{}, nil
},
}
handler := serverTool.MCPHandler()
_, err := handler(context.Background(), &mcp.CallToolRequest{Params: &mcp.CallToolParamsRaw{}})
assertProtocolErrorCode(t, err, jsonrpc.CodeInternalError)
if _, err := handler(context.Background(), &mcp.CallToolRequest{Params: &mcp.CallToolParamsRaw{}}); err != nil {
t.Fatalf("second handler call after panic error = %v", err)
}
})
}
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)
}
}
+89 -12
View File
@@ -1,26 +1,39 @@
package tool
import (
"bytes"
"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 +42,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 +66,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 +76,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 +86,70 @@ 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) {
name := ""
if s.Tool != nil {
name = s.Tool.Name
}
defer func() {
if recovered := recover(); recovered != nil {
panicErr := fmt.Errorf("panic recovered in %s tool handler: %v", name, recovered)
log.Errorf("%s", panicErr)
result = nil
err = &jsonrpc.Error{Code: jsonrpc.CodeInternalError, Message: panicErr.Error()}
}
}()
if req == nil || req.Params == nil {
return nil, invalidParamsError("missing tool call parameters")
}
arguments, err := decodeArguments(req.Params.Arguments)
if err != nil {
return nil, err
}
if s.Handler == nil {
return nil, internalError(fmt.Errorf("tool %q has no handler", name))
}
result, err = s.Handler(ctx, arguments)
if err != nil {
var protocolErr *jsonrpc.Error
if errors.As(err, &protocolErr) {
return nil, err
}
return nil, internalError(err)
}
return result, nil
}
}
func decodeArguments(raw json.RawMessage) (map[string]any, error) {
trimmed := bytes.TrimSpace(raw)
if len(trimmed) == 0 {
return map[string]any{}, nil
}
if bytes.Equal(trimmed, []byte("null")) {
return nil, invalidParamsError("tool arguments must be an object")
}
var arguments map[string]any
if err := json.Unmarshal(trimmed, &arguments); err != nil {
return nil, invalidParamsError(fmt.Sprintf("invalid tool arguments: %v", err))
}
return arguments, nil
}
func invalidParamsError(message string) error {
return &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: message}
}
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