Documentation
¶
Overview ¶
Package claudecode provides the Claude Code SDK for Go.
This SDK enables programmatic interaction with Claude Code CLI through two main APIs: - Query() for one-shot requests with automatic cleanup - Client for bidirectional streaming conversations
The SDK follows Go-native patterns with goroutines and channels instead of async/await, providing context-first design for cancellation and timeouts.
Example usage:
import "github.com/severity1/claude-code-sdk-go"
// One-shot query
messages, err := claudecode.Query(ctx, "Hello, Claude!")
if err != nil {
log.Fatal(err)
}
// Streaming client
client := claudecode.NewClient(
claudecode.WithSystemPrompt("You are a helpful assistant"),
)
defer client.Close()
The SDK provides 100% feature parity with the Python SDK while embracing Go idioms and patterns.
Index ¶
- Constants
- Variables
- func WithClient(ctx context.Context, fn func(Client) error, opts ...Option) error
- func WithClientTransport(ctx context.Context, transport Transport, fn func(Client) error, ...) error
- type AgentDefinition
- type AgentModel
- type AssistantMessage
- type AssistantMessageError
- type BaseError
- type CLINotFoundError
- type Client
- type ClientImpl
- func (c *ClientImpl) Connect(ctx context.Context, _ ...StreamMessage) error
- func (c *ClientImpl) Disconnect() error
- func (c *ClientImpl) GetServerInfo(_ context.Context) (map[string]interface{}, error)
- func (c *ClientImpl) GetStreamIssues() []StreamIssue
- func (c *ClientImpl) GetStreamStats() StreamStats
- func (c *ClientImpl) Interrupt(ctx context.Context) error
- func (c *ClientImpl) Query(ctx context.Context, prompt string) error
- func (c *ClientImpl) QueryStream(ctx context.Context, messages <-chan StreamMessage) error
- func (c *ClientImpl) QueryWithSession(ctx context.Context, prompt string, sessionID string) error
- func (c *ClientImpl) ReceiveMessages(_ context.Context) <-chan Message
- func (c *ClientImpl) ReceiveResponse(_ context.Context) MessageIterator
- type ConnectionError
- type ContentBlock
- type ControlProtocol
- type ControlResponse
- type InitializeRequest
- type InitializeResponse
- type InterruptRequest
- type JSONDecodeError
- type McpHTTPServerConfig
- type McpSSEServerConfig
- type McpServerConfig
- type McpServerType
- type McpStdioServerConfig
- type Message
- type MessageIterator
- type MessageParseError
- type Option
- func WithAddDirs(dirs ...string) Option
- func WithAgent(name string, agent AgentDefinition) Option
- func WithAgents(agents map[string]AgentDefinition) Option
- func WithAllowedTools(tools ...string) Option
- func WithAppendSystemPrompt(prompt string) Option
- func WithAutoAllowBashIfSandboxed(autoAllow bool) Option
- func WithBetas(betas ...SdkBeta) Option
- func WithCLIPath(path string) Option
- func WithClaudeCodeTools() Option
- func WithContinueConversation(continueConversation bool) Option
- func WithCwd(cwd string) Option
- func WithDebugDisabled() Option
- func WithDebugStderr() Option
- func WithDebugWriter(w io.Writer) Option
- func WithDisallowedTools(tools ...string) Option
- func WithEnv(env map[string]string) Option
- func WithEnvVar(key, value string) Option
- func WithExtraArgs(args map[string]*string) Option
- func WithFallbackModel(model string) Option
- func WithForkSession(fork bool) Option
- func WithIncludePartialMessages(include bool) Option
- func WithJSONSchema(schema map[string]any) Option
- func WithLocalPlugin(path string) Option
- func WithMaxBudgetUSD(budget float64) Option
- func WithMaxBufferSize(size int) Option
- func WithMaxThinkingTokens(tokens int) Option
- func WithMaxTurns(turns int) Option
- func WithMcpServers(servers map[string]McpServerConfig) Option
- func WithModel(model string) Option
- func WithOutputFormat(format *OutputFormat) Option
- func WithPartialStreaming() Option
- func WithPermissionMode(mode PermissionMode) Option
- func WithPermissionPromptToolName(toolName string) Option
- func WithPlugin(plugin SdkPluginConfig) Option
- func WithPlugins(plugins []SdkPluginConfig) Option
- func WithResume(sessionID string) Option
- func WithSandbox(sandbox *SandboxSettings) Option
- func WithSandboxEnabled(enabled bool) Option
- func WithSandboxExcludedCommands(commands ...string) Option
- func WithSandboxNetwork(network *SandboxNetworkConfig) Option
- func WithSettingSources(sources ...SettingSource) Option
- func WithSettings(settings string) Option
- func WithStderrCallback(callback func(string)) Option
- func WithSystemPrompt(prompt string) Option
- func WithTools(tools ...string) Option
- func WithToolsPreset(preset string) Option
- func WithTransport(_ Transport) Option
- func WithUser(user string) Option
- type Options
- type OutputFormat
- type PermissionMode
- type ProcessError
- type RawControlMessage
- type ResultMessage
- type SDKControlRequest
- type SDKControlResponse
- type SDKError
- type SandboxIgnoreViolations
- type SandboxNetworkConfig
- type SandboxSettings
- type SdkBeta
- type SdkPluginConfig
- type SdkPluginType
- type SettingSource
- type StreamEvent
- type StreamIssue
- type StreamMessage
- type StreamStats
- type StreamValidator
- type SystemMessage
- type TextBlock
- type ThinkingBlock
- type ToolResultBlock
- type ToolUseBlock
- type ToolsPreset
- type Transport
- type UserMessage
Constants ¶
const ( PermissionModeDefault = shared.PermissionModeDefault PermissionModeAcceptEdits = shared.PermissionModeAcceptEdits PermissionModePlan = shared.PermissionModePlan PermissionModeBypassPermissions = shared.PermissionModeBypassPermissions McpServerTypeStdio = shared.McpServerTypeStdio McpServerTypeSSE = shared.McpServerTypeSSE McpServerTypeHTTP = shared.McpServerTypeHTTP SdkBetaContext1M = shared.SdkBetaContext1M SettingSourceUser = shared.SettingSourceUser SettingSourceProject = shared.SettingSourceProject SettingSourceLocal = shared.SettingSourceLocal SdkPluginTypeLocal = shared.SdkPluginTypeLocal )
Re-export constants
const ( MessageTypeUser = shared.MessageTypeUser MessageTypeAssistant = shared.MessageTypeAssistant MessageTypeSystem = shared.MessageTypeSystem MessageTypeResult = shared.MessageTypeResult // Control protocol message types MessageTypeControlRequest = shared.MessageTypeControlRequest MessageTypeControlResponse = shared.MessageTypeControlResponse // Partial message streaming type MessageTypeStreamEvent = shared.MessageTypeStreamEvent )
Re-export message type constants
const ( ContentBlockTypeText = shared.ContentBlockTypeText ContentBlockTypeThinking = shared.ContentBlockTypeThinking ContentBlockTypeToolUse = shared.ContentBlockTypeToolUse ContentBlockTypeToolResult = shared.ContentBlockTypeToolResult )
Re-export content block type constants
const ( StreamEventTypeContentBlockStart = shared.StreamEventTypeContentBlockStart StreamEventTypeContentBlockDelta = shared.StreamEventTypeContentBlockDelta StreamEventTypeContentBlockStop = shared.StreamEventTypeContentBlockStop StreamEventTypeMessageStart = shared.StreamEventTypeMessageStart StreamEventTypeMessageDelta = shared.StreamEventTypeMessageDelta StreamEventTypeMessageStop = shared.StreamEventTypeMessageStop )
Re-export stream event type constants for Event["type"] discrimination.
const ( AssistantMessageErrorAuthFailed = shared.AssistantMessageErrorAuthFailed AssistantMessageErrorBilling = shared.AssistantMessageErrorBilling AssistantMessageErrorRateLimit = shared.AssistantMessageErrorRateLimit AssistantMessageErrorInvalidRequest = shared.AssistantMessageErrorInvalidRequest AssistantMessageErrorServer = shared.AssistantMessageErrorServer AssistantMessageErrorUnknown = shared.AssistantMessageErrorUnknown )
Re-export AssistantMessageError constants
const ( AgentModelSonnet = shared.AgentModelSonnet AgentModelOpus = shared.AgentModelOpus AgentModelHaiku = shared.AgentModelHaiku AgentModelInherit = shared.AgentModelInherit )
Re-export agent model constants
const ( // Control request subtypes SubtypeInterrupt = control.SubtypeInterrupt SubtypeCanUseTool = control.SubtypeCanUseTool SubtypeInitialize = control.SubtypeInitialize SubtypeSetPermissionMode = control.SubtypeSetPermissionMode SubtypeHookCallback = control.SubtypeHookCallback SubtypeMcpMessage = control.SubtypeMcpMessage // Control response subtypes ResponseSubtypeSuccess = control.ResponseSubtypeSuccess ResponseSubtypeError = control.ResponseSubtypeError )
Re-export control protocol subtype constants
const Version = "0.1.0"
Version represents the current version of the Claude Code SDK for Go.
Variables ¶
var ErrNoMoreMessages = errors.New("no more messages")
ErrNoMoreMessages indicates the message iterator has no more messages.
var NewCLINotFoundError = shared.NewCLINotFoundError
NewCLINotFoundError creates a new CLI not found error.
var NewConnectionError = shared.NewConnectionError
NewConnectionError creates a new connection error.
var NewJSONDecodeError = shared.NewJSONDecodeError
NewJSONDecodeError creates a new JSON decode error.
var NewMessageParseError = shared.NewMessageParseError
NewMessageParseError creates a new message parse error.
var NewProcessError = shared.NewProcessError
NewProcessError creates a new process error.
Functions ¶
func WithClient ¶
WithClient provides Go-idiomatic resource management equivalent to Python SDK's async context manager. It automatically connects to Claude Code CLI, executes the provided function, and ensures proper cleanup. This eliminates the need for manual Connect/Disconnect calls and prevents resource leaks.
The function follows Go's established resource management patterns using defer for guaranteed cleanup, similar to how database connections, files, and other resources are typically managed in Go.
Example - Basic usage:
err := claudecode.WithClient(ctx, func(client claudecode.Client) error {
return client.Query(ctx, "What is 2+2?")
})
if err != nil {
log.Fatal(err)
}
Example - With configuration options:
err := claudecode.WithClient(ctx, func(client claudecode.Client) error {
if err := client.Query(ctx, "Calculate the area of a circle with radius 5"); err != nil {
return err
}
// Process responses
for msg := range client.ReceiveMessages(ctx) {
if assistantMsg, ok := msg.(*claudecode.AssistantMessage); ok {
fmt.Println("Claude:", assistantMsg.Content[0].(*claudecode.TextBlock).Text)
}
}
return nil
}, claudecode.WithSystemPrompt("You are a helpful math tutor"),
claudecode.WithAllowedTools("Read", "Write"))
The client will be automatically connected before fn is called and disconnected after fn returns, even if fn returns an error or panics. This provides 100% functional parity with Python SDK's 'async with ClaudeSDKClient()' pattern while using idiomatic Go resource management.
Parameters:
- ctx: Context for connection management and cancellation
- fn: Function to execute with the connected client
- opts: Optional client configuration options
Returns an error if connection fails or if fn returns an error. Disconnect errors are handled gracefully without overriding the original error from fn.
func WithClientTransport ¶
func WithClientTransport(ctx context.Context, transport Transport, fn func(Client) error, opts ...Option) error
WithClientTransport provides Go-idiomatic resource management with a custom transport for testing. This is the testing-friendly version of WithClient that accepts an explicit transport parameter.
Usage in tests:
transport := newClientMockTransport()
err := WithClientTransport(ctx, transport, func(client claudecode.Client) error {
return client.Query(ctx, "What is 2+2?")
}, opts...)
Parameters:
- ctx: Context for connection management and cancellation
- transport: Custom transport to use (typically a mock for testing)
- fn: Function to execute with the connected client
- opts: Optional client configuration options
Returns an error if connection fails or if fn returns an error. Disconnect errors are handled gracefully without overriding the original error from fn.
Types ¶
type AgentDefinition ¶ added in v0.4.0
type AgentDefinition = shared.AgentDefinition
AgentDefinition defines a programmatic subagent.
type AgentModel ¶ added in v0.4.0
type AgentModel = shared.AgentModel
AgentModel represents the model to use for an agent.
type AssistantMessage ¶
type AssistantMessage = shared.AssistantMessage
AssistantMessage represents a message from the assistant.
type AssistantMessageError ¶ added in v0.3.1
type AssistantMessageError = shared.AssistantMessageError
AssistantMessageError represents error types in assistant messages.
type CLINotFoundError ¶
type CLINotFoundError = shared.CLINotFoundError
CLINotFoundError indicates that the Claude Code CLI was not found.
type Client ¶
type Client interface {
Connect(ctx context.Context, prompt ...StreamMessage) error
Disconnect() error
Query(ctx context.Context, prompt string) error
QueryWithSession(ctx context.Context, prompt string, sessionID string) error
QueryStream(ctx context.Context, messages <-chan StreamMessage) error
ReceiveMessages(ctx context.Context) <-chan Message
ReceiveResponse(ctx context.Context) MessageIterator
Interrupt(ctx context.Context) error
GetStreamIssues() []StreamIssue
GetStreamStats() StreamStats
GetServerInfo(ctx context.Context) (map[string]interface{}, error)
}
Client provides bidirectional streaming communication with Claude Code CLI.
func NewClientWithTransport ¶
NewClientWithTransport creates a new Client with a custom transport (for testing).
type ClientImpl ¶
type ClientImpl struct {
// contains filtered or unexported fields
}
ClientImpl implements the Client interface.
func (*ClientImpl) Connect ¶
func (c *ClientImpl) Connect(ctx context.Context, _ ...StreamMessage) error
Connect establishes a connection to the Claude Code CLI.
func (*ClientImpl) Disconnect ¶
func (c *ClientImpl) Disconnect() error
Disconnect closes the connection to the Claude Code CLI.
func (*ClientImpl) GetServerInfo ¶ added in v0.5.2
func (c *ClientImpl) GetServerInfo(_ context.Context) (map[string]interface{}, error)
GetServerInfo returns diagnostic information about the client and its connection. This provides useful information for debugging, health checks, and support scenarios.
This method is thread-safe and can be called concurrently from multiple goroutines.
Returns a map containing:
- "connected": bool - Whether the client is currently connected
- "transport_type": string - The type of transport being used (e.g., "subprocess")
Returns an error if the client is not connected.
Example:
info, err := client.GetServerInfo(ctx)
if err != nil {
log.Printf("Client not connected: %v", err)
return
}
fmt.Printf("Connected: %v, Transport: %s\n",
info["connected"], info["transport_type"])
func (*ClientImpl) GetStreamIssues ¶ added in v0.3.1
func (c *ClientImpl) GetStreamIssues() []StreamIssue
GetStreamIssues returns validation issues found in the message stream. This can help diagnose problems like missing tool results or incomplete streams.
func (*ClientImpl) GetStreamStats ¶ added in v0.3.1
func (c *ClientImpl) GetStreamStats() StreamStats
GetStreamStats returns statistics about the message stream. This includes counts of tools requested/received and pending tools.
func (*ClientImpl) Interrupt ¶
func (c *ClientImpl) Interrupt(ctx context.Context) error
Interrupt sends an interrupt signal to stop the current operation.
func (*ClientImpl) Query ¶
func (c *ClientImpl) Query(ctx context.Context, prompt string) error
Query sends a simple text query using the default session. This is equivalent to QueryWithSession(ctx, prompt, "default").
Example:
client.Query(ctx, "What is Go?")
func (*ClientImpl) QueryStream ¶
func (c *ClientImpl) QueryStream(ctx context.Context, messages <-chan StreamMessage) error
QueryStream sends a stream of messages.
func (*ClientImpl) QueryWithSession ¶ added in v0.2.3
QueryWithSession sends a simple text query using the specified session ID. Each session maintains its own conversation context, allowing for isolated conversations within the same client connection.
If sessionID is empty, it defaults to "default".
Example:
client.QueryWithSession(ctx, "Remember this", "my-session") client.QueryWithSession(ctx, "What did I just say?", "my-session") // Remembers context client.Query(ctx, "What did I just say?") // Won't remember, different session
func (*ClientImpl) ReceiveMessages ¶
func (c *ClientImpl) ReceiveMessages(_ context.Context) <-chan Message
ReceiveMessages returns a channel of incoming messages.
func (*ClientImpl) ReceiveResponse ¶
func (c *ClientImpl) ReceiveResponse(_ context.Context) MessageIterator
ReceiveResponse returns an iterator for the response messages.
type ConnectionError ¶
type ConnectionError = shared.ConnectionError
ConnectionError represents errors that occur during CLI connection.
type ContentBlock ¶
type ContentBlock = shared.ContentBlock
ContentBlock represents a content block within a message.
type ControlProtocol ¶ added in v0.5.0
ControlProtocol manages bidirectional control communication with CLI.
type ControlResponse ¶ added in v0.5.0
ControlResponse is the inner response structure.
type InitializeRequest ¶ added in v0.5.0
type InitializeRequest = control.InitializeRequest
InitializeRequest for control protocol handshake.
type InitializeResponse ¶ added in v0.5.0
type InitializeResponse = control.InitializeResponse
InitializeResponse from CLI with supported capabilities.
type InterruptRequest ¶ added in v0.5.0
type InterruptRequest = control.InterruptRequest
InterruptRequest to interrupt current operation via control protocol.
type JSONDecodeError ¶
type JSONDecodeError = shared.JSONDecodeError
JSONDecodeError represents JSON parsing errors from CLI responses.
type McpHTTPServerConfig ¶
type McpHTTPServerConfig = shared.McpHTTPServerConfig
McpHTTPServerConfig represents an HTTP MCP server configuration.
type McpSSEServerConfig ¶
type McpSSEServerConfig = shared.McpSSEServerConfig
McpSSEServerConfig represents an SSE MCP server configuration.
type McpServerConfig ¶
type McpServerConfig = shared.McpServerConfig
McpServerConfig represents an MCP server configuration.
type McpServerType ¶
type McpServerType = shared.McpServerType
McpServerType defines the type of MCP server.
type McpStdioServerConfig ¶
type McpStdioServerConfig = shared.McpStdioServerConfig
McpStdioServerConfig represents a stdio MCP server configuration.
type MessageIterator ¶
type MessageIterator = shared.MessageIterator
MessageIterator provides iteration over messages.
func Query ¶
Query executes a one-shot query with automatic cleanup. This follows the Python SDK pattern but uses dependency injection for transport.
func QueryWithTransport ¶
func QueryWithTransport( ctx context.Context, prompt string, transport Transport, opts ...Option, ) (MessageIterator, error)
QueryWithTransport executes a query with a custom transport. The transport parameter is required and must not be nil.
type MessageParseError ¶
type MessageParseError = shared.MessageParseError
MessageParseError represents errors parsing message content.
type Option ¶
type Option func(*Options)
Option configures Options using the functional options pattern.
func WithAddDirs ¶
WithAddDirs adds directories to the context.
func WithAgent ¶ added in v0.4.0
func WithAgent(name string, agent AgentDefinition) Option
WithAgent adds or updates a single agent definition. Multiple calls merge agents (later calls override same-name agents).
func WithAgents ¶ added in v0.4.0
func WithAgents(agents map[string]AgentDefinition) Option
WithAgents sets the programmatic agent definitions. This replaces any existing agents.
func WithAllowedTools ¶
WithAllowedTools sets the allowed tools list.
func WithAppendSystemPrompt ¶
WithAppendSystemPrompt sets the append system prompt.
func WithAutoAllowBashIfSandboxed ¶ added in v0.4.0
WithAutoAllowBashIfSandboxed sets whether to auto-approve bash when sandboxed. If sandbox settings don't exist, they are initialized.
func WithBetas ¶ added in v0.3.1
WithBetas sets the SDK beta features to enable. See https://docs.anthropic.com/en/api/beta-headers
func WithClaudeCodeTools ¶ added in v0.3.2
func WithClaudeCodeTools() Option
WithClaudeCodeTools sets tools to the claude_code preset.
func WithContinueConversation ¶
WithContinueConversation enables conversation continuation.
func WithDebugDisabled ¶ added in v0.4.0
func WithDebugDisabled() Option
WithDebugDisabled discards all CLI debug output. This is more explicit than the default nil behavior but has the same effect.
func WithDebugStderr ¶ added in v0.4.0
func WithDebugStderr() Option
WithDebugStderr redirects CLI debug output to os.Stderr. This is useful for seeing debug output in real-time during development.
func WithDebugWriter ¶ added in v0.4.0
WithDebugWriter sets the writer for CLI debug output. If not set, stderr is isolated to a temporary file (default behavior). Common values: os.Stderr, io.Discard, or a custom io.Writer like bytes.Buffer.
func WithDisallowedTools ¶
WithDisallowedTools sets the disallowed tools list.
func WithEnv ¶ added in v0.2.5
WithEnv sets environment variables for the subprocess. Multiple calls to WithEnv or WithEnvVar merge the values. Later calls override earlier ones for the same key.
func WithEnvVar ¶ added in v0.2.5
WithEnvVar sets a single environment variable for the subprocess. This is a convenience method for setting individual variables.
func WithExtraArgs ¶
WithExtraArgs sets arbitrary CLI flags via ExtraArgs.
func WithFallbackModel ¶ added in v0.3.1
WithFallbackModel sets the fallback model when primary model is unavailable.
func WithForkSession ¶ added in v0.3.3
WithForkSession enables forking to a new session ID when resuming. When true, resumed sessions fork to a new session ID rather than continuing the previous session.
func WithIncludePartialMessages ¶ added in v0.5.0
WithIncludePartialMessages enables streaming of partial message updates. When true, StreamEvent messages are emitted during response generation, providing real-time progress as the model generates content.
func WithJSONSchema ¶ added in v0.4.0
WithJSONSchema is a convenience function that sets a JSON schema output format. This is equivalent to WithOutputFormat(OutputFormatJSONSchema(schema)).
func WithLocalPlugin ¶ added in v0.4.0
WithLocalPlugin appends a local plugin by path. This is a convenience method for the common case of local plugins.
func WithMaxBudgetUSD ¶ added in v0.3.1
WithMaxBudgetUSD sets the maximum budget in USD for API usage.
func WithMaxBufferSize ¶ added in v0.3.1
WithMaxBufferSize sets the maximum buffer size for CLI output.
func WithMaxThinkingTokens ¶
WithMaxThinkingTokens sets the maximum thinking tokens.
func WithMaxTurns ¶
WithMaxTurns sets the maximum number of conversation turns.
func WithMcpServers ¶
func WithMcpServers(servers map[string]McpServerConfig) Option
WithMcpServers sets the MCP server configurations.
func WithOutputFormat ¶ added in v0.4.0
func WithOutputFormat(format *OutputFormat) Option
WithOutputFormat sets the output format for structured responses.
func WithPartialStreaming ¶ added in v0.5.0
func WithPartialStreaming() Option
WithPartialStreaming is a convenience function that enables partial message streaming. Equivalent to WithIncludePartialMessages(true).
func WithPermissionMode ¶
func WithPermissionMode(mode PermissionMode) Option
WithPermissionMode sets the permission mode.
func WithPermissionPromptToolName ¶
WithPermissionPromptToolName sets the permission prompt tool name.
func WithPlugin ¶ added in v0.4.0
func WithPlugin(plugin SdkPluginConfig) Option
WithPlugin appends a single plugin configuration. Multiple calls accumulate plugins.
func WithPlugins ¶ added in v0.4.0
func WithPlugins(plugins []SdkPluginConfig) Option
WithPlugins sets the plugin configurations. This replaces any previously configured plugins.
func WithResume ¶
WithResume sets the session ID to resume.
func WithSandbox ¶ added in v0.4.0
func WithSandbox(sandbox *SandboxSettings) Option
WithSandbox sets the sandbox settings for bash command isolation.
func WithSandboxEnabled ¶ added in v0.4.0
WithSandboxEnabled enables or disables sandbox. If sandbox settings don't exist, they are initialized.
func WithSandboxExcludedCommands ¶ added in v0.4.0
WithSandboxExcludedCommands sets commands that always bypass sandbox. If sandbox settings don't exist, they are initialized.
func WithSandboxNetwork ¶ added in v0.4.0
func WithSandboxNetwork(network *SandboxNetworkConfig) Option
WithSandboxNetwork sets the network configuration for sandbox. If sandbox settings don't exist, they are initialized.
func WithSettingSources ¶ added in v0.3.3
func WithSettingSources(sources ...SettingSource) Option
WithSettingSources sets which settings sources to load. Valid sources are SettingSourceUser, SettingSourceProject, and SettingSourceLocal.
func WithSettings ¶
WithSettings sets the settings file path or JSON string.
func WithStderrCallback ¶ added in v0.5.1
WithStderrCallback sets a callback for receiving CLI stderr output. The callback is invoked for each non-empty line of stderr output. Lines are stripped of trailing whitespace before being passed to the callback. This takes precedence over WithDebugWriter if both are set. Callback panics are silently recovered to prevent crashing the SDK. Matches Python SDK's stderr callback behavior.
func WithSystemPrompt ¶
WithSystemPrompt sets the system prompt.
func WithToolsPreset ¶ added in v0.3.2
WithToolsPreset sets tools to a preset configuration.
func WithTransport ¶
WithTransport sets a custom transport for testing. Since Transport is not part of Options struct, this is handled in client creation.
type Options ¶
Options contains configuration for Claude Code CLI interactions.
func NewOptions ¶
NewOptions creates Options with default values using functional options pattern.
type OutputFormat ¶ added in v0.4.0
type OutputFormat = shared.OutputFormat
OutputFormat specifies the format for structured output.
func OutputFormatJSONSchema ¶ added in v0.4.0
func OutputFormatJSONSchema(schema map[string]any) *OutputFormat
OutputFormatJSONSchema creates an OutputFormat for JSON schema constraints.
type PermissionMode ¶
type PermissionMode = shared.PermissionMode
PermissionMode defines the permission handling mode.
type ProcessError ¶
type ProcessError = shared.ProcessError
ProcessError represents errors from the CLI process execution.
type RawControlMessage ¶ added in v0.5.0
type RawControlMessage = shared.RawControlMessage
RawControlMessage wraps raw control protocol messages for passthrough.
type ResultMessage ¶
type ResultMessage = shared.ResultMessage
ResultMessage represents a result or status message.
type SDKControlRequest ¶ added in v0.5.0
type SDKControlRequest = control.SDKControlRequest
SDKControlRequest represents a control request sent to the CLI.
type SDKControlResponse ¶ added in v0.5.0
type SDKControlResponse = control.SDKControlResponse
SDKControlResponse represents a control response received from the CLI.
type SandboxIgnoreViolations ¶ added in v0.4.0
type SandboxIgnoreViolations = shared.SandboxIgnoreViolations
SandboxIgnoreViolations specifies patterns to ignore during sandbox violations.
type SandboxNetworkConfig ¶ added in v0.4.0
type SandboxNetworkConfig = shared.SandboxNetworkConfig
SandboxNetworkConfig configures network access within sandbox.
type SandboxSettings ¶ added in v0.4.0
type SandboxSettings = shared.SandboxSettings
SandboxSettings configures sandbox behavior for bash command execution.
type SdkPluginConfig ¶ added in v0.4.0
type SdkPluginConfig = shared.SdkPluginConfig
SdkPluginConfig represents a plugin configuration.
type SdkPluginType ¶ added in v0.4.0
type SdkPluginType = shared.SdkPluginType
SdkPluginType represents the type of SDK plugin.
type SettingSource ¶ added in v0.3.3
type SettingSource = shared.SettingSource
SettingSource represents a settings source location.
type StreamEvent ¶ added in v0.5.0
type StreamEvent = shared.StreamEvent
StreamEvent represents a partial message update during streaming.
type StreamIssue ¶ added in v0.3.1
type StreamIssue = shared.StreamIssue
StreamIssue represents a validation issue found in the stream.
type StreamMessage ¶
type StreamMessage = shared.StreamMessage
StreamMessage represents a message in the streaming protocol.
type StreamStats ¶ added in v0.3.1
type StreamStats = shared.StreamStats
StreamStats provides statistics about the message stream.
type StreamValidator ¶ added in v0.3.1
type StreamValidator = shared.StreamValidator
StreamValidator tracks tool requests and results to detect incomplete streams.
type SystemMessage ¶
type SystemMessage = shared.SystemMessage
SystemMessage represents a system prompt message.
type ThinkingBlock ¶
type ThinkingBlock = shared.ThinkingBlock
ThinkingBlock represents a thinking content block.
type ToolResultBlock ¶
type ToolResultBlock = shared.ToolResultBlock
ToolResultBlock represents a tool result content block.
type ToolUseBlock ¶
type ToolUseBlock = shared.ToolUseBlock
ToolUseBlock represents a tool usage content block.
type ToolsPreset ¶ added in v0.3.2
type ToolsPreset = shared.ToolsPreset
ToolsPreset represents a preset tools configuration.
type Transport ¶
type Transport interface {
Connect(ctx context.Context) error
SendMessage(ctx context.Context, message StreamMessage) error
ReceiveMessages(ctx context.Context) (<-chan Message, <-chan error)
Interrupt(ctx context.Context) error
Close() error
GetValidator() *StreamValidator
}
Transport abstracts the communication layer with Claude Code CLI. This interface stays in main package because it's used by client code.
type UserMessage ¶
type UserMessage = shared.UserMessage
UserMessage represents a message from the user.
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
cli
Package cli provides CLI discovery and command building functionality.
|
Package cli provides CLI discovery and command building functionality. |
|
control
Package control provides the SDK control protocol for bidirectional communication with Claude CLI.
|
Package control provides the SDK control protocol for bidirectional communication with Claude CLI. |
|
parser
Package parser provides JSON message parsing functionality with speculative parsing and buffer management.
|
Package parser provides JSON message parsing functionality with speculative parsing and buffer management. |
|
shared
Package shared provides shared types and interfaces used across internal packages.
|
Package shared provides shared types and interfaces used across internal packages. |
|
subprocess
Package subprocess provides the subprocess transport implementation for Claude Code CLI.
|
Package subprocess provides the subprocess transport implementation for Claude Code CLI. |
