Wait for queued recordings before exporting or exiting, and inspect cleanup diagnostics separately from your application's original error. Async cancellation stops waiting; it does not prove native rollback.
When to use this
Use this when an async application needs to drain observations, close owners and preserve cleanup diagnostics before exiting.
Install the matching API preview
These examples use the API 2 preview, not names promised by the public RC5 release. Existing RC5 entry points remain available. The Python wheel below is verified on Windows x64; it is not a cross-platform release.
python -m pip install https://docs.soterias.io/downloads/api-preview/soterias_local-0.1.0rc5%2Bapi2-cp311-abi3-win_amd64.whlnpm install https://docs.soterias.io/downloads/api-preview/soterias-core-0.1.0-rc.5-api.2.tgz
npm install --save-dev typescript@5.8.3 @types/node@24Python imports soterias. TypeScript imports @soterias/core. Use Python 3.11+ for this wheel and Node 22.23.4+ for these examples. For a .mts file, compile with npx tsc example.mts --target ES2022 --module NodeNext --moduleResolution NodeNext --skipLibCheck, then run the emitted .mjs file.
Before you run
This program creates its own local example state. After installing the matching SDK, save the chunks in order and run python example.py or compile and run example.mts. No credentials, model or service are required.
Application walkthrough
Choose Python or TypeScript. Create example.py or example.mts and append that language's chunks in order. Each language forms one complete program; indentation and open blocks carry across chunks.
Import the packages
Import the SDK and standard-library helpers. These are the real package exports used by the executable program.
"""A complete local application: Python chunks on the feature pages use this source."""
import asyncio
import json
from pathlib import Path
import sqlite3
import tempfile
from soterias import Soteriasimport assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { Soterias } from '@soterias/core';Create an application and an ordinary database
Soterias observes this existing code; it does not secure these direct writes.
# %% Create an application and an ordinary database
# Soterias observes this existing code; it does not secure these direct writes.
root = Path(tempfile.mkdtemp(prefix="soterias-invoices-"))
database = sqlite3.connect(root / "invoices.sqlite3")
database.execute("CREATE TABLE invoices (id INTEGER PRIMARY KEY, cents INTEGER)")
sdk = Soterias(workflow="invoices", directory=root / "metrics")
def post_invoice(cents):
row = database.execute("INSERT INTO invoices(cents) VALUES (?)", (cents,))
database.commit()
return {"id": row.lastrowid, "cents": cents}// %% Create an application and an ordinary database
// Soterias observes this existing code; it does not secure these direct writes.
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'soterias-invoices-'));
const database = new DatabaseSync(path.join(root, 'invoices.sqlite3'));
database.exec('CREATE TABLE invoices (id INTEGER PRIMARY KEY, cents INTEGER)');
const sdk = new Soterias({ workflow: 'invoices', directory: path.join(root, 'metrics') });
function postInvoice(cents: number) {
const row = database.prepare('INSERT INTO invoices(cents) VALUES (?)').run(cents);
return { id: Number(row.lastInsertRowid), cents };
}
try {Observe synchronous and asynchronous calls
Repeating the same input still runs the write twice.
# %% Observe synchronous and asynchronous calls
# Repeating the same input still runs the write twice.
first = sdk.invoke(post_invoice, 1500)
second = sdk.invoke(post_invoice, 1500)
assert first["id"] != second["id"]
tracked_post = sdk.track(post_invoice)
assert tracked_post(500)["cents"] == 500
async def review_invoices():
await asyncio.sleep(0)
return database.execute("SELECT SUM(cents) FROM invoices").fetchone()[0]
async def finish():
try:
total = await sdk.ainvoke(review_invoices)
assert total == 3500
tracked_review = sdk.track_async(review_invoices)
assert await tracked_review() == total
await sdk.flush()
summary = sdk.summary()
assert summary["counts"]["raw"] == 5 // %% Observe synchronous and asynchronous calls
// Repeating the same input still runs the write twice.
const first = sdk.invoke(postInvoice, 1500);
const second = sdk.invoke(postInvoice, 1500);
assert.notEqual(first.id, second.id);
const trackedPost = sdk.track(postInvoice);
assert.equal(trackedPost(500).cents, 500);
const total = await sdk.invokeAsync(async () => {
await Promise.resolve();
return database.prepare('SELECT SUM(cents) AS total FROM invoices').get()!.total;
});
assert.equal(total, 3500);
const trackedReview = sdk.trackAsync(async () => total);
assert.equal(await trackedReview(), total);
await sdk.flush();
const summary = sdk.summary();
assert.equal(summary.counts.raw, 5);Inspect and export local measurements
Each export is explicit; nothing is uploaded.
# %% Inspect and export local measurements
# Each export is explicit; nothing is uploaded.
for name, export in (
("runs.json", sdk.metrics.export_json()),
("runs.csv", sdk.metrics.export_csv()),
("runs.otlp.json", sdk.metrics.export_otlp()),
):
(root / name).write_bytes(export.data)
print(json.dumps({"status": "PASS", "total_cents": total,
"runs": summary["counts"]["raw"], "directory": str(root)}))
finally: // %% Inspect and export local measurements
// Each export is explicit; nothing is uploaded.
for (const [name, page] of [
['runs.json', sdk.metrics.exportJson()],
['runs.csv', sdk.metrics.exportCsv()],
['runs.otlp.json', sdk.metrics.exportOtlp()],
] as const) fs.writeFileSync(path.join(root, name), page.data);
console.log(JSON.stringify({ status: 'PASS', total_cents: total,
runs: summary.counts.raw, directory: root }));
} finally {Close the runtime and database
Wait for pending recordings before leaving the process.
# %% Close the runtime and database
# Wait for pending recordings before leaving the process.
await sdk.close_async()
database.close()
asyncio.run(finish()) // %% Close the runtime and database
// Wait for pending recordings before leaving the process.
await sdk.closeAsync();
database.close();
}MCP composition
This complete stdio server calls this feature's real SDK operation. Its bounded tool inputs cannot replace host-selected trust, checkpoint or storage paths. Save it as mcp.mjs and configure your MCP client to launch node mcp.mjs. Public data inputs use the same environment settings as the application program. The code is a custom application tool, not a newly claimed built-in Soterias endpoint.
Install the matching adapter with npm install https://docs.soterias.io/downloads/api-preview/soterias-mcp-server-0.1.0-rc.5-api.2.tgz. Its SDK peer dependency shares the same native class identities as your installed preview.
mcp.mjs
Create mcp.mjs and append these chunks in order. Together they form one complete program; indentation carries across chunks.
Step 1
Import the SDK and standard-library helpers. These are the real package exports used by the executable program.
import { Soterias, observe, canonicalize, Metrics, audit, HistoricalPolicyInputs } from '@soterias/core';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import * as z from 'zod/v4';
// Trusted startup: paths, trust and credentials are fixed by the host.
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'soterias-mcp-'));
const sdk = new Soterias({workflow: 'invoice-tools', directory: path.join(root, 'metrics')});
const sum = input => input.cents.reduce((a, b) => a + b, 0);
// Agent input is bounded data. It cannot replace host configuration or trust.
const handle = serveStdio(() => {
const server = new McpServer({name: 'soterias-lifecycle', version: '1.0.0'});
server.registerTool('invoice_async', {
description: 'Use lifecycle through the host-selected native SDK.',
inputSchema: z.object({cents: z.array(z.number().int().min(0).max(1000000)).max(100)}).strict(),
}, async input => {
try {
const result = await (async () => {
const total = await sdk.invokeAsync(async value => sum(value), input);
await sdk.flush();Step 2
Finish outstanding work and release owned resources. Cleanup errors must not silently replace an existing application error.
return {total_cents: total, runs: sdk.summary().counts.raw};
})();
return {content: [{type: 'text', text: JSON.stringify(result, (_key, value) => typeof value === 'bigint' ? value.toString() : value)}]};
} catch {
return {isError: true, content: [{type: 'text', text: 'feature_request_refused'}]};
}
});
return server;
}, {maxSubscriptions: 0});
process.stdin.once('end', () => {
void (async () => { await handle.close(); await sdk.closeAsync(); })();
});Test the tool over a real MCP connection
Save this client next to mcp.mjs, then run node client.mjs. It starts the host, calls the actual feature tool and closes the connection. It does more than list the tool catalog.
client.mjs
Create client.mjs and append these chunks in order. Together they form one complete program; indentation carries across chunks.
Step 1
Import the SDK and standard-library helpers. These are the real package exports used by the executable program.
import { Client } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
import { fileURLToPath } from 'node:url';
const client = new Client({name: 'feature-example', version: '1.0.0'});
try {
await client.connect(new StdioClientTransport({
command: process.execPath,
args: [fileURLToPath(new URL('./mcp.mjs', import.meta.url))],
env: Object.fromEntries(Object.entries(process.env).filter(([, value]) => value !== undefined)),
}));
const result = await client.callTool({name: 'invoice_async', arguments: {cents: [500, 1000]}});
if (result.isError) throw new Error('Feature request refused');
console.log(JSON.stringify(result));
} finally { await client.close(); }Check the result
The application program prints a JSON result and preserves native refusals. For protected operations inspect status and target_observed: transport success does not imply a completed effect. The pure examples contain assertions for their exact expected values. Successful startup is not proof of production enrollment, a physical human review or current authority.
Put it into a workflow
Use the AML walkthrough for protected document reads, reviewed writes and signed outcome checks. Use multi-agent workflows for personal and enterprise orchestration. Keep each agent's proposals separate from operator authority.