agent_client_protocol/lib.rs
1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3//! # agent-client-protocol -- the Agent Client Protocol (ACP) SDK
4//!
5//! **agent-client-protocol** is a Rust SDK for building [Agent-Client Protocol (ACP)][acp] applications.
6//! ACP is a protocol for communication between AI agents and their clients (IDEs, CLIs, etc.),
7//! enabling features like tool use, permission requests, and streaming responses.
8//!
9//! [acp]: https://agentclientprotocol.com/
10//!
11//! ## What can you build with agent-client-protocol?
12//!
13//! - **Clients** that talk to ACP agents (like building your own Claude Code interface)
14//! - **Proxies** that add capabilities to existing agents (like adding custom tools via MCP)
15//! - **Agents** that respond to prompts with AI-powered responses
16//!
17//! ## Protocol versions
18//!
19//! Every connection names the ACP protocol version it speaks:
20//!
21//! - [`Client.v1()`](Client::v1), [`Agent.v1()`](Agent::v1) and
22//! [`Proxy.v1()`](Proxy::v1) start a stable protocol v1 connection. Its
23//! types are in [`v1`] and its messages in [`v1::schema`].
24//! - With the `unstable_protocol_v2` feature, `Client.v2()`, `Agent.v2()` and
25//! `Proxy.v2()` start a draft protocol v2 connection. Its types are in
26//! `agent_client_protocol::v2` and its messages in `v2::schema`.
27//!
28//! The `v1` and `v2` modules use the same names for the connection, the builder,
29//! the request handles and `schema` (`ConnectionTo`, `Builder`, `Responder`,
30//! `Dispatch`, `SentRequest`, ...). Their session APIs differ:
31//! `v1::ActiveSession` reads the session's updates from its own stream, while
32//! `v2::ActiveSession` only sends commands and the updates arrive through
33//! typed handlers on the connection. Some names exist in only one module, such
34//! as `v1::LoadSessionBuilder` and `v1::SessionMessage`, or
35//! `v2::InitializeOutcome`.
36//! The crate root holds what every version shares: transports, roles, the
37//! JSON-RPC traits, [`Error`], the generic request handles (which default to
38//! the version-neutral [`Raw`] marker) and, with `unstable_protocol_v2`, the
39//! routers that serve both versions. [`Builder::new`] remains as the raw,
40//! version-neutral escape hatch: it applies no protocol-version guard.
41//!
42//! ## Quick Start: Connecting to an Agent
43//!
44//! The most common use case is connecting to an existing ACP agent as a client.
45//! This example uses stable ACP protocol v1. The draft protocol v2 feature
46//! provides a command-only `v2::ActiveSession` API and receives updates and interactive
47//! requests through typed connection handlers because prompt acceptance and
48//! inbound traffic are independent. With both v2 and MCP-over-ACP features,
49//! `Proxy.v2()` supports global MCP attachment, while `v2::SessionBuilder` and
50//! `v2::ResumeSessionBuilder` support per-session attachment plus non-blocking
51//! proxy setup. With `unstable_session_fork`, `v2::ForkSessionBuilder` provides
52//! the same shape for forked sessions and uses the response's new session ID.
53//! Per-session MCP routes and runners are ready before a setup request is
54//! published, as is proxy session routing for resume replay. Successful v2
55//! setup detaches MCP handlers for the connection lifetime; dropping the
56//! returned `v2::ActiveSession` does not unregister them. In v1, `v1::ActiveSession` owns
57//! per-session MCP registrations until drop, unless a proxy handoff detaches
58//! them (`proxy_remaining_messages` or successful `on_proxy_session_start`).
59//! Global proxy attachments are connection-scoped in both versions.
60//!
61//! Here's a minimal example that initializes a v1 connection, creates a
62//! session, and sends a prompt:
63//!
64//! ```no_run
65//! use agent_client_protocol::Client;
66//! use agent_client_protocol::{schema::ProtocolVersion, v1::schema::InitializeRequest};
67//! use agent_client_protocol::v1::SessionSetup;
68//!
69//! # async fn run(transport: impl agent_client_protocol::ConnectTo<agent_client_protocol::Client>) -> agent_client_protocol::Result<()> {
70//! Client.v1()
71//! .name("my-client")
72//! .connect_with(transport, async |cx| {
73//! // Step 1: Initialize the connection
74//! cx.send_request(InitializeRequest::new(ProtocolVersion::V1))
75//! .block_task().await?;
76//!
77//! // Step 2: Create a session and send a prompt
78//! cx.build_session_cwd()?
79//! .block_task()
80//! .run_until(async |SessionSetup { mut session, .. }| {
81//! session.send_prompt("What is 2 + 2?")?;
82//! let response = session.read_to_string().await?;
83//! println!("{}", response);
84//! Ok(())
85//! })
86//! .await
87//! })
88//! .await
89//! # }
90//! ```
91//!
92//! For a complete working example, see [`yolo_one_shot_client.rs`][yolo].
93//!
94//! [yolo]: https://github.com/agentclientprotocol/rust-sdk/blob/main/src/agent-client-protocol/examples/yolo_one_shot_client.rs
95//!
96//! ## Cookbook
97//!
98//! The [`agent_client_protocol_cookbook`] crate contains practical guides and examples:
99//!
100//! - Connecting as a client
101//! - Global MCP server
102//! - Per-session MCP server with workspace context
103//! - Building agents and reusable components
104//! - Running proxies with the conductor
105//!
106//! [`agent_client_protocol_cookbook`]: https://docs.rs/agent-client-protocol-cookbook
107//!
108//! ## Cargo Features
109//!
110//! No features are enabled by default. Protocol serialization, connections,
111//! sessions, custom MCP servers, and the generic transport adapters remain
112//! available without opting in to native I/O or JSON Schema generation.
113//!
114//! - `process`: native subprocess support through `AcpAgent` and `AcpAgentConfig`.
115//! - `stdio`: the native `Stdio` adapter.
116//! - `schemars`: `JsonSchema` implementations on protocol types and typed MCP
117//! tool helpers in [`mcp_server`].
118//!
119//! For example, a native client launching an agent opts into `process`:
120//!
121//! ```toml
122//! agent-client-protocol = { version = "5", features = ["process"] }
123//! ```
124//!
125//! Enable `stdio` for an agent using `Stdio`, or `schemars` for typed MCP tool
126//! definitions. `LineDirection` is available on native targets with either
127//! `process` or `stdio`; neither feature enables the other.
128//!
129//! The `agent-client-protocol-rmcp` crate explicitly enables `schemars` for its
130//! tool builders. Unstable protocol features remain independent opt-ins.
131//! No features have been enabled by default since 3.0. When upgrading from
132//! 2.x, explicitly enable every feature your application uses;
133//! `default-features = false` is no longer needed for a lean dependency.
134//!
135//! ## Stability
136//!
137//! - The stable API, everything that is not behind an `unstable_*` feature,
138//! follows semver: it changes incompatibly only in a major release.
139//! - Everything behind an `unstable_*` feature may change in a minor release.
140//! This includes all of `agent_client_protocol::v2` and the other items that
141//! `unstable_protocol_v2` enables. Stabilizing protocol v2 only removes the
142//! `unstable_protocol_v2` gate.
143//! - This crate depends on one exact version of `agent-client-protocol-schema`
144//! (an `=` requirement), and a minor release may move that pin to a newer
145//! schema release. Use each version's message types through [`v1::schema`]
146//! and `v2::schema`, and the version-neutral items such as
147//! [`ProtocolVersion`](schema::ProtocolVersion) through [`schema`], instead
148//! of depending on `agent-client-protocol-schema` directly. A direct
149//! dependency must allow the exact version this crate pins, or Cargo cannot
150//! resolve the dependency graph.
151//! - All SDK crates share one version number, so moving a public dependency of
152//! any of them to a new major version, such as `axum` or `reqwest` in
153//! `agent-client-protocol-http`, is a major release of all of them.
154//!
155//! ## WebAssembly
156//!
157//! The runtime-neutral protocol engine and transport abstractions compile for
158//! `wasm32-wasip1` and `wasm32-wasip2` without additional features. For
159//! JavaScript-hosted `wasm32-unknown-unknown`, enable `wasm_js` to select Web
160//! Crypto through `wasm-bindgen` as the UUID randomness backend. The target
161//! does not imply a JavaScript host, so this feature is not enabled by default;
162//! other OS-less WebAssembly hosts must arrange a compatible UUID randomness
163//! backend instead.
164//!
165//! This crate does not provide a WebAssembly executor or host I/O adapter. The
166//! native `process` and `stdio` features depend on process spawning and
167//! blocking-thread facilities, so their dependencies and exports (including
168//! `LineDirection`) remain excluded on WebAssembly even when enabled.
169//!
170//! Embedders provide their own runtime and transport. They can exchange
171//! `TransportFrame` values through `Channel`, newline-delimited JSON through
172//! `Lines`, or use `ByteStreams` with `futures::io::AsyncRead` and
173//! `AsyncWrite`. The embedding runtime must drive the resulting connection
174//! future.
175//!
176//! Handlers, transports, and connection futures must be `Send` on every
177//! target, including WebAssembly. JavaScript host values such as
178//! `wasm_bindgen::JsValue` are `!Send`, so keep them outside the connection and
179//! exchange `Send` data with it through `Channel` or `ByteStreams`. A later
180//! release may relax these bounds on WebAssembly. That change would not affect
181//! native code.
182//!
183//! ## Core Concepts
184//!
185//! The [`concepts`] module provides detailed explanations of how agent-client-protocol works,
186//! including connections, sessions, callbacks, ordering guarantees, and more.
187//!
188//! ## Related Crates
189//!
190//! - [`agent-client-protocol-conductor`] - Binary for running proxy chains
191//!
192//! [`agent-client-protocol-conductor`]: https://crates.io/crates/agent-client-protocol-conductor
193
194/// Component abstraction for agents and proxies
195pub mod component;
196/// Core concepts for understanding and using agent-client-protocol
197pub mod concepts;
198/// JSON-RPC connection and handler infrastructure
199mod jsonrpc;
200/// Runtime-agnostic MCP server support, including optional attachment to ACP sessions.
201pub mod mcp_server;
202/// Role types for ACP connections
203pub mod role;
204pub mod schema;
205/// Utility functions and types
206pub mod util;
207pub mod v1;
208#[cfg(feature = "unstable_protocol_v2")]
209#[cfg_attr(docsrs, doc(cfg(feature = "unstable_protocol_v2")))]
210pub mod v2;
211
212pub use jsonrpc::{
213 Builder, ByteStreams, CONNECTION_TERMINATED_REASON, Channel, ConnectionTermination,
214 ConnectionTo, Dispatch, DynamicHandlerGuard, HandleConnectionClose, HandleDispatchFrom,
215 Handled, INCOMING_TRANSPORT_CLOSED_REASON, IntoHandled, JsonRpcMessage, JsonRpcNotification,
216 JsonRpcRequest, JsonRpcResponse, Lines, NullClose, NullHandler, PreparedRequest, Protocol, Raw,
217 RawJsonRpcError, RawJsonRpcId, RawJsonRpcMessage, RawJsonRpcNotification, RawJsonRpcParams,
218 RawJsonRpcRequest, RawJsonRpcResponse, Responder, ResponseRouter, SentRequest, TransportFrame,
219 UntypedMessage, V1, is_connection_terminated, is_incoming_transport_closed,
220 run::{ChainRun, NullRun, RunWithConnectionTo},
221};
222#[cfg(feature = "unstable_protocol_v2")]
223pub use jsonrpc::{InitializationVersionMismatch, SelectedInitializeResponse, V2};
224pub use jsonrpc::{RequestCancellation, RequestCancellationHandle, is_cancel_request_notification};
225
226#[cfg(feature = "unstable_protocol_v2")]
227pub use role::acp::{AgentProtocolRouter, ClientProtocolConnector, ProxyProtocolRouter};
228pub use role::{
229 Role, RoleId, UntypedRole,
230 acp::{Agent, Client, Conductor, Proxy},
231};
232
233pub use component::{ConnectTo, ConnectionDriver, DynConnectTo};
234
235/// Implementation details used by the derive macros.
236#[doc(hidden)]
237pub mod __private {
238 pub use crate::util::{json_cast, json_cast_params};
239 pub use serde;
240 pub use serde_json;
241}
242
243// Re-export BoxFuture for implementing SDK traits that return boxed futures.
244pub use futures::future::BoxFuture;
245
246mod error;
247pub use error::{Error, ErrorCode, Result};
248
249// Re-export derive macros for custom JSON-RPC types
250pub use agent_client_protocol_derive::{JsonRpcNotification, JsonRpcRequest, JsonRpcResponse};
251
252mod session;
253
254#[cfg(all(feature = "process", not(target_family = "wasm")))]
255mod acp_agent;
256#[cfg(all(feature = "process", not(target_family = "wasm")))]
257#[cfg_attr(
258 docsrs,
259 doc(cfg(all(feature = "process", not(target_family = "wasm"))))
260)]
261pub use acp_agent::{AcpAgent, AcpAgentConfig};
262
263#[cfg(all(
264 any(feature = "process", feature = "stdio"),
265 not(target_family = "wasm")
266))]
267mod line_direction;
268#[cfg(all(
269 any(feature = "process", feature = "stdio"),
270 not(target_family = "wasm")
271))]
272pub use line_direction::LineDirection;
273
274#[cfg(all(feature = "stdio", not(target_family = "wasm")))]
275mod stdio;
276#[cfg(all(feature = "stdio", not(target_family = "wasm")))]
277#[cfg_attr(docsrs, doc(cfg(all(feature = "stdio", not(target_family = "wasm")))))]
278pub use stdio::Stdio;
279
280/// This is a hack that must be given as the final argument of
281/// the MCP server builder's `tool_fn_mut` method when defining tools.
282///
283/// The `agent-client-protocol-rmcp` crate provides the builder this macro is
284/// typically used with.
285/// Look away, lest ye be blinded by its vileness!
286///
287/// Fine, if you MUST know, it's a horrific workaround for not having
288/// [return-type notation](https://github.com/rust-lang/rust/issues/109417)
289/// and for [this !@$#!%! bug](https://github.com/rust-lang/rust/issues/110338).
290/// Trust me, the need for it hurts me more than it hurts you. --nikomatsakis
291#[macro_export]
292macro_rules! tool_fn_mut {
293 () => {
294 |func, params, context| Box::pin(func(params, context))
295 };
296}
297
298/// This is a hack that must be given as the final argument of
299/// the MCP server builder's `tool_fn` method when defining stateless concurrent tools.
300///
301/// The `agent-client-protocol-rmcp` crate provides the builder this macro is
302/// typically used with.
303/// See [`tool_fn_mut!`] for the gory details.
304#[macro_export]
305macro_rules! tool_fn {
306 () => {
307 |func, params, context| Box::pin(func(params, context))
308 };
309}
310
311/// This macro is used for the value of the `to_future_hack` parameter of
312/// [`Builder::on_receive_request`] and [`Builder::on_receive_request_from`].
313///
314/// It expands to `|f, req, responder, cx| Box::pin(f(req, responder, cx))`.
315///
316/// This is needed until [return-type notation](https://github.com/rust-lang/rust/issues/109417)
317/// is stabilized.
318#[macro_export]
319macro_rules! on_receive_request {
320 () => {
321 |f: &mut _, req, responder, cx| Box::pin(f(req, responder, cx))
322 };
323}
324
325/// This macro is used for the value of the `to_future_hack` parameter of
326/// [`Builder::on_receive_notification`] and [`Builder::on_receive_notification_from`].
327///
328/// It expands to `|f, notif, cx| Box::pin(f(notif, cx))`.
329///
330/// This is needed until [return-type notation](https://github.com/rust-lang/rust/issues/109417)
331/// is stabilized.
332#[macro_export]
333macro_rules! on_receive_notification {
334 () => {
335 |f: &mut _, notif, cx| Box::pin(f(notif, cx))
336 };
337}
338
339/// This macro is used for the value of the `to_future_hack` parameter of
340/// [`Builder::on_receive_dispatch`] and [`Builder::on_receive_dispatch_from`].
341///
342/// It expands to `|f, dispatch, cx| Box::pin(f(dispatch, cx))`.
343///
344/// This is needed until [return-type notation](https://github.com/rust-lang/rust/issues/109417)
345/// is stabilized.
346#[macro_export]
347macro_rules! on_receive_dispatch {
348 () => {
349 |f: &mut _, dispatch, cx| Box::pin(f(dispatch, cx))
350 };
351}