1use 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";
28const REQUEST_CANCELLED: i64 = -32800;
30
31#[derive(Debug, Clone, PartialEq, serde::Serialize)]
33#[serde(tag = "type", rename_all = "snake_case")]
34pub enum ToolContent {
35 Text {
37 text: String,
39 },
40 Image {
42 data: String,
44 #[serde(rename = "mimeType")]
46 mime_type: String,
47 },
48 Resource {
50 resource: Value,
52 },
53 ResourceLink(serde_json::Map<String, Value>),
55}
56
57#[derive(Debug, Clone, PartialEq)]
59pub struct ToolResult {
60 pub content: Vec<ToolContent>,
62 pub structured: Option<Value>,
64 pub is_error: bool,
66}
67
68impl ToolResult {
69 pub fn text(text: impl Into<String>) -> Self {
71 Self::content(vec![ToolContent::Text { text: text.into() }])
72 }
73
74 pub fn error(text: impl Into<String>) -> Self {
76 Self { is_error: true, ..Self::text(text) }
77 }
78
79 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 #[must_use]
86 pub fn content(content: Vec<ToolContent>) -> Self {
87 Self { content, structured: None, is_error: false }
88 }
89
90 #[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 #[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#[derive(Debug, Clone, Default)]
127pub struct ToolContext {
128 pub tool_use_id: Option<String>,
130 pub session_id: Option<String>,
132 pub meta: Value,
134}
135
136impl ToolContext {
137 fn from_params(params: Option<&Value>) -> Self {
138 let meta = params.and_then(|p| p.get("_meta")).cloned().unwrap_or(Value::Null);
139 let field = |k: &str| meta.get(k).and_then(Value::as_str).map(str::to_owned);
140 Self { tool_use_id: field("claudecode/toolUseId"), session_id: field("claudecode/sessionId"), meta }
141 }
142}
143
144#[derive(Clone)]
151pub struct SdkTool {
152 pub def: ToolDef,
154 handler: ToolFn,
155}
156
157impl fmt::Debug for SdkTool {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 f.debug_struct("SdkTool").field("name", &self.def.name).finish_non_exhaustive()
160 }
161}
162
163impl SdkTool {
164 pub fn new<F, Fut>(def: ToolDef, handler: F) -> Self
166 where
167 F: Fn(Value) -> Fut + Send + Sync + 'static,
168 Fut: Future<Output = ToolResult> + Send + 'static,
169 {
170 Self { def, handler: Arc::new(move |args, _ctx| Box::pin(handler(args))) }
171 }
172
173 pub fn with_context<F, Fut>(def: ToolDef, handler: F) -> Self
175 where
176 F: Fn(Value, ToolContext) -> Fut + Send + Sync + 'static,
177 Fut: Future<Output = ToolResult> + Send + 'static,
178 {
179 Self { def, handler: Arc::new(move |args, ctx| Box::pin(handler(args, ctx))) }
180 }
181}
182
183#[derive(Debug, Clone)]
185pub struct SdkMcpServer {
186 pub name: String,
188 pub version: String,
190 pub timeout: Option<Duration>,
193 tools: Vec<SdkTool>,
194 in_flight: Arc<DashMap<String, oneshot::Sender<()>>>,
196}
197
198impl SdkMcpServer {
199 pub fn new(name: impl Into<String>) -> Self {
201 Self {
202 name: name.into(),
203 version: "1.0.0".into(),
204 timeout: None,
205 tools: vec![],
206 in_flight: Arc::new(DashMap::new()),
207 }
208 }
209
210 #[must_use]
212 pub fn tool(mut self, tool: SdkTool) -> Self {
213 self.tools.push(tool);
214 self
215 }
216
217 #[must_use]
219 pub fn timeout(mut self, timeout: Duration) -> Self {
220 self.timeout = Some(timeout);
221 self
222 }
223
224 #[must_use]
226 pub fn qualified_tool_names(&self) -> Vec<String> {
227 self.tools.iter().map(|t| format!("mcp__{}__{}", self.name, t.def.name)).collect()
228 }
229
230 pub(crate) fn config(&self) -> Value {
232 let mut config = json!({ "type": "sdk", "name": self.name });
233 if let Some(t) = self.timeout {
234 config["timeout"] = json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
235 }
236 config
237 }
238
239 pub async fn handle(&self, message: &Value) -> Value {
242 let id = message.get("id").cloned().unwrap_or(Value::Null);
243 let method = message.get("method").and_then(Value::as_str).unwrap_or("");
244 let params = message.get("params");
245 match method {
246 "initialize" => rpc_result(id, json!({
247 "protocolVersion": PROTOCOL_VERSION,
248 "capabilities": { "tools": {} },
249 "serverInfo": { "name": self.name, "version": self.version },
250 })),
251 "ping" => rpc_result(id, json!({})),
252 "notifications/cancelled" => {
253 let request_id = params.and_then(|p| p.get("requestId")).map(Value::to_string);
254 if let Some((_, cancel)) = request_id.and_then(|rid| self.in_flight.remove(&rid)) {
255 let _ = cancel.send(());
256 }
257 json!({ "jsonrpc": "2.0", "result": {} })
258 }
259 m if m.starts_with("notifications/") => json!({ "jsonrpc": "2.0", "result": {} }),
260 "tools/list" => {
261 let tools: Vec<Value> = self.tools.iter().map(|t| tool_listing(&t.def)).collect();
262 rpc_result(id, json!({ "tools": tools }))
263 }
264 "tools/call" => self.call_tool(id, params).await,
265 other => rpc_error(id, -32601, &format!("Method '{other}' not found")),
266 }
267 }
268
269 async fn call_tool(&self, id: Value, params: Option<&Value>) -> Value {
270 let name = params.and_then(|p| p.get("name")).and_then(Value::as_str).unwrap_or("");
271 let args = params.and_then(|p| p.get("arguments")).cloned().unwrap_or_else(|| json!({}));
272 let Some(tool) = self.tools.iter().find(|t| t.def.name == name) else {
273 return rpc_error(id, -32602, &format!("Tool '{name}' not found"));
274 };
275 let key = id.to_string();
276 let (cancel_tx, cancel_rx) = oneshot::channel();
277 self.in_flight.insert(key.clone(), cancel_tx);
278 let _registered = InFlightGuard { in_flight: &self.in_flight, key: &key };
280 let run = (tool.handler)(args, ToolContext::from_params(params));
281 let outcome = tokio::select! {
282 result = run => Some(result),
283 Ok(()) = cancel_rx => None,
284 };
285 match outcome {
286 Some(result) => rpc_result(id, result.into_wire()),
287 None => rpc_error(id, REQUEST_CANCELLED, "Request cancelled"),
288 }
289 }
290}
291
292struct InFlightGuard<'a> {
294 in_flight: &'a DashMap<String, oneshot::Sender<()>>,
295 key: &'a str,
296}
297
298impl Drop for InFlightGuard<'_> {
299 fn drop(&mut self) {
300 self.in_flight.remove(self.key);
301 }
302}
303
304fn tool_listing(def: &ToolDef) -> Value {
305 let mut tool = json!({
306 "name": def.name,
307 "description": def.description,
308 "inputSchema": def.input_schema.clone()
309 .unwrap_or_else(|| json!({ "type": "object", "properties": {} })),
310 });
311 if let Some(title) = &def.title {
312 tool["title"] = json!(title);
313 }
314 if let Some(schema) = &def.output_schema {
315 tool["outputSchema"] = schema.clone();
316 }
317 if let Some(annotations) = &def.annotations {
318 tool["annotations"] = json!(annotations);
319 }
320 tool
321}
322
323pub(crate) fn server_map(servers: &[SdkMcpServer], external: Option<&serde_json::Map<String, Value>>) -> Value {
325 let mut map: serde_json::Map<String, Value> =
326 servers.iter().map(|s| (s.name.clone(), s.config())).collect();
327 if let Some(external) = external {
328 map.extend(external.iter().map(|(k, v)| (k.clone(), v.clone())));
329 }
330 Value::Object(map)
331}
332
333fn rpc_result(id: Value, result: Value) -> Value {
336 rpc_reply(id, "result", result)
337}
338
339fn rpc_error(id: Value, code: i64, message: &str) -> Value {
340 rpc_reply(id, "error", json!({ "code": code, "message": message }))
341}
342
343fn rpc_reply(id: Value, key: &str, payload: Value) -> Value {
344 let mut reply = serde_json::Map::with_capacity(3);
345 reply.insert("jsonrpc".into(), "2.0".into());
346 reply.insert("id".into(), id);
347 reply.insert(key.into(), payload);
348 Value::Object(reply)
349}