Expand description
claude-code-agent — Rust SDK for Claude Code.
Drives the claude CLI (verified against 2.1.328) over its stream-json
control protocol: one persistent process per session, Rust closures as
hook callbacks and permission handlers, in-process tools over the SDK MCP
bridge, record/replay, and a session pool.
§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;
Modules§
- agent
- Agent layer — sends a turn and returns a streaming event iterator.
- background
- Background task tree tracking.
- code_
mode - Force Code Mode (the
REPLtool) 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.328 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.