From 3e82d1719cb0c6a5e0e4978a73d6893072c2ce17 Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:45:52 +0100 Subject: [PATCH] craft-mcp-server: options for apps that report argument errors as tool results (#2061) * craft-mcp-server: options for apps that report argument errors as tool results (#778) Add `Options` (default = today's behaviour) and `Server::with_options`: - `website_url`: sent as `serverInfo.websiteUrl` at `initialize`. - `tool_errors_as_results`: a `tools/call` whose arguments fail the schema check, or whose tool is unknown, returns a tool result with `isError: true` and the message as text, not -32602. - `strict_request_ids`: a request id that is not a string or number gets -32600 with a null id. `Info` is unchanged, so existing struct-literal callers still compile. Tests cover each option on and off, and hostile input with all options on. Co-Authored-By: Claude Opus 5.5 * craft-mcp-server: strict request ids also apply to the missing-method error (#778) With strict_request_ids, a message without `method` echoed an object, array or bool id in its -32600 reply. It now answers with a null id for any id that is not a string or number, as the later strict check does. Valid ids, absent ids and incoming responses behave as before. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/mcp-server/src/lib.rs | 2 +- crates/mcp-server/src/server.rs | 45 +++++++++-- crates/mcp-server/src/tests.rs | 131 +++++++++++++++++++++++++++++++- 3 files changed, 171 insertions(+), 7 deletions(-) diff --git a/crates/mcp-server/src/lib.rs b/crates/mcp-server/src/lib.rs index 17e6827c4..66568fc05 100644 --- a/crates/mcp-server/src/lib.rs +++ b/crates/mcp-server/src/lib.rs @@ -15,7 +15,7 @@ mod server; pub use content::{Contents, base64, image_result, text_result}; pub use schema::{Effect, check_arguments, object, string, tool}; -pub use server::{Incoming, Info, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, read_message, response}; +pub use server::{Incoming, Info, Options, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, read_message, response}; #[cfg(test)] mod tests; diff --git a/crates/mcp-server/src/server.rs b/crates/mcp-server/src/server.rs index b7ed05027..e0d064da5 100644 --- a/crates/mcp-server/src/server.rs +++ b/crates/mcp-server/src/server.rs @@ -4,7 +4,7 @@ use std::io::{BufRead, Write}; use serde_json::{Value, json}; -use crate::content::Contents; +use crate::content::{Contents, text_result}; use crate::schema::{check_arguments, check_prompt_arguments}; /// The newest protocol revision we speak; offered when the client asks for one we don't know. @@ -88,9 +88,25 @@ pub struct Info { pub max_line: usize, } +/// Opt-in behaviour for apps with their own conventions; `Options::default()` is what [`Server::new`] +/// does. Set with [`Server::with_options`]. +#[derive(Clone, Debug, Default)] +pub struct Options { + /// Sent as `serverInfo.websiteUrl` at `initialize` (MCP 2025-06-18) when set. + pub website_url: Option, + /// Report a `tools/call` whose arguments fail the check against the tool's schema, or whose + /// tool is unknown, as a tool result with `isError: true` and the message as text, not as a + /// JSON-RPC -32602 error. For apps whose clients read every tool failure from the result. + pub tool_errors_as_results: bool, + /// Refuse a request whose `id` is neither a string nor a number (JSON-RPC 2.0) with -32600 and + /// a null id, instead of echoing the id back. + pub strict_request_ids: bool, +} + /// An MCP server over the app's [`Tools`]. pub struct Server { info: Info, + options: Options, tools: T, initialized: bool, } @@ -157,7 +173,13 @@ pub fn response(id: Value, result: Value) -> Value { impl Server { pub fn new(info: Info, tools: T) -> Self { - Self { info, tools, initialized: false } + Self { info, options: Options::default(), tools, initialized: false } + } + /// This server with `options` ([`Options`]) in place of the defaults. + #[must_use] + pub fn with_options(mut self, options: Options) -> Self { + self.options = options; + self } pub fn tools(&mut self) -> &mut T { &mut self.tools @@ -215,7 +237,11 @@ impl Server { if o.contains_key("result") || o.contains_key("error") { return None; } - return Some(error(id.unwrap_or(Value::Null), INVALID_REQUEST, "missing `method`")); + let echoed = match id { + Some(id) if !self.options.strict_request_ids || id.is_string() || id.is_number() => id, + _ => Value::Null, + }; + return Some(error(echoed, INVALID_REQUEST, "missing `method`")); }; let params = o.get("params").cloned().unwrap_or(Value::Null); let Some(id) = id else { @@ -224,6 +250,9 @@ impl Server { } return None; }; + if self.options.strict_request_ids && !(id.is_string() || id.is_number()) { + return Some(error(Value::Null, INVALID_REQUEST, "`id` must be a string or number")); + } Some(match self.request(method, ¶ms) { Ok(r) => response(id, r), Err((code, m)) => error(id, code, m), @@ -236,10 +265,14 @@ impl Server { let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL_VERSION); let version = if SUPPORTED_VERSIONS.contains(&asked) { asked } else { PROTOCOL_VERSION }; let Info { name, title, version: server_version, .. } = self.info; + let mut server_info = json!({"name": name, "title": title, "version": server_version}); + if let Some(url) = &self.options.website_url { + server_info["websiteUrl"] = json!(url); + } Ok(json!({ "protocolVersion": version, "capabilities": self.capabilities(), - "serverInfo": {"name": name, "title": title, "version": server_version}, + "serverInfo": server_info, "instructions": self.tools.instructions(), })) } @@ -251,7 +284,9 @@ impl Server { None | Some(Value::Null) => json!({}), Some(a) => a.clone(), }; - check_arguments(&self.tools.list(), name, &args).map_err(|e| (INVALID_PARAMS, e))?; + if let Err(e) = check_arguments(&self.tools.list(), name, &args) { + return if self.options.tool_errors_as_results { Ok(text_result(e, true)) } else { Err((INVALID_PARAMS, e)) }; + } Ok(self.tools.call(name, &args)) } "resources/list" => Ok(json!({"resources": self.tools.resources()})), diff --git a/crates/mcp-server/src/tests.rs b/crates/mcp-server/src/tests.rs index b687ee2e8..3f8f8d315 100644 --- a/crates/mcp-server/src/tests.rs +++ b/crates/mcp-server/src/tests.rs @@ -1,7 +1,8 @@ use serde_json::{Value, json}; use crate::{ - Contents, Effect, Info, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, check_arguments, object, string, text_result, tool, + Contents, Effect, Info, Options, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, check_arguments, object, string, text_result, + tool, }; /// One app's tools: `echo` and `level`, nothing behind them (no engine, no design). `log` records @@ -366,3 +367,131 @@ fn every_call_runs_right_after_its_listing() { reply(&mut s, &json!([call("level", json!({})), call("echo", json!({"text": "b"}))])); assert_eq!(s.tools().log, ["list", "list", "call echo", "list", "list", "call level", "list", "call echo"]); } + +fn with(options: Options) -> Server { + Server::new(info(), Echo::default()).with_options(options) +} + +fn call_msg(id: u64, name: &str, args: Value) -> Value { + json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": name, "arguments": args}}) +} + +/// `websiteUrl` is sent only when set. +#[test] +fn website_url_is_sent_only_when_set() { + let init = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}); + let off = reply(&mut with(Options::default()), &init).unwrap(); + assert!(off["result"]["serverInfo"].get("websiteUrl").is_none(), "{off}"); + let on = reply(&mut with(Options { website_url: Some("https://example.org/echo".into()), ..Options::default() }), &init).unwrap(); + assert_eq!(on["result"]["serverInfo"]["websiteUrl"], "https://example.org/echo"); + assert_eq!(on["result"]["serverInfo"]["name"], "echo"); +} + +/// With `tool_errors_as_results`, argument failures and unknown tools are `isError` results that +/// carry the message and never run the tool; other errors stay JSON-RPC errors. +#[test] +fn tool_errors_as_results_replaces_invalid_params() { + let mut s = with(Options { tool_errors_as_results: true, ..Options::default() }); + let bad = [ + call_msg(1, "echo", json!({})), + call_msg(2, "echo", json!({"text": 3})), + call_msg(3, "echo", json!({"text": "a", "loud": true})), + call_msg(4, "shout", json!({})), + call_msg(5, "echo", json!([])), + call_msg(6, "echo", json!("text")), + call_msg(7, "echo", json!(7)), + ]; + for msg in &bad { + let r = reply(&mut s, msg).unwrap(); + assert!(r.get("error").is_none(), "{r}"); + assert_eq!(r["result"]["isError"], true, "{r}"); + assert!(r["result"]["content"][0]["text"].as_str().is_some_and(|t| !t.is_empty()), "{r}"); + } + let r = reply(&mut s, &bad[0]).unwrap(); + assert_eq!(r["result"]["content"][0]["text"], "echo: missing required argument `text`"); + assert!(s.tools().calls.is_empty()); + let ok = reply(&mut s, &call_msg(8, "echo", json!({"text": "hi"}))).unwrap(); + assert_eq!(ok["result"], json!({"content": [{"type": "text", "text": "hi"}]})); + let nomethod = reply(&mut s, &json!({"jsonrpc": "2.0", "id": 9, "method": "nope"})).unwrap(); + assert_eq!(nomethod["error"]["code"], -32601); + let noname = reply(&mut s, &json!({"jsonrpc": "2.0", "id": 10, "method": "tools/call", "params": {}})).unwrap(); + assert_eq!(noname["error"]["code"], -32602); + // Unchanged with the option off. + let mut off = with(Options::default()); + for msg in &bad { + assert_eq!(reply(&mut off, msg).unwrap()["error"]["code"], -32602); + } +} + +/// With `strict_request_ids`, an id that is not a string or number is -32600 with a null id; the +/// tool never runs. Off, such ids are echoed as before. Notifications have no id and are unaffected. +#[test] +fn strict_request_ids_refuse_other_id_types() { + let odd = [json!(null), json!(true), json!({"a": 1}), json!([1])]; + let mut on = with(Options { strict_request_ids: true, ..Options::default() }); + let mut off = with(Options::default()); + for id in &odd { + let msg = json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": "echo", "arguments": {"text": "x"}}}); + let r = reply(&mut on, &msg).unwrap(); + assert_eq!(r["error"]["code"], -32600, "{id}: {r}"); + assert_eq!(r["id"], Value::Null); + let r = reply(&mut off, &json!({"jsonrpc": "2.0", "id": id, "method": "ping"})).unwrap(); + assert_eq!(r["id"], *id); + assert_eq!(r["result"], json!({})); + } + assert!(on.tools().calls.is_empty()); + for id in [json!("a"), json!(1), json!(1.5), json!(-3)] { + let r = reply(&mut on, &json!({"jsonrpc": "2.0", "id": id, "method": "ping"})).unwrap(); + assert_eq!(r["result"], json!({}), "{id}"); + } + assert!(reply(&mut on, ¬ification()).is_none()); +} + +/// The missing-`method` error follows the same id rule: strict mode echoes only string and number +/// ids and answers with a null id for the rest; off, ids are echoed as before. +#[test] +fn strict_request_ids_apply_to_the_missing_method_error() { + let mut on = with(Options { strict_request_ids: true, ..Options::default() }); + let mut off = with(Options::default()); + for id in [json!(true), json!({"a": 1}), json!([1])] { + let msg = json!({"jsonrpc": "2.0", "id": id}); + let r = reply(&mut on, &msg).unwrap(); + assert_eq!((r["error"]["code"].clone(), r["id"].clone()), (json!(-32600), Value::Null), "{id}"); + assert_eq!(reply(&mut off, &msg).unwrap()["id"], id); + } + for id in [json!("a"), json!(7)] { + assert_eq!(reply(&mut on, &json!({"jsonrpc": "2.0", "id": id})).unwrap()["id"], id); + } + assert_eq!(reply(&mut on, &json!({"jsonrpc": "2.0"})).unwrap()["id"], Value::Null); +} + +/// Hostile input with every option on: oversized and non-UTF-8 lines, odd ids and wrongly typed +/// arguments are answered and serving goes on, and nothing panics. +#[test] +fn every_option_on_survives_hostile_input() { + let mut input = vec![b'x'; (1 << 16) + 10]; + input.push(b'\n'); + input.extend_from_slice(b"\xff\xfe\n"); + for id in ["null", "true", "{}", "[]", "\"s\"", "1e999"] { + input.extend_from_slice( + format!( + "{{\"jsonrpc\":\"2.0\",\"id\":{id},\"method\":\"tools/call\",\"params\":{{\"name\":\"echo\",\"arguments\":{{\"text\":{id}}}}}}}\n" + ) + .as_bytes(), + ); + } + for args in ["null", "1", "\"a\"", "[]", "{\"text\":[1]}", "{\"text\":{}}"] { + input.extend_from_slice( + format!("{{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{{\"name\":\"level\",\"arguments\":{args}}}}}\n").as_bytes(), + ); + } + input.extend_from_slice(json!({"jsonrpc": "2.0", "id": 9, "method": "ping"}).to_string().as_bytes()); + let mut output = Vec::new(); + let options = Options { website_url: Some("https://example.org".into()), tool_errors_as_results: true, strict_request_ids: true }; + with(options).serve(std::io::Cursor::new(input), &mut output).unwrap(); + let replies: Vec = String::from_utf8(output).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(replies.len(), 2 + 6 + 6 + 1, "{replies:?}"); + assert_eq!(replies[0]["error"]["code"], -32600); + assert_eq!(replies[1]["error"]["code"], -32700); + assert_eq!(replies.last().map(|r| &r["result"]), Some(&json!({}))); +}