Skip to main content

claude_code_agent/
mcp.rs

1//! In-process (SDK) MCP servers — Rust functions exposed to Claude as tools.
2//!
3//! The CLI is told about each server with
4//! `--mcp-config {"mcpServers":{"<name>":{"type":"sdk","name":"<name>"}}}`
5//! (or later with `Session::set_mcp_servers`) and then forwards every
6//! JSON-RPC message for it as an `mcp_message` control request; the session
7//! answers with `{"mcp_response": <JSON-RPC response>}`.
8//! Claude sees the tools as `mcp__<server>__<tool>`.
9//!
10//! Source: `claude_agent_sdk` 0.1.48 `transport/subprocess_cli.py:240–260`,
11//!         _internal/query.py:305–320, :394–500; binary sdk MCP config schema
12use std::fmt;
13use std::future::Future;
14use std::pin::Pin;
15use std::sync::Arc;
16use std::time::Duration;
17
18use dashmap::DashMap;
19use serde_json::{json, Value};
20use tokio::sync::oneshot;
21
22use crate::protocol::ToolDef;
23
24type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
25type ToolFn = Arc<dyn Fn(Value, ToolContext) -> BoxFuture<ToolResult> + Send + Sync>;
26
27const PROTOCOL_VERSION: &str = "2024-11-05";
28/// JSON-RPC error code for a request the client cancelled.
29const REQUEST_CANCELLED: i64 = -32800;
30
31/// One content item of a tool result. Source: MCP `CallToolResult.content`
32#[derive(Debug, Clone, PartialEq, serde::Serialize)]
33#[serde(tag = "type", rename_all = "snake_case")]
34pub enum ToolContent {
35    /// Plain text.
36    Text {
37        /// The text.
38        text: String,
39    },
40    /// Base64 image data, e.g. `mime_type` "image/png".
41    Image {
42        /// Base64-encoded image bytes.
43        data: String,
44        /// Image MIME type (`mimeType`).
45        #[serde(rename = "mimeType")]
46        mime_type: String,
47    },
48    /// An embedded resource: `{"uri", "mimeType", "text" | "blob"}`.
49    Resource {
50        /// The resource object.
51        resource: Value,
52    },
53    /// A link to a resource: `{"uri", "name", …}` fields.
54    ResourceLink(serde_json::Map<String, Value>),
55}
56
57/// Result of a tool call, returned to the model.
58#[derive(Debug, Clone, PartialEq)]
59pub struct ToolResult {
60    /// Content returned to the model.
61    pub content: Vec<ToolContent>,
62    /// Machine-readable output matching `ToolDef::output_schema`.
63    pub structured: Option<Value>,
64    /// The call failed (`isError`).
65    pub is_error: bool,
66}
67
68impl ToolResult {
69    /// A single text item.
70    pub fn text(text: impl Into<String>) -> Self {
71        Self::content(vec![ToolContent::Text { text: text.into() }])
72    }
73
74    /// A text item marked as an error.
75    pub fn error(text: impl Into<String>) -> Self {
76        Self { is_error: true, ..Self::text(text) }
77    }
78
79    /// A base64 image.
80    pub fn image(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
81        Self::content(vec![ToolContent::Image { data: data.into(), mime_type: mime_type.into() }])
82    }
83
84    /// A successful result with these items.
85    #[must_use]
86    pub fn content(content: Vec<ToolContent>) -> Self {
87        Self { content, structured: None, is_error: false }
88    }
89
90    /// Strings are passed through verbatim, anything else as JSON text.
91    #[must_use]
92    pub fn from_value(value: Value) -> Self {
93        match value {
94            Value::String(s) => Self::text(s),
95            other => Self::text(other.to_string()),
96        }
97    }
98
99    /// Attach structured output (also sent to the model as JSON text when
100    /// the result has no content).
101    #[must_use]
102    pub fn with_structured(mut self, value: Value) -> Self {
103        self.structured = Some(value);
104        self
105    }
106
107    fn into_wire(self) -> Value {
108        let content = if self.content.is_empty() {
109            let text = self.structured.as_ref().map(Value::to_string).unwrap_or_default();
110            vec![ToolContent::Text { text }]
111        } else {
112            self.content
113        };
114        let mut body = json!({ "content": content });
115        if let Some(s) = self.structured {
116            body["structuredContent"] = s;
117        }
118        if self.is_error {
119            body["isError"] = Value::Bool(true);
120        }
121        body
122    }
123}
124
125/// What a tool handler knows about its call besides the arguments.
126#[derive(Debug, Clone, Default)]
127pub struct ToolContext {
128    /// The model's `tool_use` id for this call.
129    pub tool_use_id: Option<String>,
130    /// The session's id: `claudecode/sessionId` in `_meta` when the CLI
131    /// sends it (behind a CLI feature flag), else the id the session last
132    /// reported. `None` only outside a session (`SdkMcpServer::handle`) or
133    /// before the CLI's first `system` frame.
134    pub session_id: Option<String>,
135    /// The request's raw `_meta` object.
136    pub meta: Value,
137}
138
139impl ToolContext {
140    fn from_params(params: Option<&Value>, session_id: Option<String>) -> Self {
141        let meta = params.and_then(|p| p.get("_meta")).cloned().unwrap_or(Value::Null);
142        let field = |k: &str| meta.get(k).and_then(Value::as_str).map(str::to_owned);
143        Self {
144            tool_use_id: field("claudecode/toolUseId"),
145            session_id: field("claudecode/sessionId").or(session_id),
146            meta,
147        }
148    }
149}
150
151/// A tool definition plus the async function that runs it.
152/// `#[claude_tool]` generates `<fn>_tool() -> SdkTool`.
153///
154/// A call the CLI cancels (`notifications/cancelled`, e.g. after an
155/// interrupt) drops the handler's future, so `.await` points are where a
156/// handler stops.
157#[derive(Clone)]
158pub struct SdkTool {
159    /// Name, description and schemas sent to the CLI.
160    pub def: ToolDef,
161    handler: ToolFn,
162}
163
164impl fmt::Debug for SdkTool {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        f.debug_struct("SdkTool").field("name", &self.def.name).finish_non_exhaustive()
167    }
168}
169
170impl SdkTool {
171    /// `handler` receives the raw `arguments` object of the tool call.
172    pub fn new<F, Fut>(def: ToolDef, handler: F) -> Self
173    where
174        F: Fn(Value) -> Fut + Send + Sync + 'static,
175        Fut: Future<Output = ToolResult> + Send + 'static,
176    {
177        Self { def, handler: Arc::new(move |args, _ctx| Box::pin(handler(args))) }
178    }
179
180    /// Like `new`, with the call's `ToolContext` (`tool_use` id, session id).
181    pub fn with_context<F, Fut>(def: ToolDef, handler: F) -> Self
182    where
183        F: Fn(Value, ToolContext) -> Fut + Send + Sync + 'static,
184        Fut: Future<Output = ToolResult> + Send + 'static,
185    {
186        Self { def, handler: Arc::new(move |args, ctx| Box::pin(handler(args, ctx))) }
187    }
188}
189
190/// A named group of SDK tools, served in-process.
191#[derive(Debug, Clone)]
192pub struct SdkMcpServer {
193    /// Server name; tools are exposed as `mcp__<name>__<tool>`.
194    pub name: String,
195    /// `serverInfo.version` reported to the CLI. Default "1.0.0".
196    pub version: String,
197    /// Per-call timeout the CLI applies to this server's tools (≥ 1 s);
198    /// `None` = the CLI's `MCP_TOOL_TIMEOUT` or its default.
199    pub timeout: Option<Duration>,
200    tools: Vec<SdkTool>,
201    /// Running `tools/call`s by JSON-RPC id; firing one cancels the call.
202    /// One map per session (`for_session`): every CLI numbers its requests
203    /// from 0, so ids from two sessions collide.
204    in_flight: Arc<DashMap<String, oneshot::Sender<()>>>,
205}
206
207impl SdkMcpServer {
208    /// An empty server named `name`.
209    pub fn new(name: impl Into<String>) -> Self {
210        Self {
211            name: name.into(),
212            version: "1.0.0".into(),
213            timeout: None,
214            tools: vec![],
215            in_flight: Arc::new(DashMap::new()),
216        }
217    }
218
219    /// Add a tool.
220    #[must_use]
221    pub fn tool(mut self, tool: SdkTool) -> Self {
222        self.tools.push(tool);
223        self
224    }
225
226    /// Set the per-call timeout (`SdkMcpServer::timeout`).
227    #[must_use]
228    pub fn timeout(mut self, timeout: Duration) -> Self {
229        self.timeout = Some(timeout);
230        self
231    }
232
233    /// Fully qualified tool names as Claude sees them: `mcp__<server>__<tool>`.
234    #[must_use]
235    pub fn qualified_tool_names(&self) -> Vec<String> {
236        self.tools.iter().map(|t| format!("mcp__{}__{}", self.name, t.def.name)).collect()
237    }
238
239    /// A copy of this server with its own in-flight call registry, for one
240    /// session. Clones share the registry.
241    pub(crate) fn for_session(&self) -> Self {
242        Self { in_flight: Arc::new(DashMap::new()), ..self.clone() }
243    }
244
245    /// This server's entry in an MCP server map (`--mcp-config`, `mcp_set_servers`).
246    pub(crate) fn config(&self) -> Value {
247        let mut config = json!({ "type": "sdk", "name": self.name });
248        if let Some(t) = self.timeout {
249            config["timeout"] = json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
250        }
251        config
252    }
253
254    /// Answer one JSON-RPC message from the CLI. Notifications get an empty
255    /// result: the control channel answers every `mcp_message`.
256    pub async fn handle(&self, message: &Value) -> Value {
257        self.handle_in_session(message, None).await
258    }
259
260    /// `handle`, with the id of the session the message came from.
261    pub(crate) async fn handle_in_session(&self, message: &Value, session_id: Option<String>) -> Value {
262        let id = message.get("id").cloned().unwrap_or(Value::Null);
263        let method = message.get("method").and_then(Value::as_str).unwrap_or("");
264        let params = message.get("params");
265        match method {
266            "initialize" => rpc_result(id, json!({
267                "protocolVersion": PROTOCOL_VERSION,
268                "capabilities": { "tools": {} },
269                "serverInfo": { "name": self.name, "version": self.version },
270            })),
271            "ping" => rpc_result(id, json!({})),
272            "notifications/cancelled" => {
273                let request_id = params.and_then(|p| p.get("requestId")).map(Value::to_string);
274                if let Some((_, cancel)) = request_id.and_then(|rid| self.in_flight.remove(&rid)) {
275                    let _ = cancel.send(());
276                }
277                json!({ "jsonrpc": "2.0", "result": {} })
278            }
279            m if m.starts_with("notifications/") => json!({ "jsonrpc": "2.0", "result": {} }),
280            "tools/list" => {
281                let tools: Vec<Value> = self.tools.iter().map(|t| tool_listing(&t.def)).collect();
282                rpc_result(id, json!({ "tools": tools }))
283            }
284            "tools/call" => self.call_tool(id, params, session_id).await,
285            other => rpc_error(id, -32601, &format!("Method '{other}' not found")),
286        }
287    }
288
289    async fn call_tool(&self, id: Value, params: Option<&Value>, session_id: Option<String>) -> Value {
290        let name = params.and_then(|p| p.get("name")).and_then(Value::as_str).unwrap_or("");
291        let args = params.and_then(|p| p.get("arguments")).cloned().unwrap_or_else(|| json!({}));
292        let Some(tool) = self.tools.iter().find(|t| t.def.name == name) else {
293            return rpc_error(id, -32602, &format!("Tool '{name}' not found"));
294        };
295        let key = id.to_string();
296        let (cancel_tx, cancel_rx) = oneshot::channel();
297        self.in_flight.insert(key.clone(), cancel_tx);
298        // Unregisters also when this future is dropped mid-call.
299        let _registered = InFlightGuard { in_flight: &self.in_flight, key: &key };
300        let run = (tool.handler)(args, ToolContext::from_params(params, session_id));
301        let outcome = tokio::select! {
302            result = run => Some(result),
303            Ok(()) = cancel_rx => None,
304        };
305        match outcome {
306            Some(result) => rpc_result(id, result.into_wire()),
307            None => rpc_error(id, REQUEST_CANCELLED, "Request cancelled"),
308        }
309    }
310}
311
312/// Removes a tool call's cancel registration when dropped.
313struct InFlightGuard<'a> {
314    in_flight: &'a DashMap<String, oneshot::Sender<()>>,
315    key: &'a str,
316}
317
318impl Drop for InFlightGuard<'_> {
319    fn drop(&mut self) {
320        self.in_flight.remove(self.key);
321    }
322}
323
324fn tool_listing(def: &ToolDef) -> Value {
325    let mut tool = json!({
326        "name": def.name,
327        "description": def.description,
328        "inputSchema": def.input_schema.clone()
329            .unwrap_or_else(|| json!({ "type": "object", "properties": {} })),
330    });
331    if let Some(title) = &def.title {
332        tool["title"] = json!(title);
333    }
334    if let Some(schema) = &def.output_schema {
335        tool["outputSchema"] = schema.clone();
336    }
337    if let Some(annotations) = &def.annotations {
338        tool["annotations"] = json!(annotations);
339    }
340    tool
341}
342
343/// An MCP server map with `servers` as SDK entries plus `external` as given.
344pub(crate) fn server_map(servers: &[SdkMcpServer], external: Option<&serde_json::Map<String, Value>>) -> Value {
345    let mut map: serde_json::Map<String, Value> =
346        servers.iter().map(|s| (s.name.clone(), s.config())).collect();
347    if let Some(external) = external {
348        map.extend(external.iter().map(|(k, v)| (k.clone(), v.clone())));
349    }
350    Value::Object(map)
351}
352
353/// A JSON-RPC reply; `id` and `result` are moved in, not copied (`json!`
354/// would deep-copy a possibly large tool result).
355fn rpc_result(id: Value, result: Value) -> Value {
356    rpc_reply(id, "result", result)
357}
358
359fn rpc_error(id: Value, code: i64, message: &str) -> Value {
360    rpc_reply(id, "error", json!({ "code": code, "message": message }))
361}
362
363fn rpc_reply(id: Value, key: &str, payload: Value) -> Value {
364    let mut reply = serde_json::Map::with_capacity(3);
365    reply.insert("jsonrpc".into(), "2.0".into());
366    reply.insert("id".into(), id);
367    reply.insert(key.into(), payload);
368    Value::Object(reply)
369}