Skip to main content

agent_client_protocol_schema/v2/
mcp.rs

1//! MCP-over-ACP transport types.
2
3use std::sync::Arc;
4
5use derive_more::{Display, From};
6use serde::{Deserialize, Serialize};
7use serde_json::{Map, Value};
8use serde_with::{DefaultOnError, serde_as, skip_serializing_none};
9
10use crate::{IntoOption, MaybeUndefined};
11
12use super::{McpServerAcpId, Meta};
13
14/// **UNSTABLE**
15///
16/// An inner MCP error, distinct from an outer ACP binding or runtime error.
17///
18/// `code` and `message` are required and non-null. `data` is optional.
19/// Explicit `null` is preserved separately from an omitted key.
20#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
21#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
22#[non_exhaustive]
23pub struct McpError {
24    /// Inner MCP error code. Never an ACP error code.
25    pub code: i32,
26    /// Inner MCP error message.
27    pub message: String,
28    /// Optional error data. Explicit null is retained.
29    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
30    pub data: MaybeUndefined<Value>,
31    /// Additional fields on the inner MCP error object.
32    #[serde(flatten)]
33    pub extra: Map<String, Value>,
34}
35
36impl McpError {
37    /// Construct an inner MCP error without data.
38    #[must_use]
39    pub fn new(code: i32, message: impl Into<String>) -> Self {
40        Self {
41            code,
42            message: message.into(),
43            data: MaybeUndefined::Undefined,
44            extra: Map::new(),
45        }
46    }
47
48    /// Set data, preserving explicit JSON null.
49    #[must_use]
50    pub fn data(mut self, data: Value) -> Self {
51        self.data = if data.is_null() {
52            MaybeUndefined::Null
53        } else {
54            MaybeUndefined::Value(data)
55        };
56        self
57    }
58}
59
60/// **UNSTABLE**
61///
62/// The successful outer ACP `mcp/message` response carries exactly one
63/// inner MCP outcome: an opaque result (including JSON null), or an MCP error.
64/// Outer ACP errors are reserved for binding and runtime failures.
65///
66/// Both branches require their carrier key. An error MUST be a non-null object.
67/// Unknown outer fields are ignored. Inner result and error fields are preserved.
68/// Carrier `_meta` is optional. Omitted and `null` are equivalent.
69/// Senders MUST include exactly one outcome.
70#[serde_as]
71#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
72#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
73#[serde(untagged)]
74#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = "mcp/message")))]
75#[non_exhaustive]
76pub enum MessageMcpResponse {
77    /// An opaque inner MCP result.
78    Result {
79        /// Required, even if JSON null.
80        #[serde(deserialize_with = "Deserialize::deserialize")]
81        result: Value,
82        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
83        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
84        /// Implementations MUST NOT assign meaning to keys they do not recognize.
85        /// This is ACP metadata, not the inner MCP message's `_meta`.
86        ///
87        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
88        #[serde_as(deserialize_as = "DefaultOnError")]
89        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
90        #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
91        meta: Option<Map<String, Value>>,
92    },
93    /// A structured inner MCP error.
94    Error {
95        /// Required, non-null MCP error object.
96        error: McpError,
97        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
98        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
99        /// Implementations MUST NOT assign meaning to keys they do not recognize.
100        /// This is ACP metadata, not the inner MCP message's `_meta`.
101        ///
102        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
103        #[serde_as(deserialize_as = "DefaultOnError")]
104        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
105        #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
106        meta: Option<Map<String, Value>>,
107    },
108}
109
110impl MessageMcpResponse {
111    /// Wrap any JSON result without interpreting its MCP result type.
112    #[must_use]
113    pub fn success(result: Value) -> Self {
114        Self::Result { result, meta: None }
115    }
116
117    /// Wrap an inner MCP error in a successful outer ACP response.
118    #[must_use]
119    pub fn error(error: McpError) -> Self {
120        Self::Error { error, meta: None }
121    }
122
123    /// Attach optional carrier-level ACP metadata.
124    #[must_use]
125    pub fn meta(mut self, meta: impl IntoOption<Map<String, Value>>) -> Self {
126        match &mut self {
127            Self::Result { meta: field, .. } | Self::Error { meta: field, .. } => {
128                *field = meta.into_option();
129            }
130        }
131        self
132    }
133}
134
135/// **UNSTABLE**
136///
137/// Identifies an inner MCP request active against a server on this ACP connection.
138/// Generated by the caller and preserved unchanged by proxies, independently of
139/// the outer ACP JSON-RPC request ID.
140#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
141#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
142#[serde(transparent)]
143#[from(Arc<str>, String, &'static str)]
144#[non_exhaustive]
145pub struct McpRequestId(pub Arc<str>);
146
147impl McpRequestId {
148    /// Wraps a protocol string as a typed [`McpRequestId`].
149    #[must_use]
150    pub fn new(id: impl Into<Arc<str>>) -> Self {
151        Self(id.into())
152    }
153}
154
155/// **UNSTABLE**
156///
157/// Request parameters for `mcp/message`, sent from consumer to provider.
158#[serde_as]
159#[skip_serializing_none]
160#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
161#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
162#[serde(rename_all = "camelCase")]
163#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = MCP_MESSAGE_METHOD_NAME)))]
164#[cfg_attr(feature = "schemars", schemars(extend("x-scope" = {"mcpServer": ["serverId"]})))]
165#[non_exhaustive]
166pub struct MessageMcpRequest {
167    /// The declared ACP MCP server receiving this request.
168    pub server_id: McpServerAcpId,
169    /// The caller-generated identifier for the inner MCP request.
170    pub request_id: McpRequestId,
171    /// The inner MCP method name.
172    pub method: String,
173    /// Optional inner MCP params. Null is equivalent to omission.
174    #[serde(default)]
175    pub params: Option<serde_json::Map<String, serde_json::Value>>,
176    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
177    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
178    /// Implementations MUST NOT assign meaning to keys they do not recognize.
179    /// This is ACP metadata, not the inner MCP message's `_meta`.
180    ///
181    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
182    #[serde_as(deserialize_as = "DefaultOnError")]
183    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
184    #[serde(default)]
185    #[serde(rename = "_meta")]
186    pub meta: Option<Meta>,
187}
188
189impl MessageMcpRequest {
190    /// Builds [`MessageMcpRequest`] with required fields set.
191    #[must_use]
192    pub fn new(
193        server_id: impl Into<McpServerAcpId>,
194        request_id: impl Into<McpRequestId>,
195        method: impl Into<String>,
196    ) -> Self {
197        Self {
198            server_id: server_id.into(),
199            request_id: request_id.into(),
200            method: method.into(),
201            params: None,
202            meta: None,
203        }
204    }
205
206    /// Sets optional inner MCP params.
207    #[must_use]
208    pub fn params(
209        mut self,
210        params: impl IntoOption<serde_json::Map<String, serde_json::Value>>,
211    ) -> Self {
212        self.params = params.into_option();
213        self
214    }
215
216    /// Sets optional ACP extension metadata.
217    #[must_use]
218    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
219        self.meta = meta.into_option();
220        self
221    }
222}
223
224/// **UNSTABLE**
225///
226/// Notification for an active request, sent from provider to consumer.
227/// Includes subscription acknowledgements and updates.
228#[serde_as]
229#[skip_serializing_none]
230#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
231#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
232#[serde(rename_all = "camelCase")]
233#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = MCP_MESSAGE_METHOD_NAME)))]
234#[non_exhaustive]
235pub struct MessageMcpNotification {
236    /// The declared ACP MCP server handling the associated request.
237    pub server_id: McpServerAcpId,
238    /// The identifier of the active inner MCP request.
239    pub request_id: McpRequestId,
240    /// The inner MCP method name.
241    pub method: String,
242    /// Optional inner MCP params. Null is equivalent to omission.
243    #[serde(default)]
244    pub params: Option<serde_json::Map<String, serde_json::Value>>,
245    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
246    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
247    /// Implementations MUST NOT assign meaning to keys they do not recognize.
248    /// This is ACP metadata, not the inner MCP message's `_meta`.
249    ///
250    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
251    #[serde_as(deserialize_as = "DefaultOnError")]
252    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
253    #[serde(default)]
254    #[serde(rename = "_meta")]
255    pub meta: Option<Meta>,
256}
257
258impl MessageMcpNotification {
259    /// Builds [`MessageMcpNotification`] with required fields set.
260    #[must_use]
261    pub fn new(
262        server_id: impl Into<McpServerAcpId>,
263        request_id: impl Into<McpRequestId>,
264        method: impl Into<String>,
265    ) -> Self {
266        Self {
267            server_id: server_id.into(),
268            request_id: request_id.into(),
269            method: method.into(),
270            params: None,
271            meta: None,
272        }
273    }
274
275    /// Sets optional inner MCP params.
276    #[must_use]
277    pub fn params(
278        mut self,
279        params: impl IntoOption<serde_json::Map<String, serde_json::Value>>,
280    ) -> Self {
281        self.params = params.into_option();
282        self
283    }
284
285    /// Sets optional ACP extension metadata.
286    #[must_use]
287    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
288        self.meta = meta.into_option();
289        self
290    }
291}
292
293/// Method name for exchanging MCP-over-ACP messages.
294pub(crate) const MCP_MESSAGE_METHOD_NAME: &str = "mcp/message";
295
296#[cfg(test)]
297mod tests {
298    use serde_json::{Value, json};
299
300    use super::{McpError, MessageMcpResponse};
301    use crate::MaybeUndefined;
302
303    #[test]
304    fn result_is_opaque_and_present_even_when_null() {
305        for result in [
306            Value::Null,
307            json!(false),
308            json!(42),
309            json!("opaque"),
310            json!([null, 1]),
311            json!({"resultType": "future", "unknown": {"value": true}}),
312        ] {
313            let response = MessageMcpResponse::success(result.clone());
314            let wire = json!({"result": result});
315            assert_eq!(serde_json::to_value(&response).unwrap(), wire);
316            assert_eq!(
317                serde_json::from_value::<MessageMcpResponse>(wire).unwrap(),
318                response
319            );
320        }
321    }
322
323    #[test]
324    fn error_round_trips_data_and_extensions_without_acp_translation() {
325        for data in [
326            MaybeUndefined::Undefined,
327            MaybeUndefined::Null,
328            MaybeUndefined::Value(json!({"arbitrary": [1, null]})),
329        ] {
330            let mut error = McpError::new(-32000, "inner error");
331            error.data = data.clone();
332            error.extra.insert("future".into(), json!({"key": 1}));
333            let response = MessageMcpResponse::error(error);
334            let wire = serde_json::to_value(&response).unwrap();
335            assert_eq!(wire["error"]["code"], -32000);
336            assert_eq!(wire["error"].get("data").is_some(), !data.is_undefined());
337            assert_eq!(wire["error"]["future"], json!({"key": 1}));
338            assert_eq!(
339                serde_json::from_value::<MessageMcpResponse>(wire).unwrap(),
340                response
341            );
342        }
343        assert_eq!(
344            McpError::new(1, "x").data(Value::Null).data,
345            MaybeUndefined::Null
346        );
347    }
348
349    #[test]
350    fn a_carrier_key_is_required_and_errors_must_be_valid() {
351        for wire in [
352            Value::Null,
353            json!([]),
354            json!({}),
355            json!({"_meta": null}),
356            json!({"unexpected": 1}),
357            json!({"error": null}),
358            json!({"error": 1}),
359            json!({"error": []}),
360            json!({"error": {}}),
361            json!({"error": {"code": 1}}),
362            json!({"error": {"message": "x"}}),
363            json!({"error": {"code": null, "message": "x"}}),
364            json!({"error": {"code": 1, "message": null}}),
365            json!({"error": {"code": 1.5, "message": "x"}}),
366            json!({"error": {"code": "1", "message": "x"}}),
367        ] {
368            assert!(
369                serde_json::from_value::<MessageMcpResponse>(wire.clone()).is_err(),
370                "accepted {wire}"
371            );
372        }
373    }
374
375    #[test]
376    fn result_takes_precedence_when_both_outcome_keys_are_present() {
377        for result in [Value::Null, json!(42), json!({"opaque": [null, true]})] {
378            for error in [
379                Value::Null,
380                json!({"code": 1, "message": "x"}),
381                json!({}),
382                json!({"code": 1, "message": null}),
383            ] {
384                let wire = json!({"result": result, "error": error});
385                assert_eq!(
386                    serde_json::from_value::<MessageMcpResponse>(wire).unwrap(),
387                    MessageMcpResponse::success(result.clone())
388                );
389            }
390        }
391    }
392
393    #[test]
394    fn unknown_outer_fields_are_ignored_and_inner_extensions_are_preserved() {
395        for wire in [
396            json!({"result": null, "unexpected": {"nested": true}}),
397            json!({"result": {"future": [null, {"error": "opaque"}]}, "unexpected": 1}),
398            json!({"error": {"code": 1, "message": "x", "future": [null, true]}, "unexpected": null}),
399        ] {
400            let parsed: MessageMcpResponse = serde_json::from_value(wire.clone()).unwrap();
401            let mut expected = wire;
402            expected.as_object_mut().unwrap().remove("unexpected");
403            assert_eq!(serde_json::to_value(parsed).unwrap(), expected);
404        }
405    }
406
407    #[test]
408    fn carrier_metadata_is_optional_and_invalid_values_are_salvaged() {
409        for outcome in [
410            json!({"result": null}),
411            json!({"error": {"code": 1, "message": "x"}}),
412        ] {
413            let parsed: MessageMcpResponse = serde_json::from_value(outcome.clone()).unwrap();
414            assert_eq!(serde_json::to_value(parsed).unwrap(), outcome);
415            for meta in [
416                Value::Null,
417                json!(true),
418                json!(1),
419                json!("invalid"),
420                json!([]),
421            ] {
422                let mut wire = outcome.clone();
423                wire["_meta"] = meta;
424                let parsed: MessageMcpResponse = serde_json::from_value(wire).unwrap();
425                assert_eq!(serde_json::to_value(parsed).unwrap(), outcome);
426            }
427            let mut wire = outcome;
428            wire["_meta"] = json!({"extension": [null, true]});
429            let parsed: MessageMcpResponse = serde_json::from_value(wire.clone()).unwrap();
430            assert_eq!(serde_json::to_value(parsed).unwrap(), wire);
431        }
432        let meta = json!({"extension": [null, true]})
433            .as_object()
434            .unwrap()
435            .clone();
436        let response =
437            MessageMcpResponse::success(json!({"_meta": {"inner": true}})).meta(meta.clone());
438        assert_eq!(
439            serde_json::to_value(response).unwrap(),
440            json!({"result": {"_meta": {"inner": true}}, "_meta": meta})
441        );
442    }
443
444    #[cfg(feature = "schemars")]
445    #[test]
446    fn response_schema_requires_a_key_without_closing_outer_fields() {
447        let schema = serde_json::to_value(schemars::schema_for!(MessageMcpResponse)).unwrap();
448        assert!(schema.get("not").is_none());
449        let branches = schema["anyOf"].as_array().unwrap();
450        assert_eq!(branches.len(), 2);
451        assert_eq!(branches[0]["required"], json!(["result"]));
452        assert_eq!(branches[1]["required"], json!(["error"]));
453        for branch in branches {
454            assert_ne!(branch.get("additionalProperties"), Some(&json!(false)));
455            assert_eq!(
456                branch["properties"]["_meta"]["x-deserialize-default-on-error"],
457                true
458            );
459        }
460        assert_ne!(schema.get("additionalProperties"), Some(&json!(false)));
461    }
462}