agentleFS
severity1severity1/claude-agent-sdk-go/CLAUDE.md

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,…

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
  1. Very specific:

    Idiomatic Go: Use gofmt formatting, standard naming conventions

    line 87
  2. Very specific:

    Interface-driven: All message types implement Message, all content blocks implement ContentBlock

    line 88
  3. Very specific:

    Error handling: Use fmt.Errorf with %w verb for wrapping, include contextual information

    line 89
  4. Very specific:

    Context-first: All blocking functions accept context.Context as first parameter

    line 90
  5. Distinctive:

    No unnecessary exports: Keep identifiers unexported unless needed by external consumers

    line 94
  6. Distinctive:

    Table-driven tests: Use for complex scenarios with multiple test cases

    line 113
  7. Very specific:

    Benchmark tests: Use var sink any to prevent dead code elimination, always call b.ReportAllocs() and b.ResetTimer()

    line 115
  8. Very specific:

    WithHook() generic API: use WithHook(eventName, toolFilter, callback) for hook events that have no convenience helper (e.g.

    line 140
  9. Very specific:

    PostToolUseFailure IsInterrupt nil-check: always guard failInput.IsInterrupt != nil && *failInput.IsInterrupt before treating as interrupt.

    line 142
  10. Distinctive:

    TDD approach: Write failing tests first, implement to make them pass

    line 178
  11. Distinctive:

    Test file organization: Test functions first, then mocks, then helpers

    line 179
  12. Very specific:

    Helper functions: Always call t.Helper() in test utilities

    line 180
  13. Distinctive:

    Thread safety: All mocks must be thread-safe with proper mutex usage

    line 181
  14. Very specific:

    Benchmark organization: Use table-driven benchmarks with realistic scenarios, measure allocations with b.ReportAllocs()

    line 183
  15. Very specific:

    t.Fatal() + return: Always follow t.Fatal() with return in subtests to prevent staticcheck SA5011 nil pointer dereference warnings …

    line 184
  16. Distinctive:

    Add project-specific notes here.

    line 192

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

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:

  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, interfaces, data flow, and contribution guidelines.

<!-- END AUTO-MANAGED --><!-- AUTO-MANAGED: conventions -->

Code Conventions

  • Idiomatic Go: Use gofmt formatting, standard naming conventions
  • Interface-driven: All message types implement Message, all content blocks implement ContentBlock
  • Error handling: Use fmt.Errorf with %w verb for wrapping, include contextual information
  • Context-first: All blocking functions accept context.Context as first parameter
  • JSON handling: Custom UnmarshalJSON for union types, discriminate on "type" field
  • Cyclomatic complexity: Keep functions under complexity 15 (measured by gocyclo); use //nolint:gocyclo on functions that legitimately exceed the threshold (large table-driven test functions, complex orchestration); extract helpers (e.g. buildToolsListResult from routeMcpMethod) 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 use XxxError suffix
  • 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 MockTransport for tests
  • Process cleanup: SIGTERM -> wait 5 seconds -> SIGKILL; startProcessWaiter() is the sole cmd.Wait() caller, started right after Start(), and closes processDone on exit, after it sets t.exit (*processExit{done, err}, with exitReason(cmd.ProcessState, waitErr); a nil state gives a ConnectionError) under exitMu; Transport.Done()/Err() read t.exit under exitMu and never take t.mu, cleanup clears it, and openStdin uses t.Err() (TestTransportDoneAndErrDoNotTakeTransportLock); terminateProcess() never calls cmd.Wait(), it waits on processDone and no longer treats stdoutDone (stdout EOF) as process exit (a CLI that closes stdout but stays alive must still be signaled); child stdout and the stderr callback use os.Pipe via newChildOutputPipe() instead of cmd.StdoutPipe/StderrPipe because cmd.Wait() closes those readers and drops buffered output (Python reads stdout to EOF, reaps separately); the childPipeEnds write ends are closed in the parent after Start(); handleStdout(protocol, childProcess{cmd, done}) closes stdoutDone at stdout EOF (signalStdoutDone) before waiting for exit, then childProcess.exitError(ctx, lastErrorResult) returns *shared.ProcessError (ExitCode from ProcessState) for a non-zero exit, nil for a clean exit or cancelled ctx (handleStdout drops it while t.closing is closed); after an error ResultMessage the message is "Claude Code returned an error result: <errors or subtype>" (Python #918; trackErrorResult resets on any other message except system session_state_changed); SendMessage returns *shared.ConnectionError once processDone is closed and IsConnected() is false after exit (processExitedLocked); isProcessAlreadyFinishedError() suppresses expected termination errors including Windows "TerminateProcess: Access is denied"; graceful shutdown (tracker rows 14a/30, PR #163): teardownLocked order is close protocol+adapter, close(t.closing), stdinWriter.Close() (does not wait for a blocked write), terminateProcess(), then t.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 keep handleStdout blocked in its read; TestCloseDoesNotWaitForDescendantHoldingOutput, mock modes close_orphan_stdout/orphan_stdout_and_stderr re-exec the test binary as the descendant), wait wg at most pipeDrainGrace (500ms, for the stderr callback to drain its pipe), cleanup; terminateProcess never reads t.ctx: wait 5s on processDone (grace after stdin EOF), SIGTERM, wait 5s, Kill, wait 5s via waitProcessDone(d) (Windows SIGTERM fails, goes to Kill); handleStdout keeps draining while t.closing is closed (msgChan send, sendStreamError, control routing and the exitError result are dropped); Connect uses exec.Command and a t.ctx from context.Background(), so the connect ctx bounds only connect + Initialize (net.Dialer.DialContext semantics) and the client lives until Disconnect; queryIterator.watchContext() closes the iterator when its ctx ends
  • stdinWriter: internal/subprocess/stdin.go; writeMu serializes writes (Python _write_lock); EndInput waits for an in-flight write, Close does not (pipe close runs on a goroutine); t.stdin is *stdinWriter, non-nil after EndInput (isClosed()); SendMessage writes outside t.mu (openStdin helper); control delegations use connectedProtocol() and call the protocol outside t.mu; ProtocolAdapter.Write does not hold pa.mu during the write
  • Stderr callback delivery: handleStderrCallback never checks ctx.Done() inside its scan loop, so lines already read still reach StderrCallback after cancel (Python parity: its stderr reader never drops a read line); pinned by TestStderrCallbackDeliversLinesAfterCancel
  • 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.ErrTooLong becomes parser.NewBufferOverflowError(limit, err), a *JSONDecodeError with text "JSON message exceeded maximum buffer size of N bytes" (same text as the parser)
  • Rate limit event: RateLimitInfo keeps the whole rate_limit_info object in Raw map[string]any (json "-", PR #187). Utilization *float64 is nil when absent. OverageDisabledReason is a string. Constants RateLimitStatusAllowedWarning/RateLimitStatusRejected and RateLimitTypeFiveHour/SevenDay/SevenDayOpus/SevenDaySonnet/Overage are untyped strings, re-exported in types.go. IsUsingOverage is a Go extra. uuid and session_id stay optional (deliberate divergence: Python raises MessageParseError). Tracker row 15
  • Environment variables: Set CLAUDE_CODE_ENTRYPOINT to identify SDK to CLI
  • buildEnvironment order: drops the inherited CLAUDECODE variable, then sets CLAUDE_AGENT_SDK_VERSION=shared.SDKVersion last so user env cannot override it; internal/shared/version.go holds SDKVersion ("0.9.1"), and root Version = shared.SDKVersion
  • Setting sources argv: SettingSources is 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 *[]string set by control.WithSkills; Transport.skillsProtocolOption sends it only when the option value is []string
  • Thinking config: ThinkingConfig is a sealed interface (unexported thinkingArgs(); shared.ThinkingArgs(cfg) is the helper for internal/cli, nil or a typed nil pointer (one reflect check) gives nil, and addThinkingFlags then falls back to MaxThinkingTokens). ThinkingConfigAdaptive{Display} emits --thinking adaptive, ThinkingConfigEnabled{BudgetTokens, Display} emits --max-thinking-tokens N, ThinkingConfigDisabled emits --thinking disabled. ThinkingDisplay (summarized, omitted) emits --thinking-display <v>, never for disabled and not when empty. Options.Thinking takes precedence over MaxThinkingTokens. addThinkingFlags emits --max-thinking-tokens only when MaxThinkingTokens > 0. NewOptions no longer sets 8000, so the CLI chooses. DefaultMaxThinkingTokens and WithMaxThinkingTokens are deprecated; the MaxThinkingTokens field 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) in client.go covers resume, resume_session_at and resume_drops_turn
  • Table-driven tests: Use for complex scenarios with multiple test cases
  • Functional options: WithXxx() pattern for configuration
  • Benchmark tests: Use var sink any to prevent dead code elimination, always call b.ReportAllocs() and b.ResetTimer()
  • tool_use_result metadata: UserMessage.ToolUseResult carries rich edit info (filePath, structuredPatch, diffs); check with HasToolUseResult() before accessing via GetToolUseResult()
  • parent_tool_use_id placement: parsed from top-level JSON data (not nested message object) for UserMessage, AssistantMessage, and StreamEvent; identifies messages produced inside a subagent (Agent/Task tool)
  • AssistantMessage error field: AssistantMessage.Error is *AssistantMessageError parsed from top-level data["error"] (not nested data["message"]["error"]); CLI wire format is {"type":"assistant","error":"rate_limit","message":{...}}; use HasError() to check presence, IsRateLimited() for rate limit specifically; AssistantMessageError constants (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; both Query() and Client route 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 --agents CLI flag. The prompt for Query() is written to stdin as a user-message JSON line ({"type":"user","session_id":"","message":{"role":"user","content":...},"parent_tool_use_id":null}) after Connect() returns. Wire-shape pins (no omitempty, key always emitted): StreamMessage.SessionID and StreamMessage.ParentToolUseID always emit "session_id":"" and "parent_tool_use_id":null when unset; InitializeRequest.Hooks always emits "hooks":null when no hooks are registered (matches Python "hooks": hooks_config if hooks_config else None). Transport.EndInput(ctx) is declared on the public Transport interface (parity-review W2 fix; previously only on subprocess.Transport, discovered via inline-interface assertion in query.go); closes the stdin write side only (idempotent); invoked by queryIterator.start() immediately when no bidirectional channel is needed, or after the first ResultMessage when hooks/CanUseTool/SDK-MCP/file-checkpointing keep the control protocol alive. The needs-bidirectional decision lives in needsBidirectionalStdin() in query.go. The Go gate is deliberately wider than Python's (Python: sdk_mcp_servers OR hooks; Go: those + CanUseTool + EnableFileCheckpointing) as an idiomatic-Go divergence - Go has no preflight rejection for Query(str) + CanUseTool, and EnableFileCheckpointing legitimately requires the control protocol because RewindFiles() rides over it. agentsToMap stripping 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: Hooks field has no omitempty (always emits "hooks":null when no hooks registered, matching Python wire shape); Agents field has omitempty (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_subagents Example 4 demonstrates a large-payload (~260 KB, 20 agents) that would previously exceed OS ARG_MAX via --agents but 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 reads t.connected/t.protocol unlocked. routeInitError(protocol, msg) is a free function in io.go: it detects an error ResultMessage arriving before initialize completes (protocol.IsInitialized(), checked under the protocol lock) and calls protocol.HandleControlInitErr() to unblock SendControlRequest() via initErrChan. setupControlProtocol() additionally spawns a watcher goroutine that calls HandleControlInitErr() when the CLI exits before responding to initialize (stdoutDone closed by handleStdout at stdout EOF, before the process exit wait); the watcher captures channel/protocol pointers locally to avoid races on reconnect. HandleControlInitErr() reads p.initialized under lock and is a no-op after Initialize() succeeds, so the post-init watcher cannot poison initErrChan for later SendControlRequest calls (e.g. SetModel/GetMcpStatus).
  • Concurrent control dispatch: Protocol.HandleIncomingMessageAsync() runs each incoming control_request on its own goroutine (responses and regular messages stay inline) so a slow CanUseTool/hook/MCP callback cannot stall handleStdout(); per-request ctx cancel funcs live in Protocol.inflightRequests keyed by request_id, and Close() 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 error control_response for handler errors and panics; an unsupported subtype now returns an error (error response, Python parity) instead of being silently ignored; mock mode two_permission_requests and TestTransportSlowPermissionCallbackDoesNotBlockReader cover it
  • Control protocol delegation: Interrupt(), SetModel(), SetPermissionMode(), RewindFiles(), GetMcpStatus(), ReconnectMcpServer(), ToggleMcpServer() guard with t.connected (error "transport not connected") before delegating to t.protocol; nil protocol guard uses descriptive error "internal error: transport connected but control protocol is nil". Interrupt() sends only the {"subtype":"interrupt"} control request (Python Query.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 when Close() runs returns control.ErrProtocolClosed at once (TestCloseFailsPendingInterrupt, mock mode ignore_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 from handleStdout). (No more closeStdin gate - every connection runs control protocol now.)
  • MCP config serialization: generateMcpConfigFile() strips Go Instance field from SDK servers and propagates AlwaysLoad explicitly (not via struct json tags) when building CLI config
  • Resume argv safety (Python PR #1123): addSessionFlags emits --resume=<value> as ONE argv token (the CLI declares --resume with an optional value, so a two-token form lets a dash-leading value like --version parse as a flag); prepareOptions() also calls validateWindowsArgValue(runtime.GOOS, "resume", value) in client.go, which rejects cmd.exe metacharacters (&|<>^%!", CR/LF) only when goos is windowsOS, so Query, QueryWithTransport and Client.Connect all validate
  • Windows batch CLI refusal (Python PR #1127, BatBadBut CVE-2024-27980): cli.RejectWindowsBatchCLI(goos, path) returns *shared.ConnectionError on Windows for any path with a .bat/.cmd component (isWindowsBatchPath is pure string logic, also splits on :, so claude.cmd:stream and claude.cmd. are caught); subprocess.Transport.Connect() calls it before the version probe spawns the CLI. FindCLI on Windows prefers a native claude.exe over an npm claude.cmd PATH 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. addExtraFlags emits --flag=value when the value starts with - (P32 item a; audit vs CLI 2.1.286: only optional-value flags --debug/--resume are injectable)
  • Permission suggestions: ToolPermissionContext.Suggestions []PermissionUpdate carries CLI-provided permission suggestions to CanUseTool callbacks; PermissionUpdate.Type is one of addRules, 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.go and internal/cli/mock_cli_test.go each define a TestMain that 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 before m.Run(). This is the Go analog of Python's sys.executable -c "..." and matches the os/exec stdlib TestHelperProcess idiom. Replaces per-platform .bat/.sh fixtures. 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 a hold_stdout descendant that keeps stdout open for orphanHoldTime, then exits 3), ignore_sigterm, slow_exit_after_eof, stop_reading (these three dispatch via runShutdownMock to keep runMockCLI gocyclo flat; its default case calls runStreamMock, which handles fixed_size_line (emits a line of mockFixedLineLen=4096 bytes); env CLAUDE_SDK_TEST_MOCK_EVENT_LOG makes the mock append NAME <unix-ms> lines EOF/SIGTERM/EXIT, used by shutdown_test.go) (init_error: emits PID on stderr, responds to initialize with subtype:"error", then keeps reading stdin so the SDK must terminate the process - used by TestTransportConnectFailureTearsDown). connectWithWatchdog() in lifecycle_test.go fails a test whose Connect() hangs past a time limit. Test helpers (e.g. newTransportMockCLI(t), newTransportMockCLIInitError(t)) set the env var via t.Setenv (auto-cleaned). t.Setenv is incompatible with t.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) and McpToggleRequest{subtype, serverName, enabled} (mcp_toggle; enabled has no omitempty, so false is sent); Protocol.ReconnectMcpServer/ToggleMcpServer use mcpControlTimeout (60s) and reject an empty server name before sending; both are on the public Transport and Client interfaces. integrationMockTransport (//go:build integration) implements the full Transport interface so go vet -tags integration ./... passes; TestTransportControlProtocolIntegration parent ctx is 30s
  • Constructor functions: NewGetMcpStatusRequest() follows NewPermissionResultAllow/Deny pattern - constructor sets required Subtype field (SubtypeGetMcpStatus = "mcp_status", not "get_mcp_status"); use constructors for control request types with fixed subtype values
  • McpServerConfigType constants: McpServerConfigTypeStdio/SSE/HTTP/SDK/ClaudeAI re-exported in root types.go alongside McpServerConnectionStatus constants; discriminate McpServerStatusConfig.Type field
  • McpServerStatus conditional fields: ServerInfo non-nil only when Status == McpServerConnectionStatusConnected; Error non-nil only when Status == McpServerConnectionStatusFailed; Tools populated only when connected
  • streamErrChan fan-in: ClientImpl.streamErrChan chan error (buffered, size 1) receives errors from QueryStream goroutine; passed directly to clientIterator alongside transport errChan and streamErrChan; Next() selects on both so callers see all stream errors without spawning goroutines; clientIterator and queryIterator read the transport channels through streamReader (stream_reader.go): a closed errChan/streamErrChan is set to nil for the call and reading continues, so Next never returns (nil, nil); the transport sends its terminal error after the last message, so streamReader.next always calls drainToPending first ((nil, nil) from it means keep reading), so every buffered message is delivered before the error (an error read early is held as pending; TestStreamReaderSharedPendingError) and, when msgChan closes, still returns an error left in errChan before ErrNoMoreMessages; ClientImpl.stream is shared by successive ReceiveResponse iterators, so the exit error after a turn's ResultMessage surfaces on the next call (clientIterator.markClosed); QueryStream write errors go to streamErrChan (surfaced by ReceiveResponse), 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 through Disconnect) and Client.Err() says why, following context.Context: nil while running, *ProcessError for a non-zero exit (ExitCode -1 for a signal), *ConnectionError for a clean exit, *ConnectionError wrapping root ErrNotConnected before Connect/after Disconnect (Done is then closed; notConnectedError() builds it and is also used by liveTransportLocked and GetServerInfo; TestClientNotConnectedErrors). The Go analog of Python receive_messages() raising the ProcessError, which a <-chan Message cannot carry. ClientImpl type-asserts the unexported processWatcher interface (Done/Err), which subprocess.Transport implements on processDone (no second waiter); Done does not wait for stdout EOF. Custom transports without it get connectionWatch.disconnected, closed on Disconnect. Done()/Err() never take c.mu: they read c.watch *connectionWatch{watcher, disconnected} under watchMu, set at Connect and cleared (swapWatch) before transport.Close() in Disconnect, so Err() during Disconnect returns the not-connected *ConnectionError and never the transport's plain "transport not connected" error; a failed Close restores it (TestClientErrDuringDisconnect, TestClientFailedDisconnectKeepsWatch, cleanupThenBlockTransport mock) (TestClientDoneAndErrDoNotBlockDuringDisconnect, blockingCloseTransport mock). Root ErrProtocolClosed = control.ErrProtocolClosed is exported in errors.go. liveTransport()/liveTransportLocked() gate Query, QueryWithSession, QueryStream, Interrupt, SetModel, SetPermissionMode, RewindFiles, GetMcpStatus, StopTask, ReconnectMcpServer, ToggleMcpServer: a dead process returns *ConnectionError("cannot write to terminated CLI process", Err()) (Python: CLIConnectionError raised from _exit_error), so QueryStream no 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.Initialize keeps the whole response map in initResult (it still decodes supported_commands into InitializeResponse); Protocol.InitializationResult() returns a deep copy (copyJSONValue), nil before the handshake. subprocess.Transport.InitializationResult() delegates through connectedProtocol() (nil when not connected). ClientImpl.GetServerInfo type-asserts the unexported serverInfoSource interface and returns that map, nil for a custom transport without it, "client not connected" error when not connected; the old hard-coded connected/transport_type keys are gone. Mock mode server_info answers initialize with mockInitializeResponse. Tests: TestInitializationResultKeepsFullResponse, TestTransportInitializationResult, TestGetServerInfo, TestGetServerInfoConcurrent, TestSubprocessTransportKeepsServerInfo (guards the optional interface)
  • prepareOptions(): applies defaults before validating - auto-configures PermissionPromptToolName = "stdio" when CanUseTool callback is set; renamed from validateOptions() to reflect dual role
  • ReceiveResponse() disconnected behavior: returns non-nil clientIterator with closed msgChan and empty errChan (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"; IsInterrupt nil means key absent in JSON (Python NotRequired[bool] semantics); PostToolUseFailureHookSpecificOutput is structurally identical to PostToolUseHookSpecificOutput (only HookEventName literal differs), both have AdditionalContext *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 helpers WithPreToolUseHook / WithPostToolUseHook exist only for PreToolUse and PostToolUse; see examples/12_hooks Example 4 (PostToolUseFailure) and Example 5 (Notification) for canonical usage
  • HookSpecificOutput types: PostToolUseHookSpecificOutput, PostToolUseFailureHookSpecificOutput both require HookEventName field set to the event name string (json tag hookEventName); AdditionalContext *string (omitempty) is the field for injecting context Claude will read on the next turn; use a local ptrTo[T any] helper (func ptrTo[T any](v T) *T { return &v }) in examples for constructing *string values; PermissionRequestHookSpecificOutput.Decision map[string]any is the only output field without omitempty - it is required (mirrors Python required dict)
  • PostToolUseFailure IsInterrupt nil-check: always guard failInput.IsInterrupt != nil && *failInput.IsInterrupt before 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, AgentType added as flat required string fields in Python SDK PR #545 (NOT via _SubagentContextMixin); SubagentStart/SubagentStop keep required string fields, while PreToolUseHookInput, PostToolUseHookInput, PostToolUseFailureHookInput and PermissionRequestHookInput carry AgentID/AgentType *string (omitempty, parsed with getStringPtr, nil = key absent; tracker row 13 done)
  • getAnySlice helper: mirrors getMap in internal/control/hooks.go; returns nil when key absent (preserving Python NotRequired semantics); use when Python field type is list[Any] with NotRequired semantics (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); Title nil maps to Python NotRequired[str] absent state - always nil-guard before dereferencing; Notification hooks return empty HookJSONOutput{} (observation only, no HookSpecificOutput); PermissionRequestHookInput.PermissionSuggestions is []any (mirrors Python list[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 *T omitempty) vs control.McpToolAnnotations (CLI status response side, Hint suffix stripped: ReadOnly/Destructive/OpenWorld); mirrors Python mcp.types.ToolAnnotations vs McpToolAnnotations TypedDict split; ToolOption functional option pattern extends NewTool() with variadic ...ToolOption (backward compatible); consumers use NewTool(..., WithToolAnnotations(&ToolAnnotations{...})); annotationsToMap uses json.Marshal+Unmarshal round-trip to honor omitempty; buildToolsListResult is a standalone helper (not inlined in routeMcpMethod switch) to keep dispatch under gocyclo budget; tools/list wire behavior: nil pointer 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() calls teardownLocked() when setupControlProtocol fails 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 between Close() (called after setting connected=false) and the Connect error path, so no subprocess is ever leaked on a failed connect. TestTransportConnectFailureTearsDown verifies this by capturing the mock CLI PID via StderrCallback and probing syscall.Signal(0) after the failed Connect() returns.
  • Query iterator close-on-drain (Issue #145): queryIterator.Next() calls qi.Close() on every terminal path (end of stream, terminal error, ctx done, start() failure after Connect), so a caller that drains Query() without calling Close() leaks no transport or temp file (Python parity: query() closes in finally). Close() is idempotent. TestQueryClosesTransportAtStreamEnd verifies this; queryMockTransport records calls via closeCalls / getCloseCalls().
  • ReceiveResponse stops at ResultMessage: clientIterator.Next() calls markClosed() after returning a *ResultMessage, so the next Next() returns ErrNoMoreMessages (Python receive_response() parity); transport msgChan stays open so the next Query + ReceiveResponse reads the next turn; ReceiveMessages() channel is unchanged; tests TestClientIteratorStopsAfterResultMessage, TestClientReceiveResponseMultiTurn
  • ResultMessage.StopReason: *string (json stop_reason,omitempty), nil when absent; parsed in parseResultOptionalFields (internal/parser/json.go), extracted to keep parseResultMessage under gocyclo 15 (tracker row 9 done)
  • Unknown message types: parser.ParseMessage returns (nil, nil) for an unknown top-level type, and parseContentBlocks drops unknown content block types (Python parity, forward compatible); a known type with a missing field still returns MessageParseError. ConversationResetMessage{MessageType, NewConversationID, UUID, SessionID} (MessageTypeConversationReset = "conversation_reset") needs all three ID fields and is re-exported in types.go. Server tool blocks: ServerToolUseBlock{ID, Name ServerToolName, Input} (ContentBlockTypeServerToolUse = "server_tool_use") and ServerToolResultBlock{ToolUseID, Content map} (ContentBlockTypeAdvisorToolResult = "advisor_tool_result"), with ServerToolName* constants; the parser cases require all keys (else MessageParseError). Typed task structs carry no JSON tags: json.Marshal writes the raw payload, so use AsTask*, not a type switch
  • Allow permission sends updatedInput: sendPermissionResponse(..., originalInput) in internal/control/permissions.go sends the original tool input as "updatedInput" when an allow result has nil UpdatedInput (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), use Closes #N in 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 has continue-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), CanUseTool configuration applied on the Query path (PR #152, issue #146), concurrent control-request dispatch (PR #151, from #142; see Concurrent control dispatch pattern), single Wait owner for the CLI process + os.Pipe child 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 (updatedInput fallback), #159 (ReceiveResponse stops at the ResultMessage), #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; both Query() and Client use streaming mode + unconditional initialize handshake; agents travel on initialize control request; EndInput() closes stdin write side; post-feat fixes: (1) InitializeRequest.Hooks emits "hooks":null (no omitempty, matching Python wire shape), (2) StreamMessage.SessionID/ParentToolUseID lack omitempty (wire always emits both keys), (3) HandleControlInitErr() is no-op after successful Initialize (race guard for long-lived clients), (4) cross-platform mock CLI via TestMain + os.Args[0] re-entrancy replaces .bat/.sh fixtures in both internal/subprocess and internal/cli, (5) examples/15_programmatic_subagents Example 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 public Transport interface (was only on subprocess.Transport, found via inline-interface assertion in query.go), (7) teardownLocked() extracted as unified post-Start cleanup primitive shared between Close() and Connect() error path so no subprocess leaks on failed connect, (8) terminateProcess() calls cmd.Wait() on stdoutDone fast path to reap process and release exec.Cmd watchCtx goroutine, (9) init_error mock mode + TestTransportConnectFailureTearsDown test verifies subprocess is reaped after connect failure (probes PID via syscall.Signal(0)); Phase1 item #5 - MCP tool annotations (Python PR #551): shared.ToolAnnotations struct (authoring side) + ToolOption/WithToolAnnotations on NewTool(); annotationsToMap json round-trip; buildToolsListResult extracted from routeMcpMethod (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.md tracks 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-turn AssistantMessage.Usage); Phase3 item #35 done (Go PR #114, Python PR #749); post-snapshot PRs (merged after Apr 12, 2026) tracked in docs/tracking/post-snapshot.md using "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() with return in 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/.sh fixtures) for packages that need a mock subprocess; dispatch on a package-scoped env var set with t.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 -->

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.