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