Skip to content

Cap the MCP request body behind the bearer gate - #241

Merged
aterga merged 8 commits into
mainfrom
mcp-body-limit
Nov 19, 2026
Merged

aterga merged 8 commits into
mainfrom
mcp-body-limit

Conversation

@raymondk

@raymondk raymondk commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

What

The hosted /mcp route gets a cap on the request body, enforced behind the bearer gate.

Why

rmcp's streamable-HTTP service collects each request body whole before parsing it as JSON-RPC (expect_json in server_side_http.rs), and because it is a tower service rather than an axum extractor, axum's default 2 MiB extractor limit never applies to it. There was no body-limit layer on the route and Caddy sets only a read timeout, so any bearer-token holder could make the process buffer a body of arbitrary size. The staging unit runs under MemoryMax=2G.

This is independent of the deploy stack (#230–#232), but the hosted deploy work that follows will need a deploy-aware exemption from a general cap, so the general cap comes first and on its own.

How

  • src/body_limit.rs: a middleware that refuses a body over the cap with 413. A declared Content-Length over the cap is refused without reading the body; an undeclared (chunked) body is read up to the cap and no further (axum::body::to_bytes with the limit, telling LengthLimitError from a transport error). A body within the cap is handed on whole, which the transport buffers anyway.
  • Layer order on the MCP fallback: CORS, then require_token, then the cap. An unauthenticated request is still answered on its headers alone with the 401 challenge, so only an authenticated caller's body is read at all.
  • Default DEFAULT_MAX_REQUEST_BODY = 4 MiB. The cap is a budget for the serialized request, independent of the IC's 2 MiB ingress limit (which bounds the encoded call) and of the tools' 1 MiB-per-field text limits (which count the text after JSON decoding). 4 MiB is headroom, not a guarantee that every request the tools would accept fits: two fields at the tools' limit with little to escape are about 2 MiB as JSON, but JSON escaping can double that text or more, so a heavily escaped request can exceed the cap and is refused with 413. Embedders override with McpServer::with_max_request_body(bytes) (a setter, so McpConfig keeps its shape for the published crate's embedders); the binary reads $MCP_MAX_REQUEST_BODY, reads a blank value as unset, and refuses to start on any other value that is not a byte count.
  • Tests: the middleware alone (under, at, over the cap; declared vs undeclared length; the body is not drained past the cap; a body that fails mid-read is answered 400, not 413), the composed router (authenticated oversized → 413, unauthenticated oversized → 401, authenticated JSON-RPC within the cap is answered by the transport), and the binary's reading of the variable (unset, blank, a byte count, not a byte count, not Unicode). AuthStore::test_bearer is a cfg(test) helper that mints a token without an II handshake.
  • http-body-util moves from dev-dependencies to dependencies for LengthLimitError; futures-util is added as a dev-dependency for streamed test bodies. Both were already in the tree.

Generated by Claude Code

The streamable-HTTP transport reads each request body whole into memory
before parsing it as JSON-RPC, and axum's default extractor limit never
reaches it (the transport is a tower service, not an extractor), so the
hosted /mcp route had no bound on what one request could make the
process buffer. Caddy in front sets a read timeout but no size cap.

A middleware layer inside the bearer gate now refuses a body over the
cap with 413: a declared Content-Length over it is refused unread, and
an undeclared (chunked) body is read up to the cap and no further. The
gate still answers an unauthenticated request on its headers alone, so
only an authenticated caller's body is read at all. Default 4 MiB (an
IC ingress message is at most 2 MiB, so any one canister call fits even
spelled out as JSON); embedders set it with
McpServer::with_max_request_body, the binary from $MCP_MAX_REQUEST_BODY.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

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

🟡 Changes recommended

The environment-variable handling silently defaults on invalid Unicode instead of reporting a configuration error, violating the documented fail-fast behavior.

2 open issues
What changed in this PR

Adds a configurable request-body cap to the hosted MCP endpoint, limiting authenticated requests while preserving header-only rejection of unauthenticated callers.

Changes:

  • Reject oversized declared-length and streamed bodies with 413, behind the bearer gate.
  • Default to 4 MiB, with embedder and MCP_MAX_REQUEST_BODY overrides.
  • Add middleware and router tests, update dependencies, and document the setting.
File Description
src/​main.rs Reads the body-cap setting and applies it to production and beta instances.
src/​lib.rs Adds the builder override, installs the middleware, and tests route behavior.
src/​body_limit.rs Implements bounded body collection, error responses, and focused tests.
src/​auth.rs Adds a test-only bearer-token helper for router tests.
README.md Documents the body-cap environment variable and default.
Cargo.toml Promotes http-body-util to runtime dependencies and adds streamed-test support.
Cargo.lock Records the new direct test dependency on futures-util.

Review effort: Max

Comment thread src/main.rs Resolved
Comment thread src/lib.rs Resolved
`max_request_body` took any error from `std::env::var` to mean the variable
was unset. `std::env::var` also fails with `VarError::NotUnicode` when the
variable is set to bytes that are not UTF-8, which Unix allows, so such a
value started the server on the default cap instead of refusing to start, the
one thing the function's doc says a value that is not a byte count must do.

Only `NotPresent` means the default now, and `NotUnicode` is a configuration
error like any other value that is not a byte count. The reading moves to
`max_request_body_from`, which takes the result of the lookup, so a test can
cover it without writing the process environment; the error also quotes the
value it refused.

The binary's module docs list the variable next to the others it honours.
The router test's last case sent an authenticated JSON-RPC `ping` within the
cap and asserted only that the status was neither 413 nor 401. It sent no
`Host` header, so the transport turned it away with a 400 before reading the
body, and the two assertions held anyway: the case would have passed with a
cap that dropped or cut the body it is meant to hand on.

The request now carries a `Host` the transport allows, and the test asserts
the 200 and the JSON-RPC reply. The reply's `id` exists only in the request
body, so it can only come back if the body reached the transport whole.
@aterga
aterga marked this pull request as ready for review November 19, 2026 14:31
@aterga
aterga requested review from a team and a max review from Copilot November 19, 2026 14:31
A variable set to nothing (`MCP_MAX_REQUEST_BODY=`) was parsed as a byte
count, failed, and stopped the server from starting. The native deploy renders
a variable nobody set as `NAME=`, and every variable templated into
`deploy/native/imcp2.service` reads that as unset, so templating this one the
same way would have stopped the service on any environment that does not set
it.

Blank, after trimming, now means the default, as unset does. Any other value
that is not a byte count is still a configuration error that refuses to start.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTGzTcUirKpHj7zVXG6

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

🟡 Changes recommended

The body-limit documentation needs to distinguish the independent HTTP request-size cap from the IC encoded-call limit and direct callers to the override.

1 open issue
2 resolved since last review

Review effort: Max

Comment thread src/body_limit.rs Resolved
sea-snake
sea-snake previously approved these changes Nov 19, 2026
…read

The default's doc justified 4 MiB by the IC's 2 MiB ingress limit. That limit
bounds the encoded call, while the HTTP body is JSON carrying the argument as
textual Candid, possibly a caller-supplied interface beside it, and JSON's
escaping of both, so the one does not bound the other.

The doc now says the cap is a separate limit on the serialized request, and
gives the reason the default holds: the tools take at most 1 MiB of text per
field, and a request with the argument and an interface both at that size is 2
to 3 MiB as JSON, so nothing the tools would act on is turned away at the cap
first. It also points to the override.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTGzTcUirKpHj7zVXG6
Copilot AI max review requested due to automatic review settings November 19, 2026 14:47

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

🟡 Changes recommended

The default-limit documentation and PR rationale need correction because JSON escaping and envelope overhead can push otherwise tool-valid requests beyond 4 MiB.

1 open issue
1 resolved since last review

Review effort: Max

Comment thread src/body_limit.rs Resolved
The previous wording said that no request the tools would accept is turned
away at the cap first. That overstated it: the tools' 1 MiB-per-field limits
count text after JSON decoding, while the cap counts the body on the wire,
where JSON's escaping can double that text or more and the JSON-RPC envelope
comes on top. Two fields at the tools' limit made of characters JSON must
escape come to just over 4 MiB, even in plain ASCII.

The doc now calls the cap a budget for the serialized request, independent of
both the ingress limit and the tools' limits, says what 4 MiB leaves room for
(two fields at the tools' limit with little to escape are about 2 MiB), and
says that a heavily escaped request can still be refused with 413.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTGzTcUirKpHj7zVXG6
Copilot AI max review requested due to automatic review settings November 19, 2026 15:04

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

🔵 Needs a closer look

Human review is needed to assess whether missing coverage for the BAD_REQUEST response to mid-stream body-read failures should affect approval.

No open issues 🎉

1 resolved since last review

Review effort: Max

The cap tells a body over the limit (`LengthLimitError`, answered 413) from a
body that could not be read (answered 400), and only the first had a test. A
stream that breaks well inside the cap must not be reported as too large,
which would send the client off to shrink a request that was never oversized.

The new test feeds the middleware a stream that yields a chunk and then an
I/O error, and asserts the 400 and its message.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTGzTcUirKpHj7zVXG6
Copilot AI max review requested due to automatic review settings November 19, 2026 15:20

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

🟢 Approval recommended

No active review issues are recorded that would block approval.

No open issues 🎉

Review effort: Max

@aterga
aterga requested a review from sea-snake November 19, 2026 15:33
@aterga
aterga merged commit 4f78438 into main Nov 19, 2026
17 checks passed
aterga pushed a commit that referenced this pull request Nov 19, 2026
Conflicts with #241 (the MCP request-body cap) resolved by keeping both
sides: McpServer has both `deploy` and `max_request_body`, the body cap is
layered inside the bearer gate on the deploy-aware MCP router (the bundle
upload stays a route of its own, outside both, with its own limits), and the
binary reads $MCP_MAX_REQUEST_BODY next to the deploy settings. futures-util
is a normal dependency (the deploy endpoint streams bodies), so it is no
longer listed again under dev-dependencies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTFUYW9ZKb1Rjv176Za
@raymondk raymondk mentioned this pull request Nov 19, 2026
6 of 8 tasks
aterga pushed a commit that referenced this pull request Nov 19, 2026
* Bump crates to 0.7.0

All three crates share one version. A minor bump: since 0.6.1 the server
gained the deploy tools (bundle host, upload store, pipeline, MCP tools,
remote serving and metrics, #261, #265, #266), the cap on the MCP request
body behind the bearer gate (#241), vetted-connector branding surfaced to
Internet Identity (#200), and get_canister_candid now carries the interface
text in its structured output (#229).

The rc-0.7.0 candidate needs this on main first: deploy-candidate.yml and
publish-crate.yml both refuse a tag whose version disagrees with every
Cargo.toml.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTGJNrpdaVxN1aY8XSX

* Deploy tools: say per server how to hand icp_deploy the bundle again

#266 rewrote the icp_deploy description and hard-coded its step (2) as
"upload that bundle via icp_deploy_upload". The local server does not list
that tool: it takes the bundle as `bundle_path`. The sentence that
IcDeployTools::tools() put in per server was anchored on text the rewrite
removed, so it silently stopped being put in, and
a_server_lists_the_bundle_argument_it_takes has failed on main since.

Step (2) is now the anchor. The description says "hand that bundle to this
tool", and each server replaces that with its own way in: upload via
`icp_deploy_upload` on a server with an upload store, the bundle's absolute
path as `bundle_path` on one without. The hosted server's text is what #266
wrote, with the tool name in backticks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTGJNrpdaVxN1aY8XSX

* README: depend on imcp2 0.7

`imcp2 = "0.6"` matches 0.6.x only, and the README ships in the crate, so a
reader of 0.7.0's page would be told to depend on the release before it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTGJNrpdaVxN1aY8XSX

* Deploy tools: keep the description's step (2) as written

Review asked for the description's text back. The tool's description in
the source says step (2) as #266 wrote it, "upload that bundle via
icp_deploy_upload", and the hosted server lists it unchanged. Only a
server without an upload store, imcp2-local, puts "pass that bundle's
absolute path as `bundle_path`" in its place, since it lists no
icp_deploy_upload.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VP2vTGJNrpdaVxN1aY8XSX

---------

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants