Claude Agent SDK Go
Roasbeef/claude-agent-sdk-go
SDK Go para agentes Claude com MCP, tool use e streaming nativo
Ver no GitHubSDK nativo em Go para construir agentes IA com Claude, oferecendo integração com MCP, chamadas de ferramentas, pensamento estendido e streaming de respostas. Comunica-se com Claude Code CLI via JSON line-delimited, permitindo controle bidirecional de chamadas de ferramentas.
Instalação
npx convez-ai Roasbeef/claude-agent-sdk-go1 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
Casos de uso
- Construir agentes autônomos em Go que interagem com Claude
- Integrar ferramentas customizadas via MCP em aplicações Go
- Streaming de conversas multi-turnos com Claude
Veredito

SDK bem estruturado para desenvolvedores Go que precisam de integração profunda com Claude. Requer Go 1.23+ e Claude Code CLI, mas oferece controle fino sobre agentes e ferramentas customizadas em produção.
README
A tradução para o português deste README ainda está na fila.
claude-agent-sdk-go
A pure Go SDK for Claude's agentic capabilities.
Overview
claude-agent-sdk-go provides a native Go interface to Claude Code by managing the CLI as a subprocess. It communicates via line-delimited JSON over stdin/stdout, giving you access to Claude's tool use, extended thinking, session management, and hook system.
This repository tracks the official TypeScript Agent SDK surface through the v0.3.168 catchup work, using Go idioms where the API shape differs.
flowchart TB
subgraph SDK[Go SDK]
Client --> Protocol --> Transport
MCP[SDK MCP] <-.->|tool calls| Protocol
end
Transport <-->|stream-json| CLI[Claude CLI]
CLI <--> API[Claude API]
When you call Query() or Stream(), the SDK spawns the CLI, sends your
prompt, and yields messages as they arrive. For MCP tools, the flow includes
bidirectional control messages:
sequenceDiagram
participant App as Go App
participant CLI as Claude CLI
participant API as Claude API
App->>CLI: prompt (stdin)
CLI->>API: API request
API-->>CLI: response stream
CLI-->>App: messages (stdout)
CLI->>App: mcp_message (tool call)
App-->>CLI: mcp_response
CLI-->>App: result
Installation
go get github.com/roasbeef/claude-agent-sdk-go
Requirements:
- Go 1.23+ (for
iter.Seq) - Claude Code CLI:
npm install -g @anthropic-ai/claude-code ANTHROPIC_API_KEYorCLAUDE_CODE_OAUTH_TOKENin your environment
Quick Start
package main
import (
"context"
"fmt"
"log"
"github.com/roasbeef/claude-agent-sdk-go"
)
func main() {
client, err := claudeagent.NewClient(
claudeagent.WithSystemPrompt("You are a helpful assistant."),
)
if err != nil {
log.Fatal(err)
}
defer client.Close()
ctx := context.Background()
for msg := range client.Query(ctx, "What is the capital of France?") {
switch m := msg.(type) {
case claudeagent.AssistantMessage:
fmt.Println(m.ContentText())
case claudeagent.ResultMessage:
fmt.Printf("Cost: $%.4f\n", m.TotalCostUSD)
}
}
}
Streaming
For multi-turn conversations:
stream, _ := client.Stream(ctx)
defer stream.Close()
stream.Send(ctx, "Let's plan a trip to Japan.")
for msg := range stream.Messages() {
if m, ok := msg.(claudeagent.AssistantMessage); ok {
fmt.Println(m.ContentText())
}
}
// Continue the conversation
stream.Send(ctx, "What about Kyoto?")
Configuration
client, _ := claudeagent.NewClient(
claudeagent.WithModel("claude-sonnet-4-5-20250929"),
claudeagent.WithSystemPrompt("You are an expert Go developer."),
claudeagent.WithPermissionMode(claudeagent.PermissionModeAcceptEdits),
claudeagent.WithMaxTurns(20),
)
Settings can be supplied either as a settings file path or as inline JSON:
client, _ := claudeagent.NewClient(
claudeagent.WithSettingsPath("/path/to/settings.json"),
)
client, _ = claudeagent.NewClient(
claudeagent.WithSettings(claudeagent.Settings{
Model: "claude-sonnet-4-5-20250929",
Permissions: &claudeagent.SettingsPermissions{
Allow: []string{"Bash(git status)"},
},
}),
)
Custom Tools (MCP)
Define tools that Claude can use during conversations:
type AddArgs struct {
A int `json:"a"`
B int `json:"b"`
}
server := claudeagent.CreateMcpServer(claudeagent.McpServerOptions{
Name: "calculator",
Tools: []claudeagent.ToolRegistrar{
claudeagent.Tool("add", "Add two numbers",
func(ctx context.Context, args AddArgs) (claudeagent.ToolResult, error) {
return claudeagent.TextResult(fmt.Sprintf("%d", args.A+args.B)), nil
},
),
},
})
client, _ := claudeagent.NewClient(
claudeagent.WithMcpServer("calculator", server),
)
See MCP Tools for typed responses, binary servers, and more.
Ralph Wiggum Loop
For complex iterative tasks, use the Ralph Wiggum loop. Claude works on a task repeatedly, seeing its previous work each iteration, until it outputs a completion signal:
loop := claudeagent.NewRalphLoop(claudeagent.RalphConfig{
Task: "Implement a Redis cache layer with tests",
CompletionPromise: "TASK COMPLETE",
MaxIterations: 10,
})
for iter := range loop.Run(ctx, claudeagent.WithModel("claude-sonnet-4-5-20250929")) {
fmt.Printf("Iteration %d\n", iter.Number)
if iter.Complete {
fmt.Println("Task completed!")
break
}
}
fmt.Printf("Total cost: $%.4f\n", loop.TotalCost())
The loop intercepts session exit via a Stop hook and reinjects the task prompt
if the completion promise (<promise>TASK COMPLETE</promise>) hasn't been
detected. See Ralph Loop for details.
Documentation
For detailed guides and examples, see docs/examples/:
- MCP Tools - Integrate custom tools via Model Context Protocol
- Hooks - Intercept and modify Claude's execution
- Subagents - Define and monitor specialized agents
- Questions - Handle interactive questions from Claude
- Sessions - Persist and resume conversations
- Permissions - Control what Claude can do
- Streaming - Real-time response handling
- Skills - Filesystem-based capability extensions
- Ralph Loop - Iterative task completion pattern
- Task Lists - Multi-agent task coordination system
TypeScript SDK Parity
The SDK tracks the upstream TypeScript Agent SDK release cadence. Coverage landed across three catchup cycles.
The v0.2.119 catchup added:
- thinking effort, task budgets, debug files, extra CLI args, agent selection, and prompt/agent progress toggles
- programmatic subagents, richer hook inputs/outputs, permission updates, and MCP HTTP/SSE configuration
- stream control and introspection helpers, runtime MCP server updates, file/read-state/plugin control, and local JSONL session helpers
- explicit settings support via
WithSettingsPath,WithSettings, andWithManagedSettings
The v0.3.150 catchup added:
- per-server MCP
TimeoutandAlwaysLoadknobs across Stdio/HTTP/SSE/proxy configurations - background-tasks control protocol (
Query.BackgroundTasks) plusBackgroundTaskSummaryandSessionCronSummarypayloads onStop/SessionEndhooks - new
system/permission_deniedmessage subtype,SDKAssistantMessage.Errorenum (incl.oauth_org_not_allowed,model_not_found),ResultMessageTTFT + origin metadata, andMemoryRecallEntryorganizationscope - hook output additions:
UpdatedToolOutputonPostToolUse,TerminalSequenceOSC notifications,SuppressOriginalPromptonUserPromptSubmit, plus per-hookArgs(no-shell exec form) andContinueOnBlock - managed-org / sandbox / worktree / marketplace settings batch covering
PolicyHelper,DisableAgentView,IsolatePeerMachines,Sandbox.TLSTerminate,Worktree.BaseRef,StatusLine.HideVimModeIndicator, marketplaceskills-dir/unsupportedsource variants, and others read_fileEncoding(utf-8 / base64),applyFlagSettingsper-key null clearing, host-sidehost_auth_token_refreshandsubmit_feedbackcontrol subtypes
The v0.3.168 catchup added:
- new system message subtypes (
ThinkingTokensMessage,CommandsChangedMessage), theMessageDisplayhook event, and theMessageOriginKindAutoContinuationorigin variant ResultMessagetiming fields (Duration*MS), anOverloadedSDKAssistantMessage.Errorvariant, and theSessionTitlefield onSessionStart+UserPromptSubmithook inputs- hook output additions:
ReloadSkillsonSessionStartandAdditionalContextonNotification/PostToolBatch/PostToolUse*/PreToolUse/SessionStart/Setup/Stop/SubagentStart/SubagentStop/UserPromptExpansion/UserPromptSubmit - new control RPCs:
OnUserDialogcallback forrequest_user_dialog,Stream.ReloadSkills, andStream.RegisterRepoRootwithWithReloadClaudeMD/WithReloadPlugins/WithReloadSkills - managed-settings batch:
RequiredMinimumVersion,RequiredMaximumVersion,SwitchModelsOnFlag,ForceLoginMethod"gateway",Settings.FallbackModellist,PluginSuggestionMarketplaces, marketplaceSkipLfs, plusWorkflows/EnableWorkflows/WorkflowKeywordTriggerEnabled/Ultracodeknobs - correctness fixes:
pending_permission_requestsround-trips on control success payloads, marketplace source variants documentskipLfsflow, andEffort/ strict-MCP docstrings refreshed for clarity
PRs in this cycle (squash-merged): #96 MessageDisplay hook, #97 ThinkingTokensMessage, #98 SessionStart reloadSkills, #99 SessionTitle hook fields, #100 workflows + ultracode + pluginSuggestionMarketplaces, #101 marketplace skipLfs, #102 option docstring refresh, #103 pending_permission_requests round-trip, #104 CommandsChangedMessage, #105 Stop/SubagentStop additionalContext, #106 OnUserDialog + request_user_dialog, #107 reload_skills RPC, #108 register_repo_root + Stream.RegisterRepoRoot, #109 overloaded assistant error, #110 MessageOriginKindAutoContinuation, #111 ResultMessage timing fields, #112 Settings.FallbackModel list, #113 managed required/maximum version + switchModelsOnFlag + forceLoginMethod "gateway".
Some areas remain intentionally limited by the CLI or integration harness: desktop/IDE-only settings are not modeled exhaustively, several runtime control paths have unit coverage plus skipped integration slots until stable live CLI fixtures exist, and alpha task/agent behavior should still be checked against the installed Claude Code CLI version.
Porting from the TypeScript SDK - Go-side differences
A short list of places the Go SDK consciously diverges from the TS shape; if you are translating TS code, watch for these:
Options.Envmerges, it does not replace. TSOptions.envREPLACES the subprocess environment entirely; the GoOptions.Envis overlaid on top ofos.Environ(). If you relied on the TS replace-semantics, clear inherited variables yourself before spawning. There is no opt-in flag for replace mode.- Cancellation is
context.Context, notAbortSignal. TS forwards a derivedAbortSignalthat fires only after a stdin-EOF + grace window. In Go, that grace window lives insideSubprocessTransport.Close(): the SDK closes stdin, waits up to 5 seconds for the CLI to exit on its own, and only then force-kills. Anything you hang off the samecontext.Context(HTTP cancellation, in-flight tool teardown) inherits the same ordering guarantee. 'Skill'inAllowedToolsis deprecated upstream. Per TS SDK v0.3.150, passing'Skill'inAllowedToolsorAgentDefinition.Toolsis deprecated. UseAgentDefinition.Skillsfor per-agent preload. The Go SDK does not currently expose the upstream top-level user-facingskillsoption; the existingOptions.Skillsmirrors the control-init system-prompt loading allowlist, which is a different surface.Effort"max"/"xhigh"are model-gated.EffortMaxrequires Opus 4.6/4.7 or Sonnet 4.6;EffortXHighrequires Opus 4.7. On unsupported models the CLI silently downgrades per its own policy. The CLI is the authority on which model accepts which level - the SDK only forwards the enum value.OnUserDialoganswers cancelled by default, including on unknowndialogKind. Per TS SDK v0.3.168,dialogKindis an open string union: a new CLI release can ship a kind the host has never seen. The contract is that the host MUST respond cancelled in that case, and the CLI then applies the dialog's default behavior. The Go SDK enforces this automatically: ifOnUserDialogis unset, or the callback returns a non-nil error, the SDK emits cancelled on the host's behalf. Callbacks that do recognize the kind should still returnUserDialogBehaviorCancelled(rather than fabricating a result) for any branch they cannot honor — a misbehaving host should never wedge the CLI on an unresolved dialog.
For internal architecture, see DESIGN.md. For CLI protocol details (how this and the official Typescript SDK actually work), see cli-protocol.md.
Testing
go test ./...