1mod builder;
84mod controlled;
85mod fast;
86pub mod protocol;
87mod schema;
88mod tool;
89mod transport;
90
91pub use blazingly_json::{json, Map, RawJson, RawValue, Value};
92pub use builder::McpServer;
93pub use controlled::{
94 serve_controlled, serve_controlled_streams, CancellationToken, ConcurrentMcpServer,
95 ConcurrentToolServer, RequestContext, RuntimeConfig,
96};
97pub use schema::{validate_tool_schema, SchemaDefect, SchemaDefectKind};
98pub use tool::{
99 decorate_schema, object_schema, IntoToolReply, Json, PreparedTool, ToolAnnotations,
100 ToolDefinition, ToolError, ToolSchema,
101};
102pub use transport::{FlushPolicy, TransportConfig, TransportLimits};
103
104#[cfg(feature = "macros")]
105pub use mcport_macros::{tool, tools, ToolOutput, ToolSchema};
106
107#[doc(hidden)]
109pub mod __private {
110 pub use blazingly_json::{from_str, to_value};
111}
112
113use serde::Serialize;
114use std::io::{self, BufRead, Write};
115
116pub const DEFAULT_PROTOCOL_VERSION: &str = "2025-11-25";
118
119pub const MODERN_PROTOCOL_VERSION: &str = "2026-07-28";
121
122pub const SUPPORTED_PROTOCOL_VERSIONS: &[&str] =
124 &[MODERN_PROTOCOL_VERSION, "2025-11-25", "2025-06-18"];
125
126const SUPPORTED_LEGACY_PROTOCOL_VERSIONS: &[&str] = &["2025-11-25", "2025-06-18"];
127
128#[must_use]
133pub fn negotiate_protocol_version(requested: Option<&str>) -> &'static str {
134 requested
135 .and_then(|requested| {
136 SUPPORTED_LEGACY_PROTOCOL_VERSIONS
137 .iter()
138 .copied()
139 .find(|supported| *supported == requested)
140 })
141 .unwrap_or(DEFAULT_PROTOCOL_VERSION)
142}
143
144#[derive(Debug, Clone)]
146pub struct ServerIdentity {
147 pub name: String,
149 pub version: String,
151 pub instructions: String,
153}
154
155impl ServerIdentity {
156 #[must_use]
157 pub fn new(
158 name: impl Into<String>,
159 version: impl Into<String>,
160 instructions: impl Into<String>,
161 ) -> Self {
162 Self {
163 name: name.into(),
164 version: version.into(),
165 instructions: instructions.into(),
166 }
167 }
168}
169
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
178pub enum ToolPayload {
179 Text,
181 #[default]
184 Mirrored,
185 Structured,
191}
192
193impl ToolPayload {
194 #[must_use]
196 pub fn is_structured(self) -> bool {
197 matches!(self, Self::Mirrored | Self::Structured)
198 }
199
200 #[must_use]
202 pub fn has_text(self) -> bool {
203 matches!(self, Self::Text | Self::Mirrored)
204 }
205}
206
207#[derive(Debug, Clone)]
209pub enum ToolReply {
210 Success {
212 value: Value,
214 payload: ToolPayload,
216 },
217 Serialized {
219 value: Box<RawValue>,
221 payload: ToolPayload,
223 },
224 StructuredAny {
228 value: Box<RawValue>,
230 },
231 Error(String),
233 Literal {
235 text: String,
237 },
238}
239
240impl ToolReply {
241 #[must_use]
246 pub fn structured(value: impl Serialize) -> Self {
247 Self::success_with(value, ToolPayload::Mirrored)
248 }
249
250 #[must_use]
258 pub fn text(value: impl Serialize) -> Self {
259 Self::success_with(value, ToolPayload::Text)
260 }
261
262 #[must_use]
268 pub fn literal_text(text: impl Into<String>) -> Self {
269 Self::Literal { text: text.into() }
270 }
271
272 #[must_use]
277 pub fn structured_only(value: impl Serialize) -> Self {
278 Self::success_with(value, ToolPayload::Structured)
279 }
280
281 #[must_use]
283 pub fn success(value: impl Serialize, structured: bool) -> Self {
284 Self::success_with(
285 value,
286 if structured {
287 ToolPayload::Mirrored
288 } else {
289 ToolPayload::Text
290 },
291 )
292 }
293
294 #[must_use]
302 pub fn success_with(value: impl Serialize, payload: ToolPayload) -> Self {
303 match blazingly_json::to_raw_value(&value) {
304 Ok(value) if payload.is_structured() && !value.get().starts_with('{') => {
305 Self::StructuredAny { value }
306 }
307 Ok(value) => Self::Serialized { payload, value },
308 Err(error) => Self::Error(format!("tool result serialization failed: {error}")),
309 }
310 }
311
312 #[must_use]
314 pub fn error(message: impl Into<String>) -> Self {
315 Self::Error(message.into())
316 }
317}
318
319#[derive(Debug, Clone)]
321pub enum MethodReply {
322 Success(Value),
324 Error {
326 code: i64,
328 message: String,
330 data: Option<Value>,
332 },
333}
334
335impl MethodReply {
336 #[must_use]
338 pub fn success(value: impl Serialize) -> Self {
339 match blazingly_json::to_value(value) {
340 Ok(value) => Self::Success(value),
341 Err(error) => Self::error(
342 -32_603,
343 format!("method result serialization failed: {error}"),
344 ),
345 }
346 }
347
348 #[must_use]
350 pub fn error(code: i64, message: impl Into<String>) -> Self {
351 Self::Error {
352 code,
353 message: message.into(),
354 data: None,
355 }
356 }
357
358 #[must_use]
360 pub fn error_with_data(code: i64, message: impl Into<String>, data: impl Serialize) -> Self {
361 Self::Error {
362 code,
363 message: message.into(),
364 data: blazingly_json::to_value(data).ok(),
365 }
366 }
367}
368
369#[derive(Debug, Clone)]
371pub struct ToolPage {
372 pub tools: Value,
374 pub next_cursor: Option<String>,
376}
377
378impl ToolPage {
379 #[must_use]
381 pub const fn complete(tools: Value) -> Self {
382 Self {
383 tools,
384 next_cursor: None,
385 }
386 }
387}
388
389pub trait ToolServer {
391 fn identity(&self) -> ServerIdentity;
393
394 fn identity_ref(&self) -> Option<&ServerIdentity> {
400 None
401 }
402
403 fn capabilities(&self) -> Value {
405 json!({"tools": {"listChanged": false}})
406 }
407
408 fn capabilities_ref(&self) -> Option<&Value> {
410 None
411 }
412
413 fn catalog(&mut self) -> Value;
415
416 fn catalog_ref(&mut self) -> Option<&Value> {
420 None
421 }
422
423 fn catalog_raw_ref(&mut self) -> Option<&RawValue> {
429 None
430 }
431
432 fn registration_errors(&self) -> &[String] {
437 &[]
438 }
439
440 fn catalog_is_paginated(&self) -> bool {
442 false
443 }
444
445 fn catalog_page(&mut self, cursor: Option<&str>) -> Result<ToolPage, String> {
447 if cursor.is_some() {
448 return Err("invalid tools/list cursor".to_owned());
449 }
450 Ok(ToolPage::complete(self.catalog()))
451 }
452
453 fn has_tool(&self, _name: &str) -> Option<bool> {
460 None
461 }
462
463 fn call(&mut self, name: &str, arguments: Value) -> ToolReply;
465
466 fn call_raw(&mut self, name: &str, arguments: RawJson<'_>) -> ToolReply {
472 match arguments.deserialize::<Value>() {
473 Ok(arguments) => self.call(name, arguments),
474 Err(error) => ToolReply::error(format!("invalid arguments for {name}: {error}")),
475 }
476 }
477
478 fn call_method(&mut self, _method: &str, _params: Value) -> Option<MethodReply> {
482 None
483 }
484
485 fn strict_schema_defects(&self) -> &[SchemaDefect] {
494 &[]
495 }
496}
497
498pub fn serve(server: &mut impl ToolServer) -> io::Result<()> {
505 serve_with_limits(server, TransportLimits::default())
506}
507
508pub fn serve_with_limits(server: &mut impl ToolServer, limits: TransportLimits) -> io::Result<()> {
514 let stdin = io::stdin();
515 let stdout = io::stdout();
516 serve_streams_with_limits(server, stdin.lock(), stdout.lock(), limits)
517}
518
519pub fn serve_with_config(server: &mut impl ToolServer, config: TransportConfig) -> io::Result<()> {
526 let stdin = io::stdin();
527 let stdout = io::stdout();
528 match config.flush_policy {
529 FlushPolicy::PerMessage => {
530 serve_streams_with_config(server, stdin.lock(), stdout.lock(), config)
531 }
532 FlushPolicy::Batch { .. } => serve_streams_with_config(
533 server,
534 stdin.lock(),
535 io::BufWriter::new(stdout.lock()),
536 config,
537 ),
538 }
539}
540
541pub fn serve_streams(
550 server: &mut impl ToolServer,
551 reader: impl BufRead,
552 writer: impl Write,
553) -> io::Result<()> {
554 serve_streams_with_limits(server, reader, writer, TransportLimits::default())
555}
556
557pub fn serve_streams_with_limits(
567 server: &mut impl ToolServer,
568 reader: impl BufRead,
569 writer: impl Write,
570 limits: TransportLimits,
571) -> io::Result<()> {
572 transport::serve_streams_bounded(server, reader, writer, limits)
573}
574
575pub fn serve_streams_with_config(
581 server: &mut impl ToolServer,
582 reader: impl BufRead,
583 writer: impl Write,
584 config: TransportConfig,
585) -> io::Result<()> {
586 transport::serve_streams_configured(server, reader, writer, config)
587}
588
589pub fn serve_message(
599 server: &mut impl ToolServer,
600 line: &str,
601 writer: &mut impl Write,
602) -> io::Result<bool> {
603 let line = line.trim_start_matches('\u{feff}');
604 if line.trim().is_empty() {
605 return Ok(false);
606 }
607 fast::dispatch_line(server, line, writer)
608}
609
610pub fn dispatch(server: &mut impl ToolServer, request: &Value) -> Option<Value> {
615 if !request.is_object() {
616 return Some(protocol::error(
617 &Value::Null,
618 -32_600,
619 "invalid JSON-RPC request",
620 ));
621 }
622 let id = request.get("id").cloned();
623 if request.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
624 return Some(protocol::error(
625 id.as_ref().unwrap_or(&Value::Null),
626 -32_600,
627 "invalid JSON-RPC version",
628 ));
629 }
630 let Some(method) = request.get("method").and_then(Value::as_str) else {
631 return Some(protocol::error(
632 id.as_ref().unwrap_or(&Value::Null),
633 -32_600,
634 "missing JSON-RPC method",
635 ));
636 };
637 let modern = match request_uses_modern_protocol(request, id.as_ref().unwrap_or(&Value::Null)) {
638 Ok(modern) => modern,
639 Err(response) => return Some(response),
640 };
641 let id = id?;
642 Some(match method {
643 "initialize" => initialize_response(server, request, &id),
644 "server/discover" if modern => discover_response(server, &id),
645 "ping" if modern => protocol::error(&id, -32_601, "method not found: ping"),
646 "ping" => protocol::success(&id, &json!({})),
647 "tools/list" => tools_list_response(server, request, &id, modern),
648 "tools/call" => tool_call_response(server, request, &id, modern),
649 _ => extension_method_response(server, method, request, &id),
650 })
651}
652
653fn extension_method_response(
654 server: &mut impl ToolServer,
655 method: &str,
656 request: &Value,
657 id: &Value,
658) -> Value {
659 let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
660 match server.call_method(method, params) {
661 Some(MethodReply::Success(result)) => protocol::success(id, &result),
662 Some(MethodReply::Error {
663 code,
664 message,
665 data: Some(data),
666 }) => protocol::error_with_data(id, code, message, data),
667 Some(MethodReply::Error {
668 code,
669 message,
670 data: None,
671 }) => protocol::error(id, code, message),
672 None => protocol::error(id, -32_601, format!("method not found: {method}")),
673 }
674}
675
676fn request_uses_modern_protocol(request: &Value, id: &Value) -> Result<bool, Value> {
677 let requested_version = request
678 .pointer("/params/_meta/io.modelcontextprotocol~1protocolVersion")
679 .and_then(Value::as_str);
680 let Some(requested_version) = requested_version else {
681 return Ok(false);
682 };
683 if !SUPPORTED_PROTOCOL_VERSIONS.contains(&requested_version) {
684 return Err(protocol::error_with_data(
685 id,
686 -32_022,
687 "Unsupported protocol version",
688 json!({
689 "supported": SUPPORTED_PROTOCOL_VERSIONS,
690 "requested": requested_version
691 }),
692 ));
693 }
694 if requested_version != MODERN_PROTOCOL_VERSION {
695 return Err(protocol::error(
696 id,
697 -32_600,
698 "legacy protocol versions require the initialize lifecycle",
699 ));
700 }
701 if request
702 .pointer("/params/_meta/io.modelcontextprotocol~1clientCapabilities")
703 .is_none()
704 {
705 return Err(protocol::error(
706 id,
707 -32_602,
708 "missing io.modelcontextprotocol/clientCapabilities",
709 ));
710 }
711 Ok(true)
712}
713
714fn initialize_response(server: &impl ToolServer, request: &Value, id: &Value) -> Value {
715 let requested_version = request
716 .pointer("/params/protocolVersion")
717 .and_then(Value::as_str);
718 let version = negotiate_protocol_version(requested_version);
719 let identity = server.identity();
720 let capabilities = server
721 .capabilities_ref()
722 .cloned()
723 .unwrap_or_else(|| server.capabilities());
724 protocol::success(
725 id,
726 &json!({
727 "protocolVersion": version,
728 "capabilities": capabilities,
729 "serverInfo": {
730 "name": identity.name,
731 "version": identity.version
732 },
733 "instructions": identity.instructions
734 }),
735 )
736}
737
738fn discover_response(server: &impl ToolServer, id: &Value) -> Value {
739 let identity = server.identity();
740 let capabilities = server
741 .capabilities_ref()
742 .cloned()
743 .unwrap_or_else(|| server.capabilities());
744 protocol::success(
745 id,
746 &json!({
747 "resultType": "complete",
748 "supportedVersions": SUPPORTED_PROTOCOL_VERSIONS,
749 "capabilities": capabilities,
750 "_meta": {
751 "io.modelcontextprotocol/serverInfo": {
752 "name": identity.name,
753 "version": identity.version
754 }
755 },
756 "instructions": identity.instructions
757 }),
758 )
759}
760
761fn tool_call_response(
762 server: &mut impl ToolServer,
763 request: &Value,
764 id: &Value,
765 modern: bool,
766) -> Value {
767 let Some(name) = request.pointer("/params/name").and_then(Value::as_str) else {
768 return protocol::error(id, -32_602, "tools/call requires params.name");
769 };
770 if server.has_tool(name) == Some(false) {
771 return protocol::error(id, -32_602, format!("unknown tool: {name}"));
772 }
773 let arguments = request
774 .pointer("/params/arguments")
775 .cloned()
776 .unwrap_or_else(|| json!({}));
777 let mut response = match server.call(name, arguments) {
778 ToolReply::Success { value, payload } => protocol::tool_success(id, &value, payload),
779 ToolReply::Serialized { value, payload } => protocol::tool_success_raw(id, &value, payload),
780 ToolReply::StructuredAny { value } if modern => protocol::tool_success_raw_any(id, &value),
781 ToolReply::StructuredAny { value } => {
782 protocol::tool_success_raw(id, &value, ToolPayload::Text)
783 }
784 ToolReply::Literal { text } => protocol::tool_literal_text(id, text),
785 ToolReply::Error(message) => protocol::tool_error(id, message),
786 };
787 if modern {
788 protocol::mark_complete(&mut response);
789 }
790 response
791}
792
793fn tools_list_response(
794 server: &mut impl ToolServer,
795 request: &Value,
796 id: &Value,
797 modern: bool,
798) -> Value {
799 let cursor = request.pointer("/params/cursor").and_then(Value::as_str);
800 let page = if server.catalog_is_paginated() || cursor.is_some() {
801 match server.catalog_page(cursor) {
802 Ok(page) => page,
803 Err(message) => return protocol::error(id, -32_602, message),
804 }
805 } else {
806 ToolPage::complete(server.catalog())
807 };
808 let mut result = json!({"tools": page.tools});
809 if let (Some(result), Some(next_cursor)) = (result.as_object_mut(), page.next_cursor) {
810 result.insert("nextCursor".to_owned(), Value::String(next_cursor));
811 }
812 let mut response = protocol::success(id, &result);
813 if modern {
814 protocol::mark_complete(&mut response);
815 }
816 response
817}
818
819#[cfg(test)]
820mod tests {
821 use super::{
822 dispatch, json, serve_message, serve_streams, MethodReply, ServerIdentity, ToolReply,
823 ToolServer, Value,
824 };
825
826 struct Echo {
827 calls: usize,
828 }
829
830 impl ToolServer for Echo {
831 fn identity(&self) -> ServerIdentity {
832 ServerIdentity::new("echo", "1.2.3", "Echoes tool arguments back.")
833 }
834
835 fn catalog(&mut self) -> Value {
836 json!([{
837 "name": "echo",
838 "description": "Echo the arguments.",
839 "inputSchema": {"type": "object", "additionalProperties": true}
840 }])
841 }
842
843 fn call(&mut self, name: &str, arguments: Value) -> ToolReply {
844 self.calls += 1;
845 match name {
846 "echo" => ToolReply::structured(arguments),
847 "flat" => ToolReply::text(arguments),
848 "scalar" => ToolReply::structured(5),
849 _ => ToolReply::error(format!("unknown tool: {name}")),
850 }
851 }
852 }
853
854 struct Resources;
855
856 impl ToolServer for Resources {
857 fn identity(&self) -> ServerIdentity {
858 ServerIdentity::new("resources", "1.0.0", "Resource test server.")
859 }
860
861 fn capabilities(&self) -> Value {
862 json!({
863 "tools": {"listChanged": false},
864 "resources": {"subscribe": false, "listChanged": false}
865 })
866 }
867
868 fn catalog(&mut self) -> Value {
869 json!([])
870 }
871
872 fn call(&mut self, name: &str, _arguments: Value) -> ToolReply {
873 ToolReply::error(format!("unknown tool: {name}"))
874 }
875
876 fn call_method(&mut self, method: &str, params: Value) -> Option<MethodReply> {
877 match method {
878 "resources/list" => Some(MethodReply::success(json!({
879 "resources": [{
880 "uri": "test://resource",
881 "name": "test"
882 }]
883 }))),
884 "resources/read" => {
885 if params.get("uri").and_then(Value::as_str) == Some("test://resource") {
886 Some(MethodReply::success(json!({
887 "contents": [{
888 "uri": "test://resource",
889 "text": "ok"
890 }]
891 })))
892 } else {
893 Some(MethodReply::error(-32_602, "unknown resource URI"))
894 }
895 }
896 _ => None,
897 }
898 }
899 }
900
901 #[test]
902 fn composes_capabilities_and_extension_methods() {
903 let mut server = Resources;
904 let initialized = dispatch(
905 &mut server,
906 &json!({
907 "jsonrpc": "2.0",
908 "id": 1,
909 "method": "initialize",
910 "params": {"protocolVersion": "2025-11-25"}
911 }),
912 )
913 .unwrap();
914 assert_eq!(
915 initialized["result"]["capabilities"]["resources"]["subscribe"],
916 false
917 );
918
919 let listed = dispatch(
920 &mut server,
921 &json!({
922 "jsonrpc": "2.0",
923 "id": 2,
924 "method": "resources/list"
925 }),
926 )
927 .unwrap();
928 assert_eq!(listed["result"]["resources"][0]["uri"], "test://resource");
929
930 let mut output = Vec::new();
931 assert!(serve_message(
932 &mut server,
933 r#"{"jsonrpc":"2.0","id":3,"method":"resources/read","params":{"uri":"missing"}}"#,
934 &mut output,
935 )
936 .unwrap());
937 let response: Value = blazingly_json::from_slice(&output).expect("valid JSON response");
938 assert_eq!(response["error"]["code"], -32_602);
939 }
940
941 #[test]
942 fn negotiates_lists_and_calls() {
943 let mut server = Echo { calls: 0 };
944 let initialized = dispatch(
945 &mut server,
946 &json!({
947 "jsonrpc": "2.0",
948 "id": 1,
949 "method": "initialize",
950 "params": {"protocolVersion": "2025-06-18"}
951 }),
952 )
953 .unwrap();
954 assert_eq!(initialized["result"]["protocolVersion"], "2025-06-18");
955 assert_eq!(initialized["result"]["serverInfo"]["name"], "echo");
956 assert_eq!(server.calls, 0, "initialize must not call tools");
957
958 let fallback = dispatch(
959 &mut server,
960 &json!({"jsonrpc": "2.0", "id": 2, "method": "initialize"}),
961 )
962 .unwrap();
963 assert_eq!(
964 fallback["result"]["protocolVersion"],
965 super::DEFAULT_PROTOCOL_VERSION
966 );
967
968 let unknown_version = dispatch(
969 &mut server,
970 &json!({
971 "jsonrpc": "2.0",
972 "id": 3,
973 "method": "initialize",
974 "params": {"protocolVersion": "2099-01-01"}
975 }),
976 )
977 .unwrap();
978 assert_eq!(
979 unknown_version["result"]["protocolVersion"],
980 super::DEFAULT_PROTOCOL_VERSION
981 );
982
983 let listed = dispatch(
984 &mut server,
985 &json!({"jsonrpc": "2.0", "id": 4, "method": "tools/list"}),
986 )
987 .unwrap();
988 assert_eq!(listed["result"]["tools"].as_array().map(Vec::len), Some(1));
989
990 let called = dispatch(
991 &mut server,
992 &json!({
993 "jsonrpc": "2.0",
994 "id": 5,
995 "method": "tools/call",
996 "params": {"name": "echo", "arguments": {"value": 7}}
997 }),
998 )
999 .unwrap();
1000 assert_eq!(called["result"]["isError"], false);
1001 assert_eq!(called["result"]["structuredContent"]["value"], 7);
1002
1003 let flat = dispatch(
1004 &mut server,
1005 &json!({
1006 "jsonrpc": "2.0",
1007 "id": 6,
1008 "method": "tools/call",
1009 "params": {"name": "flat", "arguments": {"value": 7}}
1010 }),
1011 )
1012 .unwrap();
1013 assert!(flat["result"].get("structuredContent").is_none());
1014
1015 let failed = dispatch(
1016 &mut server,
1017 &json!({
1018 "jsonrpc": "2.0",
1019 "id": 7,
1020 "method": "tools/call",
1021 "params": {"name": "missing"}
1022 }),
1023 )
1024 .unwrap();
1025 assert_eq!(failed["result"]["isError"], true);
1026 }
1027
1028 #[test]
1029 fn rejects_invalid_requests_without_stopping() {
1030 let mut server = Echo { calls: 0 };
1031 let no_method = dispatch(&mut server, &json!({"jsonrpc": "2.0", "id": 1})).unwrap();
1032 assert_eq!(no_method["error"]["code"], -32_600);
1033
1034 let wrong_version = dispatch(
1035 &mut server,
1036 &json!({"jsonrpc": "1.0", "id": 2, "method": "ping"}),
1037 )
1038 .unwrap();
1039 assert_eq!(wrong_version["error"]["code"], -32_600);
1040
1041 let non_object = dispatch(&mut server, &json!([])).unwrap();
1042 assert_eq!(non_object["error"]["code"], -32_600);
1043
1044 let unknown = dispatch(
1045 &mut server,
1046 &json!({"jsonrpc": "2.0", "id": 3, "method": "resources/list"}),
1047 )
1048 .unwrap();
1049 assert_eq!(unknown["error"]["code"], -32_601);
1050
1051 let unnamed = dispatch(
1052 &mut server,
1053 &json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call"}),
1054 )
1055 .unwrap();
1056 assert_eq!(unnamed["error"]["code"], -32_602);
1057
1058 let notification = dispatch(
1059 &mut server,
1060 &json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
1061 );
1062 assert!(notification.is_none(), "notifications are not answered");
1063
1064 let malformed_notification =
1065 dispatch(&mut server, &json!({"jsonrpc": "1.0", "method": "ping"})).unwrap();
1066 assert_eq!(malformed_notification["id"], Value::Null);
1067 assert_eq!(malformed_notification["error"]["code"], -32_600);
1068 }
1069
1070 #[test]
1071 fn supports_modern_discovery_and_versioned_tool_results() {
1072 let modern_meta = json!({
1073 "io.modelcontextprotocol/protocolVersion": super::MODERN_PROTOCOL_VERSION,
1074 "io.modelcontextprotocol/clientInfo": {"name": "test", "version": "1"},
1075 "io.modelcontextprotocol/clientCapabilities": {}
1076 });
1077 let mut server = Echo { calls: 0 };
1078 let discovered = dispatch(
1079 &mut server,
1080 &json!({
1081 "jsonrpc": "2.0",
1082 "id": "discover",
1083 "method": "server/discover",
1084 "params": {"_meta": modern_meta.clone()}
1085 }),
1086 )
1087 .unwrap();
1088 assert_eq!(discovered["result"]["resultType"], "complete");
1089 assert_eq!(
1090 discovered["result"]["supportedVersions"][0],
1091 super::MODERN_PROTOCOL_VERSION
1092 );
1093 assert_eq!(
1094 discovered["result"]["_meta"]["io.modelcontextprotocol/serverInfo"]["name"],
1095 "echo"
1096 );
1097
1098 let listed = dispatch(
1099 &mut server,
1100 &json!({
1101 "jsonrpc": "2.0",
1102 "id": 1,
1103 "method": "tools/list",
1104 "params": {"_meta": modern_meta.clone()}
1105 }),
1106 )
1107 .unwrap();
1108 assert_eq!(listed["result"]["resultType"], "complete");
1109
1110 let called = dispatch(
1111 &mut server,
1112 &json!({
1113 "jsonrpc": "2.0",
1114 "id": 2,
1115 "method": "tools/call",
1116 "params": {
1117 "_meta": modern_meta.clone(),
1118 "name": "echo",
1119 "arguments": {"modern": true}
1120 }
1121 }),
1122 )
1123 .unwrap();
1124 assert_eq!(called["result"]["resultType"], "complete");
1125 assert_eq!(called["result"]["structuredContent"]["modern"], true);
1126
1127 let scalar = dispatch(
1128 &mut server,
1129 &json!({
1130 "jsonrpc": "2.0",
1131 "id": "scalar",
1132 "method": "tools/call",
1133 "params": {
1134 "_meta": modern_meta,
1135 "name": "scalar",
1136 "arguments": {}
1137 }
1138 }),
1139 )
1140 .unwrap();
1141 assert_eq!(scalar["result"]["structuredContent"], 5);
1142
1143 let unsupported = dispatch(
1144 &mut server,
1145 &json!({
1146 "jsonrpc": "2.0",
1147 "id": 3,
1148 "method": "tools/list",
1149 "params": {"_meta": {
1150 "io.modelcontextprotocol/protocolVersion": "1900-01-01",
1151 "io.modelcontextprotocol/clientCapabilities": {}
1152 }}
1153 }),
1154 )
1155 .unwrap();
1156 assert_eq!(unsupported["error"]["code"], -32_022);
1157 assert_eq!(unsupported["error"]["data"]["requested"], "1900-01-01");
1158 }
1159
1160 #[test]
1161 fn serves_a_full_session_over_streams() {
1162 let mut server = Echo { calls: 0 };
1163 let input = concat!(
1164 "\u{feff}{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n",
1165 "\n",
1166 "not json\n",
1167 "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n",
1168 "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",",
1169 "\"params\":{\"name\":\"echo\",\"arguments\":{\"ok\":true}}}\n",
1170 );
1171 let mut output = Vec::new();
1172 serve_streams(&mut server, input.as_bytes(), &mut output).unwrap();
1173 let lines = String::from_utf8(output).unwrap();
1174 let lines = lines.lines().collect::<Vec<_>>();
1175 assert_eq!(lines.len(), 3, "ping, parse error, tool call");
1176
1177 let ping = blazingly_json::from_str::<Value>(lines[0]).unwrap();
1178 assert_eq!(ping["id"], 1, "BOM-prefixed first request still parses");
1179
1180 let parse_error = blazingly_json::from_str::<Value>(lines[1]).unwrap();
1181 assert_eq!(parse_error["error"]["code"], -32_700);
1182
1183 let called = blazingly_json::from_str::<Value>(lines[2]).unwrap();
1184 assert_eq!(called["result"]["structuredContent"]["ok"], true);
1185 assert_eq!(server.calls, 1);
1186 }
1187
1188 #[test]
1189 fn fast_message_path_preserves_public_dispatch_semantics() {
1190 let fixtures = [
1191 r#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#,
1192 r#"{"jsonrpc":"2.0","id":"init","method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#,
1193 r#"{"jsonrpc":"2.0","id":"future","method":"initialize","params":{"protocolVersion":"2099-01-01"}}"#,
1194 r#"{"method":"initialize","id":-2,"jsonrpc":"2.0"}"#,
1195 r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#,
1196 r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"ok":true}}}"#,
1197 r#"{"jsonrpc":"2.0","id":"modern-list","method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}"#,
1198 r#"{"jsonrpc":"2.0","id":"modern-call","method":"tools/call","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}},"name":"echo","arguments":{"modern":true}}}"#,
1199 r#"{"jsonrpc":"2.0","id":"modern-scalar","method":"tools/call","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}},"name":"scalar","arguments":{}}}"#,
1200 r#"{"jsonrpc":"2.0","id":"modern-bad","method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"1900-01-01","io.modelcontextprotocol/clientCapabilities":{}}}}"#,
1201 r#"{"params":{"arguments":[1,2],"name":"fl\u0061t"},"method":"tools/call","id":4,"jsonrpc":"2.0"}"#,
1202 r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"missing"}}"#,
1203 r#"{"jsonrpc":"2.0","id":6}"#,
1204 r#"{"jsonrpc":"2.0","id":7,"method":"resources/list"}"#,
1205 r#"{"jsonrpc":"2.0","id":8,"method":"tools/call"}"#,
1206 r#"{"jsonrpc":"2.0","id":9,"method":"tools/call","params":null}"#,
1207 r#"{"jsonrpc":"2.0","id":10,"method":false}"#,
1208 r#"{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"echo","arguments":{"text":"quote: \" slash: \\ newline: \n snowman: ☃"}}}"#,
1209 r#"{"jsonrpc":"2.0","id":1.5,"method":"ping"}"#,
1210 r#"{"jsonrpc":"2.0","id":{"legacy":true},"method":"ping"}"#,
1211 r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
1212 r#"{"jsonrpc":"1.0","method":"ping"}"#,
1213 r#"{"jsonrpc":"2.0","method":false}"#,
1214 r"[]",
1215 ];
1216
1217 for fixture in fixtures {
1218 let request = blazingly_json::from_str::<Value>(fixture).unwrap();
1219 let mut expected_server = Echo { calls: 0 };
1220 let expected = dispatch(&mut expected_server, &request);
1221
1222 let mut actual_server = Echo { calls: 0 };
1223 let mut output = Vec::new();
1224 let wrote = serve_message(&mut actual_server, fixture, &mut output).unwrap();
1225 let actual = if output.is_empty() {
1226 None
1227 } else {
1228 Some(blazingly_json::from_slice::<Value>(&output).unwrap())
1229 };
1230
1231 assert_eq!(wrote, actual.is_some(), "fixture: {fixture}");
1232 assert_eq!(actual, expected, "fixture: {fixture}");
1233 assert_eq!(actual_server.calls, expected_server.calls);
1234 }
1235 }
1236}