From c5cbc22d9c1f53654d982f1b6408008959f83f2b Mon Sep 17 00:00:00 2001 From: Michael Vorburger Date: Sun, 9 Nov 2025 01:02:42 +0100 Subject: [PATCH] fix: Validate JSONRPCResponse in constructor (fixes #605) --- .../modelcontextprotocol/spec/McpSchema.java | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/mcp-core/src/main/java/io/modelcontextprotocol/spec/McpSchema.java b/mcp-core/src/main/java/io/modelcontextprotocol/spec/McpSchema.java index e43469903..3a587e15d 100644 --- a/mcp-core/src/main/java/io/modelcontextprotocol/spec/McpSchema.java +++ b/mcp-core/src/main/java/io/modelcontextprotocol/spec/McpSchema.java @@ -250,15 +250,19 @@ public record JSONRPCRequest( // @formatter:off /** * Constructor that validates MCP-specific ID requirements. Unlike base JSON-RPC, * MCP requires that: (1) Requests MUST include a string or integer ID; (2) The ID - * MUST NOT be null + * MUST NOT be null. */ public JSONRPCRequest { - Assert.notNull(id, "MCP requests MUST include an ID - null IDs are not allowed"); - Assert.isTrue(id instanceof String || id instanceof Integer || id instanceof Long, - "MCP requests MUST have an ID that is either a string or integer"); + validateID(id); } } + private static void validateID(Object id) { + Assert.notNull(id, "MCP requests/responses MUST include an ID - null IDs are not allowed"); + Assert.isTrue(id instanceof String || id instanceof Integer || id instanceof Long, + "MCP requests/responses MUST have an ID that is either a string or integer"); + } + /** * A notification which does not expect a response. * @@ -294,6 +298,16 @@ public record JSONRPCResponse( // @formatter:off @JsonProperty("result") Object result, @JsonProperty("error") JSONRPCError error) implements JSONRPCMessage { // @formatter:on + /** + * Constructor that validates (a) MCP-specific ID requirements (unlike base + * JSON-RPC, MCP requires that: (1) Requests MUST include a string or integer ID; + * (2) The ID MUST NOT be null.) and (b) that EITHER result OR error are non-null. + */ + public JSONRPCResponse { + validateID(id); + Assert.isTrue(result != null || error != null, "MCP responses MUST have EITHER a result OR an error"); + } + /** * A response to a request that indicates an error occurred. *