claude

package module
v0.0.0-...-fa87db7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 12, 2026 License: MIT Imports: 24 Imported by: 0

README

claude-agent-sdk-go

A Go port of Anthropic's Python claude-agent-sdk. It drives the locally installed claude CLI over its bidirectional control protocol and exposes a one-shot Query plus a stateful, interactive Client with a pull-based message stream.

Status: pre-release (v0.2.0). API may still change before v1.

How it works

The SDK does not call the Anthropic API directly. It spawns the user-installed claude CLI as a subprocess and speaks its control protocol over stdio. This means:

  • You need the claude CLI installed (>= 2.0.0) and authenticated.
  • Auth and model availability come from the CLI — subscription login works; no ANTHROPIC_API_KEY is required or injected.
  • Sessions are read from and written to the same on-disk store the CLI uses (~/.claude/projects/...).

Requirements

  • Go (module floor declared in go.mod)
  • The claude CLI on PATH, version >= 2.0.0, authenticated.

Install

go get github.com/chai-rs/go-claude
import claude "github.com/chai-rs/go-claude"

Quick start — one-shot Query

The shortest path is QueryText: one prompt in, final text out.

answer, err := claude.QueryText(ctx, "What is the capital of France?")

For streaming, Query is fire-and-forget: it connects a fresh session, sends one prompt, and streams the result. Drain the stream to completion, then Close it to reap the subprocess.

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)
		}

		if am, ok := msg.(*claude.AssistantMessage); ok {
			fmt.Println(am.Text())
		}
	}
}

AssistantMessage.Text() concatenates the text blocks; type-switch on msg / am.Content when you need tool calls, thinking, or stream events.

Query cannot use a CanUseTool permission callback (that needs streaming mode) — use Client for tool gating.

Interactive Client

For multi-turn, stateful conversations and live control operations (interrupt, model swap, MCP management), use Client. Lifecycle is NewClient → Connect → Query/Send → Close.

c, err := claude.NewClient(claude.WithModel("claude-sonnet-4-5"))
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() {
	// ...
}

The context passed to Connect governs connection establishment only — cancelling it later does not kill the session. The subprocess lives until Close.

Errors

Every SDK error matches errors.Is(err, claude.ErrClaudeSDK) and has a concrete type for errors.As: CLINotFoundError, CLIConnectionError, ProcessError (CLI exited non-zero; carries ExitCode and captured stderr), CLIJSONDecodeError, MessageParseError, ControlProtocolError, ConfigError, ValidationError, SessionError, TurnError, VersionMismatchError.

Two distinct failure surfaces to handle:

  • Stream errors — if the session dies mid-turn, Recv/Seq yield the fatal error (e.g. *ProcessError) after the buffered messages; a clean end is plain io.EOF (Seq just stops).
  • Turn errors — a turn can complete and still fail (budget exceeded, max turns). The blessed pattern is res, err := stream.Final(): on failure err is a *TurnError and res is still the full ResultMessage (cost/usage readable). On the raw Recv path, check res.Err().

Resuming a session

The session ID arrives on every message of a turn — most conveniently on the terminal ResultMessage.SessionID. Store it, then pass it to WithResume later (ListSessions can also recover IDs from disk):

stream, err := claude.Query(ctx, "Continue where we left off.",
	claude.WithResume(sessionID))

WithForkSession(true) branches the resumed conversation instead of appending to it.

Configuration

Options are functional (With*) and passed to both Query and NewClient:

claude.Query(ctx, prompt,
	claude.WithSystemPrompt(&claude.SystemPromptString{Text: "You are concise."}),
	claude.WithAllowedTools("Read", "Write"),
	claude.WithMaxTurns(1),
	claude.WithMaxBudgetUSD(0.50),
)

Covered areas: model, system prompt, max turns, working/added directories, env, agents, plugins, thinking, sandbox, partial-message streaming, USD budget cap, tool gating, hooks, in-process MCP servers, session persistence, and resume/continue/fork. See the examples/ directory and docs/capabilities-report.md for the full surface.

What you can build

Area Capability Key API Example
One-shot Fire a prompt, stream to result Query quick_start
Interactive Multi-turn stateful session NewClient → Connect → Query/Send → Close streaming_mode
Streaming Incremental / partial output WithIncludePartialMessages, StreamEvent include_partial_messages
Budget Hard USD cap per run WithMaxBudgetUSD max_budget_usd
Tool gating Allow/deny each tool call live WithCanUseTool (Client only) tool_permission_callback
Hooks PreToolUse/PostToolUse/Stop/… matchers; block or rewrite WithHooks hooks
In-proc MCP Expose Go funcs as Claude tools NewToolFor[T] (schema derived from your struct) or raw NewTool + CreateSdkMcpServer (tools are named mcp__<server>__<tool> — use that full name in WithAllowedTools / permission rules) mcp_calculator
Turn control Interrupt, stop task, swap model/mode, rewind files Interrupt, StopTask, SetModel, SetPermissionMode, RewindFiles —
Continuity Resume / continue / fork WithResume / WithContinueConversation / WithForkSession —
History Browse recorded sessions ListSessions / GetSessionInfo / GetSessionMessages list_sessions
Persistence Custom session storage + transcript mirroring WithSessionStore —
Structured output Typed answers, schema derived from a Go struct QueryStructured[T] —
Typed tool calls Decode built-in tool inputs without hand-written structs toolinput package + ToolUseBlock.DecodeInput —
Lifecycle Connect/Close guaranteed by scope WithClient(ctx, fn, opts...) —
Cancellation Abandon a wait without killing the turn RecvContext / SeqContext / FinalContext —
Turn outcome Failed turns as typed errors; drain-to-result stream.Final(), res.Err(), *TurnError —
Diagnostics CLI stderr stream; tool-call pairing stats WithStderr callback, stream.Stats() stderr_callback

Examples

Runnable programs live under examples/. Run one with:

go run ./examples/quick_start
Example Shows
quick_start Basic query, custom options, tool use
streaming_mode Interactive multi-turn Client
include_partial_messages Incremental streaming output
system_prompt System-prompt configuration
agents Custom agent definitions
setting_sources Setting-source layering
plugin_example Plugins
max_budget_usd Hard USD budget cap
tool_permission_callback Live tool gating via CanUseTool
hooks Hook matchers (block / rewrite)
mcp_calculator In-process MCP tool server
list_sessions Browsing recorded session history
stderr_callback CLI stderr diagnostics

Limitations

  • CLI-bound — requires a user-installed, authenticated claude CLI; models are whatever the CLI exposes.
  • Query cannot gate tools — CanUseTool requires streaming mode; use Client + Send.
  • No active-session discovery — there is no system-wide "who is running now"; track the Client handles your app spawns.
  • History listing is a per-directory disk snapshot — you must know the project directory; only the main chain is returned (sidechains/metadata dropped).
  • A few live-state returns are untyped — GetServerInfo / GetContextUsage hand back json.RawMessage to parse (turn usage/cost ARE typed via ResultMessage.Usage/ModelUsage).

See docs/capabilities-report.md for the full capabilities-and-limitations matrix with source citations.

Testing your code

The claudetest package provides a scriptable in-memory transport so code built on the SDK can be tested without the real CLI. Inject it with WithTransport, script the session, assert on what was written:

tr := claudetest.NewFakeTransport()

c, _ := claude.NewClient(claude.WithTransport(tr))
_ = c.Connect(ctx)

stream, _ := c.Query(ctx, "2+2?")
tr.EmitAssistantText("s1", "4")
tr.EmitResult("s1")

for msg, err := range stream.Seq() { /* assert */ }

The fake auto-answers control requests (initialize, interrupt, …) so the handshake just works; FailWith scripts a mid-turn process death, and Writes() exposes every frame the SDK sent. WithTransport also accepts any custom claude.Transport implementation (e.g. a remote process bridge).

Development

make test    # run tests
make lint    # run golangci-lint

License

MIT — see LICENSE.

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

Examples

Constants

View Source
const (
	SourceUser    = config.SourceUser
	SourceProject = config.SourceProject
	SourceLocal   = config.SourceLocal
)

Setting source literals.

View Source
const (
	EffortLow       = config.EffortLow
	EffortMedium    = config.EffortMedium
	EffortHigh      = config.EffortHigh
	EffortXHigh     = config.EffortXHigh
	EffortMax       = config.EffortMax
	EffortUltracode = config.EffortUltracode
)

Effort level literals.

View Source
const (
	ThinkingDisplaySummarized = config.ThinkingDisplaySummarized
	ThinkingDisplayOmitted    = config.ThinkingDisplayOmitted
)

Thinking display literals.

View Source
const (
	AgentMemoryUser    = config.AgentMemoryUser
	AgentMemoryProject = config.AgentMemoryProject
	AgentMemoryLocal   = config.AgentMemoryLocal
)

Agent memory scope literals.

View Source
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.

View Source
const (
	ModeDefault           = permission.ModeDefault
	ModeAcceptEdits       = permission.ModeAcceptEdits
	ModePlan              = permission.ModePlan
	ModeBypassPermissions = permission.ModeBypassPermissions
	ModeDontAsk           = permission.ModeDontAsk
	ModeAuto              = permission.ModeAuto
)

Permission mode literals.

View Source
const (
	BehaviorAllow = permission.BehaviorAllow
	BehaviorDeny  = permission.BehaviorDeny
	BehaviorAsk   = permission.BehaviorAsk
)

Permission behavior literals.

View Source
const (
	UpdateAddRules          = permission.UpdateAddRules
	UpdateReplaceRules      = permission.UpdateReplaceRules
	UpdateRemoveRules       = permission.UpdateRemoveRules
	UpdateSetMode           = permission.UpdateSetMode
	UpdateAddDirectories    = permission.UpdateAddDirectories
	UpdateRemoveDirectories = permission.UpdateRemoveDirectories
)

Permission update type literals.

View Source
const (
	DestUserSettings    = permission.DestUserSettings
	DestProjectSettings = permission.DestProjectSettings
	DestLocalSettings   = permission.DestLocalSettings
	DestSession         = permission.DestSession
)

Permission update destination literals.

View Source
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.

View Source
const (
	StatusConnected = mcpserver.StatusConnected
	StatusFailed    = mcpserver.StatusFailed
	StatusNeedsAuth = mcpserver.StatusNeedsAuth
	StatusPending   = mcpserver.StatusPending
	StatusDisabled  = mcpserver.StatusDisabled
)

MCP server connection status literals.

View Source
const (
	FlushBatched = session.FlushBatched
	FlushEager   = session.FlushEager
)

Session-store flush mode literals.

View Source
const BetaContext1M = config.BetaContext1M

BetaContext1M enables the 1M-token context window (Sonnet 4/4.5 only).

View Source
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

View Source
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).

View Source
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

func ProjectKeyForDirectory(dir string) string

ProjectKeyForDirectory derives the SessionStore project_key for a directory, matching the CLI's project directory naming.

func QueryText

func QueryText(ctx context.Context, prompt string, opts ...Option) (string, error)

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)
}

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

func TextContent(text string) map[string]any

TextContent builds the MCP text content item {"type":"text","text":…} that tool handlers return inside ToolResult.Content.

func WithClient

func WithClient(ctx context.Context, fn func(*Client) error, opts ...Option) (err error)

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)
		}
	}
}

func NewClient

func NewClient(opts ...Option) (*Client, error)

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

func NewClientWithOptions(o *Options) (*Client, error)

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

func (c *Client) Close() error

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

func (c *Client) Connect(ctx context.Context) error

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

func (c *Client) GetContextUsage(ctx context.Context) (json.RawMessage, error)

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) Interrupt

func (c *Client) Interrupt(ctx context.Context) error

Interrupt sends an interrupt control request, aborting the current turn.

func (*Client) Query

func (c *Client) Query(ctx context.Context, prompt string) (*MessageStream, error)

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

func (c *Client) ReconnectMCPServer(ctx context.Context, serverName string) error

ReconnectMCPServer reconnects a disconnected or failed MCP server by name.

func (*Client) RewindFiles

func (c *Client) RewindFiles(ctx context.Context, userMessageID string) error

RewindFiles rewinds tracked files to their state at userMessageID. Requires file checkpointing.

func (*Client) Send

func (c *Client) Send(ctx context.Context, msg json.RawMessage) error

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

func (c *Client) SetModel(ctx context.Context, model *string) error

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.

func (*Client) StopTask

func (c *Client) StopTask(ctx context.Context, taskID string) error

StopTask stops a running task by its task_notification ID.

func (*Client) ToggleMCPServer

func (c *Client) ToggleMCPServer(ctx context.Context, serverName string, enabled bool) error

ToggleMCPServer enables or disables an MCP server by name.

type ConfigError

type ConfigError = config.Error

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

type HookCallback = hook.Callback

HookCallback runs for a matched hook event and returns the directive the CLI should apply.

type HookContext

type HookContext = hook.Context

HookContext carries hook invocation metadata.

type HookEvent

type HookEvent = hook.Event

HookEvent is a lifecycle event name.

type HookInput

type HookInput = hook.Input

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

type HookMatcher = hook.Matcher

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

type McpToolInfo = mcpserver.ToolInfo

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

func Query(ctx context.Context, prompt string, opts ...Option) (*MessageStream, error)

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())
		}
	}
}
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())
		}
	}
}

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

func (s *MessageStream) SeqContext(ctx context.Context) iter.Seq2[Message, error]

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

type Option = config.Option

Option mutates an Options during NewOptions.

func WithAddDirs

func WithAddDirs(dirs ...string) Option

WithAddDirs sets additional accessible directories.

func WithAgents

func WithAgents(agents map[string]AgentDefinition) Option

WithAgents sets the programmatic agent definitions.

func WithAllowedTools

func WithAllowedTools(tools ...string) Option

WithAllowedTools sets the auto-allowed tool names.

func WithBetas

func WithBetas(betas ...SdkBeta) Option

WithBetas sets the beta feature headers.

func WithCLIPath

func WithCLIPath(path string) Option

WithCLIPath overrides the CLI executable path.

func WithCWD

func WithCWD(dir string) Option

WithCWD sets the working directory.

func WithCanUseTool

func WithCanUseTool(cb CanUseTool) Option

WithCanUseTool sets the custom permission callback.

func WithContinueConversation

func WithContinueConversation(v bool) Option

WithContinueConversation toggles continuing the most recent conversation.

func WithDisallowedTools

func WithDisallowedTools(tools ...string) Option

WithDisallowedTools sets the disallowed tool names.

func WithEffort

func WithEffort(e EffortLevel) Option

WithEffort sets the response effort level.

func WithEnableFileCheckpointing

func WithEnableFileCheckpointing(v bool) Option

WithEnableFileCheckpointing toggles file checkpointing.

func WithEnv

func WithEnv(env map[string]string) Option

WithEnv sets extra environment variables.

func WithExtraArgs

func WithExtraArgs(args map[string]*string) Option

WithExtraArgs sets raw extra CLI flags.

func WithFallbackModel

func WithFallbackModel(model string) Option

WithFallbackModel sets the fallback model.

func WithForkSession

func WithForkSession(v bool) Option

WithForkSession toggles forking a resumed session.

func WithHooks

func WithHooks(hooks map[HookEvent][]HookMatcher) Option

WithHooks sets the lifecycle hooks.

func WithIncludeHookEvents

func WithIncludeHookEvents(v bool) Option

WithIncludeHookEvents toggles --include-hook-events.

func WithIncludePartialMessages

func WithIncludePartialMessages(v bool) Option

WithIncludePartialMessages toggles --include-partial-messages.

func WithMCPServers

func WithMCPServers(servers map[string]McpServerConfig) Option

WithMCPServers sets the MCP server configurations.

func WithMaxBudgetUSD

func WithMaxBudgetUSD(usd float64) Option

WithMaxBudgetUSD caps spend in USD.

func WithMaxBufferSize

func WithMaxBufferSize(n int) Option

WithMaxBufferSize caps stdout buffering.

func WithMaxThinkingTokens

func WithMaxThinkingTokens(n int) Option

WithMaxThinkingTokens sets the deprecated thinking budget.

func WithMaxTurns

func WithMaxTurns(n int) Option

WithMaxTurns caps conversation turns.

func WithModel

func WithModel(model string) Option

WithModel sets the Claude model.

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

func WithPermissionPromptToolName(name string) Option

WithPermissionPromptToolName routes permission prompts through an MCP tool.

func WithPlugins

func WithPlugins(plugins ...SdkPluginConfig) Option

WithPlugins sets the local plugins.

func WithResume

func WithResume(sessionID string) Option

WithResume sets the session ID to resume.

func WithSandbox

func WithSandbox(s *SandboxSettings) Option

WithSandbox sets the sandbox configuration.

func WithSessionID

func WithSessionID(id string) Option

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

func WithSettings(settings string) Option

WithSettings sets the settings JSON string or file path.

func WithSkills

func WithSkills(s Skills) Option

WithSkills sets the tri-state skills selector.

func WithStderr

func WithStderr(cb func(string)) Option

WithStderr sets the stderr line callback.

func WithStrictMCPConfig

func WithStrictMCPConfig(v bool) Option

WithStrictMCPConfig toggles --strict-mcp-config.

func WithStrictVersionCheck

func WithStrictVersionCheck(v bool) Option

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

func WithSystemPromptText(text string) Option

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

func WithTransport(tr Transport) Option

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.

func WithUser

func WithUser(user string) Option

WithUser sets the subprocess user identifier.

type Options

type Options = config.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

func NewOptions(opts ...Option) (*Options, error)

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/<project_key>/*.jsonl (honoring CLAUDE_CONFIG_DIR). A missing project directory yields an empty slice, not an error. Use limit/offset to page; pass limit nil for all.

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 SdkBeta

type SdkBeta = config.SdkBeta

SdkBeta names a beta feature header.

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__<server>__<tool> — here mcp__calc__add — and that full name is what tool-permission rules and AllowedTools match against.

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)
	}
}

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

type SessionError = session.Error

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

type SessionKey = session.Key

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

type SessionMessage = session.Message

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

type SessionStore = session.Store

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

type Skills = config.Skills

Skills is the tri-state skills selector for the main session.

func SkillsAll

func SkillsAll() Skills

SkillsAll enables every discovered skill.

func SkillsNamed

func SkillsNamed(names ...string) Skills

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 TextBlock

type TextBlock = conversation.TextBlock

TextBlock is a plain text content block.

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

type Transport = transport.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 UserMessage

type UserMessage = conversation.UserMessage

UserMessage is a user turn.

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.

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/<project_key>/*.jsonl.
Command list_sessions prints the local Claude Code session history for a directory (default: the current working directory), reading ~/.claude/projects/<project_key>/*.jsonl.
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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL