claude

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2026 License: MIT Imports: 22 Imported by: 0

README

Claude Go SDK

Go Reference Go Report Card

A Go SDK for automating Claude Code CLI with concurrent session management, real-time streaming, custom tools, and hooks. This is the Go equivalent of the Python Claude Agent SDK.

Features

  • Simple Query Function: One-shot queries without session management
  • Concurrent Sessions: Run multiple Claude sessions simultaneously with goroutines
  • Structured Message Types: Typed messages (AssistantMessage, UserMessage, ResultMessage, etc.)
  • Custom Tools (MCP): Define in-process MCP tools that run directly in your Go application
  • Hooks: Intercept and control tool execution with PreToolUse, PostToolUse hooks
  • JSON Streaming: Real-time streaming with typed content blocks
  • CLI Discovery: Automatic detection of Claude CLI in PATH and common locations
  • Comprehensive Errors: Typed errors for precise error handling
  • Session Management: Create, manage, and reuse conversation sessions

Installation

go get github.com/standardbeagle/claude-go

Quick Start

Simple One-Shot Query
package main

import (
    "context"
    "fmt"
    "log"

    claude "github.com/standardbeagle/claude-go"
)

func main() {
    ctx := context.Background()

    messages, err := claude.Query(ctx, "What is 2+2?", nil)
    if err != nil {
        log.Fatal(err)
    }

    for _, msg := range messages {
        if text := claude.GetText(msg); text != "" {
            fmt.Println(text)
        }
    }
}
Client-Based Usage
client := claude.New(&claude.AgentOptions{
    PermissionMode: claude.PermissionModeBypassPermission,
    Model:          "sonnet",
})
defer client.Close()

resp, err := client.Query(ctx, &claude.QueryRequest{
    Prompt: "Write a hello world function in Go",
})
if err != nil {
    log.Fatal(err)
}

for msg := range resp.Messages {
    fmt.Printf("%s: %s\n", msg.Type, msg.Content)
}

Custom Tools (In-Process MCP Servers)

Define custom tools that Claude can use during conversations:

// Create a tool using the builder pattern
addTool := claude.Tool("add", "Add two numbers").
    Param("a", "number", "First number").
    Param("b", "number", "Second number").
    Required("a", "b").
    HandlerFunc(func(ctx context.Context, args map[string]interface{}) (string, error) {
        a := args["a"].(float64)
        b := args["b"].(float64)
        return fmt.Sprintf("%g", a+b), nil
    })

// Create an SDK MCP server
server := claude.CreateSDKMCPServer("calculator", "1.0.0", addTool)

// Register with client
client := claude.New(&claude.AgentOptions{
    PermissionMode: claude.PermissionModeBypassPermission,
    AllowedTools:   []string{"mcp__calculator__add"},
})
client.RegisterSDKMCPServer("calculator", server)

Hooks

Intercept and control tool execution:

// Create a hook to block dangerous commands
bashBlocker := func(ctx context.Context, input claude.HookInput, toolUseID string, hookCtx claude.HookContext) (*claude.HookOutput, error) {
    if preInput, ok := input.(claude.PreToolUseInput); ok {
        if cmd, ok := preInput.ToolInput["command"].(string); ok {
            if strings.Contains(cmd, "rm -rf") {
                return &claude.HookOutput{
                    PermissionDecision: claude.PermissionBehaviorDeny,
                    PermissionDecisionReason: "Dangerous command blocked",
                }, nil
            }
        }
    }
    return nil, nil
}

registry := claude.NewHookRegistry()
registry.Register(claude.HookEventPreToolUse, []claude.HookMatcher{
    {Matcher: "Bash", Hooks: []claude.HookCallback{bashBlocker}},
})

client := claude.New(&claude.AgentOptions{
    Hooks: registry,
})

Configuration Options (AgentOptions)

type AgentOptions struct {
    // Model configuration
    Model             string         // Model to use (e.g., "sonnet", "opus")
    MaxThinkingTokens int            // Maximum tokens for thinking

    // System prompt
    SystemPrompt string

    // Tool configuration
    AllowedTools    []string
    DisallowedTools []string

    // Permission handling
    PermissionMode PermissionMode // default, acceptEdits, plan, bypassPermissions

    // Resource limits
    MaxTurns     int
    MaxBudgetUSD float64

    // Session management
    Resume               string
    ContinueConversation bool

    // MCP servers
    MCPServers    MCPServers
    MCPConfigPath string

    // Hooks
    Hooks *HookRegistry

    // File management
    WorkingDirectory string
    AddDirectories   []string

    // Environment
    Environment map[string]string
    CLIPath     string

    // Debug
    Debug   bool
    Verbose bool
}

Structured Message Types

Parse typed messages from Claude:

msg, err := claude.ParseMessage(jsonData)

switch m := msg.(type) {
case claude.AssistantMessage:
    for _, block := range m.Content {
        switch b := block.(type) {
        case claude.TextBlock:
            fmt.Println(b.Text)
        case claude.ToolUseBlock:
            fmt.Printf("Tool: %s(%v)\n", b.Name, b.Input)
        }
    }
case claude.ResultMessage:
    fmt.Printf("Cost: $%.4f, Turns: %d\n", m.TotalCostUSD, m.NumTurns)
}

Error Handling

The SDK provides typed errors for precise error handling:

resp, err := client.Query(ctx, req)
if err != nil {
    switch {
    case claude.IsCLINotFound(err):
        log.Fatal("Install Claude CLI: npm install -g @anthropic-ai/claude-code")
    case claude.IsProcessError(err):
        log.Fatal("CLI process failed")
    case claude.IsCLIConnectionError(err):
        log.Fatal("Connection error")
    default:
        log.Fatal(err)
    }
}

Error types:

  • ClaudeSDKError - Base error type
  • CLINotFoundError - Claude CLI not installed
  • CLIConnectionError - Connection issues
  • ProcessError - CLI process failures
  • CLIJSONDecodeError - JSON parsing errors
  • MessageParseError - Message parsing errors
  • SessionClosedError - Using a closed session
  • ToolError - Tool execution failures
  • HookError - Hook execution failures

Session Management

Multi-turn Conversations
client := claude.New(&claude.AgentOptions{
    PermissionMode: claude.PermissionModeBypassPermission,
    Interactive:    true,
})

resp, _ := client.Query(ctx, &claude.QueryRequest{
    Prompt:    "My name is Alice. Remember this.",
    SessionID: "my-session",
})

// Continue the conversation
session, _ := client.GetSession("my-session")
session.SendMessage("What is my name?") // Claude remembers "Alice"
Concurrent Sessions
var wg sync.WaitGroup

for _, prompt := range prompts {
    wg.Add(1)
    go func(p string) {
        defer wg.Done()
        resp, _ := client.Query(ctx, &claude.QueryRequest{Prompt: p})
        for msg := range resp.Messages {
            fmt.Println(msg.Content)
        }
    }(prompt)
}

wg.Wait()

Examples

  • Basic Usage: examples/basic/main.go
  • Concurrent Processing: examples/concurrent/main.go
  • Interactive Session: examples/interactive/main.go
  • Custom MCP Tools: examples/mcp/main.go
  • Hooks: examples/hooks/main.go

Requirements

  • Go 1.21 or later
  • Claude CLI installed and accessible in PATH
  • Valid Claude authentication

CLI Discovery

The SDK automatically finds the Claude CLI in this order:

  1. CLAUDE_CLI_PATH environment variable
  2. Current working directory
  3. System PATH
  4. Common installation locations (npm, yarn, homebrew)

Authentication

# Using Claude CLI setup
claude setup-token

# Or set environment variable
export ANTHROPIC_API_KEY=your-api-key

Thread Safety

  • Multiple goroutines can create sessions concurrently
  • Sessions can be safely accessed from multiple goroutines
  • Proper cleanup handled with context cancellation
  • client.Close() safely shuts down all sessions

License

MIT License

Documentation

Overview

Package claude provides a Go SDK for automating Claude Code CLI with concurrent session management, real-time streaming, custom tools, and hooks. This is the Go equivalent of the Python Claude Agent SDK.

This library enables Go applications to interact with Claude Code CLI programmatically, supporting both single queries and multi-turn conversations with proper session management, file operations, and concurrent execution.

Quick Start - Simple Query

For one-shot queries without session management:

messages, err := claude.Query(ctx, "What is 2+2?", nil)
if err != nil {
	log.Fatal(err)
}
for _, msg := range messages {
	if text := claude.GetText(msg); text != "" {
		fmt.Println(text)
	}
}

Client-Based Usage

client := claude.New(&claude.AgentOptions{
	PermissionMode: claude.PermissionModeBypassPermission,
	Interactive:    false, // Use -p mode for simple queries
})
defer client.Close()

resp, err := client.Query(ctx, &claude.QueryRequest{
	Prompt: "Write a hello world function in Go",
})
if err != nil {
	log.Fatal(err)
}

for msg := range resp.Messages {
	fmt.Printf("%s: %s\n", msg.Type, msg.Content)
}

Multi-turn Conversations

client := claude.New(&claude.AgentOptions{
	PermissionMode: claude.PermissionModeBypassPermission,
	Interactive:    true, // Enable session persistence
})

resp, err := client.Query(ctx, &claude.QueryRequest{
	Prompt: "My name is Alice. Remember this.",
})

session, _ := client.GetSession(resp.SessionID)
session.SendMessage("What is my name?") // Claude will remember "Alice"

Concurrent Sessions

var wg sync.WaitGroup
for _, prompt := range prompts {
	wg.Add(1)
	go func(p string) {
		defer wg.Done()
		resp, _ := client.Query(ctx, &claude.QueryRequest{Prompt: p})
		// Process response...
	}(prompt)
}
wg.Wait()

Custom Tools (In-Process MCP Servers)

Define custom tools that run directly in your Go application:

// Create a tool using the builder pattern
addTool := claude.Tool("add", "Add two numbers").
	Param("a", "number", "First number").
	Param("b", "number", "Second number").
	Required("a", "b").
	HandlerFunc(func(ctx context.Context, args map[string]interface{}) (string, error) {
		a := args["a"].(float64)
		b := args["b"].(float64)
		return fmt.Sprintf("%g", a+b), nil
	})

// Create an SDK MCP server with your tools
server := claude.CreateSDKMCPServer("calculator", "1.0.0", addTool)

// Register with client
client := claude.New(&claude.AgentOptions{
	PermissionMode: claude.PermissionModeBypassPermission,
	AllowedTools:   []string{"mcp__calculator__add"},
})
client.RegisterSDKMCPServer("calculator", server)

Hooks

Intercept and control tool execution with hooks:

// Create a hook to block dangerous commands
bashBlocker := func(ctx context.Context, input claude.HookInput, toolUseID string, hookCtx claude.HookContext) (*claude.HookOutput, error) {
	if preInput, ok := input.(claude.PreToolUseInput); ok {
		if cmd, ok := preInput.ToolInput["command"].(string); ok {
			if strings.Contains(cmd, "rm -rf") {
				return &claude.HookOutput{
					PermissionDecision: claude.PermissionBehaviorDeny,
					PermissionDecisionReason: "Dangerous command blocked",
				}, nil
			}
		}
	}
	return nil, nil
}

registry := claude.NewHookRegistry()
registry.Register(claude.HookEventPreToolUse, []claude.HookMatcher{
	{Matcher: "Bash", Hooks: []claude.HookCallback{bashBlocker}},
})

client := claude.New(&claude.AgentOptions{
	Hooks: registry,
})

Structured Message Types

The SDK provides typed messages for parsing CLI JSON output:

// Parse JSON stream messages
msg, err := claude.ParseMessage(jsonData)

switch m := msg.(type) {
case claude.AssistantMessage:
	for _, block := range m.Content {
		switch b := block.(type) {
		case claude.TextBlock:
			fmt.Println(b.Text)
		case claude.ToolUseBlock:
			fmt.Printf("Tool: %s\n", b.Name)
		}
	}
case claude.ResultMessage:
	fmt.Printf("Cost: $%.4f\n", m.TotalCostUSD)
}

File Operations

client := claude.New(&claude.AgentOptions{
	PermissionMode:   claude.PermissionModeBypassPermission,
	Interactive:      true,
	WorkingDirectory: "/path/to/project",
	AddDirectories:   []string{"/path/to/project"},
})

resp, _ := client.Query(ctx, &claude.QueryRequest{
	Prompt: "Create a file called main.go with a hello world program",
})

Configuration Options (AgentOptions)

The AgentOptions struct provides extensive configuration matching the Python SDK's ClaudeAgentOptions:

  • Model: Specify Claude model ("sonnet", "opus", etc.)
  • MaxTurns: Maximum conversation turns
  • MaxThinkingTokens: Maximum tokens for thinking
  • MaxBudgetUSD: Maximum cost budget
  • SystemPrompt: Custom system prompt
  • Interactive: Enable persistent sessions vs single queries
  • PermissionMode: Control Claude's permission level
  • WorkingDirectory: Set working directory for Claude process
  • AddDirectories: Grant access to additional directories
  • AllowedTools/DisallowedTools: Control tool usage
  • MCPServers: Configure MCP servers
  • Hooks: Register hook callbacks
  • Sandbox: Configure sandbox settings
  • Resume/ContinueConversation: Session continuation
  • Environment: Set environment variables for Claude process
  • CLIPath: Custom path to Claude CLI

Error Handling

The SDK provides typed errors for precise error handling:

resp, err := client.Query(ctx, req)
if err != nil {
	switch {
	case claude.IsCLINotFound(err):
		log.Fatal("Install Claude CLI: npm install -g @anthropic-ai/claude-code")
	case claude.IsProcessError(err):
		log.Fatal("CLI process failed")
	default:
		log.Fatal(err)
	}
}

// Runtime errors
for err := range resp.Errors {
	log.Printf("Claude error: %v", err)
}

Error types include:

  • ClaudeSDKError: Base error type
  • CLINotFoundError: Claude CLI not installed
  • CLIConnectionError: Connection issues
  • ProcessError: CLI process failures
  • CLIJSONDecodeError: JSON parsing errors
  • MessageParseError: Message parsing errors
  • SessionClosedError: Using a closed session
  • ToolError: Tool execution failures
  • HookError: Hook execution failures

CLI Discovery

The SDK automatically finds the Claude CLI in this order:

  1. CLAUDE_CLI_PATH environment variable
  2. Current working directory
  3. System PATH
  4. Common installation locations (npm, yarn, homebrew)

Thread Safety

The library is designed to be thread-safe:

  • Multiple goroutines can create sessions concurrently
  • Sessions can be safely accessed from multiple goroutines
  • Proper cleanup is handled automatically with context cancellation
  • Client.Close() safely shuts down all sessions

Requirements

  • Go 1.21 or later
  • Claude CLI installed and accessible in PATH
  • Valid Claude authentication (API key or subscription)

Authentication

The library uses Claude CLI's existing authentication. Ensure Claude CLI is properly authenticated before using this library:

claude setup-token

Or set environment variables:

export ANTHROPIC_API_KEY=your-api-key

Index

Constants

View Source
const (
	// API Authentication
	EnvAnthropicAPIKey   = "ANTHROPIC_API_KEY"
	EnvClaudeCodeAPIKey  = "CLAUDE_CODE_API_KEY"
	EnvClaudeAPIKey      = "CLAUDE_API_KEY"
	EnvClaudeAccessToken = "CLAUDE_ACCESS_TOKEN"

	// API Endpoint Configuration
	EnvAnthropicBaseURL = "ANTHROPIC_BASE_URL"
	EnvClaudeAPIURL     = "CLAUDE_API_URL"
	EnvClaudeCodeAPIURL = "CLAUDE_CODE_API_URL"

	// Model Configuration
	EnvClaudeModel          = "CLAUDE_MODEL"
	EnvClaudeCodeModel      = "CLAUDE_CODE_MODEL"
	EnvClaudeSmallFastModel = "CLAUDE_CODE_SMALL_FAST_MODEL"
	EnvClaudeBigModel       = "CLAUDE_CODE_BIG_MODEL"

	// MinMax Configuration
	EnvMinMaxAPIKey    = "MINMAX_API_KEY"
	EnvMinMaxAuthToken = "ANTHROPIC_AUTH_TOKEN"

	// GLM Configuration
	EnvGLMAPIToken = "ANTHROPIC_AUTH_TOKEN"

	// Provider Selection
	EnvClaudeCodeUseBedrock = "CLAUDE_CODE_USE_BEDROCK"
	EnvClaudeCodeUseVertex  = "CLAUDE_CODE_USE_VERTEX"

	// AWS Bedrock Configuration
	EnvAWSRegion            = "AWS_REGION"
	EnvAWSDefaultRegion     = "AWS_DEFAULT_REGION"
	EnvAWSAccessKeyID       = "AWS_ACCESS_KEY_ID"
	EnvAWSSecretAccessKey   = "AWS_SECRET_ACCESS_KEY"
	EnvAWSSessionToken      = "AWS_SESSION_TOKEN"
	EnvAWSProfile           = "AWS_PROFILE"
	EnvBedrockEndpointURL   = "BEDROCK_ENDPOINT_URL"
	EnvBedrockCrossRegion   = "BEDROCK_CROSS_REGION"
	EnvBedrockPromptCaching = "BEDROCK_PROMPT_CACHING"

	// Google Vertex AI Configuration
	EnvVertexProject  = "ANTHROPIC_VERTEX_PROJECT_ID"
	EnvVertexRegion   = "ANTHROPIC_VERTEX_REGION"
	EnvVertexLocation = "CLOUD_ML_REGION"
	EnvGoogleProject  = "GOOGLE_CLOUD_PROJECT"
	EnvGoogleRegion   = "GOOGLE_CLOUD_REGION"

	// OAuth / Authentication
	EnvClaudeCodeSkipOAuth    = "CLAUDE_CODE_SKIP_OAUTH"
	EnvClaudeCodeDisableOAuth = "CLAUDE_CODE_DISABLE_OAUTH"
	EnvClaudeCodeTokens       = "CLAUDE_CODE_TOKENS"

	// Proxy Configuration
	EnvHTTPProxy  = "HTTP_PROXY"
	EnvHTTPSProxy = "HTTPS_PROXY"
	EnvNoProxy    = "NO_PROXY"

	// Runtime Configuration
	EnvClaudeCodeMaxTokens     = "CLAUDE_CODE_MAX_TOKENS"
	EnvClaudeCodeMaxTurns      = "CLAUDE_CODE_MAX_TURNS"
	EnvClaudeCodeTimeout       = "CLAUDE_CODE_TIMEOUT"
	EnvClaudeCodeMaxBudgetUSD  = "CLAUDE_CODE_MAX_BUDGET_USD"
	EnvClaudeCodeDebug         = "CLAUDE_CODE_DEBUG"
	EnvClaudeCodeVerbose       = "CLAUDE_CODE_VERBOSE"
	EnvClaudeCodeNoTelemetry   = "CLAUDE_CODE_NO_TELEMETRY"
	EnvClaudeCodeEntrypoint    = "CLAUDE_CODE_ENTRYPOINT"
	EnvClaudeCodeSkipPermcheck = "CLAUDE_CODE_SKIP_PERMCHECK"
)

Environment variable names for Claude Code configuration.

View Source
const (
	ModelClaude4Opus   = "claude-opus-4-20250514"
	ModelClaude45Opus  = "claude-opus-4-5-20251101"
	ModelClaude4Sonnet = "claude-sonnet-4-20250514"
	ModelClaude35Haiku = "claude-3-5-haiku-20241022"

	// Shorthand aliases
	ModelOpus   = "opus"
	ModelSonnet = "sonnet"
	ModelHaiku  = "haiku"

	// GLM (ChatGLM/Zhipu AI) models
	ModelGLM4     = "glm-4"
	ModelGLM4Plus = "glm-4-plus"
	ModelGLM3_5   = "glm-3-5-turbo"

	// MinMax models
	ModelMinMaxABAB6_5Chat = "minimax-abab6.5-chat"
	ModelMinMaxABAB6Chat   = "minimax-abab6-chat"
)

Standard model identifiers for convenience.

View Source
const (
	DefaultSmallFastModel = ModelClaude35Haiku
	DefaultModel          = ModelClaude4Sonnet
	DefaultBigModel       = ModelClaude45Opus
)

Model tier defaults

Variables

This section is empty.

Functions

func BuildCLIArgs added in v1.1.0

func BuildCLIArgs(opts *AgentOptions) []string

BuildCLIArgs builds command-line arguments for the Claude CLI.

func BuildCLIEnv added in v1.1.0

func BuildCLIEnv(opts *AgentOptions) []string

BuildCLIEnv builds environment variables for the Claude CLI subprocess. This merges the provided options with the current process environment.

func FindCLI added in v1.1.0

func FindCLI() (string, error)

FindCLI searches for the Claude CLI in standard locations.

func GetText added in v1.1.0

func GetText(msg MessageType) string

GetText extracts text content from a message.

func IsCLIConnectionError added in v1.1.0

func IsCLIConnectionError(err error) bool

IsCLIConnectionError checks if the error is a CLIConnectionError.

func IsCLINotFound added in v1.1.0

func IsCLINotFound(err error) bool

IsCLINotFound checks if the error is a CLINotFoundError.

func IsHookError added in v1.1.0

func IsHookError(err error) bool

IsHookError checks if the error is a HookError.

func IsJSONDecodeError added in v1.1.0

func IsJSONDecodeError(err error) bool

IsJSONDecodeError checks if the error is a CLIJSONDecodeError.

func IsMessageParseError added in v1.1.0

func IsMessageParseError(err error) bool

IsMessageParseError checks if the error is a MessageParseError.

func IsProcessError added in v1.1.0

func IsProcessError(err error) bool

IsProcessError checks if the error is a ProcessError.

func IsSessionClosedError added in v1.1.0

func IsSessionClosedError(err error) bool

IsSessionClosedError checks if the error is a SessionClosedError.

func IsToolError added in v1.1.0

func IsToolError(err error) bool

IsToolError checks if the error is a ToolError.

Types

type APIProvider added in v1.1.0

type APIProvider string

APIProvider represents the cloud provider for the Claude API.

const (
	APIProviderAnthropic APIProvider = "anthropic"
	APIProviderBedrock   APIProvider = "bedrock"
	APIProviderVertex    APIProvider = "vertex"
	APIProviderGLM       APIProvider = "glm"    // ChatGLM / Zhipu AI
	APIProviderMinMax    APIProvider = "minmax" // MiniMax
)

type AgentDefinition added in v1.1.0

type AgentDefinition struct {
	Description string   `json:"description"`
	Prompt      string   `json:"prompt"`
	Tools       []string `json:"tools,omitempty"`
	Model       string   `json:"model,omitempty"`
}

AgentDefinition defines a custom agent.

type AgentOptions added in v1.1.0

type AgentOptions struct {
	// API Authentication
	APIKey      string `json:"api_key,omitempty"`
	AccessToken string `json:"access_token,omitempty"`

	// API Endpoint Configuration
	BaseURL string `json:"base_url,omitempty"`

	// Provider Selection (anthropic, bedrock, vertex)
	Provider APIProvider `json:"provider,omitempty"`

	// Model configuration
	Model             string `json:"model,omitempty"`
	SmallFastModel    string `json:"small_fast_model,omitempty"` // Haiku-class model
	BigModel          string `json:"big_model,omitempty"`        // Opus-class model
	MaxThinkingTokens int    `json:"max_thinking_tokens,omitempty"`
	MaxTokens         int    `json:"max_tokens,omitempty"` // Max output tokens

	// System prompt
	SystemPrompt string `json:"system_prompt,omitempty"`

	// Tool configuration
	AllowedTools    []string `json:"allowed_tools,omitempty"`
	DisallowedTools []string `json:"disallowed_tools,omitempty"`

	// Permission handling
	PermissionMode PermissionMode `json:"permission_mode,omitempty"`

	// Resource limits
	MaxTurns     int     `json:"max_turns,omitempty"`
	MaxBudgetUSD float64 `json:"max_budget_usd,omitempty"`
	TimeoutSecs  int     `json:"timeout_secs,omitempty"`

	// Session management
	Resume               string `json:"resume,omitempty"`
	ContinueConversation bool   `json:"continue_conversation,omitempty"`
	ForkSession          string `json:"fork_session,omitempty"`

	// MCP servers
	MCPServers    MCPServers `json:"-"`
	MCPConfigPath string     `json:"mcp_config,omitempty"`

	// Hooks
	Hooks *HookRegistry `json:"-"`

	// Plugins
	Plugins map[string]SDKPluginConfig `json:"plugins,omitempty"`

	// Agent definitions
	Agents map[string]AgentDefinition `json:"agents,omitempty"`

	// Sandbox settings
	Sandbox *SandboxSettings `json:"sandbox,omitempty"`

	// File management
	FileCheckpoints  bool     `json:"file_checkpoints,omitempty"`
	AddDirectories   []string `json:"add_directories,omitempty"`
	WorkingDirectory string   `json:"working_directory,omitempty"`

	// AWS Bedrock Configuration
	Bedrock *BedrockConfig `json:"bedrock,omitempty"`

	// Google Vertex Configuration
	Vertex *VertexConfig `json:"vertex,omitempty"`

	// Proxy Configuration
	Proxy *ProxyConfig `json:"proxy,omitempty"`

	// Environment variables (passed to CLI subprocess)
	Environment map[string]string `json:"environment,omitempty"`

	// CLI configuration
	CLIPath string `json:"cli_path,omitempty"`

	// Behavior flags
	Debug       bool `json:"debug,omitempty"`
	Verbose     bool `json:"verbose,omitempty"`
	NoTelemetry bool `json:"no_telemetry,omitempty"`
	SkipOAuth   bool `json:"skip_oauth,omitempty"`

	// Output configuration
	OutputFormat string `json:"output_format,omitempty"` // text, json, stream-json

	// Legacy: Interactive mode (for backward compatibility)
	Interactive bool `json:"interactive,omitempty"`
}

AgentOptions provides comprehensive configuration for Claude agents. This is the Go equivalent of Python's ClaudeAgentOptions.

type AssistantMessage added in v1.1.0

type AssistantMessage struct {
	Type            string          `json:"type"` // Always "assistant"
	UUID            string          `json:"uuid,omitempty"`
	Content         []ContentBlock  `json:"-"`
	RawContent      json.RawMessage `json:"content,omitempty"`
	Model           string          `json:"model,omitempty"`
	ParentToolUseID string          `json:"parent_tool_use_id,omitempty"`
	IsError         bool            `json:"is_error,omitempty"`
}

AssistantMessage represents a message from Claude.

type BaseHookInput added in v1.1.0

type BaseHookInput struct {
	SessionID      string `json:"session_id"`
	TranscriptPath string `json:"transcript_path,omitempty"`
	WorkingDir     string `json:"cwd,omitempty"`
}

BaseHookInput contains common fields for all hook inputs.

type BedrockConfig added in v1.1.0

type BedrockConfig struct {
	Region            string `json:"region,omitempty"`
	EndpointURL       string `json:"endpoint_url,omitempty"`
	AccessKeyID       string `json:"access_key_id,omitempty"`
	SecretAccessKey   string `json:"secret_access_key,omitempty"`
	SessionToken      string `json:"session_token,omitempty"`
	Profile           string `json:"profile,omitempty"`
	CrossRegion       bool   `json:"cross_region,omitempty"`
	PromptCaching     bool   `json:"prompt_caching,omitempty"`
	PromptCacheTypes  string `json:"prompt_cache_types,omitempty"`
	UseStreamingTypes bool   `json:"use_streaming_types,omitempty"`
}

BedrockConfig holds AWS Bedrock-specific configuration.

type CLIConnectionError added in v1.1.0

type CLIConnectionError struct {
	ClaudeSDKError
}

CLIConnectionError is raised when unable to connect to Claude Code.

func NewCLIConnectionError added in v1.1.0

func NewCLIConnectionError(message string, cause error) *CLIConnectionError

NewCLIConnectionError creates a new CLIConnectionError.

type CLIJSONDecodeError added in v1.1.0

type CLIJSONDecodeError struct {
	ClaudeSDKError
	Line string
}

CLIJSONDecodeError is raised when unable to decode JSON from CLI output.

func NewCLIJSONDecodeError added in v1.1.0

func NewCLIJSONDecodeError(message string, line string, cause error) *CLIJSONDecodeError

NewCLIJSONDecodeError creates a new CLIJSONDecodeError.

func (*CLIJSONDecodeError) Error added in v1.1.0

func (e *CLIJSONDecodeError) Error() string

type CLINotFoundError added in v1.1.0

type CLINotFoundError struct {
	CLIConnectionError
	CLIPath string
}

CLINotFoundError is raised when Claude Code is not found or not installed.

func NewCLINotFoundError added in v1.1.0

func NewCLINotFoundError(message string, cliPath string) *CLINotFoundError

NewCLINotFoundError creates a new CLINotFoundError.

func (*CLINotFoundError) Error added in v1.1.0

func (e *CLINotFoundError) Error() string

type ClaudeSDKError added in v1.1.0

type ClaudeSDKError struct {
	Message string
	Cause   error
}

ClaudeSDKError is the base error type for all Claude SDK errors.

func NewClaudeSDKError added in v1.1.0

func NewClaudeSDKError(message string, cause error) *ClaudeSDKError

NewClaudeSDKError creates a new ClaudeSDKError.

func (*ClaudeSDKError) Error added in v1.1.0

func (e *ClaudeSDKError) Error() string

func (*ClaudeSDKError) Unwrap added in v1.1.0

func (e *ClaudeSDKError) Unwrap() error

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client manages Claude sessions and queries.

func New

func New(opts *AgentOptions) *Client

New creates a new Client with the given options.

func (*Client) Close

func (c *Client) Close() error

Close closes all sessions and cleans up resources.

func (*Client) CloseSession

func (c *Client) CloseSession(sessionID string) error

CloseSession closes a specific session.

func (*Client) GetSession

func (c *Client) GetSession(sessionID string) (*Session, bool)

GetSession retrieves an active session by ID.

func (*Client) Query

func (c *Client) Query(ctx context.Context, req *QueryRequest) (*QueryResponse, error)

Query sends a prompt to Claude and returns a response channel.

func (*Client) RegisterMCPServer added in v1.1.0

func (c *Client) RegisterMCPServer(name string, config MCPServerConfig)

RegisterMCPServer registers an MCP server with the client.

func (*Client) RegisterSDKMCPServer added in v1.1.0

func (c *Client) RegisterSDKMCPServer(name string, server *SDKMCPServer)

RegisterSDKMCPServer registers an in-process MCP server.

type Config added in v1.1.0

type Config struct {
	// API Authentication
	APIKey      string `json:"api_key,omitempty"`
	AccessToken string `json:"access_token,omitempty"`

	// API Endpoint
	BaseURL string `json:"base_url,omitempty"`

	// Provider Selection
	Provider APIProvider `json:"provider,omitempty"`

	// Model Configuration
	Model          string `json:"model,omitempty"`
	SmallFastModel string `json:"small_fast_model,omitempty"`
	BigModel       string `json:"big_model,omitempty"`

	// AWS Bedrock Configuration
	Bedrock *BedrockConfig `json:"bedrock,omitempty"`

	// Google Vertex Configuration
	Vertex *VertexConfig `json:"vertex,omitempty"`

	// Proxy Configuration
	Proxy *ProxyConfig `json:"proxy,omitempty"`

	// Runtime Limits
	MaxTokens    int     `json:"max_tokens,omitempty"`
	MaxTurns     int     `json:"max_turns,omitempty"`
	TimeoutSecs  int     `json:"timeout_secs,omitempty"`
	MaxBudgetUSD float64 `json:"max_budget_usd,omitempty"`

	// Behavior Flags
	Debug       bool `json:"debug,omitempty"`
	Verbose     bool `json:"verbose,omitempty"`
	NoTelemetry bool `json:"no_telemetry,omitempty"`
	SkipOAuth   bool `json:"skip_oauth,omitempty"`

	// CLI Path
	CLIPath string `json:"cli_path,omitempty"`
}

Config holds all configuration options for the Claude SDK. It can be populated from environment variables, code, or both.

func LoadConfigFromEnv added in v1.1.0

func LoadConfigFromEnv() *Config

LoadConfigFromEnv creates a Config populated from environment variables. Values can be overridden programmatically after loading.

func NewConfigFromOptions added in v1.1.0

func NewConfigFromOptions(opts *AgentOptions) *Config

NewConfigFromOptions creates a Config from AgentOptions. This is useful for round-tripping between the two formats.

func (*Config) Merge added in v1.1.0

func (c *Config) Merge(other *Config) *Config

Merge combines two configs, with the other config taking precedence.

func (*Config) ToAgentOptions added in v1.1.0

func (c *Config) ToAgentOptions() *AgentOptions

ToAgentOptions converts Config to AgentOptions for use with the SDK.

type ContentBlock added in v1.1.0

type ContentBlock interface {
	// contains filtered or unexported methods
}

ContentBlock represents the content of a message. It can be one of: TextBlock, ThinkingBlock, ToolUseBlock, or ToolResultBlock.

func ParseContentBlock added in v1.1.0

func ParseContentBlock(raw json.RawMessage) (ContentBlock, error)

ParseContentBlock parses a raw JSON content block into the appropriate type.

func ParseContentBlocks added in v1.1.0

func ParseContentBlocks(raw json.RawMessage) ([]ContentBlock, error)

ParseContentBlocks parses an array of raw JSON content blocks.

type HookCallback added in v1.1.0

type HookCallback func(ctx context.Context, input HookInput, toolUseID string, hookCtx HookContext) (*HookOutput, error)

HookCallback is the function signature for hook callbacks. ctx provides context for the hook execution. input is the event-specific input data. toolUseID is the ID of the tool use (only for tool-related hooks). hookCtx provides additional context information.

func AddContext added in v1.1.0

func AddContext(contextStr string) HookCallback

AddContext creates a hook that adds context to the prompt.

func AllowTool added in v1.1.0

func AllowTool() HookCallback

AllowTool creates a hook that allows a specific tool.

func DenyTool added in v1.1.0

func DenyTool(reason string) HookCallback

DenyTool creates a hook that denies a specific tool.

func StopExecution added in v1.1.0

func StopExecution(reason string) HookCallback

StopExecution creates a hook that stops execution.

type HookContext added in v1.1.0

type HookContext struct {
	SessionID      string
	TranscriptPath string
	WorkingDir     string
}

HookContext provides context information for hook callbacks.

type HookError added in v1.1.0

type HookError struct {
	ClaudeSDKError
	HookEvent string
	ToolName  string
}

HookError is raised when a hook fails to execute.

func NewHookError added in v1.1.0

func NewHookError(message string, hookEvent string, toolName string, cause error) *HookError

NewHookError creates a new HookError.

func (*HookError) Error added in v1.1.0

func (e *HookError) Error() string

type HookEvent added in v1.1.0

type HookEvent string

HookEvent represents the type of hook event.

const (
	HookEventPreToolUse       HookEvent = "PreToolUse"
	HookEventPostToolUse      HookEvent = "PostToolUse"
	HookEventUserPromptSubmit HookEvent = "UserPromptSubmit"
	HookEventStop             HookEvent = "Stop"
	HookEventSubagentStop     HookEvent = "SubagentStop"
	HookEventPreCompact       HookEvent = "PreCompact"
)

type HookInput added in v1.1.0

type HookInput interface {
	// contains filtered or unexported methods
}

HookInput is a union type for all hook inputs.

func ParseHookInput added in v1.1.0

func ParseHookInput(event HookEvent, raw json.RawMessage) (HookInput, error)

ParseHookInput parses raw JSON into the appropriate HookInput type.

type HookMatcher added in v1.1.0

type HookMatcher struct {
	// Matcher is the pattern to match against tool names.
	// Can be "*" to match all, or a specific tool name.
	// For non-tool hooks, this is typically empty or "*".
	Matcher string

	// Hooks are the callbacks to execute when this matcher matches.
	Hooks []HookCallback

	// TimeoutMS is the timeout for hook execution in milliseconds.
	// If 0, a default timeout is used.
	TimeoutMS int
}

HookMatcher defines a pattern for matching hook events.

type HookOutput added in v1.1.0

type HookOutput struct {
	// For PreToolUse hooks
	PermissionDecision       PermissionBehavior     `json:"permissionDecision,omitempty"`
	PermissionDecisionReason string                 `json:"permissionDecisionReason,omitempty"`
	UpdatedInput             map[string]interface{} `json:"updatedInput,omitempty"`

	// For PostToolUse hooks
	Feedback      string `json:"feedback,omitempty"`
	SystemMessage string `json:"systemMessage,omitempty"`

	// For UserPromptSubmit hooks
	UpdatedPrompt string `json:"updatedPrompt,omitempty"`
	Context       string `json:"context,omitempty"`

	// For all hooks
	Continue   *bool  `json:"continue,omitempty"`
	StopReason string `json:"stopReason,omitempty"`

	// For async hooks
	Async   bool   `json:"async,omitempty"`
	AsyncID string `json:"asyncId,omitempty"`
}

HookOutput contains the response from a hook callback.

type HookRegistry added in v1.1.0

type HookRegistry struct {
	// contains filtered or unexported fields
}

HookRegistry manages hook registrations.

func NewHookRegistry added in v1.1.0

func NewHookRegistry() *HookRegistry

NewHookRegistry creates a new HookRegistry.

func (*HookRegistry) ExecuteHooks added in v1.1.0

func (r *HookRegistry) ExecuteHooks(ctx context.Context, event HookEvent, input HookInput, toolUseID string, hookCtx HookContext) (*HookOutput, error)

ExecuteHooks executes all matching hooks for an event.

func (*HookRegistry) GetMatchers added in v1.1.0

func (r *HookRegistry) GetMatchers(event HookEvent) []HookMatcher

GetMatchers returns the matchers for a specific event type.

func (*HookRegistry) Register added in v1.1.0

func (r *HookRegistry) Register(event HookEvent, matchers []HookMatcher)

Register registers hooks for a specific event type.

type Hooks added in v1.1.0

type Hooks map[HookEvent][]HookMatcher

Hooks is a map of hook events to their matchers, used for configuration.

func (Hooks) ToRegistry added in v1.1.0

func (h Hooks) ToRegistry() *HookRegistry

ToRegistry converts a Hooks map to a HookRegistry.

type MCPHTTPServerConfig added in v1.1.0

type MCPHTTPServerConfig struct {
	Type    MCPServerType     `json:"type"` // Always "http"
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
}

MCPHTTPServerConfig configures an MCP server using HTTP.

func (MCPHTTPServerConfig) GetType added in v1.1.0

type MCPSDKServerConfig added in v1.1.0

type MCPSDKServerConfig struct {
	Type   MCPServerType `json:"type"` // Always "sdk"
	Server *SDKMCPServer `json:"-"`
}

MCPSDKServerConfig wraps an in-process SDK MCP server.

func (MCPSDKServerConfig) GetType added in v1.1.0

type MCPSSEServerConfig added in v1.1.0

type MCPSSEServerConfig struct {
	Type    MCPServerType     `json:"type"` // Always "sse"
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
}

MCPSSEServerConfig configures an MCP server using Server-Sent Events.

func (MCPSSEServerConfig) GetType added in v1.1.0

type MCPServerConfig added in v1.1.0

type MCPServerConfig interface {
	GetType() MCPServerType
	// contains filtered or unexported methods
}

MCPServerConfig is the interface for all MCP server configurations.

type MCPServerManager added in v1.1.0

type MCPServerManager struct {
	// contains filtered or unexported fields
}

MCPServerManager manages MCP server instances.

func NewMCPServerManager added in v1.1.0

func NewMCPServerManager() *MCPServerManager

NewMCPServerManager creates a new MCP server manager.

func (*MCPServerManager) AllowedToolNames added in v1.1.0

func (m *MCPServerManager) AllowedToolNames() []string

AllowedToolNames returns tool names in the format expected by the CLI. For SDK servers, returns "mcp__<server>__<tool>" format.

func (*MCPServerManager) ExecuteSDKTool added in v1.1.0

func (m *MCPServerManager) ExecuteSDKTool(ctx context.Context, serverName, toolName string, args map[string]interface{}) (*ToolResult, error)

ExecuteSDKTool executes a tool on an SDK server.

func (*MCPServerManager) Get added in v1.1.0

func (m *MCPServerManager) Get(name string) (MCPServerConfig, bool)

Get returns an MCP server configuration by name.

func (*MCPServerManager) GetAllSDKTools added in v1.1.0

func (m *MCPServerManager) GetAllSDKTools() map[string]*ToolDefinition

GetAllSDKTools returns all tools from all SDK servers.

func (*MCPServerManager) GetSDKServer added in v1.1.0

func (m *MCPServerManager) GetSDKServer(name string) (*SDKMCPServer, bool)

GetSDKServer returns an SDK MCP server by name.

func (*MCPServerManager) Register added in v1.1.0

func (m *MCPServerManager) Register(name string, config MCPServerConfig)

Register registers an MCP server.

func (*MCPServerManager) RegisterSDKServer added in v1.1.0

func (m *MCPServerManager) RegisterSDKServer(name string, server *SDKMCPServer)

RegisterSDKServer registers an SDK MCP server.

func (*MCPServerManager) ToJSON added in v1.1.0

func (m *MCPServerManager) ToJSON() (json.RawMessage, error)

ToJSON returns a JSON representation of the servers for CLI configuration.

type MCPServerType added in v1.1.0

type MCPServerType string

MCPServerType defines the type of MCP server.

const (
	MCPServerTypeStdio MCPServerType = "stdio"
	MCPServerTypeSSE   MCPServerType = "sse"
	MCPServerTypeHTTP  MCPServerType = "http"
	MCPServerTypeSDK   MCPServerType = "sdk"
)

type MCPServers added in v1.1.0

type MCPServers map[string]MCPServerConfig

MCPServers is a map of server names to their configurations.

type MCPStdioServerConfig added in v1.1.0

type MCPStdioServerConfig struct {
	Type    MCPServerType     `json:"type"` // Always "stdio"
	Command string            `json:"command"`
	Args    []string          `json:"args,omitempty"`
	Env     map[string]string `json:"env,omitempty"`
}

MCPStdioServerConfig configures an MCP server running as a subprocess.

func (MCPStdioServerConfig) GetType added in v1.1.0

type Message

type Message struct {
	Type      string          `json:"type"`
	Content   string          `json:"content,omitempty"`
	Role      string          `json:"role,omitempty"`
	Timestamp time.Time       `json:"timestamp"`
	Metadata  json.RawMessage `json:"metadata,omitempty"`
	Error     string          `json:"error,omitempty"`
}

Message represents a streaming message from Claude. For structured messages, use the typed message types (AssistantMessage, etc.)

type MessageParseError added in v1.1.0

type MessageParseError struct {
	ClaudeSDKError
	Data json.RawMessage
}

MessageParseError is raised when unable to parse a message from CLI output.

func NewMessageParseError added in v1.1.0

func NewMessageParseError(message string, data json.RawMessage, cause error) *MessageParseError

NewMessageParseError creates a new MessageParseError.

func (*MessageParseError) Error added in v1.1.0

func (e *MessageParseError) Error() string

type MessageType added in v1.1.0

type MessageType interface {
	// contains filtered or unexported methods
}

Message is the interface for all message types.

func ParseMessage added in v1.1.0

func ParseMessage(raw json.RawMessage) (MessageType, error)

ParseMessage parses a raw JSON message into the appropriate message type.

func Query added in v1.1.0

func Query(ctx context.Context, prompt string, opts *AgentOptions) ([]MessageType, error)

Query is a simple function for one-shot queries. It creates a client, sends the prompt, collects all messages, and returns them.

type ModelTier added in v1.1.0

type ModelTier string

ModelTier represents different model quality/speed tiers.

const (
	ModelTierDefault   ModelTier = ""
	ModelTierSmallFast ModelTier = "small-fast" // Haiku-class
	ModelTierDefault_  ModelTier = "default"    // Sonnet-class
	ModelTierBig       ModelTier = "big"        // Opus-class
)

type Options

type Options = AgentOptions

Options is an alias for backward compatibility. Deprecated: Use AgentOptions instead.

type PermissionBehavior added in v1.1.0

type PermissionBehavior string

PermissionBehavior defines the behavior for a permission decision.

const (
	PermissionBehaviorAllow PermissionBehavior = "allow"
	PermissionBehaviorDeny  PermissionBehavior = "deny"
	PermissionBehaviorAsk   PermissionBehavior = "ask"
)

type PermissionMode added in v1.1.0

type PermissionMode string

PermissionMode defines how permissions are handled.

const (
	PermissionModeDefault          PermissionMode = "default"
	PermissionModeAcceptEdits      PermissionMode = "acceptEdits"
	PermissionModePlan             PermissionMode = "plan"
	PermissionModeBypassPermission PermissionMode = "bypassPermissions"
)

type PostToolUseInput added in v1.1.0

type PostToolUseInput struct {
	BaseHookInput
	ToolName   string                 `json:"tool_name"`
	ToolInput  map[string]interface{} `json:"tool_input"`
	ToolResult interface{}            `json:"tool_result"`
	IsError    bool                   `json:"is_error,omitempty"`
}

PostToolUseInput is the input for PostToolUse hooks.

type PreCompactInput added in v1.1.0

type PreCompactInput struct {
	BaseHookInput
	TokenCount int `json:"token_count"`
}

PreCompactInput is the input for PreCompact hooks.

type PreToolUseInput added in v1.1.0

type PreToolUseInput struct {
	BaseHookInput
	ToolName  string                 `json:"tool_name"`
	ToolInput map[string]interface{} `json:"tool_input"`
}

PreToolUseInput is the input for PreToolUse hooks.

type ProcessError added in v1.1.0

type ProcessError struct {
	ClaudeSDKError
	ExitCode int
	Stderr   string
}

ProcessError is raised when the CLI process fails.

func NewProcessError added in v1.1.0

func NewProcessError(message string, exitCode int, stderr string, cause error) *ProcessError

NewProcessError creates a new ProcessError.

func (*ProcessError) Error added in v1.1.0

func (e *ProcessError) Error() string

type PropertySchema added in v1.1.0

type PropertySchema struct {
	Type        string          `json:"type"`
	Description string          `json:"description,omitempty"`
	Enum        []string        `json:"enum,omitempty"`
	Default     any             `json:"default,omitempty"`
	Items       *PropertySchema `json:"items,omitempty"` // For array types
}

PropertySchema defines a property in a tool schema.

type ProxyConfig added in v1.1.0

type ProxyConfig struct {
	HTTPProxy  string `json:"http_proxy,omitempty"`
	HTTPSProxy string `json:"https_proxy,omitempty"`
	NoProxy    string `json:"no_proxy,omitempty"`
}

ProxyConfig holds HTTP proxy configuration.

type QueryIterator added in v1.1.0

type QueryIterator struct {
	// contains filtered or unexported fields
}

QueryIterator returns an iterator for streaming messages from a one-shot query.

func NewQueryIterator added in v1.1.0

func NewQueryIterator(ctx context.Context, prompt string, opts *AgentOptions) (*QueryIterator, error)

NewQueryIterator creates a new query iterator.

func (*QueryIterator) Close added in v1.1.0

func (q *QueryIterator) Close() error

Close closes the iterator and releases resources.

func (*QueryIterator) Errors added in v1.1.0

func (q *QueryIterator) Errors() <-chan error

Errors returns a channel for receiving errors.

func (*QueryIterator) Messages added in v1.1.0

func (q *QueryIterator) Messages() <-chan MessageType

Messages returns a channel for receiving messages.

func (*QueryIterator) Next added in v1.1.0

func (q *QueryIterator) Next() (MessageType, error)

Next returns the next message or nil if done.

type QueryRequest

type QueryRequest struct {
	Prompt    string        `json:"prompt"`
	Options   *AgentOptions `json:"options,omitempty"`
	SessionID string        `json:"session_id,omitempty"`
}

QueryRequest defines the input for a query.

type QueryResponse

type QueryResponse struct {
	SessionID string        `json:"session_id"`
	Messages  chan *Message `json:"-"`
	Errors    chan error    `json:"-"`
}

QueryResponse provides channels for receiving query results.

type ResultMessage added in v1.1.0

type ResultMessage struct {
	Type             string                 `json:"type"` // Always "result"
	DurationMS       int64                  `json:"duration_ms"`
	DurationAPIMS    int64                  `json:"duration_api_ms,omitempty"`
	IsError          bool                   `json:"is_error"`
	NumTurns         int                    `json:"num_turns"`
	SessionID        string                 `json:"session_id"`
	TotalCostUSD     float64                `json:"total_cost_usd,omitempty"`
	Usage            *Usage                 `json:"usage,omitempty"`
	Result           string                 `json:"result,omitempty"`
	StructuredOutput map[string]interface{} `json:"structured_output,omitempty"`
}

ResultMessage contains metadata about the completed interaction.

type SDKMCPServer added in v1.1.0

type SDKMCPServer struct {
	// contains filtered or unexported fields
}

SDKMCPServer is an in-process MCP server.

func CreateSDKMCPServer added in v1.1.0

func CreateSDKMCPServer(name, version string, tools ...*ToolDefinition) *SDKMCPServer

CreateSDKMCPServer creates an in-process MCP server with the given tools. This is the Go equivalent of Python's create_sdk_mcp_server().

func NewSDKMCPServer added in v1.1.0

func NewSDKMCPServer(name, version string) *SDKMCPServer

NewSDKMCPServer creates a new in-process MCP server.

func (*SDKMCPServer) ExecuteTool added in v1.1.0

func (s *SDKMCPServer) ExecuteTool(ctx context.Context, name string, args map[string]interface{}) (*ToolResult, error)

ExecuteTool executes a tool by name with the given arguments.

func (*SDKMCPServer) GetTool added in v1.1.0

func (s *SDKMCPServer) GetTool(name string) (*ToolDefinition, bool)

GetTool returns a tool by name.

func (*SDKMCPServer) ListTools added in v1.1.0

func (s *SDKMCPServer) ListTools() []*ToolDefinition

ListTools returns all registered tools.

func (*SDKMCPServer) Name added in v1.1.0

func (s *SDKMCPServer) Name() string

Name returns the server name.

func (*SDKMCPServer) RegisterTool added in v1.1.0

func (s *SDKMCPServer) RegisterTool(tool *ToolDefinition)

RegisterTool registers a tool with the server.

func (*SDKMCPServer) ToConfig added in v1.1.0

func (s *SDKMCPServer) ToConfig() MCPSDKServerConfig

ToConfig returns an MCPSDKServerConfig for this server.

func (*SDKMCPServer) Version added in v1.1.0

func (s *SDKMCPServer) Version() string

Version returns the server version.

type SDKPluginConfig added in v1.1.0

type SDKPluginConfig struct {
	Type     string `json:"type"` // Always "local"
	FilePath string `json:"file_path"`
}

SDKPluginConfig defines a local SDK plugin.

type SandboxIgnoreViolations added in v1.1.0

type SandboxIgnoreViolations struct {
	FilePaths    []string `json:"file_paths,omitempty"`
	NetworkHosts []string `json:"network_hosts,omitempty"`
}

SandboxIgnoreViolations configures violations to ignore in sandbox mode.

type SandboxNetworkConfig added in v1.1.0

type SandboxNetworkConfig struct {
	UnixSockets  []string `json:"unix_sockets,omitempty"`
	LocalBinding bool     `json:"local_binding,omitempty"`
	ProxyPorts   []int    `json:"proxy_ports,omitempty"`
}

SandboxNetworkConfig configures network access in sandbox mode.

type SandboxSettings added in v1.1.0

type SandboxSettings struct {
	Enabled          bool                     `json:"enabled,omitempty"`
	AutoApprove      bool                     `json:"auto_approve,omitempty"`
	ExcludedCommands []string                 `json:"excluded_commands,omitempty"`
	Network          *SandboxNetworkConfig    `json:"network,omitempty"`
	IgnoreViolations *SandboxIgnoreViolations `json:"ignore_violations,omitempty"`
}

SandboxSettings configures sandbox behavior.

type Session

type Session struct {
	ID string
	// contains filtered or unexported fields
}

Session represents an active Claude CLI session.

func (*Session) Close

func (s *Session) Close() error

Close closes the session and releases resources.

func (*Session) SendMessage

func (s *Session) SendMessage(content string) error

SendMessage sends a follow-up message in the session.

func (*Session) Wait

func (s *Session) Wait() error

Wait waits for the session to complete.

type SessionClosedError added in v1.1.0

type SessionClosedError struct {
	ClaudeSDKError
	SessionID string
}

SessionClosedError is raised when trying to use a closed session.

func NewSessionClosedError added in v1.1.0

func NewSessionClosedError(sessionID string) *SessionClosedError

NewSessionClosedError creates a new SessionClosedError.

func (*SessionClosedError) Error added in v1.1.0

func (e *SessionClosedError) Error() string

type StopInput added in v1.1.0

type StopInput struct {
	BaseHookInput
	Reason string `json:"reason,omitempty"`
}

StopInput is the input for Stop hooks.

type StreamEvent added in v1.1.0

type StreamEvent struct {
	Type            string          `json:"type"` // Always "stream_event"
	UUID            string          `json:"uuid,omitempty"`
	SessionID       string          `json:"session_id,omitempty"`
	Event           string          `json:"event,omitempty"`
	ParentToolUseID string          `json:"parent_tool_use_id,omitempty"`
	RawEvent        json.RawMessage `json:"raw_event,omitempty"`
}

StreamEvent represents a streaming event from the CLI.

type StreamParser added in v1.1.0

type StreamParser struct {
	// contains filtered or unexported fields
}

StreamParser parses JSON stream messages from the CLI.

func NewStreamParser added in v1.1.0

func NewStreamParser() *StreamParser

NewStreamParser creates a new stream parser.

func (*StreamParser) Errors added in v1.1.0

func (p *StreamParser) Errors() <-chan error

Errors returns the error channel.

func (*StreamParser) Messages added in v1.1.0

func (p *StreamParser) Messages() <-chan MessageType

Messages returns the parsed message channel.

func (*StreamParser) Parse added in v1.1.0

func (p *StreamParser) Parse(ctx context.Context, transport Transport)

Parse processes transport messages into typed messages.

type SubagentStopInput added in v1.1.0

type SubagentStopInput struct {
	BaseHookInput
	SubagentID string `json:"subagent_id"`
	Reason     string `json:"reason,omitempty"`
}

SubagentStopInput is the input for SubagentStop hooks.

type SubprocessTransport added in v1.1.0

type SubprocessTransport struct {
	// contains filtered or unexported fields
}

SubprocessTransport communicates with Claude via subprocess using pipes.

func NewSubprocessTransport added in v1.1.0

func NewSubprocessTransport(opts *SubprocessTransportOptions) (*SubprocessTransport, error)

NewSubprocessTransport creates a new subprocess transport.

func (*SubprocessTransport) Close added in v1.1.0

func (t *SubprocessTransport) Close() error

Close terminates the subprocess.

func (*SubprocessTransport) Connect added in v1.1.0

func (t *SubprocessTransport) Connect(ctx context.Context) error

Connect starts the subprocess and establishes communication. Uses standard pipes for stdin/stdout/stderr for clean JSON communication.

func (*SubprocessTransport) IsConnected added in v1.1.0

func (t *SubprocessTransport) IsConnected() bool

IsConnected returns the connection status.

func (*SubprocessTransport) IsPTYMode added in v1.2.0

func (t *SubprocessTransport) IsPTYMode() bool

IsPTYMode returns true if the transport is using PTY mode. Note: This transport always uses pipes, so this returns false.

func (*SubprocessTransport) Receive added in v1.1.0

func (t *SubprocessTransport) Receive() <-chan TransportMessage

Receive returns the message channel.

func (*SubprocessTransport) Send added in v1.1.0

func (t *SubprocessTransport) Send(msg []byte) error

Send writes a message to stdin.

func (*SubprocessTransport) SignalInputComplete added in v1.2.0

func (t *SubprocessTransport) SignalInputComplete() error

SignalInputComplete signals that no more input will be sent by closing stdin. This allows the subprocess to detect EOF and complete processing.

type SubprocessTransportOptions added in v1.1.0

type SubprocessTransportOptions struct {
	CLIPath      string
	Args         []string
	Env          map[string]string // Legacy: use AgentOptions instead
	EnvList      []string          // Pre-built environment list (takes precedence)
	AgentOptions *AgentOptions     // Full options for environment building
	WorkingDir   string
	BufferSize   int
	// UsePipes disables PTY mode and uses standard pipes for stdin/stdout/stderr.
	// This is useful for non-interactive JSON communication where PTY echo
	// and line discipline features are not needed.
	UsePipes bool
}

SubprocessTransportOptions configures a subprocess transport.

type SystemMessage added in v1.1.0

type SystemMessage struct {
	Type    string                 `json:"type"` // Always "system"
	Subtype string                 `json:"subtype"`
	Data    map[string]interface{} `json:"data,omitempty"`
}

SystemMessage represents a system-level message.

type TextBlock added in v1.1.0

type TextBlock struct {
	Type string `json:"type"` // Always "text"
	Text string `json:"text"`
}

TextBlock contains plain text content.

type ThinkingBlock added in v1.1.0

type ThinkingBlock struct {
	Type      string `json:"type"` // Always "thinking"
	Thinking  string `json:"thinking"`
	Signature string `json:"signature,omitempty"`
}

ThinkingBlock contains Claude's internal reasoning.

type Timestamp added in v1.1.0

type Timestamp time.Time

Timestamp helper for message timing.

func (Timestamp) MarshalJSON added in v1.1.0

func (t Timestamp) MarshalJSON() ([]byte, error)

func (*Timestamp) UnmarshalJSON added in v1.1.0

func (t *Timestamp) UnmarshalJSON(data []byte) error

type ToolBuilder added in v1.1.0

type ToolBuilder struct {
	// contains filtered or unexported fields
}

ToolBuilder provides a fluent API for building tool definitions.

func Tool added in v1.1.0

func Tool(name, description string) *ToolBuilder

Tool creates a new tool definition with a builder pattern. This is the Go equivalent of Python's @tool decorator.

func (*ToolBuilder) Handler added in v1.1.0

func (b *ToolBuilder) Handler(handler ToolHandler) *ToolDefinition

Handler sets the tool handler function.

func (*ToolBuilder) HandlerFunc added in v1.1.0

func (b *ToolBuilder) HandlerFunc(fn func(ctx context.Context, args map[string]interface{}) (string, error)) *ToolDefinition

HandlerFunc is a convenience for creating simple string-returning handlers.

func (*ToolBuilder) Param added in v1.1.0

func (b *ToolBuilder) Param(name string, paramType string, description string) *ToolBuilder

Param adds a parameter to the tool schema.

func (*ToolBuilder) ParamWithDefault added in v1.1.0

func (b *ToolBuilder) ParamWithDefault(name string, paramType string, description string, defaultVal any) *ToolBuilder

ParamWithDefault adds a parameter with a default value.

func (*ToolBuilder) ParamWithEnum added in v1.1.0

func (b *ToolBuilder) ParamWithEnum(name string, paramType string, description string, enum []string) *ToolBuilder

ParamWithEnum adds a parameter with enum constraints.

func (*ToolBuilder) Required added in v1.1.0

func (b *ToolBuilder) Required(names ...string) *ToolBuilder

Required marks parameters as required.

type ToolDefinition added in v1.1.0

type ToolDefinition struct {
	Name        string      `json:"name"`
	Description string      `json:"description"`
	InputSchema ToolSchema  `json:"inputSchema"`
	Handler     ToolHandler `json:"-"`
}

ToolDefinition defines a tool that can be called by Claude.

type ToolError added in v1.1.0

type ToolError struct {
	ClaudeSDKError
	ToolName  string
	ToolUseID string
}

ToolError is raised when a tool execution fails.

func NewToolError added in v1.1.0

func NewToolError(message string, toolName string, toolUseID string, cause error) *ToolError

NewToolError creates a new ToolError.

func (*ToolError) Error added in v1.1.0

func (e *ToolError) Error() string

type ToolHandler added in v1.1.0

type ToolHandler func(ctx context.Context, args map[string]interface{}) (*ToolResult, error)

ToolHandler is the function signature for tool handlers.

type ToolResult added in v1.1.0

type ToolResult struct {
	Content []ToolResultContent `json:"content"`
	IsError bool                `json:"isError,omitempty"`
}

ToolResult is the result of a tool execution.

func ErrorResult added in v1.1.0

func ErrorResult(err error) *ToolResult

ErrorResult creates an error tool result.

func ImageResult added in v1.1.0

func ImageResult(data string, mimeType string) *ToolResult

ImageResult creates an image tool result.

func TextResult added in v1.1.0

func TextResult(text string) *ToolResult

TextResult creates a simple text tool result.

type ToolResultBlock added in v1.1.0

type ToolResultBlock struct {
	Type      string `json:"type"` // Always "tool_result"
	ToolUseID string `json:"tool_use_id"`
	Content   string `json:"content,omitempty"`
	IsError   bool   `json:"is_error,omitempty"`
}

ToolResultBlock contains the result of a tool execution.

type ToolResultContent added in v1.1.0

type ToolResultContent struct {
	Type string `json:"type"` // "text", "image", "resource"
	Text string `json:"text,omitempty"`
	// For image type
	Data     string `json:"data,omitempty"`
	MimeType string `json:"mimeType,omitempty"`
	// For resource type
	URI string `json:"uri,omitempty"`
}

ToolResultContent represents a single content item in a tool result.

type ToolSchema added in v1.1.0

type ToolSchema struct {
	Type       string                    `json:"type"`
	Properties map[string]PropertySchema `json:"properties,omitempty"`
	Required   []string                  `json:"required,omitempty"`
}

ToolSchema defines the input schema for a tool.

type ToolUseBlock added in v1.1.0

type ToolUseBlock struct {
	Type  string                 `json:"type"` // Always "tool_use"
	ID    string                 `json:"id"`
	Name  string                 `json:"name"`
	Input map[string]interface{} `json:"input"`
}

ToolUseBlock represents a tool invocation by Claude.

func GetToolCalls added in v1.1.0

func GetToolCalls(msg AssistantMessage) []ToolUseBlock

GetToolCalls extracts tool use blocks from an assistant message.

type Transport added in v1.1.0

type Transport interface {
	// Connect establishes a connection and starts the session.
	Connect(ctx context.Context) error

	// Send sends a message to Claude.
	Send(msg []byte) error

	// Receive returns a channel for receiving messages.
	Receive() <-chan TransportMessage

	// Close closes the transport.
	Close() error

	// IsConnected returns whether the transport is connected.
	IsConnected() bool
}

Transport defines the interface for communicating with Claude.

type TransportMessage added in v1.1.0

type TransportMessage struct {
	Data  json.RawMessage
	Error error
}

TransportMessage wraps a message from the transport.

type Usage added in v1.1.0

type Usage struct {
	InputTokens  int `json:"input_tokens"`
	OutputTokens int `json:"output_tokens"`
	CacheRead    int `json:"cache_read,omitempty"`
	CacheWrite   int `json:"cache_write,omitempty"`
}

Usage tracks API usage statistics.

type UserMessage added in v1.1.0

type UserMessage struct {
	Type            string          `json:"type"` // Always "user"
	UUID            string          `json:"uuid,omitempty"`
	Content         []ContentBlock  `json:"-"`
	RawContent      json.RawMessage `json:"content,omitempty"`
	ParentToolUseID string          `json:"parent_tool_use_id,omitempty"`
}

UserMessage represents a message from the user.

type UserPromptSubmitInput added in v1.1.0

type UserPromptSubmitInput struct {
	BaseHookInput
	Prompt string `json:"prompt"`
}

UserPromptSubmitInput is the input for UserPromptSubmit hooks.

type VCRMode added in v1.1.0

type VCRMode int

VCRMode determines whether the VCR records or replays.

const (
	// VCRModeAuto automatically determines mode based on cassette existence.
	// If cassette exists, replay. Otherwise, record.
	VCRModeAuto VCRMode = iota

	// VCRModeRecord always records, overwriting existing cassettes.
	VCRModeRecord

	// VCRModeReplay only replays from existing cassettes, fails if not found.
	VCRModeReplay

	// VCRModePassthrough disables VCR, passes through to real API.
	VCRModePassthrough
)

type VCROption added in v1.1.0

type VCROption func(*VCRServer)

VCROption configures a VCRServer.

func WithTargetURL added in v1.1.0

func WithTargetURL(url string) VCROption

WithTargetURL sets the target API URL for recording mode. Defaults to https://api.anthropic.com

func WithVCRMode added in v1.1.0

func WithVCRMode(mode VCRMode) VCROption

WithVCRMode sets the recording/replay mode.

type VCRRecorder added in v1.1.0

type VCRRecorder struct {
	// contains filtered or unexported fields
}

VCRRecorder provides direct access to the go-vcr recorder for testing. Use this when you want to test HTTP interactions directly without the proxy server.

func NewVCRRecorder added in v1.1.0

func NewVCRRecorder(cassettePath string, opts ...VCROption) (*VCRRecorder, error)

NewVCRRecorder creates a VCR recorder for direct HTTP client use. This is useful for testing HTTP-level interactions without the proxy overhead.

func (*VCRRecorder) Close added in v1.1.0

func (v *VCRRecorder) Close() error

Close stops the recorder and saves the cassette.

func (*VCRRecorder) HTTPClient added in v1.1.0

func (v *VCRRecorder) HTTPClient() *http.Client

HTTPClient returns an http.Client configured for VCR recording/replay.

func (*VCRRecorder) IsRecording added in v1.1.0

func (v *VCRRecorder) IsRecording() bool

IsRecording returns true if the recorder is in recording mode.

type VCRServer added in v1.1.0

type VCRServer struct {
	// contains filtered or unexported fields
}

VCRServer provides HTTP recording and replay for integration tests. It starts a local HTTP server that either: - Records requests to the real Anthropic API and saves them to cassettes - Replays previously recorded responses from cassettes

Usage:

vcr := NewVCRServer("testdata/cassettes/my_test")
defer vcr.Close()
baseURL := vcr.Start()
// Use baseURL as ANTHROPIC_BASE_URL

func NewVCRServer added in v1.1.0

func NewVCRServer(cassettePath string, opts ...VCROption) *VCRServer

NewVCRServer creates a new VCR server for the given cassette path. The cassette path should not include the .yaml extension.

func (*VCRServer) BaseURL added in v1.1.0

func (v *VCRServer) BaseURL() string

BaseURL returns the base URL of the VCR server. Returns empty string if not started.

func (*VCRServer) Close added in v1.1.0

func (v *VCRServer) Close() error

Close stops the VCR server and saves any recorded cassettes.

func (*VCRServer) HTTPClient added in v1.1.0

func (v *VCRServer) HTTPClient() *http.Client

HTTPClient returns an http.Client configured for VCR recording/replay. Useful for testing HTTP-level interactions directly.

func (*VCRServer) IsRecording added in v1.1.0

func (v *VCRServer) IsRecording() bool

IsRecording returns true if the VCR is in recording mode.

func (*VCRServer) RecordingTransport added in v1.1.0

func (v *VCRServer) RecordingTransport() http.RoundTripper

RecordingTransport returns an http.RoundTripper that records/replays. Useful for direct API testing without the CLI.

func (*VCRServer) Start added in v1.1.0

func (v *VCRServer) Start() (string, error)

Start starts the VCR server and returns the base URL to use. This URL should be set as ANTHROPIC_BASE_URL.

type VCRTestHelper added in v1.1.0

type VCRTestHelper struct {
	// contains filtered or unexported fields
}

VCRTestHelper provides convenient test setup for VCR-based tests.

func NewVCRTestHelper added in v1.1.0

func NewVCRTestHelper(cassetteName string, opts ...VCROption) *VCRTestHelper

NewVCRTestHelper creates a test helper that manages VCR and environment.

func (*VCRTestHelper) BaseURL added in v1.1.0

func (h *VCRTestHelper) BaseURL() string

BaseURL returns the VCR server's base URL.

func (*VCRTestHelper) CreateVCRClient added in v1.1.0

func (h *VCRTestHelper) CreateVCRClient(opts *AgentOptions) *Client

CreateVCRClient creates a Claude client configured to use the VCR.

func (*VCRTestHelper) IsRecording added in v1.1.0

func (h *VCRTestHelper) IsRecording() bool

IsRecording returns true if recording new interactions.

func (*VCRTestHelper) Setup added in v1.1.0

func (h *VCRTestHelper) Setup() (cleanup func(), err error)

Setup starts the VCR and configures environment variables. Returns a cleanup function that should be deferred.

type VertexConfig added in v1.1.0

type VertexConfig struct {
	ProjectID string `json:"project_id,omitempty"`
	Region    string `json:"region,omitempty"`
}

VertexConfig holds Google Vertex AI-specific configuration.

Directories

Path Synopsis
cmd
test-runner command
examples
basic command
concurrent command
hooks command
Example: Hooks for Tool Control
Example: Hooks for Tool Control
interactive command
mcp command
Example: Custom MCP Tools
Example: Custom MCP Tools

Jump to

Keyboard shortcuts

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