Skip to content

Handle JsonRpcError in initialize #563

@wzxxing

Description

@wzxxing

Describe the bug
A clear and concise description of what the bug is.

When the MCP protocol initialization failed, the server can return a JSON RPC Error object, which is currently ignored by the rust SDK.

// Server SHOULD NOT send any other messages before handshake. We ignore them anyway
_ => tracing::warn!(?message, "Received unexpected message"),

The Specification suggested that

Implementations SHOULD be prepared to handle these error cases:

https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle#error-handling

To Reproduce
Steps to reproduce the behavior:

  1. I found this when using the Kiro CLI which uses the rust-sdk. Plugging a MCP server that initialize failure. The error can only be found through tracing
2025-11-26T11:05:21.291608Z  WARN rmcp::service::client: 129: Received unexpected message Error(JsonRpcError { jsonrpc: JsonRpcVersion2_0, id: Number(0), error: ErrorData { code: ErrorCode(-32001), message: "Your AWS session token has expired. Please refresh your credentials and try again. If you're using temporary credentials, you may need to re-authenticate to obtain new credentials.", data: None } })

expect_response ignores the mcp jsonrpc error, hence there was never a response received by the client.

let (response, response_id) = expect_response(
&mut transport,
"initialize response",
&service,
peer.clone(),
)
.await?;

Because my test-mcp server quits after the initialization error, I got a very generic "connection closed" message.

Expected behavior

My test server response to initialization with a synthesized JSON RPC error, I expect the JSON RPC error should be used as the ClientInitializeError.

Logs
If applicable, add logs to help explain your problem.

Additional context
Add any other context about the problem here.

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