Documentation
¶
Overview ¶
Package claudesdk provides a Go SDK for interacting with the Claude CLI agent.
This SDK enables Go applications to programmatically communicate with Claude through the official Claude 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 claudesdk.Query(ctx, claudesdk.Text("What is 2+2?"),
claudesdk.WithPermissionMode("acceptEdits"),
claudesdk.WithMaxTurns(1),
) {
if err != nil {
log.Fatal(err)
}
switch m := msg.(type) {
case *claudesdk.AssistantMessage:
for _, block := range m.Content {
if text, ok := block.(*claudesdk.TextBlock); ok {
fmt.Println(text.Text)
}
}
case *claudesdk.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 := claudesdk.WithClient(ctx, func(c claudesdk.Client) error {
if err := c.Query(ctx, claudesdk.Text("Hello Claude")); err != nil {
return err
}
for msg, err := range c.ReceiveResponse(ctx) {
if err != nil {
return err
}
// process message...
}
return nil
},
claudesdk.WithLogger(slog.Default()),
claudesdk.WithPermissionMode("acceptEdits"),
)
// Or using NewClient directly for more control
client := claudesdk.NewClient()
defer client.Close()
err := client.Start(ctx,
claudesdk.WithLogger(slog.Default()),
claudesdk.WithPermissionMode("acceptEdits"),
)
Plan Mode User Input ¶
AskUserQuestion prompts can be handled with WithOnUserInput:
onUserInput := func(
_ context.Context,
req *claudesdk.UserInputRequest,
) (*claudesdk.UserInputResponse, error) {
answers := make(map[string]*claudesdk.UserInputAnswer, len(req.Questions))
for _, q := range req.Questions {
if len(q.Options) > 0 {
answers[q.Question] = &claudesdk.UserInputAnswer{
Answers: []string{q.Options[0].Label},
}
}
}
return &claudesdk.UserInputResponse{Answers: answers}, nil
}
for msg, err := range claudesdk.Query(ctx,
claudesdk.Text("Use AskUserQuestion to ask me to choose Go or Rust."),
claudesdk.WithPermissionMode("plan"),
claudesdk.WithOnUserInput(onUserInput),
) {
_ = msg
_ = err
}
Logging ¶
For detailed operation tracking, use WithLogger:
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))
for msg, err := range claudesdk.Query(ctx, claudesdk.Text("Hello Claude"),
claudesdk.WithLogger(logger),
) {
_ = msg
_ = err
}
Error Handling ¶
The SDK provides typed errors for different failure scenarios:
for _, err := range claudesdk.Query(ctx, claudesdk.Text(prompt), claudesdk.WithPermissionMode("acceptEdits")) {
if err != nil {
if cliErr, ok := errors.AsType[*claudesdk.CLINotFoundError](err); ok {
log.Fatalf("Claude CLI not installed, searched: %v", cliErr.SearchedPaths)
}
if procErr, ok := errors.AsType[*claudesdk.ProcessError](err); ok {
log.Fatalf("CLI process failed with exit code %d: %s", procErr.ExitCode, procErr.Stderr)
}
log.Fatal(err)
}
}
Requirements ¶
This SDK requires the Claude CLI to be installed and available in your system PATH. You can specify a custom CLI path using the WithCliPath option.
Index ¶
- Constants
- Variables
- func ErrorResult(message string) *mcp.CallToolResult
- func ImageResult(data []byte, mimeType string) *mcp.CallToolResult
- func MessagesFromChannel(ch <-chan StreamingMessage) iter.Seq[StreamingMessage]
- func MessagesFromContent(content UserMessageContent) iter.Seq[StreamingMessage]
- func MessagesFromSlice(msgs []StreamingMessage) iter.Seq[StreamingMessage]
- func ModelCapabilities(modelID string) []string
- func NewMcpTool(name, description string, inputSchema *jsonschema.Schema) *mcp.Tool
- func NopLogger() *slog.Logger
- func ParseArguments(req *mcp.CallToolRequest) (map[string]any, error)
- func Query(ctx context.Context, content UserMessageContent, opts ...Option) iter.Seq2[Message, error]
- func QueryStream(ctx context.Context, messages iter.Seq[StreamingMessage], opts ...Option) iter.Seq2[Message, error]
- func SimpleSchema(props map[string]string) *jsonschema.Schema
- func SingleMessage(content UserMessageContent) iter.Seq[StreamingMessage]
- func TextResult(text string) *mcp.CallToolResult
- func WithClient(ctx context.Context, fn func(Client) error, opts ...Option) error
- type AgentDefinition
- type AssistantMessage
- type AssistantMessageError
- type AsyncHookJSONOutput
- type Base64Source
- type BaseHookInput
- type CLIConnectionError
- type CLIJSONDecodeError
- type CLINotFoundError
- type CallToolRequest
- type CallToolResult
- type ClaudeAgentOptions
- type ClaudeSDKError
- type Client
- type ContentBlock
- type Effort
- type HookCallback
- type HookContext
- type HookEvent
- type HookInput
- type HookJSONOutput
- type HookMatcher
- type HookSpecificOutput
- type InputDocumentBlock
- type InputImageBlock
- type MCPHTTPServerConfig
- type MCPSSEServerConfig
- type MCPSdkServerConfig
- type MCPServerConfig
- type MCPServerConnectionStatus
- type MCPServerInfo
- type MCPServerStatus
- type MCPServerStatusConfig
- type MCPServerType
- type MCPStatus
- type MCPStdioServerConfig
- type MCPToolAnnotations
- type MCPToolInfo
- type McpAudioContent
- type McpContent
- type McpImageContent
- type McpTextContent
- type McpTool
- type McpToolAnnotations
- type McpToolHandler
- type Message
- type MessageParseError
- type MessageStream
- type Model
- type ModelCapability
- type ModelCostTier
- type ModelInfo
- type ModelListResponse
- type NotificationHookInput
- type NotificationHookSpecificOutput
- type Option
- func WithAddDirs(dirs ...string) Option
- func WithAgents(agents map[string]*AgentDefinition) Option
- func WithAllowedTools(tools ...string) Option
- func WithBetas(betas ...SdkBeta) Option
- func WithCanUseTool(callback ToolPermissionCallback) Option
- func WithClaudeHome(path string) Option
- func WithCliPath(path string) Option
- func WithContinueConversation(cont bool) Option
- func WithCwd(cwd string) Option
- func WithDisallowedTools(tools ...string) Option
- func WithEffort(effort config.Effort) Option
- func WithEnableFileCheckpointing(enable bool) Option
- func WithEnv(env map[string]string) Option
- func WithExtraArgs(args map[string]*string) Option
- func WithFallbackModel(model string) Option
- func WithForkSession(fork bool) Option
- func WithHooks(hooks map[HookEvent][]*HookMatcher) Option
- func WithIncludePartialMessages(include bool) Option
- func WithInitializeTimeout(timeout time.Duration) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMCPConfig(config string) Option
- func WithMCPServers(servers map[string]MCPServerConfig) Option
- func WithMaxBudgetUSD(budget float64) Option
- func WithMaxBufferSize(size int) Option
- func WithMaxTurns(maxTurns int) Option
- func WithModel(model string) Option
- func WithOnUserInput(callback UserInputCallback) Option
- func WithOutputFormat(format map[string]any) Option
- func WithPermissionMode(mode string) Option
- func WithPermissionPromptToolName(name string) Option
- func WithPlugins(plugins ...*SdkPluginConfig) Option
- func WithResume(sessionID string) Option
- func WithSDKTools(tools ...Tool) Option
- func WithSandboxSettings(settings *SandboxSettings) Option
- func WithSettingSources(sources ...SettingSource) Option
- func WithSettings(path string) Option
- func WithStderr(handler func(string)) Option
- func WithSystemPrompt(prompt string) Option
- func WithSystemPromptPreset(preset *SystemPromptPreset) Option
- func WithThinking(thinking config.ThinkingConfig) Option
- func WithTools(tools config.ToolsConfig) Option
- func WithTransport(transport config.Transport) Option
- func WithUser(user string) Option
- type PermissionBehavior
- type PermissionMode
- type PermissionRequestHookInput
- type PermissionRequestHookSpecificOutput
- type PermissionResult
- type PermissionResultAllow
- type PermissionResultDeny
- type PermissionRuleValue
- type PermissionUpdate
- type PermissionUpdateDestination
- type PermissionUpdateType
- type PostToolUseFailureHookInput
- type PostToolUseFailureHookSpecificOutput
- type PostToolUseHookInput
- type PostToolUseHookSpecificOutput
- type PreCompactHookInput
- type PreToolUseHookInput
- type PreToolUseHookSpecificOutput
- type ProcessError
- type ReasoningEffortOption
- type ResultMessage
- type SDKSessionInfo
- type SandboxIgnoreViolations
- type SandboxNetworkConfig
- type SandboxSettings
- type Schema
- type SdkBeta
- type SdkMcpServerInstance
- type SdkMcpTool
- type SdkMcpToolHandler
- type SdkMcpToolOption
- type SdkPluginConfig
- type SessionListOptions
- type SessionMessage
- type SessionMessagesOptions
- type SessionStat
- type SettingSource
- type StopHookInput
- type StreamEvent
- type StreamingMessage
- type StreamingMessageContent
- type SubagentStartHookInput
- type SubagentStartHookSpecificOutput
- type SubagentStopHookInput
- type SyncHookJSONOutput
- type SystemMessage
- type SystemPromptPreset
- type TaskNotificationMessage
- type TaskNotificationStatus
- type TaskProgressMessage
- type TaskStartedMessage
- type TaskUsage
- type TextBlock
- type ThinkingBlock
- type ThinkingConfig
- type ThinkingConfigAdaptive
- type ThinkingConfigDisabled
- type ThinkingConfigEnabled
- type Tool
- type ToolFunc
- type ToolPermissionCallback
- type ToolPermissionContext
- type ToolReferenceBlock
- type ToolResultBlock
- type ToolUseBlock
- type ToolsConfig
- type ToolsList
- type ToolsPreset
- type Transport
- type UnknownBlock
- type Usage
- type UserInputAnswer
- type UserInputCallback
- type UserInputQuestion
- type UserInputQuestionOption
- type UserInputRequest
- type UserInputResponse
- type UserMessage
- type UserMessageContent
- type UserPromptSubmitHookInput
- type UserPromptSubmitHookSpecificOutput
Constants ¶
const ( // ModelCapVision indicates the model supports image/vision inputs. ModelCapVision = models.CapVision // ModelCapToolUse indicates the model supports tool/function calling. ModelCapToolUse = models.CapToolUse // ModelCapReasoning indicates the model supports extended reasoning. ModelCapReasoning = models.CapReasoning // ModelCapStructuredOutput indicates the model supports structured JSON output. ModelCapStructuredOutput = models.CapStructuredOutput )
Model capability constants.
const ( // ModelCostTierHigh represents opus-class pricing. ModelCostTierHigh = models.CostTierHigh // ModelCostTierMedium represents sonnet-class pricing. ModelCostTierMedium = models.CostTierMedium // ModelCostTierLow represents haiku-class pricing. ModelCostTierLow = models.CostTierLow )
Model cost tier constants.
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 )
const ( // EffortLow uses minimal thinking. EffortLow = config.EffortLow // EffortMedium uses moderate thinking. EffortMedium = config.EffortMedium // EffortHigh uses deep thinking. EffortHigh = config.EffortHigh )
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 )
const ( // TaskNotificationStatusCompleted indicates the task finished successfully. TaskNotificationStatusCompleted = message.TaskNotificationStatusCompleted // TaskNotificationStatusFailed indicates the task failed. TaskNotificationStatusFailed = message.TaskNotificationStatusFailed // TaskNotificationStatusStopped indicates the task was stopped. TaskNotificationStatusStopped = message.TaskNotificationStatusStopped )
const ( // BlockTypeText contains plain text content. BlockTypeText = message.BlockTypeText // BlockTypeImage contains inline image input content. BlockTypeImage = message.BlockTypeImage // BlockTypeDocument contains inline PDF document input content. BlockTypeDocument = message.BlockTypeDocument )
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 )
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 )
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 )
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 )
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 )
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 )
const ( // MCPServerConnectionStatusConnected indicates the server is connected. MCPServerConnectionStatusConnected = mcp.ServerConnectionStatusConnected // MCPServerConnectionStatusFailed indicates the server failed to connect. MCPServerConnectionStatusFailed = mcp.ServerConnectionStatusFailed // MCPServerConnectionStatusNeedsAuth indicates the server requires authentication. MCPServerConnectionStatusNeedsAuth = mcp.ServerConnectionStatusNeedsAuth // MCPServerConnectionStatusPending indicates the server is still connecting. MCPServerConnectionStatusPending = mcp.ServerConnectionStatusPending // MCPServerConnectionStatusDisabled indicates the server is disabled. MCPServerConnectionStatusDisabled = mcp.ServerConnectionStatusDisabled )
const MinimumCLIVersion = "2.1.59"
MinimumCLIVersion is the minimum required Claude CLI version.
const ( // SdkBetaContext1M enables 1 million token context window. SdkBetaContext1M = config.BetaContext1M )
const Version = "0.1.0"
Version is the SDK version.
Variables ¶
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 // ErrSessionNotFound indicates no persisted session was found for the given session ID. ErrSessionNotFound = errors.ErrSessionNotFound )
Public sentinel errors.
var NewUserMessageContent = message.NewUserMessageContent
NewUserMessageContent creates UserMessageContent from a string.
var NewUserMessageContentBlocks = message.NewUserMessageContentBlocks
NewUserMessageContentBlocks creates UserMessageContent from blocks.
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 MessagesFromContent ¶ added in v0.0.5
func MessagesFromContent(content UserMessageContent) iter.Seq[StreamingMessage]
MessagesFromContent creates a single-message stream from user content.
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 ModelCapabilities ¶
ModelCapabilities returns capability strings for the given model ID. Returns nil if the model is not found.
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 ¶
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, content UserMessageContent, opts ...Option, ) iter.Seq2[Message, error]
Query executes a one-shot query to Claude 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, Text("What is 2+2?"),
WithLogger(logger),
WithPermissionMode("acceptEdits"),
) {
if err != nil {
log.Fatal(err)
}
// handle msg
}
The iterator yields messages as they arrive from Claude, 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, OnUserInput 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.
Example usage:
ctx := context.Background()
for msg, err := range Query(ctx, Text("What is 2+2?"),
WithPermissionMode("acceptEdits"),
WithMaxTurns(1),
) {
if err != nil {
log.Fatal(err)
}
switch m := msg.(type) {
case *AssistantMessage:
// Handle assistant response
case *ResultMessage:
// Handle final result
}
}
Error Handling:
Errors are yielded inline as the second return value. The iterator distinguishes between recoverable and fatal errors:
Parse errors: If a message from Claude cannot be parsed, the error is yielded and iteration continues with the next message. This allows callers to log malformed messages without losing subsequent data.
Fatal errors: Transport failures, context cancellation, and controller errors cause iteration to stop after yielding the error.
Callers can always stop iteration early by breaking from the loop, regardless of error type.
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 Claude via stdin in streaming mode. The transport uses --input-format stream-json.
By default, logging is disabled. Use WithLogger to enable logging.
The iterator yields messages as they arrive from Claude, 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.
QueryStream supports hooks, CanUseTool callbacks, OnUserInput 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.
Example usage:
ctx := context.Background()
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
messages := claudesdk.MessagesFromSlice([]claudesdk.StreamingMessage{
claudesdk.NewUserMessage(Text("Hello")),
claudesdk.NewUserMessage(Text("How are you?")),
})
for msg, err := range claudesdk.QueryStream(ctx, messages,
claudesdk.WithLogger(logger),
claudesdk.WithPermissionMode("acceptEdits"),
) {
if err != nil {
log.Fatal(err)
}
// Handle messages
}
Error Handling:
Errors are yielded inline as the second return value. The iterator distinguishes between recoverable and fatal errors:
Parse errors: If a message from Claude cannot be parsed, the error is yielded and iteration continues with the next message. This allows callers to log malformed messages without losing subsequent data.
Fatal errors: Transport failures, context cancellation, and controller errors cause iteration to stop after yielding the error.
Callers can always stop iteration early by breaking from the loop, regardless of error type.
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 UserMessageContent) iter.Seq[StreamingMessage]
SingleMessage creates a MessageStream with a single user message. This is a convenience function for simple one-message streaming queries.
func TextResult ¶
func TextResult(text string) *mcp.CallToolResult
TextResult creates a CallToolResult with text content.
func WithClient ¶
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 := claudesdk.WithClient(ctx, func(c claudesdk.Client) error {
if err := c.Query(ctx, Text("Hello")); err != nil {
return err
}
for msg, err := range c.ReceiveResponse(ctx) {
if err != nil {
return err
}
// process message...
}
return nil
},
claudesdk.WithLogger(log),
claudesdk.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 Claude.
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 Base64Source ¶ added in v0.0.5
type Base64Source = message.Base64Source
Base64Source contains inline base64 content for Claude CLI multimodal inputs.
type BaseHookInput ¶
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 Claude 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 ClaudeAgentOptions ¶
ClaudeAgentOptions configures the behavior of the Claude agent.
type ClaudeSDKError ¶
type ClaudeSDKError = errors.ClaudeSDKError
ClaudeSDKError is the base interface for all SDK errors.
type Client ¶
type Client interface {
// Start establishes a connection to the Claude CLI.
// Must be called before any other methods.
// Returns CLINotFoundError if CLI not found, CLIConnectionError on failure.
Start(ctx context.Context, opts ...Option) error
// StartWithContent establishes a connection and immediately sends initial user content.
// Equivalent to calling Start() followed by Query(ctx, Text(content))).
// The content is sent to the "default" session.
// Returns CLINotFoundError if CLI not found, CLIConnectionError on failure.
StartWithContent(ctx context.Context, content UserMessageContent, 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 user content to Claude.
// Returns immediately after sending; use ReceiveMessages() or ReceiveResponse() to get responses.
// Optional sessionID defaults to "default" for multi-session support.
Query(ctx context.Context, content UserMessageContent, 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 Claude'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
// ListModels returns the SDK's static Claude model catalog in the ListModels payload shape.
// This is not a live account-specific list from the Claude CLI.
ListModels(ctx context.Context) ([]ModelInfo, 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)
// ReconnectMCPServer reconnects a disconnected or failed MCP server.
ReconnectMCPServer(ctx context.Context, serverName string) error
// ToggleMCPServer enables or disables an MCP server.
ToggleMCPServer(ctx context.Context, serverName string, enabled bool) error
// StopTask stops a running task by task ID.
StopTask(ctx context.Context, taskID string) 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.
// Requires EnableFileCheckpointing=true in ClaudeAgentOptions.
RewindFiles(ctx context.Context, userMessageID string) error
// SendToolResult sends a tool_result message back to Claude for a pending tool_use.
// This is used when the SDK intercepts a tool_use (e.g. AskUserQuestion) and needs
// to provide the result back to Claude so it can continue processing.
SendToolResult(ctx context.Context, toolUseID, content string, isError bool) 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 with Claude.
Unlike the one-shot Query() function, Client maintains session state across multiple exchanges. It supports interruption and bidirectional communication with the Claude CLI.
Lifecycle: Clients are single-use. After Close(), create a new client with NewClient().
Example usage:
client := NewClient()
defer client.Close(ctx)
err := client.Start(ctx,
WithLogger(slog.Default()),
WithPermissionMode("acceptEdits"),
)
if err != nil {
log.Fatal(err)
}
// Send a query
err = client.Query(ctx, Text("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...
}
type ContentBlock ¶
type ContentBlock = message.ContentBlock
ContentBlock represents a block of content within a message.
type HookCallback ¶
HookCallback is the function signature for hook callbacks.
type HookJSONOutput ¶
type HookJSONOutput = hook.JSONOutput
HookJSONOutput is the interface for hook output types.
type HookMatcher ¶
HookMatcher configures which tools/events a hook applies to.
type HookSpecificOutput ¶
type HookSpecificOutput = hook.SpecificOutput
HookSpecificOutput is the interface for hook-specific outputs.
type InputDocumentBlock ¶ added in v0.0.5
type InputDocumentBlock = message.InputDocumentBlock
InputDocumentBlock contains an inline PDF document input for multimodal prompts.
func PDFFileInput ¶ added in v0.0.5
func PDFFileInput(path string) (*InputDocumentBlock, error)
PDFFileInput reads a local PDF file and returns an inline PDF document block.
func PDFInput ¶ added in v0.0.5
func PDFInput(data string) *InputDocumentBlock
PDFInput creates an inline PDF document block from base64 data.
type InputImageBlock ¶ added in v0.0.5
type InputImageBlock = message.InputImageBlock
InputImageBlock contains an inline image input for multimodal prompts.
func ImageFileInput ¶ added in v0.0.5
func ImageFileInput(path string) (*InputImageBlock, error)
ImageFileInput reads a local image file and returns an inline image block.
func ImageInput ¶ added in v0.0.5
func ImageInput(mediaType, data string) *InputImageBlock
ImageInput creates an inline image block from base64 data and media type.
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.
This function creates an MCP server that runs within your application, providing better performance than external MCP servers.
The returned config can be used directly in ClaudeAgentOptions.MCPServers:
addTool := claudesdk.NewSdkMcpTool("add", "Add two numbers",
claudesdk.SimpleSchema(map[string]string{"a": "float64", "b": "float64"}),
func(ctx context.Context, req *claudesdk.CallToolRequest) (*claudesdk.CallToolResult, error) {
args, _ := claudesdk.ParseArguments(req)
a, b := args["a"].(float64), args["b"].(float64)
return claudesdk.TextResult(fmt.Sprintf("Result: %v", a+b)), nil
},
)
calculator := claudesdk.CreateSdkMcpServer("calculator", "1.0.0", addTool)
options := &claudesdk.ClaudeAgentOptions{
MCPServers: map[string]claudesdk.MCPServerConfig{
"calculator": calculator,
},
AllowedTools: []string{"mcp__calculator__add"},
}
Parameters:
- name: Server name (also used as key in MCPServers map, determines tool naming: mcp__<name>__<toolName>)
- version: Server version string
- tools: SdkMcpTool instances to register with the server
type MCPServerConfig ¶
type MCPServerConfig = mcp.ServerConfig
MCPServerConfig is the interface for MCP server configurations.
type MCPServerConnectionStatus ¶ added in v0.0.2
type MCPServerConnectionStatus = mcp.ServerConnectionStatus
MCPServerConnectionStatus represents the connection state of an MCP server.
type MCPServerInfo ¶ added in v0.0.2
type MCPServerInfo = mcp.ServerInfo
MCPServerInfo describes server information returned from initialize.
type MCPServerStatus ¶
type MCPServerStatus = mcp.ServerStatus
MCPServerStatus represents the connection status of a single MCP server.
type MCPServerStatusConfig ¶ added in v0.0.2
type MCPServerStatusConfig = mcp.ServerStatusConfig
MCPServerStatusConfig captures the serializable server config included in status responses.
type MCPServerType ¶
type MCPServerType = mcp.ServerType
MCPServerType represents the type of MCP server.
type MCPStdioServerConfig ¶
type MCPStdioServerConfig = mcp.StdioServerConfig
MCPStdioServerConfig configures a stdio-based MCP server.
type MCPToolAnnotations ¶ added in v0.0.2
type MCPToolAnnotations = mcp.ToolAnnotations
MCPToolAnnotations describes MCP tool capability metadata.
type MCPToolInfo ¶ added in v0.0.2
MCPToolInfo describes an MCP tool exposed by a server.
type McpAudioContent ¶
type McpAudioContent = mcp.AudioContent
McpAudioContent represents audio content in a tool result.
type McpContent ¶
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 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 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 Model ¶
Model holds metadata for a single Claude model.
func Models ¶
func Models() []Model
Models returns a copy of the SDK's static Claude model catalog. It is not a live list of models available to the logged-in Claude CLI user.
func ModelsByCostTier ¶
func ModelsByCostTier(tier ModelCostTier) []Model
ModelsByCostTier returns all models matching the given cost tier.
type ModelCapability ¶
type ModelCapability = models.Capability
ModelCapability represents a model capability such as vision or tool use.
type ModelCostTier ¶
ModelCostTier represents a provider-agnostic relative cost tier.
type ModelListResponse ¶ added in v0.0.2
type ModelListResponse = models.ListResponse
ModelListResponse is the response payload backing ListModels.
func ListModelsResponse ¶ added in v0.0.2
func ListModelsResponse(_ context.Context) (*ModelListResponse, error)
ListModelsResponse returns the full static model-list response payload.
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(*ClaudeAgentOptions)
Option configures ClaudeAgentOptions using the functional options pattern. This is the primary option type for configuring clients and queries.
func WithAddDirs ¶
WithAddDirs adds additional directories to make accessible.
func WithAgents ¶
func WithAgents(agents map[string]*AgentDefinition) Option
WithAgents defines custom agent configurations.
func WithAllowedTools ¶
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.
func WithClaudeHome ¶
WithClaudeHome overrides the Claude home directory (default: ~/.claude).
func WithCliPath ¶
WithCliPath sets the explicit path to the claude CLI binary. If not set, the CLI will be searched in PATH.
func WithContinueConversation ¶
WithContinueConversation indicates whether to continue an existing conversation.
func WithDisallowedTools ¶
WithDisallowedTools sets tools that are explicitly blocked.
func WithEffort ¶
WithEffort sets the thinking effort level.
func WithEnableFileCheckpointing ¶
WithEnableFileCheckpointing enables file change tracking and rewinding.
func WithExtraArgs ¶
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 WithFallbackModel ¶
WithFallbackModel specifies a model to use if the primary model fails.
func WithForkSession ¶
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.
func WithIncludePartialMessages ¶
WithIncludePartialMessages enables streaming of partial message updates.
func WithInitializeTimeout ¶
WithInitializeTimeout sets the timeout for the initialize control request.
func WithLogger ¶
WithLogger sets the logger for debug output. If not set, logging is disabled (silent operation).
func WithMCPConfig ¶
WithMCPConfig sets a path to an MCP config file or a raw JSON string. If set, this takes precedence over WithMCPServers.
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 WithMaxBudgetUSD ¶
WithMaxBudgetUSD sets a cost limit for the session in USD.
func WithMaxBufferSize ¶
WithMaxBufferSize sets the maximum bytes for CLI stdout buffering.
func WithMaxTurns ¶
WithMaxTurns limits the maximum number of conversation turns.
func WithOnUserInput ¶
func WithOnUserInput(callback UserInputCallback) Option
WithOnUserInput sets a callback for handling AskUserQuestion prompts.
func WithOutputFormat ¶
WithOutputFormat specifies a JSON schema for structured output.
The canonical format uses a wrapper object:
claudesdk.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:
claudesdk.WithOutputFormat(map[string]any{
"type": "object",
"properties": map[string]any{...},
"required": []string{...},
})
Structured output is available on ResultMessage.StructuredOutput (parsed) or ResultMessage.Result (JSON string).
func WithPermissionMode ¶
WithPermissionMode controls how permissions are handled. Valid values: "default", "acceptEdits", "plan", "bypassPermissions".
func WithPermissionPromptToolName ¶
WithPermissionPromptToolName specifies the tool name to use for permission prompts.
func WithPlugins ¶
func WithPlugins(plugins ...*SdkPluginConfig) Option
WithPlugins configures plugins to load.
func WithResume ¶
WithResume sets a session ID to resume from.
func WithSDKTools ¶
WithSDKTools registers high-level Tool instances as an in-process MCP server. Tools are exposed under the "sdk" MCP server name (tool names: mcp__sdk__<name>). Each tool is automatically added to AllowedTools.
func WithSandboxSettings ¶
func WithSandboxSettings(settings *SandboxSettings) Option
WithSandboxSettings configures CLI sandbox behavior.
func WithSettingSources ¶
func WithSettingSources(sources ...SettingSource) Option
WithSettingSources specifies which setting sources to use.
func WithSettings ¶
WithSettings sets the path to a settings file to load.
func WithStderr ¶
WithStderr sets a callback function for handling stderr output.
func WithSystemPrompt ¶
WithSystemPrompt sets the system message to send to Claude.
func WithSystemPromptPreset ¶
func WithSystemPromptPreset(preset *SystemPromptPreset) Option
WithSystemPromptPreset sets a preset system prompt configuration. If set, this takes precedence over WithSystemPrompt.
func WithThinking ¶
func WithThinking(thinking config.ThinkingConfig) Option
WithThinking sets the thinking configuration.
func WithTools ¶
func WithTools(tools config.ToolsConfig) Option
WithTools specifies which tools are available. Accepts ToolsList (tool names) or *ToolsPreset.
func WithTransport ¶
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 ¶ added in v0.0.2
type ReasoningEffortOption = models.ReasoningEffortOption
ReasoningEffortOption describes a selectable reasoning effort level.
type ResultMessage ¶
type ResultMessage = message.ResultMessage
ResultMessage represents the final result of a query.
type SDKSessionInfo ¶ added in v0.0.2
type SDKSessionInfo struct {
SessionID string `json:"session_id"`
Summary string `json:"summary"`
LastModified int64 `json:"last_modified"`
FileSize int64 `json:"file_size"`
CustomTitle *string `json:"custom_title,omitempty"`
FirstPrompt *string `json:"first_prompt,omitempty"`
GitBranch *string `json:"git_branch,omitempty"`
Cwd *string `json:"cwd,omitempty"`
}
SDKSessionInfo contains metadata for a persisted Claude session.
func ListSessions ¶ added in v0.0.2
func ListSessions(options SessionListOptions) []SDKSessionInfo
ListSessions lists Claude sessions for a project or across all projects.
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 ¶
SandboxSettings configures CLI sandbox behavior.
type Schema ¶
type Schema = jsonschema.Schema
Schema is a JSON Schema object for tool input validation.
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 := claudesdk.NewSdkMcpTool("add", "Add two numbers",
claudesdk.SimpleSchema(map[string]string{"a": "float64", "b": "float64"}),
func(ctx context.Context, req *claudesdk.CallToolRequest) (*claudesdk.CallToolResult, error) {
args, _ := claudesdk.ParseArguments(req)
a, b := args["a"].(float64), args["b"].(float64)
return claudesdk.TextResult(fmt.Sprintf("Result: %v", a+b)), nil
},
claudesdk.WithAnnotations(&claudesdk.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.
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 *claudesdk.CallToolRequest) (*claudesdk.CallToolResult, error) {
args, err := claudesdk.ParseArguments(req)
if err != nil {
return claudesdk.ErrorResult(err.Error()), nil
}
a := args["a"].(float64)
return claudesdk.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 SessionListOptions ¶ added in v0.0.2
type SessionListOptions struct {
Directory string
Limit int
IncludeWorktrees *bool
ClaudeHome string
}
SessionListOptions controls ListSessions behavior.
type SessionMessage ¶ added in v0.0.2
type SessionMessage struct {
Type string `json:"type"`
UUID string `json:"uuid"`
SessionID string `json:"session_id"`
Message map[string]any `json:"message"`
ParentToolUseID *string `json:"parent_tool_use_id,omitempty"`
}
SessionMessage contains a top-level user or assistant message from a saved transcript.
func GetSessionMessages ¶ added in v0.0.2
func GetSessionMessages(sessionID string, options SessionMessagesOptions) []SessionMessage
GetSessionMessages returns top-level conversation messages from a saved session.
type SessionMessagesOptions ¶ added in v0.0.2
SessionMessagesOptions controls GetSessionMessages behavior.
type SessionStat ¶
type SessionStat struct {
SessionID string
SizeBytes int64
LastModified time.Time
MessageCount *int
CreatedAt *time.Time
UpdatedAt *time.Time
}
SessionStat contains local metadata for a persisted Claude session.
This metadata is read from local Claude persistence files. It does not represent live remote state or lock/occupancy status.
func StatSession ¶
StatSession returns metadata for a locally persisted session.
The lookup is project-scoped and read-only; no prompt is sent and no session content is modified. Returns ErrSessionNotFound when the session cannot be found in local Claude persistence for the resolved project path.
type SettingSource ¶
type SettingSource = config.SettingSource
SettingSource represents where settings should be loaded from.
type StreamEvent ¶
type StreamEvent = message.StreamEvent
StreamEvent represents a streaming event from the Claude API.
type StreamingMessage ¶
type StreamingMessage = message.StreamingMessage
StreamingMessage represents a message sent in streaming mode.
func NewUserMessage ¶
func NewUserMessage(content UserMessageContent) 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 TaskNotificationMessage ¶ added in v0.0.2
type TaskNotificationMessage = message.TaskNotificationMessage
TaskNotificationMessage is emitted when a task completes, fails, or stops.
type TaskNotificationStatus ¶ added in v0.0.2
type TaskNotificationStatus = message.TaskNotificationStatus
TaskNotificationStatus represents the final status of a task.
type TaskProgressMessage ¶ added in v0.0.2
type TaskProgressMessage = message.TaskProgressMessage
TaskProgressMessage is emitted while a task is running.
type TaskStartedMessage ¶ added in v0.0.2
type TaskStartedMessage = message.TaskStartedMessage
TaskStartedMessage is emitted when a task starts.
type TextBlock ¶
TextBlock contains plain text content.
type ThinkingBlock ¶
type ThinkingBlock = message.ThinkingBlock
ThinkingBlock contains Claude'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 Claude.
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 Claude can invoke.
Tools allow users to extend Claude's capabilities with domain-specific functionality. When registered, Claude can discover and execute these tools during a session.
Example:
tool := claudesdk.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 ¶
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 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 ToolReferenceBlock ¶ added in v0.0.2
type ToolReferenceBlock = message.ToolReferenceBlock
ToolReferenceBlock points to a deferred tool selected by Claude tool search.
type ToolResultBlock ¶
type ToolResultBlock = message.ToolResultBlock
ToolResultBlock contains the result of a tool execution.
type ToolUseBlock ¶
type ToolUseBlock = message.ToolUseBlock
ToolUseBlock represents Claude 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 ToolsPreset ¶
type ToolsPreset = config.ToolsPreset
ToolsPreset represents a preset configuration for available tools.
type Transport ¶
Transport defines the interface for Claude 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 ClaudeAgentOptions.Transport.
type UnknownBlock ¶ added in v0.0.2
type UnknownBlock = message.UnknownBlock
UnknownBlock preserves unrecognized content block payloads without failing parsing.
type UserInputAnswer ¶
UserInputAnswer contains response(s) for a question.
type UserInputCallback ¶
UserInputCallback handles AskUserQuestion prompts.
type UserInputQuestion ¶
UserInputQuestion represents a single AskUserQuestion prompt.
type UserInputQuestionOption ¶
type UserInputQuestionOption = userinput.QuestionOption
UserInputQuestionOption represents a selectable choice within a question.
type UserInputRequest ¶
UserInputRequest contains parsed AskUserQuestion payload data.
type UserInputResponse ¶
UserInputResponse contains answers keyed by question text.
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.
func Blocks ¶ added in v0.0.5
func Blocks(blocks ...ContentBlock) UserMessageContent
Blocks creates block-based user content.
func Text ¶ added in v0.0.5
func Text(text string) UserMessageContent
Text creates text-only user content.
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
agents
command
|
|
|
cancellation
command
|
|
|
client_multi_turn
command
|
|
|
compaction_hook
command
Package main demonstrates context compaction monitoring using the PreCompact hook.
|
Package main demonstrates context compaction monitoring using the PreCompact hook. |
|
error_handling
command
|
|
|
extended_thinking
command
Package main demonstrates extended thinking capabilities with Claude.
|
Package main demonstrates extended thinking capabilities with Claude. |
|
filesystem_agents
command
|
|
|
hooks
command
|
|
|
include_partial_messages
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. |
|
multimodal_input
command
|
|
|
parallel_queries
command
|
|
|
pipeline
command
|
|
|
plugin_example
command
Package main demonstrates how to use plugins with Claude Code SDK.
|
Package main demonstrates how to use plugins with Claude Code SDK. |
|
query_stream
command
|
|
|
quick_start
command
|
|
|
sessions
command
|
|
|
setting_sources
command
|
|
|
stderr_callback
command
|
|
|
structured_output
command
|
|
|
system_prompt
command
|
|
|
tool_permission_callback
command
|
|
|
tools_option
command
|
|
|
user_input_callback
command
|
|
|
internal
|
|
|
cli
Package cli provides CLI discovery, version validation, and command building for the Claude Code CLI binary.
|
Package cli provides CLI discovery, version validation, and command building for the Claude Code CLI binary. |
|
client
Package client implements the interactive Client for multi-turn conversations with Claude.
|
Package client implements the interactive Client for multi-turn conversations with Claude. |
|
config
Package config provides configuration types for the Claude SDK.
|
Package config provides configuration types for the Claude SDK. |
|
errors
Package errors defines error types for the Claude SDK.
|
Package errors defines error types for the Claude SDK. |
|
hook
Package hook provides hook types for intercepting Claude CLI events.
|
Package hook provides hook types for intercepting Claude 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 Claude conversations.
|
Package message provides message and content block types for Claude conversations. |
|
models
Package models provides a catalog of known Claude models and their capabilities.
|
Package models provides a catalog of known Claude models and their capabilities. |
|
permission
Package permission provides permission handling types for the Claude CLI.
|
Package permission provides permission handling types for the Claude CLI. |
|
protocol
Package protocol implements bidirectional control message handling for the Claude CLI.
|
Package protocol implements bidirectional control message handling for the Claude CLI. |
|
sandbox
Package sandbox provides sandbox configuration types for the Claude CLI.
|
Package sandbox provides sandbox configuration types for the Claude CLI. |
|
subprocess
Package subprocess provides subprocess-based transport for the Claude CLI.
|
Package subprocess provides subprocess-based transport for the Claude CLI. |
|
userinput
Package userinput provides typed structures for AskUserQuestion handling.
|
Package userinput provides typed structures for AskUserQuestion handling. |