Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 17 additions & 8 deletions result/cap.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ const withheldHint = "The result exceeded the server's size limit and could not
// Holding the result to the limit less this keeps the message under the
// limit. A server whose Implementation serializes to more than a few hundred
// bytes (icons, say) overruns it by the difference.
// TestMiddleware_CapHoldsForTheResponseFrame measures the frame the server
// writes against the limit.
const frameReserve = 512

// MinBytes is the smallest cap enforced: room for the truncation envelope and
Expand Down Expand Up @@ -143,13 +145,14 @@ type truncation struct {
// Cap holds a successful result to maxBytes of serialized result, frameReserve
// included. It returns
// the result unchanged when maxBytes <= 0, the result is an error (an error
// must reach the caller whole), or it already fits; a positive maxBytes below
// must reach the caller whole) or asks for input (an input request is the
// protocol's, not a payload to cut), or it already fits; a positive maxBytes below
// MinBytes is raised to it. The result passed in is never modified.
//
// The one-text-block JSON shape gets the exact cut; any other shape the
// coarse one (see the package's size-cap notes).
func Cap(result *mcp.CallToolResult, maxBytes int) *mcp.CallToolResult {
if result == nil || result.IsError || maxBytes <= 0 {
if result == nil || result.IsError || result.NeedsInput() || maxBytes <= 0 {
Comment thread
jeremy marked this conversation as resolved.
Resolved
return result
}
limit := max(maxBytes, MinBytes)
Expand Down Expand Up @@ -228,12 +231,18 @@ func capExact(result *mcp.CallToolResult, originalBytes, limit int) *mcp.CallToo
// frameReserve.
func capCoarse(result *mcp.CallToolResult, originalBytes, limit int) *mcp.CallToolResult {
t := truncation{LimitBytes: limit, OriginalBytes: originalBytes, Hint: withheldHint}
out := &mcp.CallToolResult{
Meta: result.Meta,
Content: []mcp.Content{&mcp.TextContent{Text: fmt.Sprintf(
"[truncated: this %d-byte result exceeded the server's %d-byte limit and was withheld. %s]",
originalBytes, limit, withheldHint)}},
}
// A copy, so what the SDK set on the result before this middleware ran
// (its resultType) reaches the client, as the exact cut's copy does. A
// complete result carries no input requests or request state; clearing
// them keeps the notice's size fixed.
copied := *result
out := &copied
out.Content = []mcp.Content{&mcp.TextContent{Text: fmt.Sprintf(
"[truncated: this %d-byte result exceeded the server's %d-byte limit and was withheld. %s]",
originalBytes, limit, withheldHint)}}
out.StructuredContent = nil
out.InputRequests = nil
out.RequestState = ""
if result.StructuredContent != nil {
out.StructuredContent = map[string]any{"truncated": true, "truncation": t}
}
Expand Down
22 changes: 22 additions & 0 deletions result/cap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,27 @@ func TestCap_ErrorsUntouched(t *testing.T) {
// The boundary is the serialized size plus the frame reserve: a result
// exactly at the limit passes whole, one byte over it is cut, and the cut
// fits.
// A result asking for input is the protocol's, not a payload: cutting it
// would turn an input request into a complete result with a notice.
func TestCap_InputRequestsUntouched(t *testing.T) {
var in mcp.CallToolResult
require.NoError(t, json.Unmarshal([]byte(`{"resultType":"input_required","requestState":"`+strings.Repeat("s", 50_000)+`"}`), &in))
require.True(t, in.NeedsInput())
assert.Same(t, &in, Cap(&in, MinBytes))
}

// The coarse cut keeps the result's protocol envelope: the resultType the
// SDK set before the middleware ran still reaches the client.
func TestCap_CoarseKeepsTheResultType(t *testing.T) {
var in mcp.CallToolResult
require.NoError(t, json.Unmarshal([]byte(`{"resultType":"complete","content":[{"type":"text","text":"`+strings.Repeat("a", 50_000)+`"}]}`), &in))
out := Cap(&in, MinBytes)
data, err := json.Marshal(out)
require.NoError(t, err)
assert.Contains(t, string(data), `"resultType":"complete"`)
assert.Contains(t, resultText(t, out), "withheld")
}

func TestCap_BoundaryIsTheSerializedSize(t *testing.T) {
r := JSON(map[string]any{"items": bigItems(40)})
n := wireLen(t, r)
Expand Down Expand Up @@ -512,6 +533,7 @@ func TestCapCoarse_AlwaysFitsTheLimit(t *testing.T) {
"structured": {StructuredContent: map[string]any{"a": 1}},
"structured with meta": {StructuredContent: map[string]any{"a": 1}, Meta: mcp.Meta{"blob": strings.Repeat("m", 3_500)}},
"huge meta": {Meta: mcp.Meta{"blob": strings.Repeat("m", math.MaxUint16)}},
"stray request state": {Content: []mcp.Content{&mcp.TextContent{Text: "x"}}, RequestState: strings.Repeat("s", 10_000)},
} {
t.Run(name, func(t *testing.T) {
for _, limit := range []int{MinBytes, MinBytes + 1, 10_000, 100_000} {
Expand Down
123 changes: 101 additions & 22 deletions result/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ package result
import (
"context"
"encoding/json"
"fmt"
"strings"
"sync"
"testing"

"github.com/modelcontextprotocol/go-sdk/jsonrpc"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -77,30 +80,106 @@ func TestMiddleware_Caps(t *testing.T) {
assert.NotEmpty(t, asList(t, got["items"]))
}

// What the client receives fits the cap, including what the SDK adds after
// the middleware (resultType, the serverInfo _meta): a prefix cut packs the
// result to the limit, so an unreserved cap would land over it.
func TestMiddleware_CapHoldsForWhatTheClientReceives(t *testing.T) {
for name, payload := range map[string]any{
"quotes": map[string]any{"body": strings.Repeat(`"`, 24_000)},
"list": bigItems(100),
"plain big": nil,
} {
t.Run(name, func(t *testing.T) {
session := serve(t, 8_000, func() *mcp.CallToolResult {
if payload == nil {
return Text(strings.Repeat("a", 50_000))
}
return JSON(payload)
// What the client receives fits the cap: the whole JSON-RPC response frame,
// as the server writes it, including what the SDK adds after the middleware
// has measured the result (resultType, the serverInfo _meta, the frame
// around the result). A prefix cut packs the result to the limit less
// frameReserve, so the reserve is all that keeps these under it. The result
// the client decodes is not the measure: it drops resultType and the frame.
func TestMiddleware_CapHoldsForTheResponseFrame(t *testing.T) {
// Identified the way a product server is, by name and a module
// pseudo-version.
impl := &mcp.Implementation{Name: "example-mcp-server", Version: "v0.0.0-20261017204500-0123456789ab"}
payloads := map[string]func() *mcp.CallToolResult{
"quotes": func() *mcp.CallToolResult { return JSON(map[string]any{"body": strings.Repeat(`"`, 24_000)}) },
"html": func() *mcp.CallToolResult { return JSON(map[string]any{"body": strings.Repeat(`<&>`, 24_000)}) },
"long field": func() *mcp.CallToolResult { return JSON(map[string]any{"body": strings.Repeat("x", 60_000)}) },
"list": func() *mcp.CallToolResult { return JSON(bigItems(100)) },
"plain big": func() *mcp.CallToolResult { return Text(strings.Repeat("a", 50_000)) },
}
for _, limit := range []int{MinBytes, 8_000} {
for name, answer := range payloads {
t.Run(fmt.Sprintf("%s/%d", name, limit), func(t *testing.T) {
frame := callFrame(t, impl, limit, answer)
assert.LessOrEqual(t, len(frame), limit)
assert.Contains(t, frame, "truncated")
assert.Contains(t, frame, `"resultType"`, "the frame carries what the SDK adds after the middleware")
assert.Contains(t, frame, impl.Version, "the frame carries the serverInfo _meta")
})
res, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: "annotated"})
require.NoError(t, err)
wire, err := json.Marshal(res)
require.NoError(t, err)
assert.LessOrEqual(t, len(wire), 8_000)
assert.Contains(t, string(wire), "truncated")
})
}
}
}

// callFrame serves one tool behind Middleware(maxBytes), calls it, and
// returns the tools/call response as the server wrote it to its transport.
func callFrame(t *testing.T, impl *mcp.Implementation, maxBytes int, answer func() *mcp.CallToolResult) string {
t.Helper()
server := mcp.NewServer(impl, nil)
server.AddTool(&mcp.Tool{Name: "t", InputSchema: map[string]any{"type": "object"}},
func(context.Context, *mcp.CallToolRequest) (*mcp.CallToolResult, error) { return answer(), nil })
server.AddReceivingMiddleware(Middleware(maxBytes))

clientTransport, serverTransport := mcp.NewInMemoryTransports()
recorder := &recordingTransport{Transport: serverTransport}
serverSession, err := server.Connect(context.Background(), recorder, nil)
require.NoError(t, err)
t.Cleanup(func() { _ = serverSession.Close() })
client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "0.0.0"}, nil)
clientSession, err := client.Connect(context.Background(), clientTransport, nil)
require.NoError(t, err)
t.Cleanup(func() { _ = clientSession.Close() })

_, err = clientSession.CallTool(context.Background(), &mcp.CallToolParams{Name: "t"})
require.NoError(t, err)

frame := recorder.last(`"content"`)
require.NotEmpty(t, frame, "no tools/call response was written")
return frame
}

// recordingTransport keeps every message the server writes, encoded the way
// the stdio and HTTP transports encode it, before handing it on: the client
// can't have the response before it is recorded.
type recordingTransport struct {
mcp.Transport
mu sync.Mutex
written []string
}

func (r *recordingTransport) Connect(ctx context.Context) (mcp.Connection, error) {
conn, err := r.Transport.Connect(ctx)
if err != nil {
return nil, err
}
return &recordingConn{Connection: conn, recorder: r}, nil
}

// last returns the last written message containing marker.
func (r *recordingTransport) last(marker string) string {
r.mu.Lock()
defer r.mu.Unlock()
for i := len(r.written) - 1; i >= 0; i-- {
if strings.Contains(r.written[i], marker) {
return r.written[i]
}
}
return ""
}

type recordingConn struct {
mcp.Connection
recorder *recordingTransport
}

func (c *recordingConn) Write(ctx context.Context, msg jsonrpc.Message) error {
data, err := jsonrpc.EncodeMessage(msg)
if err != nil {
return err
}
c.recorder.mu.Lock()
c.recorder.written = append(c.recorder.written, string(data))
c.recorder.mu.Unlock()
return c.Connection.Write(ctx, msg)
}

// Mirroring copies a changed tool rather than writing through to the
Expand Down
Loading