1use 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#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
21#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
22#[non_exhaustive]
23pub struct McpError {
24 pub code: i32,
26 pub message: String,
28 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
30 pub data: MaybeUndefined<Value>,
31 #[serde(flatten)]
33 pub extra: Map<String, Value>,
34}
35
36impl McpError {
37 #[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 #[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#[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 Result {
79 #[serde(deserialize_with = "Deserialize::deserialize")]
81 result: Value,
82 #[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 Error {
95 error: McpError,
97 #[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 #[must_use]
113 pub fn success(result: Value) -> Self {
114 Self::Result { result, meta: None }
115 }
116
117 #[must_use]
119 pub fn error(error: McpError) -> Self {
120 Self::Error { error, meta: None }
121 }
122
123 #[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#[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 #[must_use]
150 pub fn new(id: impl Into<Arc<str>>) -> Self {
151 Self(id.into())
152 }
153}
154
155#[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 pub server_id: McpServerAcpId,
169 pub request_id: McpRequestId,
171 pub method: String,
173 #[serde(default)]
175 pub params: Option<serde_json::Map<String, serde_json::Value>>,
176 #[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 #[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 #[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 #[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#[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 pub server_id: McpServerAcpId,
238 pub request_id: McpRequestId,
240 pub method: String,
242 #[serde(default)]
244 pub params: Option<serde_json::Map<String, serde_json::Value>>,
245 #[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 #[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 #[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 #[must_use]
287 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
288 self.meta = meta.into_option();
289 self
290 }
291}
292
293pub(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}