mirror of
https://gitea.com/gitea/gitea-mcp.git
synced 2026-08-03 15:49:23 +02:00
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:
+17
-14
@@ -32,6 +32,15 @@ import (
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
// maxRequestBodyBytes raises the SDK's 4 MiB default, which is too tight for the
|
||||
// base64 file content create_or_update_file accepts.
|
||||
const maxRequestBodyBytes = 32 << 20
|
||||
|
||||
// sessionTimeout expires idle sessions, which the SDK otherwise keeps for the
|
||||
// process lifetime: a client that goes away without DELETE /mcp leaks its
|
||||
// session, and initialize takes no token. Clients re-initialize on the 404.
|
||||
const sessionTimeout = 30 * time.Minute
|
||||
|
||||
var (
|
||||
mcpServer *mcp.Server
|
||||
|
||||
@@ -95,24 +104,18 @@ func authTokenMiddleware(next mcp.MethodHandler) mcp.MethodHandler {
|
||||
}
|
||||
}
|
||||
|
||||
func newStreamableHTTPHandler(s *mcp.Server) http.Handler {
|
||||
return mcp.NewStreamableHTTPHandler(
|
||||
func newHTTPServer(addr string, s *mcp.Server) *http.Server {
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/mcp", mcp.NewStreamableHTTPHandler(
|
||||
func(*http.Request) *mcp.Server { return s },
|
||||
&mcp.StreamableHTTPOptions{
|
||||
Logger: log.Slog(),
|
||||
MaxRequestBodyBytes: -1,
|
||||
Stateless: false,
|
||||
MaxRequestBodyBytes: maxRequestBodyBytes,
|
||||
Stateless: false, // PR 2 switches this on
|
||||
SessionTimeout: sessionTimeout,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func newHTTPServer(addr string, s *mcp.Server) *http.Server {
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/mcp", newStreamableHTTPHandler(s))
|
||||
return &http.Server{
|
||||
Addr: addr,
|
||||
Handler: mux,
|
||||
}
|
||||
))
|
||||
return &http.Server{Addr: addr, Handler: mux}
|
||||
}
|
||||
|
||||
func Run() error {
|
||||
|
||||
@@ -1,53 +1,6 @@
|
||||
package operation
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.com/gitea/gitea-mcp/pkg/flag"
|
||||
)
|
||||
|
||||
// TestAllToolsHaveDescriptions ensures every registered tool sets a non-empty
|
||||
// Tool.Description, as strict MCP clients reject tools without one.
|
||||
func TestAllToolsHaveDescriptions(t *testing.T) {
|
||||
origRO, origAllow := flag.ReadOnly, flag.AllowedTools
|
||||
t.Cleanup(func() {
|
||||
flag.ReadOnly, flag.AllowedTools = origRO, origAllow
|
||||
})
|
||||
flag.ReadOnly = false
|
||||
flag.AllowedTools = nil
|
||||
|
||||
var missing []string
|
||||
for _, d := range domainTools {
|
||||
for _, st := range d.Tools() {
|
||||
if st.Tool.Description == "" {
|
||||
missing = append(missing, st.Tool.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
t.Errorf("tools missing a description: %v", missing)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDomainToolsScopesAreUniqueAndNonEmpty ensures every entry registered in
|
||||
// domainTools has a canonical, non-empty scope name and that no two domains
|
||||
// share the same scope (each domain.Tools() call is filtered by exactly one
|
||||
// scope name via flag.AllowedScopes).
|
||||
func TestDomainToolsScopesAreUniqueAndNonEmpty(t *testing.T) {
|
||||
seen := map[string]struct{}{}
|
||||
for _, d := range domainTools {
|
||||
scope := d.Scope()
|
||||
if scope == "" {
|
||||
t.Errorf("domainTools contains a domain with an empty scope")
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[scope]; ok {
|
||||
t.Errorf("domainTools contains a duplicate scope %q", scope)
|
||||
continue
|
||||
}
|
||||
seen[scope] = struct{}{}
|
||||
}
|
||||
}
|
||||
import "testing"
|
||||
|
||||
func TestParseAuthToken(t *testing.T) {
|
||||
tests := []struct {
|
||||
|
||||
@@ -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:")
|
||||
}
|
||||
|
||||
Vendored
-2817
File diff suppressed because it is too large
Load Diff
+99
-136
@@ -1,179 +1,142 @@
|
||||
package operation
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
const updateToolContractEnv = "UPDATE_TOOL_CONTRACT"
|
||||
|
||||
type toolContract struct {
|
||||
Scope string `json:"scope"`
|
||||
Access string `json:"access"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema any `json:"inputSchema"`
|
||||
Annotations contractAnnotations `json:"annotations"`
|
||||
}
|
||||
|
||||
type contractAnnotations struct {
|
||||
Title string `json:"title"`
|
||||
ReadOnlyHint bool `json:"readOnlyHint"`
|
||||
DestructiveHint bool `json:"destructiveHint"`
|
||||
IdempotentHint bool `json:"idempotentHint"`
|
||||
OpenWorldHint bool `json:"openWorldHint"`
|
||||
}
|
||||
|
||||
// TestToolContract checks the properties every exposed tool must hold, rather
|
||||
// than a snapshot of the current surface, so adding a tool needs no fixture
|
||||
// update and a malformed schema fails here instead of panicking in AddTool.
|
||||
func TestToolContract(t *testing.T) {
|
||||
const (
|
||||
wantDomains = 18
|
||||
wantTools = 54
|
||||
wantRead = 33
|
||||
wantWrite = 21
|
||||
)
|
||||
|
||||
contracts := make([]toolContract, 0, wantTools)
|
||||
seenScopes := make(map[string]struct{}, wantDomains)
|
||||
seenNames := make(map[string]struct{}, wantTools)
|
||||
readCount, writeCount := 0, 0
|
||||
|
||||
scopeByName := map[string]string{}
|
||||
seenScopes := map[string]struct{}{}
|
||||
for _, domain := range domainTools {
|
||||
scope := domain.Scope()
|
||||
if scope == "" {
|
||||
t.Fatal("registered tool domain has an empty scope")
|
||||
t.Error("domainTools contains a domain with an empty scope")
|
||||
}
|
||||
// Tools() filters one domain by exactly one scope name, so a shared
|
||||
// scope would make --scope select more than the caller asked for.
|
||||
if _, duplicate := seenScopes[scope]; duplicate {
|
||||
t.Fatalf("duplicate tool domain scope %q", scope)
|
||||
t.Errorf("domainTools contains a duplicate scope %q", scope)
|
||||
}
|
||||
seenScopes[scope] = struct{}{}
|
||||
|
||||
for _, registered := range domain.ReadTools() {
|
||||
contracts = append(contracts, decodeToolContract(t, scope, "read", registered.Tool))
|
||||
readCount++
|
||||
assertToolContract(t, scope, registered.Tool, true, scopeByName)
|
||||
}
|
||||
for _, registered := range domain.WriteTools() {
|
||||
contracts = append(contracts, decodeToolContract(t, scope, "write", registered.Tool))
|
||||
writeCount++
|
||||
assertToolContract(t, scope, registered.Tool, false, scopeByName)
|
||||
}
|
||||
}
|
||||
if len(scopeByName) == 0 {
|
||||
t.Fatal("no tools are registered")
|
||||
}
|
||||
}
|
||||
|
||||
if len(seenScopes) != wantDomains {
|
||||
t.Errorf("domain count = %d, want %d", len(seenScopes), wantDomains)
|
||||
}
|
||||
if len(contracts) != wantTools {
|
||||
t.Errorf("tool count = %d, want %d", len(contracts), wantTools)
|
||||
}
|
||||
if readCount != wantRead {
|
||||
t.Errorf("read tool count = %d, want %d", readCount, wantRead)
|
||||
}
|
||||
if writeCount != wantWrite {
|
||||
t.Errorf("write tool count = %d, want %d", writeCount, wantWrite)
|
||||
}
|
||||
func assertToolContract(t *testing.T, scope string, definition *mcp.Tool, readOnly bool, scopeByName map[string]string) {
|
||||
t.Helper()
|
||||
|
||||
for _, contract := range contracts {
|
||||
if _, duplicate := seenNames[contract.Name]; duplicate {
|
||||
t.Errorf("duplicate tool name %q", contract.Name)
|
||||
t.Run(definition.Name, func(t *testing.T) {
|
||||
if previous, duplicate := scopeByName[definition.Name]; duplicate {
|
||||
t.Errorf("tool name is already registered in scope %q; AddTool would silently replace it", previous)
|
||||
}
|
||||
seenNames[contract.Name] = struct{}{}
|
||||
}
|
||||
scopeByName[definition.Name] = scope
|
||||
|
||||
sort.Slice(contracts, func(i, j int) bool {
|
||||
if contracts[i].Scope != contracts[j].Scope {
|
||||
return contracts[i].Scope < contracts[j].Scope
|
||||
// Strict MCP clients reject a tools/list entry without a description.
|
||||
if definition.Description == "" {
|
||||
t.Error("tool has no description")
|
||||
}
|
||||
if contracts[i].Access != contracts[j].Access {
|
||||
return contracts[i].Access < contracts[j].Access
|
||||
|
||||
// A write tool registered as read stays exposed under --read-only.
|
||||
if definition.Annotations == nil || definition.Annotations.ReadOnlyHint != readOnly {
|
||||
t.Errorf("annotations = %+v, want readOnlyHint %v", definition.Annotations, readOnly)
|
||||
}
|
||||
|
||||
schema := decodeJSON(t, definition.InputSchema)
|
||||
if schema["type"] != "object" {
|
||||
t.Fatalf("input schema type = %v, want object", schema["type"])
|
||||
}
|
||||
properties, ok := schema["properties"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("input schema properties = %T, want a JSON object", schema["properties"])
|
||||
}
|
||||
|
||||
for name, raw := range properties {
|
||||
property, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
t.Errorf("property %q = %T, want a JSON object", name, raw)
|
||||
continue
|
||||
}
|
||||
assertPropertyContract(t, name, property)
|
||||
}
|
||||
return contracts[i].Name < contracts[j].Name
|
||||
})
|
||||
|
||||
got, err := json.MarshalIndent(contracts, "", " ")
|
||||
if err != nil {
|
||||
t.Fatalf("marshal tool contract: %v", err)
|
||||
}
|
||||
got = append(got, '\n')
|
||||
|
||||
goldenPath := filepath.Join("testdata", "tools.golden.json")
|
||||
if os.Getenv(updateToolContractEnv) == "1" {
|
||||
if err := os.WriteFile(goldenPath, got, 0o644); err != nil {
|
||||
t.Fatalf("update tool contract: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
want, err := os.ReadFile(goldenPath)
|
||||
if err != nil {
|
||||
t.Fatalf("read tool contract: %v", err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Errorf("tool contract changed; inspect the semantic diff before running %s=1 go test -run '^TestToolContract$' ./operation/", updateToolContractEnv)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeToolContract(t *testing.T, scope, access string, toolDefinition any) toolContract {
|
||||
func assertPropertyContract(t *testing.T, name string, property map[string]any) {
|
||||
t.Helper()
|
||||
|
||||
data, err := json.Marshal(toolDefinition)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal %s tool in scope %q: %v", access, scope, err)
|
||||
}
|
||||
var definition map[string]any
|
||||
if err := json.Unmarshal(data, &definition); err != nil {
|
||||
t.Fatalf("decode %s tool in scope %q: %v", access, scope, err)
|
||||
}
|
||||
|
||||
name := requiredString(t, definition, "name", scope)
|
||||
description := requiredString(t, definition, "description", name)
|
||||
inputSchema, ok := definition["inputSchema"].(map[string]any)
|
||||
propertyType, ok := property["type"].(string)
|
||||
if !ok {
|
||||
t.Fatalf("tool %q has inputSchema of type %T, want JSON object", name, definition["inputSchema"])
|
||||
t.Errorf("property %q has no type", name)
|
||||
return
|
||||
}
|
||||
// An omitted required keyword and an empty array have the same JSON Schema meaning.
|
||||
if _, ok := inputSchema["required"]; !ok {
|
||||
inputSchema["required"] = []any{}
|
||||
}
|
||||
annotations, _ := definition["annotations"].(map[string]any)
|
||||
|
||||
// Normalize protocol defaults independently of SDK omitempty behavior.
|
||||
return toolContract{
|
||||
Scope: scope,
|
||||
Access: access,
|
||||
Name: name,
|
||||
Description: description,
|
||||
InputSchema: inputSchema,
|
||||
Annotations: contractAnnotations{
|
||||
Title: stringField(annotations, "title", ""),
|
||||
ReadOnlyHint: boolField(annotations, "readOnlyHint", false),
|
||||
DestructiveHint: boolField(annotations, "destructiveHint", true),
|
||||
IdempotentHint: boolField(annotations, "idempotentHint", false),
|
||||
OpenWorldHint: boolField(annotations, "openWorldHint", true),
|
||||
},
|
||||
enum, hasEnum := property["enum"].([]any)
|
||||
if _, declared := property["enum"]; declared && len(enum) == 0 {
|
||||
t.Errorf("property %q has an empty enum", name)
|
||||
}
|
||||
|
||||
defaultValue, hasDefault := property["default"]
|
||||
if !hasDefault {
|
||||
return
|
||||
}
|
||||
if !matchesJSONType(defaultValue, propertyType) {
|
||||
t.Errorf("property %q default %#v is not a %s", name, defaultValue, propertyType)
|
||||
}
|
||||
if hasEnum && !slices.Contains(enum, defaultValue) {
|
||||
t.Errorf("property %q default %#v is not one of its enum values %#v", name, defaultValue, enum)
|
||||
}
|
||||
}
|
||||
|
||||
func requiredString(t *testing.T, object map[string]any, key, owner string) string {
|
||||
func matchesJSONType(value any, propertyType string) bool {
|
||||
switch propertyType {
|
||||
case "string":
|
||||
_, ok := value.(string)
|
||||
return ok
|
||||
case "number":
|
||||
_, ok := value.(float64)
|
||||
return ok
|
||||
case "boolean":
|
||||
_, ok := value.(bool)
|
||||
return ok
|
||||
case "array":
|
||||
_, ok := value.([]any)
|
||||
return ok
|
||||
case "object":
|
||||
_, ok := value.(map[string]any)
|
||||
return ok
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// decodeJSON round-trips through JSON so the assertions see what an MCP client
|
||||
// receives rather than the Go values behind it.
|
||||
func decodeJSON(t *testing.T, value any) map[string]any {
|
||||
t.Helper()
|
||||
|
||||
value, ok := object[key].(string)
|
||||
if !ok || value == "" {
|
||||
t.Fatalf("%s has missing or empty %q", owner, key)
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func stringField(object map[string]any, key, fallback string) string {
|
||||
if value, ok := object[key].(string); ok {
|
||||
return value
|
||||
var decoded map[string]any
|
||||
if err := json.Unmarshal(encoded, &decoded); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func boolField(object map[string]any, key string, fallback bool) bool {
|
||||
if value, ok := object[key].(bool); ok {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
return decoded
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user