Skip to main content

weirdnet_mcp/
lib.rs

1//! A small Model Context Protocol tools server.
2//!
3//! The crate speaks MCP's JSON-RPC 2.0 messages and knows nothing about HTTP or the app:
4//! a front end (an axum `POST /mcp` route, a gRPC bridge, a test) passes each decoded message
5//! to [`Server::handle`] with the caller's bearer token, and the app implements [`Tools::call`].
6//! The server is stateless, so it fits MCP's streamable HTTP transport with JSON responses.
7//!
8//! - [`ToolSpec`] / [`Param`]: static tool tables with `readOnlyHint`, `destructiveHint` and
9//!   `openWorldHint` annotations, and an auth flag that adds "Requires a bearer token." to the
10//!   description.
11//! - [`args`]: typed argument getters with uniform error messages.
12//! - [`stdio`]: the `<app>ctl mcp` loop that forwards stdio messages to a remote server.
13#![forbid(unsafe_code)]
14#![warn(missing_docs)]
15
16pub mod args;
17pub mod stdio;
18
19use serde_json::{Value, json};
20
21/// Protocol versions this server negotiates, newest first.
22pub const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
23
24/// JSON-RPC error codes used here.
25pub mod codes {
26    /// Invalid request.
27    pub const INVALID_REQUEST: i64 = -32600;
28    /// Method not found.
29    pub const METHOD_NOT_FOUND: i64 = -32601;
30    /// Invalid params (unknown tool).
31    pub const INVALID_PARAMS: i64 = -32602;
32    /// Internal error.
33    pub const INTERNAL: i64 = -32603;
34}
35
36/// JSON Schema type of a parameter.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum ParamType {
39    /// `string`
40    String,
41    /// `integer`
42    Integer,
43    /// `number`
44    Number,
45    /// `boolean`
46    Boolean,
47    /// `array` of strings
48    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/// One tool parameter.
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub struct Param {
66    /// Name.
67    pub name: &'static str,
68    /// Type.
69    pub ty: ParamType,
70    /// Description.
71    pub description: &'static str,
72    /// Required.
73    pub required: bool,
74}
75
76impl Param {
77    /// A required parameter.
78    pub const fn required(name: &'static str, ty: ParamType, description: &'static str) -> Self {
79        Self { name, ty, description, required: true }
80    }
81
82    /// An optional parameter.
83    pub const fn optional(name: &'static str, ty: ParamType, description: &'static str) -> Self {
84        Self { name, ty, description, required: false }
85    }
86}
87
88/// A tool.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub struct ToolSpec {
91    /// Name.
92    pub name: &'static str,
93    /// Description.
94    pub description: &'static str,
95    /// Parameters.
96    pub params: &'static [Param],
97    /// Needs the caller's bearer token.
98    pub auth: bool,
99    /// `readOnlyHint`.
100    pub read_only: bool,
101    /// `destructiveHint`.
102    pub destructive: bool,
103    /// `openWorldHint` (reaches outside the app's own data).
104    pub open_world: bool,
105}
106
107impl ToolSpec {
108    /// The `tools/list` entry.
109    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/// What `initialize` reports.
131#[derive(Clone, Debug, PartialEq, Eq)]
132pub struct ServerInfo {
133    /// Machine name, e.g. `taur`.
134    pub name: String,
135    /// Display name, e.g. `TAUR`.
136    pub title: String,
137    /// Server version.
138    pub version: String,
139    /// Instructions shown to the model.
140    pub instructions: String,
141}
142
143/// A tool failure, reported to the model as an `isError` result (not a JSON-RPC error).
144#[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
153/// The app side: runs a tool.
154pub trait Tools {
155    /// The tool table.
156    fn specs(&self) -> &[ToolSpec];
157
158    /// Runs `tool` with `args` for a caller presenting `token`. Auth, permission checks and
159    /// hiding internal errors are the app's.
160    fn call(&self, tool: &ToolSpec, args: &Value, token: Option<&str>) -> Result<Value, ToolError>;
161}
162
163/// A JSON-RPC success.
164pub fn rpc_ok(id: Value, result: Value) -> Value {
165    json!({"jsonrpc": "2.0", "id": id, "result": result})
166}
167
168/// A JSON-RPC error.
169pub fn rpc_err(id: Value, code: i64, msg: &str) -> Value {
170    json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": msg}})
171}
172
173/// A successful tool result: pretty JSON text plus `structuredContent`.
174pub 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
182/// A failed tool result.
183pub fn tool_error(text: &str) -> Value {
184    json!({"content": [{"type": "text", "text": text}], "isError": true})
185}
186
187/// The MCP server.
188pub struct Server<T> {
189    /// `initialize` data.
190    pub info: ServerInfo,
191    /// The app's tools.
192    pub tools: T,
193}
194
195impl<T: Tools> Server<T> {
196    /// A server.
197    pub fn new(info: ServerInfo, tools: T) -> Self {
198        Self { info, tools }
199    }
200
201    /// Handles one JSON-RPC message or batch. `None` means no response (notifications,
202    /// responses, or a batch of only those).
203    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;