Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

Reduce allocations when serializing large content blocks and SSE JSON-RPC responses - #2079

Open
flipcyde101 wants to merge 1 commit into
modelcontextprotocol:mainfrom
flipcyde101:perf/large-tool-result-serialization-1971
Open

flipcyde101 wants to merge 1 commit into
modelcontextprotocol:mainfrom
flipcyde101:perf/large-tool-result-serialization-1971

Conversation

@flipcyde101

Copy link
Copy Markdown

Implements proposed optimizations (1) and (2) from #1971 to significantly reduce LOH/buffer allocations when serializing large tool/resource content payloads and JSON-RPC SSE responses, with no public API changes.

Addresses #1971

What Changed

  1. Segmented string/base64 serialization in content and resource converters:
    • Added internal McpJsonUtilities.WriteStringSegmented helpers (string? and ReadOnlySpan<byte> overloads) that use Utf8JsonWriter.WriteStringValueSegment in 16 KiB chunks when payloads exceed 64 KiB on net10.0 and netstandard2.0 (which references System.Text.Json 10.x), falling back to WriteString on net8.0/net9.0 and for small payloads.
    • Updated ContentBlock.Converter.Write (TextContentBlock.Text, ImageContentBlock.Data, AudioContentBlock.Data) and ResourceContents.Converter.Write (TextResourceContents.Text, BlobResourceContents.Blob) to use WriteStringSegmented, bounding the escape scratch buffer to the chunk size instead of growing proportionally to the full payload.
  2. Single-buffer JSON-RPC framing in SseEventWriter:
    • Exposed PooledByteBufferWriter.WrittenSpan and added SseEventWriter.WriteSingleLineJsonAsync, which writes the data: prefix and serializes JSON directly into _bufferWriter, eliminating the intermediate _userDataBufferWriter copy.
    • Normalized any raw \r/\n bytes emitted by custom converters (WriteRawValue) in place to spaces using vectorized IndexOfAny, preserving single-line SSE framing without re-copying.
    • Lazily initialized _userDataBufferWriter so JSON-only SSE writers avoid allocating a second pooled buffer, and wrapped writes in try/finally to guarantee buffer resets on cancellation/error.
    • Routed McpSseEventWriterExtensions.WriteAsync(this SseEventWriter, SseItem<JsonRpcMessage?>, ...) through WriteSingleLineJsonAsync.
  3. Tests (tests/ModelContextProtocol.Tests/Protocol/LargeContentSerializationTests.cs):
    • Added 7 unit/integration tests covering >64 KiB TextContentBlock and TextResourceContents with surrogate pairs placed across 16 KiB segment boundaries (verifying byte-for-byte identity with unsegmented Utf8JsonWriter.WriteString and exact round-trip), >64 KiB ImageContentBlock/AudioContentBlock/BlobResourceContents base64 payloads, end-to-end SseResponseStreamTransport framing of large JsonRpcResponses, and a .NET 10 per-thread allocation bound check (< 1 MiB scratch allocation for a 1M-char escaping payload).

How Has This Been Tested?

  • dotnet build -c Release src/ModelContextProtocol.Core/ModelContextProtocol.Core.csproj (netstandard2.0, net8.0, net9.0, net10.0): 0 warnings, 0 errors.
  • dotnet test tests/ModelContextProtocol.Tests/ModelContextProtocol.Tests.csproj -f net10.0 --filter FullyQualifiedName~LargeContentSerializationTests|FullyQualifiedName~ContentBlock|FullyQualifiedName~ResourceContents|FullyQualifiedName~Sse: 448 passed, 0 failed, 2 skipped (Docker-only).

…-RPC responses

Signed-off-by: Flipcyde <169501444+flipcyde101@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant