# Python & TypeScript SDKs

Drive local ct runs and the hosted CircuitTwin API from typed Python and TypeScript test suites without parsing raw terminal output.

## Overview

Both official SDKs wrap the same deterministic wire verdicts (`pass`, `fail`, `inconclusive`, `error`, `skipped`, `no_verdict`), structured diagnostics, and hosted workspace APIs as the [ct CLI](https://circuittwin.ai/docs/cli). Pick the Python package when your verification harness runs under `pytest`, or the TypeScript package for Node.js automation and web tooling.

| SDK        | Package             | Runtime                                  | Highlights                                                                                                                                                                                                                                                  |
| ---------- | ------------------- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Python     | circuittwin         | Python 3.10+ (zero runtime dependencies) | Sync & async clients (CircuitTwinClient, AsyncCircuitTwinClient), WebhooksResource, SharesResource, verify\_webhook\_signature, runs.vcd()/bus()/perfetto(), 5-format FirmwareFormat, pytest helpers, and LCOV coverage export                              |
| TypeScript | @circuittwin-ai/sdk | Node.js 22+ (ESM-only, root export)      | Full-parity OpenAPI 3.1 REST & SSE client (createClient / createClientFromEnv, boards, twins, scenes, matrices, webhooks, shares, verifyWebhookSignature, runs.vcd()/bus()/perfetto(), 5-format FirmwareFormat, account), and root-exported testing helpers |

## Python SDK (circuittwin)

The Python SDK ships with zero third-party runtime dependencies (standard library only, PEP 561 `py.typed`) and reaches full hosted API parity alongside `@circuittwin-ai/sdk`:

- **Sync & async clients**: use `CircuitTwinClient` for synchronous scripts or `AsyncCircuitTwinClient` for `asyncio` harnesses. Both read `CT_TOKEN`, `CT_SERVER`, and `CT_ORGANIZATION` automatically.
- **Observability, webhooks & shares**: download hosted captures via `runs.vcd()`, `runs.bus()`, and `runs.perfetto()` (`provisional`), manage workspace endpoints with `WebhooksResource` (`client.webhooks`) and `SharesResource` (`client.shares`), and validate incoming webhook headers with `verify_webhook_signature`.
- **5-format `FirmwareFormat`**: upload and run `elf`, `hex`, `bin`, `uf2`, and `srec` images with typed format literals.

Install it in your test virtual environment alongside `pytest`:

terminal

```
pip install circuittwin
pip install pytest   # optional, for pytest helpers
```

### Run firmware from Python

run\_smoke.py

```
from circuittwin import CircuitTwinClient, assert_run_passed

with CircuitTwinClient() as client:  # reads CT_TOKEN + CT_SERVER
    uploaded = client.firmware.upload("build/app.elf")
    created = client.runs.start(
        board_id="nucleo-f767zi",
        firmware_id=uploaded.firmware["id"],
        assertions=[
            {"kind": "marker", "pass": "READY"},
            {"kind": "no_fault"},
        ],
        limits={"maxVirtualTimeNs": 5_000_000_000},
    )
    run = client.runs.wait(created.run["id"])
    assert_run_passed(run)  # requires verdict == "pass" (inconclusive != pass)
    print(client.runs.console(run["id"]))
```

### pytest helpers

Use the built-in helpers (`load_local_ct_run`, `assert_run_passed`, `assert_no_bus_errors`, plus declarative `PinStimulus`, `SensorStimulus`, and `ScriptedPeer` builders) to test unmodified ELF, HEX, UF2, SREC, raw BIN, or ESP-IDF `build/` images inside standard Python test suites:

tests/test\_firmware.py

```
from circuittwin import (
    assert_no_bus_errors,
    assert_run_passed,
    load_local_ct_run,
)

def test_sensor_boot():
    result = load_local_ct_run(
        "build/app.elf",
        "nucleo-f767zi",
        devices=["INA226@I2C1:0x40"],
        until="SENSOR_READY",
        max_ms=3000,
    )
    assert_run_passed(result)
    assert "INA226 OK" in result.get("console", {}).get("vcp", "")

def test_scene_clean(scene_report):
    assert_run_passed(scene_report)
    assert_no_bus_errors(scene_report)
```

Failed assertions include the wire verdict (`pass`, `fail`, `inconclusive`, or `error`), failed assertion details, console tail, and any unmodelled-register diagnostics directly in the `pytest` traceback.

### LCOV & Cobertura coverage export

Fetch structural coverage collected during matrix runs as standard `lcov.info` (or raw JSON including provisional 7-ISA object-code MC/DC) via `client.matrices.coverage(matrix_id, fmt="lcov")` for GitHub, GitLab, Codecov, or SonarQube dashboards. To generate Cobertura XML (`cobertura.xml`), run `ct compliance coverage --format cobertura` from the CLI. Plain LCOV and Cobertura exports work on every plan (including Free); signed compliance evidence packs and tool qualification kits are on Team and Enterprise ([Compliance support](https://circuittwin.ai/docs/compliance)).

export\_coverage.py

```
from pathlib import Path
from circuittwin import CircuitTwinClient

with CircuitTwinClient() as client:
    lcov = client.matrices.coverage(matrix_id, fmt="lcov")
    Path("out/lcov.info").write_text(lcov, encoding="utf-8")
```

## TypeScript SDK (@circuittwin-ai/sdk)

The TypeScript SDK ships as an **ESM-only** package (`"type": "module"`, root `.` export only) targeting **Node.js 22+** with full OpenAPI 3.1 parity, typed helper functions, live Server-Sent Events streaming, and Vitest/Jest assertion helpers:

- **Client factories & resource helpers**: create a typed `CircuitTwinClient` with `createClient({ baseUrl, token })` or `createClientFromEnv()`, then call root-exported helpers such as `getMe`, `createRun` / `runs.start`, `getRun`, `waitForRun`, `runs.vcd` / `runs.bus` / provisional `runs.perfetto`, `runSuite`, `runTestMatrix`, `getTestMatrixCoverage`, `structuralCoverageToLcov`, `listBoards`, `searchCatalog`, `createScene`, `createWebhook`, `rotateWebhookSecret`, and `createShare`.
- **Webhook verification & 5-format `FirmwareFormat`**: verify `X-CircuitTwin-Signature` headers with async `verifyWebhookSignature({ secret, timestamp, signature, body })` and upload `elf`, `hex`, `bin`, `uf2`, or `srec` images via `uploadFirmware`.
- **Live streaming & root testing helpers**: `streamRunEvents(client, runId)` consumes typed SSE run updates in real time, and root exports `assertRunPassed`, `assertNoBusErrors`, and `circuitTwinMatchers` integrate directly with Node’s test runner, Vitest, or Jest.

terminal

```
npm install @circuittwin-ai/sdk
```

ci-check.ts

```
import {
  assertRunPassed,
  createClient,
  createRun,
  createShare,
  getMe,
  getRun,
  streamRunEvents,
} from '@circuittwin-ai/sdk';

const client = createClient({
  baseUrl: process.env.CT_SERVER ?? 'https://app.circuittwin.ai',
  token: process.env.CT_TOKEN,
});

const me = await getMe(client);
console.log('Workspace:', me.organization.name);

const { run } = await createRun(client, {
  boardId: process.env.CT_BOARD_ID!,
  firmwareId: process.env.CT_FIRMWARE_ID!,
  captureVcd: true,
  captureBus: true,
  assertions: [
    { kind: 'marker', pass: 'READY' },
    { kind: 'no_fault' },
  ],
  limits: { maxVirtualTimeNs: 5_000_000_000 },
});

for await (const frame of streamRunEvents(client, run.id)) {
  if (frame.event === 'end') break;
}

const completed = await getRun(client, run.id);
assertRunPassed(completed); // requires verdict === "pass"

const share = await createShare(client, {
  kind: 'run',
  targetId: completed.id,
  expiresIn: '24h',
});
console.log('Shareable read-only link:', share.url);
```

## Authentication

Both SDKs reuse the same authentication paths as `ct`:

- **Developer machines**: run `ct login --device` once to sign in through your browser using the RFC 8628 device-code flow ([Install & sign in](https://circuittwin.ai/docs/install)).
- **CI and headless automation**: export `CT_SERVER=https://app.circuittwin.ai` and a scoped `CT_TOKEN=ctk_...` secret ([Access tokens](https://circuittwin.ai/docs/tokens)).

## Next

- [Quickstart](https://circuittwin.ai/docs/quickstart): scaffold a project with `ct init` and run your first smoke test
- [ct CLI reference](https://circuittwin.ai/docs/cli): subcommands, flags, and exit codes
- [Test your firmware](https://circuittwin.ai/docs/testing): suites, fault matrices, run comparison, and display previews
- [Test in CI](https://circuittwin.ai/docs/ci): GitHub Actions and GitLab CI/CD workflows
