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, SessionId, ToolCallId};
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///
159/// `sessionId` and `toolCallId` name the session and tool call the request was
160/// sent for. Both are optional. The provider can use `sessionId` to choose
161/// which session the request runs for, and `toolCallId` to show the request
162/// with the tool call that the Agent reports. Neither field grants
163/// permission to run the request.
164///
165/// See RFD: [MCP-over-ACP](https://agentclientprotocol.com/rfds/mcp-over-acp#session-and-tool-call-attribution)
166#[serde_as]
167#[skip_serializing_none]
168#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
169#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
170#[serde(rename_all = "camelCase")]
171#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = MCP_MESSAGE_METHOD_NAME)))]
172#[cfg_attr(feature = "schemars", schemars(extend("x-scope" = {"mcpServer": ["serverId"], "session": ["sessionId"], "toolCall": ["toolCallId"]})))]
173#[cfg_attr(feature = "schemars", schemars(extend(
174    "if" = {"required": ["toolCallId"], "properties": {"toolCallId": {"type": "string"}}},
175    "then" = {"required": ["sessionId"], "properties": {"sessionId": {"type": "string"}}}
176)))]
177#[non_exhaustive]
178pub struct MessageMcpRequest {
179    /// The declared ACP MCP server receiving this request.
180    pub server_id: McpServerAcpId,
181    /// The caller-generated identifier for the inner MCP request.
182    pub request_id: McpRequestId,
183    /// The inner MCP method name.
184    pub method: String,
185    /// Optional inner MCP params. Null is equivalent to omission.
186    #[serde(default)]
187    pub params: Option<serde_json::Map<String, serde_json::Value>>,
188    /// The session whose work caused this request. It is the `sessionId` the
189    /// Agent uses on `session/update` for that work. For a child session's work,
190    /// that is the child's ID.
191    ///
192    /// Optional. Omitted and `null` are equivalent and mean the Agent supplied
193    /// no session. The Agent SHOULD include it when it knows the session, and
194    /// MUST NOT send another session's ID when it does not. A provider that
195    /// needs the session to run the request MAY reject a request without it.
196    #[serde(default)]
197    pub session_id: Option<SessionId>,
198    /// The tool call in that session that this request is part of. It is the
199    /// `toolCallId` the Agent uses to report the call in `session/update`. The
200    /// Agent SHOULD report the tool call before it sends the request.
201    ///
202    /// Optional. Omitted and `null` are equivalent and mean the Agent supplied
203    /// no tool call. The Agent MUST NOT send it without `sessionId`. More than
204    /// one request can name the same tool call.
205    #[serde_as(deserialize_as = "DefaultOnError")]
206    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
207    #[serde(default)]
208    pub tool_call_id: Option<ToolCallId>,
209    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
210    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
211    /// Implementations MUST NOT assign meaning to keys they do not recognize.
212    /// This is ACP metadata, not the inner MCP message's `_meta`.
213    ///
214    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
215    #[serde_as(deserialize_as = "DefaultOnError")]
216    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
217    #[serde(default)]
218    #[serde(rename = "_meta")]
219    pub meta: Option<Meta>,
220}
221
222impl MessageMcpRequest {
223    /// Builds [`MessageMcpRequest`] with required fields set.
224    #[must_use]
225    pub fn new(
226        server_id: impl Into<McpServerAcpId>,
227        request_id: impl Into<McpRequestId>,
228        method: impl Into<String>,
229    ) -> Self {
230        Self {
231            server_id: server_id.into(),
232            request_id: request_id.into(),
233            method: method.into(),
234            params: None,
235            session_id: None,
236            tool_call_id: None,
237            meta: None,
238        }
239    }
240
241    /// Sets optional inner MCP params.
242    #[must_use]
243    pub fn params(
244        mut self,
245        params: impl IntoOption<serde_json::Map<String, serde_json::Value>>,
246    ) -> Self {
247        self.params = params.into_option();
248        self
249    }
250
251    /// Sets or clears the session whose work caused this request.
252    #[must_use]
253    pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
254        self.session_id = session_id.into_option();
255        self
256    }
257
258    /// Sets or clears the tool call this request is part of. The Agent MUST
259    /// NOT send it without `sessionId`.
260    #[must_use]
261    pub fn tool_call_id(mut self, tool_call_id: impl IntoOption<ToolCallId>) -> Self {
262        self.tool_call_id = tool_call_id.into_option();
263        self
264    }
265
266    /// Sets optional ACP extension metadata.
267    #[must_use]
268    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
269        self.meta = meta.into_option();
270        self
271    }
272}
273
274/// **UNSTABLE**
275///
276/// Notification for an active request, sent from provider to consumer.
277/// Includes subscription acknowledgements and updates.
278#[serde_as]
279#[skip_serializing_none]
280#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
281#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
282#[serde(rename_all = "camelCase")]
283#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = MCP_MESSAGE_METHOD_NAME)))]
284#[non_exhaustive]
285pub struct MessageMcpNotification {
286    /// The declared ACP MCP server handling the associated request.
287    pub server_id: McpServerAcpId,
288    /// The identifier of the active inner MCP request.
289    pub request_id: McpRequestId,
290    /// The inner MCP method name.
291    pub method: String,
292    /// Optional inner MCP params. Null is equivalent to omission.
293    #[serde(default)]
294    pub params: Option<serde_json::Map<String, serde_json::Value>>,
295    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
296    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
297    /// Implementations MUST NOT assign meaning to keys they do not recognize.
298    /// This is ACP metadata, not the inner MCP message's `_meta`.
299    ///
300    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
301    #[serde_as(deserialize_as = "DefaultOnError")]
302    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
303    #[serde(default)]
304    #[serde(rename = "_meta")]
305    pub meta: Option<Meta>,
306}
307
308impl MessageMcpNotification {
309    /// Builds [`MessageMcpNotification`] with required fields set.
310    #[must_use]
311    pub fn new(
312        server_id: impl Into<McpServerAcpId>,
313        request_id: impl Into<McpRequestId>,
314        method: impl Into<String>,
315    ) -> Self {
316        Self {
317            server_id: server_id.into(),
318            request_id: request_id.into(),
319            method: method.into(),
320            params: None,
321            meta: None,
322        }
323    }
324
325    /// Sets optional inner MCP params.
326    #[must_use]
327    pub fn params(
328        mut self,
329        params: impl IntoOption<serde_json::Map<String, serde_json::Value>>,
330    ) -> Self {
331        self.params = params.into_option();
332        self
333    }
334
335    /// Sets optional ACP extension metadata.
336    #[must_use]
337    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
338        self.meta = meta.into_option();
339        self
340    }
341}
342
343/// Method name for exchanging MCP-over-ACP messages.
344pub(crate) const MCP_MESSAGE_METHOD_NAME: &str = "mcp/message";
345
346#[cfg(test)]
347mod tests {
348    use serde_json::{Value, json};
349
350    use super::{McpError, MessageMcpRequest, MessageMcpResponse, SessionId, ToolCallId};
351    use crate::MaybeUndefined;
352
353    #[test]
354    fn result_is_opaque_and_present_even_when_null() {
355        for result in [
356            Value::Null,
357            json!(false),
358            json!(42),
359            json!("opaque"),
360            json!([null, 1]),
361            json!({"resultType": "future", "unknown": {"value": true}}),
362        ] {
363            let response = MessageMcpResponse::success(result.clone());
364            let wire = json!({"result": result});
365            assert_eq!(serde_json::to_value(&response).unwrap(), wire);
366            assert_eq!(
367                serde_json::from_value::<MessageMcpResponse>(wire).unwrap(),
368                response
369            );
370        }
371    }
372
373    #[test]
374    fn error_round_trips_data_and_extensions_without_acp_translation() {
375        for data in [
376            MaybeUndefined::Undefined,
377            MaybeUndefined::Null,
378            MaybeUndefined::Value(json!({"arbitrary": [1, null]})),
379        ] {
380            let mut error = McpError::new(-32000, "inner error");
381            error.data = data.clone();
382            error.extra.insert("future".into(), json!({"key": 1}));
383            let response = MessageMcpResponse::error(error);
384            let wire = serde_json::to_value(&response).unwrap();
385            assert_eq!(wire["error"]["code"], -32000);
386            assert_eq!(wire["error"].get("data").is_some(), !data.is_undefined());
387            assert_eq!(wire["error"]["future"], json!({"key": 1}));
388            assert_eq!(
389                serde_json::from_value::<MessageMcpResponse>(wire).unwrap(),
390                response
391            );
392        }
393        assert_eq!(
394            McpError::new(1, "x").data(Value::Null).data,
395            MaybeUndefined::Null
396        );
397    }
398
399    #[test]
400    fn a_carrier_key_is_required_and_errors_must_be_valid() {
401        for wire in [
402            Value::Null,
403            json!([]),
404            json!({}),
405            json!({"_meta": null}),
406            json!({"unexpected": 1}),
407            json!({"error": null}),
408            json!({"error": 1}),
409            json!({"error": []}),
410            json!({"error": {}}),
411            json!({"error": {"code": 1}}),
412            json!({"error": {"message": "x"}}),
413            json!({"error": {"code": null, "message": "x"}}),
414            json!({"error": {"code": 1, "message": null}}),
415            json!({"error": {"code": 1.5, "message": "x"}}),
416            json!({"error": {"code": "1", "message": "x"}}),
417        ] {
418            assert!(
419                serde_json::from_value::<MessageMcpResponse>(wire.clone()).is_err(),
420                "accepted {wire}"
421            );
422        }
423    }
424
425    #[test]
426    fn result_takes_precedence_when_both_outcome_keys_are_present() {
427        for result in [Value::Null, json!(42), json!({"opaque": [null, true]})] {
428            for error in [
429                Value::Null,
430                json!({"code": 1, "message": "x"}),
431                json!({}),
432                json!({"code": 1, "message": null}),
433            ] {
434                let wire = json!({"result": result, "error": error});
435                assert_eq!(
436                    serde_json::from_value::<MessageMcpResponse>(wire).unwrap(),
437                    MessageMcpResponse::success(result.clone())
438                );
439            }
440        }
441    }
442
443    #[test]
444    fn unknown_outer_fields_are_ignored_and_inner_extensions_are_preserved() {
445        for wire in [
446            json!({"result": null, "unexpected": {"nested": true}}),
447            json!({"result": {"future": [null, {"error": "opaque"}]}, "unexpected": 1}),
448            json!({"error": {"code": 1, "message": "x", "future": [null, true]}, "unexpected": null}),
449        ] {
450            let parsed: MessageMcpResponse = serde_json::from_value(wire.clone()).unwrap();
451            let mut expected = wire;
452            expected.as_object_mut().unwrap().remove("unexpected");
453            assert_eq!(serde_json::to_value(parsed).unwrap(), expected);
454        }
455    }
456
457    #[test]
458    fn carrier_metadata_is_optional_and_invalid_values_are_salvaged() {
459        for outcome in [
460            json!({"result": null}),
461            json!({"error": {"code": 1, "message": "x"}}),
462        ] {
463            let parsed: MessageMcpResponse = serde_json::from_value(outcome.clone()).unwrap();
464            assert_eq!(serde_json::to_value(parsed).unwrap(), outcome);
465            for meta in [
466                Value::Null,
467                json!(true),
468                json!(1),
469                json!("invalid"),
470                json!([]),
471            ] {
472                let mut wire = outcome.clone();
473                wire["_meta"] = meta;
474                let parsed: MessageMcpResponse = serde_json::from_value(wire).unwrap();
475                assert_eq!(serde_json::to_value(parsed).unwrap(), outcome);
476            }
477            let mut wire = outcome;
478            wire["_meta"] = json!({"extension": [null, true]});
479            let parsed: MessageMcpResponse = serde_json::from_value(wire.clone()).unwrap();
480            assert_eq!(serde_json::to_value(parsed).unwrap(), wire);
481        }
482        let meta = json!({"extension": [null, true]})
483            .as_object()
484            .unwrap()
485            .clone();
486        let response =
487            MessageMcpResponse::success(json!({"_meta": {"inner": true}})).meta(meta.clone());
488        assert_eq!(
489            serde_json::to_value(response).unwrap(),
490            json!({"result": {"_meta": {"inner": true}}, "_meta": meta})
491        );
492    }
493
494    #[test]
495    fn request_attribution_is_optional_and_null_means_omitted() {
496        let plain = MessageMcpRequest::new("s", "r", "tools/call");
497        let session = plain.clone().session_id(SessionId::new("child"));
498        for (attribution, expected) in [
499            (json!({}), plain.clone()),
500            (json!({"sessionId": null, "toolCallId": null}), plain),
501            (json!({"sessionId": "child"}), session.clone()),
502            (
503                json!({"sessionId": "child", "toolCallId": "call"}),
504                session.tool_call_id(ToolCallId::new("call")),
505            ),
506        ] {
507            let mut wire = json!({"serverId": "s", "requestId": "r", "method": "tools/call"});
508            wire.as_object_mut()
509                .unwrap()
510                .extend(attribution.as_object().unwrap().clone());
511            let parsed: MessageMcpRequest = serde_json::from_value(wire.clone()).unwrap();
512            assert_eq!(parsed, expected, "{wire}");
513            // Unset fields are left out, so a request without them is unchanged.
514            wire.as_object_mut().unwrap().retain(|_, v| !v.is_null());
515            assert_eq!(serde_json::to_value(&parsed).unwrap(), wire);
516        }
517    }
518
519    #[test]
520    fn request_rejects_a_malformed_session_id() {
521        for session_id in [json!(42), json!({}), json!(["child"])] {
522            let wire = json!({
523                "serverId": "s",
524                "requestId": "r",
525                "method": "tools/call",
526                "sessionId": session_id,
527                "toolCallId": "call",
528            });
529            assert!(
530                serde_json::from_value::<MessageMcpRequest>(wire.clone()).is_err(),
531                "accepted {wire}"
532            );
533        }
534    }
535
536    #[cfg(feature = "schemars")]
537    #[test]
538    fn request_schema_requires_a_session_for_a_tool_call() {
539        let schema = serde_json::to_value(schemars::schema_for!(MessageMcpRequest)).unwrap();
540        assert_eq!(
541            schema["required"],
542            json!(["serverId", "requestId", "method"])
543        );
544        assert_eq!(schema["if"]["required"], json!(["toolCallId"]));
545        assert_eq!(schema["then"]["required"], json!(["sessionId"]));
546    }
547
548    #[cfg(feature = "schemars")]
549    #[test]
550    fn response_schema_requires_a_key_without_closing_outer_fields() {
551        let schema = serde_json::to_value(schemars::schema_for!(MessageMcpResponse)).unwrap();
552        assert!(schema.get("not").is_none());
553        let branches = schema["anyOf"].as_array().unwrap();
554        assert_eq!(branches.len(), 2);
555        assert_eq!(branches[0]["required"], json!(["result"]));
556        assert_eq!(branches[1]["required"], json!(["error"]));
557        for branch in branches {
558            assert_ne!(branch.get("additionalProperties"), Some(&json!(false)));
559            assert_eq!(
560                branch["properties"]["_meta"]["x-deserialize-default-on-error"],
561                true
562            );
563        }
564        assert_ne!(schema.get("additionalProperties"), Some(&json!(false)));
565    }
566}