agent_client_protocol_schema/lib.rs
1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3//! [](https://agentclientprotocol.com/)
4//!
5//! # Agent Client Protocol Schema
6//!
7//! Strongly-typed Rust definitions of the Agent Client Protocol (ACP) wire
8//! format. ACP is a JSON-RPC based protocol that standardizes communication
9//! between code editors (IDEs, text-editors, etc.) and coding agents
10//! (programs that use generative AI to autonomously modify code).
11//!
12//! This crate is **only** the schema: the request, response, and
13//! notification types, plus serde plumbing and optional JSON Schema generation.
14//! For the runtime pieces (transport, connection setup, the `Agent` / `Client`
15//! traits, etc.) use the higher-level [`agent-client-protocol`] crate, which
16//! builds on top of these types.
17//!
18//! [`agent-client-protocol`]: https://crates.io/crates/agent-client-protocol
19//!
20//! ## What's in this crate
21//!
22//! - Versioned wire-format types for every ACP method: request, response, and
23//! notification structs grouped by which side handles them, currently under
24//! the [`v1`] module.
25//! - JSON-RPC envelope and routing types: [`v1::JsonRpcMessage`],
26//! [`rpc::JsonRpcBatch`], [`v1::Request`], [`v1::Response`],
27//! [`v1::Notification`], [`v1::RequestId`], [`v1::Error`].
28//! - Aggregated routing enums: [`v1::AgentRequest`], [`v1::AgentResponse`],
29//! [`v1::AgentNotification`], and the matching client-side trio used by SDK
30//! crates to dispatch incoming JSON-RPC messages.
31//!
32//! ## Parsing aggregate enums
33//!
34//! Do not deserialize an aggregate routing enum directly from a wire payload.
35//! Its untagged `Deserialize` implementation selects by payload shape, not the
36//! JSON-RPC method, and can silently select an unrelated variant.
37//! Use the enum's `from_method_and_params` or `from_method_and_result` method
38//! instead. Individual payload structs can be deserialized directly once the
39//! method is known.
40//!
41//! These helpers only select and deserialize payloads. Use the SDK for
42//! connections, request tracking, and JSON-RPC error handling.
43//!
44//! ```
45//! use agent_client_protocol_schema::v1::ClientRequest;
46//! use serde_json::json;
47//!
48//! let params = json!({"cwd": "/work", "mcpServers": []});
49//! let request = ClientRequest::from_method_and_params("session/new", ¶ms)?;
50//! assert!(matches!(request, ClientRequest::NewSessionRequest(_)));
51//! # Ok::<(), agent_client_protocol_schema::MethodDispatchError>(())
52//! ```
53//!
54//! ## Maps
55//!
56//! Maps keep the order of their keys, so the types hold them in an
57//! [`IndexMap`]. The crate re-exports it, so building one needs no direct
58//! `indexmap` dependency.
59//!
60//! ```
61//! use agent_client_protocol_schema::IndexMap;
62//! use agent_client_protocol_schema::v1::{OtherStateUpdate, StateUpdate};
63//! use serde_json::json;
64//!
65//! let fields = IndexMap::from([
66//! ("reason".to_string(), json!("rate_limited")),
67//! ("attempt".to_string(), json!(2)),
68//! ]);
69//! let state = StateUpdate::Other(OtherStateUpdate::new("_paused", fields));
70//! assert_eq!(
71//! serde_json::to_string(&state)?,
72//! r#"{"state":"_paused","reason":"rate_limited","attempt":2}"#
73//! );
74//! # Ok::<(), serde_json::Error>(())
75//! ```
76//!
77//! ## Cargo features
78//!
79//! The `schemars` feature implements `schemars::JsonSchema` for the protocol
80//! types. It is enabled by default to preserve the existing default API.
81//! Consumers that only need serialization can disable default features to omit
82//! the dependency and those trait implementations.
83//!
84//! The `uuid` feature adds `IdempotencyKey::generate` to the `v2` module, which
85//! creates a key from a random UUID. It is off by default.
86//!
87//! ## Versioning
88//!
89//! Stable protocol types are exposed through explicit version modules. For
90//! example, use `agent_client_protocol_schema::v1::SessionId` for ACP protocol
91//! version 1 types.
92//!
93//! For the complete protocol specification and documentation, visit
94//! <https://agentclientprotocol.com>.
95
96#[macro_use]
97mod dispatch;
98pub mod rpc;
99mod serde_util;
100pub mod v1;
101#[cfg(feature = "unstable_protocol_v2")]
102pub mod v2;
103mod version;
104
105// The `uuid` feature only adds API to the `v2` module. With `uuid` on and
106// `unstable_protocol_v2` off, the dependency is enabled and nothing uses it.
107// That combination is valid, so reference the crate to say so. Remove this
108// once the `v2` module is no longer behind `unstable_protocol_v2`.
109#[cfg(all(feature = "uuid", not(feature = "unstable_protocol_v2")))]
110use uuid as _;
111
112pub use dispatch::MethodDispatchError;
113pub use indexmap::IndexMap;
114pub use serde_util::{IntoMaybeUndefined, IntoOption, MaybeUndefined};
115pub use version::*;
116
117#[cfg(test)]
118mod serde_json_feature_tests {
119 #[cfg(feature = "schemars")]
120 use schemars::JsonSchema;
121 use serde_json::Value;
122
123 #[cfg(feature = "schemars")]
124 #[test]
125 fn protocol_types_implement_json_schema_when_enabled() {
126 fn assert_json_schema<T: JsonSchema>() {}
127
128 assert_json_schema::<crate::ProtocolVersion>();
129 assert_json_schema::<crate::v1::InitializeRequest>();
130 }
131
132 #[test]
133 fn serde_json_values_preserve_object_key_order() {
134 let Value::Object(object) =
135 serde_json::from_str::<Value>(r#"{"z":1,"a":2,"m":3}"#).unwrap()
136 else {
137 panic!("expected JSON object");
138 };
139
140 let keys = object.keys().map(String::as_str).collect::<Vec<_>>();
141 assert_eq!(keys, ["z", "a", "m"]);
142 }
143}