Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

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

Merged
connor4312 merged 5 commits into
modelcontextprotocol:mainfrom
matinsanei:fix/oversized-response-client-error
Dec 3, 2026
Merged

connor4312 merged 5 commits into
modelcontextprotocol:mainfrom
matinsanei:fix/oversized-response-client-error

Conversation

@matinsanei

Copy link
Copy Markdown
Contributor

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-03T23:04:47.327476Z 4072fc3 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
Contributor 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
Contributor 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 👍 / 👎.

@matinsanei
matinsanei requested a review from connor4312 December 3, 2026 12:54

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

Reviewed at 2038ed8a (CI had not reported yet: check-runs empty, commit status pending, so everything below is local).

Claims reproduced. cargo test -p rmcp --lib --all-features → 952 passed, exactly the number in the description. cargo test -p rmcp --all-features --test test_async_rw_max_line_length → 20 passed (the body still says 18; two tests landed after it was written, so just update the count).

The two follow-up findings have regression tests, not just fixes. oversized_response_with_late_id_after_payload_surfaces_local_error covers the whole result-before-id ordering, the escaped key "\u0069d":124, and — after the last commit — a duplicate id in the discarded tail, which must not produce a local error. That last one is the piece I expected to be missing, since the prefix parser cannot see it.

Nothing is written back on the response path. oversized_response_surfaces_local_error_without_writing_to_peer reads the peer side to EOF and asserts empty output, and the id-less/unmatched case is safe: service.rs:1839/1855 drop an error whose id is not in local_responder_pool, so an unsolicited oversized response cannot terminate the session.

The classification is conservative where it has to be. finish_oversized_line only trusts a prefix Request(id) when the prefix has method and no result/error, and defers to the full-line scanner otherwise; the scanner rejects duplicate top-level keys, treats nested keys as opaque by depth, and caps the retained id at 256 bytes. I could not construct a case where a valid response gets a wrong id.

Two notes, neither blocking:

  1. The error text says raise it with AsyncRwTransport::with_max_line_length. For the common stdio path (TokioChildProcess) that method does not exist — the builder option is #1522, still open. Once #1522 lands, the hint should mention TokioChildProcessBuilder too, otherwise the message tells most affected users to call something they cannot reach.
  2. ErrorData::oversized_message_limit is pub(crate), so it is only reachable through ServiceError/ClientInitializeError. That is the right public surface; I note it because a custom Transport that surfaces raw ErrorData would have to match on message text.

Given that the ServiceError::ResponseTooLarge variant, the ClientInitializeError mapping, and is_stale_fallback_eligible => false all match what was asked for, I have no further correctness concerns.

connor4312
connor4312 previously approved these changes Dec 3, 2026

@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, the rework addresses everything I raised. There's now a ServiceError::ResponseTooLarge { max_line_length } variant, and the Auto client no longer falls back to the legacy handshake on an oversized reply. The message says how to raise the limit, and escaped keys are decoded. The tail scanner stays bounded in memory and linear in time, and lines within the limit pay nothing extra. One follow-up: TokioChildProcess users can't call with_max_line_length until #1522 lands, so the message should mention the builder option once it does. LGTM.

The constructor is only called from AsyncRwTransport, so a client-only
build reported it as dead code and failed clippy with -D warnings.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

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

Re-approving after pushing 4072fc3. It gates ErrorData::oversized_message on transport-async-rw too, because a client-only build flagged it as dead code and failed the per-feature clippy step. Clippy now passes for every feature on its own and with all features.

@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: 4072fc36dd

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +568 to +571
_ => {
if self.current_field == ScannerField::Id {
self.push_id_byte(b);
}

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 discarded response values before routing IDs

When an oversized line has a valid id/response key but an invalid non-ID value—for example {"jsonrpc":"2.0","id":1,"result":xxxx...}—this branch ignores every x while current_field is Other; the later } moves the scanner to Closed, so finish() returns the ID and receive synthesizes ResponseTooLarge. Normal-sized malformed JSON is explicitly ignored, but this path removes the matching pending request and fails it, so a malformed oversized line is routed as a valid response; validate the complete streamed JSON value (including non-ID fields) before returning an ID.

Useful? React with 👍 / 👎.

@connor4312
connor4312 merged commit 3725772 into modelcontextprotocol:main Dec 3, 2026
23 checks passed
@matinsanei

Copy link
Copy Markdown
Contributor Author

Thanks so much for the review and guidance Connor Really appreciate :)

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.

5 participants