Skip to main content

agent_client_protocol/schema/
mod.rs

1//! Version-neutral ACP schema items.
2//!
3//! Each protocol version's messages (requests, responses, notifications and
4//! supporting types) are in that version's SDK module: [`crate::v1::schema`]
5//! and, with `unstable_protocol_v2`, `agent_client_protocol::v2::schema`. This
6//! module holds only the items every version shares: [`ProtocolVersion`],
7//! [`MaybeUndefined`], [`MethodDispatchError`], the [`IntoOption`] and
8//! [`IntoMaybeUndefined`] conversion traits, and [`SuccessorMessage`].
9//!
10//! The types come from the `agent-client-protocol-schema` crate, which this
11//! crate pins to one exact version. Use them through the SDK instead of
12//! depending on `agent-client-protocol-schema` directly.
13
14// ---------------------------------------------------------------------------
15// Macros for implementing JsonRpc traits on schema types
16// ---------------------------------------------------------------------------
17
18/// Implement `JsonRpcMessage`, `JsonRpcRequest`, and `JsonRpcResponse` for a
19/// request/response pair from the schema crate.
20///
21/// ```ignore
22/// impl_jsonrpc_request!(PromptRequest, PromptResponse, "session/prompt");
23/// ```
24macro_rules! impl_jsonrpc_request {
25    ($req:ty, $resp:ty, $method:literal) => {
26        impl $crate::JsonRpcMessage for $req {
27            fn matches_method(method: &str) -> bool {
28                method == $method
29            }
30
31            fn method(&self) -> &str {
32                $method
33            }
34
35            fn to_untyped_message(&self) -> Result<$crate::UntypedMessage, $crate::Error> {
36                $crate::UntypedMessage::new($method, self)
37            }
38
39            fn parse_message(
40                method: &str,
41                params: &serde_json::Value,
42            ) -> Result<Self, $crate::Error> {
43                if method != $method {
44                    return Err($crate::Error::method_not_found());
45                }
46                $crate::util::json_cast_params(params)
47            }
48        }
49
50        impl $crate::JsonRpcRequest for $req {
51            type Response = $resp;
52        }
53
54        impl $crate::JsonRpcResponse for $resp {
55            fn into_json(self, _method: &str) -> Result<serde_json::Value, $crate::Error> {
56                serde_json::to_value(self).map_err($crate::Error::into_internal_error)
57            }
58
59            fn from_json(_method: &str, value: serde_json::Value) -> Result<Self, $crate::Error> {
60                $crate::util::json_cast(&value)
61            }
62        }
63    };
64}
65
66/// Implement `JsonRpcMessage` and `JsonRpcNotification` for a notification type
67/// from the schema crate.
68///
69/// ```ignore
70/// impl_jsonrpc_notification!(CancelNotification, "session/cancel");
71/// ```
72macro_rules! impl_jsonrpc_notification {
73    ($notif:ty, $method:literal) => {
74        impl $crate::JsonRpcMessage for $notif {
75            fn matches_method(method: &str) -> bool {
76                method == $method
77            }
78
79            fn method(&self) -> &str {
80                $method
81            }
82
83            fn to_untyped_message(&self) -> Result<$crate::UntypedMessage, $crate::Error> {
84                $crate::UntypedMessage::new($method, self)
85            }
86
87            fn parse_message(
88                method: &str,
89                params: &serde_json::Value,
90            ) -> Result<Self, $crate::Error> {
91                if method != $method {
92                    return Err($crate::Error::method_not_found());
93                }
94                $crate::util::json_cast_params(params)
95            }
96        }
97
98        impl $crate::JsonRpcNotification for $notif {}
99    };
100}
101
102// The schema owns method-to-variant dispatch. These adapters retain SDK handler
103// matching, untyped envelopes, and error policy.
104macro_rules! impl_jsonrpc_message_enum {
105    ($enum:ty, $matches:expr) => {
106        impl $crate::JsonRpcMessage for $enum {
107            fn matches_method(method: &str) -> bool {
108                ($matches)(method)
109            }
110
111            fn method(&self) -> &str {
112                <$enum>::method(self)
113            }
114
115            fn to_untyped_message(&self) -> Result<$crate::UntypedMessage, $crate::Error> {
116                $crate::UntypedMessage::new(<$enum>::method(self), self)
117            }
118
119            fn parse_message(
120                method: &str,
121                params: &serde_json::Value,
122            ) -> Result<Self, $crate::Error> {
123                <$enum>::from_method_and_params(method, params).map_err(|error| {
124                    $crate::schema::dispatch_error(
125                        error,
126                        params.clone(),
127                        $crate::Error::invalid_params,
128                    )
129                })
130            }
131        }
132    };
133}
134
135macro_rules! impl_jsonrpc_request_enum {
136    ($enum:ty) => {
137        // Aggregate request handlers remain catch-all handlers. Their parser
138        // rejects unknown methods rather than falling through to another handler.
139        impl_jsonrpc_message_enum!($enum, |_| true);
140        impl $crate::JsonRpcRequest for $enum {
141            type Response = serde_json::Value;
142        }
143    };
144}
145
146macro_rules! impl_jsonrpc_notification_enum {
147    ($enum:ty) => {
148        impl_jsonrpc_message_enum!($enum, |_| true);
149        impl $crate::JsonRpcNotification for $enum {}
150    };
151}
152
153macro_rules! impl_jsonrpc_protocol_level_notification_enum {
154    ($enum:ty) => {
155        impl_jsonrpc_message_enum!($enum, <$enum>::supports_method);
156        impl $crate::JsonRpcNotification for $enum {}
157    };
158}
159
160macro_rules! impl_jsonrpc_response_enum {
161    ($enum:ty) => {
162        impl $crate::JsonRpcResponse for $enum {
163            fn into_json(self, _method: &str) -> Result<serde_json::Value, $crate::Error> {
164                serde_json::to_value(self).map_err($crate::Error::into_internal_error)
165            }
166
167            fn from_json(method: &str, value: serde_json::Value) -> Result<Self, $crate::Error> {
168                <$enum>::from_method_and_result(method, value.clone()).map_err(|error| {
169                    $crate::schema::dispatch_error(error, value, $crate::Error::parse_error)
170                })
171            }
172        }
173    };
174}
175
176// Match json_cast_params/json_cast diagnostics without putting SDK error codes
177// or payload-bearing diagnostics into the schema's dispatch implementation.
178fn dispatch_error(
179    error: agent_client_protocol_schema::MethodDispatchError,
180    payload: serde_json::Value,
181    invalid_payload: fn() -> crate::Error,
182) -> crate::Error {
183    use agent_client_protocol_schema::MethodDispatchError;
184
185    match error {
186        MethodDispatchError::UnknownMethod { .. } => crate::Error::method_not_found(),
187        MethodDispatchError::InvalidPayload { source, .. } => {
188            invalid_payload().data(serde_json::json!({
189                "error": source.to_string(),
190                "json": payload,
191                "phase": "deserialization",
192            }))
193        }
194        _ => crate::Error::internal_error(),
195    }
196}
197
198// Internal organization
199mod agent_to_client;
200mod client_to_agent;
201mod enum_impls;
202#[cfg(feature = "unstable_mcp_over_acp")]
203mod mcp;
204mod protocol_level;
205mod proxy_protocol;
206#[cfg(feature = "unstable_protocol_v2")]
207mod v2_impls;
208
209pub use agent_client_protocol_schema::{
210    IndexMap, IntoMaybeUndefined, IntoOption, MaybeUndefined, MethodDispatchError, ProtocolVersion,
211};
212
213pub use proxy_protocol::SuccessorMessage;