Skip to content

fix(rmcp): reject null CallToolRequestParams fields and ignore pre-init cancellations - #1532

Open
aloneangel45 wants to merge 5 commits into
modelcontextprotocol:mainfrom
aloneangel45:fix/reject-null-tool-args-and-preinit-cancel
Open

aloneangel45 wants to merge 5 commits into
modelcontextprotocol:mainfrom
aloneangel45:fix/reject-null-tool-args-and-preinit-cancel

Conversation

@aloneangel45

Copy link
Copy Markdown

Closes #1525

Summary

Fixes both server-side issues reported in #1525:

  1. Reject explicit null for CallToolRequestParams optional object/string fields (-32602 Invalid params):

    • Added deserialize_non_null_option on CallToolRequestParams::{arguments, input_responses, request_state} in crates/rmcp/src/model.rs so omitted fields remain None while explicit null values are rejected.
    • Because ClientRequest is #[serde(untagged)] with CustomRequest as its catch-all variant, a malformed tools/call payload falls through to CustomRequest instead of reaching CallToolRequest; updated ServerHandler::handle_request and Router::handle_request to return ErrorCode::INVALID_PARAMS (-32602) when method == "tools/call" and tools capability is enabled (instead of falling back to -32601 Method not found).
  2. Ignore notifications/cancelled arriving before initialization finishes:

    • Updated the pre-init loop in serve_server_with_ct_inner (crates/rmcp/src/service/server.rs) to ignore ClientNotification::CancelledNotification(_) (for example cancelling a completed server/discover probe or unknown request id) instead of aborting startup with ServerInitializeError::ExpectedInitializeRequest.

Verification

  • cargo fmt --all -- --check
  • cargo clippy -p rmcp --lib --features "client,server,macros,schemars" -- -D warnings -A clippy::result_large_err
  • cargo test -p rmcp --lib --features "server,macros,schemars" (305 passed)
  • cargo test -p rmcp --test test_server_initialization --test test_tool_macros --test test_custom_request --test test_tool_routers --test test_deserialization --features "client,server,macros,schemars" (including new regression tests pre_init_cancelled_notification_is_ignored_and_server_continues, test_tools_call_rejects_explicit_null_arguments_with_invalid_params, and call_tool_params_rejects_explicit_null_fields)

@aloneangel45
aloneangel45 requested a review from a team as a code owner December 1, 2026 03:44
@github-actions github-actions Bot added T-test Testing related changes T-core Core library changes T-handler Handler implementation changes T-model Model/data structure changes T-service Service layer changes labels Dec 1, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-01T19:11:07.198133Z 93412b6 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions
github-actions Bot requested a review from connor4312 December 1, 2026 03:44
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

@connor4312 is on triage rotation this week and is the reviewer for this one.

Labels come from the PR labeler. Please review the change.

Automated triage. Labels are a first pass and the assigned maintainer has the final say.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7624d726fc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/rmcp/src/model.rs Outdated
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_non_null_option"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove null from the generated tool-call schema

With schemars enabled, JsonSchema still derives these properties from Option<T>: the checked-in client_json_rpc_message_schema_current.json permits null for arguments, inputResponses, and requestState. Consumers validating CallToolRequestParams against that schema can construct explicit-null tools/call requests that this deserializer now rejects with -32602; add non-null schema overrides and update the generated schema snapshots alongside the runtime change.

Useful? React with 👍 / 👎.

@github-actions github-actions Bot added the T-config Configuration file changes label Dec 1, 2026
@aloneangel45

Copy link
Copy Markdown
Author

Updated CallToolRequestParams in ad47b5f so arguments, inputResponses, and requestState generate non-nullable schemars schemas (with = "JsonObject", "InputResponses", "String") while remaining optional, and updated both client_json_rpc_message_schema.json and client_json_rpc_message_schema_current.json. Verified test_message_schema, test_deserialization, test_tool_macros, and clippy pass locally.

@jokemanfire jokemanfire left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified at ad47b5f1 (base d0dab0e3 = current origin/main). I re-ran the gate and reproduced both bugs at the base commit instead of trusting the PR text.

What I ran (all in a clean worktree at the head SHA, CARGO_TARGET_DIR shared with the cached build)

  • cargo fmt --all -- --check → clean.
  • cargo clippy -p rmcp --lib --features "client,server,macros,schemars" -- -D warnings -A clippy::result_large_err → clean (1m18s).
  • cargo test -p rmcp --test test_tool_macros --test test_server_initialization --test test_deserialization --test test_message_schema --features "client,server,macros,schemars" → 25 / 3 / 23 / 18 passed, 0 failed.
  • Red-before: the two new tests copied onto d0dab0e3 fail as expected —
    • pre_init_cancelled_notification_is_ignored_and_server_continues: panicked at tests/test_server_initialization.rs:702:48: called Option::unwrap() on a None value (the server never came up).
    • test_tools_call_rejects_explicit_null_arguments_with_invalid_params: panicked at tests/test_tool_macros.rs:766:18 (it got a successful tool response instead of -32602).

Independent probe (my own throwaway test, not part of the branch)
Served a Router::new(NoToolsHandler) over a duplex transport and drove it with raw JSON-RPC:

  • {"name":"hi","arguments":null} → -32602 invalid parameters for tools/call (guard active).
  • "params": null, "arguments": 5, missing name → same -32602.
  • A valid tools/call for a nonexistent tool still goes down the normal path (-32602 "tool not found"), i.e. the guard does not swallow well-formed requests.

One thing worth fixing: the condition in router.rs is always true
crates/rmcp/src/handler/server/router.rs:149-151 gates on self.get_info().capabilities.tools.is_some(), but this type's own get_info() (same file, :162-168) unconditionally does tools.get_or_insert_with(Default::default()). My probe confirms it: for a wrapped handler whose ServerInfo has capabilities.tools = None, Router::get_info() still reports Some(ToolsCapability { list_changed: Some(true) }). So on the Router path the guard is unconditional, and a Router wrapping a handler that deliberately answers tools/call through on_custom_request would now get -32602 instead of the handler's answer. If the intent is "only when tools are really advertised", use the inner service's info (ServerHandler::get_info(&self.service).capabilities.tools.is_some()); if unconditional is intended, drop the clause so the invariant is explicit.

Coverage gap: the new test drives a #[tool_handler] type, which exercises the ServerHandler::handle_request arm (handler/server.rs:254-265) only. Nothing in the suite exercises the new Router arm, even though Router::handle_request is a separate entry point that runs before delegation. A test shaped like the probe above (serve a Router, send arguments: null, expect -32602) would lock it down.

Minor:

  • deserialize_non_null_option (model.rs:4177) is deserialize_present_value (model.rs:4167) generalized; the latter could be expressed as deserialize_non_null_option::<Value> to avoid two near-identical helpers with opposite doc wording.
  • Behaviour change worth a line in the release notes: "arguments": null / "inputResponses": null / "requestState": null were accepted before and now return -32602. Spec-correct, but clients that serialize None as null will start failing.
  • Codex's P2 about the generated schema allowing null is addressed at head: JsonObject/InputResponses/String overrides make the schema non-nullable while the fields stay optional, and test_message_schema + both snapshots agree (I diffed them).

Overall this is the right shape and the verification claims hold up. I'm not approving yet — mainly because of the always-true capability check on the Router path and the missing test for it; a reply on those two is all I need.

@jokemanfire

Copy link
Copy Markdown
Member

Correction to my review above: I wrote that the PR base equals current origin/main; it does not any more. d0dab0e3 is still an ancestor, but main is now c8e8b084 (#1471 async_rw oversized-stdio reply, #1529 ci doc links). Neither touches service.rs, model.rs, handler/ or the transport this PR changes, and all numbers in the review were produced at the PR head SHA, so the findings stand — only that one clause was wrong.

Worth a rebase before merge so CI exercises both new main commits alongside this change.

@aloneangel45

Copy link
Copy Markdown
Author

@jokemanfire Thanks for the thorough review and probe! Addressed everything in rebased head 02f6930 (onto upstream/main 68ce081):

  1. Router::handle_request invariant (crates/rmcp/src/handler/server/router.rs): Dropped the always-true self.get_info().capabilities.tools.is_some() clause on the CustomRequest tools/call arm and documented why Router always rejects malformed tools/call requests directly (since Router::get_info unconditionally advertises capabilities.tools).
  2. Router test coverage (crates/rmcp/tests/test_tool_macros.rs): Extracted assert_null_arguments_rejected and added test_router_tools_call_rejects_explicit_null_arguments_with_invalid_params serving Router::new(PlainHandler) over a duplex transport.
  3. Unified deserialize helper (crates/rmcp/src/model.rs): Consolidated deserialize_present_value and deserialize_non_null_option into a single deserialize_present_option<T> helper.
  4. Rebased onto upstream/main (68ce081 / c8e8b08).

@aloneangel45
aloneangel45 force-pushed the fix/reject-null-tool-args-and-preinit-cancel branch from ad47b5f to 02f6930 Compare December 1, 2026 14:42
@aloneangel45
aloneangel45 force-pushed the fix/reject-null-tool-args-and-preinit-cancel branch from 02f6930 to 2253ab8 Compare December 1, 2026 16:03
@aloneangel45

Copy link
Copy Markdown
Author

Rebased onto main to resolve the merge conflict in crates/rmcp/src/service/server.rs (keeping upstream's generalized pre-init notification drop). Verified test_server_initialization (23 passed) and test_tool_macros (19 passed).

@github-actions github-actions Bot removed the T-service Service layer changes label Dec 1, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2253ab8604

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/rmcp/src/handler/server.rs Outdated
Comment on lines +255 to +256
if request.method == CallToolRequestMethod::VALUE
&& self.get_info().capabilities.tools.is_some()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate malformed calls before generic Service dispatch

For a server that implements the public Service<RoleServer> directly rather than using the ServerHandler blanket implementation or Router, tools/call with arguments: null falls back to ClientRequest::CustomRequest; this guard and the router’s parallel branch are never reached. A direct handler that dispatches custom requests as tool calls can still execute the malformed request. Move this validation to shared server dispatch if null rejection is meant to cover every serve path.

Useful? React with 👍 / 👎.

@aloneangel45

Copy link
Copy Markdown
Author

@chatgpt-codex-connector[bot] Good catch - moved malformed tools/call validation into shared ServiceRole::validate_peer_request in serve_inner (service.rs / service/server.rs), removed the duplicate guards from ServerHandler and Router, and added a direct Service<RoleServer> integration test (test_direct_service_tools_call_rejects_explicit_null_arguments_with_invalid_params). Verified all 354 rmcp --lib, 23 test_server_initialization, and 20 test_tool_macros tests pass.

@github-actions github-actions Bot added T-service Service layer changes and removed T-handler Handler implementation changes labels Dec 1, 2026

@SIDDARTHAREDDY8 SIDDARTHAREDDY8 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read the diff against base 95e7465 and the new tests. The deserialize_present_option change itself looks right: structured_content: Option<Value> keeps its old Some(Value::Null) behavior since Value accepts null, and the schema snapshots now correctly show the three CallToolRequestParams fields as non-nullable.

A few things I noticed:

  1. The pre-init cancellation fix looks test-only in this diff. The body says the pre-init loop in serve_server_with_ct_inner was updated to ignore CancelledNotification, but the server.rs diff only adds validate_peer_request. The arm that drops all pre-init notifications (logging "dropping a client notification received before the first request") is already on base. So part 2 here is the regression test, not a behavior change. Is that intended, or did a loop change get lost in the rebase onto main? Either way the new test is a useful lock-in for the behavior.

  2. The capability check described in the body is not in the code. The body says the -32602 applies when the method is tools/call and tools capability is enabled, but RoleServer::validate_peer_request does not check the capability, and it runs in the shared serve loop before handle_request. So on a server without tools enabled, a malformed tools/call now gets -32602 while a well-formed one would presumably still get -32601 from the handler. Is that split intended, or should the guard check the capability first?

  3. The -32602 carries no detail about what was wrong. By the time the request has fallen through to CustomRequest, the serde error is gone, so a client sending "arguments": null gets "invalid parameters for tools/call" with no hint which field failed. Would it be worth re-running the CallToolRequestParams deserialization inside validate_peer_request and putting the serde error in the error data? That would make the new error code much more actionable for client authors.

  4. Small test gap: the wire-level tests in test_tool_macros.rs only exercise "arguments": null; inputResponses: null and requestState: null are covered only by the serde unit test in serde_impl.rs. Extending one of the three paths (handler, Router, direct service) to the other two fields would close the loop.

  5. The client_json_rpc_message_schema_current.json snapshot also gains "additionalProperties": true on ClientCapabilities, which does not look related to the tools/call change. Is that intended, or regenerated snapshot drift?

@aloneangel45

Copy link
Copy Markdown
Author

Thanks for the detailed review @SIDDARTHAREDDY8 and @jokemanfire! Pushed 93412b6 and aligned the PR description:

  1. Pre-init cancellation test: Confirmed intentional - serve_server_with_ct_inner on main already drops pre-init notifications, so test_server_initialization.rs locks in that behavior with a wire-level regression test.
  2. RoleServer::validate_peer_request scope: Kept the guard unconditional in RoleServer::validate_peer_request (without gating on capabilities.tools) so malformed tools/call payloads return -32602 uniformly across ServerHandler, Router, and direct Service<RoleServer> implementations before handler dispatch, while well-formed tools/call requests on handlers without tools continue through handle_request. (Updated the PR body to remove the stale capabilities.tools wording.)
  3. Actionable -32602 detail: validate_peer_request now re-runs serde_json::from_value::<CallToolRequestParams> on request.params (or notes missing params when None) and attaches { "detail": "<message>" } in ErrorData.data.
  4. Wire-level coverage for inputResponses: null and requestState: null: Extended assert_null_arguments_rejected in crates/rmcp/tests/test_tool_macros.rs (which runs against ElidedToolHandlerServer, Router, and DirectService) to verify all three fields (arguments, inputResponses, requestState) return -32602 with non-empty data.detail.
  5. client_json_rpc_message_schema_current.json snapshot: ClientCapabilities on main already emits additionalProperties: true in client_json_rpc_message_schema.json; _current.json was simply stale on base and synced when re-running UPDATE_SCHEMA=1.

Verified locally:

  • cargo fmt -p rmcp -- --check
  • cargo clippy -p rmcp --lib --test test_tool_macros --test test_server_initialization --test test_deserialization --test test_message_schema --features "client,server,macros,schemars" --no-deps -- -D warnings -A clippy::result_large_err -A clippy::needless_bool
  • cargo test -q -p rmcp --lib --features "client,server,macros,schemars" (354 passed, 0 failed)
  • cargo test -q -p rmcp --test test_tool_macros --test test_server_initialization --test test_deserialization --test test_message_schema --features "client,server,macros,schemars" (25 / 23 / 20 / 3 passed, 0 failed)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

T-config Configuration file changes T-core Core library changes T-model Model/data structure changes T-service Service layer changes T-test Testing related changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

rmcp 3.12.0: explicit arguments: null accepted as omission; notifications/cancelled before initialization ends the server

3 participants