|
| 1 | +//! MCP server over stdio, started by `rocco mcp`. |
| 2 | +//! |
| 3 | +//! Written from the Model Context Protocol specification, revision 2025-06-18: |
| 4 | +//! the initialize/initialized lifecycle with version negotiation, `ping`, |
| 5 | +//! `tools/list`, `tools/call` and JSON-RPC 2.0 errors, one message per line. |
| 6 | +//! The forge-mcp copy this replaces is not the reference: its Codex-adapted |
| 7 | +//! client framing is not ported and its 2026-07-28 stateless era is not served. |
| 8 | +//! |
| 9 | +//! Bounds: a frame over `wire::MAX_FRAME_BYTES` (1 MiB) is discarded as it |
| 10 | +//! streams in and answered with `-32600`; the server keeps serving. Pending work |
| 11 | +//! is exactly one frame, read, answered, then the next is read, so a slow peer |
| 12 | +//! can never queue anything. End of input ends the loop with exit code 0. |
| 13 | +
|
| 14 | +mod tools; |
| 15 | +mod wire; |
| 16 | + |
| 17 | +use lgwks_std::json::{self, Map, Value, json}; |
| 18 | +use std::io::{self, BufRead, Write}; |
| 19 | + |
| 20 | +/// Newest revision served; the reply to an initialize that names an unknown one. |
| 21 | +const LATEST_VERSION: &str = "2025-06-18"; |
| 22 | +/// Revisions whose lifecycle and `tools/*` shapes this server answers, newest first. |
| 23 | +const SUPPORTED_VERSIONS: [&str; 3] = [LATEST_VERSION, "2025-03-26", "2024-11-05"]; |
| 24 | +/// Reply text for a request that needs a completed initialize. |
| 25 | +const NOT_INITIALIZED: &str = "server not initialized: send initialize first"; |
| 26 | + |
| 27 | +/// Serves MCP until the reader reaches end of input. |
| 28 | +pub(crate) fn serve<R: BufRead, W: Write>(reader: R, writer: W) -> io::Result<()> { |
| 29 | + serve_bounded(reader, writer, wire::MAX_FRAME_BYTES) |
| 30 | +} |
| 31 | + |
| 32 | +/// `serve` with an explicit frame bound, so a unit test can use a small one. |
| 33 | +fn serve_bounded<R: BufRead, W: Write>(mut reader: R, mut writer: W, max: usize) -> io::Result<()> { |
| 34 | + let mut session = Session::default(); |
| 35 | + loop { |
| 36 | + let reply = match wire::read_frame(&mut reader, max)? { |
| 37 | + wire::Frame::End => return Ok(()), |
| 38 | + wire::Frame::Oversized => Some(wire::error( |
| 39 | + &Value::Null, |
| 40 | + wire::INVALID_REQUEST, |
| 41 | + "frame exceeds the size limit and was discarded", |
| 42 | + )), |
| 43 | + wire::Frame::Line(bytes) => session.handle(&bytes), |
| 44 | + }; |
| 45 | + if let Some(value) = reply { |
| 46 | + writer.write_all(&wire::encode(&value))?; |
| 47 | + writer.flush()?; |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +/// Per-connection state: the whole lifecycle is one flag. |
| 53 | +#[derive(Default)] |
| 54 | +struct Session { |
| 55 | + /// Set when an initialize request has been answered. |
| 56 | + initialized: bool, |
| 57 | +} |
| 58 | + |
| 59 | +impl Session { |
| 60 | + /// Maps one frame to its reply; `None` when JSON-RPC calls for silence. |
| 61 | + fn handle(&mut self, bytes: &[u8]) -> Option<Value> { |
| 62 | + match json::from_slice::<Value>(bytes) { |
| 63 | + Err(error) => Some(wire::error( |
| 64 | + &Value::Null, |
| 65 | + wire::PARSE_ERROR, |
| 66 | + &format!("parse error: {error}"), |
| 67 | + )), |
| 68 | + Ok(Value::Object(frame)) => self.handle_object(&frame), |
| 69 | + Ok(_) => Some(wire::error( |
| 70 | + &Value::Null, |
| 71 | + wire::INVALID_REQUEST, |
| 72 | + "a frame must be one JSON object; batches are not supported", |
| 73 | + )), |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + /// Validates one JSON-RPC object and routes it. |
| 78 | + fn handle_object(&mut self, frame: &Map<String, Value>) -> Option<Value> { |
| 79 | + let id = match frame.get("id") { |
| 80 | + None => None, |
| 81 | + Some(value) if is_valid_id(value) => Some(value), |
| 82 | + Some(_) => { |
| 83 | + return Some(wire::error( |
| 84 | + &Value::Null, |
| 85 | + wire::INVALID_REQUEST, |
| 86 | + "id must be a string or an integer", |
| 87 | + )); |
| 88 | + } |
| 89 | + }; |
| 90 | + let reply_id = match id { |
| 91 | + Some(value) => value, |
| 92 | + None => &Value::Null, |
| 93 | + }; |
| 94 | + if frame.get("jsonrpc").and_then(Value::as_str) != Some("2.0") { |
| 95 | + return Some(wire::error( |
| 96 | + reply_id, |
| 97 | + wire::INVALID_REQUEST, |
| 98 | + "jsonrpc must be \"2.0\"", |
| 99 | + )); |
| 100 | + } |
| 101 | + let Some(method_value) = frame.get("method") else { |
| 102 | + if frame.contains_key("result") || frame.contains_key("error") { |
| 103 | + return None; |
| 104 | + } |
| 105 | + return Some(wire::error( |
| 106 | + reply_id, |
| 107 | + wire::INVALID_REQUEST, |
| 108 | + "method is required", |
| 109 | + )); |
| 110 | + }; |
| 111 | + let Some(method) = method_value.as_str() else { |
| 112 | + return Some(wire::error( |
| 113 | + reply_id, |
| 114 | + wire::INVALID_REQUEST, |
| 115 | + "method must be a string", |
| 116 | + )); |
| 117 | + }; |
| 118 | + let params = match frame.get("params") { |
| 119 | + None => None, |
| 120 | + Some(value) => match value.as_object() { |
| 121 | + Some(map) => Some(map), |
| 122 | + None => { |
| 123 | + return id.map(|request_id| { |
| 124 | + wire::error(request_id, wire::INVALID_PARAMS, "params must be an object") |
| 125 | + }); |
| 126 | + } |
| 127 | + }, |
| 128 | + }; |
| 129 | + let request_id = id?; |
| 130 | + Some(self.request(request_id, method, params)) |
| 131 | + } |
| 132 | + |
| 133 | + /// Answers one request. |
| 134 | + fn request(&mut self, id: &Value, method: &str, params: Option<&Map<String, Value>>) -> Value { |
| 135 | + match method { |
| 136 | + "ping" => wire::result(id, json!({})), |
| 137 | + "initialize" => self.initialize(id, params), |
| 138 | + "tools/list" | "tools/call" if !self.initialized => { |
| 139 | + wire::error(id, wire::INVALID_REQUEST, NOT_INITIALIZED) |
| 140 | + } |
| 141 | + "tools/list" => tools_list(id, params), |
| 142 | + "tools/call" => tools_call(id, params), |
| 143 | + _ => wire::error(id, wire::METHOD_NOT_FOUND, "method not found"), |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + /// The lifecycle handshake: negotiate a revision and open the session. |
| 148 | + fn initialize(&mut self, id: &Value, params: Option<&Map<String, Value>>) -> Value { |
| 149 | + if self.initialized { |
| 150 | + return wire::error(id, wire::INVALID_REQUEST, "already initialized"); |
| 151 | + } |
| 152 | + let Some(requested) = params |
| 153 | + .and_then(|map| map.get("protocolVersion")) |
| 154 | + .and_then(Value::as_str) |
| 155 | + else { |
| 156 | + return wire::error( |
| 157 | + id, |
| 158 | + wire::INVALID_PARAMS, |
| 159 | + "initialize requires params.protocolVersion as a string", |
| 160 | + ); |
| 161 | + }; |
| 162 | + let negotiated = match SUPPORTED_VERSIONS |
| 163 | + .iter() |
| 164 | + .copied() |
| 165 | + .find(|version| *version == requested) |
| 166 | + { |
| 167 | + Some(version) => version, |
| 168 | + None => LATEST_VERSION, |
| 169 | + }; |
| 170 | + self.initialized = true; |
| 171 | + wire::result( |
| 172 | + id, |
| 173 | + json!({ |
| 174 | + "protocolVersion": negotiated, |
| 175 | + "capabilities": { "tools": { "listChanged": false } }, |
| 176 | + "serverInfo": { |
| 177 | + "name": "larry", |
| 178 | + "title": "Larry", |
| 179 | + "version": env!("CARGO_PKG_VERSION") |
| 180 | + }, |
| 181 | + "instructions": "Hand Larry a typed task with larry_submit_task." |
| 182 | + }), |
| 183 | + ) |
| 184 | + } |
| 185 | +} |
| 186 | + |
| 187 | +/// Whether `value` is a legal request id: a string or an integer, never null. |
| 188 | +fn is_valid_id(value: &Value) -> bool { |
| 189 | + value.is_string() || value.is_i64() || value.is_u64() |
| 190 | +} |
| 191 | + |
| 192 | +/// `tools/list`: the declared tools; no cursor is ever issued, so none is valid. |
| 193 | +fn tools_list(id: &Value, params: Option<&Map<String, Value>>) -> Value { |
| 194 | + if params.is_some_and(|map| map.contains_key("cursor")) { |
| 195 | + return wire::error(id, wire::INVALID_PARAMS, "invalid cursor"); |
| 196 | + } |
| 197 | + wire::result(id, tools::list()) |
| 198 | +} |
| 199 | + |
| 200 | +/// `tools/call`: an unknown tool or a malformed call is a protocol error; a |
| 201 | +/// tool's own failure comes back as a result with `isError` true. |
| 202 | +fn tools_call(id: &Value, params: Option<&Map<String, Value>>) -> Value { |
| 203 | + let Some(name) = params |
| 204 | + .and_then(|map| map.get("name")) |
| 205 | + .and_then(Value::as_str) |
| 206 | + else { |
| 207 | + return wire::error( |
| 208 | + id, |
| 209 | + wire::INVALID_PARAMS, |
| 210 | + "tools/call requires params.name as a string", |
| 211 | + ); |
| 212 | + }; |
| 213 | + let none = Map::new(); |
| 214 | + let arguments = match params.and_then(|map| map.get("arguments")) { |
| 215 | + None => &none, |
| 216 | + Some(value) => match value.as_object() { |
| 217 | + Some(map) => map, |
| 218 | + None => { |
| 219 | + return wire::error( |
| 220 | + id, |
| 221 | + wire::INVALID_PARAMS, |
| 222 | + "params.arguments must be an object", |
| 223 | + ); |
| 224 | + } |
| 225 | + }, |
| 226 | + }; |
| 227 | + match tools::call(name, arguments) { |
| 228 | + Some(outcome) => wire::result(id, outcome), |
| 229 | + None => wire::error(id, wire::INVALID_PARAMS, "unknown tool"), |
| 230 | + } |
| 231 | +} |
| 232 | + |
| 233 | +#[cfg(test)] |
| 234 | +mod tests { |
| 235 | + use super::serve_bounded; |
| 236 | + use lgwks_std::json::{self, Value}; |
| 237 | + use std::io::Cursor; |
| 238 | + |
| 239 | + /// Serves `input` and returns every reply line parsed. |
| 240 | + fn replies(input: &str, max: usize) -> Result<Vec<Value>, Box<dyn std::error::Error>> { |
| 241 | + let mut out = Vec::new(); |
| 242 | + serve_bounded(Cursor::new(input.as_bytes().to_vec()), &mut out, max)?; |
| 243 | + let mut parsed = Vec::new(); |
| 244 | + for line in String::from_utf8(out)?.lines() { |
| 245 | + parsed.push(json::from_str(line)?); |
| 246 | + } |
| 247 | + Ok(parsed) |
| 248 | + } |
| 249 | + |
| 250 | + /// The lifecycle, in order, with the notification silent. |
| 251 | + #[test] |
| 252 | + fn initialize_then_list_then_ping() -> Result<(), Box<dyn std::error::Error>> { |
| 253 | + let input = concat!( |
| 254 | + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#, |
| 255 | + "\n", |
| 256 | + r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, |
| 257 | + "\n", |
| 258 | + r#"{"jsonrpc":"2.0","id":"a","method":"tools/list"}"#, |
| 259 | + "\n", |
| 260 | + r#"{"jsonrpc":"2.0","id":3,"method":"ping"}"#, |
| 261 | + "\n", |
| 262 | + ); |
| 263 | + let got = replies(input, 1_048_576)?; |
| 264 | + assert_eq!(got.len(), 3, "the notification gets no reply"); |
| 265 | + assert_eq!( |
| 266 | + got[0]["result"]["protocolVersion"], "2025-06-18", |
| 267 | + "version echoed" |
| 268 | + ); |
| 269 | + assert_eq!(got[1]["id"], "a", "string ids come back as strings"); |
| 270 | + assert_eq!( |
| 271 | + got[1]["result"]["tools"][0]["name"], "larry_submit_task", |
| 272 | + "tool listed" |
| 273 | + ); |
| 274 | + assert_eq!(got[2]["result"], json::json!({}), "ping is an empty result"); |
| 275 | + Ok(()) |
| 276 | + } |
| 277 | + |
| 278 | + /// A tool request before initialize is refused, an oversized line is |
| 279 | + /// refused, and the server keeps serving after both. |
| 280 | + #[test] |
| 281 | + fn pre_initialize_and_oversized_are_refused_then_serving_continues() |
| 282 | + -> Result<(), Box<dyn std::error::Error>> { |
| 283 | + let input = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}\n\ |
| 284 | + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\ |
| 285 | + {\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"}\n"; |
| 286 | + let got = replies(input, 64)?; |
| 287 | + assert_eq!(got[0]["error"]["code"], -32600, "not initialized"); |
| 288 | + assert_eq!(got[1]["error"]["code"], -32600, "oversized"); |
| 289 | + assert_eq!(got[2]["id"], 2, "still serving"); |
| 290 | + Ok(()) |
| 291 | + } |
| 292 | +} |
0 commit comments