claudecode

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 20 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

claude-code-go

A Go driver for the Claude Code CLI. It starts claude as a subprocess and speaks the stream-json control protocol that Anthropic's Agent SDKs use: streamed messages, permission prompts, questions to a person, hook callbacks, in-process MCP tools, interrupts and resume.

It is written for programs that run coding agents unattended: the defaults load no settings files, pass the host's environment through an allowlist, and kill everything the agent started when the session ends.

This is not an official Anthropic SDK. It is an independent implementation of the same protocol. Anthropic's own SDKs are for Python and TypeScript.

go get github.com/trutohq/claude-code-go

No dependencies outside the standard library. Go 1.24 or later.

Status

Pre-1.0. The API can change between minor versions until 1.0.

Tested CLI version 2.1.296 (claudecode.TestedVersion)
Platforms Linux (full process cleanup), macOS and other Unix (process-group cleanup only). Windows builds but only the CLI process itself is stopped. CI runs on Linux.
Protocol notes docs/protocol.md: every flag, line type and control request the driver relies on, with what was verified and how

Version pinning

The stream-json control protocol is not a documented stable API. A renamed field can mean a question that is never answered or a permission granted on the wrong input, with no error anywhere. So the driver refuses CLI versions it was not tested with:

  1. Start resolves the claude binary (symlinks followed) and runs <binary> --version. The result is cached per file.
  2. A version other than TestedVersion fails with a *claudecode.VersionError.
  3. The initialize reply's claude_code_version is checked again, in case the binary changed in between.
  4. The driver sets DISABLE_AUTOUPDATER=1, so the CLI does not replace itself during a run.

To run an untested version anyway, set Driver.AllowUntestedVersion. The session then starts, and Session.ClaudeInfo().VersionWarning says why it should not have.

To keep a version pinned, point Options.BinaryPath at the versioned binary (~/.local/share/claude/versions/<version> for the native installer) and not at the claude symlink, which moves on update.

A new CLI version is supported by re-running the protocol checks against it and raising TestedVersion (see "Re-verifying on a CLI upgrade" in docs/protocol.md).

Quick start

import (
	claudecode "github.com/trutohq/claude-code-go"
	"github.com/trutohq/claude-code-go/agent"
)

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.ToolName == "Edit" || req.ToolName == "Write" {
			return agent.Allow(), nil
		}
		return agent.Deny("only file edits are allowed"), nil
	},
})
if err != nil {
	return 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 {
	return 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:
		if ev.State == "idle" && sawResult {
			s.CloseInput() // nothing left to do: let the CLI exit
		}
	}
}
return s.Wait() // nil, or an *agent.ExitError with the stderr tail

The full example is in example_test.go.

Things to know:

  • A result ends a turn, not the session. Background tasks can wake the agent for more turns. Wait for KindSessionState with state idle after a result before you close input. Once input is closed, permission prompts, hooks and in-process tools stop working.
  • Drain Events() until it is closed. It is an unbounded queue, so control requests are served even when you read slowly, but memory grows until you read.
  • Every line is kept raw. Event.Raw holds the exact bytes of each line the CLI wrote, each line the driver wrote (KindSent) and each stderr line (KindStderr). The typed fields are a convenience. Unknown line types arrive as KindUnknown and are never dropped, so you can store a complete transcript.
  • Send works while the agent is working. UserMessage.Priority (now, next, later) says when the message is delivered. Interrupt stops the current turn and keeps the session.
  • Session.SetModel, Session.SetPermissionMode and Session.Request (any control request, for example get_context_usage) are on the concrete *claudecode.Session, which Driver.StartSession returns.

Permission prompts and questions

When Options.Permission is set, the CLI asks it before each tool call that is not already allowed (AllowedTools, the permission mode). When it is nil, the CLI denies anything that would prompt and does not offer AskUserQuestion.

  • The callback runs on its own goroutine and can wait as long as a person needs. Its context is cancelled if the CLI withdraws the request or the session ends.
  • agent.Allow(), agent.Deny(msg), or a PermissionDecision with UpdatedInput (change the tool's input) or Interrupt (deny and stop the turn).
  • An error or a panic in the callback is a denial.
  • AskUserQuestion arrives as a request with req.IsQuestion() true and req.Questions parsed. Answer it with agent.Answer(map[question]label) or agent.AnswerMulti. An allow without answers is refused, so a blanket "allow everything" callback cannot skip a question meant for a person.
  • No question timeout was found on this path on 2.1.296, so a person can take as long as they need (details in docs/protocol.md).

Hooks

Driver.StartSession takes claudecode.Extra, with in-process hook callbacks by event name:

s, err := claudecode.New().StartSession(ctx, opts, claudecode.Extra{
	Hooks: map[string][]claudecode.HookMatcher{
		"PreToolUse": {{Matcher: "Bash", Callbacks: []claudecode.HookFunc{noForcePush}}},
	},
})

A HookFunc returns the hook output in the CLI's JSON format, or nil for no opinion.

  • PreToolUse hooks fail closed. The CLI reads a failed hook callback as "no opinion" and runs the tool. The driver turns an error, a panic or an output that is not a JSON object from a PreToolUse hook into an explicit deny. For other events a failure is reported to the CLI as an error.
  • claudecode.DeferToolUse(reason) builds a PreToolUse output that stops the CLI before the tool runs. The result then carries Deferred, and you resume the session later. A permission callback that waits is usually simpler.

In-process MCP tools

Options.ToolServers exposes Go functions to the agent as MCP tools, with no extra process or socket. A server named tickets with a tool comment is seen by the model as mcp__tickets__comment.

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) {
		return agent.TextResult("comment added"), nil
	},
}}}
opts.ToolServers = []agent.ToolServer{tickets}
opts.AllowedTools = append(opts.AllowedTools, "mcp__tickets__comment") // else each call prompts
  • In-process tools are permission-checked like any other tool. List them in AllowedTools to skip the prompt.
  • A handler error or panic becomes a tool result with isError: true, which the model reads. The session goes on.
  • On 2.1.296 the CLI defers MCP tool schemas: the model first loads the tool with ToolSearch, which costs one extra turn. Allow for it in MaxTurns.
  • External MCP servers go in Options.MCPConfig (paths or JSON, as for --mcp-config). Set StrictMCPConfig to ignore every server you did not list, including the user's and any claude.ai connectors.

Resume

  • Options.SessionID (a UUID) starts a new conversation with that id. Options.Resume continues an existing one. Session.SessionID() returns the id the CLI reports.
  • The CLI resumes from the project directory of the working directory it runs in. claudecode.SessionFile(configDir, cwd, sessionID) returns where that conversation file is, so you can copy it when the working directory or the machine changes. It does not reproduce the CLI's hashed names for working directories longer than 200 characters.
  • Resuming does not restore the permission mode. The driver passes --permission-mode on every start (default when empty).
  • Never run two processes on one session id.

Safety notes

The defaults assume the agent works on a repository you do not fully trust, and that prompt injection is possible.

  • No settings files. The driver always passes --setting-sources= (empty) unless Options.SettingSources says otherwise. A .claude/settings.json committed to the repository cannot add permissions.allow rules or hooks that get around your permission callback. Project agents, skills and the repository's .mcp.json are not loaded either. Load agents and skills you trust through Options.PluginDirs. Add user only deliberately, with a dedicated Options.ConfigDir.
  • The permission mode is always passed. Without it the CLI takes defaultMode from the user's settings, which can be bypassPermissions.
  • Environment allowlist. Only PATH, HOME, USER, LOGNAME, SHELL, LANG, LC_*, TZ, TERM, TMPDIR, the XDG_* directories, proxy variables and CA-bundle variables are inherited. Your program's tokens and cloud keys do not reach the agent, where env in a Bash tool would show them. Options.Env adds variables (unfiltered, so anything secret there is visible to the agent). Options.InheritEnv passes everything. In both modes the variables a parent Claude Code session sets for its children are removed, so a session started from inside Claude Code does not attach to it.
  • One login per config directory. Options.ConfigDir sets CLAUDE_CONFIG_DIR, which is never inherited, so the login is always chosen explicitly.
  • Process cleanup. The CLI runs in its own process group. Close closes input, waits 5 seconds (Extra.ShutdownGrace), sends SIGTERM to the group, waits again and sends SIGKILL. When the CLI exits, the group is killed. The CLI starts its Bash shells and hooks with setsid, outside the group, so the driver also puts a random marker, CCGO_AGENT_SESSION=<id>, in the CLI's environment. On Linux it then kills every process whose environment carries that marker, including a dev server an agent left running. A process that clears its environment, or runs as another user, escapes. For full containment run each session in its own cgroup or container.
  • Values are passed as --flag=value, so a value that starts with - cannot be read as another flag.

Testing

go test -race ./...

The tests run against a fake CLI: the test binary runs itself again as a scripted claude (fake_test.go), so they need no login and no network.

TestRealCLI runs the installed CLI once (Haiku, a few turns, a permission prompt, a question and an in-process tool call; about one cent on your own login):

CCGO_CLAUDE_IT=1 go test -count=1 -run TestRealCLI -v .

CCGO_CLAUDE_BIN selects the binary, and CCGO_CLAUDE_ALLOW_UNTESTED=1 lets it run a version other than TestedVersion.

Licence

MIT, see LICENSE.

The protocol handling was ported from Anthropic's MIT-licensed Python Agent SDK. NOTICE has the attribution and that SDK's licence. "Claude" and "Claude Code" are trademarks of Anthropic, PBC.

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)
	}
}
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()
}
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
	}
}

Index

Examples

Constants

View Source
const AskUserQuestionTool = "AskUserQuestion"

AskUserQuestionTool is the CLI's built-in question tool.

View Source
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.

View Source
const Name = "claude-code"

Name is the driver name.

View Source
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.

View Source
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

func ParseVersion(out string) (string, error)

ParseVersion extracts the version from `claude --version` output.

func ResolveBinary

func ResolveBinary(path string) (string, error)

ResolveBinary finds the claude executable and resolves symlinks, so that the version checked is the version run even if the symlink moves.

func SessionFile

func SessionFile(configDir, cwd, sessionID string) string

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

type ControlError struct {
	Subtype string
	Message string
}

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.

func New

func New() *Driver

New returns a Driver that refuses untested CLI versions.

func (*Driver) Name

func (d *Driver) Name() string

Name implements agent.Driver.

func (*Driver) Start

func (d *Driver) Start(ctx context.Context, opts agent.Options) (agent.Session, error)

Start implements agent.Driver.

func (*Driver) StartSession

func (d *Driver) StartSession(ctx context.Context, opts agent.Options, extra Extra) (*Session, error)

StartSession starts claude with agent-neutral options plus Claude-specific extras. ctx bounds the whole session: cancelling it stops the CLI.

func (*Driver) Version

func (d *Driver) Version(ctx context.Context, binary string, env []string) (string, error)

Version runs `<binary> --version` and returns the parsed version. Results are cached per binary file (path, size and mtime).

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

type HookFunc func(ctx context.Context, in HookInput) (json.RawMessage, error)

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

func (s *Session) ClaudeInfo() Info

ClaudeInfo returns what is known about the running CLI.

func (*Session) Close

func (s *Session) Close() error

Close implements agent.Session: close stdin, then SIGTERM, then SIGKILL the process group, each after the shutdown grace period.

func (*Session) CloseInput

func (s *Session) CloseInput() error

CloseInput implements agent.Session.

func (*Session) Done

func (s *Session) Done() <-chan struct{}

Done is closed once the session has fully ended.

func (*Session) Events

func (s *Session) Events() <-chan agent.Event

Events implements agent.Session.

func (*Session) Info

func (s *Session) Info() agent.SessionInfo

Info implements agent.Session.

func (*Session) Interrupt

func (s *Session) Interrupt(ctx context.Context) error

Interrupt implements agent.Session.

func (*Session) Request

func (s *Session) Request(ctx context.Context, fields map[string]any) (json.RawMessage, error)

Request sends any control request (fields must include "subtype") and returns the CLI's reply payload.

func (*Session) Send

func (s *Session) Send(ctx context.Context, msg agent.UserMessage) error

Send implements agent.Session.

func (*Session) SessionID

func (s *Session) SessionID() string

SessionID implements agent.Session.

func (*Session) SetModel

func (s *Session) SetModel(ctx context.Context, model string) error

SetModel changes the model of the running session.

func (*Session) SetPermissionMode

func (s *Session) SetPermissionMode(ctx context.Context, mode string) error

SetPermissionMode changes the permission mode of the running session.

func (*Session) Wait

func (s *Session) Wait() error

Wait implements agent.Session.

type VersionError

type VersionError struct {
	Binary string
	Found  string
	Tested string
}

VersionError reports a CLI version this driver has not been tested with.

func (*VersionError) Error

func (e *VersionError) Error() string

Directories

Path Synopsis
Package agent is an agent-neutral interface for driving a coding agent CLI as a subprocess.
Package agent is an agent-neutral interface for driving a coding agent CLI as a subprocess.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL