Skip to main content

ChainlessChain Agent SDK for Python

PyPI version Python versions

chainlesschain-agent-sdk is the zero-runtime-dependency Python client for the same Agent Protocol v1 used by @chainlesschain/agent-sdk. It starts one cc agent subprocess, frames its NDJSON stream safely, exposes frozen typed events, and performs approval, question, and MCP elicitation round trips.

Version 0.2.2 is available from PyPI. Python 3.10 or newer is required. This release adds canonical structured approval decisions, request bindings, requested permissions, and fail-closed callback handling.

Install

Install the SDK and a compatible cc CLI:

python -m pip install "chainlesschain-agent-sdk==0.2.2"
npm install --global "chainlesschain@0.166.3"

The Python distribution has no runtime dependencies. The CLI is installed separately because AgentSession controls it as a subprocess:

python -c "import chainlesschain_agent_sdk as sdk; print(sdk.__version__)"
cc --version

Basic session

import asyncio

from chainlesschain_agent_sdk import (
    AgentSession,
    AgentSessionOptions,
    ElicitationResponse,
    ResultEvent,
    UnknownAgentEvent,
)


async def main() -> None:
    session = AgentSession(
        AgentSessionOptions(
            cwd=".",
            session_id="ci-fix-1042",  # declare new sessions that must be resumable
            permission_mode="acceptEdits",
        ),
        on_approval=lambda request: (
            {"kind": "acceptOnce"}
            if request.tool == "run_shell"
            else {"kind": "decline", "reason": "Tool is not allow-listed"}
        ),
        on_question=lambda request: None,  # cancel in non-interactive hosts
        on_elicitation=lambda request: ElicitationResponse("decline"),
    )
    await session.start()
    await session.send("Run the focused tests and fix failures.")

    async for event in session:
        # Every wire object is yielded. A newer CLI type is never discarded.
        if isinstance(event, UnknownAgentEvent):
            print("unknown event preserved:", event.to_dict())
        elif isinstance(event, ResultEvent):
            print(event.subtype, event.result)
            await session.end()

    await session.wait()


asyncio.run(main())

Approval callbacks may still return booleans for source compatibility. Direct respond_approval(id, bool) calls retain the legacy boolean wire; structured decisions echo the request binding and can express scoped turn/session grants.

SystemInitEvent.session_id is the authoritative live ID. Persist it and resume later with AgentSessionOptions(resume=that_id). Anonymous stream sessions are not persisted by CLI design; use session_id when creating a session that must be resumable. resume takes precedence over session_id, matching the TypeScript SDK.

Event and callback guarantees

  • The 24 classes in KNOWN_EVENT_CLASSES mirror the TypeScript AgentStreamEvent union. Nested token usage, deltas, questions, and plan records are dataclasses too.
  • Every event retains its original object in the read-only raw mapping; to_dict() returns a deep mutable copy, including unknown additive fields.
  • Unknown outer type values are delivered as UnknownAgentEvent through both on_event and async iteration.
  • NDJSON decoding carries split lines and split UTF-8 code points across chunks, accepts CRLF, and flushes a final line without a newline.
  • Approval callback errors answer approve:false (fail closed). Question callbacks automatically echo the opaque runtime binding on both normal and null answers, so stale/cross-turn answers remain fail closed. MCP elicitation accepts only an explicit ElicitationResponse("accept", content) (or equivalent mapping); all other outcomes cancel. URL requests expose metadata.url / metadata.url_host; the host must show the full HTTPS URL and obtain explicit consent before opening it. URL completion and non-interactive fallback arrive as typed ElicitationCompleteEvent / ElicitationDeferredEvent objects.
  • stderr is diagnostics only. It is available through on_stderr and is never parsed as protocol data.

Callbacks may be synchronous functions or coroutines. Keep them bounded: the CLI also applies its own interaction timeouts.

CI consumer

examples/ci_gate.py is an executable consumer with an explicit handler for every current event class. It journals every raw event before dispatch and preserves unknown events in the same artifact:

python examples/ci_gate.py \
  --prompt "Run unit tests and fix only the failing implementation" \
  --provider openai \
  --session-id "ci-${GITHUB_RUN_ID}" \
  --output agent-events.ndjson

The script denies approvals unless a tool is explicitly repeated with --approve-tool. examples/github-actions.yml is a manual-dispatch GitHub Actions template with read-only repository permissions and a short-lived event artifact. Raw events can contain prompts, tool output, and model responses, so do not publish that artifact publicly.

The same script has a hermetic replay mode used by this repository's CI:

python examples/ci_gate.py \
  --replay ../agent-sdk/__fixtures__/protocol/*.ndjson \
  --output protocol-events.ndjson

Conformance and tests

Python tests read the canonical fixtures in packages/agent-sdk/__fixtures__/protocol/ directly; there is no copied Python fixture set to drift from TypeScript and Java consumers.

cd packages/agent-sdk-python
PYTHONPATH=src python -m unittest discover -s tests -v

The language-neutral contract remains packages/agent-sdk/docs/PROTOCOL.md.

Download files

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

Source Distribution

chainlesschain_agent_sdk-0.2.2.tar.gz (34.5 kB view details)

Uploaded Source

Built Distribution

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

chainlesschain_agent_sdk-0.2.2-py3-none-any.whl (28.1 kB view details)

Uploaded Python 3

File details

Details for the file chainlesschain_agent_sdk-0.2.2.tar.gz.

File metadata

  • Download URL: chainlesschain_agent_sdk-0.2.2.tar.gz
  • Upload date:
  • Size: 34.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for chainlesschain_agent_sdk-0.2.2.tar.gz
Algorithm Hash digest
SHA256 c6106b6589011dd5f3aa3af5ec0daad136187a03ccdcec613f75ef4a6d651e98
MD5 216498d8a0997b88eb76c3deda9ded9e
BLAKE2b-256 60de2a168ef10ca17d88a6ba9d9e19e8922657867537f71d7697cd19c5440e58

See more details on using hashes here.

Provenance

The following attestation bundles were made for chainlesschain_agent_sdk-0.2.2.tar.gz:

Publisher: python-agent-sdk-release.yml on chainlesschain/chainlesschain

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file chainlesschain_agent_sdk-0.2.2-py3-none-any.whl.

File metadata

File hashes

Hashes for chainlesschain_agent_sdk-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 0050a92a5ad4bb44e29cda56ecabb90151075c3af25da470d72d924b0599ec16
MD5 116fb420314d7958745791642623c482
BLAKE2b-256 c4309d31a73285b74c8a41bdef5e2eb7e9c256176a5eb73afcc5349da2242a1f

See more details on using hashes here.

Provenance

The following attestation bundles were made for chainlesschain_agent_sdk-0.2.2-py3-none-any.whl:

Publisher: python-agent-sdk-release.yml on chainlesschain/chainlesschain

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.2.8

2 files

0.2.7

2 files

0.2.6

2 files

0.2.4

2 files

0.2.3

2 files

This release

0.2.2 This release

2 files

0.2.1

2 files

0.2.0

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page