Documentation
¶
Overview ¶
Package claudecode wraps the Claude Code CLI as a first-class eino Agent and Tool.
It provides ClaudeCodeAgent (implements adk.Agent) and ClaudeCodeTool (implements tool.InvokableTool), enabling Claude Code to participate in eino's multi-agent orchestration, streaming, interrupt/resume, and callback systems — just like any built-in eino agent.
Quick start ¶
agent, _ := claudecode.New(claudecode.WithMaxTurns(5))
runner := adk.NewRunner(ctx, adk.RunnerConfig{Agent: agent})
events := runner.Run(ctx, []adk.Message{schema.UserMessage("Hello!")})
Design ¶
Each call to ClaudeCodeAgent.Run spawns a one-shot claude -p process. Session continuity across calls is achieved via WithSessionID / WithResume. SDK-appropriate defaults (bare mode, dontAsk permissions, prompt-cache optimization) are on by default — no configuration needed for basic use.
Custom tools ¶
WithCustomTools exposes eino [tool.InvokableTool]s to Claude Code via an embedded MCP HTTP server. The server starts automatically on a random localhost port and is passed to the CLI via --mcp-config. Claude Code discovers and calls these tools during task execution without any additional setup.
Sub-agents ¶
WithAgents defines custom agent types. WithAgent selects which agent to run the session as. Together they let you run Claude Code with a custom identity, prompt, tool set, and model — no need to pre-write agent files.
[agent_tool.go]: for using ClaudeCodeAgent as a tool callable by other eino agents, see [NewAgentTool] and ClaudeCodeTool.
Index ¶
- Constants
- Variables
- func FindCLI(name string) string
- func NewSessionID() string
- type AgentDefinition
- type AgentError
- type CLIError
- type ClaudeCodeAgent
- func (a *ClaudeCodeAgent) Description(ctx context.Context) string
- func (a *ClaudeCodeAgent) Name(ctx context.Context) string
- func (a *ClaudeCodeAgent) Resume(ctx context.Context, info *adk.ResumeInfo, opts ...adk.AgentRunOption) *adk.AsyncIterator[*adk.AgentEvent]
- func (a *ClaudeCodeAgent) Run(ctx context.Context, input *adk.AgentInput, opts ...adk.AgentRunOption) *adk.AsyncIterator[*adk.AgentEvent]
- type ClaudeCodeTool
- type Option
- func WithAddDirs(dirs ...string) Option
- func WithAgent(name string) Option
- func WithAgents(agents map[string]AgentDefinition) Option
- func WithAllowedTools(tools ...string) Option
- func WithAppendSystemPrompt(prompt string) Option
- func WithBare(v bool) Option
- func WithBetas(betas ...string) Option
- func WithBin(bin string) Option
- func WithCWD(dir string) Option
- func WithContinueConversation() Option
- func WithCustomTools(tools ...tool.InvokableTool) Option
- func WithDebug(filter string) Option
- func WithDebugFile(path string) Option
- func WithDescription(desc string) Option
- func WithDisallowedTools(tools ...string) Option
- func WithEffort(effort string) Option
- func WithEmitToolEvents() Option
- func WithEnv(env ...string) Option
- func WithExcludeDynamicSystemPromptSections(v bool) Option
- func WithExtraArgs(args map[string]string) Option
- func WithFallbackModel(model string) Option
- func WithForkSession() Option
- func WithIncludePartialMessages() Option
- func WithMCPConfig(configJSON string) Option
- func WithMCPConfigPath(path string) Option
- func WithMaxBudgetUSD(budget float64) Option
- func WithMaxTurns(n int) Option
- func WithModel(model string) Option
- func WithName(name string) Option
- func WithNoSessionPersistence(v bool) Option
- func WithPermissionMode(mode string) Option
- func WithPluginDir(path string) Option
- func WithPluginURL(url string) Option
- func WithResume(sessionID string) Option
- func WithRunner(r Runner) Option
- func WithSessionID(id string) Option
- func WithSettingSources(sources ...string) Option
- func WithSettings(settingsJSON string) Option
- func WithStderr(fn func(string)) Option
- func WithStrictMCPConfig(v bool) Option
- func WithStructuredOutput(schema string) Option
- func WithSystemPrompt(prompt string) Option
- func WithTools(tools ...string) Option
- type Options
- type Runner
- type StreamEvent
Constants ¶
const ( ToolBash = "Bash" ToolRead = "Read" ToolWrite = "Write" ToolEdit = "Edit" ToolGlob = "Glob" ToolGrep = "Grep" ToolWebFetch = "WebFetch" ToolWebSearch = "WebSearch" ToolTask = "Task" )
Built-in tool names. Use these with WithTools, WithAllowedTools, WithDisallowedTools instead of raw strings for compile-time safety.
const ( AgentDefault = "claude" AgentExplore = "Explore" AgentPlan = "Plan" AgentGeneralPurpose = "general-purpose" )
Built-in agent names. Use these with WithAgent instead of raw strings.
Variables ¶
var ( ErrCLINotFound = errors.New("claude CLI not found") ErrEmptyPrompt = errors.New("empty prompt") )
Sentinel errors for programmatic error handling.
Functions ¶
func FindCLI ¶
FindCLI locates the claude CLI binary. If the given name is an absolute or relative path, it is returned as-is. Otherwise PATH is searched. Returns the original name if nothing is found (the exec layer will report a clear error when it can't start the process).
func NewSessionID ¶
func NewSessionID() string
NewSessionID returns a new random UUID for use with WithSessionID and WithResume. Sessions persist conversation context across separate ClaudeCodeAgent.Run calls or program restarts.
Pass the returned ID to WithSessionID on the first call and WithResume on subsequent calls to continue the conversation. See examples/session for a complete example.
Types ¶
type AgentDefinition ¶
type AgentDefinition struct {
Description string `json:"description"`
Prompt string `json:"prompt"`
Tools []string `json:"tools,omitempty"`
Model string `json:"model,omitempty"` // "sonnet", "opus", "haiku", "inherit"
}
AgentDefinition defines a custom agent type for Claude Code's sub-agent system. It is serialized to JSON and passed via --agents.
type AgentError ¶
AgentError wraps an error that occurs during agent execution.
func (*AgentError) Error ¶
func (e *AgentError) Error() string
func (*AgentError) Unwrap ¶
func (e *AgentError) Unwrap() error
type ClaudeCodeAgent ¶
type ClaudeCodeAgent struct {
// contains filtered or unexported fields
}
ClaudeCodeAgent is an eino Agent that invokes a locally installed Claude Code CLI in one-shot mode (claude -p). It implements adk.Agent and can be used with eino's runner, composed into multi-agent topologies, or wrapped as a tool.
Basic usage:
agent, _ := claudecode.New(
claudecode.WithSystemPrompt("You are a helpful assistant."),
claudecode.WithTools("Read", "Write", "Bash"),
)
runner := adk.NewRunner(ctx, adk.RunnerConfig{Agent: agent})
events := runner.run(ctx, []adk.Message{schema.UserMessage("Hello!")})
func New ¶
func New(opts ...Option) (*ClaudeCodeAgent, error)
New creates a ClaudeCodeAgent with the given options.
func (*ClaudeCodeAgent) Description ¶
func (a *ClaudeCodeAgent) Description(ctx context.Context) string
Description returns the agent description.
func (*ClaudeCodeAgent) Name ¶
func (a *ClaudeCodeAgent) Name(ctx context.Context) string
Name returns the agent name.
func (*ClaudeCodeAgent) Resume ¶
func (a *ClaudeCodeAgent) Resume(ctx context.Context, info *adk.ResumeInfo, opts ...adk.AgentRunOption) *adk.AsyncIterator[*adk.AgentEvent]
Resume restores the agent from a checkpoint and continues execution using the CLI --resume flag to reconnect to the saved session.
func (*ClaudeCodeAgent) Run ¶
func (a *ClaudeCodeAgent) Run(ctx context.Context, input *adk.AgentInput, opts ...adk.AgentRunOption) *adk.AsyncIterator[*adk.AgentEvent]
Run executes the Claude Code CLI and returns a stream of Agent events.
Each call spawns a new one-shot claude -p process. If WithCustomTools is configured, an embedded MCP HTTP server starts automatically and is passed to the CLI via --mcp-config; it shuts down when the CLI exits.
type ClaudeCodeTool ¶
type ClaudeCodeTool struct {
// contains filtered or unexported fields
}
ClaudeCodeTool wraps a ClaudeCodeAgent as an eino Tool so it can be used by any eino ChatModelAgent as a "super tool" for delegating complex, multi-step tasks.
When invoked, it runs the Claude Code CLI with the given task and returns the result text. This integrates naturally with eino's ReAct loop — the parent agent decides when to delegate a task to Claude Code and receives the result.
func NewTool ¶
func NewTool(opts ...Option) (*ClaudeCodeTool, error)
NewTool creates a ClaudeCodeTool backed by the given agent configuration.
func NewToolFromAgent ¶ added in v0.2.0
func NewToolFromAgent(agent *ClaudeCodeAgent) *ClaudeCodeTool
NewToolFromAgent wraps an existing ClaudeCodeAgent as a ClaudeCodeTool. The agent's name and description become the tool's metadata. This is useful when the same agent configuration needs to serve both as a standalone agent and as a callable tool in a multi-agent setup.
func (*ClaudeCodeTool) InvokableRun ¶
func (t *ClaudeCodeTool) InvokableRun(ctx context.Context, argumentsInJSON string, opts ...tool.Option) (string, error)
InvokableRun executes the tool. Expects {"task": "..."}.
type Option ¶
type Option func(*Options)
Option is a functional option for configuring a ClaudeCodeAgent.
func WithAddDirs ¶
WithAddDirs adds directories to the CLI's workspace.
func WithAgent ¶ added in v0.2.0
WithAgent selects which agent type to run as for this session. The name must match a key defined via WithAgents, or a built-in agent like "Plan" or "Explore". Passed to the CLI via --agent.
func WithAgents ¶
func WithAgents(agents map[string]AgentDefinition) Option
WithAgents registers custom agent definitions for sub-agent delegation. Keys are agent type names (e.g., "reviewer", "tester"). The map is serialized to JSON and passed to the CLI via --agents.
func WithAllowedTools ¶
WithAllowedTools sets tools that are auto-approved without prompting.
func WithAppendSystemPrompt ¶
WithAppendSystemPrompt appends to the default system prompt instead of replacing it.
func WithBare ¶
WithBare controls minimal mode (bare). Default: true. Bare mode skips hooks, LSP, plugin sync, attribution, auto-memory, keychain reads, and CLAUDE.md auto-discovery — appropriate for SDK/programmatic use. Set WithBare(false) if you need interactive initialization features.
func WithContinueConversation ¶
func WithContinueConversation() Option
WithContinueConversation resumes the most recent conversation.
func WithCustomTools ¶ added in v0.2.0
func WithCustomTools(tools ...tool.InvokableTool) Option
WithCustomTools registers eino InvokableTools that are exposed to Claude Code via an embedded MCP HTTP server. The server starts on a random localhost port at agent.Run() time and is passed to the CLI via --mcp-config.
Claude Code discovers these tools automatically and can call them during task execution. This lets you extend Claude Code's capabilities with arbitrary Go code while keeping the black-box executor model.
func WithDebug ¶
WithDebug enables debug mode with optional category filtering. Example filter: "api,hooks". Pass "" to enable all debug output.
func WithDebugFile ¶
WithDebugFile writes debug logs to the given file path. Implicitly enables debug mode. Use for capturing CLI debug output separately from stderr.
func WithDescription ¶
WithDescription sets the agent description.
func WithDisallowedTools ¶
WithDisallowedTools sets tools that are blocked.
func WithEffort ¶
WithEffort sets the thinking effort level. Valid values: "low", "medium", "high", "xhigh", "max".
func WithEmitToolEvents ¶
func WithEmitToolEvents() Option
WithEmitToolEvents enables surfacing Claude Code's internal tool calls as AgentEvents (with ToolCalls on the message). This gives parent agents visibility into what tools Claude Code is using.
func WithExcludeDynamicSystemPromptSections ¶
WithExcludeDynamicSystemPromptSections controls whether per-machine sections (cwd, env info, git status) are moved from the system prompt into the first user message. Default: true. Improves Anthropic prompt-cache reuse. Ignored when a custom SystemPrompt is set.
func WithExtraArgs ¶
WithExtraArgs passes additional CLI flags through. Key is the flag name (without leading dash), value is the flag value (empty string for boolean flags).
func WithFallbackModel ¶
WithFallbackModel specifies a fallback model if the primary is unavailable.
func WithForkSession ¶
func WithForkSession() Option
WithForkSession forks a resumed session to a new session ID.
func WithIncludePartialMessages ¶
func WithIncludePartialMessages() Option
WithIncludePartialMessages enables partial streaming events from the CLI.
func WithMCPConfig ¶
WithMCPConfig sets inline MCP server configuration (JSON format). Example: `{"github":{"type":"http","url":"..."}}`.
func WithMCPConfigPath ¶
WithMCPConfigPath sets the path to an MCP configuration file.
func WithMaxBudgetUSD ¶
WithMaxBudgetUSD sets a spending cap in USD.
func WithMaxTurns ¶
WithMaxTurns sets the maximum number of agent turns.
func WithNoSessionPersistence ¶
WithNoSessionPersistence disables writing sessions to disk. Use for stateless one-shot tasks where sessions don't need to be resumed. Default: false. Only works with one-shot mode (--print).
func WithPermissionMode ¶
WithPermissionMode sets the permission mode. Valid values: "default", "acceptEdits", "plan", "bypassPermissions", "auto", "dontAsk". Default: "dontAsk".
func WithPluginDir ¶
WithPluginDir adds a plugin directory or .zip file to load for this session. Repeatable — each call appends another path.
func WithPluginURL ¶
WithPluginURL adds a URL to fetch a plugin .zip from for this session. Repeatable — each call appends another URL.
func WithResume ¶
WithResume resumes a specific session by ID.
func WithRunner ¶ added in v0.2.0
WithRunner overrides the CLI runner (for testing).
func WithSessionID ¶
WithSessionID creates a new session with the given session ID.
func WithSettingSources ¶
WithSettingSources controls which settings files to load. nil = CLI default. Empty slice = no settings.
func WithSettings ¶
WithSettings sets inline JSON settings for the CLI.
func WithStderr ¶
WithStderr sets a callback that receives each line of stderr output from the CLI process. Useful for debugging CLI issues.
func WithStrictMCPConfig ¶
WithStrictMCPConfig controls whether only --mcp-config servers are used. When true (default), local .mcp.json files are ignored — appropriate for SDK use where MCP configuration should be explicit.
func WithStructuredOutput ¶
WithStructuredOutput sets a JSON Schema for structured output.
func WithSystemPrompt ¶
WithSystemPrompt sets the system prompt.
type Options ¶
type Options struct {
// Name is the agent name (default: "claude-code").
Name string
// Description is a short description of the agent.
Description string
// Bin is the path to the claude CLI executable (default: auto-discovered).
Bin string
// --- Prompt options ---
// SystemPrompt sets the system prompt (replaces default).
SystemPrompt string
// AppendSystemPrompt appends to the default system prompt.
AppendSystemPrompt string
// --- Tool options ---
// Tools is the list of tool names the agent can use.
// nil means default CLI tools; empty slice means no tools.
Tools []string
// AllowedTools is the list of tools auto-approved without prompting.
AllowedTools []string
// DisallowedTools is the list of tools blocked from the agent.
DisallowedTools []string
// --- Model options ---
// Model specifies the model to use (e.g., "claude-sonnet-4-6").
Model string
// FallbackModel specifies a fallback model if the primary is unavailable.
FallbackModel string
// --- Budget options ---
// MaxTurns limits the number of agent turns (0 = default).
MaxTurns int
// MaxBudgetUSD sets a spending cap in USD (0 = no limit).
MaxBudgetUSD float64
// --- Permission options ---
// PermissionMode sets the permission mode.
// Valid: "default", "acceptEdits", "plan", "bypassPermissions", "auto", "dontAsk".
// Default: "dontAsk" (no interactive prompts — appropriate for SDK use).
PermissionMode string
// PermissionPromptToolName sets the tool used for permission prompts (default: auto when hooks are set).
PermissionPromptToolName string
// --- Session options ---
// ContinueConversation resumes the most recent conversation.
ContinueConversation bool
// Resume resumes a specific session by ID.
Resume string
// SessionID creates a new session with the given ID.
SessionID string
// ForkSession forks the resumed session to a new session ID.
ForkSession bool
// NoSessionPersistence disables writing sessions to disk.
// When true, sessions cannot be resumed. Only works with --print (one-shot mode).
// Default: false (sessions are persisted for cross-agent context sharing).
NoSessionPersistence bool
// --- MCP options ---
// MCPConfig is inline MCP server configuration in JSON format.
MCPConfig string
// MCPConfigPath is the path to an MCP configuration file.
MCPConfigPath string
// StrictMCPConfig ignores all MCP servers except those from --mcp-config.
// Default: true (SDK should not load local .mcp.json).
StrictMCPConfig bool
// --- Config options ---
// Bare enables minimal mode: skip hooks, LSP, plugin sync, attribution,
// auto-memory, keychain reads, and CLAUDE.md auto-discovery.
// Default: true (SDK/programmatic use doesn't need interactive initialization).
Bare bool
// ExcludeDynamicSystemPromptSections moves per-machine sections (cwd, env,
// git status) from the system prompt into the first user message, improving
// Anthropic prompt-cache reuse. Default: true. Ignored when SystemPrompt is set.
ExcludeDynamicSystemPromptSections bool
// SettingSources controls which settings files to load (nil = default, empty = none).
SettingSources []string
// Settings is JSON settings to pass inline.
Settings string
// AddDirs adds directories to the CLI's workspace.
AddDirs []string
// Betas enables beta features.
Betas []string
// Agents is a JSON string defining custom agent types for sub-agent delegation.
// Use WithAgents(map[string]AgentDefinition{...}) to build it.
Agents string
// Agent selects which agent type to run the session as.
// Must match a key in Agents or a built-in agent.
// Passed to the CLI via --agent.
Agent string
// PluginDirs are paths to plugin directories or .zip files to load.
PluginDirs []string
// PluginURLs are URLs to fetch plugin .zip files from.
PluginURLs []string
// --- Environment options ---
// CWD sets the working directory for the CLI process.
CWD string
// Env adds environment variables (KEY=VALUE) for the CLI process.
Env []string
// --- Advanced options ---
// IncludePartialMessages requests partial message streaming events.
IncludePartialMessages bool
// Effort sets the thinking effort level.
// Valid: "low", "medium", "high", "xhigh", "max".
Effort string
// StructuredOutput sets a JSON Schema for structured output.
StructuredOutput string
// Debug enables debug mode. Default: false.
Debug bool
// DebugFilter is an optional category filter for debug output (e.g. "api,hooks").
// Only used when Debug is true.
DebugFilter string
// DebugFile writes debug logs to a specific file path.
// Implicitly enables debug mode.
DebugFile string
// --- eino integration options ---
// EmitToolEvents controls whether Claude Code's internal tool calls are surfaced
// as AgentEvents with ToolCalls.
EmitToolEvents bool
// CustomTools are eino InvokableTools exposed to Claude Code via an embedded
// MCP HTTP server. The server is started on a random localhost port and
// passed to the CLI via --mcp-config.
CustomTools []tool.InvokableTool
// --- Callbacks ---
// Stderr receives each line of stderr output from the CLI process.
Stderr func(string)
// ExtraArgs are additional CLI flags to pass through.
// Key is the flag name (without leading dash), value is the flag value
// (empty string for boolean flags).
ExtraArgs map[string]string
// --- Internal / testing ---
// Runner allows custom CLI execution (default: execRunner).
Runner Runner
}
Options holds all configuration for a ClaudeCodeAgent.
func DefaultOptions ¶
func DefaultOptions() *Options
DefaultOptions returns the recommended default configuration.
func (*Options) BuildArgs ¶
BuildArgs constructs the CLI argument list for one-shot mode (claude -p).
func (*Options) BuildFlags ¶ added in v0.2.0
BuildFlags returns the CLI flags without the positional prompt. This allows callers to insert additional flags before the prompt.
type Runner ¶ added in v0.2.0
type Runner interface {
// Run executes the CLI and returns all responses (batch mode).
Run(ctx context.Context, args []string) ([]cliResponse, error)
// RunStreaming reads CLI responses as they arrive on stdout.
// The channel is closed when the CLI process exits or ctx is cancelled.
RunStreaming(ctx context.Context, args []string) <-chan StreamEvent
}
Runner abstracts CLI process execution for testability and custom deployment (e.g. Docker containers, SSH remotes). The default implementation is [execRunner].
type StreamEvent ¶ added in v0.2.0
type StreamEvent struct {
Response cliResponse
Err error
}
StreamEvent is a single event from the streaming CLI reader.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
chain
command
|
|
|
customtools
command
|
|
|
delegate
command
|
|
|
helloworld
command
|
|
|
parallel
command
|
|
|
runas
command
|
|
|
session
command
|
|
|
tool
command
|