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