Skip to content

Python SDK and Tool Bridge Guide ​

When to use it ​

Drive the same Node runtime over stdio JSON-RPC from Python. Default Protocol v1 can register Python callables as agent tools; choose Protocol v2 explicitly for host verification.

Minimal example ​

text
from __future__ import annotations

with CoreMindClient(config_path='coremind.yaml') as client:
    @client.tool(
        description='查询模拟订单',
        effect={'operations': ['read'], 'reversible': True},
    )
    def lookup_order(order_id: str) -> dict[str, str]:
        return {'id': order_id, 'status': 'paid'}
    result = client.run('查询 A-100')
    print(result['snapshot']['operation'], result['snapshot']['artifacts'])
    if result['outcome']['status'] != 'succeeded':
        raise RuntimeError(result['outcome']['finishReason'])

The example above uses default Protocol v1. For host verification in 0.8.0, use CoreMindClient(..., protocol_version="2.0"): run() first returns a RunHandle; check received_verification_requests, submit the host decision with submit_verification, and read the final Projection outcome with query(runId). V2 does not execute @client.tool Python callables. See the host verification example.

If background Runtime initialization fails after v2 run() has returned a RunHandle, read that Run's persisted failure through query(runId) or events. Registered errors retain their shared classification's stable code, corresponding outcome status, and safe message. Unknown exceptions pause as unclassified_error and require human audit before deciding what happens next. This differs from the SDK initialize call itself raising an exception; do not collapse every startup failure into agent_failed or expose credentials and raw stacks.

In v1, effect travels with register_tool to the shared runtime. Use pathFields and urlFields for non-standard arguments. Terminal states live in result['outcome']; Python exceptions remain for protocol, startup, and caller failures.

When parameters is omitted, @client.tool builds a schema from parameter annotations, including future or string annotations for int, str, bool, and existing supported containers such as list[int]. Node applies existing conversion rules before validation: for an int parameter, the string '5' becomes the integer 5 before reaching the callable. Arguments that still fail schema validation after conversion are rejected before execution. An unresolvable forward reference fails explicitly and requires parameters. Complex typing retains the existing support limits; provide an explicit schema for precise constraints. Existing explicit parameters usage remains unchanged.

If initialization or any tool registration fails, the client closes the started worker before returning the exception. Continue to use a context manager or finally for the normal lifecycle.

Controls during a Run (1.1 development) ​

Python retains existing Protocol v2 control, events, and query methods without a new convenience API or protocol version. Select protocol_version="2.0" explicitly. The default Worker comes from the installed package, not a source checkout. For a ready active Run, take run_id from its RunHandle:

python
receipt = client.control({
    'schemaVersion': 1,
    'runId': run_id,
    'controlId': 'review-tests-1',
    'type': 'steering',
    'message': 'Check test results first',
})
page = client.events(run_id, after_sequence=0)

Type can be steering or follow_up; follow-up continues in the same Run after the agent would naturally stop. Await the corresponding AsyncCoreMindClient methods for the same contract. Every events call requires explicit after_sequence. Save each Run’s returned nextCursor after processing its page and use it for catch-up; never derive it from live notification sequence values. An empty page is not a terminal result. Use events or query to check the final outcome.

Retain controlId for retries: identical content returns duplicate, different content returns conflict. Other receipts are accepted, applied, and rejected. Accepted means durably received; applied means the applied fact committed before delivery to the agent queue. Neither proves model consumption. Match independent input_receipt/input_claimed/input_completed/input_discarded events by inputId. Wrong, unready, or sealed Runs reject controls. Controls neither approve tools nor change permissions or budgets, and they start no concurrent Run.

Cold recovery may apply accepted controls. Applied controls without confirmed consumption are explicitly discarded rather than automatically redelivered; the durable-commit/in-memory-delivery crash window remains. Paused original inputs remain resumable under existing gates; discarded ordinary inputs do not. Control receipts do not replace Session content or full conversation reconstruction. Default v1 clients and the tool bridge retain their existing contract. See the bundled Worker regressions.

Explicit MCP login (1.1 development line) ​

Interaction requires a new Worker negotiating mcpAuthentication, explicit v2, and a dedicated handler:

python
from coremind import CoreMindClient

def show_authorization(request):
    show_temporary_link(request['authorizationUrl'])

with CoreMindClient(config, protocol_version='2.0',
                    mcp_auth_handler=show_authorization) as client:
    client.mcp_login('remote', transaction_id='login-1')
    handle = client.run('Read authorized resources')
    # 按 handle 的 runId 补读 events/query,直到真实终态。
    client.mcp_logout('remote')

The host supplies config and the temporary link UI. Wait for the Run's actual terminal state before logout. The reader only validates and queues; sync handlers run on the login caller's thread. Another thread can call mcp_cancel_auth('login-1') and wait for Node cleanup. Handler errors also cancel that transaction. Handlers must return within a bounded time.

Use the same constructor arguments with AsyncCoreMindClient and await the three authentication methods. Async handlers run on the original event loop. Cancelling the login Task cancels its handler, sends cancellation for the owned Node transaction, and joins cleanup instead of merely abandoning Python's wait. Never reuse an active transaction ID or cancel another login's transaction.

Default v1 or a missing handler fails before authentication requests with protocol_capability_missing or mcp_auth_required. Old v2 Workers still fail the exact schema fingerprint check; interaction is never silently downgraded. Dedicated authorization notifications do not enter received_events. Tokens, callback codes, and verifiers remain in Node. Python has no TokenStore seam and creates no default plaintext files. Memory credentials span Runs in one client and disappear on close; local logout does not promise remote revocation. External-service interoperability remains unverified; see the configuration boundary.

Tool discovery and Worker compatibility (1.1 development line) ​

Deferred tool configuration requires explicit Config 3. Existing Config 2 files omitting exposure keep their behavior. Python uses the existing run/chat methods; the same Node Runtime owns search and declaration installation, without another configuration process or a Python tool catalog.

Default v1 retains its original first initialize packet with no capabilities field. Only protocol_capability_missing with details exactly {schemaVersion: 1, requiredCapabilities: ['toolDiscovery'], retryInitialize: true} permits at most one retry in the same process, adding only toolDiscovery. Ordinary errors and malformed challenges are not retried, and success must acknowledge that capability. V2 declares the capability in its first packet and checks the exact schema fingerprint and capability receipt, without fallback. Older Workers must reject Config 3 before any Run; older SDKs that do not understand the challenge fail explicitly.

A search match does not approve execution. Durable installation at the next request still preserves approval and deny rules. New Runs rebuild declarations; the same Run retains its configuration-fingerprint resume gate. Optional toolDiscovery fields on context_prefix and provider_request carry only the five-field safe summary, which Python validates as a closed object. Complete catalogs and schemas never travel through public events. These are usage and protocol contracts, not claims of external interoperability or completed release qualification.

resume_run reuses an installed tool set only when the latest authoritative pause exactly binds the execution to continue. Quality retries start new executions. After a crash without that binding, existing resume admission may allow a fresh deferred declaration, never activation borrowed from the same Run/Agent/Step. Node manages this binding in private facts; it adds no Python catalog, public owners field, or complete-message-recovery promise. Configuration fingerprints, input, approval, and effect checks still apply.

Long-lived notification consumption (1.2 development) ​

Without explicit drain, received_events, received_tool_calls, received_tool_cancellations, and received_verification_requests retain the complete history. A drain takes all four current client-wide buckets, preserving original list identities, per-bucket order, and shallow Mapping references. Batches may contain several runIds and do not provide global cross-bucket interleaving. Direct concurrent external mutation of the lists is outside the SDK guarantee.

These functions retain the complete batch. The host owns retained and releases each batch after all four buckets are processed or reliably saved; do not let that host container grow indefinitely. Draining starts no Worker or RPC and can retrieve history retained before close.

python
from coremind import AsyncCoreMindClient, CoreMindClient, NotificationHistory

def collect(client: CoreMindClient, retained: list[NotificationHistory]) -> None:
    retained.append(client.drain_notifications())

async def collect_async(client: AsyncCoreMindClient,
                        retained: list[NotificationHistory]) -> None:
    retained.append(await client.drain_notifications())

The host handles batch['events'], batch['tool_calls'], batch['tool_cancellations'], and batch['verification_requests']. Correlate tools and cancellations by runId/callId/registrationId and continue to answer explicitly through submit_tool_result/submit_verification. Taking a batch is not a server acknowledgement, does not approve or execute anything, and does not prove business or callback completion. Callback queues, running handlers, overflow errors, and v1 callables remain unchanged; handlers may reenter drain. MCP authorization stays in its dedicated handler.

Async drain performs the local copy under the short lock in the calling Task, without a to_thread consumer whose destructive clear could finish after the awaiting Task is cancelled. Copying remains O(N) and temporarily occupies the calling thread/loop. This is not an automatic hard retention limit; consume regularly. Default complete retention remains unchanged without an explicit call.

Durable catch-up is separate. Explicit v2 events() neither reads nor refills the four live lists. Save each Run’s returned nextCursor after handling the page; live notification sequence values are a different domain and must not be incremented or substituted. Here consume_page is the host’s function that processes or reliably saves the complete page; failure leaves the cursor unchanged:

python
from collections.abc import Callable, Mapping
from typing import Any

def catch_up_page(client: CoreMindClient, run_id: str,
                  cursors: dict[str, int],
                  consume_page: Callable[[Mapping[str, Any]], None]) -> bool:
    page = client.events(run_id, after_sequence=cursors.get(run_id, 0), limit=100)
    consume_page(page)
    cursors[run_id] = page['nextCursor']
    return page['hasMore']

Await events() with the async client and retain the same per-Run commit order. Continue while hasMore=True; a temporarily empty page or False during execution is not terminal, so check events or query. Handle cursor_expired using the existing ProtocolError.details recovery/projection/newCursor contract; do not reset arbitrarily or borrow another Run’s cursor. Drain never advances these cursors. Durable events provide fact/event/projection recovery evidence, not guaranteed verbatim replay of every dedicated tool_call, tool_cancel, or verification_request, and do not replace pending host notifications. V1 retains inspect_run/snapshot without acquiring the v2 durable events API.

Verification ​

  1. Follow the SOP.
  2. Run the module example.
  3. Run coremind check; also run coremind eval for business outputs.
  4. Inspect failure status, budgets, traces, approvals, and checkpoints instead of judging only fluent text.
  5. For v1 results, verify Python and TypeScript expose the same six terminal states, tool effects, and approval fields; in v2, check the Projection outcome with query(runId).
  6. For the v1 tool bridge only, inject a registration failure and confirm client.pid is cleared and the temporary directory can be removed.
  7. For an explicit Loop, compare Python and TypeScript loop_state order, then call resume_run after pause and confirm committed effects do not replay.
  8. For v1, verify result['snapshot'] matches top-level runId, outcome, operation, metrics, and trace. Stop using a Worker that reports invalid_run_snapshot.
  9. For v2 host verification, catch up with events using each RunId’s returned nextCursor, confirm rejection repairs within the same Run, and distinguish control receipts from the final outcome.
  10. For v2 input controls, verify sync/async, duplicate/conflict, cancellation discard, and no queue leakage into the next Run, retaining real request and input-event evidence.
  11. For v1 automatic schemas, cover future/string int, str, bool, and existing container annotations. Confirm Node preserves existing type conversion, convertible values reach the callable in the target type, and arguments that still fail schema validation are rejected before execution. Unresolvable forward references require explicit parameters, and existing explicit schemas must still work.

Common mistakes ​

  • Do not let the model invent business rules for the owner.
  • Do not treat one successful run as stability evidence.
  • Do not use full mode to bypass configured deny rules, audit, checkpoints, effect receipts, or recovery. Path-aware file tools enforce workspace policy; arbitrary shell execution has separate platform limits.
  • Do not describe inherited providers as genuinely certified.

Worker output delivery limits ​

The bundled Worker's stdout queue plus in-flight data are limited to 64 MiB of encoded UTF-8 and 1024 messages, with at most 64 MiB per message. Required RPC responses, approval/tool/authentication notifications, and control receipts never disappear silently when the queue is full. Other existing best-effort event notifications may be dropped when the total budget is exhausted. A v2 host can catch up with durable events, using each Run's actual page nextCursor; live notification sequence is a separate counter and cannot serve as that cursor. V1 has no equivalent durable catch-up guarantee. An oversized single message still fails the transport.

Normal write/drain waits do not pause input, so approval, cancel, and tool_result messages remain processable. Hard overflow, a broken pipe, or a write error starts one shutdown: stop new input, cancel the active Run, reject pending tools and approvals, and await the existing quiescence check. EOF also waits for shutdown, then gives already accepted RPC responses and the actual output flush a shared 10-second deadline. Failure to reach quiescence is not success. When stdout is unavailable, an error response or cancel ACK cannot be guaranteed. The Worker reports delivery failure through a nonzero exit status and an output_delivery_failed stderr diagnostic; Python may raise the existing WorkerExitedError, so a JSON-RPC error carrying that code is not guaranteed.

This is a bounded transport failure contract. Runtime synchronous event callbacks have not become asynchronous backpressure. The limits exclude transient JSON encoding memory, upstream response generation, and receiver resources. The transport does not rewrite existing persisted Facts or grant permissions. Runtime still records its own cancellation and cleanup outcome; delivery failure is not fabricated as business completion and does not trigger automatic replay of potentially effectful work.

The 10-second limit bounds delivery waiting, not forced termination of a physical stream or uncooperative JavaScript. Logical close returns without an unbounded wait; an outstanding owned write retains only one error guard and its close cleanup listener until that callback or stream close settles. A timeout is not proof that all accepted operations are quiescent; related resources must not be released or reused on that assumption.

Cross-language tasks and session branches (1.4 release line) ​

CoreMindClient and AsyncCoreMindClient expose task_start(task_id, definition_id, checkpoint), task_query/task_resume/task_cancel/task_calls(task_id), task_next_wake() and task_wake(task_id, wake_id, sleep_id). Await the async methods with the same arguments. Results are complete DTOs: result["task"], result["calls"] and result["deadline"]; querying an unknown task returns task=None. These are not RunHandles, and sleeping tasks require explicit wake and resume.

Session methods are inspect_session_tree(), create_session_branch(branch_id, at), select_session_branch(branch_id) and fork_session(at), returning result["tree"]. A node reference is { "sessionId": ..., "entryId": ... }; use None only when creating an empty branch. Fork creates a new session ID; explicitly open a new client with host configuration. It copies neither Run identities nor authorization. Trees contain original messages and require host access control.

Use protocol_version="2.0", matching schema fingerprints and the negotiated durableTasks / sessionBranches capabilities. Missing capabilities, older Workers and incorrect response identities fail explicitly; there is no v1 fallback. Existing v1 behavior remains supported. Stop writers and restore complete pre-upgrade backups before rolling back new task ledgers or session selections to an older SDK.

A trusted Node host registers definitions at startup through runStdioWorker(input, output, { tasks: { definitions, documentSchemas?, runtime? } }); Python launches it using the existing worker_command option. The default bundled Worker supports session navigation but has no task registry, so task requests report protocol_capability_missing. Requests carry definition IDs and JSON business data, never executable modules, source, Python callables or credential options. Keep secrets out of checkpoints.

The optional task runtime provides existing tools, approval callbacks, environment and authorityVersion; config/configDir come from initialization. Trust in registered host code grants neither configured project-code imports nor tool permission. trust_project_code remains independent and its value is bound into task authority identity. Update the host authorityVersion for external policy, closure or credential-routing changes. All model/tool execution retains the original Node Runtime, Run budgets, timeouts, cancellation and effect-recovery gates.

Import ProtocolV2SessionClient from coremind-ai or coremind-protocol. Construct it with { sessionId, initialized, request }; the existing host transport's request(method, params) returns the RPC result or throws the original structured error. .task({ action: "query", taskId }) and .session({ action: "inspect" }) bind the session and validate request/response identity. This wrapper owns no process, store or scheduler.

Errors keep the original Error Contract classification. ProtocolError.details adds operation/action/sessionId/taskId; TaskExecutionError/TaskCallError subcodes such as task_definition_unknown, task_authority_mismatch and task_cancelled appear in taskCode, not as new top-level classifications. While a phase is active, queries and explicit task cancellation remain available; competing execution, navigation and ordinary Runs are rejected. RPC failure or process exit does not imply rollback: preserve records, query first and never blindly replay unknown effects.

After building, run python -X utf8 examples/modules/embed-coremind-python/tasks.py for sync/async A→process close→reopen→wake→B and cancellation. python/tests/test_session_management.py uses real Node processes to compare TS/Python identities, results and errors, including exit after Run-result persistence but before task-phase commit without repeating tool effects. It uses no real Provider. There is no second Python runtime, background scheduler or external exactly-once guarantee.

Last updated:

Released under the MIT License.