claude-agent-sdk-go

by severity1Verified

Unofficial Go SDK for Claude Code CLI integration. See the Claude Agent SDK documentation for more information. This project has been renamed from claude-code-sdk-go.

151
Stars
29
Forks
Go
Language
8/23/2026
Added
View on GitHubDownload ZIP

⚠️ Third-Party Software Notice

This skill is third-party open-source software developed and hosted independently on GitHub. SkillTip is an informational directory and does not control or maintain the underlying repository. Any security checks displayed are automated and limited in scope. Review the source code before installing.

Read the Terms of Service

Installation

Add to your Claude Code skills directory:

# Add to your Claude Code skills
git clone https://github.com/severity1/claude-agent-sdk-go

Getting Started

Guides for using skills like claude-agent-sdk-go.

Security Report

Verified

Last scanned: —

{
  "status": "PASSED",
  "issues": []
}

README.md

Claude Agent SDK for Go

Go Gopher

CI Go Reference Go Report Card codecov License: MIT

Unofficial Go SDK for Claude Code CLI integration. Build production-ready applications that leverage Claude's advanced code understanding, secure file operations, and external tool integrations through a clean, idiomatic Go API with comprehensive error handling and automatic resource management.

Two powerful APIs for different use cases:

  • Query API: One-shot operations, automation, CI/CD integration
  • Client API: Interactive conversations, multi-turn workflows, streaming responses
  • WithClient: Go-idiomatic context manager for automatic resource management

Claude Agent SDK in Action

Installation

go get github.com/severity1/claude-agent-sdk-go

Prerequisites: Go 1.18+, Node.js, Claude Code (npm install -g @anthropic-ai/claude-code)

Key Features

Two APIs for different needs - Query for automation, Client for interaction 100% Python SDK compatibility - Same functionality, Go-native design Automatic resource management - WithClient provides Go-idiomatic context manager pattern Session management - Isolated conversation contexts with Query() and QueryWithSession() Built-in tool integration - File operations, AWS, GitHub, databases, and more Production ready - Comprehensive error handling, timeouts, resource cleanup Security focused - Granular tool permissions and access controls Context-aware - Maintain conversation state across multiple interactions Advanced capabilities - Permission callbacks, lifecycle hooks, file checkpointing

Usage

Query API - One-Shot Operations

Best for automation, scripting, and tasks with clear completion criteria:

package main

import (
    "context"
    "errors"
    "fmt"
    "log"

    "github.com/severity1/claude-agent-sdk-go"
)

func main() {
    fmt.Println("Claude Agent SDK - Query API Example")
    fmt.Println("Asking: What is 2+2?")

    ctx := context.Background()

    // Create and execute query
    iterator, err := claudecode.Query(ctx, "What is 2+2?")
    if err != nil {
        // Use error type helpers for specific error handling
        if cliErr := claudecode.AsCLINotFoundError(err); cliErr != nil {
            fmt.Printf("Claude CLI not found: %v\n", cliErr)
            fmt.Println("Install with: npm install -g @anthropic-ai/claude-code")
            return
        }
        if connErr := claudecode.AsConnectionError(err); connErr != nil {
            fmt.Printf("Connection failed: %v\n", connErr)
            return
        }
        log.Fatalf("Query failed: %v", err)
    }
    defer iterator.Close()

    fmt.Println("\nResponse:")

    // Iterate through messages
    for {
        message, err := iterator.Next(ctx)
        if err != nil {
            if errors.Is(err, claudecode.ErrNoMoreMessages) {
                break
            }
            log.Fatalf("Failed to get message: %v", err)
        }

        if message == nil {
            break
        }

        // Handle different message types
        switch msg := message.(type) {
        case *claudecode.AssistantMessage:
            for _, block := range msg.Content {
                if textBlock, ok := block.(*claudecode.TextBlock); ok {
                    fmt.Print(textBlock.Text)
                }
            }
        case *claudecode.ResultMessage:
            if msg.IsError {
                if msg.Result != nil {
                    log.Printf("Error: %s", *msg.Result)
                } else {
                    log.Printf("Error: unknown error")
                }
            }
        }
    }

    fmt.Println("\nQuery completed!")
}

Client API - Interactive & Multi-Turn

WithClient provides automatic resource management (equivalent to Python's async with):

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/severity1/claude-agent-sdk-go"
)

func main() {
    fmt.Println("Claude Agent SDK - Client Streaming Example")
    fmt.Println("Asking: Explain Go goroutines with a simple example")

    ctx := context.Background()
    question := "Explain what Go goroutines are and show a simple example"

    // WithClient handles connection lifecycle automatically
    err := claudecode.WithClient(ctx, func(client claudecode.Client) error {
        fmt.Println("\nConnected! Streaming response:")

        // Simple query uses default session
        if err := client.Query(ctx, question); err != nil {
            return fmt.Errorf("query failed: %w", err)
        }

        // Stream messages in real-time
        msgChan := client.ReceiveMessages(ctx)
        for {
            select {
            case message := <-msgChan:
                if message == nil {
                    return nil // Stream ended
                }

                switch msg := message.(type) {
                case *claudecode.AssistantMessage:
                    // Print streaming text as it arrives
                    for _, block := range msg.Content {
                        if textBlock, ok := block.(*claudecode.TextBlock); ok {
                            fmt.Print(textBlock.Text)
                        }
                    }
                case *claudecode.ResultMessage:
                    if msg.IsError {
                        if msg.Result != nil {
                            return fmt.Errorf("error: %s", *msg.Result)
                        }
                        return fmt.Errorf("error: unknown error")
                    }
                    return nil // Success, stream complete
                }
            case <-ctx.Done():
                return ctx.Err()
            }
        }
    })

    if err != nil {
        log.Fatalf("Streaming failed: %v", err)
    }

    fmt.Println("\n\nStreaming completed!")
}

Session Management

Maintain conversation context across multiple queries with session management:

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/severity1/claude-agent-sdk-go"
)

func main() {
    fmt.Println("Claude Agent SDK - Session Management Example")

    ctx := context.Background()

    err := claudecode.WithClient(ctx, func(client claudecode.Client) error {
        fmt.Println("\nDemonstrating isolated sessions:")

        // Session A: Math conversation
        sessionA := "math-session"
        if err := client.QueryWithSession(ctx, "Remember this: x = 5", sessionA); err != nil {
            return err
        }

        // Session B: Programming conversation
        sessionB := "programming-session"
        if err := client.QueryWithSession(ctx, "Remember this: language = Go", sessionB); err != nil {
            return err
        }

        // Query each session - they maintain separate contexts
        fmt.Println("\nQuerying math session:")
        if err := client.QueryWithSession(ctx, "What is x * 2?", sessionA); err != nil {
            return err
        }

        fmt.Println("\nQuerying programming session:")
        if err := client.QueryWithSession(ctx, "What language did I mention?", sessionB); err != nil {
            return err
        }

        // Default session query (separate from above)
        fmt.Println("\nDefault session (no context from above):")
        return client.Query(ctx, "What did I just ask about?") // Won't know about x or Go
    })

    if err != nil {
        log.Fatalf("Session demo failed: %v", err)
    }

    fmt.Println("Session management demo completed!")
}

Traditional Client API (still supported):

Click to see manual resource management approach
func traditionalClientExample() {
    ctx := context.Background()
    
    client := claudecode.NewClient()
    if err := client.Connect(ctx); err != nil {
        log.Fatalf("Failed to connect: %v", err)
    }
    defer client.Disconnect() // Manual cleanup required
    
    // Use client...
}

Tool Integration & External Services

Integrate with file systems, cloud services, databases, and development tools:

Core Tools (built-in file operations):

// File analysis and documentation generation
claudecode.Query(ctx, "Read all Go files and create API documentation",
    claudecode.WithAllowedTools("Read", "Write"))

MCP Tools (external service integrations):

// AWS infrastructure automation
claudecode.Query(ctx, "List my S3 buckets and analyze their security settings",
    claudecode.WithAllowedTools("mcp__aws-api-mcp__call_aws", "mcp__aws-api-mcp__suggest_aws_commands", "Write"))

Configuration Options

Customize Claude's behavior with functional options:

Tool & Permission Control:

claudecode.Query(ctx, prompt,
    claudecode.WithAllowedTools("Read", "Write"),
    claudecode.WithPermissionMode(claudecode.PermissionModeAcceptEdits))

System Behavior:

claudecode.Query(ctx, prompt,
    claudecode.WithSystemPrompt("You are a senior Go developer"),
    claudecode.WithModel("claude-sonnet-4-5"),
    claudecode.WithMaxTurns(10))

Environment Variables (new in v0.2.5):

// Proxy configuration
claudecode.NewClient(
    claudecode.WithEnv(map[string]string{
        "HTTP_PROXY":  "http://proxy.example.com:8080",
        "HTTPS_PROXY": "http://proxy.example.com:8080",
    }))

// Individual variables
claudecode.NewClient(
    claudecode.WithEnvVar("DEBUG", "1"),
    claudecode.WithEnvVar("CUSTOM_PATH", "/usr/local/bin"))

Context & Working Directory:

claudecode.Query(ctx, prompt,
    claudecode.WithCwd("/path/to/project"),
    claudecode.WithAddDirs("src", "docs"))

Session Management (Client API):

// WithClient provides isolated session contexts
err := claudecode.WithClient(ctx, func(client claudecode.Client) error {
    // Default session
    client.Query(ctx, "Remember: x = 5")

    // Named session (isolated context)
    return client.QueryWithSession(ctx, "What is x?", "math-session")
})

Programmatic Agents:

// Define custom agents for specialized tasks
claudecode.Query(ctx, "Review this codebase for security issues",
    claudecode.WithAgent("security-reviewer", claudecode.AgentDefinition{
        Description: "Reviews code for security vulnerabilities",
        Prompt:      "You are a security expert focused on OWASP top 10...",
        Tools:       []string{"Read", "Grep", "Glob"},
        Model:       claudecode.AgentModelSonnet,
    }))

// Multiple agents for complex workflows
claudecode.Query(ctx, "Analyze and improve this code",
    claudecode.WithAgents(map[string]claudecode.AgentDefinition{
        "code-reviewer": {
            Description: "Reviews code quality and best practices",
            Prompt:      "You are a senior engineer focused on code quality...",
            Tools:       []string{"Read", "Grep"},
            Model:       claudecode.AgentModelSonnet,
        },
        "test-writer": {
            Description: "Writes comprehensive unit tests",
            Prompt:      "You are a testing expert...",
            Tools:       []string{"Read", "Write", "Bash"},
            Model:       claudecode.AgentModelHaiku,
        },
    }))

Available agent models: AgentModelSonnet, AgentModelOpus, AgentModelHaiku, AgentModelInherit

Documentation

Advanced Features

The SDK includes advanced capabilities for production use:

  • Permission Callbacks - Programmatic tool access control (Example 11)
  • Lifecycle Hooks - Intercept tool execution events (Example 12)
  • File Checkpointing - Track and rewind file changes (Example 13)
  • SDK MCP Servers - Create in-process custom tools (Example 14)
  • Stream Diagnostics - Monitor stream health with GetStreamIssues() and GetStreamStats()

See the examples directory for complete documentation.

When to Use Which API

Use Query API when you:

  • Need one-shot automation or scripting
  • Have clear task completion criteria
  • Want automatic resource cleanup
  • Are building CI/CD integrations
  • Prefer simple, stateless operations

Use Client API (WithClient) when you:

  • Need interactive conversations
  • Want to build context across multiple requests
  • Are creating complex, multi-step workflows
  • Need real-time streaming responses
  • Want to iterate and refine based on previous results
  • Need automatic resource management (recommended)

Examples

See examples/README.md for detailed documentation.

Getting Started

ExampleDescription
01_quickstartQuery API fundamentals
02_client_streamingWithClient streaming basics
03_client_multi_turnMulti-turn conversations

Tool Integration

ExampleDescription
04_query_with_toolsFile operations with Query API
05_client_with_toolsInteractive file workflows
06_query_with_mcpExternal MCP server integration
07_client_with_mcpMulti-turn MCP workflows

Production Patterns

ExampleDescription
08_client_advancedError handling, model switching
09_context_managerWithClient vs manual patterns
10_session_managementSession isolation

Security & Lifecycle

ExampleDescription
11_permission_callbackPermission callbacks
12_hooksLifecycle hooks
13_file_checkpointingFile rewind capabilities
14_sdk_mcp_serverIn-process custom tools

License

MIT

Frequently Asked Questions

What is claude-agent-sdk-go?

claude-agent-sdk-go is an open-source ai agents skill for AI coding assistants such as Claude Code, Codex CLI, and ChatGPT, built by severity1. Unofficial Go SDK for Claude Code CLI integration. See the Claude Agent SDK documentation for more information. This project has been renamed from claude-code-sdk-go. It has 151 GitHub stars.

Is claude-agent-sdk-go safe to use?

Yes. claude-agent-sdk-go passed SkillsLLM's automated security scan — a dependency vulnerability audit plus prompt-injection heuristics — with no high-severity issues. You can read the full report in the Security Report section on this page.

How do I install claude-agent-sdk-go?

Clone the repository with "git clone https://github.com/severity1/claude-agent-sdk-go" and add it to your Claude Code skills directory (see the Installation section above).

What programming language is claude-agent-sdk-go written in?

claude-agent-sdk-go is primarily written in Go. It is open-source under severity1 on GitHub, so you can review or fork the full source.

Are there alternatives to claude-agent-sdk-go?

Yes. SkillsLLM lists many other AI Agents skills you can browse and compare side by side. Open the AI Agents category from the badge at the top of this page, or use the Related Skills and comparison links further down to weigh claude-agent-sdk-go against similar tools.

Comments (0)

No comments yet. Be the first to share your thoughts!

ECC

by affaan-m

10

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

242,21936,702JavaScript
AI Agentsai-agentsanthropicclaude-code
View details
15

An agentic skills framework & software development methodology that works.

234,96620,863Shell
AI Agentsai-agentsbrainstorming
View details

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

185,94028,768JavaScript
AI Agentsai-agentsanthropicclaude-code
View details

cc-switch

by farion1231

3

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode, OpenClaw, Grok Build & Hermes Agent. Only official website: ccswitch.io

128,8688,826Rust
AI Agentsclaude-codeai-tools
View details

claude-code

by anthropics

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

120,03119,897Shell
AI Agents
View details

Developers Also Liked

Based on votes and bookmarks from developers who liked this skill

ECC

by affaan-m

10

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

242,21936,702JavaScript
AI Agentsai-agentsanthropicclaude-code
View details
15

An agentic skills framework & software development methodology that works.

234,96620,863Shell
AI Agentsai-agentsbrainstorming
View details

n8n

by n8n-io

12

Fair-code workflow automation platform with native AI capabilities. Combine visual building with custom code, self-host or cloud, 400+ integrations.

201,88160,308TypeScript
MCP Serversapisai-tools
View details

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

185,94028,768JavaScript
AI Agentsai-agentsanthropicclaude-code
View details

cc-switch

by farion1231

3

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode, OpenClaw, Grok Build & Hermes Agent. Only official website: ccswitch.io

128,8688,826Rust
AI Agentsclaude-codeai-tools
View details