1mod 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
44const 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
53pub 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
79struct Server {
82 workspace: Workspace,
83}
84
85impl Server {
86 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 return msg
102 .get("id")
103 .map(|id| error(id.clone(), INVALID_REQUEST, "expected a request"));
104 };
105 let id = msg.get("id")?.clone();
107 let params = msg.get("params").cloned().unwrap_or(Value::Null);
108 Some(match self.dispatch(method, ¶ms) {
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 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}