> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/yocxy2/claurst/llms.txt
> Use this file to discover all available pages before exploring further.

# Tool system

> How the Tool trait is defined, how the 33 built-in tools are organized, and how input schemas and permissions work in cc-tools.

The tool system lives in the `cc-tools` crate. It defines the `Tool` trait, a registry of 33 built-in tools, and the `ToolContext` struct that carries runtime state into every tool call.

## The Tool trait

Every tool is a zero-sized struct that implements the `Tool` trait, defined in `crates/tools/src/lib.rs`:

```rust theme={null}
#[async_trait]
pub trait Tool: Send + Sync {
    fn name(&self) -> &str;
    fn description(&self) -> &str;
    fn permission_level(&self) -> PermissionLevel;
    fn input_schema(&self) -> Value;   // JSON Schema for tool parameters
    async fn execute(&self, input: Value, ctx: &ToolContext) -> ToolResult;

    // Default implementation — builds a ToolDefinition from the above methods
    fn to_definition(&self) -> ToolDefinition {
        ToolDefinition {
            name: self.name().to_owned(),
            description: self.description().to_owned(),
            input_schema: self.input_schema(),
        }
    }
}
```

### PermissionLevel

Each tool declares a `PermissionLevel` that controls which permission modes will allow it to run automatically:

| Level       | Meaning                                                                |
| ----------- | ---------------------------------------------------------------------- |
| `None`      | No permission check required (metadata tools, signalling tools)        |
| `ReadOnly`  | Safe to run automatically in `Default` and `AcceptEdits` modes         |
| `Write`     | Requires user approval in `Default` mode; automatic in `AcceptEdits`   |
| `Execute`   | Runs shell commands; requires explicit approval or `BypassPermissions` |
| `Dangerous` | Highest risk; denied in `Plan` mode                                    |

### ToolResult

```rust theme={null}
pub struct ToolResult {
    pub content: String,
    pub is_error: bool,
    pub metadata: Option<Value>,   // Optional structured data for TUI rendering
}

impl ToolResult {
    pub fn success(content: impl Into<String>) -> Self { ... }
    pub fn error(content: impl Into<String>) -> Self { ... }
    pub fn with_metadata(self, meta: Value) -> Self { ... }
}
```

### ToolContext

`ToolContext` is passed to every `execute()` call and carries all runtime state a tool needs:

```rust theme={null}
pub struct ToolContext {
    pub working_dir: PathBuf,
    pub permission_mode: PermissionMode,
    pub permission_handler: Arc<dyn PermissionHandler>,
    pub cost_tracker: Arc<CostTracker>,
    pub session_id: String,
    pub non_interactive: bool,
    pub mcp_manager: Option<Arc<McpManager>>,
    pub config: Config,
}
```

`ctx.resolve_path(path)` resolves relative paths against `working_dir`. `ctx.check_permission(tool_name, description, is_read_only)` runs the permission check and returns `Err(ClaudeError::PermissionDenied(...))` if access is denied.

## Input schema validation

Tool input schemas are generated using **schemars** (derive-based) and serialized to `serde_json::Value`. The schemas follow JSON Schema draft-07. The query loop validates tool inputs against these schemas before calling `execute()`.

The tool schema cache: `ToolDefinition` structs produced by `to_definition()` are collected once at startup into a `Vec<ApiToolDefinition>` and reused across turns. The last tool in the list automatically receives a `CacheControl::ephemeral()` annotation from `cc-api`, enabling prompt caching on the tools block.

### Registry functions

```rust theme={null}
// Returns all 33 built-in tools
pub fn all_tools() -> Vec<Box<dyn Tool>>

// Finds a tool by its exact name constant
pub fn find_tool(name: &str) -> Option<Box<dyn Tool>>
```

## Tool categories and names

<AccordionGroup>
  <Accordion title="File tools">
    | Tool name      | Permission | Description                                                             |
    | -------------- | ---------- | ----------------------------------------------------------------------- |
    | `Read`         | `ReadOnly` | Read file contents with optional line offset and limit                  |
    | `Write`        | `Write`    | Create or overwrite a file; creates parent directories automatically    |
    | `Edit`         | `Write`    | Replace exact string in a file; `replace_all` flag for bulk replacement |
    | `NotebookEdit` | `Write`    | Edit Jupyter `.ipynb` cells: `replace`, `insert`, or `delete`           |
  </Accordion>

  <Accordion title="Shell tools">
    | Tool name    | Permission | Description                                                                                |
    | ------------ | ---------- | ------------------------------------------------------------------------------------------ |
    | `Bash`       | `Execute`  | Run a shell command via `bash -c` (or `cmd /C` on Windows); default timeout 120s, max 600s |
    | `PowerShell` | `Execute`  | Run a PowerShell command; uses `pwsh` on non-Windows                                       |
  </Accordion>

  <Accordion title="Search tools">
    | Tool name | Permission | Description                                                                                     |
    | --------- | ---------- | ----------------------------------------------------------------------------------------------- |
    | `Glob`    | `ReadOnly` | Find files by glob pattern, sorted by modification time; max 250 results                        |
    | `Grep`    | `ReadOnly` | Search file contents with a regex; three output modes: `files_with_matches`, `content`, `count` |
  </Accordion>

  <Accordion title="Agent tools">
    | Tool name | Permission | Description                                                                                 |
    | --------- | ---------- | ------------------------------------------------------------------------------------------- |
    | `Task`    | `Execute`  | Spawn a sub-agent that runs its own `run_query_loop()`; returns the final assistant message |
  </Accordion>

  <Accordion title="Web tools">
    | Tool name   | Permission | Description                                                                      |
    | ----------- | ---------- | -------------------------------------------------------------------------------- |
    | `WebFetch`  | `ReadOnly` | HTTP GET with HTML stripping; 30s timeout; 100K character limit                  |
    | `WebSearch` | `ReadOnly` | Search via Brave Search API (with `BRAVE_SEARCH_API_KEY`) or DuckDuckGo fallback |
  </Accordion>

  <Accordion title="MCP tools">
    | Tool name          | Permission | Description                                        |
    | ------------------ | ---------- | -------------------------------------------------- |
    | `ListMcpResources` | `ReadOnly` | List all resources from connected MCP servers      |
    | `ReadMcpResource`  | `ReadOnly` | Read a resource by URI from a connected MCP server |
  </Accordion>

  <Accordion title="Task management tools">
    | Tool name    | Permission | Description                                             |
    | ------------ | ---------- | ------------------------------------------------------- |
    | `TaskCreate` | `None`     | Create a task in the global `TASK_STORE` with a UUID    |
    | `TaskGet`    | `None`     | Retrieve a task by ID                                   |
    | `TaskUpdate` | `None`     | Update task fields; `status=deleted` removes from store |
    | `TaskList`   | `None`     | List all non-deleted tasks, with optional status filter |
    | `TaskStop`   | `None`     | Set a task's status to `Failed`                         |
    | `TaskOutput` | `None`     | Append text to a task's output vector                   |
    | `TodoWrite`  | `None`     | Replace the entire todo list atomically                 |
  </Accordion>

  <Accordion title="Scheduling tools">
    | Tool name    | Permission | Description                                                         |
    | ------------ | ---------- | ------------------------------------------------------------------- |
    | `CronCreate` | `None`     | Create a scheduled task with a 5-field cron expression; max 50 jobs |
    | `CronDelete` | `None`     | Delete a scheduled task by ID                                       |
    | `CronList`   | `None`     | List all scheduled tasks with human-readable schedules              |
  </Accordion>

  <Accordion title="Plan mode tools">
    | Tool name       | Permission | Description                                              |
    | --------------- | ---------- | -------------------------------------------------------- |
    | `EnterPlanMode` | `None`     | Switch the session to `Plan` (read-only) permission mode |
    | `ExitPlanMode`  | `None`     | Return from plan mode; accepts an optional `summary`     |
  </Accordion>

  <Accordion title="Worktree tools">
    | Tool name       | Permission | Description                                                        |
    | --------------- | ---------- | ------------------------------------------------------------------ |
    | `EnterWorktree` | `None`     | Create a git worktree on a new branch and switch the session to it |
    | `ExitWorktree`  | `None`     | Return from a worktree session; `keep` or `remove` the worktree    |
  </Accordion>

  <Accordion title="Meta / utility tools">
    | Tool name         | Permission | Description                                                                      |
    | ----------------- | ---------- | -------------------------------------------------------------------------------- |
    | `ToolSearch`      | `None`     | Find tools by keyword with a scoring algorithm; `select:Name` for exact lookup   |
    | `AskUserQuestion` | `None`     | Surface a question to the user in the TUI; returns error in non-interactive mode |
    | `SendMessage`     | `None`     | Deliver a message to a named recipient in the shared `INBOX` map                 |
    | `Brief`           | `None`     | Attach files and a status message for TUI rendering                              |
    | `Sleep`           | `None`     | Async delay up to 300 seconds                                                    |
    | `Config`          | `None`     | Read or write fields in `~/.claude/settings.json`                                |
    | `Skill`           | `None`     | Load and execute a skill from `.claude/commands/` or `~/.claude/commands/`       |
  </Accordion>
</AccordionGroup>

## Simplified tool implementation example

The following example is representative of how a read-only tool is structured, based on the pattern used throughout `cc-tools`:

```rust theme={null}
use async_trait::async_trait;
use serde_json::Value;

pub struct GlobTool;

#[async_trait]
impl Tool for GlobTool {
    fn name(&self) -> &str {
        "Glob"
    }

    fn description(&self) -> &str {
        "Find files by name pattern. Returns paths sorted by modification time."
    }

    fn permission_level(&self) -> PermissionLevel {
        PermissionLevel::ReadOnly
    }

    fn input_schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "Glob pattern (e.g. \"**/*.rs\")"
                },
                "path": {
                    "type": "string",
                    "description": "Directory to search in (defaults to working directory)"
                }
            },
            "required": ["pattern"]
        })
    }

    async fn execute(&self, input: Value, ctx: &ToolContext) -> ToolResult {
        let pattern = input["pattern"].as_str().unwrap_or("");
        let base = input["path"]
            .as_str()
            .map(|p| ctx.resolve_path(p))
            .unwrap_or_else(|| ctx.working_dir.clone());

        let full_pattern = base.join(pattern).to_string_lossy().into_owned();
        let mut results: Vec<_> = glob::glob(&full_pattern)
            .into_iter()
            .flatten()
            .flatten()
            .take(250)
            .collect();

        // Sort by modification time, most recent first
        results.sort_by_key(|p| {
            std::fs::metadata(p)
                .and_then(|m| m.modified())
                .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
        });
        results.reverse();

        let output = results
            .iter()
            .map(|p| p.display().to_string())
            .collect::<Vec<_>>()
            .join("\n");

        ToolResult::success(output)
    }
}
```

<Note>
  Tool names in `cc-tools` match the TypeScript constants exactly (e.g. `"Bash"`, `"Read"`, `"Edit"`, `"Task"`). This ensures full compatibility with any system that references tools by name.
</Note>
