Repository navigation
imcp2-deploy 6/6: serve the deploy tools on the hosted server, with the bundle uploaded on a ticket - #243
imcp2-deploy 6/6: serve the deploy tools on the hosted server, with the bundle uploaded on a ticket#243raymondk wants to merge 2 commits into
Conversation
aterga
left a comment
There was a problem hiding this comment.
How could we mitigate a DoS attack from a malicious MCP client exhausting all the available deploy slots?
| } | ||
|
|
||
| /// `dir`, created if missing, and on Unix readable by its owner alone. | ||
| fn make_private_dir(dir: &Path) -> std::io::Result<()> { |
There was a problem hiding this comment.
@blind-oracle could you check if this works with the IC gateways, please?
There was a problem hiding this comment.
Maybe a dumb question, but what's the point of having a skill here?
Shouldn't the MCP tools be self-documenting?
Who would consume this file?
aterga
left a comment
There was a problem hiding this comment.
Note to self: Check if the curl approach is reasonable.
| tools act as. It needs an \"Actions & questions\" session, {concurrency}, lasts as \ | ||
| long as the deploy (send a progressToken to see each phase as it completes; \ | ||
| cancelling the call interrupts the deploy at its next step), and returns the \ | ||
| canister-id mapping to pass back next time. {bundle} The `skill://{DEPLOY_SKILL_NAME}` \ |
There was a problem hiding this comment.
Can we abstract away and call this, e.g., "app development metadata"?
I'd rather the agent not look into the mapping too closely, but just dump it into a file and use it as an opaque blob. This would avoid hallucinations, and I don't think the agent actually needs to look into that metadata.
| cancelling the call interrupts the deploy at its next step), and returns the \ | ||
| canister-id mapping to pass back next time. {bundle} The `skill://{DEPLOY_SKILL_NAME}` \ | ||
| resource walks through the loop: bundle, deploy, write the mapping back into the \ | ||
| project; `icp_deploy_guide` returns the same text." |
There was a problem hiding this comment.
Please justify why we need to duplicate the deployment guide and consider avoiding the redundancy.
… or the slot count From the review of #243. The instructions no longer call the deploy tool an exception: where core's closing paragraph says nothing here deploys (now the exported DEPLOYS_ELSEWHERE), a server with the deploy tools puts the paragraph on how deploying works. That paragraph is about a third of its length. What an agent reads (the instructions, the description of icp_cycles_balance, the skill) no longer names https://cli.id.ai or the icp CLI's identity commands: the principal is the developer principal of the user's identity, where cycles are sent and what is added as a controller. How many deploys a server runs at once is no longer in the instructions. A server that is full says to try again in a few minutes. The canister ids are passed in and written back unchanged, as the app's development metadata: the skill no longer shows the file's shape or asks for a merge, since what the tool returns holds every id passed in. The instructions point at icp_deploy_guide alone, not at it and the skill resource. Co-Authored-By: Claude Fable 5.2 <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical issues allow cross-session upload access, unbounded upload storage growth, and deletion of pre-existing state during tests.
9 open issues
Reject caller-supplied bundle paths on hosted requests · New Limit test cleanup to its unique temporary directory · New Bound retained upload storage per session and globally · New Recover or clean up pending uploads after restart · New Clean up partial uploads when receive is cancelled · New Allow long-running deploys to drain during shutdown · New Share the deploy concurrency limit across hosted instances · New Forward hosted cancellation notifications to active deploys · New Return server errors for upload storage failures · New
What changed in this PR
Adds optional hosted deployment support to imcp2, reusing the local server’s deploy tools with ticket-based bundle uploads and streamed progress responses.
Changes:
- Extracts shared deploy-handler composition for local and hosted servers.
- Adds upload tickets, deploy concurrency controls, SSE responses, and disconnect cancellation.
- Enables hosted deploys in native builds and adds tests, CI coverage, and documentation.
| File | Description |
|---|---|
src/main.rs |
Reads deploy configuration and enables it on hosted instances. |
src/lib.rs |
Adds optional deploy composition and upload-route integration. |
src/deploy.rs |
Implements uploads, JSON/SSE dispatch, and disconnect detection. |
src/auth.rs |
Adds a test-only bearer-token helper. |
README.md |
Documents hosted deployment workflows and configuration. |
deploy/native/README.md |
Documents deployment storage, limits, and upload timeouts. |
deploy/native/build.sh |
Enables the deploy feature in native release builds. |
crates/imcp2-local/src/server.rs |
Reuses the shared deploy handler while retaining local login tools. |
crates/imcp2-local/README.md |
Updates composition and deployment logging documentation. |
crates/imcp2-deploy/static/skills/deploy-with-mcp.md |
Explains uploads, concurrency, and hosted recovery. |
crates/imcp2-deploy/src/uploads.rs |
Implements ticket and upload lifecycles with per-file limits. |
crates/imcp2-deploy/src/server.rs |
Adds shared tool, resource, and instruction composition. |
crates/imcp2-deploy/src/lib.rs |
Adds upload inputs, ticket issuance, concurrency accounting, and cancellation links. |
crates/imcp2-deploy/src/deploy.rs |
Handles upload-source validation and adds deployment tracing. |
crates/imcp2-deploy/Cargo.toml |
Adds upload and logging-test dependencies. |
Cargo.toml |
Declares the hosted deploy feature and dependencies. |
Cargo.lock |
Updates dependency records. |
.github/workflows/ci.yml |
Adds tests with the hosted deploy feature enabled. |
Review effort: Max
| state.uploads.insert( | ||
| upload_id.clone(), | ||
| Upload { session: session.clone(), path, expires: Instant::now() + UPLOAD_TTL }, | ||
| ); |
| .and_then(|()| dir.canonicalize()) | ||
| .or_else(|_| std::path::absolute(&dir)) | ||
| .unwrap_or(dir); | ||
| Self { inner: Arc::new(Inner { dir, max_bytes, state: Mutex::default() }) } |
| make_private_dir(&self.inner.dir).map_err(|e| ReceiveError::Io(e.to_string()))?; | ||
| let upload_id = random_token(); | ||
| let path = self.inner.dir.join(format!("{upload_id}.tar.gz")); | ||
| let received = write_up_to(&path, &mut body, max).await; |
| COPY src ./src | ||
| COPY crates ./crates | ||
| RUN cargo build --release | ||
| RUN cargo build --release --features deploy |
| let deploy = IcDeployTools::new(self.identities.clone(), auth::bearer_session_resolver()) | ||
| .concurrent(config.concurrent) |
| let deploy_call = parts.method == Method::POST && is_deploy_call(&bytes); | ||
| let mut request = Request::from_parts(parts, Body::from(bytes)); | ||
| if !deploy_call { | ||
| return mcp.json.handle(request).await.into_response(); |
453bb56 to
dba1ba2
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Outstanding uploads lack per-session and global quotas, and cancellation or restarts can leave permanent orphan files, putting the shared state disk at risk of exhaustion.
11 open issues
Limit plugin memory before enabling shared-server deployments · New Bound retained upload storage per session and globally Limit test cleanup to its unique temporary directory Seed an expired identity grant to keep the deploy test offline · New Share the deploy semaphore across server mounts · New Return server errors for upload storage failures Forward hosted cancellation notifications to active deploys Share the deploy concurrency limit across hosted instances Allow long-running deploys to drain during shutdown Clean up partial uploads when receive is cancelled Recover or clean up pending uploads after restart
1 resolved since last review
Review effort: Max
| COPY src ./src | ||
| COPY crates ./crates | ||
| RUN cargo build --release | ||
| RUN cargo build --release --features deploy |
There was a problem hiding this comment.
Addressed in #253, stacked on this: a hosted server now runs only the sync plugins it knows, by the SHA-256 of the module, checked on the upload and again at deploy preflight before anything is created. A bundle carrying any other plugin is refused. The runtime still has no memory limiter (that belongs upstream in icp-sync-plugin), but an unknown plugin is no longer run at all. Leaving this open until #253 merges.
| #[tokio::test(flavor = "multi_thread")] | ||
| async fn the_hosted_endpoint_serves_the_deploy_loop() { | ||
| let (_dir, server) = server(); | ||
| let bearer = format!("Bearer {}", server.store.test_bearer().await); |
| cimd_enabled: cimd_on, | ||
| }); | ||
| #[cfg(feature = "deploy")] | ||
| let beta = beta.with_deploy(deploy.clone()); |
dba1ba2 to
fd0db65
Compare
… on a ticket
Behind the `deploy` cargo feature, which the native build turns on, the
hosted `imcp2` mounts `WithDeploy` over the core surface. The agent cannot
hand this server a file, so the bundle arrives by upload: `icp_deploy_upload`
mints a ticket inside an authenticated call, and `PUT {mcp_path}/deploy/upload`
takes the archive on that ticket, outside the bearer gate and under the
upload cap.
The deploy call alone is answered as an event stream, so its phases reach
the client while it runs; a response body dropped by the client cancels the
deploy (`ClientGone`). Deploys run one per session and up to a configured
number across sessions. Uploads and working directories live under the
state directory, resolved to absolute paths when the server starts.
CI tests the feature in a run of its own.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical defects block crate publishing and can leave cancelled deploys running or exhaust shared server resources.
19 open issues
Optional path dependency still blocks publishing imcp2 · New Expired upload archives persist across restarts and idle periods · New Disconnected deploys can accumulate extracted working directories · New Uploads lack quotas, allowing shared disk exhaustion · New Limit plugin memory before enabling shared-server deployments Bound retained upload storage per session and globally Limit test cleanup to its unique temporary directory Service shutdown can kill deploys before they drain · New Disconnect during preflight does not stop deploy work · New Empty state directory setting causes startup panic · New Zero concurrency setting still allows a deploy · New Share the deploy semaphore across server mounts Seed an expired identity grant to keep the deploy test offline Return server errors for upload storage failures Forward hosted cancellation notifications to active deploys Share the deploy concurrency limit across hosted instances Allow long-running deploys to drain during shutdown Clean up partial uploads when receive is cancelled Recover or clean up pending uploads after restart
Review effort: Max
| # feature. imcp2-deploy is not published, so the published `imcp2` cannot | ||
| # carry the feature until it is; a release build with the feature is a | ||
| # deployment's choice. | ||
| imcp2-deploy = { path = "crates/imcp2-deploy", optional = true } |
| transport: StreamableHttpServerConfig, | ||
| ) -> (Router, Router) { | ||
| let deploys_dir = self.state_dir().join("deploys"); | ||
| let uploads = Uploads::new(deploys_dir.join("uploads"), config.max_upload_bytes); |
| let gone = CancellationToken::new(); | ||
| request.extensions_mut().insert(ClientGone(gone.clone())); | ||
| let response = mcp.sse.handle(request).await; | ||
| cancel_on_drop(response.into_response(), gone) |
| let reader = tokio_util::io::StreamReader::new( | ||
| request.into_body().into_data_stream().map_err(std::io::Error::other), | ||
| ); | ||
| match mcp.uploads.receive(&ticket, declared, reader).await { |
| COPY src ./src | ||
| COPY crates ./crates | ||
| RUN cargo build --release | ||
| RUN cargo build --release --features deploy |
| return mcp.json.handle(request).await.into_response(); | ||
| } | ||
| let gone = CancellationToken::new(); | ||
| request.extensions_mut().insert(ClientGone(gone.clone())); |
fd0db65 to
37bda8f
Compare
There was a problem hiding this comment.
🟡 Changes recommended
The optional path-only dependency blocks publishing even with deploy disabled, while unbounded upload storage and plugin memory expose the shared server to resource exhaustion.
21 open issues
Interrupted deploys can exhaust shared disk storage · New Uploads lack aggregate storage quotas · New Uploads lack quotas, allowing shared disk exhaustion Disconnected deploys can accumulate extracted working directories Expired upload archives persist across restarts and idle periods Optional path dependency still blocks publishing imcp2 Limit plugin memory before enabling shared-server deployments Bound retained upload storage per session and globally Limit test cleanup to its unique temporary directory Zero concurrency setting still allows a deploy Empty state directory setting causes startup panic Disconnect during preflight does not stop deploy work Service shutdown can kill deploys before they drain Share the deploy semaphore across server mounts Seed an expired identity grant to keep the deploy test offline Return server errors for upload storage failures Forward hosted cancellation notifications to active deploys Share the deploy concurrency limit across hosted instances Allow long-running deploys to drain during shutdown Clean up partial uploads when receive is cancelled
And 1 more that still need to be addressed.
Review effort: Max
| let gone = CancellationToken::new(); | ||
| request.extensions_mut().insert(ClientGone(gone.clone())); | ||
| let response = mcp.sse.handle(request).await; | ||
| cancel_on_drop(response.into_response(), gone) |
| let reader = tokio_util::io::StreamReader::new( | ||
| request.into_body().into_data_stream().map_err(std::io::Error::other), | ||
| ); | ||
| match mcp.uploads.receive(&ticket, declared, reader).await { |
…e failure's status, and a test's cleanup - An empty IMCP2_STATE_DIR reads as unset again, instead of panicking at startup where the path is resolved. - MCP_DEPLOY_MAX_CONCURRENT=0 refuses to start, rather than being served as a cap of one. - An upload the server could not store answers 500, not 400: ReceiveError tells a body that failed to arrive from a file that could not be written. - The relative-deploy-directory test works in a directory of its own and no longer removes a `state` directory it did not make. Co-Authored-By: Claude Fable 5.2 <[email protected]> Claude-Session: https://claude.ai/code/session_01XSXgo38kH12wagL3rstXfV
There was a problem hiding this comment.
🔵 Needs a closer look
The new path-only dependency blocks publishing imcp2, and missing aggregate upload quotas allow one authenticated session to exhaust the shared state filesystem.
17 open issues
Uploads lack aggregate storage quotas Interrupted deploys can exhaust shared disk storage Uploads lack quotas, allowing shared disk exhaustion Disconnected deploys can accumulate extracted working directories Expired upload archives persist across restarts and idle periods Optional path dependency still blocks publishing imcp2 Limit plugin memory before enabling shared-server deployments Bound retained upload storage per session and globally Disconnect during preflight does not stop deploy work Service shutdown can kill deploys before they drain Share the deploy semaphore across server mounts Seed an expired identity grant to keep the deploy test offline Forward hosted cancellation notifications to active deploys Share the deploy concurrency limit across hosted instances Allow long-running deploys to drain during shutdown Clean up partial uploads when receive is cancelled Recover or clean up pending uploads after restart
4 resolved since last review
Review effort: Max


Summary
The hosted composition: the deploy tools on the MCP endpoint of the
imcp2binary, behind adeploycargo feature that the native build turns on. Everything incrates/imcp2-deployis already in place below this PR; this one is the root crate.src/deploy.rs, under#[cfg(feature = "deploy")], withMcpServer::with_deploy(DeployConfig). The binary readsMCP_DEPLOY_MAX_CONCURRENT(default 2) andMCP_DEPLOY_MAX_UPLOAD_BYTES(default 64 MiB).How the bundle arrives
icp_deploy_uploadmints a ticket inside the authenticated call and returns the upload URL, the ticket and thecurlline to run.PUT {mcp_path}/deploy/uploadsits outside the bearer gate (the ticket is its authentication), streams the body to disk under the cap, refuses a declared length over it unread, and answers201with the upload id.icp_deploy_bundletakesbundle_upload; the archive is removed with the deploy. This server lists nobundle_pathand refuses one.The ticket's properties are #247.
How the deploy call is answered
The endpoint answers a POST with plain JSON, the one message the handler returns; in rmcp's JSON mode a notification emitted before the result would be returned as the result. So the dispatch reads the JSON-RPC method and tool name off the buffered body and hands a
tools/calloficp_deploy_bundleto a secondStreamableHttpServiceconfigured for SSE responses, still stateless. Everything else keeps the JSON service, so existing clients see no change.A client that goes away
The SSE response body is wrapped (
cancel_on_drop) so that its drop, which is what a disconnect does on the server, cancels a token placed in the request's extensions asClientGone. The deploy stops at its next step and keeps its directory as the record.Where things live
Uploads and working directories are under
{state_dir}/deploys, resolved to absolute paths when the server starts.What changed in this PR at the re-cut
uploads.rsmoved to imcp2-deploy 4/6: receive a bundle by upload ticket #247;WithDeploy, the slots and the upload tool moved to imcp2-deploy 5/6: the MCP tools, served from the local server #232; the server log moved to imcp2-deploy 3/6: deploy a bundle through icp-project, the pipeline, its events and its interruption #231.bundle_pathis not reachable here (Take the bundle one way per server: a path locally, an upload on the hosted one #245's fix), from the first commit that mounts the tools.Review so far
aterga's comments on this PR about the instructions, the skill and the slot count are answered in #232, where that text now lives; the ones about the ticket are carried to #247. Still open here:
Caveats
imcp2-deployis not published, so the publishedimcp2cannot carry thedeployfeature until it is.MemoryMax.read_body 30sapplies to the uploadPUT; the native README says what that means for the cap.AuthStore::test_beareris the samecfg(test)helper Cap the MCP request body behind the bearer gate #241 adds, with an identical hunk.Changes
src/deploy.rs(221 lines of code, 241 of tests),src/lib.rs,src/main.rs,src/auth.rs.Cargo.toml: thedeployfeature and its dependencies..github/workflows/ci.yml: a test run with the feature.deploy/native/build.shbuilds with it.README.md,deploy/native/README.md.Testing
cargo build --locked --workspace --all-targetscargo test --locked --workspace --all-targetscargo test --locked -p imcp2 --features deploy --all-targetscargo clippy --locked --workspace --all-targets --features deploy(clean)cargo fmt --all -- --checksrc/deploy.rstests the whole loop over the composed router with a minted test token:tools/liststays JSON and lists the deploy tools withbundle_uploadalone;icp_deploy_uploadreturns a ticket; thePUTis refused without a ticket (401), on a wrong one (403), over the cap (413), accepted once (201) and spent; abundle_pathis refused without spending the upload; the deploy call is answered astext/event-streamcarrying the result; an unauthenticated deploy call still gets the 401. Pluscancel_on_dropfiring on body drop, and the dispatch predicate.The stack
Six stacked PRs that bring
icp deployto the MCP servers through the icp CLI's own project library. Re-cut on 2026-11-18 so that each file arrives once, in the form it has at the top; the tree at the top is unchanged from before the re-cut, rebased onto currentmain.icp-projecthost for an untrusted bundleic-agent, an identity that refreshes#242 (streamed phases, interruption) and #245 (one bundle source per server, crates.io) are closed: their changes are folded into the PRs above.
Checklist
🤖 Generated with Claude Code