Documentation Index
Fetch the complete documentation index at: https://docs.qoder.com/llms.txt
Use this file to discover all available pages before exploring further.
Functions
query()
The SDK’s main entry function. Creates an async generator that streams SDKMessage in message arrival order.
Parameters
| Parameter | Type | Description |
|---|---|---|
prompt | string | AsyncIterable<SDKUserMessage> | Pass a string for single-turn; pass an async iterable for multi-turn |
options | Options | Optional session configuration |
Return Value
ReturnsQuery — an AsyncGenerator<SDKMessage, void>, consumed via for await.
Types
Options
Configuration object for query().
| Field | Type | Default | Description |
|---|---|---|---|
abortController | AbortController | new AbortController() | Controller to cancel the session |
additionalDirectories | string[] | [] | Additional directories accessible to the AI |
agent | string | undefined | Agent name used by the main session; see Agents Reference |
agents | Record<string, AgentDefinition> | undefined | Programmatically defined subagents; see Agents Reference |
allowDangerouslySkipPermissions | boolean | false | Allow skipping permission checks; used with permissionMode: 'bypassPermissions' |
allowedTools | string[] | [] | Tool allowlist; listed tools are pre-authorized. Built-in tool names are listed in Tools Reference |
auth | AuthOptions | undefined | Authentication configuration, required for query() |
canUseTool | CanUseTool | undefined | Custom tool permission callback |
continue | boolean | false | Continue the most recent session |
cwd | string | process.cwd() | Working directory |
disallowedTools | string[] | [] | Tool blocklist; priority is higher than allowedTools and permissionMode. Built-in tool names are listed in Tools Reference |
enableFileCheckpointing | boolean | false | Enable file checkpointing for use with rewindFiles(); see Checkpoint |
env | Record<string, string | undefined> | process.env | Environment variables passed to the CLI process |
executable | 'bun' | 'deno' | 'node' | Auto-detected | JavaScript runtime |
executableArgs | string[] | [] | Arguments passed to the runtime |
experimentalCloudAgent | CloudAgentOptions | undefined | Switch to the Qoder Cloud Agent runtime (experimental); see Cloud Agent |
extraArgs | Record<string, string | null> | {} | Additional arguments passed to the CLI |
fallbackModel | string | undefined | Fallback model when the main model fails |
forkSession | boolean | false | Fork into a new session ID when used with resume |
hooks | Partial<Record<HookEvent, HookCallbackMatcher[]>> | {} | Lifecycle hooks; see Hooks |
includeHookEvents | boolean | false | Include hook lifecycle events in the message stream |
includePartialMessages | boolean | false | Include stream_event streaming fragments; see Streaming Output |
maxTurns | number | undefined | Maximum conversation turns (tool call round-trips) |
mcpServers | Record<string, McpServerConfig> | {} | MCP server configuration; see MCP |
model | string | CLI default | Model to use; options: 'auto' / 'ultimate' / 'performance' / 'efficient' / 'lite' |
pathToQoderCLIExecutable | string | Auto-resolved bundled binary | Path to qodercli executable |
permissionMode | PermissionMode | 'default' | Session permission mode |
permissionPromptToolName | string | undefined | MCP tool name for permission prompts; mutually exclusive with canUseTool |
planModeInstructions | string | undefined | Override plan mode workflow body when permissionMode: 'plan' |
plugins | SdkPluginConfig[] | [] | Load local plugins; see Plugins |
promptSuggestions | boolean | false | Emit prompt_suggestion messages after each turn’s result |
resolveModel | ModelPolicyProvider | undefined | Dynamic model-selection callback. Passing it switches the query into dynamic-callback mode; see Model Policy |
resolveModelTimeoutMs | number | 500 | Callback timeout in milliseconds; only effective when resolveModel is passed |
resume | string | undefined | Session ID to resume |
resumeSessionAt | string | undefined | Resume from a specified message UUID |
sandbox | SandboxSettings | undefined | Sandbox configuration |
sessionId | string | Auto-generated | Specify session UUID |
settings | string | Settings | undefined | Inline settings object or settings file path |
settingSources | SettingSource[] | CLI default | Which filesystem settings to load; pass [] to skip user/project/local |
skills | string[] | 'all' | undefined | Enabled Skills; pass 'all' to enable all; see Skills |
spawnQoderCLIProcess | (options: SpawnOptions) => SpawnedProcess | undefined | Custom process spawn function |
strictMcpConfig | boolean | false | Strict MCP validation |
systemPrompt | string | { type: 'preset'; preset: 'qodercli'; append?: string } | undefined | System prompt. String overrides; preset form appends after qodercli preset |
toolConfig | ToolConfig | undefined | Built-in tool behavior configuration; see Tools |
tools | string[] | { type: 'preset'; preset: 'qodercli' } | undefined | Tool set. Pass a string array to restrict available tools; pass an empty array to disable all tools. Built-in tool names are listed in Tools Reference |
AuthOptions
| Form | Description |
|---|---|
{ type: 'accessToken'; accessToken: string } | Pass PAT directly |
{ type: 'accessToken'; accessToken: { envVar } } | Read PAT from specified environment variable; defaults to QODER_PERSONAL_ACCESS_TOKEN |
{ type: 'qodercli' } | Reuse local qodercli login session |
accessToken(token) / accessTokenFromEnv(envVar?) / qodercliAuth(); see SDK Authentication.
options.agents
Type: Record<string, AgentDefinition>
Registers custom Agents available to the current query() session. The object key is the Agent name and the value is that Agent’s definition.
TheAgenttool is required: Custom subagents require the main session to delegate through the built-inAgenttool. The Agent tool must be included inallowedToolsbecause Qoder invokes subagents through the Agent tool.
Agent tool. The main session must include Agent in its tool set to delegate work; allowedTools: ['Agent'] is the required pre-authorization form. If you use options.tools to narrow the main session’s available tools, include Agent there as well.
options.agent
Type: string
Specifies which Agent identity the main session should run as. The value can be a name registered in options.agents, or a built-in / plugin Agent name discovered by the current CLI.
prompt, model, and tool restrictions. When omitted, the session uses the default main-session behavior.
AgentDefinition
Definition of a custom Agent. The fields below are the stable capabilities currently covered and verified by the SDK.
| Field | Type | Required | Description |
|---|---|---|---|
description | string | Yes | Agent purpose description; the model uses it to decide when to invoke the Agent |
prompt | string | Yes | Agent system prompt |
tools | string[] | No | Tool allowlist for this Agent |
disallowedTools | string[] | No | Tools excluded from this Agent’s tool set |
model | string | No | Model override; 'inherit' means inherit the main session model |
mcpServers | AgentMcpServerSpec[] | No | MCP server specs available to this Agent |
skills | string[] | No | Skill names preloaded into the Agent context |
initialPrompt | string | No | First user input automatically submitted when this Agent is used as the main session Agent |
maxTurns | number | No | Maximum API turns for the Agent |
effort | EffortLevel | No | Reasoning effort level |
permissionMode | PermissionMode | No | Permission mode for tool execution inside this Agent |
description
Describes what tasks the Agent is suitable for. It affects whether the model chooses this Agent.
Helpful assistant.
prompt
The Agent’s system prompt. Use it to define the role, constraints, and output format.
tools
Tool allowlist for the Agent. When set, the Agent can only use the listed tools.
tools is omitted, the subagent default tool set is used. A subagent’s tool set does not inherit trimming from the main session’s allowedTools.
disallowedTools
Excludes specific tools from the Agent’s tool set.
disallowedTools is omitted, the subagent does not inherit trimming from the main session’s disallowedTools. Usually avoid setting both tools and disallowedTools unless you know the final tool set explicitly.
model
Specifies the model for the Agent. When omitted, the session default model is used. Supported model tiers include:
| Value | Tier | Description | Suitable for | Credit cost |
|---|---|---|---|---|
auto | Smart routing | Intelligently selects the best model, balancing capability and cost | Most daily development work; recommended default | ~1.0x |
ultimate | Ultimate | Expert-level deep reasoning and thinking capability | Complex system design and difficult analysis | ~1.6x |
performance | Performance | Advanced reasoning and high-quality output | Core implementation, architecture design, refactoring | ~1.1x |
efficient | Efficient | Standard reasoning with good cost efficiency | Basic code generation, unit tests, daily Q&A | ~0.3x |
lite | Lite | Basic reasoning, free to use | Quick validation, simple logic, quick questions | 0x |
| Value | Description |
|---|---|
inherit | Inherit the main session model |
| Full model ID | Directly specify a model ID supported by the current CLI / backend |
mcpServers
Limits or adds MCP servers available to this Agent.
skills
List of skill names to preload into the Agent context. Plain skill names and plugin-qualified names are both supported.
initialPrompt
Automatically submitted as the first user input when this Agent becomes the main session Agent through options.agent.
Agent tool.
maxTurns
Limits the Agent’s maximum API turns. Use it to control cost, execution time, and loop risk.
effort
effort is usually suitable for complex reviews, architecture analysis, and high-risk changes, but increases latency and token usage.
permissionMode
Controls the permission mode for tool execution inside this Agent. It uses the same semantics as the session-level permissionMode, but its scope is limited to this Agent. For the session-level permission chain, allowedTools / disallowedTools / canUseTool priority, and examples, see Permission Control.
| Value | Meaning | Suitable for |
|---|---|---|
'default' | Standard permission behavior. Tool calls still pass through tool sets, allow / deny rules, runtime approval, or CLI default policy | Most interactive subagents |
'acceptEdits' | Automatically accepts file-edit operations; other sensitive operations still follow the permission flow | A subagent that is approved to modify workspace files |
'bypassPermissions' | Skips permission checks. High-risk mode, usually only for trusted automation or test environments | Controlled CI, temporary validation, one-off automation |
'yolo' | Compatibility alias for 'bypassPermissions'; also skips permission checks | Compatibility with older configs; not recommended for new code |
'plan' | Plan mode. Suitable for producing a plan first; by default it does not perform real changes | Planning, design, review, or cases where the subagent should not modify files |
'dontAsk' | Does not ask interactively; operations that are not pre-authorized or allowed by rules are denied | Non-interactive environments, or workflows that should fail instead of prompting |
'auto' | Runtime capability decides allow or deny automatically; safe workspace file edits may be auto-allowed | Reduce confirmation interruptions while retaining runtime judgment |
AgentInfo
Agent summary returned by q.supportedAgents().
| Field | Type | Description |
|---|---|---|
name | string | Agent name |
description | string | Agent purpose description |
model | string | undefined | Agent model override; usually empty when unset or when model: 'inherit' |
options.agents, and may also include built-in, project, user, or plugin Agents discovered by the current CLI. The actual available entries depend on the qodercli version and current configuration.
Context and Invocation Boundaries
- Subagents use independent context and do not receive the parent session’s full history.
- The main information passed from the parent session to a subagent is the task prompt supplied to the
Agenttool. - A subagent’s intermediate tool results do not directly enter the parent session; the parent session receives the subagent’s final response.
- Subagents cannot spawn their own subagents, so do not put
Agentin a subagent’stools. initialPromptonly takes effect for the main session Agent specified byoptions.agent.
Model Policy
Dynamic model-selection capability ofquery(). Two modes: fixed-model (no resolveModel, uses options.model or backend default) and dynamic-callback (pass resolveModel, the callback decides the model before every LLM call). For full concepts, triggers and error handling see Model Policy.
options.resolveModel
Type: ModelPolicyProvider
Entry point for dynamic-callback mode. Once passed, dynamic-callback mode is enabled and the SDK calls this callback before every LLM request to fetch the model. The model returned by the callback is the final model for that request; there is no automatic fallback.
options.resolveModelTimeoutMs
Type: number, default 500
Callback timeout, in milliseconds. On timeout ModelPolicyTimeoutError is thrown and the query fails (no fallback). Only effective when resolveModel is passed.
ModelPolicyProvider
Callback function signature. May be synchronous or asynchronous.
QoderModelPurpose:
| Scenario | purpose | Notes |
|---|---|---|
| Main conversation | 'main' | Re-invoked between turns / tools — a session may trigger many times |
| Subagent | 'subagent' | Subagents share the same provider |
| WebFetch tool | 'web_fetch' | After WebFetch retrieves content, a second LLM call summarises it |
| ImageGen tool | 'image_gen' | Used to pick the image-generation model |
| Context compaction | 'compact' | Before compaction starts, the callback is queried for the compaction model |
| BYOK | any | Set model to a CustomModel object to route via a third-party LLM |
- The callback may be triggered many times within a single session (re-invoked before every turn / tool / sub-task).
- The
modelreturned by the callback is the final model for that request; the SDK does not re-validate it. - Throwing an exception or returning an empty
modelfails the query. See Model Policy — Error handling.
ModelPolicyContext
The context passed to the callback on every invocation.
| Field | Type | Required | Description |
|---|---|---|---|
purpose | QoderModelPurpose | yes | Purpose of this LLM call |
sessionId | string | yes | Current session ID; the same value is passed across callback invocations within a session, so it can be used as a cache / telemetry key |
availableModels | ModelInfo[] | yes | The models currently available to the account, supplied by the CLI on every get_model_policy request |
QoderModelPurpose
| Value | Triggering scenario |
|---|---|
'main' | Main-conversation LLM call |
'subagent' | Subagent call |
'web_fetch' | Secondary LLM call triggered by the WebFetch tool |
'image_gen' | Image-generation call triggered by the ImageGen tool |
'compact' | Context compaction / summarisation |
ModelPolicyResult
The callback’s return value.
| Field | Type | Required | Description |
|---|---|---|---|
model | string | (CustomModel & { model: string }) | yes | String: model identifier; object: BYOK credentials + model identifier |
parameters | Record<string, unknown> | no | Model-parameter overrides (e.g. temperature, max_tokens) |
model forms:
- String — any model ID supported by the backend (such as
auto/performance/glm51); the exact set of valid values is returned in real time byq.getAvailableModels(). Must be non-empty, otherwise the query fails. CustomModelobject (BYOK) — the SDK extracts the object’smodelfield as the model identifier for this call, and forwards the remaining fields as credentials to the CLI for routing to a third-party LLM.
CustomModel
BYOK credentials. In the resolveModel callback, set the model field to this object directly, and that LLM request will be routed to a third-party provider.
| Field | Type | Required | Description |
|---|---|---|---|
provider | string | yes | Provider key — must match a BYOKProviderInfo.key |
model | string | yes | Model identifier — extracted by the SDK as the model ID for this call |
api_key | string | yes | The API Key supplied by the user |
style | string | no | Upstream protocol style, e.g. "openai" / "anthropic"; defaults to "openai" |
providermust match akeyin the catalog, otherwise backend authentication fails.- A wrong
api_keycauses authentication to fail, which fails the query directly (dynamic-callback mode does not fall back). - BYOK calls report
total_cost_usdas 0 on the platform; token usage is reported as-is and billed by the provider.
BYOK catalog types
The provider/model catalog returned byq.listByokProviders().
BYOKProviderInfo
| Field | Type | Description |
|---|---|---|
key | string | Provider key — fill into CustomModel.provider for BYOK |
display_name | string | Display name |
api_key_url | string | URL pointing the user where to obtain an API Key |
types | BYOKModelTypeInfo[] | Model groups under this provider |
BYOKModelTypeInfo
| Field | Type | Description |
|---|---|---|
key | string | undefined | Group key, common values: cp / tp / pg |
display_name | string | Group display name |
models | BYOKModelInfo[] | Models within the group |
BYOKModelInfo
| Field | Type | Description |
|---|---|---|
key | string | Model ID — fill into CustomModel.model |
display_name | string | Display name |
is_vl | boolean | Whether vision / multi-modal input is supported |
is_reasoning | boolean | Whether this is a reasoning model |
format | string | Upstream protocol format (e.g. openai) |
max_input_tokens | number | Maximum input token count |
ModelInfo
Summary of an available model returned by q.getAvailableModels(). Also used as the element type of ModelPolicyContext.availableModels.
| Field | Type | Description |
|---|---|---|
value | string | Model identifier — usable as ModelPolicyResult.model or q.setModel() argument |
displayName | string | Display name |
isEnabled | boolean | undefined | Whether currently available; undefined is treated as available |
ModelPolicyTimeoutError
resolveModel callback exceeds options.resolveModelTimeoutMs without returning. The query fails directly, with no fallback.
q.setModel()
ModelInfo.value.
q.getAvailableModels()
ModelPolicyContext.availableModels already carries the same up-to-date list, so calling this method explicitly is unnecessary.
q.listByokProviders()
- Returns
null: the CLI does not support this API (graceful fallback, no exception). - Returns an array (may be empty): the list of providers available to the current account (an empty array means the account has not enabled BYOK).
CanUseTool
Host-defined custom tool permission approval callback.
CanUseToolOptions
options Field | Type | Description |
|---|---|---|
signal | AbortSignal | Aborted when cancelled |
suggestions | PermissionUpdate[] | Permission update suggestions from CLI |
blockedPath | string | File path triggering authorization (file-related scenarios only) |
decisionReason | string | Human-readable authorization reason from CLI |
decisionReasonType | PermissionDecisionReasonType | Permission reason classification |
classifierApprovable | boolean | Whether the current call can be auto-approved by the runtime classifier |
title / displayName / description | string | Human-readable authorization text generated at runtime |
toolUseID | string | This tool invocation’s ID |
agentID | string | Sub-Agent ID initiating the call |
exitPlanMode | ExitPlanModeApprovalDetails | Approval details for exiting plan mode |
PermissionMode
| Value | Meaning | Suitable for |
|---|---|---|
'default' | Standard permission behavior. Tool calls are handled by tools, allow / deny rules, dynamic approval, or runtime policy | Most interactive sessions |
'acceptEdits' | Automatically accepts file-edit operations; other sensitive operations still follow the permission flow | Sessions that are approved to modify workspace files |
'bypassPermissions' | Skips permission checks; must also set allowDangerouslySkipPermissions: true | Trusted automation or test environments |
'yolo' | Compatibility alias for 'bypassPermissions'; must also set allowDangerouslySkipPermissions: true | Compatibility with older configs; not recommended for new code |
'plan' | Plan mode. Suitable for producing a plan first; by default it does not perform real changes | Planning, design, review |
'dontAsk' | Does not ask interactively; operations that are not pre-authorized or allowed by rules are denied | Non-interactive environments, or workflows that should fail instead of prompting |
'auto' | Runtime capability decides allow or deny automatically; safe workspace file edits may be auto-allowed | Reduce confirmation interruptions while retaining runtime judgment |
PermissionResult
Return value of CanUseTool.
allow.updatedInput replaces the actual parameters the tool receives when modified. deny.interrupt: true denies and also interrupts the Agent.
McpServerConfig
MCP server configuration, passed to Options.mcpServers.
McpStdioServerConfig
McpSSEServerConfig
McpHttpServerConfig
McpSdkServerConfigWithInstance
createSdkMcpServer() factory; see MCP - In-Process Server.
SdkPluginConfig
Load local plugins.
| Field | Type | Description |
|---|---|---|
type | 'local' | Currently only local is supported |
path | string | Absolute or relative path to the plugin directory |
CloudAgentOptions
Type of Options.experimentalCloudAgent. Configures the agent / session reference for the Cloud runtime; full usage in Cloud Agent.
| Field | Type | Description |
|---|---|---|
agent.id | string | Reuse an existing Cloud Agent; mutually exclusive with agent.create |
agent.create | AgentCreateParams | Create a new Cloud Agent; mutually exclusive with agent.id |
session.id | string | Reuse an existing Cloud session; agent must not be passed |
session.create | CloudSessionCreateParams | Create a new Cloud session; environment_id is required |
stream.afterId | string | SSE replay anchor — start after this event ID |
stream.deltaFlushIntervalMs | number | Delta merge / flush interval, in milliseconds |
AgentCreateParams
Request body for creating a new Cloud Agent, matching the agent-create fields of the Qoder Cloud OpenAPI.
| Field | Type | Description |
|---|---|---|
model | string | Model identifier. Accepted values: 'auto' / 'ultimate' / 'performance' / 'efficient' / 'lite' |
name | string | Human-readable agent name |
description | string | null | Description |
system | string | null | System prompt |
tools | see above | Built-in toolset; enabled_tools controls the allowlist |
mcp_servers | see above | URL-based MCP server connections |
skills | see above | User-defined custom skills |
metadata | Record<string, string> | Arbitrary key-value metadata |
CloudSessionCreateParams
Request body for creating a new Cloud session.
| Field | Type | Description |
|---|---|---|
environment_id | string | Container environment ID; required |
resources | see above | Resources mounted into the session container (currently only file) |
title | string | null | Session title |
vault_ids | string[] | Credential vault IDs |
memory_store_ids | string[] | Memory store IDs |
SandboxSettings
Sandbox behavior configuration.
| Field | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Enable sandbox |
autoAllowBashIfSandboxed | boolean | true | Auto-allow bash when sandbox is enabled |
excludedCommands | string[] | [] | Commands that statically bypass sandbox (e.g., ['docker']) |
allowUnsandboxedCommands | boolean | true | Allow model to request running commands outside sandbox (falls to canUseTool) |
network | SandboxNetworkConfig | undefined | Network restrictions |
filesystem | SandboxFilesystemConfig | undefined | Filesystem restrictions |
ignoreViolations | { file?, network? } | undefined | Violations to ignore by pattern |
SandboxNetworkConfig
SandboxFilesystemConfig
SettingSource
Controls which filesystem settings are loaded.
| Value | Meaning | Location |
|---|---|---|
'user' | User-level global settings | ~/.qoder/settings.json |
'project' | Project shared settings (version controlled) | .qoder/settings.json |
'local' | Project local settings (gitignored) | .qoder/settings.local.json |
[] to skip entirely.
ToolConfig
Built-in tool behavior configuration.
Built-in Tool List
Intools, allowedTools, disallowedTools, canUseTool, hook matchers, and Agent tool allowlists, built-in tools use the runtime tool names in the table below.
| Category | Tool name | Description |
|---|---|---|
| Command execution | Bash | Execute shell commands |
| File operations | Read | Read file contents |
| File operations | Edit | Edit files by string matching |
| File operations | Write | Create or overwrite files |
| Search | Glob | Search by filename pattern |
| Search | Grep | Search by content regex |
| Network | WebFetch | Fetch and process URL content |
| Network | WebSearch | Web search |
| Agent | Agent | Invoke a subagent |
| Interaction | AskUserQuestion | Ask the user a question |
| Notebook | NotebookEdit | Edit notebook cells |
| Background tasks | TaskOutput | Send output to a background task |
| Background tasks | TaskStop | Stop a background task |
| Plan / worktree | ExitPlanMode | Exit plan mode |
| Plan / worktree | EnterWorktree | Enter a git worktree |
| Plan / worktree | ExitWorktree | Exit a worktree |
| Config | Config | Read or write configuration |
| Todo | TodoWrite | Manage todo items |
| MCP resources | ListMcpResources | List MCP resources |
| MCP resources | ReadMcpResource | Read an MCP resource |
| MCP invocation | Mcp | Generic MCP tool call |
tool()
Creates a type-safe SDK MCP tool definition.
| Parameter | Type | Required | Meaning | Current Qoder behavior |
|---|---|---|---|---|
name | string | Yes | Unique tool identifier within the current MCP server | Forms the model-visible full tool name mcp__{serverName}__{name}; registration requires it to be non-empty |
description | string | Yes | Tool description shown to the model; describe when to use it, what it does, and what it returns | Forwarded into the tool list and directly affects whether the model calls the tool correctly; registration requires it to be non-empty |
inputSchema | Schema extends AnyZodRawShape | Yes | Zod raw shape defining tool input parameters | The SDK uses it to generate the MCP input schema and infer handler args as InferShape<Schema> |
handler | (args, extra) => Promise<CallToolResult> | Yes | Async function executed when the tool is called | Executed by the SDK when the model calls the tool; the return value is sent back to the model as a tool result |
extras | ToolExtras | No | Extra tool metadata, currently used for annotations | The SDK registers supported annotations on the MCP server; this does not replace permission configuration |
tool() itself is a factory for defining tools. Registration constraints such as non-empty name, non-empty description, and duplicate tool names are validated by createSdkMcpServer() when tools are registered.
AnyZodRawShape
AnyZodRawShape is compatible with Zod 3 / Zod 4. It represents a field object, not z.object(...).
InferShape
InferShape infers the handler args type from the Zod raw shape.
SdkMcpToolDefinition
ToolExtras
ToolAnnotations
| Field | Type | Optional | Meaning | Current Qoder behavior |
|---|---|---|---|---|
title | string | Yes | Human-readable title for the tool | MCP metadata; currently not documented as a verified Qoder behavioral capability |
readOnlyHint | boolean | Yes | Marks that the tool does not modify state | Current observable effect: read-only tools can be eligible for concurrent execution within the same batch of tool calls; this is not a permission switch |
destructiveHint | boolean | Yes | Marks that the tool may perform destructive updates | Risk metadata; currently does not automatically block an authorized tool execution |
openWorldHint | boolean | Yes | Marks whether the tool interacts with the external open world | External-interaction metadata; currently does not automatically block an authorized tool execution |
tools, allowedTools, disallowedTools, permissionMode, canUseTool, and hooks. In the feature documentation, the verified behavior capabilities are readOnlyHint, destructiveHint, and openWorldHint; title is retained here only as MCP metadata in the type reference.
createSdkMcpServer()
Creates an MCP server that runs in the same process as the SDK.
CreateSdkMcpServerOptions
| Field | Default | Description |
|---|---|---|
name | Required | MCP server name; it becomes part of mcp__{serverName}__{toolName} |
version | '1.0.0' | Server version information |
tools | undefined | Tools registered to this server |
Return Value
ReturnsMcpSdkServerConfigWithInstance, which can be passed directly as a value in options.mcpServers. For the full MCP server configuration, see McpServerConfig.
CallToolResult
A tool handler returns the MCP protocol CallToolResult.
McpToolResultContent
| Field | Description |
|---|---|
content | Array of content blocks returned to the model |
isError | When true, indicates the tool failed semantically |
_meta | Tool-result metadata, forwarded with the MCP response |
Built-in Tool Input and Output Types
The SDK provides input / output structures for built-in tools at the type level. Note: these are TypeScript type names; permission configuration still uses the runtime tool names above.AgentInput / AgentOutput
BashInput / BashOutput
FileReadInput / FileReadOutput
The runtime tool name is Read; the type names remain FileReadInput / FileReadOutput.
FileEditInput / FileEditOutput
The runtime tool name is Edit.
FileWriteInput / FileWriteOutput
The runtime tool name is Write.
GlobInput / GlobOutput
GrepInput / GrepOutput
WebFetchInput / WebFetchOutput
WebSearchInput / WebSearchOutput
AskUserQuestionInput / AskUserQuestionOutput
NotebookEditInput / NotebookEditOutput
TaskOutputInput
TaskStopInput / TaskStopOutput
ExitPlanModeInput / ExitPlanModeOutput
ConfigInput / ConfigOutput
EnterWorktreeInput / EnterWorktreeOutput
ExitWorktreeInput / ExitWorktreeOutput
TodoWriteInput / TodoWriteOutput
ListMcpResourcesInput / ListMcpResourcesOutput
ReadMcpResourceInput
McpInput / McpOutput
ToolInputSchemas
ToolOutputSchemas
Hooks Reference
For usage guide and examples, see Hooks.Event Overview
| Event | Trigger | Controllable Behavior |
|---|---|---|
PreToolUse | Before tool invocation | Intercept / allow / modify input |
PostToolUse | After tool succeeds | Audit / inject context / override output |
PostToolUseFailure | After tool fails | Error handling / logging |
UserPromptSubmit | Before user prompt is sent | Inject context / intercept |
SessionStart | Session begins | Initialize / inject context |
SessionEnd | Session ends | Cleanup / logging |
Stop | AI stops generating | Prevent stop, force continuation |
SubagentStart | Subagent starts | Observe / log |
SubagentStop | Subagent stops | Observe / log |
PreCompact | Before context compaction | Observe / log |
PostCompact | After context compaction | Observe / log |
CwdChanged | Working directory changes | Observe / log |
InstructionsLoaded | Instruction file loaded | Observe / log |
FileChanged | File created/modified/deleted | Observe / log |
PermissionRequest | Permission requested | Auto-approve / deny permission requests |
HookEvent
Union type of registrable hook events.
HookCallback
HookCallbackMatcher
| Field | Type | Description |
|---|---|---|
matcher | string | Optional regex; filters by tool_name |
hooks | HookCallback[] | Callback list executed on match |
timeout | number | Optional timeout in seconds (default: 60) |
BaseHookInput
Common input fields shared by all hook events.
| Field | Type | Description |
|---|---|---|
hook_event_name | string | Event type identifier (e.g. "PreToolUse") |
session_id | string | Unique identifier for the current session |
transcript_path | string | Path to session transcript file (JSONL format) |
cwd | string | Current working directory of the session |
HookJSONOutput
Return type for hook callbacks.
| Field | Type | Default | Description |
|---|---|---|---|
continue | boolean | true | Set to false to terminate the session. Only effective for PreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit, Stop, SubagentStop |
stopReason | string | — | Human-readable reason for stopping (used with continue: false) |
decision | string | — | "approve" or "block". "block" prevents tool execution; for Stop events, "block" prevents stopping and forces continuation |
reason | string | — | Reason for the decision (shown to the model; for Stop event "block", injected as a continuation prompt) |
hookSpecificOutput | object | — | Event-specific output (see each event type) |
When multiple hooks return conflictingdecisionvalues,"deny"/"block"takes precedence (strictest rule wins).
PreToolUseHookInput
| Field | Type | Description |
|---|---|---|
permission_mode | string | undefined | Current session permission mode |
tool_name | string | Name of the tool being called |
tool_input | unknown | Arguments passed to the tool |
hookSpecificOutput:
| Field | Type | Description |
|---|---|---|
hookEventName | "PreToolUse" | Must be set |
permissionDecision | string | "allow" / "deny" / "ask" / "defer" |
permissionDecisionReason | string | Reason for the permission decision |
updatedInput | Record<string, unknown> | Modified tool input, replaces original tool_input |
additionalContext | string | Extra context injected into the model’s next turn |
PostToolUseHookInput
| Field | Type | Description |
|---|---|---|
tool_name | string | Name of the tool that was called |
tool_input | unknown | Arguments passed to the tool |
tool_response | unknown | Tool execution result |
| Field | Location | Behavior |
|---|---|---|
hookSpecificOutput.updatedToolOutput | Event-specific output | Overrides tool_response; model only sees the overridden value |
hookSpecificOutput.additionalContext | Event-specific output | Appends supplementary context without modifying original result |
decision: "block" + reason | Top-level output | Prevents agent from further processing this tool result |
hookSpecificOutput:
| Field | Type | Description |
|---|---|---|
hookEventName | "PostToolUse" | Must be set |
updatedToolOutput | string | Overrides tool response content |
additionalContext | string | Extra context appended alongside tool result |
When multiple hooks set updatedToolOutput, the last non-empty value wins. For chained transforms, execute them sequentially within a single callback.
PostToolUseFailureHookInput
| Field | Type | Description |
|---|---|---|
tool_name | string | Name of the failed tool |
tool_input | unknown | Arguments passed to the tool |
error | string | Error message |
is_interrupt | boolean | undefined | Whether caused by an interrupt/abort |
UserPromptSubmitHookInput
| Field | Type | Description |
|---|---|---|
prompt | string | User input text |
hookSpecificOutput:
| Field | Type | Description |
|---|---|---|
hookEventName | "UserPromptSubmit" | Must be set |
additionalContext | string | Extra context appended to the user prompt |
SessionStartHookInput
| Field | Type | Description |
|---|---|---|
source | string | Session start reason: "startup" / "resume" / "clear" / "compact" |
hookSpecificOutput:
| Field | Type | Description |
|---|---|---|
hookEventName | "SessionStart" | Must be set |
additionalContext | string | Context injected at session start |
SessionEndHookInput
| Field | Type | Description |
|---|---|---|
reason | string | Session end reason: "clear" / "resume" / "logout" / "prompt_input_exit" / "other" / "bypass_permissions_disabled" |
StopHookInput
| Field | Type | Description |
|---|---|---|
stop_hook_active | boolean | Whether a Stop hook is currently preventing stop |
{ decision: 'block', reason: '...' } to prevent the AI from stopping and force continuation. reason is injected as a continuation prompt into the model context.
SubagentStartHookInput
| Field | Type | Description |
|---|---|---|
agent_id | string | Unique identifier of the subagent instance |
agent_type | string | Type/role of the subagent |
SubagentStopHookInput
| Field | Type | Description |
|---|---|---|
stop_hook_active | boolean | Whether a Stop hook is currently preventing stop |
PreCompactHookInput
| Field | Type | Description |
|---|---|---|
trigger | string | Trigger reason: "manual" / "auto" |
custom_instructions | string | null | Custom instructions for compaction summary |
PostCompactHookInput
| Field | Type | Description |
|---|---|---|
trigger | string | Trigger reason: "manual" / "auto" |
compact_summary | string | Summary generated after context compaction |
CwdChangedHookInput
| Field | Type | Description |
|---|---|---|
old_cwd | string | Working directory before the change |
new_cwd | string | Working directory after the change |
InstructionsLoadedHookInput
| Field | Type | Description |
|---|---|---|
load_reason | string | Load reason: "nested_traversal" / "path_glob_match" |
FileChangedHookInput
| Field | Type | Description |
|---|---|---|
file_path | string | Path of the changed file |
event | string | Filesystem event: "change" / "add" / "unlink" |
PermissionRequestHookInput
| Field | Type | Description |
|---|---|---|
tool_name | string | Tool requesting permission |
tool_input | unknown | Tool input arguments |
permission_suggestions | PermissionUpdate[] | undefined | Suggested permission rules |
hookSpecificOutput:
| Field | Type | Description |
|---|---|---|
hookEventName | "PermissionRequest" | Must be set |
decision | object | Permission decision (see below) |
decision is one of:
- Approve:
{ behavior: "allow", updatedInput?: Record<string, unknown>, updatedPermissions?: PermissionUpdate[] } - Deny:
{ behavior: "deny", message?: string }
Message Types
SDKMessage
Discriminated union of all messages flowing from Query.
message.type, then further dispatch on subtype (only system / result types have subtypes).
SDKAssistantMessage
AI’s complete reply, delivered once per turn.
SDKUserMessage
User message or tool result feedback.
SDKUserMessageReplay
Historical user messages replayed during session resume.
SDKResultMessage
Final message when the entire session ends.
SDKSystemMessage
Session initialization message (subtype: 'init'). Other system events are delivered via separate message types; see the various SDK*Message types below.
SDKPartialAssistantMessage
Requires includePartialMessages: true; streams out incrementally per token. For full usage, see Streaming Output.
SDKCompactBoundaryMessage
Boundary marker for context compaction completion.
SDKStatusMessage
Session running state changes (e.g., compacting).
SDKMcpStatusChangeMessage
MCP connection pool state change.
SDKAPIRetryMessage
Automatic retry on network/service errors.
SDKLocalCommandOutputMessage
Output from local slash commands.
SDKHookStartedMessage
Hook begins execution.
SDKHookProgressMessage
Hook execution output in progress.
SDKHookResponseMessage
Hook finishes.
SDKTaskStartedMessage
Sub-Agent task starts.
SDKTaskProgressMessage
Sub-Agent task progress.
SDKTaskNotificationMessage
Sub-Agent task finishes.
SDKSessionStateChangedMessage
Main session running state change.
SDKSessionTitleChangedMessage
Session title change.
SDKBridgeStateMessage
Bridge connection state change.
SDKFilesPersistedEvent
File checkpoint persistence result.
SDKElicitationCompleteMessage
MCP elicitation complete.
SDKPermissionDeniedMessage
Tool call short-circuited by permission policy (dontAsk / auto / deny rule, etc.).
SDKPromptSuggestionMessage
When promptSuggestions: true is enabled, next-step suggestions that may be received after each turn’s result.
SDKCloudAgentEventMessage
Under the Cloud runtime (options.experimentalCloudAgent), events forwarded from the Qoder Cloud session SSE stream. See Cloud Agent for full usage.
| Field | Type | Description |
|---|---|---|
event | string | Cloud event name, e.g. user.message, agent.message, session.status_idle |
id | string | SSE event ID; usable as stream.afterId for replay |
data | unknown | Cloud event payload (includes turn_id and other fields) |
session_id | string | Cloud session ID this event belongs to |
SDKPermissionDenial
Element in the SDKResultMessage.permission_denials array.