Documentation
¶
Overview ¶
Package claude provides a Go SDK for interacting with Claude Code CLI.
The SDK supports two main usage patterns:
1. One-shot queries using the Query function:
messages, errs := claude.Query(ctx, "What is 2 + 2?", nil)
for msg := range messages {
// Process messages
}
2. Bidirectional conversations using ClaudeSDKClient:
client := claude.NewClient(opts)
client.Connect(ctx)
defer client.Close()
messages, _ := client.Query(ctx, "Hello")
for msg := range messages {
// Process messages
}
The SDK also supports custom MCP tools and hooks for extending Claude's capabilities and controlling its behavior.
Index ¶
- Constants
- Variables
- func DeleteSession(sessionID string, directory *string) error
- func DeleteSessionViaStore(ctx context.Context, store SessionStore, sessionID string, directory *string) error
- func ImportSessionToStore(ctx context.Context, sessionID string, directory *string, store SessionStore, ...) (int, error)
- func IsBufferOverflowError(err error) bool
- func IsCLIConnectionError(err error) bool
- func IsCLIJSONDecodeError(err error) bool
- func IsCLINotFoundError(err error) bool
- func IsMessageParseError(err error) bool
- func IsProcessError(err error) bool
- func IsTimeoutError(err error) bool
- func ListSubagents(opts *ListSubagentsOptions) ([]string, error)
- func ListSubagentsFromStore(ctx context.Context, opts *ListSubagentsFromStoreOptions) ([]string, error)
- func ProjectKeyForDirectory(dir string) string
- func Query(ctx context.Context, prompt interface{}, opts *ClaudeAgentOptions) (<-chan Message, <-chan error)
- func RenameSession(sessionID, title string, directory *string) error
- func RenameSessionViaStore(ctx context.Context, store SessionStore, sessionID, title string, ...) error
- func TagSession(sessionID string, tag *string, directory *string) error
- func TagSessionViaStore(ctx context.Context, store SessionStore, sessionID string, tag *string, ...) error
- func TextContent(text string) map[string]interface{}
- func ToolErrorResponse(text string) map[string]interface{}
- func ToolResponse(text string) map[string]interface{}
- type AgentDefinition
- type AssistantMessage
- type AssistantMessageError
- type BaseSessionStore
- func (*BaseSessionStore) Append(_ context.Context, _ SessionKey, _ []SessionStoreEntry) error
- func (*BaseSessionStore) Delete(_ context.Context, _ SessionKey) error
- func (*BaseSessionStore) ListSessionSummaries(_ context.Context, _ string) ([]SessionSummaryEntry, error)
- func (*BaseSessionStore) ListSessions(_ context.Context, _ string) ([]SessionStoreListEntry, error)
- func (*BaseSessionStore) ListSubkeys(_ context.Context, _ SessionListSubkeysKey) ([]string, error)
- func (*BaseSessionStore) Load(_ context.Context, _ SessionKey) ([]SessionStoreEntry, error)
- type BufferOverflowError
- type CLIConnectionError
- type CLIJSONDecodeError
- type CLINotFoundError
- type CanUseToolFunc
- type ClaudeAgentOptions
- type ClaudeSDKClient
- func (c *ClaudeSDKClient) Close() error
- func (c *ClaudeSDKClient) Connect(ctx context.Context, prompt ...interface{}) error
- func (c *ClaudeSDKClient) GetContextUsage(ctx context.Context) (*ContextUsageResponse, error)
- func (c *ClaudeSDKClient) GetMCPStatus(ctx context.Context) (*McpStatusResponse, error)
- func (c *ClaudeSDKClient) GetServerInfo() map[string]interface{}
- func (c *ClaudeSDKClient) Interrupt(ctx context.Context) error
- func (c *ClaudeSDKClient) Query(ctx context.Context, prompt string, opts ...QueryOption) (<-chan Message, error)
- func (c *ClaudeSDKClient) ReceiveResponse(ctx context.Context) (<-chan Message, error)
- func (c *ClaudeSDKClient) ReconnectMCPServer(ctx context.Context, serverName string) error
- func (c *ClaudeSDKClient) RewindFiles(ctx context.Context, userMessageID string) error
- func (c *ClaudeSDKClient) Send(ctx context.Context, prompt string, opts ...QueryOption) error
- func (c *ClaudeSDKClient) SetModel(ctx context.Context, model string) error
- func (c *ClaudeSDKClient) SetPermissionMode(ctx context.Context, mode PermissionMode) error
- func (c *ClaudeSDKClient) StopTask(ctx context.Context, taskID string) error
- func (c *ClaudeSDKClient) ToggleMCPServer(ctx context.Context, serverName string, enabled bool) error
- type ClaudeSDKError
- type ContentBlock
- type ContextUsageCategory
- type ContextUsageResponse
- type DeferredToolUse
- type EffortLevel
- type ForkSessionOptions
- type ForkSessionResult
- type ForkSessionViaStoreOptions
- type GetSessionInfoFromStoreOptions
- type GetSessionInfoOptions
- type GetSessionMessagesFromStoreOptions
- type GetSessionMessagesOptions
- type GetSubagentMessagesFromStoreOptions
- type GetSubagentMessagesOptions
- type HookCallback
- type HookContext
- type HookEvent
- type HookEventMessage
- type HookInput
- type HookMatcher
- type HookOutput
- type ImportSessionToStoreOptions
- type InMemorySessionStore
- func (s *InMemorySessionStore) Append(_ context.Context, key SessionKey, entries []SessionStoreEntry) error
- func (s *InMemorySessionStore) Clear()
- func (s *InMemorySessionStore) Delete(_ context.Context, key SessionKey) error
- func (s *InMemorySessionStore) GetEntries(key SessionKey) []SessionStoreEntry
- func (s *InMemorySessionStore) ListSessionSummaries(_ context.Context, projectKey string) ([]SessionSummaryEntry, error)
- func (s *InMemorySessionStore) ListSessions(_ context.Context, projectKey string) ([]SessionStoreListEntry, error)
- func (s *InMemorySessionStore) ListSubkeys(_ context.Context, key SessionListSubkeysKey) ([]string, error)
- func (s *InMemorySessionStore) Load(_ context.Context, key SessionKey) ([]SessionStoreEntry, error)
- func (s *InMemorySessionStore) Size() int
- type ListSessionsFromStoreOptions
- type ListSessionsOptions
- type ListSubagentsFromStoreOptions
- type ListSubagentsOptions
- type MCPHTTPServerConfig
- type MCPSSEServerConfig
- type MCPSdkServerConfig
- type MCPServerConfig
- type MCPStdioServerConfig
- type MaterializedResume
- type McpClaudeAIProxyServerConfig
- type McpSdkServerConfigStatus
- type McpServerConnectionStatus
- type McpServerInfo
- type McpServerStatus
- type McpServerStatusConfig
- type McpStatusResponse
- type McpToolAnnotations
- type McpToolInfo
- type Message
- type MessageParseError
- type MirrorErrorMessage
- type PermissionMode
- type PermissionResult
- type PermissionResultAllow
- type PermissionResultDeny
- type PermissionRuleValue
- type PermissionUpdate
- type PluginConfig
- type ProcessError
- type QueryOption
- type RateLimitEvent
- type RateLimitInfo
- type RateLimitStatus
- type RateLimitType
- type ResultMessage
- type SDKControlMcpReconnectRequest
- type SDKControlMcpToggleRequest
- type SDKControlStopTaskRequest
- type SDKSessionInfo
- func GetSessionInfo(opts *GetSessionInfoOptions) (*SDKSessionInfo, error)
- func GetSessionInfoFromStore(ctx context.Context, opts *GetSessionInfoFromStoreOptions) (*SDKSessionInfo, error)
- func ListSessions(opts *ListSessionsOptions) ([]SDKSessionInfo, error)
- func ListSessionsFromStore(ctx context.Context, opts *ListSessionsFromStoreOptions) ([]SDKSessionInfo, error)
- type SandboxIgnoreViolations
- type SandboxNetworkConfig
- type SandboxSettings
- type SdkBeta
- type SdkMcpTool
- type ServerToolName
- type ServerToolResultBlock
- type ServerToolUseBlock
- type SessionKey
- type SessionListSubkeysKey
- type SessionMessage
- func GetSessionMessages(opts *GetSessionMessagesOptions) ([]SessionMessage, error)
- func GetSessionMessagesFromStore(ctx context.Context, opts *GetSessionMessagesFromStoreOptions) ([]SessionMessage, error)
- func GetSubagentMessages(opts *GetSubagentMessagesOptions) ([]SessionMessage, error)
- func GetSubagentMessagesFromStore(ctx context.Context, opts *GetSubagentMessagesFromStoreOptions) ([]SessionMessage, error)
- type SessionMessageType
- type SessionStore
- type SessionStoreEntry
- type SessionStoreFlushMode
- type SessionStoreListEntry
- type SessionSummaryEntry
- type SettingSource
- type StreamEvent
- type SystemMessage
- type SystemPromptFile
- type SystemPromptPreset
- type TaskBudget
- type TaskNotificationMessage
- type TaskNotificationStatus
- type TaskProgressMessage
- type TaskStartedMessage
- type TaskUsage
- type TextBlock
- type ThinkingBlock
- type ThinkingConfig
- type TimeoutError
- type ToolBuilder
- type ToolPermissionContext
- type ToolResultBlock
- type ToolUseBlock
- type ToolsPreset
- type UserMessage
Constants ¶
const ( ServerToolNameAdvisor = "advisor" ServerToolNameWebSearch = "web_search" ServerToolNameWebFetch = "web_fetch" ServerToolNameCodeExecution = "code_execution" ServerToolNameBashCodeExecution = "bash_code_execution" ServerToolNameTextEditorCodeExecution = "text_editor_code_execution" ServerToolNameToolSearchRegex = "tool_search_tool_regex" ServerToolNameToolSearchBM25 = "tool_search_tool_bm25" )
const Version = "0.2.87"
Version is the current version of the Go SDK. This is set to track the Python SDK version.
Variables ¶
var ErrNotImplemented = errors.New("method not implemented")
ErrNotImplemented is returned by BaseSessionStore optional methods. Store implementations that do not support an optional capability should return this error. SDK helper functions (e.g. ListSessionsFromStore) check errors.Is(err, ErrNotImplemented) to determine which capabilities the store provides.
Functions ¶
func DeleteSession ¶ added in v0.1.52
DeleteSession deletes a session by removing its JSONL file and the sibling subagent transcript directory (if present).
func DeleteSessionViaStore ¶ added in v0.1.65
func DeleteSessionViaStore(ctx context.Context, store SessionStore, sessionID string, directory *string) error
DeleteSessionViaStore deletes a session from a SessionStore.
This is the store-backed counterpart to DeleteSession. If the store does not implement Delete (returns ErrNotImplemented), deletion is silently skipped — appropriate for WORM/append-only backends.
func ImportSessionToStore ¶ added in v0.1.65
func ImportSessionToStore(ctx context.Context, sessionID string, directory *string, store SessionStore, opts *ImportSessionToStoreOptions) (int, error)
ImportSessionToStore reads a session .jsonl file and appends all of its entries to the given SessionStore using streaming batch processing.
After the main transcript is imported, unless ExcludeSubagents is set the function scans <sessionDir>/subagents/** for additional .jsonl files and imports each one using a subkey that includes a Subpath. For every subagent .jsonl file, a corresponding .meta.json sidecar (if present) is also imported as an agent_metadata entry.
The session key is derived from the file's location relative to ProjectsDir:
project_key = <directory-name-under-projects-dir> session_id = <file-name-without-.jsonl>
Returns the total number of entries imported (main transcript + subagents).
func IsBufferOverflowError ¶
IsBufferOverflowError checks if the error is a BufferOverflowError.
func IsCLIConnectionError ¶
IsCLIConnectionError checks if the error is a CLIConnectionError.
func IsCLIJSONDecodeError ¶
IsCLIJSONDecodeError checks if the error is a CLIJSONDecodeError.
func IsCLINotFoundError ¶
IsCLINotFoundError checks if the error is a CLINotFoundError.
func IsMessageParseError ¶
IsMessageParseError checks if the error is a MessageParseError.
func IsProcessError ¶
IsProcessError checks if the error is a ProcessError.
func IsTimeoutError ¶
IsTimeoutError checks if the error is a TimeoutError.
func ListSubagents ¶ added in v0.1.65
func ListSubagents(opts *ListSubagentsOptions) ([]string, error)
ListSubagents returns the agent IDs of subagents that ran under a session. Subagent transcripts are stored as agent-<agentID>.jsonl files in the sibling directory <projectDir>/<sessionID>/.
func ListSubagentsFromStore ¶ added in v0.1.65
func ListSubagentsFromStore(ctx context.Context, opts *ListSubagentsFromStoreOptions) ([]string, error)
ListSubagentsFromStore lists subagent IDs for a session from a SessionStore.
This is the store-backed counterpart to ListSubagents. The store must implement ListSubkeys; if it does not, an error is returned. Returns an empty slice if the session_id is invalid or no subagents exist.
func ProjectKeyForDirectory ¶ added in v0.1.65
ProjectKeyForDirectory derives a portable project key from a directory path. The key is normalised to a slash-separated path and truncated to 200 characters. When truncation occurs, a djb2 hash of the full path is appended so that distinct long paths with the same 200-character prefix are still unique.
func Query ¶
func Query(ctx context.Context, prompt interface{}, opts *ClaudeAgentOptions) (<-chan Message, <-chan error)
Query performs a one-shot query to Claude Code. It returns two channels: one for messages and one for errors. The message channel is closed when the query completes.
func RenameSession ¶ added in v0.1.52
RenameSession renames a session by appending a custom-title entry. list_sessions reads the LAST custom-title from the file tail, so repeated calls are safe.
func RenameSessionViaStore ¶ added in v0.1.65
func RenameSessionViaStore(ctx context.Context, store SessionStore, sessionID, title string, directory *string) error
RenameSessionViaStore renames a session by appending a custom-title entry to a SessionStore.
This is the store-backed counterpart to RenameSession.
func TagSession ¶ added in v0.1.52
TagSession tags a session. Pass nil tag to clear the tag. Appends a {type:'tag',tag:<tag>,sessionId:<id>} JSONL entry.
func TagSessionViaStore ¶ added in v0.1.65
func TagSessionViaStore(ctx context.Context, store SessionStore, sessionID string, tag *string, directory *string) error
TagSessionViaStore tags a session by appending a tag entry to a SessionStore. Pass nil for tag to clear the tag.
This is the store-backed counterpart to TagSession.
func TextContent ¶
TextContent creates a text content block for tool responses.
func ToolErrorResponse ¶
ToolErrorResponse creates an error tool response.
func ToolResponse ¶
ToolResponse creates a standard tool response with text content.
Types ¶
type AgentDefinition ¶
type AgentDefinition struct {
Description string `json:"description"`
Prompt string `json:"prompt"`
Tools []string `json:"tools,omitempty"`
DisallowedTools []string `json:"disallowedTools,omitempty"`
Model string `json:"model,omitempty"`
Skills []string `json:"skills,omitempty"`
Memory string `json:"memory,omitempty"` // "user", "project", "local"
McpServers []interface{} `json:"mcpServers,omitempty"`
InitialPrompt string `json:"initialPrompt,omitempty"`
MaxTurns *int `json:"maxTurns,omitempty"`
Background *bool `json:"background,omitempty"`
Effort interface{} `json:"effort,omitempty"` // "low", "medium", "high", "xhigh", "max", or int
PermissionMode PermissionMode `json:"permissionMode,omitempty"` // e.g. PermissionModeDefault
}
AgentDefinition defines a custom agent configuration.
type AssistantMessage ¶
type AssistantMessage struct {
Content []ContentBlock `json:"content"`
Model string `json:"model"`
ParentToolUseID string `json:"parent_tool_use_id,omitempty"`
Error string `json:"error,omitempty"`
Usage map[string]interface{} `json:"usage,omitempty"`
MessageID string `json:"message_id,omitempty"`
StopReason string `json:"stop_reason,omitempty"`
SessionID string `json:"session_id,omitempty"`
UUID string `json:"uuid,omitempty"`
}
AssistantMessage represents an assistant message with content blocks.
type AssistantMessageError ¶
type AssistantMessageError string
AssistantMessageError represents error types for assistant messages.
const ( AssistantMessageErrorAuthFailed AssistantMessageError = "authentication_failed" AssistantMessageErrorBilling AssistantMessageError = "billing_error" AssistantMessageErrorRateLimit AssistantMessageError = "rate_limit" AssistantMessageErrorInvalidRequest AssistantMessageError = "invalid_request" AssistantMessageErrorServer AssistantMessageError = "server_error" AssistantMessageErrorUnknown AssistantMessageError = "unknown" )
type BaseSessionStore ¶ added in v0.1.65
type BaseSessionStore struct{}
BaseSessionStore provides default "not implemented" implementations of all SessionStore methods. Embed *BaseSessionStore (or BaseSessionStore) in your custom store struct so you only need to override the methods you support.
type MyStore struct {
claude.BaseSessionStore
// ... your fields
}
func (s *MyStore) Append(ctx context.Context, key claude.SessionKey, entries []claude.SessionStoreEntry) error { ... }
func (s *MyStore) Load(ctx context.Context, key claude.SessionKey) ([]claude.SessionStoreEntry, error) { ... }
// ListSessions, ListSessionSummaries, Delete, ListSubkeys are inherited
// from BaseSessionStore and return ErrNotImplemented.
func (*BaseSessionStore) Append ¶ added in v0.1.65
func (*BaseSessionStore) Append(_ context.Context, _ SessionKey, _ []SessionStoreEntry) error
func (*BaseSessionStore) Delete ¶ added in v0.1.65
func (*BaseSessionStore) Delete(_ context.Context, _ SessionKey) error
func (*BaseSessionStore) ListSessionSummaries ¶ added in v0.1.65
func (*BaseSessionStore) ListSessionSummaries(_ context.Context, _ string) ([]SessionSummaryEntry, error)
func (*BaseSessionStore) ListSessions ¶ added in v0.1.65
func (*BaseSessionStore) ListSessions(_ context.Context, _ string) ([]SessionStoreListEntry, error)
func (*BaseSessionStore) ListSubkeys ¶ added in v0.1.65
func (*BaseSessionStore) ListSubkeys(_ context.Context, _ SessionListSubkeysKey) ([]string, error)
func (*BaseSessionStore) Load ¶ added in v0.1.65
func (*BaseSessionStore) Load(_ context.Context, _ SessionKey) ([]SessionStoreEntry, error)
type BufferOverflowError ¶
type BufferOverflowError struct {
ClaudeSDKError
BufferSize int
Limit int
}
BufferOverflowError indicates that a message exceeded the buffer size limit.
func NewBufferOverflowError ¶
func NewBufferOverflowError(bufferSize, limit int) *BufferOverflowError
NewBufferOverflowError creates a new BufferOverflowError.
func (*BufferOverflowError) Error ¶
func (e *BufferOverflowError) Error() string
type CLIConnectionError ¶
type CLIConnectionError struct {
ClaudeSDKError
}
CLIConnectionError indicates connection or transport issues with the CLI.
func NewCLIConnectionError ¶
func NewCLIConnectionError(message string, cause error) *CLIConnectionError
NewCLIConnectionError creates a new CLIConnectionError.
type CLIJSONDecodeError ¶
type CLIJSONDecodeError struct {
ClaudeSDKError
Line string
}
CLIJSONDecodeError indicates that JSON parsing from CLI output failed.
func NewCLIJSONDecodeError ¶
func NewCLIJSONDecodeError(line string, cause error) *CLIJSONDecodeError
NewCLIJSONDecodeError creates a new CLIJSONDecodeError.
func (*CLIJSONDecodeError) Error ¶
func (e *CLIJSONDecodeError) Error() string
type CLINotFoundError ¶
type CLINotFoundError struct {
ClaudeSDKError
CLIPath string
}
CLINotFoundError indicates that the Claude Code CLI is not installed or not found.
func NewCLINotFoundError ¶
func NewCLINotFoundError(cliPath string) *CLINotFoundError
NewCLINotFoundError creates a new CLINotFoundError.
func (*CLINotFoundError) Error ¶
func (e *CLINotFoundError) Error() string
type CanUseToolFunc ¶
type CanUseToolFunc func(toolName string, input map[string]interface{}, ctx ToolPermissionContext) (PermissionResult, error)
CanUseToolFunc is the callback type for tool permission requests.
type ClaudeAgentOptions ¶
type ClaudeAgentOptions struct {
// Tools specifies the base set of tools available.
Tools []string
// ToolsPreset specifies a preset for tools (e.g., "claude_code").
ToolsPreset *ToolsPreset
// AllowedTools specifies which tools are allowed.
AllowedTools []string
// SystemPrompt sets a custom system prompt.
SystemPrompt string
// SystemPromptPreset specifies a system prompt preset.
SystemPromptPreset *SystemPromptPreset
// SystemPromptFile specifies a system prompt from a file.
SystemPromptFile *SystemPromptFile
// MCPServers configures MCP servers (external or SDK).
MCPServers map[string]MCPServerConfig
// PermissionMode sets the permission level for tool execution.
PermissionMode PermissionMode
// ContinueConversation continues an existing conversation.
ContinueConversation bool
// Resume resumes a specific session.
Resume string
// SessionID specifies a session ID to use.
SessionID string
// MaxTurns limits the number of conversation turns.
MaxTurns int
// MaxBudgetUSD sets a cost limit in USD.
MaxBudgetUSD float64
// DisallowedTools specifies which tools are not allowed.
DisallowedTools []string
// Model specifies the AI model to use.
Model string
// FallbackModel specifies a fallback model.
FallbackModel string
// Betas enables beta features.
Betas []SdkBeta
// PermissionPromptToolName sets the tool for permission prompts.
PermissionPromptToolName string
// CWD sets the working directory for the CLI.
CWD string
// CLIPath specifies a custom path to the Claude CLI.
CLIPath string
// Settings specifies settings as JSON string or file path.
Settings string
// AddDirs adds additional directories.
AddDirs []string
// Env sets environment variables for the CLI process.
Env map[string]string
// ExtraArgs passes arbitrary CLI flags.
ExtraArgs map[string]string
// MaxBufferSize sets the maximum buffer size for CLI output.
MaxBufferSize int
// StderrCallback receives stderr output from CLI.
StderrCallback func(string)
// CanUseTool is a callback for tool permission requests.
CanUseTool CanUseToolFunc
// Hooks configures hook callbacks for various events.
Hooks map[HookEvent][]HookMatcher
// User specifies the user for the CLI process.
User string
// IncludePartialMessages enables streaming of partial messages.
IncludePartialMessages bool
// ForkSession forks resumed sessions to a new session ID.
ForkSession bool
// Agents defines custom agent configurations.
Agents map[string]AgentDefinition
// SettingSources specifies which setting sources to load.
SettingSources []SettingSource
// Sandbox configures bash command sandboxing.
Sandbox *SandboxSettings
// Plugins configures custom plugins.
Plugins []PluginConfig
// MaxThinkingTokens sets the max tokens for thinking blocks.
// Deprecated: Use Thinking instead.
MaxThinkingTokens int
// Thinking configures extended thinking behavior.
Thinking *ThinkingConfig
// OutputFormat specifies the output format for structured outputs.
OutputFormat map[string]interface{}
// EnableFileCheckpointing enables file change tracking.
EnableFileCheckpointing bool
// Effort controls thinking depth. Use EffortLevel constants (EffortLevelLow, EffortLevelMedium, etc.).
Effort string
// TaskBudget sets an API-side task budget in tokens.
TaskBudget *TaskBudget
// Skills configures the skills allowlist.
// Accepted values:
// nil → no SDK auto-configuration (CLI defaults apply)
// "all" → enable every discovered skill ("Skill" tool injected)
// []string → enable only the named skills ("Skill(name)" entries injected)
// When Skills is set and SettingSources is nil, SettingSources defaults to
// ["user","project"].
Skills interface{}
// SessionStore is the transcript-mirror store adapter.
// When set, --session-mirror is passed to the CLI subprocess and incoming
// transcript_mirror frames are forwarded to the store via the batcher.
SessionStore SessionStore
// SessionStoreFlush controls when transcript-mirror entries are flushed to
// SessionStore. "batched" (default) coalesces entries and flushes once per
// turn or at overflow. "eager" triggers a background flush after every
// frame for near-real-time delivery. Ignored when SessionStore is nil.
SessionStoreFlush SessionStoreFlushMode
// StrictMCPConfig when true, only use MCP servers passed via MCPServers,
// ignoring all other MCP configurations the CLI would otherwise load (e.g.
// project .mcp.json, user/global settings, plugin-provided servers).
// Maps to the CLI's --strict-mcp-config flag.
StrictMCPConfig bool
// IncludeHookEvents when true, the CLI emits hook events (PreToolUse, PostToolUse,
// Stop, etc.) as HookEventMessage objects in the message stream.
IncludeHookEvents bool
// LoadTimeoutMs is the upper bound on SessionStore.Load / ListSubkeys calls
// during resume materialization, in milliseconds.
// A value of 0 means immediate timeout; use a large value to effectively
// disable. Defaults to 60 000 ms (60 seconds).
LoadTimeoutMs int
}
ClaudeAgentOptions configures SDK behavior.
func DefaultOptions ¶
func DefaultOptions() *ClaudeAgentOptions
DefaultOptions returns ClaudeAgentOptions with default values.
type ClaudeSDKClient ¶
type ClaudeSDKClient struct {
// contains filtered or unexported fields
}
ClaudeSDKClient provides bidirectional communication with Claude Code.
func NewClient ¶
func NewClient(opts *ClaudeAgentOptions) *ClaudeSDKClient
NewClient creates a new ClaudeSDKClient.
func (*ClaudeSDKClient) Close ¶
func (c *ClaudeSDKClient) Close() error
Close disconnects and cleans up resources.
func (*ClaudeSDKClient) Connect ¶
func (c *ClaudeSDKClient) Connect(ctx context.Context, prompt ...interface{}) error
Connect establishes connection to Claude Code CLI. prompt can be a string, a channel of messages, or nil for interactive mode.
func (*ClaudeSDKClient) GetContextUsage ¶ added in v0.1.52
func (c *ClaudeSDKClient) GetContextUsage(ctx context.Context) (*ContextUsageResponse, error)
GetContextUsage returns a breakdown of current context window usage by category. Returns the same data shown by the `/context` command in the CLI, including token counts per category, total usage, and detailed breakdowns of MCP tools, memory files, and agents.
func (*ClaudeSDKClient) GetMCPStatus ¶
func (c *ClaudeSDKClient) GetMCPStatus(ctx context.Context) (*McpStatusResponse, error)
GetMCPStatus returns the current MCP server connection status.
func (*ClaudeSDKClient) GetServerInfo ¶
func (c *ClaudeSDKClient) GetServerInfo() map[string]interface{}
GetServerInfo returns information about the connected server.
func (*ClaudeSDKClient) Interrupt ¶
func (c *ClaudeSDKClient) Interrupt(ctx context.Context) error
Interrupt sends an interrupt signal.
func (*ClaudeSDKClient) Query ¶
func (c *ClaudeSDKClient) Query(ctx context.Context, prompt string, opts ...QueryOption) (<-chan Message, error)
Query sends a message and returns a channel of responses.
func (*ClaudeSDKClient) ReceiveResponse ¶
func (c *ClaudeSDKClient) ReceiveResponse(ctx context.Context) (<-chan Message, error)
ReceiveResponse returns messages until a ResultMessage is received.
func (*ClaudeSDKClient) ReconnectMCPServer ¶ added in v0.1.46
func (c *ClaudeSDKClient) ReconnectMCPServer(ctx context.Context, serverName string) error
ReconnectMCPServer reconnects to an MCP server.
func (*ClaudeSDKClient) RewindFiles ¶
func (c *ClaudeSDKClient) RewindFiles(ctx context.Context, userMessageID string) error
RewindFiles rewinds tracked files to a specific user message.
func (*ClaudeSDKClient) Send ¶
func (c *ClaudeSDKClient) Send(ctx context.Context, prompt string, opts ...QueryOption) error
Send sends a message to Claude without waiting for a response.
func (*ClaudeSDKClient) SetModel ¶
func (c *ClaudeSDKClient) SetModel(ctx context.Context, model string) error
SetModel changes the AI model.
func (*ClaudeSDKClient) SetPermissionMode ¶
func (c *ClaudeSDKClient) SetPermissionMode(ctx context.Context, mode PermissionMode) error
SetPermissionMode changes the permission mode.
func (*ClaudeSDKClient) StopTask ¶ added in v0.1.46
func (c *ClaudeSDKClient) StopTask(ctx context.Context, taskID string) error
StopTask stops a running task.
func (*ClaudeSDKClient) ToggleMCPServer ¶ added in v0.1.46
func (c *ClaudeSDKClient) ToggleMCPServer(ctx context.Context, serverName string, enabled bool) error
ToggleMCPServer enables or disables an MCP server.
type ClaudeSDKError ¶
ClaudeSDKError is the base error type for all Claude SDK errors.
func NewClaudeSDKError ¶
func NewClaudeSDKError(message string, cause error) *ClaudeSDKError
NewClaudeSDKError creates a new ClaudeSDKError.
func (*ClaudeSDKError) Error ¶
func (e *ClaudeSDKError) Error() string
func (*ClaudeSDKError) Unwrap ¶
func (e *ClaudeSDKError) Unwrap() error
type ContentBlock ¶
type ContentBlock interface {
// contains filtered or unexported methods
}
ContentBlock is the interface for content blocks within messages.
func ParseContentBlock ¶
func ParseContentBlock(raw map[string]interface{}) (ContentBlock, error)
ParseContentBlock parses a raw content block map into a typed ContentBlock.
func ParseContentBlocks ¶
func ParseContentBlocks(rawBlocks []interface{}) ([]ContentBlock, error)
ParseContentBlocks parses a slice of raw content block maps into typed ContentBlocks.
type ContextUsageCategory ¶ added in v0.1.52
type ContextUsageCategory struct {
Name string `json:"name"`
Tokens int `json:"tokens"`
Color string `json:"color"`
IsDeferred bool `json:"isDeferred,omitempty"`
}
ContextUsageCategory represents a single context usage category.
type ContextUsageResponse ¶ added in v0.1.52
type ContextUsageResponse struct {
Categories []ContextUsageCategory `json:"categories"`
TotalTokens int `json:"totalTokens"`
MaxTokens int `json:"maxTokens"`
RawMaxTokens int `json:"rawMaxTokens"`
Percentage float64 `json:"percentage"`
Model string `json:"model"`
IsAutoCompactEnabled bool `json:"isAutoCompactEnabled"`
MemoryFiles []map[string]interface{} `json:"memoryFiles"`
McpTools []map[string]interface{} `json:"mcpTools"`
Agents []map[string]interface{} `json:"agents"`
GridRows [][]map[string]interface{} `json:"gridRows"`
AutoCompactThreshold *int `json:"autoCompactThreshold,omitempty"`
DeferredBuiltinTools []map[string]interface{} `json:"deferredBuiltinTools,omitempty"`
SystemTools []map[string]interface{} `json:"systemTools,omitempty"`
SystemPromptSections []map[string]interface{} `json:"systemPromptSections,omitempty"`
SlashCommands map[string]interface{} `json:"slashCommands,omitempty"`
Skills map[string]interface{} `json:"skills,omitempty"`
MessageBreakdown map[string]interface{} `json:"messageBreakdown,omitempty"`
APIUsage map[string]interface{} `json:"apiUsage,omitempty"`
}
ContextUsageResponse represents the response from GetContextUsage.
type DeferredToolUse ¶ added in v0.1.76
type DeferredToolUse struct {
ID string `json:"id"`
Name string `json:"name"`
Input map[string]interface{} `json:"input"`
}
DeferredToolUse represents a tool use that was deferred by a PreToolUse hook returning decision "defer".
When a PreToolUse hook returns decision "defer", the run stops and the result message carries the deferred tool call here so the caller can inspect it and decide whether to resume.
type EffortLevel ¶ added in v0.2.87
type EffortLevel = string
EffortLevel represents the effort level for Claude responses. Controls how much effort Claude puts into its response, working with adaptive thinking to guide thinking depth.
const ( // EffortLevelLow uses minimal effort. EffortLevelLow EffortLevel = "low" // EffortLevelMedium uses moderate effort. EffortLevelMedium EffortLevel = "medium" // EffortLevelHigh uses high effort. EffortLevelHigh EffortLevel = "high" // EffortLevelXHigh uses extra-high effort (Opus 4.7 only; falls back to high on other models). EffortLevelXHigh EffortLevel = "xhigh" // EffortLevelMax uses maximum effort. EffortLevelMax EffortLevel = "max" )
type ForkSessionOptions ¶ added in v0.1.52
type ForkSessionOptions struct {
// SessionID is the UUID of the source session to fork.
SessionID string
// Directory is the project directory path. When omitted, all project directories are searched.
Directory *string
// UpToMessageID slices transcript up to this message UUID (inclusive).
UpToMessageID *string
// Title is the custom title for the fork.
Title *string
}
ForkSessionOptions contains options for forking a session.
type ForkSessionResult ¶ added in v0.1.52
type ForkSessionResult struct {
SessionID string `json:"session_id"`
}
ForkSessionResult contains the result of a fork operation.
func ForkSession ¶ added in v0.1.52
func ForkSession(opts *ForkSessionOptions) (*ForkSessionResult, error)
ForkSession forks a session into a new branch with fresh UUIDs.
func ForkSessionViaStore ¶ added in v0.1.65
func ForkSessionViaStore(ctx context.Context, opts *ForkSessionViaStoreOptions) (*ForkSessionResult, error)
ForkSessionViaStore forks a session into a new branch with fresh UUIDs via a SessionStore.
This is the store-backed counterpart to ForkSession. Runs the fork transform directly over the objects returned by SessionStore.Load — no JSONL round-trip.
Returns ForkSessionResult with the new session's UUID, or an error if the source session is not found or has no messages.
type ForkSessionViaStoreOptions ¶ added in v0.1.65
type ForkSessionViaStoreOptions struct {
// Store is the session store to fork from/to. Required.
Store SessionStore
// SessionID is the UUID of the source session.
SessionID string
// Directory is the project directory used to compute the project_key.
Directory *string
// UpToMessageID slices the transcript at this message UUID (inclusive).
// If empty, copies the full transcript.
UpToMessageID string
// Title is the custom title for the fork.
// If empty, derives from the original title + " (fork)".
Title string
}
ForkSessionViaStoreOptions contains options for ForkSessionViaStore.
type GetSessionInfoFromStoreOptions ¶ added in v0.1.65
type GetSessionInfoFromStoreOptions struct {
// Store is the session store to query. Required.
Store SessionStore
// SessionID is the UUID of the session to look up.
SessionID string
// Directory is the project directory used to compute the project_key.
Directory string
}
GetSessionInfoFromStoreOptions contains options for GetSessionInfoFromStore.
type GetSessionInfoOptions ¶ added in v0.1.52
type GetSessionInfoOptions struct {
// SessionID is the UUID of the session to look up.
SessionID string
// Directory is the project directory path. When omitted, all project directories are searched.
Directory *string
}
GetSessionInfoOptions contains options for getting single session metadata.
type GetSessionMessagesFromStoreOptions ¶ added in v0.1.65
type GetSessionMessagesFromStoreOptions struct {
// Store is the session store to query. Required.
Store SessionStore
// SessionID is the UUID of the session to read.
SessionID string
// Directory is the project directory used to compute the project_key.
Directory string
// Limit caps the number of messages returned.
Limit *int
// Offset skips messages from the beginning.
Offset int
}
GetSessionMessagesFromStoreOptions contains options for GetSessionMessagesFromStore.
type GetSessionMessagesOptions ¶ added in v0.1.46
type GetSessionMessagesOptions struct {
// SessionID is the UUID of the session to read.
SessionID string
// Directory to find the session in. If nil, searches all project directories.
Directory *string
// Maximum number of messages to return.
Limit *int
// Number of messages to skip from the start.
Offset int
}
GetSessionMessagesOptions contains options for getting session messages.
type GetSubagentMessagesFromStoreOptions ¶ added in v0.1.65
type GetSubagentMessagesFromStoreOptions struct {
// Store is the session store to query. Required.
Store SessionStore
// SessionID is the UUID of the parent session.
SessionID string
// AgentID is the ID of the subagent.
AgentID string
// Directory is the project directory used to compute the project_key.
Directory string
// Limit caps the number of messages returned.
Limit *int
// Offset skips messages from the beginning.
Offset int
}
GetSubagentMessagesFromStoreOptions contains options for GetSubagentMessagesFromStore.
type GetSubagentMessagesOptions ¶ added in v0.1.65
type GetSubagentMessagesOptions struct {
// SessionID is the UUID of the parent session.
SessionID string
// AgentID is the agent ID returned by ListSubagents.
AgentID string
// Directory is the project directory path. When omitted, all project directories are searched.
Directory *string
// Maximum number of messages to return.
Limit *int
// Number of messages to skip from the start.
Offset int
}
GetSubagentMessagesOptions contains options for reading subagent messages.
type HookCallback ¶
type HookCallback func(input HookInput, toolUseID string, ctx HookContext) (HookOutput, error)
HookCallback is the function signature for hook handlers.
type HookContext ¶
type HookContext struct {
Signal interface{} // Future: abort signal support
}
HookContext provides context for hook callbacks.
type HookEvent ¶
type HookEvent string
HookEvent defines the type of hook event.
const ( HookEventPreToolUse HookEvent = "PreToolUse" HookEventPostToolUse HookEvent = "PostToolUse" HookEventPostToolUseFailure HookEvent = "PostToolUseFailure" HookEventUserPromptSubmit HookEvent = "UserPromptSubmit" HookEventStop HookEvent = "Stop" HookEventSubagentStop HookEvent = "SubagentStop" HookEventPreCompact HookEvent = "PreCompact" HookEventNotification HookEvent = "Notification" HookEventSubagentStart HookEvent = "SubagentStart" HookEventPermissionRequest HookEvent = "PermissionRequest" )
type HookEventMessage ¶ added in v0.1.76
type HookEventMessage struct {
Subtype string `json:"subtype"` // "hook_started" or "hook_response"
HookEventName string `json:"hook_event_name"`
Data map[string]interface{} `json:"data"`
SessionID string `json:"session_id,omitempty"`
UUID string `json:"uuid,omitempty"`
}
HookEventMessage is a hook event emitted by the CLI when IncludeHookEvents is enabled.
When ClaudeAgentOptions.IncludeHookEvents is true, the CLI emits hook lifecycle events (PreToolUse, PostToolUse, Stop, etc.) into the message stream. Each event is identified by HookEventName and the full raw payload is available in Data.
These arrive on the wire as {"type": "system", "subtype": "hook_started" | "hook_response", ...}.
type HookInput ¶
type HookInput struct {
HookEventName string `json:"hook_event_name"`
SessionID string `json:"session_id"`
TranscriptPath string `json:"transcript_path"`
CWD string `json:"cwd"`
PermissionMode string `json:"permission_mode,omitempty"`
ToolName string `json:"tool_name,omitempty"` // PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest (includes agent_id/agent_type for subagents)
ToolInput map[string]interface{} `json:"tool_input,omitempty"` // PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest
ToolResponse interface{} `json:"tool_response,omitempty"` // PostToolUse
ToolUseID string `json:"tool_use_id,omitempty"` // PreToolUse, PostToolUse, PostToolUseFailure
Error string `json:"error,omitempty"` // PostToolUseFailure
IsInterrupt bool `json:"is_interrupt,omitempty"` // PostToolUseFailure
Prompt string `json:"prompt,omitempty"` // UserPromptSubmit
StopHookActive bool `json:"stop_hook_active,omitempty"` // Stop, SubagentStop
AgentID string `json:"agent_id,omitempty"` // SubagentStop, SubagentStart, PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest
AgentTranscriptPath string `json:"agent_transcript_path,omitempty"` // SubagentStop
AgentType string `json:"agent_type,omitempty"` // SubagentStop, SubagentStart, PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest
Trigger string `json:"trigger,omitempty"` // PreCompact: "manual" or "auto"
CustomInstructions string `json:"custom_instructions,omitempty"` // PreCompact
Message string `json:"message,omitempty"` // Notification
Title string `json:"title,omitempty"` // Notification
NotificationType string `json:"notification_type,omitempty"` // Notification
PermissionSuggestions []map[string]interface{} `json:"permission_suggestions,omitempty"` // PermissionRequest
}
HookInput contains data passed to hook callbacks.
type HookMatcher ¶
type HookMatcher struct {
Matcher string // Tool name pattern (e.g., "Bash", "Write|MultiEdit|Edit")
Hooks []HookCallback // Hook callback functions
Timeout time.Duration // Timeout for hooks in this matcher
}
HookMatcher configures which hooks to invoke.
type HookOutput ¶
type HookOutput struct {
Continue *bool `json:"continue,omitempty"`
Async bool `json:"async,omitempty"` // Mapped to async_ in Python
AsyncTimeout int `json:"asyncTimeout,omitempty"`
SuppressOutput bool `json:"suppressOutput,omitempty"`
StopReason string `json:"stopReason,omitempty"`
Decision string `json:"decision,omitempty"` // "block", "defer"
SystemMessage string `json:"systemMessage,omitempty"`
Reason string `json:"reason,omitempty"`
HookSpecificOutput map[string]interface{} `json:"hookSpecificOutput,omitempty"`
}
HookOutput defines the response from a hook callback.
type ImportSessionToStoreOptions ¶ added in v0.1.65
type ImportSessionToStoreOptions struct {
// ProjectsDir is the root projects directory used to derive the project key
// from the session file path (e.g. ~/.claude/projects).
// When empty, getProjectsDir() is used.
ProjectsDir string
// ExcludeSubagents controls whether subagent JSONL files under
// <sessionDir>/subagents/ are skipped. Defaults to false (subagents are
// included). Set to true to skip subagent import.
ExcludeSubagents bool
// BatchSize controls how many entries are buffered before flushing to the
// store via Append. When zero or negative, maxImportBatchEntries (500) is used.
BatchSize int
}
ImportSessionToStoreOptions contains options for ImportSessionToStore.
type InMemorySessionStore ¶ added in v0.1.65
type InMemorySessionStore struct {
// contains filtered or unexported fields
}
InMemorySessionStore is a thread-safe in-process implementation of SessionStore.
It is intended for tests and lightweight integrations that do not need persistence. The store maintains both the raw entry lists and a derived SessionSummaryEntry sidecar so that ListSessionSummaries is cheap.
func NewInMemorySessionStore ¶ added in v0.1.65
func NewInMemorySessionStore() *InMemorySessionStore
NewInMemorySessionStore creates an empty InMemorySessionStore.
func (*InMemorySessionStore) Append ¶ added in v0.1.65
func (s *InMemorySessionStore) Append(_ context.Context, key SessionKey, entries []SessionStoreEntry) error
Append adds entries to the session identified by key.
func (*InMemorySessionStore) Clear ¶ added in v0.1.65
func (s *InMemorySessionStore) Clear()
Clear removes all stored data from the store. This is a test helper — it is not part of the SessionStore interface.
func (*InMemorySessionStore) Delete ¶ added in v0.1.65
func (s *InMemorySessionStore) Delete(_ context.Context, key SessionKey) error
Delete removes stored entries for the given key. When deleting a main-transcript key (Subpath empty), it cascades to all subkeys so subagent transcripts are not orphaned.
func (*InMemorySessionStore) GetEntries ¶ added in v0.1.65
func (s *InMemorySessionStore) GetEntries(key SessionKey) []SessionStoreEntry
GetEntries returns a copy of all stored entries for the given key. This is a test helper — it is not part of the SessionStore interface.
func (*InMemorySessionStore) ListSessionSummaries ¶ added in v0.1.65
func (s *InMemorySessionStore) ListSessionSummaries(_ context.Context, projectKey string) ([]SessionSummaryEntry, error)
ListSessionSummaries returns full summary entries for all sessions in a project. Only returns summaries for main transcripts (no subpath).
func (*InMemorySessionStore) ListSessions ¶ added in v0.1.65
func (s *InMemorySessionStore) ListSessions(_ context.Context, projectKey string) ([]SessionStoreListEntry, error)
ListSessions returns lightweight list entries for all sessions in a project.
func (*InMemorySessionStore) ListSubkeys ¶ added in v0.1.65
func (s *InMemorySessionStore) ListSubkeys(_ context.Context, key SessionListSubkeysKey) ([]string, error)
ListSubkeys returns all distinct subkeys (second path component) for a key. For a standard key (no Subpath set), this returns the set of subpaths stored under the same ProjectKey+SessionID prefix.
func (*InMemorySessionStore) Load ¶ added in v0.1.65
func (s *InMemorySessionStore) Load(_ context.Context, key SessionKey) ([]SessionStoreEntry, error)
Load returns all stored entries for the given key.
func (*InMemorySessionStore) Size ¶ added in v0.1.65
func (s *InMemorySessionStore) Size() int
Size returns the total number of stored entries across all sessions. This is a test helper — it is not part of the SessionStore interface.
type ListSessionsFromStoreOptions ¶ added in v0.1.65
type ListSessionsFromStoreOptions struct {
// Store is the session store to query. Required.
Store SessionStore
// Directory is the project directory used to compute the project_key.
// Defaults to the current working directory.
Directory string
// Limit caps the number of results returned.
Limit *int
// Offset skips results from the beginning of the sorted set.
Offset int
}
ListSessionsFromStoreOptions contains options for ListSessionsFromStore.
type ListSessionsOptions ¶ added in v0.1.46
type ListSessionsOptions struct {
// Directory to list sessions for. If nil, returns sessions across all projects.
Directory *string
// Maximum number of sessions to return.
Limit *int
// Number of sessions to skip from the start of the sorted result set.
// Use with Limit for pagination. Defaults to 0.
Offset int
// Include sessions from git worktrees when directory is provided.
IncludeWorktrees bool
}
ListSessionsOptions contains options for listing sessions.
type ListSubagentsFromStoreOptions ¶ added in v0.1.65
type ListSubagentsFromStoreOptions struct {
// Store is the session store to query. Required.
Store SessionStore
// SessionID is the UUID of the parent session.
SessionID string
// Directory is the project directory used to compute the project_key.
Directory string
}
ListSubagentsFromStoreOptions contains options for ListSubagentsFromStore.
type ListSubagentsOptions ¶ added in v0.1.65
type ListSubagentsOptions struct {
// SessionID is the UUID of the parent session.
SessionID string
// Directory is the project directory path. When omitted, all project directories are searched.
Directory *string
}
ListSubagentsOptions contains options for listing subagents.
type MCPHTTPServerConfig ¶
type MCPHTTPServerConfig struct {
Type string `json:"type"` // "http"
URL string `json:"url"`
Headers map[string]string `json:"headers,omitempty"`
}
MCPHTTPServerConfig configures an MCP HTTP server.
type MCPSSEServerConfig ¶
type MCPSSEServerConfig struct {
Type string `json:"type"` // "sse"
URL string `json:"url"`
Headers map[string]string `json:"headers,omitempty"`
}
MCPSSEServerConfig configures an MCP SSE server.
type MCPSdkServerConfig ¶
type MCPSdkServerConfig struct {
Type string `json:"type"` // "sdk"
Name string `json:"name"`
Instance interface{} `json:"-"` // The actual server instance (not serialized)
}
MCPSdkServerConfig configures an in-process SDK MCP server.
func CreateSdkMcpServer ¶
func CreateSdkMcpServer(name, version string, tools []SdkMcpTool) *MCPSdkServerConfig
CreateSdkMcpServer creates an in-process MCP server.
Example:
calculator := claude.CreateSdkMcpServer("calculator", "1.0.0", []claude.SdkMcpTool{
addTool,
subtractTool,
})
opts := &claude.ClaudeAgentOptions{
MCPServers: map[string]claude.MCPServerConfig{
"calc": calculator,
},
AllowedTools: []string{"mcp__calc__add", "mcp__calc__subtract"},
}
type MCPServerConfig ¶
type MCPServerConfig interface {
// contains filtered or unexported methods
}
MCPServerConfig is the interface for MCP server configurations.
type MCPStdioServerConfig ¶
type MCPStdioServerConfig struct {
Type string `json:"type,omitempty"` // "stdio" (optional for backwards compatibility)
Command string `json:"command"`
Args []string `json:"args,omitempty"`
Env map[string]string `json:"env,omitempty"`
}
MCPStdioServerConfig configures an MCP stdio server.
type MaterializedResume ¶ added in v0.1.65
type MaterializedResume struct {
// ConfigDir is the temporary directory laid out like ~/.claude/ —
// point the subprocess at it via CLAUDE_CONFIG_DIR.
ConfigDir string
// ResumeSessionID is the session ID to pass as --resume. When the input
// was ContinueConversation, this is the most-recent session resolved via
// SessionStore.ListSessions.
ResumeSessionID string
// Cleanup removes ConfigDir (best-effort). Call after the subprocess exits.
Cleanup func() error
}
MaterializedResume is the result of materializeResumeSession.
type McpClaudeAIProxyServerConfig ¶ added in v0.1.46
type McpClaudeAIProxyServerConfig struct {
Type string `json:"type"` // "claudeai-proxy"
URL string `json:"url"`
ID string `json:"id"`
}
McpClaudeAIProxyServerConfig represents the configuration for a Claude.ai proxy server.
type McpSdkServerConfigStatus ¶ added in v0.1.46
type McpSdkServerConfigStatus struct {
Type string `json:"type"` // "sdk"
Name string `json:"name"`
}
McpSdkServerConfigStatus represents the status configuration for an SDK MCP server.
type McpServerConnectionStatus ¶ added in v0.1.46
type McpServerConnectionStatus string
McpServerConnectionStatus represents the connection status of an MCP server.
const ( McpServerStatusConnected McpServerConnectionStatus = "connected" McpServerStatusFailed McpServerConnectionStatus = "failed" McpServerStatusNeedsAuth McpServerConnectionStatus = "needs-auth" McpServerStatusPending McpServerConnectionStatus = "pending" McpServerStatusDisabled McpServerConnectionStatus = "disabled" )
type McpServerInfo ¶ added in v0.1.46
McpServerInfo represents server information from an MCP server.
type McpServerStatus ¶ added in v0.1.46
type McpServerStatus struct {
Name string `json:"name"`
Status McpServerConnectionStatus `json:"status"`
ServerInfo *McpServerInfo `json:"serverInfo,omitempty"`
Error string `json:"error,omitempty"`
Config map[string]interface{} `json:"config,omitempty"`
Scope string `json:"scope,omitempty"`
Tools []McpToolInfo `json:"tools,omitempty"`
}
McpServerStatus represents the status of an MCP server.
type McpServerStatusConfig ¶ added in v0.1.46
type McpServerStatusConfig interface {
// contains filtered or unexported methods
}
McpServerStatusConfig is a union type for MCP server status configurations.
type McpStatusResponse ¶ added in v0.1.46
type McpStatusResponse struct {
MCPServers []McpServerStatus `json:"mcpServers"`
}
McpStatusResponse represents the response from an MCP status request.
type McpToolAnnotations ¶ added in v0.1.46
type McpToolAnnotations struct {
ReadOnly bool `json:"readOnly,omitempty"`
Destructive bool `json:"destructive,omitempty"`
OpenWorld bool `json:"openWorld,omitempty"`
}
McpToolAnnotations represents optional hints for tool usage.
type McpToolInfo ¶ added in v0.1.46
type McpToolInfo struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Annotations *McpToolAnnotations `json:"annotations,omitempty"`
}
McpToolInfo represents information about an MCP tool.
type Message ¶
type Message interface {
// contains filtered or unexported methods
}
Message is the interface for all message types from Claude Code.
func ParseMessage ¶
ParseMessage parses a raw JSON message into a typed Message. Returns nil for unknown message types for forward compatibility.
type MessageParseError ¶
type MessageParseError struct {
ClaudeSDKError
Data map[string]interface{}
}
MessageParseError indicates that message parsing failed due to unknown type or structure.
func NewMessageParseError ¶
func NewMessageParseError(message string, data map[string]interface{}) *MessageParseError
NewMessageParseError creates a new MessageParseError.
func (*MessageParseError) Error ¶
func (e *MessageParseError) Error() string
type MirrorErrorMessage ¶ added in v0.1.65
type MirrorErrorMessage struct {
Subtype string `json:"subtype"` // always "mirror_error"
Data interface{} `json:"data"`
Key *SessionKey `json:"key,omitempty"`
Error string `json:"error"`
UUID string `json:"uuid,omitempty"`
SessionID string `json:"session_id,omitempty"`
}
MirrorErrorMessage is a system message emitted when a SessionStore.Append call fails.
Non-fatal — the local-disk transcript is already durable, so the session continues unaffected. The mirrored copy in the external store will be missing the failed batch.
type PermissionMode ¶
type PermissionMode string
PermissionMode defines security levels for tool execution.
const ( // PermissionModeDefault is the default mode where CLI prompts for dangerous tools. PermissionModeDefault PermissionMode = "default" // PermissionModeAcceptEdits auto-accepts file edits. PermissionModeAcceptEdits PermissionMode = "acceptEdits" // PermissionModePlan is for planning mode. PermissionModePlan PermissionMode = "plan" // PermissionModeBypassPermissions allows all tools (use with caution). PermissionModeBypassPermissions PermissionMode = "bypassPermissions" // PermissionModeDontAsk denies any tool not pre-approved by allow rules // (i.e. anything unapproved is silently denied rather than prompted). PermissionModeDontAsk PermissionMode = "dontAsk" // PermissionModeAuto uses a model classifier to decide the appropriate // permission level at runtime. PermissionModeAuto PermissionMode = "auto" )
type PermissionResult ¶
type PermissionResult interface {
// contains filtered or unexported methods
}
PermissionResult is the interface for permission results.
type PermissionResultAllow ¶
type PermissionResultAllow struct {
Behavior string `json:"behavior"` // "allow"
UpdatedInput map[string]interface{} `json:"updated_input,omitempty"`
UpdatedPermissions []PermissionUpdate `json:"updated_permissions,omitempty"`
}
PermissionResultAllow allows the tool execution.
type PermissionResultDeny ¶
type PermissionResultDeny struct {
Behavior string `json:"behavior"` // "deny"
Message string `json:"message,omitempty"`
Interrupt bool `json:"interrupt,omitempty"`
}
PermissionResultDeny denies the tool execution.
type PermissionRuleValue ¶
type PermissionRuleValue struct {
ToolName string `json:"toolName"`
RuleContent string `json:"ruleContent,omitempty"`
}
PermissionRuleValue represents a permission rule.
type PermissionUpdate ¶
type PermissionUpdate struct {
Type string `json:"type"` // "addRules", "replaceRules", "removeRules", "setMode", "addDirectories", "removeDirectories"
Rules []PermissionRuleValue `json:"rules,omitempty"`
Behavior string `json:"behavior,omitempty"` // "allow", "deny", "ask"
Mode PermissionMode `json:"mode,omitempty"`
Directories []string `json:"directories,omitempty"`
Destination string `json:"destination,omitempty"` // "userSettings", "projectSettings", "localSettings", "session"
}
PermissionUpdate represents a permission update.
type PluginConfig ¶
PluginConfig configures a plugin.
type ProcessError ¶
type ProcessError struct {
ClaudeSDKError
ExitCode int
Stderr string
}
ProcessError indicates that the CLI process failed with a non-zero exit code.
func NewProcessError ¶
func NewProcessError(message string, exitCode int, stderr string) *ProcessError
NewProcessError creates a new ProcessError.
func (*ProcessError) Error ¶
func (e *ProcessError) Error() string
type QueryOption ¶
type QueryOption func(*queryOptions)
QueryOption configures a query or send operation.
func WithSessionID ¶
func WithSessionID(id string) QueryOption
WithSessionID sets the session ID for the message.
type RateLimitEvent ¶ added in v0.1.52
type RateLimitEvent struct {
RateLimitInfo RateLimitInfo `json:"rate_limit_info"`
UUID string `json:"uuid"`
SessionID string `json:"session_id"`
}
RateLimitEvent represents a rate limit event emitted when rate limit info changes.
type RateLimitInfo ¶ added in v0.1.52
type RateLimitInfo struct {
Status RateLimitStatus `json:"status"`
ResetsAt *int64 `json:"resets_at,omitempty"`
RateLimitType RateLimitType `json:"rate_limit_type,omitempty"`
Utilization *float64 `json:"utilization,omitempty"`
OverageStatus RateLimitStatus `json:"overage_status,omitempty"`
OverageResetsAt *int64 `json:"overage_resets_at,omitempty"`
OverageDisabledReason string `json:"overage_disabled_reason,omitempty"`
Raw map[string]interface{} `json:"raw,omitempty"`
}
RateLimitInfo contains rate limit status details.
type RateLimitStatus ¶ added in v0.1.52
type RateLimitStatus string
RateLimitStatus represents the current rate limit state.
const ( RateLimitStatusAllowed RateLimitStatus = "allowed" RateLimitStatusAllowedWarning RateLimitStatus = "allowed_warning" RateLimitStatusRejected RateLimitStatus = "rejected" )
type RateLimitType ¶ added in v0.1.52
type RateLimitType string
RateLimitType identifies which rate limit window applies.
const ( RateLimitTypeFiveHour RateLimitType = "five_hour" RateLimitTypeSevenDay RateLimitType = "seven_day" RateLimitTypeSevenDayOpus RateLimitType = "seven_day_opus" RateLimitTypeSevenDaySonnet RateLimitType = "seven_day_sonnet" RateLimitTypeOverage RateLimitType = "overage" )
type ResultMessage ¶
type ResultMessage struct {
Subtype string `json:"subtype"`
DurationMS int `json:"duration_ms"`
DurationAPIMS int `json:"duration_api_ms"`
IsError bool `json:"is_error"`
NumTurns int `json:"num_turns"`
SessionID string `json:"session_id"`
StopReason string `json:"stop_reason,omitempty"`
TotalCostUSD float64 `json:"total_cost_usd,omitempty"`
Usage map[string]interface{} `json:"usage,omitempty"`
Result string `json:"result,omitempty"`
StructuredOutput interface{} `json:"structured_output,omitempty"`
ModelUsage map[string]interface{} `json:"model_usage,omitempty"`
PermissionDenials []interface{} `json:"permission_denials,omitempty"`
DeferredToolUse *DeferredToolUse `json:"deferred_tool_use,omitempty"`
APIErrorStatus *int `json:"api_error_status,omitempty"`
Errors []string `json:"errors,omitempty"`
UUID string `json:"uuid,omitempty"`
}
ResultMessage represents a result message with cost and usage information.
type SDKControlMcpReconnectRequest ¶ added in v0.1.46
type SDKControlMcpReconnectRequest struct {
Subtype string `json:"subtype"` // "mcp_reconnect"
ServerName string `json:"serverName"`
}
SDKControlMcpReconnectRequest requests reconnection to an MCP server.
type SDKControlMcpToggleRequest ¶ added in v0.1.46
type SDKControlMcpToggleRequest struct {
Subtype string `json:"subtype"` // "mcp_toggle"
ServerName string `json:"serverName"`
Enabled bool `json:"enabled"`
}
SDKControlMcpToggleRequest requests toggling an MCP server on/off.
type SDKControlStopTaskRequest ¶ added in v0.1.46
type SDKControlStopTaskRequest struct {
Subtype string `json:"subtype"` // "stop_task"
TaskID string `json:"task_id"`
}
SDKControlStopTaskRequest requests stopping a running task.
type SDKSessionInfo ¶ added in v0.1.46
type SDKSessionInfo struct {
SessionID string `json:"session_id"`
Summary string `json:"summary"`
LastModified int64 `json:"last_modified"`
FileSize *int64 `json:"file_size,omitempty"`
CustomTitle *string `json:"custom_title,omitempty"`
FirstPrompt *string `json:"first_prompt,omitempty"`
GitBranch *string `json:"git_branch,omitempty"`
CWD *string `json:"cwd,omitempty"`
Tag *string `json:"tag,omitempty"`
CreatedAt *int64 `json:"created_at,omitempty"`
}
SDKSessionInfo contains metadata about a Claude Code session.
func GetSessionInfo ¶ added in v0.1.52
func GetSessionInfo(opts *GetSessionInfoOptions) (*SDKSessionInfo, error)
GetSessionInfo reads metadata for a single session by ID. Wraps readSessionLite for one file — no O(n) directory scan.
func GetSessionInfoFromStore ¶ added in v0.1.65
func GetSessionInfoFromStore(ctx context.Context, opts *GetSessionInfoFromStoreOptions) (*SDKSessionInfo, error)
GetSessionInfoFromStore reads metadata for a single session from a SessionStore.
Returns nil if the session is not found, the session_id is invalid, the session is a sidechain session, or it has no extractable summary.
func ListSessions ¶ added in v0.1.46
func ListSessions(opts *ListSessionsOptions) ([]SDKSessionInfo, error)
ListSessions returns session metadata extracted from stat + head/tail reads.
When Directory is provided, returns sessions for that project directory and its git worktrees. When omitted, returns sessions across all projects.
func ListSessionsFromStore ¶ added in v0.1.65
func ListSessionsFromStore(ctx context.Context, opts *ListSessionsFromStoreOptions) ([]SDKSessionInfo, error)
ListSessionsFromStore lists sessions from a SessionStore.
This is the async store-backed counterpart to ListSessions. It loads each session's entries to derive a real summary via the same lite-parse used by the filesystem path, so disk and store paths produce identical results for the same transcript content.
If the store implements ListSessionSummaries it is called first (one batch call). Sessions with fresh sidecars are returned immediately; sessions missing a sidecar or with a stale one are gap-filled via Load.
Returns an error if the store implements neither ListSessionSummaries nor ListSessions.
type SandboxIgnoreViolations ¶
type SandboxIgnoreViolations struct {
File []string `json:"file,omitempty"`
Network []string `json:"network,omitempty"`
}
SandboxIgnoreViolations specifies violations to ignore.
type SandboxNetworkConfig ¶
type SandboxNetworkConfig struct {
AllowedDomains []string `json:"allowedDomains,omitempty"`
DeniedDomains []string `json:"deniedDomains,omitempty"`
AllowManagedDomainsOnly bool `json:"allowManagedDomainsOnly,omitempty"`
AllowUnixSockets []string `json:"allowUnixSockets,omitempty"`
AllowAllUnixSockets bool `json:"allowAllUnixSockets,omitempty"`
AllowLocalBinding bool `json:"allowLocalBinding,omitempty"`
AllowMachLookup []string `json:"allowMachLookup,omitempty"`
HTTPProxyPort int `json:"httpProxyPort,omitempty"`
SOCKSProxyPort int `json:"socksProxyPort,omitempty"`
}
SandboxNetworkConfig configures network settings for sandbox.
type SandboxSettings ¶
type SandboxSettings struct {
Enabled bool `json:"enabled,omitempty"`
AutoAllowBashIfSandboxed bool `json:"autoAllowBashIfSandboxed,omitempty"`
ExcludedCommands []string `json:"excludedCommands,omitempty"`
AllowUnsandboxedCommands bool `json:"allowUnsandboxedCommands,omitempty"`
Network *SandboxNetworkConfig `json:"network,omitempty"`
IgnoreViolations *SandboxIgnoreViolations `json:"ignoreViolations,omitempty"`
EnableWeakerNestedSandbox bool `json:"enableWeakerNestedSandbox,omitempty"`
}
SandboxSettings configures bash command sandboxing.
type SdkBeta ¶ added in v0.1.52
type SdkBeta = string
SdkBeta defines known beta feature identifiers.
const (
SdkBetaContext1M SdkBeta = "context-1m-2025-08-07"
)
type SdkMcpTool ¶
type SdkMcpTool struct {
Name string
Description string
InputSchema interface{}
Handler func(args map[string]interface{}) (map[string]interface{}, error)
}
SdkMcpTool defines a custom MCP tool.
type ServerToolName ¶ added in v0.1.65
type ServerToolName = string
ServerToolName identifies a server-side tool (e.g. advisor, web_search).
type ServerToolResultBlock ¶ added in v0.1.65
type ServerToolResultBlock struct {
ToolUseID string `json:"tool_use_id"`
Content map[string]interface{} `json:"content"`
}
ServerToolResultBlock represents the result of a server-side tool call.
Content is the raw dict from the API, opaque to this layer — callers that care about a specific server tool's result schema can inspect Content["type"].
func (*ServerToolResultBlock) MarshalJSON ¶ added in v0.1.65
func (b *ServerToolResultBlock) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler for ServerToolResultBlock.
type ServerToolUseBlock ¶ added in v0.1.65
type ServerToolUseBlock struct {
ID string `json:"id"`
Name ServerToolName `json:"name"`
Input map[string]interface{} `json:"input"`
}
ServerToolUseBlock represents a server-side tool use content block (e.g. advisor, web_search).
These are tools the API executes server-side on the model's behalf, so they appear in the message stream alongside regular tool_use blocks but the caller never needs to return a result. Name is a discriminator — branch on it to know which server tool was invoked.
func (*ServerToolUseBlock) MarshalJSON ¶ added in v0.1.65
func (b *ServerToolUseBlock) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler for ServerToolUseBlock.
type SessionKey ¶ added in v0.1.65
type SessionKey struct {
ProjectKey string `json:"project_key"`
SessionID string `json:"session_id"`
// Subpath is empty for the main transcript; set for subagent files.
// Opaque to the adapter — just use it as a storage key suffix.
Subpath string `json:"subpath,omitempty"`
}
SessionKey identifies a session transcript or subagent transcript in a store.
Main transcripts have an empty Subpath; subagent transcripts include a Subpath like "subagents/agent-{id}" that mirrors the on-disk directory structure.
func FilePathToSessionKey ¶ added in v0.1.65
func FilePathToSessionKey(filePath, projectsDir string) *SessionKey
FilePathToSessionKey converts a raw .jsonl file path to a SessionKey by deriving the project_key from the parent directory and the session_id from the file name.
projectsDir is the root projects directory (e.g. ~/.claude/projects). Returns nil when the path cannot be parsed as a session file.
type SessionListSubkeysKey ¶ added in v0.1.65
type SessionListSubkeysKey struct {
ProjectKey string `json:"project_key"`
SessionID string `json:"session_id"`
}
SessionListSubkeysKey is a key argument to SessionStore.ListSubkeys (no Subpath).
type SessionMessage ¶ added in v0.1.46
type SessionMessage struct {
Type SessionMessageType `json:"type"`
UUID string `json:"uuid"`
SessionID string `json:"session_id"`
Message interface{} `json:"message"`
ParentToolUseID *string `json:"parent_tool_use_id,omitempty"`
}
SessionMessage represents a message in a session's conversation.
func GetSessionMessages ¶ added in v0.1.46
func GetSessionMessages(opts *GetSessionMessagesOptions) ([]SessionMessage, error)
GetSessionMessages reads a session's conversation messages from its JSONL transcript file.
Parses the full JSONL, builds the conversation chain via parentUuid links, and returns user/assistant messages in chronological order.
func GetSessionMessagesFromStore ¶ added in v0.1.65
func GetSessionMessagesFromStore(ctx context.Context, opts *GetSessionMessagesFromStoreOptions) ([]SessionMessage, error)
GetSessionMessagesFromStore reads a session's conversation messages from a SessionStore.
This is the store-backed counterpart to GetSessionMessages. It feeds SessionStore.Load() results directly into the chain builder — no JSONL round-trip. Returns an empty slice if the session is not found or the session_id is invalid.
func GetSubagentMessages ¶ added in v0.1.65
func GetSubagentMessages(opts *GetSubagentMessagesOptions) ([]SessionMessage, error)
GetSubagentMessages reads messages from a subagent transcript.
func GetSubagentMessagesFromStore ¶ added in v0.1.65
func GetSubagentMessagesFromStore(ctx context.Context, opts *GetSubagentMessagesFromStoreOptions) ([]SessionMessage, error)
GetSubagentMessagesFromStore reads a subagent's conversation messages from a SessionStore.
This is the store-backed counterpart to GetSubagentMessages. Subagents may live at subagents/agent-<id> or nested under subagents/workflows/<runId>/agent-<id>. Scans subkeys when the store implements ListSubkeys; otherwise tries the direct path. Returns an empty slice if not found or the session_id is invalid.
type SessionMessageType ¶ added in v0.1.46
type SessionMessageType string
SessionMessageType represents the type of a session message.
const ( SessionMessageTypeUser SessionMessageType = "user" SessionMessageTypeAssistant SessionMessageType = "assistant" )
type SessionStore ¶ added in v0.1.65
type SessionStore interface {
// Append mirrors a batch of transcript entries.
// Called AFTER the subprocess's local write succeeds — durability is
// already guaranteed locally.
Append(ctx context.Context, key SessionKey, entries []SessionStoreEntry) error
// Load loads a full session for resume.
// Return nil for a key that was never written.
Load(ctx context.Context, key SessionKey) ([]SessionStoreEntry, error)
// ListSessions lists sessions for a project_key. Returns IDs + modification times.
// Optional — if unimplemented, list operations raise.
ListSessions(ctx context.Context, projectKey string) ([]SessionStoreListEntry, error)
// ListSessionSummaries returns incrementally-maintained summaries for all
// sessions in one call. Optional.
ListSessionSummaries(ctx context.Context, projectKey string) ([]SessionSummaryEntry, error)
// Delete deletes a session. Deleting a main-transcript key (Subpath=="")
// must cascade to all subkeys so subagent transcripts aren't orphaned.
// Optional.
Delete(ctx context.Context, key SessionKey) error
// ListSubkeys lists the subpath keys for a session (e.g. subagent transcripts).
// Optional.
ListSubkeys(ctx context.Context, key SessionListSubkeysKey) ([]string, error)
}
SessionStore is the interface for adapters that mirror session transcripts to external storage.
The subprocess still writes to local disk; the adapter receives a secondary copy. Only Append and Load are required. The remaining methods are optional.
type SessionStoreEntry ¶ added in v0.1.65
type SessionStoreEntry = map[string]interface{}
SessionStoreEntry is one JSONL transcript line as observed by a SessionStore adapter. Adapters should treat entries as pass-through blobs; round-tripping via JSON is the only required invariant.
type SessionStoreFlushMode ¶ added in v0.1.73
type SessionStoreFlushMode = string
SessionStoreFlushMode controls when transcript-mirror entries are flushed to a SessionStore.
- "batched" (default): buffer entries and flush once per turn (on the result message) or when the pending buffer exceeds thresholds. Keeps adapter latency off the streaming hot path.
- "eager": trigger a background flush after every transcript_mirror frame so SessionStore.Append sees entries in near real time. Appends are still serialized in enqueue order; a slow adapter will not stall the read loop.
const ( // SessionStoreFlushModeBatched buffers entries and flushes once per turn. // This is the default behavior. SessionStoreFlushModeBatched SessionStoreFlushMode = "batched" // SessionStoreFlushModeEager triggers a flush after every frame for // near-real-time delivery to the SessionStore. SessionStoreFlushModeEager SessionStoreFlushMode = "eager" )
type SessionStoreListEntry ¶ added in v0.1.65
type SessionStoreListEntry struct {
SessionID string `json:"session_id"`
// Mtime is the last-modified time in Unix epoch milliseconds.
Mtime int64 `json:"mtime"`
}
SessionStoreListEntry is an entry returned by SessionStore.ListSessions.
type SessionSummaryEntry ¶ added in v0.1.65
type SessionSummaryEntry struct {
SessionID string `json:"session_id"`
// Mtime is the storage write time of the sidecar, in Unix epoch milliseconds.
Mtime int64 `json:"mtime"`
// Data is opaque SDK-owned summary state. Persist verbatim; do not interpret.
Data map[string]interface{} `json:"data"`
}
SessionSummaryEntry is an incrementally-maintained session summary.
Stores obtain this from FoldSessionSummary inside Append and persist it verbatim; they return the full set from ListSessionSummaries. The Data field is opaque SDK-owned state — stores MUST NOT interpret it.
func FoldSessionSummary ¶ added in v0.1.65
func FoldSessionSummary(prev *SessionSummaryEntry, key SessionKey, entries []SessionStoreEntry) SessionSummaryEntry
FoldSessionSummary computes an updated SessionSummaryEntry by applying new transcript entries on top of an existing (possibly zero-value) summary.
Fields follow two update strategies:
- Set-once (first writer wins): created_at, cwd, is_sidechain
- Last-wins: custom_title, ai_title, last_prompt, summary_hint, git_branch, mtime
- Tag: set on "tag" type entries; cleared when tag value is ""
type SettingSource ¶
type SettingSource string
SettingSource specifies which setting sources to load.
const ( SettingSourceUser SettingSource = "user" SettingSourceProject SettingSource = "project" SettingSourceLocal SettingSource = "local" )
type StreamEvent ¶
type StreamEvent struct {
UUID string `json:"uuid"`
SessionID string `json:"session_id"`
Event map[string]interface{} `json:"event"`
ParentToolUseID string `json:"parent_tool_use_id,omitempty"`
}
StreamEvent represents a stream event for partial message updates.
type SystemMessage ¶
type SystemMessage struct {
Subtype string `json:"subtype"`
Data map[string]interface{} `json:"data"`
}
SystemMessage represents a system message with metadata.
type SystemPromptFile ¶ added in v0.1.52
SystemPromptFile configures a system prompt loaded from a file.
type SystemPromptPreset ¶
type SystemPromptPreset struct {
Type string `json:"type"` // "preset"
Preset string `json:"preset"` // "claude_code"
Append string `json:"append,omitempty"`
// ExcludeDynamicSections strips per-user dynamic sections (working directory,
// auto-memory, git status) from the system prompt so it stays static and
// cacheable across users. The stripped content is re-injected into the first
// user message so the model still has access to it.
//
// Use this when many users share the same preset system prompt and you
// want the prompt-caching prefix to hit cross-user.
//
// Requires a Claude Code CLI version that supports this option; older
// CLIs silently ignore it.
ExcludeDynamicSections *bool `json:"excludeDynamicSections,omitempty"`
}
SystemPromptPreset represents a system prompt preset configuration.
type TaskBudget ¶ added in v0.1.52
type TaskBudget struct {
Total int `json:"total"`
}
TaskBudget configures an API-side task budget in tokens.
type TaskNotificationMessage ¶ added in v0.1.46
type TaskNotificationMessage struct {
TaskID string `json:"task_id"`
Status TaskNotificationStatus `json:"status"`
OutputFile string `json:"output_file"`
Summary string `json:"summary"`
UUID string `json:"uuid"`
SessionID string `json:"session_id"`
ToolUseID string `json:"tool_use_id,omitempty"`
Usage *TaskUsage `json:"usage,omitempty"`
}
TaskNotificationMessage represents a task notification system message.
type TaskNotificationStatus ¶ added in v0.1.46
type TaskNotificationStatus string
TaskNotificationStatus represents the status of a task notification.
const ( TaskNotificationStatusCompleted TaskNotificationStatus = "completed" TaskNotificationStatusFailed TaskNotificationStatus = "failed" TaskNotificationStatusStopped TaskNotificationStatus = "stopped" )
type TaskProgressMessage ¶ added in v0.1.46
type TaskProgressMessage struct {
TaskID string `json:"task_id"`
Description string `json:"description"`
Usage TaskUsage `json:"usage"`
UUID string `json:"uuid"`
SessionID string `json:"session_id"`
ToolUseID string `json:"tool_use_id,omitempty"`
LastToolName string `json:"last_tool_name,omitempty"`
}
TaskProgressMessage represents a task progress system message.
type TaskStartedMessage ¶ added in v0.1.46
type TaskStartedMessage struct {
TaskID string `json:"task_id"`
Description string `json:"description"`
UUID string `json:"uuid"`
SessionID string `json:"session_id"`
ToolUseID string `json:"tool_use_id,omitempty"`
TaskType string `json:"task_type,omitempty"`
}
TaskStartedMessage represents a task started system message.
type TaskUsage ¶ added in v0.1.46
type TaskUsage struct {
TotalTokens int `json:"total_tokens"`
ToolUses int `json:"tool_uses"`
DurationMS int `json:"duration_ms"`
}
TaskUsage represents usage statistics reported in task_progress and task_notification messages.
type TextBlock ¶
type TextBlock struct {
Text string `json:"text"`
}
TextBlock represents a text content block.
func (*TextBlock) MarshalJSON ¶
MarshalJSON implements json.Marshaler for TextBlock.
type ThinkingBlock ¶
ThinkingBlock represents a thinking content block.
func (*ThinkingBlock) MarshalJSON ¶
func (b *ThinkingBlock) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler for ThinkingBlock.
type ThinkingConfig ¶
type ThinkingConfig struct {
Type string `json:"type"` // "adaptive", "enabled", "disabled"
BudgetTokens int `json:"budget_tokens,omitempty"`
// Display controls how thinking text is surfaced: "summarized" or "omitted".
// Only valid for "adaptive" and "enabled" types.
Display string `json:"display,omitempty"` // "summarized" or "omitted"
}
ThinkingConfig represents thinking configuration.
type TimeoutError ¶
type TimeoutError struct {
ClaudeSDKError
RequestType string
}
TimeoutError indicates that a control request timed out.
func NewTimeoutError ¶
func NewTimeoutError(requestType string) *TimeoutError
NewTimeoutError creates a new TimeoutError.
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
type ToolBuilder ¶
type ToolBuilder struct {
// contains filtered or unexported fields
}
ToolBuilder provides a fluent interface for building tools.
func Tool ¶
func Tool(name, description string, inputSchema interface{}) *ToolBuilder
Tool creates a new ToolBuilder for defining an MCP tool.
Example:
addTool := claude.Tool("add", "Add two numbers", map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"a": map[string]interface{}{"type": "number"},
"b": map[string]interface{}{"type": "number"},
},
}).Handler(func(args map[string]interface{}) (map[string]interface{}, error) {
a := args["a"].(float64)
b := args["b"].(float64)
return map[string]interface{}{
"content": []map[string]interface{}{
{"type": "text", "text": fmt.Sprintf("%.2f + %.2f = %.2f", a, b, a+b)},
},
}, nil
})
func (*ToolBuilder) Handler ¶
func (b *ToolBuilder) Handler(fn func(args map[string]interface{}) (map[string]interface{}, error)) SdkMcpTool
Handler sets the handler function for the tool and returns the completed SdkMcpTool.
type ToolPermissionContext ¶
type ToolPermissionContext struct {
Signal interface{} // Future: abort signal support
Suggestions []PermissionUpdate // Permission suggestions from CLI
ToolUseID string // Unique identifier for this specific tool call
AgentID string // If running within a sub-agent, the sub-agent's ID
BlockedPath string // File path that triggered the permission request
DecisionReason string // Explains why this permission request was triggered
Title string // Full permission prompt sentence (e.g. "Claude wants to read foo.txt")
DisplayName string // Short noun phrase for the tool action (e.g. "Read file")
Description string // Human-readable subtitle for the permission UI
}
ToolPermissionContext provides context for tool permission callbacks.
type ToolResultBlock ¶
type ToolResultBlock struct {
ToolUseID string `json:"tool_use_id"`
Content interface{} `json:"content,omitempty"`
IsError bool `json:"is_error,omitempty"`
}
ToolResultBlock represents a tool result content block.
func (*ToolResultBlock) MarshalJSON ¶
func (b *ToolResultBlock) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler for ToolResultBlock.
type ToolUseBlock ¶
type ToolUseBlock struct {
ID string `json:"id"`
Name string `json:"name"`
Input map[string]interface{} `json:"input"`
}
ToolUseBlock represents a tool use content block.
func (*ToolUseBlock) MarshalJSON ¶
func (b *ToolUseBlock) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler for ToolUseBlock.
type ToolsPreset ¶
type ToolsPreset struct {
Type string `json:"type"` // "preset"
Preset string `json:"preset"` // "claude_code"
}
ToolsPreset represents a tools preset configuration.
type UserMessage ¶
type UserMessage struct {
Content interface{} `json:"content"` // string or []ContentBlock
UUID string `json:"uuid,omitempty"`
ParentToolUseID string `json:"parent_tool_use_id,omitempty"`
ToolUseResult map[string]interface{} `json:"tool_use_result,omitempty"`
}
UserMessage represents a user message.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
hooks
command
Package main demonstrates hooks with the Claude Agent SDK.
|
Package main demonstrates hooks with the Claude Agent SDK. |
|
mcp_calculator
command
Package main demonstrates custom MCP tools with the Claude Agent SDK.
|
Package main demonstrates custom MCP tools with the Claude Agent SDK. |
|
quickstart
command
Package main demonstrates basic usage of the Claude Agent SDK.
|
Package main demonstrates basic usage of the Claude Agent SDK. |
|
say_hi
command
Package main demonstrates saying hi to Claude.
|
Package main demonstrates saying hi to Claude. |
|
streaming
command
Package main demonstrates ClaudeSDKClient for bidirectional conversations.
|
Package main demonstrates ClaudeSDKClient for bidirectional conversations. |
|
transport
Package transport provides the transport layer for CLI communication.
|
Package transport provides the transport layer for CLI communication. |
|
Package testutil provides test utilities for the Claude Agent SDK.
|
Package testutil provides test utilities for the Claude Agent SDK. |