claude

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2025 License: MIT Imports: 9 Imported by: 0

README

Claude Code Go SDK

A Go SDK for integrating Claude AI into your Go applications through the Claude Code CLI. This SDK provides a type-safe, streaming-capable interface with comprehensive error handling.

Installation

go get github.com/upamune/claude-code-go

Prerequisites

  • Claude Code CLI installed and configured
  • Valid Claude API key configured in the CLI

Quick Start

Basic Query
package main

import (
    "context"
    "fmt"
    "log"
    
    claude "github.com/upamune/claude-code-go"
)

func main() {
    ctx := context.Background()
    
    // Check if Claude CLI is available
    if !claude.IsClaudeAvailable() {
        log.Fatal("Claude Code CLI is not installed")
    }
    
    opts := &claude.Options{
        Model: "claude-3-5-sonnet-20241022",
        WorkingDir: "/path/to/project",
    }
    
    result, err := claude.Query(ctx, "Help me write a function", opts)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("Result: %s\n", result.Result)
    fmt.Printf("Cost: $%.4f\n", result.TotalCostUSD)
}
Streaming Output
stream, err := claude.QueryStream(ctx, "Write a detailed explanation", opts)
if err != nil {
    log.Fatal(err)
}
defer stream.Close()

for msg := range stream.Messages {
    if msg.Err != nil {
        log.Printf("Error: %v\n", msg.Err)
        continue
    }
    
    switch m := msg.Message.(type) {
    case *claude.UserMessage:
        fmt.Printf("[USER] %s\n", m.Content)
    case *claude.AssistantMessage:
        if m.ToolCalls != nil {
            fmt.Printf("[ASSISTANT] Using tool: %s\n", m.ToolCalls[0].Name)
        } else {
            fmt.Printf("[ASSISTANT] %s\n", m.PartialContent)
        }
    case *claude.SystemMessage:
        fmt.Printf("[SYSTEM] %s: %s\n", m.Subtype, m.Subtype)
    case *claude.ResultMessage:
        fmt.Printf("\n=== Final Result ===\n%s\n", m.Result)
        fmt.Printf("Total cost: $%.4f\n", m.TotalCostUSD)
    }
}
Using Custom Client
// Create a custom client with specific executor
client := claude.NewClient()

// Or with custom command executor for testing
executor := &MyCustomExecutor{}
client := claude.NewClientWithExecutor(executor)

// Use the client
result, err := client.Query(ctx, "Your prompt", opts)

Features

  • 🚀 Simple, idiomatic Go interface
  • 🔄 Real-time streaming support with channel-based API
  • 🛡️ Type-safe message handling
  • ⚡ Zero dependencies (uses only standard library)
  • 🔧 Customizable client with dependency injection
  • 📊 Built-in cost tracking
  • 🎯 Comprehensive error types

Configuration Options

type Options struct {
    // Model selection
    Model         string   // e.g., "claude-3-5-sonnet-20241022"
    FallbackModel string   // Fallback if primary model unavailable
    
    // Working directory
    WorkingDir string      // Project directory for context
    
    // Tool restrictions
    AllowedTools    []string  // Whitelist specific tools
    DisallowedTools []string  // Blacklist specific tools
    
    // System prompts
    CustomSystemPrompt  string  // Replace default system prompt
    AppendSystemPrompt string  // Append to system prompt
    
    // Resource limits
    MaxThinkingTokens *int     // Limit thinking tokens
    MaxTurns         *int     // Limit conversation turns
    
    // MCP server configuration
    MCPServers map[string]MCPServerConfig  // MCP server configs
    
    // Permission handling
    PermissionMode           PermissionMode  // default, acceptEdits, bypassPermissions, plan
    PermissionPromptToolName string          // Custom permission tool
    
    // Session management
    Continue bool    // Continue previous session
    Resume   string  // Resume specific session ID
    
    // Advanced
    PathToClaudeCodeExecutable string  // Custom CLI path
}
MCP Server Types
// Stdio MCP server
&StdioMCPServerConfig{
    Command: "node",
    Args:    []string{"server.js"},
    Env:     map[string]string{"NODE_ENV": "production"},
}

// SSE MCP server
&SSEMCPServerConfig{
    URL:     "http://localhost:8080/sse",
    Headers: map[string]string{"Authorization": "Bearer token"},
}

// HTTP MCP server
&HTTPMCPServerConfig{
    URL:     "https://api.example.com",
    Headers: map[string]string{"API-Key": "key"},
}

Message Types

Message Type Description Key Fields
UserMessage User input Content, Role
AssistantMessage Claude's responses Content, PartialContent, ToolCalls
ResultMessage Final session result Result, TotalCostUSD, CacheWriteTokens
SystemMessage System events Subtype (info, warning, error)
PermissionRequestMessage Tool permission requests ToolName, Arguments, Reason

Error Handling

result, err := claude.Query(ctx, prompt, opts)
if err != nil {
    switch e := err.(type) {
    case *claude.AbortError:
        // User cancelled operation
        fmt.Println("Operation cancelled")
    case *claude.ProcessError:
        // CLI process error
        fmt.Printf("Process error (exit %d): %s\n", e.ExitCode, e.Message)
    case *claude.ParseError:
        // JSON parsing error
        fmt.Printf("Parse error: %s\n", e.Message)
    case *claude.ConfigError:
        // Configuration error
        fmt.Printf("Config error in %s: %s\n", e.Field, e.Message)
    default:
        // Other errors
        log.Fatal(err)
    }
}

Advanced Usage

Permission Handling
opts := &claude.Options{
    PermissionMode: claude.PermissionModeAsk,
    PermissionPromptToolName: "my_permission_handler",
}

stream, _ := claude.QueryStream(ctx, prompt, opts)
for msg := range stream.Messages {
    if perm, ok := msg.Message.(*claude.PermissionRequestMessage); ok {
        fmt.Printf("Permission requested for %s\n", perm.ToolName)
        // Handle permission request
    }
}
Session Continuation
// Continue previous session
opts := &claude.Options{
    Continue: true,
}

// Resume specific session
opts := &claude.Options{
    Resume: "session-id-123",
}
Tool Restrictions
// Only allow specific tools
opts := &claude.Options{
    AllowedTools: []string{"read_file", "write_file"},
}

// Disallow dangerous tools
opts := &claude.Options{
    DisallowedTools: []string{"run_command", "delete_file"},
}

Examples

  • Basic Usage - Simple query execution
  • More examples coming soon...

API Reference

Package Functions
// Check if Claude CLI is available
func IsClaudeAvailable() bool

// Execute a query (uses default client)
func Query(ctx context.Context, prompt string, opts *Options) (*ResultMessage, error)

// Stream query results (uses default client)
func QueryStream(ctx context.Context, prompt string, opts *Options) (*MessageStream, error)

// Execute raw CLI command
func Exec(ctx context.Context, args []string) (*bytes.Buffer, error)
Client Interface
type Client interface {
    Query(ctx context.Context, prompt string, opts *Options) (*ResultMessage, error)
    QueryStream(ctx context.Context, prompt string, opts *Options) (*MessageStream, error)
}

// Create default client
func NewClient() Client

// Create client with custom executor
func NewClientWithExecutor(executor CommandExecutor) Client
MessageStream
type MessageStream struct {
    Messages <-chan MessageOrError
}

// Close the stream
func (s *MessageStream) Close()

Testing

The SDK is designed with testability in mind. You can inject custom command executors:

type MockExecutor struct{}

func (m *MockExecutor) Execute(ctx context.Context, executable string, args []string, input string) ([]byte, error) {
    // Return mock response
    return []byte(`{"result": "mock result", "totalCostUsd": 0.01}`), nil
}

client := claude.NewClientWithExecutor(&MockExecutor{})

Requirements

  • Go 1.18 or higher
  • Claude Code CLI installed and configured

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see LICENSE file for details

Documentation

Overview

Package claude provides a Go SDK for interacting with Claude Code CLI. It allows you to programmatically execute Claude queries and process responses.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Exec

func Exec(ctx context.Context, args []string) (*bytes.Buffer, error)

Exec executes a raw claude command with custom arguments

func IsClaudeAvailable

func IsClaudeAvailable() bool

IsClaudeAvailable checks if the Claude CLI is available in the system PATH

Types

type AbortError

type AbortError struct {
	Message string
}

AbortError represents an operation that was aborted

func (*AbortError) Error

func (e *AbortError) Error() string

type ArgumentBuilder

type ArgumentBuilder struct{}

ArgumentBuilder builds command line arguments for Claude CLI

func (*ArgumentBuilder) BuildArgs

func (b *ArgumentBuilder) BuildArgs(opts *Options) []string

BuildArgs constructs command line arguments from options

func (*ArgumentBuilder) Validate

func (b *ArgumentBuilder) Validate(opts *Options) error

Validate checks if options are valid

type AssistantMessage

type AssistantMessage struct {
	Type            string          `json:"type"`
	Message         json.RawMessage `json:"message"`
	ParentToolUseID *string         `json:"parent_tool_use_id"`
	SessionID       string          `json:"session_id"`
}

AssistantMessage represents a message from the assistant

type Client

type Client interface {
	Query(ctx context.Context, prompt string, opts *Options) (*ResultMessage, error)
	QueryStream(ctx context.Context, prompt string, opts *Options) (*MessageStream, error)
}

Client interface for Claude Code interaction

func NewClient

func NewClient() Client

NewClient creates a new Client with default components

func NewClientWithExecutor

func NewClientWithExecutor(executor CommandExecutor) Client

NewClientWithExecutor creates a new Client with a custom executor

type CommandExecutor

type CommandExecutor interface {
	Execute(ctx context.Context, name string, args []string, stdin string, workingDir string) ([]byte, error)
	ExecuteStream(ctx context.Context, name string, args []string, stdin string, workingDir string) (io.ReadCloser, error)
}

CommandExecutor is an interface for executing commands

type ConfigError

type ConfigError struct {
	Field   string
	Value   string
	Reason  string
	Message string
}

ConfigError represents a configuration error

func (*ConfigError) Error

func (e *ConfigError) Error() string

type DefaultCommandExecutor

type DefaultCommandExecutor struct{}

DefaultCommandExecutor implements CommandExecutor using os/exec

func (*DefaultCommandExecutor) Execute

func (e *DefaultCommandExecutor) Execute(ctx context.Context, name string, args []string, stdin string, workingDir string) ([]byte, error)

Execute runs a command and returns its output

func (*DefaultCommandExecutor) ExecuteStream

func (e *DefaultCommandExecutor) ExecuteStream(ctx context.Context, name string, args []string, stdin string, workingDir string) (io.ReadCloser, error)

ExecuteStream runs a command and returns a stream of its output

type DefaultMessageParser

type DefaultMessageParser struct{}

DefaultMessageParser implements MessageParser

func (*DefaultMessageParser) ParseMessage

func (p *DefaultMessageParser) ParseMessage(line string) (Message, error)

ParseMessage parses a JSON line into a Message

type MCPHTTPServerConfig

type MCPHTTPServerConfig struct {
	URL     string
	Headers map[string]string
}

MCPHTTPServerConfig represents an HTTP-based MCP server

func (MCPHTTPServerConfig) ToArg

func (c MCPHTTPServerConfig) ToArg() string

ToArg converts the config to a CLI argument string

type MCPSSEServerConfig

type MCPSSEServerConfig struct {
	URL     string
	Headers map[string]string
}

MCPSSEServerConfig represents an SSE-based MCP server

func (MCPSSEServerConfig) ToArg

func (c MCPSSEServerConfig) ToArg() string

ToArg converts the config to a CLI argument string

type MCPServerConfig

type MCPServerConfig interface {
	ToArg() string
	// contains filtered or unexported methods
}

MCPServerConfig is an interface for MCP server configurations

type MCPServerStatus

type MCPServerStatus struct {
	Name   string `json:"name"`
	Status string `json:"status"`
	Error  string `json:"error,omitempty"`
}

MCPServerStatus represents the status of an MCP server

type MCPStdioServerConfig

type MCPStdioServerConfig struct {
	Command string
	Args    []string
	Env     map[string]string
}

MCPStdioServerConfig represents a stdio-based MCP server

func (MCPStdioServerConfig) ToArg

func (c MCPStdioServerConfig) ToArg() string

ToArg converts the config to a CLI argument string

type Message

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

Message is an interface for all message types from Claude Code CLI

func ParseMessage

func ParseMessage(line string) (Message, error)

ParseMessage parses a JSON line from the Claude Code CLI into a Message

type MessageOrError

type MessageOrError struct {
	Message Message
	Err     error
}

MessageOrError wraps a Message or an error

type MessageParser

type MessageParser interface {
	ParseMessage(line string) (Message, error)
}

MessageParser interface for parsing messages

type MessageStream

type MessageStream struct {
	Messages <-chan MessageOrError
	// contains filtered or unexported fields
}

MessageStream represents a stream of messages from Claude

func QueryStream

func QueryStream(ctx context.Context, prompt string, opts *Options) (*MessageStream, error)

QueryStream executes a Claude Code query and returns a channel of messages

func (*MessageStream) Close

func (s *MessageStream) Close()

Close cancels the stream

type Options

type Options struct {
	// Tools configuration
	AllowedTools    []string
	DisallowedTools []string

	// System prompt configuration
	CustomSystemPrompt string
	AppendSystemPrompt string

	// Working directory for the Claude Code CLI
	WorkingDir string

	// Token and turn limits
	MaxThinkingTokens *int
	MaxTurns          *int

	// MCP server configuration
	MCPServers map[string]MCPServerConfig

	// Path to the Claude Code CLI executable
	PathToClaudeCodeExecutable string // Default: "claude"

	// Permission handling
	PermissionMode           PermissionMode
	PermissionPromptToolName string

	// Session continuation
	Continue bool
	Resume   string

	// Model configuration
	Model         string
	FallbackModel string
}

Options configures the behavior of Claude Code SDK

type ParseError

type ParseError struct {
	Line    string
	Message string
}

ParseError represents an error parsing messages from the CLI

func (*ParseError) Error

func (e *ParseError) Error() string

type PermissionMode

type PermissionMode string

PermissionMode represents how the SDK handles permissions for tool use

const (
	// PermissionDefault uses the default permission mode
	PermissionDefault PermissionMode = "default"
	// PermissionAcceptEdits automatically accepts file edits
	PermissionAcceptEdits PermissionMode = "acceptEdits"
	// PermissionBypassPermissions bypasses all permission prompts
	PermissionBypassPermissions PermissionMode = "bypassPermissions"
	// PermissionPlan uses plan mode
	PermissionPlan PermissionMode = "plan"
)

PermissionMode constants define how Claude Code handles permissions for tool use

type PermissionRequestMessage

type PermissionRequestMessage struct {
	Type      string `json:"type"`
	SessionID string `json:"session_id"`
	Subtype   string `json:"subtype"`
}

PermissionRequestMessage represents a permission request for tool use

type ProcessError

type ProcessError struct {
	ExitCode int
	Message  string
}

ProcessError represents an error from the Claude Code CLI process

func (*ProcessError) Error

func (e *ProcessError) Error() string

type ResultMessage

type ResultMessage struct {
	Type          string  `json:"type"`
	Subtype       string  `json:"subtype"`
	DurationMS    int64   `json:"duration_ms"`
	DurationAPIMS int64   `json:"duration_api_ms"`
	IsError       bool    `json:"is_error"`
	NumTurns      int     `json:"num_turns"`
	Result        string  `json:"result,omitempty"`
	SessionID     string  `json:"session_id"`
	TotalCostUSD  float64 `json:"total_cost_usd"`
	Usage         Usage   `json:"usage"`
}

ResultMessage represents the final result of a Claude Code session

func Query

func Query(ctx context.Context, prompt string, opts *Options) (*ResultMessage, error)

Query executes a Claude Code query and returns the result

type SystemMessage

type SystemMessage struct {
	Type           string            `json:"type"`
	Subtype        string            `json:"subtype"`
	APIKeySource   string            `json:"apiKeySource"`
	CWD            string            `json:"cwd"`
	SessionID      string            `json:"session_id"`
	Tools          []string          `json:"tools"`
	MCPServers     []MCPServerStatus `json:"mcp_servers"`
	Model          string            `json:"model"`
	PermissionMode string            `json:"permissionMode"`
}

SystemMessage represents system information from Claude Code CLI

type Usage

type Usage struct {
	CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
	CacheReadInputTokens     int `json:"cache_read_input_tokens,omitempty"`
	InputTokens              int `json:"input_tokens"`
	OutputTokens             int `json:"output_tokens"`
}

Usage represents token usage information

type UserMessage

type UserMessage struct {
	Type            string          `json:"type"`
	Message         json.RawMessage `json:"message"`
	ParentToolUseID *string         `json:"parent_tool_use_id"`
	SessionID       string          `json:"session_id"`
}

UserMessage represents a message from the user

Jump to

Keyboard shortcuts

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