Skip to content

Commit eec28fc

Browse files
Copilothalter73
andcommitted
Fix NullReferenceException when request.Params is null in JSON-RPC
When a client omits the "params" field from a JSON-RPC message, JsonSerializer.Deserialize returns null. Since RequestContext.Params is now non-nullable, we need to deserialize from an empty JSON object instead to get a valid default TParams instance. Co-authored-by: halter73 <54385+halter73@users.noreply.github.com> Agent-Logs-Url: https://github.com/modelcontextprotocol/csharp-sdk/sessions/1e9aed1a-2748-4117-987c-611e23751bea
1 parent db960e6 commit eec28fc

1 file changed

Lines changed: 6 additions & 1 deletion

File tree

src/ModelContextProtocol.Core/RequestHandlers.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ namespace ModelContextProtocol;
77

88
internal sealed class RequestHandlers : Dictionary<string, Func<JsonRpcRequest, CancellationToken, Task<JsonNode?>>>
99
{
10+
private static readonly JsonNode EmptyJsonObject = JsonNode.Parse("{}")!;
11+
1012
/// <summary>
1113
/// Registers a handler for incoming requests of a specific method in the MCP protocol.
1214
/// </summary>
@@ -40,7 +42,10 @@ public void Set<TParams, TResult>(
4042

4143
this[method] = async (request, cancellationToken) =>
4244
{
43-
TParams typedRequest = JsonSerializer.Deserialize(request.Params, requestTypeInfo)!;
45+
// When request.Params is null (e.g. the client omitted "params" from the JSON-RPC message),
46+
// deserialize from an empty JSON object so we get a valid default TParams instance
47+
// rather than null, since RequestContext.Params is now non-nullable.
48+
TParams typedRequest = JsonSerializer.Deserialize(request.Params ?? EmptyJsonObject, requestTypeInfo)!;
4449
object? result = await handler(typedRequest, request, cancellationToken).ConfigureAwait(false);
4550
return JsonSerializer.SerializeToNode(result, responseTypeInfo);
4651
};

0 commit comments

Comments
 (0)