Skip to main content

bynk/mcp/
mod.rs

1//! `bynk mcp` — a stdio Model Context Protocol server (#2466).
2//!
3//! The same read-only answers the VS Code language-model tools give (#2463), for
4//! any agent that speaks MCP: diagnostics, a symbol's type and definition, a
5//! unit's documentation, the project's architecture, a handler's wire contract,
6//! a diagnostic's explanation, a project check, and a search of the Book. Each answers in compact
7//! Markdown with `path:line:column` locations (1-based, relative to the
8//! workspace), and every result is capped with a note on how to ask for less.
9//!
10//! **Where it lives (DECISION A).** In the driver, calling `bynk-ide` and the
11//! project model directly rather than through `bynk-lsp`: an agent has no editor
12//! to hold a language server open, and a process that analyses on demand needs
13//! neither the LSP's transport nor its async runtime. The cost is that the
14//! answers come from the files on disk, not from unsaved buffers.
15//!
16//! **Read-only (DECISION C).** No tool writes, runs the compiler's emitter, or
17//! reaches the network, and a `file` argument cannot name anything outside the
18//! workspace root (`Workspace::resolve_file`), so an agent steered
19//! by text it read cannot point a tool at another project.
20//!
21//! **Transport (DECISION D).** Hand-written JSON-RPC 2.0 over newline-delimited
22//! stdio, ~100 lines (`Server::handle`), with no MCP SDK: the driver is
23//! synchronous and carries no async runtime, the protocol surface used here
24//! (`initialize`, `ping`, `tools/list`, `tools/call`) is small and stable, and
25//! an SDK would add a runtime and its dependency tree to every `bynk` install
26//! for it. See the ADR in `design/pending/bynk-mcp.md`.
27//!
28//! Standard output carries protocol messages only; anything for a human goes to
29//! standard error.
30
31mod render;
32mod tools;
33mod workspace;
34
35use bynk_driver::emsg;
36use std::io::{BufRead, Write};
37use std::path::Path;
38use std::process::ExitCode;
39
40use serde_json::{Value, json};
41
42use workspace::Workspace;
43
44/// The protocol revisions this server speaks, newest first. `initialize` answers
45/// with the client's if it is listed, else the newest.
46const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
47
48const PARSE_ERROR: i64 = -32700;
49const INVALID_REQUEST: i64 = -32600;
50const METHOD_NOT_FOUND: i64 = -32601;
51const INVALID_PARAMS: i64 = -32602;
52
53/// Run `bynk mcp` over the process's stdin and stdout, serving `path`.
54pub fn run(path: &Path) -> ExitCode {
55    let workspace = match Workspace::new(path) {
56        Ok(w) => w,
57        Err(e) => {
58            emsg!("bynk mcp: error: {e}");
59            return ExitCode::FAILURE;
60        }
61    };
62    let server = Server { workspace };
63    let stdin = std::io::stdin();
64    let mut stdout = std::io::stdout().lock();
65    for line in stdin.lock().lines() {
66        let Ok(line) = line else { break };
67        if line.trim().is_empty() {
68            continue;
69        }
70        if let Some(reply) = server.handle(&line)
71            && (writeln!(stdout, "{reply}").is_err() || stdout.flush().is_err())
72        {
73            break;
74        }
75    }
76    ExitCode::SUCCESS
77}
78
79/// The server's state: just the workspace it may read. Each call re-analyses
80/// from disk, so an edit an agent just made is always seen.
81struct Server {
82    workspace: Workspace,
83}
84
85impl Server {
86    /// One incoming line to its reply line, or `None` for a notification (which
87    /// is never answered).
88    fn handle(&self, line: &str) -> Option<String> {
89        let msg: Value = match serde_json::from_str(line) {
90            Ok(v) => v,
91            Err(e) => {
92                return Some(error(
93                    Value::Null,
94                    PARSE_ERROR,
95                    &format!("parse error: {e}"),
96                ));
97            }
98        };
99        let Some(method) = msg.get("method").and_then(Value::as_str) else {
100            // A response to a request we never sent, or not JSON-RPC at all.
101            return msg
102                .get("id")
103                .map(|id| error(id.clone(), INVALID_REQUEST, "expected a request"));
104        };
105        // A request without an `id` is a notification: handled, never answered.
106        let id = msg.get("id")?.clone();
107        let params = msg.get("params").cloned().unwrap_or(Value::Null);
108        Some(match self.dispatch(method, &params) {
109            Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }).to_string(),
110            Err((code, message)) => error(id, code, &message),
111        })
112    }
113
114    fn dispatch(&self, method: &str, params: &Value) -> Result<Value, (i64, String)> {
115        match method {
116            "initialize" => {
117                let asked = params.get("protocolVersion").and_then(Value::as_str);
118                let version = asked
119                    .and_then(|v| PROTOCOL_VERSIONS.iter().find(|p| **p == v))
120                    .unwrap_or(&PROTOCOL_VERSIONS[0]);
121                Ok(json!({
122                    "protocolVersion": version,
123                    "capabilities": { "tools": { "listChanged": false } },
124                    "serverInfo": { "name": "bynk", "version": env!("CARGO_PKG_VERSION") },
125                    "instructions": tools::INSTRUCTIONS,
126                }))
127            }
128            "ping" => Ok(json!({})),
129            "tools/list" => Ok(json!({ "tools": tools::definitions() })),
130            "tools/call" => {
131                let name = params
132                    .get("name")
133                    .and_then(Value::as_str)
134                    .ok_or((INVALID_PARAMS, "tools/call needs a tool `name`".to_string()))?;
135                let args = params.get("arguments").cloned().unwrap_or(json!({}));
136                if !args.is_object() {
137                    return Err((INVALID_PARAMS, "`arguments` must be an object".to_string()));
138                }
139                // A tool's own failure is a result the agent can read and act
140                // on (`isError`), not a protocol error.
141                match tools::call(&self.workspace, name, &args) {
142                    tools::Outcome::Unknown => {
143                        Err((INVALID_PARAMS, format!("unknown tool `{name}`")))
144                    }
145                    tools::Outcome::Text(text) => Ok(tool_result(&text, false)),
146                    tools::Outcome::Failed(text) => Ok(tool_result(&text, true)),
147                }
148            }
149            other => Err((
150                METHOD_NOT_FOUND,
151                format!("method `{other}` is not supported"),
152            )),
153        }
154    }
155}
156
157fn tool_result(text: &str, is_error: bool) -> Value {
158    json!({ "content": [{ "type": "text", "text": text }], "isError": is_error })
159}
160
161fn error(id: Value, code: i64, message: &str) -> String {
162    json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } }).to_string()
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    fn server() -> Server {
170        Server {
171            workspace: Workspace::new(&std::env::temp_dir()).unwrap(),
172        }
173    }
174
175    fn reply(server: &Server, msg: Value) -> Value {
176        serde_json::from_str(&server.handle(&msg.to_string()).expect("a reply")).unwrap()
177    }
178
179    #[test]
180    fn initialise_echoes_a_supported_version_else_the_newest() {
181        let s = server();
182        let r = reply(
183            &s,
184            json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05"}}),
185        );
186        assert_eq!(r["result"]["protocolVersion"], "2024-11-05");
187        let r = reply(
188            &s,
189            json!({"jsonrpc":"2.0","id":2,"method":"initialize","params":{"protocolVersion":"1999-01-01"}}),
190        );
191        assert_eq!(r["result"]["protocolVersion"], PROTOCOL_VERSIONS[0]);
192        assert_eq!(r["result"]["serverInfo"]["name"], "bynk");
193    }
194
195    #[test]
196    fn a_notification_gets_no_reply() {
197        let s = server();
198        let line = json!({"jsonrpc":"2.0","method":"notifications/initialized"}).to_string();
199        assert!(s.handle(&line).is_none());
200    }
201
202    #[test]
203    fn bad_input_is_a_protocol_error_with_the_request_id() {
204        let s = server();
205        let r = reply(&s, json!({"jsonrpc":"2.0","id":7,"method":"nope"}));
206        assert_eq!(r["id"], 7);
207        assert_eq!(r["error"]["code"], METHOD_NOT_FOUND);
208        let r: Value = serde_json::from_str(&s.handle("{not json").unwrap()).unwrap();
209        assert_eq!(r["error"]["code"], PARSE_ERROR);
210        assert_eq!(r["id"], Value::Null);
211    }
212
213    #[test]
214    fn a_tool_failure_is_a_result_not_a_protocol_error() {
215        let s = server();
216        let r = reply(
217            &s,
218            json!({"jsonrpc":"2.0","id":3,"method":"tools/call",
219                   "params":{"name":"bynk_describe_symbol","arguments":{}}}),
220        );
221        assert_eq!(r["result"]["isError"], true);
222        let r = reply(
223            &s,
224            json!({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"nope"}}),
225        );
226        assert_eq!(r["error"]["code"], INVALID_PARAMS);
227    }
228
229    #[test]
230    fn lists_every_tool_with_a_schema() {
231        let s = server();
232        let r = reply(&s, json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}));
233        let tools = r["result"]["tools"].as_array().unwrap();
234        assert_eq!(tools.len(), 8);
235        for t in tools {
236            assert_eq!(t["inputSchema"]["type"], "object", "{t}");
237            assert_eq!(t["annotations"]["readOnlyHint"], true, "{t}");
238        }
239    }
240}