1use serde_json::{json, Value};
22
23pub const PROTOCOL_VERSION: &str = "2024-11-05";
25
26const 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#[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#[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 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 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 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 Err(e) => result(
138 id,
139 json!({
140 "content": [{ "type": "text", "text": e.to_string() }],
141 "isError": true,
142 }),
143 ),
144 }
145}
146
147pub 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 #[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 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 #[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 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 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 #[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 #[test]
326 fn serve_propagates_a_writer_error() {
327 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}