Agent Client Protocol Rust SDK
This repository contains the Rust SDK for the Agent-Client Protocol (ACP).
For Users
If you want to build something with these crates, see the rustdoc:
agent-client-protocol- Core SDK for building clients, agents, and proxiesagent-client-protocol-cookbook- Practical patterns and examplesagent-client-protocol-conductor- Running proxy chains
The agent-client-protocol crate includes a concepts module that explains how connections, sessions, callbacks, and message ordering work.
For Maintainers and Agents
This book documents the design and architecture for people working on the codebase itself.
Repository Structure
src/
├── agent-client-protocol/ # Core protocol SDK
├── agent-client-protocol-http/ # HTTP/SSE/WebSocket transport
├── agent-client-protocol-rmcp/ # Integration with rmcp crate
├── agent-client-protocol-cookbook/ # Usage patterns (rendered as rustdoc)
├── agent-client-protocol-derive/ # Proc macros
├── agent-client-protocol-conductor/ # Conductor binary and library
├── agent-client-protocol-polyfill/ # MCP-over-ACP transport compatibility
├── agent-client-protocol-test/ # Test utilities and fixtures
├── agent-client-protocol-trace-viewer/ # Trace visualization tool
└── yopo/ # "You Only Prompt Once" example client
Crate Relationships
graph TD
acp[agent-client-protocol<br/>Core SDK, stdio, process spawning]
http[agent-client-protocol-http<br/>HTTP/SSE/WebSocket transport]
rmcp[agent-client-protocol-rmcp<br/>rmcp integration]
conductor[agent-client-protocol-conductor<br/>Proxy orchestration]
polyfill[agent-client-protocol-polyfill<br/>MCP transport compatibility]
trace[agent-client-protocol-trace-viewer<br/>Trace visualization]
cookbook[agent-client-protocol-cookbook<br/>Usage patterns]
http --> acp
rmcp --> acp
conductor --> acp
conductor --> trace
polyfill --> acp
cookbook --> acp
cookbook --> rmcp
cookbook --> conductor
Key Design Documents
- Core Library Design - How the core crate and its transport and integration crates are organized
- Transport Architecture - The frame-aware boundary shared by transports and in-process components
- Conductor Design - How the conductor orchestrates proxy chains
- Protocol Reference - Wire protocol details and extension methods
- MCP Bridge - Adapting native MCP-over-ACP for HTTP-capable agents
- Original P/ACP Design Proposal - Historical design context; not the current wire reference
- Migrating to v2.0 - Upgrade guide from 1.x to 2.0
- Migrating to v0.11 - Upgrade guide from 0.10.x to 0.11
Core Library Design
This document describes the design of the agent-client-protocol crate and its companion transport and integration crates.
For API usage, see the rustdoc and cookbook.
Crate Organization
agent-client-protocol
The core SDK. Provides:
- Role types (
Client,Agent,Proxy,Conductor) - the identities in ACP - Versioned connection builders (
Client.v1(),Agent.v2(), …,connect_to(),connect_with()) - Per-version modules (
agent_client_protocol::v1, andagent_client_protocol::v2withunstable_protocol_v2) - the same names (ConnectionTo,Builder,Responder,SessionBuilder, …) for each protocol version - Message handling (
on_receive_request,on_receive_notification,on_receive_dispatch) - Protocol types (
agent_client_protocol::v1::schema, andagent_client_protocol::v2::schemawithunstable_protocol_v2) - each protocol version’s ACP message types, with the version-neutral items such asProtocolVersioninagent_client_protocol::schema - Transports and process launching (
Channel,Lines,ByteStreams,Stdio,AcpAgent) - MCP server attachment - runtime-agnostic interfaces for wiring MCP servers into ACP sessions through the opt-in
unstable_mcp_over_acptransport
Schema dispatch boundary
The agent-client-protocol-schema crate selects aggregate request, notification,
and response variants by method name. Its from_method_and_params and
from_method_and_result helpers deserialize only the selected payload type.
Do not deserialize an aggregate enum directly with its untagged Deserialize
implementation. Overlapping payload shapes can select the wrong variant.
The SDK’s JSON-RPC traits delegate aggregate parsing to those helpers. The SDK
still owns handler matching, envelopes, request-ID tracking, and error mapping.
During aggregate parsing, the SDK maps unknown methods to Method not found
(-32601) and malformed incoming params to Invalid params (-32602). Malformed
response results retain the SDK’s local parse-error handling. Payloads,
including null, are passed to the selected type’s deserializer unchanged.
Aggregate handlers can receive variants for any method enabled on the schema dependency, including methods enabled through Cargo feature unification. Recognizing a method does not install a handler. Requests no handler claims still follow the unhandled-message rules.
agent-client-protocol-http
Optional HTTP/SSE and WebSocket clients and servers built on the core transport-frame boundary.
agent-client-protocol-rmcp
Integration with the rmcp crate. Each supported rmcp
major version has its own module behind a matching feature (rmcp_3 for the
rmcp_3 module); none is enabled by default. Each module provides:
McpServer::builder()- define MCP tools in Rust codeMcpServer::from_rmcp()- wrap an rmcp server as an ACP MCP server
Standalone rmcp-backed servers need no ACP transport feature. Enable the
integration crate’s unstable_mcp_over_acp feature to advertise an attached
server as McpServer::Acp. Agents limited to HTTP MCP transports require the
separate compatibility polyfill.
Role System
The type system is built around roles - the logical identity of an endpoint.
graph LR
Client -->|connects to| Agent
Agent -->|connects to| Client
Proxy -->|connects to| Conductor
Conductor -->|connects to| Proxy
Counterpart Relationship
Each role has exactly one counterpart - who it connects to:
| Role | Counterpart |
|---|---|
Client | Agent |
Agent | Client |
Proxy | Conductor |
Conductor | Proxy |
This is encoded in the type system: impl ConnectTo<Client> for MyAgent means “MyAgent can connect to a client” (i.e., MyAgent plays the Agent role).
Peer Relationship
Some roles can communicate with multiple peers. The Proxy role is the key example:
graph TB
subgraph "Proxy's view"
Proxy
Client[Client peer]
Agent[Agent peer]
Conductor[Conductor counterpart]
end
Proxy -.->|"send_to(Client, ...)"| Client
Proxy -.->|"send_to(Agent, ...)"| Agent
Proxy -->|"connect_to(conductor)"| Conductor
- Counterpart (Conductor) - who the proxy connects to (transport layer)
- Peers (Client, Agent) - who the proxy exchanges logical messages with
Message Flow
Dispatch Loop
Each connection runs a dispatch loop that processes incoming messages:
sequenceDiagram
participant Transport
participant DispatchLoop
participant Handlers
participant UserCode
Transport->>DispatchLoop: incoming TransportFrame
DispatchLoop->>Handlers: try handlers in order
alt Handler matches
Handlers->>UserCode: invoke callback
UserCode-->>Handlers: return result
else No handler matches
Handlers->>DispatchLoop: default handler
end
Handler Chain
Handlers are tried in registration order. The first matching handler wins:
graph TD
Message[Incoming Message]
H1[Handler 1: InitializeRequest]
H2[Handler 2: PromptRequest]
H3[Handler 3: catch-all]
Message --> H1
H1 -->|not InitializeRequest| H2
H2 -->|not PromptRequest| H3
H3 --> Done[Handle or error]
H1 -->|matches| Process1[Process Initialize]
H2 -->|matches| Process2[Process Prompt]
Unhandled Messages
When no handler claims a message, the dispatch loop answers a request with
-32601 (Method not found), ignores a notification, and forwards a response to
its awaiter.
A handler can instead return Handled::No { retry: true, .. } to park the
message until a dynamic handler is added. On v1 and unguarded connections, a
client’s role does this for messages from the agent that carry a sessionId,
so messages that arrive just before a session’s dynamic handler is installed
are not lost. Parking is bounded:
- A connection parks at most 1024 messages. Parking one more gives up on the
oldest: a request gets
-32601, a notification is dropped with a log. - A session request the role retries is parked only while a dropped dynamic
handler’s removal is still queued.
ActiveSession::proxy_remaining_messagesrelies on this to hand a session over to its proxy handler. Once no such removal is left, the request gets-32601. Any other unhandled session request is answered right away, so the agent never waits for a handler that nobody registers.
The SDK’s session helpers install the session handler before the next incoming
message is dispatched, so they do not depend on parking. The answer is -32601
and not -32002 (Resource not found): the SDK cannot tell an unknown session
from a method nobody implements, and v1 assigns -32002 for unknown sessions to
Agents answering session requests.
Ordering Guarantees
The dispatch loop provides sequential processing:
- Messages are processed one at a time
- A handler runs to completion before the next message is processed
- Spawned tasks (
connection.spawn()) run concurrently with the dispatch loop
Important: Don’t block the dispatch loop. Use spawn() for long-running work.
Connection Lifecycle
stateDiagram-v2
[*] --> Building: Client.v1() / Agent.v2() / ...
Building --> Building: on_receive_*()
Building --> Connected: connect_to(transport)
Building --> Connected: connect_with(transport, closure)
Connected --> Running: dispatch loop starts
Running --> [*]: connection closes
Two Connection Modes
Reactive mode (connect_to): The connection runs handlers until the incoming transport reaches clean EOF, drains responses and notifications already accepted by the outgoing queue through the transport sink, then returns Ok(()), including when the builder has long-running with_spawned work. Used for agents and proxies.
Active mode (connect_with): Runs a closure with access to the connection, then closes. Used for clients that drive the interaction. Incoming EOF fails requests that still need responses, but it does not automatically cancel unrelated work in the closure.
Clean Incoming EOF
Incoming EOF is a connection event and a request-liveness boundary:
- Every pending request is completed with an internal error whose data identifies
incoming_transport_closedand the request method;is_incoming_transport_closed()detects it. - A request created after EOF fails immediately with the same error.
ConnectionTo::incoming_closed()waits for the close event, andis_incoming_closed()reports whether it has completed.Builder::on_close()runs cleanup callbacks in registration order. Returning an error terminates a still-runningconnect_withforeground; returningOk(())leaves its lifetime under application control.
This keeps request correctness separate from async cancellation policy. Applications can finish cleanup or notify a central dispatcher without having an arbitrary foreground future dropped at an await point. Pending requests are failed before close callbacks begin; the close signal is published after callbacks finish, so a callback must not await incoming_closed() itself.
Connection Termination
Clean EOF is only one way a driven connection ends. ConnectionTo::terminated() resolves, and termination() returns, a ConnectionTermination for every way the connect_to/connect_with driver can stop:
| Variant | Cause |
|---|---|
IncomingClosed | Clean incoming EOF, including a connect_with foreground returning Ok after EOF |
LocalShutdown | The connect_with foreground returned Ok before EOF |
ForegroundError | The connect_with foreground returned an error |
TransportError | The transport driver failed to read, write, or drain |
HandlerError | A message handler, close callback, runner, or spawned task failed |
Dropped | The driver future was dropped before completing |
The termination is published once, synchronously, as the driver future returns or is dropped:
- No further handler, close callback, runner, or
spawned task of the connection runs afterwards; each has completed or been dropped.on_closecallbacks run only for clean EOF. - Requests pending at clean EOF were already failed with
incoming_transport_closed. Every request still pending at termination, and every request sent afterwards, fails with an error whosedata.reasonisconnection_terminated(is_connection_terminated()), withdata.terminationnaming the variant. is_incoming_transport_closed()andis_connection_terminated()check a marker the SDK sets on the errors it produces. The marker is never serialized, so an error response from a peer never matches, even when itsdatacarries the samereason. Thedatafields only describe the error.- Dropping the driver performs only this synchronous bookkeeping. The SDK does not promise asynchronous cleanup, close callbacks, or output draining after an arbitrary drop.
Termination is not child-process reaping or application-queue drain; applications that own those remain responsible for them.
Key Source Files
| File | Purpose |
|---|---|
src/agent-client-protocol/src/role.rs | Role trait and type definitions |
src/agent-client-protocol/src/role/acp.rs | Client, Agent, Proxy, Conductor roles |
src/agent-client-protocol/src/component.rs | ConnectTo component abstraction |
src/agent-client-protocol/src/jsonrpc.rs | Connection builder and frame types |
src/agent-client-protocol/src/jsonrpc/handlers.rs | Handler chain implementation |
src/agent-client-protocol/src/jsonrpc/transport_actor.rs | Line framing and JSON parsing |
src/agent-client-protocol/src/util/typed.rs | Dispatch typing and matching helpers |
src/agent-client-protocol/src/mcp_server/ | Runtime-agnostic MCP server attachment |
src/agent-client-protocol/src/concepts/ | Rustdoc concept explanations |
Design Decisions
Why Roles Instead of Links?
Earlier versions used “link types” that encoded both sides (e.g., ClientToAgent). Roles are simpler:
- One concept instead of two (role vs link)
- Role types double as peer selectors (
send_to(Agent, ...)) - Clearer mental model: “I am X, connecting to Y”
Why Witness Macros?
The on_receive_request!() macros work around Rust’s lack of return-type notation. They capture the return type of closures at the call site, enabling type inference to work.
Why Not Traits for Handlers?
Handler closures are more ergonomic than trait implementations for most use cases. The HandleDispatchFrom trait exists for advanced cases (reusable handler components).
Cargo Features
Since the 3.0 release, the core agent-client-protocol crate enables no
features by default. Protocol serialization, connections, sessions, custom
MCP servers, and the Channel, Lines, and ByteStreams
adapters remain available without native I/O or JSON Schema generation.
[dependencies]
agent-client-protocol = "5"
You do not need default-features = false for a lean core dependency.
Native transports
| Feature | Provides | Native dependencies |
|---|---|---|
process | AcpAgent and AcpAgentConfig for launching agents | async-process, async-io, shell-words, platform process support |
stdio | Stdio for serving an agent or proxy over standard input/output | blocking |
These features are independent. process handles the child process’s stdio
itself and does not enable stdio; stdio does not enable process spawning.
LineDirection, used by native debug callbacks, is exported with either.
For a client that launches an external agent:
[dependencies]
agent-client-protocol = { version = "5", features = ["process"] }
For an agent that uses Stdio::new():
[dependencies]
agent-client-protocol = { version = "5", features = ["stdio"] }
The conductor explicitly enables both native features. Other libraries using only generic transports need neither. The native dependencies and exports remain excluded on WebAssembly, even when these features are enabled.
JSON Schema generation and typed tools
Opt into schemars to generate JSON Schemas for protocol types and typed tools:
[dependencies]
agent-client-protocol = { version = "5", features = ["schemars"] }
This enables the SDK’s direct dependency and the matching
agent-client-protocol-schema feature. Without it, protocol types still support
serialization and deserialization. Within mcp_server, these typed APIs require
schemars:
McpToolMcpToolRegistry,RegisteredMcpTool, andUnknownToolErrorMcpToolMetadataandMcpToolSchema- The
tool_fnandtool_fn_mutfunctions
McpServer, McpServerConnect, McpConnectionTo, and McpConnectionContext
remain available without it. MCP-over-ACP attachment still only requires its
protocol feature, not JSON Schema generation.
The agent-client-protocol-rmcp integration explicitly enables schemars for
its tool builders. HTTP and polyfill transports do not enable it themselves.
Cargo features are additive: another dependency that requests a feature can
enable it for the same core crate, even if your direct dependency omits it.
Transport and tooling dependencies
Internal crates request only the core capabilities they use:
| Consumer | Core features requested |
|---|---|
| HTTP client/server | None; transport sides remain opt-in through client and server |
| MCP-over-ACP polyfill | unstable_mcp_over_acp, with independent draft-v2 and session-fork passthrough features |
| rmcp integration | schemars; one feature per rmcp major version (rmcp_3), and an unstable_mcp_over_acp passthrough feature. The core crate is only a dependency with an rmcp version feature, so the passthrough does nothing on its own. It has no draft-v2 feature: enable unstable_protocol_v2 on agent-client-protocol itself |
| Conductor | process, stdio, and unstable_mcp_over_acp for launching components, serving stdio, and classifying MCP traces |
| YOPO | process for launching the agent |
| Test utilities | process and stdio for fixture binaries and launch helpers |
Conductor integration tests and cookbook recipes explicitly enable the rmcp
integration’s rmcp_3 feature, and its unstable_mcp_over_acp feature when
attaching native servers.
Conductor tests request schemars separately from production dependencies, and
enable draft-v2 polyfill support only with the conductor’s unstable_protocol_v2
feature. Internal consumers disable test-utility defaults rather than enabling
the core’s entire unstable aggregate incidentally.
The Axum consumers share HTTP1/Tokio serving and tracing/tower-log observability, but do not enable its default extractor features. The HTTP server opts into WebSockets, the polyfill opts into JSON responses, and HTTP tests opt into JSON extraction. The trace viewer serializes its responses directly and requires neither. Axum macros are not needed. Tracing subscribers retain environment filtering and text output without JSON log formatting.
The core SDK enables the futures executor only for tests and doctests. The
conductor’s Tokio/futures compatibility adapter is test-only, and the test
utilities need it only for the arrow_proxy example. The rmcp integration keeps
compatibility adapters and cancellation tokens in production; rmcp itself still
enables the futures executor transitively.
Draft protocol features
Unstable protocol features are independent of the native and schema features. For example, to use draft v2 and MCP-over-ACP without JSON Schema generation:
[dependencies]
agent-client-protocol = { version = "5", features = ["unstable_protocol_v2", "unstable_mcp_over_acp"] }
The unstable aggregate does not select draft v2; enable unstable_protocol_v2
explicitly when using that version.
Session notices and context compaction are stable in schema 1.11 and available
without feature flags in v1. Draft v2 only needs unstable_protocol_v2 for these
surfaces. The former unstable_session_notices and unstable_session_compaction
SDK features have been removed. Applications still negotiate support through
the corresponding protocol capabilities.
Subagent sessions are stable in schema 1.20 and available without feature
flags in v1: the subagents client capability, subagent_update,
session_message, session_message_chunk, and session tool call content.
The former unstable_subagents SDK feature has been removed. v2 has included
subagents since schema 1.18 with only unstable_protocol_v2, where they need
no client capability. The existing session/update notification route carries
subagent updates in both versions. This is schema support, not a subagent
scheduler or an implementation of application-level ownership and lifecycle
policy.
Plan operations are stable in schema 1.20 too: plan_update with items and
markdown plans, and plan_removed. The former unstable_plan_operations SDK
feature has been removed. A v1 agent sends them only to a client that
advertises the plan capability. v2 needs no capability.
Client-provided system prompts are stable in schema 1.16 and available without
feature flags in v1. Draft v2 only needs unstable_protocol_v2. The former
unstable_session_system_prompt SDK feature has been removed. SystemPrompt
and the session system-prompt capability types are always available. Send it
on the complete lifecycle request through build_session_from,
load_session_from (v1), or resume_session_from. systemPrompt on
session/fork still requires unstable_session_fork. Only send systemPrompt
when the agent advertises it, and only use override when mode.override is
advertised. See
Client-provided system prompts.
Schema 1.15 adds unstable_auth_status (auth/status and the
auth/status_update notification), unstable_session_archive
(session/archive and session/unarchive), unstable_session_status
(session/status) and unstable_session_set_title (session/set_title). Each
is also included in unstable, and the v1 and v2 dispatch enums parse the
methods into their typed variants when the feature is enabled. Draft v2 also
gains tool_call/cancel and terminal/cancel with unstable_protocol_v2.
Schema 1.17 adds unstable_session_options, which is also included in
unstable. It exposes session/options, the sessionCapabilities.options
(v1) and session.options (v2) capability, and configOptions on
session/new, session/load (v1) and session/resume. Send initial values
on the complete lifecycle request through build_session_from,
load_session_from (v1), or resume_session_from, and only when the agent
advertises the capability. A malformed configOptions entry fails the request
with -32602. The agent ignores an entry whose configId is unknown or whose
value is not allowed, so compare the configOptions in the response with what
you sent. Schema 1.17 also adds the session tool call content variant
(ToolCallContent::Session), which needed unstable_subagents in v1 until
schema 1.20, and description on AuthAccount under unstable_auth_status.
Schema 1.18 adds three features, each also included in unstable:
unstable_prompt_suggestionsexposes theprompt_suggestions_updatesession update and the client’ssession.promptSuggestionscapability in v1 and draft v2. Agents only send the update to a client that advertises the capability. A client must not send a suggestion as a prompt without an explicit user action.unstable_agent_skillsexposes Agent Skills in draft v2:AvailableCommand::Skill, theskillcontent block (ContentBlock::Skill), the agent’ssession.prompt.skillcapability, and the client’ssession.commands.skillcapability. It adds nothing to v1.unstable_speed_config_categoryaddsSessionConfigOptionCategory::Speed(speed). Without it,speedparses asOther("speed").
Schema 1.18 also adds configOptions on session/fork, which needs both
unstable_session_fork and unstable_session_options. In draft v2, send it
through fork_session_from. The file plan type is removed: PlanFile and
PlanUpdateContent::file no longer exist. Name the file that holds a markdown
plan with PlanMarkdown::path instead. See
Schema 1.18 for the draft v2 changes.
Schema 1.19 adds unstable_session_cursors, which is also included in
unstable. It exposes the cursor_update session update and its CursorId,
CursorAnchor, and CursorCapabilities types in v1 and draft v2, and the v1
client capability session.cursors. With unstable_session_fork as well, it
adds cursorId on session/fork, which forks a session at a cursor that
advertises capabilities.fork. A malformed cursorId fails the request with
-32602. A proxy that parses session/fork into the typed request and sends
it on must enable unstable_session_cursors too. Without it the typed request
drops cursorId, and the agent forks the whole session.
Schema 1.19 also adds idempotencyKey on draft v2 session/prompt.
unstable_protocol_v2 enables the schema’s uuid feature, so
v2::schema::IdempotencyKey::generate is available without another
dependency. The SDK already depends on uuid for request IDs. See
Schema 1.19 for the other draft v2 changes.
Schema 1.20 adds no feature and removes two: unstable_plan_operations and
unstable_subagents, whose surfaces are stable. Drop both from your
Cargo.toml. ACP v2 is in Preview from this release and stays behind
unstable_protocol_v2. Several v2 types change with it, and the schema’s maps
are now IndexMaps. See Schema 1.20.
Schema 1.21 adds no feature. The SDK re-exports the map type as
agent_client_protocol::schema::IndexMap, so building unknown variants,
elicitation forms, or provider headers by name needs no indexmap dependency
of your own. See Schema 1.21.
Schema 1.22 adds no feature. Under unstable_mcp_over_acp, an mcp/message
request can name the session and tool call it was sent for. An MCP service
reads them from its request context, and a server’s admission check can reject
a request for its session before it runs. See
Schema 1.22.
The schema’s unstable_proxy_chains feature is not an SDK feature: the SDK
always enables it, because the Proxy and Conductor roles and the conductor
crate use its proxy/initialize and proxy/successor types.
WebAssembly and the rmcp integration
The core library compiles for wasm32-wasip1 and wasm32-wasip2 with default
features. No WASI feature or default-feature opt-out is required. For
JavaScript-hosted wasm32-unknown-unknown, enable wasm_js; it selects Web
Crypto through wasm-bindgen for UUID randomness. The target does not imply a
JavaScript host, so this feature remains opt-in.
The rmcp integration library, with its rmcp_3 feature, also compiles for both
WASI targets, including native MCP-over-ACP attachment support. Its production dependencies use Tokio’s
single-thread-capable runtime and async I/O utilities, not Tokio stdio or the
multithreaded runtime. Native examples and tests enable those conveniences
separately. An application using rmcp macros or stdio transports opts into the
corresponding features on its own rmcp dependency.
Neither library provides a WASI executor or host I/O adapter. Supply a compatible runtime and transport; see Transport Architecture. This portability does not extend to the native HTTP server, polyfill, or conductor crates.
Migrating from 2.x defaults
A dependency that previously relied on native transports and typed tools:
# Before
agent-client-protocol = "2.2"
# After: select only the capabilities your application actually uses.
agent-client-protocol = { version = "5", features = ["process", "stdio", "schemars"] }
A protocol-only application can instead use agent-client-protocol = "5".
Applications that already disabled defaults must still enable process or
stdio if they use those adapters: native I/O used to be unconditional on
native targets, independently of defaults.
Core examples declare their required features explicitly. For the v2 example
pair, build with --features process,stdio,unstable_protocol_v2. The v1
simple_agent requires stdio, while yolo_one_shot_client requires process.
SDK Protocol Reference
This chapter documents shared schema features, the proxy chain methods
implemented by the Rust SDK’s conductor, and the opt-in native MCP-over-ACP
transport. The proxy methods come from the
ACP proxy chains RFD and
are unstable in the schema, behind its unstable_proxy_chains feature. The SDK
always enables that feature, so proxy and conductor support needs no feature
flag. MCP-over-ACP is also unstable and is available only with the
unstable_mcp_over_acp feature.
Client-provided system prompts
Schema 1.16 stabilizes client-authored instructions, so they need no feature
flag. In v1, check agentCapabilities.sessionCapabilities.systemPrompt; in v2,
check capabilities.session.systemPrompt. Omitted or null means unsupported.
An object advertises support for text content in append mode. Only request
override if the agent also advertises systemPrompt.mode.override.
Use the version’s SystemPrompt::new builder and pass the complete request
through the SDK’s _from session helpers:
#![allow(unused)]
fn main() {
use agent_client_protocol::v1::schema;
let instructions = schema::SystemPrompt::new(vec![
"Review changes without modifying files.".into(),
]);
let request = schema::NewSessionRequest::new("/workspace/project")
.system_prompt(instructions);
// After checking the agent's advertised capability:
// connection.build_session_from(request).block_task().start_session().await?;
let _ = request;
}
In v2, this needs unstable_protocol_v2 and uses the equivalent v2::schema
types.
SystemPrompt::new defaults to append in Rust, but both mode and content
are required on the wire. Omitted or null systemPrompt supplies no client
instructions. Malformed values fail typed request decoding with -32602;
unknown modes are preserved for forwarding, not treated as append.
Clients should re-send the prompt on load (v1), resume, and fork (with
unstable_session_fork). Agents that advertise support must apply a supplied
prompt or reject the lifecycle operation, not silently create or restore a
session without it. In v2 the error must be -32602 when the cause is the
value itself: an unadvertised mode, an unsupported content block type, or
content over the agent’s limits. Override replaces agent-authored default instructions, not
tools, permissions, or workspace instructions. Only supply content trusted at
system-instruction precedence.
Method Summary
| Method | JSON-RPC shape | Purpose |
|---|---|---|
proxy/initialize | request | Initialize a component as a proxy |
proxy/successor | request or notification | Forward one inner ACP message to the next component |
mcp/message | request or notification | Invoke one MCP operation or carry its notification |
There are no separate request and notification method names for successor or
MCP message forwarding. The presence of an outer JSON-RPC id distinguishes a
request from a notification.
Raw JSON-RPC Responses
Transport frames carry protocol-neutral RawJsonRpcResponse values. Their
boxed RawJsonRpcError preserves numeric error codes, distinguishes omitted
data from explicit null, and retains error extension fields. Raw relays
should forward these values without ACP interpretation.
Typed ACP dispatch converts raw errors to Error explicitly using
RawJsonRpcError::into_acp_error; ACP error codes are interpreted at that
boundary and error extension fields are discarded. RawJsonRpcMessage::response
still accepts an ACP Result<Value, Error> and converts its error to the raw
representation. Other protocols should construct RawJsonRpcResponse directly.
Proxy Initialization
Earlier SDK releases used
_proxy/initializeand_proxy/successor. See Migrating to v5; conductors and proxies must be upgraded together.
The conductor sends proxy/initialize to a component that has a successor.
Its parameters are the same fields as the normal InitializeRequest for the
selected ACP version. Receiving this method, rather than initialize, tells the
component that it is running as a proxy and may forward messages with
proxy/successor.
The response is the matching version’s normal InitializeResponse result. The
SDK uses the schema crate’s types, one per version:
v1::schema::InitializeProxyRequest and, with unstable_protocol_v2,
v2::schema::InitializeProxyRequest. Each is answered with that version’s
InitializeProxyResponse, a transparent wrapper around its
InitializeResponse. Convert a forwarded initialize response with .into().
The final agent receives the ordinary initialize method and does not need to
understand the proxy extension.
Successor Forwarding
proxy/successor wraps one inner ACP method and its parameters. The outer
parameters hold the inner message’s method and params:
{
"jsonrpc": "2.0",
"id": 12,
"method": "proxy/successor",
"params": {
"method": "session/prompt",
"params": {
"sessionId": "session-1",
"prompt": []
}
}
}
The conductor unwraps the message and sends the inner request to the next
component. The outer response carries the inner request’s result or error
unchanged. To forward an inner notification, omit the outer id; no response
is produced. The inner params may be omitted or null when the inner message
has none. Optional metadata for the envelope itself may be included as _meta
next to method and params; the inner message keeps its own _meta inside
its params.
$/cancel_request is hop-local and is never wrapped. To cancel a
proxy/successor request, a proxy sends a plain $/cancel_request whose
requestId is the ID of that proxy/successor request. The conductor then
cancels the request it forwarded to the next component, with that hop’s ID.
The conductor still accepts a $/cancel_request wrapped in proxy/successor
and treats it the same way.
Only a proxy and its conductor send proxy/successor. The conductor answers a
proxy/successor request from the agent, or from the client of a conductor in
agent mode, with -32600 and drops such a notification, without forwarding
either. The same applies to a proxy/successor wrapped in another
proxy/successor.
The schema types for the envelope are ProxySuccessorRequest,
ProxySuccessorNotification and ProxySuccessorResponse in v1::schema and
v2::schema, with the ProxyRequest, ProxyResponse and ProxyNotification
unions and the method names in PROXY_METHOD_NAMES. They hold the inner
message as raw JSON. schema::SuccessorMessage<M> is the SDK’s typed view of
the same envelope: it holds the inner message as an SDK message type, works for
every protocol version, and for a wrapped request uses the inner request’s
response type. The SDK’s proxy routing wraps and unwraps messages with it.
Results and errors
The result or error of a wrapped request reaches the original requester
unchanged, in both directions: error codes, messages and data (including an
explicit null) are not rewritten, and results are not re-encoded through
typed schema structs by the conductor or by the default proxy forwarding.
Two limits remain. Every hop parses messages into serde_json::Value, so a
number is re-encoded in serde_json’s form (1E2 becomes 100.0) and an
integer outside the 64-bit range loses precision. Typed ACP dispatch also drops
members of an error object other than code, message and data, which
JSON-RPC does not define.
Native MCP-over-ACP
Enable unstable_mcp_over_acp to use the draft native transport. A component
providing an MCP server adds McpServer::Acp to session setup requests
(session/new, session/load, session/resume, and the opt-in session/fork).
Its wire shape contains a human-readable name and an opaque server identifier:
{
"type": "acp",
"name": "project-tools",
"serverId": "mcp-server:01"
}
serverId identifies the declared server and is used to route mcp/message
back to the component that provided it. A provider must not reuse one server ID
for multiple visible servers on the same ACP connection. The high-level
agent_client_protocol::mcp_server::McpServer APIs create this declaration
automatically.
An agent that consumes this transport advertises
agentCapabilities.mcpCapabilities.acp. If the final agent supports HTTP but
not ACP-transport MCP servers, place the MCP-over-ACP compatibility
bridge immediately before it.
mcp/message
An agent-to-provider request invokes one MCP operation. A provider-to-agent
notification belongs to that active operation. This is an ACP envelope choice,
not an MCP method-name convention: the outer id distinguishes message kind,
and inner methods such as tools/call and notifications/progress stay distinct.
Reverse requests are not part of this binding.
{
"jsonrpc": "2.0",
"id": 21,
"method": "mcp/message",
"params": {
"serverId": "mcp-server:01",
"requestId": "logical-request:01",
"method": "tools/call",
"params": {
"name": "example",
"arguments": {},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}
}
The logical ID stays stable through proxies; the outer ACP ID is hop-local.
Each inner request declares its version and capabilities. This binding exposes
MCP 2026-07-28 only, without initialize or a discovery prerequisite.
A request can also carry sessionId and toolCallId, which name the session
and tool call the agent sent it for. Both are optional, and toolCallId is
only sent with sessionId. A provider can use sessionId to choose which
session a request acts on, and can reject a request that has none with
-32602. See the RFD.
{
"jsonrpc": "2.0",
"id": 21,
"result": {
"result": { "content": [] }
}
}
Successful ACP responses carry exactly one inner result or error.
An MCP error’s code, omitted/null data, and extensions retain MCP meaning.
Outer ACP errors describe binding failures. MRTR’s input_required remains an
inner result; subscriptions remain active requests with scoped notifications.
Cancellation uses ACP’s existing best-effort mechanism. The Rust SDK supervises owned cleanup, but that stronger implementation behavior is not an extra requirement for advertising the transport capability.
See the native guide and migration guide. The previous connection IDs and connect/disconnect methods are removed.
Related Documentation
Native MCP-over-ACP
The native binding exposes MCP 2026-07-28 over an existing ACP connection.
Enable unstable_mcp_over_acp; draft ACP v2 also requires
unstable_protocol_v2.
Services and operations
Attach an mcp_server::McpServer through the existing global or session builder
APIs. Session setup advertises an opaque serverId. Each mcp/message request
addresses that server directly; there is no MCP connect/disconnect exchange,
initialization handshake, or discovery prerequisite.
McpService is a reusable application service. Its execute method receives a
McpRequest and a request-scoped McpRequestContext. The context exposes:
- The declared server ID and logical request ID.
- The session and tool call that the agent says the request was sent for, when it supplies them.
- Validated MCP metadata, including version and client capabilities.
- Caller cancellation and operation cancellation caused by removal or shutdown.
- An operation-scoped notification sender.
- The host ACP connection for application tools.
Share caches, tool catalogs, and database pools deliberately. Do not infer a request’s identity or capabilities from a previous call.
session_id() and tool_call_id() return the request’s sessionId and
toolCallId. McpConnectionTo has the same accessors, so a tool_fn closure
can read them from its connection. An rmcp handler reads them from a
McpRequestAttribution. Both are None when the agent
sent none, for example for a request it sends during session setup. A child
session’s work carries the child’s ID. Even when sessionId names the active
session, serverId routes the request to the provider, not to the session’s
update stream.
The SDK does not check these values. Before a tool uses the session to choose what it acts on, check that the session is active on the connection, or is a child the agent announced for an active session, and that this server was declared to it or to one of its ancestors. Do not reject or delay a request because you have not seen its tool call. The agent can report the call afterwards. See the RFD.
Rejecting a request for its session
A server that needs the session of a request, or that refuses a session after
its own check, decides that before the request runs. Add an admission check
to the server with McpServer::with_admission. The check is an async closure
of the request. Like the SDK’s other async callbacks, it is followed by a
macro as the last argument, here mcp_admission!(). The check can capture the
provider’s state and await:
let server = McpServer::new_service("notes", NotesService::new(), NullRun)
.with_admission(
async move |request| {
let session_id = request.require_session_id()?;
if !sessions.is_active(session_id).await {
return Err(McpRejection::session_rejected("the session is not active"));
}
Ok(())
},
agent_client_protocol::mcp_admission!(),
);
A check that needs no await is the same closure without one:
.with_admission(
async |request| {
request.require_session_id()?;
Ok(())
},
agent_client_protocol::mcp_admission!(),
)
The check receives an McpAdmission: the server ID, the request ID, the inner
method() and params(), the tool_name() of a tools/call request, and the
request’s session_id() and tool_call_id(). require_session_id() returns
the session ID, or McpRejection::session_required() to return with ?. It
only reads the request. A request is rejected when the check returns an
McpRejection.
- The check runs for every request to the server, such as
tools/call,tools/list, andserver/discover. It works the same for a service, a connector-based server, anMcpServerBuilderserver, and afrom_rmcpserver, whether the server is attached to one session or to every session of a proxy. - It runs after the SDK has checked the inner request’s own metadata, and before the service, connector, or tool is called. A rejected request reaches none of them.
- The agent receives the outer ACP error Invalid params (
-32602). Itsdatastring isthis MCP server requires sessionId on mcp/messageforMcpRejection::session_required(), andsessionId rejected: {reason}forMcpRejection::session_rejected(reason). - A request holds its request ID while its check is pending, so another request with that ID is answered as a duplicate. The ID is free again once the request is answered, also after a rejection.
- Cancellation by the agent, removal of the server’s registration, and
connection shutdown end a pending check as they end a running request: with
Request cancelled (
-32800), with-33001, and without a response. The SDK then drops the check’s future, so a check must not own work that needs cleanup. - Calling
with_admissionagain adds another check. The SDK runs them one after the other in the order they were added. The first rejection answers the request, and the checks after it do not run. - The checks of several requests can be pending at the same time, so a check cannot change the state it captures. Put state that changes behind a lock.
Any Err from McpService::execute is still a backend failure (-33002), and
any Err from a function tool is still a tool result with isError: true.
Neither can reject a request.
A server that rejects every request without a session also rejects the requests an agent sends during session setup, and every request from an agent that sends no attribution. The HTTP re-export sends none. Give the rule to the tools that need it instead:
.with_admission(
async |request| {
if request.tool_name() == Some("add_note") {
request.require_session_id()?;
}
Ok(())
},
agent_client_protocol::mcp_admission!(),
)
To test a check without a connection, build its request with
McpAdmission::new(server_id, request_id, method), and add the optional parts
with with_params, with_session_id, and with_tool_call_id:
let request = McpAdmission::new("server-1", "request-1", "tools/call");
assert_eq!(
needs_session(request.clone()).await,
Err(McpRejection::session_required())
);
assert_eq!(needs_session(request.with_session_id("sess_1")).await, Ok(()));
Rules of one tool
A tool that the SDK registers can state its rule next to its definition. The
server awaits it before a tools/call request that names the tool runs, after
the server’s own checks. An McpTool implements admit:
impl<R: Role> McpTool<R> for AddNote {
// ...
async fn admit(&self, request: McpAdmission) -> Result<(), McpRejection> {
request.require_session_id()?;
Ok(())
}
}
A tool_fn or tool_fn_mut tool has no McpTool impl of its own. Add its
rule by name on the rmcp McpServerBuilder. The rmcp_3 module re-exports
mcp_admission! next to tool_fn!:
let server = McpServer::builder("notes")
.tool_fn("add_note", "Adds a note", add_note, tool_fn!())
.tool_admission(
"add_note",
async |request| {
request.require_session_id()?;
Ok(())
},
mcp_admission!(),
)?
.build();
A call of a tool that is not registered or is disabled gets no tool rule. The
server reports it as it does without admission checks. A hand-written
McpService states its own rule in McpService::admit, which also runs after
the server’s checks.
The #[tool] methods of a from_rmcp handler are not registered with the
SDK. Their rules go in the server’s check, by tool_name(), as shown above.
Standalone connections
A standalone MCP connection has no mcp/message request, so no admission
check runs for it, and tools see no session. A tool that is also served
standalone has to handle a call without a session.
In an rmcp handler
An rmcp ServerHandler passed to from_rmcp reads the attribution of a
request from a McpRequestAttribution, from the rmcp_3 module of
agent-client-protocol-rmcp. A #[tool] method takes it as a parameter:
#[tool(description = "Lists the notes of the session")]
async fn list_notes(&self, attribution: McpRequestAttribution) -> CallToolResult {
let session_id = attribution.session_id();
// ...
}
A ServerHandler method you write yourself gets it with
McpRequestAttribution::of. That works in every method that receives a
RequestContext, such as call_tool, list_tools, and discover:
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
let attribution = McpRequestAttribution::of(&context);
// ...
}
McpRequestAttribution has session_id() and tool_call_id(). It only reads
the request. To require a session, add an admission check to the server that
from_rmcp returns. On a standalone connection the attribution has no session
and no tool call.
Use McpServer::new_service for native-only execution, or
new_service_with_standalone to also serve a separate standalone transport.
The connector-based constructor remains an adapter for backends that need a
fresh component per operation.
The rmcp builder and from_rmcp use a shared native service and rmcp’s
one-request transport. Standalone serving retains its ordinary MCP lifecycle.
Scoped tool_fn and tool_fn_mut closures remain supported; cancelling a call
must not poison the runner or start already-cancelled queued work.
Calling a server
Use MessageMcpRequest::new(server_id, request_id, method). Choose a fresh
logical ID for every operation and include these inner parameters:
{
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {}
}
}
The logical ID stays unchanged through proxies and becomes the inner MCP JSON-RPC ID. It is separate from the outer ACP ID, which can change on each hop.
When the request is for a session’s work, name the session with
.session_id(...), and add .tool_call_id(...) for the tool call you report in
session/update. Use the IDs you send on session/update for that work, so a
child session’s request carries the child’s ID. Omit a value you do not know,
and do not send a tool call without its session. A provider can reject a
request that has no session.
Register a MessageMcpNotification handler before starting an operation that
streams notifications. Route notifications by server and logical request ID.
Use spawned work or the application’s connection future to wait for peer
traffic; do not block the ACP dispatcher.
Results and errors
First handle the outer ACP result, then match MessageMcpResponse:
Result { result, .. }contains an opaque MCP result, including JSON null, metadata, and MRTR’sinput_requiredresult.Error { error, .. }contains an MCP error. Preserve its numeric code, data omission versus explicit null, and unknown extensions.- An outer ACP error describes a binding failure, not an MCP method outcome.
A provider that needs the session answers
-32602for a request without asessionId, or with one it refuses.
An inner MCP -32000 is not ACP authentication-required. Tool execution
failures with isError remain MCP results. For MRTR, retry with a fresh logical
ID, current metadata, input responses, and the unchanged opaque request state.
ACP v1 and v2 have independent carrier/error types. Their wire representations currently agree; use the types for the negotiated ACP version.
Cancellation and cleanup
A subscription is one long-running request, not shared connection state.
Acknowledgments and updates carry the logical request ID in
_meta["io.modelcontextprotocol/subscriptionId"].
ACP cancellation is best effort on the wire. The Rust SDK revokes an owned operation’s notification rights, cancels its work, and joins supported cleanup. The logical ID remains active until cleanup finishes; completion may win a cancellation race.
Mutable function tools serialize user execution, not cancellation of queued work. A cancelled queued call is destroyed without entering its closure or waiting for another registration’s active call. Recoverable session-local runner failures close only that session’s registrations; they do not seal connection-wide admission.
Custom services must observe operation_cancellation() and return only after
owned cleanup finishes. This also applies when their registration is removed,
the ACP input closes, or the application foreground completes. The SDK keeps
native supervisors and scoped runners driven during that cleanup. It cannot
roll back arbitrary detached application work.
Example and scope
cargo run -p agent-client-protocol-rmcp \
--example stateless_native_mcp \
--features rmcp_3,unstable_mcp_over_acp
See the wire reference, HTTP re-export, and migration guide.
This change does not redesign generic ACP queues, frame types, task admission, or byte accounting. Native MCP protocol state is request-scoped; that is not a claim of bounded total process memory or complete optional MCP conformance.
Sending Requests
v1::ConnectionTo, v2::ConnectionTo and the version-neutral
ConnectionTo support two request APIs. The versioned connections return
v1::SentRequest / v1::PreparedRequest and v2::SentRequest /
v2::PreparedRequest, whose id() is that version’s request ID:
send_request(request)sends immediately and returns aSentRequest. Keep this when eager publication is useful, such as starting work before choosing how to consume its result. Existing behavior is unchanged.prepare_request(request)returns aPreparedRequestwithout sending. Choose this when response handling must be selected before the peer can reply, especially for ordered callbacks from outside the connection future.
Both have an explicit-peer variant: send_request_to(peer, request) and
prepare_request_to(peer, request).
Publication means synchronously registering the pending reply and enqueueing the request. Peer transformation and physical transmission happen later in the connection driver; successful publication does not acknowledge peer receipt.
Select handling before publication
#![allow(unused)]
fn main() {
connection.prepare_request(request).on_receiving_result(async move |result| {
application_queue.enqueue(result)?;
Ok(())
})?;
}
The callback task and ordering marker are installed before the request enters the outgoing queue. When the peer response is routed during its original dispatch, the loop waits for the callback to finish before dispatching later messages. Success and error responses have the same ordering.
on_receiving_ok_result(responder, callback) and
forward_response_to(responder) also select ordered handling before sending.
For a forwarding proxy, prepare_request_to(Agent, request).forward_response_to(responder)
also records the predecessor’s ID before the agent can send a request-scoped
elicitation. If you need a custom response callback, call
forwarded_from(&responder) on the prepared request first. This propagates
cancellation as well. Use forward_cancellation_from(...) instead for a child
operation that should be cancelled with its parent but is not the same request.
In the reverse direction, relay a request-scoped elicitation with
prepare_request_to(Client, challenge).forward_response_to(responder) or
send_proxied_message_to(Client, dispatch). Both translate the challenge’s
params.requestId before sending it. An eager send cannot rewrite it afterward.
Keep ordered callbacks short. They must not await another response, notification, or other inbound traffic on the same connection: dispatch cannot deliver that traffic until the callback returns. Enqueue application work and return, or spawn follow-up work.
Eager send_request(...).on_receiving_result(...) retains its existing
conditional guarantee: if response routing wins the race with registration,
the callback runs without a barrier. Even immediate chaining can race when the
connection runs concurrently. Neither API imposes a barrier on EOF-generated
failures or on a retained ResponseRouter routed after its original dispatch.
Unordered consumption
prepare_request(...).block_task() sends during the method call, then
returns a response future. It does not wait for the first poll to send:
#![allow(unused)]
fn main() {
let response = connection.prepare_request(request).block_task();
connection.send_notification(notification)?; // Queued after the request.
let result = response.await?;
}
Await that future only outside incoming handlers. Dispatch does not wait for the caller to process its result.
prepare_request(...).detach()? sends and discards the eventual response
without cancelling. It does not select ordered consumption.
Outgoing order follows publication, not preparation. A notification sent between preparation and consumption enters the queue before the request.
Cancellation after selecting a consumer
Obtain cancellation_handle() before consuming a prepared or sent request to
retain explicit cancellation control alongside its callback or response future:
#![allow(unused)]
fn main() {
let prepared = connection.prepare_request(request);
let cancellation = prepared.cancellation_handle();
prepared.on_receiving_result(async move |result| {
application_queue.enqueue(result)?;
Ok(())
})?;
caller.on_abandoned(move || cancellation.cancel());
}
Hand cancellation control to the caller’s abandonment handler only after publication returns, and have that handler deal with any immediate error. Merely dropping the public handle does not cancel. The callback owns eventual completion and any late-resource cleanup independently of the caller.
Cancelling does not discard the eventual result. The cloneable handle shares
SDK settlement and once-only cancellation state, rather than sending an
unconditional notification for a saved request ID. Dropping the handle does
nothing. Calls before publication or after a response/local failure do nothing.
Detachment suppresses automatic cancellation but preserves retained explicit
control until settlement. Ok(()) is not acknowledgment that cancellation was
sent or took effect. See Request Cancellation for
the full contract, including publication races and peer wrapping.
Drop and errors
Dropping an unconsumed PreparedRequest sends nothing. Dropping the response
future returned by block_task() asks the peer to cancel an outstanding request,
as dropping an eager SentRequest does.
Preparation and publication failures reach the selected callback or response
future. Callback registration failure returns an error without sending the
request. detach() returns immediate preparation and enqueue failures directly;
later local transformation errors and peer response errors are discarded.
Transport failures still propagate through the connection future. Returning an
error from a callback terminates the connection, so handle expected request
errors inside it.
See Ordered Application Dispatch for extending these guarantees to a separate application executor.
Request Cancellation
This chapter documents the $/cancel_request protocol-level notification and
how the SDK implements it.
For API usage (cancelling a SentRequest, observing cancellation from a
Responder, or retaining a RequestCancellationHandle alongside a callback),
see the concepts::cancellation chapter in the
agent-client-protocol rustdoc.
The $/cancel_request Notification
Either side of a connection may send $/cancel_request to ask the peer to
cancel one outstanding JSON-RPC request, identified by its ID:
{
"jsonrpc": "2.0",
"method": "$/cancel_request",
"params": {
"requestId": "70b9f1c9-c2a3-4bd2-b6b9-65a06d96b675"
}
}
requestId is the JSON-RPC id of the request to cancel, as allocated by the
sender of that request (a string, number, or null).
Semantics
Cancellation is cooperative. After receiving $/cancel_request, the peer
may:
- ignore it and respond to the request normally,
- finish early with whatever data it has, or
- respond to the original request with the standard cancellation error,
code
-32800(“Request cancelled”).
The requesting side always receives a response to the original request;
cancellation only changes which response that is. A $/cancel_request for
an unknown or already-completed request ID is silently ignored. A
$/cancel_request with malformed params (for example, a requestId that is
not a string, number, or null) is logged and ignored without a reply, like any
other malformed notification.
Unanswered Requests
The SDK makes sure a request it received is always answered, even when the
handler never responds. If a Responder is dropped without a response having
been sent through it, the SDK sends an error response for the request:
-32800(Request cancelled) if the peer had cancelled the request with$/cancel_request, as ACP requires for a cancelled request whose method defines no cancellation result;- otherwise
-32603(Internal error), with data naming the method.
If the handler that dropped the responder returns an error, that error is the
response instead. No automatic response is sent when a response was already
sent or handed off (for example with forward_response_to), when the
responder was moved into another task or wrapper that still owns it, or when
the connection is shutting down or has terminated. Notifications have no
responder and never get a reply.
The automatic error is an ordinary error response. A dropped initialize
responder fails initialization like any other initialize error: a first
initialize leaves the connection uninitialized, so the client can retry, and
a failed repeat keeps the previous initialization.
Interoperability
Protocol-level ($/-prefixed) notifications are optional by design. The SDK
ignores unhandled notifications instead of rejecting them with a
method-not-found error. A peer that sends $/cancel_request to a component
that does not support cancellation therefore loses nothing: the request simply
runs to completion.
Dropping an unconsumed SentRequest asks the peer to cancel it. Use
SentRequest::detach() for requests whose eventual response should be ignored,
but which should continue running on the peer. The peer is still expected to
answer the JSON-RPC request eventually; use a notification instead when no
response is expected at all.
Retaining Cancellation Control
Before consuming a PreparedRequest or SentRequest, call
cancellation_handle() to retain a cloneable RequestCancellationHandle.
Its cancel() method requests cancellation independently of response consumption:
an ordered callback or response future still receives the eventual result.
The handle shares once-only cancellation and settlement state with
SentRequest::cancel, forwarded cancellation, and automatic request-drop
cancellation. It cancels over the original request’s connection with that
request’s ID. Dropping the handle
neither sends cancellation nor disables automatic request-drop cancellation.
To cancel when a caller is abandoned, its application-owned guard or abandonment
handler must explicitly call cancel() and handle any immediate error.
Calling it before a prepared request is published does nothing and is not remembered for later publication. A call racing publication may also do nothing; hand control to independent cancellers after the publishing method returns. Once the SDK routes a response or fails the request, new cancellation calls do nothing—even if the application has not consumed the result yet. An attempt begun before settlement may still enqueue afterward.
Detachment is separate from settlement: detach() discards the response and
suppresses automatic cancellation on drop, but does not revoke retained explicit
handles. They can still cancel the detached request while it remains pending.
Ok(()) means the call encountered no immediate error, not that a notification
was sent or the peer stopped work. Cancellation is cooperative; it does not
guarantee transmission, peer cooperation, or a successful response. A handle does
not abort local callback work or keep the connection driver/response consumer alive.
Request Cancellation Is Not Session Cancellation
$/cancel_request targets one pending JSON-RPC request, not the lifetime of the
session work it may start. In ACP v2, session/prompt succeeds once the user
message is inserted and returns its messageId. After insertion the Agent must
return success, not -32800, even if cancellation races the response. Stopping
active session work uses session/cancel. See the
v2 cancellation specification
and prompt lifecycle.
Proxy Chains
Cancellation propagates hop by hop rather than end to end. Request IDs are
allocated per connection, so a $/cancel_request only ever refers to a
request on the connection it is sent over:
- The client sends
$/cancel_requestfor a request it made to its direct peer (for example, a proxy). - A proxy that forwarded the request downstream (the SDK does this with
forward_response_to) reacts by sending its own$/cancel_requestfor the downstream request, using the downstream connection’s request ID. - The downstream response — normal data or the cancellation error — flows back up the chain as the response to each hop’s request.
Because the notification is hop-scoped, it is never tunneled across hops:
generic forwarding helpers (send_proxied_message_to in the SDK, and the
conductor’s internal routing) drop a raw $/cancel_request instead of
forwarding a request ID that means nothing on the next connection. The
cancellation still reaches the next hop, re-issued by forward_response_to
with that hop’s own request ID.
Proxies that intercept methods with custom handlers stay in control: the
request’s cancellation marker is their decision point, and handlers see the
raw notification before any generic forwarding fallback. A custom handler can
handle the cancellation locally, propagate it to a forwarded request
(forward_response_to, or forward_cancellation_from when the forwarding
needs custom logic), absorb it, or claim the notification and route it itself.
See the concepts::cancellation chapter in the
agent-client-protocol rustdoc for
the full decision matrix.
When the notification targets a request that was wrapped in a
proxy/successor envelope (see the Protocol Reference), the
$/cancel_request is sent plain, not wrapped, and requestId is the JSON-RPC
id of the proxy/successor request on that connection. Receivers, including
the conductor, also accept a $/cancel_request wrapped in proxy/successor,
which earlier SDK releases sent, and treat it the same way.
The conductor translates cancellations between hops. Since request IDs are
reallocated at every hop, a raw $/cancel_request cannot match anything
beyond the hop it was sent over; the conductor re-issues cancellation with the
next hop’s request ID instead.
Related Documentation
- Protocol Reference - The
proxy/successorenvelope protocol - agent-client-protocol rustdoc - SDK API for sending, observing, and forwarding cancellations (see
concepts::cancellation)
Logging and diagnostic privacy
Ordinary SDK warning logs describe protocol errors using the numeric error code and a fixed, code-derived reason. Dispatch warnings also identify the method and, where applicable, request ID and handler. They do not format the error’s application-controlled message or data.
This applies to malformed typed notifications, request and notification handler failures (including dynamic handlers), and outgoing error responses. Serde parse reasons can quote invalid strings or enum variants, so they are not safe to log even though the errors for params and results that cannot be decoded leave out the failing JSON. The SDK does not extract field paths from free-form error text; there is currently no separately trusted structured field path to include in these warnings.
Detailed diagnostics are sensitive
Log redaction does not change the errors returned to callers or sent to peers.
When params or a result cannot be decoded, including by util::json_cast and
util::json_cast_params, the error does not include the failing JSON input, but
its parse reason can quote values from it. Applications should not log these
errors using their ordinary Debug or Display representations unless they
intend to record that content.
DEBUG and TRACE logs
DEBUG logs identify messages by kind, method, and request ID only. They never format params, results, or error messages and data, so enabling DEBUG does not record prompts, tool arguments, or credentials. Serde parse failures are logged by category (and position, for syntax errors) rather than their reason text.
Only the transport-level TRACE events (Received JSON-RPC message, Sending JSON-RPC message, and Relaying invalid JSON-RPC value) record complete messages. They redact every value of an env or
headers field (MCP server declarations in session setup, terminal auth
methods, terminal creation, and provider configuration), keeping the names, and
omit lines that are not valid JSON. Other TRACE events carry metadata only.
Explicitly enabled TRACE logging still records terminal output, prompts, tool
arguments, error responses, and any credentials outside env/headers. Treat
these traces as private data and enable, store, and share them accordingly.
Application-provided logging callbacks, such as AcpAgent::with_debug, receive
raw lines and are not redacted.
Ordered Application Dispatch
The SDK’s inbound ordering does not automatically extend to an application’s UI
executor. A notification handler may have finished enqueueing an update while
the application has not yet applied it. Awaiting a request with block_task()
on another task does not drain that application queue.
Use one FIFO queue with one sequential consumer for:
- Notifications, enqueued by typed connection handlers.
- Response results, enqueued by
PreparedRequest::on_receiving_result. - Connection closure, enqueued by
Builder::on_close.
Apply updates in the consumer and expose a response result only when the consumer reaches that event. For v2 resume, this makes preceding replay visible to application code before it observes the resume result. Do not spawn a separate application task for each event unless that executor also preserves their application order.
The compiled ordered application-dispatch cookbook recipe
demonstrates this with an application callback that need not be Send.
Connection handlers retain only event senders, not the application view or an
owning connection. This is an integration pattern, not a new session state
machine or coordinator.
Response barriers are short dispatch steps
Use prepare_request(...).on_receiving_result(...) to install ordered handling
before publishing the request, even from another task. Eager
send_request(...).on_receiving_result(...) only holds dispatch if registration
wins the race with response routing. The barrier is not retroactive:
already-routed responses and later routing through a retained ResponseRouter
do not hold subsequent wire traffic. See Sending Requests
for the additive API and publication timing.
The callback should enqueue the result and return. Do not await another
inbound response or notification on that connection inside the callback.
That traffic cannot be dispatched until the callback finishes, causing a
deadlock even on a multithreaded runtime. Perform work that needs later traffic
in the application consumer, the connect_with foreground, or a task started
with ConnectionTo::spawn.
If another application task needs a projection-drained acknowledgement, the consumer can send it after applying the response marker. The SDK callback should not wait for that acknowledgement.
See the SDK ordering contract for the full callback and response-routing semantics. Queue capacity is an application decision: the recipe uses an unbounded queue, while a bounded queue requires a backpressure policy that cannot deadlock inbound dispatch.
Closure is an application event too
Clean incoming EOF follows already-received notifications and timely ordered
wire responses. Putting on_close on the same queue lets the consumer apply
those events before marking the connection closed.
EOF fails pending SDK requests before running close callbacks, but their
synthetic error callbacks are not ordered wire-response barriers and can
enqueue results after the closure event. The application should settle its
outstanding operations at Closed and tolerate late completions, rather than
waiting for every callback before accepting closure. Transport and handler
errors still propagate from the connection future; this pattern does not turn
all failures into clean EOF. To run shared disconnect cleanup for every
outcome, also observe ConnectionTo::terminated(). It reports why the driver
stopped, but is not ordered with the application queue, so keep on_close as
the projection barrier for clean EOF.
Do not add prompt attribution
The queue preserves dispatch order, not a relationship the protocol does not
provide. A v2 prompt response acknowledges acceptance. Session running and
idle updates describe foreground state, not a specific prompt’s completion,
and background updates may continue while idle. Keep these as separate
application events; do not assign the next Idle to a prompt without an
additional protocol guarantee. See high-level v2 sessions.
Configurable LLM Providers
The core SDK exposes the draft configurable-provider API through the
unstable_llm_providers feature:
agent-client-protocol = { version = "...", features = ["unstable_llm_providers"] }
Draft protocol v2 applications must enable both unstable_protocol_v2 and
unstable_llm_providers.
An agent advertises support with AgentCapabilities.providers. After
initialization, clients can use three typed client-to-agent requests:
providers/listdiscovers configurable providers, supported API protocols, whether each provider is required, and its current non-secret routing target.providers/setreplaces one provider’s API protocol, base URL, and complete header map.providers/disabledisables a non-required provider.
Clients should configure providers before creating or loading sessions. Provider configuration is process-scoped and should not be persisted. Disabling an unknown provider is idempotent, while attempts to disable a required provider must be rejected.
The SDK supplies typed wire routing only. Applications remain responsible for
capability checks, validating provider IDs and API protocols, enforcing required
providers, applying configuration to sessions, and storing header values
securely. Since headers may contain credentials, providers/list intentionally
returns only apiType and baseUrl and must never echo configured headers.
Sensitive logging: SDK debug and trace instrumentation can include complete JSON-RPC bodies. Treat those logs as sensitive and do not enable body-level logging where provider headers may contain credentials.
Protocol V2
The core SDK can opt into ACP protocol v2 with the unstable_protocol_v2 crate
feature. Protocol v2 has been in Preview since schema 1.20: it is ready to build
on, and it is not frozen. The SDK’s v2 API can still change in a minor release.
agent-client-protocol = { version = "...", features = ["unstable_protocol_v2"] }
This feature is separate from the broad unstable feature because protocol v2
is a separate protocol version, not an unstable method family.
To start from working code, build and run the companion agent and client in the Runnable Protocol V2 Quickstart. The examples exercise prompt acceptance, independent session updates, and the terminal idle state over a real stdio connection.
JSON-RPC batches
Protocol v2 removed JSON-RPC batching, and the SDK no longer supports it in
either protocol version. Every connection answers an incoming JSON array with a
single -32600 (Invalid Request) error with id: null and processes none of
its entries. The SDK never sends a batch. See Transport Architecture: JSON-RPC
Batches.
Every connection names its version: Client.v1(), Agent.v1(), and
Proxy.v1() expose the stable v1 API, and Client.v2(), Agent.v2(), and
Proxy.v2() the v2 API. The SDK types for each version live in
agent_client_protocol::v1 and agent_client_protocol::v2, which export the
same names: ConnectionTo, Builder, Responder, ResponseRouter,
SentRequest, PreparedRequest, Dispatch, SessionBuilder,
ResumeSessionBuilder, SessionSetup, ActiveSession, and schema (plus
ForkSessionBuilder and the send_initialize outcome types in v2). Moving code from v1 to v2 is
mostly a matter of changing which module it imports from.
Fluent typed handlers, spawned tasks, close callbacks, and connect_with
receive v2::ConnectionTo<_>, so the protocol version is reflected in the
high-level Rust API as well as on the wire:
#![allow(unused)]
fn main() {
use agent_client_protocol::schema::ProtocolVersion;
use agent_client_protocol::v2::schema;
use agent_client_protocol::{Agent, Client};
fn implementation() -> schema::Implementation {
schema::Implementation::new("example", "0.1.0")
}
async fn run(agent_transport: impl agent_client_protocol::ConnectTo<agent_client_protocol::Client>) -> agent_client_protocol::Result<()> {
Client
.v2()
.connect_with(agent_transport, async |cx| {
let initialize = cx
.send_request(schema::InitializeRequest::new(
ProtocolVersion::V2,
implementation(),
))
.block_task()
.await?;
assert_eq!(initialize.protocol_version, ProtocolVersion::V2);
Ok(())
})
.await?;
Ok(())
}
async fn serve(client_transport: impl agent_client_protocol::ConnectTo<agent_client_protocol::Agent>) -> agent_client_protocol::Result<()> {
Agent
.v2()
.on_receive_request(
async |initialize: schema::InitializeRequest, responder, _cx| {
responder.respond(schema::InitializeResponse::new(
initialize.protocol_version,
implementation(),
))
},
agent_client_protocol::on_receive_request!(),
)
.connect_to(client_transport)
.await?;
Ok(())
}
}
When v2 mode is enabled, application code should use SDK types from
agent_client_protocol::v2 and message types from v2::schema. Importing
agent_client_protocol::v2::{self, schema} brings both into scope without a
name clash. The preceding agent fragment demonstrates version negotiation only.
An agent that advertises session support must also implement the complete
baseline session surface shown in the runnable quickstart.
tool_call/cancel and terminal/cancel
Neither method has an initialize-time capability. An agent that advertises
capabilities.cancel on a tool call or terminal must implement the corresponding
request. The SDK answers an unhandled method with -32601 (Method not found).
Before initialization these requests get -32600 like any other.
If you implement the method, respond with -32002 and data.sessionId for an
unknown or inactive session. An announced child of an active session is not
unknown. For a known session, respond with -32602 (Invalid params) if the tool
call or terminal is unknown, final, or not cancellable.
sessionId is the session that reports the tool call or terminal. For a
subagent’s tool call or terminal, that is the child session. The item’s own
capabilities.cancel enables the request even when the child session doesn’t
advertise cancel, and it enables nothing else on the child. Send
v2::schema::CancelToolCallRequest or v2::schema::CancelTerminalRequest with
the child’s sessionId.
High-level v2 sessions
Stable callbacks receive v1::ConnectionTo<_> and expose the protocol v1
build_session*, load_session*, resume_session*,
v1::SessionBuilder, v1::ActiveSession, and v1::SessionMessage APIs.
Callbacks installed through Client.v2() receive v2::ConnectionTo<_> and expose
the v2 build_session* and resume_session* helpers, plus feature-gated
fork_session* helpers when unstable_session_fork is enabled. The shared
names describe the same lifecycle operations while the connection type selects
their schema and return types at compile time. Resume and fork return
v2::ResumeSessionBuilder and v2::ForkSessionBuilder. Call start_session to
publish the request and obtain a v2::SessionSetup containing the command
handle and complete operation-specific response.
Low-level custom with_handler and with_runner implementations continue to
receive the protocol-neutral ConnectionTo<_>, and generic send_request
remains schema-agnostic. These generic APIs do not infer a protocol version from
the Rust payload type: callers on a v2 connection must use v2::schema types,
or deliberately send extension or untyped messages. The connection guard
enforces negotiation and initialization lifecycle, not Rust-type provenance.
Dynamic handlers registered through v2::ConnectionTo::add_dynamic_handler use
the same low-level HandleDispatchFrom interface and therefore also receive
ConnectionTo<_>. Raw code converts explicitly: connection.into_protocol::<V1>()
returns a v1::ConnectionTo (and into_protocol::<V2>() a v2::ConnectionTo),
and either versioned connection’s into_raw() returns the version-neutral one.
into_protocol fails with -32603 when the connection’s builder guards a
different version, so a connection from Client.v1() never becomes a
v2::ConnectionTo. ConnectionTo::protocol_version() reports the guarded
version, or None for an unguarded Builder::new connection.
spawn_connection returns the connection type the child builder’s callbacks
receive, on the raw ConnectionTo and on both versioned connections:
spawning Client.v2() returns a v2::ConnectionTo<_>, spawning
Client.v1() a v1::ConnectionTo<_>, and spawning a raw Builder::new
builder a raw ConnectionTo<_>.
A complete client installs update and interactive-request handlers before
connecting. After session/prompt is accepted, it must keep the connection
alive and consume updates until the matching session reaches idle. The
v2_one_shot_client
example demonstrates the full sequence, while the compiled cookbook
v2_one_shot_prompt recipe shows how to embed it in an application. Permission
handlers should transfer the request and responder to application-owned work
rather than waiting for user input inside the dispatch callback.
V2 deliberately separates prompt submission from session observation:
session/promptreturns aPromptResponseas soon as the agent accepts the prompt. Itsmessage_ididentifies the inserted user message, and liveUserMessageupdates for that prompt use the same ID. Persisting the message in resumable history remains optional. The response does not indicate turn completion.v2::ActiveSession::send_promptreturns that request as aSentRequest<PromptResponse, V2>. Callers must explicitly await it, register a response callback, or detach it.v2::SessionBuilder::start_sessionlikewise returns a mappedSentRequest. Itsv2::SessionSetupresult keeps the command handle separate from the completeNewSessionResponserepresented by the linked schema, rather than reconstructing a selected subset of its fields.v2::ConnectionTo::resume_sessionandresume_session_fromreturn av2::ResumeSessionBuilder. Itsstart_sessionmethod publishessession/resumeand returns av2::SessionSetupcontaining the completeResumeSessionResponsewithout reconstructing it.- With
unstable_session_fork,v2::ConnectionTo::fork_sessionandfork_session_fromreturn av2::ForkSessionBuilder. Itsstart_sessionpublishessession/fork, preserves the completeForkSessionResponse, and uses that response’s newly allocated session ID for the command handle. v2::ActiveSessionis a cloneable command handle containing only the session ID and connection. It does not own, buffer, or unregister inbound messages.- Register typed
UpdateSessionNotificationandRequestPermissionRequesthandlers onClient.v2()before connecting. Updates and interactive requests are separate protocol lanes. Permission handlers should transfer responders to application-owned work rather than waiting for user input inside the connection dispatch loop. Without matching handlers, unhandled v2 notifications are ignored and unhandled requests receive a method-not-found response. They are not retained for a later per-session receiver. session/updateevents can arrive before, during, or after a prompt request. They carry a session ID and entity IDs, but no prompt or turn ID. The SDK therefore does not attribute intervening events to a locally submitted prompt or provide a prompt-scoped text accumulator.state_updatedescribes the session-wide foreground state.idlemeans the session can accept ordinary new foreground work. It is not a wire-level boundary assigning previous events to one prompt, and background updates may continue while idle.send_promptmay be called in any state. The agent inserts the prompt right away or holds it and inserts held prompts in received order; it must not reject a prompt only because foreground work is active. A held prompt’s response stays pending until insertion.cancel_active_workandclosedrop the prompts the agent has received and not inserted. Cancelling a held prompt’sSentRequestsends$/cancel_request, which is best effort: the agent either answers-32800or inserts the prompt as usual. An inserted prompt cannot be withdrawn.send_prompt_blocks_with_keysends the prompt with anidempotencyKey. While the agent recognizes the key, a retry with the same key does not insert a second user message. A resumed session does not tell the client which keys the agent kept, so a retry after a reconnect can still insert one (see Schema 1.20).send_promptandsend_prompt_blockssend no key.cancel_active_worksends session-widesession/cancel. It covers the session’s foreground work and prompts received before it that the agent has not yet inserted; those prompt requests fail with-32800(request cancelled), while a prompt whose user message was already inserted still succeeds with its message ID. A prompt sent after it is not cancelled. Work in the latestbackgroundlist is not covered and keeps running; the agent may stop background activity it does not list. Cancellation of active foreground work completes after the requiredidleupdate with stop reasoncancelled, which the agent sends before it starts new foreground work in the session. Updates for listed background work can still arrive after it. Cancelling an idle session need not emit another idle update, and work that had already ended keeps its stop reason.cancelledis reserved for work the client cancelled withsession/cancelor by closing the session, and for a child session whose parent cancelled its work. Work the agent stops on its own uses another reason, such aserror. A prompt sent while cancellation is in progress is not rejected for that reason: the agent inserts it, or holds it until the cancelled work has reportedidle. The client should immediately mark unfinished tool calls for the active work as cancelled. The agent owns pending permission requests: it stops waiting for those of the cancelled work, treats them as not approved, and must cancel each with$/cancel_request. The agent decides which requests belong to that work, so the client does not answer every pending permission request when it sendssession/cancel. The client should dismiss a cancelled permission request and answer it with thecancelledoutcome, and may answer one it knows belongs to the cancelled work that way without waiting. Permission requests for listed background work stay open. Elicitations are not all cancelled implicitly: the agent must cancel each elicitation it stops waiting for with an individual$/cancel_request, and the client should answer it with thecancelaction. Cancelling or dropping the prompt’sSentRequestis the separate JSON-RPC request-cancellation mechanism; insertion still requires a successful prompt response with its message ID.set_config_optionmust only name aconfigIdthe agent advertised for the session. An unknownconfigIdor invalid value fails with-32602and leaves the configuration unchanged. A successful response is the complete option set as of the response and may report a differentcurrentValuethan requested. Apply responses andconfig_option_updatenotifications in the order received, each replacing the whole list, even though a duplicate notification for the same change may arrive before the response.closereturns the complete close response. Closing is idempotent, soclosealso resolves a-32002response (an unknown or already-closed session) as success. Mutable configuration is not cached on the command handle.
Install connection handlers before session/new, session/resume, and
feature-gated session/fork requests. This is especially important before
calling start_session on a v2::ResumeSessionBuilder: replay updates precede
the resume response on the wire, so preinstalled typed handlers observe them in
order. The agent ends the replayed history with a replay_complete update
(see Schema 1.18). Do not send a second session/resume with a
replayFrom cursor for a session while the first one is pending. If a handler forwards updates to another
task, the application is responsible for any additional projection-drained
barrier it needs before treating replay as locally applied.
See Ordered Application Dispatch for a
single-consumer queue that carries updates, response results, and closure.
For an application-owned prototype that additionally coordinates shared resume
replay, abandonment, and close, see
Session Operation Coordination. It is a
cookbook policy example, not a public SDK coordinator.
Dropping command handles has no network or inbound-routing side effect. For a
session configured with v2::SessionBuilder::with_mcp_server or
v2::ResumeSessionBuilder::with_mcp_server, or feature-gated
v2::ForkSessionBuilder::with_mcp_server, the SDK installs the MCP routes and
initially polls their runner tasks before publishing the corresponding setup
request, so the agent can connect to those servers during setup or resume
replay. Runners may continue asynchronous initialization, so custom connectors
must be able to queue connections and messages once constructed. A successful
setup promotes the attachment to the connection lifetime. A setup failure,
including an error response after cancellation, cleans up the pending
attachment. This attachment requires both unstable_protocol_v2 and
unstable_mcp_over_acp. Fork additionally requires
unstable_session_fork.
A v2 proxy can instead attach one server globally with
Proxy.v2().with_mcp_server(...). The proxy reuses one connection-scoped
server ID and adds its declaration to v2 session/new, session/resume, and
feature-gated session/fork requests. It modifies only the mcpServers field,
preserving unrelated setup fields and extensions for downstream handlers.
MCP server names must be unique within mcpServers. If the client already
declares a server with the proxy server’s name, the proxy fails that request
with -32602, naming the server it configures, instead of forwarding a request
the agent must reject. It does not rename or drop either server.
v2::SessionBuilder::on_proxy_session_start and
v2::ResumeSessionBuilder::on_proxy_session_start, plus
v2::ForkSessionBuilder::on_proxy_session_start when enabled, are the
non-blocking setup helpers for a v2 proxy:
use agent_client_protocol::v2::{SessionSetup, schema};
use agent_client_protocol::{Client, Proxy};
Proxy
.v2()
.on_receive_request_from(
Client,
async |request: schema::NewSessionRequest, responder, cx| {
cx.build_session_from(request)
.with_mcp_server(session_server)?
.on_proxy_session_start(responder, async |setup| {
let SessionSetup { session, response, .. } = setup;
record_session(session.session_id(), response);
Ok(())
})
},
agent_client_protocol::on_receive_request!(),
);
These helpers forward request cancellation, send an ordered downstream setup
request, and forward the complete operation-specific response without
reconstruction. For session/new and session/fork, routing is installed when
the response makes the new session ID available and before later inbound
traffic is dispatched. Fork routing uses the response’s new ID rather than the
source session ID. For session/resume, the ID is already known, so routing and any per-session
MCP attachment are ready before the downstream request is published. Replay
updates can therefore be forwarded upstream before the complete
ResumeSessionResponse, as required by the protocol. A failed or cancelled
downstream response drops pending routing and MCP attachment. Successful setup
keeps them for the connection lifetime. A cancellation signal itself remains
advisory: it is forwarded downstream while the helper awaits that response.
Each helper then spawns the callback outside the ordering barrier with an
v2::SessionSetup containing the command-only session handle and complete setup
response. Updates and interactive requests remain independent connection
traffic and should still be handled by typed callbacks on Proxy.v2().
If an application wants stream ergonomics, it can fan typed updates out from the connection handler with an explicit buffering and subscriber policy.
Conductor and proxy initialization
Proxy authors should make the version boundary explicit. Proxy.v1() is
the stable v1 builder, while Proxy.v2() is v2-only. A proxy negotiates
proxy/initialize exactly as an agent of the same version negotiates
initialize: a v1 proxy selects v1 for every request, keeping only what
parses under v1 for a newer one; a v2 proxy selects v2 for a request for v2 or
newer, keeping only what parses under v2 for a newer one, and rejects a
request below v2 with -32022. A proxy never parses one version’s request
through a permissive schema for another.
When one component must expose independently authored v1 and v2 proxies,
compose them with
Proxy.protocol_router().with_v1(v1_proxy).with_v2(v2_proxy). The proxy
router selects an implementation from proxy/initialize exactly as
Agent.protocol_router() does from initialize: a request for v2 or newer
selects v2, and with a v1 implementation configured everything else goes to
v1, which negotiates it as it would alone. It hands over the complete,
unchanged initial transport frame for a request for exactly the selected
version and does not convert later traffic.
Components implementing their own raw version selector can use
Builder::new(Proxy) and keep protocol-neutral ConnectionTo callbacks.
Builder::new applies no protocol-version guard, so it is not a substitute
for selecting Proxy.v2() in an ordinary v2 proxy implementation. A proxy’s default forwarding is the same for every builder and
every protocol version: proxy/initialize has the same wire shape in v1 and
v2, so the proxy forwards untyped messages, and fields the SDK does not know
survive. After a forwarded session/new succeeds, the proxy reads the raw
sessionId from the response and routes that session’s updates back to the
client.
The unstable_protocol_v2 feature only adds v2 items. Enabling it never
changes how a v1 connection behaves: where one code path serves both versions,
the SDK selects v2 behavior from the connection’s protocol version at runtime.
The conductor forwards both versions through one untyped path that does not
depend on the feature or on the selected version. Its connections to the
client and to the final agent have no version guard; the endpoints validate
the traffic of the version the chain negotiated. The conductor rejects a
proxy/initialize that arrives from outside, renames the client’s
initialize to proxy/initialize for the first proxy without touching its
params (the proxy restores the ordinary method before the request reaches the
final agent), and forwards everything else unchanged. info, capabilities,
metadata, and unknown extension fields therefore retain their wire shape
across conductor-controlled rewrites in both versions. A proxy implementation
can still deliberately replace the request it forwards.
Before it instantiates the chain, the conductor selects the version from the
raw protocolVersion: with the conductor crate’s unstable_protocol_v2
feature, a request for v2 or newer selects v2; every other request selects v1,
keeping v1’s fallback-to-latest rule. A request for a newer version than the
selected one keeps only what parses under the selected version, as the SDK’s
own agents negotiate (agent_client_protocol::util::initialize_params_for_version).
A conductor acting as a proxy negotiates its proxy/initialize the same way.
The conductor’s selection is the highest version the chain may speak, and it
forwards the request at that version. Because each proxy negotiates like an
agent, a proxy that supports only a lower version initializes the rest of the
chain with that version, and the initialize response that reaches the client
carries the version every component accepted. A component that cannot accept
it, such as a v2-only agent behind a v1-only proxy, rejects the
initialization, and the client sees the error.
Proxy implementations use the schema crate’s
agent_client_protocol::v2::schema::InitializeProxyRequest. Its response is
v2::schema::InitializeProxyResponse, a transparent wrapper around the v2
InitializeResponse. v1::schema::InitializeProxyRequest is the v1
type. Static conductor component providers can carry either selected
schema, but each supplied component must support that version. Use
Agent.protocol_router() or Proxy.protocol_router() when a static component
has separate implementations.
Custom InstantiateProxiesAndAgent and InstantiateProxies implementations
receive a SelectedInitializeRequest whose variant is the selected version.
An instantiator that supports only a lower version negotiates down by
returning the request for that version (for example with
SelectedInitializeRequest::into_v1, which keeps what parses under v1).
Returning the initialize request unchanged preserves its complete raw
parameters for an exact-version request, including unknown extensions.
Returning a modified typed request makes that serialized request
authoritative. The conductor sets protocolVersion to the version of the
returned variant even if an instantiator attempts to change the field, and
rejects a variant above the selected version.
MCP compatibility polyfill
The concrete
agent_client_protocol_polyfill::mcp_over_acp::McpOverAcpPolyfill can
participate in a v2 conductor chain when its unstable_protocol_v2 feature is
enabled. It selects v1 or v2 from proxy/initialize, uses that version’s MCP
capability and wire types, and adapts native McpServer::Acp declarations in
v2 session/new, session/resume, and session/fork requests.
Other declarations and unrelated request fields remain unchanged. See
MCP-over-ACP Compatibility Bridge for placement and feature
configuration.
This feature extends the concrete compatibility proxy only. The core SDK’s global MCP attachment and proxy-session helpers support v1 and v2 independently, as described above.
Version routing
The SDK handles the initialize negotiation at the JSON-RPC boundary:
- Native
Client.v2()andAgent.v2()connections reject ordinary protocol traffic until the initialization response completes.$/cancel_requestremains available while initialization is in progress. The client is the initializer and the agent is the responder. Attempts in the opposite direction are rejected. An initialization error leaves the connection uninitialized so the client can retry. A secondinitializewhile one is in flight is rejected with-32600. - The client may repeat
initializeafter the previous one completed and before it sends any other request, for example to resend its parameters for the version the agent selected. The agent dispatches each repeat to its initialize handler and the latest one is authoritative. While a repeat is in flight, other requests are rejected as they are during the first. Each repeat is negotiated like the firstinitialize: a v2 agent selects v2 for a request for v2 or newer, and answers a request below v2 with-32022anddata: { "requested", "supported": [2] }. A repeat that fails, whether rejected by the SDK or by the handler, keeps the previous initialization in place and the client may repeat again. The first other request closes this window: a laterinitializeis rejected with-32600on both sides and the connection stays ready. Notifications such as$/cancel_requestdo not close it. - V2 request ids must be strings or integers. A v2 connection answers a request
with a
nullid with-32600andid: null. V1 connections still acceptnullids. - Since schema 1.13, v2 has its own
v2::schema::RequestIdwithout aNullvariant. Request handles carry a protocol marker as their last type parameter:Responder<T, V2>,ResponseRouter<T, V2>,SentRequest<T, V2>,PreparedRequest<T, V2>andDispatch<Req, Notif, V2>, namedv2::Responder<T>,v2::ResponseRouter<T>,v2::SentRequest<T>,v2::PreparedRequest<T>andv2::Dispatch<Req, Notif>. Handles fromClient.v2(),Agent.v2(),Proxy.v2()andv2::ConnectionTouseV2, so theirid()returns av2::schema::RequestId, for example to match an elicitation’srequestId. It never fails, because the SDK rejectsnullIDs on v2 connections and never assignsnullitself. v1 builders useV1. Low-levelHandleDispatchFromandMatchDispatchhandlers are not tied to a version: they receive handles with the defaultRawmarker, whoseid()is the version-neutralRawJsonRpcId. Convert one to a v2 handle withinto_protocol::<V2>(), for example to callon_proxy_session_startfrom a raw router. Every handle also hasraw_id(). - Closures registered on a v2 builder that spell out the responder type need
the v2 handle:
responder: v2::Responder<schema::PromptResponse>withuse agent_client_protocol::v2::{self, schema}(orResponder<schema::PromptResponse, V2>). Unannotated closure parameters are inferred. - A v2 client advertises protocol v2 as its latest supported version.
- A v2 client requires a v2 agent. Send initialization with
send_initializeto learn how the agent negotiated: it resolves withv2::InitializeOutcome::Initializedfor a v2 selection, orv2::InitializeOutcome::LowerVersionwith the agent’s validated response for the selected version, anInitializationVersionMismatchwhoseresponseis aSelectedInitializeResponse::V1. Both types are at the crate root because they are not tied to one protocol version. TheInitializedandV1variants each hold a boxedInitializeResponsefrom the selected schema. Read its fields directly, or use*responseto take the owned response out of the box. After a lower selection the connection stays uninitialized, and the caller can explicitly fall back to a v1 client implementation if that is acceptable. Errors returned by the agent, including-32022, malformed responses, and transport failures still resolve with errors. A plainsend_requestof the initialize request instead resolves a v1 selection with a local error. - A native v1 agent selects v1 for requests advertising v1 or a newer version,
with or without
unstable_protocol_v2enabled. Newer initialization metadata is normalized into v1 identity and shared capabilities. Terminal authentication is kept: an object-valuedauth.terminalbecomes v1’sauth.terminal: true. Elicitation capabilities and an object_metaare kept when they parse under v1. The SDK never enables v1 file-system or terminal-execution capabilities from unknown newer fields. V1’s original fallback-to-latest rule is retained, including a v1 selection when the client requests an unsupported older version. - A v1 agent that registers a typed
initializerequest handler rejects any other request that arrives before initialization completes with-32600. Agents without one, including those with only catch-all handlers, keep serving requests without initialization. V1 agents still accept a repeatedinitializeat any time. - A standalone v2 agent accepts a request for v2 or a newer version and
selects v2. The request delivered to the handler has
protocol_versionnormalized to v2, and the response selects v2. A request for exactly v2 must be a valid v2 request. A request for a newer version was written for a version the agent doesn’t know, so the SDK keeps what parses under v2 instead of rejecting it: capabilities that don’t parse and a_metathat is not an object are dropped, fields v2 doesn’t define are dropped, and a missing or malformedinfois replaced by an implementation namedunknownwith versionunknown. A v1 agent downgrading a newer request applies the same rule to v1’s shape, leaving its optionalclientInfounset instead. If a client initializes with v1, the request resolves with-32022(Unsupported protocol version) anddata: { "requested": 1, "supported": [2] }. The v2 initialization handler is not invoked. Use an agent router with a v1 implementation to serve v1 sessions. - If the agent responds with any other unsupported version, the request resolves with an error so the client can close the connection.
- After initialization, the local API version and negotiated wire version must match. The SDK does not convert traffic between v1 and v2.
That means v1 and v2 implementations still need separate handlers.
Agent.v2(), Client.v2(), and Proxy.v2() are v2-only. While protocol v2
stabilizes, the unstable_protocol_v2 crate feature also exposes
Agent.protocol_router(), Proxy.protocol_router(), and
Client.protocol_connector() for composing version-specific implementations.
Keep these protocol handlers as adapters around shared application logic, not as general-purpose conversions between wire types. In particular, v1 prompt responses end a turn, while v2 prompt responses acknowledge insertion and completion arrives through session state updates. Shared storage also does not automatically make sessions resumable through both versions. See the protocol’s dual-stack migration guidance for adapter boundaries and a validation checklist.
Agents can add protocol implementations independently, which makes it easy for applications built with v2 support to control v2 rollout with a runtime feature flag:
#![allow(unused)]
fn main() {
use agent_client_protocol::{v1, v2};
use agent_client_protocol::{Agent, ConnectTo};
fn implementation() -> v2::schema::Implementation {
v2::schema::Implementation::new("example", "0.1.0")
}
async fn serve(client_transport: impl agent_client_protocol::ConnectTo<Agent>) -> agent_client_protocol::Result<()> {
let enable_protocol_v2 = true;
let v1_agent = Agent.v1().on_receive_request(
async |initialize: v1::schema::InitializeRequest, responder, _cx| {
responder.respond(v1::schema::InitializeResponse::new(initialize.protocol_version))
},
agent_client_protocol::on_receive_request!(),
);
let agent = Agent.protocol_router().with_v1(v1_agent);
let agent = if enable_protocol_v2 {
let v2_agent = Agent.v2().on_receive_request(
async |initialize: v2::schema::InitializeRequest, responder, _cx| {
responder.respond(v2::schema::InitializeResponse::new(
initialize.protocol_version,
implementation(),
))
},
agent_client_protocol::on_receive_request!(),
);
agent.with_v2(v2_agent)
} else {
agent
};
agent
.connect_to(client_transport)
.await?;
Ok(())
}
}
The agent protocol router reads the initial initialize request and selects
a version-specific implementation. A request for v2 or a newer version selects
the v2 implementation. When a v1 implementation is configured, everything else
is handed to it unchanged: a request for v1 or an older version, a malformed
initialize, and any other first message. A v1 client therefore sees exactly
the v1 implementation, including v1’s original fallback-to-latest rule, as it
would without unstable_protocol_v2. A v2-only endpoint rejects a request
below v2 with a structured version-mismatch error. The router
normalizes a v2 initialize request when selecting a v1 implementation, but does
not convert messages between v1 and v2 after routing. The selected
implementation owns the connection: a repeated initialize is forwarded to it
and never re-routed, so it is negotiated like a first initialize against the
selected version alone. A v2 implementation answers a repeat that requests v1
with -32022 listing only v2, because the connection cannot switch to the v1
API, and the v2 initialization stays in effect. A v1 implementation selects v1
for a repeat that requests a newer version. The
router preserves the complete initial frame when handing it to the selected
implementation. A batched first initialize gets one -32600 error with
id: null, and the client may send initialize again. Response-only frames
before initialization are ignored.
Version mismatch errors
A v2-only endpoint rejects a v1 request without requiring v2’s Client identity
or manufacturing a higher-version success response. The error code is
-32022, and its data contains requested and the endpoint’s supported
versions. This diagnostic is separate from malformed initialization parameters,
which remain -32602. The router answers with the request’s ID and does not
start an application. A failed initialize leaves the connection
uninitialized and open, so the client may send initialize again, for
example with a supported version or corrected parameters. Notifications that
arrive before initialization are ignored. The proxy protocol router, whose
proxy/initialize comes from the conductor, also answers a version mismatch
with -32022 but closes after a rejection.
Custom endpoints can construct the same wire error with
v2::schema::Error::unsupported_protocol_version(requested, supported).into().
The code is defined by v2 negotiation, not by a change to the v1 protocol.
The SDK’s version-neutral Error carries any numeric code, so a v1 client
receives the initialization error as an unknown code without new v1 schema
definitions.
just test runs the negotiation tests in both the all-features workspace and
the core crate without default features, so v1 negotiation does not depend on
whether the draft v2 API is compiled in.
Clients that cannot use any supported version should close after a version mismatch and display the supported versions. A successful downgrade must also be checked against the Client’s actual supported versions, because advertising a latest version does not imply support for every older version.
Proxy and client routing
The proxy protocol router negotiates proxy/initialize like the agent
protocol router negotiates initialize: it selects the highest configured
version at or below the requested one, rewrites a request for a newer version
to keep what parses under the selected one, and hands the initial frame to
that implementation. A request for exactly the selected version is validated
and handed over unchanged.
Clients use a connector because fallback may require opening a new transport. Both client implementations and the agent transport are factories:
use agent_client_protocol::Client;
let connector = Client
.protocol_connector()
.with_v1(|| v1_client())
.with_v2(|| v2_client());
connector.connect_to(|| open_agent_transport()).await?;
The connector starts the highest configured implementation. If a successful v2 initialize response negotiates v1 and a v1 implementation is configured, the connector starts the v1 implementation and compares the complete initialize parameters it would send with the normalized v2 request already seen by the agent:
- If they match exactly, the connector reuses the current agent connection and delivers the original response to the v1 implementation with its request ID. It does not send a second initialize request.
- If they differ, the connector closes that connection, calls both factories again as needed, and performs a fresh v1 initialization on a new agent connection. The protocol permits requesting the lower selected version in that initialization.
- If the agent rejects the v2 initialize request, the error is surfaced. A rejected initialize is not treated as permission to retry with v1.
The reuse probe is conservative: if parsing and serializing the raw v2 request would change any parameter, reuse is disabled and fallback opens a fresh connection. That does not turn an otherwise valid v2 request into an error.
Schema changes in schema 1.5 through 1.22
The unstable_protocol_v2 API follows the v2 schema as it changes. Schema 1.5 added
semantic newtypes for paths, media types, IDs, and cursors, renamed
DiffPatch.diff to DiffPatch.text, and added terminal state and output update
types. Schema 1.7 removed the former schema-wide v1/v2 conversion API:
versioned implementations should remain separate, with
purpose-specific adapters at runtime boundaries where the required state and
policy are available. These are draft API changes rather than stable v1 wire
changes. See Migrating to
v2.0 for concrete source changes.
Schema 1.6 adds Cancelled tool-call and plan-entry statuses to draft v2.
Schema 1.7 stabilizes elicitation and terminal authentication, so neither
surface requires its former SDK feature flag. It also adds context compaction
updates (stable since schema 1.11). The SDK carries them through its
existing typed session/update routing in both protocol versions. V1 clients
advertise compaction support through ClientSessionCapabilities::compaction.
Schema 1.8 stabilizes optional programmatic tool-call names in both protocol
versions. No tool-name-specific feature is required. Draft v2 users only need
unstable_protocol_v2. In v1, an omitted or null name leaves the existing
value unchanged on updates. In v2, omission leaves it unchanged, null clears
it, and a string replaces it. V1 cannot express the explicit v2 null clear
operation.
Schema 1.11 stabilizes session notices and compaction. No surface-specific
feature is required. Draft v2 users still need unstable_protocol_v2.
In draft v2, failures after a prompt’s user message is inserted end active work
with StopReason::Error(ErrorStopReason) on the idle state update, optionally
including a JSON-RPC error object. Failures before insertion remain error
responses to session/prompt. StopReason now serializes as an object tagged
by stopReason, flattened into IdleStateUpdate. Its Other variant takes
OtherStopReason rather than a string and preserves unknown payload fields.
V1 prompt responses are unchanged and do not accept an error stop reason.
Schema 1.11 also rejects malformed payloads that receivers act on rather than
silently dropping invalid entries or substituting defaults. This includes
session setup’s MCP servers and additional directories, terminal launch
arguments and environment, and v2 replay cursors. Typed request decoding
reports invalid parameters (-32602) without invoking the handler. null
still means empty for the defaultable acted-on lists. Omission is accepted
only where the field is optional. Capability and display metadata retain their
lenient decoding.
Schema 1.12
Client-provided system prompts were added behind the
unstable_session_system_prompt feature. Schema 1.16 stabilizes them and the
feature has been removed. Use the complete lifecycle request with _from
helpers and negotiate the agent’s capability first; see
Client-provided system prompts.
Next Edit Suggestions, their document events, and their position-encoding
capabilities have been removed from both protocol versions.
Foreground states are aggregate snapshots, not per-prompt events:
- Report
runningwhen work starts, orrequires_actionif it starts blocked on user action. Agent-initiated workflows and local commands use the same lifecycle without needing a model call or a synthetic user prompt. requires_actionmeans the foreground workflow as a whole is blocked. A pending permission or elicitation does not imply this state while other foreground work can progress or when it belongs to background activity. Once reported, sendrunningwhen progress resumes oridlewhen work ends.- When no foreground work remains, report
idle; normally include a stop reason. Repeated snapshots, including an old stop reason, are idempotent, not additional completions, cancellations, or token usage. - New sessions default to idle, but updates can precede the new-session response. Do not overwrite them with idle when that response arrives.
- Every successful resume must send a current-state snapshot after any replay
and its
replay_complete, and before its response, even without a replay cursor. Do not replay historical states as live activity or reset state to idle on the response. Testy and the echo example only resume sessions without foreground work, so their snapshot is idle without a new stop reason. - A resume must also return the session’s current
configOptionsand available commands in its response when it has any, because the response replaces the client’s lists. It should send current session info throughsession_info_updateafter any replay and before responding. Like the state snapshot, this synchronizes current state rather than replaying historical configuration or metadata changes.
Prompt acceptance means logical user-message insertion with an ID and a
position, not receipt or queueing. Running may precede insertion. Rejection
before insertion requires an error response and no user-message updates for
that submission; it does not alone end foreground work. A pre-insertion
foreground failure can also require an error idle update. After insertion,
the response stays successful and failure is reported on idle instead.
This includes authentication failures: after insertion, -32000
(Authentication required) belongs in the error stop reason, not an error
prompt response.
Authenticating again does not restart ended work, and automatically retrying
an inserted prompt would insert another message and could repeat side effects.
When closing cancels active work, final updates and idle with cancelled
precede the close response. An uninserted prompt cancelled by close gets
-32800; an inserted one still gets its successful message ID.
On session/cancel, the agent must stop waiting for the pending
session/request_permission requests of the cancelled foreground work and
treat them as not approved. It must cancel each of them with
$/cancel_request (a recommendation before schema 1.19): call
SentRequest::cancel or RequestCancellationHandle::cancel, or drop the
SentRequest, which sends $/cancel_request and discards the late answer.
The agent decides which requests belong to the cancelled work. Requests for
work in the latest background list are not affected. Before responding to
session/close, the agent must cancel every pending permission request and
elicitation in the session with $/cancel_request. Protocol v1 is unchanged:
there the client must answer every pending permission request with
cancelled when it sends session/cancel.
Agents reject unsupported replay cursor types with -32602, rather than
substituting another cursor. Retained user messages preserve the prompt
response’s ID across replay. Agent and thought message IDs may change across
reconnections, so do not deduplicate a replay against history you already
hold by ID. A client can rebuild its transcript from a full replay, which
holds the history the agent retained and not necessarily everything the client
saw live. A chunk replay’s empty-content primer clears only its replay ID.
Since schema 1.19 the primer applies to every entity replayed as chunks, not
only to messages (see Schema 1.19).
Top-level _meta on upsert updates patches stored metadata by key: omission
leaves it unchanged, null clears it, and an object preserves omitted keys,
removes keys whose values are null, and replaces each other value whole.
Nested objects are not merged; nested nulls are ordinary data. An empty object
does not clear metadata. Replay uses the same rules and never implicitly resets
metadata. ToolCallUpdate::apply_update and TerminalUpdate::apply_update
apply this rule; use v2::schema::apply_meta_update for application-owned
message, session, usage, compaction, or subagent projections. Metadata on chunks,
content, snapshots, and plan_update is not an entity patch.
Protocol v2 negotiation does not select every experimental feature. Operations such as provider configuration require their advertised capabilities. Informational notices, compaction, plan updates, subagent updates, and idle token usage can use their documented capability-free fallbacks; accepting an unknown variant is not a support advertisement. Unknown capability fields are ignored, while malformed known discriminators must not fall through to an unknown-variant fallback.
Client projections of tool calls and terminals should follow these rules:
tool_call_updateis an upsert keyed bytoolCallId. On an existing tool call, omission leaves a field unchanged andnullresets it to its default. A new ID starts from the defaults:kindisother,statusispending,contentandlocationsare empty, andtitle,name,rawInput, andrawOutputare unset. Show a generic title whiletitleis unset.- Treat a tool call whose
statusis unrecognized as still in progress. - A
tool_call_content_chunkfor atoolCallIdthe client has not seen creates the tool call with those defaults and then appends. Likewise aterminal_output_chunkfor an unseenterminalIdcreates the terminal with unknown fields and empty output, then appends. - Decode each terminal chunk independently and append the bytes in order.
Agents should send all output before a
concrete
exitStatus, but clients still append output that arrives after it. Clients may cap how much output they retain, for example by dropping the oldest bytes; a lateroutputsnapshot replaces whatever they kept. - In a diff,
changesis authoritative for affected paths and operations. Followchangeswhenpatchdisagrees with it, and handle diffs without apatch.
For v2 git_patch diffs, every path must be absolute and have no a/ or b/
prefix, including rename/copy header paths. Git quoting and /dev/null for
an added/deleted file’s missing side still apply. Configure diff parsers not to
strip a leading path component, since that would drop part of an absolute
path, and take paths from changes or from the ---, +++, rename, and copy
lines rather than by splitting the diff --git header. The SDK carries patch
text; it does not rewrite paths or compute diffs from snippets.
Schema 1.13
Draft v2 type changes:
- v2 has its own
RequestId,Request, andResponsetypes. Request IDs are a string or an integer, nevernull; error responses may still usenullwhen the request ID could not be determined. AvailableCommandis atype-tagged union. Build commands withAvailableCommand::Command(Command::new(..))and read them throughname(),description(), andmeta(). Unknown command kinds parse asOther. Ignore them, and do not show them as slash commands. Schema 1.13 allowed showing them as plain commands. Schema 1.18 forbids it, because each command type defines how its entries are invoked.ToolCallLocation.lineis a 1-basedNonZeroU32. The builder still takes au32and treats0as no line.TerminalExitStatus.exit_codeis ani64holding the code the platform reports, so negative codes such as Windows NTSTATUS values survive.ResourceLink.sizeis au64byte count; a negative value parses as unknown.terminal_updatehas an optionalsizewithcolsandrows, patched like the other terminal fields. Clients should render the output at that size when it is present.RequestPermissionOutcome::Cancelledcarries aCancelledPermissionOutcomewith optional_meta;{"outcome": "cancelled"}still parses.AuthCapabilitiesis nowClientAuthCapabilities.DiffPatch,ToolCallPermissionSubject, andIcongain a_metafield (meta).- Unknown variants keep their optional fields verbatim in
fields.
v2::SessionBuilder::with_mcp_server, v2::ResumeSessionBuilder::with_mcp_server,
v2::ForkSessionBuilder::with_mcp_server, and Proxy.v2().with_mcp_server
declare an McpServer::Acp server. The agent must advertise
session.mcp.acp to accept it; otherwise a conforming agent rejects the setup
request with -32602. When the downstream agent only supports another MCP
transport, place a compatibility proxy such as McpOverAcpPolyfill in front of
it. The SDK does not check the agent’s capability before sending the
declaration.
Client projections should also follow these rules:
- A
state_updatewith an unrecognized state never means idle. Show a generic busy state until a known state arrives. - An update or chunk for an unseen message ID creates the message. Its first update or chunk fixes its timeline position; later updates patch it in place, even after idle. Updates for different entities may interleave, and a new ID does not end any other entity.
- Show an unrecognized tool
kindasother. - A
tool_callpermission subject applies to the stored tool call exactly like atool_call_update, in the order received and before the prompt is shown. A first-seentoolCallIdcreates the tool call. - The Agent owns remembered
allow_alwaysandreject_alwaysdecisions and their scope. Clients do not infer that scope from the option kind.
Schema 1.14
Draft v2 type changes:
- JSON-RPC batching is removed from v2, and
v2::schema::JsonRpcBatchno longer exists. The SDK dropped batch support in both protocol versions: every connection answers a JSON array with a single-32600error withid: null(see JSON-RPC batches). Error.datais typed asErrorData:UnsupportedProtocolVersionErrorDatafor-32022,SessionNotFoundErrorDatafor-32002, or any other JSON.v2::Error::resource_not_found()no longer takes auri; usesession_not_found(session_id)for a missing session.v2::Error::unsupported_protocol_versionbuilds the typed data; convert either into the SDK’sErrorwith.into(). An error response’sidmay benull.UsageUpdate.costis aMaybeUndefined<Cost>patch field: omitted leaves the cost unchanged,nullclears it, and a value replaces it.Cost.currencyis any unit string, not only an ISO 4217 code.ElicitationContentValue::Otherholds any JSON value, such as the value of a custom or future property type. Validate accepted content against the requested schema yourself.ElicitationSchemarequirestype: "object"andpropertieson the wire.PromptRequest.promptmust not be empty, and select config options and option groups must not be empty.SessionInfo.additionalDirectoriestreatsnullas[], andAnnotations.lastModifiedaccepts any ISO 8601 string.- Subagent updates gain
cwdandadditional_directoriespatch fields (absolute paths; omitted leaves them unchanged,nullinherits the parent’s). They neededunstable_subagentsuntil schema 1.18.
Connection and lifecycle rules:
- A failed
initializeleaves the connection uninitialized, and the client may sendinitializeagain.Agent.protocol_router()now keeps the connection open after rejecting a first message. Agents ignore notifications that arrive before initialization. - Each side picks its own request IDs, so the same ID may be in flight in both
directions.
$/cancel_requestnames a request its sender issued, and is ignored for unknown or already-answered requests. Unknown notifications, including$/-prefixed ones, are ignored. A connection’s end fails its unanswered outgoing requests. session/closeis idempotent: closing an unknown or already-closed session succeeds.v2::ActiveSession::closetreats a-32002response as success, and Testy andsimple_agent_v2close idempotently.- Closing cancels the session’s work like
session/cancel, cancels pending elicitations scoped to it, and answers held prompts with-32800. After the close response the agent sends no notifications or requests for that session, but it still answerssession/promptrequests that were pending. Deleting a session first cancels its work and frees its resources, as if it had been closed when it is active. cwdmust be absolute in the native syntax of the agent’s machine, and agents reject a relativecwdinsession/new,session/resume, and thesession/listfilter with-32602. That filter matches only the exact directory. Agents that advertiseadditionalDirectoriesreject relative entries; agents that do not ignore the field. Testy andsimple_agent_v2follow these rules.- MCP server names must be unique within
mcpServers, and agents reject duplicates with-32602. The v2with_mcp_serverbuilders fail with-32602instead of declaring a server whose name is already in the request. Onsession/resumeandsession/fork,mcpServersis the complete set for the session; agents do not restore servers from earlier requests. A resume must use the session’scwd. session/new,session/resume, andsession/forkresponses carry the completeconfigOptionsand available commands when the session has any. Clients replace their lists with them, including lists from updates that arrived before the response.- An empty-string
nextCursorfromsession/listis a valid cursor; only an omitted ornullcursor ends the results.
Client projections should also follow these rules:
- A
plan_updatereplaces the whole plan with thatplanId, even when itstypechanged to one the client does not understand. - A
cancelledpermission outcome, or aselectedoutcome whoseoptionIdwas not offered, means not approved. Clients sendcancelledwhen the user dismisses the request or the client declines it by policy. completed,failed, andcancelledtool call statuses are final, and agents finalize unfinished tool calls when foreground work ends.- A prompt invokes a slash command only when its first text block starts with
/and the command name followed by whitespace or the end of the block. This applies tocommandentries only. - Show a placeholder for content you cannot render rather than dropping it.
- A terminal’s
sizeis a rendering hint. _metakeystraceparent,tracestate, andbaggageuse the W3C formats; extensions use reverse-DNS prefixes such ascom.example/requestId.
Schema 1.18
Draft v2 type changes:
SessionUpdate::ReplayCompletemarks the end of the history replay that asession/resumerequest asked for.ReplayCompletehas only an optional_meta.- Subagents are part of v2 and no longer need
unstable_subagents:SessionUpdate::SubagentUpdate,SessionUpdate::SessionMessage,SessionUpdate::SessionMessageChunk,StateUpdate::Unknown,BackgroundWork::Subagent, andToolCallContent::Sessionare always available. These wire values used to parse asOtherwithout the feature and now parse as their typed variants, so add match arms where you relied on the fallback. v1 neededunstable_subagentsuntil schema 1.20. - The
fileplan type is removed (plan operations neededunstable_plan_operationsuntil schema 1.20):PlanUpdateContent::File,PlanFile, andPlanUpdateContent::fileno longer exist, and a receivedfileplan parses asPlanUpdateContent::Other.PlanMarkdowngains an optionalpath, the absolute path of the file that holds the plan. Build it withPlanUpdateContent::Markdown(PlanMarkdown::new(..).path(..)). - With
unstable_agent_skills,AvailableCommand::Skilladvertises an Agent Skill andContentBlock::Skill(SkillReference) invokes one in a prompt. The agent advertisesPromptCapabilities::skill, and the client advertisessession.commands.skill. - With
unstable_prompt_suggestions,SessionUpdate::PromptSuggestionsUpdatereplaces the session’s list of prompts the agent predicts the user will send next. The client advertisessession.promptSuggestions. ClientCapabilities::session(ClientSessionCapabilities) exists with either of those two features. It only groups capabilities:{}advertises nothing.- With
unstable_speed_config_category,SessionConfigOptionCategory::Speedmarks a response speed option such as a fast mode toggle. - With
unstable_session_forkandunstable_session_options,ForkSessionRequest::config_optionscarries initial config option values. The entries apply on top of the configuration the fork would start with.
Agents must follow these replay rules:
- For a
session/resumerequest with areplayFromcursor, sendreplay_completeexactly once on the session, after the last replayed update and before current-state synchronization and the response. Send it for an empty replay too. - Do not send it when
replayFromis omitted ornull, forsession/new, when the cursor is rejected with-32602, or when the replay cannot finish. - From the time you receive the request until you send
replay_complete, every update you send for the session must be replayed history. Hold everything else until after it: chunks of a message that is still streaming, notices,available_commands_update,config_option_update, and the current session info and state snapshots. Permission requests and elicitations should wait too. - Each child session announced with
subagent_updateduring the resume gets its ownreplay_completeon its ownsessionId, after its last replayed update. The markers of different sessions have no required order. replay_completedoes not make the session active. A session that was not active before the request becomes active with the successful response, sosession/promptfails with-32002until then.- Report known gaps in the retained history after
replay_complete, for example with a notice.
Testy and simple_agent_v2 follow these rules.
Other agent rules:
auth/logoutis idempotent. Respond with the same empty result when there is no authenticated state to end.- Answer a repeated
tool_call/cancelorterminal/cancelwith-32602once the tool call is final or the terminal has exited. Thetool_call_updateorterminal_updatereports the outcome. - List the values of a
selectthought_leveloption from lowest to highest, and of aselectspeedoption from slowest to fastest. In abooleanspeedoption,trueis the faster setting. contentontool_call_updatereplaces the whole array, so send thesessionreferences again when you send new content. Add a reference only for a handle you can resolve to a known session.- Omit
senderSessionIdon a session-directed message when you have no evidence of who sent it. Do not assume the parent. - Report
unknownon an actual loss of observability, not after silence. Leave unfinished tool calls and terminals as last reported, and update capabilities explicitly when a control is no longer available. - Send
skillcommand entries only to a client that advertisessession.commands.skill, and advertisesession.prompt.skillwhen you do. Reject a prompt with askillblock that your capability does not allow, or whosenameyou cannot resolve, with-32602and without inserting it. - Send
prompt_suggestions_updateonly to a client that advertisessession.promptSuggestions. When you accept asession/prompt, replace a non-empty list or withdraw it with an empty one. Do not replay suggestions. - While applying initial
configOptions, do not sendconfig_option_updatefor them on the requesting connection, and send other updates they cause only after thesession/neworsession/forkresponse. A resumed session that is active on other connections does getconfig_option_updatethere. session/optionsmay start the agent’s runtime to resolve the options. It still stores no session and writes no history.
Client projections should also follow these rules:
- Use
replay_completeto find the end of the replay you requested. Every update for the session after it is not history. Sendingsession/resumedoes not mark the start of the replay: when the session is already active on the connection, a live update the agent sent before it received the request can still arrive beforereplay_complete. A resume that ends in an error response or a closed connection withoutreplay_completedelivered a truncated replay. Do not treat those updates as a complete replay. A successful response withoutreplay_completeis a protocol violation, but the response still confirms that the requested replay finished. - Ignore command types you do not understand, and never show them as slash
commands. The
/namesyntax invokescommandentries only. Invoke a skill with askillcontent block, and only where the agent’ssession.prompt.skillcapability allows it: one leading block, or any number at any position withinline. - On
unknown, stop presenting a previousrunningorrequires_actionas confirmed live activity. It is notidle, not an outcome, and not a cancellation. A later known state replaces it. - Session-directed messages are agent content. Attribute them to the sending session and do not present them as user messages.
- Render a markdown plan from
content. Usepathonly to open the file, and do not read apathoutside the session’s roots without user action. - Skip a whole prompt suggestion you cannot use rather than dropping one of its blocks. Never send a suggestion as a prompt without an explicit user action.
- Render
speedoptions near the model selector. - Do not call
session/optionson a timer.
Schema 1.19
Type changes:
PromptRequest::idempotency_key(idempotencyKey) identifies onesession/promptsubmission across attempts.IdempotencyKeyis an opaque, case-sensitive string of 1 to 255 characters.IdempotencyKey::newand deserialization reject any other value, so a typed handler never sees a malformed key: the SDK answers that request with-32602.unstable_protocol_v2also enablesIdempotencyKey::generate, which creates a key from a random UUID.StringPropertySchema::patternis removed from draft v2. A string property in an elicitation form takesminLength,maxLength,format, anddefault. Apatternon a received form is ignored and not kept. v1 keepspattern.Diff.changeshasminItems: 1in the JSON Schema. The SDK still parses an empty list.- With
unstable_session_cursors,SessionUpdate::CursorUpdateannounces a session cursor: one position in the session’s timeline where the client can run a method.CursorUpdatecarries aCursorId, aCursorCapabilitiespatch, and aCursorAnchorthat names a message, tool call, or compaction and the side of it the cursor is on. Withunstable_session_forkas well,ForkSessionRequest::cursor_idforks the session at a cursor that advertisescapabilities.fork. Both exist in v1 and draft v2. v1 clients opt in withClientSessionCapabilities::cursors. Draft v2 needs no capability, and without the featurecursor_updateparses asSessionUpdate::Other. - The schema’s aggregate enums (
ClientRequest,AgentResponse,AgentNotificationand the others, in both versions) gainfrom_method_and_params,from_method_and_result, andsupports_method, withschema::MethodDispatchErroras their error. They select the payload type from the JSON-RPC method. SDK connections already parse messages by method throughJsonRpcMessage::parse_message, so these are for code that parses messages without a connection. Do not deserialize an aggregate enum directly: its untaggedDeserializeselects a variant by payload shape.
Agents must follow these session/prompt retry rules:
- Support
idempotencyKeywhen you advertisecapabilities.session. There is no separate capability. - Look the key up in the session named by
sessionId. With nothing recorded, handle the prompt as usual and record the key in the same step as the inserted user message. - For a key recorded with an inserted message, insert nothing, start no second
round of work, and respond with that message’s
messageId. - For a key whose prompt is not inserted yet, such as a held prompt, do not hold a second prompt. Answer the retry when you answer the first request, with the same outcome.
- An error response means the message was not inserted. Record nothing, so the client can send the same prompt with the same key again.
- If you honor
$/cancel_requestfor any pending request with a key, withdraw the prompt if it is not inserted yet and answer every pending request for that key with-32800. - A key is scoped to its session. The same key in another session, including
one that
session/forkcreated from this one, names an unrelated submission. - Never insert a second message for a recorded key. A request that reuses a
recorded key with a different prompt is answered as a retry, or rejected
with
-32602if you compare prompts. Comparing is optional. - Recognize a key for as long as you retain its message, across connections and restarts. For a message you do not retain, recognize the key while the session stays active on a connection.
- Do not echo keys in session updates,
session/listresults, or replayed history. A proxy forwardsidempotencyKeyunchanged.
Testy and simple_agent_v2 follow these rules. They do not compare prompts.
Other agent rules:
- Include the session’s
configOptionsandavailableCommandsin thesession/newandsession/resumeresponses when the lists are nonempty. If a new session is not idle, send itsstate_updateafter thesession/newresponse. - If the agent cannot apply a supplied
systemPromptbecause the value is unsupported or exceeds its limits, answer-32602without creating or resuming the session. session/cancelandsession/closedrop the prompts you have received and not inserted. Answer each with-32800. Honoring$/cancel_requestfor a held prompt is optional: either answer-32800and do not insert the message, or insert it as usual. When the connection ends, you may insert or discard the prompts you were holding.- Cancel each permission request and elicitation you stop waiting for after
session/cancelwith$/cancel_request. This is now required. - Before you replay an entity from its beginning as chunks, send that entity’s
update with the chunked field emptied:
content: []on the message update for message and session-directed message chunks,content: []ontool_call_updatefortool_call_content_chunk,output: { "data": "" }onterminal_updateforterminal_output_chunk, andsummary: []oncompaction_updateforcompaction_summary_chunk. An entity you replay without chunks needs no such update. - A resume without
replayFromsynchronizes the session’s state, not its conversation. Send the currentstate_update, and before it a currentterminal_update,tool_call_update, orsubagent_updatefor each item in itsbackgroundlist. You are not required to resend foreground work in progress. - Do not move a tool call back to
pending, also not with"status": null.completed,failed, andcancelledare final. Report further work on a new tool call. - Include at least one entry in a diff’s
changes. - Do not send
patternon string properties. Validate the submitted value yourself. - A child session you announced with
subagent_updateis not an unknown session.session/cancel,tool_call/cancel, andterminal/cancelcan name a child where its capabilities allow. Reject any other request that names a child with-32602. Do not return child sessions fromsession/list. Closing a session also stops its child sessions, at any depth. - The
capabilitiesandstatein a replayedsubagent_updateare historical. After a replay, send a currentsubagent_updatefor each child in thebackgroundlist after the parent’sreplay_complete. - A session’s
costincludes the costs of its descendants. - Announce a session cursor only for a position where at least one method
works, and only after the entity it is anchored to. Never change a cursor’s
anchor. Reject a
cursorIdyou did not issue for that session, no longer accept, or that does not support the method with-32602. Never act at another position and never fork the whole session instead. In v1, sendcursor_updateonly to a client that advertisessession.cursors, and send amessageIdon every message you anchor to.
Client projections should also follow these rules:
- To let the agent recognize a retry of a prompt whose response was lost, send
the prompt with
send_prompt_blocks_with_key. Create one key per submission when the user submits the input, and store it with the pending input. Use a new key for a new submission, and never send a key with a different prompt. On a new connection, callinitializeandsession/resumebefore you retry. Schema 1.20 changed what a client does next: see Schema 1.20. - Without a key, or with a key the agent has forgotten, a
session/promptsent again can insert a second user message.auth/login,auth/logout,session/resume,session/set_config_option,session/list,session/close,session/delete,tool_call/cancel, andterminal/cancelcan be sent again as they are. A secondsession/newcreates a second session. Do not sendsession/cancelagain later: a later copy can cancel newer foreground work or a newly held prompt. Retrysession/set_config_optionbefore you send further changes, because a retry sent after a later change to the same option overwrites it. Treat-32002fromsession/deleteas a successful delete. Atool_call/cancelorterminal/cancelretry gets-32602once the tool call is final or the terminal has exited. See Retrying requests. - When
$/cancel_requestarrives for asession/request_permissionorelicitation/createrequest you have not answered, dismiss the prompt and answer with thecancelledoutcome or thecancelaction. Observe it withResponder::cancellation. A responder dropped after the cancellation answers-32800instead. Also dismiss permission and elicitation prompts for a session you closed. - Correlate a submitted prompt with the agent’s
user_messageby the response’smessageId, not by content. The agent owns the inserted message and may report different content. The client may display what it originally sent; replay carries the agent’s content. - A resume without
replayFromdoes not resynchronize messages or foreground tool calls. Keep the session’s entities if you missed no updates, and request replay otherwise, for example after a lost connection. - Tool call
content, terminaloutput, and compactionsummaryfollow the same order as message content: an update that carries the field replaces what the chunks accumulated, and later chunks append to it. - Show the status from the latest
tool_call_updateyou received. refusalonly reports that the agent refused to continue. Do not remove or mark the user’s message because of it. The v1 stop reason still means that the prompt and everything after it are left out of the next prompt.- Do not evaluate
patternon string properties. - Register the child session that a
subagent_updateannounces, and attribute updates and requests with itssessionIdto it. Send nothing for a child except responses to its requests,session/cancelwhile the child advertisescapabilities.cancel, andtool_call/cancelorterminal/cancelfor an item that advertises its own. When you resume the parent, discard the child state and capabilities you held and wait for current ones: asubagent_updatebefore the parent’sreplay_completecarries historicalcapabilitiesandstate. A permission request or elicitation can name a child session, so do not sendsession/cancelfor the session a request names unless it is a session you created or a child that advertisescapabilities.cancel. - A session’s
costalready includes the costs of its descendants. Do not add a child session’s cost to an ancestor’s. A child without a reported cost has an unknown cost, not zero. Context window usage belongs to each session and is not summed. See Subagents for the other client rules: the patch semantics ofsubagent_update, inherited working directories, read-only child configuration, session-directed messages, and what to show after the connection ends. - Build cursors from
cursor_updatebycursorId. Pass a cursor to a method only when the agent announced it on that session and it currently advertises that method’s capability, and pass thecursorId, never the anchored entity’s ID. Do not guess a place for a cursor whose anchor you do not hold or do not recognize. A full replay rebuilds the session’s cursors, so discard the ones you held. A forked session does not inherit cursors.
Schema 1.20
ACP v2 moved from Draft to Preview with this release, and its schema is
2.0.0-beta.1. The SDK’s v2 API stays behind unstable_protocol_v2.
Type changes:
- Plan operations are stable in both protocol versions, and the
unstable_plan_operationsfeature is removed. In v2,PlanUpdateContent::Markdown,PlanMarkdown, andSessionUpdate::PlanRemovedare always available and need no client capability. Amarkdownplan and aplan_removedupdate used to parse asOtherwithout the feature and now parse as their typed variants, so add match arms where you relied on the fallback. In v1,SessionUpdate::PlanUpdate,SessionUpdate::PlanRemoved, andClientCapabilities::planneed no feature. - Subagent sessions are stable in v1, and the
unstable_subagentsfeature is removed. v2 has included them since schema 1.18. - Maps on the wire keep their key order. In v2 they are
indexmap::IndexMaps instead ofBTreeMaps: thefieldsof everyOther*variant,ElicitationSchema::properties, andElicitationAcceptAction::content.SetProviderRequest::headers(withunstable_llm_providers) was aHashMapand is anIndexMapin both versions. In v1, thefieldsofOtherStateUpdate,OtherStopReason, andOtherCursorAnchorareIndexMaps too. The other v1 maps are unchanged. Name the type asagent_client_protocol::schema::IndexMap, which the SDK re-exports since schema 1.21. Where a function takes the map directly, such asOtherMcpServer::new, an array of pairs with.into()also works.apply_meta_updatekeeps the order of the remaining keys when it removes one. CompactionUpdate::statusis aMaybeUndefined<CompactionStatus>patch field: omitted leaves the status unchanged,nullresets it toin_progress, and a value replaces it.CompactionUpdate::newtakes only the ID. Set the status withCompactionUpdate::status. v1 still requiresstatus.UsageUpdate::metais aMaybeUndefined<Meta>metadata patch, like the_metaof the other upsert updates. Apply it withapply_meta_update.TerminalSize::colsandTerminalSize::rowsareNonZeroU16. A receivedsizewith a zero is parsed as no size, and the rest of theterminal_updatestill applies.- A
RequestPermissionRequestwith an emptyoptionslist fails typed parsing. The SDK answers that request with-32602and the handler does not run. CreateElicitationRequestrejects arequestIdsent together withsessionIdortoolCallId, and anullin the scope field that is not used.MultiSelectItemsis selected bytype: the titledanyOfform has notype, and atypeof"string"needsenum.SystemPrompt.contenthasminItems: 1in the JSON Schema. The SDK still parses an empty list.- The v2 JSON Schema validates the JSON-RPC envelope by method and direction
and rejects
"params": null. The SDK omitsparamswhen a message has none. The schema also carriesx-stateandx-scopehints, which say what a message changes and which session, tool call, or request it belongs to. They add no Rust types.
Agents must follow these rules:
- When
session/cancelstops active foreground work, send that work’s pending updates and thenidlewithstopReason: "cancelled"before you start new foreground work in the session, including work you start yourself. Do not reject a prompt because cancellation is in progress. Insert and acknowledge it, or hold it with its response pending if its work would start right away. Listed background work is not covered, and its updates can follow the idle update. If the foreground work had already ended, its stop reason stands. - A
selectedpermission outcome is not approval by itself. MatchoptionIdagainst the options you offered in that request. Do not perform the operation when the option’s kind isreject_onceorreject_always, when no option matches, or when you do not understand the kind or the outcome. Neither the option’snamenor the spelling of itsoptionIdoverrides a rejection. An error response is not approval, and neither is a connection that ends before the client answers. - Reject a stdio MCP server whose
commandis not an absolute path with-32602. When a server fails to launch or connect, continue without it and tell the user, for example with a notice. - Reject a
session/closeor asession/deletethat names a child session with-32602. A child’s config options are read-only, because no child capability permitssession/set_config_option. - Give every config option a
configIdthat is unique inconfigOptions, and every group agroupIdthat is unique in its option. - Do not replay past
usage_update,session_info_update,config_option_update, oravailable_commands_updatenotifications. They describe earlier values. Synchronize the current ones instead. - During a replaying resume, hold live updates and requests for each child
you announce until that child’s
replay_complete. - Report
unknownwhenever you can no longer observe a session’s foreground work. This applies to every session, not only to child sessions. - A child session also reports
cancelledwhen its parent cancels its work. A response that arrives after work was cancelled must not permit a new task for the same child. - Return the sessions with the most recent activity first from
session/list. - Send
plan_removedwhen a plan is cancelled, for example when the user rejects it. A finished plan does not need to be removed. Thepathof a markdown plan must be absolute. - In an elicitation, omit the scope field you do not use instead of sending
null, and do not sendtoolCallIdwithrequestId. - Every authentication method carries a
type, amethodId, and aname. Theenvnames of a terminal method should be unique. Otherwise the last entry with a name wins.
Testy and simple_agent_v2 already follow the rules that apply to them. They
have no permission requests, MCP servers, config options, plans, or child
sessions.
Client projections should also follow these rules:
- A successful
session/resume, with or without replay, does not tell you whether an unanswered prompt was inserted or whether the agent kept itsidempotencyKey. If a duplicate would matter and you cannot rule one out, do not resend the prompt automatically. Tell the user that the prompt might already have run and let them decide. A retry sends the original prompt and key in a newsession/promptrequest. This replaces the earlier advice to resend a pending prompt as soon as the session is resumed. - Accept
itemsandmarkdownplans andplan_removed. Accepting a plan does not require showing it. Aplan_updatereplaces the whole plan with thatplanId. Ignore aplan_removedfor aplanIdyou do not know. - When the user picks an offered option, answer with
selectedand itsoptionId, also for a rejection. You can return the ID without interpreting the option’s kind. - Keep accepting updates after
session/cancel, including updates for surviving background work after theidleupdate withstopReason: "cancelled". To stop a listed tool call or terminal, sendtool_call/cancelorterminal/cancelwhile the item advertisescapabilities.cancel.session/cancelon a child does not stop a terminal in the child’sbackgroundlist. - Adjacent text blocks form one continuous text. Join them without a separator before rendering, in messages and in tool call content.
- Tool call titles, session titles, and the names of commands and config
options are plain text. Do not render them as Markdown. A plan entry’s
contentmay contain Markdown. As of schema 1.21.2, so may the descriptions listed under Schema 1.21. - Answer
elicitation/createwith-32602when you cannot render the form. - Follow a
nextCursorfromsession/listwith the samecwdyou sent before. - Call
auth/logoutonly when the agent advertised authentication methods. - After the agent selects a lower protocol version, you may send that
version, or a lower one you support, when you repeat
initializeor open a new connection.Client.protocol_connector()does this when it falls back.
Schema 1.21
Schema 1.21 changes Rust types, not the wire format:
-
agent_client_protocol::schema::IndexMapis the map type of the schema’s ordered maps: thefieldsof everyOther*variant,ElicitationSchema::properties,ElicitationAcceptAction::content, andSetProviderRequest::headers. The schema crate re-exports it fromindexmap, and the SDK passes it on. If you addedindexmapto your dependencies for schema 1.20 only to name this type, you can remove it.#![allow(unused)] fn main() { use agent_client_protocol::schema::IndexMap; use agent_client_protocol::v1::schema::{OtherStateUpdate, StateUpdate}; use serde_json::json; let fields = IndexMap::from([("reason".to_string(), json!("rate_limited"))]); let state = StateUpdate::Other(OtherStateUpdate::new("_paused", fields)); } -
As of 1.21.1, two preview v2 variants take boxed payloads. When constructing
v2::schema::SessionConfigOptionValue::Other(other), useSessionConfigOptionValue::from(other)instead. Forv2::schema::ToolCallContent::Diff(diff), useToolCallContent::from(diff). Both conversions accept the unboxed payload. When matching an owned variant,*otheror*diffgives you the owned payload again. The v1 types are unchanged.
Schema 1.21.2 changes one rule for clients. These description fields in
v2::schema may contain Markdown, like a text block:
- An authentication method:
AuthMethodAgent::descriptionandAuthMethodTerminal::description. - A command:
Command::description, andSkill::descriptionunderunstable_agent_skills. - A config option and each of its values:
SessionConfigOption::descriptionandSessionConfigSelectOption::description. - A permission request:
RequestPermissionRequest::description. - A subagent:
SubagentUpdate::description.
Schema 1.20 listed the descriptions of commands and config options as plain
text. A client that renders Markdown in text blocks can now render these
fields the same way. Names, titles, and every other description, such as
those in an elicitation form, are still plain text.
There are no new rules for agents. An agent can use Markdown in these fields.
Schema 1.22
Schema 1.22 adds two fields to one unstable request and makes two v1 payloads fail to parse.
With unstable_mcp_over_acp, a MessageMcpRequest can name the session and
tool call it was sent for, in v1::schema and v2::schema: session_id and
tool_call_id. Both are optional. See the RFD.
For a client or proxy that provides an MCP server:
McpRequestContext::session_id()andtool_call_id()return what the agent sent.McpConnectionToandMcpConnectionContexthave the same accessors, so atool_fnclosure can read them from its connection. An rmcpServerHandlerpassed tofrom_rmcpreads them from aMcpRequestAttribution: a parameter of a#[tool]method, orMcpRequestAttribution::of(&context)in a method it writes itself.- The SDK does not check the values. Before a tool uses the session to choose what it acts on, check that the session is active on the connection, or is a child the agent announced for an active session, and that the server was declared to it or to one of its ancestors.
- Handle
None. A request the agent sends during session setup has no session, and an agent that cannot tell which session a request belongs to omits it. - Do not reject or delay a request because you have not seen its tool call. The agent can report the call after it sends the request.
- A server that needs the session, or refuses one after its own check, rejects
the request before it runs. Add an admission check with
McpServer::with_admission. It is an async closure, passed withmcp_admission!(), that receives anMcpAdmissionand returns anMcpRejection, such asMcpRejection::session_required()fromrequire_session_id()?, orMcpRejection::session_rejected(reason). The agent receives Invalid params (-32602), and no service, connector, or tool runs. The check works for every kind of server and every method, includingtools/listandserver/discover. - A tool can state its own rule:
McpTool::admit, ortool_admissionon the rmcpMcpServerBuilderfor atool_fnortool_fn_muttool. See Rejecting a request for its session. - An error returned from
McpService::executeis still reported as a backend failure (-33002), and an error from a function tool is still a tool result withisError: true. Neither rejects a request.
For an agent that calls a server:
- Set the fields with
MessageMcpRequest::session_idandtool_call_id. Use the IDs you send onsession/updatefor that work. A child session’s request carries the child’s ID. - Omit a value you do not know. Do not send the root session’s ID or the
latest tool call’s ID in its place, and do not send
tool_call_idwithoutsession_id. - Report the tool call before you send the request that names it, when you can.
- The MCP polyfill’s HTTP bridge sends neither field. An MCP HTTP request does not say which session or tool call it belongs to.
Two malformed v1 payloads no longer parse, so an agent built on the SDK answers
Invalid params (-32602) instead of acting on them:
- An MCP server whose
typeishttporsseand that fails that transport’s schema. It was read as a stdio server when it also had acommand. A server with notype, or with"type": "stdio", is still a stdio server. - A config value with
"type": "boolean"and a stringvalue, insession/set_config_optionand, underunstable_session_options, in theconfigOptionsof a session setup request. It was read as the ID of a select value.
Neither needs a code change. The v2 changes in this release are wording only.
Runnable Protocol V2 Quickstart
The core crate includes a small ACP v2 agent and client that run together over
stdio. Both require unstable_protocol_v2; the agent also requires stdio,
and the client requires process:
simple_agent_v2.rsimplements initialization and the complete baseline session lifecycle.v2_one_shot_client.rsinitializes the agent, creates a session, sends one prompt, renders text output, waits for the matching session to become idle, and closes it.
Run the pair
Build both examples from the repository root:
cargo build -p agent-client-protocol \
--features process,stdio,unstable_protocol_v2 \
--examples
Then point the client at the agent executable:
./target/debug/examples/v2_one_shot_client \
--command ./target/debug/examples/simple_agent_v2 \
"Hello from ACP v2"
The result shows the two independent parts of a v2 prompt:
Prompt accepted; waiting for session output and completion...
Echo: Hello from ACP v2
Session is idle: Some(EndTurn)
The agent writes only JSON-RPC to stdout because ACP uses stdout as the wire. Write logs and diagnostics to stderr when extending it.
Client lifecycle
The client installs its session/update and session/request_permission
handlers before it opens a session. Permission requests are part of the
baseline client surface and have no capability marker; this non-interactive
example declines them. It selects the agent’s reject_once option when one is
offered and answers with the cancelled outcome otherwise. It then follows
this sequence:
- Send
initializeand verify that the agent advertised session support. - Send
session/newand retain the returned command handle and session ID. - Send
session/promptand await its response. This only confirms acceptance. - Ignore queued updates for that new session until its foreground state becomes
runningorrequires_action. Work may start blocked and end without ever running. The active update may already be queued when prompt acceptance arrives. - Project subsequent message updates, and treat the next matching
state_updatewithidleas completion of foreground work. An idle update queued before active work is only the session’s earlier ready state. Background updates may still arrive afterward. - Send
session/closewhen the client no longer needs the active session.
Real clients normally maintain one shared update projection for every session.
Do not install a temporary handler after sending a prompt: updates can arrive
before the prompt response and are not scoped to a prompt or turn ID.
Within that projection, message chunks append by messageId; a later message
snapshot with concrete content replaces the accumulated chunks, null clears
them, and omitted content preserves them. Rendering chunks and then rendering a
snapshot again would duplicate output. An empty content array is also a
replacement. Identical chunks append again; chunk updates are not automatically
idempotent. The example renders messages in first-seen order, even when the
first update for a message only carries metadata.
Run just test from the repository root to execute the example’s unit tests
alongside the workspace suite. They cover interleaved message IDs, metadata-only
updates, content replacement and clearing, and repeated chunks.
Agent lifecycle
Advertising AgentCapabilities::session(SessionCapabilities::new()) commits an
agent to the baseline session surface. The example handles:
session/newsession/listsession/resumesession/closesession/promptsession/cancelsession/updatenotifications sent to the client
The prompt handler validates and marks the session busy, responds to
session/prompt immediately, and moves the actual work into a spawned task so
the connection can continue dispatching cancellation and other traffic. That
task sends the accepted user message, a running update, output, and finally an
idle update with a stop reason.
The example supports idempotencyKey on session/prompt, as every agent that
advertises session support must. It records the key with the inserted user
message, answers a retry with that message’s ID, and starts no second round of
work. A client that may need to retry a prompt sends it with
ActiveSession::send_prompt_blocks_with_key.
The example keeps history in memory and supports replay from the start. It
ends a requested replay with a replay_complete update, also when the history
is empty. Every successful resume sends a current idle-state snapshot after
any replay and before the response, even without replay. A production agent
should replace this with durable session storage, synchronize its actual
foreground state, define its supported replay cursors, and make resource
cleanup and cancellation robust across process failure.
For the connection APIs, proxy routing, and compatibility details surrounding these examples, continue with Protocol V2.
Session Operation Coordination
The private
v2_session_coordination
example is a cookbook prototype, not a public SDK coordinator. It shows one
application policy for sharing draft-v2 session/resume replay and sequencing
session/close on a single application executor. Its state uses Rc, so it is
not a cross-thread service.
Ownership and ordering
The example initializes the connection before creating application owners.
Sessions, pending loads, and delivered sessions are the only owners of the
command sender. SDK callbacks own a separate sender for ordered wire events;
they never capture an application owner or a connection. The caller owns and
may cancel the enclosing connection future, including during initialization.
One driver consumes notifications, resume and close response markers, and EOF from a single wire-event FIFO. This extends the ordered application dispatch pattern: callbacks only enqueue events and never await another inbound response. The driver installs cleanup state before it considers reopening a session. Already-queued application commands take priority over wire events, so release and acquisition decisions are honored before exposing a response. Synthetic failure callbacks for unanswered requests can arrive after closure; the application must not wait for them. When the last command sender is dropped, the foreground transport stops without waiting for unanswered wire operations. Keep an application owner alive to continue cleanup; the driver does not keep the transport alive solely to obtain a close acknowledgement.
Load policy
Every load uses the fixed working directory passed to with_sessions and
ReplayFrom::Start.
- Concurrent active loads for one session share one resume operation and one
projection, so the client never has two replaying
session/resumerequests pending for one session. Dropping only some loads does not affect those that remain. - A lease covers both consumed sessions and results that were delivered but never consumed, so either path eventually releases its load.
- If every load is abandoned during resume, accumulated replay is discarded, while lightweight state remains to settle the in-flight wire response.
- A replacement arriving during abandonment or close waits for the old resume response and a successful close, then starts a fresh replay. Cleanup state is recorded before reopening.
- Resume failure is returned to that operation’s loaders; a waiting or later load may retry.
- Close failure fails queued replacements and blocks only that session until reconnect. There is no automatic close retry.
The selected policy is drain the published resume, then close. It does not cancel or detach the resume.
Projection and completion
The projection is intentionally just a raw, lossless SessionUpdate log, not a
general reducer. The complete resume setup response is retained alongside that
log by the operation result. Loads expose their shared projection only after
the resume response; live updates continue appending afterward. This example
does not expose partial replay to a loading view. Production applications
should project protocol entities according to their own UI needs, outside SDK
callbacks.
The agent ends the replayed history with a replay_complete update. The
projection records how many leading updates precede it in history_len. The
marker, current-state synchronization, and later updates are live. A resume
that fails is never exposed, so a truncated replay never reaches a view. An
agent that responds successfully without replay_complete violates the
protocol. The response still confirms that the requested replay finished, so
the example counts the updates before it as history. This example only resumes
a session that is not active on its connection. A client that resumes a
session that is already active can also receive a live update before the
marker, if the agent sent it before it received the request.
Do not generalize the next idle state into completion of a particular prompt:
v2 state is session-wide, updates have no prompt identity, and background
updates may continue while idle.
Limitations
This prototype has no timeouts, automatic retries, MCP attachments, session new/fork, or prompt scheduling. It deliberately uses unbounded command/event queues and an unbounded update log for clarity; production code needs explicit memory, backpressure, and fairness policies. UI work and user code must not run in SDK callbacks.
The prototype routes updates only for the sessions it resumed, so it drops the
updates of child sessions that an agent announces with subagent_update. A
complete client registers each child and attributes its updates and requests
to it.
Run it against an agent with an existing resumable session:
cargo run -p agent-client-protocol --features process,unstable_protocol_v2 \
--example v2_session_coordination -- \
--command 'my-agent-command' --session-id 'existing-session-id'
The repository verification command is:
just test
The prototype’s focused tests exercise abandonment, replacement, failure, and shutdown behavior; this page does not duplicate the implementation.
Transport Architecture
For the broader user-facing API, see the Core Library Design and
the agent-client-protocol rustdoc.
This chapter explains how the connection layer separates protocol semantics from transport mechanisms, enabling flexible deployment patterns including in-process message passing.
Overview
The SDK’s connection core provides the JSON-RPC abstraction used by ACP components. It supports pluggable transports that work with different I/O mechanisms while maintaining consistent protocol semantics.
Design Principles
Separation of Concerns
The architecture separates two distinct responsibilities:
-
Protocol Layer: JSON-RPC semantics
- Request ID assignment
- Request/response correlation
- Method dispatch to handlers
- Error handling
-
Transport and framing layer: Message movement and JSON-RPC envelope validation
- Reading/writing from I/O sources
- Serialization/deserialization
- Preserving each wire value, including malformed input
- Connection management
This separation enables:
- In-process efficiency: Components in the same process can skip serialization
- Transport flexibility: Easy to add new transport types (WebSockets, named pipes, etc.)
- Testability: Mock transports for unit testing
- Clarity: Clear boundaries between protocol and I/O concerns
The TransportFrame Boundary
The public, transport-neutral boundary is TransportFrame. A frame contains
one RawJsonRpcMessage or a malformed wire value that a relay must preserve.
RawJsonRpcMessage is the same for every ACP protocol version:
#![allow(unused)]
fn main() {
enum RawJsonRpcMessage {
Request(RawJsonRpcRequest),
Notification(Notification<RawJsonRpcParams>),
Response(RawJsonRpcResponse),
}
}
Requests and responses carry a RawJsonRpcId: the JSON-RPC id exactly as
it appears on the wire (an integer, a string or null). Each protocol
version’s schema has its own request ID type, and converts to and from it.
At that boundary:
- Above: Protocol layer works with application types (
OutgoingMessage,UntypedMessage) - Below: Transport actors parse and serialize JSON-RPC frames
- Boundary:
TransportFramecarries one raw message or a malformed wire value retained for a relay - In-process API:
Channel::rxandChannel::txcarryTransportFramedirectly - Failures: I/O and connection failures are returned by the future driving a transport; they are not sent as channel entries
TransportFrame::parse_json returns one frame for every input string, including
malformed response-shaped input. Malformed input retains its exact text. A JSON
array is a malformed frame with an Invalid Request error, since JSON-RPC
batches are not supported (see JSON-RPC Batches). The
protocol actor, not the parser, decides whether malformed input requires a
response.
Actor Architecture
Protocol Actors
These actors live in the protocol connection core and understand JSON-RPC semantics:
Outgoing Protocol Actor
Input: mpsc::UnboundedReceiver<OutgoingMessage>
Output: mpsc::UnboundedSender<TransportFrame>
Responsibilities:
- Assign unique IDs to outgoing requests
- Register pending replies before sending requests
- Convert application-level
OutgoingMessageto protocol-levelRawJsonRpcMessage
Incoming Protocol Actor
Input: mpsc::UnboundedReceiver<TransportFrame>
Output: Routes to pending request awaiters or registered handlers
Responsibilities:
- Route responses to pending request awaiters (matched by ID)
- Route requests/notifications to registered handlers
- Convert schema request/notification envelopes to
UntypedMessagefor handlers - Answer malformed call-shaped input, including any JSON array, with one error
response with
id: null
Pending Reply Registry
The shared pending-reply registry manages request/response correlation:
- Maintains map from request ID to response channel
- When response arrives, delivers to waiting request
Task Actor
Runs user-spawned concurrent tasks via cx.spawn().
Transport Actors
These actors are driven by physical transport components. They understand JSON-RPC framing and envelope validity, but they do not dispatch ACP methods or correlate responses with pending requests:
Transport Outgoing Actor
Input: mpsc::UnboundedReceiver<TransportFrame>
Output: Writes to I/O (byte stream, channel, socket, etc.)
For byte streams:
- Serialize a single
RawJsonRpcMessageto JSON, or write a relayed malformed value unchanged - Write newline-delimited JSON to stream
For in-process channels:
- Directly forward
TransportFrameto the channel
Transport Incoming Actor
Input: Reads from I/O (byte stream, channel, socket, etc.)
Output: mpsc::UnboundedSender<TransportFrame>
For byte streams:
- Read newline-delimited JSON from stream
- Replace bytes that are not valid UTF-8 with U+FFFD, so a line with such a byte is one message to parse, not a read failure that ends the connection
- Parse a single message
- Retain malformed input, including JSON arrays, so relays can forward it
- Leave call/response-shape classification and Error Response decisions to the incoming protocol actor
For in-process channels:
- Directly forward
TransportFramefrom the channel
The public Channel boundary preserves complete frames. The SDK sends every
request, notification, and response as an individual JSON-RPC message. Relays
and instrumentation must forward frames intact so they do not change wire
semantics.
JSON-RPC Batches
The SDK does not support JSON-RPC batching, in either protocol version. ACP protocol v2 removed batches, and v1 support was experimental and best-effort.
Lines,ByteStreams,Stdio, and in-process channels parse an incoming JSON array, including an empty one, as one malformed frame. The connection answers it with a singleInvalid Request(-32600) error withid: nulland processes none of its entries. The connection stays usable.- The HTTP transport answers a
POSTbody that is a JSON array with400 Bad Requestand that JSON-RPC error as the body. The WebSocket transport answers an array frame with that error. Neither forwards any entry to the agent. AgentProtocolRouteranswers a batched firstinitializethe same way and keeps the connection open, so the client can sendinitializeagain.- The SDK never sends a batch.
Since the removal, TransportFrame has only the Single and Malformed
variants, and TransportBatch and TransportBatchEntry no longer exist. Code
that matched TransportFrame::Batch or built batches should send each message
as its own TransportFrame::Single. A dropped Responder is answered with an
automatic error; see
Request Cancellation.
Lifecycle-sensitive routing is unaffected: ProxyProtocolRouter negotiates
proxy/initialize like AgentProtocolRouter negotiates initialize and does
not convert traffic after initialization, and ClientProtocolConnector starts each attempted
client implementation with an individual initialize request. Response-only
frames received before initialization are ignored.
Message Flow
Outgoing Message Flow
User Handler
|
| OutgoingMessage (request/notification/response)
v
Outgoing Protocol Actor
| - Assign ID (for requests)
| - Subscribe to replies
| - Convert to RawJsonRpcMessage
v
| TransportFrame (single message)
|
Transport Outgoing Actor
| - Serialize (byte streams)
| - Or forward directly (channels)
v
I/O Destination
Incoming Message Flow
I/O Source
|
Transport Incoming Actor
| - Parse (byte streams)
| - Or forward directly (channels)
v
| TransportFrame (single message or malformed input)
|
Incoming Protocol Actor
| - Route responses → pending request awaiters
| - Route requests → registered handlers
v
Handler or request awaiter
Message Ordering in the Conductor
The conductor’s central routing loop serializes forwarding decisions for incoming requests and notifications. Responses stay paired with the request contexts managed by the protocol layer and may take a direct response path. The conductor therefore does not promise a global total order across unrelated concurrent requests, but every underlying transport sink preserves the order in which complete frames are accepted. See Conductor Routing and Ordering.
Component Boundary
ConnectTo
is the common component and transport abstraction. connect_to joins a
component to its counterpart and drives the connection until completion.
into_channel_and_future exposes the canonical low-level boundary as a
Channel plus an explicit connection driver:
fn into_channel_and_future(self) -> (Channel, Option<ConnectionDriver>);
The channel carries only TransportFrame wire events. The optional driver
distinguishes owned work from a passive endpoint:
| Returned work | Lifetime rule |
|---|---|
Some(ConnectionDriver::new(future)) | Poll the owned work alongside traffic; successful completion ends it after accepted output is drained. |
None | No work is owned here; each channel half determines its own lifetime. |
A ConnectionDriver always contains a real future; the optional return value
cannot itself be awaited. There is no ready-successful passive driver and no
finish hook in the None case. This makes the ownership decision explicit
rather than requiring callers to recognize a special future.
A raw Channel returns None. Its bridge preserves both directions
independently:
one sender closing must not prevent a final response in the reverse direction.
Owned completion lets a bridge stop accepting new output, drain frames already
accepted, and finish without waiting for unrelated remote input to close.
Outbound forwarding must remain polled while owned work is running; otherwise
a component waiting for a response to its own request could deadlock.
Buffered adapters are responsible for flushing their accepted output before
reporting successful completion. The built-in line and byte-stream adapters
keep the read half moving during write drain and propagate incoming errors;
their explicit finish handling does not require remote read EOF.
ConnectionDriver::with_finish(future, finish) lets custom adapters declare
the same cooperative contract. Its one-shot, nonblocking hook requests finish
after protocol output handoff; the still-polled future performs the drain and
reports completion or I/O errors. request_finish() exposes this request to
low-level callers and is idempotent: a supported request remains supported
after it has been issued. The callback still runs at most once. Neither
requesting finish nor dropping the hook proves a successful flush, and no
implicit timeout is imposed.
ConnectionDriver::new(future) remains appropriate for opaque cancellable
work. A finite foreground does not wait indefinitely for such work after
handing off protocol output. Merely wrapping an arbitrary future cannot make
an opaque custom adapter drain safely.
Most components implement only connect_to; default normalization supplies
Some(driver) containing the owned work. Direct transports override
into_channel_and_future to avoid an intermediate copy. Wrappers that expose an
existing endpoint should forward
its driver unchanged so absence and cooperative completion handling are
not lost. Wrappers that decorate execution use map_future to transform the
owned future while preserving its finish capability and requested state.
Direct custom transport entry points must also request and await cooperative
finish after a finite peer completes; a bare join does not provide that step.
See Migrating Connection Drivers for custom override changes. This lifecycle distinction does not change the existing raw channel types or introduce frame-size, queue, or task limits.
Transport Implementations
Byte Stream Transport
ByteStreams<Outgoing, Incoming> works with futures::io::AsyncWrite and
AsyncRead. It adapts them to Lines, parses each incoming JSON value into one
frame, and serializes each outgoing frame to one newline-delimited JSON value.
Runtime adapters with different I/O traits can instead bridge asynchronous
lines into Lines.
The native Stdio and AcpAgent transports build on ByteStreams and require
the independent stdio and process features, respectively. No features are
enabled by default. Their implementations depend on process spawning and
blocking-thread facilities, so their dependencies and exports remain excluded
on WebAssembly even when enabled. The runtime-neutral
protocol engine and transport abstractions compile for wasm32-wasip1 and
wasm32-wasip2 without additional features. JavaScript-hosted
wasm32-unknown-unknown builds require the opt-in wasm_js feature, which
selects Web Crypto through wasm-bindgen as the UUID randomness backend. Since
the target does not imply a JavaScript host, other OS-less WebAssembly hosts
must arrange a compatible UUID randomness backend instead. This crate does not
provide a WebAssembly executor or host I/O adapter.
Handlers, transports, and connection futures must be Send on every target,
including WebAssembly. JavaScript host values such as wasm_bindgen::JsValue
are !Send, so keep them outside the connection and exchange Send data with
it through Channel or ByteStreams. A later release may relax these bounds
on WebAssembly. That change would not affect native code.
The rmcp integration library also compiles for WASI with its rmcp_3 feature,
alone or with its MCP-over-ACP features. It uses Tokio’s async I/O utilities and
single-thread-capable runtime without requiring native stdio or a multithreaded
executor. Embedders still provide their runtime and host transport. See
Cargo Features for configuration and migration examples.
Use cases:
- Stdio connections to subprocess agents
- TCP socket connections
- Unix domain sockets
- Any stream-based I/O
In-Process Channel
For components in the same process, Channel::duplex() creates paired
endpoints and skips serialization entirely. Relays forward each received
TransportFrame without unpacking it; this preserves the original
representation of malformed wire input.
Benefits:
- Zero serialization overhead: Messages passed by value
- Same-process efficiency: Ideal for conductor with in-process proxies
- Explicit wire state: No serialize/parse round trip is required, while a malformed value received from a physical transport remains an explicit frame
Typed Component Interface
The community yosh:acp@8.0.1 package
defines an independently versioned typed WIT projection of ACP for the WASI
0.3 async component model. In that design, the host processes the ACP JSON-RPC
connection outside the component and maps it to typed calls across the
component boundary. The package provides interface definitions, not a
transport or integration supplied by this SDK.
Use Cases
1. Standard Agent (Stdio)
Use native Stdio for the current process or AcpAgent for a child process.
Both use the same frame-aware line transport underneath.
AcpAgent shuts its child down as the ACP stdio transport specifies. Its driver
supports graceful finish, so when a connect_with foreground returns (or the
agent closes its stdout under connect_to), the transport drains accepted
output and then closes the agent’s stdin. The agent gets a one-second grace
period to exit on its own; a nonzero exit in that window is reported as an
error, with a bounded stderr tail. If the agent is still running, then on Unix
its process group (which includes agents behind npx or uvx launchers) is
sent SIGTERM, followed by SIGKILL if it has not exited two seconds later.
On Windows the process is killed. An exit that the SDK forced this way is not
reported as an error.
If a write fails or an unanswered request ends the connection on stdout EOF,
AcpAgent also waits up to one second for the child to exit. A nonzero exit
in that window supplies the connection error, including the stderr tail.
A successful exit or an expired wait preserves the original error.
An independent client error, such as a cancelled operation, bypasses this wait.
Dropping the connection future is cancellation and cannot wait, so it kills
the agent’s process group immediately with SIGKILL.
2. In-Process Proxy Chain
Connect builders, proxies, and conductor components directly. Their default
ConnectTo adapter uses Channel, so complete frames cross each wrapper with
no serialization.
3. Network-Based Components
Split the socket and pass compatible read/write halves to ByteStreams::new.
4. WebAssembly Embedding
Embedders supply and drive their own runtime and host transport:
- Exchange
TransportFramevalues through an in-componentChannel. A caller usingConnectTo::into_channel_and_futurepolls a present owned driver alongside traffic. When no driver is returned, preserve the channel halves’ independent lifetimes; absence is not EOF. - Exchange newline-delimited JSON through
Lines, using afutures::Sink<String>andfutures::Stream<Item = std::io::Result<String>>. - Use
ByteStreamswithfutures::io::AsyncReadandAsyncWrite.
5. Testing with Mock Transport
Use Channel::duplex() to inject and inspect TransportFrame values without
real I/O.
Benefits
Performance
- In-process optimization: Skip serialization when components are co-located
- Zero-copy potential: Direct message passing for channels
- Flexible trade-offs: Choose appropriate transport for deployment
Flexibility
- Transport-agnostic handlers: Write handler logic once, use anywhere
- Easy experimentation: Try different transports without code changes
- Future-proof: Add new transports (WebSockets, gRPC, etc.) without refactoring
Testing
- Mock transports: Unit test handlers without I/O
- Deterministic tests: Control message timing precisely
- Isolated testing: Test protocol logic separate from I/O
Clarity
- Clear boundaries: Protocol semantics vs transport mechanics
- Focused implementations: Each layer has single responsibility
- Maintainability: Changes to transport don’t affect protocol logic
Related Documentation
- Core Library Design - High-level crate architecture
- Conductor Design - How the conductor uses transports
HTTP / WebSocket Transport
agent-client-protocol-http exposes ACP agents over one /acp endpoint.
POST /acpwithinitializecreates a connection and returnsAcp-Connection-Id.- Later
POST /acprequests includeAcp-Connection-Id; session-scoped requests also includeAcp-Session-Idorparams.sessionId. GET /acpwithAccept: text/event-streamstreams agent messages over SSE. Use a connection-level stream for connection-scoped messages and per-session streams for session-scoped messages.GET /acpwith a WebSocket upgrade uses text frames for JSON-RPC messages.DELETE /acptears down the connection.
POST /acp request bodies are limited to 16 MiB.
Diagnostic Privacy
Ordinary transport diagnostics use byte lengths, fixed message kinds, stream scope, and fixed failure labels rather than message bodies. They do not format raw methods, request/session IDs, WebSocket close reasons, or transport error text, which can contain prompts, file/image content, or credential-bearing URLs. This does not change messages or errors delivered through the protocol.
Opt-in conductor recordings are different: they intentionally retain protocol payloads and must be treated as sensitive. This policy covers diagnostics emitted by the HTTP transport crate, not logs from applications or underlying libraries.
JSON-RPC Batches
JSON-RPC batches are not supported. ACP protocol v2 removed them, and the SDK rejects them in both protocol versions:
- A
POST /acpbody that is a JSON array, including an empty one, gets400 Bad Requestwith a single JSON-RPC error body:-32600(Invalid Request) withid: null. None of its entries is forwarded, and no connection is created. - A WebSocket text frame that is a JSON array gets that error as one text frame, and none of its entries is forwarded.
HttpClientsends every message individually. A JSON array received from the server, in an SSE event or a POST response body, is treated as a malformed message.
If the agent emits a notification or callback before its initialize response is ready, the server buffers that frame for the connection’s SSE stream until initialization completes. See Transport Architecture for the shared rules.
HTTP + SSE Streams
After initialize, clients should open a connection-level SSE stream:
GET /acpAccept: text/event-streamAcp-Connection-Id: <connection id>- no
Acp-Session-Id
This stream carries connection-scoped messages.
Session-scoped messages are routed to session-specific SSE streams. For each active session, clients should also open:
GET /acpAccept: text/event-streamAcp-Connection-Id: <connection id>Acp-Session-Id: <session id>
Open a session stream before sending methods such as session/prompt,
session/load, session/resume, or other session-scoped requests. When a
session/new or session/fork response returns a new sessionId, open an SSE
stream for that returned session before expecting updates or responses for it.
The server only keeps streams for sessions that exist on the connection. A
session exists once the agent names it: in a session/new or session/fork
result, in a successful response to a request scoped to that session (such as
session/load or session/resume), or in a request or notification the agent
sends for it. The server records a new session before it queues the response
that names it, so a stream opened right after that response finds it.
Sending a session-scoped request does not create a session stream. If the session has no stream when the agent answers, the response goes to the connection stream instead.
A client may open a stream for a session that does not exist yet, so it
receives the updates session/load replays. The server allows up to 16 such
unconfirmed session streams per connection and forgets each one when the client
closes it before the agent names the session. Beyond that limit, a GET for an
unknown Acp-Session-Id gets 404 Not Found. A successful session/close or
session/delete removes the session’s stream. A client still reading it
receives the response and the stream stays open until the client closes it.
Features
The crate does not enable either transport side by default. Opt into only the side(s) you need.
agent-client-protocol-http = { version = "5", features = ["client"] }
# For a server instead:
# agent-client-protocol-http = { version = "5", features = ["server"] }
# To enable both sides:
# agent-client-protocol-http = { version = "5", features = ["client", "server"] }
The client feature exposes HttpClient. Its configure_http and
from_http_client hooks take reqwest types, and HttpClientError::Reqwest
holds a reqwest::Error, so add a matching reqwest dependency to customize
the HTTP client or inspect that error. The server feature exposes
AcpHttpServer, ServerOptions, and CorsOptions.
AcpHttpServer::into_router returns an axum::Router to mount in your axum
application, so your axum dependency must match this crate’s.
Request Cancellation
Request cancellation is available through the core SDK:
agent-client-protocol-http = { version = "5", features = ["client", "server"] }
$/cancel_request is connection-scoped. The HTTP transport does not apply
Acp-Session-Id to cancellation notifications, and routes outgoing
cancellation notifications over the connection stream rather than a session
stream.
WebSocket connections can carry cancellation at any point after the socket is
open. With HTTP + SSE, cancellation can be sent after initialize completes and
the client has received Acp-Connection-Id; an in-flight initialize request
cannot be cancelled with a hop-local $/cancel_request on this transport shape.
Server
#![allow(unused)]
fn main() {
use agent_client_protocol_http::AcpHttpServer;
let app = AcpHttpServer::new(|| my_agent()).into_router();
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await?;
axum::serve(listener, app).await?;
}
Cross-origin browser access is disabled by default. Enable it by allowlisting the browser origins that should be able to access the ACP endpoint:
#![allow(unused)]
fn main() {
use agent_client_protocol_http::{AcpHttpServer, CorsOptions, ServerOptions};
let app = AcpHttpServer::new(|| my_agent())
.with_options(
ServerOptions::default()
.with_cors(CorsOptions::allow_origins(["http://localhost:5173"])?),
)
.into_router();
}
ServerOptions is non-exhaustive. Start from ServerOptions::default() and use
with_path(...), with_cors(...), and with_health_endpoint(...); its fields
remain public for reading and mutation. Defaults remain /acp, disabled CORS,
and an enabled /health endpoint. See the config API migration
for replacing struct literals and update syntax.
Browser authentication and credential policy
CORS controls browser cross-origin access; it does not authenticate clients.
The WebSocket origin check accepts requests without an Origin header, so an
origin allowlist is not a substitute for authentication.
The built-in CORS policy allows ACP transport headers, but not Authorization,
and does not enable credentialed CORS (Access-Control-Allow-Credentials).
CorsOptions::allow_any_origin() is a wildcard origin policy, not an
authentication or credential policy.
Hosts that need bearer headers, cookies, or another credential policy should
enforce authentication on the router returned by into_router() and supply
their own CORS layer. Leave ServerOptions::cors disabled when providing that
HTTP CORS layer to avoid stacking conflicting policies. The separate WebSocket
origin check still uses CorsOptions; with the built-in policy disabled it
rejects upgrades carrying an Origin header. Browser WebSocket hosts can use
an explicit CorsOptions::allow_origins(...) allowlist, but a host needing a
different credentialed HTTP CORS policy and browser WebSocket origins on the
same endpoint needs additional host routing/policy integration beyond these
options. This SDK does not provide a general authentication configuration.
Client
#![allow(unused)]
fn main() {
use agent_client_protocol_http::HttpClient;
let transport = HttpClient::new("http://127.0.0.1:8080")?;
my_client().connect_to(transport).await?;
}
The same HttpClient also speaks WebSocket — pass a ws:// or wss:// URL
and it will open a single bidirectional connection instead of using POST + SSE:
#![allow(unused)]
fn main() {
let transport = HttpClient::new("ws://127.0.0.1:8080")?;
my_client().connect_to(transport).await?;
}
The client validates the WebSocket handshake before sending any queued ACP
messages. This transport does not negotiate WebSocket subprotocols or extensions,
including compression. Setting Sec-WebSocket-Protocol or
Sec-WebSocket-Extensions in custom default headers does not enable support for
them; a server response selecting either is rejected.
Client Configuration
Use the client builder to configure headers, proxies, DNS, TLS, and timeouts. The configuration is used for both HTTP/SSE requests and WebSocket handshakes:
#![allow(unused)]
fn main() {
use std::time::Duration;
use agent_client_protocol_http::HttpClient;
let transport = HttpClient::builder("wss://agent.example")
.configure_http(|http| {
http.user_agent("my-acp-client")
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(10))
})
.build()?;
}
configure_http transforms the current reqwest::ClientBuilder; repeated calls
retain earlier configuration. Use it for options such as default_headers,
proxy, resolve, tls_certs_merge, and identity. It does not open a
connection. URL validation and HTTP-client construction errors are returned by
build(), before connecting the transport.
builder(base_url) uses the same path rule as new: append /acp unless the
path already ends with it, after removing trailing slashes. For an exact
endpoint, including a custom server path or query string, use
builder_with_endpoint(endpoint) instead. with_endpoint(endpoint) remains
the unconfigured convenience constructor.
For WebSocket URLs, the SDK applies HTTP/1.1 and disables redirects after the configuration callback. These are transport requirements, not defaults a callback can override. A redirect fails at the original endpoint without sending handshake headers to its destination; resolve the intended WebSocket endpoint before connecting. HTTP/SSE retains the caller’s HTTP-version and redirect settings.
Proxy Headers
For WebSocket clients, do not set Host, Connection, Upgrade, or any
Sec-WebSocket-* header through reqwest::Proxy::headers. Use that API only
for non-handshake headers required by the proxy; proxy authentication can use
Proxy::basic_auth or custom_http_auth.
The SDK explicitly sets Connection, Upgrade, Sec-WebSocket-Version, and
Sec-WebSocket-Key over default_headers, but reqwest applies non-tunnel proxy
headers afterward on plain ws:// requests and can overwrite those values.
The callback’s proxy configuration is opaque: the SDK cannot
inspect, sanitize, or reject those settings at build(). This is a caller
configuration constraint, not an enforced builder restriction. Upgrade response
validation still precedes ACP data; it does not prove that every request header
was unchanged. For example, replacing the random key causes a response computed
from the replacement key to fail accept validation, but other reserved-header
overrides are not necessarily detected. For wss://, proxy headers apply to the
CONNECT request rather than the tunneled WebSocket handshake.
Reqwest’s connection timeout covers connection establishment. Its request/read timeouts also cover the opening WebSocket handshake but do not impose a lifetime or idle timeout on the upgraded socket. For HTTP/SSE, request/read timeouts retain their normal reqwest semantics, including the long-lived SSE response body.
For custom trust roots and client certificates, prefer reqwest’s TLS options.
If using tls_backend_preconfigured, configure that backend’s ALPN for
HTTP/1.1 yourself: reqwest does not rewrite a preconfigured TLS backend’s ALPN,
even when HTTP/1.1 is selected on its builder. For rustls, set
ClientConfig::alpn_protocols to vec![b"http/1.1".to_vec()]. Incompatible
negotiation is rejected before any ACP messages are sent; HTTP/2 and HTTP/3
WebSocket negotiation is not implemented.
Reusing an HTTP Client
To share an already-built reqwest client and its connection pool, use the
HTTP/SSE-only constructor with an exact endpoint, including /acp or the
server’s custom path:
#![allow(unused)]
fn main() {
let http = reqwest::Client::builder().build()?;
let transport = HttpClient::from_http_client(
"https://agent.example/acp",
http.clone(),
)?;
}
from_http_client rejects ws:// and wss:// URLs before any network request.
An already-built reqwest client cannot be reconfigured to enforce the
WebSocket connection policies. Use the SDK builder for those URLs.
HttpClient itself can also be cloned to reuse its endpoint and underlying
HTTP client. Each connection has independent ACP transport state.
Migrating Custom Client Construction
HttpClient::with_client(base_url, client) and
with_endpoint_and_client(endpoint, client) have been removed. An already-built
reqwest client cannot be reconfigured to enforce the WebSocket connection
policies, so migrate as follows:
- For HTTP/SSE or WebSocket configuration, move the reqwest builder settings into
HttpClient::builder(base_url).configure_http(|http| ...).build(). Do not call reqwest’sbuild()inside the callback. - For an exact endpoint, use
builder_with_endpoint(endpoint)instead. - To retain a shared, already-built HTTP/SSE client, use
from_http_client(exact_endpoint, client). Unlike the old base-URL constructor, this does not append/acp. - Code using
neworwith_endpointneeds no source changes, but WebSocket proxy discovery and TLS trust defaults change as described below.
WebSocket Proxy and TLS Defaults
Unconfigured WebSockets intentionally share reqwest’s defaults with HTTP/SSE.
Previously, the tungstenite connection was direct and WSS used bundled WebPKI
roots. Now new, with_endpoint, and unconfigured builders discover environment
proxies, honor system proxies when reqwest’s system-proxy feature is enabled,
and use reqwest’s TLS verifier. With this SDK’s rustls feature selection, that
is platform certificate verification instead of the old bundled roots. Downstream
reqwest feature selection and explicit TLS configuration can affect this behavior.
Consequently, an unchanged WebSocket URL may take a different network route or
trust a different set of certificate authorities.
To disable proxy discovery and explicitly supplied proxies, opt into a direct connection:
#![allow(unused)]
fn main() {
let transport = HttpClient::builder("wss://agent.example")
.configure_http(|http| http.no_proxy())
.build()?;
}
For deterministic trust, supply the application’s root certificates with
reqwest 0.13’s tls_certs_only, which disables platform/built-in roots:
#![allow(unused)]
fn main() {
use agent_client_protocol_http::HttpClient;
fn direct_with_root(root_pem: &[u8]) -> Result<HttpClient, Box<dyn std::error::Error>> {
let root = reqwest::Certificate::from_pem(root_pem)?;
Ok(HttpClient::builder("wss://agent.example")
.configure_http(|http| http.no_proxy().tls_certs_only([root]))
.build()?)
}
}
Supply the complete root set you intend to trust; this example does not recreate
the old bundled WebPKI root set. Use tls_certs_merge([root]) instead to add
private roots while retaining the selected verifier’s default trust. Do not disable
certificate validation to work around a trust-store difference. The
proxy-header constraint applies when explicitly configuring proxies.
Conductor Design
The agent-client-protocol-conductor crate runs a chain of ACP proxy
components. It presents one ACP endpoint upstream while owning the connections
to every proxy and, in agent mode, the final agent.
For API details, see the
agent-client-protocol-conductor rustdoc.
Chain Model
flowchart LR
Client[ACP client]
Conductor[Conductor]
Proxy1[Proxy 1]
Proxy2[Proxy 2]
Agent[Agent]
Client <--> Conductor
Conductor <--> Proxy1
Conductor <--> Proxy2
Conductor <--> Agent
Components do not open direct connections to one another. The conductor owns each transport and maps the logical chain onto those connections:
- Upstream traffic is delivered to the first proxy as ordinary ACP messages.
- A proxy uses
proxy/successorto send a request or notification to the next component. - Traffic from a successor is presented to its predecessor through the same typed proxy abstraction.
- JSON-RPC responses remain paired with the request context that caused them.
Cancellation is hop-local. A $/cancel_request names a request on the
connection it arrives on, so the conductor never forwards one. When a request
it forwarded is cancelled, it sends its own $/cancel_request to the next
component with that hop’s request ID. It accepts a proxy’s cancellation of a
proxy/successor request both plain, as the SDK’s proxies send it, and
wrapped in proxy/successor.
proxy/successor is exchanged only between the conductor and the proxies it
initialized, and between a conductor in proxy mode and its own conductor. The
conductor answers a proxy/successor request from the agent, or from the
client of a conductor in agent mode, with -32600 (Invalid request), and drops
and logs such a notification. It does the same for a proxy/successor that a
proxy, or the conductor of a conductor in proxy mode, wraps in a second
proxy/successor. Forwarding any of these would deliver it to a proxy as a
message from that proxy’s successor.
The final agent receives ordinary ACP and does not need to implement the proxy
extension. See the Proxy Extension Protocol Reference for the
wire method shapes. The conductor uses proxy/initialize and proxy/successor
from the ACP proxy chains RFD, with the message types and method names from
agent-client-protocol-schema (its unstable_proxy_chains feature, which the
SDK always enables). Earlier releases used _proxy/initialize and
_proxy/successor, so upgrade conductors and proxies together (see
Migrating to v5).
The conductor and the default proxy forwarding return the result or error of every wrapped request unchanged, as the RFD requires: they forward responses without re-wrapping them, rewriting error codes, or re-encoding results through typed schema structs. See Results and errors for the limits of that guarantee.
Lazy Initialization
Proxy and agent components are instantiated when the first initialize
request arrives. For each non-final component, the conductor sends
proxy/initialize; the last component in agent mode receives ordinary
initialize. Each proxy can initialize its successor before completing its own
response, so capabilities flow back toward the client through the chain.
Lazy construction allows an InstantiateProxiesAndAgent or
InstantiateProxies implementation to inspect and, when appropriate, adjust
the initialize request before choosing components.
Initialization selects the protocol version from the raw protocolVersion
before deserialization, so v2 info, capabilities, metadata, and future
extension fields are never interpreted as a permissive v1 request. With the
conductor crate’s unstable_protocol_v2 feature, a request for v2 or newer
selects v2; every other request selects v1, keeping v1’s fallback-to-latest
rule. A request for a newer version than the selected one keeps only what
parses under the selected version. A conductor in proxy mode negotiates its
proxy/initialize the same way. The instantiator receives a
SelectedInitializeRequest for the selected version. An unchanged request for
exactly the selected version keeps its original raw parameters, including
unknown extensions; a modified typed request is serialized as the new
authoritative payload, while its protocolVersion remains pinned to the
selected version.
The selected version is the highest version the chain may speak. Proxies
negotiate proxy/initialize the way agents negotiate initialize: a v1 proxy
answers a request for v2 or newer as v1 and initializes its successor with v1,
and a v2 proxy keeps what parses under v2 for a newer request and rejects a
request below v2 with -32022. So a proxy that supports only a lower version
narrows the rest of the chain to that version, and the initialize response
the client receives carries the version every component accepted. A component
that cannot accept the narrowed version, such as a v2-only agent behind a
v1-only proxy, or a v2-only proxy whose successor answers with v1, rejects the
initialization, and the client sees that error.
The command-line component provider, AgentOnly, ProxiesAndAgent, and static
proxy vectors use their components for every version, so each supplied
component must support the selected version. Use Agent.protocol_router() or
Proxy.protocol_router() when a static component has separate
implementations. A custom instantiator that supports only a lower version
negotiates down by returning the request for that version (for example with
SelectedInitializeRequest::into_v1), and the client receives an initialize
response for it. An instantiator returns InstantiatedChain (agent mode) or
InstantiatedProxies (proxy mode). An instantiator error answers the
initialize request and leaves the connection in a failed state that rejects
later traffic. A first message that is not a valid initialization is answered
with an error and leaves the conductor uninitialized, so the client can retry.
Forwarding
Forwarding is the same for every protocol version and does not depend on the
feature: proxy/initialize has the same wire shape in v1 and v2. The
conductor rejects a proxy/initialize that arrives from outside, renames
initialize to proxy/initialize for the first proxy with its params
untouched, and preserves fields it doesn’t recognize.
Each hop allocates a new JSON-RPC ID. When an agent sends a request-scoped
elicitation/create, each forwarding hop translates params.requestId back
to the ID its predecessor used. A reference with no matching live forwarded
request on that hop is answered with -32602 (Invalid params), not passed
through. The callback’s own ID and response use normal request routing;
session-scoped elicitations, tool-call IDs and nested MCP payloads are unchanged.
The conductor’s connections to its client and to the final agent, and the pass-through proxy it inserts for tracing, have no protocol version guard; the endpoints validate the traffic of the negotiated version.
Agent and Proxy Modes
In agent mode, the conductor owns zero or more proxies followed by a final agent and acts as an agent toward its upstream client.
In proxy mode, the conductor owns only a proxy sub-chain. The final managed proxy’s successor is the conductor’s own downstream successor, allowing a sub-chain to participate as one proxy inside a larger composition.
Routing and Ordering
A central routing loop serializes forwarding decisions for incoming requests and notifications. Responses are associated with their original requests by the core JSON-RPC contexts and may use a direct response path; the conductor does not maintain a second global request-ID table.
Every physical and in-process bridge carries TransportFrame, so tracing and
delegating components relay each wire value, including malformed input,
unchanged. JSON-RPC batches are not supported; see Transport
Architecture.
Command-Line Usage
Global options precede the subcommand. Each component argument is one shell-parsed command string, so quote commands that include arguments:
agent-client-protocol-conductor agent \
"proxy-one --flag" \
"proxy-two" \
"base-agent --acp"
The last command in agent mode is the agent; earlier commands are proxies.
Proxy mode accepts only proxy commands:
agent-client-protocol-conductor proxy "proxy-one" "proxy-two"
Tracing options are global:
agent-client-protocol-conductor --trace ./trace.jsons agent "proxy-one" "base-agent"
agent-client-protocol-conductor --serve agent "proxy-one" "base-agent"
agent-client-protocol-conductor --trace ./trace.jsons --serve agent "proxy-one" "base-agent"
Build the opt-in binary with draft-v2 proxy initialization enabled using:
cargo build -p agent-client-protocol-conductor --features unstable_protocol_v2
There is no conductor mcp subcommand. Compatibility for HTTP-capable agents that lack the
native ACP MCP transport lives in agent-client-protocol-polyfill and must
be inserted explicitly when needed.
Programmatic Usage
use agent_client_protocol_conductor::{ConductorImpl, ProxiesAndAgent};
let components = ProxiesAndAgent::new(agent)
.proxy(first_proxy)
.proxy(second_proxy);
ConductorImpl::new_agent("conductor", components)
.run(upstream_transport)
.await?;
ConductorImpl::new_proxy accepts an InstantiateProxies implementation for
the nested-proxy case. Both modes can use dynamic instantiator closures that
receive the SelectedInitializeRequest when the chain depends on
initialization data.
MCP Compatibility
MCP-over-ACP adaptation is intentionally not built into ConductorImpl. Add
McpOverAcpPolyfill::http() as a proxy in the chain immediately before a final
agent that cannot consume native McpServer::Acp declarations. The
provider-facing side uses feature-gated, request-scoped mcp/message
operations for MCP 2026-07-28; only the final-agent side is adapted to HTTP.
Keeping the polyfill explicit prevents instrumentation or
orchestration from silently changing session MCP declarations. See MCP
Bridge.
The polyfill supports v1 by default. For a draft-v2 chain, enable
unstable_protocol_v2 on both the conductor and the polyfill crate; the
conductor’s feature does not enable the polyfill’s. A polyfill built without
the feature negotiates its proxy/initialize down to v1 like any v1-only
proxy, so the whole chain, and the initialize response the client
receives, use v1.
Tracing
The conductor can record an idealized logical sequence of ACP and MCP messages. Its snooping bridges retain complete transport frames, so enabling tracing does not change what is sent on the wire. See Trace Viewer for the event format and current CLI/API examples.
Request-scoped MCP HTTP Re-export
agent-client-protocol-polyfill::mcp_over_acp::McpOverAcpPolyfill adapts the
native ACP MCP transport for a final agent with an MCP 2026-07-28 HTTP client.
MCP adaptation is explicit and is not built into the conductor. There is no
fallback to older revisions.
The component-facing side of the bridge always uses the opt-in native protocol:
- Servers are declared as
McpServer::Acpwith aserverId. - Each operation uses
mcp/messagewith the server ID and a fresh logical ID. - Provider notifications belong to that operation; its final response carries an inner MCP result or error.
- There is no initialize/connect/disconnect or MCP session-header exchange.
The SDK-local underscore-prefixed method family and HTTP declarations with a special URL scheme have been retired. The polyfill now translates native declarations to real localhost HTTP URLs only at the compatibility boundary.
Native MCP-over-ACP requires the core SDK’s unstable_mcp_over_acp feature. The
polyfill enables that feature on its core dependency, so applications using the
polyfill receive it through Cargo feature unification.
The polyfill supports stable protocol v1 by default. To place it in a draft-v2
conductor chain, enable unstable_protocol_v2 on both the conductor and
polyfill dependencies:
agent-client-protocol-conductor = { version = "...", features = ["unstable_protocol_v2"] }
agent-client-protocol-polyfill = { version = "...", features = ["unstable_protocol_v2"] }
The feature makes this concrete compatibility proxy recognize v2
initialization, capability, session setup, and mcp/* wire types. It does not
change the core attachment API. Proxy.v2().with_mcp_server(...) provides
connection-global attachment. v2::SessionBuilder::with_mcp_server(...) and
v2::ResumeSessionBuilder::with_mcp_server(...) provide per-session attachment
for new and resumed sessions respectively. With unstable_session_fork,
v2::ForkSessionBuilder::with_mcp_server(...) provides per-session fork
attachment. The polyfill adapts their native declarations when the final agent
supports only HTTP MCP.
Placement
Insert the polyfill immediately before the final agent that lacks native MCP-over-ACP support:
use agent_client_protocol_conductor::{ConductorImpl, ProxiesAndAgent};
use agent_client_protocol_polyfill::mcp_over_acp::McpOverAcpPolyfill;
let components = ProxiesAndAgent::new(agent)
.proxy(application_proxy)
.proxy(McpOverAcpPolyfill::http());
ConductorImpl::new_agent("conductor", components)
.run(upstream_transport)
.await?;
The application proxy can attach a high-level
agent_client_protocol::mcp_server::McpServer. The SDK advertises it in session
setup requests as McpServer::Acp; callers do not need to construct a transport
placeholder themselves. In v2, Proxy.v2().with_mcp_server(...) provides
connection-global attachment. v2::SessionBuilder::with_mcp_server(...) and
v2::ResumeSessionBuilder::with_mcp_server(...) provide per-session attachment
for new and resumed sessions respectively. With unstable_session_fork,
v2::ForkSessionBuilder::with_mcp_server(...) provides per-session fork
attachment. The polyfill translates those native declarations at the final
compatibility boundary.
During initialization, the polyfill forwards the request to its successor. When the successor advertises HTTP MCP support, the polyfill advertises native ACP MCP support in the response seen upstream:
- v1 sets
agentCapabilities.mcpCapabilities.acptotrue. - v2 adds the
capabilities.session.mcp.acpmarker.
In this chain position that capability means the chain can consume native MCP-over-ACP declarations through the adapter; it does not imply that the final agent implements the transport itself.
If the successor already advertises native ACP MCP support, the polyfill leaves
the capability, declarations, and mcp/message traffic unchanged. If it
supports neither native nor HTTP MCP, the polyfill does not advertise ACP MCP
support and rejects any native declaration that is nevertheless supplied.
Transformation
For each schema-selected McpServer::Acp entry in a session setup request, the
polyfill:
- Creates or reuses one connection-scoped loopback listener.
- Replaces the declaration with a server-addressed URL and an HMAC-derived Bearer token in an Authorization header, preserving name and metadata.
- Maps each HTTP POST to one independent
mcp/messagerequest with a fresh UUID logical ID. External HTTP IDs may overlap without sharing lifetime. - Streams that operation’s notifications and projects its terminal carrier into the corresponding HTTP JSON-RPC response.
- Cancels only that operation if its HTTP response stream is dropped.
The polyfill adapts the declarations of every session setup request: v1
session/new, session/load, session/resume, and session/fork, and draft
v2 session/new, session/resume, and session/fork. With the polyfill
crate’s unstable_session_fork feature it also validates session/fork
requests against the schema’s fork type. Without it, the agent validates them.
Declarations using another transport are left unchanged, including extension
transports represented by v2’s McpServer::Other.
Routes are derived from server IDs, not accumulated as per-server listeners or route-table entries. The token authenticates that server on this ACP connection. Keep the declaration’s header; never place its bearer credential in the URL.
The native wire envelopes are documented in the SDK Protocol Reference.
HTTP Mode
McpOverAcpPolyfill::http() replaces native declarations with loopback HTTP
URLs. Each POST carries current MCP method/version headers and required inner
version/client-capabilities metadata. Results use JSON, or an operation-scoped
SSE response when notifications are emitted.
let bridge = McpOverAcpPolyfill::http();
Authentication and Origin checks precede bounded request parsing. The adapter does not accept batches, client responses, MCP initialize/session headers, or standalone GET/DELETE streams. It has no resumable SSE event IDs.
Native-tool semantics, not another HTTP gateway’s policy
The endpoint re-exports native tools with its own routing and authentication.
It strips transport-only x-mcp-header annotations from schema positions in
tools/list, retaining argument validation, property names, defaults, examples,
and other instance data. Annotated native tools remain listed and callable.
tools/call is forwarded directly, without hidden descriptor discovery.
Mcp-Param-* headers are rejected and have no authorization or routing meaning.
An external HTTP gateway’s mirrored-header security policy is not transported;
deployments relying on it must enforce that policy separately at the new endpoint.
Lifecycle and Failure Behavior
Previously queued notifications precede the terminal outcome. Only a matching namespaced subscription ID is rewritten to the external HTTP ID; opaque retry state, unrelated metadata, and progress tokens are untouched.
Inner MCP errors retain their code, data, and extensions. Outer ACP failures are projected as binding failures, not mistaken for MCP method outcomes. Local overflow cancels that request and reports a distinct resource error.
The codes -33000, -33001, -33002, and -32800 of an outer ACP failure
pass through. Every other code becomes -33002. Both keep the ACP error’s
message and drop its data, with one exception.
A provider answers -32602 for the ACP envelope, such as a sessionId it
needs or refuses. To the MCP client -32602 would mean that its own params
are invalid, and a model that reads “Invalid params” retries with other tool
arguments. So the code still becomes -33002, and the message says that the
server refused the request, and why:
{
"jsonrpc": "2.0",
"id": 4,
"error": {
"code": -33002,
"message": "The MCP server refused this request before running it. Reason: this MCP server requires sessionId on mcp/message. Changing the tool arguments will not help."
}
}
The reason is the provider error’s data when that is a non-empty string.
Otherwise it is the error’s message without a leading Invalid params: . It
is trimmed and loses one trailing period. When no reason is left, the message
is The MCP server refused this request before running it. Changing the tool arguments will not help.
Admission belongs to the HTTP response body until consumption or drop, including admitted validation-error responses. Notification buffering and request/terminal payload sizes have adapter-local bounds. These policies do not change generic ACP frame queues or establish a bound on arbitrary application memory.
The polyfill does not infer ACP session IDs. It sends every mcp/message
request without sessionId and toolCallId, because an MCP HTTP request does
not say which session it belongs to. Native registration dispatch remains
the authority for whether a server exists. The listener and signing secret live
only for the containing ACP connection.
Testy ACP Test Agent
testy is a deterministic ACP agent binary for exercising clients against ACP.
It is built from the agent-client-protocol-test crate and communicates over stdio like a normal
agent. Its v1 and draft v2 implementations are native rather than protocol conversions.
The default build enables agent-client-protocol-test’s unstable cargo feature, which forwards
to the SDK’s unstable feature and builds the v1 agent:
cargo build -p agent-client-protocol-test --bin testy
Enable the separate draft v2 feature to build a dual-version binary:
cargo build -p agent-client-protocol-test --bin testy --features unstable_protocol_v2
That binary selects v1 or v2 from the client’s initialize request. Everything that does not
request v2 goes to the v1 agent unchanged, so a v1 client sees the same agent as with the stable-only
build. just prep-tests already
builds Testy with all features, so the prebuilt test binary supports both versions.
Run the complete workspace suite with just test. Its prep-tests dependency builds
all ordinary workspace binaries and examples in one Cargo invocation, including
Testy, the conductor, mcp-echo-server, and arrow_proxy. The subsequent test run
builds and runs the test harnesses and doctests. CI uses the same recipe rather
than performing a separate all-target build first.
To build stable-only coverage:
cargo build -p agent-client-protocol-test --bin testy --no-default-features
The binary lands at target/debug/testy. Integration tests that need to spawn it should use
agent_client_protocol_test::test_binaries::testy() after prebuilding test binaries.
In-process tests use the library types, which follow the SDK’s v1/v2 module layout:
agent_client_protocol_test::testy::v1::Testyis the protocol v1 agent.agent_client_protocol_test::testy::v2::Testyis the draft protocol v2 agent (unstable_protocol_v2).agent_client_protocol_test::testy::protocol_router()serves both versions on one transport, as the binary does (unstable_protocol_v2).TestyCommandandTestyScenarioare shared by both agents.
Prompt Commands
Prompt text can be either plain text or a JSON-serialized TestyCommand.
Plain-text commands:
helpreturns the supported commands and scenarios.echo <message>streams<message>back.wait_for_cancelaccepts the prompt and waits forsession/cancel.session_updatesemits every stablesession/updatevariant.contentemits prompt/content-focused updates, including every stableContentBlockvariant.tool_callsemits tool call create and update flows.callbackssends every stable agent-to-client request.elicitationssends only elicitation requests.cancel_statusreports whethersession/cancelhas been received.fullruns all stable scenarios in deterministic order.
callbacks and full also run the elicitation coverage.
JSON command form:
{"command":"run_scenario","scenario":"elicitations"}
Coverage
Protocol v1
The binary handles every stable client-to-agent v1 request and notification:
initialize, authenticate, logout, session/new, session/load, session/list,
session/delete, session/resume, session/close, session/set_mode,
session/set_config_option, session/prompt, and session/cancel.
Closing is idempotent: session/close of an unknown or already-closed session succeeds with the
empty result, like session/delete.
The full scenario sends every stable agent-to-client callback request:
session/request_permission, fs/write_text_file, fs/read_text_file, terminal/create,
terminal/output, terminal/wait_for_exit, terminal/kill, and terminal/release.
It also emits the stable session update variants, including message chunks, tool calls, plans,
available commands, mode/config/session info, and usage.
Every path a scenario sends is rooted in the session’s cwd: the testy-write.txt file that
fs/write_text_file writes and fs/read_text_file reads back, the working directory of each
terminal/create, the tool-call locations and diff (testy-input.txt, testy-output.txt), and
the file: URIs of the image, resource link, and embedded resource. A client that confines file
and terminal access to the session’s directories can run the scenarios in a project directory,
and sessions rooted in different directories never share a file.
elicitations, callbacks, and full cover elicitation/create form mode,
URL mode, session scope, request scope, accept, decline, cancel, and elicitation/complete.
If the client does not advertise form elicitation, the scenario returns a deterministic
invalid-params prompt error before sending an elicitation request.
If the client advertises form elicitation but not URL elicitation, the URL part returns a
deterministic invalid-params prompt error.
Draft protocol v2
With unstable_protocol_v2, the binary also handles the complete advertised v2 session baseline:
initialize, session/new, session/list, session/resume, session/close, session/prompt,
session/cancel, and session/update.
The v2 implementation follows the split prompt lifecycle:
session/promptreturns an acceptance response carrying the accepted user message’smessageId.- Testy independently sends the accepted user message and a
runningstate update. - Output arrives through message updates.
- An
idlestate update with a stop reason completes the foreground work.
wait_for_cancel makes this separation deterministic for client tests: prompt acceptance returns
while work remains active, and session/cancel is confirmed by idle with the cancelled stop
reason. Testy also keeps simple message history and replays it before a session/resume response
when the client requests replay from the start. It ends that replay with a
replay_complete update, also when the history is empty, and sends none when
replay was not requested. Every successful resume sends
the current session info (session_info_update with the title) and a current
idle-state snapshot after any replay and before responding, including when
replay was not requested. Neither is a replayed historical change, and the
snapshot is not another completed turn.
Prompts may contain only the baseline text and resource_link content blocks; any other block
is rejected with -32602 before the turn begins. An empty prompt array is likewise rejected with
-32602 without inserting a user message. session/list returns every session in one page,
with the most recent activity first, and never issues nextCursor, so any cursor is rejected
with -32602. A session’s activity is its creation or its latest inserted user message.
A prompt that arrives while the session has foreground work is held, not rejected. Held prompts
are inserted in received order once the current work ends, and their responses stay pending until
then. session/cancel and session/close answer prompts held before them with -32800. Testy
also honors $/cancel_request for a held prompt and answers it with -32800, which the protocol
leaves optional. A prompt received after session/cancel is not cancelled by it.
Testy supports idempotencyKey on session/prompt. It inserts at most one user message for a key
in a session and answers a retry with the original messageId, without starting the work again.
It does not compare a retry’s prompt with the first one. A retry of a prompt that is still held is
not held a second time. Testy answers it when it answers the held prompt, with the same outcome. A
prompt that is rejected or dropped before insertion leaves its key unused. A key lasts as long as
the session’s history, across session/close and session/resume. A malformed key fails the
request with -32602.
Testy does not advertise session.systemPrompt. A session/new or session/resume that carries
a systemPrompt is rejected with -32602, and the session is not created or resumed. Testy
advertises capabilities.cancel on nothing and does not implement tool_call/cancel or
terminal/cancel, so both get -32601.
A relative cwd in session/new, session/resume, or a session/list filter is rejected with
-32602. Testy does not advertise additionalDirectories, so it ignores that field and never
lists additional directories. session/close is idempotent: closing an unknown or already-closed
session succeeds.
The existing v1 scenarios do not map one-to-one onto v2. V2 scenario parity, client callbacks, MCP, authentication, deletion, configuration, and other optional capabilities remain unadvertised for now.
Trace Viewer
agent-client-protocol-trace-viewer renders conductor message traces as an
interactive sequence diagram. Capture lives in
agent-client-protocol-conductor; the viewer can read the resulting file while
the conductor is running or after it exits.
Capture and View
Conductor options are global and therefore precede the subcommand:
agent-client-protocol-conductor --trace ./trace.jsons agent \
"proxy-one" "base-agent"
agent-client-protocol-trace-viewer ./trace.jsons
The standalone viewer chooses a loopback port and opens a browser. Use
--port PORT to choose the port or --no-open to suppress browser launch.
The conductor can also host the viewer directly:
# In-memory live trace
agent-client-protocol-conductor --serve agent "proxy-one" "base-agent"
# File-backed live trace
agent-client-protocol-conductor --trace ./trace.jsons --serve agent \
"proxy-one" "base-agent"
Starting file capture truncates an existing trace file. Each event is flushed as one JSON object followed by a newline.
Recording Privacy
Explicit recordings intentionally retain prompts, image/file content, and other protocol payloads. Treat both files and in-memory viewer data as sensitive. They are not the metadata-only HTTP transport diagnostics.
The conductor redacts, in the trace copy only, every value of an env or
headers field, keeping the variable and header names. This covers MCP server
declarations in session/new, session/load, session/resume, and
session/fork (v1 and v2), terminal auth methods, terminal/create, and
provider configuration. Fields are matched by name anywhere in a payload, so
unrelated env or headers fields are redacted too.
It also redacts HTTP(S) url fields. URL userinfo is removed. Query values are replaced with [REDACTED]
for these recognized keys, case-insensitively after percent decoding, ignoring
hyphens and underscores:
token,access_token,refresh_token,id_token,api_key,keysecret,client_secret,password,passwd,pwdauth,authorization,bearer,signature,sig,credential,credentials
Repeated and valueless credential parameters follow the same rule. Unparsable HTTP(S) URLs are redacted in full. Credential-free URLs remain unchanged; redacted URLs may be canonicalized, but non-secret query pair spelling, order, and encoding are retained. Redaction never changes the original wire message.
This is not a general-purpose payload sanitizer: arbitrary custom credential fields/query keys, URL path or fragment secrets, and secrets embedded in prompt text cannot all be detected. Review recordings before sharing them.
The --debug log applies the same redaction to protocol lines on component
stdin/stdout and to JSON component configurations. It records stderr as-is.
Event Schema
The .jsons file contains exactly three event variants: request, response, and
notification. It does not capture stderr or general tracing log records.
type TraceEvent = RequestEvent | ResponseEvent | NotificationEvent;
interface RequestEvent {
type: "request";
ts: number;
protocol: "acp" | "mcp";
from: string;
to: string;
id: unknown;
method: string;
session?: string;
params: unknown;
}
interface ResponseEvent {
type: "response";
ts: number;
from: string;
to: string;
id: unknown;
is_error: boolean;
error_domain?: "acp" | "mcp";
payload: unknown;
}
interface NotificationEvent {
type: "notification";
ts: number;
protocol: "acp" | "mcp";
from: string;
to: string;
method: string;
session?: string;
params: unknown;
}
ts is monotonic seconds since capture began. JSON-RPC IDs may be strings,
integers, or null; consumers must not assume they are numbers. The
optional session field is omitted when the tracer has no session context; it
is not serialized as null.
error_domain is present on error responses and says whether the error came
from the ACP binding or the inner MCP peer. Older traces omit it.
from and to are Client, Proxy(N) for the proxy at index N (starting
at 0), or Agent for the conductor’s successor: the agent, or the outer
conductor when the conductor runs as a proxy.
Idealized Message Flow
The trace shows logical component-to-component traffic rather than conductor plumbing:
proxy/successoris unwrapped and logged as its inner ACP method.mcp/messageis unwrapped and its inner method is marked with protocolmcp.- Responses are correlated with the request details retained by the trace writer.
The snooping bridges carry complete TransportFrame values, so enabling
tracing relays each wire value unchanged, including malformed input that the
viewer does not render.
Viewer Features
The web UI provides ACP/MCP/response filters, request-response color pairing,
active-request spans, elapsed-time labels, session/update text previews, a
resizable JSON detail panel, and adjustable swimlane width. The file-backed
server rereads the trace on each poll so new events appear during capture.
Programmatic Capture
use agent_client_protocol_conductor::{ConductorImpl, ProxiesAndAgent};
let conductor = ConductorImpl::new_agent(
"conductor",
ProxiesAndAgent::new(agent).proxy(proxy),
)
.trace_to_path("./trace.jsons")?;
conductor.run(upstream_transport).await?;
Use trace_to with a custom implementation of
agent_client_protocol_conductor::trace::WriteEvent to send events somewhere
other than a file. with_trace_writer accepts an already configured
TraceWriter.
The viewer crate also exposes serve_file and serve_memory. The memory-backed
form returns a TraceHandle for pushing JSON events and a server future that
the caller must drive.
Versioning and protocol versions
This page is for maintainers. It covers how the SDK crates are versioned and what to change when the SDK adds an ACP protocol version.
Release policy
- Every published crate is in the
acpversion group in.release-plz.toml, so all crates share one version number. - The stable API, everything that is not behind an
unstable_*feature, follows semver. - Everything behind an
unstable_*feature, including all ofagent_client_protocol::v2, may change in a minor release. Stabilizing a protocol version only removes its feature gate. - Moving a public dependency to a new major version is a major release of the
whole group. This applies to
axumandreqwest, whose types appear inagent-client-protocol-http’s API. A newrmcpmajor version is added as a new feature and module (rmcp_4) in a minor release. Only dropping support for an rmcp major version is a major release. agent-client-protocolpinsagent-client-protocol-schemawith an exact (=) requirement, andagent-client-protocol-derivewith an exact requirement as well. Release the derive and core crates together.
The user-facing version of this policy is in the crate docs
(agent_client_protocol#stability) and in the
v5 migration guide.
Semver checks in CI
CI does not run a semver check yet, because there is no published 5.x release
to compare against. After 5.0.0 is on crates.io, add a job to
.github/workflows/ci.yml that compares each published crate with its latest
release. Pin the actions to commit SHAs like the other jobs do:
semver:
name: Semver checks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: obi1kenobi/cargo-semver-checks-action@v2
with:
# Unstable features may change in minor releases, so check the
# stable API only.
feature-group: default-features
exclude: agent-client-protocol-test,agent-client-protocol-yopo
Run it on pull requests. A failure on a PR whose commits are not marked as
breaking (! or BREAKING CHANGE:) means the change needs a major release or
a different design.
Adding a protocol version
Adding protocol v3 should be additive: the version-dispatching types are
#[non_exhaustive], Protocol is sealed, and the router and connector slots
are private. Work through this list, using v2 as the template. Search for
ProtocolVersion::V2 and unstable_protocol_v2 to find each place.
- Schema. Bump the
agent-client-protocol-schemapin to a release with the new version’s types. Implement the JSON-RPC traits for its messages insrc/agent-client-protocol/src/schema/(seev2_impls.rs), including its proxy-chain types (impl_proxy_jsonrpc!inproxy_protocol.rs). The messages are re-exported asv3::schemain step 4, the only public path to them. - Feature gate. Add
unstable_protocol_v3tosrc/agent-client-protocol/Cargo.toml, forwarding to the schema crate’s feature, and to the crates that need a passthrough (the polyfill and the conductor). Without the feature, the SDK must behave exactly as before. - Marker. Add a
V3marker next toV1andV2insrc/agent-client-protocol/src/jsonrpc/protocol.rs. Implement the sealed trait: itsprotocol_version, its connection type, and its request ID conversions. - Connection and module. Add
jsonrpc/v3_connection.rsandsrc/agent-client-protocol/src/v3.rs, re-exporting the shared names (ConnectionTo,Builder, the request handle aliases, andpub use agent_client_protocol_schema::v3 as schema;) and the version’s session API. AddClient.v3(),Agent.v3()andProxy.v3(). - Negotiation. Teach the wire guard in
jsonrpc/protocol_compat.rsthe new version: selecting it frominitializeandproxy/initialize,util::initialize_params_for_version, and the newSelectedInitializeResponsevariant for a peer that selects a lower version. - Router slots. Add a
V3arm toSelectedProtocoland awith_v3slot toAgentProtocolRouter,ProxyProtocolRouterandClientProtocolConnectorinsrc/agent-client-protocol/src/role/acp.rs. Check everymatchon the protocol version there, including the Agent role’s retry rule for unhandled session messages, which only applies to v1 and unguarded connections. - Conductor and polyfill. Add a
SelectedInitializeRequest::V3variant and its version selection in the conductor, and the new version’s setup requests in the MCP-over-ACP polyfill. - Tests. Copy the v2 suites (
tests/protocol_v2.rs,tests/session_v2.rs,tests/proxy_protocol_router_v2.rs, the conductor’sinitialization_v2.rs) for v3. Add negotiation tests between each pair of versions, and keep the feature-equivalence tests (tests/v1_feature_equivalence.rs) passing with and without the new feature. - Docs. Add a book page like Protocol V2, update the crate docs and READMEs, and add the new feature to Cargo Features.
Migrating to v5
This page covers the breaking changes in agent-client-protocol 5.0 and the
crates released with it.
There is no 4.x of agent-client-protocol. All SDK crates now share one
version number. agent-client-protocol-rmcp, which was at 4.x, joined that
version group in this release, so the shared version had to start above 4.x.
Upgrade from 3.6 directly to 5.0.
Stability
- The stable v1 API, everything that is not behind an
unstable_*feature, follows semver: it changes incompatibly only in a major release. - Everything behind an
unstable_*feature may change in a 5.x minor release. This includes all ofagent_client_protocol::v2and the other items thatunstable_protocol_v2enables. Stabilizing protocol v2 only removes theunstable_protocol_v2gate. - All SDK crates share one version number. Moving a public dependency to a
new major version, such as
axumorreqwestinagent-client-protocol-http, forces a major release of all of them. rmcp is handled differently: support for a new rmcp major version arrives as a new feature in a minor release, and only dropping support for one forces a major release. agent-client-protocoldepends on one exact version ofagent-client-protocol-schema(an=requirement), and a minor SDK release may move that pin to a newer schema release. Use each version’s message types throughv1::schemaandv2::schema, and the version-neutral items throughagent_client_protocol::schema, instead of depending onagent-client-protocol-schemadirectly. A direct dependency must allow the exact version the SDK pins, or Cargo cannot resolve the dependency graph.
v1 and v2 modules and versioned entry points
Every connection now names its protocol version, in the entry point and in the imports:
Client.v1(),Agent.v1()andProxy.v1()start a stable protocol v1 connection. They replaceClient.builder(),Agent.builder()andProxy.builder(), which are removed.Client.v2(),Agent.v2()andProxy.v2()start a draft protocol v2 connection (unstable_protocol_v2), as before.agent_client_protocol::v1and, withunstable_protocol_v2,agent_client_protocol::v2hold each version’s SDK types under the same names. Each also re-exports its protocol messages asschema:v1::schemaandv2::schemareplaceschema::v1andschema::v2, which are removed. Seev1::schemaandv2::schema.
The crate root keeps what every version shares: transports (Channel,
Lines, ByteStreams, Stdio, AcpAgent, TransportFrame and the Raw*
types), ConnectTo, ConnectionDriver, the roles, the JsonRpc* traits and
derives, UntypedMessage, Error, ErrorCode, Result, Protocol with
Raw/V1/V2, the generic request handles (Responder, ResponseRouter,
SentRequest, PreparedRequest, Dispatch and Builder, defaulting to
Raw), the version-neutral ConnectionTo, and the routers that serve both
versions (AgentProtocolRouter, ProxyProtocolRouter,
ClientProtocolConnector). With unstable_protocol_v2 it also has
InitializationVersionMismatch and SelectedInitializeResponse, which
v2::InitializeOutcome::LowerVersion uses to report a lower version the
peer selected.
| Name | agent_client_protocol::v1 | agent_client_protocol::v2 |
|---|---|---|
ConnectionTo<Counterpart> | the v1 connection | the v2 connection |
Builder<Host> | Builder<Host, .., V1> | Builder<Host, .., V2> |
Responder<T> | Responder<T, V1> | Responder<T, V2> |
ResponseRouter<T> | ResponseRouter<T, V1> | ResponseRouter<T, V2> |
Dispatch<Req, Notif> | Dispatch<Req, Notif, V1> | Dispatch<Req, Notif, V2> |
SentRequest<T>, PreparedRequest<T> | SentRequest<T, V1>, PreparedRequest<T, V1> | SentRequest<T, V2>, PreparedRequest<T, V2> |
SessionBuilder | new session (build_session*) | new session (build_session*) |
ResumeSessionBuilder | resume_session* | resume_session* |
SessionSetup | a session and the response of the request that set it up | a session and the response of the request that set it up |
ActiveSession | the session handle with its update stream | the command-only session handle |
ForkSessionBuilder | - | fork_session* (unstable_session_fork) |
LoadSessionBuilder, SessionMessage, Blocking, NonBlocking, SessionBlockState | v1 session helpers | - |
InitializeOutcome | - | the result of send_initialize |
schema | the protocol v1 messages | the protocol v2 messages |
v1::ConnectionTo is its own type
v1::ConnectionTo is a v1 connection type, like v2::ConnectionTo, not the
crate root’s version-neutral ConnectionTo. It is what callbacks on
Client.v1(), Agent.v1() and Proxy.v1() receive, and it carries the v1
session helpers (build_session*, load_session*, resume_session*).
Requests sent through it return v1::SentRequest<T> and
v1::PreparedRequest<T>, whose id() is a v1::schema::RequestId
(raw_id() still gives the wire RawJsonRpcId). The wire format is
unchanged.
The root ConnectionTo stays the raw connection: HandleDispatchFrom
handlers, RunWithConnectionTo runners, dynamic handlers, Builder::new
callbacks and the conductor receive it, and its sends return Raw handles.
It no longer has the v1 session helpers. Convert explicitly between the two;
v2::ConnectionTo offers the same conversions:
use agent_client_protocol::{ConnectionTo, V1, v1};
// raw -> v1, for example in a custom runner that opens a v1 session
let v1_cx: v1::ConnectionTo<Agent> = raw_cx.into_protocol::<V1>()?;
v1_cx.build_session_cwd()?.block_task().start_session().await?;
// v1 -> raw, for example to drive a `RunWithConnectionTo` runner
let raw_cx: ConnectionTo<Agent> = v1_cx.into_raw();
Code that spelled out the root type on v1 callbacks or helpers changes the import:
// Before
use agent_client_protocol::{ConnectionTo, SentRequest};
fn send(cx: &ConnectionTo<Agent>) -> SentRequest<PromptResponse> { ... }
// After
use agent_client_protocol::v1::{ConnectionTo, SentRequest};
fn send(cx: &ConnectionTo<Agent>) -> SentRequest<PromptResponse> { ... }
Where code compared a v1 request’s id() with IDs from the raw layer, use
raw_id().
Converting, spawning and cancelling on connections
ConnectionTo::into_protocol::<P>()returnsResult<P::Connection<_>, Error>. It fails with an Internal error (-32603) when the connection’s builder guards another version, for exampleinto_protocol::<V2>()on a connection fromClient.v1(). Connections from unguarded builders such asBuilder::newconvert to every version.ConnectionTo::protocol_version()returns the guarded version, orNonefor an unguarded connection.ConnectionTo::spawn_connectionreturns the connection type the child builder’s callbacks receive, likev1::ConnectionTo::spawn_connectionandv2::ConnectionTo::spawn_connectionalready did. It replacesConnectionTo::spawn_connection_with_context, which is removed. SpawningClient.v1()now returns av1::ConnectionTo<_>; call.into_raw()where the raw connection is wanted. A raw builder still returns the rawConnectionTo. Turbofish calls name both parameters:spawn_connection::<UntypedRole, _>(...).v1::ConnectionTo::send_cancel_request(_to)takesimpl Into<v1::schema::RequestId>andv2::ConnectionTo::send_cancel_request(_to)takesimpl Into<v2::schema::RequestId>, the type their requests’id()returns. The v1 change is source-compatible:RawJsonRpcIdconverts intov1::schema::RequestId, so v1 calls that pass one still compile. V2 calls that pass aRawJsonRpcIdmust pass av2::schema::RequestIdinstead, so the v2 methods can no longer send{"requestId": null}, which v2 forbids. The rawConnectionTomethods still take anyRawJsonRpcId.Builder::with_v2_protocol_guard(unstable_protocol_v2) is removed. A builder that needs the v2 guard isClient.v2()orAgent.v2(); code that needs raw handles in its callbacks converts them withinto_raw().
Every session setup method returns SessionSetup
v1::SessionSetup and v2::SessionSetup replace RestoredSession and
OpenedV2Session. A SessionSetup is the session plus the complete
response of the request that set it up, as public fields. It is
#[non_exhaustive], so destructure it with ..:
#[non_exhaustive]
pub struct SessionSetup<'runner, Link, Response> { // v2: SessionSetup<Link, Response>
pub session: ActiveSession<'runner, Link>,
pub response: Response,
}
Every setup method returns one, in both versions: v1 start_session for
session/new (which used to return a bare ActiveSession), session/load
and session/resume; v2 session/new, session/resume and
session/fork. The v1 run_until and on_session_start callbacks receive
one too, as do the v2 on_proxy_session_start callbacks. The v1
on_proxy_session_start callback receives a clone of the complete
NewSessionResponse forwarded to the client, and start_session_proxy
returns it. Both used to give only the SessionId. There is no
SessionSetup here, because the session is proxied rather than handed to the
caller.
// Before
.on_proxy_session_start(responder, async |session_id| { ... })
let session_id = builder.block_task().start_session_proxy(responder).await?;
// After
.on_proxy_session_start(responder, async |response| { let session_id = response.session_id; ... })
let session_id = builder.block_task().start_session_proxy(responder).await?.session_id;
The RestoredSession and OpenedV2Session accessors are removed in favor of
the fields: session(), session_mut(), response(), into_parts() and
into_session(). The v1 ActiveSession no longer stores the session/new response:
ActiveSession::response(), modes(), config_options() and meta() are
removed; read them from SessionSetup::response.
// Before
let mut session = cx.build_session_cwd()?.block_task().start_session().await?;
let response = session.response();
.run_until(async |mut session| { ... })
let (session, response) = restored.into_parts();
let session = opened.into_session();
// After
let SessionSetup { mut session, response, .. } =
cx.build_session_cwd()?.block_task().start_session().await?;
.run_until(async |SessionSetup { mut session, .. }| { ... })
let SessionSetup { session, response, .. } = restored;
let session = opened.session;
The v1 session stream reports prompt responses and errors
v1::ActiveSession::send_prompt used to close the whole connection, and every
session on it, when the agent answered session/prompt with an error. The
caller never saw the error. The response, or the error, now arrives on the
session’s update stream, and v1::SessionMessage changed to carry it:
SessionMessage::StopReason(StopReason)is nowSessionMessage::PromptResponse(Result<PromptResponse, Error>). It keeps the fullPromptResponse, includingusageand_meta, which used to be dropped.SessionMessage::SessionMessage(Dispatch)is nowSessionMessage::Message(v1::Dispatch), whose request handles are typed for v1. Call.into_raw()before handing it toMatchDispatch.read_to_stringreturns the prompt’s error instead of the connection closing.send_prompt_blocks(Vec<ContentBlock>)sends prompts that are not plain text.
v1::SessionBlockState is sealed. v1::Blocking and v1::NonBlocking are
its only implementations.
// Before
match session.read_update().await? {
SessionMessage::SessionMessage(dispatch) => MatchDispatch::new(dispatch)
/* .if_notification(..) */,
SessionMessage::StopReason(stop_reason) => { /* .. */ }
_ => {}
}
// After
match session.read_update().await? {
SessionMessage::Message(dispatch) => MatchDispatch::new(dispatch.into_raw())
/* .if_notification(..) */,
SessionMessage::PromptResponse(response) => {
let stop_reason = response?.stop_reason;
/* .. */
}
_ => {}
}
Renamed and moved items
Every path is relative to agent_client_protocol. Items not listed keep
their path.
| Before (3.x) | After |
|---|---|
Client.builder() | Client.v1() |
Agent.builder() | Agent.v1() |
Proxy.builder() | Proxy.v1() |
Role::builder(role) (generic code, other roles) | Builder::new(role) |
Client.connect_with(agent, f) | Client.v1().connect_with(agent, f) |
X.builder().without_acp_version_guard() | Builder::new(X) |
Builder::without_acp_version_guard() | removed; Builder::new applies no version guard |
V2Builder | v2::Builder |
V2ConnectionTo | v2::ConnectionTo |
V2SessionBuilder | v2::SessionBuilder |
V2ResumeSessionBuilder | v2::ResumeSessionBuilder |
V2ForkSessionBuilder | v2::ForkSessionBuilder |
OpenedV2Session | v2::SessionSetup |
V2Session | v2::ActiveSession |
InitializeOutcome | v2::InitializeOutcome |
InitializationVersionMismatch | unchanged, at the crate root |
InitializationVersionMismatch::selected (field) | InitializationVersionMismatch::selected(), the version of response |
SelectedInitializeResponse | unchanged, at the crate root |
SessionBuilder | v1::SessionBuilder |
ActiveSession | v1::ActiveSession |
RestoredSession | v1::SessionSetup |
RestoreSessionBuilder | v1::LoadSessionBuilder / v1::ResumeSessionBuilder (the generic builder is no longer exported) |
SessionMessage | v1::SessionMessage |
SessionMessage::SessionMessage(Dispatch) | v1::SessionMessage::Message(v1::Dispatch) |
SessionMessage::StopReason(StopReason) | v1::SessionMessage::PromptResponse(Result<PromptResponse, Error>) |
Blocking, NonBlocking, SessionBlockState | v1::Blocking, v1::NonBlocking, v1::SessionBlockState |
schema::InitializeProxyRequest | v1::schema::InitializeProxyRequest, now the schema crate’s type; see Proxy chains |
RestoredSession::session(), session_mut(), response(), into_parts(), into_session() (and the OpenedV2Session equivalents) | the session and response fields |
ActiveSession::response(), modes(), config_options(), meta() | removed; use v1::SessionSetup::response |
v1 SessionBuilder::start_session() -> ActiveSession | returns v1::SessionSetup<'static, _, NewSessionResponse> |
ConnectionTo in v1 callbacks and session helpers | v1::ConnectionTo |
SentRequest<T>, PreparedRequest<T> from a v1 connection | v1::SentRequest<T>, v1::PreparedRequest<T> |
Builder::new, Builder::new_with, UntypedRole.builder(),
Conductor.builder() and the MCP roles’ builder() are version-neutral and
stay.
Builder::new applies no version guard
Builder::new(Client), Builder::new(Agent) and Builder::new(Proxy) (and
Builder::new_with) used to apply the v1 wire guard, like
Client.builder(). They are now raw: they apply no protocol-version guard,
exactly like without_acp_version_guard() did, and their callbacks receive
Raw handles. Only .v1() applies v1’s guard and only .v2() applies v2’s.
without_acp_version_guard() is removed, because no builder needs it any
more.
This changes wire behavior for code that kept Builder::new with an ACP
role and relied on the guard. Such a connection no longer:
- negotiates
initialize(orproxy/initialize) down to v1 before the handler sees it, so the handler receives the requested version unchanged; - rejects a peer’s response that selects a different version;
- rejects other requests before initialization on an agent that handles
initialize.
Use the versioned entry point to keep the guard:
// Before: v1 guard applied implicitly
Builder::new(Agent).on_receive_request(...)
// After
Agent.v1().on_receive_request(...)
// Before: explicitly unguarded
Builder::new(Proxy).without_acp_version_guard()
// After
Builder::new(Proxy)
In agent-client-protocol-test, Testy follows the same layout:
| Before | After |
|---|---|
testy::Testy | testy::v1::Testy |
testy::V2Testy, Testy::new().v2() | testy::v2::Testy, testy::v2::Testy::new() |
Testy::new().protocol_router() | testy::protocol_router() |
v1::schema and v2::schema
Each protocol version’s messages have one path: agent_client_protocol::v1::schema
and, with unstable_protocol_v2, agent_client_protocol::v2::schema.
agent_client_protocol::schema::v1 and schema::v2 are removed. The root
schema module keeps only the version-neutral items: ProtocolVersion,
MaybeUndefined, IntoOption, IntoMaybeUndefined and SuccessorMessage.
| Before | After |
|---|---|
schema::v1::X | v1::schema::X |
schema::v2::X | v2::schema::X |
schema::ProtocolVersion, schema::MaybeUndefined, schema::SuccessorMessage | unchanged |
Code that imports the schema modules as v1 and v2 cannot also import the
SDK modules under those names. Import each version’s messages through its SDK
module as schema:
use agent_client_protocol::v2::{self, schema};
async |request: schema::PromptRequest,
responder: v2::Responder<schema::PromptResponse>,
cx: v2::ConnectionTo<Client>| { ... }
// or
use agent_client_protocol::v2::{ConnectionTo, Responder, schema};
To keep the short v1::X and v2::X names in code that does not use the
SDK modules, alias the import: use agent_client_protocol::v2::schema as v2;.
The other examples in this guide use that shorthand for schema types.
A v1 client
// Before
use agent_client_protocol::{ActiveSession, Agent, Client, ConnectTo, ConnectionTo};
use agent_client_protocol::schema::{ProtocolVersion, v1::InitializeRequest};
Client
.builder()
.connect_with(transport, async |cx: ConnectionTo<Agent>| {
cx.send_request(InitializeRequest::new(ProtocolVersion::V1)).block_task().await?;
cx.build_session_cwd()?
.block_task()
.run_until(async |mut session: ActiveSession<'_, Agent>| {
session.send_prompt("Hello")?;
println!("{}", session.read_to_string().await?);
Ok(())
})
.await
})
.await
// After
use agent_client_protocol::{Agent, Client, ConnectTo};
use agent_client_protocol::schema::ProtocolVersion;
use agent_client_protocol::v1::{ConnectionTo, SessionSetup, schema::InitializeRequest};
Client
.v1()
.connect_with(transport, async |cx: ConnectionTo<Agent>| {
cx.send_request(InitializeRequest::new(ProtocolVersion::V1)).block_task().await?;
cx.build_session_cwd()?
.block_task()
.run_until(async |SessionSetup { mut session, .. }| {
session.send_prompt("Hello")?;
println!("{}", session.read_to_string().await?);
Ok(())
})
.await
})
.await
A v1 agent
// Before
use agent_client_protocol::{Agent, Responder};
use agent_client_protocol::schema::v1::{InitializeRequest, InitializeResponse};
Agent
.builder()
.on_receive_request(
async |request: InitializeRequest, responder: Responder<InitializeResponse>, _cx| {
responder.respond(InitializeResponse::new(request.protocol_version))
},
agent_client_protocol::on_receive_request!(),
)
.connect_to(transport)
.await
// After
use agent_client_protocol::Agent;
use agent_client_protocol::v1::Responder;
use agent_client_protocol::v1::schema::{InitializeRequest, InitializeResponse};
Agent
.v1()
.on_receive_request(
async |request: InitializeRequest, responder: Responder<InitializeResponse>, _cx| {
responder.respond(InitializeResponse::new(request.protocol_version))
},
agent_client_protocol::on_receive_request!(),
)
.connect_to(transport)
.await
A v2 client
// Before
use agent_client_protocol::{Agent, Client, InitializeOutcome, V2ConnectionTo, V2Session};
use agent_client_protocol::schema::{ProtocolVersion, v2};
Client
.v2()
.connect_with(transport, async |cx: V2ConnectionTo<Agent>| {
let InitializeOutcome::Initialized(_) = cx.send_initialize(request).block_task().await? else {
return Err(Error::internal_error());
};
let session: V2Session<Agent> =
cx.build_session_cwd()?.start_session().block_task().await?.into_session();
session.send_prompt("Hello").block_task().await?;
Ok(())
})
.await
// After
use agent_client_protocol::{Agent, Client};
use agent_client_protocol::schema::ProtocolVersion;
use agent_client_protocol::v2::{ConnectionTo, InitializeOutcome, SessionSetup};
Client
.v2()
.connect_with(transport, async |cx: ConnectionTo<Agent>| {
let InitializeOutcome::Initialized(_) = cx.send_initialize(request).block_task().await? else {
return Err(Error::internal_error());
};
let SessionSetup { session, .. } =
cx.build_session_cwd()?.start_session().block_task().await?;
session.send_prompt("Hello").block_task().await?;
Ok(())
})
.await
A v2 agent
// Before
use agent_client_protocol::{Agent, Client, Responder, V2ConnectionTo};
use agent_client_protocol::schema::v2;
Agent
.v2()
.on_receive_request(
async |request: v2::PromptRequest,
responder: Responder<v2::PromptResponse>,
cx: V2ConnectionTo<Client>| { ... },
agent_client_protocol::on_receive_request!(),
)
.connect_to(transport)
.await
// After
use agent_client_protocol::{Agent, Client};
use agent_client_protocol::v2::{ConnectionTo, Responder, schema};
Agent
.v2()
.on_receive_request(
async |request: schema::PromptRequest,
responder: Responder<schema::PromptResponse>,
cx: ConnectionTo<Client>| { ... },
agent_client_protocol::on_receive_request!(),
)
.connect_to(transport)
.await
A version-neutral Error
agent_client_protocol::Error used to be a re-export of
schema::v1::Error, even on v2 connections. It is now the SDK’s own type,
the same on every protocol version, with the same three public fields:
pub struct Error {
pub code: ErrorCode,
pub message: String,
pub data: Option<serde_json::Value>,
}
Errors are sent on the wire exactly as before, on both v1 and v2 connections.
What still works unchanged
Error::new(code, message),.data(...),Error::parse_error(),invalid_request(),method_not_found(),invalid_params(),internal_error(),request_cancelled(),auth_required()andError::into_internal_error(err). These codes mean the same in every protocol version.agent_client_protocol::Result<T>,?onserde_json::Error(becomes-32602) and onanyhow::Error(anError,v1::schema::Errororv2::schema::Errorinside it is recovered; anything else becomes-32603).Display,Debug,Clone,PartialEq,SerializeandDeserialize, with the same output as before.
Version-specific constructors moved to the schema types
Error::resource_not_found(uri) and Error::session_not_found(id) are
removed from the SDK error, because their data differs between protocol
versions. Build the error for the version you speak and convert it:
use agent_client_protocol::Error;
use agent_client_protocol::{v1::schema as v1, v2::schema as v2};
// Before
Err(Error::session_not_found(session_id))
Err(Error::resource_not_found(Some(uri)))
// After, on a v1 connection
Err(v1::Error::session_not_found(session_id).into())
Err(v1::Error::resource_not_found(Some(uri)).into())
// After, on a v2 connection (`unstable_protocol_v2`)
Err(v2::Error::session_not_found(session_id).into())
Err(v2::Error::resource_not_found().into())
agent_client_protocol::util::unsupported_protocol_version is removed. Use
v2::Error::unsupported_protocol_version(requested, supported).into(); the
wire error (-32022 with requested and supported) is the same.
Converting to and from the schema errors
Error converts losslessly in both directions with v1::schema::Error and,
with unstable_protocol_v2, v2::schema::Error. Unknown codes and any
data, including an explicit null, are kept.
let error: Error = v1_error.into();
let v2_error = v2::Error::from(error);
Typed v2 error data is read with serde_json from error.data:
if error.code == v2::ErrorCode::ResourceNotFound
&& let Some(data) = error.data.clone()
&& let Ok(data) = serde_json::from_value::<v2::SessionNotFoundErrorData>(data)
{
// data.session_id
}
ErrorCode is the SDK’s own
agent_client_protocol::ErrorCode used to be schema::v1::ErrorCode. It is
now a version-neutral newtype over the i32 on the wire, with constants for
the codes every version defines the same way:
Before (v1::ErrorCode variant) | After |
|---|---|
ErrorCode::ParseError | ErrorCode::PARSE_ERROR |
ErrorCode::InvalidRequest | ErrorCode::INVALID_REQUEST |
ErrorCode::MethodNotFound | ErrorCode::METHOD_NOT_FOUND |
ErrorCode::InvalidParams | ErrorCode::INVALID_PARAMS |
ErrorCode::InternalError | ErrorCode::INTERNAL_ERROR |
ErrorCode::RequestCancelled | ErrorCode::REQUEST_CANCELLED |
ErrorCode::AuthRequired | ErrorCode::AUTH_REQUIRED |
ErrorCode::ResourceNotFound | ErrorCode::RESOURCE_NOT_FOUND |
ErrorCode::Other(code) | ErrorCode::new(code) or code.into() |
ErrorCode compares directly with v1::schema::ErrorCode and
v2::schema::ErrorCode, so you can also keep the schema enum and name the
version:
assert_eq!(error.code, v1::ErrorCode::InvalidParams);
assert_eq!(error.code, v2::ErrorCode::UnsupportedProtocolVersion);
Codes defined by only some versions, such as v2’s -32022, have no
ErrorCode constant; compare with that version’s enum. i32::from(code)
and ErrorCode::value() give the raw code.
Code that used schema::v1::Error as the SDK error
Because the two used to be the same type, some code imported Error from
schema::v1 and used it with SDK callbacks. Import
agent_client_protocol::Error instead, or convert with .into().
A version-neutral RawJsonRpcId
The raw JSON-RPC layer used schema::v1::RequestId as its ID type, even on
v2 connections. It now uses the SDK’s own agent_client_protocol::RawJsonRpcId,
the same on every protocol version:
pub enum RawJsonRpcId {
Null,
Number(i64),
Str(String),
}
It has the same variants, serialization, Display, Hash and ordering as
v1::schema::RequestId, so IDs are sent on the wire exactly as before: 1
and "1" stay distinct, and integers keep the full 64-bit signed range.
What changed
| Before | After |
|---|---|
RawJsonRpcMessage::Request(schema::v1::Request<RawJsonRpcParams>) | RawJsonRpcMessage::Request(RawJsonRpcRequest), with the same id, method and params fields |
RawJsonRpcMessage::Notification(schema::v1::Notification<RawJsonRpcParams>) | RawJsonRpcMessage::Notification(RawJsonRpcNotification), with the same method and params fields |
RawJsonRpcResponse, an alias of schema::v1::Response<Value, Box<RawJsonRpcError>> | RawJsonRpcResponse, the SDK’s own enum with the same Result { id, result } and Error { id, error } variants and new |
RawJsonRpcMessage::response_id() returned Option<&v1::RequestId> | returns Option<&RawJsonRpcId> |
The request handles keep a typed id(); see
Request handles are typed by protocol version.
RawJsonRpcMessage::request, RawJsonRpcMessage::response and
RawJsonRpcResponse::new take impl Into<RawJsonRpcId>, so passing a
v1::RequestId, v2::RequestId, i64 or String still compiles. So do
ConnectionTo::send_cancel_request and send_cancel_request_to. A bare
1.into() no longer infers its type; write RawJsonRpcId::Number(1).
Updating your code
Replace schema::v1::RequestId with RawJsonRpcId where you build or match
raw messages, or store IDs from the raw dispatch layer or from several protocol
versions:
use agent_client_protocol::{RawJsonRpcId, RawJsonRpcMessage};
// Before
let request = RawJsonRpcMessage::request(method, params, v1::RequestId::Number(1))?;
let mut pending: HashMap<v1::RequestId, Route> = HashMap::new();
// After
let request = RawJsonRpcMessage::request(method, params, RawJsonRpcId::Number(1))?;
let mut pending: HashMap<RawJsonRpcId, Route> = HashMap::new();
pending.insert(responder.raw_id().clone(), route);
Where a schema type needs a request ID, such as v1::CancelRequestNotification
or an elicitation’s requestId, convert. RawJsonRpcId converts losslessly to
and from v1::RequestId, and from v2::RequestId. Converting to
v2::RequestId fails only for null, with the same Invalid Request error
(-32600) a v2 connection sends for a null request ID:
let raw_id = RawJsonRpcId::from(cancel.request_id);
let v1_id = v1::RequestId::from(raw_id.clone());
let v2_id = v2::RequestId::try_from(raw_id)?;
Request handles are typed by protocol version
Responder, ResponseRouter, SentRequest, PreparedRequest, Dispatch
and Builder take a protocol marker as their last type parameter. The
markers implement the sealed agent_client_protocol::Protocol trait, and the
marker selects the type that id() returns:
| Marker | Used by | id() |
|---|---|---|
Raw (the default) | HandleDispatchFrom, MatchDispatch, ConnectionTo::send_request, Builder::new and other unguarded builders | &RawJsonRpcId |
V1 | typed handlers on Client.v1(), Agent.v1(), Proxy.v1(); v1::ConnectionTo | &v1::schema::RequestId |
V2 (unstable_protocol_v2) | typed handlers on Client.v2(), Agent.v2(), Proxy.v2(); v2::ConnectionTo | &v2::schema::RequestId |
Dispatch::id() returns an Option of the same type. A V2 id() never
fails: the SDK rejects null request IDs on v2 connections and never assigns
null itself.
Every handle also has raw_id(), which returns the ID as a &RawJsonRpcId
whatever the marker (Option<&RawJsonRpcId> on Dispatch).
The raw dispatch layer is version-neutral
HandleDispatchFrom, MatchDispatch/MatchDispatchFrom, dynamic handlers,
Role::default_handle_dispatch_from and requests sent through ConnectionTo
are not tied to one protocol version. Their handles use the Raw marker,
which is the default, so Dispatch, Responder<T> and SentRequest<T>
written without a marker are the raw ones, and their id() returns
&RawJsonRpcId:
// Before (3.x): id() was a v1::RequestId even on v2 connections
impl HandleDispatchFrom<Client> for MyRouter {
async fn handle_dispatch_from(&mut self, message: Dispatch, cx: ConnectionTo<Client>)
-> Result<Handled<Dispatch>, Error>
{
let id: Option<&v1::RequestId> = message.id();
...
}
}
// After: the signature is unchanged, and id() is the wire ID
let id: Option<&RawJsonRpcId> = message.id();
Code that stored these IDs as v1::RequestId switches to RawJsonRpcId, or
converts with v1::RequestId::from(id.clone()).
Typed handlers on v1 builders
Typed handlers on Client.v1(), Agent.v1() and Proxy.v1() receive V1
handles, so id() still returns &v1::schema::RequestId. Closures whose
parameters are not annotated need no change. Where the handle type is spelled
out, use the v1 alias (or add the marker), because the root default is now
Raw:
use agent_client_protocol::v1::{Dispatch, Responder};
// Before
Agent.builder().on_receive_request(
async |request: PromptRequest, responder: Responder<PromptResponse>, cx| { ... },
on_receive_request!(),
)
// After
Agent.v1().on_receive_request(
async |request: PromptRequest, responder: Responder<PromptResponse>, cx| { ... },
on_receive_request!(),
)
// Likewise for on_receive_dispatch
async |message: Dispatch<PromptRequest, SessionNotification>, cx| { ... }
Client.v1(), Agent.v1() and Proxy.v1() return v1::Builder<_>
(Builder<_, _, _, _, V1>).
Builder::new and other roles’ builders use Raw. The v1 session helpers that take
a responder, such as v1::SessionBuilder::on_proxy_session_start, take a
v1::Responder<_>.
v2 code
id() on handles from the v2 builders and v2::ConnectionTo returns a
&v2::schema::RequestId instead of a &v1::schema::RequestId:
// Before
let id: &v1::RequestId = responder.id();
// After
let id: &v2::RequestId = responder.id();
let raw: &RawJsonRpcId = responder.raw_id();
Closures registered on a v2 builder whose parameters are not annotated need
no change. Where a v2 handle type is spelled out, use the v2 alias:
use agent_client_protocol::v2::{ActiveSession, Responder, SentRequest};
// Before
async |request: v2::PromptRequest, responder: Responder<v2::PromptResponse>, cx| { ... }
fn send(session: &V2Session<Agent>) -> SentRequest<v2::PromptResponse> { ... }
// After
async |request: v2::PromptRequest, responder: Responder<v2::PromptResponse>, cx| { ... }
fn send(session: &ActiveSession<Agent>) -> SentRequest<v2::PromptResponse> { ... }
Getting a typed handle from the raw layer
Responder, ResponseRouter, SentRequest, PreparedRequest and
Dispatch with the Raw marker convert to a typed marker with
into_protocol. Only the ID’s type changes. It fails
only for a null ID on V2, with the Invalid Request error (-32600) a v2
connection sends for such a request; a request received on a v2 connection
never has one. Any handle converts back with the infallible into_raw:
MatchDispatchFrom::new(message, &cx)
.if_request_from(Client, async |request: v2::NewSessionRequest, responder| {
// `responder` is a `Responder<_, Raw>`; the v2 helper wants `V2`.
let responder = responder.into_protocol::<V2>()?;
v2_cx.build_session_from(request).on_proxy_session_start(responder, op)
})
.await
Helpers that accept handles of several versions can take the marker as a type parameter:
fn respond<P: agent_client_protocol::Protocol>(responder: Responder<MyResponse, P>) { ... }
Forwarding between versions
SentRequest::forward_response_to, on_receiving_ok_result (and the
PreparedRequest equivalents) accept a responder of any marker, and
send_proxied_message / send_proxied_message_to accept a Dispatch of any
marker, so forwarding between connections needs no conversion.
MatchDispatch::otherwise_ignore answers unmatched requests
MatchDispatch::otherwise_ignore now answers an unmatched request with a
method not found error (-32601). Before, it dropped the responder, so the
peer got no answer. Unmatched notifications and
responses are still ignored.
v1::ActiveSession::read_to_string uses otherwise_ignore, so a request routed
to the session that it does not handle, such as session/request_permission,
now gets -32601. Handle such requests yourself if the peer needs a different
answer.
Renamed builder context types
The hidden ConnectionContext trait and its RawConnectionContext and
V2ConnectionContext implementations are replaced by Protocol, Raw, V1
and V2. Protocol::Connection<Counterpart> is the connection type builder
callbacks receive (ConnectionTo for Raw, v1::ConnectionTo for V1,
v2::ConnectionTo for V2), so code generic over a builder’s context changes
Context: ConnectionContext to P: Protocol.
Generic code can turn a P::Connection<Counterpart> back into the
version-neutral ConnectionTo with .into(): v1::ConnectionTo and
v2::ConnectionTo implement From for it, and Protocol::Connection
requires Into<ConnectionTo<Counterpart>>. Their own methods, such as the v1
session helpers, are only available on the concrete types.
Channel, JsonRpcMessage::parse_message and JsonRpcResponse::from_json
-
Channelis#[non_exhaustive]. Build one withChannel::new(rx, tx)(orChannel::duplex()) and take it apart withinto_parts()or a pattern with..:// Before let channel = Channel { rx, tx }; let Channel { rx, tx } = channel; // After let channel = Channel::new(rx, tx); let Channel { rx, tx, .. } = channel; -
JsonRpcMessage::parse_messagetakesparams: &serde_json::Valueinstead of&impl Serialize. Update hand-written implementations; derived ones change with the derive macros. Callers holding rawOption<RawJsonRpcParams>pass¶ms.map_or(serde_json::Value::Null, RawJsonRpcParams::into_value). -
JsonRpcResponse::from_valueis renamed tofrom_json, to pair withinto_json. Rename it in hand-written implementations and calls such asPromptResponse::from_value(method, value); derived implementations change with the derive macros.
Core changes
JSON-RPC batches are rejected
TransportBatch, TransportBatchEntry and TransportFrame::Batch are
removed. The SDK no longer processes JSON-RPC batches. A batch (a JSON array
on the wire, including an empty one) gets one Invalid Request error
(-32600) with "id": null, and none of its entries run. Send each message
on its own. Code that built or matched TransportFrame::Batch removes that
case.
TransportFrame is #[non_exhaustive], so matches on it need a wildcard arm:
match frame {
TransportFrame::Single(message) => { /* .. */ }
TransportFrame::Malformed { raw, error } => { /* .. */ }
_ => {}
}
MetaCapability and MetaCapabilityExt are removed
The MetaCapability and MetaCapabilityExt traits, which read and wrote
capability flags under _meta.symposium in initialize requests and
responses, are removed. Read and write the _meta map of the
InitializeRequest or InitializeResponse directly if you still need those
flags.
A dropped Responder answers the request
When a Responder is dropped without a response, the SDK now answers the
request itself:
-32800(Error::request_cancelled) if the peer cancelled the request with$/cancel_request;- otherwise
-32603(Error::internal_error), with data naming the method.
Before, the peer got no answer and waited. This change compiles without any
warning. Check handlers that drop a responder on purpose, for example to
answer later through another path: move the responder to the code that
answers instead of dropping it. Handing it to something that answers through
it, such as SentRequest::forward_response_to, or moving it into another task
does not trigger the automatic answer. No automatic answer is sent while the
connection shuts down.
v1 forwarding keeps unknown fields
v1 proxies and conductor chains no longer parse and re-serialize the messages
they forward. Fields the SDK does not know, for example in session/new
requests and responses or in initialize, now reach the next component
instead of being dropped. Proxies that relied on forwarding to strip such
fields must remove them themselves.
ProxyProtocolRouter keeps reading after a rejected first message
ProxyProtocolRouter (unstable_protocol_v2) used to close the connection
when it rejected the first proxy/initialize, for example for an unsupported
version, or when the first frame was malformed. It now answers the rejected
request or malformed frame with an error and keeps reading, like
AgentProtocolRouter, so the conductor can send proxy/initialize again. The
router finishes when its input closes.
Schema enums and SDK helpers
v1 extension methods keep their _ prefix
Parsing a v1 dispatch enum (v1::schema::ClientRequest, AgentRequest,
ClientNotification or AgentNotification) from an extension method used to
strip the leading _: a parsed _vendor/x reported method() as vendor/x
and was sent on as vendor/x, which the peer answered with Method not found.
The ExtMethodRequest and ExtNotification variants now keep the method
exactly as it was on the wire, as v2 already did. Code that matched on
ext.method without the prefix matches the full name instead:
// Before
v1::ClientRequest::ExtMethodRequest(ext) if &*ext.method == "vendor/x" => ...
// After
v1::ClientRequest::ExtMethodRequest(ext) if &*ext.method == "_vendor/x" => ...
Removed util helpers
util::internal_error(message) and util::parse_error(message) duplicated the
Error constructors and are removed. Build the error directly:
// Before
Err(util::internal_error(format!("lost {id}")))
result.map_err(util::internal_error)?;
// After
Err(Error::internal_error().data(format!("lost {id}")))
result.map_err(Error::into_internal_error)?; // any `std::error::Error`
util::TypeNotification is removed. It duplicated
MatchDispatch::if_notification for notifications. Wrap the message in
Dispatch::Notification and use MatchDispatch, which returns a parse error
for malformed params instead of logging and dropping them:
// Before
TypeNotification::new(message)
.handle_if(async |notif: SessionNotification| { ... })
.await
.otherwise(async |untyped| { ... })
.await
// After
MatchDispatch::new(Dispatch::Notification(message))
.if_notification(async |notif: SessionNotification| { ... })
.await
.otherwise(async |dispatch| { ... })
.await
agent-client-protocol now depends on the agent-client-protocol-derive
version released with it exactly (=), because the derive output calls
hidden SDK internals. Depend on the derives through agent_client_protocol
rather than adding the derive crate separately.
MCP-over-ACP error codes are ErrorCodes
mcp_server::MCP_SERVER_UNAVAILABLE (-33001) and
mcp_server::MCP_BACKEND_FAILURE (-33002) are now ErrorCode constants
instead of i32, and mcp_server::MCP_RESOURCE_LIMIT_EXCEEDED (-33000) is
new. Error::new(MCP_BACKEND_FAILURE, ..) still compiles. Compare with
error.code == MCP_BACKEND_FAILURE directly instead of through
i32::from(error.code), and use .value() where you need an i32 (for
example, against a JSON code).
Schema 1.15
This release uses agent-client-protocol-schema 1.15. Its new unstable
methods are forwarded as SDK features under the same names, and each is part
of the unstable feature:
| SDK feature | Methods |
|---|---|
unstable_auth_status | auth/status, and the auth/status_update notification |
unstable_session_archive | session/archive, session/unarchive |
unstable_session_status | session/status |
unstable_session_set_title | session/set_title |
With a feature enabled, the v1 and v2 dispatch enums (ClientRequest,
AgentResponse, AgentNotification) parse these methods into their typed
variants, and each request type implements JsonRpcRequest. Draft v2 also
adds tool_call/cancel and terminal/cancel (background work), which need
only unstable_protocol_v2.
An Agent.v2() agent without a handler for tool_call/cancel or
terminal/cancel answers them with -32602 (Invalid params) instead of
-32601 (Method not found), as the spec requires for a tool call or terminal
that is unknown or not cancellable. A typed or catch-all handler still takes
precedence. v1 and unguarded agents are unchanged.
After SDK 5.4.0, the SDK no longer overrides the fallback for these methods.
An unhandled method gets -32601. See the v2 cancellation
rules for the errors an
agent returns when it implements the method.
The schema’s unstable_proxy_chains feature is not forwarded: the SDK always
enables it. See Proxy chains.
The schema enums gained variants under these features. They are
#[non_exhaustive], so matches need no change.
Proxy chains
Proxy method names
The proxy protocol now uses the method names defined by the
ACP proxy chains RFD.
Earlier SDK releases used _-prefixed names, which ACP reserves for vendor
extensions.
| Old method | New method |
|---|---|
_proxy/initialize | proxy/initialize |
_proxy/successor | proxy/successor |
The message shapes are unchanged. proxy/successor still carries the wrapped
message’s method and params in its params and sends optional envelope
metadata as _meta. The non-spec meta key is no longer read on receive.
Upgrade conductors and proxies together
This is a wire-breaking rename with no compatibility fallback: the SDK no
longer sends or accepts the old _proxy/* names. A conductor built with this
release cannot drive a proxy built with an earlier release, and vice versa.
Upgrade the conductor and every proxy in a chain at the same time, including
nested conductors running in proxy mode.
Code that only uses the Proxy and Conductor roles and their default
forwarding needs no changes for the rename. Update any hard-coded method
strings, such as in raw JSON-RPC handlers, test fixtures, or trace filters.
Proxy types come from the schema crate
agent-client-protocol-schema 1.15 defines the proxy-chain messages behind
its unstable_proxy_chains feature. The SDK always enables that feature, so
proxy and conductor support needs no feature flag, and it uses the schema’s
types instead of its own. v1::schema and v2::schema re-export the schema
crate’s modules:
| Before | After |
|---|---|
schema::InitializeProxyRequest (SDK type) | v1::schema::InitializeProxyRequest (schema type) |
schema::v2::InitializeProxyRequest (SDK type) | v2::schema::InitializeProxyRequest (schema type) |
response of InitializeProxyRequest: InitializeResponse | v1::schema::InitializeProxyResponse / v2::schema::InitializeProxyResponse |
schema::METHOD_INITIALIZE_PROXY | v1::schema::PROXY_METHOD_NAMES.proxy_initialize |
schema::METHOD_SUCCESSOR_MESSAGE | v1::schema::PROXY_METHOD_NAMES.proxy_successor |
| (none) | v1::schema::ProxySuccessorRequest, ProxySuccessorNotification, ProxySuccessorResponse |
| (none) | v1::schema::ProxyRequest, ProxyResponse, ProxyNotification |
schema::SuccessorMessage | unchanged; see below |
Each v2 type is at the same name in v2::schema. The SDK implements its
JSON-RPC traits for all of them: InitializeProxyRequest is answered with
InitializeProxyResponse, ProxySuccessorRequest with
ProxySuccessorResponse (the wrapped request’s raw result), and
ProxyRequest with ProxyResponse.
InitializeProxyResponse is a transparent wrapper around the version’s
InitializeResponse, so the wire format is unchanged. A proxy that answers
proxy/initialize itself wraps its response, and one that forwards the
successor’s initialize response converts it:
// Before
async |request: v1::InitializeProxyRequest, responder, cx| {
cx.send_request_to(Agent, request.initialize)
.forward_response_to(responder)
}
responder.respond(v1::InitializeResponse::new(version))
// After
async |request: v1::InitializeProxyRequest, responder, cx| {
cx.send_request_to(Agent, request.initialize)
.map(|response| Ok(response.into()))
.forward_response_to(responder)
}
responder.respond(v1::InitializeResponse::new(version).into())
// or v1::InitializeProxyResponse::new(v1::InitializeResponse::new(version))
InitializeProxyRequest, InitializeProxyResponse and the successor
envelopes are #[non_exhaustive]. Build them with new, the builder methods,
or From (initialize.into()), and read their public fields.
SuccessorMessage stays as a typed view of proxy/successor
schema::SuccessorMessage<M> remains. The schema’s ProxySuccessorRequest
and ProxySuccessorNotification hold the wrapped message as a raw method
and raw params, and exist once per protocol version. SuccessorMessage<M>
holds the wrapped message as a typed SDK message M, works for every protocol
version, and for a wrapped request has that request’s response type, because
the RFD returns the result of a wrapped request unchanged. The SDK’s proxy
routing uses it to wrap and unwrap messages for a proxy’s successor.
Its wire format is the schema envelope and it is built and parsed through the schema types. As a result:
SuccessorMessageno longer implementsSerializeandDeserialize. Use itsJsonRpcMessageimplementation (to_untyped_message,parse_message), or the schema envelope types for raw JSON.- An envelope without
params, or with"params": null, is accepted and unwraps to a message without params. Earlier releases rejected an omittedparams. metaisOption<v1::schema::Meta>, the sameserde_json::Map<String, Value>as before. A_metathat is not an object is ignored.
SuccessorMessage is #[non_exhaustive]; build it with
SuccessorMessage::new(message) and .meta(meta).
Proxies send $/cancel_request plain
A proxy cancels a request it sent to its successor with a plain
$/cancel_request whose requestId is the ID of the proxy/successor
request, as the proxy chains RFD specifies. Earlier releases wrapped the
notification in proxy/successor. SentRequest::cancel,
RequestCancellationHandle::cancel and ConnectionTo::send_cancel_request_to
now send it plain for every peer. The conductor and the SDK still accept the
wrapped form and treat it the same way, so a v5 conductor works with proxies
built on earlier releases. No code change is needed unless you match the
wrapped form on the wire.
Results and errors pass through unchanged
The RFD requires the result or error of a wrapped request to reach the
original requester unchanged. The default proxy forwarding used to answer a
session/new with a parse error (-32700) when the successor’s result had no
readable sessionId. It now forwards that result unchanged and only skips
routing the session’s updates.
ConductorHostRole is sealed
agent-client-protocol-conductor::ConductorHostRole can no longer be
implemented outside the conductor crate. Its methods take a ConductorRunner,
whose fields are private, so no external implementation could be written
before either. Use the provided Agent and Proxy host roles.
ConductorHostRole is now a marker trait: its Instantiator type and its
initialize_method, select_protocol_version, instantiate and
handle_dispatch methods moved to a private supertrait and take an argument
only the conductor crate can create, so code outside it cannot call them.
ConductorImpl::new
is private. Create conductors with ConductorImpl::new_agent or
ConductorImpl::new_proxy.
Conductor changes
Instantiators receive a SelectedInitializeRequest
InstantiateProxies::instantiate_proxies,
InstantiateProxiesAndAgent::instantiate_proxies_and_agent and instantiator
closures receive a SelectedInitializeRequest instead of a
v1::schema::InitializeRequest, and return one inside InstantiatedProxies
or InstantiatedChain. It is the client’s initialize request, parsed for
the protocol version the conductor selected: SelectedInitializeRequest::V1
or, with unstable_protocol_v2, SelectedInitializeRequest::V2. This
affects every custom instantiator, including v1-only ones.
A v1-only instantiator converts the request with into_v1()?:
use agent_client_protocol_conductor::{
ConductorImpl, InstantiatedChain, SelectedInitializeRequest,
};
// Before
ConductorImpl::new_agent("my-conductor", |init_req: InitializeRequest| async move {
Ok((init_req, proxies, agent))
})
// After
ConductorImpl::new_agent("my-conductor", |init_req: SelectedInitializeRequest| async move {
let init_req = init_req.into_v1()?;
Ok(InstantiatedChain::new(init_req, proxies, agent))
})
SelectedInitializeRequest is #[non_exhaustive], so an instantiator that
handles each version matches the variants and adds a wildcard arm:
match init_req {
SelectedInitializeRequest::V1(request) => { /* .. */ }
SelectedInitializeRequest::V2(request) => { /* .. */ }
_ => return Err(Error::invalid_request()),
}
The v2 instantiator methods are removed
InstantiateProxies::instantiate_v2_proxies and
InstantiateProxiesAndAgent::instantiate_v2_proxies_and_agent
(unstable_protocol_v2) are removed. The single method receives a v2 request
as SelectedInitializeRequest::V2. Move the body of a v2 method into the
V2 arm of a match.
ConductorHostRole::initialize and InitializationOutcome are removed
ConductorHostRole::initialize, ConductorHostRole::initialize_with_outcome
and InitializationOutcome (unstable_protocol_v2) are removed. The
conductor initializes the chain itself and only calls the instantiator. See
ConductorHostRole is sealed.
Conductor internals are no longer exported
The conductor crate exports its API explicitly instead of through a glob.
ConductorRunner, ConductorMessage, ConductorSuccessor, ComponentIndex
and SourceComponentIndex are no longer public; they only described the
conductor’s internal routing.
Instantiators return InstantiatedChain and InstantiatedProxies
InstantiateProxiesAndAgent and InstantiateProxies, including instantiator
closures, return #[non_exhaustive] structs instead of tuples.
| Before | After |
|---|---|
Ok((request, proxies, agent)) | Ok(InstantiatedChain::new(request, proxies, agent)) |
Ok((request, proxies)) | Ok(InstantiatedProxies::new(request, proxies)) |
new takes impl Into<SelectedInitializeRequest>, so a v1::InitializeRequest
needs no .into().
Instantiators can negotiate down
SelectedInitializeRequest::into_v1 now converts a v2 request to v1 the way
the SDK’s agents negotiate initialize, instead of failing. An instantiator
may return a request for a lower version than the one the conductor selected,
and the chain then initializes with that version. A v1-only instantiator that
calls into_v1()? therefore accepts a v2 client and answers it with a v1
initialize response, where it used to reject it with -32600. Returning a
request for a version above the selected one is still rejected.
Other conductor changes
ConductorArgs,ConductorCommandand its variants are#[non_exhaustive]. CreateConductorArgsby parsing arguments withclap::Parser.trace::Protocolis renamed totrace::MessageProtocol, so it no longer shares a name with the coreProtocoltrait. The serialized trace format is unchanged.- The conductor’s
unstable_protocol_v2feature no longer enables the polyfill’s feature (it only did so for the conductor’s own tests). Enableunstable_protocol_v2onagent-client-protocol-polyfillyourself for a v2 chain. McpOverAcpPolyfillis#[non_exhaustive]. Create it withMcpOverAcpPolyfill::http().- The polyfill rewrites
McpServer::Acpentries insession/forkin every build. It used to forward them unchanged unlessunstable_session_forkwas enabled. - The polyfill forwards a repeated
proxy/initializeon the connection’s protocol version instead of closing its connection. An invalidprotocolVersionis answered with-32602instead of-32603, and a request for a different version than the first one with-32600. - A conductor in proxy mode forwards a repeated
proxy/initializethrough its chain, as a conductor in agent mode forwards a repeatedinitialize. It used to answer it with-32600(“only sent by the conductor”). - The conductor no longer forwards
proxy/successorfrom its client (in agent mode) or from its agent, or one wrapped in a secondproxy/successor. It answers such a request with-32600and drops such a notification. It used to forward them, so the client or the agent could send a message that a proxy received as coming from its successor. - Conductor traces record the messages between the last proxy and the agent. Trace snapshots and tools that read traces see these extra events.
agent_client_protocol_trace_viewer::TraceViewerConfigis#[non_exhaustive]. Start fromTraceViewerConfig::default()and use theportandopen_browsersetters.TraceSourceis no longer public.
The rmcp integration moves behind the rmcp_3 feature
agent-client-protocol-rmcp now has one module per supported rmcp major
version, each behind a matching Cargo feature. The rmcp 3.x integration lives
in the rmcp_3 module, enabled by the rmcp_3 feature. No rmcp feature is
enabled by default, so without one the crate is empty.
Enable the feature next to the features you already use; your own rmcp
dependency stays as it is:
[dependencies]
agent-client-protocol-rmcp = { version = "5", features = ["rmcp_3", "unstable_mcp_over_acp"] }
rmcp = "3"
The unstable_mcp_over_acp passthrough feature is unchanged and applies to
every rmcp module. The unstable_protocol_v2 passthrough feature is removed
because the crate has no v2-specific code. Enable unstable_protocol_v2 on
agent-client-protocol instead.
Then add rmcp_3:: to every import from the crate:
| Before | After |
|---|---|
agent_client_protocol_rmcp::McpServerExt | agent_client_protocol_rmcp::rmcp_3::McpServerExt |
agent_client_protocol_rmcp::McpServerBuilder | agent_client_protocol_rmcp::rmcp_3::McpServerBuilder |
agent_client_protocol_rmcp::McpTool | agent_client_protocol_rmcp::rmcp_3::McpTool |
agent_client_protocol_rmcp::tool_fn! | agent_client_protocol_rmcp::rmcp_3::tool_fn! |
agent_client_protocol_rmcp::tool_fn_mut! | agent_client_protocol_rmcp::rmcp_3::tool_fn_mut! |
McpTool, tool_fn! and tool_fn_mut! are re-exports of the
core crate’s items, which you can also import from
agent_client_protocol::mcp_server and agent_client_protocol directly.
Future rmcp major versions arrive as new features and modules (such as
rmcp_4) in minor releases, so you can enable both while moving your services
to the new rmcp major version. Removing support for an rmcp major version is a
breaking change and only happens in an ACP major release.
Other rmcp and mcp_server changes
EnabledToolsis no longer public. No public API took or returned it. Useenable_tool,disable_tool,enable_all_tools, anddisable_all_tools.McpServerBuilder::enable_tool/disable_toolandMcpToolRegistry::enable_tool/disable_toolreturnUnknownToolErrorinstead of a-32600Error.?still converts it into anError.McpServerExtis sealed. It was only meant to be implemented forMcpServer.McpConnectionContext::Acpis#[non_exhaustive]. Match it asMcpConnectionContext::Acp { server_id, .. }.- Builder-built servers report the builder name and
McpServerBuilder::version(default0.0.0) as their MCPserverInfo, notrmcp. - An error from a builder tool, including arguments that do not match its input
schema, is a
tools/callresult withisError: trueinstead of a JSON-RPC error. A call to an unknown or disabled tool still gets-32602.RegisteredMcpTool::call_toolreports bad arguments as-32602instead of-32603. - The native MCP-over-ACP path for
McpServer::from_rmcpand builder servers follows the core crate’sunstable_mcp_over_acpfeature. Before, enabling the feature only onagent-client-protocolmade each request bridge a new rmcp service.
HTTP transport
agent-client-protocol-http narrows its public types:
HttpClientErroris#[non_exhaustive], so matches need a wildcard arm.InvalidUrlandReqwestno longer implementFrom, and theirDisplaytext no longer repeats the underlying error. Walkstd::error::Error::sourceto see it.InvalidUrlnow holds an opaqueInvalidUrlErrorinstead ofurl::ParseError; it displays the parser’s message.CorsOptionsis an opaque struct. TheDisabled,AllowOrigins, andAllowAnyOriginvariants are gone. UseCorsOptions::disabled(),CorsOptions::allow_origins(...), andCorsOptions::allow_any_origin(), and compare policies with==.CorsOptions::allow_originsreturnsInvalidOriginErrorinstead ofaxum::http::header::InvalidHeaderValue. It names the rejected origin throughorigin().
The crate does not re-export axum, reqwest, or url. Its public API uses
third-party types in four places: AcpHttpServer::into_router returns an
axum::Router, HttpClientBuilder::configure_http and
HttpClient::from_http_client take reqwest types, and
HttpClientError::Reqwest holds a reqwest::Error. Depend on matching
versions of those crates to use them.
AcpAgent
AcpAgent::spawn_processis no longer public. It returnedasync_processtypes and skipped the process-group teardown thatConnectToinstalls. Connect theAcpAgentitself instead.AcpAgent::claude_agent()andAcpAgent::codex()are removed. They rannpx -y ...@latest, which installs whatever version was published last. Name the adapter version yourself:
#![allow(unused)]
fn main() {
use std::str::FromStr;
use agent_client_protocol::AcpAgent;
let agent = AcpAgent::from_str("npx -y @agentclientprotocol/claude-agent-acp@<version>")?;
Ok::<(), agent_client_protocol::Error>(())
}
Migrating to Core v3
The 3.0 release paired agent-client-protocol 3.x with
agent-client-protocol-rmcp 4.x and rmcp 3.x. Applications using the
integration must upgrade both public dependencies together; see the
rmcp integration migration for service and tool API
changes. The minimum supported Rust version remains 1.88.
For the other transport changes in core 3.x, follow:
- Migrating Connection Drivers for
(Channel, Option<ConnectionDriver>)and active/passive transport ownership. - Migrating the Native MCP Binding for the replacement of connect/disconnect with request-scoped MCP 2026-07-28.
- Migrating Custom HTTP Client Construction for WebSocket configuration through the transport builder instead of a prebuilt reqwest client.
- Native MCP-over-ACP for request-scoped provider usage and the MCP HTTP bridge for modern-only HTTP re-export.
For Cargo feature selection and defaults, see Cargo Features.
For non-exhaustive server options and CORS policies, see Migrating the Config API. Agent subprocess config constructors and fluent methods remain unchanged.
Raw responses are no longer ACP errors
RawJsonRpcMessage::Response now contains RawJsonRpcResponse, whose error
variant carries Box<RawJsonRpcError> instead of an ACP Error. Typed ACP
request APIs still return ACP Error; raw transports, interceptors, and
relays must use the protocol-neutral type.
Raw error codes are i32, not ErrorCode. Raw errors distinguish omitted
data from explicit JSON null and preserve unknown error-object fields in
extra. Do not interpret MCP or other protocols’ error codes as ACP codes.
Construct and match raw responses
Use RawJsonRpcResponse::new with a Result<Value, Box<RawJsonRpcError>>, or
construct its Result and Error variants directly. Use the constructor for
the non-exhaustive raw error struct, then set data and extensions:
use agent_client_protocol::{RawJsonRpcError, RawJsonRpcMessage, RawJsonRpcResponse};
use serde_json::{Value, json};
fn main() {
let success = RawJsonRpcResponse::new(1_i64, Ok(json!({"answer": 42})));
assert!(matches!(success, RawJsonRpcResponse::Result { .. }));
let mut error = RawJsonRpcError::new(-32000, "Tool unavailable").data(Value::Null);
error.extra.insert("retryable".into(), json!(true));
let failure = RawJsonRpcResponse::Error {
id: 2_i64.into(),
error: Box::new(error),
};
let message = RawJsonRpcMessage::Response(failure);
match message {
RawJsonRpcMessage::Response(RawJsonRpcResponse::Result { id, result }) => {
println!("{id}: {result}");
}
RawJsonRpcMessage::Response(RawJsonRpcResponse::Error { id, error }) => {
assert_eq!(error.code, -32000);
assert!(error.data.is_null());
assert_eq!(error.extra["retryable"], json!(true));
println!("{id}: {}", error.message);
}
_ => panic!("expected a response"),
}
}
RawJsonRpcError::new leaves data omitted; .data(Value::Null) explicitly
includes "data": null. The boxing is required by the response type.
Convert only at a typed ACP boundary
When a response is known to be ACP, explicitly unbox and consume the raw
error with into_acp_error. This interprets ACP error codes, keeps data
presence, and intentionally discards error extension fields:
use agent_client_protocol::{Error, ErrorCode, RawJsonRpcError, RawJsonRpcResponse};
use serde_json::{Value, json};
fn into_acp_result(response: RawJsonRpcResponse) -> Result<Value, Error> {
match response {
RawJsonRpcResponse::Result { result, .. } => Ok(result),
RawJsonRpcResponse::Error { error, .. } => Err((*error).into_acp_error()),
}
}
fn main() {
// This response belongs to ACP, where -32000 means authentication required.
let mut raw = RawJsonRpcError::new(-32000, "Authentication required").data(Value::Null);
raw.extra.insert("peerExtension".into(), json!(true));
let response = RawJsonRpcResponse::new(3_i64, Err(Box::new(raw)));
let error = into_acp_result(response).unwrap_err();
assert_eq!(error.code, ErrorCode::AuthRequired);
assert_eq!(error.data, Some(Value::Null));
let raw_again = RawJsonRpcError::from(error);
assert!(raw_again.extra.is_empty()); // Conversion is not a lossless relay.
}
For locally generated ACP responses, RawJsonRpcMessage::response(id, Result<Value, Error>) remains available and converts the ACP error to its raw
representation. It is not a constructor for another protocol’s errors.
Relay without ACP interpretation
Forward a raw message unchanged when no ID rewrite is needed. If a relay
maps request IDs, move the original boxed raw error into the new response;
do not round-trip it through Error or RawJsonRpcMessage::response:
use agent_client_protocol::{RawJsonRpcMessage, RawJsonRpcResponse};
use serde_json::{Value, json};
fn main() {
// A downstream protocol's -32000 is not necessarily ACP AuthRequired.
let wire = json!({
"jsonrpc": "2.0",
"id": "downstream",
"error": {
"code": -32000,
"message": "Tool unavailable",
"data": null,
"retryable": true
}
});
let message: RawJsonRpcMessage = serde_json::from_value(wire.clone()).unwrap();
let RawJsonRpcMessage::Response(response) = message else {
panic!("expected a response");
};
let upstream_id = String::from("upstream").into();
let relayed = match response {
RawJsonRpcResponse::Result { result, .. } => {
RawJsonRpcResponse::Result { id: upstream_id, result }
}
RawJsonRpcResponse::Error { error, .. } => {
RawJsonRpcResponse::Error { id: upstream_id, error }
}
};
let actual: Value = serde_json::to_value(RawJsonRpcMessage::Response(relayed)).unwrap();
let mut expected = wire;
expected["id"] = json!("upstream");
assert_eq!(actual, expected); // Code, explicit null, and extensions survive.
}
The same relay rule preserves omission when the input has no data field.
See the raw response reference for
the protocol boundary.
Migrating the Config API
The 3.0 release made agent-client-protocol-http::ServerOptions,
agent-client-protocol-http::CorsOptions, and
agent-client-protocol::AcpAgentConfig non-exhaustive so future configuration
fields or policies can be added without another breaking release.
HTTP server options
Breaking: downstream crates cannot construct ServerOptions with a struct
literal, including ..ServerOptions::default() update syntax.
Before (no longer compiles outside the HTTP crate):
let options = ServerOptions {
path: "/agent".into(),
cors: CorsOptions::allow_origins(["https://example.com"])?,
health_endpoint: false,
};
// Partial literals with ..ServerOptions::default() also need migration.
After:
#![allow(unused)]
fn main() {
use agent_client_protocol_http::{CorsOptions, ServerOptions};
let options = ServerOptions::default()
.with_path("/agent")
.with_cors(CorsOptions::allow_origins(["https://example.com"])?)
.with_health_endpoint(false);
}
All existing fields remain public, so reading or assigning options.path,
options.cors, or options.health_endpoint still works. Destructuring patterns
must include ...
Defaults and runtime policies are unchanged: /acp, disabled cross-origin
browser access, and an enabled /health endpoint. Setters replace the chosen
value and preserve the other options.
CORS policies
In 3.x, CorsOptions was a #[non_exhaustive] enum, so exhaustive matches
outside the HTTP crate needed a wildcard arm.
Breaking: in v5, CorsOptions is an opaque struct and its variants are no
longer public. Code that matched on the variants no longer compiles.
Build policies with CorsOptions::disabled(), CorsOptions::allow_origins(...),
or CorsOptions::allow_any_origin(), and compare them with ==:
#![allow(unused)]
fn main() {
use agent_client_protocol_http::CorsOptions;
fn is_disabled(policy: &CorsOptions) -> bool {
*policy == CorsOptions::disabled()
}
}
CORS does not authenticate requests. Authorization headers and credentialed CORS are host-owned policies; see browser authentication and credential policy.
Agent subprocess configuration
AcpAgentConfig already has private fields. Keep using its existing constructor
and fluent methods; no new builder type or Default is required because an
executable must be specified:
#![allow(unused)]
fn main() {
use agent_client_protocol::AcpAgentConfig;
let config = AcpAgentConfig::new("python")
.arg("agent.py")
.args(["--mode", "fast"])
.env("RUST_LOG", "info")
.envs([("NO_COLOR", "1")]);
}
Its getters, serialization, required command, empty argument/environment
defaults, and rejection of unknown JSON fields are unchanged.
Migrating the Native MCP Binding
The unstable connection-oriented prototype is replaced by a request-scoped binding for MCP 2026-07-28 only. Standalone MCP serving is unaffected.
| Previous prototype | New binding |
|---|---|
mcp/connect, mcp/disconnect | Removed |
McpConnectionId, connectionId | Removed |
mcp/message(connectionId, method, params) | mcp/message(serverId, requestId, method, params) |
| MCP initialization | Version and client capabilities in every request |
| Reverse MCP requests | MRTR results followed by explicit caller retries |
| Raw result or outer MCP error | Exactly one inner result or error carrier |
| Shared HTTP session and GET stream | Independent HTTP POSTs |
Keep the advertised server ID and generate a fresh McpRequestId per operation.
Use MessageMcpRequest::new(server_id, request_id, method) with MCP version and
client capabilities in the inner _meta. Do not send initialize; optional
discovery is an ordinary request.
Match MessageMcpResponse::{Result, Error} after handling outer ACP failure.
Never interpret an inner MCP error through ACP’s error-code enum. Explicit
data: null, unknown error extensions, and opaque result metadata survive.
V1 and v2 carriers remain separate Rust types.
For native providers, prefer reusable McpService implementations and
request-scoped McpRequestContext. from_rmcp lazily creates one shared
application service for ACP execution; standalone connections still use the
factory. Scoped tool builders remain available.
McpConnectionContext::Acp and McpConnectionTo::request_id() now identify an
operation, not a connection. Standalone contexts have no logical request ID.
Observe operation cancellation and finish owned cleanup before returning. Removing a registration or closing the ACP connection stops active work. There is no new unadvertisement message: omitting a declaration from a later setup request is not removal of the local registration.
The local HTTP polyfill re-exports native tools with its own server-bound
Authorization header. Preserve that header, not a bearer token in the URL.
Transport-only x-mcp-header annotations are normalized; an external HTTP
gateway’s parameter-header policy is not transported.
The merged connection-driver API is
unchanged: passive endpoints remain None, and owned adapters retain their
graceful-finish capability. Raw Channel sender/receiver types and generic
queue policies are unchanged by this migration.
See the native guide and HTTP adapter contract for usage and lifecycle details.
Migrating Connection Drivers
ConnectTo::into_channel_and_future now returns
(Channel, Option<ConnectionDriver>) instead of
(Channel, BoxFuture<'static, Result<()>>). The same change applies when
accessing a component through DynConnectTo.
This is a source-breaking transport-adapter change. It does not change ACP wire
messages, the raw Channel sender/receiver types, or unbounded_send, and it
introduces no new frame-size, queue, or task limits.
Components using the default conversion
If your component implements only connect_to, no change is needed. The
default conversion still creates a channel pair and drives your component, now
returning Some(ConnectionDriver). That default wraps opaque work; it cannot
infer a physical finish hook. A buffered transport that needs a finite
foreground to await physical flush should override normalization with
with_finish, as described below.
Low-level callers must handle the optional work explicitly. The optional value is not a future: awaiting it directly no longer compiles. For a component that is known to own work, extract its driver before polling it:
let (channel, driver) = component.into_channel_and_future();
let driver = driver.expect("this component owns connection work");
// Use channel while continuing to poll the driver.
driver.await?;
For a generic component, handle both cases: poll Some(driver) alongside
traffic and drain accepted output on completion; for None, retain the
channel’s independent halves until they close. Absence of work is not EOF.
Do not replace None with a ready-success future in a shutdown race.
Custom conversion overrides
Import ConnectionDriver from agent_client_protocol and change the return
type. Wrap a future that owns the connection work with ConnectionDriver::new:
fn into_channel_and_future(self) -> (Channel, Option<ConnectionDriver>) {
let (channel, future) = self.into_channel_transport();
(channel, Some(ConnectionDriver::new(future)))
}
For an endpoint whose work is driven elsewhere, return None instead of
wrapping a ready no-op future:
fn into_channel_and_future(self) -> (Channel, Option<ConnectionDriver>) {
(self.channel, None)
}
An existing Channel has no driver. There is no awaitable passive sentinel,
and no finish hook belongs to the None case. ConnectionDriver always holds
real owned work; cooperative drivers additionally support a finish hook.
Passive bridges retain each read/write half until its
own closure; an input half-close can still be followed by a final response.
If a wrapper simply exposes another component’s endpoint, return its original
(channel, optional_driver) pair. Re-boxing an owned driver and wrapping it
with new would hide its finish capability. Inventing a ready
driver for None would also turn absence into a false completion signal.
For tracing, error annotation, or completion cleanup, decorate the future with
map_future. This preserves both the finish capability and any already-issued
request; opaque work stays opaque:
use futures::FutureExt;
let (channel, driver) = component.into_channel_and_future();
let driver = driver.map(|driver| {
driver.map_future(|work| {
work.inspect(|result| eprintln!("transport completed: {result:?}"))
})
});
(channel, driver)
The transformed future must still drive the original work and must not report success before its accepted output has drained.
Completion and drain responsibilities
Poll owned work and outbound forwarding concurrently. A driver may need its outbound request to be delivered before it can receive a response and finish.
An adapter must not report success before flushing output it already accepted.
Use ConnectionDriver::with_finish(future, finish) for a custom normalized
transport that needs to flush during finite foreground shutdown. The
nonblocking FnOnce() hook requests graceful completion; the future proves
completion and reports any I/O error.
let (finish_tx, finish_rx) = futures::channel::oneshot::channel();
let future = async move {
// Keep processing input and output while waiting for the finish request.
// A dropped sender is not a finish request; it may simply mean that
// finish control was abandoned while normal half-closes remain in use.
//
// After a successful signal, seal the outgoing queue, drain every accepted
// frame, and flush/close the physical write half. Do not wait for remote
// read EOF; continue observing genuine I/O errors during the drain.
run_custom_adapter(outgoing_rx, physical_io, finish_rx).await
};
let driver = ConnectionDriver::with_finish(future, move || {
let _ = finish_tx.send(());
});
(channel, Some(driver))
SDK shutdown coordination invokes this hook only after protocol output has
been handed off to the normalized transport, then awaits the driver. Low-level
callers can use driver.request_finish() themselves. A true return means
cooperative finish is supported and has been requested, including a request
already issued. Requests are idempotent, but the hook runs only once. A false
return means opaque work, not “already requested.”
Requesting finish does not prove output has finished flushing; continue polling or await the driver. Capability remains intact if that driver is handed to another owner while flushing. Quiesce and hand off output before requesting finish; idempotence does not permit new output after sealing. Dropping the driver drops its owned future without a graceful request. Dropping only the hook does not invoke it or necessarily stop that future.
There is no implicit timeout. A cooperative adapter that cannot flush keeps
the connection pending, so applications that need a deadline must impose one
and accept that cancelling it can truncate output. with_finish declares the
adapter’s contract; it cannot make an arbitrary future or external buffer
flush automatically.
Built-in Lines and ByteStreams preserve normal half-close behavior. When
their owner explicitly finishes, they drain accepted output while continuing
to poll incoming I/O for errors, rather than waiting for unrelated remote
input to reach EOF. Errors may terminate the connection without graceful drain.
Direct adapter entry point
Returning a cooperative driver from into_channel_and_future lets normalized
SDK consumers coordinate finish. A custom transport’s direct connect_to
implementation must coordinate it too: try_join!(bridge, driver) alone can
wait forever after a finite peer has returned.
This scaffold follows the built-in Lines policy, using only public APIs:
use agent_client_protocol::{Channel, ConnectTo, ConnectionDriver, Result, UntypedRole};
use futures::{future::{select, Either}, FutureExt};
struct BufferedAdapter {
channel: Channel,
driver: ConnectionDriver,
}
impl ConnectTo<UntypedRole> for BufferedAdapter {
async fn connect_to(self, peer: impl ConnectTo<UntypedRole>) -> Result<()> {
let bridge = Box::pin(self.channel.connect_to(peer));
match select(bridge, self.driver).await {
Either::Left((result, mut driver)) => {
result?; // The peer's accepted output has been handed off.
if driver.request_finish() {
driver.await // Prove physical drain; propagate its errors.
} else {
// Preserve a ready error, then cancel opaque work.
driver.now_or_never().unwrap_or(Ok(()))
}
}
Either::Right((result, _bridge)) => result,
}
}
fn into_channel_and_future(self) -> (Channel, Option<ConnectionDriver>) {
(self.channel, Some(self.driver))
}
}
The adapter’s own future must own/close its physical producers before reporting completion. Its finish implementation must stop forwarding successful input to a completed peer while still observing genuine read errors during drain. Otherwise, late input can fail against the dropped receiver and cancel final output. Both direct and normalized entry points should be tested with output backpressure and independently open input.
Finite foreground shutdown
On successful Builder::connect_with foreground completion, routable queued
output is drained. Requests still blocked on unresolved readiness are failed
and removed rather than published after shutdown. Physical transport and
protocol progress continue during this drain; queued application tasks are
not started merely to finish the sink. The inherited cleanup coordinator can
still poll application tasks while protecting a close callback already
underway; a blocked close callback can delay completion.
Foreground success stops beginning new application delivery or close callbacks. Physical reads remain driven without delivering their input to the completed foreground. A close callback already underway finishes before the outgoing drain boundary seals, and its errors retain precedence.
Protocol connectors and routers use the same ownership-aware rule. An owned foreground’s completion requests cooperative drain instead of waiting for unrelated remote input. Initialization rejection also hands off its reply before requesting finish. Passive half-closes alone do not request finish; they preserve the other direction for a final response.
Cooperative drivers, both built-in and custom, are awaited through physical
write shutdown.
An opaque driver constructed with ConnectionDriver::new(future) has no
externally requestable finish control: finite foreground shutdown transfers
protocol output into its normalized channel, then cancels that work without
guaranteeing custom physical flush. Reactive connect_to still joins owned
work after input EOF. Choose new for opaque cancellable work and with_finish
when the adapter can honor an explicit graceful-finish request.
See Transport Architecture for the active/passive boundary and forwarding rules.
Migrating the rmcp Integration to v4
The 4.0 release of agent-client-protocol-rmcp upgraded its public rmcp
dependency from 2.x to 3.4. This is a breaking change for integrations that
pass rmcp services or types across the crate boundary. It shipped together
with the core agent-client-protocol 3.x release, which also changed public
APIs. Migrate both public dependencies together; the minimum supported Rust
version remains 1.88.
| Integration crate | Core ACP SDK | MCP SDK |
|---|---|---|
agent-client-protocol-rmcp 4.x | 3.x | rmcp 3.x |
agent-client-protocol-rmcp 3.x | 2.x | rmcp 2.x |
Upgrade the application’s core ACP and rmcp dependencies together with the
integration crate. See the core 3.x migration guide for
raw-response API changes and links to the transport migrations.
A service implementing rmcp 2.x’s Service cannot be passed to the new
McpServer::from_rmcp, even when it provides the same tools.
Custom services and tools
- Use
ServerConfigandClientConfiginstead of the deprecatedServerInfoandClientInfoaliases. - A manual
ServerHandler::call_toolimplementation now returnsResult<CallToolResponse, ErrorData>. Convert a completedCallToolResultwith.into(). The response enum also represents MRTR input-required results and task-extension results; do not assume every response is a completed tool result. - Functions registered with rmcp’s
#[tool]macro can still returnCallToolResult. The ACP integration’stoolandtool_fnbuilder APIs also remain available, and their results become completed tool responses. ToolExecutionandTool::with_executionare no longer part of the tool model. Do not add the old task-execution marker to tool definitions.
For example, a manual handler that previously returned
Ok(CallToolResult::structured(value)) returns
Ok(CallToolResult::structured(value).into()) under its new
CallToolResponse return type.
Modern MCP is now available to supplied services
rmcp 3.4 implements discovery, per-request metadata, modern result shapes,
MRTR, and subscription APIs for MCP 2026-07-28. The adapter preserves those
requests and results when using McpServer::from_rmcp; a supplied service is
still responsible for its advertised capabilities and handlers.
The integration tests exercise both the built-in tool server and a supplied
rmcp service with actual 2026-07-28 requests, without sending initialize.
They cover direct tool calls before discovery, discovery itself, per-request
version errors, and an MRTR retry with fresh request metadata.
The dependency requirement supports rmcp 3.4 and later compatible 3.x versions; the workspace lockfile currently resolves 3.5. Their version constants differ:
- In rmcp 3.4,
ProtocolVersion::LATESTis 2025-11-25. - In rmcp 3.5,
ProtocolVersion::LATESTis 2026-07-28, which has no initialize handshake.LATEST_WITH_INITIALIZEis 2025-11-25.
Do not treat a changing LATEST constant or dependency upgrade alone as
protocol selection. For modern no-initialize requests, explicitly select
ProtocolVersion::V_2026_07_28 and include the required request metadata.
For a legacy initialize handshake, select its supported revision; with rmcp
3.5, LATEST_WITH_INITIALIZE names the latest such revision. The native ACP
binding below requires modern per-request metadata regardless of the resolved
rmcp version.
Native attachments also migrate in this release
The combined release replaces ACP’s unstable mcp/connect / mcp/disconnect
binding with request-scoped, server-addressed mcp/message operations for
MCP 2026-07-28 only, without initialization. Migrate native attachments
using the native binding migration and
request-scoped MCP guide. from_rmcp lazily creates one
shared application service for native requests, whose metadata, notifications,
and cancellation belong to each operation.
Standalone rmcp connections still use the factory per connection and retain rmcp’s protocol negotiation; the native binding’s modern-only requirement does not apply to them. Custom transports and low-level connection callers must also follow the connection-driver migration for the core 3.x API.
Migrating from agent-client-protocol 1.x to 2.0
Version 2.0 makes JSON-RPC notification semantics explicit, changes the low-level in-process
transport boundary so frames remain intact across components and adapters, clarifies the
distinction between responding to requests and routing responses, makes dynamic handler lifetimes
explicit, and gives AcpAgent an SDK-owned process-launch configuration instead of reusing an MCP
wire-schema type. It also replaces the SDK-local MCP-over-ACP wire extension with the shared
schema’s opt-in native transport.
Coordinated crate versions
Most published workspace crates move to the 2.x version family together. Crates whose public APIs
expose core SDK types must use the matching major release; the trace viewer and cookbook are
version-aligned as part of the coordinated release but do not impose that public dependency
constraint. The rmcp integration moves to 3.x because both agent-client-protocol and rmcp are
public dependencies in its API:
| Crate | Coordinated release |
|---|---|
agent-client-protocol | 2.x |
agent-client-protocol-derive | 2.x |
agent-client-protocol-conductor | 2.x |
agent-client-protocol-cookbook | 2.x |
agent-client-protocol-http | 2.x |
agent-client-protocol-polyfill | 2.x |
agent-client-protocol-trace-viewer | 2.x |
agent-client-protocol-rmcp | 3.x |
Notifications cannot receive error responses
The SDK no longer exposes ConnectionTo::send_error_notification, and
Dispatch::respond_with_error has been removed. Match the dispatch variant when a catch-all
handler needs different behavior:
#![allow(unused)]
fn main() {
use agent_client_protocol::{Dispatch, Error};
fn handle(message: Dispatch) -> Result<(), Error> {
match message {
Dispatch::Request(_, responder) => {
responder.respond_with_error(Error::method_not_found())
}
Dispatch::Notification(_) => Ok(()),
Dispatch::Response(result, router) => router.route_with_result(result),
}
}
}
In most applications, omit the catch-all handler entirely. The built-in fallback responds to
unknown requests with Method not found, ignores unhandled notifications, and routes responses
to their pending requests.
TypeNotification no longer has a role parameter or takes a connection:
#![allow(unused)]
fn main() {
use agent_client_protocol::util::TypeNotification;
// 1.x
// TypeNotification::<Peer>::new(message, &connection)
// 2.0
TypeNotification::new(message)
;
}
The notification type parameter of Dispatch<Req, Notif> now requires
Notif: JsonRpcNotification, matching the variant it can contain. The duplicate
Dispatch::erase_to_json method was removed; use into_untyped_dispatch.
Raw channels carry frames
Channel is now the single batch-aware in-process transport boundary. Its rx and tx carry
TransportFrame, not Result<RawJsonRpcMessage, Error>:
#![allow(unused)]
fn main() {
use agent_client_protocol::{Channel, RawJsonRpcMessage, TransportFrame};
fn send(channel: &Channel, message: RawJsonRpcMessage) {
channel.tx.unbounded_send(TransportFrame::Single(message)).unwrap();
}
}
TransportFrame distinguishes a valid single message, a non-empty TransportBatch, and an
explicit malformed wire value. Each batch contains public TransportBatchEntry values so a
relay can retain invalid siblings without turning a protocol error into a transport failure.
All three public frame types implement Clone, and TransportBatch::into_entries() provides an
owned, source-order iterator.
Transport I/O failures are returned by the future from
ConnectTo::into_channel_and_future; they are never channel items. Components should preserve a
received frame intact when relaying it so batch response grouping remains correct.
TransportFrame::parse_json returns a frame directly for every input. It retains malformed
response-shaped values so raw framed intermediaries can preserve them; protocol actors suppress
replies to response-only shapes. Standalone malformed input keeps its exact source text. Batch
entries retain parsed JSON values and source order, but reserialization may normalize whitespace.
The standard line, byte-stream, stdio, HTTP, and WebSocket transports now accept incoming
JSON-RPC batches in both protocol v1 and v2 mode. Entries are handled independently, replies are
grouped into one response array, notification-only batches produce no reply, and an empty array
produces one standalone Invalid Request response. Malformed entries that are response-shaped but
not call-shaped are ignored because JSON-RPC responses must not themselves receive responses. The
SDK does not initiate batches of requests or notifications.
Batch support was later removed:
TransportFrame::Batch,TransportBatch, andTransportBatchEntryno longer exist, and every connection answers a JSON array with a singleInvalid Requesterror. See Transport Architecture.
Dropping a Responder for one request in a batch now produces an Internal Error fallback after
dispatch completes, allowing completed sibling responses to flush. A handler error overrides the
fallback with that error. The longstanding behavior for an individual request is unchanged:
dropping its responder does not automatically send a response.
Existing ConnectTo implementations that override into_channel_and_future must now return the
frame-aware Channel. Most components need to implement only ConnectTo::connect_to; a direct
channel adapter may still override into_channel_and_future to avoid an intermediate copy.
Response routing uses routing terminology
ResponseRouter completes a local pending request; it does not send a new JSON-RPC response.
Its methods have therefore been renamed:
| 1.x | 2.0 |
|---|---|
respond_with_result | route_with_result |
respond | route |
respond_with_error | route_with_error |
respond_with_internal_error | route_with_internal_error |
Responder still uses respond*, because it sends the response to an incoming request.
If a catch-all response handler returns Err, that error is now routed to the local
SentRequest awaiter. It is never serialized as a response to the peer’s response. This replaces
the misleading generic failure that previously appeared when the real interceptor error was lost.
Response callbacks enforce ordered dispatch
The 1.x documentation said that on_receiving_result and on_receiving_ok_result callbacks held
the dispatch loop until completion, but the implementation did not enforce that ordering. In 2.0,
registering either callback before a peer response is routed during its original dispatch selects
ordered consumption: registration returns immediately, then the loop waits for response handling
to finish before processing the next message.
This is a behavioral change. An ordered response callback must not await a later response,
notification, or other inbound traffic on the same connection, because the loop cannot dispatch
that traffic until the callback returns. Spawn that follow-up work and return from the callback,
or use block_task from a task that already runs outside the dispatch loop, such as the foreground
future passed to connect_with.
The barrier is not retroactive. A pending-request failure delivered without an incoming response
(such as EOF), a response that was already routed, or a retained ResponseRouter routed after its
original dispatch runs without holding the loop.
Session-start helpers apply this barrier only to framework-owned runner and routing installation, then spawn the user callback. This preserves the actual 1.x scheduling behavior for user session work while correcting the old documentation that claimed the user callback itself blocked dispatch.
Request IDs remain typed
Responder::id, ResponseRouter::id, and SentRequest::id now return &RequestId.
Dispatch::id returns Option<&RequestId>. Clone the ID when it must outlive the handle:
#![allow(unused)]
fn main() {
let id = sent_request.id().clone();
}
This removes JSON round-trips and lets IDs pass directly to APIs such as request cancellation. If an integration still needs an untyped JSON value, serialize the borrowed ID explicitly:
#![allow(unused)]
fn main() {
let id_json = serde_json::to_value(sent_request.id())?;
let dispatch_id_json = dispatch.id().map(serde_json::to_value).transpose()?;
let _ = (id_json, dispatch_id_json);
}
Dynamic handlers use a guard
DynamicHandlerRegistration is now DynamicHandlerGuard and is exported from the crate root.
The guard is must_use and no longer Clone: keep its single owner in the object that owns the
registration. Dropping it unregisters the handler. To leave a handler registered for the rest of
the connection, replace run_indefinitely() with detach(). Detaching no longer leaks an extra
ConnectionTo handle.
Background tasks use runner terminology
Builder extensions implementing RunWithConnectionTo run alongside the connection; they do not
respond to an individual JSON-RPC request. The builder method now reflects that distinction:
| 1.x | 2.0 |
|---|---|
Builder::with_responder | Builder::with_runner |
The conductor crate applies the same terminology to its public background task:
| 1.x | 2.0 |
|---|---|
agent_client_protocol_conductor::ConductorResponder | agent_client_protocol_conductor::ConductorRunner |
This is a type rename only; custom code that names the conductor task should update its imports and type references.
Matchers use dispatch terminology
The combined matchers operate on Dispatch values, which can represent requests, notifications,
or responses. Their method names now reflect that input:
| 1.x | 2.0 |
|---|---|
MatchDispatch::if_message | MatchDispatch::if_dispatch |
MatchDispatchFrom::if_message_from | MatchDispatchFrom::if_dispatch_from |
Connection and session accessors borrow
McpConnectionTo::acp_id is now server_id and returns Option<&McpServerAcpId>. The new name
matches the native McpServer::Acp declaration; the Option reflects that a server can also be
connected directly without ACP. connection_id returns an Option<&McpConnectionId> for the
distinct active connection created by mcp/connect. Use context() to match explicitly on
McpConnectionContext::Standalone or McpConnectionContext::Acp { server_id, connection_id }.
The deprecated acp_url alias was removed. McpConnectionTo::connection_to is now connection
and returns &ConnectionTo<_>.
ActiveSession::modes and ActiveSession::meta now return Option<&T> instead of &Option<T>,
and ActiveSession::connection returns &ConnectionTo<_>.
These accessors avoid implicit allocation and handle cloning. Call .cloned() on server_id(),
connection_id(), modes, or meta, and .clone() on either connection accessor when an owned
value is required.
MCP servers use the native opt-in transport
The runtime-agnostic agent_client_protocol::mcp_server module remains available without an
unstable ACP feature, so standalone MCP servers do not allocate or retain schema transport IDs.
Enable the feature when attaching a server to ACP with Builder::with_mcp_server or
SessionBuilder::with_mcp_server:
agent-client-protocol = { version = "2", features = ["unstable_mcp_over_acp"] }
agent-client-protocol-rmcp no longer enables this feature merely to build or directly serve an
MCP server. Applications that attach an rmcp-backed server to ACP should enable its matching
unstable_mcp_over_acp passthrough feature. The transport remains unstable and may change
independently of the stable ACP surface.
In 1.x, the SDK represented an ACP-provided MCP server as McpServer::Http with an acp: URL and
routed it through SDK-local underscore-prefixed methods. In 2.0, providers and native consumers
use:
McpServer::Acp(McpServerAcp { name, server_id, .. })in session setup requests;mcp/connectwithserverId, returning a distinctconnectionId;mcp/messagerequests and notifications keyed by that connection ID; and- a request/response
mcp/disconnectexchange.
The low-level SDK-local McpConnectRequest, McpConnectResponse, McpOverAcpMessage, and
McpDisconnectNotification types were removed. Use the feature-gated schema types instead:
| 1.x SDK-local type | 2.0 schema type |
|---|---|
McpConnectRequest | schema::v1::ConnectMcpRequest |
McpConnectResponse | schema::v1::ConnectMcpResponse |
McpOverAcpMessage request | schema::v1::MessageMcpRequest |
McpOverAcpMessage notification | schema::v1::MessageMcpNotification |
McpDisconnectNotification | schema::v1::DisconnectMcpRequest and DisconnectMcpResponse |
The public method-name constants moved to the schema’s generated method-name tables:
| 1.x SDK-local constant | 2.0 schema constant |
|---|---|
METHOD_MCP_CONNECT_REQUEST | schema::v1::CLIENT_METHOD_NAMES.mcp_connect |
METHOD_MCP_MESSAGE | schema::v1::CLIENT_METHOD_NAMES.mcp_message or AGENT_METHOD_NAMES.mcp_message, depending on direction |
METHOD_MCP_DISCONNECT_NOTIFICATION | schema::v1::CLIENT_METHOD_NAMES.mcp_disconnect |
Code using Builder::with_mcp_server or SessionBuilder::with_mcp_server continues to attach the
high-level server in the same place; the emitted declaration and wire methods change. Global
builder attachment advertises the same server ID on session/new, session/load,
session/resume, and feature-gated session/fork. Stable v1 per-session attachment remains
specific to session/new; draft v2 additionally supports per-session resume attachment through
V2ResumeSessionBuilder::with_mcp_server and feature-gated fork attachment through
V2ForkSessionBuilder::with_mcp_server. Do not construct an HTTP server with an acp: URL. If the
final agent accepts HTTP but not native ACP MCP servers, insert McpOverAcpPolyfill immediately
before it. The polyfill now consumes native McpServer::Acp declarations and adapts only its
final-agent-facing side.
The polyfill’s public BridgeMode enum and McpOverAcpPolyfill::stdio were removed because the
required conductor mcp helper subcommand no longer exists. The polyfill has one supported mode;
construct it with McpOverAcpPolyfill::http() or Default, or manage a standard MCP transport
separately.
Low-level helpers have a narrower surface
NullHandler::new was removed. Construct the unit struct as NullHandler or use
NullHandler::default().
MatchDispatch::from_handled was removed because it exposed an internal composition state. Start
a standalone match with MatchDispatch::new, or continue a peer-aware chain with
MatchDispatchFrom.
Channel::copy is now an implementation detail. Connect channels through ConnectTo, or use
Channel::bridge_with_inspection when building an inspecting relay.
DynConnectTo::type_name now returns &'static str without allocating. Call .to_owned() when
an owned type name is required.
The generic util::both helper was removed. Replace util::both(a, b).await with
futures::future::try_join(a, b).await.map(|((), ())| ()).
util::process_stream_concurrently is no longer public. An equivalent unbounded fallible loop can
be written with futures::{StreamExt, TryStreamExt}:
stream
.map(Ok::<_, agent_client_protocol::Error>)
.try_for_each_concurrent(None, |item| process_fn(item))
.await
Pass a finite limit instead of None to bound concurrency.
ConnectionTo::attach_session is no longer public. Create sessions through
ConnectionTo::build_session, build_session_cwd, or build_session_from instead. Restore
stable-v1 sessions through load_session, load_session_from, resume_session, or
resume_session_from; blocking start_session returns a RestoredSession containing the
ActiveSession and exact load or resume response, while on_session_start delivers that value to
its callback. Both builder families expose on_session_start for non-blocking use and
block_task().start_session() for tasks already outside the dispatch loop. Restore routing is
acknowledged before the request is published so session/load replay cannot overtake local setup.
For new sessions, SessionBuilder::run_until is also available after block_task(). Proxy
handlers must use on_proxy_session_start; only call block_task().start_session_proxy(...) from
a task already outside the dispatch loop, such as a connect_with foreground future or a spawned
task. Directly attaching an already-returned NewSessionResponse is no longer supported, so move
request customization into build_session_from before the builder sends session/new.
For new sessions, when the response is routed during its original dispatch, on_session_start and
on_proxy_session_start install session routing under the ordered response callback, then spawn
the user callback. No user callback code runs under that ordering guarantee. The callback itself
must be 'static, but its returned future does not need an additional 'static bound and may
safely wait for later connection or session traffic. A response interceptor that retains and
routes the response later cannot retroactively order that setup before already-processed messages.
Register application state needed for routing before calling these helpers. Bookkeeping that
requires the returned session or session ID runs concurrently with later traffic. If handlers
must observe ID-keyed bookkeeping first, install a gate or placeholder before calling the helper,
have those handlers await it, and populate it from the callback.
Construct Lines and ByteStreams with Lines::new(outgoing, incoming) and
ByteStreams::new(outgoing, incoming); their stream fields are no longer public.
Draft v2 schema updates
The optional unstable_protocol_v2 surface now tracks
agent-client-protocol-schema 1.8. The draft API changes accumulated across schema 1.5
through 1.7 are included in the SDK 2.0 migration because this API is explicitly
unstable, rather than treated as stable-v1 wire changes.
- Many values that were plain
StringorPathBuffields are semantic newtypes, includingAbsolutePath,MediaType, session/message/tool/terminal IDs, and list cursors. Construct them with.into()or theirnewmethods, and useAsRef<Path>oras_ref()when borrowing their contents. v2::DiffPatch.diffis nowtext.DiffPatch::new(text)remains the preferred constructor.- Terminal state is represented by
Terminal,TerminalUpdate,TerminalOutput,TerminalOutputChunk, andTerminalExitStatus.SessionUpdatealso has terminal update and output-chunk variants, so exhaustive matches must handle the new variants. - The experimental
v2::conversionmodule and its cross-version helpers have been removed. Implement v1 and v2 handlers separately, and translate only application-owned shared state where the application’s semantics define a faithful mapping.
Schema 1.8 stabilizes optional tool-call name metadata in both v1 and draft
v2. Remove unstable_tool_call_name from your enabled Cargo features; v2 still
requires unstable_protocol_v2. The version-specific update semantics are
unchanged.
SentRequest::map accepts arbitrary output
SentRequest::map can now consume a typed response into any output type; the mapped value no
longer needs to implement JsonRpcResponse. This includes mapped values carrying non-'static
lifetimes when they are consumed with block_task; callback-style consumption still requires
'static because it is spawned onto the connection. The mapper may also be a one-shot closure.
This is additive, so existing mapping code does not need to change.
AcpAgent has its own process configuration
AcpAgent now accepts AcpAgentConfig instead of the ACP wire-schema McpServer. An ACP agent
subprocess is not an MCP server, and its local launch settings should not depend on the v1
protocol schema:
#![allow(unused)]
fn main() {
use agent_client_protocol::{AcpAgent, AcpAgentConfig};
let agent = AcpAgent::new(
AcpAgentConfig::new("my-agent")
.arg("--verbose")
.env("RUST_LOG", "info"),
);
let configuration = agent.config();
let _ = configuration;
}
server() and into_server() are now config() and into_config(). The MCP-only name and
_meta fields have no equivalents because they never affected process launching. Use command(),
arguments(), and environment() to inspect the configuration.
The JSON configuration shape also changes. The MCP type, name, and _meta fields are removed,
and environment variables change from schema objects:
{
"type": "stdio",
"name": "my-agent",
"command": "python",
"args": ["agent.py"],
"env": [{ "name": "RUST_LOG", "value": "info" }]
}
to a string map:
{
"command": "python",
"args": ["agent.py"],
"env": { "RUST_LOG": "info" }
}
Command-string and from_args construction are unchanged. HTTP and SSE McpServer variants were
never valid subprocess launch configurations; callers using them must select an appropriate
network transport separately.
The deprecated AcpAgent::zed_claude_code and AcpAgent::zed_codex constructors were removed;
use claude_agent and codex. The google_gemini convenience constructor was also removed;
replace it with the explicit command:
#![allow(unused)]
fn main() {
let agent = AcpAgent::from_args([
"npx",
"-y",
"--",
"@google/gemini-cli@latest",
"--experimental-acp",
]).unwrap();
}
Migrating from agent-client-protocol 0.10.x to 0.11
This guide explains how to move existing code to the programming model planned for agent-client-protocol 0.11.
Historical note: later releases merged subprocess and stdio support into
agent-client-protocol. The examples below use the current import path where that does not obscure the 0.11 migration itself.
Throughout this guide:
- old API =
agent-client-protocol0.10.x - new API = the planned
agent-client-protocol0.11API
All code snippets below use the intended 0.11 import paths.
1. Move message types under schema
The current 0.10.x crate exports most protocol message types at the crate root.
The 0.11 API moves most ACP request, response, and notification types under schema.
#![allow(unused)]
fn main() {
// Old (0.10.x)
use agent_client_protocol as acp;
use acp::{InitializeRequest, NewSessionRequest, PromptRequest, ProtocolVersion};
// New (0.11)
use agent_client_protocol as acp;
use acp::schema::{
InitializeRequest, NewSessionRequest, PromptRequest, ProtocolVersion,
};
}
Most ACP request, response, and notification types live under schema in 0.11
2. Replace connection construction
The main construction changes are:
ClientSideConnection::new(handler, outgoing, incoming, spawn)- becomes
Client.builder().connect_with(ByteStreams::new(outgoing, incoming), async |cx| { ... })
- becomes
AgentSideConnection::new(handler, outgoing, incoming, spawn)- becomes
Agent.builder().connect_to(ByteStreams::new(outgoing, incoming)).await?
- becomes
- custom
spawnfunction +handle_iofuture- becomes builder-managed connection execution
If you already have stdin/stdout or socket-like byte streams, wrap them with ByteStreams::new(outgoing, incoming).
If you are spawning subprocess agents, prefer the core crate’s AcpAgent over hand-rolled process wiring.
If you already have a reason to stay at the raw request/response level, you can still send PromptRequest directly with cx.send_request(...); the session helpers are just the default migration path for most client code.
3. Replace outbound trait-style calls with send_request and send_notification
In the old API, the connection itself implemented the remote trait, so calling the other side looked like this:
#![allow(unused)]
fn main() {
conn.initialize(InitializeRequest::new(ProtocolVersion::V1)).await?;
}
In 0.11, you send a typed request through ConnectionTo<Peer>:
#![allow(unused)]
fn main() {
cx.send_request(InitializeRequest::new(ProtocolVersion::V1))
.block_task()
.await?;
}
The main replacements are:
| Old style | New style |
|---|---|
conn.initialize(req).await? | cx.send_request(req).block_task().await? |
conn.new_session(req).await? | usually cx.build_session(...) or cx.build_session_cwd()? |
conn.prompt(req).await? | usually session.send_prompt(...) on an ActiveSession |
conn.cancel(notification).await? | cx.send_notification(notification)? |
A few behavioral differences matter during migration:
send_request(...)returns aSentRequest, not the response directly.- Call
.block_task().await?when you want to wait for the response from a context that does not block the dispatch loop. Themain_fnclosure passed toconnect_with(...)and tasks spawned viacx.spawn(...)are both safe; the dispatch loop continues processing messages (including the response you are waiting for) in the background. - Do not call
.block_task().await?insideon_receive_*callbacks. Those callbacks run on the dispatch loop, so blocking them deadlocks the connection. Preferon_receiving_result(...),on_receiving_ok_result(...),on_session_start(...), orcx.spawn(...)from handlers.
4. Replace manual session management with SessionBuilder
One of the biggest user-facing changes is session handling.
Old code typically looked like this:
#![allow(unused)]
fn main() {
let session = conn
.new_session(NewSessionRequest::new(cwd))
.await?;
conn.prompt(PromptRequest::new(
session.session_id.clone(),
vec!["Hello".into()],
))
.await?;
}
New code usually starts from the connection and uses a session builder:
#![allow(unused)]
fn main() {
cx.build_session_cwd()?
.block_task()
.run_until(async |mut session| {
session.send_prompt("Hello")?;
let output = session.read_to_string().await?;
println!("{output}");
Ok(())
})
.await?;
}
Useful replacements:
| Old pattern | New pattern |
|---|---|
new_session(NewSessionRequest::new(cwd)) | build_session(cwd) |
new_session(NewSessionRequest::new(current_dir)) | build_session_cwd()? |
store session_id and pass it into every PromptRequest | let ActiveSession manage the session lifecycle |
subscribe() to observe streamed session output | ActiveSession::read_update() or ActiveSession::read_to_string() |
intercept and rewrite a session/new request in a proxy | build_session_from(request) |
Also note:
- use
start_session()when you want anActiveSession<'static, _>you can keep around - use
on_session_start(...)insideon_receive_*callbacks when you need to start a session without manually blocking the current task - use
on_proxy_session_start(...)orstart_session_proxy(...)for proxy-style session startup and forwarding
5. Replace Client trait impls with builder callbacks
In 0.10.x, your client behavior lived in an impl acp::Client for T block.
In 0.11, register typed handlers on Client.builder() instead.
Each on_receive_* call takes two arguments: the async handler, and one of
the helper macros acp::on_receive_request!(),
acp::on_receive_notification!(), or acp::on_receive_dispatch!(). These
macros are a temporary workaround until return-type notation stabilizes;
pass the one that matches the method you are calling.
Common client-side method mapping
request_permission->.on_receive_request(|req: RequestPermissionRequest, responder, cx| ...)write_text_file->.on_receive_request(|req: WriteTextFileRequest, responder, cx| ...)read_text_file->.on_receive_request(|req: ReadTextFileRequest, responder, cx| ...)create_terminal->.on_receive_request(|req: CreateTerminalRequest, responder, cx| ...)terminal_output->.on_receive_request(|req: TerminalOutputRequest, responder, cx| ...)release_terminal->.on_receive_request(|req: ReleaseTerminalRequest, responder, cx| ...)wait_for_terminal_exit->.on_receive_request(|req: WaitForTerminalExitRequest, responder, cx| ...)kill_terminal->.on_receive_request(|req: KillTerminalRequest, responder, cx| ...)session_notification->.on_receive_notification(|notif: SessionNotification, cx| ...)ext_method/ext_notification-> your own derivedJsonRpcRequest/JsonRpcNotificationtypes, or a catch-allon_receive_dispatch(...)
A small client-side translation looks like this:
use agent_client_protocol as acp;
use acp::schema::{
RequestPermissionOutcome, RequestPermissionRequest, RequestPermissionResponse,
SessionNotification,
};
#[tokio::main]
async fn main() -> acp::Result<()> {
let transport = todo!("create the transport that connects to your agent");
acp::Client
.builder()
.on_receive_request(
async move |_: RequestPermissionRequest, responder, _cx| {
responder.respond(RequestPermissionResponse::new(
RequestPermissionOutcome::Cancelled,
))
},
acp::on_receive_request!(),
)
.on_receive_notification(
async move |notification: SessionNotification, _cx| {
println!("{:?}", notification.update);
Ok(())
},
acp::on_receive_notification!(),
)
.connect_with(transport, async |_cx: acp::ConnectionTo<acp::Agent>| {
// send requests here, e.g. `_cx.send_request(...).block_task().await?`
Ok(())
})
.await
}
6. Replace Agent trait impls with builder callbacks
The same shift applies on the agent side.
Common agent-side method mapping
initialize->.on_receive_request(|req: InitializeRequest, responder, cx| ...)authenticate->.on_receive_request(|req: AuthenticateRequest, responder, cx| ...)new_session->.on_receive_request(|req: NewSessionRequest, responder, cx| ...)prompt->.on_receive_request(|req: PromptRequest, responder, cx| ...)cancel->.on_receive_notification(|notif: CancelNotification, cx| ...)load_session->.on_receive_request(|req: LoadSessionRequest, responder, cx| ...)set_session_mode->.on_receive_request(|req: SetSessionModeRequest, responder, cx| ...)set_session_config_option->.on_receive_request(|req: SetSessionConfigOptionRequest, responder, cx| ...)list_sessionsand other unstable session methods -> request handlers for the corresponding schema typeext_method/ext_notification-> your own derivedJsonRpcRequest/JsonRpcNotificationtypes, or a catch-allon_receive_dispatch(...)
A minimal agent skeleton now looks like this:
use agent_client_protocol as acp;
use acp::schema::{
AgentCapabilities, CancelNotification, InitializeRequest, InitializeResponse,
PromptRequest, PromptResponse, StopReason,
};
use acp::{Client, Dispatch};
#[tokio::main]
async fn main() -> acp::Result<()> {
let outgoing = todo!("create the agent's outgoing byte stream");
let incoming = todo!("create the agent's incoming byte stream");
acp::Agent
.builder()
.name("my-agent")
.on_receive_request(
async move |request: InitializeRequest, responder, _cx| {
responder.respond(
InitializeResponse::new(request.protocol_version)
.agent_capabilities(AgentCapabilities::new()),
)
},
acp::on_receive_request!(),
)
.on_receive_request(
async move |_request: PromptRequest, responder, _cx| {
responder.respond(PromptResponse::new(StopReason::EndTurn))
},
acp::on_receive_request!(),
)
.on_receive_notification(
async move |_notification: CancelNotification, _cx| {
Ok(())
},
acp::on_receive_notification!(),
)
.connect_to(acp::ByteStreams::new(outgoing, incoming))
.await
}
If you need a catch-all handler, use on_receive_dispatch(...).
7. Replace subscribe() with session readers or explicit callbacks
There is no direct connection-level replacement for ClientSideConnection::subscribe().
Choose the replacement based on what you were using it for:
- if you were reading prompt output for one session, prefer
ActiveSession::read_update()orActiveSession::read_to_string() - if you were observing inbound notifications generally, register
on_receive_notification(...) - if you were forwarding or inspecting raw messages in a proxy, use
on_receive_dispatch(...)plussend_proxied_message(...)
8. Remove LocalSet, spawn_local, and manual I/O tasks
The old crate examples needed a LocalSet because the connection futures were !Send.
Most migrations to the 0.11 API can remove:
tokio::task::LocalSettokio::task::spawn_local(...)- the custom
spawnclosure passed into connection construction - the separate
handle_iofuture you had to drive manually
When you need concurrency from a handler in 0.11, use cx.spawn(...).
9. Prefer AcpAgent for subprocess agents
If your old client code spawned an agent with tokio::process::Command, the new stack has a higher-level helper for that. AcpAgent implements ConnectTo<Client> and takes care of spawning the process and wiring up its stdio:
use agent_client_protocol as acp;
use acp::schema::{InitializeRequest, ProtocolVersion};
use agent_client_protocol::AcpAgent;
use std::str::FromStr;
#[tokio::main]
async fn main() -> acp::Result<()> {
let agent = AcpAgent::from_str("python my_agent.py")?;
acp::Client
.builder()
.name("my-client")
.connect_with(agent, async |cx| {
cx.send_request(InitializeRequest::new(ProtocolVersion::V1))
.block_task()
.await?;
// ...send more requests, build a session, etc.
Ok(())
})
.await
}
Use connect_to(agent) (without a main_fn) only when the client has no
outbound requests to send and just needs to keep the connection alive so
registered handlers can respond to the agent. In that mode the builder
runs until the transport closes or a handler returns an error.
You can still use ByteStreams::new(...) when you already own the byte
streams and do not want the extra helper crate.
10. Common gotchas
ClientandAgentare role markers now, not traits you implement.- The response type for
send_request(...)is inferred from the request type. send_request(...)does not wait by itself; use.block_task().await?oron_receiving_result(...).- Be careful about calling blocking operations from
on_receive_*callbacks. Those callbacks run in the dispatch loop and preserve message ordering. - If your old code used
subscribe()as a global message tap, plan a new strategy aroundActiveSession, notification callbacks, or proxy dispatch handlers. - For reusable ACP components, implement
ConnectTo<Role>instead of trying to recreate the old monolithic trait pattern.
Original P/ACP Design Proposal (Historical)
This document records the original proxying design and is retained for historical context. It contains method names and capability shapes that were superseded during implementation. Do not use it as a wire-protocol specification; see the current Protocol Reference instead.
In particular, the SDK-local
_mcp/*methods andMcpServer::Httpvalues using anacp:URL were retired. Current opt-in implementations useMcpServer::Acpwith request-scopedmcp/messagerequests.mcp/connectandmcp/disconnectwere removed as well. The compatibility polyfill translates those native declarations only for HTTP-capable agents. Do not copy the historical MCP examples below.Likewise, the
proxy/successor/{send,receive}/*methods below were replaced by a singleproxy/successormethod, and proxies are initialized withproxy/initialize, as described in the proxy chains RFD.
Elevator pitch
What are you proposing to change?
We propose to prototype P/ACP (Proxying ACP), an extension to Zed’s Agent Client Protocol (ACP) that enables composable agent architectures through proxy chains. Instead of building monolithic AI tools, P/ACP allows developers to create modular components that can intercept and transform messages flowing between editors and agents.
This RFD builds on the concepts introduced in SymmACP: extending Zed’s ACP to support Composable Agents, with the protocol renamed to P/ACP for this implementation.
Key changes:
- Define a proxy chain architecture where components can transform ACP messages
- Create an orchestrator (Conductor) that manages the proxy chain and presents as a normal ACP agent to editors
- Establish the
proxy/successor/*protocol for proxies to communicate with downstream components - Enable composition without requiring editors to understand P/ACP internals
Status quo
How do things work today and what problems does this cause? Why would we change things?
Today’s AI agent ecosystem is dominated by monolithic agents. We want people to be able to combine independent components to build custom agents targeting their specific needs. We want them to be able to use these with whatever editors and tooling they have. This is aligned with ACP’s core values of openness, interoperability, and extensibility.
Motivating Example: Sparkle Integration
Consider integrating Sparkle (a collaborative AI framework) into a coding session with Zed and Claude. Sparkle provides an MCP server with tools, but requires an initialization sequence to load patterns and set up collaborative context.
Without P/ACP:
- Users must manually run the initialization sequence each session
- Or use agent-specific hooks (Claude Code has them, but not standardized across agents)
- Or modify the agent to handle initialization automatically
- Result: Manual intervention required, agent-specific configuration, no generic solution
With P/ACP:
flowchart LR
Editor[Editor<br/>Zed]
subgraph Conductor[Conductor Orchestrator]
Sparkle[Sparkle Component]
Agent[Base Agent]
MCP[Sparkle MCP Server]
Sparkle -->|proxy chain| Agent
Sparkle -.->|provides tools| MCP
end
Editor <-->|ACP| Conductor
The Sparkle component:
- Injects Sparkle MCP server into the agent’s tool list during
initialize - Intercepts the first
promptand prepends Sparkle embodiment sequence - Passes all other messages through transparently
From the editor’s perspective, it talks to a normal ACP agent. From the base agent’s perspective, it has Sparkle tools available. No code changes required on either side.
This demonstrates P/ACP’s core value: adding capabilities through composition rather than modification.
What we propose to do about it
What are you proposing to improve the situation?
We will develop an extension to ACP called P/ACP (Proxying ACP).
The heart of P/ACP is a proxy chain where each component adds specific capabilities:
flowchart LR
Editor[ACP Editor]
subgraph Orchestrator[P/ACP Orchestrator]
O[Orchestrator Process]
end
subgraph ProxyChain[Proxy Chain - managed by orchestrator]
P1[Proxy 1]
P2[Proxy 2]
Agent[ACP Agent]
P1 -->|proxy/successor/*| P2
P2 -->|proxy/successor/*| Agent
end
Editor <-->|ACP| O
O <-->|routes messages| ProxyChain
P/ACP defines three kinds of actors:
- Editors spawn the orchestrator and communicate via standard ACP
- Orchestrator manages the proxy chain, appears as a normal ACP agent to editors
- Proxies intercept and transform messages, communicate with downstream via
proxy/successor/*protocol - Agents provide base AI model behavior using standard ACP
The orchestrator handles message routing, making the proxy chain transparent to editors. Proxies can transform requests, responses, or add side-effects without editors or agents needing P/ACP awareness.
The Orchestrator: Conductor
P/ACP’s orchestrator is called the Conductor (binary name: conductor). The conductor has three core responsibilities:
- Process Management - Creates and manages component processes based on command-line configuration
- Message Routing - Routes messages between editor, components, and agent through the proxy chain
- Capability Adaptation - Observes component capabilities and adapts between them
Key adaptation: MCP Bridge
- If the agent supports
mcpCapabilities.acp, conductor passes MCP servers with ACP transport through unchanged - If not, conductor spawns
conductor mcp $portprocesses to bridge between stdio (MCP) and ACP messages - Components can provide MCP servers without requiring agent modifications
- See “MCP Bridge” section in Implementation Details for full protocol
Other adaptations include session pre-population, streaming support, content types, and tool formats.
From the editor’s perspective, it spawns one conductor process and communicates using normal ACP over stdio. The editor doesn’t know about the proxy chain.
Command-line usage:
# Agent mode - manages proxy chain
conductor agent sparkle-acp claude-code-acp
# MCP mode - bridges stdio to TCP for MCP-over-ACP
conductor mcp 54321
To editors, the conductor is a normal ACP agent - no special capabilities are advertised upstream.
Proxy Capability Handshake:
The implementation replaced this capability handshake with a dedicated proxy initialization request. See Proxy Initialization.
The conductor uses a two-way capability handshake to verify that proxy components can fulfill their responsibilities:
- Conductor offers proxy capability - When initializing non-last components (proxies), the conductor signals the proxy role in the InitializeRequest
- Component accepts proxy capability - The component must accept the proxy role in its InitializeResponse
- Last component (agent) - The final component is treated as a standard ACP agent and does NOT receive the proxy capability offer
Why a two-way handshake? The proxy capability is an active protocol - it requires the component to handle proxy/successor/* messages and route communications appropriately. Unlike passive capabilities (like “http” or “sse”) which are just declarations, proxy components must actively participate in message routing. If a component doesn’t respond with the proxy capability, the conductor fails initialization with an error like “component X is not a proxy”, since that component cannot fulfill its required function in the chain.
Shiny future
How will things will play out once this feature exists?
Composable Agent Ecosystems
P/ACP enables a marketplace of reusable proxy components. Developers can:
- Compose custom agent pipelines from independently-developed proxies
- Share proxies across different editors and agents
- Test and debug proxies in isolation
- Mix community-developed and custom proxies
Simplified Agent Development
Agent developers can focus on core model behavior without implementing cross-cutting concerns:
- Logging, metrics, and observability become proxy responsibilities
- Rate limiting and caching handled externally
- Content filtering and safety policies applied consistently
Editor Simplicity
Editors gain enhanced functionality without custom integrations:
- Add sophisticated agent behaviors by changing proxy chain configuration
- Support new agent features without editor updates
- Maintain compatibility with any ACP agent
Standardization Path
As the ecosystem matures, successful patterns may be:
- Standardized in ACP specification itself
- Adopted by other agent protocols
- Used as reference implementations for proxy architectures
Implemented Extensions
MCP Bridge - ✅ Implemented via the _mcp/* protocol (see “Implementation details and plan” section). Components can provide MCP servers using ACP transport, enabling tool provision without agents needing P/ACP awareness. The conductor bridges between agents lacking native support and components.
Future Protocol Extensions
Extensions under consideration for future development:
Agent-Initiated Messages - Allow components to send messages after the agent has sent end-turn, outside the normal request-response cycle. Use cases include background task completion notifications, time-based reminders, or autonomous checkpoint creation.
Session Pre-Population - Create sessions with existing conversation history. Conductor adapts based on agent capabilities: uses native support if available, otherwise synthesizes a dummy prompt containing the history, intercepts the response, and starts the real session.
Rich Content Types - Extend content types beyond text to include HTML panels, interactive GUI components, or other structured formats. Components can transform between content types based on what downstream agents support.
Implementation details and plan
Tell me more about your implementation. What is your detailed implementation plan?
The implementation focuses on building the Conductor and demonstrating the Sparkle integration use case.
P/ACP protocol
Definition: Editor vs Agent of a proxy
For an P/ACP proxy, the “editor” is defined as the upstream connection and the “agent” is the downstream connection.
flowchart LR
Editor --> Proxy --> Agent
P/ACP proxy handshake
This proposal originally signalled P/ACP support and the proxy role with a
capability object under an unprefixed _meta key. ACP reserves unprefixed
_meta keys for the protocol itself, so that capability was never adopted.
The implementation uses a dedicated proxy initialization request instead; see
Proxy Initialization in the Protocol
Reference.
The conductor sends the proxy initialization request to every non-last
component. The last component in the chain (the agent) receives a normal
initialize request. Agents are just normal ACP agents with no P/ACP awareness
required.
The proxy/successor/{send,receive} protocol
Proxies communicate with their downstream component (next proxy or agent) through special messages handled by the orchestrator:
proxy/successor/send/request - Proxy wants to send a request downstream:
{
"method": "proxy/successor/send/request",
"params": {
"message": <ACP_REQUEST>
}
}
proxy/successor/send/notification - Proxy wants to send a notification downstream:
{
"method": "proxy/successor/send/notification",
"params": {
"message": <ACP_NOTIFICATION>
}
}
proxy/successor/receive/request - Orchestrator delivers a request from downstream:
{
"method": "proxy/successor/receive/request",
"params": {
"message": <ACP_REQUEST>
}
}
proxy/successor/receive/notification - Orchestrator delivers a notification from downstream:
{
"method": "proxy/successor/receive/notification",
"params": {
"message": <ACP_NOTIFICATION>
}
}
Message flow example:
- Editor sends ACP
promptrequest to orchestrator - Orchestrator forwards to Proxy1 as normal ACP message
- Proxy1 transforms and sends
proxy/successor/send/request { message: <modified_prompt> } - Orchestrator routes that to Proxy2 as normal ACP
prompt - Eventually reaches agent, response flows back through chain
- Orchestrator wraps responses going upstream appropriately
Transparent proxy pattern: A pass-through proxy is trivial - just forward everything:
#![allow(unused)]
fn main() {
match message {
// Forward requests from editor to successor
AcpRequest(req) => send_to_successor_request(req),
// Forward notifications from editor to successor
AcpNotification(notif) => send_to_successor_notification(notif),
// Forward from successor back to editor
ExtRequest("proxy/successor/receive/request", msg) => respond_to_editor(msg),
ExtNotification("proxy/successor/receive/notification", msg) => forward_to_editor(msg),
}
}
The MCP Bridge: _mcp/* Protocol
P/ACP enables components to provide MCP servers that communicate over ACP messages rather than traditional stdio. This allows components to handle MCP tool calls without agents needing special P/ACP awareness.
MCP Server Declaration with ACP Transport
Components declare MCP servers with ACP transport by using the HTTP MCP server format with a special URL scheme:
{
"tools": {
"mcpServers": {
"sparkle": {
"transport": "http",
"url": "acp:550e8400-e29b-41d4-a716-446655440000",
"headers": {}
}
}
}
}
The acp:$UUID URL signals ACP transport. The component generates the UUID to identify which component handles calls to this MCP server.
Agent Capability: mcpCapabilities.acp
Agents that natively support MCP-over-ACP declare this capability:
{
"agentCapabilities": {
"mcpCapabilities": {
"acp": true
}
}
}
Conductor behavior:
- If the final agent has
mcpCapabilities.acp: true, conductor passes MCP server declarations through unchanged - If the final agent lacks this capability, conductor performs bridging adaptation:
- Binds a fresh TCP port (e.g.,
localhost:54321) - Transforms the MCP server declaration to use
conductor mcp $portas the command - Spawns
conductor mcp $portwhich connects back via TCP and bridges to ACP messages - Always advertises
mcpCapabilities.acp: trueto intermediate components
- Binds a fresh TCP port (e.g.,
Bridging Transformation Example
Original MCP server spec (from component):
{
"sparkle": {
"transport": "http",
"url": "acp:550e8400-e29b-41d4-a716-446655440000",
"headers": {}
}
}
Transformed spec (passed to agent without mcpCapabilities.acp):
{
"sparkle": {
"command": "conductor",
"args": ["mcp", "54321"],
"transport": "stdio"
}
}
The agent thinks it’s talking to a normal MCP server over stdio. The conductor mcp process bridges between stdio (MCP JSON-RPC) and TCP (connection to main conductor), which then translates to ACP _mcp/* messages.
MCP Message Flow Protocol
When MCP tool calls occur, they flow as ACP extension messages:
_mcp/client_to_server/request - Agent calling an MCP tool (flows backward up chain):
{
"jsonrpc": "2.0",
"id": "T1",
"method": "_mcp/client_to_server/request",
"params": {
"url": "acp:550e8400-e29b-41d4-a716-446655440000",
"message": {
"jsonrpc": "2.0",
"id": "mcp-123",
"method": "tools/call",
"params": {
"name": "embody_sparkle",
"arguments": {}
}
}
}
}
Response:
{
"jsonrpc": "2.0",
"id": "T1",
"result": {
"message": {
"jsonrpc": "2.0",
"id": "mcp-123",
"result": {
"content": [{ "type": "text", "text": "Embodiment complete" }]
}
}
}
}
_mcp/client_to_server/notification - Agent sending notification to MCP server:
{
"jsonrpc": "2.0",
"method": "_mcp/client_to_server/notification",
"params": {
"url": "acp:550e8400-e29b-41d4-a716-446655440000",
"message": {
"jsonrpc": "2.0",
"method": "notifications/cancelled",
"params": {}
}
}
}
_mcp/server_to_client/request - MCP server calling back to agent (flows forward down chain):
{
"jsonrpc": "2.0",
"id": "S1",
"method": "_mcp/server_to_client/request",
"params": {
"url": "acp:550e8400-e29b-41d4-a716-446655440000",
"message": {
"jsonrpc": "2.0",
"id": "mcp-456",
"method": "sampling/createMessage",
"params": {
"messages": [...],
"modelPreferences": {...}
}
}
}
}
_mcp/server_to_client/notification - MCP server sending notification to agent:
{
"jsonrpc": "2.0",
"method": "_mcp/server_to_client/notification",
"params": {
"url": "acp:550e8400-e29b-41d4-a716-446655440000",
"message": {
"jsonrpc": "2.0",
"method": "notifications/progress",
"params": {
"progressToken": "token-1",
"progress": 50,
"total": 100
}
}
}
}
Message Routing
Client→Server messages (agent calling MCP tools):
- Flow backward up the proxy chain (agent → conductor → components)
- Component matches on
params.urlto identify which MCP server - Component extracts
params.message, handles the MCP call, responds
Server→Client messages (MCP server callbacks):
- Flow forward down the proxy chain (component → conductor → agent)
- Component initiates when its MCP server needs to call back (sampling, logging, progress)
- Conductor routes to agent (or via bridge if needed)
Conductor MCP Mode
The conductor binary has two modes:
-
Agent mode:
conductor agent [proxies...] agent- Manages P/ACP proxy chain
- Routes ACP messages
-
MCP mode:
conductor mcp $port- Acts as MCP server over stdio
- Connects to
localhost:$portvia TCP - Bridges MCP JSON-RPC (stdio) ↔ raw JSON-RPC (TCP to main conductor)
When bridging is needed, the main conductor spawns conductor mcp $port as the child process that the agent communicates with via stdio.
Additional Extension Messages
Proxies can define their own extension messages beyond proxy/successor to provide specific capabilities. Like any ACP extension, these should use an _-prefixed vendor name (unprefixed names are reserved for ACP). Examples might include:
- Logging/observability:
_acme/logmessages for structured logging - Metrics:
_acme/metricmessages for tracking usage - Configuration:
_acme/configmessages for dynamic reconfiguration
The orchestrator can handle routing these messages appropriately, or they can be handled by specific proxies in the chain.
These extensions are beyond the scope of this initial RFD and will be defined as needed by specific proxy implementations.
Implementation progress
What is the current status of implementation and what are the next steps?
Current Status: Implementation Phase
Completed:
- ✅ P/ACP protocol design with Conductor orchestrator architecture
- ✅
proxy/successor/{send,receive}message protocol defined - ✅
scpRust crate with JSON-RPC layer and ACP message types - ✅ Comprehensive JSON-RPC test suite (21 tests)
- ✅ Proxy message type definitions (
ToSuccessorRequest, etc.)
In Progress:
- Conductor orchestrator implementation
- Sparkle P/ACP component
- MCP Bridge implementation (see checklist below)
MCP Bridge Implementation Checklist
Phase 1: Conductor MCP Mode (COMPLETE ✅)
- Implement
conductor mcp $portCLI parsing - TCP connection to
localhost:$port - Stdio → TCP bridging (read from stdin, send via TCP)
- TCP → Stdio bridging (read from TCP, write to stdout)
- Newline-delimited JSON framing
- Error handling (connection failures, parse errors, reconnection logic)
- Unit tests for message bridging
- Integration test: standalone MCP bridge with mock MCP client/server
Phase 2: Conductor Agent Mode - MCP Detection & Bridging
- Detect
"transport": "http", "url": "acp:$UUID"MCP servers in initialization - Check final agent for
mcpCapabilities.acpcapability - Bind ephemeral TCP ports when bridging needed
- Transform MCP server specs to use
conductor mcp $port - Spawn
conductor mcp $portsubprocess per ACP-transport MCP server - Store mapping:
UUID → TCP port → bridge process - Always advertise
mcpCapabilities.acp: trueto intermediate components - Integration test: full chain with MCP bridging
Phase 3: _mcp/* Message Routing
- Route
_mcp/client_to_server/request(TCP → ACP, backward up chain) - Route
_mcp/client_to_server/notification(TCP → ACP, backward) - Route
_mcp/server_to_client/request(ACP → TCP, forward down chain) - Route
_mcp/server_to_client/notification(ACP → TCP, forward) - URL matching for component routing (
params.urlmatches UUID) - Response routing back through bridge
- Integration test: full
_mcp/*message flow
Phase 4: Bridge Lifecycle Management
- Clean up bridge processes on session end
- Handle bridge process crashes
- Handle component crashes (clean up associated bridges)
- TCP connection cleanup on errors
- Port cleanup and reuse
Phase 5: Component-Side MCP Integration
- Sparkle component declares ACP-transport MCP server
- Sparkle handles
_mcp/client_to_server/*messages - Sparkle initiates
_mcp/server_to_client/*callbacks - End-to-end test: Sparkle embodiment via MCP bridge
Phase 1: Minimal Sparkle Demo
Goal: Demonstrate Sparkle integration through P/ACP composition.
Components:
- Conductor orchestrator - Process management, message routing, capability adaptation
- Sparkle P/ACP component - Injects Sparkle MCP server, handles embodiment sequence
- Integration test - Validates end-to-end flow with mock editor/agent
Demo flow:
Zed → Conductor → Sparkle Component → Claude
↓
Sparkle MCP Server
Success criteria:
- Sparkle MCP server appears in agent’s tool list
- First prompt triggers Sparkle embodiment sequence
- Subsequent prompts work normally
- All other ACP messages pass through unchanged
Detailed MVP Walkthrough
This section shows the exact message flows for the minimal Sparkle demo.
Understanding UUIDs in the flow:
There are two distinct types of UUIDs in these sequences:
-
Message IDs (JSON-RPC request IDs): These identify individual JSON-RPC requests and must be tracked to route responses correctly. When a component forwards a message using
proxy/successor/request, it creates a fresh message ID for the downstream request and remembers the mapping to route the response back. -
Session IDs (ACP session identifiers): These identify ACP sessions and flow through the chain unchanged. The agent creates a session ID, and all components pass it back unmodified.
Conductor’s routing rules:
- Message from Editor → Forward “as is” to first component (same message ID)
proxy/successor/requestfrom component → Unwrap payload and send to next component (using message ID from the wrapper)- Response from downstream → Send back to whoever made the
_proxyrequest - First component’s response → Send back to Editor
Components don’t talk directly to each other - all communication flows through Conductor via the _proxy protocol.
Scenario 1: Initialization and Session Creation
The editor spawns Conductor with component names, Conductor spawns the components, and initialization flows through the chain.
sequenceDiagram
participant Editor as Editor<br/>(Zed)
participant Conductor as Conductor<br/>Orchestrator
participant Sparkle as Sparkle<br/>Component
participant Agent as Base<br/>Agent
Note over Editor: Spawns Conductor with args:<br/>"sparkle-acp agent-acp"
Editor->>Conductor: spawn process
activate Conductor
Note over Conductor: Spawns both components
Conductor->>Sparkle: spawn "sparkle-acp"
activate Sparkle
Conductor->>Agent: spawn "agent-acp"
activate Agent
Note over Editor,Agent: === Initialization Phase ===
Editor->>Conductor: initialize (id: I0)
Conductor->>Sparkle: initialize (id: I0)<br/>(offers PROXY capability)
Note over Sparkle: Sees proxy capability offer,<br/>initializes successor
Sparkle->>Conductor: proxy/successor/request (id: I1)<br/>payload: initialize
Conductor->>Agent: initialize (id: I1)<br/>(NO proxy capability - agent is last)
Agent-->>Conductor: initialize response (id: I1)
Conductor-->>Sparkle: proxy/successor response (id: I1)
Note over Sparkle: Sees Agent capabilities,<br/>prepares response
Sparkle-->>Conductor: initialize response (id: I0)<br/>(accepts PROXY capability)
Note over Conductor: Verifies Sparkle accepted proxy.<br/>If not, would fail with error.
Conductor-->>Editor: initialize response (id: I0)
Note over Editor,Agent: === Session Creation ===
Editor->>Conductor: session/new (id: U0, tools: M0)
Conductor->>Sparkle: session/new (id: U0, tools: M0)
Note over Sparkle: Wants to inject Sparkle MCP server
Sparkle->>Conductor: proxy/successor/request (id: U1)<br/>payload: session/new with tools (M0, sparkle-mcp)
Conductor->>Agent: session/new (id: U1, tools: M0 + sparkle-mcp)
Agent-->>Conductor: response (id: U1, sessionId: S1)
Conductor-->>Sparkle: response to _proxy request (id: U1, sessionId: S1)
Note over Sparkle: Remembers mapping U0 → U1
Sparkle-->>Conductor: response (id: U0, sessionId: S1)
Conductor-->>Editor: response (id: U0, sessionId: S1)
Note over Editor,Agent: Session S1 created,<br/>Sparkle MCP server available to agent
Key messages:
-
Editor → Conductor: initialize (id: I0)
{ "jsonrpc": "2.0", "id": "I0", "method": "initialize", "params": { "protocolVersion": "0.1.0", "capabilities": {}, "clientInfo": { "name": "Zed", "version": "0.1.0" } } } -
Conductor → Sparkle: initialize (id: I0, with PROXY capability)
{ "jsonrpc": "2.0", "id": "I0", "method": "initialize", "params": { "protocolVersion": "0.1.0", "capabilities": {}, "clientInfo": { "name": "Conductor", "version": "0.1.0" } } } -
Sparkle → Conductor: \proxy/successor/request (id: I1, wrapping initialize)
{ "jsonrpc": "2.0", "id": "I1", "method": "proxy/successor/request", "params": { "message": { "method": "initialize", "params": { "protocolVersion": "0.1.0", "capabilities": {}, "clientInfo": { "name": "Sparkle", "version": "0.1.0" } } } } } -
Conductor → Agent: initialize (id: I1, unwrapped, without PROXY capability)
{ "jsonrpc": "2.0", "id": "I1", "method": "initialize", "params": { "protocolVersion": "0.1.0", "capabilities": {}, "clientInfo": { "name": "Sparkle", "version": "0.1.0" } } } -
Agent → Conductor: initialize response (id: I1)
{ "jsonrpc": "2.0", "id": "I1", "result": { "protocolVersion": "0.1.0", "capabilities": {}, "serverInfo": { "name": "claude-code-acp", "version": "0.1.0" } } } -
Conductor → Sparkle: \proxy/successor response (id: I1, wrapping Agent’s response)
{ "jsonrpc": "2.0", "id": "I1", "result": { "protocolVersion": "0.1.0", "capabilities": {}, "serverInfo": { "name": "claude-code-acp", "version": "0.1.0" } } } -
Sparkle → Conductor: initialize response (id: I0, accepting proxy capability)
{ "jsonrpc": "2.0", "id": "I0", "result": { "protocolVersion": "0.1.0", "capabilities": {}, "serverInfo": { "name": "Sparkle + claude-code-acp", "version": "0.1.0" } } }Note: The original proposal carried the proxy offer and acceptance in an unprefixed
_metacapability object, which this example omits. The implementation sends a dedicated proxy initialization request instead; see Proxy Initialization. -
Editor → Conductor: session/new (id: U0)
{ "jsonrpc": "2.0", "id": "U0", "method": "session/new", "params": { "tools": { "mcpServers": { "filesystem": { "command": "mcp-filesystem", "args": [] } } } } } -
Conductor → Sparkle: session/new (id: U0, forwarded as-is)
{ "jsonrpc": "2.0", "id": "U0", "method": "session/new", "params": { "tools": { "mcpServers": { "filesystem": { "command": "mcp-filesystem", "args": [] } } } } } -
Sparkle → Conductor: \proxy/successor/request (id: U1, with injected Sparkle MCP)
{
"jsonrpc": "2.0",
"id": "U1",
"method": "proxy/successor/request",
"params": {
"message": {
"method": "session/new",
"params": {
"tools": {
"mcpServers": {
"filesystem": { "command": "mcp-filesystem", "args": [] },
"sparkle": { "command": "sparkle-mcp", "args": [] }
}
}
}
}
}
}
- Conductor → Agent: session/new (id: U1, unwrapped from _proxy message)
{
"jsonrpc": "2.0",
"id": "U1",
"method": "session/new",
"params": {
"tools": {
"mcpServers": {
"filesystem": { "command": "mcp-filesystem", "args": [] },
"sparkle": { "command": "sparkle-mcp", "args": [] }
}
}
}
}
- Agent → Conductor: response (id: U1, with new session S1)
{
"jsonrpc": "2.0",
"id": "U1",
"result": {
"sessionId": "S1",
"serverInfo": { "name": "claude-code-acp", "version": "0.1.0" }
}
}
- Conductor → Sparkle: \proxy/successor response (id: U1)
{
"jsonrpc": "2.0",
"id": "U1",
"result": {
"sessionId": "S1",
"serverInfo": { "name": "claude-code-acp", "version": "0.1.0" }
}
}
- Sparkle → Conductor: response (id: U0, with session S1)
{
"jsonrpc": "2.0",
"id": "U0",
"result": {
"sessionId": "S1",
"serverInfo": { "name": "Conductor + Sparkle", "version": "0.1.0" }
}
}
Scenario 2: First Prompt (Sparkle Embodiment)
When the first prompt arrives, Sparkle intercepts it and runs the embodiment sequence before forwarding the actual user prompt.
sequenceDiagram
participant Editor as Editor<br/>(Zed)
participant Conductor as Conductor<br/>Orchestrator
participant Sparkle as Sparkle<br/>Component
participant Agent as Base<br/>Agent
Note over Editor,Agent: === First Prompt Flow ===
Editor->>Conductor: session/prompt (id: P0, sessionId: S1)
Conductor->>Sparkle: session/prompt (id: P0, sessionId: S1)
Note over Sparkle: First prompt detected!<br/>Run embodiment sequence first
Sparkle->>Conductor: proxy/successor/request (id: P1)<br/>payload: session/prompt (embodiment)
Conductor->>Agent: session/prompt (id: P1, embodiment)
Agent-->>Conductor: response (id: P1, tool_use: embody_sparkle)
Conductor-->>Sparkle: response to _proxy request (id: P1)
Note over Sparkle: Embodiment complete,<br/>now send real prompt
Sparkle->>Conductor: proxy/successor/request (id: P2)<br/>payload: session/prompt (user message)
Conductor->>Agent: session/prompt (id: P2, user message)
Agent-->>Conductor: response (id: P2, actual answer)
Conductor-->>Sparkle: response to _proxy request (id: P2)
Note over Sparkle: Maps P2 → P0
Sparkle-->>Conductor: response (id: P0, actual answer)
Conductor-->>Editor: response (id: P0, actual answer)
Note over Editor,Agent: User sees response,<br/>Sparkle initialized
Key messages:
-
Editor → Conductor: session/prompt (id: P0, user’s first message)
{ "jsonrpc": "2.0", "id": "P0", "method": "session/prompt", "params": { "sessionId": "S1", "messages": [ { "role": "user", "content": "Hello! Can you help me with my code?" } ] } } -
Conductor → Sparkle: session/prompt (id: P0, forwarded as-is)
{ "jsonrpc": "2.0", "id": "P0", "method": "session/prompt", "params": { "sessionId": "S1", "messages": [ { "role": "user", "content": "Hello! Can you help me with my code?" } ] } } -
Sparkle → Conductor: \proxy/successor/request (id: P1, embodiment sequence)
{ "jsonrpc": "2.0", "id": "P1", "method": "proxy/successor/request", "params": { "message": { "method": "session/prompt", "params": { "sessionId": "S1", "messages": [ { "role": "user", "content": "Please use the embody_sparkle tool to load your collaborative patterns." } ] } } } } -
Conductor → Agent: session/prompt (id: P1, unwrapped embodiment)
{ "jsonrpc": "2.0", "id": "P1", "method": "session/prompt", "params": { "sessionId": "S1", "messages": [ { "role": "user", "content": "Please use the embody_sparkle tool to load your collaborative patterns." } ] } } -
Agent → Conductor: response (id: P1, embodiment tool call)
{ "jsonrpc": "2.0", "id": "P1", "result": { "role": "assistant", "content": [ { "type": "tool_use", "id": "tool-1", "name": "embody_sparkle", "input": {} } ] } } -
Sparkle → Conductor: \proxy/successor/request (id: P2, actual user prompt)
{ "jsonrpc": "2.0", "id": "P2", "method": "proxy/successor/request", "params": { "message": { "method": "session/prompt", "params": { "sessionId": "S1", "messages": [ { "role": "user", "content": "Hello! Can you help me with my code?" } ] } } } } -
Conductor → Agent: session/prompt (id: P2, unwrapped user prompt)
{ "jsonrpc": "2.0", "id": "P2", "method": "session/prompt", "params": { "sessionId": "S1", "messages": [ { "role": "user", "content": "Hello! Can you help me with my code?" } ] } } -
Sparkle → Conductor: response (id: P0, forwarded to editor)
{ "jsonrpc": "2.0", "id": "P0", "result": { "role": "assistant", "content": "I'd be happy to help you with your code! What would you like to work on?" } }
Scenario 3: Subsequent Prompts (Pass-Through)
After embodiment, Sparkle passes all messages through transparently.
sequenceDiagram
participant Editor as Editor<br/>(Zed)
participant Conductor as Conductor<br/>Orchestrator
participant Sparkle as Sparkle<br/>Component
participant Agent as Base<br/>Agent
Note over Editor,Agent: === Subsequent Prompt Flow ===
Editor->>Conductor: session/prompt (id: P3, sessionId: S1)
Conductor->>Sparkle: session/prompt (id: P3, sessionId: S1)
Note over Sparkle: Already embodied,<br/>pass through unchanged
Sparkle->>Conductor: proxy/successor/request (id: P4)<br/>payload: session/prompt (unchanged)
Conductor->>Agent: session/prompt (id: P4, unchanged)
Agent-->>Conductor: response (id: P4)
Conductor-->>Sparkle: response to _proxy request (id: P4)
Note over Sparkle: Maps P4 → P3
Sparkle-->>Conductor: response (id: P3)
Conductor-->>Editor: response (id: P3)
Note over Editor,Agent: Normal ACP flow,<br/>Sparkle and Conductor transparent
Key messages:
-
Editor → Conductor: session/prompt (id: P3)
{ "jsonrpc": "2.0", "id": "P3", "method": "session/prompt", "params": { "sessionId": "S1", "messages": [ { "role": "user", "content": "Can you refactor the authenticate function?" } ] } } -
Sparkle → Conductor: \proxy/successor/request (id: P4, message unchanged)
{ "jsonrpc": "2.0", "id": "P4", "method": "proxy/successor/request", "params": { "message": { "method": "session/prompt", "params": { "sessionId": "S1", "messages": [ { "role": "user", "content": "Can you refactor the authenticate function?" } ] } } } } -
Conductor → Agent: session/prompt (id: P4, unwrapped)
{ "jsonrpc": "2.0", "id": "P4", "method": "session/prompt", "params": { "sessionId": "S1", "messages": [ { "role": "user", "content": "Can you refactor the authenticate function?" } ] } } -
Sparkle → Conductor: response (id: P3, forwarded to editor)
{ "jsonrpc": "2.0", "id": "P3", "result": { "role": "assistant", "content": "I'll help you refactor the authenticate function..." } }
Note that even though Sparkle is passing messages through “transparently”, it still uses the proxy/successor/request protocol. This maintains the consistent routing pattern where all downstream communication flows through Conductor.
Implementation Note on Embodiment Responses:
For the MVP, when Sparkle runs the embodiment sequence before the user’s actual prompt, it will buffer both responses and concatenate them before sending back to the editor. This makes the embodiment transparent but loses some structure. A future RFD will explore richer content types (like subconversation) that would allow editors to distinguish between nested exchanges and main responses.
Phase 2: Tool Interception (FUTURE)
Goal: Route MCP tool calls through the proxy chain.
Conductor registers as a dummy MCP server. When Claude calls a Sparkle tool, the call routes back through the proxy chain to the Sparkle component for handling. This enables richer component interactions without requiring agents to understand P/ACP.
Phase 3: Additional Components (FUTURE)
Build additional P/ACP components that demonstrate different use cases:
- Session history/context management
- Logging and observability
- Rate limiting
- Content filtering
These will validate the protocol design and inform refinements.
Testing Strategy
Unit tests:
- Test message serialization/deserialization
- Test process spawning logic
- Test stdio communication
Integration tests:
- Spawn real proxy chains
- Use actual ACP agents for end-to-end validation
- Test error handling and cleanup
Manual testing:
- Use with VSCode + ACP-aware agents
- Verify with different proxy configurations
- Test process management under various failure modes
Frequently asked questions
What questions have arisen over the course of authoring this document or during subsequent discussions?
What alternative approaches did you consider, and why did you settle on this one?
We considered extending MCP directly, but MCP is focused on tool provision rather than conversation flow control. We also looked at building everything as VSCode extensions, but that would lock us into a single editor ecosystem.
P/ACP’s proxy chain approach provides the right balance of modularity and compatibility - components can be developed independently while still working together.
How does this relate to other agent protocols like Google’s A2A?
P/ACP is complementary to protocols like A2A. While A2A focuses on agent-to-agent communication for remote services, P/ACP focuses on composing the user-facing development experience. You could imagine P/ACP components that use A2A internally to coordinate with remote agents.
What about security concerns with arbitrary proxy chains?
Users are responsible for the proxies they choose to run, similar to how they’re responsible for the software they install. Proxies can intercept and modify all communication, so trust is essential. For future versions, we’re considering approaches like Microsoft’s Wassette (WASM-based capability restrictions) to provide sandboxed execution environments.
What about the chat GUI interface?
We currently have a minimal chat GUI working in VSCode that can exchange basic messages with ACP agents. However, a richer chat interface with features like message history, streaming support, context providers, and interactive elements remains TBD.
Continue.dev has solved many of the hard problems for production-quality chat interfaces in VS Code extensions. Their GUI is specifically designed to be reusable - they use the exact same codebase for both VS Code and JetBrains IDEs by implementing different adapter layers.
Their architecture proves that message-passing protocols can cleanly separate GUI concerns from backend logic, which aligns perfectly with P/ACP’s composable design. When we’re ready to enhance the chat interface, we can evaluate whether to build on Continue.dev’s foundation or develop our own approach based on what we learn from the P/ACP proxy framework.
The Apache 2.0 license makes this legally straightforward, and their well-documented message protocols provide a clear integration path.
Why not just use hooks or plugins?
Hooks are fundamentally limited to what the host application anticipated. P/ACP proxies can intercept and modify the entire conversation flow, enabling innovations that the original tool designer never envisioned. This is the difference between customization and true composability.
What about performance implications of the proxy chain?
The proxy chain does add some latency as messages pass through multiple hops. However, we don’t expect this to be noticeable for typical development workflows. Most interactions are human-paced rather than high-frequency, and the benefits of composability outweigh the minimal latency cost.
How will users discover and configure proxy chains?
This will be determined over time as the ecosystem develops. We expect solutions to emerge organically, potentially including registries, configuration files, or marketplace-style discovery mechanisms.
What about resource management with multiple proxy processes?
Each proxy manages the lifecycle of processes it starts. When a proxy terminates, it cleans up its downstream processes. This creates a natural cleanup chain that prevents resource leaks.
Revision history
Initial draft based on architectural discussions.