Documentation
¶
Overview ¶
Package claudecode provides a Go SDK for interacting with Claude Code CLI.
This package enables programmatic interaction with Claude Code, including:
- One-shot queries via Query() and QuerySync()
- Multi-turn conversations via Client
- Hook registration for tool interception
- Custom tool permission callbacks
- In-process MCP server integration
Quick Start ¶
For simple one-shot queries:
messages, err := claudecode.QuerySync(ctx, "What is 2+2?")
if err != nil {
log.Fatal(err)
}
for _, msg := range messages {
if am, ok := msg.(*claudecode.AssistantMessage); ok {
fmt.Println(am.GetText())
}
}
Multi-Turn Conversations ¶
For interactive conversations with state:
client := claudecode.NewClient(
claudecode.WithModel("claude-sonnet-4-5"),
claudecode.WithCWD("/path/to/project"),
)
if err := client.Connect(ctx); err != nil {
log.Fatal(err)
}
defer client.Close(ctx)
// Send a query (sessionID "default" is used for single-session conversations)
if err := client.Query(ctx, "Help me understand this codebase", "default"); err != nil {
log.Fatal(err)
}
// Receive the response
for msg := range client.ReceiveResponse(ctx) {
if msg.Err != nil {
log.Printf("Error: %v", msg.Err)
continue
}
switch m := msg.Message.(type) {
case *claudecode.AssistantMessage:
fmt.Println(m.GetText())
case *claudecode.ResultMessage:
fmt.Printf("Cost: $%.4f\n", *m.TotalCostUSD)
}
}
Hooks ¶
Register hooks to intercept tool execution:
client := claudecode.NewClient(
claudecode.WithHook(claudecode.HookPreToolUse, claudecode.HookMatcher{
Matcher: "Bash",
Hooks: []claudecode.HookCallback{
func(ctx context.Context, input claudecode.HookInput, toolUseID *string) (claudecode.HookOutput, error) {
// Inspect or modify the tool input
if pi, ok := input.(claudecode.PreToolUseInput); ok {
fmt.Printf("Bash command: %v\n", pi.ToolInput["command"])
}
return claudecode.NewPreToolUseAllow(), nil
},
},
}),
)
Tool Permissions ¶
Implement custom tool permission logic:
client := claudecode.NewClient(
claudecode.WithCanUseTool(func(ctx context.Context, toolName string, input map[string]any, permCtx claudecode.ToolPermissionContext) (claudecode.PermissionResult, error) {
if toolName == "Bash" {
// Deny dangerous commands
if cmd, ok := input["command"].(string); ok {
if strings.Contains(cmd, "rm -rf") {
return claudecode.PermissionDeny{
Message: "Dangerous command not allowed",
}, nil
}
}
}
return claudecode.PermissionAllow{}, nil
}),
)
MCP Servers ¶
Integrate in-process MCP servers with chat.Tool implementations:
client := claudecode.NewClient(
claudecode.WithSDKMCPServer("calculator", myCalculatorTool),
claudecode.WithAllowedTools("mcp__calculator__add"),
)
Configuration Options ¶
The package supports extensive configuration via functional options:
- WithModel: Set the AI model to use
- WithSystemPrompt: Custom system prompt
- WithTools: Explicit tool list
- WithAllowedTools: Restrict available tools
- WithPermissionMode: Set permission behavior
- WithMaxTurns: Limit conversation length
- WithMaxBudgetUSD: Set spending limit
- WithCWD: Set working directory
- WithHook: Register hook callbacks
- WithCanUseTool: Custom permission callback
- WithSDKMCPServer: Add in-process MCP server
See the Option type documentation for the complete list.
Package claudecode provides a Go SDK for interacting with Claude Code CLI.
Index ¶
- Constants
- Variables
- func ClaudeCodeProjectPath(projectDir string) (string, error)
- func GetSessionMessagesFromTranscript(projectDir, sessionID string) ([]chat.Message, error)
- func NewClaudeCodeSandboxPolicy(workDir string, opts ...SandboxOptions) (*sandbox.Policy, error)
- func Query(ctx context.Context, prompt string, opts ...Option) <-chan MessageOrError
- func QueryWithInput(ctx context.Context, input <-chan InputMessage, opts ...Option) <-chan MessageOrError
- func ToChatMessage(msg Message) (chat.Message, error)
- func ToChatMessages(messages []Message) ([]chat.Message, error)
- func TranscriptPath(projectDir, sessionID string) (string, error)
- type AgentDefinition
- type AssistantMessage
- type AssistantMessageError
- type BaseHookInput
- type Beta
- type CanUseToolFunc
- type Client
- func (c *Client) Close(ctx context.Context) error
- func (c *Client) Connect(ctx context.Context) error
- func (c *Client) ConnectWithPrompt(ctx context.Context, prompt string) error
- func (c *Client) ConnectWithStream(ctx context.Context, input <-chan InputMessage) error
- func (c *Client) GetMCPStatus(ctx context.Context) (map[string]any, error)
- func (c *Client) GetServerInfo() map[string]any
- func (c *Client) Interrupt(ctx context.Context) error
- func (c *Client) Query(ctx context.Context, prompt, sessionID string) error
- func (c *Client) QueryStream(ctx context.Context, input <-chan InputMessage, sessionID string) error
- func (c *Client) ReceiveMessages(ctx context.Context) <-chan MessageOrError
- func (c *Client) ReceiveResponse(ctx context.Context) <-chan MessageOrError
- func (c *Client) RewindFiles(ctx context.Context, userMessageUUID string) error
- func (c *Client) SessionID() string
- func (c *Client) SetModel(ctx context.Context, model string) error
- func (c *Client) SetPermissionMode(ctx context.Context, mode PermissionMode) error
- func (c *Client) StreamError() error
- type ContentBlock
- type ControlCancelRequest
- type ControlRequest
- type ControlResponse
- type ControlRouter
- func (r *ControlRouter) GetMCPStatus(ctx context.Context) (map[string]any, error)
- func (r *ControlRouter) GetServerInfo() map[string]any
- func (r *ControlRouter) HandleMessage(ctx context.Context, msg Message, raw []byte) (bool, error)
- func (r *ControlRouter) Initialize(ctx context.Context) (map[string]any, error)
- func (r *ControlRouter) Interrupt(ctx context.Context) error
- func (r *ControlRouter) RewindFiles(ctx context.Context, userMessageUUID string) error
- func (r *ControlRouter) SetModel(ctx context.Context, model string) error
- func (r *ControlRouter) SetPermissionMode(ctx context.Context, mode PermissionMode) error
- type HookCallback
- type HookEvent
- type HookInput
- type HookMatcher
- type HookOutput
- type InputContent
- type InputMessage
- type JSONDecodeError
- type MCPHTTPConfig
- type MCPSDKConfig
- type MCPSSEConfig
- type MCPServerConfig
- type MCPStdioConfig
- type Message
- type MessageOrError
- type MessageParseError
- type NotificationInput
- type NotificationSpecificOutput
- type Option
- func WithAddDirs(dirs ...string) Option
- func WithAgent(name string, def AgentDefinition) Option
- func WithAllowedTools(tools ...string) Option
- func WithBetas(betas ...Beta) Option
- func WithCLIPath(path string) Option
- func WithCWD(cwd string) Option
- func WithCanUseTool(fn CanUseToolFunc) Option
- func WithContinueConversation() Option
- func WithDisallowedTools(tools ...string) Option
- func WithDiscardStderr() Option
- func WithEffort(level string) Option
- func WithEnableFileCheckpointing() Option
- func WithEnv(key, value string) Option
- func WithExtraArg(flag string, value *string) Option
- func WithFallbackModel(model string) Option
- func WithForkSession() Option
- func WithHook(event HookEvent, matcher HookMatcher) Option
- func WithIncludePartialMessages() Option
- func WithJSONSchemaOutput(schema map[string]any) Option
- func WithMCPServer(name string, config MCPServerConfig) Option
- func WithMCPServersJSON(jsonStr string) Option
- func WithMCPServersPath(path string) Option
- func WithMaxBudgetUSD(budget float64) Option
- func WithMaxThinkingTokens(tokens int) Option
- func WithMaxTurns(turns int) Option
- func WithModel(model string) Option
- func WithOSSandboxPolicy(policy *sandbox.Policy) Option
- func WithOutputFormat(format map[string]any) Option
- func WithPermissionMode(mode PermissionMode) Option
- func WithPermissionPromptToolName(name string) Option
- func WithPlugin(config PluginConfig) Option
- func WithResume(sessionID string) Option
- func WithSDKMCPServer(name string, tools ...chat.Tool) Option
- func WithSandbox(settings SandboxSettings) Option
- func WithSettingSources(sources ...SettingSource) Option
- func WithSettings(settings string) Option
- func WithStderr(fn func(string)) Option
- func WithSystemPrompt(prompt string) Option
- func WithSystemPromptPreset(append string) Option
- func WithThinking(config ThinkingConfig) Option
- func WithTools(tools ...string) Option
- func WithToolsPreset() Option
- type Options
- type PermissionAllow
- type PermissionDeny
- type PermissionMode
- type PermissionRequestInput
- type PermissionRequestSpecificOutput
- type PermissionResult
- type PermissionRuleValue
- type PermissionUpdate
- type PluginConfig
- type PostToolUseFailureInput
- type PostToolUseFailureSpecificOutput
- type PostToolUseInput
- type PostToolUseSpecificOutput
- type PreCompactInput
- type PreToolUseInput
- type PreToolUseSpecificOutput
- type ProcessError
- type ResultMessage
- type SandboxIgnoreViolations
- type SandboxNetworkConfig
- type SandboxOptions
- type SandboxSettings
- type SettingSource
- type StopInput
- type StreamEvent
- type SubagentStartInput
- type SubagentStartSpecificOutput
- type SubagentStopInput
- type SubprocessTransport
- func (t *SubprocessTransport) Close(ctx context.Context) error
- func (t *SubprocessTransport) Connect(ctx context.Context) error
- func (t *SubprocessTransport) EndInput(ctx context.Context) error
- func (t *SubprocessTransport) IsReady() bool
- func (t *SubprocessTransport) ReadMessages(ctx context.Context) <-chan MessageOrError
- func (t *SubprocessTransport) Write(ctx context.Context, data string) error
- type SystemMessage
- type TextBlock
- type ThinkingAdaptive
- type ThinkingBlock
- type ThinkingConfig
- type ThinkingDisabled
- type ThinkingEnabled
- type ToolPermissionContext
- type ToolResultBlock
- type ToolUseBlock
- type Transport
- type UnknownContentBlock
- type UsageStats
- type UserMessage
- type UserPromptSubmitInput
- type UserPromptSubmitSpecificOutput
Constants ¶
const ( // DefaultControlTimeout is the default timeout for control requests. DefaultControlTimeout = 60 * time.Second // DefaultInitializeTimeout is the default timeout for initialize requests. DefaultInitializeTimeout = 60 * time.Second )
const ( // MinimumCLIVersion is the minimum supported Claude Code CLI version. MinimumCLIVersion = "2.0.0" // DefaultStreamCloseTimeout is the default timeout for closing stdin. DefaultStreamCloseTimeout = 60 * time.Second // SDKVersion is the version of this SDK. SDKVersion = "0.1.0" )
Variables ¶
var ( // ErrCLINotFound indicates the Claude Code CLI binary was not found. ErrCLINotFound = errors.New("claude code CLI not found") // ErrConnection indicates a connection failure to Claude Code. ErrConnection = errors.New("connection to claude code failed") // ErrProcess indicates the Claude Code process encountered an error. ErrProcess = errors.New("claude code process error") // ErrJSONDecode indicates a failure to decode JSON from the CLI. ErrJSONDecode = errors.New("failed to decode JSON from CLI") // ErrProtocol indicates a control protocol error. ErrProtocol = errors.New("control protocol error") // ErrTimeout indicates an operation timed out. ErrTimeout = errors.New("operation timed out") // ErrNotConnected indicates the client is not connected. ErrNotConnected = errors.New("client not connected") // ErrStreamingRequired indicates an operation requires streaming mode. ErrStreamingRequired = errors.New("operation requires streaming mode") // ErrClientClosed indicates the client has been closed and cannot be reused. ErrClientClosed = errors.New("client has been closed and cannot be reused") // ErrUnknownMessageType indicates an unrecognized message type in a transcript. ErrUnknownMessageType = errors.New("unknown message type") )
Sentinel errors for the claudecode package.
Functions ¶
func ClaudeCodeProjectPath ¶
ClaudeCodeProjectPath computes the path to Claude Code's project directory for a given working directory. Claude Code escapes paths by replacing "/" with "-". For example, "/Users/bob/myproject" becomes "~/.claude/projects/-Users-bob-myproject".
func GetSessionMessagesFromTranscript ¶
GetSessionMessagesFromTranscript reads a Claude Code transcript and converts it to chat.Message format. This reads directly from Claude Code's storage, making Claude Code the source of truth for conversation history.
func NewClaudeCodeSandboxPolicy ¶
func NewClaudeCodeSandboxPolicy(workDir string, opts ...SandboxOptions) (*sandbox.Policy, error)
NewClaudeCodeSandboxPolicy creates an OS-level sandbox policy for running the Claude Code CLI. Access is restricted to:
- Read-only: system dirs, Homebrew (/opt), Claude CLI binary (~/.local/share/claude, ~/.local/bin)
- Read-write: project directory (workDir), Claude config (~/.claude/)
- Network: allowed (required for Anthropic API)
Optional SandboxOptions can be provided to configure additional features like virtualenv activation.
func Query ¶
func Query(ctx context.Context, prompt string, opts ...Option) <-chan MessageOrError
Query performs a one-shot query with a string prompt. Internally delegates to QueryWithInput using the streaming control protocol, which means hooks, SDK MCP servers, and canUseTool callbacks are all supported.
func QueryWithInput ¶
func QueryWithInput(ctx context.Context, input <-chan InputMessage, opts ...Option) <-chan MessageOrError
QueryWithInput performs a query with a streaming input channel. This opens a bidirectional connection that supports the full control protocol, enabling multi-turn conversations, hooks, SDK MCP servers, and can_use_tool callbacks. Query delegates to this function internally.
func ToChatMessage ¶
ToChatMessage converts a single claudecode.Message to chat.Message. Returns an error for unsupported message types (system, result, stream_event, control).
func ToChatMessages ¶
ToChatMessages converts a slice of claudecode messages to chat messages. Filters to only user and assistant messages, silently skipping others. Builds a lookup map to populate tool names on ToolResultBlock conversions.
func TranscriptPath ¶
TranscriptPath returns the path to a Claude Code transcript file for a given project directory and session ID.
Types ¶
type AgentDefinition ¶
type AgentDefinition struct {
Description string `json:"description"`
Prompt string `json:"prompt"`
Tools []string `json:"tools,omitzero"`
Model string `json:"model,omitzero"` // "sonnet", "opus", "haiku", "inherit"
}
AgentDefinition defines a custom agent.
type AssistantMessage ¶
type AssistantMessage struct {
Content []ContentBlock `json:"content"`
Model string `json:"model"`
ParentToolUseID string `json:"parent_tool_use_id,omitzero"`
Error AssistantMessageError `json:"error,omitzero"`
}
AssistantMessage represents a message from the assistant.
func (*AssistantMessage) GetText ¶
func (m *AssistantMessage) GetText() string
GetText returns all text content from an AssistantMessage.
func (*AssistantMessage) GetToolCalls ¶
func (m *AssistantMessage) GetToolCalls() []ToolUseBlock
GetToolCalls returns all ToolUseBlocks from an AssistantMessage.
type AssistantMessageError ¶
type AssistantMessageError string
AssistantMessageError represents an error in the assistant message.
const ( ErrAuthenticationFailed AssistantMessageError = "authentication_failed" ErrBillingError AssistantMessageError = "billing_error" ErrRateLimit AssistantMessageError = "rate_limit" ErrInvalidRequest AssistantMessageError = "invalid_request" ErrServerError AssistantMessageError = "server_error" ErrUnknown AssistantMessageError = "unknown" )
type BaseHookInput ¶
type BaseHookInput struct {
HookEventName string `json:"hook_event_name"`
SessionID string `json:"session_id"`
TranscriptPath string `json:"transcript_path"`
CWD string `json:"cwd"`
PermissionMode string `json:"permission_mode,omitzero"`
}
BaseHookInput contains fields common to all hook inputs.
type CanUseToolFunc ¶
type CanUseToolFunc func(ctx context.Context, toolName string, input map[string]any, permCtx ToolPermissionContext) (PermissionResult, error)
CanUseToolFunc is the callback type for tool permission decisions.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client provides bidirectional, interactive conversations with Claude Code.
func NewClientWithTransport ¶
NewClientWithTransport creates a client with a custom transport.
func (*Client) Connect ¶
Connect starts the CLI and prepares for interactive communication. This opens a connection without sending an initial prompt. Use Query or QueryStream to send messages after connecting.
func (*Client) ConnectWithPrompt ¶
ConnectWithPrompt starts the CLI and sends an initial string prompt. Use ReceiveResponse to get the response messages.
func (*Client) ConnectWithStream ¶
func (c *Client) ConnectWithStream(ctx context.Context, input <-chan InputMessage) error
ConnectWithStream starts the CLI with a streaming input channel. Messages from the input channel are forwarded to the CLI.
func (*Client) GetMCPStatus ¶
GetMCPStatus returns the MCP server connection status.
func (*Client) GetServerInfo ¶
GetServerInfo returns the cached initialization result.
func (*Client) Query ¶
Query sends a string prompt to Claude. sessionID identifies the conversation session (use "default" for the default session).
func (*Client) QueryStream ¶
func (c *Client) QueryStream(ctx context.Context, input <-chan InputMessage, sessionID string) error
QueryStream sends messages from a channel to Claude. sessionID identifies the conversation session (use "default" for the default session).
func (*Client) ReceiveMessages ¶
func (c *Client) ReceiveMessages(ctx context.Context) <-chan MessageOrError
ReceiveMessages returns all messages from the CLI. Control messages are already routed by the internal routeMessages goroutine.
func (*Client) ReceiveResponse ¶
func (c *Client) ReceiveResponse(ctx context.Context) <-chan MessageOrError
ReceiveResponse returns messages until and including a ResultMessage. Unlike ReceiveMessages, this reads directly from the internal channel to avoid leaking goroutines when stopping early at ResultMessage.
func (*Client) RewindFiles ¶
RewindFiles rewinds tracked files to a specific user message.
func (*Client) SetPermissionMode ¶
func (c *Client) SetPermissionMode(ctx context.Context, mode PermissionMode) error
SetPermissionMode changes the permission mode.
func (*Client) StreamError ¶
StreamError returns any error that occurred during input streaming. Returns nil if no error has occurred.
type ContentBlock ¶
type ContentBlock interface {
// contains filtered or unexported methods
}
ContentBlock is a marker interface for all content block types.
type ControlCancelRequest ¶
ControlCancelRequest represents a request to cancel an operation.
type ControlRequest ¶
type ControlRequest struct {
Type string `json:"type"`
RequestID string `json:"request_id"`
Request json.RawMessage `json:"request"`
}
ControlRequest represents an incoming control request from the CLI.
type ControlResponse ¶
type ControlResponse struct {
Type string `json:"type"`
Response json.RawMessage `json:"response"`
}
ControlResponse represents a control response to send to the CLI.
type ControlRouter ¶
type ControlRouter struct {
// contains filtered or unexported fields
}
ControlRouter manages the control protocol for bidirectional communication.
func NewControlRouter ¶
func NewControlRouter(transport Transport, opts *Options) *ControlRouter
NewControlRouter creates a new control router.
func (*ControlRouter) GetMCPStatus ¶
GetMCPStatus returns the MCP server status.
func (*ControlRouter) GetServerInfo ¶
func (r *ControlRouter) GetServerInfo() map[string]any
GetServerInfo returns the cached initialization result.
func (*ControlRouter) HandleMessage ¶
HandleMessage processes an incoming message and routes control messages. Returns true if the message was a control message and was handled.
func (*ControlRouter) Initialize ¶
Initialize performs the initialization handshake with the CLI.
func (*ControlRouter) Interrupt ¶
func (r *ControlRouter) Interrupt(ctx context.Context) error
Interrupt sends an interrupt control request.
func (*ControlRouter) RewindFiles ¶
func (r *ControlRouter) RewindFiles(ctx context.Context, userMessageUUID string) error
RewindFiles rewinds tracked files to a specific user message.
func (*ControlRouter) SetModel ¶
func (r *ControlRouter) SetModel(ctx context.Context, model string) error
SetModel changes the model.
func (*ControlRouter) SetPermissionMode ¶
func (r *ControlRouter) SetPermissionMode(ctx context.Context, mode PermissionMode) error
SetPermissionMode changes the permission mode.
type HookCallback ¶
HookCallback is the function signature for hook callbacks. toolUseID is nil for non-tool hooks, non-nil for tool hooks (may be empty string).
type HookEvent ¶
type HookEvent string
HookEvent represents the type of hook event.
const ( HookPreToolUse HookEvent = "PreToolUse" HookPostToolUse HookEvent = "PostToolUse" HookPostToolUseFailure HookEvent = "PostToolUseFailure" HookUserPromptSubmit HookEvent = "UserPromptSubmit" HookNotification HookEvent = "Notification" HookStop HookEvent = "Stop" HookSubagentStop HookEvent = "SubagentStop" HookSubagentStart HookEvent = "SubagentStart" HookPreCompact HookEvent = "PreCompact" HookPermissionRequest HookEvent = "PermissionRequest" )
type HookInput ¶
type HookInput interface {
// contains filtered or unexported methods
}
HookInput is a marker interface for all hook input types.
type HookMatcher ¶
type HookMatcher struct {
// Matcher is a tool name pattern (e.g., "Bash", "Write|MultiEdit|Edit").
Matcher string
// Hooks are the callback functions to invoke.
Hooks []HookCallback
// Timeout is the maximum time to wait for the hook (default: 60s).
Timeout time.Duration
}
HookMatcher configures when and how hooks are invoked.
type HookOutput ¶
type HookOutput struct {
// Async execution (mutually exclusive with sync fields)
Async bool `json:"async,omitzero"`
AsyncTimeout int `json:"asyncTimeout,omitzero"` // milliseconds
// Sync control fields
// Continue is nil to use protocol default (true), or explicitly set to control flow.
// The protocol specifies that omitting this field means "continue".
Continue *bool `json:"continue,omitzero"`
SuppressOutput bool `json:"suppressOutput,omitzero"`
StopReason string `json:"stopReason,omitzero"`
// Decision fields
Decision string `json:"decision,omitzero"` // "block"
SystemMessage string `json:"systemMessage,omitzero"`
Reason string `json:"reason,omitzero"`
// Event-specific output
HookSpecificOutput any `json:"hookSpecificOutput,omitzero"`
}
HookOutput is the response from a hook callback.
The Continue field uses *bool because the Claude Code CLI protocol specifies that when the "continue" field is omitted (nil), execution should continue (equivalent to continue: true). This is NOT fallback behavior - it's the protocol specification. Using *bool allows us to distinguish between:
- nil: use protocol default (continue)
- true: explicitly continue
- false: explicitly block
func NewHookOutputBlock ¶
func NewHookOutputBlock(reason string) HookOutput
NewHookOutputBlock creates a hook output that blocks execution.
func NewHookOutputContinue ¶
func NewHookOutputContinue() HookOutput
NewHookOutputContinue creates a hook output that allows execution to continue.
func NewPostToolUseContext ¶
func NewPostToolUseContext(context string) HookOutput
NewPostToolUseContext creates a PostToolUse output with additional context.
func NewPreToolUseAllow ¶
func NewPreToolUseAllow() HookOutput
NewPreToolUseAllow creates a PreToolUse output that allows the tool to run.
func NewPreToolUseDeny ¶
func NewPreToolUseDeny(reason string) HookOutput
NewPreToolUseDeny creates a PreToolUse output that denies the tool.
func NewPreToolUseModify ¶
func NewPreToolUseModify(updatedInput map[string]any) HookOutput
NewPreToolUseModify creates a PreToolUse output that modifies the tool input.
type InputContent ¶
InputContent represents the content of an input message.
type InputMessage ¶
type InputMessage struct {
Type string `json:"type"`
Message InputContent `json:"message"`
ParentToolUseID string `json:"parent_tool_use_id,omitzero"`
SessionID string `json:"session_id,omitzero"`
}
InputMessage represents a message to send to Claude.
func NewUserInput ¶
func NewUserInput(content string) InputMessage
NewUserInput creates a new user input message.
func (InputMessage) WithParentToolUseID ¶
func (m InputMessage) WithParentToolUseID(toolUseID string) InputMessage
WithParentToolUseID sets the parent tool use ID for the input message.
func (InputMessage) WithSessionID ¶
func (m InputMessage) WithSessionID(sessionID string) InputMessage
WithSessionID sets the session ID for the input message.
type JSONDecodeError ¶
JSONDecodeError represents a JSON decoding error from CLI output.
func (*JSONDecodeError) Error ¶
func (e *JSONDecodeError) Error() string
Error implements the error interface.
func (*JSONDecodeError) Unwrap ¶
func (e *JSONDecodeError) Unwrap() error
Unwrap returns the underlying error.
type MCPHTTPConfig ¶
type MCPHTTPConfig struct {
URL string `json:"url"`
Headers map[string]string `json:"headers,omitzero"`
}
MCPHTTPConfig configures an MCP server via HTTP.
type MCPSDKConfig ¶
MCPSDKConfig configures an in-process MCP server using chat.Tool instances.
type MCPSSEConfig ¶
type MCPSSEConfig struct {
URL string `json:"url"`
Headers map[string]string `json:"headers,omitzero"`
}
MCPSSEConfig configures an MCP server via SSE.
type MCPServerConfig ¶
type MCPServerConfig interface {
// contains filtered or unexported methods
}
MCPServerConfig is a marker interface for MCP server configurations.
type MCPStdioConfig ¶
type MCPStdioConfig struct {
Command string `json:"command"`
Args []string `json:"args,omitzero"`
Env map[string]string `json:"env,omitzero"`
}
MCPStdioConfig configures an MCP server via stdio.
type Message ¶
type Message interface {
// contains filtered or unexported methods
}
Message is a marker interface for all message types.
func ParseTranscript ¶
ParseTranscript reads a JSONL transcript file and returns parsed messages. Empty lines are skipped. Returns an error with line number for malformed JSON.
type MessageOrError ¶
MessageOrError represents either a message or an error from the transport.
type MessageParseError ¶
MessageParseError represents an error parsing a message from CLI output.
func (*MessageParseError) Error ¶
func (e *MessageParseError) Error() string
Error implements the error interface.
type NotificationInput ¶
type NotificationInput struct {
BaseHookInput
Message string `json:"message"`
Title string `json:"title"`
NotificationType string `json:"notification_type"`
}
NotificationInput is the input for Notification hooks.
type NotificationSpecificOutput ¶
type NotificationSpecificOutput struct {
HookEventName string `json:"hookEventName"` // "Notification"
AdditionalContext string `json:"additionalContext,omitzero"`
}
NotificationSpecificOutput is hook-specific output for Notification.
type Option ¶
type Option func(*Options)
Option is a functional option for configuring a Claude Code session.
func WithAddDirs ¶
WithAddDirs adds directories to the allowed paths.
func WithAgent ¶
func WithAgent(name string, def AgentDefinition) Option
WithAgent adds a custom agent definition.
func WithAllowedTools ¶
WithAllowedTools sets the allowed tools.
func WithCLIPath ¶
WithCLIPath sets the path to the Claude CLI.
func WithCanUseTool ¶
func WithCanUseTool(fn CanUseToolFunc) Option
WithCanUseTool sets the tool permission callback (requires streaming mode).
func WithContinueConversation ¶
func WithContinueConversation() Option
WithContinueConversation enables continuing the previous conversation.
func WithDisallowedTools ¶
WithDisallowedTools sets the disallowed tools.
func WithDiscardStderr ¶
func WithDiscardStderr() Option
WithDiscardStderr discards all stderr output from the CLI. By default, stderr is written to os.Stderr.
func WithEffort ¶
WithEffort sets the effort level ("low", "medium", "high", "max").
func WithEnableFileCheckpointing ¶
func WithEnableFileCheckpointing() Option
WithEnableFileCheckpointing enables file change tracking.
func WithExtraArg ¶
WithExtraArg adds an extra CLI argument. value=nil means --flag, value="" means --flag "", value="x" means --flag x.
func WithFallbackModel ¶
WithFallbackModel sets the fallback model.
func WithForkSession ¶
func WithForkSession() Option
WithForkSession forks the resumed session instead of continuing it.
func WithHook ¶
func WithHook(event HookEvent, matcher HookMatcher) Option
WithHook registers a hook for the given event.
func WithIncludePartialMessages ¶
func WithIncludePartialMessages() Option
WithIncludePartialMessages includes partial messages in the stream.
func WithJSONSchemaOutput ¶
WithJSONSchemaOutput sets the JSON schema for structured output.
func WithMCPServer ¶
func WithMCPServer(name string, config MCPServerConfig) Option
WithMCPServer adds an MCP server configuration.
func WithMCPServersJSON ¶
WithMCPServersJSON sets the MCP servers as a JSON string.
func WithMCPServersPath ¶
WithMCPServersPath sets the path to an MCP servers JSON file.
func WithMaxBudgetUSD ¶
WithMaxBudgetUSD sets the maximum budget in USD.
func WithMaxThinkingTokens ¶
WithMaxThinkingTokens sets the maximum thinking tokens.
func WithMaxTurns ¶
WithMaxTurns sets the maximum number of conversation turns.
func WithOSSandboxPolicy ¶
WithOSSandboxPolicy sets an OS-level sandbox policy for the Claude Code CLI process. This restricts the CLI's filesystem access at the operating system level.
func WithOutputFormat ¶
WithOutputFormat sets the output format configuration. The format should follow the structure {"type":"json_schema","schema":{...}}. When set, this takes precedence over WithJSONSchemaOutput for the CLI arg.
func WithPermissionMode ¶
func WithPermissionMode(mode PermissionMode) Option
WithPermissionMode sets the permission mode.
func WithPermissionPromptToolName ¶
WithPermissionPromptToolName sets the permission prompt tool name.
func WithPlugin ¶
func WithPlugin(config PluginConfig) Option
WithPlugin adds a plugin configuration.
func WithResume ¶
WithResume resumes a specific session by ID.
func WithSDKMCPServer ¶
WithSDKMCPServer adds an in-process MCP server from chat.Tool instances.
func WithSandbox ¶
func WithSandbox(settings SandboxSettings) Option
WithSandbox configures sandbox settings.
func WithSettingSources ¶
func WithSettingSources(sources ...SettingSource) Option
WithSettingSources sets which setting sources to load.
func WithSettings ¶
WithSettings sets the settings JSON string or file path.
func WithStderr ¶
WithStderr sets a callback for stderr output from the CLI. By default, stderr is written to os.Stderr. Use this to handle it differently.
func WithSystemPrompt ¶
WithSystemPrompt sets a custom system prompt.
func WithSystemPromptPreset ¶
WithSystemPromptPreset uses the default system prompt and appends additional text.
func WithThinking ¶
func WithThinking(config ThinkingConfig) Option
WithThinking configures the model's thinking behavior. When set, this takes precedence over WithMaxThinkingTokens.
func WithToolsPreset ¶
func WithToolsPreset() Option
WithToolsPreset uses the default tools preset (--tools default).
type Options ¶
type Options struct {
// contains filtered or unexported fields
}
Options holds all configuration for a Claude Code session.
type PermissionAllow ¶
type PermissionAllow struct {
UpdatedInput map[string]any
UpdatedPermissions []PermissionUpdate
}
PermissionAllow allows tool execution, optionally with modifications.
type PermissionDeny ¶
PermissionDeny denies tool execution.
type PermissionMode ¶
type PermissionMode string
PermissionMode represents the permission mode for Claude Code.
const ( PermissionDefault PermissionMode = "default" PermissionAcceptEdits PermissionMode = "acceptEdits" PermissionPlan PermissionMode = "plan" PermissionBypassPermissions PermissionMode = "bypassPermissions" )
type PermissionRequestInput ¶
type PermissionRequestInput struct {
BaseHookInput
ToolName string `json:"tool_name"`
ToolInput map[string]any `json:"tool_input"`
PermissionSuggestions []any `json:"permission_suggestions,omitzero"`
}
PermissionRequestInput is the input for PermissionRequest hooks.
type PermissionRequestSpecificOutput ¶
type PermissionRequestSpecificOutput struct {
HookEventName string `json:"hookEventName"` // "PermissionRequest"
Decision map[string]any `json:"decision,omitzero"`
}
PermissionRequestSpecificOutput is hook-specific output for PermissionRequest.
type PermissionResult ¶
type PermissionResult interface {
// contains filtered or unexported methods
}
PermissionResult is a marker interface for permission decisions.
type PermissionRuleValue ¶
PermissionRuleValue represents a permission rule.
type PermissionUpdate ¶
type PermissionUpdate struct {
Type string // "addRules", "replaceRules", "removeRules", "setMode", "addDirectories", "removeDirectories"
Rules []PermissionRuleValue
Behavior string // "allow", "deny", "ask"
Mode PermissionMode
Directories []string
Destination string // "userSettings", "projectSettings", "localSettings", "session"
}
PermissionUpdate represents a permission update request.
func (PermissionUpdate) ToMap ¶
func (p PermissionUpdate) ToMap() map[string]any
ToMap converts PermissionUpdate to a map with correct camelCase JSON keys.
type PluginConfig ¶
PluginConfig configures a plugin.
type PostToolUseFailureInput ¶
type PostToolUseFailureInput struct {
BaseHookInput
ToolName string `json:"tool_name"`
ToolInput map[string]any `json:"tool_input"`
ToolUseID string `json:"tool_use_id"`
Error string `json:"error"`
IsInterrupt bool `json:"is_interrupt"`
}
PostToolUseFailureInput is the input for PostToolUseFailure hooks.
type PostToolUseFailureSpecificOutput ¶
type PostToolUseFailureSpecificOutput struct {
HookEventName string `json:"hookEventName"` // "PostToolUseFailure"
AdditionalContext string `json:"additionalContext,omitzero"`
}
PostToolUseFailureSpecificOutput is hook-specific output for PostToolUseFailure.
type PostToolUseInput ¶
type PostToolUseInput struct {
BaseHookInput
ToolName string `json:"tool_name"`
ToolInput map[string]any `json:"tool_input"`
ToolResponse any `json:"tool_response"`
ToolUseID string `json:"tool_use_id"`
}
PostToolUseInput is the input for PostToolUse hooks.
type PostToolUseSpecificOutput ¶
type PostToolUseSpecificOutput struct {
HookEventName string `json:"hookEventName"` // "PostToolUse"
AdditionalContext string `json:"additionalContext,omitzero"`
UpdatedMCPToolOutput any `json:"updatedMCPToolOutput,omitzero"`
}
PostToolUseSpecificOutput is hook-specific output for PostToolUse.
type PreCompactInput ¶
type PreCompactInput struct {
BaseHookInput
Trigger string `json:"trigger"` // "manual" or "auto"
CustomInstructions string `json:"custom_instructions,omitzero"`
}
PreCompactInput is the input for PreCompact hooks.
type PreToolUseInput ¶
type PreToolUseInput struct {
BaseHookInput
ToolName string `json:"tool_name"`
ToolInput map[string]any `json:"tool_input"`
ToolUseID string `json:"tool_use_id"`
}
PreToolUseInput is the input for PreToolUse hooks.
type PreToolUseSpecificOutput ¶
type PreToolUseSpecificOutput struct {
HookEventName string `json:"hookEventName"` // "PreToolUse"
PermissionDecision string `json:"permissionDecision,omitzero"` // "allow", "deny", "ask"
PermissionDecisionReason string `json:"permissionDecisionReason,omitzero"`
UpdatedInput map[string]any `json:"updatedInput,omitzero"`
AdditionalContext string `json:"additionalContext,omitzero"`
}
PreToolUseSpecificOutput is hook-specific output for PreToolUse.
type ProcessError ¶
ProcessError represents an error from the Claude Code CLI process.
func (*ProcessError) Error ¶
func (e *ProcessError) Error() string
Error implements the error interface.
func (*ProcessError) Unwrap ¶
func (e *ProcessError) Unwrap() error
Unwrap returns the underlying error.
type ResultMessage ¶
type ResultMessage struct {
Subtype string `json:"subtype"`
DurationMS int `json:"duration_ms"`
DurationAPIMS int `json:"duration_api_ms"`
IsError bool `json:"is_error"`
NumTurns int `json:"num_turns"`
SessionID string `json:"session_id"`
TotalCostUSD *float64 `json:"total_cost_usd,omitzero"`
Usage *UsageStats `json:"usage,omitzero"`
Result string `json:"result,omitzero"`
StructuredOutput any `json:"structured_output,omitzero"`
}
ResultMessage represents the final result of a conversation.
type SandboxIgnoreViolations ¶
type SandboxIgnoreViolations struct {
File []string `json:"file,omitzero"`
Network []string `json:"network,omitzero"`
}
SandboxIgnoreViolations configures violations to ignore.
type SandboxNetworkConfig ¶
type SandboxNetworkConfig struct {
AllowUnixSockets []string `json:"allowUnixSockets,omitzero"`
AllowAllUnixSockets bool `json:"allowAllUnixSockets,omitzero"`
AllowLocalBinding bool `json:"allowLocalBinding,omitzero"`
HTTPProxyPort int `json:"httpProxyPort,omitzero"`
SOCKSProxyPort int `json:"socksProxyPort,omitzero"`
}
SandboxNetworkConfig configures network access in sandbox.
type SandboxOptions ¶
type SandboxOptions struct {
// VirtualEnvPath is the absolute path to a Python virtualenv to activate.
// When set, the sandbox will:
// - Set VIRTUAL_ENV to this path
// - Prepend the virtualenv's bin directory to PATH
// - Mount the virtualenv directory as read-only
// This enables Python scripts executed by Claude Code's Bash tool to use
// packages installed in the virtualenv.
VirtualEnvPath string
// SessionDisplayDir is the host path to a session-specific directory for
// generated images and visualizations. When set, the sandbox will mount
// this directory as read-write at <workDir>/session-display/. Claude Code
// can then save images to session-display/ which will be accessible via
// the Display tool.
SessionDisplayDir string
// MplConfigDir is the absolute path to a matplotlib configuration directory.
// When set, the sandbox will:
// - Mount this directory as read-write
// - Set the MPLCONFIGDIR environment variable
// This prevents matplotlib from trying to write to ~/.matplotlib (which
// is not writable in the sandbox) and allows font cache persistence.
MplConfigDir string
}
SandboxOptions configures optional features for the Claude Code sandbox.
type SandboxSettings ¶
type SandboxSettings struct {
Enabled bool `json:"enabled,omitzero"`
AutoAllowBashIfSandboxed bool `json:"autoAllowBashIfSandboxed,omitzero"`
ExcludedCommands []string `json:"excludedCommands,omitzero"`
AllowUnsandboxedCommands bool `json:"allowUnsandboxedCommands,omitzero"`
Network *SandboxNetworkConfig `json:"network,omitzero"`
IgnoreViolations *SandboxIgnoreViolations `json:"ignoreViolations,omitzero"`
EnableWeakerNestedSandbox bool `json:"enableWeakerNestedSandbox,omitzero"`
}
SandboxSettings configures the sandbox for bash commands.
type SettingSource ¶
type SettingSource string
SettingSource represents a settings source.
const ( SettingSourceUser SettingSource = "user" SettingSourceProject SettingSource = "project" SettingSourceLocal SettingSource = "local" )
type StopInput ¶
type StopInput struct {
BaseHookInput
StopHookActive bool `json:"stop_hook_active"`
}
StopInput is the input for Stop hooks.
type StreamEvent ¶
type StreamEvent struct {
UUID string `json:"uuid"`
SessionID string `json:"session_id"`
Event map[string]any `json:"event"`
ParentToolUseID string `json:"parent_tool_use_id,omitzero"`
}
StreamEvent represents a partial message update during streaming.
type SubagentStartInput ¶
type SubagentStartInput struct {
BaseHookInput
AgentID string `json:"agent_id"`
AgentType string `json:"agent_type"`
}
SubagentStartInput is the input for SubagentStart hooks.
type SubagentStartSpecificOutput ¶
type SubagentStartSpecificOutput struct {
HookEventName string `json:"hookEventName"` // "SubagentStart"
AdditionalContext string `json:"additionalContext,omitzero"`
}
SubagentStartSpecificOutput is hook-specific output for SubagentStart.
type SubagentStopInput ¶
type SubagentStopInput struct {
BaseHookInput
StopHookActive bool `json:"stop_hook_active"`
AgentID string `json:"agent_id"`
AgentTranscriptPath string `json:"agent_transcript_path"`
AgentType string `json:"agent_type"`
}
SubagentStopInput is the input for SubagentStop hooks.
type SubprocessTransport ¶
type SubprocessTransport struct {
// contains filtered or unexported fields
}
SubprocessTransport implements Transport using the Claude Code CLI subprocess.
func NewSubprocessTransport ¶
func NewSubprocessTransport(opts *Options) *SubprocessTransport
NewSubprocessTransport creates a new subprocess transport with the given options.
func (*SubprocessTransport) Close ¶
func (t *SubprocessTransport) Close(ctx context.Context) error
Close closes the transport and releases resources.
func (*SubprocessTransport) Connect ¶
func (t *SubprocessTransport) Connect(ctx context.Context) error
Connect starts the Claude Code CLI subprocess.
func (*SubprocessTransport) EndInput ¶
func (t *SubprocessTransport) EndInput(ctx context.Context) error
EndInput closes stdin to signal end of input.
func (*SubprocessTransport) IsReady ¶
func (t *SubprocessTransport) IsReady() bool
IsReady returns true if the transport is ready for communication.
func (*SubprocessTransport) ReadMessages ¶
func (t *SubprocessTransport) ReadMessages(ctx context.Context) <-chan MessageOrError
ReadMessages returns a channel that yields messages from the transport.
type SystemMessage ¶
type SystemMessage struct {
Subtype string `json:"subtype"`
Data map[string]any `json:"data,omitzero"`
}
SystemMessage represents a system message with metadata.
type TextBlock ¶
type TextBlock struct {
Text string `json:"text"`
}
TextBlock represents text content.
type ThinkingAdaptive ¶
type ThinkingAdaptive struct{}
ThinkingAdaptive lets the model decide when to think.
type ThinkingBlock ¶
ThinkingBlock represents thinking/reasoning content.
type ThinkingConfig ¶
type ThinkingConfig interface {
// contains filtered or unexported methods
}
ThinkingConfig configures the model's thinking behavior.
type ThinkingEnabled ¶
type ThinkingEnabled struct {
BudgetTokens int
}
ThinkingEnabled enables thinking with a token budget.
type ToolPermissionContext ¶
type ToolPermissionContext struct {
Suggestions []PermissionUpdate
BlockedPath string // path that triggered the permission check
}
ToolPermissionContext provides context for permission decisions.
type ToolResultBlock ¶
type ToolResultBlock struct {
ToolUseID string `json:"tool_use_id"`
Content any `json:"content,omitzero"` // string or []ContentBlock
IsError bool `json:"is_error,omitzero"`
}
ToolResultBlock represents the result of a tool execution.
type ToolUseBlock ¶
type ToolUseBlock struct {
ID string `json:"id"`
Name string `json:"name"`
Input map[string]any `json:"input"`
}
ToolUseBlock represents a tool invocation.
type Transport ¶
type Transport interface {
// Connect establishes the connection to Claude Code.
Connect(ctx context.Context) error
// Write sends data to the transport.
Write(ctx context.Context, data string) error
// ReadMessages returns a channel that yields messages from the transport.
// The channel is closed when the transport is closed or an error occurs.
ReadMessages(ctx context.Context) <-chan MessageOrError
// EndInput signals the end of input (closes stdin for process transports).
EndInput(ctx context.Context) error
// Close closes the transport and releases resources.
Close(ctx context.Context) error
// IsReady returns true if the transport is ready for communication.
IsReady() bool
}
Transport is the low-level I/O interface for Claude communication. Exposed for custom transport implementations (e.g., remote connections).
type UnknownContentBlock ¶
type UnknownContentBlock struct {
Type string `json:"type"`
Data map[string]any `json:"-"` // Raw data preserved for inspection
}
UnknownContentBlock represents an unrecognized content block type. This enables forward compatibility when the CLI introduces new block types.
type UsageStats ¶
type UsageStats struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
CacheRead int `json:"cache_read,omitzero"`
CacheWrite int `json:"cache_write,omitzero"`
}
UsageStats represents token usage statistics.
type UserMessage ¶
type UserMessage struct {
Content any `json:"-"` // string or []ContentBlock
UUID string `json:"uuid,omitzero"`
ParentToolUseID string `json:"parent_tool_use_id,omitzero"`
ToolUseResult any `json:"tool_use_result,omitzero"` // map[string]any or []any
}
UserMessage represents a message from the user.
func (*UserMessage) GetText ¶
func (m *UserMessage) GetText() string
GetText returns the text content from a UserMessage. If content is a string, returns it directly. If content is []ContentBlock, concatenates all TextBlock texts.
type UserPromptSubmitInput ¶
type UserPromptSubmitInput struct {
BaseHookInput
Prompt string `json:"prompt"`
}
UserPromptSubmitInput is the input for UserPromptSubmit hooks.
type UserPromptSubmitSpecificOutput ¶
type UserPromptSubmitSpecificOutput struct {
HookEventName string `json:"hookEventName"` // "UserPromptSubmit"
AdditionalContext string `json:"additionalContext,omitzero"`
}
UserPromptSubmitSpecificOutput is hook-specific output for UserPromptSubmit.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package chat defines the core types for LLM tool interaction.
|
Package chat defines the core types for LLM tool interaction. |
|
internal
|
|
|
testing/fstools
Package fstools provides filesystem tools for testing MCP server implementations.
|
Package fstools provides filesystem tools for testing MCP server implementations. |
|
Package mcp provides a JSON-RPC based Model Context Protocol (MCP) server implementation.
|
Package mcp provides a JSON-RPC based Model Context Protocol (MCP) server implementation. |
|
Package sandbox provides secure command execution by spawning child processes in isolated sandboxes.
|
Package sandbox provides secure command execution by spawning child processes in isolated sandboxes. |