claudecode

package module
v0.0.0-...-e23d3f8 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2025 License: Apache-2.0 Imports: 12 Imported by: 4

README

Claude Code Go SDK (Experimental)

A Go SDK for programmatically interacting with Claude Code (Anthropic's AI coding assistant).

Installation

go get github.com/humanlayer/humanlayer/claudecode-go

Prerequisites

  • Claude Code CLI must be installed and available in your PATH
  • Valid Anthropic API key configured

Quick Start

package main

import (
    "fmt"
    "log"

    claudecode "github.com/humanlayer/humanlayer/claudecode-go"
)

func main() {
    // Create client
    client, err := claudecode.NewClient()
    if err != nil {
        log.Fatal(err)
    }

    // Run a simple query
    result, err := client.LaunchAndWait(claudecode.SessionConfig{
        Query: "Write a hello world function in Go",
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(result.Result)
}

Streaming Example

// Launch with streaming output
session, err := client.Launch(claudecode.SessionConfig{
    Query:        "Build a REST API",
    Model:        claudecode.ModelSonnet,
    OutputFormat: claudecode.OutputStreamJSON,
})

// Process events as they arrive
for event := range session.Events {
    switch event.Type {
    case "assistant":
        fmt.Println("Claude:", event.Message.Content[0].Text)
    case "result":
        fmt.Printf("Done! Cost: $%.4f\n", event.Result.CostUSD)
    }
}

MCP Integration

// Configure MCP servers
mcpConfig := &claudecode.MCPConfig{
    MCPServers: map[string]claudecode.MCPServer{
        "approvals": {
            Command: "npx",
            Args:    []string{"humanlayer", "mcp", "claude_approvals"},
        },
    },
}

// Launch with approval handling
session, err := client.Launch(claudecode.SessionConfig{
    Query:                "Deploy to production",
    MCPConfig:            mcpConfig,
    PermissionPromptTool: "mcp__approvals__request_permission",
    AllowedTools:         []string{"mcp__approvals__*"},
})

Features

  • Type-safe configuration - Build configurations with Go structs
  • Streaming support - Real-time event processing
  • MCP integration - Add approval workflows and custom tools
  • Session management - Resume previous conversations
  • Process control - Full control over Claude subprocess

Output Formats

  • OutputText - Plain text output (default)
  • OutputJSON - Structured JSON with metadata
  • OutputStreamJSON - Real-time streaming JSON events

Configuration Options

type SessionConfig struct {
    // Core
    Query     string
    SessionID string // Resume existing session

    // Model
    Model Model // ModelOpus or ModelSonnet

    // Output
    OutputFormat OutputFormat

    // MCP
    MCPConfig            *MCPConfig
    PermissionPromptTool string

    // Control
    MaxTurns           int
    WorkingDir         string
    SystemPrompt       string
    AppendSystemPrompt string
    AllowedTools       []string
    DisallowedTools    []string
    Verbose            bool
}

Error Handling

The SDK provides detailed error information:

result, err := client.LaunchAndWait(config)
if err != nil {
    // Handle launch/execution errors
    log.Fatal(err)
}

if result.IsError {
    // Handle Claude-reported errors
    fmt.Printf("Error: %s\n", result.Error)
}

Integration with HumanLayer

This SDK integrates seamlessly with HumanLayer for approval workflows:

  1. Configure the HumanLayer MCP server in your MCPConfig
  2. Set appropriate permission prompt tool
  3. Handle approvals through HumanLayer's TUI or API

License

MIT

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 NewClient

func NewClient() (*Client, error)

NewClient creates a new Claude Code client

func NewClientWithPath

func NewClientWithPath(claudePath string) *Client

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 MCPConfig

type MCPConfig struct {
	MCPServers map[string]MCPServer `json:"mcpServers"`
}

MCPConfig represents the MCP configuration structure

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 MCPStatus

type MCPStatus struct {
	Name   string `json:"name"`
	Status string `json:"status"`
}

MCPStatus represents the status of an MCP server

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 Model

type Model string

Model represents the available Claude models

const (
	ModelOpus   Model = "opus"
	ModelSonnet Model = "sonnet"
)

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) Error

func (s *Session) Error() error

Error safely gets the error

func (*Session) Interrupt

func (s *Session) Interrupt() error

Interrupt sends a SIGINT signal to the session process

func (*Session) Kill

func (s *Session) Kill() error

Kill terminates the session

func (*Session) SetError

func (s *Session) SetError(err error)

SetError safely sets the error

func (*Session) Wait

func (s *Session) Wait() (*Result, error)

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

Jump to

Keyboard shortcuts

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