claude

package module
v0.1.46 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2026 License: MIT Imports: 15 Imported by: 0

README

Claude Agent SDK for Go

Go SDK for Claude Agent. This SDK provides a high-performance, idiomatic Go interface for interacting with Claude Code CLI, mirroring the functionality of the Python SDK.

Installation

go get github.com/ProjAnvil/claude-agent-sdk-golang

Prerequisites:

  • Go 1.25+
  • Claude Code CLI installed (curl -fsSL https://claude.ai/install.sh | bash)

Quick Start

package main

import (
	"context"
	"fmt"
	"log"

	claude "github.com/ProjAnvil/claude-agent-sdk-golang"
)

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

	// Simple one-shot query
	messages, errs := claude.Query(ctx, "What is 2 + 2?", nil)

	for {
		select {
		case msg, ok := <-messages:
			if !ok {
				return
			}
			if assistant, ok := msg.(*claude.AssistantMessage); ok {
				for _, block := range assistant.Content {
					if text, ok := block.(*claude.TextBlock); ok {
						fmt.Println(text.Text)
					}
				}
			}
		case err := <-errs:
			if err != nil {
				log.Fatal(err)
			}
		}
	}
}

Basic Usage: Query()

Query() is a function for one-shot queries to Claude Code. It returns channels for messages and errors, allowing for idiomatic Go concurrency patterns.

// Simple query
messages, errs := claude.Query(ctx, "Hello Claude", nil)

// With options
opts := &claude.ClaudeAgentOptions{
	SystemPrompt: "You are a helpful assistant",
	MaxTurns:     1,
}
messages, errs := claude.Query(ctx, "Tell me a joke", opts)

// Synchronous query (collects all messages)
allMessages, err := claude.QuerySync(ctx, "What is Go?", nil)
Using Tools
opts := &claude.ClaudeAgentOptions{
	AllowedTools: []string{"Read", "Write", "Bash"},
	PermissionMode: "acceptEdits", // auto-accept file edits
}

messages, errs := claude.Query(ctx, "Create a hello.go file", opts)
// Process messages...
Working Directory
opts := &claude.ClaudeAgentOptions{
	CWD: "/path/to/project",
}

ClaudeSDKClient

ClaudeSDKClient supports bidirectional, interactive conversations with Claude Code.

Unlike Query(), ClaudeSDKClient additionally enables custom tools and hooks.

Custom Tools (as In-Process SDK MCP Servers)

A custom tool is a Go function that you can offer to Claude. These run in-process, similar to the Python SDK's implementation.

// Define a tool
addTool := claude.Tool("add", "Add two numbers", map[string]interface{}{
	"type": "object",
	"properties": map[string]interface{}{
		"a": map[string]interface{}{"type": "number"},
		"b": map[string]interface{}{"type": "number"},
	},
}).Handler(func(args map[string]interface{}) (map[string]interface{}, error) {
	a := args["a"].(float64)
	b := args["b"].(float64)
	return map[string]interface{}{
		"content": []map[string]interface{}{
			{"type": "text", "text": fmt.Sprintf("%.2f + %.2f = %.2f", a, b, a+b)},
		},
	}, nil
})

// Create SDK MCP server
calculator := claude.CreateSdkMcpServer("calculator", "1.0.0", []claude.SdkMcpTool{addTool})

// Use it with Claude
opts := &claude.ClaudeAgentOptions{
	MCPServers:   map[string]interface{}{"calc": calculator},
	AllowedTools: []string{"mcp__calc__add"},
}

client := claude.NewClient(opts)
if err := client.Connect(ctx); err != nil {
	log.Fatal(err)
}
defer client.Close()

messages, _ := client.Query(ctx, "Add 10 and 20")
// Process response...
Hooks

A hook is a function invoked at specific points of the Claude agent loop.

opts := &claude.ClaudeAgentOptions{
	AllowedTools: []string{"Bash"},
	Hooks: map[claude.HookEvent][]claude.HookMatcher{
		claude.HookEventPreToolUse: {
			{
				Matcher: "Bash",
				Hooks: []claude.HookCallback{
					func(input claude.HookInput, toolUseID string, ctx claude.HookContext) (claude.HookOutput, error) {
						// Check command before execution
						if strings.Contains(input.ToolInput["command"].(string), "rm -rf") {
							return claude.HookOutput{
								HookSpecificOutput: map[string]interface{}{
									"hookEventName":            "PreToolUse",
									"permissionDecision":       "deny",
									"permissionDecisionReason": "Dangerous command blocked",
								},
							}, nil
						}
						return claude.HookOutput{}, nil
					},
				},
			},
		},
	},
}

Agents

Define custom agents with specific personalities and tools:

opts := &claude.ClaudeAgentOptions{
	Agents: map[string]claude.AgentDefinition{
		"coder": {
			Description: "A specialized coding agent",
			Prompt:      "You are an expert Go developer.",
			Tools:       []string{"Bash", "Read", "Write"},
			Model:       "claude-3-7-sonnet-20250219",
		},
	},
}

Thinking Mode

Enable extended thinking for complex tasks:

opts := &claude.ClaudeAgentOptions{
	Thinking: &claude.ThinkingConfig{
		Type:         "adaptive", // or "enabled"
		BudgetTokens: 16000,
	},
	Model: "claude-3-7-sonnet-20250219", // Required for thinking
}

Sandbox

Secure your environment by sandboxing bash commands:

opts := &claude.ClaudeAgentOptions{
	Sandbox: &claude.SandboxSettings{
		Enabled: true,
		Network: &claude.SandboxNetworkConfig{
			AllowLocalBinding:   true,
		},
		ExcludedCommands: []string{"git", "go"},
	},
}

Types

See types.go for complete type definitions:

  • ClaudeAgentOptions - Configuration options
  • UserMessage, AssistantMessage, SystemMessage, ResultMessage - Message types
  • TextBlock, ThinkingBlock, ToolUseBlock, ToolResultBlock - Content blocks

Error Handling

messages, errs := claude.Query(ctx, "Hello", nil)

for {
	select {
	case msg, ok := <-messages:
		if !ok {
			return
		}
		// Process message
	case err := <-errs:
		if err != nil {
			switch e := err.(type) {
			case *claude.CLINotFoundError:
				fmt.Println("Please install Claude Code")
			case *claude.ProcessError:
				fmt.Printf("Process failed with exit code: %d\n", e.ExitCode)
			case *claude.CLIJSONDecodeError:
				fmt.Printf("Failed to parse response: %s\n", e.Line)
			default:
				fmt.Printf("Error: %v\n", err)
			}
		}
	}
}

License

Use of this SDK is governed by Anthropic's Commercial Terms of Service.

Documentation

Overview

Package claude provides a Go SDK for interacting with Claude Code CLI.

The SDK supports two main usage patterns:

1. One-shot queries using the Query function:

messages, errs := claude.Query(ctx, "What is 2 + 2?", nil)
for msg := range messages {
    // Process messages
}

2. Bidirectional conversations using ClaudeSDKClient:

client := claude.NewClient(opts)
client.Connect(ctx)
defer client.Close()

messages, _ := client.Query(ctx, "Hello")
for msg := range messages {
    // Process messages
}

The SDK also supports custom MCP tools and hooks for extending Claude's capabilities and controlling its behavior.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsBufferOverflowError

func IsBufferOverflowError(err error) bool

IsBufferOverflowError checks if the error is a BufferOverflowError.

func IsCLIConnectionError

func IsCLIConnectionError(err error) bool

IsCLIConnectionError checks if the error is a CLIConnectionError.

func IsCLIJSONDecodeError

func IsCLIJSONDecodeError(err error) bool

IsCLIJSONDecodeError checks if the error is a CLIJSONDecodeError.

func IsCLINotFoundError

func IsCLINotFoundError(err error) bool

IsCLINotFoundError checks if the error is a CLINotFoundError.

func IsMessageParseError

func IsMessageParseError(err error) bool

IsMessageParseError checks if the error is a MessageParseError.

func IsProcessError

func IsProcessError(err error) bool

IsProcessError checks if the error is a ProcessError.

func IsTimeoutError

func IsTimeoutError(err error) bool

IsTimeoutError checks if the error is a TimeoutError.

func Query

func Query(ctx context.Context, prompt interface{}, opts *ClaudeAgentOptions) (<-chan Message, <-chan error)

Query performs a one-shot query to Claude Code. It returns two channels: one for messages and one for errors. The message channel is closed when the query completes.

func TextContent

func TextContent(text string) map[string]interface{}

TextContent creates a text content block for tool responses.

func ToolErrorResponse

func ToolErrorResponse(text string) map[string]interface{}

ToolErrorResponse creates an error tool response.

func ToolResponse

func ToolResponse(text string) map[string]interface{}

ToolResponse creates a standard tool response with text content.

Types

type AgentDefinition

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

AgentDefinition defines a custom agent configuration.

type AssistantMessage

type AssistantMessage struct {
	Content         []ContentBlock `json:"content"`
	Model           string         `json:"model"`
	ParentToolUseID string         `json:"parent_tool_use_id,omitempty"`
	Error           string         `json:"error,omitempty"`
}

AssistantMessage represents an assistant message with content blocks.

type AssistantMessageError

type AssistantMessageError string

AssistantMessageError represents error types for assistant messages.

const (
	AssistantMessageErrorAuthFailed     AssistantMessageError = "authentication_failed"
	AssistantMessageErrorBilling        AssistantMessageError = "billing_error"
	AssistantMessageErrorRateLimit      AssistantMessageError = "rate_limit"
	AssistantMessageErrorInvalidRequest AssistantMessageError = "invalid_request"
	AssistantMessageErrorServer         AssistantMessageError = "server_error"
	AssistantMessageErrorUnknown        AssistantMessageError = "unknown"
)

type BufferOverflowError

type BufferOverflowError struct {
	ClaudeSDKError
	BufferSize int
	Limit      int
}

BufferOverflowError indicates that a message exceeded the buffer size limit.

func NewBufferOverflowError

func NewBufferOverflowError(bufferSize, limit int) *BufferOverflowError

NewBufferOverflowError creates a new BufferOverflowError.

func (*BufferOverflowError) Error

func (e *BufferOverflowError) Error() string

type CLIConnectionError

type CLIConnectionError struct {
	ClaudeSDKError
}

CLIConnectionError indicates connection or transport issues with the CLI.

func NewCLIConnectionError

func NewCLIConnectionError(message string, cause error) *CLIConnectionError

NewCLIConnectionError creates a new CLIConnectionError.

type CLIJSONDecodeError

type CLIJSONDecodeError struct {
	ClaudeSDKError
	Line string
}

CLIJSONDecodeError indicates that JSON parsing from CLI output failed.

func NewCLIJSONDecodeError

func NewCLIJSONDecodeError(line string, cause error) *CLIJSONDecodeError

NewCLIJSONDecodeError creates a new CLIJSONDecodeError.

func (*CLIJSONDecodeError) Error

func (e *CLIJSONDecodeError) Error() string

type CLINotFoundError

type CLINotFoundError struct {
	ClaudeSDKError
	CLIPath string
}

CLINotFoundError indicates that the Claude Code CLI is not installed or not found.

func NewCLINotFoundError

func NewCLINotFoundError(cliPath string) *CLINotFoundError

NewCLINotFoundError creates a new CLINotFoundError.

func (*CLINotFoundError) Error

func (e *CLINotFoundError) Error() string

type CanUseToolFunc

type CanUseToolFunc func(toolName string, input map[string]interface{}, ctx ToolPermissionContext) (PermissionResult, error)

CanUseToolFunc is the callback type for tool permission requests.

type ClaudeAgentOptions

type ClaudeAgentOptions struct {
	// Tools specifies the base set of tools available.
	Tools []string
	// ToolsPreset specifies a preset for tools (e.g., "claude_code").
	ToolsPreset *ToolsPreset
	// AllowedTools specifies which tools are allowed.
	AllowedTools []string
	// SystemPrompt sets a custom system prompt.
	SystemPrompt string
	// SystemPromptPreset specifies a system prompt preset.
	SystemPromptPreset *SystemPromptPreset
	// MCPServers configures MCP servers (external or SDK).
	MCPServers map[string]MCPServerConfig
	// PermissionMode sets the permission level for tool execution.
	PermissionMode PermissionMode
	// ContinueConversation continues an existing conversation.
	ContinueConversation bool
	// Resume resumes a specific session.
	Resume string
	// MaxTurns limits the number of conversation turns.
	MaxTurns int
	// MaxBudgetUSD sets a cost limit in USD.
	MaxBudgetUSD float64
	// DisallowedTools specifies which tools are not allowed.
	DisallowedTools []string
	// Model specifies the AI model to use.
	Model string
	// FallbackModel specifies a fallback model.
	FallbackModel string
	// Betas enables beta features.
	Betas []string
	// PermissionPromptToolName sets the tool for permission prompts.
	PermissionPromptToolName string
	// CWD sets the working directory for the CLI.
	CWD string
	// CLIPath specifies a custom path to the Claude CLI.
	CLIPath string
	// Settings specifies settings as JSON string or file path.
	Settings string
	// AddDirs adds additional directories.
	AddDirs []string
	// Env sets environment variables for the CLI process.
	Env map[string]string
	// ExtraArgs passes arbitrary CLI flags.
	ExtraArgs map[string]string
	// MaxBufferSize sets the maximum buffer size for CLI output.
	MaxBufferSize int
	// StderrCallback receives stderr output from CLI.
	StderrCallback func(string)
	// CanUseTool is a callback for tool permission requests.
	CanUseTool CanUseToolFunc
	// Hooks configures hook callbacks for various events.
	Hooks map[HookEvent][]HookMatcher
	// User specifies the user for the CLI process.
	User string
	// IncludePartialMessages enables streaming of partial messages.
	IncludePartialMessages bool
	// ForkSession forks resumed sessions to a new session ID.
	ForkSession bool
	// Agents defines custom agent configurations.
	Agents map[string]AgentDefinition
	// SettingSources specifies which setting sources to load.
	SettingSources []SettingSource
	// Sandbox configures bash command sandboxing.
	Sandbox *SandboxSettings
	// Plugins configures custom plugins.
	Plugins []PluginConfig
	// MaxThinkingTokens sets the max tokens for thinking blocks.
	// Deprecated: Use Thinking instead.
	MaxThinkingTokens int
	// Thinking configures extended thinking behavior.
	Thinking *ThinkingConfig
	// OutputFormat specifies the output format for structured outputs.
	OutputFormat map[string]interface{}
	// EnableFileCheckpointing enables file change tracking.
	EnableFileCheckpointing bool
}

ClaudeAgentOptions configures SDK behavior.

func DefaultOptions

func DefaultOptions() *ClaudeAgentOptions

DefaultOptions returns ClaudeAgentOptions with default values.

type ClaudeSDKClient

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

ClaudeSDKClient provides bidirectional communication with Claude Code.

func NewClient

func NewClient(opts *ClaudeAgentOptions) *ClaudeSDKClient

NewClient creates a new ClaudeSDKClient.

func (*ClaudeSDKClient) Close

func (c *ClaudeSDKClient) Close() error

Close disconnects and cleans up resources.

func (*ClaudeSDKClient) Connect

func (c *ClaudeSDKClient) Connect(ctx context.Context, prompt ...interface{}) error

Connect establishes connection to Claude Code CLI. prompt can be a string, a channel of messages, or nil for interactive mode.

func (*ClaudeSDKClient) GetMCPStatus

func (c *ClaudeSDKClient) GetMCPStatus(ctx context.Context) (*McpStatusResponse, error)

GetMCPStatus returns the current MCP server connection status.

func (*ClaudeSDKClient) GetServerInfo

func (c *ClaudeSDKClient) GetServerInfo() map[string]interface{}

GetServerInfo returns information about the connected server.

func (*ClaudeSDKClient) Interrupt

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

Interrupt sends an interrupt signal.

func (*ClaudeSDKClient) Query

func (c *ClaudeSDKClient) Query(ctx context.Context, prompt string, opts ...QueryOption) (<-chan Message, error)

Query sends a message and returns a channel of responses.

func (*ClaudeSDKClient) ReceiveResponse

func (c *ClaudeSDKClient) ReceiveResponse(ctx context.Context) (<-chan Message, error)

ReceiveResponse returns messages until a ResultMessage is received.

func (*ClaudeSDKClient) ReconnectMCPServer added in v0.1.46

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

ReconnectMCPServer reconnects to an MCP server.

func (*ClaudeSDKClient) RewindFiles

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

RewindFiles rewinds tracked files to a specific user message.

func (*ClaudeSDKClient) Send

func (c *ClaudeSDKClient) Send(ctx context.Context, prompt string, opts ...QueryOption) error

Send sends a message to Claude without waiting for a response.

func (*ClaudeSDKClient) SetModel

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

SetModel changes the AI model.

func (*ClaudeSDKClient) SetPermissionMode

func (c *ClaudeSDKClient) SetPermissionMode(ctx context.Context, mode PermissionMode) error

SetPermissionMode changes the permission mode.

func (*ClaudeSDKClient) StopTask added in v0.1.46

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

StopTask stops a running task.

func (*ClaudeSDKClient) ToggleMCPServer added in v0.1.46

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

ToggleMCPServer enables or disables an MCP server.

type ClaudeSDKError

type ClaudeSDKError struct {
	Message string
	Cause   error
}

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

func NewClaudeSDKError

func NewClaudeSDKError(message string, cause error) *ClaudeSDKError

NewClaudeSDKError creates a new ClaudeSDKError.

func (*ClaudeSDKError) Error

func (e *ClaudeSDKError) Error() string

func (*ClaudeSDKError) Unwrap

func (e *ClaudeSDKError) Unwrap() error

type ContentBlock

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

ContentBlock is the interface for content blocks within messages.

func ParseContentBlock

func ParseContentBlock(raw map[string]interface{}) (ContentBlock, error)

ParseContentBlock parses a raw content block map into a typed ContentBlock.

func ParseContentBlocks

func ParseContentBlocks(rawBlocks []interface{}) ([]ContentBlock, error)

ParseContentBlocks parses a slice of raw content block maps into typed ContentBlocks.

type GetSessionMessagesOptions added in v0.1.46

type GetSessionMessagesOptions struct {
	// SessionID is the UUID of the session to read.
	SessionID string
	// Directory to find the session in. If nil, searches all project directories.
	Directory *string
	// Maximum number of messages to return.
	Limit *int
	// Number of messages to skip from the start.
	Offset int
}

GetSessionMessagesOptions contains options for getting session messages.

type HookCallback

type HookCallback func(input HookInput, toolUseID string, ctx HookContext) (HookOutput, error)

HookCallback is the function signature for hook handlers.

type HookContext

type HookContext struct {
	Signal interface{} // Future: abort signal support
}

HookContext provides context for hook callbacks.

type HookEvent

type HookEvent string

HookEvent defines the type of hook event.

const (
	HookEventPreToolUse         HookEvent = "PreToolUse"
	HookEventPostToolUse        HookEvent = "PostToolUse"
	HookEventPostToolUseFailure HookEvent = "PostToolUseFailure"
	HookEventUserPromptSubmit   HookEvent = "UserPromptSubmit"
	HookEventStop               HookEvent = "Stop"
	HookEventSubagentStop       HookEvent = "SubagentStop"
	HookEventPreCompact         HookEvent = "PreCompact"
	HookEventNotification       HookEvent = "Notification"
	HookEventSubagentStart      HookEvent = "SubagentStart"
	HookEventPermissionRequest  HookEvent = "PermissionRequest"
)

type HookInput

type HookInput struct {
	HookEventName         string                 `json:"hook_event_name"`
	SessionID             string                 `json:"session_id"`
	TranscriptPath        string                 `json:"transcript_path"`
	CWD                   string                 `json:"cwd"`
	PermissionMode        string                 `json:"permission_mode,omitempty"`
	ToolName              string                 `json:"tool_name,omitempty"`              // PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest (includes agent_id/agent_type for subagents)
	ToolInput             map[string]interface{} `json:"tool_input,omitempty"`             // PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest
	ToolResponse          interface{}            `json:"tool_response,omitempty"`          // PostToolUse
	ToolUseID             string                 `json:"tool_use_id,omitempty"`            // PreToolUse, PostToolUse, PostToolUseFailure
	Error                 string                 `json:"error,omitempty"`                  // PostToolUseFailure
	IsInterrupt           bool                   `json:"is_interrupt,omitempty"`           // PostToolUseFailure
	Prompt                string                 `json:"prompt,omitempty"`                 // UserPromptSubmit
	StopHookActive        bool                   `json:"stop_hook_active,omitempty"`       // Stop, SubagentStop
	AgentID               string                 `json:"agent_id,omitempty"`               // SubagentStop, SubagentStart, PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest
	AgentTranscriptPath   string                 `json:"agent_transcript_path,omitempty"`  // SubagentStop
	AgentType             string                 `json:"agent_type,omitempty"`             // SubagentStop, SubagentStart, PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest
	Trigger               string                 `json:"trigger,omitempty"`                // PreCompact: "manual" or "auto"
	CustomInstructions    string                 `json:"custom_instructions,omitempty"`    // PreCompact
	Message               string                 `json:"message,omitempty"`                // Notification
	Title                 string                 `json:"title,omitempty"`                  // Notification
	NotificationType      string                 `json:"notification_type,omitempty"`      // Notification
	PermissionSuggestions []interface{}          `json:"permission_suggestions,omitempty"` // PermissionRequest
}

HookInput contains data passed to hook callbacks.

type HookMatcher

type HookMatcher struct {
	Matcher string         // Tool name pattern (e.g., "Bash", "Write|MultiEdit|Edit")
	Hooks   []HookCallback // Hook callback functions
	Timeout time.Duration  // Timeout for hooks in this matcher
}

HookMatcher configures which hooks to invoke.

type HookOutput

type HookOutput struct {
	Continue           *bool                  `json:"continue,omitempty"`
	Async              bool                   `json:"async,omitempty"` // Mapped to async_ in Python
	AsyncTimeout       int                    `json:"asyncTimeout,omitempty"`
	SuppressOutput     bool                   `json:"suppressOutput,omitempty"`
	StopReason         string                 `json:"stopReason,omitempty"`
	Decision           string                 `json:"decision,omitempty"` // "block"
	SystemMessage      string                 `json:"systemMessage,omitempty"`
	Reason             string                 `json:"reason,omitempty"`
	HookSpecificOutput map[string]interface{} `json:"hookSpecificOutput,omitempty"`
}

HookOutput defines the response from a hook callback.

type ListSessionsOptions added in v0.1.46

type ListSessionsOptions struct {
	// Directory to list sessions for. If nil, returns sessions across all projects.
	Directory *string
	// Maximum number of sessions to return.
	Limit *int
	// Include sessions from git worktrees when directory is provided.
	IncludeWorktrees bool
}

ListSessionsOptions contains options for listing sessions.

type MCPHTTPServerConfig

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

MCPHTTPServerConfig configures an MCP HTTP server.

type MCPSSEServerConfig

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

MCPSSEServerConfig configures an MCP SSE server.

type MCPSdkServerConfig

type MCPSdkServerConfig struct {
	Type     string      `json:"type"` // "sdk"
	Name     string      `json:"name"`
	Instance interface{} `json:"-"` // The actual server instance (not serialized)
}

MCPSdkServerConfig configures an in-process SDK MCP server.

func CreateSdkMcpServer

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

CreateSdkMcpServer creates an in-process MCP server.

Example:

calculator := claude.CreateSdkMcpServer("calculator", "1.0.0", []claude.SdkMcpTool{
    addTool,
    subtractTool,
})

opts := &claude.ClaudeAgentOptions{
    MCPServers: map[string]claude.MCPServerConfig{
        "calc": calculator,
    },
    AllowedTools: []string{"mcp__calc__add", "mcp__calc__subtract"},
}

type MCPServerConfig

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

MCPServerConfig is the interface for MCP server configurations.

type MCPStdioServerConfig

type MCPStdioServerConfig struct {
	Type    string            `json:"type,omitempty"` // "stdio" (optional for backwards compatibility)
	Command string            `json:"command"`
	Args    []string          `json:"args,omitempty"`
	Env     map[string]string `json:"env,omitempty"`
}

MCPStdioServerConfig configures an MCP stdio server.

type McpClaudeAIProxyServerConfig added in v0.1.46

type McpClaudeAIProxyServerConfig struct {
	Type string `json:"type"` // "claudeai-proxy"
	URL  string `json:"url"`
	ID   string `json:"id"`
}

McpClaudeAIProxyServerConfig represents the configuration for a Claude.ai proxy server.

type McpSdkServerConfigStatus added in v0.1.46

type McpSdkServerConfigStatus struct {
	Type string `json:"type"` // "sdk"
	Name string `json:"name"`
}

McpSdkServerConfigStatus represents the status configuration for an SDK MCP server.

type McpServerConnectionStatus added in v0.1.46

type McpServerConnectionStatus string

McpServerConnectionStatus represents the connection status of an MCP server.

const (
	McpServerStatusConnected McpServerConnectionStatus = "connected"
	McpServerStatusFailed    McpServerConnectionStatus = "failed"
	McpServerStatusNeedsAuth McpServerConnectionStatus = "needs-auth"
	McpServerStatusPending   McpServerConnectionStatus = "pending"
	McpServerStatusDisabled  McpServerConnectionStatus = "disabled"
)

type McpServerInfo added in v0.1.46

type McpServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

McpServerInfo represents server information from an MCP server.

type McpServerStatus added in v0.1.46

type McpServerStatus struct {
	Name       string                    `json:"name"`
	Status     McpServerConnectionStatus `json:"status"`
	ServerInfo *McpServerInfo            `json:"serverInfo,omitempty"`
	Error      string                    `json:"error,omitempty"`
	Config     map[string]interface{}    `json:"config,omitempty"`
	Scope      string                    `json:"scope,omitempty"`
	Tools      []McpToolInfo             `json:"tools,omitempty"`
}

McpServerStatus represents the status of an MCP server.

type McpServerStatusConfig added in v0.1.46

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

McpServerStatusConfig is a union type for MCP server status configurations.

type McpStatusResponse added in v0.1.46

type McpStatusResponse struct {
	MCPServers []McpServerStatus `json:"mcpServers"`
}

McpStatusResponse represents the response from an MCP status request.

type McpToolAnnotations added in v0.1.46

type McpToolAnnotations struct {
	ReadOnly    bool `json:"readOnly,omitempty"`
	Destructive bool `json:"destructive,omitempty"`
	OpenWorld   bool `json:"openWorld,omitempty"`
}

McpToolAnnotations represents optional hints for tool usage.

type McpToolInfo added in v0.1.46

type McpToolInfo struct {
	Name        string              `json:"name"`
	Description string              `json:"description,omitempty"`
	Annotations *McpToolAnnotations `json:"annotations,omitempty"`
}

McpToolInfo represents information about an MCP tool.

type Message

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

Message is the interface for all message types from Claude Code.

func ParseMessage

func ParseMessage(data map[string]interface{}) (Message, error)

ParseMessage parses a raw JSON message into a typed Message. Returns nil for unknown message types for forward compatibility.

func QuerySync

func QuerySync(ctx context.Context, prompt interface{}, opts *ClaudeAgentOptions) ([]Message, error)

QuerySync performs a synchronous query, collecting all messages. It blocks until the query completes and returns all messages or an error.

type MessageParseError

type MessageParseError struct {
	ClaudeSDKError
	Data map[string]interface{}
}

MessageParseError indicates that message parsing failed due to unknown type or structure.

func NewMessageParseError

func NewMessageParseError(message string, data map[string]interface{}) *MessageParseError

NewMessageParseError creates a new MessageParseError.

func (*MessageParseError) Error

func (e *MessageParseError) Error() string

type PermissionMode

type PermissionMode string

PermissionMode defines security levels for tool execution.

const (
	// PermissionModeDefault is the default mode where CLI prompts for dangerous tools.
	PermissionModeDefault PermissionMode = "default"
	// PermissionModeAcceptEdits auto-accepts file edits.
	PermissionModeAcceptEdits PermissionMode = "acceptEdits"
	// PermissionModePlan is for planning mode.
	PermissionModePlan PermissionMode = "plan"
	// PermissionModeBypassPermissions allows all tools (use with caution).
	PermissionModeBypassPermissions PermissionMode = "bypassPermissions"
)

type PermissionResult

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

PermissionResult is the interface for permission results.

type PermissionResultAllow

type PermissionResultAllow struct {
	Behavior           string                 `json:"behavior"` // "allow"
	UpdatedInput       map[string]interface{} `json:"updated_input,omitempty"`
	UpdatedPermissions []PermissionUpdate     `json:"updated_permissions,omitempty"`
}

PermissionResultAllow allows the tool execution.

type PermissionResultDeny

type PermissionResultDeny struct {
	Behavior  string `json:"behavior"` // "deny"
	Message   string `json:"message,omitempty"`
	Interrupt bool   `json:"interrupt,omitempty"`
}

PermissionResultDeny denies the tool execution.

type PermissionRuleValue

type PermissionRuleValue struct {
	ToolName    string `json:"toolName"`
	RuleContent string `json:"ruleContent,omitempty"`
}

PermissionRuleValue represents a permission rule.

type PermissionUpdate

type PermissionUpdate struct {
	Type        string                `json:"type"` // "addRules", "replaceRules", "removeRules", "setMode", "addDirectories", "removeDirectories"
	Rules       []PermissionRuleValue `json:"rules,omitempty"`
	Behavior    string                `json:"behavior,omitempty"` // "allow", "deny", "ask"
	Mode        PermissionMode        `json:"mode,omitempty"`
	Directories []string              `json:"directories,omitempty"`
	Destination string                `json:"destination,omitempty"` // "userSettings", "projectSettings", "localSettings", "session"
}

PermissionUpdate represents a permission update.

type PluginConfig

type PluginConfig struct {
	Type string `json:"type"` // "local"
	Path string `json:"path"`
}

PluginConfig configures a plugin.

type ProcessError

type ProcessError struct {
	ClaudeSDKError
	ExitCode int
	Stderr   string
}

ProcessError indicates that the CLI process failed with a non-zero exit code.

func NewProcessError

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

NewProcessError creates a new ProcessError.

func (*ProcessError) Error

func (e *ProcessError) Error() string

type QueryOption

type QueryOption func(*queryOptions)

QueryOption configures a query or send operation.

func WithSessionID

func WithSessionID(id string) QueryOption

WithSessionID sets the session ID for the message.

type ResultMessage

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

ResultMessage represents a result message with cost and usage information.

type SDKControlMcpReconnectRequest added in v0.1.46

type SDKControlMcpReconnectRequest struct {
	Subtype    string `json:"subtype"` // "mcp_reconnect"
	ServerName string `json:"serverName"`
}

SDKControlMcpReconnectRequest requests reconnection to an MCP server.

type SDKControlMcpToggleRequest added in v0.1.46

type SDKControlMcpToggleRequest struct {
	Subtype    string `json:"subtype"` // "mcp_toggle"
	ServerName string `json:"serverName"`
	Enabled    bool   `json:"enabled"`
}

SDKControlMcpToggleRequest requests toggling an MCP server on/off.

type SDKControlStopTaskRequest added in v0.1.46

type SDKControlStopTaskRequest struct {
	Subtype string `json:"subtype"` // "stop_task"
	TaskID  string `json:"task_id"`
}

SDKControlStopTaskRequest requests stopping a running task.

type SDKSessionInfo added in v0.1.46

type SDKSessionInfo struct {
	SessionID    string  `json:"session_id"`
	Summary      string  `json:"summary"`
	LastModified int64   `json:"last_modified"`
	FileSize     int64   `json:"file_size"`
	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 about a Claude Code session.

func ListSessions added in v0.1.46

func ListSessions(opts *ListSessionsOptions) ([]SDKSessionInfo, error)

ListSessions returns session metadata extracted from stat + head/tail reads.

When Directory is provided, returns sessions for that project directory and its git worktrees. When omitted, returns sessions across all projects.

type SandboxIgnoreViolations

type SandboxIgnoreViolations struct {
	File    []string `json:"file,omitempty"`
	Network []string `json:"network,omitempty"`
}

SandboxIgnoreViolations specifies violations to ignore.

type SandboxNetworkConfig

type SandboxNetworkConfig struct {
	AllowUnixSockets    []string `json:"allowUnixSockets,omitempty"`
	AllowAllUnixSockets bool     `json:"allowAllUnixSockets,omitempty"`
	AllowLocalBinding   bool     `json:"allowLocalBinding,omitempty"`
	HTTPProxyPort       int      `json:"httpProxyPort,omitempty"`
	SOCKSProxyPort      int      `json:"socksProxyPort,omitempty"`
}

SandboxNetworkConfig configures network settings for sandbox.

type SandboxSettings

type SandboxSettings struct {
	Enabled                   bool                     `json:"enabled,omitempty"`
	AutoAllowBashIfSandboxed  bool                     `json:"autoAllowBashIfSandboxed,omitempty"`
	ExcludedCommands          []string                 `json:"excludedCommands,omitempty"`
	AllowUnsandboxedCommands  bool                     `json:"allowUnsandboxedCommands,omitempty"`
	Network                   *SandboxNetworkConfig    `json:"network,omitempty"`
	IgnoreViolations          *SandboxIgnoreViolations `json:"ignoreViolations,omitempty"`
	EnableWeakerNestedSandbox bool                     `json:"enableWeakerNestedSandbox,omitempty"`
}

SandboxSettings configures bash command sandboxing.

type SdkMcpTool

type SdkMcpTool struct {
	Name        string
	Description string
	InputSchema interface{}
	Handler     func(args map[string]interface{}) (map[string]interface{}, error)
}

SdkMcpTool defines a custom MCP tool.

type SessionMessage added in v0.1.46

type SessionMessage struct {
	Type            SessionMessageType `json:"type"`
	UUID            string             `json:"uuid"`
	SessionID       string             `json:"session_id"`
	Message         interface{}        `json:"message"`
	ParentToolUseID *string            `json:"parent_tool_use_id,omitempty"`
}

SessionMessage represents a message in a session's conversation.

func GetSessionMessages added in v0.1.46

func GetSessionMessages(opts *GetSessionMessagesOptions) ([]SessionMessage, error)

GetSessionMessages reads a session's conversation messages from its JSONL transcript file.

Parses the full JSONL, builds the conversation chain via parentUuid links, and returns user/assistant messages in chronological order.

type SessionMessageType added in v0.1.46

type SessionMessageType string

SessionMessageType represents the type of a session message.

const (
	SessionMessageTypeUser      SessionMessageType = "user"
	SessionMessageTypeAssistant SessionMessageType = "assistant"
)

type SettingSource

type SettingSource string

SettingSource specifies which setting sources to load.

const (
	SettingSourceUser    SettingSource = "user"
	SettingSourceProject SettingSource = "project"
	SettingSourceLocal   SettingSource = "local"
)

type StreamEvent

type StreamEvent struct {
	UUID            string                 `json:"uuid"`
	SessionID       string                 `json:"session_id"`
	Event           map[string]interface{} `json:"event"`
	ParentToolUseID string                 `json:"parent_tool_use_id,omitempty"`
}

StreamEvent represents a stream event for partial message updates.

type SystemMessage

type SystemMessage struct {
	Subtype string                 `json:"subtype"`
	Data    map[string]interface{} `json:"data"`
}

SystemMessage represents a system message with metadata.

type SystemPromptPreset

type SystemPromptPreset struct {
	Type   string `json:"type"`   // "preset"
	Preset string `json:"preset"` // "claude_code"
	Append string `json:"append,omitempty"`
}

SystemPromptPreset represents a system prompt preset configuration.

type TaskNotificationMessage added in v0.1.46

type TaskNotificationMessage struct {
	TaskID     string                 `json:"task_id"`
	Status     TaskNotificationStatus `json:"status"`
	OutputFile string                 `json:"output_file"`
	Summary    string                 `json:"summary"`
	UUID       string                 `json:"uuid"`
	SessionID  string                 `json:"session_id"`
	ToolUseID  string                 `json:"tool_use_id,omitempty"`
	Usage      *TaskUsage             `json:"usage,omitempty"`
}

TaskNotificationMessage represents a task notification system message.

type TaskNotificationStatus added in v0.1.46

type TaskNotificationStatus string

TaskNotificationStatus represents the status of a task notification.

const (
	TaskNotificationStatusCompleted TaskNotificationStatus = "completed"
	TaskNotificationStatusFailed    TaskNotificationStatus = "failed"
	TaskNotificationStatusStopped   TaskNotificationStatus = "stopped"
)

type TaskProgressMessage added in v0.1.46

type TaskProgressMessage struct {
	TaskID       string    `json:"task_id"`
	Description  string    `json:"description"`
	Usage        TaskUsage `json:"usage"`
	UUID         string    `json:"uuid"`
	SessionID    string    `json:"session_id"`
	ToolUseID    string    `json:"tool_use_id,omitempty"`
	LastToolName string    `json:"last_tool_name,omitempty"`
}

TaskProgressMessage represents a task progress system message.

type TaskStartedMessage added in v0.1.46

type TaskStartedMessage struct {
	TaskID      string `json:"task_id"`
	Description string `json:"description"`
	UUID        string `json:"uuid"`
	SessionID   string `json:"session_id"`
	ToolUseID   string `json:"tool_use_id,omitempty"`
	TaskType    string `json:"task_type,omitempty"`
}

TaskStartedMessage represents a task started system message.

type TaskUsage added in v0.1.46

type TaskUsage struct {
	TotalTokens int `json:"total_tokens"`
	ToolUses    int `json:"tool_uses"`
	DurationMS  int `json:"duration_ms"`
}

TaskUsage represents usage statistics reported in task_progress and task_notification messages.

type TextBlock

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

TextBlock represents a text content block.

func (*TextBlock) MarshalJSON

func (b *TextBlock) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for TextBlock.

type ThinkingBlock

type ThinkingBlock struct {
	Thinking  string `json:"thinking"`
	Signature string `json:"signature"`
}

ThinkingBlock represents a thinking content block.

func (*ThinkingBlock) MarshalJSON

func (b *ThinkingBlock) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for ThinkingBlock.

type ThinkingConfig

type ThinkingConfig struct {
	Type         string `json:"type"` // "adaptive", "enabled", "disabled"
	BudgetTokens int    `json:"budget_tokens,omitempty"`
}

ThinkingConfig represents thinking configuration.

type TimeoutError

type TimeoutError struct {
	ClaudeSDKError
	RequestType string
}

TimeoutError indicates that a control request timed out.

func NewTimeoutError

func NewTimeoutError(requestType string) *TimeoutError

NewTimeoutError creates a new TimeoutError.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

type ToolBuilder

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

ToolBuilder provides a fluent interface for building tools.

func Tool

func Tool(name, description string, inputSchema interface{}) *ToolBuilder

Tool creates a new ToolBuilder for defining an MCP tool.

Example:

addTool := claude.Tool("add", "Add two numbers", map[string]interface{}{
    "type": "object",
    "properties": map[string]interface{}{
        "a": map[string]interface{}{"type": "number"},
        "b": map[string]interface{}{"type": "number"},
    },
}).Handler(func(args map[string]interface{}) (map[string]interface{}, error) {
    a := args["a"].(float64)
    b := args["b"].(float64)
    return map[string]interface{}{
        "content": []map[string]interface{}{
            {"type": "text", "text": fmt.Sprintf("%.2f + %.2f = %.2f", a, b, a+b)},
        },
    }, nil
})

func (*ToolBuilder) Handler

func (b *ToolBuilder) Handler(fn func(args map[string]interface{}) (map[string]interface{}, error)) SdkMcpTool

Handler sets the handler function for the tool and returns the completed SdkMcpTool.

type ToolPermissionContext

type ToolPermissionContext struct {
	Signal      interface{}        // Future: abort signal support
	Suggestions []PermissionUpdate // Permission suggestions from CLI
}

ToolPermissionContext provides context for tool permission callbacks.

type ToolResultBlock

type ToolResultBlock struct {
	ToolUseID string      `json:"tool_use_id"`
	Content   interface{} `json:"content,omitempty"`
	IsError   bool        `json:"is_error,omitempty"`
}

ToolResultBlock represents a tool result content block.

func (*ToolResultBlock) MarshalJSON

func (b *ToolResultBlock) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for ToolResultBlock.

type ToolUseBlock

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

ToolUseBlock represents a tool use content block.

func (*ToolUseBlock) MarshalJSON

func (b *ToolUseBlock) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for ToolUseBlock.

type ToolsPreset

type ToolsPreset struct {
	Type   string `json:"type"`   // "preset"
	Preset string `json:"preset"` // "claude_code"
}

ToolsPreset represents a tools preset configuration.

type UserMessage

type UserMessage struct {
	Content         interface{}            `json:"content"` // string or []ContentBlock
	UUID            string                 `json:"uuid,omitempty"`
	ParentToolUseID string                 `json:"parent_tool_use_id,omitempty"`
	ToolUseResult   map[string]interface{} `json:"tool_use_result,omitempty"`
}

UserMessage represents a user message.

Directories

Path Synopsis
examples
hooks command
Package main demonstrates hooks with the Claude Agent SDK.
Package main demonstrates hooks with the Claude Agent SDK.
mcp_calculator command
Package main demonstrates custom MCP tools with the Claude Agent SDK.
Package main demonstrates custom MCP tools with the Claude Agent SDK.
quickstart command
Package main demonstrates basic usage of the Claude Agent SDK.
Package main demonstrates basic usage of the Claude Agent SDK.
say_hi command
Package main demonstrates saying hi to Claude.
Package main demonstrates saying hi to Claude.
streaming command
Package main demonstrates ClaudeSDKClient for bidirectional conversations.
Package main demonstrates ClaudeSDKClient for bidirectional conversations.
transport
Package transport provides the transport layer for CLI communication.
Package transport provides the transport layer for CLI communication.
Package testutil provides test utilities for the Claude Agent SDK.
Package testutil provides test utilities for the Claude Agent SDK.

Jump to

Keyboard shortcuts

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