Skip to content

Commit 54e853b

Browse files
committed
Match protocol property names case-sensitively
Protocol DTOs were deserialized with the source-generated context, which uses the web defaults and binds property names case-insensitively, while the JSON-RPC envelope converter matches its properties exactly. A request such as tools/call with params.Name was therefore dispatched even though middleware inspecting params.name would not recognize it. The source-generated context now matches property names case-sensitively. DefaultOptions keeps case-insensitive matching because it is also used for user-defined types such as tool parameters. Fixes modelcontextprotocol#1897 Signed-off-by: FenjuFu <[email protected]>
1 parent af0fda3 commit 54e853b

3 files changed

Lines changed: 153 additions & 3 deletions

File tree

‎src/ModelContextProtocol.Core/McpJsonUtilities.cs‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ public static partial class McpJsonUtilities
2727
/// <item>Enables <see cref="JsonNumberHandling.AllowReadingFromString"/> as the default number handling for number types.</item>
2828
/// </list>
2929
/// </para>
30+
/// <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.
34+
/// </para>
3035
/// </remarks>
3136
public static JsonSerializerOptions DefaultOptions { get; } = CreateDefaultOptions();
3237

@@ -39,7 +44,12 @@ public static partial class McpJsonUtilities
3944
private static JsonSerializerOptions CreateDefaultOptions()
4045
{
4146
// Copy the configuration from the source generated context.
42-
JsonSerializerOptions options = new(JsonContext.Default.Options);
47+
JsonSerializerOptions options = new(JsonContext.Default.Options)
48+
{
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,
52+
};
4353

4454
// Chain with all supported types from MEAI.
4555
options.TypeInfoResolverChain.Add(AIJsonUtilities.DefaultOptions.TypeInfoResolver!);
@@ -101,10 +111,13 @@ internal static bool IsValidMcpToolSchema(JsonElement element)
101111
internal static bool IsValidToolOutputSchema(JsonElement element) =>
102112
element.ValueKind is JsonValueKind.Object or JsonValueKind.True or JsonValueKind.False;
103113

104-
// Keep in sync with CreateDefaultOptions above.
114+
// Keep in sync with CreateDefaultOptions above. Unlike DefaultOptions, property names are matched
115+
// case-sensitively: these contracts deserialize protocol messages, whose property names are defined
116+
// by the MCP and JSON-RPC specifications, and must agree with the JSON-RPC envelope converter.
105117
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web,
106118
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
107-
NumberHandling = JsonNumberHandling.AllowReadingFromString)]
119+
NumberHandling = JsonNumberHandling.AllowReadingFromString,
120+
PropertyNameCaseInsensitive = false)]
108121

109122
// JSON-RPC
110123
[JsonSerializable(typeof(JsonRpcMessage))]

‎tests/ModelContextProtocol.Tests/McpJsonUtilitiesTests.cs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,25 @@ public static void DefaultOptions_IsSingleton()
1717
Assert.Same(options, McpJsonUtilities.DefaultOptions);
1818
}
1919

20+
[Fact]
21+
public static void DefaultOptions_MatchesPropertyNamesCaseInsensitively()
22+
{
23+
var options = McpJsonUtilities.DefaultOptions;
24+
25+
Assert.True(options.PropertyNameCaseInsensitive);
26+
27+
if (JsonSerializer.IsReflectionEnabledByDefault)
28+
{
29+
var query = JsonSerializer.Deserialize<WeatherQuery>("""{"CITY":"Hefei"}""", options);
30+
Assert.Equal("Hefei", query?.City);
31+
}
32+
}
33+
34+
private sealed class WeatherQuery
35+
{
36+
public string? City { get; set; }
37+
}
38+
2039
[Fact]
2140
public static void DefaultOptions_UseReflectionWhenEnabled()
2241
{

‎tests/ModelContextProtocol.Tests/Server/McpServerTests.cs‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1297,6 +1297,124 @@ await transport.SendMessageAsync(
12971297
await runTask;
12981298
}
12991299

1300+
[Fact]
1301+
public async Task Call_Tool_Request_Params_Are_Matched_Case_Sensitively()
1302+
{
1303+
await using var transport = new TestServerTransport();
1304+
var options = CreateOptions(new ServerCapabilities { Tools = new() });
1305+
var invocations = new List<CallToolRequestParams?>();
1306+
options.Handlers.CallToolHandler = (request, ct) =>
1307+
{
1308+
invocations.Add(request.Params);
1309+
return new ValueTask<CallToolResult>(new CallToolResult());
1310+
};
1311+
options.Handlers.ListToolsHandler = (request, ct) => throw new NotImplementedException();
1312+
1313+
await using var server = McpServer.Create(transport, options, LoggerFactory);
1314+
var runTask = server.RunAsync(TestContext.Current.CancellationToken);
1315+
1316+
var replies = new Dictionary<string, TaskCompletionSource<JsonRpcMessageWithId>>
1317+
{
1318+
["1"] = new(),
1319+
["2"] = new(),
1320+
["3"] = new(),
1321+
["4"] = new(),
1322+
["5"] = new(),
1323+
};
1324+
transport.OnMessageSent = message =>
1325+
{
1326+
if (message is JsonRpcResponse or JsonRpcError &&
1327+
replies.TryGetValue(((JsonRpcMessageWithId)message).Id.ToString(), out var tcs))
1328+
{
1329+
tcs.TrySetResult((JsonRpcMessageWithId)message);
1330+
}
1331+
};
1332+
1333+
// "Name" is not the protocol's "name", so the required property is missing and the tool is not invoked.
1334+
await transport.SendMessageAsync(
1335+
new JsonRpcRequest
1336+
{
1337+
Method = RequestMethods.ToolsCall,
1338+
Id = new RequestId(1),
1339+
Params = JsonNode.Parse("""{"Name":"echo","arguments":{}}"""),
1340+
},
1341+
TestContext.Current.CancellationToken);
1342+
var rejected = await replies["1"].Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken);
1343+
Assert.IsType<JsonRpcError>(rejected);
1344+
Assert.Empty(invocations);
1345+
1346+
// An alternately cased optional property is not bound either.
1347+
await transport.SendMessageAsync(
1348+
new JsonRpcRequest
1349+
{
1350+
Method = RequestMethods.ToolsCall,
1351+
Id = new RequestId(2),
1352+
Params = JsonNode.Parse("""{"name":"echo","Arguments":{"text":"hi"}}"""),
1353+
},
1354+
TestContext.Current.CancellationToken);
1355+
Assert.IsType<JsonRpcResponse>(await replies["2"].Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken));
1356+
1357+
await transport.SendMessageAsync(
1358+
new JsonRpcRequest
1359+
{
1360+
Method = RequestMethods.ToolsCall,
1361+
Id = new RequestId(3),
1362+
Params = JsonNode.Parse("""{"name":"echo","arguments":{"text":"hi"}}"""),
1363+
},
1364+
TestContext.Current.CancellationToken);
1365+
Assert.IsType<JsonRpcResponse>(await replies["3"].Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken));
1366+
1367+
// When both spellings are present, only "name" is bound, regardless of order. Keys inside "arguments"
1368+
// are user data and are preserved as distinct entries.
1369+
await transport.SendMessageAsync(
1370+
new JsonRpcRequest
1371+
{
1372+
Method = RequestMethods.ToolsCall,
1373+
Id = new RequestId(4),
1374+
Params = JsonNode.Parse("""{"name":"echo","Name":"other","arguments":{"text":"hi","Text":"HI"}}"""),
1375+
},
1376+
TestContext.Current.CancellationToken);
1377+
Assert.IsType<JsonRpcResponse>(await replies["4"].Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken));
1378+
1379+
await transport.SendMessageAsync(
1380+
new JsonRpcRequest
1381+
{
1382+
Method = RequestMethods.ToolsCall,
1383+
Id = new RequestId(5),
1384+
Params = JsonNode.Parse("""{"Name":"other","name":"echo"}"""),
1385+
},
1386+
TestContext.Current.CancellationToken);
1387+
Assert.IsType<JsonRpcResponse>(await replies["5"].Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken));
1388+
1389+
Assert.Collection(invocations,
1390+
p =>
1391+
{
1392+
Assert.Equal("echo", p?.Name);
1393+
Assert.Null(p?.Arguments);
1394+
},
1395+
p =>
1396+
{
1397+
Assert.Equal("echo", p?.Name);
1398+
Assert.Equal("hi", p?.Arguments?["text"].GetString());
1399+
},
1400+
p =>
1401+
{
1402+
Assert.Equal("echo", p?.Name);
1403+
Assert.NotNull(p?.Arguments);
1404+
Assert.Equal(2, p.Arguments.Count);
1405+
Assert.Equal("hi", p.Arguments["text"].GetString());
1406+
Assert.Equal("HI", p.Arguments["Text"].GetString());
1407+
},
1408+
p =>
1409+
{
1410+
Assert.Equal("echo", p?.Name);
1411+
Assert.Null(p?.Arguments);
1412+
});
1413+
1414+
await transport.DisposeAsync();
1415+
await runTask;
1416+
}
1417+
13001418
private async Task Can_Handle_Requests(ServerCapabilities? serverCapabilities, string method, Action<McpServerOptions>? configureOptions, Action<McpServer, JsonNode?> assertResult)
13011419
{
13021420
await using var transport = new TestServerTransport();

0 commit comments

Comments
 (0)