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 { text: String },
36 Image {
38 data: String,
39 #[serde(rename = "mimeType")]
40 mime_type: String,
41 },
42 Resource { resource: Value },
44 ResourceLink(serde_json::Map<String, Value>),
46}
47
48#[derive(Debug, Clone, PartialEq)]
50pub struct ToolResult {
51 pub content: Vec<ToolContent>,
52 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 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 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 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#[derive(Debug, Clone, Default)]
110pub struct ToolContext {
111 pub tool_use_id: Option<String>,
113 pub session_id: Option<String>,
114 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#[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 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 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#[derive(Debug, Clone)]
170pub struct SdkMcpServer {
171 pub name: String,
172 pub version: String,
173 pub timeout: Option<Duration>,
176 tools: Vec<SdkTool>,
177 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 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 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 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
287pub(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}