1#![forbid(unsafe_code)]
14#![warn(missing_docs)]
15
16pub mod args;
17pub mod stdio;
18
19use serde_json::{Value, json};
20
21pub const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
23
24pub mod codes {
26 pub const INVALID_REQUEST: i64 = -32600;
28 pub const METHOD_NOT_FOUND: i64 = -32601;
30 pub const INVALID_PARAMS: i64 = -32602;
32 pub const INTERNAL: i64 = -32603;
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum ParamType {
39 String,
41 Integer,
43 Number,
45 Boolean,
47 StringArray,
49}
50
51impl ParamType {
52 fn schema(self) -> Value {
53 match self {
54 Self::String => json!({"type": "string"}),
55 Self::Integer => json!({"type": "integer"}),
56 Self::Number => json!({"type": "number"}),
57 Self::Boolean => json!({"type": "boolean"}),
58 Self::StringArray => json!({"type": "array", "items": {"type": "string"}}),
59 }
60 }
61}
62
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub struct Param {
66 pub name: &'static str,
68 pub ty: ParamType,
70 pub description: &'static str,
72 pub required: bool,
74}
75
76impl Param {
77 pub const fn required(name: &'static str, ty: ParamType, description: &'static str) -> Self {
79 Self { name, ty, description, required: true }
80 }
81
82 pub const fn optional(name: &'static str, ty: ParamType, description: &'static str) -> Self {
84 Self { name, ty, description, required: false }
85 }
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub struct ToolSpec {
91 pub name: &'static str,
93 pub description: &'static str,
95 pub params: &'static [Param],
97 pub auth: bool,
99 pub read_only: bool,
101 pub destructive: bool,
103 pub open_world: bool,
105}
106
107impl ToolSpec {
108 pub fn to_json(&self) -> Value {
110 let mut props = serde_json::Map::new();
111 let mut required = vec![];
112 for p in self.params {
113 let mut schema = p.ty.schema();
114 schema["description"] = json!(p.description);
115 props.insert(p.name.to_string(), schema);
116 if p.required {
117 required.push(p.name);
118 }
119 }
120 let description = if self.auth { format!("{} Requires a bearer token.", self.description) } else { self.description.to_string() };
121 json!({
122 "name": self.name,
123 "description": description,
124 "inputSchema": {"type": "object", "properties": props, "required": required},
125 "annotations": {"readOnlyHint": self.read_only, "destructiveHint": self.destructive, "openWorldHint": self.open_world},
126 })
127 }
128}
129
130#[derive(Clone, Debug, PartialEq, Eq)]
132pub struct ServerInfo {
133 pub name: String,
135 pub title: String,
137 pub version: String,
139 pub instructions: String,
141}
142
143#[derive(Clone, Debug, PartialEq, Eq)]
145pub struct ToolError(pub String);
146
147impl<E: std::fmt::Display> From<E> for ToolError {
148 fn from(e: E) -> Self {
149 Self(e.to_string())
150 }
151}
152
153pub trait Tools {
155 fn specs(&self) -> &[ToolSpec];
157
158 fn call(&self, tool: &ToolSpec, args: &Value, token: Option<&str>) -> Result<Value, ToolError>;
161}
162
163pub fn rpc_ok(id: Value, result: Value) -> Value {
165 json!({"jsonrpc": "2.0", "id": id, "result": result})
166}
167
168pub fn rpc_err(id: Value, code: i64, msg: &str) -> Value {
170 json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": msg}})
171}
172
173pub fn tool_ok(v: &Value) -> Value {
175 json!({
176 "content": [{"type": "text", "text": serde_json::to_string_pretty(v).unwrap_or_default()}],
177 "structuredContent": if v.is_object() { v.clone() } else { json!({"result": v}) },
178 "isError": false,
179 })
180}
181
182pub fn tool_error(text: &str) -> Value {
184 json!({"content": [{"type": "text", "text": text}], "isError": true})
185}
186
187pub struct Server<T> {
189 pub info: ServerInfo,
191 pub tools: T,
193}
194
195impl<T: Tools> Server<T> {
196 pub fn new(info: ServerInfo, tools: T) -> Self {
198 Self { info, tools }
199 }
200
201 pub fn handle(&self, token: Option<&str>, msg: Value) -> Option<Value> {
204 if let Value::Array(batch) = msg {
205 let out: Vec<Value> = batch.into_iter().filter_map(|m| self.handle(token, m)).collect();
206 return (!out.is_empty()).then_some(Value::Array(out));
207 }
208 let id = msg.get("id").cloned();
209 let method = msg.get("method").and_then(Value::as_str);
210 let (Some(id), Some(method)) = (id, method) else {
211 return if msg.get("method").is_some() || msg.get("result").is_some() {
212 None
213 } else {
214 Some(rpc_err(Value::Null, codes::INVALID_REQUEST, "invalid request"))
215 };
216 };
217 let params = msg.get("params").cloned().unwrap_or(json!({}));
218 Some(match method {
219 "initialize" => {
220 let asked = params["protocolVersion"].as_str().unwrap_or("");
221 let v = if PROTOCOL_VERSIONS.contains(&asked) { asked } else { PROTOCOL_VERSIONS[0] };
222 rpc_ok(
223 id,
224 json!({
225 "protocolVersion": v,
226 "capabilities": {"tools": {"listChanged": false}},
227 "serverInfo": {"name": self.info.name, "title": self.info.title, "version": self.info.version},
228 "instructions": self.info.instructions,
229 }),
230 )
231 }
232 "ping" => rpc_ok(id, json!({})),
233 "tools/list" => rpc_ok(id, json!({"tools": self.tools.specs().iter().map(ToolSpec::to_json).collect::<Vec<_>>()})),
234 "tools/call" => {
235 let name = params["name"].as_str().unwrap_or("");
236 let Some(tool) = self.tools.specs().iter().find(|t| t.name == name) else {
237 return Some(rpc_err(id, codes::INVALID_PARAMS, &format!("unknown tool: {name}")));
238 };
239 let args = params.get("arguments").cloned().unwrap_or(json!({}));
240 match self.tools.call(tool, &args, token) {
241 Ok(v) => rpc_ok(id, tool_ok(&v)),
242 Err(ToolError(text)) => rpc_ok(id, tool_error(&text)),
243 }
244 }
245 _ => rpc_err(id, codes::METHOD_NOT_FOUND, &format!("method not found: {method}")),
246 })
247 }
248}
249
250#[cfg(test)]
251mod tests;