Documentation
¶
Overview ¶
Package claudecode provides the Claude Agent 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, providing context-first design for cancellation and timeouts.
Example usage:
import "github.com/tea4go/claude-agent-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()
Index ¶
- Constants
- Variables
- func CanonicalSkillName(name string) string
- func RegisterSkill(name string, handler func(context.Context, string) (string, error))
- func RegisterSkills(skills map[string]func(context.Context, string) (string, error))
- func SkillRegistryScopedName(pluginName, skillName string) string
- 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 AsyncHookJSONOutput
- type BaseError
- type BaseHookInput
- type CLINotFoundError
- type CanUseToolCallback
- type Client
- type ClientImpl
- func (c *ClientImpl) Connect(ctx context.Context, _ ...StreamMessage) error
- func (c *ClientImpl) Disconnect() error
- func (c *ClientImpl) GetMcpStatus(ctx context.Context) (*McpStatusResponse, error)
- func (c *ClientImpl) GetServerInfo(_ context.Context) (map[string]interface{}, error)
- func (c *ClientImpl) GetSlashCommands(ctx context.Context) ([]SlashCommand, 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
- func (c *ClientImpl) RewindFiles(ctx context.Context, messageUUID string) error
- func (c *ClientImpl) SetModel(ctx context.Context, model *string) error
- func (c *ClientImpl) SetPermissionMode(ctx context.Context, mode PermissionMode) error
- type ConnectionError
- type ContentBlock
- type ControlProtocol
- type ControlResponse
- type EffortLevel
- type GetMcpStatusRequest
- type HookCallback
- type HookContext
- type HookEvent
- type HookJSONOutput
- type HookMatcher
- type InitializeRequest
- type InitializeResponse
- type InterruptRequest
- type JSONDecodeError
- type McpContent
- type McpHTTPServerConfig
- type McpSSEServerConfig
- type McpSdkServerConfig
- type McpServerConfig
- type McpServerConnectionStatus
- type McpServerInfo
- type McpServerStatus
- type McpServerStatusConfig
- type McpServerType
- type McpStatusResponse
- type McpStdioServerConfig
- type McpTool
- type McpToolAnnotations
- type McpToolDefinition
- type McpToolHandler
- type McpToolInfo
- type McpToolResult
- type Message
- type MessageIterator
- type MessageParseError
- type NotificationHookInput
- type NotificationHookSpecificOutput
- 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 WithCanUseTool(callback CanUseToolCallback) 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 WithEffort(effort EffortLevel) Option
- func WithEnableFileCheckpointing(enable bool) 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 WithFileCheckpointing() Option
- func WithForkSession(fork bool) Option
- func WithHook(event HookEvent, matcher string, callback HookCallback) Option
- func WithHooks(hooks map[HookEvent][]HookMatcher) 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 WithPostToolUseHook(matcher string, callback HookCallback) Option
- func WithPreToolUseHook(matcher string, callback HookCallback) 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 WithSdkMcpServer(name string, server *McpSdkServerConfig) Option
- func WithSettingSources(sources ...SettingSource) Option
- func WithSettings(settings string) Option
- func WithSkillImplementation(name string, handler func(context.Context, string) (string, error)) Option
- func WithSkillImplementations(skills map[string]func(context.Context, string) (string, error)) Option
- func WithSkillRegistry(root string, names ...string) Option
- func WithSkillRegistryAll(root string) Option
- func WithSkills(skills any) Option
- func WithSkillsAll() Option
- func WithSkillsDisabled() Option
- func WithSkillsList(names ...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 PermissionRequestHookInput
- type PermissionRequestHookSpecificOutput
- type PermissionResult
- type PermissionResultAllow
- type PermissionResultDeny
- type PermissionRuleValue
- type PermissionUpdate
- type PermissionUpdateType
- type PostToolUseFailureHookInput
- type PostToolUseFailureHookSpecificOutput
- type PostToolUseHookInput
- type PostToolUseHookSpecificOutput
- type PreCompactHookInput
- type PreToolUseHookInput
- type PreToolUseHookSpecificOutput
- type ProcessError
- type RateLimitEventMessage
- type RateLimitInfo
- type RawControlMessage
- type RawMessage
- type ResultMessage
- type SDKControlRequest
- type SDKControlResponse
- type SDKError
- type SDKSessionInfo
- type SandboxIgnoreViolations
- type SandboxNetworkConfig
- type SandboxSettings
- type SdkBeta
- type SdkMcpServer
- type SdkPluginConfig
- type SdkPluginType
- type SessionContentBlock
- type SessionContentType
- type SessionMessage
- type SessionMessageContent
- type SessionOption
- type SetModelRequest
- type SetPermissionModeRequest
- type SettingSource
- type SkillRegistryConfig
- type SlashCommand
- type StopHookInput
- type StreamEvent
- type StreamIssue
- type StreamMessage
- type StreamStats
- type StreamValidator
- type SubagentStartHookInput
- type SubagentStartHookSpecificOutput
- type SubagentStopHookInput
- type SystemMessage
- type TextBlock
- type ThinkingBlock
- type ToolAnnotations
- type ToolOption
- type ToolPermissionContext
- type ToolResultBlock
- type ToolUseBlock
- type ToolsPreset
- type Transport
- type Usage
- type UserMessage
- type UserPromptSubmitHookInput
- type UserPromptSubmitHookSpecificOutput
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 EffortLow = shared.EffortLow EffortMedium = shared.EffortMedium EffortHigh = shared.EffortHigh EffortXHigh = shared.EffortXHigh EffortMax = shared.EffortMax )
Re-export constants
const ( PermissionUpdateTypeAddRules = control.PermissionUpdateTypeAddRules PermissionUpdateTypeReplaceRules = control.PermissionUpdateTypeReplaceRules PermissionUpdateTypeRemoveRules = control.PermissionUpdateTypeRemoveRules PermissionUpdateTypeSetMode = control.PermissionUpdateTypeSetMode PermissionUpdateTypeAddDirectories = control.PermissionUpdateTypeAddDirectories PermissionUpdateTypeRemoveDirectories = control.PermissionUpdateTypeRemoveDirectories )
Permission update type constants
const ( // HookEventPreToolUse is triggered before a tool is executed. HookEventPreToolUse = control.HookEventPreToolUse // HookEventPostToolUse is triggered after a tool is executed. HookEventPostToolUse = control.HookEventPostToolUse // HookEventPostToolUseFailure is triggered after a tool execution fails. HookEventPostToolUseFailure = control.HookEventPostToolUseFailure // HookEventUserPromptSubmit is triggered when a user submits a prompt. HookEventUserPromptSubmit = control.HookEventUserPromptSubmit // HookEventStop is triggered when the session is stopping. HookEventStop = control.HookEventStop // HookEventSubagentStop is triggered when a subagent is stopping. HookEventSubagentStop = control.HookEventSubagentStop // HookEventPreCompact is triggered before context compaction. HookEventPreCompact = control.HookEventPreCompact // HookEventNotification is triggered when the CLI emits a notification. HookEventNotification = control.HookEventNotification // HookEventSubagentStart is triggered when a subagent starts. HookEventSubagentStart = control.HookEventSubagentStart // HookEventPermissionRequest is triggered when a permission is requested. HookEventPermissionRequest = control.HookEventPermissionRequest )
Hook event constants.
const ( SessionContentTypeString = session.ContentTypeString SessionContentTypeBlocks = session.ContentTypeBlocks )
SessionContentType constants.
const ( SessionBlockTypeText = session.BlockTypeText SessionBlockTypeThinking = session.BlockTypeThinking SessionBlockTypeRedactedThinking = session.BlockTypeRedactedThinking SessionBlockTypeToolUse = session.BlockTypeToolUse SessionBlockTypeServerToolUse = session.BlockTypeServerToolUse SessionBlockTypeToolResult = session.BlockTypeToolResult SessionBlockTypeImage = session.BlockTypeImage SessionBlockTypeWebSearchToolResult = session.BlockTypeWebSearchToolResult SessionBlockTypeWebFetchToolResult = session.BlockTypeWebFetchToolResult SessionBlockTypeCodeExecutionToolResult = session.BlockTypeCodeExecutionToolResult SessionBlockTypeBashCodeExecutionToolResult = session.BlockTypeBashCodeExecutionToolResult SessionBlockTypeTextEditorCodeExecToolResult = session.BlockTypeTextEditorCodeExecToolResult SessionBlockTypeToolSearchToolResult = session.BlockTypeToolSearchToolResult SessionBlockTypeContainerUpload = session.BlockTypeContainerUpload )
Session content block type 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 // Session heartbeat carrying rate-limit window state. MessageTypeRateLimitEvent = shared.MessageTypeRateLimitEvent )
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 ( StopReasonEndTurn = shared.StopReasonEndTurn StopReasonToolUse = shared.StopReasonToolUse StopReasonStopSequence = shared.StopReasonStopSequence StopReasonMaxTokens = shared.StopReasonMaxTokens )
Re-export stop reason constants
const ( AgentModelSonnet = shared.AgentModelSonnet AgentModelOpus = shared.AgentModelOpus AgentModelHaiku = shared.AgentModelHaiku AgentModelInherit = shared.AgentModelInherit )
Re-export agent model constants
const ( McpServerConnectionStatusConnected = control.McpServerConnectionStatusConnected McpServerConnectionStatusFailed = control.McpServerConnectionStatusFailed McpServerConnectionStatusNeedsAuth = control.McpServerConnectionStatusNeedsAuth McpServerConnectionStatusPending = control.McpServerConnectionStatusPending McpServerConnectionStatusDisabled = control.McpServerConnectionStatusDisabled )
Re-export MCP server connection status constants
const ( McpServerConfigTypeStdio = control.McpServerConfigTypeStdio McpServerConfigTypeSSE = control.McpServerConfigTypeSSE McpServerConfigTypeHTTP = control.McpServerConfigTypeHTTP McpServerConfigTypeSDK = control.McpServerConfigTypeSDK McpServerConfigTypeClaudeAI = control.McpServerConfigTypeClaudeAI )
Re-export MCP server config type constants for McpServerStatusConfig.Type.
const ( // Control request subtypes SubtypeInterrupt = control.SubtypeInterrupt SubtypeCanUseTool = control.SubtypeCanUseTool SubtypeInitialize = control.SubtypeInitialize SubtypeSetPermissionMode = control.SubtypeSetPermissionMode SubtypeSetModel = control.SubtypeSetModel SubtypeHookCallback = control.SubtypeHookCallback SubtypeMcpMessage = control.SubtypeMcpMessage SubtypeGetMcpStatus = control.SubtypeGetMcpStatus SubtypeRewindFiles = control.SubtypeRewindFiles // Control response subtypes ResponseSubtypeSuccess = control.ResponseSubtypeSuccess ResponseSubtypeError = control.ResponseSubtypeError )
Re-export control protocol subtype constants
const DefaultSkillRegistryPluginName = shared.DefaultSkillRegistryPluginName
DefaultSkillRegistryPluginName is the plugin name used by WithSkillRegistry and WithSkillRegistryAll when no explicit plugin name is configured.
const McpServerTypeSdk = shared.McpServerTypeSdk
McpServerTypeSdk represents an in-process SDK MCP server.
const (
RateLimitStatusAllowed = shared.RateLimitStatusAllowed
)
Rate-limit window status constants.
const SkillsAll = shared.SkillsAll
SkillsAll is the sentinel value for enabling every discovered Skill. Passing this to WithSkills enables all Skills found on the filesystem.
const Version = "0.1.0"
Version represents the current version of the Claude Agent SDK for Go.
Variables ¶
var AsCLINotFoundError = shared.AsCLINotFoundError
AsCLINotFoundError returns the error as a *CLINotFoundError if it is one, or nil otherwise.
var AsConnectionError = shared.AsConnectionError
AsConnectionError returns the error as a *ConnectionError if it is one, or nil otherwise.
var AsJSONDecodeError = shared.AsJSONDecodeError
AsJSONDecodeError returns the error as a *JSONDecodeError if it is one, or nil otherwise.
var AsMessageParseError = shared.AsMessageParseError
AsMessageParseError returns the error as a *MessageParseError if it is one, or nil otherwise.
var AsProcessError = shared.AsProcessError
AsProcessError returns the error as a *ProcessError if it is one, or nil otherwise.
var ErrNoMoreMessages = errors.New("no more messages")
ErrNoMoreMessages indicates the message iterator has no more messages.
var IsCLINotFoundError = shared.IsCLINotFoundError
IsCLINotFoundError reports whether err is or wraps a CLINotFoundError.
var IsConnectionError = shared.IsConnectionError
IsConnectionError reports whether err is or wraps a ConnectionError.
var IsJSONDecodeError = shared.IsJSONDecodeError
IsJSONDecodeError reports whether err is or wraps a JSONDecodeError.
var IsMessageParseError = shared.IsMessageParseError
IsMessageParseError reports whether err is or wraps a MessageParseError.
var IsProcessError = shared.IsProcessError
IsProcessError reports whether err is or wraps a ProcessError.
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 NewPermissionResultAllow = control.NewPermissionResultAllow
NewPermissionResultAllow creates an Allow result with proper defaults. Use this to permit tool execution.
Example:
return claudecode.NewPermissionResultAllow(), nil
var NewPermissionResultDeny = control.NewPermissionResultDeny
NewPermissionResultDeny creates a Deny result with proper defaults. Use this to deny tool execution with a reason message.
Example:
return claudecode.NewPermissionResultDeny("Only Read tool is allowed"), nil
var NewProcessError = shared.NewProcessError
NewProcessError creates a new process error.
var WithIncludeWorktrees = session.WithIncludeWorktrees
WithIncludeWorktrees controls whether git worktree directories are included when searching for sessions. Defaults to true. Only has effect when a directory is specified via WithSessionDirectory.
var WithSessionDirectory = session.WithSessionDirectory
WithSessionDirectory scopes the query to a specific project directory. When omitted, sessions across all projects are searched.
var WithSessionLimit = session.WithSessionLimit
WithSessionLimit sets the maximum number of results to return.
var WithSessionOffset = session.WithSessionOffset
WithSessionOffset skips the first n messages (GetSessionMessages only).
Functions ¶
func CanonicalSkillName ¶ added in v0.0.9
CanonicalSkillName returns the runtime name Claude Code assigns to a plugin Skill. Pass the declared frontmatter name, or the directory name when the Skill does not declare a different name.
func RegisterSkill ¶
func RegisterSkills ¶
func SkillRegistryScopedName ¶ added in v0.0.9
SkillRegistryScopedName returns the scoped runtime name used to explicitly invoke a Skill exposed by WithSkillRegistry. Pass an empty pluginName to use DefaultSkillRegistryPluginName.
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 ¶
type AgentDefinition = shared.AgentDefinition
AgentDefinition defines a programmatic subagent.
type AgentModel ¶
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 ¶
type AssistantMessageError = shared.AssistantMessageError
AssistantMessageError represents error types in assistant messages.
type AsyncHookJSONOutput ¶
type AsyncHookJSONOutput = control.AsyncHookJSONOutput
AsyncHookJSONOutput indicates the hook will respond asynchronously.
type BaseHookInput ¶
type BaseHookInput = control.BaseHookInput
BaseHookInput contains common fields present across all hook events.
type CLINotFoundError ¶
type CLINotFoundError = shared.CLINotFoundError
CLINotFoundError indicates that the Claude Code CLI was not found.
type CanUseToolCallback ¶
type CanUseToolCallback = control.CanUseToolCallback
CanUseToolCallback is invoked when CLI requests permission to use a tool. The callback receives tool name, input parameters, and permission context. Return PermissionResultAllow to permit, PermissionResultDeny to deny. The callback must be thread-safe as it may be invoked concurrently.
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
// SetModel changes the AI model during a streaming session.
// Pass nil to reset to the default model.
// Only works in streaming mode (after Connect()).
SetModel(ctx context.Context, model *string) error
// SetPermissionMode changes the permission mode during a streaming session.
// Valid modes: PermissionModeDefault, PermissionModeAcceptEdits,
// PermissionModePlan, PermissionModeBypassPermissions.
// Only works in streaming mode (after Connect()).
SetPermissionMode(ctx context.Context, mode PermissionMode) error
// RewindFiles reverts tracked files to their state at a specific user message.
// The messageUUID should be the UUID from a UserMessage received during the session.
// Requires WithFileCheckpointing() or WithEnableFileCheckpointing(true) option.
// Only works in streaming mode (after Connect()).
RewindFiles(ctx context.Context, messageUUID string) error
// GetMcpStatus returns the connection status of all configured MCP servers.
// Only works in streaming mode (after Connect()).
GetMcpStatus(ctx context.Context) (*McpStatusResponse, error)
// GetSlashCommands returns slash commands available in the current session.
// Only works in streaming mode (after Connect()).
GetSlashCommands(ctx context.Context) ([]SlashCommand, 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) GetMcpStatus ¶
func (c *ClientImpl) GetMcpStatus(ctx context.Context) (*McpStatusResponse, error)
GetMcpStatus returns the connection status of all configured MCP servers. Returns error if not connected or if the control request fails.
func (*ClientImpl) GetServerInfo ¶
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) GetSlashCommands ¶ added in v0.0.5
func (c *ClientImpl) GetSlashCommands(ctx context.Context) ([]SlashCommand, error)
GetSlashCommands returns slash commands available in the current session. Returns error if not connected or if the control request fails.
func (*ClientImpl) GetStreamIssues ¶
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 ¶
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 ¶
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.
func (*ClientImpl) RewindFiles ¶
func (c *ClientImpl) RewindFiles(ctx context.Context, messageUUID string) error
RewindFiles reverts tracked files to their state at a specific user message. The messageUUID should be the UUID from a UserMessage received during the session. Requires file checkpointing to be enabled via WithFileCheckpointing() option. Returns error if not connected or the request fails.
Example:
client := claudecode.NewClient(claudecode.WithFileCheckpointing())
// ... connect and receive messages, capture UUID from UserMessage
if msg, ok := receivedMsg.(*claudecode.UserMessage); ok && msg.UUID != nil {
err := client.RewindFiles(ctx, *msg.UUID)
}
func (*ClientImpl) SetModel ¶
func (c *ClientImpl) SetModel(ctx context.Context, model *string) error
SetModel changes the AI model during a streaming session. Pass nil to reset to the default model. Returns error if not connected or if the control request fails.
Example - Change to a specific model:
model := "claude-sonnet-4-5" err := client.SetModel(ctx, &model)
Example - Reset to default model:
err := client.SetModel(ctx, nil)
func (*ClientImpl) SetPermissionMode ¶
func (c *ClientImpl) SetPermissionMode(ctx context.Context, mode PermissionMode) error
SetPermissionMode changes the permission mode during a streaming session. Valid modes: PermissionModeDefault, PermissionModeAcceptEdits, PermissionModePlan, PermissionModeBypassPermissions. Returns error if not connected or if the control request fails.
Example - Enable auto-accept for edits:
err := client.SetPermissionMode(ctx, claudecode.PermissionModeAcceptEdits)
Example - Switch to plan mode:
err := client.SetPermissionMode(ctx, claudecode.PermissionModePlan)
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 ¶
ControlProtocol manages bidirectional control communication with CLI.
type ControlResponse ¶
ControlResponse is the inner response structure.
type EffortLevel ¶ added in v0.0.6
type EffortLevel = shared.EffortLevel
EffortLevel controls how many tokens Claude spends per response.
type GetMcpStatusRequest ¶
type GetMcpStatusRequest = control.GetMcpStatusRequest
GetMcpStatusRequest to query MCP server status via control protocol.
type HookCallback ¶
type HookCallback = control.HookCallback
HookCallback is the function signature for hook callbacks.
type HookContext ¶
type HookContext = control.HookContext
HookContext provides context information for hook callbacks.
type HookJSONOutput ¶
type HookJSONOutput = control.HookJSONOutput
HookJSONOutput is the synchronous hook output structure.
type HookMatcher ¶
type HookMatcher = control.HookMatcher
HookMatcher defines which hooks to trigger for a given pattern.
type InitializeRequest ¶
type InitializeRequest = control.InitializeRequest
InitializeRequest for control protocol handshake.
type InitializeResponse ¶
type InitializeResponse = control.InitializeResponse
InitializeResponse from CLI with supported capabilities.
type InterruptRequest ¶
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 McpContent ¶
type McpContent = shared.McpContent
McpContent represents content returned by a tool.
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 McpSdkServerConfig ¶
type McpSdkServerConfig = shared.McpSdkServerConfig
McpSdkServerConfig configures an in-process SDK MCP server.
func CreateSDKMcpServer ¶
func CreateSDKMcpServer(name, version string, tools ...*McpTool) *McpSdkServerConfig
CreateSDKMcpServer creates an in-process MCP server with the given tools. This is the Go equivalent of Python's create_sdk_mcp_server().
Example:
calculator := claudecode.CreateSDKMcpServer("calculator", "1.0.0", addTool, sqrtTool)
client := claudecode.NewClient(
claudecode.WithSdkMcpServer("calc", calculator),
claudecode.WithAllowedTools("mcp__calc__add", "mcp__calc__sqrt"),
)
type McpServerConfig ¶
type McpServerConfig = shared.McpServerConfig
McpServerConfig represents an MCP server configuration.
type McpServerConnectionStatus ¶
type McpServerConnectionStatus = control.McpServerConnectionStatus
McpServerConnectionStatus represents the connection state of an MCP server.
type McpServerInfo ¶
type McpServerInfo = control.McpServerInfo
McpServerInfo contains version information about a connected MCP server.
type McpServerStatus ¶
type McpServerStatus = control.McpServerStatus
McpServerStatus contains the full status of a single MCP server.
type McpServerStatusConfig ¶
type McpServerStatusConfig = control.McpServerStatusConfig
McpServerStatusConfig covers all MCP server config variants, discriminated by Type.
type McpServerType ¶
type McpServerType = shared.McpServerType
McpServerType defines the type of MCP server.
type McpStatusResponse ¶
type McpStatusResponse = control.McpStatusResponse
McpStatusResponse is the response payload for a GetMcpStatus request.
type McpStdioServerConfig ¶
type McpStdioServerConfig = shared.McpStdioServerConfig
McpStdioServerConfig represents a stdio MCP server configuration.
type McpTool ¶
type McpTool struct {
// contains filtered or unexported fields
}
McpTool represents a tool for SDK MCP servers.
Create tools using NewTool() for proper initialization.
func NewTool ¶
func NewTool(name, description string, inputSchema map[string]any, handler McpToolHandler, opts ...ToolOption) *McpTool
NewTool creates a new MCP tool definition.
Example:
addTool := claudecode.NewTool(
"add",
"Add two numbers together",
map[string]any{
"type": "object",
"properties": map[string]any{
"a": map[string]any{"type": "number"},
"b": map[string]any{"type": "number"},
},
"required": []string{"a", "b"},
},
func(ctx context.Context, args map[string]any) (*claudecode.McpToolResult, error) {
a, _ := args["a"].(float64)
b, _ := args["b"].(float64)
return &claudecode.McpToolResult{
Content: []claudecode.McpContent{
{Type: "text", Text: fmt.Sprintf("%.2f + %.2f = %.2f", a, b, a+b)},
},
}, nil
},
)
func (*McpTool) Annotations ¶ added in v0.0.4
func (t *McpTool) Annotations() *ToolAnnotations
Annotations returns the tool's MCP-spec annotations, or nil if none were attached via WithToolAnnotations.
func (*McpTool) Call ¶
Call executes the tool handler with the given context and arguments. Returns an error if no handler is set.
func (*McpTool) Description ¶
Description returns the tool's description.
func (*McpTool) InputSchema ¶
InputSchema returns the tool's input JSON schema.
type McpToolAnnotations ¶
type McpToolAnnotations = control.McpToolAnnotations
McpToolAnnotations describes behavioral hints for an MCP tool.
type McpToolDefinition ¶
type McpToolDefinition = shared.McpToolDefinition
McpToolDefinition describes a tool exposed by an MCP server.
type McpToolHandler ¶
McpToolHandler is the function signature for tool handlers. Context-first per Go idioms, explicit error return.
Example:
handler := func(ctx context.Context, args map[string]any) (*McpToolResult, error) {
a, _ := args["a"].(float64)
b, _ := args["b"].(float64)
return &McpToolResult{
Content: []McpContent{{Type: "text", Text: fmt.Sprintf("%f", a+b)}},
}, nil
}
type McpToolInfo ¶
type McpToolInfo = control.McpToolInfo
McpToolInfo describes a tool exposed by an MCP server.
type McpToolResult ¶
type McpToolResult = shared.McpToolResult
McpToolResult represents the result of a tool call.
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 NotificationHookInput ¶ added in v0.0.4
type NotificationHookInput = control.NotificationHookInput
NotificationHookInput is the input for Notification hook events.
type NotificationHookSpecificOutput ¶ added in v0.0.4
type NotificationHookSpecificOutput = control.NotificationHookSpecificOutput
NotificationHookSpecificOutput contains Notification-specific output fields.
type Option ¶
type Option func(*Options)
Option configures Options using the functional options pattern.
func WithAddDirs ¶
WithAddDirs adds directories to the context.
func WithAgent ¶
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 ¶
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 ¶
WithAutoAllowBashIfSandboxed sets whether to auto-approve bash when sandboxed. If sandbox settings don't exist, they are initialized.
func WithBetas ¶
WithBetas sets the SDK beta features to enable. See https://docs.anthropic.com/en/api/beta-headers
func WithCanUseTool ¶
func WithCanUseTool(callback CanUseToolCallback) Option
WithCanUseTool sets the permission callback for tool usage requests. The callback is invoked when Claude CLI requests permission to use a tool. It receives the tool name, input parameters, and context for decision-making.
Example - Allow all Read tool calls, deny others:
client := claudecode.NewClient(
claudecode.WithCanUseTool(func(
ctx context.Context,
toolName string,
input map[string]any,
permCtx claudecode.ToolPermissionContext,
) (claudecode.PermissionResult, error) {
if toolName == "Read" {
return claudecode.NewPermissionResultAllow(), nil
}
return claudecode.NewPermissionResultDeny("Only Read tool is allowed"), nil
}),
)
The callback must be thread-safe as it may be invoked concurrently. If no callback is set, all tool requests are denied (secure default).
func WithClaudeCodeTools ¶
func WithClaudeCodeTools() Option
WithClaudeCodeTools sets tools to the claude_code preset.
func WithContinueConversation ¶
WithContinueConversation enables conversation continuation.
func WithDebugDisabled ¶
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 ¶
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 ¶
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 WithEffort ¶ added in v0.0.6
func WithEffort(effort EffortLevel) Option
WithEffort sets the effort level (--effort), controlling how many tokens Claude spends per response. Known levels are EffortLow..EffortMax, but any value is passed through to the CLI to tolerate future levels.
func WithEnableFileCheckpointing ¶
WithEnableFileCheckpointing enables or disables file checkpointing. When enabled, file changes are tracked during the session and can be rewound to their state at any user message using Client.RewindFiles().
func WithEnv ¶
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 ¶
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 ¶
WithFallbackModel sets the fallback model when primary model is unavailable.
func WithFileCheckpointing ¶
func WithFileCheckpointing() Option
WithFileCheckpointing enables file checkpointing. Equivalent to WithEnableFileCheckpointing(true). This is the recommended convenience function for enabling file checkpointing.
func WithForkSession ¶
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 WithHook ¶
func WithHook(event HookEvent, matcher string, callback HookCallback) Option
WithHook adds a single hook callback for a specific event and tool pattern. Multiple calls accumulate hooks for the same event. Pass empty string for matcher to match all tools.
Example - Add a PreToolUse hook for Bash commands:
client := claudecode.NewClient(
claudecode.WithHook(claudecode.HookEventPreToolUse, "Bash", myCallback),
)
func WithHooks ¶
func WithHooks(hooks map[HookEvent][]HookMatcher) Option
WithHooks sets the complete hook configuration for lifecycle events. This replaces any previously configured hooks.
Example - Configure multiple hooks:
client := claudecode.NewClient(
claudecode.WithHooks(map[claudecode.HookEvent][]claudecode.HookMatcher{
claudecode.HookEventPreToolUse: {
{Matcher: "Bash", Hooks: []claudecode.HookCallback{myCallback}},
},
}),
)
func WithIncludePartialMessages ¶
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 ¶
WithJSONSchema is a convenience function that sets a JSON schema output format. This is equivalent to WithOutputFormat(OutputFormatJSONSchema(schema)).
func WithLocalPlugin ¶
WithLocalPlugin appends a local plugin by path. This is a convenience method for the common case of local plugins.
func WithMaxBudgetUSD ¶
WithMaxBudgetUSD sets the maximum budget in USD for API usage.
func WithMaxBufferSize ¶
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 ¶
func WithOutputFormat(format *OutputFormat) Option
WithOutputFormat sets the output format for structured responses.
func WithPartialStreaming ¶
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 ¶
func WithPlugin(plugin SdkPluginConfig) Option
WithPlugin appends a single plugin configuration. Multiple calls accumulate plugins.
func WithPlugins ¶
func WithPlugins(plugins []SdkPluginConfig) Option
WithPlugins sets the plugin configurations. This replaces any previously configured plugins.
func WithPostToolUseHook ¶
func WithPostToolUseHook(matcher string, callback HookCallback) Option
WithPostToolUseHook is a convenience function to add a PostToolUse hook. Pass empty string for matcher to match all tools.
func WithPreToolUseHook ¶
func WithPreToolUseHook(matcher string, callback HookCallback) Option
WithPreToolUseHook is a convenience function to add a PreToolUse hook. Pass empty string for matcher to match all tools.
Example:
client := claudecode.NewClient(
claudecode.WithPreToolUseHook("Bash", func(ctx context.Context, input any, toolUseID *string, hookCtx claudecode.HookContext) (claudecode.HookJSONOutput, error) {
// Log the bash command
return claudecode.HookJSONOutput{}, nil
}),
)
func WithResume ¶
WithResume sets the session ID to resume.
func WithSandbox ¶
func WithSandbox(sandbox *SandboxSettings) Option
WithSandbox sets the sandbox settings for bash command isolation.
func WithSandboxEnabled ¶
WithSandboxEnabled enables or disables sandbox. If sandbox settings don't exist, they are initialized.
func WithSandboxExcludedCommands ¶
WithSandboxExcludedCommands sets commands that always bypass sandbox. If sandbox settings don't exist, they are initialized.
func WithSandboxNetwork ¶
func WithSandboxNetwork(network *SandboxNetworkConfig) Option
WithSandboxNetwork sets the network configuration for sandbox. If sandbox settings don't exist, they are initialized.
func WithSdkMcpServer ¶
func WithSdkMcpServer(name string, server *McpSdkServerConfig) Option
WithSdkMcpServer adds an in-process SDK MCP server by name. This is a convenience method for adding SDK MCP servers created with CreateSDKMcpServer. Multiple calls accumulate servers.
Example:
calculator := claudecode.CreateSDKMcpServer("calculator", "1.0.0", addTool, sqrtTool)
client := claudecode.NewClient(
claudecode.WithSdkMcpServer("calc", calculator),
claudecode.WithAllowedTools("mcp__calc__add", "mcp__calc__sqrt"),
)
func WithSettingSources ¶
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 WithSkillImplementation ¶ added in v0.0.4
func WithSkillImplementation(name string, handler func(context.Context, string) (string, error)) Option
WithSkillImplementation registers a single in-process skill implementation.
func WithSkillImplementations ¶ added in v0.0.4
func WithSkillImplementations(skills map[string]func(context.Context, string) (string, error)) Option
WithSkillImplementations sets in-process skill implementations directly.
func WithSkillRegistry ¶ added in v0.0.5
WithSkillRegistry exposes selected Skills from an external registry directory. The registry root must contain one subdirectory per Skill, each with a SKILL.md file. The SDK presents the selected Skills to Claude CLI via a temporary local plugin wrapper without copying them into the project or user ~/.claude directory. Use SkillRegistryScopedName when explicitly instructing Claude to invoke one of these Skills.
func WithSkillRegistryAll ¶ added in v0.0.5
WithSkillRegistryAll exposes every direct child Skill in an external registry directory. A child directory is considered a Skill when it contains SKILL.md.
func WithSkills ¶
WithSkills sets the Skills configuration directly. Accepts the string "all" (use SkillsAll) to enable every discovered Skill, a []string of Skill names to enable only those, or []string{} to disable all. When set, SettingSources defaults to [user, project] if unset so the CLI discovers installed Skills. Mirrors the Python SDK's skills option.
func WithSkillsAll ¶ added in v0.0.4
func WithSkillsAll() Option
WithSkillsAll enables every discovered Skill in the session.
func WithSkillsDisabled ¶ added in v0.0.4
func WithSkillsDisabled() Option
WithSkillsDisabled disables all Skills in the session.
func WithSkillsList ¶ added in v0.0.4
WithSkillsList enables only the named Skills. Names match the name field in SKILL.md or the Skill's directory name. Use "plugin:skill" for plugin-provided Skills.
func WithStderrCallback ¶
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.
func WithSystemPrompt ¶
WithSystemPrompt sets the system prompt.
func WithToolsPreset ¶
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 ¶
type OutputFormat = shared.OutputFormat
OutputFormat specifies the format for structured output.
func OutputFormatJSONSchema ¶
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 PermissionRequestHookInput ¶ added in v0.0.4
type PermissionRequestHookInput = control.PermissionRequestHookInput
PermissionRequestHookInput is the input for PermissionRequest hook events.
type PermissionRequestHookSpecificOutput ¶ added in v0.0.4
type PermissionRequestHookSpecificOutput = control.PermissionRequestHookSpecificOutput
PermissionRequestHookSpecificOutput contains PermissionRequest-specific output fields.
type PermissionResult ¶
type PermissionResult = control.PermissionResult
PermissionResult is the interface for permission callback results. Implementations are PermissionResultAllow and PermissionResultDeny.
type PermissionResultAllow ¶
type PermissionResultAllow = control.PermissionResultAllow
PermissionResultAllow permits tool execution with optional modifications. Use NewPermissionResultAllow() to create with proper defaults.
type PermissionResultDeny ¶
type PermissionResultDeny = control.PermissionResultDeny
PermissionResultDeny prevents tool execution. Use NewPermissionResultDeny(message) to create with proper defaults.
type PermissionRuleValue ¶
type PermissionRuleValue = control.PermissionRuleValue
PermissionRuleValue represents a permission rule.
type PermissionUpdate ¶
type PermissionUpdate = control.PermissionUpdate
PermissionUpdate represents a dynamic permission rule update.
type PermissionUpdateType ¶
type PermissionUpdateType = control.PermissionUpdateType
PermissionUpdateType specifies the type of permission update.
type PostToolUseFailureHookInput ¶ added in v0.0.4
type PostToolUseFailureHookInput = control.PostToolUseFailureHookInput
PostToolUseFailureHookInput is the input for PostToolUseFailure hook events.
type PostToolUseFailureHookSpecificOutput ¶ added in v0.0.4
type PostToolUseFailureHookSpecificOutput = control.PostToolUseFailureHookSpecificOutput
PostToolUseFailureHookSpecificOutput contains PostToolUseFailure-specific output fields.
type PostToolUseHookInput ¶
type PostToolUseHookInput = control.PostToolUseHookInput
PostToolUseHookInput is the input for PostToolUse hook events.
type PostToolUseHookSpecificOutput ¶
type PostToolUseHookSpecificOutput = control.PostToolUseHookSpecificOutput
PostToolUseHookSpecificOutput contains PostToolUse-specific output fields.
type PreCompactHookInput ¶
type PreCompactHookInput = control.PreCompactHookInput
PreCompactHookInput is the input for PreCompact hook events.
type PreToolUseHookInput ¶
type PreToolUseHookInput = control.PreToolUseHookInput
PreToolUseHookInput is the input for PreToolUse hook events.
type PreToolUseHookSpecificOutput ¶
type PreToolUseHookSpecificOutput = control.PreToolUseHookSpecificOutput
PreToolUseHookSpecificOutput contains PreToolUse-specific output fields.
type ProcessError ¶
type ProcessError = shared.ProcessError
ProcessError represents errors from the CLI process execution.
type RateLimitEventMessage ¶ added in v0.0.4
type RateLimitEventMessage = shared.RateLimitEventMessage
RateLimitEventMessage is a session heartbeat carrying rate-limit window state. Emitted on essentially every CLI session even when nothing is constrained — see IsAllowed for the quick "all good" check.
type RateLimitInfo ¶ added in v0.0.4
type RateLimitInfo = shared.RateLimitInfo
RateLimitInfo is the window state carried by RateLimitEventMessage.
type RawControlMessage ¶
type RawControlMessage = shared.RawControlMessage
RawControlMessage wraps raw control protocol messages for passthrough.
type RawMessage ¶ added in v0.0.4
type RawMessage = shared.RawMessage
RawMessage represents a CLI message with an unrecognized type field. Preserves the original type and all data for forward-compatible inspection.
type ResultMessage ¶
type ResultMessage = shared.ResultMessage
ResultMessage represents a result or status message.
type SDKControlRequest ¶
type SDKControlRequest = control.SDKControlRequest
SDKControlRequest represents a control request sent to the CLI.
type SDKControlResponse ¶
type SDKControlResponse = control.SDKControlResponse
SDKControlResponse represents a control response received from the CLI.
type SDKSessionInfo ¶ added in v0.0.6
type SDKSessionInfo = session.SDKSessionInfo
SDKSessionInfo holds metadata about a session.
func GetSessionInfo ¶ added in v0.0.6
func GetSessionInfo(sessionID string, opts ...SessionOption) (*SDKSessionInfo, error)
GetSessionInfo returns metadata for a single session by ID. Returns nil (not an error) if the session is not found.
Example:
info, err := claudecode.GetSessionInfo(sessionID)
if info != nil {
fmt.Println(info.Summary)
}
func ListSessions ¶ added in v0.0.6
func ListSessions(opts ...SessionOption) ([]SDKSessionInfo, error)
ListSessions returns metadata for sessions, sorted by LastModified descending. Use WithSessionDirectory to scope to a specific project, or omit to list all.
Example:
// List 10 most recent sessions in a project
sessions, err := claudecode.ListSessions(
claudecode.WithSessionDirectory("/path/to/project"),
claudecode.WithSessionLimit(10),
)
// List all sessions across all projects
sessions, err := claudecode.ListSessions()
type SandboxIgnoreViolations ¶
type SandboxIgnoreViolations = shared.SandboxIgnoreViolations
SandboxIgnoreViolations specifies patterns to ignore during sandbox violations.
type SandboxNetworkConfig ¶
type SandboxNetworkConfig = shared.SandboxNetworkConfig
SandboxNetworkConfig configures network access within sandbox.
type SandboxSettings ¶
type SandboxSettings = shared.SandboxSettings
SandboxSettings configures sandbox behavior for bash command execution.
type SdkMcpServer ¶
type SdkMcpServer struct {
// contains filtered or unexported fields
}
SdkMcpServer implements the McpServer interface for in-process tools. It is thread-safe and can handle concurrent tool calls.
func (*SdkMcpServer) CallTool ¶
func (s *SdkMcpServer) CallTool(ctx context.Context, name string, args map[string]any) (*McpToolResult, error)
CallTool executes a tool by name with the given arguments. Returns an error if the tool is not found. This method is thread-safe.
func (*SdkMcpServer) ListTools ¶
func (s *SdkMcpServer) ListTools(_ context.Context) ([]McpToolDefinition, error)
ListTools returns all registered tools. This method is thread-safe.
func (*SdkMcpServer) Version ¶
func (s *SdkMcpServer) Version() string
Version returns the server version.
type SdkPluginConfig ¶
type SdkPluginConfig = shared.SdkPluginConfig
SdkPluginConfig represents a plugin configuration.
type SdkPluginType ¶
type SdkPluginType = shared.SdkPluginType
SdkPluginType represents the type of SDK plugin.
type SessionContentBlock ¶ added in v0.0.6
type SessionContentBlock = session.ContentBlock
SessionContentBlock represents a typed content block from a session message.
type SessionContentType ¶ added in v0.0.6
type SessionContentType = session.ContentType
SessionContentType discriminates the SessionMessageContent union.
type SessionMessage ¶ added in v0.0.6
SessionMessage represents a message from a session transcript.
func GetSessionMessages ¶ added in v0.0.6
func GetSessionMessages(sessionID string, opts ...SessionOption) ([]SessionMessage, error)
GetSessionMessages reads user and assistant messages from a session transcript.
Example:
messages, err := claudecode.GetSessionMessages(sessionID,
claudecode.WithSessionDirectory("/path/to/project"),
claudecode.WithSessionLimit(20),
)
type SessionMessageContent ¶ added in v0.0.6
type SessionMessageContent = session.MessageContent
SessionMessageContent is a sum type representing the content of a session message.
type SessionOption ¶ added in v0.0.6
SessionOption configures session query behavior.
type SetModelRequest ¶
type SetModelRequest = control.SetModelRequest
SetModelRequest to change AI model via control protocol.
type SetPermissionModeRequest ¶
type SetPermissionModeRequest = control.SetPermissionModeRequest
SetPermissionModeRequest to change permission mode via control protocol.
type SettingSource ¶
type SettingSource = shared.SettingSource
SettingSource represents a settings source location.
type SkillRegistryConfig ¶ added in v0.0.5
type SkillRegistryConfig = shared.SkillRegistryConfig
SkillRegistryConfig represents an external directory of Skills that should be exposed through a temporary local plugin wrapper.
type SlashCommand ¶ added in v0.0.5
type SlashCommand = control.SlashCommand
SlashCommand describes a CLI slash command suitable for input suggestions.
func DiscoverSlashCommands ¶ added in v0.0.5
func DiscoverSlashCommands(ctx context.Context, opts ...Option) ([]SlashCommand, error)
DiscoverSlashCommands starts a short-lived discovery query and returns the native slash commands advertised by the CLI in the system/init message.
Slash commands are dynamic: they depend on the current directory, settings, plugins, and Skills. The CLI exposes them on session initialization rather than through a standalone control request, so this helper opens a temporary query, reads init, then closes it immediately.
type StopHookInput ¶
type StopHookInput = control.StopHookInput
StopHookInput is the input for Stop hook events.
type StreamEvent ¶
type StreamEvent = shared.StreamEvent
StreamEvent represents a partial message update during streaming.
type StreamIssue ¶
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 ¶
type StreamStats = shared.StreamStats
StreamStats provides statistics about the message stream.
type StreamValidator ¶
type StreamValidator = shared.StreamValidator
StreamValidator tracks tool requests and results to detect incomplete streams.
type SubagentStartHookInput ¶ added in v0.0.4
type SubagentStartHookInput = control.SubagentStartHookInput
SubagentStartHookInput is the input for SubagentStart hook events.
type SubagentStartHookSpecificOutput ¶ added in v0.0.4
type SubagentStartHookSpecificOutput = control.SubagentStartHookSpecificOutput
SubagentStartHookSpecificOutput contains SubagentStart-specific output fields.
type SubagentStopHookInput ¶
type SubagentStopHookInput = control.SubagentStopHookInput
SubagentStopHookInput is the input for SubagentStop hook events.
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 ToolAnnotations ¶ added in v0.0.4
type ToolAnnotations = shared.ToolAnnotations
ToolAnnotations carries MCP-spec behavioral hints (title, readOnlyHint, destructiveHint, idempotentHint, openWorldHint) attached to an SDK MCP tool.
type ToolOption ¶ added in v0.0.4
type ToolOption func(*McpTool)
ToolOption configures optional fields on an McpTool at construction time. Used as variadic args to NewTool to extend the tool without breaking the positional signature. See WithToolAnnotations for the canonical example.
func WithToolAnnotations ¶ added in v0.0.4
func WithToolAnnotations(ann *ToolAnnotations) ToolOption
WithToolAnnotations attaches MCP-spec behavioral hints to a tool. The provided pointer is stored as-is and surfaced unchanged via McpTool.Annotations() and McpToolDefinition.Annotations.
Example:
tool := claudecode.NewTool(
"read_file", "Read a file from disk", schema, handler,
claudecode.WithToolAnnotations(&claudecode.ToolAnnotations{
ReadOnlyHint: ptrTo(true),
OpenWorldHint: ptrTo(false),
}),
)
type ToolPermissionContext ¶
type ToolPermissionContext = control.ToolPermissionContext
ToolPermissionContext provides context for permission callbacks. Contains suggestions from CLI for permission decisions.
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 ¶
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
// SetModel changes the AI model during streaming session.
SetModel(ctx context.Context, model *string) error
// SetPermissionMode changes the permission mode during streaming session.
SetPermissionMode(ctx context.Context, mode PermissionMode) error
// RewindFiles reverts tracked files to their state at a specific user message.
// Requires file checkpointing to be enabled and control protocol initialized.
RewindFiles(ctx context.Context, userMessageID string) error
// GetMcpStatus returns the connection status of all configured MCP servers.
GetMcpStatus(ctx context.Context) (*McpStatusResponse, error)
// GetSlashCommands returns slash commands available in the current session.
GetSlashCommands(ctx context.Context) ([]SlashCommand, 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 Usage ¶ added in v0.0.4
Usage represents token usage information from the Claude API. Present on AssistantMessage (per-turn) and ResultMessage (conversation total).
type UserMessage ¶
type UserMessage = shared.UserMessage
UserMessage represents a message from the user.
type UserPromptSubmitHookInput ¶
type UserPromptSubmitHookInput = control.UserPromptSubmitHookInput
UserPromptSubmitHookInput is the input for UserPromptSubmit hook events.
type UserPromptSubmitHookSpecificOutput ¶
type UserPromptSubmitHookSpecificOutput = control.UserPromptSubmitHookSpecificOutput
UserPromptSubmitHookSpecificOutput contains UserPromptSubmit-specific output fields.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
11_permission_callback
command
Package main demonstrates the Permission Callback System.
|
Package main demonstrates the Permission Callback System. |
|
12_hooks
command
Package main demonstrates the Hook System for lifecycle events.
|
Package main demonstrates the Hook System for lifecycle events. |
|
13_file_checkpointing
command
Package main demonstrates the File Checkpointing and Rewind System.
|
Package main demonstrates the File Checkpointing and Rewind System. |
|
14_sdk_mcp_server
command
Package main demonstrates the In-Process SDK MCP Server feature.
|
Package main demonstrates the In-Process SDK MCP Server feature. |
|
21_skills
command
|
|
|
22_status_display
command
|
|
|
23_skill_registry
command
Package main demonstrates loading Skills from an external registry directory.
|
Package main demonstrates loading Skills from an external registry directory. |
|
24_slash_commands
command
Package main demonstrates discovering native slash commands for UI suggestions.
|
Package main demonstrates discovering native slash commands for UI suggestions. |
|
internal
|
|
|
cli
Package cli provides CLI discovery and command building functionality.
|
Package cli provides CLI discovery and command building functionality. |
|
control
Package control hook callback handling and registration.
|
Package control hook callback handling and registration. |
|
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. |
|
session
Package session provides functions for reading Claude Code session data from disk.
|
Package session provides functions for reading Claude Code session data from disk. |
|
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. |
