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    Text { text: String },
36    /// Base64 image data, e.g. `mime_type` "image/png".
37    Image {
38        data: String,
39        #[serde(rename = "mimeType")]
40        mime_type: String,
41    },
42    /// An embedded resource: `{"uri", "mimeType", "text" | "blob"}`.
43    Resource { resource: Value },
44    /// A link to a resource: `{"uri", "name", …}` fields.
45    ResourceLink(serde_json::Map<String, Value>),
46}
47
48/// Result of a tool call, returned to the model.
49#[derive(Debug, Clone, PartialEq)]
50pub struct ToolResult {
51    pub content: Vec<ToolContent>,
52    /// Machine-readable output matching `ToolDef::output_schema`.
53    pub structured: Option<Value>,
54    pub is_error: bool,
55}
56
57impl ToolResult {
58    pub fn text(text: impl Into<String>) -> Self {
59        Self::content(vec![ToolContent::Text { text: text.into() }])
60    }
61
62    pub fn error(text: impl Into<String>) -> Self {
63        Self { is_error: true, ..Self::text(text) }
64    }
65
66    /// A base64 image.
67    pub fn image(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
68        Self::content(vec![ToolContent::Image { data: data.into(), mime_type: mime_type.into() }])
69    }
70
71    pub fn content(content: Vec<ToolContent>) -> Self {
72        Self { content, structured: None, is_error: false }
73    }
74
75    /// Strings are passed through verbatim, anything else as JSON text.
76    pub fn from_value(value: Value) -> Self {
77        match value {
78            Value::String(s) => Self::text(s),
79            other => Self::text(other.to_string()),
80        }
81    }
82
83    /// Attach structured output (also sent to the model as JSON text when
84    /// the result has no content).
85    pub fn with_structured(mut self, value: Value) -> Self {
86        self.structured = Some(value);
87        self
88    }
89
90    fn to_wire(&self) -> Value {
91        let content = if self.content.is_empty() {
92            let text = self.structured.as_ref().map(Value::to_string).unwrap_or_default();
93            vec![ToolContent::Text { text }]
94        } else {
95            self.content.clone()
96        };
97        let mut body = json!({ "content": content });
98        if let Some(s) = &self.structured {
99            body["structuredContent"] = s.clone();
100        }
101        if self.is_error {
102            body["isError"] = Value::Bool(true);
103        }
104        body
105    }
106}
107
108/// What a tool handler knows about its call besides the arguments.
109#[derive(Debug, Clone, Default)]
110pub struct ToolContext {
111    /// The model's `tool_use` id for this call.
112    pub tool_use_id: Option<String>,
113    pub session_id: Option<String>,
114    /// The request's raw `_meta` object.
115    pub meta: Value,
116}
117
118impl ToolContext {
119    fn from_params(params: Option<&Value>) -> Self {
120        let meta = params.and_then(|p| p.get("_meta")).cloned().unwrap_or(Value::Null);
121        let field = |k: &str| meta.get(k).and_then(Value::as_str).map(str::to_owned);
122        Self {
123            tool_use_id: field("claudecode/toolUseId"),
124            session_id: field("claudecode/sessionId"),
125            meta: meta.clone(),
126        }
127    }
128}
129
130/// A tool definition plus the async function that runs it.
131/// `#[claude_tool]` generates `<fn>_tool() -> SdkTool`.
132///
133/// A call the CLI cancels (`notifications/cancelled`, e.g. after an
134/// interrupt) drops the handler's future, so `.await` points are where a
135/// handler stops.
136#[derive(Clone)]
137pub struct SdkTool {
138    pub def: ToolDef,
139    handler: ToolFn,
140}
141
142impl fmt::Debug for SdkTool {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        f.debug_struct("SdkTool").field("name", &self.def.name).finish()
145    }
146}
147
148impl SdkTool {
149    /// `handler` receives the raw `arguments` object of the tool call.
150    pub fn new<F, Fut>(def: ToolDef, handler: F) -> Self
151    where
152        F: Fn(Value) -> Fut + Send + Sync + 'static,
153        Fut: Future<Output = ToolResult> + Send + 'static,
154    {
155        Self { def, handler: Arc::new(move |args, _ctx| Box::pin(handler(args))) }
156    }
157
158    /// Like `new`, with the call's `ToolContext` (tool_use id, session id).
159    pub fn with_context<F, Fut>(def: ToolDef, handler: F) -> Self
160    where
161        F: Fn(Value, ToolContext) -> Fut + Send + Sync + 'static,
162        Fut: Future<Output = ToolResult> + Send + 'static,
163    {
164        Self { def, handler: Arc::new(move |args, ctx| Box::pin(handler(args, ctx))) }
165    }
166}
167
168/// A named group of SDK tools, served in-process.
169#[derive(Debug, Clone)]
170pub struct SdkMcpServer {
171    pub name: String,
172    pub version: String,
173    /// Per-call timeout the CLI applies to this server's tools (≥ 1 s);
174    /// `None` = the CLI's `MCP_TOOL_TIMEOUT` or its default.
175    pub timeout: Option<Duration>,
176    tools: Vec<SdkTool>,
177    /// Running `tools/call`s by JSON-RPC id; firing one cancels the call.
178    in_flight: Arc<DashMap<String, oneshot::Sender<()>>>,
179}
180
181impl SdkMcpServer {
182    pub fn new(name: impl Into<String>) -> Self {
183        Self {
184            name: name.into(),
185            version: "1.0.0".into(),
186            timeout: None,
187            tools: vec![],
188            in_flight: Arc::new(DashMap::new()),
189        }
190    }
191
192    pub fn tool(mut self, tool: SdkTool) -> Self {
193        self.tools.push(tool);
194        self
195    }
196
197    pub fn timeout(mut self, timeout: Duration) -> Self {
198        self.timeout = Some(timeout);
199        self
200    }
201
202    /// Fully qualified tool names as Claude sees them: `mcp__<server>__<tool>`.
203    pub fn qualified_tool_names(&self) -> Vec<String> {
204        self.tools.iter().map(|t| format!("mcp__{}__{}", self.name, t.def.name)).collect()
205    }
206
207    /// This server's entry in an MCP server map (`--mcp-config`, `mcp_set_servers`).
208    pub(crate) fn config(&self) -> Value {
209        let mut config = json!({ "type": "sdk", "name": self.name });
210        if let Some(t) = self.timeout {
211            config["timeout"] = json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
212        }
213        config
214    }
215
216    /// Answer one JSON-RPC message from the CLI. Notifications get an empty
217    /// result: the control channel answers every `mcp_message`.
218    pub async fn handle(&self, message: &Value) -> Value {
219        let id = message.get("id").cloned().unwrap_or(Value::Null);
220        let method = message.get("method").and_then(Value::as_str).unwrap_or("");
221        let params = message.get("params");
222        match method {
223            "initialize" => rpc_result(id, json!({
224                "protocolVersion": PROTOCOL_VERSION,
225                "capabilities": { "tools": {} },
226                "serverInfo": { "name": self.name, "version": self.version },
227            })),
228            "ping" => rpc_result(id, json!({})),
229            "notifications/cancelled" => {
230                let request_id = params.and_then(|p| p.get("requestId")).map(Value::to_string);
231                if let Some((_, cancel)) = request_id.and_then(|rid| self.in_flight.remove(&rid)) {
232                    let _ = cancel.send(());
233                }
234                json!({ "jsonrpc": "2.0", "result": {} })
235            }
236            m if m.starts_with("notifications/") => json!({ "jsonrpc": "2.0", "result": {} }),
237            "tools/list" => {
238                let tools: Vec<Value> = self.tools.iter().map(|t| tool_listing(&t.def)).collect();
239                rpc_result(id, json!({ "tools": tools }))
240            }
241            "tools/call" => self.call_tool(id, params).await,
242            other => rpc_error(id, -32601, format!("Method '{other}' not found")),
243        }
244    }
245
246    async fn call_tool(&self, id: Value, params: Option<&Value>) -> Value {
247        let name = params.and_then(|p| p.get("name")).and_then(Value::as_str).unwrap_or("");
248        let args = params.and_then(|p| p.get("arguments")).cloned().unwrap_or_else(|| json!({}));
249        let Some(tool) = self.tools.iter().find(|t| t.def.name == name) else {
250            return rpc_error(id, -32602, format!("Tool '{name}' not found"));
251        };
252        let key = id.to_string();
253        let (cancel_tx, cancel_rx) = oneshot::channel();
254        self.in_flight.insert(key.clone(), cancel_tx);
255        let run = (tool.handler)(args, ToolContext::from_params(params));
256        let outcome = tokio::select! {
257            result = run => Some(result),
258            Ok(()) = cancel_rx => None,
259        };
260        self.in_flight.remove(&key);
261        match outcome {
262            Some(result) => rpc_result(id, result.to_wire()),
263            None => rpc_error(id, REQUEST_CANCELLED, "Request cancelled".into()),
264        }
265    }
266}
267
268fn tool_listing(def: &ToolDef) -> Value {
269    let mut tool = json!({
270        "name": def.name,
271        "description": def.description,
272        "inputSchema": def.input_schema.clone()
273            .unwrap_or_else(|| json!({ "type": "object", "properties": {} })),
274    });
275    if let Some(title) = &def.title {
276        tool["title"] = json!(title);
277    }
278    if let Some(schema) = &def.output_schema {
279        tool["outputSchema"] = schema.clone();
280    }
281    if let Some(annotations) = &def.annotations {
282        tool["annotations"] = json!(annotations);
283    }
284    tool
285}
286
287/// An MCP server map with `servers` as SDK entries plus `external` as given.
288pub(crate) fn server_map(servers: &[SdkMcpServer], external: Option<&serde_json::Map<String, Value>>) -> Value {
289    let mut map: serde_json::Map<String, Value> =
290        servers.iter().map(|s| (s.name.clone(), s.config())).collect();
291    if let Some(external) = external {
292        map.extend(external.iter().map(|(k, v)| (k.clone(), v.clone())));
293    }
294    Value::Object(map)
295}
296
297fn rpc_result(id: Value, result: Value) -> Value {
298    json!({ "jsonrpc": "2.0", "id": id, "result": result })
299}
300
301fn rpc_error(id: Value, code: i64, message: String) -> Value {
302    json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
303}