claude-agents-sdk 0.1.7

Rust SDK for building agents with Claude Code CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! MCP (Model Context Protocol) tool support.
//!
//! This module provides functionality for defining SDK-managed tools that
//! run in-process rather than as external servers.
//!
//! # Feature Flag
//!
//! This module requires the `mcp` feature to be enabled:
//!
//! ```toml
//! [dependencies]
//! claude-agents-sdk = { version = "0.1", features = ["mcp"] }
//! ```

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Content type for tool responses.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum ToolContent {
    /// Text content.
    #[serde(rename = "text")]
    Text {
        /// The text content.
        text: String,
    },
    /// Image content.
    #[serde(rename = "image")]
    Image {
        /// Base64-encoded image data.
        data: String,
        /// MIME type of the image.
        #[serde(rename = "mimeType")]
        mime_type: String,
    },
}

impl ToolContent {
    /// Create a text content item.
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text { text: text.into() }
    }

    /// Create an image content item.
    pub fn image(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
        Self::Image {
            data: data.into(),
            mime_type: mime_type.into(),
        }
    }
}

/// Result from a tool execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResult {
    /// Content items returned by the tool.
    pub content: Vec<ToolContent>,
    /// Whether the result is an error.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_error: Option<bool>,
}

impl ToolResult {
    /// Create a successful text result.
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            content: vec![ToolContent::text(text)],
            is_error: None,
        }
    }

    /// Create an error result.
    pub fn error(message: impl Into<String>) -> Self {
        Self {
            content: vec![ToolContent::text(message)],
            is_error: Some(true),
        }
    }

    /// Create a result with multiple content items.
    pub fn with_content(content: Vec<ToolContent>) -> Self {
        Self {
            content,
            is_error: None,
        }
    }
}

/// Hints describing tool behavior for clients.
///
/// All properties are hints and not guaranteed to faithfully describe tool behavior.
/// Clients should not make tool use decisions based solely on annotations from
/// untrusted servers.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolAnnotations {
    /// A human-readable title for the tool.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// If true, the tool does not modify its environment. Default: false.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub read_only_hint: Option<bool>,
    /// If true, the tool may perform destructive updates. Default: true.
    /// Only meaningful when `read_only_hint` is false.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destructive_hint: Option<bool>,
    /// If true, calling the tool repeatedly with the same arguments has no
    /// additional effect. Default: false.
    /// Only meaningful when `read_only_hint` is false.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub idempotent_hint: Option<bool>,
    /// If true, the tool may interact with an open world of external entities.
    /// Default: true.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub open_world_hint: Option<bool>,
}

/// Input schema for a tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolInputSchema {
    /// JSON Schema type (usually "object").
    #[serde(rename = "type")]
    pub schema_type: String,
    /// Property definitions.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub properties: HashMap<String, Value>,
    /// Required property names.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required: Vec<String>,
}

impl ToolInputSchema {
    /// Create a new object schema.
    pub fn object() -> Self {
        Self {
            schema_type: "object".to_string(),
            properties: HashMap::new(),
            required: Vec::new(),
        }
    }

    /// Add a string property.
    pub fn string_property(
        mut self,
        name: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        self.properties.insert(
            name.into(),
            serde_json::json!({
                "type": "string",
                "description": description.into()
            }),
        );
        self
    }

    /// Add a number property.
    pub fn number_property(
        mut self,
        name: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        self.properties.insert(
            name.into(),
            serde_json::json!({
                "type": "number",
                "description": description.into()
            }),
        );
        self
    }

    /// Add a boolean property.
    pub fn boolean_property(
        mut self,
        name: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        self.properties.insert(
            name.into(),
            serde_json::json!({
                "type": "boolean",
                "description": description.into()
            }),
        );
        self
    }

    /// Add a required property name.
    pub fn required_property(mut self, name: impl Into<String>) -> Self {
        self.required.push(name.into());
        self
    }
}

/// Type alias for tool handler functions.
pub type ToolHandler =
    Arc<dyn Fn(Value) -> Pin<Box<dyn Future<Output = ToolResult> + Send>> + Send + Sync>;

/// SDK MCP tool definition.
///
/// Represents a tool that can be registered with the SDK for in-process execution.
pub struct SdkMcpTool {
    /// Tool name.
    pub name: String,
    /// Tool description.
    pub description: String,
    /// Input schema.
    pub input_schema: ToolInputSchema,
    /// Handler function.
    pub handler: ToolHandler,
    /// Optional annotations describing tool behavior.
    pub annotations: Option<ToolAnnotations>,
}

impl SdkMcpTool {
    /// Create a new tool.
    pub fn new<F, Fut>(
        name: impl Into<String>,
        description: impl Into<String>,
        input_schema: ToolInputSchema,
        handler: F,
    ) -> Self
    where
        F: Fn(Value) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ToolResult> + Send + 'static,
    {
        Self {
            name: name.into(),
            description: description.into(),
            input_schema,
            handler: Arc::new(move |input| Box::pin(handler(input))),
            annotations: None,
        }
    }

    /// Set annotations on this tool.
    pub fn with_annotations(mut self, annotations: ToolAnnotations) -> Self {
        self.annotations = Some(annotations);
        self
    }
}

impl std::fmt::Debug for SdkMcpTool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SdkMcpTool")
            .field("name", &self.name)
            .field("description", &self.description)
            .field("input_schema", &self.input_schema)
            .finish()
    }
}

/// Configuration for an SDK MCP server.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpSdkServerConfig {
    /// Server type (always "sdk").
    #[serde(rename = "type")]
    pub server_type: String,
    /// Server name.
    pub name: String,
    /// Server version.
    pub version: String,
}

/// Create an SDK MCP server configuration.
///
/// # Arguments
///
/// * `name` - Server name
/// * `version` - Server version
/// * `tools` - List of tools to register
///
/// # Returns
///
/// A tuple of (config, tools) where config can be added to options.mcp_servers
/// and tools should be stored for handling tool calls.
///
/// # Examples
///
/// ```rust,no_run
/// use claude_agents_sdk::mcp::{create_sdk_mcp_server, SdkMcpTool, ToolInputSchema, ToolResult};
///
/// let calculator = SdkMcpTool::new(
///     "add",
///     "Add two numbers",
///     ToolInputSchema::object()
///         .number_property("a", "First number")
///         .number_property("b", "Second number")
///         .required_property("a")
///         .required_property("b"),
///     |input| async move {
///         let a = input.get("a").and_then(|v| v.as_f64()).unwrap_or(0.0);
///         let b = input.get("b").and_then(|v| v.as_f64()).unwrap_or(0.0);
///         ToolResult::text(format!("{}", a + b))
///     },
/// );
///
/// let (config, tools) = create_sdk_mcp_server("calculator", "1.0.0", vec![calculator]);
/// ```
pub fn create_sdk_mcp_server(
    name: impl Into<String>,
    version: impl Into<String>,
    tools: Vec<SdkMcpTool>,
) -> (McpSdkServerConfig, Vec<SdkMcpTool>) {
    let config = McpSdkServerConfig {
        server_type: "sdk".to_string(),
        name: name.into(),
        version: version.into(),
    };

    (config, tools)
}

/// Macro for defining tools with a simpler syntax.
///
/// # Examples
///
/// ```rust,ignore
/// use claude_agents_sdk::tool;
///
/// tool! {
///     /// Add two numbers together.
///     fn add(a: f64, b: f64) -> ToolResult {
///         ToolResult::text(format!("{}", a + b))
///     }
/// }
/// ```
#[macro_export]
macro_rules! tool {
    (
        $(#[$meta:meta])*
        fn $name:ident($($arg:ident: $type:ty),*) -> $ret:ty $body:block
    ) => {
        {
            use $crate::mcp::{SdkMcpTool, ToolInputSchema, ToolResult};

            let mut schema = ToolInputSchema::object();
            $(
                schema = schema.string_property(stringify!($arg), "");
                schema = schema.required_property(stringify!($arg));
            )*

            SdkMcpTool::new(
                stringify!($name),
                "",
                schema,
                |input: serde_json::Value| async move {
                    $(
                        let $arg: $type = serde_json::from_value(
                            input.get(stringify!($arg)).cloned().unwrap_or_default()
                        ).unwrap_or_default();
                    )*
                    $body
                },
            )
        }
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tool_content_text() {
        let content = ToolContent::text("Hello");
        match content {
            ToolContent::Text { text } => assert_eq!(text, "Hello"),
            _ => panic!("Expected text content"),
        }
    }

    #[test]
    fn test_tool_result_text() {
        let result = ToolResult::text("Success");
        assert_eq!(result.content.len(), 1);
        assert!(result.is_error.is_none());
    }

    #[test]
    fn test_tool_result_error() {
        let result = ToolResult::error("Something went wrong");
        assert_eq!(result.is_error, Some(true));
    }

    #[test]
    fn test_input_schema_builder() {
        let schema = ToolInputSchema::object()
            .string_property("name", "The name")
            .number_property("age", "The age")
            .required_property("name");

        assert_eq!(schema.schema_type, "object");
        assert!(schema.properties.contains_key("name"));
        assert!(schema.properties.contains_key("age"));
        assert!(schema.required.contains(&"name".to_string()));
    }

    #[test]
    fn test_create_sdk_server() {
        let tool = SdkMcpTool::new("test", "Test tool", ToolInputSchema::object(), |_| async {
            ToolResult::text("ok")
        });

        let (config, tools) = create_sdk_mcp_server("test-server", "1.0.0", vec![tool]);

        assert_eq!(config.server_type, "sdk");
        assert_eq!(config.name, "test-server");
        assert_eq!(config.version, "1.0.0");
        assert_eq!(tools.len(), 1);
    }

    #[test]
    fn test_tool_annotations_default() {
        let annotations = ToolAnnotations::default();
        assert!(annotations.title.is_none());
        assert!(annotations.read_only_hint.is_none());
        assert!(annotations.destructive_hint.is_none());
        assert!(annotations.idempotent_hint.is_none());
        assert!(annotations.open_world_hint.is_none());
    }

    #[test]
    fn test_tool_annotations_serialization() {
        let annotations = ToolAnnotations {
            title: Some("My Tool".to_string()),
            read_only_hint: Some(true),
            destructive_hint: Some(false),
            idempotent_hint: Some(true),
            open_world_hint: Some(false),
        };

        let json = serde_json::to_value(&annotations).unwrap();
        assert_eq!(json["title"], "My Tool");
        assert_eq!(json["readOnlyHint"], true);
        assert_eq!(json["destructiveHint"], false);
        assert_eq!(json["idempotentHint"], true);
        assert_eq!(json["openWorldHint"], false);
    }

    #[test]
    fn test_tool_annotations_skips_none() {
        let annotations = ToolAnnotations {
            read_only_hint: Some(true),
            ..Default::default()
        };

        let json = serde_json::to_value(&annotations).unwrap();
        assert_eq!(json["readOnlyHint"], true);
        assert!(json.get("title").is_none());
        assert!(json.get("destructiveHint").is_none());
    }

    #[test]
    fn test_sdk_mcp_tool_with_annotations() {
        let tool = SdkMcpTool::new("test", "Test tool", ToolInputSchema::object(), |_| async {
            ToolResult::text("ok")
        })
        .with_annotations(ToolAnnotations {
            read_only_hint: Some(true),
            ..Default::default()
        });

        assert!(tool.annotations.is_some());
        assert_eq!(tool.annotations.unwrap().read_only_hint, Some(true));
    }

    #[test]
    fn test_sdk_mcp_tool_no_annotations_by_default() {
        let tool = SdkMcpTool::new("test", "Test tool", ToolInputSchema::object(), |_| async {
            ToolResult::text("ok")
        });

        assert!(tool.annotations.is_none());
    }
}