claude-agent-sdk-go
CLAUDE.md176 starsChanged 7 months agoMITView on GitHub
Claude Agent SDK for Go - Unofficial Go SDK for Claude Code CLI integration. Provides programmatic interaction through Query() (one-shot) and Client (streaming) APIs. Aims for 100% Python SDK parity with idiomatic Go (progress: docs/parity.md and docs/tracking/). Data Flow: 1. Query()/Client -> Transport interface -> subprocess.Transport -> Claude CLI 2. CLI stdout -> parser.Parser -> shared.Message types -> User code 3. Control protocol: control.Protocol <-> CLI (hooks, permissions, MCP) Documentation: See ARCHITECTURE.md and CONTRIBUTING.md for comprehensive details on design patterns,…
In this repositoryOne other file it gives its agents.
- examples/CLAUDE.mdCLAUDE.md
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
16 rules. About 0 are common, 6 are distinctive, and 10 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
10
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 87
Idiomatic Go: Use gofmt formatting, standard naming conventions
- Very specific: line 88
Interface-driven: All message types implement Message, all content blocks implement ContentBlock
- Very specific: line 89
Error handling: Use fmt.Errorf with %w verb for wrapping, include contextual information
- Very specific: line 90
Context-first: All blocking functions accept context.Context as first parameter
- Distinctive: line 94
No unnecessary exports: Keep identifiers unexported unless needed by external consumers
- Distinctive: line 113
Table-driven tests: Use for complex scenarios with multiple test cases
- Very specific: line 115
Benchmark tests: Use var sink any to prevent dead code elimination, always call b.ReportAllocs() and b.ResetTimer()
- Very specific: line 140
WithHook() generic API: use WithHook(eventName, toolFilter, callback) for hook events that have no convenience helper (e.g.
- Very specific: line 142
PostToolUseFailure IsInterrupt nil-check: always guard failInput.IsInterrupt != nil && *failInput.IsInterrupt before treating as interrupt.
- Distinctive: line 178
TDD approach: Write failing tests first, implement to make them pass
- Distinctive: line 179
Test file organization: Test functions first, then mocks, then helpers
- Very specific: line 180
Helper functions: Always call t.Helper() in test utilities
- Distinctive: line 181
Thread safety: All mocks must be thread-safe with proper mutex usage
- Very specific: line 183
Benchmark organization: Use table-driven benchmarks with realistic scenarios, measure allocations with b.ReportAllocs()
- Very specific: line 184
t.Fatal() + return: Always follow t.Fatal() with return in subtests to prevent staticcheck SA5011 nil pointer dereference warnings …
- Distinctive: line 192
Add project-specific notes here.
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
<!-- AUTO-MANAGED: project-description -->Overview
Claude Agent SDK for Go - Unofficial Go SDK for Claude Code CLI integration. Provides programmatic interaction through Query() (one-shot) and Client (streaming) APIs. Aims for 100% Python SDK parity with idiomatic Go (progress: docs/parity.md and docs/tracking/).
- Module:
github.com/severity1/claude-agent-sdk-go - Package:
claudecode - Go Version: 1.18+
<!-- END AUTO-MANAGED --><!-- AUTO-MANAGED: build-commands -->Build & Development Commands
# Build and test
go build ./... # Build all packages
go test ./... # Run all tests
go test -race ./... # Race condition detection
go test -cover ./... # Coverage analysis
make test-cover # Tests with coverage + HTML report
# Specific test patterns
go test -v -run TestClient # Run client tests (verbose)
go test -count=3 -run TestClient # Run tests multiple times for consistency
make bench # Run benchmarks
# Code quality (run before commits)
gofmt -s -w . # Format code (CI uses `gofmt -s`; plain `go fmt ./...` omits -s and fails CI)
go vet ./... # Static analysis
golangci-lint run # Comprehensive linting
gocyclo -over 15 . # Cyclomatic complexity check
# Makefile targets (recommended)
make check # Run all checks (fmt, vet, lint, cyclo)
make cyclo # Show complex functions (threshold: 15)
make cyclo-check # Fail if complexity exceeds threshold (CI)
make fmt-check # Verify code formatting
make security # Run security vulnerability checks
make sdk-test # Test SDK as consumer would use it
make release-check # Pre-release validation
make ci # Run full CI pipeline locally<!-- END AUTO-MANAGED --><!-- AUTO-MANAGED: architecture -->Architecture
.
├── client.go # Client interface and WithClient/WithClientTransport context managers
├── query.go # Query API (one-shot operations)
├── errors.go # Structured error types
├── transport.go # Transport interface abstraction
├── types.go # Re-exports of all internal types and constants for external consumers
├── options.go # Options types and functional options
├── options_bench_test.go # Options performance benchmarks
├── internal/
│ ├── cli/ # CLI discovery and command building
│ ├── control/ # Bidirectional control protocol (hooks, permissions, MCP)
│ ├── parser/ # JSON message parsing with speculative parsing
│ ├── shared/ # Shared types (Message, ContentBlock interfaces)
│ └── subprocess/ # Subprocess management and protocol adapter
├── examples/ # Usage examples (numbered by complexity)
└── docs/
├── architecture/ # Detailed architecture documentation
└── tracking/ # Python SDK parity tracking (PR replay tracker)Data Flow:
Query()/Client->Transportinterface ->subprocess.Transport-> Claude CLI- CLI stdout ->
parser.Parser->shared.Messagetypes -> User code - Control protocol:
control.Protocol<-> CLI (hooks, permissions, MCP)
Documentation: See ARCHITECTURE.md and CONTRIBUTING.md for comprehensive details on design patterns, interfaces, data flow, and contribution guidelines.
<!-- END AUTO-MANAGED --><!-- AUTO-MANAGED: conventions -->Code Conventions
- Idiomatic Go: Use
gofmtformatting, standard naming conventions - Interface-driven: All message types implement
Message, all content blocks implementContentBlock - Error handling: Use
fmt.Errorfwith%wverb for wrapping, include contextual information - Context-first: All blocking functions accept
context.Contextas first parameter - JSON handling: Custom
UnmarshalJSONfor union types, discriminate on"type"field - Cyclomatic complexity: Keep functions under complexity 15 (measured by gocyclo); use
//nolint:gocycloon functions that legitimately exceed the threshold (large table-driven test functions, complex orchestration); extract helpers (e.g.buildToolsListResultfromrouteMcpMethod) to keep dispatch switches within budget rather than suppressing with nolint; higher complexity acceptable for table-driven tests, examples, orchestration code, method dispatch - Naming patterns: Interfaces describe behavior, implementations use concrete names, options use
WithXxx(), errors useXxxErrorsuffix - No unnecessary exports: Keep identifiers unexported unless needed by external consumers
<!-- END AUTO-MANAGED --><!-- AUTO-MANAGED: patterns -->Detected Patterns
- Transport interface: Central abstraction for CLI communication; use
MockTransportfor tests - Process cleanup: SIGTERM -> wait 5 seconds -> SIGKILL;
startProcessWaiter()is the solecmd.Wait()caller, started right afterStart(), and closesprocessDoneon exit, after it setst.exit(*processExit{done, err}, withexitReason(cmd.ProcessState, waitErr); a nil state gives aConnectionError) underexitMu;Transport.Done()/Err()readt.exitunderexitMuand never taket.mu, cleanup clears it, andopenStdinusest.Err()(TestTransportDoneAndErrDoNotTakeTransportLock);terminateProcess()never callscmd.Wait(), it waits onprocessDoneand no longer treatsstdoutDone(stdout EOF) as process exit (a CLI that closes stdout but stays alive must still be signaled); child stdout and the stderr callback useos.PipevianewChildOutputPipe()instead ofcmd.StdoutPipe/StderrPipebecausecmd.Wait()closes those readers and drops buffered output (Python reads stdout to EOF, reaps separately); thechildPipeEndswrite ends are closed in the parent afterStart();handleStdout(protocol, childProcess{cmd, done})closesstdoutDoneat stdout EOF (signalStdoutDone) before waiting for exit, thenchildProcess.exitError(ctx, lastErrorResult)returns*shared.ProcessError(ExitCode from ProcessState) for a non-zero exit, nil for a clean exit or cancelled ctx (handleStdoutdrops it whilet.closingis closed); after an errorResultMessagethe message is"Claude Code returned an error result: <errors or subtype>"(Python #918;trackErrorResultresets on any other message except systemsession_state_changed);SendMessagereturns*shared.ConnectionErroronceprocessDoneis closed andIsConnected()is false after exit (processExitedLocked);isProcessAlreadyFinishedError()suppresses expected termination errors including Windows"TerminateProcess: Access is denied"; graceful shutdown (tracker rows 14a/30, PR #163):teardownLockedorder is close protocol+adapter,close(t.closing),stdinWriter.Close()(does not wait for a blocked write),terminateProcess(), thent.cancel(), close the stdout read end (the CLI is reaped, so nothing it wrote is still owed to a reader, and a descendant that inherited stdout would otherwise keephandleStdoutblocked in its read;TestCloseDoesNotWaitForDescendantHoldingOutput, mock modesclose_orphan_stdout/orphan_stdout_and_stderrre-exec the test binary as the descendant), wait wg at mostpipeDrainGrace(500ms, for the stderr callback to drain its pipe), cleanup;terminateProcessnever readst.ctx: wait 5s onprocessDone(grace after stdin EOF), SIGTERM, wait 5s, Kill, wait 5s viawaitProcessDone(d)(Windows SIGTERM fails, goes to Kill);handleStdoutkeeps draining whilet.closingis closed (msgChan send,sendStreamError, control routing and theexitErrorresult are dropped);Connectusesexec.Commandand at.ctxfromcontext.Background(), so the connect ctx bounds only connect + Initialize (net.Dialer.DialContextsemantics) and the client lives untilDisconnect;queryIterator.watchContext()closes the iterator when its ctx ends - stdinWriter:
internal/subprocess/stdin.go;writeMuserializes writes (Python_write_lock);EndInputwaits for an in-flight write,Closedoes not (pipe close runs on a goroutine);t.stdinis*stdinWriter, non-nil afterEndInput(isClosed());SendMessagewrites outsidet.mu(openStdinhelper); control delegations useconnectedProtocol()and call the protocol outsidet.mu;ProtocolAdapter.Writedoes not holdpa.muduring the write - Stderr callback delivery:
handleStderrCallbacknever checksctx.Done()inside its scan loop, so lines already read still reachStderrCallbackafter cancel (Python parity: its stderr reader never drops a read line); pinned byTestStderrCallbackDeliversLinesAfterCancel - Buffer protection: 1MB limit to prevent memory exhaustion;
parser.NewWithSize(n)allows configurable override; the stdout scanner buffer starts at 64 KiB (or limit+1 if smaller) and grows on demand up to limit+1, so a line of exactly the limit passes (PR #188);bufio.ErrTooLongbecomesparser.NewBufferOverflowError(limit, err), a*JSONDecodeErrorwith text "JSON message exceeded maximum buffer size of N bytes" (same text as the parser) - Rate limit event:
RateLimitInfokeeps the wholerate_limit_infoobject inRaw map[string]any(json "-", PR #187).Utilization *float64is nil when absent.OverageDisabledReasonis a string. ConstantsRateLimitStatusAllowedWarning/RateLimitStatusRejectedandRateLimitTypeFiveHour/SevenDay/SevenDayOpus/SevenDaySonnet/Overageare untyped strings, re-exported intypes.go.IsUsingOverageis a Go extra.uuidandsession_idstay optional (deliberate divergence: Python raisesMessageParseError). Tracker row 15 - Environment variables: Set
CLAUDE_CODE_ENTRYPOINTto identify SDK to CLI - buildEnvironment order: drops the inherited
CLAUDECODEvariable, then setsCLAUDE_AGENT_SDK_VERSION=shared.SDKVersionlast so user env cannot override it;internal/shared/version.goholdsSDKVersion("0.9.1"), and rootVersion = shared.SDKVersion - Setting sources argv:
SettingSourcesis nil by default (no flag);WithSettingSources()with no args gives a non-nil empty slice and emits--setting-sources=; non-empty values emit one token--setting-sources=<csv> - Skills on initialize:
InitializeRequest.Skills *[]stringset bycontrol.WithSkills;Transport.skillsProtocolOptionsends it only when the option value is[]string - Thinking config:
ThinkingConfigis a sealed interface (unexportedthinkingArgs();shared.ThinkingArgs(cfg)is the helper forinternal/cli, nil or a typed nil pointer (onereflectcheck) gives nil, andaddThinkingFlagsthen falls back toMaxThinkingTokens).ThinkingConfigAdaptive{Display}emits--thinking adaptive,ThinkingConfigEnabled{BudgetTokens, Display}emits--max-thinking-tokens N,ThinkingConfigDisabledemits--thinking disabled.ThinkingDisplay(summarized,omitted) emits--thinking-display <v>, never for disabled and not when empty.Options.Thinkingtakes precedence overMaxThinkingTokens.addThinkingFlagsemits--max-thinking-tokensonly whenMaxThinkingTokens > 0.NewOptionsno longer sets 8000, so the CLI chooses.DefaultMaxThinkingTokensandWithMaxThinkingTokensare deprecated; theMaxThinkingTokensfield is not marked deprecated because staticcheck SA1019 would flag internal reads - Resume session options:
ResumeSessionAt(string) emits--resume-session-at=<v>when non-empty;ResumeDropsTurn(pointer) emits--resume-drops-turn=<v>when non-nil;validateWindowsArgs(goos, options)inclient.gocoversresume,resume_session_atandresume_drops_turn - Table-driven tests: Use for complex scenarios with multiple test cases
- Functional options:
WithXxx()pattern for configuration - Benchmark tests: Use
var sink anyto prevent dead code elimination, always callb.ReportAllocs()andb.ResetTimer() - tool_use_result metadata:
UserMessage.ToolUseResultcarries rich edit info (filePath, structuredPatch, diffs); check withHasToolUseResult()before accessing viaGetToolUseResult() - parent_tool_use_id placement: parsed from top-level JSON data (not nested
messageobject) forUserMessage,AssistantMessage, andStreamEvent; identifies messages produced inside a subagent (Agent/Task tool) - AssistantMessage error field:
AssistantMessage.Erroris*AssistantMessageErrorparsed from top-leveldata["error"](not nesteddata["message"]["error"]); CLI wire format is{"type":"assistant","error":"rate_limit","message":{...}}; useHasError()to check presence,IsRateLimited()for rate limit specifically;AssistantMessageErrorconstants (all Python SDK parity):rate_limit,billing_error,server_error,authentication_failed,invalid_request,unknown - Unified streaming transport (Python SDK PR #468):
subprocess.New(cliPath, options, entrypoint)is the single constructor; bothQuery()andClientroute through streaming mode (--input-format stream-json) and run the initialize handshake unconditionally so the agents map can travel on the initialize control request instead of the deprecated--agentsCLI flag. The prompt forQuery()is written to stdin as a user-message JSON line ({"type":"user","session_id":"","message":{"role":"user","content":...},"parent_tool_use_id":null}) afterConnect()returns. Wire-shape pins (noomitempty, key always emitted):StreamMessage.SessionIDandStreamMessage.ParentToolUseIDalways emit"session_id":""and"parent_tool_use_id":nullwhen unset;InitializeRequest.Hooksalways emits"hooks":nullwhen no hooks are registered (matches Python"hooks": hooks_config if hooks_config else None).Transport.EndInput(ctx)is declared on the publicTransportinterface (parity-review W2 fix; previously only onsubprocess.Transport, discovered via inline-interface assertion in query.go); closes the stdin write side only (idempotent); invoked byqueryIterator.start()immediately when no bidirectional channel is needed, or after the firstResultMessagewhen hooks/CanUseTool/SDK-MCP/file-checkpointing keep the control protocol alive. The needs-bidirectional decision lives inneedsBidirectionalStdin()inquery.go. The Go gate is deliberately wider than Python's (Python:sdk_mcp_serversORhooks; Go: those +CanUseTool+EnableFileCheckpointing) as an idiomatic-Go divergence - Go has no preflight rejection forQuery(str)+CanUseTool, andEnableFileCheckpointinglegitimately requires the control protocol becauseRewindFiles()rides over it.agentsToMapstripping is intentionally stricter than Python (if v is not None): description/prompt always emit, empty Tools and empty Model are dropped - Go's zero-value-as-unset semantics can't round-trip Python's preserve-empty-list/string behavior until Phase 2 #19 (Python PR #684) lands nullable AgentDefinition fields. - InitializeRequest omitempty asymmetry:
Hooksfield has noomitempty(always emits"hooks":nullwhen no hooks registered, matching Python wire shape);Agentsfield hasomitempty(key absent when nil or empty map). Rationale: hooks absence is meaningful to the CLI; agents absence simply means no programmatic agents were configured.examples/15_programmatic_subagentsExample 4 demonstrates a large-payload (~260 KB, 20 agents) that would previously exceed OS ARG_MAX via--agentsbut now streams safely over the initialize control request. - Init error routing: the control protocol is built before
handleStdout(protocol)starts and passed in, so stdout handling never readst.connected/t.protocolunlocked.routeInitError(protocol, msg)is a free function inio.go: it detects an errorResultMessagearriving before initialize completes (protocol.IsInitialized(), checked under the protocol lock) and callsprotocol.HandleControlInitErr()to unblockSendControlRequest()viainitErrChan.setupControlProtocol()additionally spawns a watcher goroutine that callsHandleControlInitErr()when the CLI exits before responding to initialize (stdoutDoneclosed byhandleStdoutat stdout EOF, before the process exit wait); the watcher captures channel/protocol pointers locally to avoid races on reconnect.HandleControlInitErr()readsp.initializedunder lock and is a no-op afterInitialize()succeeds, so the post-init watcher cannot poisoninitErrChanfor laterSendControlRequestcalls (e.g.SetModel/GetMcpStatus). - Concurrent control dispatch:
Protocol.HandleIncomingMessageAsync()runs each incomingcontrol_requeston its own goroutine (responses and regular messages stay inline) so a slowCanUseTool/hook/MCP callback cannot stallhandleStdout(); per-request ctx cancel funcs live inProtocol.inflightRequestskeyed byrequest_id, andClose()cancels all without waiting;writeControlResponse()checks ctx before writing and is used by all four response writers (error, permission, hook, MCP) so cancelled handlers write nothing;replyHandlerFailure()sends an errorcontrol_responsefor handler errors and panics; an unsupported subtype now returns an error (error response, Python parity) instead of being silently ignored; mock modetwo_permission_requestsandTestTransportSlowPermissionCallbackDoesNotBlockReadercover it - Control protocol delegation:
Interrupt(),SetModel(),SetPermissionMode(),RewindFiles(),GetMcpStatus(),ReconnectMcpServer(),ToggleMcpServer()guard witht.connected(error"transport not connected") before delegating tot.protocol; nil protocol guard uses descriptive error"internal error: transport connected but control protocol is nil".Interrupt()sends only the{"subtype":"interrupt"}control request (PythonQuery.interrupt()parity) and never signals the process (no SIGINT, no Windows-unsupported error), so the CLI stays alive after an interrupt (issue #147). A delegation still waiting for its response whenClose()runs returnscontrol.ErrProtocolClosedat once (TestCloseFailsPendingInterrupt, mock modeignore_interrupt), and one still waiting when the CLI's stream ends with an error (non-zero exit, scanner error) returns that error at once (Protocol.FailPendingRequests, called fromhandleStdout). (No morecloseStdingate - every connection runs control protocol now.) - MCP config serialization:
generateMcpConfigFile()strips GoInstancefield from SDK servers and propagatesAlwaysLoadexplicitly (not via struct json tags) when building CLI config - Resume argv safety (Python PR #1123):
addSessionFlagsemits--resume=<value>as ONE argv token (the CLI declares--resumewith an optional value, so a two-token form lets a dash-leading value like--versionparse as a flag);prepareOptions()also callsvalidateWindowsArgValue(runtime.GOOS, "resume", value)inclient.go, which rejects cmd.exe metacharacters (&|<>^%!", CR/LF) only when goos iswindowsOS, soQuery,QueryWithTransportandClient.Connectall validate - Windows batch CLI refusal (Python PR #1127, BatBadBut CVE-2024-27980):
cli.RejectWindowsBatchCLI(goos, path)returns*shared.ConnectionErroron Windows for any path with a.bat/.cmdcomponent (isWindowsBatchPathis pure string logic, also splits on:, soclaude.cmd:streamandclaude.cmd.are caught);subprocess.Transport.Connect()calls it before the version probe spawns the CLI.FindCLIon Windows prefers a nativeclaude.exeover an npmclaude.cmdPATH hit and keeps the batch hit only as last resort so Connect reports the clear refusal; the Windows common-locations list is only~/.local/bin/claude.exe.addExtraFlagsemits--flag=valuewhen the value starts with-(P32 item a; audit vs CLI 2.1.286: only optional-value flags--debug/--resumeare injectable) - Permission suggestions:
ToolPermissionContext.Suggestions []PermissionUpdatecarries CLI-provided permission suggestions toCanUseToolcallbacks;PermissionUpdate.Typeis one ofaddRules,replaceRules,removeRules,setMode,addDirectories,removeDirectories - Test mock helpers:
newClientMockTransport()/newQueryMockTransport()with functional options (WithQueryAssistantResponse,WithQueryMultipleMessages);QueryWithTransport()for transport-injected query tests - TestMain cross-platform mock CLI:
internal/subprocess/mock_cli_test.goandinternal/cli/mock_cli_test.goeach define aTestMainthat checks a package-scoped env var (CLAUDE_SDK_TEST_MOCK_MODE/CLAUDE_SDK_TEST_CLI_MOCK_MODE) and re-enters the compiled test binary as a mock CLI process beforem.Run(). This is the Go analog of Python'ssys.executable -c "..."and matches theos/execstdlibTestHelperProcessidiom. Replaces per-platform.bat/.shfixtures. Subprocess mock modes:default,long_running,should_fail,check_environment,invalid_output,with_control_protocol,with_stderr,init_error,burst_exit,exit_before_init,stdout_closed_alive,hang_init,early_error_result,two_permission_requests,exit_nonzero(exit 3 after a message),error_result_exit(error result then exit 1),server_info(rich initialize response),exit_clean(exit 0 after initialize),orphan_stdout(starts ahold_stdoutdescendant that keeps stdout open fororphanHoldTime, then exits 3),ignore_sigterm,slow_exit_after_eof,stop_reading(these three dispatch viarunShutdownMockto keeprunMockCLIgocyclo flat; its default case callsrunStreamMock, which handlesfixed_size_line(emits a line ofmockFixedLineLen=4096 bytes); envCLAUDE_SDK_TEST_MOCK_EVENT_LOGmakes the mock appendNAME <unix-ms>lines EOF/SIGTERM/EXIT, used byshutdown_test.go) (init_error: emits PID on stderr, responds to initialize withsubtype:"error", then keeps reading stdin so the SDK must terminate the process - used byTestTransportConnectFailureTearsDown).connectWithWatchdog()inlifecycle_test.gofails a test whoseConnect()hangs past a time limit. Test helpers (e.g.newTransportMockCLI(t),newTransportMockCLIInitError(t)) set the env var viat.Setenv(auto-cleaned).t.Setenvis incompatible witht.Parallel()at the same scope - keep test functions using these helpers sequential. Race-mode parent contexts need ~30s budget because spawning the Go test binary is slower than bash. - MCP reconnect/toggle (Python PR #620, tracker row 10 done):
McpReconnectRequest{subtype, serverName}(mcp_reconnect) andMcpToggleRequest{subtype, serverName, enabled}(mcp_toggle;enabledhas noomitempty, sofalseis sent);Protocol.ReconnectMcpServer/ToggleMcpServerusemcpControlTimeout(60s) and reject an empty server name before sending; both are on the publicTransportandClientinterfaces.integrationMockTransport(//go:build integration) implements the fullTransportinterface sogo vet -tags integration ./...passes;TestTransportControlProtocolIntegrationparent ctx is 30s - Constructor functions:
NewGetMcpStatusRequest()followsNewPermissionResultAllow/Denypattern - constructor sets requiredSubtypefield (SubtypeGetMcpStatus = "mcp_status", not"get_mcp_status"); use constructors for control request types with fixed subtype values - McpServerConfigType constants:
McpServerConfigTypeStdio/SSE/HTTP/SDK/ClaudeAIre-exported in roottypes.goalongsideMcpServerConnectionStatusconstants; discriminateMcpServerStatusConfig.Typefield - McpServerStatus conditional fields:
ServerInfonon-nil only whenStatus == McpServerConnectionStatusConnected;Errornon-nil only whenStatus == McpServerConnectionStatusFailed;Toolspopulated only when connected - streamErrChan fan-in:
ClientImpl.streamErrChan chan error(buffered, size 1) receives errors fromQueryStreamgoroutine; passed directly toclientIteratoralongside transporterrChanandstreamErrChan;Next()selects on both so callers see all stream errors without spawning goroutines;clientIteratorandqueryIteratorread the transport channels throughstreamReader(stream_reader.go): a closederrChan/streamErrChanis set to nil for the call and reading continues, soNextnever returns(nil, nil); the transport sends its terminal error after the last message, sostreamReader.nextalways callsdrainToPendingfirst ((nil, nil)from it means keep reading), so every buffered message is delivered before the error (an error read early is held aspending;TestStreamReaderSharedPendingError) and, whenmsgChancloses, still returns an error left inerrChanbeforeErrNoMoreMessages;ClientImpl.streamis shared by successiveReceiveResponseiterators, so the exit error after a turn'sResultMessagesurfaces on the next call (clientIterator.markClosed);QueryStreamwrite errors go tostreamErrChan(surfaced byReceiveResponse), with a stderr log only when the buffered error is dropped - Client Done/Err (issue #144 follow-up):
Client.Done()closes when the connected CLI process exits (on its own or throughDisconnect) andClient.Err()says why, followingcontext.Context: nil while running,*ProcessErrorfor a non-zero exit (ExitCode -1 for a signal),*ConnectionErrorfor a clean exit,*ConnectionErrorwrapping rootErrNotConnectedbeforeConnect/afterDisconnect(Done is then closed;notConnectedError()builds it and is also used byliveTransportLockedandGetServerInfo;TestClientNotConnectedErrors). The Go analog of Pythonreceive_messages()raising theProcessError, which a<-chan Messagecannot carry.ClientImpltype-asserts the unexportedprocessWatcherinterface (Done/Err), whichsubprocess.Transportimplements onprocessDone(no second waiter);Donedoes not wait for stdout EOF. Custom transports without it getconnectionWatch.disconnected, closed onDisconnect.Done()/Err()never takec.mu: they readc.watch *connectionWatch{watcher, disconnected}underwatchMu, set atConnectand cleared (swapWatch) beforetransport.Close()inDisconnect, soErr()during Disconnect returns the not-connected*ConnectionErrorand never the transport's plain "transport not connected" error; a failed Close restores it (TestClientErrDuringDisconnect,TestClientFailedDisconnectKeepsWatch,cleanupThenBlockTransportmock) (TestClientDoneAndErrDoNotBlockDuringDisconnect,blockingCloseTransportmock). RootErrProtocolClosed = control.ErrProtocolClosedis exported inerrors.go.liveTransport()/liveTransportLocked()gateQuery,QueryWithSession,QueryStream,Interrupt,SetModel,SetPermissionMode,RewindFiles,GetMcpStatus,StopTask,ReconnectMcpServer,ToggleMcpServer: a dead process returns*ConnectionError("cannot write to terminated CLI process", Err())(Python:CLIConnectionErrorraised from_exit_error), soQueryStreamno longer returns nil for a dead client. Tests:TestClientCallsFailAfterProcessExit,TestClientDoneAndErrLifecycle(processMockTransport),TestSubprocessTransportReportsProcessExit(guards the optional interface),TestTransportDoneReportsCLIExit,TestTransportDoneClosesBeforeStdoutEOF,TestTransportDoneBeforeConnectAndAfterClose - GetServerInfo returns the initialize response (Python
get_server_info()):control.Protocol.Initializekeeps the whole response map ininitResult(it still decodessupported_commandsintoInitializeResponse);Protocol.InitializationResult()returns a deep copy (copyJSONValue), nil before the handshake.subprocess.Transport.InitializationResult()delegates throughconnectedProtocol()(nil when not connected).ClientImpl.GetServerInfotype-asserts the unexportedserverInfoSourceinterface and returns that map, nil for a custom transport without it, "client not connected" error when not connected; the old hard-codedconnected/transport_typekeys are gone. Mock modeserver_infoanswers initialize withmockInitializeResponse. Tests:TestInitializationResultKeepsFullResponse,TestTransportInitializationResult,TestGetServerInfo,TestGetServerInfoConcurrent,TestSubprocessTransportKeepsServerInfo(guards the optional interface) - prepareOptions(): applies defaults before validating - auto-configures
PermissionPromptToolName = "stdio"whenCanUseToolcallback is set; renamed fromvalidateOptions()to reflect dual role - ReceiveResponse() disconnected behavior: returns non-nil
clientIteratorwith closedmsgChanand emptyerrChan(never nil) when called while disconnected; callers can always range over the result safely - PostToolUseFailureHookInput: distinct from
PostToolUseHookInput; fields:ToolUseID string,Error string,IsInterrupt *bool json:"is_interrupt,omitempty";IsInterruptnil means key absent in JSON (PythonNotRequired[bool]semantics);PostToolUseFailureHookSpecificOutputis structurally identical toPostToolUseHookSpecificOutput(onlyHookEventNameliteral differs), both haveAdditionalContext *string(omitempty); hook event count is now 10 (Notification, SubagentStart, PermissionRequest added in Python SDK PR #545); HookEvent const block order matches Python SDK: PreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit, Stop, SubagentStop, PreCompact, Notification, SubagentStart, PermissionRequest - WithHook() generic API: use
WithHook(eventName, toolFilter, callback)for hook events that have no convenience helper (e.g.PostToolUseFailure,Notification,SubagentStart,PermissionRequest); convenience helpersWithPreToolUseHook/WithPostToolUseHookexist only for PreToolUse and PostToolUse; seeexamples/12_hooksExample 4 (PostToolUseFailure) and Example 5 (Notification) for canonical usage - HookSpecificOutput types:
PostToolUseHookSpecificOutput,PostToolUseFailureHookSpecificOutputboth requireHookEventNamefield set to the event name string (json taghookEventName);AdditionalContext *string(omitempty) is the field for injecting context Claude will read on the next turn; use a localptrTo[T any]helper (func ptrTo[T any](v T) *T { return &v }) in examples for constructing*stringvalues;PermissionRequestHookSpecificOutput.Decision map[string]anyis the only output field withoutomitempty- it is required (mirrors Python required dict) - PostToolUseFailure IsInterrupt nil-check: always guard
failInput.IsInterrupt != nil && *failInput.IsInterruptbefore treating as interrupt; nil means the JSON key was absent (not false); skip recovery context injection when true to respect user stop intent - SubagentStopHookInput agent fields:
AgentID,AgentTranscriptPath,AgentTypeadded as flat required string fields in Python SDK PR #545 (NOT via_SubagentContextMixin); SubagentStart/SubagentStop keep requiredstringfields, whilePreToolUseHookInput,PostToolUseHookInput,PostToolUseFailureHookInputandPermissionRequestHookInputcarryAgentID/AgentType *string(omitempty, parsed withgetStringPtr, nil = key absent; tracker row 13 done) - getAnySlice helper: mirrors
getMapininternal/control/hooks.go; returns nil when key absent (preserving PythonNotRequiredsemantics); use when Python field type islist[Any]withNotRequiredsemantics (e.g.PermissionRequestHookInput.PermissionSuggestions) - UpdatedMCPToolOutput casing: Go field name uses Go-idiomatic acronym casing (
UpdatedMCPToolOutput) while wire tag preserves Python camelCase exactly (json:"updatedMCPToolOutput,omitempty"); apply this same pattern for any future fields with acronyms (MCP, HTTP, SSE) - NotificationHookInput fields:
NotificationType string,Message string,Title *string(omitempty);Titlenil maps to PythonNotRequired[str]absent state - always nil-guard before dereferencing; Notification hooks return emptyHookJSONOutput{}(observation only, no HookSpecificOutput);PermissionRequestHookInput.PermissionSuggestionsis[]any(mirrors Pythonlist[Any]) with same nil-means-absent semantics - MCP tool annotations (Phase1 #5, Python PR #551): Two distinct annotation types -
shared.ToolAnnotations(authoring side, MCP-spec Hint suffix:ReadOnlyHint/DestructiveHint/IdempotentHint/OpenWorldHint+Title, all*Tomitempty) vscontrol.McpToolAnnotations(CLI status response side, Hint suffix stripped:ReadOnly/Destructive/OpenWorld); mirrors Pythonmcp.types.ToolAnnotationsvsMcpToolAnnotationsTypedDict split;ToolOptionfunctional option pattern extendsNewTool()with variadic...ToolOption(backward compatible); consumers useNewTool(..., WithToolAnnotations(&ToolAnnotations{...}));annotationsToMapusesjson.Marshal+Unmarshalround-trip to honor omitempty;buildToolsListResultis a standalone helper (not inlined inrouteMcpMethodswitch) to keep dispatch under gocyclo budget;tools/listwire behavior:nilpointer omits"annotations"key entirely;&ToolAnnotations{}(non-nil, all fields unset) emits"annotations": {}(key present, empty map); camelCase wire keys:title,readOnlyHint,destructiveHint,idempotentHint,openWorldHint - Connect failure cleanup invariant:
subprocess.Transport.Connect()callsteardownLocked()whensetupControlProtocolfails before returning the error.teardownLocked()is the unified post-Start cleanup primitive: closes the control protocol, closes stdin, terminates the process, cancels the context, waits for goroutines, and runs the cleanup func. Shared betweenClose()(called after settingconnected=false) and the Connect error path, so no subprocess is ever leaked on a failed connect.TestTransportConnectFailureTearsDownverifies this by capturing the mock CLI PID viaStderrCallbackand probingsyscall.Signal(0)after the failedConnect()returns. - Query iterator close-on-drain (Issue #145):
queryIterator.Next()callsqi.Close()on every terminal path (end of stream, terminal error, ctx done,start()failure after Connect), so a caller that drainsQuery()without callingClose()leaks no transport or temp file (Python parity:query()closes infinally).Close()is idempotent.TestQueryClosesTransportAtStreamEndverifies this;queryMockTransportrecords calls viacloseCalls/getCloseCalls(). - ReceiveResponse stops at ResultMessage:
clientIterator.Next()callsmarkClosed()after returning a*ResultMessage, so the nextNext()returnsErrNoMoreMessages(Pythonreceive_response()parity); transportmsgChanstays open so the nextQuery+ReceiveResponsereads the next turn;ReceiveMessages()channel is unchanged; testsTestClientIteratorStopsAfterResultMessage,TestClientReceiveResponseMultiTurn - ResultMessage.StopReason:
*string(jsonstop_reason,omitempty), nil when absent; parsed inparseResultOptionalFields(internal/parser/json.go), extracted to keepparseResultMessageunder gocyclo 15 (tracker row 9 done) - Unknown message types:
parser.ParseMessagereturns(nil, nil)for an unknown top-level type, andparseContentBlocksdrops unknown content block types (Python parity, forward compatible); a known type with a missing field still returnsMessageParseError.ConversationResetMessage{MessageType, NewConversationID, UUID, SessionID}(MessageTypeConversationReset = "conversation_reset") needs all three ID fields and is re-exported intypes.go. Server tool blocks:ServerToolUseBlock{ID, Name ServerToolName, Input}(ContentBlockTypeServerToolUse = "server_tool_use") andServerToolResultBlock{ToolUseID, Content map}(ContentBlockTypeAdvisorToolResult = "advisor_tool_result"), withServerToolName*constants; the parser cases require all keys (elseMessageParseError). Typed task structs carry no JSON tags:json.Marshalwrites the raw payload, so useAsTask*, not a type switch - Allow permission sends updatedInput:
sendPermissionResponse(..., originalInput)ininternal/control/permissions.gosends the original tool input as"updatedInput"when an allow result has nilUpdatedInput(Python always sends the key; CLI 2.1.161/2.1.173 reject an allow without it with a ZodError); the no-callback deny path passes nil (PR #158)
<!-- END AUTO-MANAGED --><!-- AUTO-MANAGED: git-insights -->Git Insights
- Conventional commit messages:
feat:,fix:,docs:,test:,refactor:,chore: - Issue references in commits:
(Issue #N)or(#N), useCloses #Nin PR body - PR-based workflow with CI checks
- CI test matrix (6 Go versions x 3 OS = 18 jobs) has
fail-fast: false, and the "Upload coverage to Codecov" step hascontinue-on-error: true, so a Codecov outage (TLS errors on Oct 5, 2026) does not fail a job or cancel the other matrix jobs. Merge needs all 27 checks SUCCESS. A CANCELLED check means the job did not run, so re-run it - Go PR #185 (commit 633cba1) holds the pre-v0.9.0 follow-ups (#175-#180, #183, #184/P8)
- Recent focus: onsi-reported bug fixes after the unified-streaming merge:
Interrupt()sent as a control request instead of SIGINT (PR #154, issue #147),Query()closes the transport when the stream ends (PR #153, issue #145),CanUseToolconfiguration applied on the Query path (PR #152, issue #146), concurrent control-request dispatch (PR #151, from #142; see Concurrent control dispatch pattern), singleWaitowner for the CLI process +os.Pipechild output + init race fix (PR #150, from #140), session JSONL lines over 1MB no longer fail parsing (PR #139); v0.7.1 (Oct 1, 2026) shipped #158 (updatedInputfallback), #159 (ReceiveResponsestops at theResultMessage), #160 (P31) and #161 (P32); #144 fixed by #156 (v0.7.0); #143 (stop_task, typed task lifecycle messages +StopTask) fixed by #168; contributor PRs #164-#169 merged; previously Phase1 item #6 - agents via initialize + unified streaming (Python PR #468):subprocess.New()single constructor; bothQuery()andClientuse streaming mode + unconditional initialize handshake; agents travel on initialize control request;EndInput()closes stdin write side; post-feat fixes: (1)InitializeRequest.Hooksemits"hooks":null(no omitempty, matching Python wire shape), (2)StreamMessage.SessionID/ParentToolUseIDlackomitempty(wire always emits both keys), (3)HandleControlInitErr()is no-op after successful Initialize (race guard for long-lived clients), (4) cross-platform mock CLI viaTestMain+os.Args[0]re-entrancy replaces.bat/.shfixtures in bothinternal/subprocessandinternal/cli, (5)examples/15_programmatic_subagentsExample 4 adds large-payload agent smoke test (~260 KB via initialize, bypasses ARG_MAX); parity-review follow-up fixes: (6)Transport.EndInput(ctx)promoted to publicTransportinterface (was only onsubprocess.Transport, found via inline-interface assertion inquery.go), (7)teardownLocked()extracted as unified post-Start cleanup primitive shared betweenClose()andConnect()error path so no subprocess leaks on failed connect, (8)terminateProcess()callscmd.Wait()on stdoutDone fast path to reap process and release exec.Cmd watchCtx goroutine, (9)init_errormock mode +TestTransportConnectFailureTearsDowntest verifies subprocess is reaped after connect failure (probes PID viasyscall.Signal(0)); Phase1 item #5 - MCP tool annotations (Python PR #551):shared.ToolAnnotationsstruct (authoring side) +ToolOption/WithToolAnnotationsonNewTool();annotationsToMapjson round-trip;buildToolsListResultextracted fromrouteMcpMethod(gocyclo refactor, removed nolint); Phase1 item #4 - 3 new hook events + missing fields (Python PR #545): Notification, SubagentStart, PermissionRequest event types; hook count 7 -> 10 - Release v0.9.1 fixes the Disconnect
Err()window from #185 (found by the post-release parity review) and marks tracker rows 42 (n/a, superseded by P5) and 47 (done, #181) - v0.9.1 (branch
fix/v0.9.1) includes contributor PRs #187 and #188 (kujtimiihoxha) and completes tracker row 15 (Go PR #189) - Release v0.9.0 (
SDKVersion"0.9.0") bundles contributor PRs #164-#169, #181 (ThinkingConfig), #182 (unknown message types skipped,ConversationResetMessage) and #185 (pre-release follow-ups) - Benchmark organization: Table-driven benchmarks across all core modules (options, parser, shared, control, cli)
- Makefile integration: All code quality checks (fmt, vet, lint, cyclo) unified under
make check - Python SDK parity tracking:
docs/tracking/README.mdtracks all Python SDK PRs to port (snapshot through Apr 12, 2026); organized into 4 chronological phases (Phase 1: Jan 26-Feb 20, Phase 2: Mar 3-Mar 16, Phase 3: Mar 20-Mar 30, Phase 4: Mar 31-Apr 8); Phase 1 items done: #1 GetMcpStatus (Go PR #124, Python PR #516), #2 PostToolUseFailure hook (Go PR #125, Python PR #535), #3 AssistantMessage error field fix (Go PR #124 squash, Python PR #506), #4 3 new hook events + missing fields (Go PR #128, Python PR #545), #5 MCP tool annotations (Python PR #551, Go PR #133), #6 Agents via initialize + unified streaming (Python PR #468, Go PR #134, bundles Go issue #113 Query→streaming migration); next pending: Phase1 item #7 is partial (#136), item #8 (Python #598) is the first pending row; Phase2 item #18 done (Go PR #148, Python PR #685, per-turnAssistantMessage.Usage); Phase3 item #35 done (Go PR #114, Python PR #749); post-snapshot PRs (merged after Apr 12, 2026) tracked indocs/tracking/post-snapshot.mdusing "P" row prefix (P1, P2, ...) with lettered deferred-scope sublists (a/b/c/...); rows P1-P47 are on main (merged via #155); Phase 1 row 7 and P10 (ThinkingConfig,WithThinking) are in Go PR #181; P25 (Python PR #918) done in Go PR #156
<!-- END AUTO-MANAGED --><!-- AUTO-MANAGED: best-practices -->Best Practices
- TDD approach: Write failing tests first, implement to make them pass
- Test file organization: Test functions first, then mocks, then helpers
- Helper functions: Always call
t.Helper()in test utilities - Thread safety: All mocks must be thread-safe with proper mutex usage
- Self-contained tests: Each test file has its own helpers to avoid dependencies
- Benchmark organization: Use table-driven benchmarks with realistic scenarios, measure allocations with
b.ReportAllocs() - t.Fatal() + return: Always follow
t.Fatal()withreturnin subtests to prevent staticcheck SA5011 nil pointer dereference warnings (staticcheck does not track that t.Fatal() stops execution) - Cross-platform mock CLI via TestMain: use
TestMain+os.Args[0]re-entrancy (not.bat/.shfixtures) for packages that need a mock subprocess; dispatch on a package-scoped env var set witht.Setenv; never use Windows-only skips to work around fixture limitations - the TestMain pattern works identically on all platforms
<!-- END AUTO-MANAGED --><!-- MANUAL -->Custom Notes
Add project-specific notes here. This section is never auto-modified.
<!-- END MANUAL -->Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

