Skip to main content

Functions

query()

The SDK’s main entry function. Creates an async iterator that streams messages in arrival order.

Parameters

Return Value

Returns AsyncIterator[Message], consumed via async for.

QoderSDKClient

Class-based multi-turn conversation API. Suitable for scenarios that need to keep session state across turns or dynamically switch the model or permission mode.

client.interrupt()

Interrupts the current generation or tool execution without disconnecting the client. The application can consume the terminal ResultMessage and send another turn. See Interrupting the current turn.

Types

QoderAgentOptions

Configuration object for query() and QoderSDKClient. The Python SDK uses snake_case field names.

Authentication

For convenience usage, see SDK Authentication.

Agents Reference

This page summarizes the stable configuration items related to SDK Agents. For getting started and usage scenarios, see Subagent Usage Guide.

Sources of Available Agents

The agents available in the current session may come from multiple sources: In the interactive CLI, you can run /agents to view the currently discovered Agents; on the command line, run qodercli agents list. In the Python SDK, after QoderSDKClient connects, call client.supported_agents() to get a summary of agents available in the current session.

QoderAgentOptions.agents

Type: dict[str, AgentDefinition] | None Registers custom Agents available in the current session. The dict key is the Agent name and the value is that Agent’s definition.
The Agent tool is required: Custom subagents require the main session to delegate through the built-in Agent tool, so allowed_tools must include the Agent tool.
After registration, the model can invoke these subagents through the built-in Agent tool. The main session must include Agent in its tool set to delegate work; allowed_tools=["Agent"] is the required pre-authorization form. If you use tools to narrow the main session’s available tools, include Agent there as well.

QoderAgentOptions.agent

Type: str | None Specifies which Agent identity the main session runs as. The value can be a name registered in agents, or a built-in / plugin Agent name discovered by the current CLI.
When set, the main session uses that Agent’s prompt, model, and tool restrictions. When omitted, the default main-session behavior is used.

AgentDefinition

Definition of a custom Agent. The Python SDK’s AgentDefinition is a dataclass whose field names use the protocol-style camelCase. The fields below are the stable capabilities currently covered and verified by the SDK.
The Python SDK serializes AgentDefinition into the initialize request via dataclasses.asdict(); qodercli then parses it according to the current Agent schema.

description

Describes what tasks the Agent is suitable for. It affects whether the model chooses this Agent.
Prefer a clear triggering scenario. Avoid broad descriptions such as 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.
When tools is omitted, the subagent default tool set is used. A subagent’s tool set does not inherit trimming from the main session’s allowed_tools.

disallowedTools

Excludes specific tools from the Agent’s tool set.
When disallowedTools is omitted, the subagent does not inherit trimming from the main session’s disallowed_tools. Usually avoid setting both tools and disallowedTools unless you explicitly know the final tool set.

model

Specifies the model for the Agent; when omitted, the session default model is used. At the Python type level it is str | None; the SDK does not restrict specific strings locally. Common model tiers include: Agents also support two special forms:

mcpServers

Limits or adds MCP servers available to this Agent. Each entry can be a session-level server name, or an inline server configuration mapping. Reference a session-level MCP server:
Configure a dedicated MCP server for a specific Agent:
When you only want to expose a specific MCP tool, also configure tools=["mcp__server__tool"] to avoid exposing every tool of that server to the Agent.

skills

A list of skill names preloaded into the Agent context. Plain skill names and plugin-qualified names are both supported.
For session-level skill behavior, see Skills.

initialPrompt

Automatically submitted as the first user input when this Agent becomes the main session Agent through QoderAgentOptions.agent.
This field only takes effect for the main session Agent. It is ignored when the Agent is invoked as a subagent through the Agent tool.

maxTurns

Limits the Agent’s maximum API turns. Use it to control cost, execution time, and loop risk.

effort

Controls the Agent’s reasoning effort level. Higher 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 permission_mode, but its scope is limited to this Agent. For the session-level permission chain, the priority of allowed_tools / disallowed_tools / can_use_tool, and examples, see Permission Control.
For permission semantics, see Permission Control.

AgentInfo

Agent summary returned by QoderSDKClient.supported_agents().
The Python SDK does not currently export a TypedDict named AgentInfo; the return type of supported_agents() is list[dict[str, Any]]. The structure above is the stable field convention of the actually returned dicts.
The returned list may include Agents registered through 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 Agent tool.
  • 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 Agent in a subagent’s tools.
  • initialPrompt only takes effect for the main session Agent specified by agent.

Model Policy

Dynamic model-selection capability of query(). Two modes: fixed-model (no resolve_model, uses options.model or backend default) and dynamic-callback (pass resolve_model, the callback decides the model before every LLM call). For full concepts, triggers and error handling see Model Policy.

options.resolve_model

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.resolve_model_timeout_ms

Type: int, default 500 Callback timeout (milliseconds). On timeout ModelPolicyTimeoutError is thrown and the query fails (no fallback). Only effective when resolve_model is passed.

ModelPolicyProvider

Callback function signature. May be synchronous or asynchronous.
Triggering scenarios are distinguished by QoderModelPurpose: Behavioral notes:
  • The callback may be triggered many times within a single session (re-invoked before every turn / tool / sub-task).
  • The model returned by the callback is the final model for that request; the SDK does not re-validate it.
  • Throwing an exception or returning an empty model fails the query directly. See Model Policy — Error handling.

ModelPolicyContext

The context passed to the callback on every invocation.

QoderModelPurpose

ModelPolicyResult

The callback’s return value.
Supported parameters keys: 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 by client.get_available_models(). Must be non-empty, otherwise the query fails.
  • CustomModel object (BYOK) — the SDK extracts the object’s model field 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 resolve_model callback, set the model field directly to this object, and that LLM request will be routed to a third-party provider.
Notes:
  • provider must match a key in the catalog, otherwise backend authentication fails.
  • A wrong api_key causes authentication to fail, which fails the query directly (dynamic-callback mode does not fall back).
  • BYOK calls report total_cost_usd as 0 on the platform; token usage is reported as-is and billed by the provider side.

BYOK Catalog Types

The provider/model catalog returned by client.list_byok_providers().

BYOKProviderInfo

BYOKFieldInfo

BYOKModelTypeInfo

BYOKModelInfo

ModelInfo

Summary of an available model returned by client.get_available_models(). Also used as the element type of ModelPolicyContext.availableModels.

ModelContextConfig

Context-window configuration keyed by tier label, such as "200K" or "1M".

ModelThinkingConfig

Thinking / reasoning configuration for a model.

ModelPromotion

Promotion / discount info forwarded from the model list API. Nested field names stay in the server’s snake_case form.

ServerModelJson

Raw JSON-compatible model entry from the model list API. Use this when a server field is needed before it has a first-class ModelInfo field.

UsageInfo

Account quota and usage snapshot returned by client.get_usage_info().
Each bucket reports used / remaining / percentage against its total (or cap for the org package) in unit (typically credits). Missing fields, or fields with an unexpected runtime type, are omitted from the returned dict.

ModelPolicyTimeoutError

Thrown by the SDK when the resolve_model callback exceeds options.resolve_model_timeout_ms without returning. The query fails directly, with no fallback.

client.set_model()

Switches the model in fixed-model mode at runtime. Takes effect on the next LLM call. Effective only in fixed-model mode; in dynamic-callback mode, calling it does not override the callback’s result. Valid model IDs: see ModelInfo.value.

client.set_proxy()

Sets or clears the proxy for the running qodercli session. Supports http://, https://, socks5://, and socks://. Pass None or an empty string to clear the proxy.

client.get_available_models()

Fetches the latest model list available to the current account in real time. Always returns the latest result, no caching; returns an empty array (does not throw) when the list cannot be fetched temporarily. In dynamic-callback mode, ModelPolicyContext.availableModels already carries the same up-to-date list, so calling this method explicitly is unnecessary.

client.list_byok_providers()

Returns the BYOK provider/model catalog available to the current account as an array:
  • Returns None: 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).
For field semantics, see BYOK Catalog Types.

client.get_usage_info()

Fetches the current account’s quota and usage information from the running CLI in real time.
  • Returns None: the CLI is unauthenticated, an older CLI version does not support this API, or the CLI did not return a dict (graceful fallback, no exception).
  • Returns a UsageInfo dict: the known account quota and usage fields whose runtime types are valid. Missing or invalid fields are omitted.
For the return type, see UsageInfo.

CanUseTool

Host-defined custom tool permission approval callback.

ToolPermissionContext

For full usage and examples, see Permission Control.

PermissionMode

For more details on the permission chain, see Permission Control.

PermissionResult

Return value of CanUseTool.
allow.updated_input, when modified, replaces the actual parameters the tool receives. deny.interrupt=True denies and also interrupts the Agent. The tool_name received by can_use_tool is the full tool name, for example "Bash", "Read", "mcp__orders__lookup_order".

McpServerConfig

MCP server configuration, passed to QoderAgentOptions.mcp_servers.

McpStdioServerConfig

McpSSEServerConfig

McpHttpServerConfig

McpSdkServerConfig

Returned by the create_sdk_mcp_server() factory; see MCP - In-Process Server.

McpServerToolPolicy

SdkPluginConfig

Load local plugins.

SettingSource

Controls which filesystem settings are loaded.
When omitted, all sources are loaded per CLI defaults; pass [] to skip entirely.

Cloud Agent Reference

This section covers the experimental Cloud Agent runtime configuration types. For usage guide and examples, see Cloud Agent.

CloudAgentOptions

Type for QoderAgentOptions.experimental_cloud_agent. Cloud runtime agent / session reference configuration; full usage in Cloud Agent.
Mutual exclusion constraints:
  • agent["id"] and agent["create"] are mutually exclusive.
  • session["id"] and session["create"] are mutually exclusive.
  • When passing session["id"], agent must not be provided (the session already binds its agent).

AgentCreateParams (Cloud)

Request body for creating a Cloud Agent, corresponding to the Qoder Cloud OpenAPI agent create fields.

BetaManagedAgentsAgentToolset20260401Params

BetaManagedAgentsURLMCPServerParams

BetaManagedAgentsSkillParams


CloudSessionCreateParams

Request body for creating a Cloud session.

CloudSessionResource


CloudAgentStreamOptions

SSE replay and delta options. The Python SDK accepts both snake_case and camelCase.

CloudAgentEventMessage

Under the Cloud runtime (options.experimental_cloud_agent), events forwarded from the Qoder Cloud session SSE stream. Full usage in Cloud Agent.

Cloud Agent Error Types


Tools Reference

This page summarizes the stable tool-related APIs, the built-in tool list, and type definitions. For usage paths and scenarios, see Tools Usage Guide.
Note: The Python SDK currently does not export the built-in tool input / output type collections from the TypeScript SDK, such as BashInput, FileReadInput, or ToolInputSchemas. The implementation status is explicitly noted in the relevant sections.

ToolConfig

The TypeScript SDK provides options.toolConfig to configure the behavior of certain built-in tools:
The Python SDK does not currently export an equivalent QoderAgentOptions.tool_config field; AskUserQuestion can still be used as a runtime tool name in tools, allowed_tools, disallowed_tools, can_use_tool, and hook matchers.

Built-in Tool List

In tools, allowed_tools, disallowed_tools, can_use_tool, hook matchers, and Agent tool allowlists, built-in tools use the runtime tool names in the table below. Custom MCP tool names use this format:

tool()

Creates an SDK MCP tool definition. The Python version is decorator-style; the handler is wrapped via @tool(...).
tool() itself only defines the tool; the decorated async handler is the function executed when the tool is called. Registration constraints such as name, description, and duplicate tool names are validated by create_sdk_mcp_server() when the tool is registered.

input_schema

The Python SDK does not have the TypeScript SDK’s AnyZodRawShape / InferShape. The Python version of input_schema supports the following forms:
Common Python type conversions:

TypeScript-only schema helper types

SdkMcpTool

The @tool() decorator returns an SdkMcpTool. You typically do not need to construct one manually.

ToolInvocationContext

The handler may take one or two parameters:
When the handler accepts a second positional parameter, the SDK passes a ToolInvocationContext. extra.signal is set when the CLI cancels an in-flight tool call.

ToolAnnotations

The Python version directly uses mcp.types.ToolAnnotations.
These fields are metadata and scheduling hints, not permission switches. Whether execution is allowed is still determined by tools, allowed_tools, disallowed_tools, permission_mode, can_use_tool, and hooks.

create_sdk_mcp_server()

Creates an MCP server that runs in the same process as the SDK.

CreateSdkMcpServerOptions

The TypeScript SDK uses a CreateSdkMcpServerOptions object parameter; the Python SDK does not export this type and does not use an options object. The Python equivalent is the three function parameters of create_sdk_mcp_server(name, version="1.0.0", tools=None).

Return Value

Returns an McpSdkServerConfig that can be used directly as a value in QoderAgentOptions.mcp_servers.

McpServerToolPolicy

The tools policy field exists in the Python types. It is primarily used for tool permission policy at the MCP server configuration layer; common in-process SDK server integrations are still controlled through allowed_tools, disallowed_tools, permission_mode, can_use_tool, and hooks.

CallToolResult

The Python SDK does not export its own CallToolResult type. Handlers return a dict, and the SDK converts it into the MCP CallToolResult.

McpToolResultContent

The Python SDK currently recognizes the following content blocks: Differences from the TS reference:
  • The Python handler uses is_error, not the MCP / TypeScript isError field name; the SDK maps it to MCP isError internally.
  • Top-level _meta on the Python handler is not currently passed through to CallToolResult.
  • The Python call_tool conversion logic does not currently handle the audio content block; even though MCP types import AudioContent, a handler returning {"type": "audio"} will fall into the unsupported-content warning branch.

can_use_tool

The tool permission approval callback is defined in the common types and is repeated here for ease of reference.

PermissionResult

The tool_name received by can_use_tool is the full tool name, for example Bash, Read, mcp__orders__lookup_order.

MCP Status Tool Information

The Python SDK exports McpToolInfo and McpToolAnnotations to describe the per-server tool information returned by QoderSDKClient.get_mcp_status().
Note: the annotation field names in status are the CLI-projected readOnly, destructive, openWorld, not the readOnlyHint, destructiveHint, openWorldHint from the ToolAnnotations input. idempotentHint is not currently echoed in the status tool list.

Built-in Tool Input/Output Types

The TypeScript SDK provides input / output structures for built-in tools at the type level. The Python SDK currently does not export these TypedDicts, nor does it export ToolInputSchemas / ToolOutputSchemas union types. Note: the type names in the table below are the TypeScript reference type names; Python permission configuration and tool allowlists still use the runtime tool names from Built-in Tool List. What the Python side exposes as stable and configurable is the runtime tool names in Built-in Tool List. If you need strongly-typed built-in tool parameters in a Python application, define your own TypedDict or dataclass on the business side.

Hooks Reference

For usage guides and examples, see Hooks.

Event Overview

HookEvent

Union type of registrable hook events.

HookCallback

HookMatcher

BaseHookInput

Common input fields for all hook events.

HookJSONOutput

Return type of a hook callback.
In the Python SDK, continue_ corresponds to the JSON key "continue" (to avoid the keyword conflict). When multiple hooks return conflicting decision values, "deny" / "block" takes priority (the strictest rule wins).

PreToolUseHookInput

hook_specific_output (hookSpecificOutput):

PostToolUseHookInput

Output behavior: hook_specific_output (hookSpecificOutput):
When multiple hooks set updatedToolOutput, the last non-empty value wins. For chained transformations, perform them sequentially within a single callback.

PostToolUseFailureHookInput

UserPromptSubmitHookInput

hook_specific_output (hookSpecificOutput):

SessionStartHookInput

hook_specific_output (hookSpecificOutput):

SessionEndHookInput

StopHookInput

Returning {"decision": "block", "reason": "..."} blocks the AI from stopping and forces continuation. reason is injected into the model context as a continuation prompt.

SubagentStartHookInput

SubagentStopHookInput

PreCompactHookInput

PostCompactHookInput

CwdChangedHookInput

InstructionsLoadedHookInput

FileChangedHookInput

PermissionRequestHookInput

hook_specific_output (hookSpecificOutput): decision is one of:
  • Approve: {"behavior": "allow", "updatedInput": {...}, "updatedPermissions": [...]}
  • Deny: {"behavior": "deny", "message": "..."}

Message Types

AssistantMessage

The complete AI reply, delivered once per turn. content is a list of TextBlock and ToolUseBlock.

ResultMessage

The final message at the end of the entire session.

SystemMessage

Session system message. When subtype == "init", data carries initialization information (session_id, model, tools, etc.).

StreamEvent

Requires include_partial_messages=True; streamed token-by-token.
event["type"] values: For full usage, see Streaming Output.

CloudAgentEventMessage

SSE event message under Cloud runtime. Only present in experimental_cloud_agent mode. Full field reference in Cloud Agent Reference.

Content Blocks

Elements in AssistantMessage.content: