Skip to content

jonwraymond/go-claude-code-sdk

Repository files navigation

Go Claude Code SDK

Go Reference Go Report Card License: MIT Claude Code Test Status Go Version Coverage

A comprehensive Go SDK providing programmatic access to the Claude Code CLI. This SDK offers idiomatic Go interfaces for subprocess-based Claude Code integration, enabling powerful AI-assisted development workflows directly from Go applications.

Key Highlights:

  • ✨ Production Ready - Battle-tested with comprehensive error handling
  • πŸš€ High Performance - Efficient streaming and concurrent operations
  • πŸ”’ Type Safe - Full Go type safety with compile-time validation
  • πŸ“š Well Documented - Extensive examples and API documentation
  • πŸ”„ Actively Maintained - Regular updates and community support

Table of Contents

🎯 Overview

The Go Claude Code SDK provides a production-ready Go wrapper for the Claude Code CLI, enabling seamless integration of AI-powered coding assistance into your Go applications. Built with Go best practices, it offers type-safe interfaces, concurrent operations, and comprehensive error handling.

⚑ Quick Start: Get up and running in under 2 minutes with our Getting Started guide.

πŸ” Looking for specific functionality? Check our Table of Contents below.

πŸ–₯️ Key Features

Core Capabilities:

  • Type-safe interfaces for all Claude Code operations
  • Streaming support for real-time responses with channels
  • Session management for conversation persistence
  • Tool execution including file operations and code analysis
  • MCP server integration for extended capabilities
  • Project-aware context for intelligent code assistance
  • Command system for structured interactions
  • Comprehensive error handling with detailed error types

Go-Specific Advantages:

  • Context propagation with context.Context support throughout
  • Concurrency control with goroutines and proper synchronization
  • Resource management with automatic cleanup and defer patterns
  • Strong typing with compile-time validation
  • Idiomatic error handling following Go conventions

πŸ“Š Feature Parity with Official Claude Code SDKs

Claude Code CLI Features

Feature Python SDK TypeScript SDK Go SDK Notes
Core Features
Query Interface βœ… query() βœ… query() βœ… QueryMessages() Go uses channels for async
Streaming Messages βœ… async iteration βœ… async iteration βœ… Channel-based Idiomatic Go approach
Session Management βœ… --session βœ… --session βœ… Full support Persistent conversations
Message Types
Content Blocks βœ… Full support βœ… Full support βœ… Full support Text, Tool Use, Tool Result
Message Roles βœ… All roles βœ… All roles βœ… All roles User, Assistant, System, Tool
Tool Calls βœ… Native βœ… Native βœ… Native Full tool execution
Configuration
Permission Modes βœ… 3 modes βœ… 3 modes βœ… 3 modes Ask, Accept, Reject
System Prompts βœ… Supported βœ… Supported βœ… Supported Custom instructions
Max Turns βœ… Configurable βœ… Configurable βœ… Configurable Conversation limits
Advanced Features
MCP Server Support βœ… Full βœ… Full βœ… Full All official servers
Project Context βœ… Auto-detect βœ… Auto-detect βœ… Enhanced Multi-language support
Tool Management βœ… Built-in βœ… Built-in βœ… Extended Additional helpers
Command System βœ… Basic βœ… Basic βœ… Extended Slash commands

Go SDK Advantages

  • Strong Type Safety: Compile-time type checking for all operations
  • Concurrency Control: Native goroutine support with proper synchronization
  • Context Cancellation: First-class context.Context support throughout
  • Error Handling: Idiomatic Go error handling with detailed error types
  • Performance: Efficient subprocess management and streaming

πŸš€ Getting Started

Prerequisites

  • Go 1.20 or higher - The SDK uses modern Go features and requires Go 1.20+ (tested up to Go 1.24)
  • Claude Code CLI - Install the official Claude Code CLI:
    npm install -g @anthropic-ai/claude-code
  • Authentication - One of the following:
    • Claude subscription (recommended) - Set up with claude setup-token
    • Anthropic API key from Anthropic Console

Installation

go get github.com/jonwraymond/go-claude-code-sdk

Quick Start

Get up and running with the Go Claude Code SDK in under 5 minutes:

1. Install the SDK

go get github.com/jonwraymond/go-claude-code-sdk

2. Install Claude Code CLI

npm install -g @anthropic-ai/claude-code

3. Set up authentication

# Option A: Use Claude subscription (recommended)
claude setup-token

# Option B: Use API key
export ANTHROPIC_API_KEY="test-api-key-not-real-your-key-here"

4. Write your first program

Here's a simple example to get you started:

package main

import (
    "context"
    "fmt"
    "log"
    
    "github.com/jonwraymond/go-claude-code-sdk/pkg/client"
    "github.com/jonwraymond/go-claude-code-sdk/pkg/types"
)

func main() {
    ctx := context.Background()
    
    // Create configuration with automatic auth detection
    config := types.NewClaudeCodeConfig()
    // The SDK will automatically detect your auth method
    
    // Create the client
    claudeClient, err := client.NewClaudeCodeClient(ctx, config)
    if err != nil {
        log.Fatal("Failed to create client:", err)
    }
    defer claudeClient.Close()
    
    // Make a simple query
    response, err := claudeClient.Query(ctx, &types.QueryRequest{
        Messages: []types.Message{
            {Role: types.RoleUser, Content: "Explain Go channels in simple terms"},
        },
    })
    if err != nil {
        log.Fatal("Query failed:", err)
    }
    
    // Print the response
    for _, block := range response.Content {
        if block.Type == "text" {
            fmt.Println(block.Text)
        }
    }
}

πŸ” Authentication Setup

The SDK supports two authentication methods:

Option 1: Subscription Authentication (Recommended)

# Set up Claude subscription authentication
claude setup-token

The SDK will automatically detect and use subscription authentication when available.

Option 2: API Key Authentication

# Set your API key as an environment variable
export ANTHROPIC_API_KEY="test-api-key-not-real-your-key-here"

Or configure it directly in code:

config := types.NewClaudeCodeConfig()
config.APIKey = "your-api-key"
config.AuthMethod = types.AuthTypeAPIKey

πŸ’» Usage Examples

Session Management

Sessions allow for persistent conversations with Claude:

// Create a session for persistent conversations
session, err := claudeClient.CreateSession(ctx, &types.SessionConfig{
    SessionID: "my-project-session",
    Model:     "claude-3-5-sonnet-20241022",
})
if err != nil {
    log.Fatal("Failed to create session:", err)
}
defer session.Close()

// Use the session for multiple interactions
response1, err := session.Query(ctx, &types.QueryRequest{
    Messages: []types.Message{
        {Role: types.RoleUser, Content: "Analyze this Go project structure"},
    },
})

// Continue the conversation
response2, err := session.Query(ctx, &types.QueryRequest{
    Messages: []types.Message{
        {Role: types.RoleUser, Content: "Now suggest improvements"},
    },
})

Streaming Responses

For real-time responses, use the streaming API:

// Create a streaming request
request := &types.QueryRequest{
    Messages: []types.Message{
        {Role: types.RoleUser, Content: "Explain goroutines with examples"},
    },
    Model: "claude-3-5-sonnet-20241022",
}

// Start streaming
stream, err := claudeClient.QueryStream(ctx, request)
if err != nil {
    log.Fatal("Failed to start stream:", err)
}
defer stream.Close()

fmt.Print("Claude: ")
for {
    chunk, err := stream.Recv()
    if err != nil {
        log.Printf("Stream error: %v", err)
        break
    }
    
    if chunk.Done {
        fmt.Println("\nβœ“ Response complete")
        break
    }
    
    // Print content in real-time
    fmt.Print(chunk.Content)
}

Advanced Configuration

Customize the client with various options:

// Create advanced configuration
config := &types.ClaudeCodeConfig{
    Model:            "claude-3-5-sonnet-20241022",
    WorkingDirectory: "/path/to/your/project",
    MaxTokens:        8000,
    Temperature:      0.7,
    AuthMethod:       types.AuthTypeAPIKey,
    APIKey:           os.Getenv("ANTHROPIC_API_KEY"),
    Debug:            true,
    Timeout:          60 * time.Second,
    Environment: map[string]string{
        "PROJECT_TYPE": "go-microservice",
        "DEBUG_MODE":   "true",
    },
}

// Apply defaults for any unset values
config.ApplyDefaults()

// Create client with custom config
claudeClient, err := client.NewClaudeCodeClient(ctx, config)

Project Context Detection

The SDK automatically detects your project structure and provides intelligent context:

// Get enhanced project context
projectCtx, err := claudeClient.GetProjectContext(ctx)
if err != nil {
    log.Fatal("Failed to get project context:", err)
}

fmt.Printf("Project Details:\n")
fmt.Printf("  Working Directory: %s\n", projectCtx.WorkingDirectory)
fmt.Printf("  Git Repository: %t\n", projectCtx.IsGitRepository)
fmt.Printf("  Project Type: %s\n", projectCtx.ProjectType)

// Use context in conversations
response, err := claudeClient.Query(ctx, &types.QueryRequest{
    Messages: []types.Message{
        {
            Role: types.RoleUser, 
            Content: fmt.Sprintf("Help me improve this %s project", projectCtx.ProjectType),
        },
    },
})

Error Handling and Timeouts

Robust error handling with context support:

// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

// Make request with timeout
response, err := claudeClient.Query(ctx, &types.QueryRequest{
    Messages: []types.Message{
        {Role: types.RoleUser, Content: "Analyze this large codebase"},
    },
})

if err != nil {
    // Handle different error types
    if errors.Is(err, context.DeadlineExceeded) {
        log.Println("Request timed out")
    } else if claudeErr, ok := err.(*errors.ClaudeCodeError); ok {
        log.Printf("Claude Code error: %s (code: %s)", claudeErr.Message, claudeErr.Code)
        if claudeErr.IsRetryable() {
            log.Println("Error is retryable")
        }
    } else {
        log.Printf("Unexpected error: %v", err)
    }
    return
}

// Process successful response
for _, block := range response.Content {
    if block.Type == "text" {
        fmt.Println(block.Text)
    }
}

Working with Multiple Models

Switch between different Claude models for different tasks:

// Use different models for different purposes
configs := map[string]*types.ClaudeCodeConfig{
    "analysis": {
        Model: "claude-3-5-sonnet-20241022", // Best for complex analysis
        MaxTokens: 8000,
        Temperature: 0.1, // Lower temperature for precise analysis
    },
    "creative": {
        Model: "claude-3-opus-20240229", // Best for creative tasks
        MaxTokens: 4000,
        Temperature: 0.7, // Higher temperature for creativity
    },
}

// Create clients for different use cases
analysisClient, err := client.NewClaudeCodeClient(ctx, configs["analysis"])
if err != nil {
    log.Fatal("Failed to create analysis client:", err)
}
defer analysisClient.Close()

creativeClient, err := client.NewClaudeCodeClient(ctx, configs["creative"])
if err != nil {
    log.Fatal("Failed to create creative client:", err)
}
defer creativeClient.Close()

// Use appropriate client for each task
codeAnalysis, _ := analysisClient.Query(ctx, &types.QueryRequest{
    Messages: []types.Message{
        {Role: types.RoleUser, Content: "Analyze the performance of this algorithm"},
    },
})

documentation, _ := creativeClient.Query(ctx, &types.QueryRequest{
    Messages: []types.Message{
        {Role: types.RoleUser, Content: "Write engaging documentation for this API"},
    },
})

πŸ› οΈ Design Philosophy

Subprocess Architecture

The Go Claude Code SDK embraces Claude Code's subprocess-based design:

  • Direct CLI Integration: Executes claude commands via subprocess
  • Streaming I/O: Real-time parsing of stdout/stderr
  • Process Management: Proper lifecycle management with cleanup
  • Session Persistence: Leverages Claude Code's --session flag

Go Idioms

The SDK follows Go best practices:

  • Context Propagation: All operations accept context.Context
  • Error Handling: Explicit error returns with typed errors
  • Interface Design: Small, composable interfaces
  • Concurrency Safety: Thread-safe operations with proper locking
  • Resource Management: Automatic cleanup with defer patterns

Type Safety

Strong typing throughout:

// Typed command system
cmd := &types.Command{
    Type: types.CommandAnalyze,  // Not a string
    Args: []string{"src/"},
}

// Typed message roles
msg := types.NewTextMessage(types.MessageRoleUser, "Hello")

// Typed configuration
options := &client.QueryOptions{
    PermissionMode: client.PermissionModeAcceptEdits,  // Not a string
}

πŸ”§ Advanced Features

Custom Tool Registration

// Register a custom tool
customTool := &client.ClaudeCodeToolDefinition{
    Name:        "my_tool",
    Description: "My custom tool",
    InputSchema: map[string]interface{}{
        "type": "object",
        "properties": map[string]interface{}{
            "input": map[string]interface{}{"type": "string"},
        },
    },
}

err = client.Tools().RegisterTool("my_tool", customTool)

Error Handling

result, err := client.QueryMessagesSync(ctx, "Build the project", nil)
if err != nil {
    switch e := err.(type) {
    case *errors.ClaudeCodeError:
        if e.IsRetryable() {
            // Retry logic
        }
    case *errors.ValidationError:
        // Handle validation error
    default:
        // Handle other errors
    }
}

Cancellation and Timeouts

// With timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

messages, err := client.QueryMessages(ctx, "Analyze this codebase", nil)
if err != nil {
    if errors.Is(err, context.DeadlineExceeded) {
        log.Println("Operation timed out")
    }
}

// With cancellation
ctx, cancel := context.WithCancel(context.Background())
go func() {
    // Cancel after some condition
    time.Sleep(5 * time.Second)
    cancel()
}()

messages, err := client.QueryMessages(ctx, "Long running task", nil)

🌍 Supported Environments

Operating Systems

  • βœ… Linux - Ubuntu 20.04+, CentOS 8+, Alpine 3.14+
  • βœ… macOS - macOS 11.0+ (Big Sur and later)
  • βœ… Windows - Windows 10/11, Windows Server 2019+

Go Versions

  • βœ… Go 1.20 - Minimum required version
  • βœ… Go 1.21 - Fully supported with enhanced features
  • βœ… Go 1.22 - Latest features and optimizations
  • βœ… Go 1.23 - Stable, fully tested and supported
  • βœ… Go 1.24 - Latest version, fully tested and supported

Claude Code CLI

  • βœ… Latest Version - Always recommended for best compatibility
  • βœ… v1.0.0+ - Minimum supported version
  • ⚠️ Development Versions - May work but not officially supported

Shell Requirements

  • βœ… Linux/macOS: Bash 4.0+, Zsh 5.0+, Fish 3.0+
  • βœ… Windows: PowerShell 5.1+, Command Prompt, Git Bash
  • βœ… Container: Docker, Podman (with Node.js 18+ base image)

Node.js Requirements (for Claude Code CLI)

  • βœ… Node.js 18+ - Required for Claude Code CLI
  • βœ… npm 8+ - For installing Claude Code CLI
  • ⚠️ Yarn/pnpm - May work but npm is recommended

πŸ“¦ Project Structure

go-claude-code-sdk/
β”œβ”€β”€ pkg/                # Claude Code CLI wrapper
β”‚   β”œβ”€β”€ client/         # Main CLI client implementation
β”‚   β”œβ”€β”€ types/          # CLI type definitions
β”‚   β”œβ”€β”€ errors/         # Error types and handling
β”‚   └── auth/           # Authentication helpers
β”œβ”€β”€ examples/           # Example applications
β”œβ”€β”€ docs/               # Comprehensive documentation
β”‚   β”œβ”€β”€ API.md          # Complete API reference
β”‚   β”œβ”€β”€ QUERY_OPTIONS.md # Query configuration guide
β”‚   └── COMPATIBILITY_GUIDE.md # Migration guidance
β”œβ”€β”€ .github/
β”‚   └── workflows/      # CI/CD configuration
β”œβ”€β”€ go.mod             # Go module definition
β”œβ”€β”€ LICENSE            # MIT License
β”œβ”€β”€ README.md          # This file (overview)
β”œβ”€β”€ CHANGELOG.md       # Version history
└── CONTRIBUTING.md    # Contribution guidelines

πŸ“š Examples

The SDK includes comprehensive examples demonstrating various use cases:

Quick Reference

Example Description Use Case
Basic Client Simple query/response Getting started, basic AI assistance
Streaming Queries Real-time responses Long-form content, live feedback
Session Lifecycle Conversation persistence Multi-turn conversations, context
Advanced Client Custom configuration Production deployments
Authentication Methods Auth setup Different deployment scenarios
MCP Integration Tool extensions Enhanced functionality
Command Execution CLI commands Automated workflows

To run any example:

# Navigate to the example directory
cd examples/basic_client

# Set up authentication (choose one):
export ANTHROPIC_API_KEY="your-api-key"  # API key method
# OR
claude setup-token                        # Subscription method

# Run the example
go run main.go

Example Output

Here's what you can expect from the basic client example:

πŸš€ Starting Claude Code SDK Example
βœ… Client created successfully
πŸ“ Sending query: "Explain Go channels in simple terms"
πŸ’­ Claude: Go channels are like pipes that allow different parts of your program 
(called goroutines) to communicate safely with each other...
βœ… Query completed successfully

See the examples README for detailed information about each example.

🎯 Use Cases

The Go Claude Code SDK is perfect for:

Development Workflows:

  • βœ… AI-assisted code review and analysis
  • βœ… Automated documentation generation
  • βœ… Code refactoring and optimization suggestions
  • βœ… Test case generation and validation

Integration Scenarios:

  • βœ… CI/CD pipeline integration for code analysis
  • βœ… IDE and editor extensions
  • βœ… Developer tools and utilities
  • βœ… Automated code quality assessment

Application Types:

  • βœ… Command-line developer tools
  • βœ… Code analysis and linting services
  • βœ… Documentation generation systems
  • βœ… Educational coding platforms

🀝 Contributing

We welcome contributions from the community! Whether you're fixing bugs, adding features, or improving documentation, your help is appreciated.

Getting Started

  1. Fork the repository and clone your fork
  2. Set up the development environment following our Contributing Guidelines
  3. Create a new branch for your feature or fix
  4. Make your changes with tests and documentation
  5. Submit a pull request with a clear description

Contribution Areas

  • πŸ› Bug fixes - Help us improve reliability
  • ✨ New features - Extend SDK capabilities
  • πŸ“š Documentation - Improve guides and examples
  • πŸ§ͺ Testing - Increase test coverage
  • πŸ”§ Performance - Optimize existing functionality

See our Contributing Guidelines for detailed information about:

  • Development setup and workflow
  • Code style and standards
  • Testing requirements
  • Pull request process

πŸ“œ License

This project is licensed under the MIT License - see the LICENSE file for details.

The MIT License allows for:

  • βœ… Commercial use
  • βœ… Modification and distribution
  • βœ… Private use
  • ❓ Provided "as is" without warranty

πŸ™ Acknowledgments

Special thanks to:

  • Anthropic for creating Claude and the Claude Code CLI
  • The Go Community for excellent tooling, standards, and best practices
  • Contributors who have helped improve this SDK
  • Early adopters who provided valuable feedback and testing

πŸ”§ Troubleshooting

Common Issues and Solutions

Installation Issues

Problem: go get fails with module not found

go: module github.com/jonwraymond/go-claude-code-sdk: not found

Solution: Ensure you're using Go 1.20+ and the correct module path:

go version  # Should be 1.20 or higher
go get -u github.com/jonwraymond/go-claude-code-sdk

Authentication Issues

Problem: "Authentication failed" or "API key not found"

Error: authentication failed: invalid API key

Solutions:

  1. For API Key Authentication:

    export ANTHROPIC_API_KEY="test-api-key-not-real-your-key-here"

    Or set it directly in code:

    config := &types.ClaudeCodeConfig{
        APIKey: "your-api-key",
        AuthMethod: types.AuthTypeAPIKey,
    }
  2. For Subscription Authentication:

    claude setup-token

    Then use:

    config := &types.ClaudeCodeConfig{
        AuthMethod: types.AuthTypeSubscription,
    }

Claude Code CLI Issues

Problem: "claude command not found"

Error: exec: "claude": executable file not found in $PATH

Solutions:

  1. Install Claude Code CLI:
    npm install -g @anthropic-ai/claude-code
  2. Verify installation:
    claude --version
    which claude
  3. If using a custom path, configure it:
    config := &types.ClaudeCodeConfig{
        ClaudePath: "/custom/path/to/claude",
    }

Session Issues

Problem: Session creation fails or sessions don't persist

Error: failed to create session: session directory not accessible

Solutions:

  1. Ensure write permissions in working directory:
    ls -la /path/to/your/project
    chmod 755 /path/to/your/project
  2. Use absolute paths:
    config := &types.ClaudeCodeConfig{
        WorkingDirectory: "/absolute/path/to/project",
    }
  3. Check session ID format (must be valid for filesystem):
    // Good: alphanumeric with hyphens
    sessionID := "my-project-session-123"
    
    // Bad: contains invalid characters
    sessionID := "my/project\\session*123"

Streaming Issues

Problem: Streaming responses hang or timeout

Error: context deadline exceeded while streaming

Solutions:

  1. Increase timeout:
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
    defer cancel()
  2. Handle context cancellation properly:
    stream, err := client.QueryStream(ctx, request)
    if err != nil {
        if errors.Is(err, context.DeadlineExceeded) {
            log.Println("Request timed out - try increasing timeout")
        }
        return err
    }

Performance Issues

Problem: Slow response times or high memory usage Solutions:

  1. Optimize project context:
    config := &types.ClaudeCodeConfig{
        IncludeProjectContext: false, // For large projects
        MaxProjectFiles: 100,         // Limit files included
    }
  2. Use appropriate models:
    // For simple queries - faster and cheaper
    config.Model = "claude-3-haiku-20240307"
    
    // For complex analysis - more capable but slower
    config.Model = "claude-3-5-sonnet-20241022"
  3. Implement connection pooling for multiple clients:
    var clientPool = sync.Pool{
        New: func() interface{} {
            client, _ := client.NewClaudeCodeClient(ctx, config)
            return client
        },
    }

Debugging Tips

Enable Debug Logging

config := &types.ClaudeCodeConfig{
    Debug: true,
    LogLevel: "debug",
}

Check Claude Code CLI Directly

# Test CLI directly
claude query "Hello, Claude!"

# Check version compatibility
claude --version

# Test with session
claude query --session test-session "What's my session ID?"

Inspect Network Issues

# Check connectivity to Anthropic
curl -I https://api.anthropic.com/

# Test with verbose output
claude query --debug "Test connection"

Environment-Specific Issues

Windows

  • Ensure PowerShell or CMD is properly configured
  • Use forward slashes in paths: /path/to/project
  • Set environment variables in PowerShell:
    $env:ANTHROPIC_API_KEY="your-key"

macOS

  • Install Claude Code CLI via npm (not Homebrew)
  • Ensure npm global bin directory is in PATH:
    echo $PATH | grep $(npm config get prefix)/bin

Linux

  • Install Node.js 18+ for Claude Code CLI compatibility
  • For Ubuntu/Debian:
    curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
    sudo apt-get install -y nodejs

Getting More Help

If you're still experiencing issues:

  1. Check our GitHub Issues for known problems
  2. Review the Claude Code CLI documentation
  3. Enable debug logging and include logs in your issue report
  4. Provide a minimal reproduction case when reporting bugs

πŸ“ž Support & Community

Getting Help

Before Reporting Issues

  1. Check existing issues to avoid duplicates
  2. Review the documentation and troubleshooting guide
  3. Test with the latest version of the SDK and Claude Code CLI
  4. Enable debug logging and include relevant logs
  5. Provide minimal reproduction steps when reporting bugs
  6. Test with Claude Code CLI directly to isolate SDK vs CLI issues

Community Guidelines

  • Be respectful and inclusive
  • Help newcomers get started
  • Share knowledge and best practices
  • Follow our Code of Conduct


Built with ❀️ for the Go and Claude Code communities

Empowering developers with AI-assisted coding workflows through idiomatic Go interfaces.

Made with Go Powered by Claude Open Source

Get Started β€’ Examples β€’ API Docs β€’ Issues

About

Go SDK for Claude Code CLI - Seamless integration with Anthropic's Claude AI coding assistant

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors