Documentation
¶
Overview ¶
Package claudecode provides a Go SDK for programmatically interacting with Claude Code, Anthropic's AI coding assistant.
This package allows you to launch Claude Code sessions, manage their lifecycle, and process their output in various formats (text, JSON, or streaming JSON).
Basic usage:
client, err := claudecode.NewClient() if err != nil { log.Fatal(err) } result, err := client.LaunchAndWait(claudecode.SessionConfig{ Query: "Write a hello world function", }) fmt.Println(result.Result)
For streaming output:
session, err := client.Launch(claudecode.SessionConfig{ Query: "Build a web server", OutputFormat: claudecode.OutputStreamJSON, }) for event := range session.Events { // Process events as they arrive }
The SDK supports all Claude Code CLI options including MCP servers, session resumption, and custom system prompts.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client provides methods to interact with the Claude Code SDK
func NewClientWithPath ¶
NewClientWithPath creates a new client with a specific claude binary path
func (*Client) Launch ¶
func (c *Client) Launch(config SessionConfig) (*Session, error)
Launch starts a new Claude session and returns immediately
Example (Streaming) ¶
// Create a new client client, err := claudecode.NewClient() if err != nil { log.Fatal(err) } // Launch with streaming JSON session, err := client.Launch(claudecode.SessionConfig{ Query: "Build a REST API", Model: claudecode.ModelSonnet, OutputFormat: claudecode.OutputStreamJSON, MaxTurns: 5, }) if err != nil { log.Fatal(err) } // Process events as they arrive for event := range session.Events { switch event.Type { case "system": if event.Subtype == "init" { fmt.Printf("Session started: %s\n", event.SessionID) fmt.Printf("Available tools: %v\n", event.Tools) } case "assistant": // Handle assistant messages if event.Message != nil && len(event.Message.Content) > 0 { fmt.Printf("Assistant: %s\n", event.Message.Content[0].Text) } case "result": fmt.Printf("Completed! Cost: $%.4f\n", event.CostUSD) } } // Wait for completion result, err := session.Wait() if err != nil { log.Fatal(err) } fmt.Printf("Session %s completed in %dms\n", result.SessionID, result.DurationMS)
Example (WithMCP) ¶
client, err := claudecode.NewClient() if err != nil { log.Fatal(err) } // Configure MCP server for approvals mcpConfig := &claudecode.MCPConfig{ MCPServers: map[string]claudecode.MCPServer{ "approvals": { Command: "npm", Args: []string{"run", "dev", "mcp", "claude_approvals"}, }, "filesystem": { Command: "npx", Args: []string{"-y", "@modelcontextprotocol/server-filesystem", "/tmp"}, }, }, } // Launch with MCP and approvals session, err := client.Launch(claudecode.SessionConfig{ Query: "Delete all files in /tmp", OutputFormat: claudecode.OutputStreamJSON, MCPConfig: mcpConfig, PermissionPromptTool: "mcp__approvals__request_permission", AllowedTools: []string{"mcp__filesystem__*", "mcp__approvals__*"}, }) if err != nil { log.Fatal(err) } // Process events for event := range session.Events { // Handle events... _ = event } result, err := session.Wait() if err != nil { log.Fatal(err) } fmt.Printf("Completed with %d turns\n", result.NumTurns)
func (*Client) LaunchAndWait ¶
func (c *Client) LaunchAndWait(config SessionConfig) (*Result, error)
LaunchAndWait starts a Claude session and waits for it to complete
Example ¶
// Create a new client client, err := claudecode.NewClient() if err != nil { log.Fatal(err) } // Simple text output result, err := client.LaunchAndWait(claudecode.SessionConfig{ Query: "Write a hello world function in Go", OutputFormat: claudecode.OutputText, }) if err != nil { log.Fatal(err) } fmt.Println("Claude says:", result.Result)
type Content ¶
type Content struct { Type string `json:"type"` Text string `json:"text,omitempty"` Thinking string `json:"thinking,omitempty"` ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` Input map[string]interface{} `json:"input,omitempty"` ToolUseID string `json:"tool_use_id,omitempty"` Content string `json:"content,omitempty"` }
Content can be text or tool use
type MCPServer ¶
type MCPServer struct { Command string `json:"command"` Args []string `json:"args,omitempty"` Env map[string]string `json:"env,omitempty"` }
MCPServer represents a single MCP server configuration
type Message ¶
type Message struct { ID string `json:"id"` Type string `json:"type"` Role string `json:"role"` Model string `json:"model,omitempty"` Content []Content `json:"content"` Usage *Usage `json:"usage,omitempty"` }
Message represents an assistant or user message
type OutputFormat ¶
type OutputFormat string
OutputFormat specifies the output format for Claude CLI
const ( OutputText OutputFormat = "text" OutputJSON OutputFormat = "json" OutputStreamJSON OutputFormat = "stream-json" )
type Result ¶
type Result struct { Type string `json:"type"` Subtype string `json:"subtype"` CostUSD float64 `json:"total_cost_usd"` IsError bool `json:"is_error"` DurationMS int `json:"duration_ms"` DurationAPI int `json:"duration_api_ms"` NumTurns int `json:"num_turns"` Result string `json:"result"` SessionID string `json:"session_id"` Usage *Usage `json:"usage,omitempty"` Error string `json:"error,omitempty"` }
Result represents the final result of a Claude session
type ServerToolUse ¶
type ServerToolUse struct {
WebSearchRequests int `json:"web_search_requests,omitempty"`
}
ServerToolUse tracks server-side tool usage
type Session ¶
type Session struct { ID string Config SessionConfig StartTime time.Time // For streaming Events chan StreamEvent // contains filtered or unexported fields }
Session represents an active Claude session
func (*Session) Wait ¶
Wait blocks until the session completes and returns the result TODO: Add context support to allow cancellation/timeout. This would help prevent indefinite blocking when waiting for interrupted sessions or hanging processes. Consider adding WaitContext(ctx context.Context) method or updating Wait() signature.
type SessionConfig ¶
type SessionConfig struct { // Required Query string // Session management SessionID string // If set, resumes this session // Optional Model Model OutputFormat OutputFormat MCPConfig *MCPConfig PermissionPromptTool string WorkingDir string MaxTurns int SystemPrompt string AppendSystemPrompt string AllowedTools []string DisallowedTools []string CustomInstructions string Verbose bool }
SessionConfig contains all configuration for launching a Claude session
Example (Resume) ¶
client, err := claudecode.NewClient() if err != nil { log.Fatal(err) } // Resume a previous session result, err := client.LaunchAndWait(claudecode.SessionConfig{ SessionID: "550e8400-e29b-41d4-a716-446655440000", Query: "Add error handling to the previous code", OutputFormat: claudecode.OutputJSON, }) if err != nil { log.Fatal(err) } fmt.Printf("Resumed session cost: $%.4f\n", result.CostUSD)
type StreamEvent ¶
type StreamEvent struct { Type string `json:"type"` Subtype string `json:"subtype,omitempty"` SessionID string `json:"session_id,omitempty"` Message *Message `json:"message,omitempty"` Tools []string `json:"tools,omitempty"` MCPServers []MCPStatus `json:"mcp_servers,omitempty"` // Parent tracking for sub-tasks ParentToolUseID string `json:"parent_tool_use_id,omitempty"` // System event fields (when type="system" and subtype="init") CWD string `json:"cwd,omitempty"` Model string `json:"model,omitempty"` PermissionMode string `json:"permissionMode,omitempty"` APIKeySource string `json:"apiKeySource,omitempty"` // Result event fields (when type="result") CostUSD float64 `json:"total_cost_usd,omitempty"` IsError bool `json:"is_error,omitempty"` DurationMS int `json:"duration_ms,omitempty"` DurationAPI int `json:"duration_api_ms,omitempty"` NumTurns int `json:"num_turns,omitempty"` Result string `json:"result,omitempty"` Usage *Usage `json:"usage,omitempty"` Error string `json:"error,omitempty"` }
StreamEvent represents a single event from the streaming JSON output
type Usage ¶
type Usage struct { InputTokens int `json:"input_tokens"` OutputTokens int `json:"output_tokens"` CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"` CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"` ServiceTier string `json:"service_tier,omitempty"` ServerToolUse *ServerToolUse `json:"server_tool_use,omitempty"` }
Usage tracks token usage