Skip to content

Handle schema validation failures gracefully #741

@kbhadury

Description

@kbhadury

When using the DefaultMcpStatelessServerHandler#handleRequest method, the SDK throws various exceptions if the incoming request doesn't adhere to the MCP schema. Here are a couple examples I've observed:

{
  "jsonrpc": "2.0",
  "id": "1",
  "method": "tools/call",
  "params": {
    "name": "myTool",
    "arguments": "This should be an object!"
  }
}

This causes an IllegalArgumentException to be thrown by McpStatelessAsyncServer when Jackson attempts to parse the arguments field, which is supposed to be an Object:

private McpStatelessRequestHandler<CallToolResult> toolsCallRequestHandler() {
return (ctx, params) -> {
McpSchema.CallToolRequest callToolRequest = jsonMapper.convertValue(params,
new TypeRef<McpSchema.CallToolRequest>() {
});

Here's a second example:

{
  "jsonrpc": "2.0",
  "id": "1",
  "method": "tools/call",
  "params": {
    "arguments": {
      "key": "value"
    }
  }
}

In this example, the name field was omitted. This causes McpStatelessAsyncServer to throw a NullPointerException when it attempts to call name().equals(...):

Optional<McpStatelessServerFeatures.AsyncToolSpecification> toolSpecification = this.tools.stream()
.filter(tr -> callToolRequest.name().equals(tr.tool().name()))
.findAny();

Is there a way to validate the incoming JSON against the MCP schema before passing it to the handler object? Or can the handler object be enhanced to deal with these kinds of errors more gracefully and return a friendlier error to the caller? Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions