Skip to main content

Qoder Agent SDK for Python

Python SDK for building applications on top of Qoder Agent.

The SDK starts qodercn for you, streams agent messages back to Python, and lets your application configure tools, permissions, working directories, MCP servers, hooks, and interactive sessions.

Installation

pip install qodercn-agent-sdk

Prerequisites:

  • Python 3.10+
  • A Qoder account or another authentication method supported by your host application

CLI Behavior

Published platform wheels include a bundled qodercn, so a separate CLI installation is not required for normal SDK use. If you prefer to use a system-wide CLI or a pinned local build, pass QoderAgentOptions(cli_path=...).

Authentication

Every SDK query needs an explicit authentication option.

Authentication method Identity Use case
Personal Access Token (PAT) A Qoder user Automation that needs the user's permissions and data
Service Account An organization workload Services and jobs that should not depend on a personal account
Local qodercn session The signed-in user Interactive development on a workstation

For a PAT, generate a token at qoder.cn/account/integrations, store it in a secret manager, and expose it through the default environment variable:

export QODERCN_PERSONAL_ACCESS_TOKEN=your-token
from qodercn_agent_sdk import QoderAgentOptions, access_token_from_env

options = QoderAgentOptions(auth=access_token_from_env())

For a Service Account, read the key from your secret manager and pass it directly to the SDK:

from qodercn_agent_sdk import QoderAgentOptions, service_account

# Get the Service Account key from the host's secret manager adapter.
service_account_key = read_secret("qoder-service-account-key")
options = QoderAgentOptions(
    auth=service_account(service_account_key=service_account_key)
)

The SDK and CLI obtain and refresh short-lived Service Account tokens for this authentication method. A host can retain the Service Account key and use service_account(fetch_service_account_token=...) to obtain and refresh short-lived SATs for qodercn. See the host callback example for a complete Token exchange and query. To reuse a signed-in developer workstation, use qodercli_auth(). See the SDK authentication guide for complete setup instructions and security guidance.

Quick Start

import anyio
from qodercn_agent_sdk import QoderAgentOptions, qodercli_auth, query


async def main() -> None:
    options = QoderAgentOptions(auth=qodercli_auth())

    async for message in query(
        prompt="What is 2 + 2?",
        options=options,
    ):
        print(message)


anyio.run(main)

Basic Usage

query() runs a single SDK query and returns an async iterator of response messages.

from qodercn_agent_sdk import (
    AssistantMessage,
    QoderAgentOptions,
    TextBlock,
    qodercli_auth,
    query,
)

options = QoderAgentOptions(
    auth=qodercli_auth(),
    system_prompt="You are a helpful assistant.",
    max_turns=1,
)

async for message in query(prompt="Explain this repository", options=options):
    if isinstance(message, AssistantMessage):
        for block in message.content:
            if isinstance(block, TextBlock):
                print(block.text)

Tools and Permissions

Qoder Agent can use tools such as file reads, file edits, shell commands, and MCP tools. allowed_tools is an approval allowlist: listed tools are auto-approved, while unlisted tools continue through permission_mode and can_use_tool for a decision. It does not remove tools from the agent's available toolset. To block tools, use disallowed_tools.

from qodercn_agent_sdk import QoderAgentOptions, qodercli_auth, query

options = QoderAgentOptions(
    auth=qodercli_auth(),
    allowed_tools=["Read", "Edit"],
    disallowed_tools=["Bash"],
    permission_mode="acceptEdits",
)

async for message in query(
    prompt="Update the README introduction.",
    options=options,
):
    print(message)

For application-specific approval flows, provide can_use_tool:

from qodercn_agent_sdk import (
    PermissionResultAllow,
    PermissionResultDeny,
    QoderAgentOptions,
    ToolPermissionContext,
    qodercli_auth,
)


async def can_use_tool(
    tool_name: str,
    tool_input: dict,
    context: ToolPermissionContext,
):
    if tool_name == "Bash":
        return PermissionResultDeny(message="Shell commands are disabled here.")
    return PermissionResultAllow()


options = QoderAgentOptions(
    auth=qodercli_auth(),
    can_use_tool=can_use_tool,
)

Working Directory

Use cwd to run the agent in a specific project directory:

from pathlib import Path

from qodercn_agent_sdk import QoderAgentOptions, qodercli_auth

options = QoderAgentOptions(
    auth=qodercli_auth(),
    cwd=Path("/path/to/project"),
)

Interactive Sessions

Use QoderSDKClient when you need a long-lived, bidirectional session instead of a single query() call.

from qodercn_agent_sdk import QoderAgentOptions, QoderSDKClient, qodercli_auth

options = QoderAgentOptions(auth=qodercli_auth())

async with QoderSDKClient(options=options) as client:
    await client.query("Inspect this project and summarize the main modules.")

    async for message in client.receive_response():
        print(message)

QoderSDKClient is useful for chat interfaces, follow-up prompts, interrupts, runtime permission changes, MCP server management, and other workflows that need state across multiple turns.

Use message priority to steer a turn that is already running:

await client.query(
    "Stop the current direction and inspect the failing tests first.",
    priority="now",
)

priority="now" stops the current response and handles the message immediately. priority="next" is the default and uses the next suitable point. priority="later" waits until the current response finishes. should_query=False adds the message to the conversation without starting a response by itself; its processing time still follows priority.

Assign a session-unique message_uuid to messages that need tracking or cancellation, and do not reuse UUIDs within a session. await client.interrupt() stops the current response and returns None. await client.cancel_async_message(message_uuid) returns True when the queued message is cancelled and False when it can no longer be cancelled.

External Session Storage

Use session_store when a host needs durable transcripts outside the local machine. The SDK mirrors entries after qodercn commits them locally. A later process can restore the same session before qodercn starts:

qodercn commit -> SDK append(key, entries) -> external store
external store -> SDK load(key) -> temporary QODERCN_CONFIG_DIR -> qodercn resume
from qodercn_agent_sdk import (
    InMemorySessionStore,
    QoderAgentOptions,
    qodercli_auth,
    query,
)

session_store = InMemorySessionStore()

options = QoderAgentOptions(
    auth=qodercli_auth(),
    cwd="/path/to/project",
    session_store=session_store,
)

async for message in query(prompt="Inspect this project.", options=options):
    print(message)

resume_options = QoderAgentOptions(
    auth=qodercli_auth(),
    cwd="/path/to/project",
    resume="11111111-1111-4111-8111-111111111111",
    session_store=session_store,
)

Every store implements async append(key, entries) and load(key). Implement list_sessions(project_key) for continue_conversation=True and session listing, list_subkeys(key) to restore child-agent transcripts, and delete(key) for deletion. Entries are opaque JSON dictionaries and must remain in append order. A child transcript uses an opaque subpath such as subagents/agent-<id>; the key does not include the on-disk .jsonl extension.

When load() returns None or an empty list for an explicit resume, the SDK falls back to the same local session ID. Missing or empty child transcripts do not prevent restoration of the main session, and unsafe subpaths are ignored.

session_store_flush="batched" is the default. "eager" starts each append without waiting for the result boundary. Final append failures are emitted as non-fatal SDKMirrorErrorMessage values. load_timeout_ms defaults to 60,000 ms. Session storage cannot be combined with file checkpointing, a custom transport. It requires the built-in subprocess transport.

The existing local session helpers remain synchronous. External stores use the async helpers list_sessions_from_store, get_session_info_from_store, get_session_messages_from_store, rename_session_via_store, tag_session_via_store, fork_session_via_store, and delete_session_via_store. Local and external child-agent transcripts are available through list_subagents / get_subagent_messages and list_subagents_from_store / get_subagent_messages_from_store. Use import_session_to_store to copy an existing local main transcript, child-agent transcripts, and metadata into a store.

Production stores

The SDK exports the SessionStore protocol but does not ship a production-ready external storage implementation. Implement the protocol against shared storage operated by your application, then validate its append/load ordering, project isolation, subkey handling, and deletion behavior with run_session_store_conformance.

Custom Tools

You can expose Python functions to Qoder Agent as in-process SDK MCP servers. This avoids managing a separate MCP subprocess for simple application-local tools.

from qodercn_agent_sdk import (
    QoderAgentOptions,
    QoderSDKClient,
    create_sdk_mcp_server,
    qodercli_auth,
    tool,
)


@tool("greet", "Greet a user", {"name": str})
async def greet_user(args):
    return {
        "content": [
            {"type": "text", "text": f"Hello, {args['name']}!"}
        ]
    }


server = create_sdk_mcp_server(
    name="my-tools",
    version="1.0.0",
    tools=[greet_user],
)

options = QoderAgentOptions(
    auth=qodercli_auth(),
    mcp_servers={"tools": server},
    allowed_tools=["mcp__tools__greet"],
)

async with QoderSDKClient(options=options) as client:
    await client.query("Greet Alice.")
    async for message in client.receive_response():
        print(message)

Hooks

Hooks are deterministic Python callbacks invoked at specific points in the agent loop. They are useful for validation, policy checks, logging, and application-specific feedback.

from qodercn_agent_sdk import HookMatcher, QoderAgentOptions, qodercli_auth


async def block_script(input_data, tool_use_id, context):
    if input_data["tool_name"] != "Bash":
        return {}

    command = input_data["tool_input"].get("command", "")
    if "./deploy.sh" in command:
        return {
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "permissionDecision": "deny",
                "permissionDecisionReason": "Deployment scripts require review.",
            }
        }
    return {}


options = QoderAgentOptions(
    auth=qodercli_auth(),
    hooks={
        "PreToolUse": [
            HookMatcher(matcher="Bash", hooks=[block_script]),
        ],
    },
)

Error Handling

from qodercn_agent_sdk import (
    CLIConnectionError,
    CLIJSONDecodeError,
    CLINotFoundError,
    ProcessError,
    QoderAgentOptions,
    QoderSDKError,
    qodercli_auth,
    query,
)

try:
    async for message in query(
        prompt="Hello Qoder",
        options=QoderAgentOptions(auth=qodercli_auth()),
    ):
        print(message)
except CLINotFoundError:
    print("qodercn was not found. Install a platform wheel or set cli_path.")
except CLIConnectionError as exc:
    print(f"Connection failed: {exc}")
except ProcessError as exc:
    print(f"qodercn exited with code {exc.exit_code}")
except CLIJSONDecodeError as exc:
    print(f"Could not parse qodercn output: {exc}")
except QoderSDKError as exc:
    print(f"SDK error: {exc}")

License and Terms

Copyright (c) 2026 Qoder

Use of this software is governed by the Qoder Product Service Terms:

https://qoder.com/product-service

By installing or using this package, you agree to those terms.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

qodercn_agent_sdk-1.0.12.tar.gz (123.0 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

qodercn_agent_sdk-1.0.12-py3-none-win_amd64.whl (60.3 MB view details)

Uploaded Python 3Windows x86-64

qodercn_agent_sdk-1.0.12-py3-none-musllinux_1_2_x86_64.whl (49.5 MB view details)

Uploaded Python 3musllinux: musl 1.2+ x86-64

qodercn_agent_sdk-1.0.12-py3-none-musllinux_1_2_aarch64.whl (48.9 MB view details)

Uploaded Python 3musllinux: musl 1.2+ ARM64

qodercn_agent_sdk-1.0.12-py3-none-manylinux_2_17_x86_64.whl (50.4 MB view details)

Uploaded Python 3manylinux: glibc 2.17+ x86-64

qodercn_agent_sdk-1.0.12-py3-none-manylinux_2_17_aarch64.whl (50.2 MB view details)

Uploaded Python 3manylinux: glibc 2.17+ ARM64

qodercn_agent_sdk-1.0.12-py3-none-macosx_11_0_x86_64.whl (42.8 MB view details)

Uploaded Python 3macOS 11.0+ x86-64

qodercn_agent_sdk-1.0.12-py3-none-macosx_11_0_arm64.whl (38.8 MB view details)

Uploaded Python 3macOS 11.0+ ARM64

File details

Details for the file qodercn_agent_sdk-1.0.12.tar.gz.

File metadata

  • Download URL: qodercn_agent_sdk-1.0.12.tar.gz
  • Upload date:
  • Size: 123.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.10.14

File hashes

Hashes for qodercn_agent_sdk-1.0.12.tar.gz
Algorithm Hash digest
SHA256 552ea2c4d4bb0e0a8816b7658852c5eec7275eb70130417a627dfea88ce1b8bc
MD5 2d58b282d9ffd18775d662d16a86e497
BLAKE2b-256 ac06a294b9c8fa733889801cb127888879e8a0c3c82b5945ad92449141f2b3e9

See more details on using hashes here.

File details

Details for the file qodercn_agent_sdk-1.0.12-py3-none-win_amd64.whl.

File metadata

File hashes

Hashes for qodercn_agent_sdk-1.0.12-py3-none-win_amd64.whl
Algorithm Hash digest
SHA256 ea218dbe92f9f3a642ca304f102c67ea2df5ae9560edea487ee0485520f078f2
MD5 50f83e03f3c536c4fe9d09120d395467
BLAKE2b-256 0d0192dcf1f96209ba6a12e9e8dbd240c154e69fe780ddd1e31a3de71fb56a44

See more details on using hashes here.

File details

Details for the file qodercn_agent_sdk-1.0.12-py3-none-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for qodercn_agent_sdk-1.0.12-py3-none-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 34b3c312a77968938c8ef8cf28e50252dc272b1165f11ed2eac2e1b894e15a54
MD5 1e35970dc6eb5e4c183e5e9995b1d464
BLAKE2b-256 398c894f8d249758a9470a6a10ae99cff34e9ed988500e52297c0d7433b5db2b

See more details on using hashes here.

File details

Details for the file qodercn_agent_sdk-1.0.12-py3-none-musllinux_1_2_aarch64.whl.

File metadata

File hashes

Hashes for qodercn_agent_sdk-1.0.12-py3-none-musllinux_1_2_aarch64.whl
Algorithm Hash digest
SHA256 7440affd8e64e1605c7108a40cc48ad09e0dd9e1e25b2414154d31ee693725c7
MD5 0e6f6b5a5ec26b84b9c0f9b7cefb0915
BLAKE2b-256 958a5556548f0a239208ac613926573390a9fb9f0377507c6d5ca1a6f9c3c0ab

See more details on using hashes here.

File details

Details for the file qodercn_agent_sdk-1.0.12-py3-none-manylinux_2_17_x86_64.whl.

File metadata

File hashes

Hashes for qodercn_agent_sdk-1.0.12-py3-none-manylinux_2_17_x86_64.whl
Algorithm Hash digest
SHA256 ceef2ac4eb297d9788da4221336a4d46af19640b6ea656757dcb5751ce9c468c
MD5 9c3ff662df8b0717c07662c2e76a5c2f
BLAKE2b-256 e64e6cba623a51b68a9d8e012fcf7f17b0f2cbc1a7b44012030604d5acb07662

See more details on using hashes here.

File details

Details for the file qodercn_agent_sdk-1.0.12-py3-none-manylinux_2_17_aarch64.whl.

File metadata

File hashes

Hashes for qodercn_agent_sdk-1.0.12-py3-none-manylinux_2_17_aarch64.whl
Algorithm Hash digest
SHA256 9ce2a17a8410c29762d1fe04db2f047be1c5bd6c3d0f167e65c730f52825c46a
MD5 e28e1a5018015f4549bb206ecfa78b2c
BLAKE2b-256 6906103f876d4613197f92a70488f44e52c3f7f5c792082cee5a9b925ec39713

See more details on using hashes here.

File details

Details for the file qodercn_agent_sdk-1.0.12-py3-none-macosx_11_0_x86_64.whl.

File metadata

File hashes

Hashes for qodercn_agent_sdk-1.0.12-py3-none-macosx_11_0_x86_64.whl
Algorithm Hash digest
SHA256 52c822fe055fc98b1aec8fc46f5e585ba0ba6db3e2b64f6f217866a3272e031d
MD5 bfc840d3f13c5415cbcc5d0049a3fb70
BLAKE2b-256 c311ed7a6cb66229642539b30a57d2f9a3c232c94d15fed5a93c851382b99fac

See more details on using hashes here.

File details

Details for the file qodercn_agent_sdk-1.0.12-py3-none-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for qodercn_agent_sdk-1.0.12-py3-none-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 41044c8d42e06b1cd6d91196a122b540e0a16939fdeafa1fa6ba33c0bff2d16c
MD5 84d13ba15a210534556b53453c49af4c
BLAKE2b-256 6879965cb64539922fca0280786f01827e4f9cd8571b5f765d78b19e7721877d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page