Skip to content

fix(transport): fail pending requests promptly on oversized responses - #1552

Open
matinsanei wants to merge 4 commits into
modelcontextprotocol:mainfrom
matinsanei:fix/oversized-response-client-error
Open

matinsanei wants to merge 4 commits into
modelcontextprotocol:mainfrom
matinsanei:fix/oversized-response-client-error

Conversation

@matinsanei

Copy link
Copy Markdown

Summary

Addresses the client/caller hang in #1513 (complementary to #1522, which exposes max_line_length on TokioChildProcessBuilder).

Previously, AsyncRwTransport::read_line discarded oversized lines and only recovered a request id when method was present (and rejected any prefix containing result or error). As a result, when a server sent a response exceeding max_line_length, AsyncRwTransport::receive dropped it silently and the pending request stayed in the responder pool until the caller's timeout.

Changes

  • crates/rmcp/src/transport/async_rw.rs:
    • Extended the bounded oversized-line prefix parser (oversized_message_from_prefix) to distinguish OversizedMessage::Request(id) from OversizedMessage::Response(id) while still rejecting malformed JSON, duplicate fields, and messages mixing method with result/error.
    • In AsyncRwTransport::receive, when an oversized response with a recoverable id is encountered, return a local RxJsonRpcMessage::error (-32600, mentioning max_line_length) for that id without writing anything back to the peer. The pending caller fails promptly with ServiceError::McpError, and the transport stays open for subsequent messages.
  • crates/rmcp/tests/test_async_rw_max_line_length.rs:
    • Updated the oversized-response test to verify that a local error is surfaced for both result and error oversized responses while nothing is written back to the peer.
    • Added oversized_response_fails_pending_client_call_promptly_and_recovers to verify end-to-end with RoleClient that an oversized tools/call response fails promptly without hanging and a subsequent call on the same session succeeds.

Verification

  • cargo fmt / cargo clippy -p rmcp --all-targets --all-features -- -D warnings
  • cargo test -p rmcp --lib --all-features (952 passed)
  • cargo test -p rmcp --all-features --test test_async_rw_max_line_length (18 passed)

@matinsanei
matinsanei requested a review from a team as a code owner December 2, 2026 19:30
Copilot AI balanced review requested due to automatic review settings December 2, 2026 19:30

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@github-actions github-actions Bot added T-test Testing related changes T-core Core library changes T-transport Transport layer changes labels Dec 2, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 2, 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-03T06:38:06.756899Z 2038ed8 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 2, 2026 19:31
@github-actions

github-actions Bot commented Dec 2, 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: 5a66bad454

ℹ️ 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".

}

if fields.has_method { fields.id } else { None }
let id = fields.id?;

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 Recover response IDs when the payload precedes them

When an oversized response puts a large result or error before id—a legal JSON-RPC key order—the retained 8 KiB prefix can end inside the payload before reaching the ID. This returns None, so receive discards the response and the matching request remains pending until its timeout. Recover the ID without depending on it appearing in the initial prefix.

Useful? React with 👍 / 👎.

Comment thread crates/rmcp/src/transport/async_rw.rs Outdated
continue;
}
LineRead::Oversized(Some(OversizedMessage::Response(id))) => {
let error = ErrorData::invalid_request(

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 reproduced this on 5a66bad with an Auto client and a valid server/discover reply whose ID comes before the payload. When the reply exceeds the local line limit, the generated -32600 makes the client send legacy initialize. If the peer closes, startup reports "discover and legacy initialize both failed," which hides the actionable size-limit error.

Could we carry the request ID and line limit through as a distinct local receive error? That would let us fail the matching call promptly, surface the size limit during startup, and preserve legacy fallback for a genuine -32600 from the peer.

@github-actions github-actions Bot added the T-service Service layer changes label Dec 2, 2026
@matinsanei

matinsanei commented Dec 2, 2026 •

Copy link
Copy Markdown
Author

Good catch @jonxsong, thanks. I added a per-process marker for oversized responses so Auto startup surfaces the size limit instead of falling back to legacy initialize, while keeping normal -32600 fallback intact. I also added a small tail scanner to recover response IDs when result or error comes before id, along with tests for both.

@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: c0a609dd56

ℹ️ 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".

self.push_id_byte(b);
} else if self.phase == ScannerPhase::Key && self.depth == 1 {
if self.escape || b == b'\\' {
self.key_overflow = true;

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 Decode escaped keys in the late-response scanner

For an oversized response whose large result or error precedes a valid escaped top-level key such as "\u0069d": 123, this branch marks the key as overflowed, so finish_key never records the ID and finish() returns None; receive then drops the line and leaves the matching call pending until timeout. The new tail scanner added in this change only recognizes unescaped raw field names, so the late-ID fix still misses this valid JSON encoding.

Useful? React with 👍 / 👎.

@connor4312 connor4312 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.

Thanks. Failing the pending call promptly is the right fix for #1513, and I found no correctness problems: the error is only produced locally and never written to the peer, the marker can't be spoofed, scanner memory stays bounded, and the #1471 request path still works. My one request is about how this error reaches callers (inline). The escaped-key gap Codex raised is fine as a follow-up: it falls back to the current behaviour, a timeout.

Comment thread crates/rmcp/src/model.rs Outdated
Self::OVERSIZED_MESSAGE_MARKER.to_owned(),
Value::from(Self::oversized_message_token()),
);
Self::invalid_request(

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.

Please give this its own ServiceError instead of a -32600 McpError.

Today a caller gets ServiceError::McpError with code -32600 (Invalid Request). JSON-RPC defines that code as "the JSON sent is not a valid Request object", so it blames the caller's request when the real problem is a local limit on the response. From outside the crate:

  • is_oversized_message() is pub(crate), so the only way to recognise this error is to match on the message text.
  • error.data contains an unexplained random u64 under io.modelcontextprotocol/oversizedMessage.
  • Any user code that branches on -32600 will misread it. That's the same mistake discover_startup needed a special case for in this PR.

The transport-closed marker already has a pattern for this: service.rs:1851 turns error.is_transport_closed() into ServiceError::TransportClosed. Can we do the same here, e.g. ServiceError::ResponseTooLarge { max_line_length }? ServiceError is #[non_exhaustive], so adding a variant doesn't break anyone. discover_startup could then match on the variant instead of checking the marker. If a new variant is too much for this PR, please at least make the predicate public and use -32603, which is what transport_closed() uses.

Comment thread crates/rmcp/src/model.rs Outdated
Value::from(Self::oversized_message_token()),
);
Self::invalid_request(
format!("Incoming response exceeded the maximum line length ({max_line_length} bytes)"),

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.

Nit: most people who hit #1513 have a legitimately large tool result, so please tell them how to raise the limit, e.g. "…exceeded the maximum line length ({max_line_length} bytes); raise it with AsyncRwTransport::with_max_line_length". Once #1522 lands, the TokioChildProcessBuilder option belongs in the message too.

@matinsanei

matinsanei commented Dec 3, 2026 •

Copy link
Copy Markdown
Author

Thanks for the review @connor4312. I added ServiceError::ResponseTooLarge and ClientInitializeError::ResponseTooLarge, switched the local error to -32603 carrying maxLineLength with the marker, and updated the message to mention AsyncRwTransport::with_max_line_length. I also updated the tail scanner to handle escaped keys and validate the full response line before routing.

@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: a6506eaae4

ℹ️ 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/transport/async_rw.rs Outdated
self.oversized_line_prefix.clear();
request_id
let late_response_id = std::mem::take(&mut self.oversized_response_scanner).finish();
message.or_else(|| late_response_id.map(OversizedMessage::Response))

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 Honor tail validation before routing a prefix-recovered response

If an oversized response has an id and the start of a large result in the retained prefix, but a duplicate top-level id appears in the discarded tail, prefix parsing returns Response(id) while the full-line scanner marks the message invalid and returns None. This or_else still selects the prefix result, so receive emits an oversized-response error for the first ID and can consume the wrong pending request instead of ignoring the malformed response. Do not use a prefix candidate when the tail scanner has rejected the message.

Useful? React with 👍 / 👎.

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-core Core library changes T-service Service layer changes T-test Testing related changes T-transport Transport layer changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants