claudesdk

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2026 License: GPL-3.0 Imports: 33 Imported by: 0

README

Claude Agent SDK Go

Go SDK for building agentic applications with Claude Code.

Installation

go get github.com/ethpandaops/claude-agent-sdk-go

Prerequisites:

  • Go 1.26+
  • Claude Code CLI v2.1.59+ (npm install -g @anthropic-ai/claude-code)

Quick Start

package main

import (
    "context"
    "fmt"

    claudesdk "github.com/ethpandaops/claude-agent-sdk-go"
)

func main() {
    ctx := context.Background()
    for msg, err := range claudesdk.Query(ctx, claudesdk.Text("What is 2 + 2?")) {
        if err != nil {
            panic(err)
        }
        if result, ok := msg.(*claudesdk.ResultMessage); ok {
            fmt.Println(result.Result)
        }
    }
}

Basic Usage: Query()

One-shot query execution returning an iterator of messages. Query() accepts UserMessageContent. Use Text(...) for plain prompts and Blocks(...) for structured multimodal input. Text-only queries use Claude CLI --print mode. Structured content uses streaming mode.

for msg, err := range claudesdk.Query(ctx, claudesdk.Text("Explain Go interfaces")) {
    // handle msg
}

Model Discovery

ListModels(ctx) returns the SDK's static Claude model catalog in a Codex-like payload shape. It is not a live per-user model list from the Claude CLI.

models, err := claudesdk.ListModels(ctx)
if err != nil {
    panic(err)
}
for _, model := range models {
    fmt.Println(model.ID, model.Metadata["modelContextWindow"])
}
With Options
for msg, err := range claudesdk.Query(ctx, claudesdk.Text("Hello"),
    claudesdk.WithSystemPrompt("You are a helpful assistant"),
    claudesdk.WithModel("claude-sonnet-4-6"),
    claudesdk.WithMaxTurns(3),
) {
    // handle msg
}
With Tools
for msg, err := range claudesdk.Query(ctx, claudesdk.Text("Create hello.py that prints hello world"),
    claudesdk.WithAllowedTools("Read", "Write"),
    claudesdk.WithPermissionMode("acceptEdits"),
) {
    // handle msg
}

Client (Multi-turn)

WithClient manages the client lifecycle for multi-turn conversations.

err := claudesdk.WithClient(ctx, func(c claudesdk.Client) error {
    if err := c.Query(ctx, claudesdk.Text("Hello, remember my name is Alice")); err != nil {
        return err
    }
    for msg, err := range c.ReceiveResponse(ctx) {
        if err != nil {
            return err
        }
        // handle response
    }

    if err := c.Query(ctx, claudesdk.Text("What's my name?")); err != nil {
        return err
    }
    for msg, err := range c.ReceiveResponse(ctx) {
        // Claude remembers: "Alice"
    }
    return nil
})

SDK MCP Servers (Custom Tools)

Create in-process tools using the Model Context Protocol.

schema := claudesdk.SimpleSchema(map[string]string{"a": "number", "b": "number"})

handler := func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
    args, _ := claudesdk.ParseArguments(req)
    sum := args["a"].(float64) + args["b"].(float64)
    return claudesdk.TextResult(fmt.Sprintf("%.0f", sum)), nil
}

tool := claudesdk.NewSdkMcpTool("add", "Add two numbers", schema, handler)
server := claudesdk.CreateSdkMcpServer("calc", "1.0.0", tool)

for msg, err := range claudesdk.Query(ctx, claudesdk.Text("Calculate 2 + 2"),
    claudesdk.WithMCPServers(map[string]claudesdk.MCPServerConfig{"calc": server}),
    claudesdk.WithAllowedTools("mcp__calc__add"),
) {
    // handle msg
}

Multimodal Input

The SDK now supports structured Claude CLI user content:

content := claudesdk.Blocks(
    claudesdk.TextInput("Describe these attachments briefly."),
    claudesdk.PathInput("/absolute/path/to/local-image.png"),
)

for msg, err := range claudesdk.Query(ctx, content) {
    // handle msg
}

Inline helpers are also available for fully programmatic payloads:

img, _ := claudesdk.ImageFileInput("/absolute/path/to/local-image.png")
pdf, _ := claudesdk.PDFFileInput("/absolute/path/to/spec.pdf")

content := claudesdk.Blocks(
    claudesdk.TextInput("Summarize the PDF and image."),
    img,
    pdf,
)

for msg, err := range claudesdk.Query(ctx, content) {
    // handle msg
}

Supported CLI formats validated by this SDK:

  • Text(...) for plain prompts
  • image blocks via ImageInput(...) / ImageFileInput(...)
  • document PDF blocks via PDFInput(...) / PDFFileInput(...)
  • @/absolute/path mentions via PathInput(...)

See examples/multimodal_input for a complete example that runs both path-based attachments and inline image/PDF blocks.

Hooks

Intercept and modify tool execution.

handler := func(ctx context.Context, hookCtx claudesdk.HookContext, input claudesdk.HookInput) (claudesdk.HookJSONOutput, error) {
    pre := input.(*claudesdk.PreToolUseHookInput)
    fmt.Printf("Tool: %s\n", pre.ToolName)
    return &claudesdk.SyncHookJSONOutput{}, nil
}

for msg, err := range claudesdk.Query(ctx, claudesdk.Text(prompt),
    claudesdk.WithHooks(map[claudesdk.HookEvent][]*claudesdk.HookMatcher{
        claudesdk.HookEventPreToolUse: {{
            ToolName: "Bash",
            Hooks:    []claudesdk.HookCallback{handler},
        }},
    }),
) {
    // handle msg
}

Plan Mode User Input

Handle AskUserQuestion prompts with a typed callback:

onUserInput := func(
    _ context.Context,
    req *claudesdk.UserInputRequest,
) (*claudesdk.UserInputResponse, error) {
    answers := map[string]*claudesdk.UserInputAnswer{}
    for _, q := range req.Questions {
        if len(q.Options) > 0 {
            answers[q.Question] = &claudesdk.UserInputAnswer{
                Answers: []string{q.Options[0].Label},
            }
        }
    }
    return &claudesdk.UserInputResponse{Answers: answers}, nil
}

for msg, err := range claudesdk.Query(ctx,
    claudesdk.Text("Use AskUserQuestion to ask me to pick Go or Rust, then confirm my choice."),
    claudesdk.WithPermissionMode("plan"),
    claudesdk.WithOnUserInput(onUserInput),
) {
    _ = msg
    _ = err
}

Types

Core message types implement the Message interface:

  • UserMessage - User input
  • AssistantMessage - Claude response with Content []ContentBlock
  • ResultMessage - Final result with Result string
  • SystemMessage - System messages

Content blocks: TextBlock, InputImageBlock, InputDocumentBlock, ThinkingBlock, ToolUseBlock, ToolResultBlock

See types.go for complete type definitions.

Static Model Catalog

Models(), ModelByID(), and ListModels(ctx) use a static SDK catalog, not a live Claude CLI model list for the logged-in user.

The catalog includes the current concrete model IDs exposed by this SDK.

Error Handling

SDK errors can be inspected using errors.AsType (Go 1.26+):

if cliErr, ok := errors.AsType[*claudesdk.CLINotFoundError](err); ok {
    fmt.Println("Claude CLI not found:", cliErr)
}

if procErr, ok := errors.AsType[*claudesdk.ProcessError](err); ok {
    fmt.Println("Process failed:", procErr)
}

Error types:

  • CLINotFoundError - Claude CLI binary not found
  • CLIConnectionError - Failed to connect to CLI
  • ProcessError - CLI process failure
  • MessageParseError - Message parsing failure
  • CLIJSONDecodeError - JSON decode failure

Sentinel errors: ErrClientNotConnected, ErrClientAlreadyConnected, ErrClientClosed, ErrSessionNotFound

Session Metadata

Inspect locally persisted session metadata without sending a prompt:

stat, err := claudesdk.StatSession(ctx, sessionID,
    claudesdk.WithStatProjectPath("/path/to/project"), // optional
    claudesdk.WithStatClaudeHome("/custom/.claude"),   // optional
)
if err != nil {
    if errors.Is(err, claudesdk.ErrSessionNotFound) {
        // session does not exist in local persistence
    }
    // handle other errors
}
fmt.Println(stat.SizeBytes, stat.LastModified)

Examples

See the examples directory for complete working examples.

Testing Examples

The scripts/test_examples.sh script runs all examples and uses Claude CLI to verify their output.

# Run all examples
./scripts/test_examples.sh

# Run specific examples
./scripts/test_examples.sh -f hooks,sessions,tools_option

# Keep going on failure
./scripts/test_examples.sh -k

# Adjust parallelism and timeout
./scripts/test_examples.sh -n 3 -t 180

Documentation

Overview

Package claudesdk provides a Go SDK for interacting with the Claude CLI agent.

This SDK enables Go applications to programmatically communicate with Claude through the official Claude CLI tool. It supports both one-shot queries and interactive multi-turn conversations.

Basic Usage

For simple, one-shot queries, use the Query function:

ctx := context.Background()
for msg, err := range claudesdk.Query(ctx, claudesdk.Text("What is 2+2?"),
    claudesdk.WithPermissionMode("acceptEdits"),
    claudesdk.WithMaxTurns(1),
) {
    if err != nil {
        log.Fatal(err)
    }
    switch m := msg.(type) {
    case *claudesdk.AssistantMessage:
        for _, block := range m.Content {
            if text, ok := block.(*claudesdk.TextBlock); ok {
                fmt.Println(text.Text)
            }
        }
    case *claudesdk.ResultMessage:
        fmt.Printf("Completed in %dms\n", m.DurationMs)
    }
}

Interactive Sessions

For multi-turn conversations, use NewClient or the WithClient helper:

// Using WithClient for automatic lifecycle management
err := claudesdk.WithClient(ctx, func(c claudesdk.Client) error {
    if err := c.Query(ctx, claudesdk.Text("Hello Claude")); err != nil {
        return err
    }
    for msg, err := range c.ReceiveResponse(ctx) {
        if err != nil {
            return err
        }
        // process message...
    }
    return nil
},
    claudesdk.WithLogger(slog.Default()),
    claudesdk.WithPermissionMode("acceptEdits"),
)

// Or using NewClient directly for more control
client := claudesdk.NewClient()
defer client.Close()

err := client.Start(ctx,
    claudesdk.WithLogger(slog.Default()),
    claudesdk.WithPermissionMode("acceptEdits"),
)

Plan Mode User Input

AskUserQuestion prompts can be handled with WithOnUserInput:

onUserInput := func(
    _ context.Context,
    req *claudesdk.UserInputRequest,
) (*claudesdk.UserInputResponse, error) {
    answers := make(map[string]*claudesdk.UserInputAnswer, len(req.Questions))
    for _, q := range req.Questions {
        if len(q.Options) > 0 {
            answers[q.Question] = &claudesdk.UserInputAnswer{
                Answers: []string{q.Options[0].Label},
            }
        }
    }
    return &claudesdk.UserInputResponse{Answers: answers}, nil
}

for msg, err := range claudesdk.Query(ctx,
    claudesdk.Text("Use AskUserQuestion to ask me to choose Go or Rust."),
    claudesdk.WithPermissionMode("plan"),
    claudesdk.WithOnUserInput(onUserInput),
) {
    _ = msg
    _ = err
}

Logging

For detailed operation tracking, use WithLogger:

logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))
for msg, err := range claudesdk.Query(ctx, claudesdk.Text("Hello Claude"),
    claudesdk.WithLogger(logger),
) {
    _ = msg
    _ = err
}

Error Handling

The SDK provides typed errors for different failure scenarios:

for _, err := range claudesdk.Query(ctx, claudesdk.Text(prompt), claudesdk.WithPermissionMode("acceptEdits")) {
    if err != nil {
        if cliErr, ok := errors.AsType[*claudesdk.CLINotFoundError](err); ok {
            log.Fatalf("Claude CLI not installed, searched: %v", cliErr.SearchedPaths)
        }
        if procErr, ok := errors.AsType[*claudesdk.ProcessError](err); ok {
            log.Fatalf("CLI process failed with exit code %d: %s", procErr.ExitCode, procErr.Stderr)
        }
        log.Fatal(err)
    }
}

Requirements

This SDK requires the Claude CLI to be installed and available in your system PATH. You can specify a custom CLI path using the WithCliPath option.

Index

Constants

View Source
const (
	// ModelCapVision indicates the model supports image/vision inputs.
	ModelCapVision = models.CapVision
	// ModelCapToolUse indicates the model supports tool/function calling.
	ModelCapToolUse = models.CapToolUse
	// ModelCapReasoning indicates the model supports extended reasoning.
	ModelCapReasoning = models.CapReasoning
	// ModelCapStructuredOutput indicates the model supports structured JSON output.
	ModelCapStructuredOutput = models.CapStructuredOutput
)

Model capability constants.

View Source
const (
	// ModelCostTierHigh represents opus-class pricing.
	ModelCostTierHigh = models.CostTierHigh
	// ModelCostTierMedium represents sonnet-class pricing.
	ModelCostTierMedium = models.CostTierMedium
	// ModelCostTierLow represents haiku-class pricing.
	ModelCostTierLow = models.CostTierLow
)

Model cost tier constants.

View Source
const (
	// SettingSourceUser loads from user-level settings.
	SettingSourceUser = config.SettingSourceUser
	// SettingSourceProject loads from project-level settings.
	SettingSourceProject = config.SettingSourceProject
	// SettingSourceLocal loads from local-level settings.
	SettingSourceLocal = config.SettingSourceLocal
)
View Source
const (
	// EffortLow uses minimal thinking.
	EffortLow = config.EffortLow
	// EffortMedium uses moderate thinking.
	EffortMedium = config.EffortMedium
	// EffortHigh uses deep thinking.
	EffortHigh = config.EffortHigh
)
View Source
const (
	// AssistantMessageErrorAuthFailed indicates authentication failure.
	AssistantMessageErrorAuthFailed = message.AssistantMessageErrorAuthFailed
	// AssistantMessageErrorBilling indicates a billing error.
	AssistantMessageErrorBilling = message.AssistantMessageErrorBilling
	// AssistantMessageErrorRateLimit indicates rate limiting.
	AssistantMessageErrorRateLimit = message.AssistantMessageErrorRateLimit
	// AssistantMessageErrorInvalidReq indicates an invalid request.
	AssistantMessageErrorInvalidReq = message.AssistantMessageErrorInvalidReq
	// AssistantMessageErrorServer indicates a server error.
	AssistantMessageErrorServer = message.AssistantMessageErrorServer
	// AssistantMessageErrorUnknown indicates an unknown error.
	AssistantMessageErrorUnknown = message.AssistantMessageErrorUnknown
)
View Source
const (
	// TaskNotificationStatusCompleted indicates the task finished successfully.
	TaskNotificationStatusCompleted = message.TaskNotificationStatusCompleted
	// TaskNotificationStatusFailed indicates the task failed.
	TaskNotificationStatusFailed = message.TaskNotificationStatusFailed
	// TaskNotificationStatusStopped indicates the task was stopped.
	TaskNotificationStatusStopped = message.TaskNotificationStatusStopped
)
View Source
const (
	// BlockTypeText contains plain text content.
	BlockTypeText = message.BlockTypeText
	// BlockTypeImage contains inline image input content.
	BlockTypeImage = message.BlockTypeImage
	// BlockTypeDocument contains inline PDF document input content.
	BlockTypeDocument = message.BlockTypeDocument
)
View Source
const (
	// HookEventPreToolUse is triggered before a tool is used.
	HookEventPreToolUse = hook.EventPreToolUse
	// HookEventPostToolUse is triggered after a tool is used.
	HookEventPostToolUse = hook.EventPostToolUse
	// HookEventUserPromptSubmit is triggered when a user submits a prompt.
	HookEventUserPromptSubmit = hook.EventUserPromptSubmit
	// HookEventStop is triggered when a session stops.
	HookEventStop = hook.EventStop
	// HookEventSubagentStop is triggered when a subagent stops.
	HookEventSubagentStop = hook.EventSubagentStop
	// HookEventPreCompact is triggered before compaction.
	HookEventPreCompact = hook.EventPreCompact
	// HookEventPostToolUseFailure is triggered after a tool use fails.
	HookEventPostToolUseFailure = hook.EventPostToolUseFailure
	// HookEventNotification is triggered when a notification is sent.
	HookEventNotification = hook.EventNotification
	// HookEventSubagentStart is triggered when a subagent starts.
	HookEventSubagentStart = hook.EventSubagentStart
	// HookEventPermissionRequest is triggered when a permission is requested.
	HookEventPermissionRequest = hook.EventPermissionRequest
)
View Source
const (
	// PermissionModeDefault uses standard permission prompts.
	PermissionModeDefault = permission.ModeDefault
	// PermissionModeAcceptEdits automatically accepts file edits.
	PermissionModeAcceptEdits = permission.ModeAcceptEdits
	// PermissionModePlan enables plan mode for implementation planning.
	PermissionModePlan = permission.ModePlan
	// PermissionModeBypassPermissions bypasses all permission checks.
	PermissionModeBypassPermissions = permission.ModeBypassPermissions
)
View Source
const (
	// PermissionUpdateTypeAddRules adds new permission rules.
	PermissionUpdateTypeAddRules = permission.UpdateTypeAddRules
	// PermissionUpdateTypeReplaceRules replaces existing permission rules.
	PermissionUpdateTypeReplaceRules = permission.UpdateTypeReplaceRules
	// PermissionUpdateTypeRemoveRules removes permission rules.
	PermissionUpdateTypeRemoveRules = permission.UpdateTypeRemoveRules
	// PermissionUpdateTypeSetMode sets the permission mode.
	PermissionUpdateTypeSetMode = permission.UpdateTypeSetMode
	// PermissionUpdateTypeAddDirectories adds accessible directories.
	PermissionUpdateTypeAddDirectories = permission.UpdateTypeAddDirectories
	// PermissionUpdateTypeRemoveDirectories removes accessible directories.
	PermissionUpdateTypeRemoveDirectories = permission.UpdateTypeRemoveDirectories
)
View Source
const (
	// PermissionUpdateDestUserSettings stores in user-level settings.
	PermissionUpdateDestUserSettings = permission.UpdateDestUserSettings
	// PermissionUpdateDestProjectSettings stores in project-level settings.
	PermissionUpdateDestProjectSettings = permission.UpdateDestProjectSettings
	// PermissionUpdateDestLocalSettings stores in local-level settings.
	PermissionUpdateDestLocalSettings = permission.UpdateDestLocalSettings
	// PermissionUpdateDestSession stores in the current session only.
	PermissionUpdateDestSession = permission.UpdateDestSession
)
View Source
const (
	// PermissionBehaviorAllow automatically allows the operation.
	PermissionBehaviorAllow = permission.BehaviorAllow
	// PermissionBehaviorDeny automatically denies the operation.
	PermissionBehaviorDeny = permission.BehaviorDeny
	// PermissionBehaviorAsk prompts the user for permission.
	PermissionBehaviorAsk = permission.BehaviorAsk
)
View Source
const (
	// MCPServerTypeStdio uses stdio for communication.
	MCPServerTypeStdio = mcp.ServerTypeStdio
	// MCPServerTypeSSE uses Server-Sent Events.
	MCPServerTypeSSE = mcp.ServerTypeSSE
	// MCPServerTypeHTTP uses HTTP for communication.
	MCPServerTypeHTTP = mcp.ServerTypeHTTP
	// MCPServerTypeSDK uses the SDK interface.
	MCPServerTypeSDK = mcp.ServerTypeSDK
)
View Source
const (
	// MCPServerConnectionStatusConnected indicates the server is connected.
	MCPServerConnectionStatusConnected = mcp.ServerConnectionStatusConnected
	// MCPServerConnectionStatusFailed indicates the server failed to connect.
	MCPServerConnectionStatusFailed = mcp.ServerConnectionStatusFailed
	// MCPServerConnectionStatusNeedsAuth indicates the server requires authentication.
	MCPServerConnectionStatusNeedsAuth = mcp.ServerConnectionStatusNeedsAuth
	// MCPServerConnectionStatusPending indicates the server is still connecting.
	MCPServerConnectionStatusPending = mcp.ServerConnectionStatusPending
	// MCPServerConnectionStatusDisabled indicates the server is disabled.
	MCPServerConnectionStatusDisabled = mcp.ServerConnectionStatusDisabled
)
View Source
const MinimumCLIVersion = "2.1.59"

MinimumCLIVersion is the minimum required Claude CLI version.

View Source
const (
	// SdkBetaContext1M enables 1 million token context window.
	SdkBetaContext1M = config.BetaContext1M
)
View Source
const Version = "0.1.0"

Version is the SDK version.

Variables

View Source
var (
	// ErrClientNotConnected indicates the client is not connected.
	ErrClientNotConnected = errors.ErrClientNotConnected

	// ErrClientAlreadyConnected indicates the client is already connected.
	ErrClientAlreadyConnected = errors.ErrClientAlreadyConnected

	// ErrClientClosed indicates the client has been closed and cannot be reused.
	ErrClientClosed = errors.ErrClientClosed

	// ErrTransportNotConnected indicates the transport is not connected.
	ErrTransportNotConnected = errors.ErrTransportNotConnected

	// ErrRequestTimeout indicates a request timed out.
	ErrRequestTimeout = errors.ErrRequestTimeout

	// ErrSessionNotFound indicates no persisted session was found for the given session ID.
	ErrSessionNotFound = errors.ErrSessionNotFound
)

Public sentinel errors.

View Source
var NewUserMessageContent = message.NewUserMessageContent

NewUserMessageContent creates UserMessageContent from a string.

View Source
var NewUserMessageContentBlocks = message.NewUserMessageContentBlocks

NewUserMessageContentBlocks creates UserMessageContent from blocks.

Functions

func ErrorResult

func ErrorResult(message string) *mcp.CallToolResult

ErrorResult creates a CallToolResult indicating an error.

func ImageResult

func ImageResult(data []byte, mimeType string) *mcp.CallToolResult

ImageResult creates a CallToolResult with image content.

func MessagesFromChannel

func MessagesFromChannel(ch <-chan StreamingMessage) iter.Seq[StreamingMessage]

MessagesFromChannel creates a MessageStream from a channel. This is useful for dynamic message generation where messages are produced over time. The iterator completes when the channel is closed.

func MessagesFromContent added in v0.0.5

func MessagesFromContent(content UserMessageContent) iter.Seq[StreamingMessage]

MessagesFromContent creates a single-message stream from user content.

func MessagesFromSlice

func MessagesFromSlice(msgs []StreamingMessage) iter.Seq[StreamingMessage]

MessagesFromSlice creates a MessageStream from a slice of StreamingMessages. This is useful for sending a fixed set of messages in streaming mode.

func ModelCapabilities

func ModelCapabilities(modelID string) []string

ModelCapabilities returns capability strings for the given model ID. Returns nil if the model is not found.

func NewMcpTool

func NewMcpTool(name, description string, inputSchema *jsonschema.Schema) *mcp.Tool

NewMcpTool creates an mcp.Tool with the given parameters. This is useful when you need direct access to the MCP Tool type.

func NopLogger

func NopLogger() *slog.Logger

NopLogger returns a logger that discards all output. Use this when you want silent operation with no logging overhead.

func ParseArguments

func ParseArguments(req *mcp.CallToolRequest) (map[string]any, error)

ParseArguments unmarshals CallToolRequest arguments into a map. This is a convenience function for extracting tool input.

func Query

func Query(
	ctx context.Context,
	content UserMessageContent,
	opts ...Option,
) iter.Seq2[Message, error]

Query executes a one-shot query to Claude and returns an iterator of messages.

By default, logging is disabled. Use WithLogger to enable logging:

logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
for msg, err := range Query(ctx, Text("What is 2+2?"),
    WithLogger(logger),
    WithPermissionMode("acceptEdits"),
) {
    if err != nil {
        log.Fatal(err)
    }
    // handle msg
}

The iterator yields messages as they arrive from Claude, including assistant responses, tool use, and a final result message. Any errors during setup or execution are yielded inline with messages, allowing callers to handle all error conditions.

Query supports hooks, CanUseTool callbacks, OnUserInput callbacks, and SDK MCP servers through the protocol controller. When these options are configured, an initialization request is sent to the CLI before processing messages.

Example usage:

ctx := context.Background()
for msg, err := range Query(ctx, Text("What is 2+2?"),
    WithPermissionMode("acceptEdits"),
    WithMaxTurns(1),
) {
    if err != nil {
        log.Fatal(err)
    }
    switch m := msg.(type) {
    case *AssistantMessage:
        // Handle assistant response
    case *ResultMessage:
        // Handle final result
    }
}

Error Handling:

Errors are yielded inline as the second return value. The iterator distinguishes between recoverable and fatal errors:

  • Parse errors: If a message from Claude cannot be parsed, the error is yielded and iteration continues with the next message. This allows callers to log malformed messages without losing subsequent data.

  • Fatal errors: Transport failures, context cancellation, and controller errors cause iteration to stop after yielding the error.

Callers can always stop iteration early by breaking from the loop, regardless of error type.

func QueryStream

func QueryStream(
	ctx context.Context,
	messages iter.Seq[StreamingMessage],
	opts ...Option,
) iter.Seq2[Message, error]

QueryStream executes a streaming query with multiple input messages.

The messages iterator yields StreamingMessage values that are sent to Claude via stdin in streaming mode. The transport uses --input-format stream-json.

By default, logging is disabled. Use WithLogger to enable logging.

The iterator yields messages as they arrive from Claude, including assistant responses, tool use, and a final result message. Any errors during setup or execution are yielded inline with messages, allowing callers to handle all error conditions.

QueryStream supports hooks, CanUseTool callbacks, OnUserInput callbacks, and SDK MCP servers through the protocol controller. When these options are configured, an initialization request is sent to the CLI before processing messages.

Example usage:

ctx := context.Background()
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))

messages := claudesdk.MessagesFromSlice([]claudesdk.StreamingMessage{
    claudesdk.NewUserMessage(Text("Hello")),
    claudesdk.NewUserMessage(Text("How are you?")),
})

for msg, err := range claudesdk.QueryStream(ctx, messages,
    claudesdk.WithLogger(logger),
    claudesdk.WithPermissionMode("acceptEdits"),
) {
    if err != nil {
        log.Fatal(err)
    }
    // Handle messages
}

Error Handling:

Errors are yielded inline as the second return value. The iterator distinguishes between recoverable and fatal errors:

  • Parse errors: If a message from Claude cannot be parsed, the error is yielded and iteration continues with the next message. This allows callers to log malformed messages without losing subsequent data.

  • Fatal errors: Transport failures, context cancellation, and controller errors cause iteration to stop after yielding the error.

Callers can always stop iteration early by breaking from the loop, regardless of error type.

func SimpleSchema

func SimpleSchema(props map[string]string) *jsonschema.Schema

SimpleSchema creates a jsonschema.Schema from a simple type map.

Input format: {"a": "float64", "b": "string"}

Type mappings:

  • "string" → {"type": "string"}
  • "int", "int64" → {"type": "integer"}
  • "float64", "float" → {"type": "number"}
  • "bool" → {"type": "boolean"}
  • "[]string" → {"type": "array", "items": {"type": "string"}}
  • "any", "object" → {"type": "object"}

func SingleMessage

func SingleMessage(content UserMessageContent) iter.Seq[StreamingMessage]

SingleMessage creates a MessageStream with a single user message. This is a convenience function for simple one-message streaming queries.

func TextResult

func TextResult(text string) *mcp.CallToolResult

TextResult creates a CallToolResult with text content.

func WithClient

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

WithClient manages client lifecycle with automatic cleanup.

This helper creates a client, starts it with the provided options, executes the callback function, and ensures proper cleanup via Close() when done.

The callback receives a fully initialized Client that is ready for use. If the callback returns an error, it is returned to the caller. If Close() fails, a warning is logged but does not override the callback's error.

Example usage:

err := claudesdk.WithClient(ctx, func(c claudesdk.Client) error {
    if err := c.Query(ctx, Text("Hello")); err != nil {
        return err
    }
    for msg, err := range c.ReceiveResponse(ctx) {
        if err != nil {
            return err
        }
        // process message...
    }
    return nil
},
    claudesdk.WithLogger(log),
    claudesdk.WithPermissionMode("acceptEdits"),
)

Types

type AgentDefinition

type AgentDefinition = config.AgentDefinition

AgentDefinition defines a custom agent configuration.

type AssistantMessage

type AssistantMessage = message.AssistantMessage

AssistantMessage represents a message from Claude.

type AssistantMessageError

type AssistantMessageError = message.AssistantMessageError

AssistantMessageError represents error types from the assistant.

type AsyncHookJSONOutput

type AsyncHookJSONOutput = hook.AsyncJSONOutput

AsyncHookJSONOutput represents an async hook output.

type Base64Source added in v0.0.5

type Base64Source = message.Base64Source

Base64Source contains inline base64 content for Claude CLI multimodal inputs.

type BaseHookInput

type BaseHookInput = hook.BaseInput

BaseHookInput contains common fields for all hook inputs.

type CLIConnectionError

type CLIConnectionError = errors.CLIConnectionError

CLIConnectionError indicates failure to connect to the CLI.

type CLIJSONDecodeError

type CLIJSONDecodeError = errors.CLIJSONDecodeError

CLIJSONDecodeError indicates JSON parsing failed for CLI output.

type CLINotFoundError

type CLINotFoundError = errors.CLINotFoundError

CLINotFoundError indicates the Claude CLI binary was not found.

type CallToolRequest

type CallToolRequest = mcp.CallToolRequest

CallToolRequest is the request passed to tool handlers.

type CallToolResult

type CallToolResult = mcp.CallToolResult

CallToolResult is the server's response to a tool call. Use TextResult, ErrorResult, or ImageResult helpers to create results.

type ClaudeAgentOptions

type ClaudeAgentOptions = config.Options

ClaudeAgentOptions configures the behavior of the Claude agent.

type ClaudeSDKError

type ClaudeSDKError = errors.ClaudeSDKError

ClaudeSDKError is the base interface for all SDK errors.

type Client

type Client interface {
	// Start establishes a connection to the Claude CLI.
	// Must be called before any other methods.
	// Returns CLINotFoundError if CLI not found, CLIConnectionError on failure.
	Start(ctx context.Context, opts ...Option) error

	// StartWithContent establishes a connection and immediately sends initial user content.
	// Equivalent to calling Start() followed by Query(ctx, Text(content))).
	// The content is sent to the "default" session.
	// Returns CLINotFoundError if CLI not found, CLIConnectionError on failure.
	StartWithContent(ctx context.Context, content UserMessageContent, opts ...Option) error

	// StartWithStream establishes a connection and streams initial messages.
	// Messages are consumed from the iterator and sent via stdin.
	// The iterator runs in a separate goroutine; use context cancellation to abort.
	// EndInput is called automatically when the iterator completes.
	// Returns CLINotFoundError if CLI not found, CLIConnectionError on failure.
	StartWithStream(ctx context.Context, messages iter.Seq[StreamingMessage], opts ...Option) error

	// Query sends user content to Claude.
	// Returns immediately after sending; use ReceiveMessages() or ReceiveResponse() to get responses.
	// Optional sessionID defaults to "default" for multi-session support.
	Query(ctx context.Context, content UserMessageContent, sessionID ...string) error

	// ReceiveMessages returns an iterator that yields messages indefinitely.
	// Messages are yielded as they arrive until EOF, an error occurs, or context is cancelled.
	// Unlike ReceiveResponse, this iterator does not stop at ResultMessage.
	// Use iter.Pull2 if you need pull-based iteration instead of range.
	ReceiveMessages(ctx context.Context) iter.Seq2[Message, error]

	// ReceiveResponse returns an iterator that yields messages until a ResultMessage is received.
	// Messages are yielded as they arrive for streaming consumption.
	// The iterator stops after yielding the ResultMessage.
	// Use iter.Pull2 if you need pull-based iteration instead of range.
	// To collect all messages into a slice, use slices.Collect or a simple loop.
	ReceiveResponse(ctx context.Context) iter.Seq2[Message, error]

	// Interrupt sends an interrupt signal to stop Claude's current processing.
	Interrupt(ctx context.Context) error

	// SetPermissionMode changes the permission mode during conversation.
	// Valid modes: "default", "acceptEdits", "plan", "bypassPermissions"
	SetPermissionMode(ctx context.Context, mode string) error

	// SetModel changes the AI model during conversation.
	// Pass nil to use the default model.
	SetModel(ctx context.Context, model *string) error

	// ListModels returns the SDK's static Claude model catalog in the ListModels payload shape.
	// This is not a live account-specific list from the Claude CLI.
	ListModels(ctx context.Context) ([]ModelInfo, error)

	// GetServerInfo returns server initialization info including available commands.
	// Returns nil if not connected or not in streaming mode.
	GetServerInfo() map[string]any

	// GetMCPStatus queries the CLI for live MCP server connection status.
	// Returns the status of all configured MCP servers.
	GetMCPStatus(ctx context.Context) (*MCPStatus, error)

	// ReconnectMCPServer reconnects a disconnected or failed MCP server.
	ReconnectMCPServer(ctx context.Context, serverName string) error

	// ToggleMCPServer enables or disables an MCP server.
	ToggleMCPServer(ctx context.Context, serverName string, enabled bool) error

	// StopTask stops a running task by task ID.
	StopTask(ctx context.Context, taskID string) error

	// RewindFiles rewinds tracked files to their state at a specific user message.
	// The userMessageID should be the ID of a previous user message in the conversation.
	// Requires EnableFileCheckpointing=true in ClaudeAgentOptions.
	RewindFiles(ctx context.Context, userMessageID string) error

	// SendToolResult sends a tool_result message back to Claude for a pending tool_use.
	// This is used when the SDK intercepts a tool_use (e.g. AskUserQuestion) and needs
	// to provide the result back to Claude so it can continue processing.
	SendToolResult(ctx context.Context, toolUseID, content string, isError bool) error

	// Close terminates the session and cleans up resources.
	// After Close(), the client cannot be reused. Safe to call multiple times.
	Close() error
}

Client provides an interactive, stateful interface for multi-turn conversations with Claude.

Unlike the one-shot Query() function, Client maintains session state across multiple exchanges. It supports interruption and bidirectional communication with the Claude CLI.

Lifecycle: Clients are single-use. After Close(), create a new client with NewClient().

Example usage:

client := NewClient()
defer client.Close(ctx)

err := client.Start(ctx,
    WithLogger(slog.Default()),
    WithPermissionMode("acceptEdits"),
)
if err != nil {
    log.Fatal(err)
}

// Send a query
err = client.Query(ctx, Text("What is 2+2?"))
if err != nil {
    log.Fatal(err)
}

// Receive all messages for this response (stops at ResultMessage)
for msg, err := range client.ReceiveResponse(ctx) {
    if err != nil {
        log.Fatal(err)
    }
    // Process message...
}

// Or receive messages indefinitely (for continuous streaming)
for msg, err := range client.ReceiveMessages(ctx) {
    if err != nil {
        break
    }
    // Process message...
}

func NewClient

func NewClient() Client

NewClient creates a new interactive client.

Call Start() with options to begin a session:

client := NewClient()
err := client.Start(ctx,
    WithLogger(slog.Default()),
    WithPermissionMode("acceptEdits"),
)

type ContentBlock

type ContentBlock = message.ContentBlock

ContentBlock represents a block of content within a message.

type Effort

type Effort = config.Effort

Effort controls thinking depth.

type HookCallback

type HookCallback = hook.Callback

HookCallback is the function signature for hook callbacks.

type HookContext

type HookContext = hook.Context

HookContext provides context for hook execution.

type HookEvent

type HookEvent = hook.Event

HookEvent represents the type of event that triggers a hook.

type HookInput

type HookInput = hook.Input

HookInput is the interface for all hook input types.

type HookJSONOutput

type HookJSONOutput = hook.JSONOutput

HookJSONOutput is the interface for hook output types.

type HookMatcher

type HookMatcher = hook.Matcher

HookMatcher configures which tools/events a hook applies to.

type HookSpecificOutput

type HookSpecificOutput = hook.SpecificOutput

HookSpecificOutput is the interface for hook-specific outputs.

type InputDocumentBlock added in v0.0.5

type InputDocumentBlock = message.InputDocumentBlock

InputDocumentBlock contains an inline PDF document input for multimodal prompts.

func PDFFileInput added in v0.0.5

func PDFFileInput(path string) (*InputDocumentBlock, error)

PDFFileInput reads a local PDF file and returns an inline PDF document block.

func PDFInput added in v0.0.5

func PDFInput(data string) *InputDocumentBlock

PDFInput creates an inline PDF document block from base64 data.

type InputImageBlock added in v0.0.5

type InputImageBlock = message.InputImageBlock

InputImageBlock contains an inline image input for multimodal prompts.

func ImageFileInput added in v0.0.5

func ImageFileInput(path string) (*InputImageBlock, error)

ImageFileInput reads a local image file and returns an inline image block.

func ImageInput added in v0.0.5

func ImageInput(mediaType, data string) *InputImageBlock

ImageInput creates an inline image block from base64 data and media type.

type MCPHTTPServerConfig

type MCPHTTPServerConfig = mcp.HTTPServerConfig

MCPHTTPServerConfig configures an HTTP-based MCP server.

type MCPSSEServerConfig

type MCPSSEServerConfig = mcp.SSEServerConfig

MCPSSEServerConfig configures a Server-Sent Events MCP server.

type MCPSdkServerConfig

type MCPSdkServerConfig = mcp.SdkServerConfig

MCPSdkServerConfig configures an SDK-provided MCP server.

func CreateSdkMcpServer

func CreateSdkMcpServer(name, version string, tools ...*SdkMcpTool) *MCPSdkServerConfig

CreateSdkMcpServer creates an in-process MCP server configuration with SdkMcpTool tools.

This function creates an MCP server that runs within your application, providing better performance than external MCP servers.

The returned config can be used directly in ClaudeAgentOptions.MCPServers:

addTool := claudesdk.NewSdkMcpTool("add", "Add two numbers",
    claudesdk.SimpleSchema(map[string]string{"a": "float64", "b": "float64"}),
    func(ctx context.Context, req *claudesdk.CallToolRequest) (*claudesdk.CallToolResult, error) {
        args, _ := claudesdk.ParseArguments(req)
        a, b := args["a"].(float64), args["b"].(float64)
        return claudesdk.TextResult(fmt.Sprintf("Result: %v", a+b)), nil
    },
)

calculator := claudesdk.CreateSdkMcpServer("calculator", "1.0.0", addTool)

options := &claudesdk.ClaudeAgentOptions{
    MCPServers: map[string]claudesdk.MCPServerConfig{
        "calculator": calculator,
    },
    AllowedTools: []string{"mcp__calculator__add"},
}

Parameters:

  • name: Server name (also used as key in MCPServers map, determines tool naming: mcp__<name>__<toolName>)
  • version: Server version string
  • tools: SdkMcpTool instances to register with the server

type MCPServerConfig

type MCPServerConfig = mcp.ServerConfig

MCPServerConfig is the interface for MCP server configurations.

type MCPServerConnectionStatus added in v0.0.2

type MCPServerConnectionStatus = mcp.ServerConnectionStatus

MCPServerConnectionStatus represents the connection state of an MCP server.

type MCPServerInfo added in v0.0.2

type MCPServerInfo = mcp.ServerInfo

MCPServerInfo describes server information returned from initialize.

type MCPServerStatus

type MCPServerStatus = mcp.ServerStatus

MCPServerStatus represents the connection status of a single MCP server.

type MCPServerStatusConfig added in v0.0.2

type MCPServerStatusConfig = mcp.ServerStatusConfig

MCPServerStatusConfig captures the serializable server config included in status responses.

type MCPServerType

type MCPServerType = mcp.ServerType

MCPServerType represents the type of MCP server.

type MCPStatus

type MCPStatus = mcp.Status

MCPStatus represents the connection status of all configured MCP servers.

type MCPStdioServerConfig

type MCPStdioServerConfig = mcp.StdioServerConfig

MCPStdioServerConfig configures a stdio-based MCP server.

type MCPToolAnnotations added in v0.0.2

type MCPToolAnnotations = mcp.ToolAnnotations

MCPToolAnnotations describes MCP tool capability metadata.

type MCPToolInfo added in v0.0.2

type MCPToolInfo = mcp.ToolInfo

MCPToolInfo describes an MCP tool exposed by a server.

type McpAudioContent

type McpAudioContent = mcp.AudioContent

McpAudioContent represents audio content in a tool result.

type McpContent

type McpContent = mcp.Content

McpContent is the interface for content types in tool results.

type McpImageContent

type McpImageContent = mcp.ImageContent

McpImageContent represents image content in a tool result.

type McpTextContent

type McpTextContent = mcp.TextContent

McpTextContent represents text content in a tool result.

type McpTool

type McpTool = mcp.Tool

McpTool represents an MCP tool definition from the official SDK.

type McpToolAnnotations

type McpToolAnnotations = mcp.ToolAnnotations

McpToolAnnotations describes optional hints about tool behavior. Fields include ReadOnlyHint, DestructiveHint, IdempotentHint, OpenWorldHint, and Title.

type McpToolHandler

type McpToolHandler = mcp.ToolHandler

McpToolHandler is the function signature for low-level tool handlers.

type Message

type Message = message.Message

Message represents any message in the conversation.

type MessageParseError

type MessageParseError = errors.MessageParseError

MessageParseError indicates message parsing failed.

type MessageStream

type MessageStream = iter.Seq[StreamingMessage]

MessageStream is an iterator that yields streaming messages.

type Model

type Model = models.Model

Model holds metadata for a single Claude model.

func ModelByID

func ModelByID(id string) *Model

ModelByID looks up a model by exact ID. Returns nil if no model is found.

func Models

func Models() []Model

Models returns a copy of the SDK's static Claude model catalog. It is not a live list of models available to the logged-in Claude CLI user.

func ModelsByCostTier

func ModelsByCostTier(tier ModelCostTier) []Model

ModelsByCostTier returns all models matching the given cost tier.

type ModelCapability

type ModelCapability = models.Capability

ModelCapability represents a model capability such as vision or tool use.

type ModelCostTier

type ModelCostTier = models.CostTier

ModelCostTier represents a provider-agnostic relative cost tier.

type ModelInfo added in v0.0.2

type ModelInfo = models.Info

ModelInfo describes a model exposed by ListModels.

func ListModels added in v0.0.2

func ListModels(_ context.Context) ([]ModelInfo, error)

ListModels returns a Codex-like model list payload backed by the SDK's static Claude catalog. This is not a live account-specific list from the Claude CLI.

type ModelListResponse added in v0.0.2

type ModelListResponse = models.ListResponse

ModelListResponse is the response payload backing ListModels.

func ListModelsResponse added in v0.0.2

func ListModelsResponse(_ context.Context) (*ModelListResponse, error)

ListModelsResponse returns the full static model-list response payload.

type NotificationHookInput

type NotificationHookInput = hook.NotificationInput

NotificationHookInput is the input for Notification hooks.

type NotificationHookSpecificOutput

type NotificationHookSpecificOutput = hook.NotificationSpecificOutput

NotificationHookSpecificOutput is the hook-specific output for Notification.

type Option

type Option func(*ClaudeAgentOptions)

Option configures ClaudeAgentOptions using the functional options pattern. This is the primary option type for configuring clients and queries.

func WithAddDirs

func WithAddDirs(dirs ...string) Option

WithAddDirs adds additional directories to make accessible.

func WithAgents

func WithAgents(agents map[string]*AgentDefinition) Option

WithAgents defines custom agent configurations.

func WithAllowedTools

func WithAllowedTools(tools ...string) Option

WithAllowedTools sets pre-approved tools that can be used without prompting.

func WithBetas

func WithBetas(betas ...SdkBeta) Option

WithBetas enables beta features.

func WithCanUseTool

func WithCanUseTool(callback ToolPermissionCallback) Option

WithCanUseTool sets a callback for permission checking before each tool use.

func WithClaudeHome

func WithClaudeHome(path string) Option

WithClaudeHome overrides the Claude home directory (default: ~/.claude).

func WithCliPath

func WithCliPath(path string) Option

WithCliPath sets the explicit path to the claude CLI binary. If not set, the CLI will be searched in PATH.

func WithContinueConversation

func WithContinueConversation(cont bool) Option

WithContinueConversation indicates whether to continue an existing conversation.

func WithCwd

func WithCwd(cwd string) Option

WithCwd sets the working directory for the CLI process.

func WithDisallowedTools

func WithDisallowedTools(tools ...string) Option

WithDisallowedTools sets tools that are explicitly blocked.

func WithEffort

func WithEffort(effort config.Effort) Option

WithEffort sets the thinking effort level.

func WithEnableFileCheckpointing

func WithEnableFileCheckpointing(enable bool) Option

WithEnableFileCheckpointing enables file change tracking and rewinding.

func WithEnv

func WithEnv(env map[string]string) Option

WithEnv provides additional environment variables for the CLI process.

func WithExtraArgs

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

WithExtraArgs provides arbitrary CLI flags to pass to the CLI. If the value is nil, the flag is passed without a value (boolean flag).

func WithFallbackModel

func WithFallbackModel(model string) Option

WithFallbackModel specifies a model to use if the primary model fails.

func WithForkSession

func WithForkSession(fork bool) Option

WithForkSession indicates whether to fork the resumed session to a new ID.

func WithHooks

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

WithHooks configures event hooks for tool interception.

func WithIncludePartialMessages

func WithIncludePartialMessages(include bool) Option

WithIncludePartialMessages enables streaming of partial message updates.

func WithInitializeTimeout

func WithInitializeTimeout(timeout time.Duration) Option

WithInitializeTimeout sets the timeout for the initialize control request.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger for debug output. If not set, logging is disabled (silent operation).

func WithMCPConfig

func WithMCPConfig(config string) Option

WithMCPConfig sets a path to an MCP config file or a raw JSON string. If set, this takes precedence over WithMCPServers.

func WithMCPServers

func WithMCPServers(servers map[string]MCPServerConfig) Option

WithMCPServers configures external MCP servers to connect to. Map key is the server name, value is the server configuration.

func WithMaxBudgetUSD

func WithMaxBudgetUSD(budget float64) Option

WithMaxBudgetUSD sets a cost limit for the session in USD.

func WithMaxBufferSize

func WithMaxBufferSize(size int) Option

WithMaxBufferSize sets the maximum bytes for CLI stdout buffering.

func WithMaxTurns

func WithMaxTurns(maxTurns int) Option

WithMaxTurns limits the maximum number of conversation turns.

func WithModel

func WithModel(model string) Option

WithModel specifies which Claude model ID to use (e.g., "claude-sonnet-4-6").

func WithOnUserInput

func WithOnUserInput(callback UserInputCallback) Option

WithOnUserInput sets a callback for handling AskUserQuestion prompts.

func WithOutputFormat

func WithOutputFormat(format map[string]any) Option

WithOutputFormat specifies a JSON schema for structured output.

The canonical format uses a wrapper object:

claudesdk.WithOutputFormat(map[string]any{
    "type": "json_schema",
    "schema": map[string]any{
        "type":       "object",
        "properties": map[string]any{...},
        "required":   []string{...},
    },
})

Raw JSON schemas (without the wrapper) are also accepted and auto-wrapped:

claudesdk.WithOutputFormat(map[string]any{
    "type":       "object",
    "properties": map[string]any{...},
    "required":   []string{...},
})

Structured output is available on ResultMessage.StructuredOutput (parsed) or ResultMessage.Result (JSON string).

func WithPermissionMode

func WithPermissionMode(mode string) Option

WithPermissionMode controls how permissions are handled. Valid values: "default", "acceptEdits", "plan", "bypassPermissions".

func WithPermissionPromptToolName

func WithPermissionPromptToolName(name string) Option

WithPermissionPromptToolName specifies the tool name to use for permission prompts.

func WithPlugins

func WithPlugins(plugins ...*SdkPluginConfig) Option

WithPlugins configures plugins to load.

func WithResume

func WithResume(sessionID string) Option

WithResume sets a session ID to resume from.

func WithSDKTools

func WithSDKTools(tools ...Tool) Option

WithSDKTools registers high-level Tool instances as an in-process MCP server. Tools are exposed under the "sdk" MCP server name (tool names: mcp__sdk__<name>). Each tool is automatically added to AllowedTools.

func WithSandboxSettings

func WithSandboxSettings(settings *SandboxSettings) Option

WithSandboxSettings configures CLI sandbox behavior.

func WithSettingSources

func WithSettingSources(sources ...SettingSource) Option

WithSettingSources specifies which setting sources to use.

func WithSettings

func WithSettings(path string) Option

WithSettings sets the path to a settings file to load.

func WithStderr

func WithStderr(handler func(string)) Option

WithStderr sets a callback function for handling stderr output.

func WithSystemPrompt

func WithSystemPrompt(prompt string) Option

WithSystemPrompt sets the system message to send to Claude.

func WithSystemPromptPreset

func WithSystemPromptPreset(preset *SystemPromptPreset) Option

WithSystemPromptPreset sets a preset system prompt configuration. If set, this takes precedence over WithSystemPrompt.

func WithThinking

func WithThinking(thinking config.ThinkingConfig) Option

WithThinking sets the thinking configuration.

func WithTools

func WithTools(tools config.ToolsConfig) Option

WithTools specifies which tools are available. Accepts ToolsList (tool names) or *ToolsPreset.

func WithTransport

func WithTransport(transport config.Transport) Option

WithTransport injects a custom transport implementation. The transport must implement the Transport interface.

func WithUser

func WithUser(user string) Option

WithUser sets a user identifier for tracking purposes.

type PermissionBehavior

type PermissionBehavior = permission.Behavior

PermissionBehavior represents the permission behavior for a rule.

type PermissionMode

type PermissionMode = permission.Mode

PermissionMode represents different permission handling modes.

type PermissionRequestHookInput

type PermissionRequestHookInput = hook.PermissionRequestInput

PermissionRequestHookInput is the input for PermissionRequest hooks.

type PermissionRequestHookSpecificOutput

type PermissionRequestHookSpecificOutput = hook.PermissionRequestSpecificOutput

PermissionRequestHookSpecificOutput is the hook-specific output for PermissionRequest.

type PermissionResult

type PermissionResult = permission.Result

PermissionResult is the interface for permission decision results.

type PermissionResultAllow

type PermissionResultAllow = permission.ResultAllow

PermissionResultAllow represents an allow decision.

type PermissionResultDeny

type PermissionResultDeny = permission.ResultDeny

PermissionResultDeny represents a deny decision.

type PermissionRuleValue

type PermissionRuleValue = permission.RuleValue

PermissionRuleValue represents a permission rule.

type PermissionUpdate

type PermissionUpdate = permission.Update

PermissionUpdate represents a permission update request.

type PermissionUpdateDestination

type PermissionUpdateDestination = permission.UpdateDestination

PermissionUpdateDestination represents where permission updates are stored.

type PermissionUpdateType

type PermissionUpdateType = permission.UpdateType

PermissionUpdateType represents the type of permission update.

type PostToolUseFailureHookInput

type PostToolUseFailureHookInput = hook.PostToolUseFailureInput

PostToolUseFailureHookInput is the input for PostToolUseFailure hooks.

type PostToolUseFailureHookSpecificOutput

type PostToolUseFailureHookSpecificOutput = hook.PostToolUseFailureSpecificOutput

PostToolUseFailureHookSpecificOutput is the hook-specific output for PostToolUseFailure.

type PostToolUseHookInput

type PostToolUseHookInput = hook.PostToolUseInput

PostToolUseHookInput is the input for PostToolUse hooks.

type PostToolUseHookSpecificOutput

type PostToolUseHookSpecificOutput = hook.PostToolUseSpecificOutput

PostToolUseHookSpecificOutput is the hook-specific output for PostToolUse.

type PreCompactHookInput

type PreCompactHookInput = hook.PreCompactInput

PreCompactHookInput is the input for PreCompact hooks.

type PreToolUseHookInput

type PreToolUseHookInput = hook.PreToolUseInput

PreToolUseHookInput is the input for PreToolUse hooks.

type PreToolUseHookSpecificOutput

type PreToolUseHookSpecificOutput = hook.PreToolUseSpecificOutput

PreToolUseHookSpecificOutput is the hook-specific output for PreToolUse.

type ProcessError

type ProcessError = errors.ProcessError

ProcessError indicates the CLI process failed.

type ReasoningEffortOption added in v0.0.2

type ReasoningEffortOption = models.ReasoningEffortOption

ReasoningEffortOption describes a selectable reasoning effort level.

type ResultMessage

type ResultMessage = message.ResultMessage

ResultMessage represents the final result of a query.

type SDKSessionInfo added in v0.0.2

type SDKSessionInfo struct {
	SessionID    string  `json:"session_id"`
	Summary      string  `json:"summary"`
	LastModified int64   `json:"last_modified"`
	FileSize     int64   `json:"file_size"`
	CustomTitle  *string `json:"custom_title,omitempty"`
	FirstPrompt  *string `json:"first_prompt,omitempty"`
	GitBranch    *string `json:"git_branch,omitempty"`
	Cwd          *string `json:"cwd,omitempty"`
}

SDKSessionInfo contains metadata for a persisted Claude session.

func ListSessions added in v0.0.2

func ListSessions(options SessionListOptions) []SDKSessionInfo

ListSessions lists Claude sessions for a project or across all projects.

type SandboxIgnoreViolations

type SandboxIgnoreViolations = sandbox.IgnoreViolations

SandboxIgnoreViolations configures which violations to ignore.

type SandboxNetworkConfig

type SandboxNetworkConfig = sandbox.NetworkConfig

SandboxNetworkConfig configures network access for the sandbox.

type SandboxSettings

type SandboxSettings = sandbox.Settings

SandboxSettings configures CLI sandbox behavior.

type Schema

type Schema = jsonschema.Schema

Schema is a JSON Schema object for tool input validation.

type SdkBeta

type SdkBeta = config.Beta

SdkBeta represents a beta feature flag for the SDK.

type SdkMcpServerInstance

type SdkMcpServerInstance = mcp.ServerInstance

SdkMcpServerInstance is the interface that SDK MCP servers must implement.

type SdkMcpTool

type SdkMcpTool struct {
	ToolName        string
	ToolDescription string
	ToolSchema      *jsonschema.Schema
	ToolHandler     SdkMcpToolHandler
	ToolAnnotations *mcp.ToolAnnotations
}

SdkMcpTool represents a tool created with NewSdkMcpTool.

func NewSdkMcpTool

func NewSdkMcpTool(
	name, description string,
	inputSchema *jsonschema.Schema,
	handler SdkMcpToolHandler,
	opts ...SdkMcpToolOption,
) *SdkMcpTool

NewSdkMcpTool creates an SdkMcpTool with optional configuration.

The inputSchema should be a *jsonschema.Schema. Use SimpleSchema for convenience or create a full Schema struct for more control.

Use WithAnnotations to set MCP tool annotations (hints about tool behavior).

Example with SimpleSchema:

addTool := claudesdk.NewSdkMcpTool("add", "Add two numbers",
    claudesdk.SimpleSchema(map[string]string{"a": "float64", "b": "float64"}),
    func(ctx context.Context, req *claudesdk.CallToolRequest) (*claudesdk.CallToolResult, error) {
        args, _ := claudesdk.ParseArguments(req)
        a, b := args["a"].(float64), args["b"].(float64)
        return claudesdk.TextResult(fmt.Sprintf("Result: %v", a+b)), nil
    },
    claudesdk.WithAnnotations(&claudesdk.McpToolAnnotations{
        ReadOnlyHint: true,
    }),
)

func (*SdkMcpTool) Annotations

func (t *SdkMcpTool) Annotations() *mcp.ToolAnnotations

Annotations returns the tool annotations, or nil if not set.

func (*SdkMcpTool) Description

func (t *SdkMcpTool) Description() string

Description returns the tool description.

func (*SdkMcpTool) Handler

func (t *SdkMcpTool) Handler() SdkMcpToolHandler

Handler returns the tool handler function.

func (*SdkMcpTool) InputSchema

func (t *SdkMcpTool) InputSchema() *jsonschema.Schema

InputSchema returns the JSON Schema for the tool input.

func (*SdkMcpTool) Name

func (t *SdkMcpTool) Name() string

Name returns the tool name.

type SdkMcpToolHandler

type SdkMcpToolHandler = mcp.ToolHandler

SdkMcpToolHandler is the function signature for SdkMcpTool handlers. It receives the context and request, and returns the result.

Use ParseArguments to extract input as map[string]any from the request. Use TextResult, ErrorResult, or ImageResult helpers to create results.

Example:

func(ctx context.Context, req *claudesdk.CallToolRequest) (*claudesdk.CallToolResult, error) {
    args, err := claudesdk.ParseArguments(req)
    if err != nil {
        return claudesdk.ErrorResult(err.Error()), nil
    }
    a := args["a"].(float64)
    return claudesdk.TextResult(fmt.Sprintf("Result: %v", a)), nil
}

type SdkMcpToolOption

type SdkMcpToolOption func(*SdkMcpTool)

SdkMcpToolOption configures an SdkMcpTool during construction.

func WithAnnotations

func WithAnnotations(annotations *mcp.ToolAnnotations) SdkMcpToolOption

WithAnnotations sets MCP tool annotations (hints about tool behavior). Annotations describe properties like whether a tool is read-only, destructive, idempotent, or operates in an open world.

type SdkPluginConfig

type SdkPluginConfig = config.PluginConfig

SdkPluginConfig configures a plugin to load.

type SessionListOptions added in v0.0.2

type SessionListOptions struct {
	Directory        string
	Limit            int
	IncludeWorktrees *bool
	ClaudeHome       string
}

SessionListOptions controls ListSessions behavior.

type SessionMessage added in v0.0.2

type SessionMessage struct {
	Type            string         `json:"type"`
	UUID            string         `json:"uuid"`
	SessionID       string         `json:"session_id"`
	Message         map[string]any `json:"message"`
	ParentToolUseID *string        `json:"parent_tool_use_id,omitempty"`
}

SessionMessage contains a top-level user or assistant message from a saved transcript.

func GetSessionMessages added in v0.0.2

func GetSessionMessages(sessionID string, options SessionMessagesOptions) []SessionMessage

GetSessionMessages returns top-level conversation messages from a saved session.

type SessionMessagesOptions added in v0.0.2

type SessionMessagesOptions struct {
	Directory  string
	Limit      int
	Offset     int
	ClaudeHome string
}

SessionMessagesOptions controls GetSessionMessages behavior.

type SessionStat

type SessionStat struct {
	SessionID    string
	SizeBytes    int64
	LastModified time.Time
	MessageCount *int
	CreatedAt    *time.Time
	UpdatedAt    *time.Time
}

SessionStat contains local metadata for a persisted Claude session.

This metadata is read from local Claude persistence files. It does not represent live remote state or lock/occupancy status.

func StatSession

func StatSession(
	ctx context.Context,
	sessionID string,
	opts ...Option,
) (*SessionStat, error)

StatSession returns metadata for a locally persisted session.

The lookup is project-scoped and read-only; no prompt is sent and no session content is modified. Returns ErrSessionNotFound when the session cannot be found in local Claude persistence for the resolved project path.

type SettingSource

type SettingSource = config.SettingSource

SettingSource represents where settings should be loaded from.

type StopHookInput

type StopHookInput = hook.StopInput

StopHookInput is the input for Stop hooks.

type StreamEvent

type StreamEvent = message.StreamEvent

StreamEvent represents a streaming event from the Claude API.

type StreamingMessage

type StreamingMessage = message.StreamingMessage

StreamingMessage represents a message sent in streaming mode.

func NewUserMessage

func NewUserMessage(content UserMessageContent) StreamingMessage

NewUserMessage creates a StreamingMessage with type "user". This is a convenience constructor for creating user messages.

type StreamingMessageContent

type StreamingMessageContent = message.StreamingMessageContent

StreamingMessageContent represents the content of a streaming message.

type SubagentStartHookInput

type SubagentStartHookInput = hook.SubagentStartInput

SubagentStartHookInput is the input for SubagentStart hooks.

type SubagentStartHookSpecificOutput

type SubagentStartHookSpecificOutput = hook.SubagentStartSpecificOutput

SubagentStartHookSpecificOutput is the hook-specific output for SubagentStart.

type SubagentStopHookInput

type SubagentStopHookInput = hook.SubagentStopInput

SubagentStopHookInput is the input for SubagentStop hooks.

type SyncHookJSONOutput

type SyncHookJSONOutput = hook.SyncJSONOutput

SyncHookJSONOutput represents a sync hook output.

type SystemMessage

type SystemMessage = message.SystemMessage

SystemMessage represents a system message.

type SystemPromptPreset

type SystemPromptPreset = config.SystemPromptPreset

SystemPromptPreset defines a system prompt preset configuration.

type TaskNotificationMessage added in v0.0.2

type TaskNotificationMessage = message.TaskNotificationMessage

TaskNotificationMessage is emitted when a task completes, fails, or stops.

type TaskNotificationStatus added in v0.0.2

type TaskNotificationStatus = message.TaskNotificationStatus

TaskNotificationStatus represents the final status of a task.

type TaskProgressMessage added in v0.0.2

type TaskProgressMessage = message.TaskProgressMessage

TaskProgressMessage is emitted while a task is running.

type TaskStartedMessage added in v0.0.2

type TaskStartedMessage = message.TaskStartedMessage

TaskStartedMessage is emitted when a task starts.

type TaskUsage added in v0.0.2

type TaskUsage = message.TaskUsage

TaskUsage contains task progress usage statistics.

type TextBlock

type TextBlock = message.TextBlock

TextBlock contains plain text content.

func PathInput added in v0.0.5

func PathInput(path string) *TextBlock

PathInput creates a text block containing a Claude CLI @path mention.

func TextInput added in v0.0.5

func TextInput(text string) *TextBlock

TextInput creates a text block for block-based multimodal user content.

type ThinkingBlock

type ThinkingBlock = message.ThinkingBlock

ThinkingBlock contains Claude's thinking process.

type ThinkingConfig

type ThinkingConfig = config.ThinkingConfig

ThinkingConfig controls extended thinking behavior.

type ThinkingConfigAdaptive

type ThinkingConfigAdaptive = config.ThinkingConfigAdaptive

ThinkingConfigAdaptive enables adaptive thinking mode.

type ThinkingConfigDisabled

type ThinkingConfigDisabled = config.ThinkingConfigDisabled

ThinkingConfigDisabled disables extended thinking.

type ThinkingConfigEnabled

type ThinkingConfigEnabled = config.ThinkingConfigEnabled

ThinkingConfigEnabled enables thinking with a specific token budget.

type Tool

type Tool interface {
	// Name returns the unique identifier for this tool.
	Name() string

	// Description returns a human-readable description for Claude.
	Description() string

	// InputSchema returns a JSON schema describing expected input.
	// The schema should follow JSON Schema Draft 7 specification.
	InputSchema() map[string]any

	// Execute runs the tool with the provided input.
	// The input will be validated against InputSchema before execution.
	Execute(ctx context.Context, input map[string]any) (map[string]any, error)
}

Tool represents a custom tool that Claude can invoke.

Tools allow users to extend Claude's capabilities with domain-specific functionality. When registered, Claude can discover and execute these tools during a session.

Example:

tool := claudesdk.NewTool(
    "calculator",
    "Performs basic arithmetic operations",
    map[string]any{
        "type": "object",
        "properties": map[string]any{
            "operation": map[string]any{
                "type": "string",
                "enum": []string{"add", "subtract", "multiply", "divide"},
            },
            "a": map[string]any{"type": "number"},
            "b": map[string]any{"type": "number"},
        },
        "required": []string{"operation", "a", "b"},
    },
    func(ctx context.Context, input map[string]any) (map[string]any, error) {
        op := input["operation"].(string)
        a := input["a"].(float64)
        b := input["b"].(float64)

        var result float64
        switch op {
        case "add":
            result = a + b
        case "subtract":
            result = a - b
        case "multiply":
            result = a * b
        case "divide":
            if b == 0 {
                return nil, fmt.Errorf("division by zero")
            }
            result = a / b
        }

        return map[string]any{"result": result}, nil
    },
)

func NewTool

func NewTool(name, description string, schema map[string]any, fn ToolFunc) Tool

NewTool creates a Tool from a function.

This is a convenience constructor for creating tools without implementing the full Tool interface.

Parameters:

  • name: Unique identifier for the tool (e.g., "calculator", "search_database")
  • description: Human-readable description of what the tool does
  • schema: JSON Schema defining the expected input structure
  • fn: Function that executes the tool logic

type ToolFunc

type ToolFunc func(ctx context.Context, input map[string]any) (map[string]any, error)

ToolFunc is a function-based tool implementation.

type ToolPermissionCallback

type ToolPermissionCallback = permission.Callback

ToolPermissionCallback is called before each tool use for permission checking.

type ToolPermissionContext

type ToolPermissionContext = permission.Context

ToolPermissionContext provides context for tool permission callbacks.

type ToolReferenceBlock added in v0.0.2

type ToolReferenceBlock = message.ToolReferenceBlock

ToolReferenceBlock points to a deferred tool selected by Claude tool search.

type ToolResultBlock

type ToolResultBlock = message.ToolResultBlock

ToolResultBlock contains the result of a tool execution.

type ToolUseBlock

type ToolUseBlock = message.ToolUseBlock

ToolUseBlock represents Claude using a tool.

type ToolsConfig

type ToolsConfig = config.ToolsConfig

ToolsConfig is an interface for configuring available tools. It represents either a list of tool names or a preset configuration.

type ToolsList

type ToolsList = config.ToolsList

ToolsList is a list of tool names to make available.

type ToolsPreset

type ToolsPreset = config.ToolsPreset

ToolsPreset represents a preset configuration for available tools.

type Transport

type Transport = config.Transport

Transport defines the interface for Claude CLI communication. Implement this to provide custom transports for testing, mocking, or alternative communication methods (e.g., remote connections).

The default implementation is CLITransport which spawns a subprocess. Custom transports can be injected via ClaudeAgentOptions.Transport.

type UnknownBlock added in v0.0.2

type UnknownBlock = message.UnknownBlock

UnknownBlock preserves unrecognized content block payloads without failing parsing.

type Usage

type Usage = message.Usage

Usage contains token usage information.

type UserInputAnswer

type UserInputAnswer = userinput.Answer

UserInputAnswer contains response(s) for a question.

type UserInputCallback

type UserInputCallback = userinput.Callback

UserInputCallback handles AskUserQuestion prompts.

type UserInputQuestion

type UserInputQuestion = userinput.Question

UserInputQuestion represents a single AskUserQuestion prompt.

type UserInputQuestionOption

type UserInputQuestionOption = userinput.QuestionOption

UserInputQuestionOption represents a selectable choice within a question.

type UserInputRequest

type UserInputRequest = userinput.Request

UserInputRequest contains parsed AskUserQuestion payload data.

type UserInputResponse

type UserInputResponse = userinput.Response

UserInputResponse contains answers keyed by question text.

type UserMessage

type UserMessage = message.UserMessage

UserMessage represents a message from the user.

type UserMessageContent

type UserMessageContent = message.UserMessageContent

UserMessageContent represents content that can be either a string or []ContentBlock.

func Blocks added in v0.0.5

func Blocks(blocks ...ContentBlock) UserMessageContent

Blocks creates block-based user content.

func Text added in v0.0.5

func Text(text string) UserMessageContent

Text creates text-only user content.

type UserPromptSubmitHookInput

type UserPromptSubmitHookInput = hook.UserPromptSubmitInput

UserPromptSubmitHookInput is the input for UserPromptSubmit hooks.

type UserPromptSubmitHookSpecificOutput

type UserPromptSubmitHookSpecificOutput = hook.UserPromptSubmitSpecificOutput

UserPromptSubmitHookSpecificOutput is the hook-specific output for UserPromptSubmit.

Directories

Path Synopsis
examples
agents command
cancellation command
compaction_hook command
Package main demonstrates context compaction monitoring using the PreCompact hook.
Package main demonstrates context compaction monitoring using the PreCompact hook.
error_handling command
extended_thinking command
Package main demonstrates extended thinking capabilities with Claude.
Package main demonstrates extended thinking capabilities with Claude.
hooks command
max_budget_usd command
mcp_calculator command
Package main demonstrates how to create calculator tools using MCP servers.
Package main demonstrates how to create calculator tools using MCP servers.
mcp_status command
Package main demonstrates querying MCP server connection status.
Package main demonstrates querying MCP server connection status.
memory_tool command
Package main demonstrates a filesystem-backed memory tool for agent state persistence.
Package main demonstrates a filesystem-backed memory tool for agent state persistence.
pipeline command
plugin_example command
Package main demonstrates how to use plugins with Claude Code SDK.
Package main demonstrates how to use plugins with Claude Code SDK.
query_stream command
quick_start command
sessions command
setting_sources command
stderr_callback command
system_prompt command
tools_option command
internal
cli
Package cli provides CLI discovery, version validation, and command building for the Claude Code CLI binary.
Package cli provides CLI discovery, version validation, and command building for the Claude Code CLI binary.
client
Package client implements the interactive Client for multi-turn conversations with Claude.
Package client implements the interactive Client for multi-turn conversations with Claude.
config
Package config provides configuration types for the Claude SDK.
Package config provides configuration types for the Claude SDK.
errors
Package errors defines error types for the Claude SDK.
Package errors defines error types for the Claude SDK.
hook
Package hook provides hook types for intercepting Claude CLI events.
Package hook provides hook types for intercepting Claude CLI events.
mcp
Package mcp implements an in-process Model Context Protocol server.
Package mcp implements an in-process Model Context Protocol server.
message
Package message provides message and content block types for Claude conversations.
Package message provides message and content block types for Claude conversations.
models
Package models provides a catalog of known Claude models and their capabilities.
Package models provides a catalog of known Claude models and their capabilities.
permission
Package permission provides permission handling types for the Claude CLI.
Package permission provides permission handling types for the Claude CLI.
protocol
Package protocol implements bidirectional control message handling for the Claude CLI.
Package protocol implements bidirectional control message handling for the Claude CLI.
sandbox
Package sandbox provides sandbox configuration types for the Claude CLI.
Package sandbox provides sandbox configuration types for the Claude CLI.
subprocess
Package subprocess provides subprocess-based transport for the Claude CLI.
Package subprocess provides subprocess-based transport for the Claude CLI.
userinput
Package userinput provides typed structures for AskUserQuestion handling.
Package userinput provides typed structures for AskUserQuestion handling.

Jump to

Keyboard shortcuts

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