Documentation
¶
Overview ¶
Package claude is a Go port of the Python claude-agent-sdk. It drives the user-installed `claude` CLI over its bidirectional control protocol, exposing a one-shot Query, a QueryText convenience, and a stateful Client with a pull-based message stream.
Choosing an entry point ¶
Capability QueryText Query Client One-shot text answer yes yes yes Streaming messages - yes yes Tool/thinking/cost inspection - yes yes Multi-turn conversation - - yes Interrupt, SetModel, SetPermissionMode - - yes CanUseTool permission callback - - yes SessionStore mirroring / resume - yes yes
Use QueryText when you only need the final answer string. Use Query to stream a single turn's messages (drain the stream, then Close it). Use Client for multi-turn sessions and live control operations: Connect once, Query per turn, Close when done.
Vocabulary packages ¶
Every type re-exported here is an alias into a public vocabulary package, where field-level documentation renders: conversation (messages, content blocks, results), config (Options), hook, permission, mcpserver (in-process MCP servers), session (stores and history), transport (the I/O boundary), and sdkerr (the error sentinel). Most users only import this root package; the subpackages exist for documentation and for advanced integrations.
Testing without the real CLI: see the claudetest package.
Index ¶
- Constants
- Variables
- func DeleteSessionViaStore(ctx context.Context, store SessionStore, sessionID, directory string) error
- func ImportSessionToStore(ctx context.Context, store SessionStore, sessionID string, opts ImportOptions) error
- func ListSubagentsFromStore(ctx context.Context, store SessionStore, sessionID, directory string) ([]string, error)
- func ProjectKeyForDirectory(dir string) string
- func QueryText(ctx context.Context, prompt string, opts ...Option) (string, error)
- func RenameSessionViaStore(ctx context.Context, store SessionStore, sessionID, title, directory string) error
- func TagSessionViaStore(ctx context.Context, store SessionStore, sessionID, tag string, clear bool, ...) error
- func TextContent(text string) map[string]any
- func WithClient(ctx context.Context, fn func(*Client) error, opts ...Option) (err error)
- type AgentDefinition
- type AgentMemory
- type AssistantMessage
- type AsyncHookJSONOutput
- type CLIConnectionError
- type CLIJSONDecodeError
- type CLINotFoundError
- type CanUseTool
- type Client
- func (c *Client) Close() error
- func (c *Client) Connect(ctx context.Context) error
- func (c *Client) GetContextUsage(ctx context.Context) (json.RawMessage, error)
- func (c *Client) GetMCPStatus(ctx context.Context) (*McpStatusResponse, error)
- func (c *Client) GetServerInfo() json.RawMessage
- func (c *Client) Interrupt(ctx context.Context) error
- func (c *Client) Query(ctx context.Context, prompt string) (*MessageStream, error)
- func (c *Client) QueryBlocks(ctx context.Context, blocks ...ContentBlock) (*MessageStream, error)
- func (c *Client) ReconnectMCPServer(ctx context.Context, serverName string) error
- func (c *Client) RewindFiles(ctx context.Context, userMessageID string) error
- func (c *Client) Send(ctx context.Context, msg json.RawMessage) error
- func (c *Client) SetModel(ctx context.Context, model *string) error
- func (c *Client) SetPermissionMode(ctx context.Context, mode PermissionMode) error
- func (c *Client) StopTask(ctx context.Context, taskID string) error
- func (c *Client) ToggleMCPServer(ctx context.Context, serverName string, enabled bool) error
- type ConfigError
- type ContentBlock
- type ControlProtocolError
- type DeferredToolUse
- type DeletableStore
- type EffortLevel
- type ForkSessionResult
- type HookCallback
- type HookContext
- type HookEvent
- type HookInput
- type HookJSONOutput
- type HookMatcher
- type ImageBlock
- type ImageSource
- type ImportOptions
- type InMemorySessionStore
- type ListableStore
- type McpHttpServerConfig
- type McpSSEServerConfig
- type McpSdkServerConfig
- type McpServerConfig
- type McpServerConnectionStatus
- type McpServerInfo
- type McpServerStatus
- type McpStatusResponse
- type McpStdioServerConfig
- type McpToolAnnotations
- type McpToolInfo
- type Message
- type MessageParseError
- type MessageStream
- func (s *MessageStream) Close() error
- func (s *MessageStream) Final() (*ResultMessage, error)
- func (s *MessageStream) FinalContext(ctx context.Context) (*ResultMessage, error)
- func (s *MessageStream) Recv() (Message, error)
- func (s *MessageStream) RecvContext(ctx context.Context) (Message, error)
- func (s *MessageStream) Seq() iter.Seq2[Message, error]
- func (s *MessageStream) SeqContext(ctx context.Context) iter.Seq2[Message, error]
- func (s *MessageStream) Stats() StreamStats
- type MirrorErrorCallback
- type ModelUsage
- type Option
- func WithAddDirs(dirs ...string) Option
- func WithAgents(agents map[string]AgentDefinition) Option
- func WithAllowedTools(tools ...string) Option
- func WithBetas(betas ...SdkBeta) Option
- func WithCLIPath(path string) Option
- func WithCWD(dir string) Option
- func WithCanUseTool(cb CanUseTool) Option
- func WithContinueConversation(v bool) Option
- func WithDisallowedTools(tools ...string) Option
- func WithEffort(e EffortLevel) Option
- func WithEnableFileCheckpointing(v bool) Option
- func WithEnv(env map[string]string) Option
- func WithExtraArgs(args map[string]*string) Option
- func WithFallbackModel(model string) Option
- func WithForkSession(v bool) Option
- func WithHooks(hooks map[HookEvent][]HookMatcher) Option
- func WithIncludeHookEvents(v bool) Option
- func WithIncludePartialMessages(v bool) Option
- func WithMCPServers(servers map[string]McpServerConfig) Option
- func WithMaxBudgetUSD(usd float64) Option
- func WithMaxBufferSize(n int) Option
- func WithMaxThinkingTokens(n int) Option
- func WithMaxTurns(n int) Option
- func WithModel(model string) Option
- func WithOutputFormat(f *OutputFormat) Option
- func WithPermissionMode(m PermissionMode) Option
- func WithPermissionPromptToolName(name string) Option
- func WithPlugins(plugins ...SdkPluginConfig) Option
- func WithResume(sessionID string) Option
- func WithSandbox(s *SandboxSettings) Option
- func WithSessionID(id string) Option
- func WithSessionStore(store SessionStore) Option
- func WithSessionStoreFlush(m SessionStoreFlushMode) Option
- func WithSettingSources(sources []SettingSource) Option
- func WithSettings(settings string) Option
- func WithSkills(s Skills) Option
- func WithStderr(cb func(string)) Option
- func WithStrictMCPConfig(v bool) Option
- func WithStrictVersionCheck(v bool) Option
- func WithSystemPrompt(sp SystemPrompt) Option
- func WithSystemPromptText(text string) Option
- func WithThinking(t ThinkingConfig) Option
- func WithTools(sel *ToolsSelection) Option
- func WithTransport(tr Transport) Option
- func WithUser(user string) Option
- type Options
- type OutputFormat
- type PermissionBehavior
- type PermissionMode
- type PermissionResult
- type PermissionResultAllow
- type PermissionResultDeny
- type PermissionRuleValue
- type PermissionUpdate
- type PermissionUpdateDestination
- type PermissionUpdateType
- type PostToolUseHookSpecificOutput
- type PreToolUseHookSpecificOutput
- type ProcessError
- type RawBlock
- type ResultMessage
- type SDKSessionInfo
- func GetSessionInfo(directory, sessionID string) (*SDKSessionInfo, error)
- func GetSessionInfoFromStore(ctx context.Context, store SessionStore, sessionID, directory string) (*SDKSessionInfo, error)
- func ListSessions(directory string, limit *int, offset int) ([]SDKSessionInfo, error)
- func ListSessionsFromStore(ctx context.Context, store SessionStore, directory string, limit *int, ...) ([]SDKSessionInfo, error)
- type SandboxIgnoreViolations
- type SandboxNetworkConfig
- type SandboxSettings
- type SdkBeta
- type SdkMcpTool
- type SdkPluginConfig
- type ServerToolName
- type ServerToolResultBlock
- type ServerToolUseBlock
- type SessionError
- type SessionKey
- type SessionListSubkeysKey
- type SessionMessage
- func GetSessionMessages(directory, sessionID string, limit *int, offset int) ([]SessionMessage, error)
- func GetSessionMessagesFromStore(ctx context.Context, store SessionStore, sessionID, directory string, ...) ([]SessionMessage, error)
- func GetSubagentMessagesFromStore(ctx context.Context, store SessionStore, sessionID, agentID, directory string, ...) ([]SessionMessage, error)
- type SessionStore
- type SessionStoreEntry
- type SessionStoreFlushMode
- type SessionStoreListEntry
- type SessionSummaryEntry
- type SettingSource
- type Skills
- type StreamEvent
- type StreamStats
- type SubkeyListableStore
- type SummarizableStore
- type SyncHookJSONOutput
- type SystemMessage
- type SystemPrompt
- type SystemPromptFile
- type SystemPromptPreset
- type SystemPromptString
- type TextBlock
- type ThinkingBlock
- type ThinkingConfig
- type ThinkingConfigAdaptive
- type ThinkingConfigDisabled
- type ThinkingConfigEnabled
- type ThinkingDisplay
- type ToolOption
- type ToolPermissionContext
- type ToolResult
- type ToolResultBlock
- type ToolUseBlock
- type ToolsSelection
- type Transport
- type TurnError
- type Usage
- type UserMessage
- type ValidationError
- type VersionMismatchError
Examples ¶
Constants ¶
const ( SourceUser = config.SourceUser SourceProject = config.SourceProject SourceLocal = config.SourceLocal )
Setting source literals.
const ( EffortLow = config.EffortLow EffortMedium = config.EffortMedium EffortHigh = config.EffortHigh EffortXHigh = config.EffortXHigh EffortMax = config.EffortMax EffortUltracode = config.EffortUltracode )
Effort level literals.
const ( ThinkingDisplaySummarized = config.ThinkingDisplaySummarized ThinkingDisplayOmitted = config.ThinkingDisplayOmitted )
Thinking display literals.
const ( AgentMemoryUser = config.AgentMemoryUser AgentMemoryProject = config.AgentMemoryProject AgentMemoryLocal = config.AgentMemoryLocal )
Agent memory scope literals.
const ( ServerToolAdvisor = conversation.ServerToolAdvisor ServerToolWebSearch = conversation.ServerToolWebSearch ServerToolWebFetch = conversation.ServerToolWebFetch ServerToolCodeExecution = conversation.ServerToolCodeExecution ServerToolBashCodeExecution = conversation.ServerToolBashCodeExecution ServerToolTextEditorCodeExecution = conversation.ServerToolTextEditorCodeExecution ServerToolSearchRegex = conversation.ServerToolSearchRegex ServerToolSearchBM25 = conversation.ServerToolSearchBM25 )
Server-side tool name literals.
const ( ModeDefault = permission.ModeDefault ModeAcceptEdits = permission.ModeAcceptEdits ModePlan = permission.ModePlan ModeBypassPermissions = permission.ModeBypassPermissions ModeDontAsk = permission.ModeDontAsk ModeAuto = permission.ModeAuto )
Permission mode literals.
const ( BehaviorAllow = permission.BehaviorAllow BehaviorDeny = permission.BehaviorDeny BehaviorAsk = permission.BehaviorAsk )
Permission behavior literals.
const ( UpdateAddRules = permission.UpdateAddRules UpdateReplaceRules = permission.UpdateReplaceRules UpdateRemoveRules = permission.UpdateRemoveRules UpdateSetMode = permission.UpdateSetMode UpdateAddDirectories = permission.UpdateAddDirectories UpdateRemoveDirectories = permission.UpdateRemoveDirectories )
Permission update type literals.
const ( DestUserSettings = permission.DestUserSettings DestProjectSettings = permission.DestProjectSettings DestLocalSettings = permission.DestLocalSettings DestSession = permission.DestSession )
Permission update destination literals.
const ( HookPreToolUse = hook.PreToolUse HookPostToolUse = hook.PostToolUse HookPostToolUseFailure = hook.PostToolUseFailure HookUserPromptSubmit = hook.UserPromptSubmit HookStop = hook.Stop HookSubagentStop = hook.SubagentStop HookPreCompact = hook.PreCompact HookNotification = hook.Notification HookSubagentStart = hook.SubagentStart HookPermissionRequest = hook.PermissionRequest )
Hook event literals.
const ( StatusConnected = mcpserver.StatusConnected StatusFailed = mcpserver.StatusFailed StatusNeedsAuth = mcpserver.StatusNeedsAuth StatusPending = mcpserver.StatusPending StatusDisabled = mcpserver.StatusDisabled )
MCP server connection status literals.
const ( FlushBatched = session.FlushBatched FlushEager = session.FlushEager )
Session-store flush mode literals.
const BetaContext1M = config.BetaContext1M
BetaContext1M enables the 1M-token context window (Sonnet 4/4.5 only).
const Version = "0.2.0"
Version is the go-claude release version. Note: the version string the transport reports to the CLI via CLAUDE_AGENT_SDK_VERSION is the pinned agent-SDK protocol version (see internal machinery), not this constant.
Variables ¶
var ErrClaudeSDK = sdkerr.ErrClaudeSDK
ErrClaudeSDK is the umbrella sentinel every SDK error reports through errors.Is, mirroring the Python base class ClaudeSDKError. Match any SDK error with errors.Is(err, claude.ErrClaudeSDK).
var ErrNoStructuredOutput = fmt.Errorf("%w: result carried no structured_output", ErrClaudeSDK)
ErrNoStructuredOutput is returned by QueryStructured when the turn succeeded but the result carried no structured_output (e.g. the model did not produce schema-conforming output). It reports through ErrClaudeSDK.
Functions ¶
func DeleteSessionViaStore ¶
func DeleteSessionViaStore(ctx context.Context, store SessionStore, sessionID, directory string) error
DeleteSessionViaStore deletes a session from a store (no-op for append-only backends).
func ImportSessionToStore ¶
func ImportSessionToStore(ctx context.Context, store SessionStore, sessionID string, opts ImportOptions) error
ImportSessionToStore replays a local session transcript into a SessionStore.
func ListSubagentsFromStore ¶
func ListSubagentsFromStore(ctx context.Context, store SessionStore, sessionID, directory string) ([]string, error)
ListSubagentsFromStore lists subagent IDs for a session from a store.
func ProjectKeyForDirectory ¶
ProjectKeyForDirectory derives the SessionStore project_key for a directory, matching the CLI's project directory naming.
func QueryText ¶
QueryText runs a one-shot Query and returns just the final text: the ResultMessage's result string when present, otherwise the concatenated text of the turn's assistant messages. It drains and closes the stream. A turn the CLI reports as failed (ResultMessage.IsError) returns an error.
answer, err := claude.QueryText(ctx, "What is the capital of France?")
Example ¶
QueryText is the one-liner for "ask a question, get the text back": it runs a one-shot Query, drains the stream, and returns the final result text.
package main
import (
"context"
"fmt"
"log"
claude "github.com/chai-rs/go-claude"
)
func main() {
ctx := context.Background()
answer, err := claude.QueryText(ctx, "What is the capital of France?")
if err != nil {
log.Fatal(err)
}
fmt.Println(answer)
}
Output:
func RenameSessionViaStore ¶
func RenameSessionViaStore(ctx context.Context, store SessionStore, sessionID, title, directory string) error
RenameSessionViaStore renames a session by appending a custom-title entry to a SessionStore.
func TagSessionViaStore ¶
func TagSessionViaStore(ctx context.Context, store SessionStore, sessionID, tag string, clear bool, directory string) error
TagSessionViaStore tags (or clears) a session via a SessionStore.
func TextContent ¶
TextContent builds the MCP text content item {"type":"text","text":…} that tool handlers return inside ToolResult.Content.
func WithClient ¶
WithClient connects a Client, runs fn with it, and always closes it — the Go analogue of Python's "async with ClaudeSDKClient(...)". Connect failure returns without invoking fn; fn's error and Close's error are joined.
err := claude.WithClient(ctx, func(c *claude.Client) error {
stream, err := c.Query(ctx, "hello")
...
}, claude.WithModel("claude-sonnet-4-5"))
Types ¶
type AgentDefinition ¶
type AgentDefinition = config.AgentDefinition
AgentDefinition programmatically defines a custom subagent.
type AgentMemory ¶
type AgentMemory = config.AgentMemory
AgentMemory selects which memory scope a programmatically-defined agent reads.
type AssistantMessage ¶
type AssistantMessage = conversation.AssistantMessage
AssistantMessage is an assistant turn carrying content blocks.
type AsyncHookJSONOutput ¶
type AsyncHookJSONOutput = hook.AsyncHookJSONOutput
AsyncHookJSONOutput defers the hook for a later result.
type CLIConnectionError ¶
type CLIConnectionError = transport.ErrCLIConnection
CLIConnectionError is reported when the subprocess cannot be started or the transport is used while not ready, mirroring the Python SDK's CLIConnectionError.
type CLIJSONDecodeError ¶
type CLIJSONDecodeError = transport.CLIJSONDecodeError
CLIJSONDecodeError is reported when a single CLI stdout frame cannot be decoded as JSON even after buffering up to MaxBufferSize bytes, mirroring the Python SDK's CLIJSONDecodeError.
type CLINotFoundError ¶
type CLINotFoundError = transport.ErrCLINotFound
CLINotFoundError is reported when the claude CLI cannot be located on PATH, via CLAUDE_CLI_PATH, in the known install locations, or at an explicit override. It mirrors the Python SDK's CLINotFoundError.
type CanUseTool ¶
type CanUseTool = permission.CanUseTool
CanUseTool is the permission callback invoked when the CLI classifies a tool as "ask". It is mutually exclusive with Options.PermissionPromptToolName and requires streaming mode (use Client, not the one-shot Query, for a string prompt with CanUseTool — see Client.Connect).
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the stateful, bidirectional entrypoint to the claude CLI, mirroring the Python SDK's ClaudeSDKClient. It owns a transport subprocess and the control-protocol Engine over it, and exposes streaming input (Send), a pull based message stream (Query), and the live control operations (Interrupt, SetPermissionMode, SetModel, MCP management, …).
Lifecycle: NewClient, then Connect once, then Query / Send / control methods, then Close. Close is the Go analogue of the Python __aexit__: always defer it after a successful Connect so the subprocess is reaped and any materialized resume directory is cleaned up.
c, err := claude.NewClient(claude.WithModel("claude-sonnet-4-5"))
if err != nil { return err }
if err := c.Connect(ctx); err != nil { return err }
defer c.Close()
stream, err := c.Query(ctx, "What is 2+2?")
...
Example ¶
Client is the stateful, multi-turn session: Connect once, then any number of Query turns, then Close. The ResultMessage carries the session ID needed to resume the conversation in a later process (see ExampleQuery_resume).
package main
import (
"context"
"fmt"
"log"
claude "github.com/chai-rs/go-claude"
)
func main() {
ctx := context.Background()
c, err := claude.NewClient(claude.WithSystemPromptText("You are terse."))
if err != nil {
log.Fatal(err)
}
if err := c.Connect(ctx); err != nil {
log.Fatal(err)
}
defer c.Close()
stream, err := c.Query(ctx, "What is 2 + 2?")
if err != nil {
log.Fatal(err)
}
for msg, err := range stream.Seq() {
if err != nil {
log.Fatal(err)
}
if res, ok := msg.(*claude.ResultMessage); ok {
fmt.Println("session to resume later:", res.SessionID)
}
}
}
Output:
func NewClient ¶
NewClient builds a Client from functional options. It applies the options and runs cross-field validation but does not spawn the subprocess — call Connect for that. A validation failure (e.g. CanUseTool together with PermissionPromptToolName) is returned here as a *ConfigError.
func NewClientWithOptions ¶
NewClientWithOptions builds a Client from an already-constructed *Options (e.g. a struct literal). It re-runs validation so an invalid combination fails fast.
func (*Client) Close ¶
Close shuts the session down: it closes the engine and transport (reaping the subprocess) and removes any materialized resume directory. It is idempotent and safe to defer immediately after a successful Connect.
func (*Client) Connect ¶
Connect spawns the subprocess and completes the control handshake, mirroring the Python connect() ordering: validate session-store options, materialize a resume session from the store into a temp CLAUDE_CONFIG_DIR (when configured), apply the materialized overrides, route CanUseTool through the stdio permission tool, build and connect the transport (which runs the version check), wire the transcript-mirror batcher, start the read loop, and send the initialize request. On any failure after the subprocess spawns it tears the transport down and removes the temp dir before returning.
func (*Client) GetContextUsage ¶
GetContextUsage returns the current context-window usage breakdown as the raw CLI response object (the same data the /context command shows).
func (*Client) GetMCPStatus ¶
func (c *Client) GetMCPStatus(ctx context.Context) (*McpStatusResponse, error)
GetMCPStatus returns the live MCP server connection status, parsed into a McpStatusResponse.
func (*Client) GetServerInfo ¶
func (c *Client) GetServerInfo() json.RawMessage
GetServerInfo returns the cached initialize result (available commands, output styles, server capabilities) obtained during Connect, or nil before Connect.
func (*Client) Query ¶
Query starts a turn by sending prompt as a user message and returns a stream over the resulting messages up to and including the ResultMessage. It mirrors the Python client.query() string path. For SDK MCP servers or hooks, stdin is kept open until the first result arrives (the engine handles that on Close).
func (*Client) QueryBlocks ¶
func (c *Client) QueryBlocks(ctx context.Context, blocks ...ContentBlock) (*MessageStream, error)
QueryBlocks starts a turn from typed content blocks and returns the MessageStream carrying the reply, exactly as Query does for a plain string. Accepted blocks: *TextBlock, *ToolResultBlock, and *RawBlock (verbatim passthrough for block types the SDK does not model yet, e.g. images). Output-only blocks (*ThinkingBlock, *ToolUseBlock, *ServerToolUseBlock, *ServerToolResultBlock) are rejected with a *ConfigError before anything is written. Ignoring the returned stream is safe: the engine multiplexes one message channel, so the reply can also be consumed from a previously obtained stream.
func (*Client) ReconnectMCPServer ¶
ReconnectMCPServer reconnects a disconnected or failed MCP server by name.
func (*Client) RewindFiles ¶
RewindFiles rewinds tracked files to their state at userMessageID. Requires file checkpointing.
func (*Client) Send ¶
Send streams one user-message frame on an already-connected session, for multi-turn streaming input. msg is a raw user-message object (e.g. {"type":"user","message":{"role":"user","content":"…"}}); a missing session_id is defaulted to "default". Consume the reply via the MessageStream returned by the original Query (the engine multiplexes one stream). Send is the raw escape hatch (the Go analogue of Python's AsyncIterable[dict] streaming-input path); prefer Query for plain text and QueryBlocks for typed content.
func (*Client) SetModel ¶
SetModel changes the AI model mid-session. A nil model clears the override.
func (*Client) SetPermissionMode ¶
func (c *Client) SetPermissionMode(ctx context.Context, mode PermissionMode) error
SetPermissionMode changes the global permission mode mid-session.
type ConfigError ¶
ConfigError reports an invalid Options combination detected before subprocess spawn (mirrors the Python SDK's ValueError from option validation).
type ContentBlock ¶
type ContentBlock = conversation.ContentBlock
ContentBlock is the sealed union of blocks inside a message's content array.
type ControlProtocolError ¶
type ControlProtocolError = sdkerr.ProtocolError
ControlProtocolError is reported when a control request fails: an error control_response from the CLI, a timeout, a cancelled context, an unknown inbound subtype, or a missing callback.
type DeferredToolUse ¶
type DeferredToolUse = conversation.DeferredToolUse
DeferredToolUse describes a tool call deferred for later resolution.
type DeletableStore ¶
type DeletableStore = session.DeletableStore
DeletableStore deletes a session, cascading to subkeys for a main transcript.
type EffortLevel ¶
type EffortLevel = config.EffortLevel
EffortLevel guides how much effort Claude puts into its response.
type ForkSessionResult ¶
type ForkSessionResult = session.ForkSessionResult
ForkSessionResult is the result of a fork operation.
func ForkSessionViaStore ¶
func ForkSessionViaStore(ctx context.Context, store SessionStore, sessionID, directory, upToID, title string) (ForkSessionResult, error)
ForkSessionViaStore forks a session into a new branch with fresh UUIDs via a store.
type HookCallback ¶
HookCallback runs for a matched hook event and returns the directive the CLI should apply.
type HookInput ¶
HookInput is the payload delivered to a hook callback. Typed per-event fields are decoded on demand from Raw via Decode.
type HookJSONOutput ¶
type HookJSONOutput = hook.JSONOutput
HookJSONOutput is the sealed return of a hook callback: either a synchronous directive or an async deferral.
type HookMatcher ¶
HookMatcher subscribes callbacks to an event. A nil Matcher matches every invocation; otherwise it is a tool-name glob (e.g. "Write|Edit").
type ImageBlock ¶
type ImageBlock = conversation.ImageBlock
ImageBlock is an image content block inside a user message.
type ImageSource ¶
type ImageSource = conversation.ImageSource
ImageSource is the payload of an ImageBlock — a base64-encoded image and its media type.
type ImportOptions ¶
type ImportOptions = session.ImportOptions
ImportOptions configures ImportSessionToStore.
type InMemorySessionStore ¶
type InMemorySessionStore = session.InMemorySessionStore
InMemorySessionStore is the reference SessionStore for testing and development.
func NewInMemorySessionStore ¶
func NewInMemorySessionStore() *InMemorySessionStore
NewInMemorySessionStore returns an empty InMemorySessionStore implementing every optional capability interface.
type ListableStore ¶
type ListableStore = session.ListableStore
ListableStore enumerates sessions for a project_key with their modification times.
type McpHttpServerConfig ¶
type McpHttpServerConfig = mcpserver.HTTPServerConfig
McpHttpServerConfig connects to a remote MCP server via HTTP (streamable).
type McpSSEServerConfig ¶
type McpSSEServerConfig = mcpserver.SSEServerConfig
McpSSEServerConfig connects to a remote MCP server via Server-Sent Events.
type McpSdkServerConfig ¶
type McpSdkServerConfig = mcpserver.SDKServerConfig
McpSdkServerConfig registers an in-process SDK MCP server.
func CreateSdkMcpServer ¶
func CreateSdkMcpServer(name, version string, tools []*SdkMcpTool) *McpSdkServerConfig
CreateSdkMcpServer builds an in-process SDK MCP server from a name, version, and tool set, mirroring the Python create_sdk_mcp_server.
type McpServerConfig ¶
type McpServerConfig = mcpserver.ServerConfig
McpServerConfig is the sealed union of MCP server configurations.
type McpServerConnectionStatus ¶
type McpServerConnectionStatus = mcpserver.ServerConnectionStatus
McpServerConnectionStatus is the current connection state of an MCP server.
type McpServerInfo ¶
type McpServerInfo = mcpserver.ServerInfo
McpServerInfo carries the server name and version from the MCP initialize handshake.
type McpServerStatus ¶
type McpServerStatus = mcpserver.ServerStatus
McpServerStatus is the per-server entry inside a McpStatusResponse.
type McpStatusResponse ¶
type McpStatusResponse = mcpserver.StatusResponse
McpStatusResponse is the top-level response from the mcp_status control request.
type McpStdioServerConfig ¶
type McpStdioServerConfig = mcpserver.StdioServerConfig
McpStdioServerConfig launches an MCP server as a subprocess over stdio.
type McpToolAnnotations ¶
type McpToolAnnotations = mcpserver.ToolAnnotations
McpToolAnnotations holds optional semantic annotations for an MCP tool.
type McpToolInfo ¶
McpToolInfo describes a single tool reported by an MCP server in a status response.
type Message ¶
type Message = conversation.Message
Message is the sealed union of top-level messages the CLI emits. Consume via a type switch on the concrete pointer types (*UserMessage, *AssistantMessage, *SystemMessage, *ResultMessage, *StreamEvent).
type MessageParseError ¶
type MessageParseError = conversation.MessageParseError
MessageParseError is reported when a known wire message type is malformed. Unknown message types are skipped, not reported as errors.
type MessageStream ¶
type MessageStream struct {
// contains filtered or unexported fields
}
MessageStream is a pull-based stream of conversation messages from one turn. Recv yields each message in order and returns io.EOF after the terminal ResultMessage (which is itself yielded first), mirroring the Python receive_response() iterator. The stream is backed by the engine's single multiplexed channel, so consuming it also drives streaming-input replies.
func Query ¶
Query runs a one-shot, unidirectional interaction with the claude CLI, mirroring the Python top-level query() function. It connects a fresh session, sends prompt as a single user message, closes stdin, and returns a MessageStream over the resulting messages up to and including the ResultMessage.
Unlike Client, a Query session is fire-and-forget: there is no interrupt or follow-up. The returned stream owns the underlying subprocess; drain it to completion (Recv until io.EOF, or range over Seq) and then call its Close to reap the process. For interactive, stateful conversations use NewClient.
stream, err := claude.Query(ctx, "What is the capital of France?")
if err != nil { return err }
defer stream.Close()
for msg, err := range stream.Seq() {
...
}
CanUseTool requires streaming mode, so it is rejected here with a *ConfigError — use NewClient + Send for a custom permission callback.
Example ¶
The one-shot Query connects a fresh session, sends a single prompt, and streams messages up to the terminal ResultMessage. AssistantMessage.Text extracts the plain text without a content-block type switch.
package main
import (
"context"
"fmt"
"log"
claude "github.com/chai-rs/go-claude"
)
func main() {
ctx := context.Background()
stream, err := claude.Query(ctx, "What is the capital of France?")
if err != nil {
log.Fatal(err)
}
defer stream.Close()
for msg, err := range stream.Seq() {
if err != nil {
log.Fatal(err) // e.g. *claude.ProcessError if the CLI died mid-turn
}
if am, ok := msg.(*claude.AssistantMessage); ok {
fmt.Println(am.Text())
}
}
}
Output:
Example (Resume) ¶
Resuming continues a previous conversation: pass the session ID captured from an earlier turn's ResultMessage (or found via ListSessions) to WithResume.
package main
import (
"context"
"fmt"
"log"
claude "github.com/chai-rs/go-claude"
)
func main() {
ctx := context.Background()
stream, err := claude.Query(ctx, "And what is its population?",
claude.WithResume("11111111-2222-4333-8444-555555555555"))
if err != nil {
log.Fatal(err)
}
defer stream.Close()
for msg, err := range stream.Seq() {
if err != nil {
log.Fatal(err)
}
if am, ok := msg.(*claude.AssistantMessage); ok {
fmt.Println(am.Text())
}
}
}
Output:
func (*MessageStream) Close ¶
func (s *MessageStream) Close() error
Close releases the resources backing the stream. For a one-shot Query stream it closes the owning Client (reaping the subprocess and cleaning up any materialized resume dir); for a Client.Query stream it is a no-op because the caller owns the Client and closes it directly.
func (*MessageStream) Final ¶
func (s *MessageStream) Final() (*ResultMessage, error)
Final drains the stream to the terminal ResultMessage and returns it. On a failed turn (ResultMessage.IsError) the result is returned NON-nil alongside the *TurnError, so cost, usage, and session fields stay readable without errors.As digging. A stream that dies before the result returns (nil, err) with the fatal stream error; a stream that closes cleanly without a result returns (nil, io.EOF).
func (*MessageStream) FinalContext ¶
func (s *MessageStream) FinalContext(ctx context.Context) (*ResultMessage, error)
FinalContext is Final with a cancellation point (see RecvContext for the cancellation semantics).
func (*MessageStream) Recv ¶
func (s *MessageStream) Recv() (Message, error)
Recv returns the next message. It returns io.EOF once the terminal ResultMessage has been delivered (the ResultMessage IS returned before EOF, matching the Python receive_response contract). If the stream ends without a result because the session died — the CLI exited non-zero (*ProcessError), a frame failed to decode (*CLIJSONDecodeError), or a known message type was malformed (*MessageParseError) — that error is returned instead of io.EOF.
func (*MessageStream) RecvContext ¶
func (s *MessageStream) RecvContext(ctx context.Context) (Message, error)
RecvContext is Recv with a cancellation point: it returns ctx.Err() when ctx ends before the next message arrives. Cancellation abandons the wait ONLY — the turn keeps running, the stream stays valid (a later Recv or RecvContext resumes exactly where it left off, losing no messages), and Close is still required to tear the session down.
func (*MessageStream) Seq ¶
func (s *MessageStream) Seq() iter.Seq2[Message, error]
Seq returns a range-over iterator over the stream, yielding each (message, error) pair until the terminal ResultMessage or stream close. The io.EOF that Recv returns to mark end-of-stream is consumed by the iterator and never yielded — iteration simply stops. A non-EOF error is yielded once and stops iteration.
func (*MessageStream) SeqContext ¶
SeqContext is Seq with a cancellation point: when ctx ends, the iterator yields (nil, ctx.Err()) once and stops. As with RecvContext, cancellation abandons iteration only — the stream remains valid for later consumption.
func (*MessageStream) Stats ¶
func (s *MessageStream) Stats() StreamStats
Stats reports the tool-call pairing observed so far. Counters update passively as messages pass through Recv/RecvContext; the call is cheap and safe from any goroutine.
type MirrorErrorCallback ¶
type MirrorErrorCallback = session.MirrorErrorCallback
MirrorErrorCallback is invoked when a mirror batch is dropped after retries.
type ModelUsage ¶
type ModelUsage = conversation.ModelUsage
ModelUsage is one per-model accounting entry (camelCase wire form — the CLI emits a different shape than the top-level usage object).
type Option ¶
Option mutates an Options during NewOptions.
func WithAddDirs ¶
WithAddDirs sets additional accessible directories.
func WithAgents ¶
func WithAgents(agents map[string]AgentDefinition) Option
WithAgents sets the programmatic agent definitions.
func WithAllowedTools ¶
WithAllowedTools sets the auto-allowed tool names.
func WithCLIPath ¶
WithCLIPath overrides the CLI executable path.
func WithCanUseTool ¶
func WithCanUseTool(cb CanUseTool) Option
WithCanUseTool sets the custom permission callback.
func WithContinueConversation ¶
WithContinueConversation toggles continuing the most recent conversation.
func WithDisallowedTools ¶
WithDisallowedTools sets the disallowed tool names.
func WithEnableFileCheckpointing ¶
WithEnableFileCheckpointing toggles file checkpointing.
func WithExtraArgs ¶
WithExtraArgs sets raw extra CLI flags.
func WithFallbackModel ¶
WithFallbackModel sets the fallback model.
func WithForkSession ¶
WithForkSession toggles forking a resumed session.
func WithHooks ¶
func WithHooks(hooks map[HookEvent][]HookMatcher) Option
WithHooks sets the lifecycle hooks.
func WithIncludeHookEvents ¶
WithIncludeHookEvents toggles --include-hook-events.
func WithIncludePartialMessages ¶
WithIncludePartialMessages toggles --include-partial-messages.
func WithMCPServers ¶
func WithMCPServers(servers map[string]McpServerConfig) Option
WithMCPServers sets the MCP server configurations.
func WithMaxBudgetUSD ¶
WithMaxBudgetUSD caps spend in USD.
func WithMaxBufferSize ¶
WithMaxBufferSize caps stdout buffering.
func WithMaxThinkingTokens ¶
WithMaxThinkingTokens sets the deprecated thinking budget.
func WithOutputFormat ¶
func WithOutputFormat(f *OutputFormat) Option
WithOutputFormat sets the structured-output configuration.
func WithPermissionMode ¶
func WithPermissionMode(m PermissionMode) Option
WithPermissionMode sets the global permission mode.
func WithPermissionPromptToolName ¶
WithPermissionPromptToolName routes permission prompts through an MCP tool.
func WithPlugins ¶
func WithPlugins(plugins ...SdkPluginConfig) Option
WithPlugins sets the local plugins.
func WithResume ¶
WithResume sets the session ID to resume.
func WithSandbox ¶
func WithSandbox(s *SandboxSettings) Option
WithSandbox sets the sandbox configuration.
func WithSessionID ¶
WithSessionID forces a specific session ID.
func WithSessionStore ¶
func WithSessionStore(store SessionStore) Option
WithSessionStore sets the transcript-mirror store.
func WithSessionStoreFlush ¶
func WithSessionStoreFlush(m SessionStoreFlushMode) Option
WithSessionStoreFlush sets the mirror flush mode.
func WithSettingSources ¶
func WithSettingSources(sources []SettingSource) Option
WithSettingSources sets the filesystem settings layers (nil = all, empty = isolation, a list = subset).
func WithSettings ¶
WithSettings sets the settings JSON string or file path.
func WithStrictMCPConfig ¶
WithStrictMCPConfig toggles --strict-mcp-config.
func WithStrictVersionCheck ¶
WithStrictVersionCheck makes a below-minimum CLI version a connect error (*VersionMismatchError) instead of a non-fatal warning.
func WithSystemPrompt ¶
func WithSystemPrompt(sp SystemPrompt) Option
WithSystemPrompt sets the system-prompt union.
func WithSystemPromptText ¶
WithSystemPromptText sets a fully custom system prompt from a plain string, the common case of WithSystemPrompt(&SystemPromptString{Text: …}).
func WithThinking ¶
func WithThinking(t ThinkingConfig) Option
WithThinking sets the thinking config.
func WithTools ¶
func WithTools(sel *ToolsSelection) Option
WithTools sets the base built-in tool selection.
func WithTransport ¶
WithTransport overrides the default subprocess transport with a custom Transport implementation. The supplied transport is used as-is: Connect connects it, the engine reads/writes frames over it, and Close closes it. Use it to drive the SDK against a fake CLI in tests (see the claudetest package) or to reach a remote claude process.
type Options ¶
Options is the ClaudeAgentOptions aggregate: every query option for a Claude SDK session. Construct it with NewOptions plus With* functional options, or build the struct literal directly.
func NewOptions ¶
NewOptions builds an Options, applies the functional options in order, and runs cross-field validation.
type OutputFormat ¶
type OutputFormat = config.OutputFormat
OutputFormat is the structured-output configuration for Options.OutputFormat.
func JSONSchemaOutput ¶
func JSONSchemaOutput(schema json.RawMessage) *OutputFormat
JSONSchemaOutput constructs an OutputFormat of type "json_schema".
type PermissionBehavior ¶
type PermissionBehavior = permission.Behavior
PermissionBehavior is the effect a permission rule grants.
type PermissionMode ¶
type PermissionMode = permission.Mode
PermissionMode is the global tool-permission policy. The empty string means unset.
type PermissionResult ¶
type PermissionResult = permission.Result
PermissionResult is the sealed result of a permission decision.
type PermissionResultAllow ¶
type PermissionResultAllow = permission.ResultAllow
PermissionResultAllow allows the tool call, optionally rewriting its input and attaching persistent permission updates.
type PermissionResultDeny ¶
type PermissionResultDeny = permission.ResultDeny
PermissionResultDeny blocks the tool call and optionally interrupts the turn.
type PermissionRuleValue ¶
type PermissionRuleValue = permission.RuleValue
PermissionRuleValue names a tool and an optional rule-content matcher.
type PermissionUpdate ¶
type PermissionUpdate = permission.Update
PermissionUpdate is a tagged permission mutation that rides on an allow decision ("allow + remember").
type PermissionUpdateDestination ¶
type PermissionUpdateDestination = permission.UpdateDestination
PermissionUpdateDestination is where a permission update is persisted.
type PermissionUpdateType ¶
type PermissionUpdateType = permission.UpdateType
PermissionUpdateType discriminates the kinds of permission mutation.
type PostToolUseHookSpecificOutput ¶
type PostToolUseHookSpecificOutput = hook.PostToolUseHookSpecificOutput
PostToolUseHookSpecificOutput replaces tool output after execution.
type PreToolUseHookSpecificOutput ¶
type PreToolUseHookSpecificOutput = hook.PreToolUseHookSpecificOutput
PreToolUseHookSpecificOutput influences the permission decision from a PreToolUse hook.
type ProcessError ¶
type ProcessError = transport.ProcessError
ProcessError is reported when the CLI subprocess exits non-zero. It carries the exit code and any captured stderr, mirroring the Python SDK's ProcessError.
type RawBlock ¶
type RawBlock = conversation.RawBlock
RawBlock preserves content blocks whose type the SDK does not model yet.
type ResultMessage ¶
type ResultMessage = conversation.ResultMessage
ResultMessage is the terminal frame of a turn.
func QueryStructured ¶
func QueryStructured[T any](ctx context.Context, prompt string, opts ...Option) (T, *ResultMessage, error)
QueryStructured runs a one-shot Query whose JSON output schema is derived from T by reflection, drains the stream, and decodes the result's structured_output into T. The ResultMessage is returned alongside the value so cost, usage, and session fields stay accessible. A caller-supplied WithOutputFormat is rejected with a *ConfigError (the schema comes from T); a failed turn returns a *TurnError; a successful turn with no structured_output returns ErrNoStructuredOutput.
type Verdict struct {
Risk string `json:"risk" jsonschema:"enum=low|medium|high"`
Reasons []string `json:"reasons"`
}
verdict, res, err := claude.QueryStructured[Verdict](ctx, "Assess this diff: ...")
type SDKSessionInfo ¶
type SDKSessionInfo = session.SDKSessionInfo
SDKSessionInfo is session metadata returned by the listing functions.
func GetSessionInfo ¶
func GetSessionInfo(directory, sessionID string) (*SDKSessionInfo, error)
GetSessionInfo reads metadata for a single local session transcript, returning nil when it does not exist or is metadata-only.
func GetSessionInfoFromStore ¶
func GetSessionInfoFromStore(ctx context.Context, store SessionStore, sessionID, directory string) (*SDKSessionInfo, error)
GetSessionInfoFromStore reads metadata for a single session from a store.
func ListSessions ¶
func ListSessions(directory string, limit *int, offset int) ([]SDKSessionInfo, error)
ListSessions lists the local Claude Code session history for a directory,
newest first, by scanning ~/.claude/projects/
func ListSessionsFromStore ¶
func ListSessionsFromStore(ctx context.Context, store SessionStore, directory string, limit *int, offset int) ([]SDKSessionInfo, error)
ListSessionsFromStore lists sessions from a SessionStore, sorted by LastModified descending.
type SandboxIgnoreViolations ¶
type SandboxIgnoreViolations = config.SandboxIgnoreViolations
SandboxIgnoreViolations lists violations to ignore in the sandbox.
type SandboxNetworkConfig ¶
type SandboxNetworkConfig = config.SandboxNetworkConfig
SandboxNetworkConfig is the network section of SandboxSettings.
type SandboxSettings ¶
type SandboxSettings = config.SandboxSettings
SandboxSettings configures how Claude Code sandboxes bash commands.
type SdkMcpTool ¶
type SdkMcpTool = mcpserver.SdkMcpTool
SdkMcpTool is the definition of a single in-process MCP tool.
func NewTool ¶
func NewTool( name string, handler func(ctx context.Context, args json.RawMessage) (*ToolResult, error), opts ...ToolOption, ) (*SdkMcpTool, error)
NewTool constructs a SdkMcpTool from a name and handler, applying any options.
Example ¶
An in-process MCP server exposes Go functions as tools. The model addresses
each tool as mcp__
package main
import (
"context"
"encoding/json"
"fmt"
"log"
claude "github.com/chai-rs/go-claude"
)
func main() {
add, err := claude.NewTool(
"add",
func(_ context.Context, args json.RawMessage) (*claude.ToolResult, error) {
var in struct{ A, B float64 }
if err := json.Unmarshal(args, &in); err != nil {
return claude.ErrorResult("bad arguments"), nil
}
return claude.TextResult(fmt.Sprintf("%g", in.A+in.B)), nil
},
claude.WithToolDescription("Add two numbers."),
claude.WithToolInputSchema(json.RawMessage(`{
"type": "object",
"properties": {"a": {"type": "number"}, "b": {"type": "number"}},
"required": ["a", "b"]
}`)),
)
if err != nil {
log.Fatal(err)
}
server := claude.CreateSdkMcpServer("calc", "1.0.0", []*claude.SdkMcpTool{add})
_, err = claude.NewClient(
claude.WithMCPServers(map[string]claude.McpServerConfig{"calc": server}),
claude.WithAllowedTools("mcp__calc__add"),
)
if err != nil {
log.Fatal(err)
}
}
Output:
func NewToolFor ¶
func NewToolFor[T any]( name, description string, handler func(ctx context.Context, args T) (*ToolResult, error), opts ...ToolOption, ) (*SdkMcpTool, error)
NewToolFor constructs a SdkMcpTool whose JSON Schema is derived from T by reflection and whose handler receives typed, already-unmarshaled args — no hand-written schema strings, no manual json.Unmarshal:
type AddArgs struct {
A float64 `json:"a" jsonschema:"description=first addend"`
B float64 `json:"b"`
}
add, err := claude.NewToolFor("add", "Add two numbers",
func(ctx context.Context, args AddArgs) (*claude.ToolResult, error) {
return claude.TextResult(fmt.Sprintf("%g", args.A+args.B)), nil
})
Malformed model arguments are answered with an isError tool result naming the problem so the model can self-correct. NewTool remains the raw escape hatch for hand-written schemas.
type SdkPluginConfig ¶
type SdkPluginConfig = config.SdkPluginConfig
SdkPluginConfig loads a local plugin for the session.
func LocalPlugin ¶
func LocalPlugin(path string) SdkPluginConfig
LocalPlugin constructs an SdkPluginConfig of type "local" for the given path.
type ServerToolName ¶
type ServerToolName = conversation.ServerToolName
ServerToolName enumerates the server-side tools the CLI may surface.
type ServerToolResultBlock ¶
type ServerToolResultBlock = conversation.ServerToolResultBlock
ServerToolResultBlock carries the result of a server-side tool.
type ServerToolUseBlock ¶
type ServerToolUseBlock = conversation.ServerToolUseBlock
ServerToolUseBlock is a server-executed tool invocation (web search, etc.).
type SessionError ¶
SessionError is the general session-layer error: invalid arguments, a missing source session, or a store/adapter call that failed during a session operation.
type SessionKey ¶
SessionKey identifies a session transcript or subagent transcript in a store.
type SessionListSubkeysKey ¶
type SessionListSubkeysKey = session.ListSubkeysKey
SessionListSubkeysKey is the key argument to SubkeyListableStore.ListSubkeys.
type SessionMessage ¶
SessionMessage is a user or assistant message from a session transcript.
func GetSessionMessages ¶
func GetSessionMessages(directory, sessionID string, limit *int, offset int) ([]SessionMessage, error)
GetSessionMessages reads a local session transcript and returns its main conversation chain as user/assistant messages, applying offset/limit.
func GetSessionMessagesFromStore ¶
func GetSessionMessagesFromStore(ctx context.Context, store SessionStore, sessionID, directory string, limit *int, offset int) ([]SessionMessage, error)
GetSessionMessagesFromStore reads a session's conversation messages from a store.
func GetSubagentMessagesFromStore ¶
func GetSubagentMessagesFromStore(ctx context.Context, store SessionStore, sessionID, agentID, directory string, limit *int, offset int) ([]SessionMessage, error)
GetSubagentMessagesFromStore reads a subagent's conversation messages from a store.
type SessionStore ¶
SessionStore is the base adapter for mirroring session transcripts to external storage. Only Append and Load are required; the remaining capabilities are separate optional interfaces probed at runtime.
type SessionStoreEntry ¶
type SessionStoreEntry = session.StoreEntry
SessionStoreEntry is one JSONL transcript line as a permissive pass-through blob.
type SessionStoreFlushMode ¶
type SessionStoreFlushMode = session.StoreFlushMode
SessionStoreFlushMode controls when transcript-mirror entries are flushed.
type SessionStoreListEntry ¶
type SessionStoreListEntry = session.StoreListEntry
SessionStoreListEntry is one entry returned by ListableStore.ListSessions.
type SessionSummaryEntry ¶
type SessionSummaryEntry = session.SummaryEntry
SessionSummaryEntry is an incrementally-maintained session summary.
func FoldSessionSummary ¶
func FoldSessionSummary(prev *SessionSummaryEntry, key SessionKey, entries []SessionStoreEntry) SessionSummaryEntry
FoldSessionSummary folds a batch of appended entries into the running summary for key. Stores call it from inside Append.
type SettingSource ¶
type SettingSource = config.SettingSource
SettingSource names a filesystem settings layer the CLI may load.
type Skills ¶
Skills is the tri-state skills selector for the main session.
func SkillsNamed ¶
SkillsNamed enables only the listed skills.
func SkillsNone ¶
func SkillsNone() Skills
SkillsNone suppresses every skill from the model's listing.
func SkillsUnset ¶
func SkillsUnset() Skills
SkillsUnset is the default tri-state: no SDK skills auto-configuration.
type StreamEvent ¶
type StreamEvent = conversation.StreamEvent
StreamEvent is a partial-message update delivered when partial messages are enabled.
type StreamStats ¶
type StreamStats struct {
// ToolsRequested counts tool_use blocks observed.
ToolsRequested int
// ToolsCompleted counts tool_result blocks observed.
ToolsCompleted int
// PendingToolIDs lists tool_use IDs with no matching tool_result yet,
// sorted for determinism.
PendingToolIDs []string
// SawResult reports whether the terminal ResultMessage has been observed.
SawResult bool
}
StreamStats is a snapshot of the tool-call pairing observed on a stream: tool_use blocks seen in assistant messages versus tool_result blocks seen in user messages. An interrupted or truncated turn shows up as non-empty PendingToolIDs with SawResult false.
type SubkeyListableStore ¶
type SubkeyListableStore = session.SubkeyListableStore
SubkeyListableStore lists all subpath keys under a session.
type SummarizableStore ¶
type SummarizableStore = session.SummarizableStore
SummarizableStore returns the incrementally-maintained summaries for all sessions in one call.
type SyncHookJSONOutput ¶
type SyncHookJSONOutput = hook.SyncHookJSONOutput
SyncHookJSONOutput is the immediate hook directive form.
type SystemMessage ¶
type SystemMessage = conversation.SystemMessage
SystemMessage is a system frame whose Subtype re-routes interpretation.
type SystemPrompt ¶
type SystemPrompt = config.SystemPrompt
SystemPrompt is the sealed union for Options.SystemPrompt.
type SystemPromptFile ¶
type SystemPromptFile = config.SystemPromptFile
SystemPromptFile loads the system prompt from a file path.
type SystemPromptPreset ¶
type SystemPromptPreset = config.SystemPromptPreset
SystemPromptPreset selects a built-in preset, optionally appending custom instructions.
type SystemPromptString ¶
type SystemPromptString = config.SystemPromptString
SystemPromptString is a fully custom system prompt supplied verbatim.
type ThinkingBlock ¶
type ThinkingBlock = conversation.ThinkingBlock
ThinkingBlock carries the model's reasoning and its signature.
type ThinkingConfig ¶
type ThinkingConfig = config.ThinkingConfig
ThinkingConfig is the sealed union for Options.Thinking.
type ThinkingConfigAdaptive ¶
type ThinkingConfigAdaptive = config.ThinkingConfigAdaptive
ThinkingConfigAdaptive lets Claude decide when and how much to think.
type ThinkingConfigDisabled ¶
type ThinkingConfigDisabled = config.ThinkingConfigDisabled
ThinkingConfigDisabled turns off extended thinking.
type ThinkingConfigEnabled ¶
type ThinkingConfigEnabled = config.ThinkingConfigEnabled
ThinkingConfigEnabled sets a fixed thinking-token budget.
type ThinkingDisplay ¶
type ThinkingDisplay = config.ThinkingDisplay
ThinkingDisplay controls whether thinking text is summarized or omitted.
type ToolOption ¶
type ToolOption = mcpserver.ToolOption
ToolOption is a functional option for NewTool.
func WithToolDescription ¶
func WithToolDescription(d string) ToolOption
WithToolDescription sets the tool description.
func WithToolInputSchema ¶
func WithToolInputSchema(schema json.RawMessage) ToolOption
WithToolInputSchema sets the tool's JSON Schema (must be valid JSON).
type ToolPermissionContext ¶
type ToolPermissionContext = permission.ToolPermissionContext
ToolPermissionContext carries the metadata the CLI attaches to a can_use_tool request.
type ToolResult ¶
type ToolResult = mcpserver.ToolResult
ToolResult is the value returned by a tool handler.
func ErrorResult ¶
func ErrorResult(text string) *ToolResult
ErrorResult builds a ToolResult carrying a single text content item with the MCP isError flag set, reporting a tool-level failure to the model without failing the control round-trip.
func TextResult ¶
func TextResult(text string) *ToolResult
TextResult builds a ToolResult carrying a single text content item — the overwhelmingly common return shape for SDK MCP tool handlers.
return claude.TextResult("4"), nil
type ToolResultBlock ¶
type ToolResultBlock = conversation.ToolResultBlock
ToolResultBlock carries the result of a tool invocation.
type ToolUseBlock ¶
type ToolUseBlock = conversation.ToolUseBlock
ToolUseBlock is a request by the model to invoke a tool.
type ToolsSelection ¶
type ToolsSelection = config.ToolsSelection
ToolsSelection is the base built-in tool set for Options.Tools.
func ToolsList ¶
func ToolsList(names ...string) *ToolsSelection
ToolsList selects an explicit set of built-in tool names (empty disables all).
func ToolsPresetClaudeCode ¶
func ToolsPresetClaudeCode() *ToolsSelection
ToolsPresetClaudeCode selects the "claude_code" tools preset.
type Transport ¶
Transport is the low-level I/O boundary to the claude process: Connect starts it, Write sends one framed NDJSON line, ReadMessages streams decoded frames, EndInput closes the input side, Close reaps everything. Supply a custom implementation via WithTransport to test against a fake CLI (see the claudetest package) or to reach a remote process.
type TurnError ¶
type TurnError = conversation.TurnError
TurnError is reported when a turn completes but the CLI marks it failed (ResultMessage.IsError) — e.g. budget exceeded or max turns. The full ResultMessage is retained on the error for inspection.
type Usage ¶
type Usage = conversation.Usage
Usage is the aggregate token accounting for a turn (snake_case wire form).
type ValidationError ¶
type ValidationError = session.ValidationError
ValidationError is reported for invalid session-store option combinations detected before subprocess spawn.
type VersionMismatchError ¶
type VersionMismatchError = sdkerr.VersionMismatchError
VersionMismatchError is reported by Connect when WithStrictVersionCheck is enabled and the installed claude CLI is older than the minimum supported version.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package claudetest provides a scriptable in-memory Transport for testing code built on the claude SDK without spawning the real CLI.
|
Package claudetest provides a scriptable in-memory Transport for testing code built on the claude SDK without spawning the real CLI. |
|
Package config owns the ClaudeAgentOptions aggregate: every query option, the functional-option setters, cross-field validation, the exhaustive CLI-flag rendering (ToFlags), and the initialize control-request payload.
|
Package config owns the ClaudeAgentOptions aggregate: every query option, the functional-option setters, cross-field validation, the exhaustive CLI-flag rendering (ToFlags), and the initialize control-request payload. |
|
Package conversation holds the wire vocabulary of the SDK: the Message and ContentBlock sealed unions and the parser that turns CLI NDJSON frames into them.
|
Package conversation holds the wire vocabulary of the SDK: the Message and ContentBlock sealed unions and the parser that turns CLI NDJSON frames into them. |
|
examples
|
|
|
agents
command
Command agents ports the Python SDK examples/agents.py: defining and using custom subagents with specific tools, prompts, and models via Options.
|
Command agents ports the Python SDK examples/agents.py: defining and using custom subagents with specific tools, prompts, and models via Options. |
|
hooks
command
Command hooks ports the Python SDK examples/hooks.py: lifecycle hooks wired through Options — a PreToolUse hook that blocks specific bash commands and a PreToolUse hook that allows or denies Write operations by file path.
|
Command hooks ports the Python SDK examples/hooks.py: lifecycle hooks wired through Options — a PreToolUse hook that blocks specific bash commands and a PreToolUse hook that allows or denies Write operations by file path. |
|
include_partial_messages
command
Command include_partial_messages ports the Python SDK examples/include_partial_messages.py: enabling partial-message streaming so StreamEvent frames carrying incremental updates are interleaved with regular messages.
|
Command include_partial_messages ports the Python SDK examples/include_partial_messages.py: enabling partial-message streaming so StreamEvent frames carrying incremental updates are interleaved with regular messages. |
|
list_sessions
command
Command list_sessions prints the local Claude Code session history for a directory (default: the current working directory), reading ~/.claude/projects/
|
Command list_sessions prints the local Claude Code session history for a directory (default: the current working directory), reading ~/.claude/projects/ |
|
max_budget_usd
command
Command max_budget_usd ports the Python SDK examples/max_budget_usd.py: capping spend with max_budget_usd and observing the result subtype, including the error_max_budget_usd terminal status when the cap is exceeded.
|
Command max_budget_usd ports the Python SDK examples/max_budget_usd.py: capping spend with max_budget_usd and observing the result subtype, including the error_max_budget_usd terminal status when the cap is exceeded. |
|
mcp_calculator
command
Command mcp_calculator ports the Python SDK examples/mcp_calculator.py: an in-process SDK MCP server exposing calculator tools, wired into a streaming client whose calculator tools are pre-approved.
|
Command mcp_calculator ports the Python SDK examples/mcp_calculator.py: an in-process SDK MCP server exposing calculator tools, wired into a streaming client whose calculator tools are pre-approved. |
|
plugin_example
command
Command plugin_example ports the Python SDK examples/plugin_example.py: loading a local plugin and verifying it appears in the init SystemMessage's plugins list.
|
Command plugin_example ports the Python SDK examples/plugin_example.py: loading a local plugin and verifying it appears in the init SystemMessage's plugins list. |
|
quick_start
command
Command quick_start ports the Python SDK examples/quick_start.py: a basic one-shot query, a query with custom options, and a query that uses tools.
|
Command quick_start ports the Python SDK examples/quick_start.py: a basic one-shot query, a query with custom options, and a query that uses tools. |
|
setting_sources
command
Command setting_sources ports the Python SDK examples/setting_sources.py: controlling which filesystem settings layers the CLI loads (nil = all, empty = none, a subset list), observed through the init SystemMessage's available slash commands.
|
Command setting_sources ports the Python SDK examples/setting_sources.py: controlling which filesystem settings layers the CLI loads (nil = all, empty = none, a subset list), observed through the init SystemMessage's available slash commands. |
|
stderr_callback
command
Command stderr_callback ports the Python SDK examples/stderr_callback_example.py: capturing the CLI's stderr output line by line through a callback.
|
Command stderr_callback ports the Python SDK examples/stderr_callback_example.py: capturing the CLI's stderr output line by line through a callback. |
|
streaming_mode
command
Command streaming_mode ports the Python SDK examples/streaming_mode.py: the stateful ClaudeSDKClient streaming interface — basic streaming, multi-turn conversation, interrupt, manual message handling, streaming-input sends, and server-info retrieval.
|
Command streaming_mode ports the Python SDK examples/streaming_mode.py: the stateful ClaudeSDKClient streaming interface — basic streaming, multi-turn conversation, interrupt, manual message handling, streaming-input sends, and server-info retrieval. |
|
system_prompt
command
Command system_prompt ports the Python SDK examples/system_prompt.py: the different SystemPrompt configurations — none, a custom string, a built-in preset, and a preset with appended instructions.
|
Command system_prompt ports the Python SDK examples/system_prompt.py: the different SystemPrompt configurations — none, a custom string, a built-in preset, and a preset with appended instructions. |
|
tool_permission_callback
command
Command tool_permission_callback ports the Python SDK examples/tool_permission_callback.py: a can_use_tool callback that allows, denies, or rewrites tool inputs.
|
Command tool_permission_callback ports the Python SDK examples/tool_permission_callback.py: a can_use_tool callback that allows, denies, or rewrites tool inputs. |
|
Package hook owns the lifecycle-hook subscription and dispatch model: the Event set, the Matcher subscription, the Callback signature, and the per-event input/output shapes.
|
Package hook owns the lifecycle-hook subscription and dispatch model: the Event set, the Matcher subscription, the Callback signature, and the per-event input/output shapes. |
|
internal
|
|
|
control
Package control implements the bidirectional control protocol the SDK speaks with the claude CLI over a transport.Transport.
|
Package control implements the bidirectional control protocol the SDK speaks with the claude CLI over a transport.Transport. |
|
schema
Package schema is a zero-dependency reflective JSON Schema generator for the MCP subset used by tool definitions and structured output.
|
Package schema is a zero-dependency reflective JSON Schema generator for the MCP subset used by tool definitions and structured output. |
|
sessionrt
Package sessionrt holds the session-layer runtime machinery — transcript mirroring, resume materialization, and option validation — split out of the public session vocabulary package so the public surface carries only types and store operations.
|
Package sessionrt holds the session-layer runtime machinery — transcript mirroring, resume materialization, and option validation — split out of the public session vocabulary package so the public surface carries only types and store operations. |
|
subprocess
Package subprocess is the default claude-CLI transport machinery: process spawn/reap, NDJSON framing, stderr capture, CLI discovery, and the version probe.
|
Package subprocess is the default claude-CLI transport machinery: process spawn/reap, NDJSON framing, stderr capture, CLI discovery, and the version probe. |
|
Package mcp implements in-process SDK MCP servers and the JSON-RPC 2.0 dispatch layer that bridges CLI control-protocol mcp_message frames to registered tool handlers.
|
Package mcp implements in-process SDK MCP servers and the JSON-RPC 2.0 dispatch layer that bridges CLI control-protocol mcp_message frames to registered tool handlers. |
|
Package permission owns the tool-permission round-trip invoked when the CLI emits a can_use_tool control request: the CanUseTool callback, the Result union, and the Update rules that ride on an allow decision.
|
Package permission owns the tool-permission round-trip invoked when the CLI emits a can_use_tool control request: the CanUseTool callback, the Result union, and the Update rules that ride on an allow decision. |
|
Package sdkerr holds the shared error vocabulary for the SDK.
|
Package sdkerr holds the shared error vocabulary for the SDK. |
|
Package session owns the Store port and the full session persistence/lifecycle surface: the store capability interfaces, the in-memory reference adapter, incremental summary folding, byte-exact project key derivation, store-backed listing/reading, resume materialization, import, mutations, and the transcript-mirror batcher.
|
Package session owns the Store port and the full session persistence/lifecycle surface: the store capability interfaces, the in-memory reference adapter, incremental summary folding, byte-exact project key derivation, store-backed listing/reading, resume materialization, import, mutations, and the transcript-mirror batcher. |
|
Package sessionstoretest provides a shared conformance suite for SessionStore adapters.
|
Package sessionstoretest provides a shared conformance suite for SessionStore adapters. |
|
Package toolinput defines the input shapes of Claude Code's built-in tools, for decoding ToolUseBlock.Input, CanUseTool inputs, and hook tool_input payloads into plain structs instead of hand-rolled types.
|
Package toolinput defines the input shapes of Claude Code's built-in tools, for decoding ToolUseBlock.Input, CanUseTool inputs, and hook tool_input payloads into plain structs instead of hand-rolled types. |
|
Package transport owns the subprocess boundary to the claude CLI: locating the binary, building its argv and environment, spawning it under a process group, streaming its NDJSON stdout as raw frames, and reaping it on close or context cancellation.
|
Package transport owns the subprocess boundary to the claude CLI: locating the binary, building its argv and environment, spawning it under a process group, streaming its NDJSON stdout as raw frames, and reaping it on close or context cancellation. |