cc-agent-sdk 0.1.7

claude agent sdk
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! Tool Restriction for Skills
//!
//! This module implements tool restriction based on the `allowed-tools` field
//! in SKILL.md metadata, as specified in Claude Code documentation.
//!
//! Based on: https://code.claude.com/docs/en/skills

use std::collections::HashSet;
use std::fmt;

/// Errors for tool restriction checking
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolRestrictionError {
    /// Tool is not in the allowed list
    ToolNotAllowed {
        /// The tool that was requested
        tool: String,
        /// Tools that are allowed
        allowed: Vec<String>,
    },

    /// Invalid tool specification format
    InvalidSpec(String),
}

impl fmt::Display for ToolRestrictionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ToolRestrictionError::ToolNotAllowed { tool, allowed } => {
                write!(
                    f,
                    "Tool '{}' is not allowed. Allowed tools: {:?}",
                    tool, allowed
                )
            }
            ToolRestrictionError::InvalidSpec(spec) => {
                write!(f, "Invalid tool specification: '{}'", spec)
            }
        }
    }
}

impl std::error::Error for ToolRestrictionError {}

/// Tool restriction enforcement for skills
///
/// # Overview
///
/// The `allowed-tools` field in SKILL.md metadata specifies which tools
/// a skill is allowed to use. This module enforces those restrictions.
///
/// # Tool Specifications
///
/// Tools can be specified in several ways:
///
/// ```text
/// allowed-tools:
///   - Read                    # Simple tool name
///   - Grep                    # Simple tool name
///   - "Bash(python:*)"        # Tool with parameter restrictions
///   - "*"                     # Wildcard (all tools)
/// ```
///
/// # Parameter Restrictions
///
/// Tools can have parameter restrictions like `Bash(python:*)` which means:
/// - The Bash tool is allowed
/// - Only when the command starts with "python:"
/// - Example: `Bash(command="python:script.py")` ✅
/// - Example: `Bash(command="node script.js")` ❌
///
/// # Example
///
/// ```no_run
/// use claude_agent_sdk::skills::tool_restriction::ToolRestriction;
///
/// let restriction = ToolRestriction::new(Some(vec![
///     "Read".to_string(),
///     "Grep".to_string(),
///     "Bash(python:*)".to_string(),
/// ]));
///
/// // Check if tools are allowed
/// assert!(restriction.is_tool_allowed("Read"));
/// assert!(restriction.is_tool_allowed("Bash(python:script.py)"));
/// assert!(!restriction.is_tool_allowed("Write"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolRestriction {
    /// Set of allowed tool specifications
    allowed_tools: Option<HashSet<String>>,
}

impl ToolRestriction {
    /// Create a new tool restriction
    ///
    /// # Arguments
    ///
    /// * `allowed_tools` - Optional list of allowed tool specifications
    ///   - None: No restrictions (all tools allowed)
    ///   - Some([]): No tools allowed
    ///   - Some([...]): Specific tools allowed
    ///
    /// # Example
    ///
    /// ```
    /// use claude_agent_sdk::skills::tool_restriction::ToolRestriction;
    ///
    /// // No restrictions
    /// let unrestricted = ToolRestriction::new(None);
    /// assert!(unrestricted.is_tool_allowed("AnyTool"));
    ///
    /// // Specific restrictions
    /// let restricted = ToolRestriction::new(Some(vec![
    ///     "Read".to_string(),
    ///     "Grep".to_string(),
    /// ]));
    /// assert!(restricted.is_tool_allowed("Read"));
    /// assert!(!restricted.is_tool_allowed("Write"));
    /// ```
    pub fn new(allowed_tools: Option<Vec<String>>) -> Self {
        Self {
            allowed_tools: allowed_tools.map(|tools| tools.into_iter().collect()),
        }
    }

    /// Create a restriction with no tool limits
    ///
    /// # Example
    ///
    /// ```
    /// use claude_agent_sdk::skills::tool_restriction::ToolRestriction;
    ///
    /// let restriction = ToolRestriction::unrestricted();
    /// assert!(restriction.is_tool_allowed("AnyTool"));
    /// assert!(restriction.is_tool_allowed("AnotherTool"));
    /// ```
    pub fn unrestricted() -> Self {
        Self { allowed_tools: None }
    }

    /// Check if a tool is allowed
    ///
    /// # Arguments
    ///
    /// * `tool_name` - Tool name with optional parameters (e.g., "Bash(python:script.py)")
    ///
    /// # Returns
    ///
    /// true if tool is allowed, false otherwise
    ///
    /// # Example
    ///
    /// ```
    /// use claude_agent_sdk::skills::tool_restriction::ToolRestriction;
    ///
    /// let restriction = ToolRestriction::new(Some(vec![
    ///     "Read".to_string(),
    ///     "Bash(python:*)".to_string(),
    /// ]));
    ///
    /// assert!(restriction.is_tool_allowed("Read"));
    /// assert!(restriction.is_tool_allowed("Bash(python:script.py)"));
    /// assert!(!restriction.is_tool_allowed("Write"));
    /// assert!(!restriction.is_tool_allowed("Bash(node:script.js)"));
    /// ```
    pub fn is_tool_allowed(&self, tool_name: &str) -> bool {
        match &self.allowed_tools {
            None => true, // No restrictions
            Some(allowed) => {
                // Check for wildcard
                if allowed.contains("*") {
                    return true;
                }

                // Parse the tool name
                let (base_tool, params) = Self::parse_tool_spec(tool_name);

                // Check for exact match
                if allowed.contains(tool_name) {
                    return true;
                }

                // Check for base tool match (without parameters)
                if allowed.contains(&base_tool) {
                    return true;
                }

                // Check for parameter-restricted tools
                for allowed_spec in allowed {
                    if let Some((allowed_base, allowed_pattern)) =
                        Self::parse_tool_spec_with_pattern(allowed_spec)
                    {
                        if allowed_base == base_tool {
                            // Check if parameters match the pattern
                            if let Some(params) = &params {
                                if Self::pattern_matches(&allowed_pattern, params) {
                                    return true;
                                }
                            }
                        }
                    }
                }

                false
            }
        }
    }

    /// Validate a tool and return an error if not allowed
    ///
    /// # Arguments
    ///
    /// * `tool_name` - Tool name with optional parameters
    ///
    /// # Returns
    ///
    /// Ok(()) if tool is allowed
    /// Err(ToolRestrictionError) if not allowed
    ///
    /// # Example
    ///
    /// ```
    /// use claude_agent_sdk::skills::tool_restriction::ToolRestriction;
    ///
    /// let restriction = ToolRestriction::new(Some(vec!["Read".to_string()]));
    ///
    /// assert!(restriction.validate_tool("Read").is_ok());
    /// assert!(restriction.validate_tool("Write").is_err());
    /// ```
    pub fn validate_tool(&self, tool_name: &str) -> Result<(), ToolRestrictionError> {
        if self.is_tool_allowed(tool_name) {
            Ok(())
        } else {
            Err(ToolRestrictionError::ToolNotAllowed {
                tool: tool_name.to_string(),
                allowed: self
                    .allowed_tools
                    .as_ref()
                    .map(|s| s.iter().cloned().collect())
                    .unwrap_or_default(),
            })
        }
    }

    /// Get list of allowed tools
    ///
    /// # Returns
    ///
    /// None if unrestricted, Some(VEC) if restricted
    ///
    /// # Example
    ///
    /// ```
    /// use claude_agent_sdk::skills::tool_restriction::ToolRestriction;
    ///
    /// let restriction = ToolRestriction::new(Some(vec![
    ///     "Read".to_string(),
    ///     "Grep".to_string(),
    /// ]));
    ///
    /// let allowed = restriction.get_allowed_tools();
    /// assert!(allowed.is_some());
    /// assert_eq!(allowed.unwrap().len(), 2);
    /// ```
    pub fn get_allowed_tools(&self) -> Option<Vec<String>> {
        self.allowed_tools
            .as_ref()
            .map(|s| s.iter().cloned().collect())
    }

    /// Check if this restriction allows all tools
    ///
    /// # Returns
    ///
    /// true if no restrictions are in place
    ///
    /// # Example
    ///
    /// ```
    /// use claude_agent_sdk::skills::tool_restriction::ToolRestriction;
    ///
    /// let unrestricted = ToolRestriction::unrestricted();
    /// assert!(unrestricted.is_unrestricted());
    ///
    /// let restricted = ToolRestriction::new(Some(vec!["Read".to_string()]));
    /// assert!(!restricted.is_unrestricted());
    /// ```
    pub fn is_unrestricted(&self) -> bool {
        self.allowed_tools.is_none()
    }

    /// Parse tool specification into base tool and parameters
    ///
    /// # Examples
    ///
    /// - "Bash(python:script.py)" -> ("Bash", Some("python:script.py"))
    /// - "Read" -> ("Read", None)
    fn parse_tool_spec(tool_spec: &str) -> (String, Option<String>) {
        if let Some(params) = tool_spec.strip_suffix(')') {
            if let Some((base, args)) = params.split_once('(') {
                return (base.to_string(), Some(args.to_string()));
            }
        }
        (tool_spec.to_string(), None)
    }

    /// Parse tool specification with pattern matching support
    ///
    /// # Examples
    ///
    /// - "Bash(python:*)" -> Some(("Bash", "python:*"))
    /// - "Read" -> None
    fn parse_tool_spec_with_pattern(spec: &str) -> Option<(String, String)> {
        if let Some(params) = spec.strip_suffix(')') {
            if let Some((base, pattern)) = params.split_once('(') {
                if pattern.contains('*') {
                    return Some((base.to_string(), pattern.to_string()));
                }
            }
        }
        None
    }

    /// Check if parameters match a pattern
    ///
    /// # Patterns
    ///
    /// - "*" matches anything
    /// - "python:*" matches anything starting with "python:"
    /// - "*" matches all parameters
    ///
    /// # Examples
    ///
    /// - pattern_matches("python:*", "python:script.py") -> true
    /// - pattern_matches("python:*", "node:script.js") -> false
    /// - pattern_matches("*", "anything") -> true
    fn pattern_matches(pattern: &str, params: &str) -> bool {
        if pattern == "*" {
            return true;
        }

        if let Some(prefix) = pattern.strip_suffix('*') {
            return params.starts_with(prefix);
        }

        pattern == params
    }

    /// Add an allowed tool to the restriction
    ///
    /// # Example
    ///
    /// ```
    /// use claude_agent_sdk::skills::tool_restriction::ToolRestriction;
    ///
    /// let mut restriction = ToolRestriction::new(Some(vec!["Read".to_string()]));
    /// restriction.add_tool("Grep".to_string());
    ///
    /// assert!(restriction.is_tool_allowed("Grep"));
    /// ```
    pub fn add_tool(&mut self, tool: String) {
        self.allowed_tools
            .get_or_insert_with(HashSet::new)
            .insert(tool);
    }

    /// Remove an allowed tool from the restriction
    ///
    /// # Example
    ///
    /// ```
    /// use claude_agent_sdk::skills::tool_restriction::ToolRestriction;
    ///
    /// let mut restriction = ToolRestriction::new(Some(vec![
    ///     "Read".to_string(),
    ///     "Grep".to_string(),
    /// ]));
    ///
    /// restriction.remove_tool("Grep");
    /// assert!(!restriction.is_tool_allowed("Grep"));
    /// ```
    pub fn remove_tool(&mut self, tool: &str) {
        if let Some(allowed) = &mut self.allowed_tools {
            allowed.remove(tool);
        }
    }
}

impl Default for ToolRestriction {
    fn default() -> Self {
        Self::unrestricted()
    }
}

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

    #[test]
    fn test_unrestricted() {
        let restriction = ToolRestriction::unrestricted();
        assert!(restriction.is_tool_allowed("AnyTool"));
        assert!(restriction.is_tool_allowed("AnotherTool"));
        assert!(restriction.is_unrestricted());
    }

    #[test]
    fn test_specific_tools() {
        let restriction = ToolRestriction::new(Some(vec![
            "Read".to_string(),
            "Grep".to_string(),
        ]));

        assert!(restriction.is_tool_allowed("Read"));
        assert!(restriction.is_tool_allowed("Grep"));
        assert!(!restriction.is_tool_allowed("Write"));
        assert!(!restriction.is_tool_allowed("Bash"));
    }

    #[test]
    fn test_tool_with_parameters() {
        let restriction = ToolRestriction::new(Some(vec![
            "Bash(python:*)".to_string(),
            "Read".to_string(),
        ]));

        // Bash with python: should be allowed
        assert!(restriction.is_tool_allowed("Bash(python:script.py)"));
        assert!(restriction.is_tool_allowed("Bash(python:-m pytest)"));

        // Bash with other commands should not be allowed
        assert!(!restriction.is_tool_allowed("Bash(node:script.js)"));
        assert!(!restriction.is_tool_allowed("Bash(ls -la)"));

        // Read should be allowed
        assert!(restriction.is_tool_allowed("Read"));
    }

    #[test]
    fn test_wildcard() {
        let restriction = ToolRestriction::new(Some(vec!["*".to_string()]));

        assert!(restriction.is_tool_allowed("AnyTool"));
        assert!(restriction.is_tool_allowed("Bash(anything)"));
        assert!(restriction.is_tool_allowed("Read"));
    }

    #[test]
    fn test_validate_tool() {
        let restriction = ToolRestriction::new(Some(vec!["Read".to_string()]));

        assert!(restriction.validate_tool("Read").is_ok());

        let result = restriction.validate_tool("Write");
        assert!(result.is_err());
        if let Err(ToolRestrictionError::ToolNotAllowed { tool, .. }) = result {
            assert_eq!(tool, "Write");
        } else {
            panic!("Expected ToolNotAllowed error");
        }
    }

    #[test]
    fn test_parse_tool_spec() {
        assert_eq!(
            ToolRestriction::parse_tool_spec("Bash(python:script.py)"),
            ("Bash".to_string(), Some("python:script.py".to_string()))
        );

        assert_eq!(
            ToolRestriction::parse_tool_spec("Read"),
            ("Read".to_string(), None)
        );
    }

    #[test]
    fn test_pattern_matches() {
        assert!(ToolRestriction::pattern_matches("python:*", "python:script.py"));
        assert!(ToolRestriction::pattern_matches("python:*", "python:-m pytest"));
        assert!(!ToolRestriction::pattern_matches("python:*", "node:script.js"));

        assert!(ToolRestriction::pattern_matches("*", "anything"));
        assert!(ToolRestriction::pattern_matches("*", ""));
    }

    #[test]
    fn test_add_tool() {
        let mut restriction = ToolRestriction::new(Some(vec!["Read".to_string()]));
        assert!(!restriction.is_tool_allowed("Grep"));

        restriction.add_tool("Grep".to_string());
        assert!(restriction.is_tool_allowed("Grep"));
    }

    #[test]
    fn test_remove_tool() {
        let mut restriction = ToolRestriction::new(Some(vec![
            "Read".to_string(),
            "Grep".to_string(),
        ]));

        assert!(restriction.is_tool_allowed("Grep"));

        restriction.remove_tool("Grep");
        assert!(!restriction.is_tool_allowed("Grep"));
        assert!(restriction.is_tool_allowed("Read"));
    }

    #[test]
    fn test_get_allowed_tools() {
        let unrestricted = ToolRestriction::unrestricted();
        assert!(unrestricted.get_allowed_tools().is_none());

        let restricted = ToolRestriction::new(Some(vec![
            "Read".to_string(),
            "Grep".to_string(),
        ]));
        let allowed = restricted.get_allowed_tools();
        assert!(allowed.is_some());
        assert_eq!(allowed.unwrap().len(), 2);
    }

    #[test]
    fn test_default() {
        let restriction = ToolRestriction::default();
        assert!(restriction.is_unrestricted());
        assert!(restriction.is_tool_allowed("AnyTool"));
    }

    #[test]
    fn test_empty_allowed_list() {
        let restriction = ToolRestriction::new(Some(vec![]));
        assert!(!restriction.is_tool_allowed("Read"));
        assert!(!restriction.is_tool_allowed("AnyTool"));
    }
}