fix: accept null tool arguments and bound HTTP resource use

Review follow-ups on the SDK migration.

An "arguments": null is what clients send for parameterless tools like get_me,
and what mcp-go accepted by returning a nil map. The new adapter rejected it
with InvalidParams, which broke those calls outright.

The /mcp endpoint took unlimited request bodies and never expired idle
sessions, so a peer that goes away without DELETE kept its session for the
process lifetime. Both are reachable before any token check, so neither can
stay unbounded; the body cap sits above the SDK default to leave room for the
base64 content create_or_update_file accepts.

Required() smuggled a bool through the property schema map and deleted it
again, colliding with the JSON Schema keyword of the same name. It now sets a
field on Property, so an object property can carry its own required list.

The tool contract fixture cost a manual regeneration step and four
hand-maintained counts on every tool change, and a snapshot freezes defects
rather than reporting them. Property assertions cover the same surface and
reject a duplicate tool name, a readOnlyHint that disagrees with the register
call, and a default that contradicts its own type or enum.

Co-Authored-By: Claude (Opus 5) <noreply@anthropic.com>
This commit is contained in:
silverwind
2026-08-02 19:34:40 +02:00
parent 80c8b25d6e
commit 0dc9868e2e
11 changed files with 316 additions and 3225 deletions
+66 -84
View File
@@ -4,7 +4,7 @@ import (
"context"
"errors"
"fmt"
"net"
"io"
"net/http"
"net/http/httptest"
"os"
@@ -41,28 +41,39 @@ func exposeAllTools(t *testing.T) {
flag.Version = testServerVersion
}
func assertVersionToolResult(t *testing.T, result *mcp.CallToolResult) {
// registeredToolCount is what the registry exposes under the current flags, so
// the transport assertions track tool additions without being edited.
func registeredToolCount() int {
count := 0
for _, domain := range domainTools {
count += len(domain.Tools())
}
return count
}
func textContent(t *testing.T, result *mcp.CallToolResult) string {
t.Helper()
if len(result.Content) != 1 {
t.Fatalf("version tool content count = %d, want 1", len(result.Content))
t.Fatalf("content count = %d, want 1", len(result.Content))
}
content, ok := result.Content[0].(*mcp.TextContent)
if !ok {
t.Fatalf("version tool content type = %T, want *mcp.TextContent", result.Content[0])
}
if !strings.Contains(content.Text, testServerVersion) {
t.Errorf("version tool result = %q, want it to contain %q", content.Text, testServerVersion)
t.Fatalf("content type = %T, want *mcp.TextContent", result.Content[0])
}
return content.Text
}
func listAndCallVersion(ctx context.Context, t *testing.T, session *mcp.ClientSession) {
// listAndCallVersion is the round trip every transport must support. wantText
// differs per transport: the stdio subprocess resolves its version from the VCS
// build info (main.go:14), so only the in-process servers have a known one.
func listAndCallVersion(ctx context.Context, t *testing.T, session *mcp.ClientSession, wantText string) {
t.Helper()
result, err := session.ListTools(ctx, nil)
if err != nil {
t.Fatalf("ListTools() error = %v", err)
}
if len(result.Tools) != 54 {
t.Fatalf("ListTools() count = %d, want 54", len(result.Tools))
if want := registeredToolCount(); len(result.Tools) != want {
t.Fatalf("ListTools() count = %d, want %d", len(result.Tools), want)
}
callResult, err := session.CallTool(ctx, &mcp.CallToolParams{
Name: "get_gitea_mcp_server_version",
@@ -70,7 +81,9 @@ func listAndCallVersion(ctx context.Context, t *testing.T, session *mcp.ClientSe
if err != nil {
t.Fatalf("CallTool() error = %v", err)
}
assertVersionToolResult(t, callResult)
if got := textContent(t, callResult); !strings.Contains(got, wantText) {
t.Errorf("version tool result = %q, want it to contain %q", got, wantText)
}
}
func TestOfficialSDKInMemory(t *testing.T) {
@@ -94,7 +107,7 @@ func TestOfficialSDKInMemory(t *testing.T) {
if got := session.InitializeResult().ProtocolVersion; got != "2026-07-28" {
t.Errorf("protocol version = %q, want %q", got, "2026-07-28")
}
listAndCallVersion(ctx, t, session)
listAndCallVersion(ctx, t, session, testServerVersion)
if err := session.Close(); err != nil {
t.Fatalf("Close() error = %v", err)
}
@@ -132,7 +145,7 @@ func TestStreamableHTTPStateful(t *testing.T) {
if got := session.InitializeResult().ProtocolVersion; got != "2025-11-25" {
t.Errorf("protocol version = %q, want %q", got, "2025-11-25")
}
listAndCallVersion(ctx, t, session)
listAndCallVersion(ctx, t, session, testServerVersion)
response, err := httpTestServer.Client().Get(httpTestServer.URL + "/not-mcp")
if err != nil {
@@ -144,25 +157,47 @@ func TestStreamableHTTPStateful(t *testing.T) {
}
}
func TestStreamableHTTPAllowsLegacyLargeBodies(t *testing.T) {
// spaceReader yields an endless run of spaces, so oversized bodies can be sent
// without allocating them.
type spaceReader struct{}
func (spaceReader) Read(p []byte) (int, error) {
for index := range p {
p[index] = ' '
}
return len(p), nil
}
func TestStreamableHTTPRequestBodyLimit(t *testing.T) {
server := newMCPServer(testServerVersion)
httpTestServer := httptest.NewServer(newHTTPServer("", server).Handler)
defer httpTestServer.Close()
body := strings.NewReader(strings.Repeat(" ", mcp.DefaultMaxRequestBodyBytes+1))
request, err := http.NewRequest(http.MethodPost, httpTestServer.URL+"/mcp", body)
if err != nil {
t.Fatalf("NewRequest() error = %v", err)
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json, text/event-stream")
response, err := httpTestServer.Client().Do(request)
if err != nil {
t.Fatalf("POST large body error = %v", err)
}
defer response.Body.Close()
if response.StatusCode == http.StatusRequestEntityTooLarge {
t.Errorf("POST large body status = %d; PR 1 must preserve the previous unlimited body behavior", response.StatusCode)
for _, test := range []struct {
name string
size int64
tooLarge bool
}{
{name: "above the SDK default", size: mcp.DefaultMaxRequestBodyBytes + 1},
{name: "above our own limit", size: maxRequestBodyBytes + 1, tooLarge: true},
} {
t.Run(test.name, func(t *testing.T) {
request, err := http.NewRequest(http.MethodPost, httpTestServer.URL+"/mcp", io.LimitReader(spaceReader{}, test.size))
if err != nil {
t.Fatalf("NewRequest() error = %v", err)
}
request.ContentLength = test.size
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json, text/event-stream")
response, err := httpTestServer.Client().Do(request)
if err != nil {
t.Fatalf("POST %d bytes error = %v", test.size, err)
}
defer response.Body.Close()
if gotTooLarge := response.StatusCode == http.StatusRequestEntityTooLarge; gotTooLarge != test.tooLarge {
t.Errorf("POST %d bytes status = %d, want %d = %v", test.size, response.StatusCode, http.StatusRequestEntityTooLarge, test.tooLarge)
}
})
}
}
@@ -179,8 +214,7 @@ func (t *authorizationTransport) set(value string) {
}
func (t *authorizationTransport) RoundTrip(request *http.Request) (*http.Response, error) {
clone := request.Clone(request.Context())
clone.Header = request.Header.Clone()
clone := request.Clone(request.Context()) // Clone already copies the header
t.mu.RLock()
value := t.value
t.mu.RUnlock()
@@ -313,6 +347,7 @@ func TestStdioCommandTransport(t *testing.T) {
if testing.Short() {
t.Skip("skipping subprocess build in short mode")
}
exposeAllTools(t) // the subprocess runs with default flags, so match them here
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
@@ -336,58 +371,5 @@ func TestStdioCommandTransport(t *testing.T) {
if got := session.InitializeResult().ProtocolVersion; got != "2026-07-28" {
t.Errorf("protocol version = %q, want %q", got, "2026-07-28")
}
result, err := session.ListTools(ctx, nil)
if err != nil {
t.Fatalf("ListTools() error = %v", err)
}
if len(result.Tools) != 54 {
t.Errorf("ListTools() count = %d, want 54", len(result.Tools))
}
callResult, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "get_gitea_mcp_server_version"})
if err != nil {
t.Fatalf("CallTool() error = %v", err)
}
content, ok := callResult.Content[0].(*mcp.TextContent)
if !ok {
t.Fatalf("CallTool() content type = %T, want *mcp.TextContent", callResult.Content[0])
}
if !strings.Contains(content.Text, "Gitea MCP Server version:") {
t.Errorf("CallTool() result = %q, want server version", content.Text)
}
}
func TestNewHTTPServerAddress(t *testing.T) {
server := newHTTPServer(":12345", newMCPServer(testServerVersion))
if server.Addr != ":12345" {
t.Errorf("server address = %q, want %q", server.Addr, ":12345")
}
if server.Handler == nil {
t.Error("server handler is nil")
}
}
func TestHTTPServerGracefulShutdown(t *testing.T) {
server := newHTTPServer("127.0.0.1:0", newMCPServer(testServerVersion))
listener, err := net.Listen("tcp", server.Addr)
if err != nil {
t.Fatalf("Listen() error = %v", err)
}
serveDone := make(chan error, 1)
go func() {
serveDone <- server.Serve(listener)
}()
shutdownCtx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
t.Fatalf("Shutdown() error = %v", err)
}
select {
case err := <-serveDone:
if !errors.Is(err, http.ErrServerClosed) {
t.Errorf("Serve() error = %v, want http.ErrServerClosed", err)
}
case <-shutdownCtx.Done():
t.Fatal("server did not stop after Shutdown()")
}
listAndCallVersion(ctx, t, session, "Gitea MCP Server version:")
}