Documentation
¶
Overview ¶
Package claudecode drives the Claude Code CLI (`claude`) as a subprocess over the stream-json control protocol that Anthropic's Agent SDKs speak.
This is not an official Anthropic SDK. It is an independent Go driver for the same protocol, written to run unattended coding agents from a Go program.
A Driver starts a Session. The session streams every line the CLI writes (and every line the driver writes to it) as agent.Event values, keeps the raw bytes of each one, and serves the CLI's control requests: permission prompts and AskUserQuestion go to agent.Options.Permission, hook callbacks to Extra.Hooks, and in-process MCP tools to agent.Options.ToolServers.
The protocol is not a documented stable API, so the driver is pinned to one CLI version (TestedVersion) and refuses others unless Driver.AllowUntestedVersion is set. docs/protocol.md in the repository describes the protocol as implemented and how to re-verify it when the CLI is upgraded.
Package agent holds the agent-neutral types (Options, Event, Session, PermissionFunc, ToolServer) that this package implements.
Defaults are chosen for running an agent on code you do not fully trust: no settings files are loaded (no user, project or local settings, so a committed .claude/settings.json cannot allow tools or add hooks), the environment is an allowlist, the permission mode is always passed, and everything the CLI started is killed when it exits.
Example ¶
Start a session, send one prompt, answer permission prompts, and read the events until the agent is idle. This example needs a Claude login and the tested CLI version, so it is compiled but not run by `go test`.
package main
import (
"context"
"fmt"
"log"
claudecode "github.com/trutohq/claude-code-go"
"github.com/trutohq/claude-code-go/agent"
)
func main() {
ctx := context.Background()
d := claudecode.New() // refuses CLI versions other than claudecode.TestedVersion
s, err := d.Start(ctx, agent.Options{
WorkDir: "/path/to/repo",
Model: "sonnet",
PermissionMode: "default",
AllowedTools: []string{"Read", "Grep", "Glob"},
Permission: func(ctx context.Context, req agent.PermissionRequest) (agent.PermissionDecision, error) {
if req.IsQuestion() {
// AskUserQuestion: pick the first option of each question.
answers := map[string]string{}
for _, q := range req.Questions {
if len(q.Options) > 0 {
answers[q.Question] = q.Options[0].Label
}
}
return agent.Answer(answers), nil
}
if req.ToolName == "Edit" || req.ToolName == "Write" {
return agent.Allow(), nil
}
return agent.Deny("only file edits are allowed"), nil
},
})
if err != nil {
log.Fatal(err) // a *claudecode.VersionError if the CLI version is untested
}
defer s.Close()
if err := s.Send(ctx, agent.UserMessage{Text: "Fix the failing test in parser_test.go"}); err != nil {
log.Fatal(err)
}
var sawResult bool
for ev := range s.Events() {
switch ev.Kind {
case agent.KindAssistant:
fmt.Print(ev.Message.Text())
case agent.KindResult:
sawResult = true
case agent.KindSessionState:
// A result ends a turn; idle after a result means nothing is left.
if ev.State == "idle" && sawResult {
_ = s.CloseInput()
}
}
}
if err := s.Wait(); err != nil {
log.Fatal(err)
}
}
Output:
Example (Hooks) ¶
Gate tools with an in-process PreToolUse hook. A hook that errors or panics denies the tool (fails closed).
package main
import (
"context"
"encoding/json"
"log"
"strings"
claudecode "github.com/trutohq/claude-code-go"
"github.com/trutohq/claude-code-go/agent"
)
func main() {
ctx := context.Background()
noForcePush := func(ctx context.Context, in claudecode.HookInput) (json.RawMessage, error) {
var p struct {
ToolInput struct {
Command string `json:"command"`
} `json:"tool_input"`
}
if err := json.Unmarshal(in.Input, &p); err != nil {
return nil, err
}
if strings.Contains(p.ToolInput.Command, "push --force") {
return json.RawMessage(`{"hookSpecificOutput":{"hookEventName":"PreToolUse",` +
`"permissionDecision":"deny","permissionDecisionReason":"force push is not allowed"}}`), nil
}
return nil, nil // no opinion
}
s, err := claudecode.New().StartSession(ctx, agent.Options{WorkDir: "/path/to/repo"}, claudecode.Extra{
Hooks: map[string][]claudecode.HookMatcher{
"PreToolUse": {{Matcher: "Bash", Callbacks: []claudecode.HookFunc{noForcePush}}},
},
})
if err != nil {
log.Fatal(err)
}
defer s.Close()
}
Output:
Example (ToolServer) ¶
Expose an in-process tool to the agent. The CLI sees it as mcp__tickets__comment.
package main
import (
"context"
"encoding/json"
"github.com/trutohq/claude-code-go/agent"
)
func main() {
tickets := agent.ToolServer{Name: "tickets", Version: "1.0.0", Tools: []agent.Tool{{
Name: "comment",
Description: "Add a comment to the ticket this run works on.",
InputSchema: json.RawMessage(`{"type":"object","properties":{"text":{"type":"string"}},"required":["text"]}`),
Handler: func(ctx context.Context, call agent.ToolCall) (agent.ToolResult, error) {
var in struct {
Text string `json:"text"`
}
if err := json.Unmarshal(call.Arguments, &in); err != nil {
return agent.ToolResult{}, err // reported to the model as a failed tool call
}
return agent.TextResult("comment added"), nil
},
}}}
_ = agent.Options{
WorkDir: "/path/to/repo",
ToolServers: []agent.ToolServer{tickets},
AllowedTools: []string{"mcp__tickets__comment"}, // no permission prompt for it
}
}
Output:
Index ¶
- Constants
- func DeferToolUse(reason string) json.RawMessage
- func ParseVersion(out string) (string, error)
- func ResolveBinary(path string) (string, error)
- func SessionFile(configDir, cwd, sessionID string) string
- type ControlError
- type Driver
- func (d *Driver) Name() string
- func (d *Driver) Start(ctx context.Context, opts agent.Options) (agent.Session, error)
- func (d *Driver) StartSession(ctx context.Context, opts agent.Options, extra Extra) (*Session, error)
- func (d *Driver) Version(ctx context.Context, binary string, env []string) (string, error)
- type Extra
- type HookFunc
- type HookInput
- type HookMatcher
- type Info
- type Session
- func (s *Session) ClaudeInfo() Info
- func (s *Session) Close() error
- func (s *Session) CloseInput() error
- func (s *Session) Done() <-chan struct{}
- func (s *Session) Events() <-chan agent.Event
- func (s *Session) Info() agent.SessionInfo
- func (s *Session) Interrupt(ctx context.Context) error
- func (s *Session) Request(ctx context.Context, fields map[string]any) (json.RawMessage, error)
- func (s *Session) Send(ctx context.Context, msg agent.UserMessage) error
- func (s *Session) SessionID() string
- func (s *Session) SetModel(ctx context.Context, model string) error
- func (s *Session) SetPermissionMode(ctx context.Context, mode string) error
- func (s *Session) Wait() error
- type VersionError
Examples ¶
Constants ¶
const AskUserQuestionTool = "AskUserQuestion"
AskUserQuestionTool is the CLI's built-in question tool.
const DefaultPermissionMode = "default"
DefaultPermissionMode is passed when Options.PermissionMode is empty. The mode is always passed explicitly: without it the CLI uses the user's settings, which on a developer machine may be bypassPermissions.
const Name = "claude-code"
Name is the driver name.
const SessionMarkerEnv = "CCGO_AGENT_SESSION"
SessionMarkerEnv is set to a random id in every CLI the driver starts. Children inherit it, even ones that leave the process group (the CLI starts its Bash shells with setsid), so on Linux the driver can find and kill everything the session left running. See killMarked.
const TestedVersion = "2.1.296"
TestedVersion is the Claude Code CLI version this driver was verified against. The protocol is not a documented stable API: upgrade by re-running the integration test (docs/protocol.md) and then bumping this.
Variables ¶
This section is empty.
Functions ¶
func DeferToolUse ¶
func DeferToolUse(reason string) json.RawMessage
DeferToolUse is a PreToolUse hook output that makes the CLI stop before the tool runs and exit; the result carries the deferred call, and the session is resumed with --resume once the answer is known.
func ParseVersion ¶
ParseVersion extracts the version from `claude --version` output.
func ResolveBinary ¶
ResolveBinary finds the claude executable and resolves symlinks, so that the version checked is the version run even if the symlink moves.
func SessionFile ¶
SessionFile is where Claude Code keeps a session's conversation: <config dir>/projects/<cwd with every character other than a letter or a digit replaced by "-">/<session id>.jsonl. A session is resumed (--resume) from the project directory of the working directory it is resumed in, so carrying a conversation to another working directory or machine means copying this file to the new directory's path. cwd should be the real path (symlinks resolved), as the CLI sees it.
Not verified against the CLI by a test here (the fake CLI follows the same layout); for working directories longer than 200 characters the CLI shortens the name with a hash this function does not reproduce, and a resume then starts afresh.
Types ¶
type ControlError ¶
ControlError is an error reply to a control request the driver sent.
func (*ControlError) Error ¶
func (e *ControlError) Error() string
type Driver ¶
type Driver struct {
// AllowUntestedVersion lets sessions start on a CLI version other than
// TestedVersion. The mismatch is then reported in Info().VersionWarning
// instead of failing Start.
AllowUntestedVersion bool
// contains filtered or unexported fields
}
Driver starts Claude Code sessions.
type Extra ¶
type Extra struct {
// Hooks registers in-process hook callbacks by hook event name
// ("PreToolUse", "PostToolUse", "Stop", ...).
Hooks map[string][]HookMatcher
// InitTimeout bounds the initialize handshake (default 60s; MCP servers
// start during it).
InitTimeout time.Duration
// ShutdownGrace is how long Close waits after closing stdin before
// SIGTERM, and again before SIGKILL (default 5s).
ShutdownGrace time.Duration
}
Extra holds Claude-specific session options that have no place in the agent-neutral agent.Options.
type HookFunc ¶
HookFunc answers a hook callback. The returned JSON is the hook output in the CLI's format (e.g. {"hookSpecificOutput": {...}}); nil means "{}".
The CLI treats a failed hook callback as "no opinion" and carries on. So for PreToolUse the driver turns an error, a panic or an output that is not a JSON object into an explicit permissionDecision "deny" with the error as the reason: a hook that gates tools fails closed. For every other event a failure is reported to the CLI as an error, and the CLI proceeds as if the hook had returned nothing.
type HookInput ¶
type HookInput struct {
CallbackID string
ToolUseID string
// Input is the hook payload (hook_event_name, tool_name, tool_input, ...).
Input json.RawMessage
}
HookInput is one hook invocation.
type HookMatcher ¶
type HookMatcher struct {
// Matcher is the tool-name pattern for tool hooks ("" matches all).
Matcher string
Timeout time.Duration
Callbacks []HookFunc
}
HookMatcher is one hook registration.
type Info ¶
type Info struct {
// Binary is the resolved CLI executable that runs.
Binary string
// Version is the CLI version (from --version and the initialize reply).
Version string
// VersionWarning is set when the version is untested and the driver
// allows it.
VersionWarning string
// PID is the CLI process id.
PID int
// PermissionMode is the mode the CLI reports after initialize.
PermissionMode string
// Initialize is the raw initialize reply (commands, models, account...).
Initialize json.RawMessage
}
Info describes a started session.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is a running Claude Code process. It implements agent.Session.
func (*Session) ClaudeInfo ¶
ClaudeInfo returns what is known about the running CLI.
func (*Session) Close ¶
Close implements agent.Session: close stdin, then SIGTERM, then SIGKILL the process group, each after the shutdown grace period.
func (*Session) CloseInput ¶
CloseInput implements agent.Session.
func (*Session) Done ¶
func (s *Session) Done() <-chan struct{}
Done is closed once the session has fully ended.
func (*Session) Request ¶
Request sends any control request (fields must include "subtype") and returns the CLI's reply payload.
func (*Session) SetPermissionMode ¶
SetPermissionMode changes the permission mode of the running session.
type VersionError ¶
VersionError reports a CLI version this driver has not been tested with.
func (*VersionError) Error ¶
func (e *VersionError) Error() string