Skip to main content

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