Documentation
¶
Overview ¶
Package claude provides the Claude Agent SDK for Go.
This SDK enables building AI agents with Claude Code. It provides both one-shot query functionality and interactive session management with support for tools, hooks, MCP servers, and session management.
Quick Start ¶
For simple one-shot queries, use the Query function:
msgChan, err := claude.Query(ctx, "What is 2+2?", nil)
if err != nil {
log.Fatal(err)
}
for msg := range msgChan {
fmt.Printf("%v\n", msg)
}
Interactive Sessions ¶
For bidirectional, interactive conversations, create a Client:
c := client.NewWithOptions(&types.ClaudeAgentOptions{
SystemPrompt: types.String("You are a helpful assistant"),
})
defer c.Close()
err := c.Connect(ctx, "Hello, Claude!")
if err != nil {
log.Fatal(err)
}
for msg := range c.ReceiveResponse(ctx) {
fmt.Printf("%T: %v\n", msg, msg)
}
Configuration ¶
Use ClaudeAgentOptions to configure behavior:
opts := &types.ClaudeAgentOptions{
SystemPrompt: types.String("You are a helpful assistant"),
MaxTurns: types.Int(5),
AllowedTools: []string{"Read", "Write", "Bash"},
PermissionMode: types.PermissionModePtr(types.PermissionModeAcceptEdits),
}
See types.ClaudeAgentOptions for all available options.
Sessions API ¶
Manage conversation sessions:
sessions, err := claude.ListSessions("/path/to/project", 10, true)
messages, err := claude.GetSessionMessages(sessionID, "", 0, 0)
err = claude.RenameSession(sessionID, "New Title", "")
err = claude.ForkSession(sessionID, "", nil, nil)
See the examples directory for more usage examples.
Index ¶
- Constants
- Variables
- func DeleteSession(sessionID, directory string) error
- func GetSessionInfo(sessionID, directory string) *types.SDKSessionInfo
- func GetSessionMessages(sessionID, directory string, limit, offset int) ([]types.SessionMessage, error)
- func ListSessions(directory string, limit int, includeWorktrees bool) ([]types.SDKSessionInfo, error)
- func NewClient() *client.Client
- func NewClientWithOptions(opts *types.Options) *client.Client
- func Query(ctx context.Context, prompt string, opts *types.ClaudeAgentOptions) (<-chan types.Message, error)
- func QueryWithClient(ctx context.Context, c *client.Client, prompt string) (<-chan types.Message, error)
- func RenameSession(sessionID, title, directory string) error
- func TagSession(sessionID, tag, directory string) error
- type AgentDefinition
- type AssistantMessage
- type CLIError
- type Client
- type ContentBlock
- type ContextUsageCategory
- type ContextUsageResponse
- type ForkSessionResult
- type HookCallback
- type HookContext
- type HookEvent
- type HookInput
- type HookMatcher
- type McpHttpServerConfig
- type McpSSEServerConfig
- type McpServerConfig
- type McpStdioServerConfig
- type Message
- type Options
- type PermissionResult
- type PermissionResultAllow
- type PermissionResultDeny
- type PermissionUpdate
- type QueryResult
- type ResultMessage
- type SDKError
- type SDKSessionInfo
- type SessionMessage
- type StreamEvent
- type SystemMessage
- type SystemPromptFile
- type TaskBudget
- type TextBlock
- type ThinkingBlock
- type ToolExecutionError
- type ToolPermissionContext
- type ToolResultBlock
- type ToolUseBlock
- type UserMessage
Constants ¶
const CLIVersion = "2.1.109"
CLIVersion is the bundled Claude Code CLI version.
Variables ¶
var ( // ErrNoAPIKey is returned when no API key is provided. ErrNoAPIKey = sdkerrors.ErrNoAPIKey // ErrNotInstalled is returned when the Claude CLI is not installed. ErrNotInstalled = sdkerrors.ErrNotInstalled // ErrConnectionFailed is returned when connection to Claude CLI fails. ErrConnectionFailed = sdkerrors.ErrConnectionFailed // ErrTimeout is returned when an operation times out. ErrTimeout = sdkerrors.ErrTimeout // ErrInterrupted is returned when an operation is interrupted. ErrInterrupted = sdkerrors.ErrInterrupted )
Re-export errors for convenience.
Functions ¶
func DeleteSession ¶
DeleteSession deletes a session file from the project directory.
Example:
err := claude.DeleteSession("550e8400-e29b-41d4-a716-446655440000", "/path/to/project")
func GetSessionInfo ¶
func GetSessionInfo(sessionID, directory string) *types.SDKSessionInfo
GetSessionInfo reads metadata for a single session by ID.
Wraps readSessionLite for one file — no O(n) directory scan. Directory resolution matches GetSessionMessages: directory is the project path; when omitted, all project directories are searched for the session file.
Returns SDKSessionInfo for the session, or nil if the session file is not found, is a sidechain session, or has no extractable summary.
Example:
// Look up a session in a specific project
info := claude.GetSessionInfo("550e8400-e29b-41d4-a716-446655440000", "/path/to/project")
if info != nil {
fmt.Println(info.Summary)
}
// Search all projects for a session
info := claude.GetSessionInfo("550e8400-e29b-41d4-a716-446655440000", "")
func GetSessionMessages ¶
func GetSessionMessages(sessionID, directory string, limit, offset int) ([]types.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.
The limit parameter limits the number of messages returned (0 means no limit). The offset parameter skips the first N messages.
Example:
messages, err := claude.GetSessionMessages("550e8400-e29b-41d4-a716-446655440000", "/path/to/project", 10, 0)
func ListSessions ¶
func ListSessions(directory string, limit int, includeWorktrees bool) ([]types.SDKSessionInfo, error)
ListSessions lists sessions with metadata extracted from stat + head/tail reads.
When directory is provided, returns sessions for that project directory and its git worktrees. When empty, returns sessions across all projects.
The limit parameter limits the number of sessions returned (0 means no limit). The includeWorktrees parameter controls whether to include git worktree sessions.
Example:
// List sessions for current directory
sessions, err := claude.ListSessions("/path/to/project", 10, true)
// List all sessions
sessions, err := claude.ListSessions("", 0, false)
func NewClient ¶
NewClient creates a new Claude client with default options.
Example:
client := claude.NewClient() defer client.Close() result, err := client.Query(ctx, "Hello, Claude!")
func NewClientWithOptions ¶
NewClientWithOptions creates a new Claude client with custom options.
Example:
client := claude.NewClientWithOptions(&types.Options{
Model: types.ModelSonnet,
MaxTokens: 4096,
Temperature: 0.7,
})
func Query ¶
func Query(ctx context.Context, prompt string, opts *types.ClaudeAgentOptions) (<-chan types.Message, error)
Query sends a one-shot query to Claude and returns messages through a channel.
This is the simplest way to interact with Claude. Pass a prompt and optional configuration, and receive messages through a channel. The channel is automatically closed when the query completes.
For interactive conversations with follow-up messages, dynamic control, or custom tools/hooks, use client.Client instead.
Parameters:
- ctx: context for cancellation
- prompt: the user prompt to send
- opts: optional configuration (nil for defaults)
Returns a channel of Message types and an error if the query fails to start.
Example:
msgChan, err := claude.Query(ctx, "What is 2+2?", nil)
if err != nil {
log.Fatal(err)
}
for msg := range msgChan {
fmt.Printf("%v\n", msg)
}
With options:
opts := &types.ClaudeAgentOptions{
SystemPrompt: types.String("You are a helpful assistant"),
MaxTurns: types.Int(1),
}
msgChan, err := claude.Query(ctx, "Tell me a joke", opts)
func QueryWithClient ¶
func QueryWithClient(ctx context.Context, c *client.Client, prompt string) (<-chan types.Message, error)
QueryWithClient sends a query using an existing client.
Use this when you have a pre-configured client with custom options.
Example:
c := claude.NewClientWithOptions(&types.ClaudeAgentOptions{
Model: types.String(types.ModelSonnet),
})
msgChan, err := claude.QueryWithClient(ctx, c, "Hello!")
func RenameSession ¶
RenameSession renames a session by appending a custom-title entry. list_sessions reads the LAST custom-title from the file tail, so repeated calls are safe.
Example:
err := claude.RenameSession("550e8400-e29b-41d4-a716-446655440000", "My refactoring session", "/path/to/project")
func TagSession ¶
TagSession tags a session. Pass empty string to clear the tag. list_sessions reads the LAST tag from the file tail, so repeated calls are safe.
Tags are Unicode-sanitized before storing for CLI filter compatibility.
Example:
err := claude.TagSession("550e8400-e29b-41d4-a716-446655440000", "experiment", "/path/to/project")
Types ¶
type AssistantMessage ¶
type AssistantMessage = types.AssistantMessage
AssistantMessage represents a message from the assistant.
type ContentBlock ¶
type ContentBlock = types.ContentBlock
ContentBlock represents a content block in a message.
type ContextUsageCategory ¶
type ContextUsageCategory = types.ContextUsageCategory
Context usage types (v0.1.50)
type ContextUsageResponse ¶
type ContextUsageResponse = types.ContextUsageResponse
Re-export types for convenience.
type ForkSessionResult ¶
type ForkSessionResult = sessions.ForkSessionResult
ForkSessionResult represents the result of a fork_session operation.
func ForkSession ¶
func ForkSession(sessionID, directory string, upToMessageID *string, title *string) (*ForkSessionResult, error)
ForkSession creates a fork (copy) of a session with remapped UUIDs.
The fork preserves the conversation structure but assigns new UUIDs to all messages. Use upToMessageID to slice the fork at a specific message (inclusive). Use title to set a custom title; default is original title + " (fork)".
Example:
// Simple fork
result, err := claude.ForkSession("550e8400-e29b-41d4-a716-446655440000", "/path/to/project", nil, nil)
// Fork with custom title
title := "My Forked Session"
result, err := claude.ForkSession(sessionID, directory, nil, &title)
// Fork up to a specific message
msgID := "previous-message-uuid"
result, err := claude.ForkSession(sessionID, directory, &msgID, nil)
type McpHttpServerConfig ¶
type McpHttpServerConfig = types.McpHttpServerConfig
Re-export types for convenience.
type McpSSEServerConfig ¶
type McpSSEServerConfig = types.McpSSEServerConfig
Re-export types for convenience.
type McpStdioServerConfig ¶
type McpStdioServerConfig = types.McpStdioServerConfig
Re-export types for convenience.
type PermissionResultAllow ¶
type PermissionResultAllow = types.PermissionResultAllow
Re-export types for convenience.
type PermissionResultDeny ¶
type PermissionResultDeny = types.PermissionResultDeny
Re-export types for convenience.
type PermissionUpdate ¶
type PermissionUpdate = types.PermissionUpdate
Re-export types for convenience.
type QueryResult ¶
type QueryResult = types.QueryResult
QueryResult represents the result of a query operation.
type ResultMessage ¶
type ResultMessage = types.ResultMessage
ResultMessage represents the final result of a conversation.
type SystemMessage ¶
type SystemMessage = types.SystemMessage
SystemMessage represents a system message.
type ThinkingBlock ¶
type ThinkingBlock = types.ThinkingBlock
ThinkingBlock represents a thinking content block.
type ToolExecutionError ¶
type ToolExecutionError = sdkerrors.ToolExecutionError
ToolExecutionError represents an error during tool execution.
type ToolPermissionContext ¶
type ToolPermissionContext = types.ToolPermissionContext
Re-export types for convenience.
type ToolResultBlock ¶
type ToolResultBlock = types.ToolResultBlock
ToolResultBlock represents a tool result content block.
type ToolUseBlock ¶
type ToolUseBlock = types.ToolUseBlock
ToolUseBlock represents a tool use content block.
type UserMessage ¶
type UserMessage = types.UserMessage
UserMessage represents a message from the user.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package client provides the Claude SDK client for interactive sessions.
|
Package client provides the Claude SDK client for interactive sessions. |
|
Package config provides configuration detection for the Claude Agent SDK.
|
Package config provides configuration detection for the Claude Agent SDK. |
|
Package e2e_tests contains end-to-end tests for the Claude Agent SDK.
|
Package e2e_tests contains end-to-end tests for the Claude Agent SDK. |
|
Package errors defines error types for the Claude Agent SDK.
|
Package errors defines error types for the Claude Agent SDK. |
|
examples
|
|
|
agents
command
Example agents demonstrates how to configure and use custom agents with the Claude Agent SDK for Go.
|
Example agents demonstrates how to configure and use custom agents with the Claude Agent SDK for Go. |
|
budget
command
Example budget demonstrates using MaxBudgetUSD and MaxTurns options with cost tracking.
|
Example budget demonstrates using MaxBudgetUSD and MaxTurns options with cost tracking. |
|
complete
command
Example complete demonstrates a comprehensive integration of Claude Agent SDK features.
|
Example complete demonstrates a comprehensive integration of Claude Agent SDK features. |
|
filesystem_agents
command
Example filesystem_agents demonstrates filesystem-focused agent configurations in the Claude Agent SDK for Go.
|
Example filesystem_agents demonstrates filesystem-focused agent configurations in the Claude Agent SDK for Go. |
|
hooks
command
Example hooks demonstrates hook registration and usage in the Claude Agent SDK for Go.
|
Example hooks demonstrates hook registration and usage in the Claude Agent SDK for Go. |
|
include_partial_messages
command
Example include_partial_messages demonstrates handling partial/streaming messages in the Claude Agent SDK for Go.
|
Example include_partial_messages demonstrates handling partial/streaming messages in the Claude Agent SDK for Go. |
|
internal
Package internal provides shared utilities for SDK examples.
|
Package internal provides shared utilities for SDK examples. |
|
mcp_calculator
command
Example mcp_calculator demonstrates how to create an in-process MCP server with calculator tools using the Claude Agent SDK for Go.
|
Example mcp_calculator demonstrates how to create an in-process MCP server with calculator tools using the Claude Agent SDK for Go. |
|
mcp_control
command
Example: MCP Control Operations
|
Example: MCP Control Operations |
|
mcp_sdk_server
command
Example mcp_sdk_server demonstrates creating an in-process MCP server with custom tools.
|
Example mcp_sdk_server demonstrates creating an in-process MCP server with custom tools. |
|
mcp_sdk_simple
command
Example mcp_sdk_simple demonstrates using the sdkmcp convenience package.
|
Example mcp_sdk_simple demonstrates using the sdkmcp convenience package. |
|
middleware
command
Package main demonstrates transport middleware usage.
|
Package main demonstrates transport middleware usage. |
|
options
command
Package main demonstrates functional options usage.
|
Package main demonstrates functional options usage. |
|
plugin_example
command
Example plugin_example demonstrates SDK plugin configuration in the Claude Agent SDK for Go.
|
Example plugin_example demonstrates SDK plugin configuration in the Claude Agent SDK for Go. |
|
quick_start
command
Example quick_start demonstrates basic usage of the Claude Agent SDK for Go.
|
Example quick_start demonstrates basic usage of the Claude Agent SDK for Go. |
|
setting_sources
command
Example setting_sources demonstrates how to control which settings are loaded.
|
Example setting_sources demonstrates how to control which settings are loaded. |
|
stderr_callback
command
Example stderr_callback demonstrates handling stderr output in the Claude Agent SDK for Go.
|
Example stderr_callback demonstrates handling stderr output in the Claude Agent SDK for Go. |
|
streaming_goroutines
command
Example goroutines demonstrates concurrent patterns using goroutines and channels with the Claude Agent SDK for Go.
|
Example goroutines demonstrates concurrent patterns using goroutines and channels with the Claude Agent SDK for Go. |
|
streaming_interactive
command
Example streaming_interactive demonstrates interactive streaming patterns with the Claude Agent SDK for Go.
|
Example streaming_interactive demonstrates interactive streaming patterns with the Claude Agent SDK for Go. |
|
streaming_mode
command
Example streaming_mode demonstrates using the Claude SDK Client with Connect() for streaming conversations.
|
Example streaming_mode demonstrates using the Claude SDK Client with Connect() for streaming conversations. |
|
system_prompt
command
Example system_prompt demonstrates system prompt configuration in the Claude Agent SDK for Go.
|
Example system_prompt demonstrates system prompt configuration in the Claude Agent SDK for Go. |
|
task_messages
command
Example: Task Messages Handling
|
Example: Task Messages Handling |
|
tool_permission
command
Example tool_permission demonstrates tool permission handling in the Claude Agent SDK for Go.
|
Example tool_permission demonstrates tool permission handling in the Claude Agent SDK for Go. |
|
tools_option
command
Example tools_option demonstrates using Tools, AllowedTools, and DisallowedTools options with the Claude Agent SDK for Go.
|
Example tools_option demonstrates using Tools, AllowedTools, and DisallowedTools options with the Claude Agent SDK for Go. |
|
internal
|
|
|
messageparser
Package messageparser provides functionality to parse raw JSON messages from the Claude CLI into typed Message objects.
|
Package messageparser provides functionality to parse raw JSON messages from the Claude CLI into typed Message objects. |
|
queryimpl
Package query provides internal query implementation for the Claude Agent SDK.
|
Package query provides internal query implementation for the Claude Agent SDK. |
|
sessions
Package sessions provides functions for listing and reading Claude Code sessions.
|
Package sessions provides functions for listing and reading Claude Code sessions. |
|
transportimpl
Package transport provides transport layer implementations for the Claude Agent SDK.
|
Package transport provides transport layer implementations for the Claude Agent SDK. |
|
Package option provides functional options for the Claude Agent SDK.
|
Package option provides functional options for the Claude Agent SDK. |
|
Package query provides a one-shot query function for Claude.
|
Package query provides a one-shot query function for Claude. |
|
Package sdkmcp provides convenience functions for creating in-process MCP servers.
|
Package sdkmcp provides convenience functions for creating in-process MCP servers. |
|
Package transport provides the transport interface for Claude SDK.
|
Package transport provides the transport interface for Claude SDK. |
|
Package types defines the core types used throughout the Claude Agent SDK.
|
Package types defines the core types used throughout the Claude Agent SDK. |