SSyncropel Docs

Programmatic agents, agents that write code

Connect Syncropel to agents that do their work by writing and running code. Many operations take one round trip to the model. Works with any model that can run code, in any sandbox.

What this is

In this pattern an AI agent gets a task done by writing a short program with a typed SDK and running it in a sandbox. The program does the work: several writes, queries and transformations. Only the final result goes back into the agent's context.

Compare it with traditional MCP, where the agent calls each tool one at a time and each result passes through the model:

  • Traditional MCP: 10 tool calls = 10 round-trips through the model's context = 10× token cost
  • Programmatic: 10 SDK calls inside one sandbox run = 1 round-trip = 1× token cost

Several teams have written about this approach. Anthropic reports 98.7% token savings for multi-step workflows, and Cloudflare reduced a 2,500-endpoint API to 2 sandboxed code tools. The idea is the same: a typed SDK, code execution, and many operations per model turn.

Why the SDKs fit

You don't need anything extra. The Syncropel SDKs (@syncropel/sdk on npm, syncropel on PyPI) are typed APIs with stable behavior, and they handle network errors without crashing your program.

The main calls are emit, query, queryThread, intend and fulfill, plus 11 Ref.* helpers for canonical references.

When an agent runs code, you give it the SDK. It writes TypeScript, the sandbox runs it, and the SDK handles talking to Syncropel.

Prerequisites

You need an agent setup that can run code. Examples:

  • Anthropic Claude with code_execution (via the API's built-in code tool)
  • OpenAI with code interpreter (supports Python; use the syncropel PyPI package)
  • Edge runtimes that can make HTTP requests
  • Custom Python/Node sandbox you control (Docker, Firecracker, gvisor)
  • Anything else that can run code. The SDK is plain HTTP and JSON.

And a Syncropel workspace reachable from the sandbox's network:

  • Local: http://localhost:9100 if the sandbox runs on the same machine
  • Remote: https://your-host.example.com:9100 with a bearer token

Quickstart: Python with a model that runs code

A common combination: a model with code execution and the syncropel PyPI package. This example uses Anthropic's API. It works the same way for any other provider with a code-execution tool; only the call to the model changes.

1. Install in your agent's Python sandbox

Usually through the sandbox's package manager or a prepared environment:

pip install syncropel anthropic

2. The agent writes this (or you give it a starter template)

The Python SDK is async: wrap the work in an async function and asyncio.run it, or use emit_sync in synchronous code. Every record needs a body.kind. The SDK checks it before the network call, so a bad kind fails right away.

import asyncio
import os
from syncropel import Client, Identity

async def main():
    async with Client(
        endpoint=os.environ.get("SYNCROPEL_URL", "http://localhost:9100"),
        identity=Identity.static(os.environ.get("AGENT_DID", "did:sync:agent:investigator")),
        api_key=os.environ.get("SPL_TOKEN"),
    ) as client:
        # Open a thread with an INTEND
        opened = await client.intend(goal="Investigate auth bug #342")
        thread = opened.thread

        # Each step of the work becomes a DO record
        for step in [
            "Read the auth module source",
            "Identified the token-refresh race condition",
            "Wrote a failing test for the race",
            "Applied fix: wrap refresh in mutex",
            "Test now passes",
        ]:
            await client.emit(
                act="DO",
                kind="bug.investigation.step",
                body={"description": step},
                thread=thread,
            )

        # Record the finding and the lesson learned
        await client.emit(
            act="KNOW",
            kind="bug.investigation.finding",
            body={"topic": "Root cause was lock-free optimistic refresh retry loop."},
            thread=thread,
        )
        await client.emit(
            act="LEARN",
            kind="engineering.insight.concurrency",
            body={"insight": "Token refresh in concurrent contexts must be mutexed"},
            thread=thread,
        )

        # Read back and print a summary: the only output the model sees
        records = await client.query_thread(thread=thread)
        print(f"Bug #342 investigation complete — {len(records)} records in thread {thread}")

asyncio.run(main())

The agent's context gets one line of output instead of 5 to 7 tool calls' worth of back-and-forth. In fully synchronous code (most code-interpreter sandboxes, scripts), replace every await client.emit(...) with client.emit_sync(...): same signature, no event loop needed.

3. The agent returns the summary and its reasoning

I investigated bug #342 and found the root cause: the auth module's
token refresh logic had a race condition in concurrent refresh attempts.
I applied a mutex around the refresh path, wrote a failing test first,
verified it passes, and recorded 8 records in thread bug-342.

It is efficient and auditable: the user can run spl thread records bug-342 to see exactly what the agent did.

Quickstart: TypeScript, edge runtime

import { Client, Identity } from "@syncropel/sdk";

interface Env {
  SYNCROPEL_URL: string;
  SPL_TOKEN: string;
  AGENT_DID: string;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const client = new Client({
      endpoint: env.SYNCROPEL_URL,
      identity: Identity.static(env.AGENT_DID),
      apiKey: env.SPL_TOKEN,
    });

    const threadId = "th_webhooks";

    // Record the incoming event
    await client.emit({
      act: "DO",
      kind: "webhook.event.received",
      body: {
        description: "Received webhook",
        event: request.headers.get("x-event"),
        path: new URL(request.url).pathname,
      },
      thread: threadId,
    });

    // Your own logic; Syncropel isn't involved here
    const result = await processWebhook(request);

    // Record the outcome
    await client.emit({
      act: "KNOW",
      kind: "webhook.event.processed",
      body: { topic: "processed", result_code: result.code },
      thread: threadId,
    });

    return new Response(JSON.stringify({ ok: true }), {
      headers: { "content-type": "application/json" },
    });
  },
};

async function processWebhook(request: Request) {
  return { code: "ok" };
}

Deploy with your edge runtime's CLI. Each webhook writes 2 records, with no model calls at all.

Design patterns

Pattern: long-running agent with session checkpoints

For agents that run for hours or days, use session checkpoints to save progress:

# Save at end of each work session
result = await client.emit(
    act="LEARN",
    kind="agent.session.checkpoint",
    body={
        "summary": "Completed auth refactor; next: migration tests",
        "learnings": ["mutex pattern worked", "refactor touched 14 files"],
        "next_steps": "Write migration tests",
    },
    thread=session_thread,
)

The next session picks up by reading the latest checkpoint on the thread, without carrying the whole history in its context.

Pattern: fan-out with independent review

When the agent delegates subtasks to other agents, open a parent thread then one INTEND per subtask:

# Parent agent creates subtasks
for worker in ["agent-a", "agent-b", "agent-c"]:
    child = await client.intend(goal=f"Review module X for {worker}")
    # Each worker reads child.thread, does the work,
    # and writes records on that thread. The parent collects
    # them with query_thread to decide when all are done.

This uses Syncropel's fan-out.

Pattern: trust-aware behavior

The SDK doesn't read trust directly; use the HTTP API instead:

import httpx

r = httpx.get(
    f"{endpoint}/v1/trust",
    headers={"Authorization": f"Bearer {api_key}"},
)
scores = r.json()["data"]
mine = [s for s in scores if s["actor"] == my_did and s["domain"] == "code"]
if not mine or mine[0]["effective_trust"] < 0.5:
    # Low trust: write an INTEND with body.awaits = "actor_decision"
    # so a human reviews before proceeding
    pass

Error handling

The SDK keeps going on network errors. Every emit returns an EmitResult:

result = await client.emit(...)
if not result.success:
    # Network error: log locally, retry later, but don't crash
    print(f"Syncropel unreachable: {result.error}")

This is intentional: your agent's main work shouldn't crash because a record failed to reach your workspace.

A malformed body.kind or an invalid act does raise an error, because those are mistakes in your code.

Authentication

Same as everywhere:

client = Client(
    endpoint="https://your-host.example.com:9100",
    identity=Identity.static("did:sync:agent:me"),
    api_key=os.environ["SPL_TOKEN"],  # from ~/.syncro/token or env
)

For a local workspace with sign-in off (testing only), omit api_key.

For cloud agents, store the token in your platform's secret manager:

  • Edge runtimes: store SPL_TOKEN as a secret with your platform's CLI
  • AWS Lambda: AWS Secrets Manager
  • Anthropic API: encrypted user metadata

See Authentication & Service Accounts for how to create a scoped token.

When this pattern is the wrong choice

  • You want a record of what the agent did without writing code → Pattern 1 (MCP), which is simpler to set up
  • You don't control the agent's runtime (an off-the-shelf AI client) → Pattern 1 or 2
  • You want the agent to see each tool result (for example, "what did the query return?") → traditional MCP lets the agent reason over each result; the programmatic pattern is better when the code handles results itself
  • You only write 1 or 2 records per session → the extra setup isn't worth it

Further reading

On this page