#![forbid(unsafe_code)]
#![warn(missing_docs)]
pub mod args;
pub mod stdio;
use serde_json::{Value, json};
pub const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
pub mod codes {
pub const INVALID_REQUEST: i64 = -32600;
pub const METHOD_NOT_FOUND: i64 = -32601;
pub const INVALID_PARAMS: i64 = -32602;
pub const INTERNAL: i64 = -32603;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ParamType {
String,
Integer,
Number,
Boolean,
StringArray,
}
impl ParamType {
fn schema(self) -> Value {
match self {
Self::String => json!({"type": "string"}),
Self::Integer => json!({"type": "integer"}),
Self::Number => json!({"type": "number"}),
Self::Boolean => json!({"type": "boolean"}),
Self::StringArray => json!({"type": "array", "items": {"type": "string"}}),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Param {
pub name: &'static str,
pub ty: ParamType,
pub description: &'static str,
pub required: bool,
}
impl Param {
pub const fn required(name: &'static str, ty: ParamType, description: &'static str) -> Self {
Self { name, ty, description, required: true }
}
pub const fn optional(name: &'static str, ty: ParamType, description: &'static str) -> Self {
Self { name, ty, description, required: false }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ToolSpec {
pub name: &'static str,
pub description: &'static str,
pub params: &'static [Param],
pub auth: bool,
pub read_only: bool,
pub destructive: bool,
pub open_world: bool,
}
impl ToolSpec {
pub fn to_json(&self) -> Value {
let mut props = serde_json::Map::new();
let mut required = vec![];
for p in self.params {
let mut schema = p.ty.schema();
schema["description"] = json!(p.description);
props.insert(p.name.to_string(), schema);
if p.required {
required.push(p.name);
}
}
let description = if self.auth { format!("{} Requires a bearer token.", self.description) } else { self.description.to_string() };
json!({
"name": self.name,
"description": description,
"inputSchema": {"type": "object", "properties": props, "required": required},
"annotations": {"readOnlyHint": self.read_only, "destructiveHint": self.destructive, "openWorldHint": self.open_world},
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServerInfo {
pub name: String,
pub title: String,
pub version: String,
pub instructions: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ToolError(pub String);
impl<E: std::fmt::Display> From<E> for ToolError {
fn from(e: E) -> Self {
Self(e.to_string())
}
}
pub trait Tools {
fn specs(&self) -> &[ToolSpec];
fn call(&self, tool: &ToolSpec, args: &Value, token: Option<&str>) -> Result<Value, ToolError>;
}
pub fn rpc_ok(id: Value, result: Value) -> Value {
json!({"jsonrpc": "2.0", "id": id, "result": result})
}
pub fn rpc_err(id: Value, code: i64, msg: &str) -> Value {
json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": msg}})
}
pub fn tool_ok(v: &Value) -> Value {
json!({
"content": [{"type": "text", "text": serde_json::to_string_pretty(v).unwrap_or_default()}],
"structuredContent": if v.is_object() { v.clone() } else { json!({"result": v}) },
"isError": false,
})
}
pub fn tool_error(text: &str) -> Value {
json!({"content": [{"type": "text", "text": text}], "isError": true})
}
pub struct Server<T> {
pub info: ServerInfo,
pub tools: T,
}
impl<T: Tools> Server<T> {
pub fn new(info: ServerInfo, tools: T) -> Self {
Self { info, tools }
}
pub fn handle(&self, token: Option<&str>, msg: Value) -> Option<Value> {
if let Value::Array(batch) = msg {
let out: Vec<Value> = batch.into_iter().filter_map(|m| self.handle(token, m)).collect();
return (!out.is_empty()).then_some(Value::Array(out));
}
let id = msg.get("id").cloned();
let method = msg.get("method").and_then(Value::as_str);
let (Some(id), Some(method)) = (id, method) else {
return if msg.get("method").is_some() || msg.get("result").is_some() {
None
} else {
Some(rpc_err(Value::Null, codes::INVALID_REQUEST, "invalid request"))
};
};
let params = msg.get("params").cloned().unwrap_or(json!({}));
Some(match method {
"initialize" => {
let asked = params["protocolVersion"].as_str().unwrap_or("");
let v = if PROTOCOL_VERSIONS.contains(&asked) { asked } else { PROTOCOL_VERSIONS[0] };
rpc_ok(
id,
json!({
"protocolVersion": v,
"capabilities": {"tools": {"listChanged": false}},
"serverInfo": {"name": self.info.name, "title": self.info.title, "version": self.info.version},
"instructions": self.info.instructions,
}),
)
}
"ping" => rpc_ok(id, json!({})),
"tools/list" => rpc_ok(id, json!({"tools": self.tools.specs().iter().map(ToolSpec::to_json).collect::<Vec<_>>()})),
"tools/call" => {
let name = params["name"].as_str().unwrap_or("");
let Some(tool) = self.tools.specs().iter().find(|t| t.name == name) else {
return Some(rpc_err(id, codes::INVALID_PARAMS, &format!("unknown tool: {name}")));
};
let args = params.get("arguments").cloned().unwrap_or(json!({}));
match self.tools.call(tool, &args, token) {
Ok(v) => rpc_ok(id, tool_ok(&v)),
Err(ToolError(text)) => rpc_ok(id, tool_error(&text)),
}
}
_ => rpc_err(id, codes::METHOD_NOT_FOUND, &format!("method not found: {method}")),
})
}
}
#[cfg(test)]
mod tests;