codexsdk

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: GPL-3.0 Imports: 25 Imported by: 0

README

Codex Agent SDK Go

Go SDK for building agentic applications with the Codex CLI. It provides:

  • Query() for one-shot requests
  • QueryStream() for multi-message streaming input
  • Client for stateful multi-turn sessions

Requirements

Compatibility constants are defined in version.go:

  • Version
  • MinimumCLIVersion

Installation

go get github.com/wagiedev/codex-agent-sdk-go

Quick Start

One-shot query
package main

import (
	"context"
	"fmt"
	"time"

	codexsdk "github.com/wagiedev/codex-agent-sdk-go"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	for msg, err := range codexsdk.Query(ctx, "What is 2 + 2?") {
		if err != nil {
			fmt.Printf("query error: %v\n", err)
			return
		}

		switch m := msg.(type) {
		case *codexsdk.AssistantMessage:
			for _, block := range m.Content {
				if text, ok := block.(*codexsdk.TextBlock); ok {
					fmt.Println(text.Text)
				}
			}
		case *codexsdk.ResultMessage:
			if m.TotalCostUSD != nil {
			fmt.Printf("done in %dms, total cost: %.6f\n", m.DurationMs, *m.TotalCostUSD)
		}
		}
	}
}
Multi-turn client
client := codexsdk.NewClient()
defer func() {
	if err := client.Close(); err != nil {
		fmt.Fprintf(os.Stderr, "failed to close client: %v\n", err)
	}
}()

if err := client.Start(ctx,
	codexsdk.WithLogger(slog.Default()),
	codexsdk.WithPermissionMode("acceptEdits"),
); err != nil {
	return err
}

if err := client.Query(ctx, "What's the capital of France?"); err != nil {
	return err
}
for msg, err := range client.ReceiveResponse(ctx) {
	if err != nil {
		return err
	}
	_ = msg
}

if err := client.Query(ctx, "What's the population of that city?"); err != nil {
	return err
}
for msg, err := range client.ReceiveResponse(ctx) {
	if err != nil {
		return err
	}
	_ = msg
}
WithClient helper
err := codexsdk.WithClient(ctx, func(c codexsdk.Client) error {
	if err := c.Query(ctx, "Hello Codex"); err != nil {
		return err
	}

	for msg, err := range c.ReceiveResponse(ctx) {
		if err != nil {
			return err
		}
		_ = msg
	}

	return nil
},
	codexsdk.WithLogger(slog.Default()),
	codexsdk.WithPermissionMode("acceptEdits"),
)
if err != nil {
	return err
}

API Overview

Top-level entrypoints
API Description
Query(ctx, prompt, opts...) One-shot query returning iter.Seq2[Message, error]
QueryStream(ctx, messages, opts...) Streams StreamingMessage input and yields Message output
NewClient() Creates a stateful client for interactive sessions
WithClient(ctx, fn, opts...) Helper that runs Start() + callback + Close()
Client methods
Method Description
Start(ctx, opts...) Connect and initialize a session
StartWithPrompt(ctx, prompt, opts...) Start and immediately send first prompt
StartWithStream(ctx, messages, opts...) Start and immediately stream input messages
Query(ctx, prompt, sessionID...) Send a user turn
ReceiveResponse(ctx) Read messages until ResultMessage
ReceiveMessages(ctx) Continuous message stream
Interrupt(ctx) Stop in-flight generation
SetPermissionMode(ctx, mode) Change permission mode during a session
SetModel(ctx, model) Change model during a session
GetMCPStatus(ctx) Fetch live MCP server connection status
RewindFiles(ctx, userMessageID) Rewind tracked files to earlier turn
Close() Close and release resources
Message and content types
  • Message types: AssistantMessage, UserMessage, SystemMessage, ResultMessage
  • Content blocks: TextBlock, ThinkingBlock, ToolUseBlock, ToolResultBlock
Stream helpers
Helper Description
SingleMessage(content) Single-message input stream
MessagesFromSlice(msgs) Stream from []StreamingMessage
MessagesFromChannel(ch) Stream from channel
NewUserMessage(content) Convenience StreamingMessage constructor

Options and Backend Behavior

Options are backend-dependent. Unsupported combinations fail fast with ErrUnsupportedOption.

Backend selection
  • Query(...) auto-selects backend:
    • Uses exec when all selected options are natively supported there.
    • Falls back to app-server when needed for selected options.
  • QueryStream(...) uses app-server semantics unless you inject a custom WithTransport(...).
  • Client.Start(...) uses app-server transport semantics.
Common options
Option Purpose
WithLogger(logger) SDK logs (*slog.Logger)
WithModel("o4-mini") Model selection
WithCwd("/path") / WithCliPath("/path/codex") / WithEnv(...) Process/runtime setup
WithPermissionMode("acceptEdits") / WithSandbox("workspace-write") Permission/sandbox behavior
WithSystemPrompt("...") / WithSystemPromptPreset(...) System instructions
WithImages(...) / WithConfig(...) Codex-native CLI inputs/config
WithOutputSchema(json) Passes --output-schema
WithOutputFormat(map[string]any{...}) Structured output wrapper/schema for app-server flow
WithSkipVersionCheck(true) Skip CLI version check
WithInitializeTimeout(d) Initialize control request timeout
WithStderr(func(string){...}) Stderr callback
WithTransport(customTransport) Custom transport injection
Tool and MCP options
Option Purpose
WithHooks(hooks) Hook callbacks for tool/session events
WithCanUseTool(callback) Per-tool permission callback
WithTools(...) / WithAllowedTools(...) / WithDisallowedTools(...) Tool allow/block policy
WithPermissionPromptToolName("stdio") Permission prompt tool name
WithMCPServers(...) Register MCP servers
WithSDKTools(tools...) Register SDK-defined tools via NewTool (uses dynamicTools API)
Session and advanced options
Option Purpose
WithResume("session-id") / WithForkSession(true) Resume/fork sessions
WithContinueConversation(true) Continue prior conversation
WithEffort(codexsdk.EffortHigh) Extended thinking effort
WithAddDirs("/extra/path") Additional accessible directories
WithExtraArgs(map[string]*string{...}) Raw CLI flags
Important caveats
  • WithContinueConversation(true) requires WithResume(...) on app-server paths.
  • WithPermissionPromptToolName(...) only supports "stdio" on app-server paths.
  • WithAddDirs(...) and WithExtraArgs(...) are unsupported on app-server paths.
  • WithOutputSchema(...) and WithOutputFormat(...) serve different integration styles; choose one based on how you want structured output surfaced.

Error Handling

for msg, err := range codexsdk.Query(ctx, prompt) {
	if err != nil {
		var cliErr *codexsdk.CLINotFoundError
		if errors.As(err, &cliErr) {
			log.Fatalf("codex CLI not found: %v", cliErr.SearchedPaths)
		}

		var procErr *codexsdk.ProcessError
		if errors.As(err, &procErr) {
			log.Fatalf("codex failed (exit %d): %s", procErr.ExitCode, procErr.Stderr)
		}

		if errors.Is(err, codexsdk.ErrUnsupportedOption) {
			log.Fatalf("unsupported option combination: %v", err)
		}

		log.Fatal(err)
	}

	_ = msg
}
Error Description
CLINotFoundError Codex CLI binary not found
CLIConnectionError Connection/init failure
ProcessError CLI process exited with error
MessageParseError Failed to parse SDK message payload
CLIJSONDecodeError JSON decode failure from CLI output
ErrUnsupportedOption Option/backend combination is unsupported

Examples

Example Description
quick_start Basic Query() usage
client_multi_turn Stateful multi-turn client patterns
query_stream QueryStream() with streaming inputs
mcp_calculator In-process MCP server tools
mcp_status Querying MCP server status
tool_permission_callback WithCanUseTool permission callback
tools_option Tool allow/block configuration
structured_output Structured output patterns
extended_thinking WithEffort(...) usage
sessions Resume/fork session behavior
parallel_queries Concurrent one-shot queries
pipeline Multi-step orchestration flow
sdk_tools SDK-defined tools with WithSDKTools
error_handling Typed error handling

Run examples:

go run ./examples/quick_start
go run ./examples/client_multi_turn basic_streaming
go run ./examples/query_stream

Build and Test

go build ./...
go test ./...
go test -race ./...
go test -tags=integration ./... # requires Codex CLI + working runtime environment
golangci-lint run

Documentation

Overview

Package codexsdk provides a Go SDK for interacting with the Codex CLI agent.

This SDK enables Go applications to programmatically communicate with the Codex CLI tool. It supports both one-shot queries and interactive multi-turn conversations.

Basic Usage

For simple, one-shot queries, use the Query function:

ctx := context.Background()
for msg, err := range codexsdk.Query(ctx, "What is 2+2?",
    codexsdk.WithPermissionMode("acceptEdits"),
) {
    if err != nil {
        log.Fatal(err)
    }

    switch m := msg.(type) {
    case *codexsdk.AssistantMessage:
        for _, block := range m.Content {
            if text, ok := block.(*codexsdk.TextBlock); ok {
                fmt.Println(text.Text)
            }
        }
    case *codexsdk.ResultMessage:
        fmt.Printf("Completed in %dms\n", m.DurationMs)
    }
}

Interactive Sessions

For multi-turn conversations, use NewClient or the WithClient helper:

// Using WithClient for automatic lifecycle management
err := codexsdk.WithClient(ctx, func(c codexsdk.Client) error {
    if err := c.Query(ctx, "Hello Codex"); err != nil {
        return err
    }
    for msg, err := range c.ReceiveResponse(ctx) {
        if err != nil {
            return err
        }
        // process message...
    }
    return nil
},
    codexsdk.WithLogger(slog.Default()),
    codexsdk.WithPermissionMode("acceptEdits"),
)

// Or using NewClient directly for more control
client := codexsdk.NewClient()
defer func() {
    if err := client.Close(); err != nil {
        log.Printf("failed to close client: %v", err)
    }
}()

err := client.Start(ctx,
    codexsdk.WithLogger(slog.Default()),
    codexsdk.WithPermissionMode("acceptEdits"),
)

Logging

For detailed operation tracking, use WithLogger:

logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))
messages, err := codexsdk.Query(ctx, "Hello Codex",
    codexsdk.WithLogger(logger),
)

Error Handling

The SDK provides typed errors for different failure scenarios:

messages, err := codexsdk.Query(ctx, prompt, codexsdk.WithPermissionMode("acceptEdits"))
if err != nil {
    if cliErr, ok := errors.AsType[*codexsdk.CLINotFoundError](err); ok {
        log.Fatalf("Codex CLI not installed, searched: %v", cliErr.SearchedPaths)
    }
    if procErr, ok := errors.AsType[*codexsdk.ProcessError](err); ok {
        log.Fatalf("CLI process failed with exit code %d: %s", procErr.ExitCode, procErr.Stderr)
    }
    log.Fatal(err)
}

SDK Tools

Register custom tools that the agent can call back into your Go code using NewTool and WithSDKTools. Tools are sent as dynamicTools and dispatched via the item/tool/call RPC:

add := codexsdk.NewTool("add", "Add two numbers",
    map[string]any{
        "type": "object",
        "properties": map[string]any{
            "a": map[string]any{"type": "number"},
            "b": map[string]any{"type": "number"},
        },
        "required": []string{"a", "b"},
    },
    func(_ context.Context, input map[string]any) (map[string]any, error) {
        a, _ := input["a"].(float64)
        b, _ := input["b"].(float64)
        return map[string]any{"result": a + b}, nil
    },
)

for msg, err := range codexsdk.Query(ctx, "Add 5 and 3",
    codexsdk.WithSDKTools(add),
    codexsdk.WithPermissionMode("bypassPermissions"),
) {
    // ...
}

Requirements

This SDK requires the Codex CLI to be installed and available in your system PATH. You can specify a custom CLI path using the WithCliPath option.

Index

Constants

View Source
const (
	// SettingSourceUser loads from user-level settings.
	SettingSourceUser = config.SettingSourceUser
	// SettingSourceProject loads from project-level settings.
	SettingSourceProject = config.SettingSourceProject
	// SettingSourceLocal loads from local-level settings.
	SettingSourceLocal = config.SettingSourceLocal
)
View Source
const (
	// EffortLow uses minimal thinking.
	EffortLow = config.EffortLow
	// EffortMedium uses moderate thinking.
	EffortMedium = config.EffortMedium
	// EffortHigh uses deep thinking.
	EffortHigh = config.EffortHigh
	// EffortMax uses maximum thinking depth.
	EffortMax = config.EffortMax
)
View Source
const (
	// AssistantMessageErrorAuthFailed indicates authentication failure.
	AssistantMessageErrorAuthFailed = message.AssistantMessageErrorAuthFailed
	// AssistantMessageErrorBilling indicates a billing error.
	AssistantMessageErrorBilling = message.AssistantMessageErrorBilling
	// AssistantMessageErrorRateLimit indicates rate limiting.
	AssistantMessageErrorRateLimit = message.AssistantMessageErrorRateLimit
	// AssistantMessageErrorInvalidReq indicates an invalid request.
	AssistantMessageErrorInvalidReq = message.AssistantMessageErrorInvalidReq
	// AssistantMessageErrorServer indicates a server error.
	AssistantMessageErrorServer = message.AssistantMessageErrorServer
	// AssistantMessageErrorUnknown indicates an unknown error.
	AssistantMessageErrorUnknown = message.AssistantMessageErrorUnknown
)
View Source
const (
	// HookEventPreToolUse is triggered before a tool is used.
	HookEventPreToolUse = hook.EventPreToolUse
	// HookEventPostToolUse is triggered after a tool is used.
	HookEventPostToolUse = hook.EventPostToolUse
	// HookEventUserPromptSubmit is triggered when a user submits a prompt.
	HookEventUserPromptSubmit = hook.EventUserPromptSubmit
	// HookEventStop is triggered when a session stops.
	HookEventStop = hook.EventStop
	// HookEventSubagentStop is triggered when a subagent stops.
	HookEventSubagentStop = hook.EventSubagentStop
	// HookEventPreCompact is triggered before compaction.
	HookEventPreCompact = hook.EventPreCompact
	// HookEventPostToolUseFailure is triggered after a tool use fails.
	HookEventPostToolUseFailure = hook.EventPostToolUseFailure
	// HookEventNotification is triggered when a notification is sent.
	HookEventNotification = hook.EventNotification
	// HookEventSubagentStart is triggered when a subagent starts.
	HookEventSubagentStart = hook.EventSubagentStart
	// HookEventPermissionRequest is triggered when a permission is requested.
	HookEventPermissionRequest = hook.EventPermissionRequest
)
View Source
const (
	// PermissionModeDefault uses standard permission prompts.
	PermissionModeDefault = permission.ModeDefault
	// PermissionModeAcceptEdits automatically accepts file edits.
	PermissionModeAcceptEdits = permission.ModeAcceptEdits
	// PermissionModePlan enables plan mode for implementation planning.
	PermissionModePlan = permission.ModePlan
	// PermissionModeBypassPermissions bypasses all permission checks.
	PermissionModeBypassPermissions = permission.ModeBypassPermissions
)
View Source
const (
	// PermissionUpdateTypeAddRules adds new permission rules.
	PermissionUpdateTypeAddRules = permission.UpdateTypeAddRules
	// PermissionUpdateTypeReplaceRules replaces existing permission rules.
	PermissionUpdateTypeReplaceRules = permission.UpdateTypeReplaceRules
	// PermissionUpdateTypeRemoveRules removes permission rules.
	PermissionUpdateTypeRemoveRules = permission.UpdateTypeRemoveRules
	// PermissionUpdateTypeSetMode sets the permission mode.
	PermissionUpdateTypeSetMode = permission.UpdateTypeSetMode
	// PermissionUpdateTypeAddDirectories adds accessible directories.
	PermissionUpdateTypeAddDirectories = permission.UpdateTypeAddDirectories
	// PermissionUpdateTypeRemoveDirectories removes accessible directories.
	PermissionUpdateTypeRemoveDirectories = permission.UpdateTypeRemoveDirectories
)
View Source
const (
	// PermissionUpdateDestUserSettings stores in user-level settings.
	PermissionUpdateDestUserSettings = permission.UpdateDestUserSettings
	// PermissionUpdateDestProjectSettings stores in project-level settings.
	PermissionUpdateDestProjectSettings = permission.UpdateDestProjectSettings
	// PermissionUpdateDestLocalSettings stores in local-level settings.
	PermissionUpdateDestLocalSettings = permission.UpdateDestLocalSettings
	// PermissionUpdateDestSession stores in the current session only.
	PermissionUpdateDestSession = permission.UpdateDestSession
)
View Source
const (
	// PermissionBehaviorAllow automatically allows the operation.
	PermissionBehaviorAllow = permission.BehaviorAllow
	// PermissionBehaviorDeny automatically denies the operation.
	PermissionBehaviorDeny = permission.BehaviorDeny
	// PermissionBehaviorAsk prompts the user for permission.
	PermissionBehaviorAsk = permission.BehaviorAsk
)
View Source
const (
	// MCPServerTypeStdio uses stdio for communication.
	MCPServerTypeStdio = mcp.ServerTypeStdio
	// MCPServerTypeSSE uses Server-Sent Events.
	MCPServerTypeSSE = mcp.ServerTypeSSE
	// MCPServerTypeHTTP uses HTTP for communication.
	MCPServerTypeHTTP = mcp.ServerTypeHTTP
	// MCPServerTypeSDK uses the SDK interface.
	MCPServerTypeSDK = mcp.ServerTypeSDK
)
View Source
const MinimumCLIVersion = "0.103.0"

MinimumCLIVersion is the minimum required Codex CLI version.

View Source
const (
	// SdkBetaContext1M enables 1 million token context window.
	SdkBetaContext1M = config.BetaContext1M
)
View Source
const Version = "0.1.0"

Version is the SDK version.

Variables

View Source
var (
	// ErrClientNotConnected indicates the client is not connected.
	ErrClientNotConnected = errors.ErrClientNotConnected

	// ErrClientAlreadyConnected indicates the client is already connected.
	ErrClientAlreadyConnected = errors.ErrClientAlreadyConnected

	// ErrClientClosed indicates the client has been closed and cannot be reused.
	ErrClientClosed = errors.ErrClientClosed

	// ErrTransportNotConnected indicates the transport is not connected.
	ErrTransportNotConnected = errors.ErrTransportNotConnected

	// ErrRequestTimeout indicates a request timed out.
	ErrRequestTimeout = errors.ErrRequestTimeout

	// ErrUnsupportedOption indicates an option is not supported by the selected backend.
	ErrUnsupportedOption = errors.ErrUnsupportedOption

	// ErrUnsupportedControlRequest indicates a control request subtype is not supported.
	ErrUnsupportedControlRequest = errors.ErrUnsupportedControlRequest
)

Sentinel errors for commonly checked conditions.

View Source
var NewUserMessageContent = message.NewUserMessageContent

NewUserMessageContent creates UserMessageContent from a string.

View Source
var NewUserMessageContentBlocks = message.NewUserMessageContentBlocks

NewUserMessageContentBlocks creates UserMessageContent from blocks.

View Source
var WithAgentLogger = WithLogger

WithAgentLogger is an alias for WithLogger.

Deprecated: Use WithLogger instead.

Functions

func ErrorResult

func ErrorResult(message string) *mcp.CallToolResult

ErrorResult creates a CallToolResult indicating an error.

func ImageResult

func ImageResult(data []byte, mimeType string) *mcp.CallToolResult

ImageResult creates a CallToolResult with image content.

func MessagesFromChannel

func MessagesFromChannel(ch <-chan StreamingMessage) iter.Seq[StreamingMessage]

MessagesFromChannel creates a MessageStream from a channel. This is useful for dynamic message generation where messages are produced over time. The iterator completes when the channel is closed.

func MessagesFromSlice

func MessagesFromSlice(msgs []StreamingMessage) iter.Seq[StreamingMessage]

MessagesFromSlice creates a MessageStream from a slice of StreamingMessages. This is useful for sending a fixed set of messages in streaming mode.

func NewMcpTool

func NewMcpTool(name, description string, inputSchema *jsonschema.Schema) *mcp.Tool

NewMcpTool creates an mcp.Tool with the given parameters. This is useful when you need direct access to the MCP Tool type.

func NopLogger

func NopLogger() *slog.Logger

NopLogger returns a logger that discards all output. Use this when you want silent operation with no logging overhead.

func ParseArguments

func ParseArguments(req *mcp.CallToolRequest) (map[string]any, error)

ParseArguments unmarshals CallToolRequest arguments into a map. This is a convenience function for extracting tool input.

func Query

func Query(
	ctx context.Context,
	prompt string,
	opts ...Option,
) iter.Seq2[Message, error]

Query executes a one-shot query to the Codex CLI and returns an iterator of messages.

By default, logging is disabled. Use WithLogger to enable logging:

logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
for msg, err := range Query(ctx, "What is 2+2?",
    WithLogger(logger),
    WithPermissionMode("acceptEdits"),
) {
    if err != nil {
        log.Fatal(err)
    }
    // handle msg
}

The iterator yields messages as they arrive from the Codex CLI, including assistant responses, tool use, and a final result message. Any errors during setup or execution are yielded inline with messages, allowing callers to handle all error conditions.

Query supports hooks, CanUseTool callbacks, and SDK MCP servers through the protocol controller. When these options are configured, an initialization request is sent to the CLI before processing messages.

func QueryStream

func QueryStream(
	ctx context.Context,
	messages iter.Seq[StreamingMessage],
	opts ...Option,
) iter.Seq2[Message, error]

QueryStream executes a streaming query with multiple input messages.

The messages iterator yields StreamingMessage values that are sent to the Codex CLI via stdin in streaming mode.

Example usage:

messages := codexsdk.MessagesFromSlice([]codexsdk.StreamingMessage{
    codexsdk.NewUserMessage("Hello"),
    codexsdk.NewUserMessage("How are you?"),
})

for msg, err := range codexsdk.QueryStream(ctx, messages,
    codexsdk.WithPermissionMode("acceptEdits"),
) {
    if err != nil {
        log.Fatal(err)
    }
    // Handle messages
}

func SimpleSchema

func SimpleSchema(props map[string]string) *jsonschema.Schema

SimpleSchema creates a jsonschema.Schema from a simple type map.

Input format: {"a": "float64", "b": "string"}

Type mappings:

  • "string" -> {"type": "string"}
  • "int", "int64" -> {"type": "integer"}
  • "float64", "float" -> {"type": "number"}
  • "bool" -> {"type": "boolean"}
  • "[]string" -> {"type": "array", "items": {"type": "string"}}
  • "any", "object" -> {"type": "object"}

func SingleMessage

func SingleMessage(content string) iter.Seq[StreamingMessage]

SingleMessage creates a MessageStream with a single user message. This is a convenience function for simple string prompts in streaming mode.

func TextResult

func TextResult(text string) *mcp.CallToolResult

TextResult creates a CallToolResult with text content.

func WithClient

func WithClient(ctx context.Context, fn func(Client) error, opts ...Option) error

WithClient manages client lifecycle with automatic cleanup.

This helper creates a client, starts it with the provided options, executes the callback function, and ensures proper cleanup via Close() when done.

The callback receives a fully initialized Client that is ready for use. If the callback returns an error, it is returned to the caller. If Close() fails, a warning is logged but does not override the callback's error.

Example usage:

err := codexsdk.WithClient(ctx, func(c codexsdk.Client) error {
    if err := c.Query(ctx, "Hello"); err != nil {
        return err
    }
    for msg, err := range c.ReceiveResponse(ctx) {
        if err != nil {
            return err
        }
        // process message...
    }
    return nil
},
    codexsdk.WithLogger(log),
    codexsdk.WithPermissionMode("acceptEdits"),
)

Types

type AgentDefinition

type AgentDefinition = config.AgentDefinition

AgentDefinition defines a custom agent configuration.

type AssistantMessage

type AssistantMessage = message.AssistantMessage

AssistantMessage represents a message from the agent.

type AssistantMessageError

type AssistantMessageError = message.AssistantMessageError

AssistantMessageError represents error types from the assistant.

type AsyncHookJSONOutput

type AsyncHookJSONOutput = hook.AsyncJSONOutput

AsyncHookJSONOutput represents an async hook output.

type BaseHookInput

type BaseHookInput = hook.BaseInput

BaseHookInput contains common fields for all hook inputs.

type CLIConnectionError

type CLIConnectionError = errors.CLIConnectionError

CLIConnectionError indicates failure to connect to the CLI.

type CLIJSONDecodeError

type CLIJSONDecodeError = errors.CLIJSONDecodeError

CLIJSONDecodeError indicates JSON parsing failed for CLI output.

type CLINotFoundError

type CLINotFoundError = errors.CLINotFoundError

CLINotFoundError indicates the Codex CLI binary was not found.

type CallToolRequest

type CallToolRequest = mcp.CallToolRequest

CallToolRequest is the request passed to tool handlers.

type CallToolResult

type CallToolResult = mcp.CallToolResult

CallToolResult is the server's response to a tool call. Use TextResult, ErrorResult, or ImageResult helpers to create results.

type Client

type Client interface {
	// Start establishes a connection to the Codex CLI.
	// Must be called before any other methods.
	// Returns CLINotFoundError if CLI not found, CLIConnectionError on failure.
	Start(ctx context.Context, opts ...Option) error

	// StartWithPrompt establishes a connection and immediately sends an initial prompt.
	// Equivalent to calling Start() followed by Query(ctx, prompt).
	// The prompt is sent to the "default" session.
	// Returns CLINotFoundError if CLI not found, CLIConnectionError on failure.
	StartWithPrompt(ctx context.Context, prompt string, opts ...Option) error

	// StartWithStream establishes a connection and streams initial messages.
	// Messages are consumed from the iterator and sent via stdin.
	// The iterator runs in a separate goroutine; use context cancellation to abort.
	// EndInput is called automatically when the iterator completes.
	// Returns CLINotFoundError if CLI not found, CLIConnectionError on failure.
	StartWithStream(ctx context.Context, messages iter.Seq[StreamingMessage], opts ...Option) error

	// Query sends a user prompt to the agent.
	// Returns immediately after sending; use ReceiveMessages() or ReceiveResponse() to get responses.
	// Optional sessionID defaults to "default" for multi-session support.
	Query(ctx context.Context, prompt string, sessionID ...string) error

	// ReceiveMessages returns an iterator that yields messages indefinitely.
	// Messages are yielded as they arrive until EOF, an error occurs, or context is cancelled.
	// Unlike ReceiveResponse, this iterator does not stop at ResultMessage.
	// Use iter.Pull2 if you need pull-based iteration instead of range.
	ReceiveMessages(ctx context.Context) iter.Seq2[Message, error]

	// ReceiveResponse returns an iterator that yields messages until a ResultMessage is received.
	// Messages are yielded as they arrive for streaming consumption.
	// The iterator stops after yielding the ResultMessage.
	// Use iter.Pull2 if you need pull-based iteration instead of range.
	// To collect all messages into a slice, use slices.Collect or a simple loop.
	ReceiveResponse(ctx context.Context) iter.Seq2[Message, error]

	// Interrupt sends an interrupt signal to stop the agent's current processing.
	Interrupt(ctx context.Context) error

	// SetPermissionMode changes the permission mode during conversation.
	// Valid modes: "default", "acceptEdits", "plan", "bypassPermissions"
	SetPermissionMode(ctx context.Context, mode string) error

	// SetModel changes the AI model during conversation.
	// Pass nil to use the default model.
	SetModel(ctx context.Context, model *string) error

	// GetServerInfo returns server initialization info including available commands.
	// Returns nil if not connected or not in streaming mode.
	GetServerInfo() map[string]any

	// GetMCPStatus queries the CLI for live MCP server connection status.
	// Returns the status of all configured MCP servers.
	GetMCPStatus(ctx context.Context) (*MCPStatus, error)

	// ListModels queries the CLI for available models.
	// Returns the list of models the CLI can use.
	ListModels(ctx context.Context) ([]ModelInfo, error)

	// RewindFiles rewinds tracked files to their state at a specific user message.
	// The userMessageID should be the ID of a previous user message in the conversation.
	RewindFiles(ctx context.Context, userMessageID string) error

	// Close terminates the session and cleans up resources.
	// After Close(), the client cannot be reused. Safe to call multiple times.
	Close() error
}

Client provides an interactive, stateful interface for multi-turn conversations.

Unlike the one-shot Query() function, Client maintains session state across multiple exchanges. It supports interruption and bidirectional communication with the Codex CLI.

Lifecycle: Clients are single-use. After Close(), create a new client with NewClient().

Example usage:

client := NewClient()
defer func() {
    if err := client.Close(); err != nil {
        log.Printf("failed to close client: %v", err)
    }
}()

err := client.Start(ctx,
    WithLogger(slog.Default()),
    WithPermissionMode("acceptEdits"),
)
if err != nil {
    log.Fatal(err)
}

// Send a query
err = client.Query(ctx, "What is 2+2?")
if err != nil {
    log.Fatal(err)
}

// Receive all messages for this response (stops at ResultMessage)
for msg, err := range client.ReceiveResponse(ctx) {
    if err != nil {
        log.Fatal(err)
    }
    // Process message...
}

// Or receive messages indefinitely (for continuous streaming)
for msg, err := range client.ReceiveMessages(ctx) {
    if err != nil {
        break
    }
    // Process message...
}

func NewClient

func NewClient() Client

NewClient creates a new interactive client.

Call Start() with options to begin a session:

client := NewClient()
err := client.Start(ctx,
    WithLogger(slog.Default()),
    WithPermissionMode("acceptEdits"),
)

type CodexAgentOptions

type CodexAgentOptions = config.Options

CodexAgentOptions configures the behavior of the Codex agent.

type CodexSDKError

type CodexSDKError = errors.CodexSDKError

CodexSDKError is the base interface for all SDK errors.

type ContentBlock

type ContentBlock = message.ContentBlock

ContentBlock represents a block of content within a message.

type Effort

type Effort = config.Effort

Effort controls thinking depth.

type HookCallback

type HookCallback = hook.Callback

HookCallback is the function signature for hook callbacks.

type HookContext

type HookContext = hook.Context

HookContext provides context for hook execution.

type HookEvent

type HookEvent = hook.Event

HookEvent represents the type of event that triggers a hook.

type HookInput

type HookInput = hook.Input

HookInput is the interface for all hook input types.

type HookJSONOutput

type HookJSONOutput = hook.JSONOutput

HookJSONOutput is the interface for hook output types.

type HookMatcher

type HookMatcher = hook.Matcher

HookMatcher configures which tools/events a hook applies to.

type HookSpecificOutput

type HookSpecificOutput = hook.SpecificOutput

HookSpecificOutput is the interface for hook-specific outputs.

type MCPHTTPServerConfig

type MCPHTTPServerConfig = mcp.HTTPServerConfig

MCPHTTPServerConfig configures an HTTP-based MCP server.

type MCPSSEServerConfig

type MCPSSEServerConfig = mcp.SSEServerConfig

MCPSSEServerConfig configures a Server-Sent Events MCP server.

type MCPSdkServerConfig

type MCPSdkServerConfig = mcp.SdkServerConfig

MCPSdkServerConfig configures an SDK-provided MCP server.

func CreateSdkMcpServer

func CreateSdkMcpServer(name, version string, tools ...*SdkMcpTool) *MCPSdkServerConfig

CreateSdkMcpServer creates an in-process MCP server configuration with SdkMcpTool tools.

The returned config can be used directly in CodexAgentOptions.MCPServers:

addTool := codexsdk.NewSdkMcpTool("add", "Add two numbers",
    codexsdk.SimpleSchema(map[string]string{"a": "float64", "b": "float64"}),
    func(ctx context.Context, req *codexsdk.CallToolRequest) (*codexsdk.CallToolResult, error) {
        args, _ := codexsdk.ParseArguments(req)
        a, b := args["a"].(float64), args["b"].(float64)
        return codexsdk.TextResult(fmt.Sprintf("Result: %v", a+b)), nil
    },
)

calculator := codexsdk.CreateSdkMcpServer("calculator", "1.0.0", addTool)

options := &codexsdk.CodexAgentOptions{
    MCPServers: map[string]codexsdk.MCPServerConfig{
        "calculator": calculator,
    },
    AllowedTools: []string{"mcp__calculator__add"},
}

type MCPServerConfig

type MCPServerConfig = mcp.ServerConfig

MCPServerConfig is the interface for MCP server configurations.

type MCPServerStatus

type MCPServerStatus = mcp.ServerStatus

MCPServerStatus represents the connection status of a single MCP server.

type MCPServerType

type MCPServerType = mcp.ServerType

MCPServerType represents the type of MCP server.

type MCPStatus

type MCPStatus = mcp.Status

MCPStatus represents the connection status of all configured MCP servers.

type MCPStdioServerConfig

type MCPStdioServerConfig = mcp.StdioServerConfig

MCPStdioServerConfig configures a stdio-based MCP server.

type McpAudioContent

type McpAudioContent = mcp.AudioContent

McpAudioContent represents audio content in a tool result.

type McpContent

type McpContent = mcp.Content

McpContent is the interface for content types in tool results.

type McpImageContent

type McpImageContent = mcp.ImageContent

McpImageContent represents image content in a tool result.

type McpTextContent

type McpTextContent = mcp.TextContent

McpTextContent represents text content in a tool result.

type McpTool

type McpTool = mcp.Tool

McpTool represents an MCP tool definition from the official SDK.

type McpToolAnnotations

type McpToolAnnotations = mcp.ToolAnnotations

McpToolAnnotations describes optional hints about tool behavior. Fields include ReadOnlyHint, DestructiveHint, IdempotentHint, OpenWorldHint, and Title.

type McpToolHandler

type McpToolHandler = mcp.ToolHandler

McpToolHandler is the function signature for low-level tool handlers.

type Message

type Message = message.Message

Message represents any message in the conversation.

type MessageParseError

type MessageParseError = errors.MessageParseError

MessageParseError indicates message parsing failed.

type MessageStream

type MessageStream = iter.Seq[StreamingMessage]

MessageStream is an iterator that yields streaming messages.

type ModelInfo

type ModelInfo = model.Info

ModelInfo describes a model available from the Codex CLI.

func ListModels

func ListModels(ctx context.Context, opts ...Option) ([]ModelInfo, error)

ListModels spawns a temporary Codex CLI session to discover available models. The session is automatically closed after the model list is retrieved.

type ModelListResponse

type ModelListResponse = model.ListResponse

ModelListResponse is the response payload from the model/list RPC method.

type NotificationHookInput

type NotificationHookInput = hook.NotificationInput

NotificationHookInput is the input for Notification hooks.

type NotificationHookSpecificOutput

type NotificationHookSpecificOutput = hook.NotificationSpecificOutput

NotificationHookSpecificOutput is the hook-specific output for Notification.

type Option

type Option func(*CodexAgentOptions)

Option configures CodexAgentOptions using the functional options pattern.

func WithAddDirs

func WithAddDirs(dirs ...string) Option

WithAddDirs adds additional directories to make accessible.

func WithAllowedTools

func WithAllowedTools(tools ...string) Option

WithAllowedTools sets pre-approved tools that can be used without prompting.

func WithCanUseTool

func WithCanUseTool(callback ToolPermissionCallback) Option

WithCanUseTool sets a callback for permission checking before each tool use. Permission callback invoked when CLI sends can_use_tool requests via protocol.

func WithCliPath

func WithCliPath(path string) Option

WithCliPath sets the explicit path to the codex CLI binary. If not set, the CLI will be searched in PATH.

func WithConfig

func WithConfig(cfg map[string]string) Option

WithConfig provides key=value pairs for Codex CLI configuration (passed via -c flags).

func WithContinueConversation

func WithContinueConversation(cont bool) Option

WithContinueConversation indicates whether to continue an existing conversation.

func WithCwd

func WithCwd(cwd string) Option

WithCwd sets the working directory for the CLI process.

func WithDisallowedTools

func WithDisallowedTools(tools ...string) Option

WithDisallowedTools sets tools that are explicitly blocked.

func WithEffort

func WithEffort(effort config.Effort) Option

WithEffort sets the thinking effort level. Passed to CLI via initialization; support depends on Codex CLI version.

func WithEnv

func WithEnv(env map[string]string) Option

WithEnv provides additional environment variables for the CLI process.

func WithExtraArgs

func WithExtraArgs(args map[string]*string) Option

WithExtraArgs provides arbitrary CLI flags to pass to the CLI. If the value is nil, the flag is passed without a value (boolean flag).

func WithForkSession

func WithForkSession(fork bool) Option

WithForkSession indicates whether to fork the resumed session to a new ID.

func WithHooks

func WithHooks(hooks map[HookEvent][]*HookMatcher) Option

WithHooks configures event hooks for tool interception. Hooks are registered via protocol session and dispatched when Codex CLI sends hooks/callback requests.

func WithImages

func WithImages(images ...string) Option

WithImages provides file paths for image inputs (passed via -i flags).

func WithInitializeTimeout

func WithInitializeTimeout(timeout time.Duration) Option

WithInitializeTimeout sets the timeout for the initialize control request.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger for debug output. If not set, logging is disabled (silent operation).

func WithMCPServers

func WithMCPServers(servers map[string]MCPServerConfig) Option

WithMCPServers configures external MCP servers to connect to. Map key is the server name, value is the server configuration.

func WithModel

func WithModel(model string) Option

WithModel specifies which model to use.

func WithOutputFormat

func WithOutputFormat(format map[string]any) Option

WithOutputFormat specifies a JSON schema for structured output.

The canonical format uses a wrapper object:

codexsdk.WithOutputFormat(map[string]any{
    "type": "json_schema",
    "schema": map[string]any{
        "type":       "object",
        "properties": map[string]any{...},
        "required":   []string{...},
    },
})

Raw JSON schemas (without the wrapper) are also accepted and auto-wrapped:

codexsdk.WithOutputFormat(map[string]any{
    "type":       "object",
    "properties": map[string]any{...},
    "required":   []string{...},
})

func WithOutputSchema

func WithOutputSchema(schema string) Option

WithOutputSchema sets the --output-schema flag for structured Codex output.

func WithPermissionMode

func WithPermissionMode(mode string) Option

WithPermissionMode controls how permissions are handled. For Codex, maps to sandbox modes: "default" -> full-auto, "acceptEdits" -> workspace-write, "bypassPermissions" -> danger-full-access.

func WithPermissionPromptToolName

func WithPermissionPromptToolName(name string) Option

WithPermissionPromptToolName specifies the tool name to use for permission prompts.

func WithResume

func WithResume(sessionID string) Option

WithResume sets a session ID to resume from.

func WithSDKTools

func WithSDKTools(tools ...Tool) Option

WithSDKTools registers high-level Tool instances as dynamic tools. Tools are serialized in the thread/start payload as dynamicTools and called back via item/tool/call RPC using plain tool names. Each tool is automatically added to AllowedTools.

func WithSandbox

func WithSandbox(sandbox string) Option

WithSandbox sets the Codex sandbox mode directly. Valid values: "read-only", "workspace-write", "danger-full-access".

func WithSkipVersionCheck

func WithSkipVersionCheck(skip bool) Option

WithSkipVersionCheck disables CLI version validation during discovery.

func WithStderr

func WithStderr(handler func(string)) Option

WithStderr sets a callback function for handling stderr output.

func WithSystemPrompt

func WithSystemPrompt(prompt string) Option

WithSystemPrompt sets the system message to send to the agent.

func WithSystemPromptPreset

func WithSystemPromptPreset(preset *SystemPromptPreset) Option

WithSystemPromptPreset sets a preset system prompt configuration. If set, this takes precedence over WithSystemPrompt.

func WithTools

func WithTools(tools config.ToolsConfig) Option

WithTools specifies which tools are available. Accepts ToolsList (tool names) or *ToolsPreset.

func WithTransport

func WithTransport(transport config.Transport) Option

WithTransport injects a custom transport implementation. The transport must implement the Transport interface.

type PermissionBehavior

type PermissionBehavior = permission.Behavior

PermissionBehavior represents the permission behavior for a rule.

type PermissionMode

type PermissionMode = permission.Mode

PermissionMode represents different permission handling modes.

type PermissionRequestHookInput

type PermissionRequestHookInput = hook.PermissionRequestInput

PermissionRequestHookInput is the input for PermissionRequest hooks.

type PermissionRequestHookSpecificOutput

type PermissionRequestHookSpecificOutput = hook.PermissionRequestSpecificOutput

PermissionRequestHookSpecificOutput is the hook-specific output for PermissionRequest.

type PermissionResult

type PermissionResult = permission.Result

PermissionResult is the interface for permission decision results.

type PermissionResultAllow

type PermissionResultAllow = permission.ResultAllow

PermissionResultAllow represents an allow decision.

type PermissionResultDeny

type PermissionResultDeny = permission.ResultDeny

PermissionResultDeny represents a deny decision.

type PermissionRuleValue

type PermissionRuleValue = permission.RuleValue

PermissionRuleValue represents a permission rule.

type PermissionUpdate

type PermissionUpdate = permission.Update

PermissionUpdate represents a permission update request.

type PermissionUpdateDestination

type PermissionUpdateDestination = permission.UpdateDestination

PermissionUpdateDestination represents where permission updates are stored.

type PermissionUpdateType

type PermissionUpdateType = permission.UpdateType

PermissionUpdateType represents the type of permission update.

type PostToolUseFailureHookInput

type PostToolUseFailureHookInput = hook.PostToolUseFailureInput

PostToolUseFailureHookInput is the input for PostToolUseFailure hooks.

type PostToolUseFailureHookSpecificOutput

type PostToolUseFailureHookSpecificOutput = hook.PostToolUseFailureSpecificOutput

PostToolUseFailureHookSpecificOutput is the hook-specific output for PostToolUseFailure.

type PostToolUseHookInput

type PostToolUseHookInput = hook.PostToolUseInput

PostToolUseHookInput is the input for PostToolUse hooks.

type PostToolUseHookSpecificOutput

type PostToolUseHookSpecificOutput = hook.PostToolUseSpecificOutput

PostToolUseHookSpecificOutput is the hook-specific output for PostToolUse.

type PreCompactHookInput

type PreCompactHookInput = hook.PreCompactInput

PreCompactHookInput is the input for PreCompact hooks.

type PreToolUseHookInput

type PreToolUseHookInput = hook.PreToolUseInput

PreToolUseHookInput is the input for PreToolUse hooks.

type PreToolUseHookSpecificOutput

type PreToolUseHookSpecificOutput = hook.PreToolUseSpecificOutput

PreToolUseHookSpecificOutput is the hook-specific output for PreToolUse.

type ProcessError

type ProcessError = errors.ProcessError

ProcessError indicates the CLI process failed.

type ReasoningEffortOption

type ReasoningEffortOption = model.ReasoningEffortOption

ReasoningEffortOption describes a selectable reasoning effort level.

type ResultMessage

type ResultMessage = message.ResultMessage

ResultMessage represents the final result of a query.

type SandboxIgnoreViolations

type SandboxIgnoreViolations = sandbox.IgnoreViolations

SandboxIgnoreViolations configures which violations to ignore.

type SandboxNetworkConfig

type SandboxNetworkConfig = sandbox.NetworkConfig

SandboxNetworkConfig configures network access for the sandbox.

type SandboxSettings

type SandboxSettings = sandbox.Settings

SandboxSettings configures CLI sandbox behavior.

type Schema

type Schema = jsonschema.Schema

Schema is a JSON Schema object for tool input validation.

type SdkBeta

type SdkBeta = config.Beta

SdkBeta represents a beta feature flag for the SDK.

type SdkMcpServerInstance

type SdkMcpServerInstance = mcp.ServerInstance

SdkMcpServerInstance is the interface that SDK MCP servers must implement.

type SdkMcpTool

type SdkMcpTool struct {
	ToolName        string
	ToolDescription string
	ToolSchema      *jsonschema.Schema
	ToolHandler     SdkMcpToolHandler
	ToolAnnotations *mcp.ToolAnnotations
}

SdkMcpTool represents a tool created with NewSdkMcpTool.

func NewSdkMcpTool

func NewSdkMcpTool(
	name, description string,
	inputSchema *jsonschema.Schema,
	handler SdkMcpToolHandler,
	opts ...SdkMcpToolOption,
) *SdkMcpTool

NewSdkMcpTool creates an SdkMcpTool with optional configuration.

The inputSchema should be a *jsonschema.Schema. Use SimpleSchema for convenience or create a full Schema struct for more control.

Use WithAnnotations to set MCP tool annotations (hints about tool behavior).

Example with SimpleSchema:

addTool := codexsdk.NewSdkMcpTool("add", "Add two numbers",
    codexsdk.SimpleSchema(map[string]string{"a": "float64", "b": "float64"}),
    func(ctx context.Context, req *codexsdk.CallToolRequest) (*codexsdk.CallToolResult, error) {
        args, _ := codexsdk.ParseArguments(req)
        a, b := args["a"].(float64), args["b"].(float64)
        return codexsdk.TextResult(fmt.Sprintf("Result: %v", a+b)), nil
    },
    codexsdk.WithAnnotations(&codexsdk.McpToolAnnotations{
        ReadOnlyHint: true,
    }),
)

func (*SdkMcpTool) Annotations

func (t *SdkMcpTool) Annotations() *mcp.ToolAnnotations

Annotations returns the tool annotations, or nil if not set.

func (*SdkMcpTool) Description

func (t *SdkMcpTool) Description() string

Description returns the tool description.

func (*SdkMcpTool) Handler

func (t *SdkMcpTool) Handler() SdkMcpToolHandler

Handler returns the tool handler function.

func (*SdkMcpTool) InputSchema

func (t *SdkMcpTool) InputSchema() *jsonschema.Schema

InputSchema returns the JSON Schema for the tool input.

func (*SdkMcpTool) Name

func (t *SdkMcpTool) Name() string

Name returns the tool name.

type SdkMcpToolHandler

type SdkMcpToolHandler = mcp.ToolHandler

SdkMcpToolHandler is the function signature for SdkMcpTool handlers. It receives the context and request, and returns the result.

Use ParseArguments to extract input as map[string]any from the request. Use TextResult, ErrorResult, or ImageResult helpers to create results.

Example:

func(ctx context.Context, req *codexsdk.CallToolRequest) (*codexsdk.CallToolResult, error) {
    args, err := codexsdk.ParseArguments(req)
    if err != nil {
        return codexsdk.ErrorResult(err.Error()), nil
    }
    a := args["a"].(float64)
    return codexsdk.TextResult(fmt.Sprintf("Result: %v", a)), nil
}

type SdkMcpToolOption

type SdkMcpToolOption func(*SdkMcpTool)

SdkMcpToolOption configures an SdkMcpTool during construction.

func WithAnnotations

func WithAnnotations(annotations *mcp.ToolAnnotations) SdkMcpToolOption

WithAnnotations sets MCP tool annotations (hints about tool behavior). Annotations describe properties like whether a tool is read-only, destructive, idempotent, or operates in an open world.

type SdkPluginConfig

type SdkPluginConfig = config.PluginConfig

SdkPluginConfig configures a plugin to load.

type SettingSource

type SettingSource = config.SettingSource

SettingSource represents where settings should be loaded from.

type StopHookInput

type StopHookInput = hook.StopInput

StopHookInput is the input for Stop hooks.

type StreamEvent

type StreamEvent = message.StreamEvent

StreamEvent represents a streaming event from the API.

type StreamingMessage

type StreamingMessage = message.StreamingMessage

StreamingMessage represents a message sent in streaming mode.

func NewUserMessage

func NewUserMessage(content string) StreamingMessage

NewUserMessage creates a StreamingMessage with type "user". This is a convenience constructor for creating user messages.

type StreamingMessageContent

type StreamingMessageContent = message.StreamingMessageContent

StreamingMessageContent represents the content of a streaming message.

type SubagentStartHookInput

type SubagentStartHookInput = hook.SubagentStartInput

SubagentStartHookInput is the input for SubagentStart hooks.

type SubagentStartHookSpecificOutput

type SubagentStartHookSpecificOutput = hook.SubagentStartSpecificOutput

SubagentStartHookSpecificOutput is the hook-specific output for SubagentStart.

type SubagentStopHookInput

type SubagentStopHookInput = hook.SubagentStopInput

SubagentStopHookInput is the input for SubagentStop hooks.

type SyncHookJSONOutput

type SyncHookJSONOutput = hook.SyncJSONOutput

SyncHookJSONOutput represents a sync hook output.

type SystemMessage

type SystemMessage = message.SystemMessage

SystemMessage represents a system message.

type SystemPromptPreset

type SystemPromptPreset = config.SystemPromptPreset

SystemPromptPreset defines a system prompt preset configuration.

type TextBlock

type TextBlock = message.TextBlock

TextBlock contains plain text content.

type ThinkingBlock

type ThinkingBlock = message.ThinkingBlock

ThinkingBlock contains the agent's thinking process.

type ThinkingConfig

type ThinkingConfig = config.ThinkingConfig

ThinkingConfig controls extended thinking behavior.

type ThinkingConfigAdaptive

type ThinkingConfigAdaptive = config.ThinkingConfigAdaptive

ThinkingConfigAdaptive enables adaptive thinking mode.

type ThinkingConfigDisabled

type ThinkingConfigDisabled = config.ThinkingConfigDisabled

ThinkingConfigDisabled disables extended thinking.

type ThinkingConfigEnabled

type ThinkingConfigEnabled = config.ThinkingConfigEnabled

ThinkingConfigEnabled enables thinking with a specific token budget.

type Tool

type Tool interface {
	// Name returns the unique identifier for this tool.
	Name() string

	// Description returns a human-readable description for the agent.
	Description() string

	// InputSchema returns a JSON schema describing expected input.
	// The schema should follow JSON Schema Draft 7 specification.
	InputSchema() map[string]any

	// Execute runs the tool with the provided input.
	// The input will be validated against InputSchema before execution.
	Execute(ctx context.Context, input map[string]any) (map[string]any, error)
}

Tool represents a custom tool that the Codex agent can invoke.

Tools allow users to extend the agent's capabilities with domain-specific functionality. When registered, the agent can discover and execute these tools during a session.

Example:

tool := codexsdk.NewTool(
    "calculator",
    "Performs basic arithmetic operations",
    map[string]any{
        "type": "object",
        "properties": map[string]any{
            "operation": map[string]any{
                "type": "string",
                "enum": []string{"add", "subtract", "multiply", "divide"},
            },
            "a": map[string]any{"type": "number"},
            "b": map[string]any{"type": "number"},
        },
        "required": []string{"operation", "a", "b"},
    },
    func(ctx context.Context, input map[string]any) (map[string]any, error) {
        op := input["operation"].(string)
        a := input["a"].(float64)
        b := input["b"].(float64)

        var result float64
        switch op {
        case "add":
            result = a + b
        case "subtract":
            result = a - b
        case "multiply":
            result = a * b
        case "divide":
            if b == 0 {
                return nil, fmt.Errorf("division by zero")
            }
            result = a / b
        }

        return map[string]any{"result": result}, nil
    },
)

func NewTool

func NewTool(name, description string, schema map[string]any, fn ToolFunc) Tool

NewTool creates a Tool from a function.

This is a convenience constructor for creating tools without implementing the full Tool interface.

Parameters:

  • name: Unique identifier for the tool (e.g., "calculator", "search_database")
  • description: Human-readable description of what the tool does
  • schema: JSON Schema defining the expected input structure
  • fn: Function that executes the tool logic

type ToolFunc

type ToolFunc func(ctx context.Context, input map[string]any) (map[string]any, error)

ToolFunc is a function-based tool implementation.

type ToolPermissionCallback

type ToolPermissionCallback = permission.Callback

ToolPermissionCallback is called before each tool use for permission checking.

type ToolPermissionContext

type ToolPermissionContext = permission.Context

ToolPermissionContext provides context for tool permission callbacks.

type ToolResultBlock

type ToolResultBlock = message.ToolResultBlock

ToolResultBlock contains the result of a tool execution.

type ToolUseBlock

type ToolUseBlock = message.ToolUseBlock

ToolUseBlock represents the agent using a tool.

type ToolsConfig

type ToolsConfig = config.ToolsConfig

ToolsConfig is an interface for configuring available tools. It represents either a list of tool names or a preset configuration.

type ToolsList

type ToolsList = config.ToolsList

ToolsList is a list of tool names to make available.

type ToolsPreset

type ToolsPreset = config.ToolsPreset

ToolsPreset represents a preset configuration for available tools.

type Transport

type Transport = config.Transport

Transport defines the interface for Codex CLI communication. Implement this to provide custom transports for testing, mocking, or alternative communication methods (e.g., remote connections).

The default implementation is CLITransport which spawns a subprocess. Custom transports can be injected via CodexAgentOptions.Transport.

type Usage

type Usage = message.Usage

Usage contains token usage information.

type UserMessage

type UserMessage = message.UserMessage

UserMessage represents a message from the user.

type UserMessageContent

type UserMessageContent = message.UserMessageContent

UserMessageContent represents content that can be either a string or []ContentBlock.

type UserPromptSubmitHookInput

type UserPromptSubmitHookInput = hook.UserPromptSubmitInput

UserPromptSubmitHookInput is the input for UserPromptSubmit hooks.

type UserPromptSubmitHookSpecificOutput

type UserPromptSubmitHookSpecificOutput = hook.UserPromptSubmitSpecificOutput

UserPromptSubmitHookSpecificOutput is the hook-specific output for UserPromptSubmit.

Directories

Path Synopsis
examples
cancellation command
custom_logger command
Package main demonstrates how to use a custom logging library (logrus) with the Codex SDK.
Package main demonstrates how to use a custom logging library (logrus) with the Codex SDK.
error_handling command
max_budget_usd command
mcp_calculator command
Package main demonstrates how to create calculator tools using MCP servers.
Package main demonstrates how to create calculator tools using MCP servers.
mcp_status command
Package main demonstrates querying MCP server connection status.
Package main demonstrates querying MCP server connection status.
memory_tool command
Package main demonstrates a filesystem-backed memory tool for agent state persistence.
Package main demonstrates a filesystem-backed memory tool for agent state persistence.
pipeline command
query_stream command
quick_start command
sdk_tools command
Package main demonstrates the high-level Tool API with WithSDKTools.
Package main demonstrates the high-level Tool API with WithSDKTools.
sessions command
stderr_callback command
system_prompt command
tools_option command
internal
cli
Package cli provides CLI discovery, version validation, and command building for the Codex CLI binary.
Package cli provides CLI discovery, version validation, and command building for the Codex CLI binary.
client
Package client implements the interactive Client for multi-turn conversations with the agent.
Package client implements the interactive Client for multi-turn conversations with the agent.
config
Package config provides configuration types for the Codex SDK.
Package config provides configuration types for the Codex SDK.
errors
Package errors defines error types for the Codex SDK.
Package errors defines error types for the Codex SDK.
hook
Package hook provides hook types for intercepting CLI events.
Package hook provides hook types for intercepting CLI events.
mcp
Package mcp implements an in-process Model Context Protocol server.
Package mcp implements an in-process Model Context Protocol server.
message
Package message provides message and content block types for Codex conversations.
Package message provides message and content block types for Codex conversations.
model
Package model defines types for Codex CLI model discovery.
Package model defines types for Codex CLI model discovery.
permission
Package permission provides permission handling types for the Codex CLI.
Package permission provides permission handling types for the Codex CLI.
protocol
Package protocol implements bidirectional control message handling for the Codex CLI.
Package protocol implements bidirectional control message handling for the Codex CLI.
sandbox
Package sandbox provides sandbox configuration types for the Codex CLI.
Package sandbox provides sandbox configuration types for the Codex CLI.
subprocess
Package subprocess provides subprocess-based transport for the Codex CLI.
Package subprocess provides subprocess-based transport for the Codex CLI.

Jump to

Keyboard shortcuts

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