diff --git a/Cargo.lock b/Cargo.lock index 480e000e5..13362ace1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2145,6 +2145,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-mcp-server" +version = "0.1.0" +dependencies = [ + "proptest", + "serde_json", +] + [[package]] name = "craft-media" version = "0.1.0" diff --git a/crates/mcp-server/Cargo.toml b/crates/mcp-server/Cargo.toml new file mode 100644 index 000000000..9b034c7cc --- /dev/null +++ b/crates/mcp-server/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-mcp-server" +description = "MCP server machinery any app may share: JSON-RPC 2.0 over stdio, the MCP lifecycle, tool and resource methods, tool schemas and argument checks, image results" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +serde_json = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/mcp-server/src/content.rs b/crates/mcp-server/src/content.rs new file mode 100644 index 000000000..a2a017dec --- /dev/null +++ b/crates/mcp-server/src/content.rs @@ -0,0 +1,64 @@ +//! The content blocks a tool result is made of (MCP `CallToolResult`), and the contents a resource +//! read sends (MCP `ReadResourceResult`). + +use serde_json::{Value, json}; + +/// What `resources/read` sends for one resource: text of a MIME type, or bytes of a MIME type, +/// which go out base64-encoded. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Contents { + Text { mime_type: String, text: String }, + Blob { mime_type: String, data: Vec }, +} + +impl Contents { + /// `value` as JSON text (`application/json`). + pub fn json(value: &Value) -> Self { + Self::Text { mime_type: "application/json".into(), text: value.to_string() } + } + + /// The MCP contents block of resource `uri`. + pub(crate) fn block(&self, uri: &str) -> Value { + match self { + Self::Text { mime_type, text } => json!({"uri": uri, "mimeType": mime_type, "text": text}), + Self::Blob { mime_type, data } => json!({"uri": uri, "mimeType": mime_type, "blob": base64(data)}), + } + } +} + +/// A tool result of one text block, flagged as an error when `is_error` (the model sees the +/// message; an error is still a result, not a JSON-RPC error). +pub fn text_result(text: impl Into, is_error: bool) -> Value { + let mut r = json!({"content": [{"type": "text", "text": text.into()}]}); + if is_error { + r["isError"] = json!(true); + } + r +} + +/// A tool result of an image (`data` of type `mime`, base64-encoded here) followed by a text +/// block saying what it shows. +pub fn image_result(data: &[u8], mime: &str, text: impl Into) -> Value { + json!({"content": [ + {"type": "image", "data": base64(data), "mimeType": mime}, + {"type": "text", "text": text.into()}, + ]}) +} + +/// Standard base64 with padding (RFC 4648), as MCP image content carries it. +pub fn base64(data: &[u8]) -> String { + const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(data.len().div_ceil(3) * 4); + for chunk in data.chunks(3) { + let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)]; + let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); + for (i, shift) in [18u32, 12, 6, 0].into_iter().enumerate() { + if i <= chunk.len() { + out.push(char::from(T[((n >> shift) & 63) as usize])); + } else { + out.push('='); + } + } + } + out +} diff --git a/crates/mcp-server/src/lib.rs b/crates/mcp-server/src/lib.rs new file mode 100644 index 000000000..17e6827c4 --- /dev/null +++ b/crates/mcp-server/src/lib.rs @@ -0,0 +1,21 @@ +//! MCP server machinery any app may share: JSON-RPC 2.0 over stdio (newline-delimited), the MCP +//! lifecycle, the tools, resources, prompts and completion methods, tool schemas with the check of +//! a call's arguments against them, and the content blocks tools reply with (text, images). +//! +//! An app implements [`Tools`]: what its tools are, how each one runs, its instructions, and the +//! resources, resource templates and prompts it serves, if any. [`Server`] speaks the protocol +//! around them and tells a client at `initialize` only what the app serves. Nothing here knows any +//! app's design, engine or renderer. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +mod content; +mod schema; +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}; + +#[cfg(test)] +mod tests; diff --git a/crates/mcp-server/src/schema.rs b/crates/mcp-server/src/schema.rs new file mode 100644 index 000000000..3cc72da34 --- /dev/null +++ b/crates/mcp-server/src/schema.rs @@ -0,0 +1,132 @@ +//! Tool definitions (MCP `Tool`: name, title, description, input schema, annotations) and the +//! check of a call's arguments against the definition it was listed with. + +use serde_json::{Value, json}; + +/// What a tool may do, for the client's approval prompts (MCP tool annotations). Clients that +/// auto-approve on these hints must not be told less than the truth. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Effect { + /// Only looks. + ReadOnly, + /// Changes the app's document in memory, undoably. + Edits, + /// Replaces the app's document in memory (unsaved changes are lost). + Replaces, + /// May read, write, overwrite or delete files on disk. + Files, +} + +/// A tool's definition, its annotations from `effect`. +pub fn tool(name: &str, title: &str, desc: &str, schema: Value, effect: Effect) -> Value { + let (read_only, destructive, open_world) = match effect { + Effect::ReadOnly => (true, false, false), + Effect::Edits => (false, false, false), + Effect::Replaces => (false, true, false), + Effect::Files => (false, true, true), + }; + json!({ + "name": name, + "title": title, + "description": desc, + "inputSchema": schema, + "annotations": {"title": title, "readOnlyHint": read_only, "destructiveHint": destructive, "idempotentHint": read_only, "openWorldHint": open_world}, + }) +} + +/// An object schema with these `props`, the `required` ones, and no other keys. +pub fn object(props: Value, required: &[&str]) -> Value { + let mut o = json!({"type": "object", "properties": props, "additionalProperties": false}); + if !required.is_empty() { + o["required"] = json!(required); + } + o +} + +/// A string property described by `desc`. +pub fn string(desc: &str) -> Value { + json!({"type": "string", "description": desc}) +} + +fn type_matches(t: &str, v: &Value) -> bool { + match t { + "string" => v.is_string(), + "number" => v.is_number(), + "integer" => v.is_i64() || v.is_u64(), + "boolean" => v.is_boolean(), + "array" => v.is_array(), + "object" => v.is_object(), + "null" => v.is_null(), + _ => true, + } +} + +/// Check `args` against tool `name`'s input schema as `defs` list it (top level): unknown tool, +/// missing required arguments, unknown arguments, type and enum mismatches. +pub fn check_arguments(defs: &[Value], name: &str, args: &Value) -> Result<(), String> { + let def = defs.iter().find(|d| d["name"] == name).ok_or_else(|| format!("unknown tool `{name}`"))?; + let schema = &def["inputSchema"]; + let Some(a) = args.as_object() else { return Err(format!("{name}: arguments must be an object")) }; + for r in schema["required"].as_array().into_iter().flatten().filter_map(Value::as_str) { + if a.get(r).is_none_or(Value::is_null) { + return Err(format!("{name}: missing required argument `{r}`")); + } + } + let props = schema["properties"].as_object(); + for (k, v) in a { + let Some(p) = props.and_then(|p| p.get(k)) else { + let valid: Vec<&str> = props.map(|p| p.keys().map(String::as_str).collect()).unwrap_or_default(); + let valid = if valid.is_empty() { "none".to_string() } else { valid.join(", ") }; + let k: String = k.chars().take(64).collect(); + return Err(format!("{name}: unknown argument `{k}`; its arguments are: {valid}")); + }; + if v.is_null() { + continue; + } + // An argument of several types lists them as `anyOf` (Gemini refuses a list of types). + let types: Vec<&Value> = match p["anyOf"].as_array() { + Some(alts) => alts.iter().map(|alt| &alt["type"]).collect(), + None => vec![&p["type"]], + }; + let ok = types.iter().any(|t| match t { + Value::String(t) => type_matches(t, v), + Value::Array(ts) => ts.iter().filter_map(Value::as_str).any(|t| type_matches(t, v)), + _ => true, + }); + if !ok { + let expected = if types.len() == 1 { types[0].clone() } else { Value::Array(types.into_iter().cloned().collect()) }; + return Err(format!("{name}: argument `{k}` must be of type {expected}")); + } + if let Some(allowed) = p["enum"].as_array() + && !allowed.contains(v) + { + return Err(format!("{name}: `{k}` must be one of {}", Value::Array(allowed.clone()))); + } + } + Ok(()) +} + +/// Check `args` against prompt `name` as `defs` list it (MCP `Prompt`): unknown prompt, missing +/// required arguments, unknown arguments, values that are not strings. +pub(crate) fn check_prompt_arguments(defs: &[Value], name: &str, args: &Value) -> Result<(), String> { + let def = defs.iter().find(|d| d["name"] == name).ok_or_else(|| format!("unknown prompt `{name}`"))?; + let declared = def["arguments"].as_array().map(Vec::as_slice).unwrap_or_default(); + let Some(a) = args.as_object() else { return Err(format!("{name}: arguments must be an object")) }; + for r in declared.iter().filter(|d| d["required"] == true).filter_map(|d| d["name"].as_str()) { + if !a.contains_key(r) { + return Err(format!("{name}: missing required argument `{r}`")); + } + } + for (k, v) in a { + if !declared.iter().any(|d| d["name"] == k.as_str()) { + let valid: Vec<&str> = declared.iter().filter_map(|d| d["name"].as_str()).collect(); + let valid = if valid.is_empty() { "none".to_string() } else { valid.join(", ") }; + let k: String = k.chars().take(64).collect(); + return Err(format!("{name}: unknown argument `{k}`; its arguments are: {valid}")); + } + if !v.is_string() { + return Err(format!("{name}: argument `{k}` must be a string")); + } + } + Ok(()) +} diff --git a/crates/mcp-server/src/server.rs b/crates/mcp-server/src/server.rs new file mode 100644 index 000000000..b7ed05027 --- /dev/null +++ b/crates/mcp-server/src/server.rs @@ -0,0 +1,330 @@ +//! JSON-RPC 2.0 framing and the MCP lifecycle / tools / resources / prompts / completion methods. + +use std::io::{BufRead, Write}; + +use serde_json::{Value, json}; + +use crate::content::Contents; +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. +pub const PROTOCOL_VERSION: &str = "2025-06-18"; +pub const SUPPORTED_VERSIONS: &[&str] = &[PROTOCOL_VERSION, "2025-03-26", "2024-11-05"]; + +const PARSE_ERROR: i64 = -32700; +const INVALID_REQUEST: i64 = -32600; +const METHOD_NOT_FOUND: i64 = -32601; +const INVALID_PARAMS: i64 = -32602; +const INTERNAL_ERROR: i64 = -32603; +const RESOURCE_NOT_FOUND: i64 = -32002; + +/// Most messages in one JSON-RPC batch. +const MAX_BATCH: usize = 1000; +/// Most suggestions in one `completion/complete` reply (the MCP limit). +const MAX_COMPLETIONS: usize = 100; + +/// What `completion/complete` asks about: a prompt by its name, or a resource by its URI or URI +/// template. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reference<'a> { + Prompt(&'a str), + Resource(&'a str), +} + +/// An app's tools, served by [`Server`]. +pub trait Tools { + /// What every client is told at `initialize`. + fn instructions(&self) -> String; + /// Every tool's definition ([`crate::tool`]), as `tools/list` serves it now. + fn list(&mut self) -> Vec; + /// Run tool `name`. The server calls it right after the [`Tools::list`] its arguments were + /// checked against ([`crate::check_arguments`]), so it runs the tool as that listing defined + /// it. Failures are tool results with `isError: true` ([`crate::text_result`]); it never + /// panics on hostile arguments. + fn call(&mut self, name: &str, args: &Value) -> Value; + /// The resources `resources/list` serves (MCP `Resource`: uri, name, description, mimeType). + fn resources(&self) -> Vec { + Vec::new() + } + /// The resource templates `resources/templates/list` serves (MCP `ResourceTemplate`: + /// uriTemplate, name, description, mimeType). A URI made from one is read with + /// [`Tools::read_resource`]. + fn resource_templates(&self) -> Vec { + Vec::new() + } + /// The contents of resource `uri`: `None` when there is no such resource, `Err` when it could + /// not be read now. + fn read_resource(&mut self, uri: &str) -> Option> { + let _ = uri; + None + } + /// The prompts `prompts/list` serves (MCP `Prompt`: name, title, description, arguments). + fn prompts(&self) -> Vec { + Vec::new() + } + /// Prompt `name` filled in with `args` (MCP `GetPromptResult`: description, messages). The + /// server calls it only for a listed prompt, with `args` checked against that listing: an + /// object of strings with every required argument and no other. `Err` is an internal error. + fn get_prompt(&mut self, name: &str, args: &Value) -> Result { + let _ = args; + Err(format!("prompt `{name}` cannot be filled in")) + } + /// What argument `argument` of `reference` could be, given what has been typed (`value`). + /// Asked only of an app that serves prompts or resource templates; a prompt reference is + /// always a listed prompt. The reply holds the first 100. + fn complete(&mut self, reference: Reference<'_>, argument: &str, value: &str) -> Vec { + let _ = (reference, argument, value); + Vec::new() + } +} + +/// Who the server says it is at `initialize`, and the longest request line it reads. +#[derive(Clone, Copy, Debug)] +pub struct Info { + pub name: &'static str, + pub title: &'static str, + pub version: &'static str, + /// Longest accepted request line, in bytes; a longer one is refused in bounded space. + pub max_line: usize, +} + +/// An MCP server over the app's [`Tools`]. +pub struct Server { + info: Info, + tools: T, + initialized: bool, +} + +fn error(id: Value, code: i64, message: impl Into) -> Value { + json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message.into()}}) +} + +/// One message read from a newline-delimited stream by [`read_message`]. +#[derive(Debug, PartialEq, Eq)] +pub enum Incoming { + /// A line to handle ([`Server::handle_line`]), without its newline. + Line(String), + /// A line refused unread (too long, not UTF-8): the error reply to send for it. + Refused(String), +} + +/// Read the next line of newline-delimited JSON-RPC from `input`; `None` once it closes. A line +/// longer than `max_line` is consumed in bounded space, so a client cannot exhaust memory by +/// sending an arbitrarily long request without a newline, and an unterminated last line counts. +pub fn read_message(input: &mut impl BufRead, max_line: usize) -> std::io::Result> { + let mut line = Vec::new(); + let mut oversized = false; + let mut received = false; + loop { + let chunk = input.fill_buf()?; + if chunk.is_empty() { + break; + } + let count = chunk.iter().position(|&byte| byte == b'\n').map_or(chunk.len(), |i| i + 1); + let newline = chunk[count - 1] == b'\n'; + let content_len = count - usize::from(newline); + if !oversized { + if line.len().saturating_add(content_len) > max_line { + oversized = true; + line.clear(); + } else { + line.extend_from_slice(&chunk[..content_len]); + } + } + input.consume(count); + received = true; + if newline { + break; + } + } + if !received { + return Ok(None); + } + if oversized { + return Ok(Some(Incoming::Refused(error(Value::Null, INVALID_REQUEST, "request too large").to_string()))); + } + Ok(Some(match String::from_utf8(line) { + Ok(line) => Incoming::Line(line), + // Not UTF-8: answer with a parse error and keep serving. + Err(_) => Incoming::Refused(error(Value::Null, PARSE_ERROR, "parse error: input is not UTF-8").to_string()), + })) +} + +/// The JSON-RPC response to request `id`, as [`Server::handle`] sends it. +pub fn response(id: Value, result: Value) -> Value { + json!({"jsonrpc": "2.0", "id": id, "result": result}) +} + +impl Server { + pub fn new(info: Info, tools: T) -> Self { + Self { info, tools, initialized: false } + } + pub fn tools(&mut self) -> &mut T { + &mut self.tools + } + pub fn is_initialized(&self) -> bool { + self.initialized + } + + /// Serve newline-delimited JSON-RPC until `input` closes. Only protocol messages go to + /// `output`; diagnostics belong on stderr. Consume oversized lines in bounded space so a + /// client cannot exhaust memory by sending an arbitrarily long request without a newline. + pub fn serve(&mut self, mut input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { + while let Some(incoming) = read_message(&mut input, self.info.max_line)? { + let reply = match incoming { + Incoming::Line(line) => self.handle_line(&line), + Incoming::Refused(reply) => Some(reply), + }; + if let Some(reply) = reply { + output.write_all(reply.as_bytes())?; + output.write_all(b"\n")?; + output.flush()?; + } + } + Ok(()) + } + + /// One line in, at most one line out (notifications get no reply). + pub fn handle_line(&mut self, line: &str) -> Option { + // Check the raw input before trimming: a huge whitespace prefix is still a huge line. + if line.len() > self.info.max_line { + return Some(error(Value::Null, INVALID_REQUEST, "request too large").to_string()); + } + let line = line.trim(); + if line.is_empty() { + return None; + } + let reply = match serde_json::from_str::(line) { + Ok(Value::Array(batch)) if batch.is_empty() => Some(error(Value::Null, INVALID_REQUEST, "empty batch")), + Ok(Value::Array(batch)) if batch.len() > MAX_BATCH => Some(error(Value::Null, INVALID_REQUEST, "batch too large")), + Ok(Value::Array(batch)) => { + let replies: Vec = batch.into_iter().filter_map(|m| self.handle(m)).collect(); + (!replies.is_empty()).then_some(Value::Array(replies)) + } + Ok(msg) => self.handle(msg), + Err(e) => Some(error(Value::Null, PARSE_ERROR, format!("parse error: {e}"))), + }; + reply.map(|r| r.to_string()) + } + + pub fn handle(&mut self, msg: Value) -> Option { + let Value::Object(o) = &msg else { return Some(error(Value::Null, INVALID_REQUEST, "message must be an object")) }; + let id = o.get("id").cloned(); + let Some(method) = o.get("method").and_then(Value::as_str) else { + // A response to a request of ours (we send none) or junk. + if o.contains_key("result") || o.contains_key("error") { + return None; + } + return Some(error(id.unwrap_or(Value::Null), INVALID_REQUEST, "missing `method`")); + }; + let params = o.get("params").cloned().unwrap_or(Value::Null); + let Some(id) = id else { + if method == "notifications/initialized" { + self.initialized = true; + } + return None; + }; + Some(match self.request(method, ¶ms) { + Ok(r) => response(id, r), + Err((code, m)) => error(id, code, m), + }) + } + + fn request(&mut self, method: &str, params: &Value) -> Result { + match method { + "initialize" => { + 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; + Ok(json!({ + "protocolVersion": version, + "capabilities": self.capabilities(), + "serverInfo": {"name": name, "title": title, "version": server_version}, + "instructions": self.tools.instructions(), + })) + } + "ping" => Ok(json!({})), + "tools/list" => Ok(json!({"tools": self.tools.list()})), + "tools/call" => { + let name = params.get("name").and_then(Value::as_str).ok_or((INVALID_PARAMS, "missing tool `name`".to_string()))?; + let args = match params.get("arguments") { + None | Some(Value::Null) => json!({}), + Some(a) => a.clone(), + }; + check_arguments(&self.tools.list(), name, &args).map_err(|e| (INVALID_PARAMS, e))?; + Ok(self.tools.call(name, &args)) + } + "resources/list" => Ok(json!({"resources": self.tools.resources()})), + "resources/templates/list" => Ok(json!({"resourceTemplates": self.tools.resource_templates()})), + "prompts/list" => Ok(json!({"prompts": self.tools.prompts()})), + "resources/read" => { + let uri = params.get("uri").and_then(Value::as_str).unwrap_or(""); + let contents = self + .tools + .read_resource(uri) + .ok_or_else(|| (RESOURCE_NOT_FOUND, format!("unknown resource `{uri}`")))? + .map_err(|e| (INTERNAL_ERROR, e))?; + Ok(json!({"contents": [contents.block(uri)]})) + } + "prompts/get" if !self.tools.prompts().is_empty() => { + let name = params.get("name").and_then(Value::as_str).ok_or((INVALID_PARAMS, "missing prompt `name`".to_string()))?; + let args = match params.get("arguments") { + None | Some(Value::Null) => json!({}), + Some(a) => a.clone(), + }; + check_prompt_arguments(&self.tools.prompts(), name, &args).map_err(|e| (INVALID_PARAMS, e))?; + self.tools.get_prompt(name, &args).map_err(|e| (INTERNAL_ERROR, e)) + } + "completion/complete" if self.completes() => { + let reference = params.get("ref").unwrap_or(&Value::Null); + let reference = match (reference.get("type").and_then(Value::as_str), reference.get("name"), reference.get("uri")) { + (Some("ref/prompt"), Some(Value::String(name)), _) => { + if !self.tools.prompts().iter().any(|p| p["name"] == name.as_str()) { + return Err((INVALID_PARAMS, format!("unknown prompt `{name}`"))); + } + Reference::Prompt(name) + } + (Some("ref/resource"), _, Some(Value::String(uri))) => Reference::Resource(uri), + _ => { + return Err(( + INVALID_PARAMS, + "`ref` must be a prompt's {type: ref/prompt, name} or a resource's {type: ref/resource, uri}".into(), + )); + } + }; + let argument = params.get("argument"); + let (Some(argument), Some(value)) = + (argument.and_then(|a| a.get("name")).and_then(Value::as_str), argument.and_then(|a| a.get("value")).and_then(Value::as_str)) + else { + return Err((INVALID_PARAMS, "`argument` must have a `name` and a `value`, both strings".into())); + }; + let mut values = self.tools.complete(reference, argument, value); + let total = values.len(); + values.truncate(MAX_COMPLETIONS); + Ok(json!({"completion": {"values": values, "total": total, "hasMore": total > MAX_COMPLETIONS}})) + } + _ => Err((METHOD_NOT_FOUND, format!("method `{method}` not found"))), + } + } + + /// What the server tells a client at `initialize` that it serves: the tools always, and the + /// rest only when the app has some. + fn capabilities(&self) -> Value { + let mut capabilities = json!({"tools": {"listChanged": false}}); + if !self.tools.resources().is_empty() || !self.tools.resource_templates().is_empty() { + capabilities["resources"] = json!({"listChanged": false}); + } + if !self.tools.prompts().is_empty() { + capabilities["prompts"] = json!({"listChanged": false}); + } + if self.completes() { + capabilities["completions"] = json!({}); + } + capabilities + } + + /// Whether the app has arguments to complete: those of its prompts and resource templates. + fn completes(&self) -> bool { + !self.tools.prompts().is_empty() || !self.tools.resource_templates().is_empty() + } +} diff --git a/crates/mcp-server/src/tests.rs b/crates/mcp-server/src/tests.rs new file mode 100644 index 000000000..b687ee2e8 --- /dev/null +++ b/crates/mcp-server/src/tests.rs @@ -0,0 +1,368 @@ +use serde_json::{Value, json}; + +use crate::{ + Contents, Effect, Info, 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 +/// every listing and call in order. +#[derive(Default)] +struct Echo { + calls: Vec, + log: Vec, +} + +impl Tools for Echo { + fn instructions(&self) -> String { + "Echo test tools.".into() + } + fn list(&mut self) -> Vec { + self.log.push("list".into()); + vec![ + tool("echo", "Echo", "Say `text` back.", object(json!({"text": string("What to say")}), &["text"]), Effect::ReadOnly), + tool("level", "Level", "Set the level.", object(json!({"level": {"type": "string", "enum": ["low", "high"]}}), &[]), Effect::Edits), + ] + } + fn call(&mut self, name: &str, args: &Value) -> Value { + self.log.push(format!("call {name}")); + self.calls.push(json!({"name": name, "args": args})); + text_result(args["text"].as_str().unwrap_or_default(), false) + } +} + +fn info() -> Info { + Info { name: "echo", title: "Echo", version: "1.0.0", max_line: 1 << 16 } +} + +fn serve(lines: &[Value]) -> (Server, Vec) { + serve_with(Echo::default(), lines) +} + +fn serve_with(tools: T, lines: &[Value]) -> (Server, Vec) { + let input: String = lines.iter().map(|l| format!("{l}\n")).collect(); + let mut output = Vec::new(); + let mut s = Server::new(info(), tools); + s.serve(std::io::Cursor::new(input), &mut output).unwrap(); + let replies = String::from_utf8(output).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + (s, replies) +} + +/// A registered tool is listed and called over the stdio transport, with no engine behind it. +#[test] +fn a_registered_tool_is_served_over_stdio() { + let (mut s, replies) = serve(&[ + json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-03-26"}}), + json!({"jsonrpc": "2.0", "method": "notifications/initialized"}), + json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}), + json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "echo", "arguments": {"text": "hi"}}}), + ]); + assert_eq!(replies.len(), 3, "the notification gets no reply: {replies:?}"); + let init = &replies[0]["result"]; + assert_eq!(init["protocolVersion"], "2025-03-26"); + assert_eq!(init["serverInfo"], json!({"name": "echo", "title": "Echo", "version": "1.0.0"})); + assert_eq!(init["instructions"], "Echo test tools."); + assert!(s.is_initialized()); + assert_eq!(replies[1]["result"]["tools"][0]["name"], "echo"); + assert_eq!(replies[1]["result"]["tools"][0]["annotations"]["readOnlyHint"], true); + assert_eq!(replies[2], json!({"jsonrpc": "2.0", "id": 3, "result": {"content": [{"type": "text", "text": "hi"}]}})); + assert_eq!(s.tools().calls, vec![json!({"name": "echo", "args": {"text": "hi"}})]); +} + +/// Arguments are checked against the tool's schema before the tool runs; unknown tools and +/// methods are JSON-RPC errors. +#[test] +fn arguments_break_the_schema_before_the_tool_runs() { + let (mut s, replies) = serve(&[ + json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "echo", "arguments": {}}}), + json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "echo", "arguments": {"text": 3}}}), + json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "echo", "arguments": {"text": "a", "loud": true}}}), + json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "shout", "arguments": {}}}), + json!({"jsonrpc": "2.0", "id": 5, "method": "nope"}), + json!({"jsonrpc": "2.0", "id": 6, "method": "resources/read", "params": {"uri": "x://y"}}), + ]); + let codes: Vec<&Value> = replies.iter().map(|r| &r["error"]["code"]).collect(); + assert_eq!(codes, [&json!(-32602), &json!(-32602), &json!(-32602), &json!(-32602), &json!(-32601), &json!(-32002)], "{replies:?}"); + assert_eq!(replies[0]["error"]["message"], "echo: missing required argument `text`"); + assert_eq!(replies[2]["error"]["message"], "echo: unknown argument `loud`; its arguments are: text"); + assert!(s.tools().calls.is_empty()); + let defs = s.tools().list(); + assert!(check_arguments(&defs, "echo", &json!({"text": "a"})).is_ok()); +} + +/// Hostile framing: oversized lines, bad UTF-8 and bad JSON are answered and the server goes on. +#[test] +fn hostile_lines_are_answered_and_serving_goes_on() { + let mut input = vec![b'x'; (1 << 16) + 10]; + input.push(b'\n'); + input.extend_from_slice(b"\xff\xfe\n{not json\n[]\n"); + input.extend_from_slice(json!({"jsonrpc": "2.0", "id": 9, "method": "ping"}).to_string().as_bytes()); + let mut output = Vec::new(); + Server::new(info(), Echo::default()).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(); + let codes: Vec<&Value> = replies.iter().map(|r| r.get("error").map_or(&r["result"], |e| &e["code"])).collect(); + assert_eq!(codes, [&json!(-32600), &json!(-32700), &json!(-32700), &json!(-32600), &json!({})], "{replies:?}"); +} + +#[test] +fn base64_matches_rfc4648() { + for (i, o) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE="), ("foobar", "Zm9vYmFy")] { + assert_eq!(crate::base64(i.as_bytes()), o); + } + let r = crate::image_result(b"foo", "image/png", "info"); + assert_eq!(r, json!({"content": [{"type": "image", "data": "Zm9v", "mimeType": "image/png"}, {"type": "text", "text": "info"}]})); +} + +fn ping(id: usize) -> Value { + json!({"jsonrpc": "2.0", "id": id, "method": "ping"}) +} + +fn notification() -> Value { + json!({"jsonrpc": "2.0", "method": "notifications/progress"}) +} + +fn reply(s: &mut Server, msg: &Value) -> Option { + s.handle_line(&msg.to_string()).map(|r| serde_json::from_str(&r).unwrap()) +} + +/// A batch answers each request in it and none of its notifications; a batch of notifications +/// only gets no reply at all; a batch holds at most 1000 messages. +#[test] +fn batches_answer_their_requests_up_to_the_limit() { + let mut s = Server::new(info(), Echo::default()); + let mixed = + json!([ping(1), notification(), {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "echo", "arguments": {"text": "b"}}}]); + let replies = reply(&mut s, &mixed).unwrap(); + assert_eq!( + replies, + json!([{"jsonrpc": "2.0", "id": 1, "result": {}}, {"jsonrpc": "2.0", "id": 2, "result": {"content": [{"type": "text", "text": "b"}]}}]) + ); + assert_eq!(reply(&mut s, &json!([notification(), notification()])), None); + let full: Vec = (0..1000).map(ping).collect(); + assert_eq!(reply(&mut s, &Value::Array(full)).unwrap().as_array().map(Vec::len), Some(1000)); + let over: Vec = (0..1001).map(ping).collect(); + let r = reply(&mut s, &Value::Array(over)).unwrap(); + assert_eq!(r, json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32600, "message": "batch too large"}})); +} + +/// We send no requests, so a response is never answered, alone or in a batch; a message with +/// neither a method nor a result, or one that is not an object, is refused; a blank line is skipped. +#[test] +fn a_response_we_never_asked_for_is_ignored() { + let mut s = Server::new(info(), Echo::default()); + assert_eq!(reply(&mut s, &json!({"jsonrpc": "2.0", "id": 1, "result": {}})), None); + assert_eq!(reply(&mut s, &json!({"jsonrpc": "2.0", "id": 2, "error": {"code": -1, "message": "no"}})), None); + assert_eq!( + reply(&mut s, &json!([{"jsonrpc": "2.0", "id": 3, "result": {}}, ping(4)])).unwrap(), + json!([{"jsonrpc": "2.0", "id": 4, "result": {}}]) + ); + let r = reply(&mut s, &json!({"jsonrpc": "2.0", "id": 5})).unwrap(); + assert_eq!(r, json!({"jsonrpc": "2.0", "id": 5, "error": {"code": -32600, "message": "missing `method`"}})); + let r = reply(&mut s, &json!(42)).unwrap(); + assert_eq!(r, json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32600, "message": "message must be an object"}})); + assert_eq!(s.handle_line(" "), None); + assert!(s.tools().log.is_empty()); +} + +/// A version we speak is echoed; one we don't, or none, gets ours. +#[test] +fn an_unknown_protocol_version_gets_ours() { + let mut s = Server::new(info(), Echo::default()); + let version = |s: &mut Server, params: Value| { + reply(s, &json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": params})).unwrap()["result"]["protocolVersion"].clone() + }; + for v in SUPPORTED_VERSIONS { + assert_eq!(version(&mut s, json!({"protocolVersion": v})), json!(v)); + } + assert_eq!(version(&mut s, json!({"protocolVersion": "1999-01-01"})), json!(PROTOCOL_VERSION)); + assert_eq!(version(&mut s, json!({"protocolVersion": 7})), json!(PROTOCOL_VERSION)); + assert_eq!(version(&mut s, json!({})), json!(PROTOCOL_VERSION)); + assert!(!s.is_initialized(), "initialized only by the client's notification"); +} + +/// `arguments: null` is no arguments; a value outside a property's `enum` is refused before the +/// tool runs. +#[test] +fn null_arguments_are_none_and_enums_are_checked() { + let mut s = Server::new(info(), Echo::default()); + let call = |s: &mut Server, id: u64, args: Value| { + reply(s, &json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": "level", "arguments": args}})).unwrap() + }; + assert!(call(&mut s, 1, Value::Null).get("result").is_some()); + let none = reply(&mut s, &json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "level"}})).unwrap(); + assert!(none.get("result").is_some(), "{none}"); + assert!(call(&mut s, 3, json!({"level": "high"})).get("result").is_some()); + let r = call(&mut s, 4, json!({"level": "loud"})); + assert_eq!(r["error"], json!({"code": -32602, "message": "level: `level` must be one of [\"low\",\"high\"]"})); + let r = call(&mut s, 5, json!([])); + assert_eq!(r["error"], json!({"code": -32602, "message": "level: arguments must be an object"})); + let args: Vec<&Value> = s.tools().calls.iter().map(|c| &c["args"]).collect(); + assert_eq!(args, [&json!({}), &json!({}), &json!({"level": "high"})]); +} + +/// An app that serves no resources, templates or prompts lists none of each, says it serves only +/// tools, and has no prompt to fill in or argument to complete. +#[test] +fn the_default_lists_are_empty() { + let mut s = Server::new(info(), Echo::default()); + let result = |s: &mut Server, method: &str| reply(s, &json!({"jsonrpc": "2.0", "id": 1, "method": method})).unwrap()["result"].clone(); + assert_eq!(result(&mut s, "resources/list"), json!({"resources": []})); + assert_eq!(result(&mut s, "resources/templates/list"), json!({"resourceTemplates": []})); + assert_eq!(result(&mut s, "prompts/list"), json!({"prompts": []})); + assert_eq!(result(&mut s, "initialize")["capabilities"], json!({"tools": {"listChanged": false}})); + for method in ["prompts/get", "completion/complete"] { + let r = reply(&mut s, &json!({"jsonrpc": "2.0", "id": 2, "method": method, "params": {"name": "describe"}})).unwrap(); + assert_eq!(r["error"]["code"], -32601, "{method}: {r}"); + } +} + +/// An app that serves more than tools: a prompt with a required and an optional argument, a +/// resource template, a Markdown resource and a PNG, and suggestions for any argument. `asked` +/// records every prompt filled in and every completion asked for. +#[derive(Default)] +struct Library { + asked: Vec, +} + +impl Tools for Library { + fn instructions(&self) -> String { + "Library test.".into() + } + fn list(&mut self) -> Vec { + Vec::new() + } + fn call(&mut self, name: &str, _: &Value) -> Value { + text_result(format!("no tool `{name}`"), true) + } + fn resources(&self) -> Vec { + vec![ + json!({"uri": "lib://readme", "name": "Readme", "mimeType": "text/markdown"}), + json!({"uri": "lib://logo", "name": "Logo", "mimeType": "image/png"}), + ] + } + fn resource_templates(&self) -> Vec { + vec![json!({"uriTemplate": "lib://parts/{name}", "name": "Part", "mimeType": "text/markdown"})] + } + fn read_resource(&mut self, uri: &str) -> Option> { + let markdown = |text: String| Contents::Text { mime_type: "text/markdown".into(), text }; + Some(Ok(match uri { + "lib://readme" => markdown("# Parts\n\nA \"quoted\" line.".into()), + "lib://logo" => Contents::Blob { mime_type: "image/png".into(), data: b"foo".to_vec() }, + "lib://parts/broken" => return Some(Err("the part is being rebuilt".into())), + _ => markdown(format!("# {}", uri.strip_prefix("lib://parts/")?)), + })) + } + fn prompts(&self) -> Vec { + vec![json!({"name": "describe", "title": "Describe a part", "arguments": [{"name": "part", "required": true}, {"name": "tone"}]})] + } + fn get_prompt(&mut self, name: &str, args: &Value) -> Result { + self.asked.push(format!("{name} {args}")); + let text = format!("Describe {} in a {} tone.", args["part"].as_str().unwrap_or_default(), args["tone"].as_str().unwrap_or("plain")); + Ok(json!({"messages": [{"role": "user", "content": {"type": "text", "text": text}}]})) + } + fn complete(&mut self, reference: Reference<'_>, argument: &str, value: &str) -> Vec { + self.asked.push(format!("{reference:?} {argument}={value}")); + (0..150).map(|i| format!("{value}{i}")).collect() + } +} + +/// The shared crate serves an app's prompt, resource template and Markdown and binary resources, +/// and tells the client at `initialize` that it does (#13336). +#[test] +fn an_app_serves_prompts_templates_and_markdown_or_binary_resources() { + let request = |id: u64, method: &str, params: Value| json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}); + let (mut s, replies) = serve_with( + Library::default(), + &[ + request(1, "initialize", json!({"protocolVersion": PROTOCOL_VERSION})), + request(2, "prompts/list", json!({})), + request(3, "prompts/get", json!({"name": "describe", "arguments": {"part": "bracket"}})), + request(4, "resources/templates/list", json!({})), + request(5, "resources/read", json!({"uri": "lib://readme"})), + request(6, "resources/read", json!({"uri": "lib://logo"})), + request(7, "resources/read", json!({"uri": "lib://parts/bracket"})), + request(8, "resources/read", json!({"uri": "lib://parts/broken"})), + request(9, "resources/read", json!({"uri": "lib://nope"})), + ], + ); + let result = |i: usize| &replies[i]["result"]; + assert_eq!( + result(0)["capabilities"], + json!({"tools": {"listChanged": false}, "resources": {"listChanged": false}, "prompts": {"listChanged": false}, "completions": {}}) + ); + assert_eq!(result(1)["prompts"][0]["name"], "describe"); + assert_eq!(result(2), &json!({"messages": [{"role": "user", "content": {"type": "text", "text": "Describe bracket in a plain tone."}}]})); + assert_eq!(result(3), &json!({"resourceTemplates": [{"uriTemplate": "lib://parts/{name}", "name": "Part", "mimeType": "text/markdown"}]})); + // The Markdown goes out as it is, not as a JSON string of it. + assert_eq!(result(4), &json!({"contents": [{"uri": "lib://readme", "mimeType": "text/markdown", "text": "# Parts\n\nA \"quoted\" line."}]})); + assert_eq!(result(5), &json!({"contents": [{"uri": "lib://logo", "mimeType": "image/png", "blob": "Zm9v"}]})); + assert_eq!(result(6), &json!({"contents": [{"uri": "lib://parts/bracket", "mimeType": "text/markdown", "text": "# bracket"}]})); + assert_eq!(replies[7]["error"], json!({"code": -32603, "message": "the part is being rebuilt"})); + assert_eq!(replies[8]["error"]["code"], -32002); + assert_eq!(s.tools().asked, [r#"describe {"part":"bracket"}"#]); +} + +/// A prompt is filled in only with the arguments its listing declares, each a string, the +/// required ones present; anything else is invalid params and the app is never asked. +#[test] +fn prompt_arguments_are_checked_before_the_prompt_is_filled_in() { + let mut s = Server::new(info(), Library::default()); + let get = + |s: &mut Server, params: Value| reply(s, &json!({"jsonrpc": "2.0", "id": 1, "method": "prompts/get", "params": params})).unwrap(); + for (params, message) in [ + (json!({"arguments": {"part": "a"}}), "missing prompt `name`"), + (json!({"name": "summarise"}), "unknown prompt `summarise`"), + (json!({"name": "describe"}), "describe: missing required argument `part`"), + (json!({"name": "describe", "arguments": ["a"]}), "describe: arguments must be an object"), + (json!({"name": "describe", "arguments": {"part": 3}}), "describe: argument `part` must be a string"), + (json!({"name": "describe", "arguments": {"part": null}}), "describe: argument `part` must be a string"), + (json!({"name": "describe", "arguments": {"part": "a", "size": "big"}}), "describe: unknown argument `size`; its arguments are: part, tone"), + ] { + assert_eq!(get(&mut s, params.clone())["error"], json!({"code": -32602, "message": message}), "{params}"); + } + assert!(s.tools().asked.is_empty()); + let filled = get(&mut s, json!({"name": "describe", "arguments": {"part": "hinge", "tone": "dry"}})); + assert_eq!(filled["result"]["messages"][0]["content"]["text"], "Describe hinge in a dry tone."); +} + +/// Completion asks the app about a listed prompt or a resource, and sends the first 100 +/// suggestions with how many there are; a bad reference or argument is invalid params. +#[test] +fn completion_suggests_up_to_a_hundred_values() { + let mut s = Server::new(info(), Library::default()); + let complete = |s: &mut Server, params: Value| { + reply(s, &json!({"jsonrpc": "2.0", "id": 1, "method": "completion/complete", "params": params})).unwrap() + }; + let r = complete(&mut s, json!({"ref": {"type": "ref/prompt", "name": "describe"}, "argument": {"name": "part", "value": "br"}})); + let completion = &r["result"]["completion"]; + assert_eq!(completion["values"].as_array().map(Vec::len), Some(100), "{r}"); + assert_eq!((&completion["values"][0], &completion["total"], &completion["hasMore"]), (&json!("br0"), &json!(150), &json!(true))); + let r = complete(&mut s, json!({"ref": {"type": "ref/resource", "uri": "lib://parts/{name}"}, "argument": {"name": "name", "value": ""}})); + assert_eq!(r["result"]["completion"]["values"][99], "99"); + assert_eq!(s.tools().asked, [r#"Prompt("describe") part=br"#, r#"Resource("lib://parts/{name}") name="#]); + let bad_ref = "`ref` must be a prompt's {type: ref/prompt, name} or a resource's {type: ref/resource, uri}"; + let bad_argument = "`argument` must have a `name` and a `value`, both strings"; + for (params, message) in [ + (json!({"ref": {"type": "ref/prompt", "name": "summarise"}, "argument": {"name": "a", "value": ""}}), "unknown prompt `summarise`"), + (json!({"ref": {"type": "ref/tool", "name": "x"}, "argument": {"name": "a", "value": ""}}), bad_ref), + (json!({"ref": {"type": "ref/resource"}, "argument": {"name": "a", "value": ""}}), bad_ref), + (json!({"argument": {"name": "a", "value": ""}}), bad_ref), + (json!({"ref": {"type": "ref/prompt", "name": "describe"}, "argument": {"name": "part"}}), bad_argument), + (json!({"ref": {"type": "ref/prompt", "name": "describe"}}), bad_argument), + ] { + assert_eq!(complete(&mut s, params.clone())["error"], json!({"code": -32602, "message": message}), "{params}"); + } + assert_eq!(s.tools().asked.len(), 2, "a refused completion never reaches the app"); +} + +/// `Tools::call` runs right after the listing its arguments were checked against, every time, +/// whatever was listed before it; a refused call is listed and never run. +#[test] +fn every_call_runs_right_after_its_listing() { + let mut s = Server::new(info(), Echo::default()); + let call = |name: &str, args: Value| json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}}); + reply(&mut s, &json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})); + reply(&mut s, &call("echo", json!({"text": "a"}))); + reply(&mut s, &call("echo", json!({}))); + 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"]); +}