convez.ai
AgenteIntegração & APIsIntermediário
connerohnesorge

Claude Agent SDK para Go

connerohnesorge/claude-agent-sdk-go

SDK Go type-safe para Claude Agents com streaming e MCP

Ver no GitHub
BomPluginScore · de 0 a 100

SDK oficial em Go para acessar as capacidades de agents do Claude, fornecendo integração programática com streaming de mensagens, suporte a MCP servers e controle fino de permissões. Implementação idioticamente Go com type-safety e contextos nativos.

Instalação

$npx convez-ai connerohnesorge/claude-agent-sdk-go

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
25
Forks
3
Acompanhando
0
Saúde
28%
Último commit
há 5 meses
Versão
—
Issues abertas
8
Contribuidores
3

Casos de uso

  • Construir aplicações Go que utilizem agents do Claude
  • Integrar MCP servers e ferramentas customizadas em pipelines Go
  • Automatizar workflows com conversas agentic em Go

Veredito

SDK bem estruturado e maduro para Go developers que precisam integrar Claude Agents. Requisitos claros (Go 1.23+, Claude CLI), documentação com exemplos práticos e suporte completo a features como streaming, contextos e permissões tornam-o robusto para produção.

README

A tradução para o português deste README ainda está na fila.

Claude Agent SDK for Go

Go Reference

Official Go SDK for Claude Agent, providing programmatic access to Claude's agent capabilities.

Installation

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

Prerequisites

  • Go 1.23 or later
  • Claude Code CLI version 2.0.0 or later installed and available in PATH
  • ANTHROPIC_API_KEY environment variable set (optional)

Quick Start

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/connerohnesorge/claude-agent-sdk-go/pkg/claude"
)

const (
	// maxTurns is the maximum number of conversation turns allowed.
	maxTurns = 5
)

func main() {
	ctx := context.Background()

	// Create client with basic options
	opts := &claude.Options{
		Model:    "claude-sonnet-4-5",
		MaxTurns: maxTurns,
	}

	client, err := claude.NewClient(opts)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	defer func() {
		if closeErr := client.Close(); closeErr != nil {
			log.Printf("Failed to close client: %v", closeErr)
		}
	}()

	// Send a simple query
	fmt.Println("Sending query: What is 2+2?")
	query := "What is 2+2? Just respond with the number."
	if err = client.Query(ctx, query); err != nil {
		log.Printf("Failed to send query: %v", err)

		return
	}

	// Receive and process responses
	msgChan, errChan := client.ReceiveMessages(ctx)

	for {
		select {
		case msg := <-msgChan:
			if msg == nil {
				fmt.Println("Query completed")

				return
			}

			handleMessage(msg)

		case err := <-errChan:
			if err != nil {
				log.Printf("Error: %v", err)

				return
			}
		}
	}
}

// handleMessage processes different types of SDK messages.
func handleMessage(msg claude.SDKMessage) {
	switch m := msg.(type) {
	case *claude.SDKSystemMessage:
		if m.Subtype == "init" {
			fmt.Printf("Initialized with model: %v\n", m.Data["model"])
		}

	case *claude.SDKAssistantMessage:
		fmt.Println("\nAssistant response:")
		for _, block := range m.Message.Content {
			switch b := block.(type) {
			case claude.TextBlock:
				fmt.Printf("  %s\n", b.Text)
			case claude.TextContentBlock:
				fmt.Printf("  %s\n", b.Text)
			}
		}

	case *claude.SDKResultMessage:
		fmt.Printf("\nResult: %s\n", m.Subtype)
		fmt.Printf("Duration: %dms\n", m.DurationMS)
		fmt.Printf("Cost: $%.4f\n", m.TotalCostUSD)
		fmt.Printf("Turns: %d\n", m.NumTurns)
	}
}

Features

  • Type-safe: Fully typed Go interfaces matching the TypeScript SDK
  • Streaming: Real-time message streaming support
  • MCP Support: Integration with MCP servers
  • Custom Tools: Define your own SDK MCP tools
  • Permission Control: Fine-grained permission management
  • Context Support: Full context.Context integration
  • Idiomatic Go: Follows Go best practices and conventions

Configuration Options

opts := &claude.Options{
	// Model configuration
	Model:             "claude-sonnet-4-5",
	FallbackModel:     "claude-3-5-haiku-20241022",
	MaxTurns:          10,
	MaxThinkingTokens: 8000,

	// Directory and tool configuration
	Cwd:                   "/path/to/working/dir",
	AdditionalDirectories: []string{"/path/to/extra/dir"},
	AllowedTools:          []string{"Read", "Write", "Bash"},
	DisallowedTools:       []string{"WebSearch"},

	// Permission handling
	PermissionMode:           claudeagent.PermissionModeDefault,
	PermissionPromptToolName: "PermissionPrompt",

	// Message handling
	IncludePartialMessages: true,

	// Environment variables
	Env: map[string]string{
		"MAX_THINKING_TOKENS": "8000",
	},
}

CLI Version Checking

The SDK automatically validates that the Claude Code CLI version is compatible before establishing a connection. This ensures you receive clear error messages rather than cryptic protocol failures when the CLI is outdated.

Minimum Required Version

The SDK requires Claude Code CLI version 2.0.0 or later. This can be verified by running:

claude --version

Skipping Version Check

In some cases (testing, development, or using custom builds), you may want to skip the version check:

export CLAUDE_AGENT_SDK_SKIP_VERSION_CHECK=true

When the version check fails, you'll receive a clear error message indicating the current CLI version and the minimum required version.

Version Mismatch Errors

If the CLI version is too old, the SDK returns a version_mismatch error with details:

  • The currently installed CLI version
  • The minimum required version (2.0.0)
  • A suggestion to upgrade the CLI

Examples

See the examples/ directory for complete examples:

Architecture

Testing

# Run unit tests
go test ./...

# Run with coverage
go test -cover ./...

# Run integration tests
go test -tags=integration ./test/integration/...

# Run e2e tests (requires ANTHROPIC_API_KEY)
go test -tags=e2e ./test/e2e/...

Development Status

The SDK is fully functional and tested with the claude CLI binary.

Contributing

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

License

MIT

Related Projects

Support

For issues and questions:

  • Open an issue on GitHub
  • Check the examples/ directory
  • Refer to the Claude Code documentation
Ver o original no GitHub

Bom para

Relacionados