Skip to main content

ssg_mcp/
lib.rs

1// Copyright © 2023 - 2026 Static Site Generator (SSG). All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Model Context Protocol server over ssg's existing RPC registry.
5//!
6//! MCP is line-delimited JSON-RPC 2.0 on stdio. The protocol surface an
7//! editor actually needs is small — `initialize`, `tools/list`,
8//! `tools/call` — so this is hand-rolled rather than pulling in an SDK for
9//! three message shapes.
10//!
11//! Nothing here defines tools. `#[ssg_rpc]` already registers every callable
12//! with its input and output JSON Schema, and that registry is walked at
13//! runtime, so a tool added to ssg appears over MCP without a second
14//! declaration. A separate list would be a copy, and copies drift — the
15//! failure this codebase has hit repeatedly.
16//!
17//! Transport is deliberately separate from protocol: [`handle_line`] maps
18//! one request string to an optional response string and touches no I/O, so
19//! the whole surface is testable without spawning a process or a pipe.
20
21use serde_json::{json, Value};
22
23/// MCP revision this server implements.
24pub const PROTOCOL_VERSION: &str = "2024-11-05";
25
26/// JSON-RPC 2.0 error codes used here.
27const PARSE_ERROR: i64 = -32700;
28const INVALID_REQUEST: i64 = -32600;
29const METHOD_NOT_FOUND: i64 = -32601;
30
31fn error(id: Value, code: i64, message: &str) -> String {
32    json!({
33        "jsonrpc": "2.0",
34        "id": id,
35        "error": { "code": code, "message": message },
36    })
37    .to_string()
38}
39
40fn result(id: Value, payload: Value) -> String {
41    json!({ "jsonrpc": "2.0", "id": id, "result": payload }).to_string()
42}
43
44/// Every registered RPC, as an MCP tool definition.
45///
46/// The input schema is passed through verbatim: `schemars` already emits
47/// JSON Schema, which is what MCP's `inputSchema` is.
48#[must_use]
49pub fn tools() -> Vec<Value> {
50    ssg_rpc::dispatch::iter_descriptors()
51        .map(|d| {
52            let schema = (d.schema)();
53            json!({
54                "name": d.name,
55                "description": format!(
56                    "ssg RPC `{}`. Input and output schemas are generated \
57                     from the Rust types, not hand-written.",
58                    d.name
59                ),
60                "inputSchema": schema.input,
61            })
62        })
63        .collect()
64}
65
66/// Handle one JSON-RPC line.
67///
68/// Returns `None` for notifications, which by JSON-RPC 2.0 take no reply —
69/// answering one would desynchronise a client that is not expecting a
70/// message.
71#[must_use]
72pub fn handle_line(line: &str) -> Option<String> {
73    let req: Value = match serde_json::from_str(line) {
74        Ok(v) => v,
75        Err(_) => return Some(error(Value::Null, PARSE_ERROR, "invalid JSON")),
76    };
77
78    let method = req.get("method").and_then(Value::as_str).unwrap_or("");
79    // Absent `id` means notification. `null` is a real id, so the two are
80    // distinguished by presence, not by value.
81    let id = req.get("id").cloned();
82
83    if method.is_empty() {
84        let reply_id = id.unwrap_or(Value::Null);
85        return Some(error(reply_id, INVALID_REQUEST, "missing method"));
86    }
87
88    let Some(id) = id else {
89        // Notifications: `notifications/initialized` is the expected one.
90        return None;
91    };
92
93    match method {
94        "initialize" => Some(result(
95            id,
96            json!({
97                "protocolVersion": PROTOCOL_VERSION,
98                "capabilities": { "tools": { "listChanged": false } },
99                "serverInfo": {
100                    "name": "ssg-mcp",
101                    "version": env!("CARGO_PKG_VERSION"),
102                },
103            }),
104        )),
105        "ping" => Some(result(id, json!({}))),
106        "tools/list" => Some(result(id, json!({ "tools": tools() }))),
107        "tools/call" => Some(handle_call(id, &req)),
108        _ => Some(error(id, METHOD_NOT_FOUND, method)),
109    }
110}
111
112fn handle_call(id: Value, req: &Value) -> String {
113    let params = req.get("params");
114    let Some(name) = params.and_then(|p| p.get("name")).and_then(Value::as_str)
115    else {
116        return error(id, INVALID_REQUEST, "params.name is required");
117    };
118
119    // MCP omits `arguments` when a tool takes none; the RPC trampolines
120    // expect a JSON object either way.
121    let args = params
122        .and_then(|p| p.get("arguments"))
123        .cloned()
124        .unwrap_or_else(|| json!({}));
125
126    match ssg_rpc::dispatch(name, &args.to_string()) {
127        Ok(payload) => result(
128            id,
129            json!({
130                "content": [{ "type": "text", "text": payload }],
131                "isError": false,
132            }),
133        ),
134        // A tool that fails is not a protocol failure. MCP wants the error
135        // reported *inside* a successful result so the model can read it and
136        // adapt; a JSON-RPC error would surface as a broken server instead.
137        Err(e) => result(
138            id,
139            json!({
140                "content": [{ "type": "text", "text": e.to_string() }],
141                "isError": true,
142            }),
143        ),
144    }
145}
146
147/// Drive the protocol over a reader and writer.
148///
149/// Split out from `main` so the loop itself is exercised by tests with
150/// in-memory buffers rather than a spawned process.
151///
152/// # Errors
153///
154/// Returns any I/O error from the underlying reader or writer.
155pub fn serve<R: std::io::BufRead, W: std::io::Write>(
156    input: R,
157    mut output: W,
158) -> std::io::Result<()> {
159    for line in input.lines() {
160        let line = line?;
161        if line.trim().is_empty() {
162            continue;
163        }
164        if let Some(reply) = handle_line(&line) {
165            writeln!(output, "{reply}")?;
166            output.flush()?;
167        }
168    }
169    Ok(())
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    use schemars::JsonSchema;
177    use serde::{Deserialize, Serialize};
178    use ssg_rpc::{ssg_rpc, RpcError};
179
180    #[derive(Debug, Serialize, Deserialize, JsonSchema)]
181    struct EchoIn {
182        text: String,
183    }
184
185    #[derive(Debug, Serialize, Deserialize, JsonSchema)]
186    struct EchoOut {
187        text: String,
188    }
189
190    // The host binary decides what is registered; `inventory` only sees what
191    // is linked. ssg itself currently registers no production RPC, so a test
192    // that asserted "the registry is non-empty" would be asserting a fact
193    // about someone else's crate — and would pass or fail for reasons
194    // unrelated to this code. Registering a fixture here exercises the
195    // mapping itself, which is what this crate is responsible for.
196    #[ssg_rpc]
197    #[doc = "Test fixture: echoes its input back."]
198    fn ssg_mcp_test_echo(input: EchoIn) -> Result<EchoOut, RpcError> {
199        Ok(EchoOut { text: input.text })
200    }
201
202    fn call(line: &str) -> Value {
203        let out = handle_line(line).expect("expected a response");
204        serde_json::from_str(&out).expect("response must be JSON")
205    }
206
207    #[test]
208    fn initialize_reports_protocol_and_server() {
209        let v = call(r#"{"jsonrpc":"2.0","id":1,"method":"initialize"}"#);
210        assert_eq!(v["result"]["protocolVersion"], PROTOCOL_VERSION);
211        assert_eq!(v["result"]["serverInfo"]["name"], "ssg-mcp");
212        assert_eq!(v["id"], 1);
213    }
214
215    #[test]
216    fn tools_list_is_generated_from_the_rpc_registry() {
217        let v = call(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#);
218        let tools = v["result"]["tools"].as_array().expect("tools array");
219        let names: Vec<&str> =
220            tools.iter().filter_map(|t| t["name"].as_str()).collect();
221        assert!(
222            names.contains(&"ssg_mcp_test_echo"),
223            "the fixture RPC should surface as a tool: {names:?}"
224        );
225        // Every tool must carry a schema: a tool an agent cannot call
226        // correctly is worse than one that is absent.
227        for t in tools {
228            assert!(t["name"].is_string(), "tool without a name: {t}");
229            assert!(
230                t["inputSchema"].is_object(),
231                "tool without an inputSchema: {t}"
232            );
233        }
234        assert_eq!(tools.len(), ssg_rpc::registered_names().len());
235    }
236
237    /// The path that matters: a client lists tools, calls one, and reads a
238    /// result. Everything else is framing.
239    #[test]
240    fn tools_call_round_trips_through_the_rpc_dispatcher() {
241        let v = call(
242            r#"{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"ssg_mcp_test_echo","arguments":{"text":"hello"}}}"#,
243        );
244        assert_eq!(v["result"]["isError"], false, "call failed: {v}");
245        let text = v["result"]["content"][0]["text"]
246            .as_str()
247            .expect("text content");
248        let payload: Value =
249            serde_json::from_str(text).expect("tool output must be JSON");
250        assert_eq!(payload["text"], "hello");
251    }
252
253    #[test]
254    fn notifications_get_no_reply() {
255        // JSON-RPC 2.0: a request without `id` is a notification. Replying
256        // would desynchronise a client that is not reading one.
257        assert!(handle_line(
258            r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#
259        )
260        .is_none());
261    }
262
263    #[test]
264    fn null_id_is_an_id_not_a_notification() {
265        let v = call(r#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#);
266        assert!(v.get("result").is_some(), "null id must still be answered");
267    }
268
269    #[test]
270    fn unknown_method_is_method_not_found() {
271        let v = call(r#"{"jsonrpc":"2.0","id":3,"method":"nope"}"#);
272        assert_eq!(v["error"]["code"], METHOD_NOT_FOUND);
273    }
274
275    #[test]
276    fn malformed_json_is_a_parse_error() {
277        let v = call("{not json");
278        assert_eq!(v["error"]["code"], PARSE_ERROR);
279    }
280
281    #[test]
282    fn missing_method_is_an_invalid_request() {
283        let v = call(r#"{"jsonrpc":"2.0","id":4}"#);
284        assert_eq!(v["error"]["code"], INVALID_REQUEST);
285    }
286
287    #[test]
288    fn call_without_a_name_is_rejected() {
289        let v = call(
290            r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{}}"#,
291        );
292        assert_eq!(v["error"]["code"], INVALID_REQUEST);
293    }
294
295    #[test]
296    fn unknown_tool_reports_inside_the_result() {
297        // Not a JSON-RPC error: the model should see the failure and adapt,
298        // rather than the client treating the server as broken.
299        let v = call(
300            r#"{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"nope","arguments":{}}}"#,
301        );
302        assert!(v.get("error").is_none(), "should not be a protocol error");
303        assert_eq!(v["result"]["isError"], true);
304    }
305
306    /// A reader that fails mid-stream must surface the error, not truncate
307    /// the session silently. A server that stops answering looks identical
308    /// to one that finished.
309    #[test]
310    fn serve_propagates_a_reader_error() {
311        struct Failing;
312        impl std::io::Read for Failing {
313            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
314                Err(std::io::Error::other("reader exploded"))
315            }
316        }
317        let reader = std::io::BufReader::new(Failing);
318        let mut out = Vec::new();
319        let err = serve(reader, &mut out).expect_err("should propagate");
320        assert!(err.to_string().contains("reader exploded"));
321    }
322
323    /// Likewise a writer: if the client's pipe closes, the loop must stop
324    /// with an error rather than spin producing replies nobody reads.
325    #[test]
326    fn serve_propagates_a_writer_error() {
327        // Accepts the bytes, then fails the flush — so both trait methods
328        // are exercised, and the failure lands on the path `serve` actually
329        // takes after writing a reply.
330        struct Failing;
331        impl std::io::Write for Failing {
332            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
333                Ok(buf.len())
334            }
335            fn flush(&mut self) -> std::io::Result<()> {
336                Err(std::io::Error::other("writer exploded"))
337            }
338        }
339        let input = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n";
340        let err = serve(std::io::Cursor::new(input), Failing)
341            .expect_err("should propagate");
342        assert!(err.to_string().contains("writer exploded"));
343    }
344
345    #[test]
346    fn serve_answers_requests_and_skips_notifications() {
347        let input = concat!(
348            "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\"}\n",
349            "\n",
350            "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n",
351            "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"}\n",
352        );
353        let mut out = Vec::new();
354        serve(std::io::Cursor::new(input), &mut out).expect("serve");
355        let text = String::from_utf8(out).expect("utf8");
356        let lines: Vec<_> = text.lines().collect();
357        assert_eq!(lines.len(), 2, "one reply each, none for the notification");
358        assert!(lines[0].contains("protocolVersion"));
359        assert!(lines[1].contains("\"result\""));
360    }
361}