Skip to main content

pimalaya_cli/
mcp.rs

1//! A Model Context Protocol server over stdio: the JSON-RPC answers every
2//! server gives alike, and the tool results built from what a command
3//! prints.
4//!
5//! A server reads one JSON-RPC message per line of stdin and writes one
6//! per line of stdout, which carries protocol messages only. [`read`]
7//! answers a line itself, the protocol errors, `initialize`, `ping` and
8//! `tools/list` included, or hands the binary a checked [`ToolCall`]. The
9//! binary runs it, usually a command printing into a [`CapturePrinter`],
10//! and answers a [`ToolResult`] through [`ToolCall::respond`].
11//!
12//! A server with nothing else to wait for runs [`serve`], a blocking loop
13//! over stdin. One with background events (a listener, a poll) reads
14//! stdin on a thread with [`spawn_stdin_reader`], feeding its own
15//! channel, and answers each line with [`answer`] and [`send`]. Either way
16//! stdin is claimed ([`claim_stdin`]), so a command reading its input
17//! there is refused, and [`exit_on_failure`] reports a failure on stderr.
18//!
19//! The [`grammar`] module derives a tool's input from a clap command.
20//!
21//! Refs: <https://modelcontextprotocol.io/specification/2025-06-18>
22//!
23//! [`CapturePrinter`]: crate::printer::CapturePrinter
24//! [`claim_stdin`]: crate::session::claim_stdin
25
26pub mod grammar;
27
28use std::{
29    io::{self, BufRead, Write},
30    mem, process, str,
31    sync::mpsc::Sender,
32    thread::{self, JoinHandle},
33};
34
35use anyhow::{Context, Error, Result, anyhow};
36use serde::Serialize;
37use serde_json::{Map, Value, json};
38
39use crate::{
40    error::{EXIT_FAILURE, ErrorCode, ErrorReport, NoErrorCode, partial_outcome_of},
41    printer::CapturePrinter,
42    session::claim_stdin,
43};
44
45/// The MCP revisions the server speaks, latest first.
46///
47/// 2025-06-18 is the first carrying `structuredContent` and
48/// `outputSchema`; 2025-03-26 asks for batches, which the server refuses.
49pub const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18"];
50
51/// The JSON-RPC code of a message that is not JSON.
52pub const PARSE_ERROR: i64 = -32700;
53
54/// The JSON-RPC code of a message that is no valid request.
55pub const INVALID_REQUEST: i64 = -32600;
56
57/// The JSON-RPC code of an unknown method.
58pub const METHOD_NOT_FOUND: i64 = -32601;
59
60/// The JSON-RPC code of a request whose parameters are wrong.
61pub const INVALID_PARAMS: i64 = -32602;
62
63/// What a server tells the client at `initialize`.
64#[derive(Clone, Copy, Debug)]
65pub struct ServerInfo<'a> {
66    /// The binary name.
67    pub name: &'a str,
68    /// The binary version, usually `env!("CARGO_PKG_VERSION")`.
69    pub version: &'a str,
70    /// How to use the tools, for the client to hand its model.
71    pub instructions: Option<&'a str>,
72}
73
74/// What a line read off stdin asks of the server.
75#[derive(Debug)]
76pub enum Incoming {
77    /// The answer to write back as it is.
78    Reply(Value),
79    /// A tool call to run, then answer with [`ToolCall::respond`].
80    Call(ToolCall),
81    /// Nothing to answer: a notification or a blank line.
82    Ignore,
83}
84
85/// A `tools/call` request, checked: the tool is listed and the arguments
86/// are an object whose keys the tool declares.
87#[derive(Clone, Debug)]
88pub struct ToolCall {
89    /// The request id, to answer with.
90    pub id: Value,
91    /// The tool name.
92    pub name: String,
93    /// The tool arguments, empty when the call gave none.
94    pub arguments: Map<String, Value>,
95}
96
97impl ToolCall {
98    /// The JSON-RPC response carrying `result`.
99    pub fn respond(&self, result: ToolResult) -> Value {
100        json!({ "jsonrpc": "2.0", "id": self.id, "result": result })
101    }
102}
103
104/// The result of a tool call.
105///
106/// A failure is a result with `isError` rather than a protocol error, so
107/// the model reads it.
108#[derive(Clone, Debug, Default, Serialize)]
109#[serde(rename_all = "camelCase")]
110pub struct ToolResult {
111    /// The content items, each `{type, ...}`, a text one built by [`text`].
112    pub content: Vec<Value>,
113    /// The structured result, an object.
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub structured_content: Option<Value>,
116    /// Whether the call failed.
117    #[serde(skip_serializing_if = "is_false")]
118    pub is_error: bool,
119}
120
121impl ToolResult {
122    /// A success holding `value` as text, and as `structuredContent` when
123    /// it is an object.
124    pub fn success(value: Value) -> Self {
125        Self {
126            content: vec![text(value.to_string())],
127            structured_content: value.is_object().then_some(value),
128            is_error: false,
129        }
130    }
131
132    /// A failure holding the failure object `report` as text.
133    pub fn failure(report: Value) -> Self {
134        Self {
135            content: vec![text(report.to_string())],
136            structured_content: None,
137            is_error: true,
138        }
139    }
140
141    /// A failure holding the failure object of `err`, with the code of
142    /// its chain.
143    pub fn error<C: ErrorCode>(err: Error) -> Self {
144        Self::failure(error_object::<C>(err))
145    }
146
147    /// What a command printed into `printer`, given how it ended.
148    ///
149    /// The events come first, one text item each, then the single value
150    /// the command printed. A partial outcome keeps that result and sets
151    /// `isError`; a failure, or a count of values other than one, is a
152    /// failure object.
153    pub fn printed<C: ErrorCode>(mut printer: CapturePrinter, result: Result<()>) -> Self {
154        let partial = match result {
155            Ok(()) => false,
156            Err(err) if partial_outcome_of(&err).is_some() => true,
157            Err(err) => return Self::error::<C>(err),
158        };
159
160        let events = mem::take(&mut printer.events);
161
162        let value = match printer.into_single() {
163            Ok(value) => value,
164            Err(err) => return Self::error::<C>(err),
165        };
166
167        let mut result = Self::success(value);
168        let events = events.into_iter().map(|event| text(event.to_string()));
169        result.content.splice(0..0, events);
170        result.is_error = partial;
171        result
172    }
173}
174
175/// A line of stdin as a [`spawn_stdin_reader`] thread reads it.
176#[derive(Debug)]
177pub enum Input {
178    /// One line, its newline included, as bytes.
179    Line(Vec<u8>),
180    /// stdin closed, or failed.
181    Eof,
182}
183
184/// Answers one line read off stdin, or hands the tool call it holds to
185/// the binary.
186///
187/// `tools` are the definitions `tools/list` answers. A message that is
188/// not UTF-8 or not JSON answers -32700, one that is not a JSON object
189/// (a batch included), whose `jsonrpc` is not `"2.0"`, whose `id` is not
190/// a string or a number or that has no `method` answers -32600, an
191/// unknown method -32601. A `tools/call` whose params are not an object,
192/// whose tool is missing or not listed, or whose arguments are not an
193/// object answers -32602; an argument its tool's `inputSchema` does not
194/// declare, when it sets `additionalProperties: false`, answers a failed
195/// tool result naming the declared ones.
196pub fn read(line: &[u8], info: &ServerInfo, tools: &[Value]) -> Incoming {
197    let Ok(line) = str::from_utf8(line) else {
198        let message = "Parse error: the message is not UTF-8";
199        return Incoming::Reply(error(Value::Null, PARSE_ERROR, message));
200    };
201
202    if line.trim().is_empty() {
203        return Incoming::Ignore;
204    }
205
206    let message = match serde_json::from_str(line) {
207        Ok(Value::Object(message)) => message,
208        Ok(_) => {
209            let message =
210                "Invalid request: a message is one JSON object, batches are not supported";
211            return Incoming::Reply(error(Value::Null, INVALID_REQUEST, message));
212        }
213        Err(err) => {
214            let message = format!("Parse error: {err}");
215            return Incoming::Reply(error(Value::Null, PARSE_ERROR, message));
216        }
217    };
218
219    let id = match message.get("id") {
220        None => None,
221        Some(id @ (Value::String(_) | Value::Number(_))) => Some(id.clone()),
222        Some(_) => {
223            let message = "Invalid request: the id is not a string or a number";
224            return Incoming::Reply(error(Value::Null, INVALID_REQUEST, message));
225        }
226    };
227
228    let invalid = |message: &str| {
229        let id = id.clone().unwrap_or(Value::Null);
230        Incoming::Reply(error(id, INVALID_REQUEST, message))
231    };
232
233    if message.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
234        return invalid("Invalid request: jsonrpc is not \"2.0\"");
235    }
236
237    // A response is invalid too: the server sends no request.
238    let Some(method) = message.get("method").and_then(Value::as_str) else {
239        return invalid("Invalid request: the method is missing or not a string");
240    };
241
242    let Some(id) = id else {
243        return Incoming::Ignore;
244    };
245
246    let params = message.get("params");
247
248    let result = match method {
249        "initialize" => initialize(info, params),
250        "ping" => json!({}),
251        "tools/list" => json!({ "tools": tools }),
252        "tools/call" => return call(id, params, tools),
253        method => {
254            let message = format!("Method not found: {method}");
255            return Incoming::Reply(error(id, METHOD_NOT_FOUND, message));
256        }
257    };
258
259    Incoming::Reply(json!({ "jsonrpc": "2.0", "id": id, "result": result }))
260}
261
262/// Answers one line read off stdin, running the tool call it holds with
263/// `run`; `None` when nothing is to be answered.
264pub fn answer(
265    line: &[u8],
266    info: &ServerInfo,
267    tools: &[Value],
268    run: impl FnOnce(&ToolCall) -> ToolResult,
269) -> Option<Value> {
270    match read(line, info, tools) {
271        Incoming::Reply(reply) => Some(reply),
272        Incoming::Call(call) => Some(call.respond(run(&call))),
273        Incoming::Ignore => None,
274    }
275}
276
277/// Writes one message as one line, flushed.
278pub fn send(output: &mut impl Write, message: &Value) -> Result<()> {
279    serde_json::to_writer(&mut *output, message).context("Cannot write a message to stdout")?;
280    writeln!(output)?;
281    output.flush()?;
282    Ok(())
283}
284
285/// Serves the requests of stdin until EOF, answering each on stdout,
286/// each tool call run with `run`.
287///
288/// It claims stdin first.
289pub fn serve(
290    info: &ServerInfo,
291    tools: &[Value],
292    run: impl FnMut(&ToolCall) -> ToolResult,
293) -> Result<()> {
294    claim_stdin();
295    serve_on(&mut io::stdin().lock(), &mut io::stdout(), info, tools, run)
296}
297
298/// Reads stdin on a thread of its own, sending each line, then EOF, to
299/// `events` as `wrap` turns them into the binary's event type.
300///
301/// It claims stdin first. The thread ends at EOF, on a read failure, or
302/// once nobody receives.
303pub fn spawn_stdin_reader<T: Send + 'static>(
304    events: Sender<T>,
305    wrap: impl Fn(Input) -> T + Send + 'static,
306) -> JoinHandle<()> {
307    claim_stdin();
308    thread::spawn(move || read_lines(&mut io::stdin().lock(), &events, wrap))
309}
310
311/// Unwraps the result of a server, or prints its failure as text on
312/// stderr and exits with status 1, or with the status of a partial
313/// outcome.
314///
315/// stdout carries protocol messages only, so a server failing before its
316/// loop (resolving its account) or in it reports here rather than
317/// through the printer.
318pub fn exit_on_failure<C: ErrorCode, T>(result: Result<T>) -> T {
319    match result {
320        Ok(value) => value,
321        Err(err) => {
322            if let Some(outcome) = partial_outcome_of(&err) {
323                process::exit(outcome.status());
324            }
325
326            eprint!("{}", ErrorReport::<C>::from(err));
327            process::exit(EXIT_FAILURE);
328        }
329    }
330}
331
332/// `schema` as a tool's `outputSchema`, when its root is typed `object`.
333///
334/// MCP takes an object root only: a reference, an `anyOf` or a `oneOf`
335/// root is refused even when every alternative is an object, which the
336/// registry's `non_object_roots` accepts as the shape of a printed value.
337pub fn tool_output_schema(schema: &Value) -> Option<&Value> {
338    (schema["type"] == "object").then_some(schema)
339}
340
341/// The failure object of `err`, with the code of its chain, as a failed
342/// tool call holds it and as a binary keeps it to report later.
343pub fn error_object<C: ErrorCode>(err: Error) -> Value {
344    serde_json::to_value(ErrorReport::<C>::from(err))
345        .unwrap_or_else(|err| Value::from(err.to_string()))
346}
347
348/// The text content item `{"type": "text", "text": text}` of a tool
349/// result.
350pub fn text(text: impl Into<String>) -> Value {
351    json!({ "type": "text", "text": text.into() })
352}
353
354/// The message refusing an argument `key` that `owner` does not declare,
355/// naming the `known` ones.
356pub(crate) fn unknown_argument<'a>(
357    key: &str,
358    owner: &str,
359    known: impl IntoIterator<Item = &'a str>,
360) -> Error {
361    let known: Vec<String> = known.into_iter().map(|name| format!("`{name}`")).collect();
362
363    if known.is_empty() {
364        anyhow!("Unknown argument `{key}`, {owner} takes none")
365    } else {
366        anyhow!(
367            "Unknown argument `{key}`, {owner} takes {}",
368            known.join(", ")
369        )
370    }
371}
372
373/// Serves the requests of `input` until EOF, answering each on `output`.
374fn serve_on(
375    input: &mut impl BufRead,
376    output: &mut impl Write,
377    info: &ServerInfo,
378    tools: &[Value],
379    mut run: impl FnMut(&ToolCall) -> ToolResult,
380) -> Result<()> {
381    let mut line = Vec::new();
382
383    loop {
384        line.clear();
385
386        let read = input.read_until(b'\n', &mut line);
387        if read.context("Cannot read a message from stdin")? == 0 {
388            return Ok(());
389        }
390
391        if let Some(response) = answer(&line, info, tools, &mut run) {
392            send(output, &response)?;
393        }
394    }
395}
396
397/// Sends each line of `input`, then EOF, to `events`.
398fn read_lines<T>(input: &mut impl BufRead, events: &Sender<T>, wrap: impl Fn(Input) -> T) {
399    loop {
400        let mut line = Vec::new();
401
402        match input.read_until(b'\n', &mut line) {
403            Ok(0) | Err(_) => break,
404            Ok(_) => {
405                if events.send(wrap(Input::Line(line))).is_err() {
406                    return;
407                }
408            }
409        }
410    }
411
412    let _ = events.send(wrap(Input::Eof));
413}
414
415/// The answer to `initialize`: the client's version when the server
416/// speaks it, its latest otherwise.
417fn initialize(info: &ServerInfo, params: Option<&Value>) -> Value {
418    let asked = params
419        .and_then(|params| params.get("protocolVersion"))
420        .and_then(Value::as_str);
421
422    let version = asked
423        .filter(|asked| PROTOCOL_VERSIONS.contains(asked))
424        .unwrap_or(PROTOCOL_VERSIONS[0]);
425
426    let mut result = json!({
427        "protocolVersion": version,
428        "capabilities": { "tools": { "listChanged": false } },
429        "serverInfo": { "name": info.name, "version": info.version },
430    });
431
432    if let Some(instructions) = info.instructions {
433        result["instructions"] = Value::from(instructions);
434    }
435
436    result
437}
438
439/// Checks a `tools/call` request against the listed `tools`.
440fn call(id: Value, params: Option<&Value>, tools: &[Value]) -> Incoming {
441    let refuse = |id, message: String| Incoming::Reply(error(id, INVALID_PARAMS, message));
442
443    let Some(Value::Object(params)) = params else {
444        return refuse(id, String::from("Invalid params: not an object"));
445    };
446
447    let Some(name) = params.get("name").and_then(Value::as_str) else {
448        return refuse(id, String::from("Missing tool name"));
449    };
450
451    let Some(tool) = tools.iter().find(|tool| tool["name"] == name) else {
452        return refuse(id, format!("Unknown tool: {name}"));
453    };
454
455    let arguments = match params.get("arguments") {
456        None | Some(Value::Null) => Map::new(),
457        Some(Value::Object(arguments)) => arguments.clone(),
458        Some(_) => return refuse(id, String::from("Arguments must be an object")),
459    };
460
461    let schema = &tool["inputSchema"];
462
463    if schema["additionalProperties"] == false {
464        let properties = schema["properties"].as_object();
465        let declared = |key: &String| properties.is_some_and(|known| known.contains_key(key));
466
467        if let Some(key) = arguments.keys().find(|key| !declared(key)) {
468            let known = properties.into_iter().flat_map(|known| known.keys());
469            let err = unknown_argument(key, name, known.map(String::as_str));
470            let result = ToolResult::error::<NoErrorCode>(err);
471            return Incoming::Reply(json!({ "jsonrpc": "2.0", "id": id, "result": result }));
472        }
473    }
474
475    Incoming::Call(ToolCall {
476        id,
477        name: name.to_owned(),
478        arguments,
479    })
480}
481
482/// A JSON-RPC error response.
483fn error(id: Value, code: i64, message: impl Into<String>) -> Value {
484    json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message.into() } })
485}
486
487fn is_false(value: &bool) -> bool {
488    !value
489}
490
491#[cfg(test)]
492mod tests {
493    use std::{fmt, sync::mpsc};
494
495    use anyhow::{Error, anyhow};
496    use schemars::JsonSchema;
497    use serde::Serialize;
498    use serde_json::{Value, json};
499
500    use crate::{
501        clap::commands::json_schema::output_schema,
502        error::PartialOutcome,
503        mcp::*,
504        printer::{CapturePrinter, Printer},
505    };
506
507    const INFO: ServerInfo = ServerInfo {
508        name: "app",
509        version: "1.2.3",
510        instructions: None,
511    };
512
513    fn tools() -> Vec<Value> {
514        vec![
515            json!({
516                "name": "item_get",
517                "inputSchema": {
518                    "type": "object",
519                    "properties": { "id": { "type": "string" }, "full": { "type": "boolean" } },
520                    "required": ["id"],
521                    "additionalProperties": false,
522                },
523            }),
524            json!({
525                "name": "item_list",
526                "inputSchema": { "type": "object", "properties": {}, "additionalProperties": false },
527            }),
528            json!({ "name": "open", "inputSchema": { "type": "object" } }),
529        ]
530    }
531
532    fn reply(line: &str) -> Value {
533        match read(line.as_bytes(), &INFO, &tools()) {
534            Incoming::Reply(reply) => reply,
535            incoming => panic!("not a reply: {incoming:?}"),
536        }
537    }
538
539    fn code(reply: &Value) -> i64 {
540        reply["error"]["code"].as_i64().unwrap_or_default()
541    }
542
543    #[test]
544    fn a_message_that_is_not_json_is_a_parse_error() {
545        let reply = reply("{\"jsonrpc\": ");
546        assert_eq!(code(&reply), PARSE_ERROR, "{reply}");
547        assert_eq!(reply["id"], Value::Null);
548        assert_eq!(reply["jsonrpc"], "2.0");
549    }
550
551    #[test]
552    fn bytes_that_are_not_utf8_are_a_parse_error() {
553        let Incoming::Reply(reply) = read(b"{\"id\": \"\xff\"}\n", &INFO, &[]) else {
554            panic!("no reply");
555        };
556
557        assert_eq!(code(&reply), PARSE_ERROR, "{reply}");
558        assert_eq!(reply["id"], Value::Null);
559    }
560
561    #[test]
562    fn a_batch_or_a_scalar_is_an_invalid_request() {
563        for line in [
564            r#"[{"jsonrpc":"2.0","id":1,"method":"ping"}]"#,
565            "3",
566            "\"ping\"",
567            "null",
568        ] {
569            let reply = reply(line);
570            assert_eq!(code(&reply), INVALID_REQUEST, "{line}: {reply}");
571            assert_eq!(reply["id"], Value::Null, "{line}");
572        }
573    }
574
575    #[test]
576    fn an_invalid_request_keeps_its_id_when_valid() {
577        let wrong_version = reply(r#"{"jsonrpc":"1.0","id":7,"method":"ping"}"#);
578        assert_eq!(code(&wrong_version), INVALID_REQUEST);
579        assert_eq!(wrong_version["id"], 7);
580
581        let no_version = reply(r#"{"id":"a","method":"ping"}"#);
582        assert_eq!(code(&no_version), INVALID_REQUEST);
583        assert_eq!(no_version["id"], "a");
584
585        let response = reply(r#"{"jsonrpc":"2.0","id":8,"result":{}}"#);
586        assert_eq!(code(&response), INVALID_REQUEST);
587        assert_eq!(response["id"], 8);
588
589        let bad_id = reply(r#"{"jsonrpc":"2.0","id":{},"method":"ping"}"#);
590        assert_eq!(code(&bad_id), INVALID_REQUEST);
591        assert_eq!(bad_id["id"], Value::Null);
592    }
593
594    #[test]
595    fn a_notification_or_a_blank_line_gets_no_answer() {
596        for line in [
597            &br#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#[..],
598            br#"{"jsonrpc":"2.0","method":"unknown"}"#,
599            b"  \r\n",
600        ] {
601            assert!(matches!(read(line, &INFO, &[]), Incoming::Ignore));
602        }
603    }
604
605    #[test]
606    fn an_unknown_method_is_not_found() {
607        let reply = reply(r#"{"jsonrpc":"2.0","id":1,"method":"resources/list"}"#);
608        assert_eq!(code(&reply), METHOD_NOT_FOUND, "{reply}");
609        assert_eq!(reply["id"], 1);
610    }
611
612    #[test]
613    fn ping_answers_an_empty_object() {
614        let reply = reply(r#"{"jsonrpc":"2.0","id":"p","method":"ping"}"#);
615        assert_eq!(reply, json!({ "jsonrpc": "2.0", "id": "p", "result": {} }));
616    }
617
618    #[test]
619    fn initialize_echoes_a_supported_version() {
620        let line = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#;
621        let reply = reply(line);
622
623        assert_eq!(
624            reply["result"],
625            json!({
626                "protocolVersion": "2025-06-18",
627                "capabilities": { "tools": { "listChanged": false } },
628                "serverInfo": { "name": "app", "version": "1.2.3" },
629            })
630        );
631    }
632
633    #[test]
634    fn initialize_answers_the_latest_version_to_an_unsupported_one() {
635        let info = ServerInfo {
636            instructions: Some("Call item_list first."),
637            ..INFO
638        };
639
640        for params in [r#"{"protocolVersion":"2099-01-01"}"#, "{}", "null"] {
641            let line =
642                format!(r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{params}}}"#);
643            let Incoming::Reply(reply) = read(line.as_bytes(), &info, &[]) else {
644                panic!("no reply");
645            };
646
647            assert_eq!(reply["result"]["protocolVersion"], PROTOCOL_VERSIONS[0]);
648            assert_eq!(reply["result"]["instructions"], "Call item_list first.");
649        }
650    }
651
652    #[test]
653    fn tools_list_answers_the_tools_given() {
654        let reply = reply(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#);
655        assert_eq!(reply["result"]["tools"], Value::from(tools()));
656    }
657
658    #[test]
659    fn a_call_with_bad_params_is_refused() {
660        for params in [
661            "",
662            r#","params":3"#,
663            r#","params":{}"#,
664            r#","params":{"name":"item_put"}"#,
665            r#","params":{"name":"item_get","arguments":[]}"#,
666        ] {
667            let line = format!(r#"{{"jsonrpc":"2.0","id":4,"method":"tools/call"{params}}}"#);
668            let reply = reply(&line);
669            assert_eq!(code(&reply), INVALID_PARAMS, "{line}: {reply}");
670            assert_eq!(reply["id"], 4);
671        }
672    }
673
674    #[test]
675    fn a_checked_call_is_handed_over() {
676        let line = r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"item_get","arguments":{"id":"x"}}}"#;
677        let Incoming::Call(call) = read(line.as_bytes(), &INFO, &tools()) else {
678            panic!("no call");
679        };
680
681        assert_eq!(call.id, 5);
682        assert_eq!(call.name, "item_get");
683        assert_eq!(Value::from(call.arguments.clone()), json!({ "id": "x" }));
684
685        let line = r#"{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"open","arguments":{"any":1}}}"#;
686        assert!(matches!(
687            read(line.as_bytes(), &INFO, &tools()),
688            Incoming::Call(_)
689        ));
690
691        let line = r#"{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"item_list","arguments":null}}"#;
692        let Incoming::Call(call) = read(line.as_bytes(), &INFO, &tools()) else {
693            panic!("no call");
694        };
695        assert!(call.arguments.is_empty());
696    }
697
698    #[test]
699    fn an_undeclared_argument_is_a_failed_result_naming_the_declared_ones() {
700        let line = r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"item_get","arguments":{"di":"x"}}}"#;
701        let unknown = reply(line);
702        let result = &unknown["result"];
703
704        assert_eq!(unknown["id"], 5);
705        assert_eq!(result["isError"], true, "{unknown}");
706
707        let report: Value =
708            serde_json::from_str(result["content"][0]["text"].as_str().unwrap()).unwrap();
709        assert_eq!(
710            report["error"],
711            "Unknown argument `di`, item_get takes `full`, `id`"
712        );
713
714        let line = r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"item_list","arguments":{"x":1}}}"#;
715        let none = reply(line);
716        assert!(none.to_string().contains("item_list takes none"), "{none}");
717    }
718
719    #[derive(Serialize, JsonSchema)]
720    struct Item {
721        id: u32,
722    }
723
724    impl fmt::Display for Item {
725        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
726            writeln!(f, "{}", self.id)
727        }
728    }
729
730    fn printed(values: &[u32], events: &[&str], result: Result<(), Error>) -> Value {
731        let mut printer = CapturePrinter::default();
732
733        for event in events {
734            printer.event(json!({ "event": event })).unwrap();
735        }
736
737        for id in values {
738            printer.out(Item { id: *id }).unwrap();
739        }
740
741        serde_json::to_value(ToolResult::printed::<NoErrorCode>(printer, result)).unwrap()
742    }
743
744    #[test]
745    fn a_printed_value_is_structured_after_its_events() {
746        assert_eq!(
747            printed(&[1], &["started"], Ok(())),
748            json!({
749                "content": [
750                    { "type": "text", "text": r#"{"event":"started"}"# },
751                    { "type": "text", "text": r#"{"id":1}"# },
752                ],
753                "structuredContent": { "id": 1 },
754            })
755        );
756    }
757
758    #[test]
759    fn a_partial_outcome_keeps_its_result_as_an_error() {
760        let result = printed(&[1], &[], Err(PartialOutcome::default().into()));
761
762        assert_eq!(result["structuredContent"], json!({ "id": 1 }));
763        assert_eq!(result["isError"], true);
764    }
765
766    #[test]
767    fn a_failure_or_a_wrong_count_is_a_failure_object() {
768        for (values, outcome) in [
769            (&[][..], Ok(())),
770            (&[1, 2][..], Ok(())),
771            (&[1][..], Err(anyhow!("Boom"))),
772        ] {
773            let expected = match &outcome {
774                Ok(()) => format!("The command printed {} values, one expected", values.len()),
775                Err(err) => err.to_string(),
776            };
777
778            let result = printed(values, &["started"], outcome);
779            assert_eq!(result["isError"], true, "{result}");
780            assert!(result.get("structuredContent").is_none(), "{result}");
781            assert_eq!(result["content"].as_array().unwrap().len(), 1, "{result}");
782
783            let text = result["content"][0]["text"].as_str().unwrap();
784            let report: Value = serde_json::from_str(text).unwrap();
785            assert_eq!(report["error"], expected);
786            assert_eq!(report["code"], Value::Null);
787        }
788    }
789
790    #[test]
791    fn a_value_that_is_not_an_object_is_text_alone() {
792        let result = serde_json::to_value(ToolResult::success(json!([1]))).unwrap();
793        assert_eq!(
794            result,
795            json!({ "content": [{ "type": "text", "text": "[1]" }] })
796        );
797    }
798
799    #[test]
800    fn an_output_schema_needs_an_object_root() {
801        let object = json!({ "type": "object", "properties": {} });
802        assert_eq!(tool_output_schema(&object), Some(&object));
803
804        for schema in [
805            json!({ "$ref": "#/$defs/A", "$defs": { "A": { "type": "object" } } }),
806            json!({ "anyOf": [{ "type": "object" }, { "type": "object" }] }),
807            json!({ "oneOf": [{ "type": "object" }] }),
808            json!({ "type": "array" }),
809            json!({ "type": ["object", "null"] }),
810        ] {
811            assert_eq!(tool_output_schema(&schema), None, "{schema}");
812        }
813
814        let schema = output_schema::<Item>();
815        assert!(tool_output_schema(&schema).is_some(), "{schema}");
816    }
817
818    #[test]
819    fn the_loop_answers_each_line_and_runs_each_call() {
820        let input = concat!(
821            r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#,
822            "\n\n",
823            r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
824            "\n",
825            r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"item_get","arguments":{"id":"x"}}}"#,
826            "\n\u{0}\n",
827            r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"item_list"}}"#,
828        );
829
830        let mut output = Vec::new();
831        let mut calls = Vec::new();
832
833        serve_on(
834            &mut input.as_bytes(),
835            &mut output,
836            &INFO,
837            &tools(),
838            |call| {
839                calls.push(call.name.clone());
840                ToolResult::success(json!({ "called": call.name }))
841            },
842        )
843        .unwrap();
844
845        let output = String::from_utf8(output).unwrap();
846        let replies: Vec<Value> = output
847            .lines()
848            .map(|line| serde_json::from_str(line).unwrap())
849            .collect();
850
851        assert_eq!(calls, ["item_get", "item_list"]);
852        assert_eq!(replies.len(), 4, "{output}");
853        assert_eq!(replies[0]["id"], 1);
854        assert_eq!(
855            replies[1]["result"]["structuredContent"]["called"],
856            "item_get"
857        );
858        assert_eq!(code(&replies[2]), PARSE_ERROR);
859        assert_eq!(replies[3]["id"], 3);
860    }
861
862    #[test]
863    fn the_reader_sends_each_line_then_eof() {
864        let (events, inbox) = mpsc::channel();
865        read_lines(&mut &b"a\n\xff\nb"[..], &events, |input| input);
866        drop(events);
867
868        let lines: Vec<Option<Vec<u8>>> = inbox
869            .iter()
870            .map(|input| match input {
871                Input::Line(line) => Some(line),
872                Input::Eof => None,
873            })
874            .collect();
875
876        assert_eq!(
877            lines,
878            [
879                Some(b"a\n".to_vec()),
880                Some(b"\xff\n".to_vec()),
881                Some(b"b".to_vec()),
882                None
883            ]
884        );
885    }
886
887    #[test]
888    fn a_response_carries_the_call_id() {
889        let call = ToolCall {
890            id: json!("c1"),
891            name: String::from("item_get"),
892            arguments: Map::new(),
893        };
894
895        let response = call.respond(ToolResult::success(json!({ "id": 1 })));
896        assert_eq!(response["jsonrpc"], "2.0");
897        assert_eq!(response["id"], "c1");
898        assert_eq!(response["result"]["structuredContent"], json!({ "id": 1 }));
899    }
900}