Skip to content

Commit 39ec6e5

Browse files
committed
Use case-sensitive ProtocolOptions for all protocol readers
Add McpJsonUtilities.ProtocolOptions, a cached read-only copy of DefaultOptions that matches property names case-sensitively, and use it wherever the SDK deserializes protocol messages through options rather than the source-generated context: the stdio client and server transports, the ASP.NET Core Streamable HTTP and SSE request reader, and the Tasks extension (task-based CallToolResult, InputRequest, InputResponse and error details). DefaultOptions and caller-supplied options are still used for user-defined data. Its docs now point to ProtocolOptions and state that protocol types deserialized through DefaultOptions keep case-insensitive matching. Signed-off-by: FenjuFu <[email protected]>
1 parent 54e853b commit 39ec6e5

12 files changed

Lines changed: 148 additions & 29 deletions

File tree

‎src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -714,7 +714,7 @@ internal static Task RunSessionAsync(HttpContext httpContext, McpServer session,
714714
return null;
715715
}
716716

717-
internal static JsonTypeInfo<T> GetRequiredJsonTypeInfo<T>() => (JsonTypeInfo<T>)McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(T));
717+
internal static JsonTypeInfo<T> GetRequiredJsonTypeInfo<T>() => (JsonTypeInfo<T>)McpJsonUtilities.ProtocolOptions.GetTypeInfo(typeof(T));
718718

719719
/// <summary>
720720
/// Validates that a request riding a per-request-metadata protocol revision carries the required

‎src/ModelContextProtocol.Core/Client/StreamClientSessionTransport.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ private async Task ProcessMessageAsync(string line, CancellationToken cancellati
153153
{
154154
try
155155
{
156-
var message = (JsonRpcMessage?)JsonSerializer.Deserialize(line.AsSpan().Trim(), McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonRpcMessage)));
156+
var message = (JsonRpcMessage?)JsonSerializer.Deserialize(line.AsSpan().Trim(), McpJsonUtilities.ProtocolOptions.GetTypeInfo(typeof(JsonRpcMessage)));
157157
if (message != null)
158158
{
159159
await WriteMessageAsync(message, cancellationToken).ConfigureAwait(false);

‎src/ModelContextProtocol.Core/McpJsonUtilities.cs‎

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -28,27 +28,46 @@ public static partial class McpJsonUtilities
2828
/// </list>
2929
/// </para>
3030
/// <para>
31-
/// Property names are matched case-insensitively, as with <see cref="JsonSerializerDefaults.Web"/>. The SDK itself
32-
/// deserializes incoming protocol messages with case-sensitive contracts, so a protocol property such as
33-
/// <c>params.name</c> is only recognized with the casing defined by the MCP specification.
31+
/// Property names are matched case-insensitively, as with <see cref="JsonSerializerDefaults.Web"/>, because these
32+
/// options are also used for user-defined data such as tool arguments and results. The SDK deserializes protocol
33+
/// messages with <see cref="ProtocolOptions"/> instead, so a protocol property such as <c>params.name</c> is only
34+
/// recognized with the casing defined by the MCP specification. Protocol types deserialized through these options
35+
/// keep case-insensitive matching.
3436
/// </para>
3537
/// </remarks>
36-
public static JsonSerializerOptions DefaultOptions { get; } = CreateDefaultOptions();
38+
public static JsonSerializerOptions DefaultOptions { get; } = CreateDefaultOptions(propertyNameCaseInsensitive: true);
39+
40+
/// <summary>
41+
/// Gets the <see cref="JsonSerializerOptions"/> singleton used to deserialize MCP and JSON-RPC protocol messages.
42+
/// </summary>
43+
/// <remarks>
44+
/// <para>
45+
/// These options are configured like <see cref="DefaultOptions"/>, except that property names are matched
46+
/// case-sensitively. Protocol property names are defined by the MCP and JSON-RPC specifications, so a property such
47+
/// as <c>params.Name</c> or <c>error.Code</c> is not bound to <c>name</c> or <c>code</c>.
48+
/// </para>
49+
/// <para>
50+
/// Use these options when deserializing protocol messages yourself. User-defined data, such as tool arguments,
51+
/// should continue to use <see cref="DefaultOptions"/> or caller-supplied options.
52+
/// </para>
53+
/// </remarks>
54+
public static JsonSerializerOptions ProtocolOptions { get; } = CreateDefaultOptions(propertyNameCaseInsensitive: false);
3755

3856
/// <summary>
3957
/// Creates default options to use for MCP-related serialization.
4058
/// </summary>
59+
/// <param name="propertyNameCaseInsensitive">Whether property names are matched case-insensitively.</param>
4160
/// <returns>The configured options.</returns>
4261
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL3050:RequiresDynamicCode", Justification = "Converter is guarded by IsReflectionEnabledByDefault check.")]
4362
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access", Justification = "Converter is guarded by IsReflectionEnabledByDefault check.")]
44-
private static JsonSerializerOptions CreateDefaultOptions()
63+
private static JsonSerializerOptions CreateDefaultOptions(bool propertyNameCaseInsensitive)
4564
{
46-
// Copy the configuration from the source generated context.
65+
// Copy the configuration from the source generated context. The context matches protocol property names
66+
// case-sensitively; DefaultOptions is also used for user-defined types (for example tool parameters),
67+
// so it keeps the web default.
4768
JsonSerializerOptions options = new(JsonContext.Default.Options)
4869
{
49-
// The source generated context matches protocol property names case-sensitively. These options
50-
// are also used for user-defined types (for example tool parameters), so keep the web default.
51-
PropertyNameCaseInsensitive = true,
70+
PropertyNameCaseInsensitive = propertyNameCaseInsensitive,
5271
};
5372

5473
// Chain with all supported types from MEAI.
@@ -111,7 +130,7 @@ internal static bool IsValidMcpToolSchema(JsonElement element)
111130
internal static bool IsValidToolOutputSchema(JsonElement element) =>
112131
element.ValueKind is JsonValueKind.Object or JsonValueKind.True or JsonValueKind.False;
113132

114-
// Keep in sync with CreateDefaultOptions above. Unlike DefaultOptions, property names are matched
133+
// Keep in sync with CreateDefaultOptions above. Like ProtocolOptions, property names are matched
115134
// case-sensitively: these contracts deserialize protocol messages, whose property names are defined
116135
// by the MCP and JSON-RPC specifications, and must agree with the JSON-RPC envelope converter.
117136
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web,

‎src/ModelContextProtocol.Core/Server/StreamServerTransport.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ private async Task ReadMessagesAsync()
117117

118118
try
119119
{
120-
if (JsonSerializer.Deserialize(line, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonRpcMessage))) is JsonRpcMessage message)
120+
if (JsonSerializer.Deserialize(line, McpJsonUtilities.ProtocolOptions.GetTypeInfo(typeof(JsonRpcMessage))) is JsonRpcMessage message)
121121
{
122122
await WriteMessageAsync(message, shutdownToken).ConfigureAwait(false);
123123
}

‎src/ModelContextProtocol.Extensions.Tasks/Client/McpTasksClientExtensions.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public static async ValueTask<ResultOrCreatedTask<CallToolResult>> CallToolAsTas
3737
JsonRpcRequest jsonRpcRequest = new()
3838
{
3939
Method = RequestMethods.ToolsCall,
40-
Params = JsonSerializer.SerializeToNode(paramsWithMeta, McpJsonUtilities.DefaultOptions.GetTypeInfo<CallToolRequestParams>()),
40+
Params = JsonSerializer.SerializeToNode(paramsWithMeta, McpJsonUtilities.ProtocolOptions.GetTypeInfo<CallToolRequestParams>()),
4141
};
4242

4343
JsonRpcResponse response = await client.SendRequestAsync(jsonRpcRequest, cancellationToken).ConfigureAwait(false);
@@ -51,7 +51,7 @@ public static async ValueTask<ResultOrCreatedTask<CallToolResult>> CallToolAsTas
5151
return new ResultOrCreatedTask<CallToolResult>(taskCreated);
5252
}
5353

54-
var callToolResult = JsonSerializer.Deserialize(response.Result, McpJsonUtilities.DefaultOptions.GetTypeInfo<CallToolResult>())
54+
var callToolResult = JsonSerializer.Deserialize(response.Result, McpJsonUtilities.ProtocolOptions.GetTypeInfo<CallToolResult>())
5555
?? throw new JsonException("Failed to deserialize CallToolResult from response.");
5656
return new ResultOrCreatedTask<CallToolResult>(callToolResult);
5757
}
@@ -163,7 +163,7 @@ public static async ValueTask<UpdateTaskResult> UpdateTaskAsync(
163163
{
164164
paramsObj["inputResponses"] = JsonSerializer.SerializeToNode(
165165
inputResponses,
166-
McpJsonUtilities.DefaultOptions.GetTypeInfo<IDictionary<string, InputResponse>>());
166+
McpJsonUtilities.ProtocolOptions.GetTypeInfo<IDictionary<string, InputResponse>>());
167167
}
168168

169169
JsonRpcRequest jsonRpcRequest = CreateTaskRequest(
@@ -268,7 +268,7 @@ private static async ValueTask<CallToolResult> PollTaskToCompletionAsync(
268268
switch (taskResult)
269269
{
270270
case CompletedTaskResult completed:
271-
return JsonSerializer.Deserialize(completed.Result, McpJsonUtilities.DefaultOptions.GetTypeInfo<CallToolResult>())
271+
return JsonSerializer.Deserialize(completed.Result, McpJsonUtilities.ProtocolOptions.GetTypeInfo<CallToolResult>())
272272
?? throw new JsonException("Failed to deserialize CallToolResult from completed task.");
273273

274274
case FailedTaskResult failed:

‎src/ModelContextProtocol.Extensions.Tasks/Protocol/GetTaskResult.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ internal sealed class Converter : JsonConverter<GetTaskResult>
169169
}
170170
string requestKey = reader.GetString()!;
171171
reader.Read();
172-
var inputRequest = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.DefaultOptions.GetTypeInfo<InputRequest>())
172+
var inputRequest = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.ProtocolOptions.GetTypeInfo<InputRequest>())
173173
?? throw new JsonException($"Failed to deserialize InputRequest for key '{requestKey}'.");
174174
inputRequests[requestKey] = inputRequest;
175175
}
@@ -315,7 +315,7 @@ public override void Write(Utf8JsonWriter writer, GetTaskResult value, JsonSeria
315315
foreach (var kvp in reqs)
316316
{
317317
writer.WritePropertyName(kvp.Key);
318-
JsonSerializer.Serialize(writer, kvp.Value, McpJsonUtilities.DefaultOptions.GetTypeInfo<InputRequest>());
318+
JsonSerializer.Serialize(writer, kvp.Value, McpJsonUtilities.ProtocolOptions.GetTypeInfo<InputRequest>());
319319
}
320320
}
321321
writer.WriteEndObject();

‎src/ModelContextProtocol.Extensions.Tasks/Protocol/TaskStatusNotificationParams.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ internal sealed class Converter : JsonConverter<TaskStatusNotificationParams>
171171
}
172172
string requestKey = reader.GetString()!;
173173
reader.Read();
174-
var inputRequest = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.DefaultOptions.GetTypeInfo<InputRequest>())
174+
var inputRequest = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.ProtocolOptions.GetTypeInfo<InputRequest>())
175175
?? throw new JsonException($"Failed to deserialize InputRequest for key '{requestKey}'.");
176176
inputRequests[requestKey] = inputRequest;
177177
}
@@ -311,7 +311,7 @@ public override void Write(Utf8JsonWriter writer, TaskStatusNotificationParams v
311311
foreach (var kvp in reqs)
312312
{
313313
writer.WritePropertyName(kvp.Key);
314-
JsonSerializer.Serialize(writer, kvp.Value, McpJsonUtilities.DefaultOptions.GetTypeInfo<InputRequest>());
314+
JsonSerializer.Serialize(writer, kvp.Value, McpJsonUtilities.ProtocolOptions.GetTypeInfo<InputRequest>());
315315
}
316316
}
317317
writer.WriteEndObject();

‎src/ModelContextProtocol.Extensions.Tasks/Server/McpTasksBuilderExtensions.cs‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ private async Task ExecuteTaskAsync(
225225
try
226226
{
227227
var error = new JsonRpcErrorDetail { Code = (int)McpErrorCode.InternalError, Message = outer.Message };
228-
var errorJson = JsonSerializer.SerializeToElement(error, McpJsonUtilities.DefaultOptions.GetTypeInfo<JsonRpcErrorDetail>());
228+
var errorJson = JsonSerializer.SerializeToElement(error, McpJsonUtilities.ProtocolOptions.GetTypeInfo<JsonRpcErrorDetail>());
229229
await _store.SetFailedAsync(taskId, errorJson).ConfigureAwait(false);
230230
}
231231
catch (Exception storeEx)
@@ -259,12 +259,12 @@ private async Task ExecuteToolPipelineAsync(
259259
Code = (int)McpErrorCode.InternalError,
260260
Message = $"{nameof(IMcpTaskStore)} is configured and the {nameof(McpServerHandlers.CallToolWithAlternateHandler)} returned IsAlternate = true. Use only one mechanism.",
261261
};
262-
var errorJson = JsonSerializer.SerializeToElement(error, McpJsonUtilities.DefaultOptions.GetTypeInfo<JsonRpcErrorDetail>());
262+
var errorJson = JsonSerializer.SerializeToElement(error, McpJsonUtilities.ProtocolOptions.GetTypeInfo<JsonRpcErrorDetail>());
263263
await _store.SetFailedAsync(taskId, errorJson).ConfigureAwait(false);
264264
return;
265265
}
266266

267-
var resultJson = JsonSerializer.SerializeToElement(augmented.Result!, McpJsonUtilities.DefaultOptions.GetTypeInfo<CallToolResult>());
267+
var resultJson = JsonSerializer.SerializeToElement(augmented.Result!, McpJsonUtilities.ProtocolOptions.GetTypeInfo<CallToolResult>());
268268
await _store.SetCompletedAsync(taskId, resultJson).ConfigureAwait(false);
269269
}
270270
catch (OperationCanceledException) when (taskCancellationToken.IsCancellationRequested)
@@ -278,14 +278,14 @@ private async Task ExecuteToolPipelineAsync(
278278
Code = (int)McpErrorCode.InvalidRequest,
279279
Message = "MRTR and tasks cannot be composed via [McpServerTool] yet.",
280280
};
281-
var errorJson = JsonSerializer.SerializeToElement(error, McpJsonUtilities.DefaultOptions.GetTypeInfo<JsonRpcErrorDetail>());
281+
var errorJson = JsonSerializer.SerializeToElement(error, McpJsonUtilities.ProtocolOptions.GetTypeInfo<JsonRpcErrorDetail>());
282282
await _store.SetFailedAsync(taskId, errorJson).ConfigureAwait(false);
283283
}
284284
catch (McpProtocolException mcpEx)
285285
{
286286
// SEP-2663 §186: protocol exceptions store as failed with JSON-RPC error shape.
287287
var error = new JsonRpcErrorDetail { Code = (int)mcpEx.ErrorCode, Message = mcpEx.Message };
288-
var errorJson = JsonSerializer.SerializeToElement(error, McpJsonUtilities.DefaultOptions.GetTypeInfo<JsonRpcErrorDetail>());
288+
var errorJson = JsonSerializer.SerializeToElement(error, McpJsonUtilities.ProtocolOptions.GetTypeInfo<JsonRpcErrorDetail>());
289289
await _store.SetFailedAsync(taskId, errorJson).ConfigureAwait(false);
290290
}
291291
catch (Exception ex)
@@ -302,7 +302,7 @@ private async Task ExecuteToolPipelineAsync(
302302
: $"An error occurred invoking '{request.Params?.Name}'.",
303303
}],
304304
};
305-
var resultJson = JsonSerializer.SerializeToElement(errorResult, McpJsonUtilities.DefaultOptions.GetTypeInfo<CallToolResult>());
305+
var resultJson = JsonSerializer.SerializeToElement(errorResult, McpJsonUtilities.ProtocolOptions.GetTypeInfo<CallToolResult>());
306306
await _store.SetCompletedAsync(taskId, resultJson).ConfigureAwait(false);
307307
}
308308
}
@@ -336,7 +336,7 @@ private async Task ExecuteToolPipelineAsync(
336336
// InputResponsesCore backing property on RequestParams. The extension's source-gen
337337
// context cannot see that internal member.
338338
var inputResponses = request.Params?["inputResponses"]?.Deserialize(
339-
McpJsonUtilities.DefaultOptions.GetTypeInfo<IDictionary<string, InputResponse>>())
339+
McpJsonUtilities.ProtocolOptions.GetTypeInfo<IDictionary<string, InputResponse>>())
340340
?? new Dictionary<string, InputResponse>();
341341

342342
await _store.ResolveInputRequestsAsync(taskId, inputResponses, cancellationToken).ConfigureAwait(false);

‎src/ModelContextProtocol.Extensions.Tasks/Server/McpTasksServerExtensions.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ internal static McpServer WithMcpTaskOutgoingRequestInterceptor(
6161
Method = method,
6262
Params = paramsNode is null
6363
? default
64-
: JsonSerializer.SerializeToElement(paramsNode, McpJsonUtilities.DefaultOptions.GetTypeInfo<JsonNode>()),
64+
: JsonSerializer.SerializeToElement(paramsNode, McpJsonUtilities.ProtocolOptions.GetTypeInfo<JsonNode>()),
6565
};
6666

6767
var tcs = new TaskCompletionSource<InputResponse>(TaskCreationOptions.RunContinuationsAsynchronously);

‎tests/ModelContextProtocol.Tests/McpJsonUtilitiesTests.cs‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,51 @@ private sealed class WeatherQuery
3636
public string? City { get; set; }
3737
}
3838

39+
[Fact]
40+
public static void ProtocolOptions_IsSingletonAndMatchesPropertyNamesCaseSensitively()
41+
{
42+
var options = McpJsonUtilities.ProtocolOptions;
43+
44+
Assert.NotNull(options);
45+
Assert.True(options.IsReadOnly);
46+
Assert.Same(options, McpJsonUtilities.ProtocolOptions);
47+
Assert.NotSame(McpJsonUtilities.DefaultOptions, options);
48+
Assert.False(options.PropertyNameCaseInsensitive);
49+
}
50+
51+
[Fact]
52+
public static void ProtocolOptions_DoesNotBindAlternatelyCasedErrorDetail()
53+
{
54+
const string Json = """{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"boom","Code":1,"Message":"other"}}""";
55+
56+
var message = JsonSerializer.Deserialize(Json, McpJsonUtilities.ProtocolOptions.GetTypeInfo<JsonRpcMessage>());
57+
var error = Assert.IsType<JsonRpcError>(message);
58+
Assert.Equal(-32603, error.Error.Code);
59+
Assert.Equal("boom", error.Error.Message);
60+
61+
// DefaultOptions keeps case-insensitive matching, so the later spelling wins there.
62+
message = JsonSerializer.Deserialize(Json, McpJsonUtilities.DefaultOptions.GetTypeInfo<JsonRpcMessage>());
63+
error = Assert.IsType<JsonRpcError>(message);
64+
Assert.Equal(1, error.Error.Code);
65+
Assert.Equal("other", error.Error.Message);
66+
}
67+
68+
[Fact]
69+
public static void ProtocolOptions_DoesNotBindAlternatelyCasedCallToolResultFields()
70+
{
71+
const string Json = """{"content":[{"type":"text","text":"ok"}],"Content":[],"IsError":true}""";
72+
73+
var result = JsonSerializer.Deserialize(Json, McpJsonUtilities.ProtocolOptions.GetTypeInfo<CallToolResult>());
74+
Assert.NotNull(result);
75+
Assert.Equal("ok", Assert.IsType<TextContentBlock>(Assert.Single(result.Content)).Text);
76+
Assert.Null(result.IsError);
77+
78+
result = JsonSerializer.Deserialize(Json, McpJsonUtilities.DefaultOptions.GetTypeInfo<CallToolResult>());
79+
Assert.NotNull(result);
80+
Assert.Empty(result.Content);
81+
Assert.True(result.IsError);
82+
}
83+
3984
[Fact]
4085
public static void DefaultOptions_UseReflectionWhenEnabled()
4186
{

0 commit comments

Comments
 (0)