Skip to main content

Crate claude_code_agent

Crate claude_code_agent 

Source
Expand description

Run Claude Code from Rust.

Each Session keeps one claude process running (Claude Code CLI 2.1.329 or newer). Send prompts with Agent, approve or block tools with hooks and CanUseTool, give Claude tools written in Rust, run many sessions with SessionPool, and replay recorded sessions in tests.

§Quick start

use claude_code_agent::{Session, SessionOptions, Initialize, Agent, AgentEvent};
use tokio_stream::StreamExt;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let session = Session::spawn(
        SessionOptions { cwd: Some("/my/project".into()), ..Default::default() },
        Initialize::default(),
    ).await?;

    let agent = Agent::new(session);
    let mut stream = agent.prompt("hello").await?;

    while let Some(event) = stream.next().await {
        match event {
            AgentEvent::Text(t) => print!("{}", t),
            AgentEvent::Done(r) => {
                eprintln!("\ncost: ${:.4}", r.total_cost_usd.unwrap_or(0.0));
                break;
            }
            AgentEvent::Error(e) => eprintln!("error: {}", e),
            _ => {}
        }
    }
    Ok(())
}

§With hooks

use claude_code_agent::{Agent, AgentEvent, CanUseTool, HookRegistry, Initialize, Session, SessionOptions};
use claude_code_agent::protocol::{HookOutput, ToolDecision};
use tokio_stream::StreamExt;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Hooks are declared before spawn: the CLI learns them from `initialize`.
    let mut hooks = HookRegistry::new();
    hooks.on_pre_tool_use(|payload| async move {
        match payload.tool_name.as_deref() {
            Some("Bash") => HookOutput::allow(),
            Some(name)   => HookOutput::block(format!("{name} not allowed")),
            None         => HookOutput::allow(),
        }
    });

    let opts = SessionOptions {
        hooks,
        // Asked whenever the CLI's own permission rules would prompt.
        can_use_tool: Some(CanUseTool::new(|req| async move {
            if req.tool_name == "Bash" { ToolDecision::allow() } else { ToolDecision::deny("read-only") }
        })),
        ..Default::default()
    };
    let session = Session::spawn(opts, Initialize::default()).await?;
    let agent = Agent::new(session);

    let mut stream = agent.prompt("list files in /tmp").await?;
    while let Some(ev) = stream.next().await {
        if let AgentEvent::Text(t) = &ev { print!("{}", t); }
        if matches!(ev, AgentEvent::Done(_) | AgentEvent::Error(_)) { break; }
    }
    Ok(())
}

§With session pool (high throughput)

use claude_code_agent::{SessionPool, PoolConfig, Agent, AgentEvent};
use tokio_stream::StreamExt;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let pool = SessionPool::new(PoolConfig { max_sessions: 4, ..Default::default() });
    pool.warm(2).await; // pre-warm 2 processes

    // Parallel prompts — each reuses an idle session from the pool
    let (r1, r2) = tokio::join!(
        run_prompt(&pool, "task one"),
        run_prompt(&pool, "task two"),
    );
    Ok(())
}

async fn run_prompt(pool: &SessionPool, text: &str) -> anyhow::Result<String> {
    let borrowed = pool.acquire().await?;
    let agent = Agent::new(borrowed.session.clone());
    let mut stream = agent.prompt(text).await?;
    let mut out = String::new();
    while let Some(ev) = stream.next().await {
        if let AgentEvent::Text(t) = &ev { out.push_str(t); }
        if matches!(ev, AgentEvent::Done(_) | AgentEvent::Error(_)) { break; }
    }
    Ok(out)
}

Re-exports§

pub use agent::Agent;
pub use agent::AgentError;
pub use agent::AgentEvent;
pub use agent::AgentStream;
pub use agent::TurnError;
pub use agent::TurnResult;
pub use hooks::HookRegistry;
pub use mcp::SdkMcpServer;
pub use mcp::SdkTool;
pub use mcp::ToolContent;
pub use mcp::ToolContext;
pub use mcp::ToolResult;
pub use pool::Checkout;
pub use pool::PoolConfig;
pub use pool::PooledSession;
pub use pool::SessionPool;
pub use protocol::Initialize;
pub use protocol::UserMessage;
pub use protocol::ContentBlock;
pub use protocol::Priority;
pub use protocol::Autocompact;
pub use protocol::Effort;
pub use protocol::PermissionMode;
pub use protocol::PermissionPrompts;
pub use protocol::Thinking;
pub use protocol::ThinkingDisplay;
pub use protocol::InboundMessage;
pub use protocol::SystemMessage;
pub use protocol::AssistantMessage;
pub use protocol::ResultMessage;
pub use protocol::UsageSummary;
pub use protocol::BackgroundTask;
pub use protocol::TurnErrorKind;
pub use protocol::ToolDecision;
pub use protocol::HookOutput;
pub use protocol::HookDecision;
pub use protocol::ControlRequest;
pub use protocol::ControlRequestBody;
pub use protocol::ControlResponse;
pub use protocol::CanUseToolRequest;
pub use protocol::ElicitationRequest;
pub use protocol::ElicitationResponse;
pub use protocol::UserDialogBehavior;
pub use protocol::UserDialogRequest;
pub use protocol::UserDialogResponse;
pub use protocol::HookEventKind;
pub use protocol::HookEventPayload;
pub use protocol::HookCallbackRequest;
pub use protocol::ToolDef;
pub use protocol::ToolAnnotations;
pub use protocol::McpManifest;
pub use protocol::BackgroundTasksRequest;
pub use session::CanUseTool;
pub use session::McpCall;
pub use session::OnElicitation;
pub use session::OnStderr;
pub use session::OnUserDialog;
pub use session::ReloadPlugins;
pub use session::Session;
pub use session::SessionError;
pub use session::SessionOptions;
pub use session::WeakSession;

Modules§

agent
Agent layer — sends a turn and returns a streaming event iterator.
background
Background task tree tracking.
code_mode
Force Code Mode (the REPL tool) on for SDK sessions.
compaction
Manual context compaction with custom instructions.
fs_events
Typed filesystem events from FileChanged / CwdChanged / DirectoryAdded hooks.
hooks
Hook registry — async Rust closures for all 33 hook event types.
mcp
In-process (SDK) MCP servers — Rust functions exposed to Claude as tools.
middleware
Ready-made hook policies.
pool
Session pool — pre-warmed persistent processes with idle reuse.
protocol
Wire types for the Claude Code stream-json protocol. Source: the Claude Code 2.1.329 binary’s zod schemas and the official Python SDK (claude_agent_sdk 0.1.48); citations are on the types they cover.
replay
Deterministic record/replay — run the SDK without a CLI process or API cost.
session
Persistent subprocess session — 3-task architecture.