Cortex Code Agent SDK reference – Python¶
This topic provides the complete API reference for the Cortex Code Agent SDK for Python, including all functions, classes, and types.
Installation¶
Requires Python 3.10 or later. Dependencies: anyio, mcp, typing_extensions.
Import the package as cortex_code_agent_sdk.
The SDK expects the Cortex Code CLI to be installed separately. If it is not on
your PATH, set CORTEX_CODE_CLI_PATH=/path/to/cortex or pass cli_path
in CortexCodeAgentOptions.
Functions¶
query()¶
The primary function for interacting with Cortex Code. Returns an async iterator that yields messages as they arrive.
Parameters
Parameter |
Type |
Description |
|---|---|---|
|
|
User prompt string, or async iterable of message dicts for streaming input |
|
|
Configuration options. Defaults to |
|
|
Custom transport. Defaults to subprocess CLI transport |
Returns
An async iterator yielding Message objects (AssistantMessage, ResultMessage, UserMessage,
SystemMessage, StreamEvent).
Example
CortexCodeSDKClient¶
For multi-turn interactive conversations. Supports the async context manager protocol.
Methods¶
Method |
Description |
|---|---|
|
Connect to the CLI process and keep the session open for later turns. |
|
Send a prompt to the agent |
|
Yield all messages from the agent |
|
Yield messages until a |
|
Send interrupt signal |
|
Change the permission mode for later turns in the conversation |
|
Change model during conversation |
|
Stop a running subagent task |
|
Disconnect from the CLI process |
Options¶
Configuration passed to query() or CortexCodeSDKClient.
Option |
Type |
Default |
Description |
|---|---|---|---|
|
|
|
Working directory for the session |
|
|
|
Model to use. Use |
|
|
|
Snowflake connection name from Snowflake CLI connection settings, typically
|
|
|
|
Profile name (loads from |
|
|
|
|
|
|
|
Safety flag required when using |
|
|
|
Tools to auto-approve without prompting |
|
|
|
Tools to always deny |
|
|
|
Limit the number of agent turns per query |
|
|
|
Model effort level: |
|
|
|
Custom system prompt. Pass a string for a full override, or |
|
|
|
Continue the most recent session instead of starting a new one |
|
|
|
Session ID to resume a previous conversation |
|
|
|
When resuming, fork to a new session ID instead of continuing the previous session |
|
|
|
Additional directories to add to the agent’s context |
|
|
|
Environment variables to pass to the CLI process |
|
|
|
Plugin configurations. Currently supports local plugins: |
|
|
|
An |
|
|
|
External MCP server configurations. Pass a dict that maps server names to stdio, HTTP, or SSE configs. The current SDK transport supports dict-based MCP configuration only. |
|
|
|
Hook event handlers (see Hooks) |
|
|
|
Custom tool permission callback (see Tool permissions) |
|
|
|
Include token-level streaming events ( |
|
|
|
Structured output format. Example: |
|
|
|
Disable MCP servers |
|
|
|
Explicit session ID to use |
|
|
|
Setting sources to load: |
|
|
|
Path to CLI binary. If omitted, the SDK first checks
|
|
|
|
Additional CLI flags as key-value pairs. Use |
|
|
|
Callback invoked with each line of CLI stderr output |
Message types¶
AssistantMessage¶
Emitted when the agent produces a response. Contains one or more content blocks.
AssistantMessageError is one of: "authentication_failed", "billing_error", "rate_limit",
"invalid_request", "server_error", "unknown".
ResultMessage¶
Emitted when the agent finishes a turn. Check subtype and is_error for success or failure.
UserMessage¶
Echoed back when a user message is processed.
SystemMessage¶
System events such as session initialization and task updates.
The SDK also provides specialized subclasses for task-related system messages:
Subclass |
Description |
|---|---|
|
Emitted when a subagent task starts. Fields: |
|
Emitted while a task is running. Fields: |
|
Emitted when a task completes, fails, or is stopped. Fields: |
These subclasses extend SystemMessage, so existing isinstance(msg, SystemMessage) checks continue to match.
StreamEvent¶
Partial message updates during token-level streaming. Requires include_partial_messages=True.
StreamEvent is emitted for partial text and thinking blocks. Complete tool calls still arrive as
AssistantMessage content blocks, and tool results still arrive as UserMessage content blocks.
Content blocks¶
Type |
Fields |
|---|---|
|
|
|
|
|
|
|
|
Hooks¶
Hooks let you intercept lifecycle events for logging, validation, or custom behavior.
Configuring hooks¶
Hooks are configured via the hooks option on CortexCodeAgentOptions. Each hook event maps to a list of
HookMatcher objects.
Hook callback signature¶
input: Strongly-typed hook input (see table below)
tool_use_id: Optional tool use identifier
context:
HookContextwith asignalfield (reserved for future abort signal support)
Hook events¶
Event |
Input Type |
Description |
|---|---|---|
|
|
Before a tool is executed. Fields: |
|
|
After a tool completes. Fields: |
|
|
When user submits a prompt. Fields: |
|
|
When the agent stops. Fields: |
|
|
When a subagent finishes. Fields: |
|
|
On notification events. Fields: |
|
|
When a tool requests permission. Fields: |
|
|
Before context compaction. Fields: |
All hook inputs include base fields: session_id, transcript_path, cwd, and optionally
permission_mode.
Hook output¶
Hook callbacks return a synchronous output object:
Note
The Python SDK uses continue_ (with a trailing underscore) to avoid the Python keyword conflict. This is
automatically converted to continue when sent to the CLI.
Tool permissions¶
The can_use_tool callback lets you programmatically control tool permissions.
For many ordinary tool permission checks, the callback input contains fields such as
{"action": ..., "resource": ...}. The allow/deny result and optional deny message are used for these checks.
updated_input is used for SDK-routed pseudo-tools such as AskUserQuestion and ExitPlanMode, which
contain tool-specific fields.
Types
MCP server configuration¶
The mcp_servers option accepts a dict mapping server names to external MCP server configurations:
Config type |
Description |
|---|---|
|
External process via stdio. Fields: |
|
Server-sent events. Fields: |
|
HTTP transport. Fields: |
Example
Error handling¶
Error types¶
Exception |
Description |
|---|---|
|
Base exception for all SDK errors |
|
CLI binary not found on PATH |
|
Failed to connect to or communicate with CLI |
|
CLI process exited unexpectedly |
|
Failed to parse JSON from CLI output |
Legal notices¶
Where your configuration of Cortex Code uses a model provided on the Model and Service Pass-Through Terms, your use of that model is further subject to the terms for that model on that page.
The data classification of inputs and outputs are as set forth in the following table.
Input data classification |
Output data classification |
Designation |
|---|---|---|
Usage Data |
Customer Data |
Covered AI Features [1] |
For additional information, refer to Snowflake AI and ML.