Repository navigation
Description
Proposal: TypeScript SDK — @stacklok/mecatl (browser + Node)
Why
mecatl has three client surfaces (gRPC, HTTP/SSE, ACP) but no client library: every consumer outside this repo hand-rolls the Converse choreography (first-frame prompt, ask→approval correlation, terminal-event detection, reconnect). A TypeScript SDK makes the harness embeddable the way the Claude Agent SDK makes Claude Code embeddable — but as our own thing, shaped by mecatl's actual domain (sessions as aggregates, one stream = one run, deny-dominant permissions, teams/subagents/skills/schedules), not a feature-parity clone. Goal: every feature of the harness reachable from TS, day one.
Validation case: Studio (#618). The experimental web UI had to hand-build exactly the layers this SDK would own: a typed protocol seam over raw daemon JSON (26 decoder tests), event translation with "unknown kinds render as notices, never silent drops" (independently converging on this proposal's unknown-kind passthrough rule), the schedule protojson-request/stdlib-response round-trip, capability-gated actions, and hand-wired multimodal parts. Two of Studio's explicit non-goals are server-side holes this proposal closes (enablers 3 and 4 below). A future UI written on this SDK starts where Studio's protocol layer ends.
Architecture (proposed, discussed and settled)
Audience & runtimes. Node backends/scripts AND browsers from day one. Node gets the full surface; browsers get everything a browser can physically do (bidi streaming and hosting callback tools are structurally Node-only).
Transport: dual, behind one abstraction, zero new wire formats.
- Node → real gRPC against the existing
grpc-golistener (Connect-ES gRPC transport): bidiConverse, mid-runSteer, the works. - Browser → the existing HTTP/SSE surface (
POST /v1/sessions/{id}/prompt+ SSE, control POSTs for approve/cancel). - Both share one generated type layer (
protobuf-esvia buf fromcontracts/proto/, emitted bytask generatenext tocontracts/gen/so proto and SDK can never skew). gRPC and SSE already share the exact protojsonEventshape, so event types are written once. - The browser transport is proxy-friendly by design (the Studio lesson: production browsers reach mecated through a BFF doing server-side bearer injection and Origin/CSRF gating, never directly): configurable base URL, pluggable
fetch, and a cookie/same-origin credential mode — no assumption that a bearer token lives in JS.--cors-origins(enabler 2) is the local-dev path; the BFF is the production path.
Layering. Two layers, both public:
@stacklok/mecatl/gen— generated clients + types, 100% RPC coverage by construction; the escape hatch for anything the ergonomic layer hasn't earned yet.- The ergonomic layer — hand-written where real protocol choreography lives:
connect()/spawn()→Client;client.sessions.create()→Session(resume/fork/transcript);session.run(prompt)→Run(async iterator of typed events,approve(),steer(),cancel());session.attach()(replay the durable event log, then follow live — page reloads and second tabs rejoin running sessions); a connection-status primitive (online/offline/reconnect events — Studio's 5s-poll "connection authority" generalized); typed multimodal prompt parts; teams; plan approval. Inventory/CRUD RPCs (models, skills, schedules, learning, storage ops) start as thin typed passthroughs that absorb wire warts (e.g. the schedule protojson/stdlib encode asymmetry) once, centrally. - Plus
query()— one-call sugar (spawn/create/run/close) for scripts and first-contact examples.
Spawn-or-connect (Node). spawn() launches a preinstalled mecated on a private UNIX socket and owns its lifecycle (readiness, shutdown) — the cmd/mecatui hosting pattern. connect() dials any running mecated (URL, --auth-token bearer, TLS) — first-class, since hosted deployments (mecated/mecak8s on Kubernetes) are a primary target. v1 requires the binary on PATH or binaryPath; auto-download is a named follow-up gated on binary release artifacts (today's release pipeline ships ko images to GHCR only).
Custom tools (v1, Node-only). The tool("name", schema, handler) helper hosts the user's callbacks as a local streaming-HTTP MCP server and registers it into the session. The service seam exists (Service.CreateSessionWithMCP) — only ACP exposes it on the wire today, so this needs server enabler 1 below.
Typed events. A hand-crafted discriminated union over the event taxonomy (switch (ev.kind) narrows; payloads non-null where the kind guarantees them), with an unknown-kind passthrough arm ({ kind: string, raw: Event }) preserving the wire's forward-compat contract. A kind-parity guard test in this repo's CI walks engine/session/event.go against the union so a new event kind fails CI instead of silently landing in the unknown arm.
Permissions. Both styles: an onPermissionAsk callback option (return allow_once / allow_always / deny; absent callback = never silently allow) and the raw permission.ask event + run.approve() for apps routing asks to a UI.
Packaging. One package, @stacklok/mecatl, subpath exports: . (isomorphic core + SSE transport), ./node (spawn, gRPC transport, tool()), ./gen. Conditional exports keep Node code out of browser bundles.
Location & release. In-repo at sdk/typescript/ (peer of provider/*; the proto is the source of truth and M2 touches proto + server + SDK in one PR). Independent semver starting v0.x, released via sdk/typescript/vX.Y.Z tags → CI npm publish with provenance (the existing v* image trigger never fires on them — the provider/<name>/vX.Y.Z precedent). Version skew is detected at connect time via CreateSessionResponse.ServerCapabilities feature bits — fail loudly on a missing capability, never compare version strings. The same typed capability accessor serves UIs gating actions (Studio's capability-driven rename/delete pattern).
Testing. Offline-only, per repo culture: CI builds mecated from the same checkout and the suite spawns it with --mock — e2e over both transports from Node (the SSE transport is isomorphic, so its logic is covered without a browser), plus unit tests for pure logic (event union, ask correlation, backoff) and the parity guard. Real-browser (Playwright) smoke is a follow-up.
Server enablers (small, land with the SDK milestones)
mcp_serverson session create — gRPCCreateSessionRequest+ HTTP create body, streaming-HTTP specs only (reuse ACP's validation; the no-stdio-MCP invariant holds), wired to the existingCreateSessionWithMCP.task generate.--cors-originson mecated — explicit origin allowlist + preflight on the HTTP mux (no wildcard-with-credentials). Production guidance stays "own reverse proxy"; the flag exists so local dev (Vite on :5173 → mecated on :8080) works at all.- HTTP/SSE live-tail mirror —
GET /v1/sessions/{id}/livemirroring the gRPCStreamSessionLivesubscription (same live-wire redaction discipline). Named by Studio (feat(studio): Web UI workspace #618) as the missing piece for live re-attach from a browser; powerssession.attach(). - HTTP steer endpoint —
POST /v1/sessions/{id}/steerrouting into the live run's steer path, closing the "mid-run steer is gRPC-only (v1)" gap so browser clients match Node.
Milestones
- M1 — Foundation:
sdk/typescript/scaffolding; buf → protobuf-es codegen wired intotask generate; both transports (browser transport proxy-friendly: baseUrl, pluggable fetch, cookie-mode auth);Client/Session/Runcore with approvals + steer + cancel + typed multimodal parts; event union + parity guard; offline e2e harness (mecated --mock) + CI job. ADR for the SDK architecture lands here. - M2 — Server enablers:
mcp_serverswire field;--cors-origins; the SSE live-tail mirror; the HTTP steer endpoint. - M3 — Node capabilities:
spawn()lifecycle;tool()MCP host;onPermissionAsk;query()sugar. - M4 — Full surface + ship:
session.attach()(replay-then-live) and the connection-status primitive; typed passthroughs for the remaining RPC families (teams run/roster, schedules, skills/learning/reflection, dream plans, storage ops, MCP inventory); examples;user-docs/page; npm publish workflow; firstsdk/typescript/v0.1.0.
Follow-ups (explicitly out of v1)
- Binary release artifacts (multi-platform, signed) → npm auto-download for
spawn(). - Playwright real-browser smoke suite.
- Framework bindings (
@stacklok/mecatl/reacthooks over the async-iterator core) — the core stays framework-agnostic (async iterators +AbortSignaleverywhere) so bindings are thin wrappers. - Python SDK (port the validated shape).
- Wire-level client hooks (hooks stay operator-deployed subprocesses for now; the permission callback covers the main interception need).
- Migrating Studio (feat(studio): Web UI workspace #618) onto the SDK — its protocol seam becomes an SDK consumer, the natural proof of the design.
Non-goals
- Feature parity with the Claude Agent SDK — inspiration only; the API mirrors mecatl's domain.
- A fourth wire protocol — the SDK rides the existing gRPC + HTTP/SSE surfaces.
- Browser support for structurally Node-only features (spawn,
tool()hosting).
Activity
[-]design(sdk): TypeScript SDK — @stacklok/mecatl (browser + Node)[/-][+]TypeScript SDK for mecatl (browser + Node)[/+]docs: ADRs 0243-0245 + acceptance plan for the SDK server enablers
docs: ADRs 0248-0250 + acceptance plan for the SDK server enablers (#822
samuv commentedon Sep 11, 2026
Status: delivered
The TypeScript SDK baseline is complete and published as
@stacklok/[email protected]on GitHub Packages.#821 contains the implementation history. ADRs 0279, 0288, 0292, 0304, and
0313 record the final architecture and release decisions, including the
package name and interim registry.
The remaining work has moved to bounded follow-ups:
v0.1.0release and its release criteria.follow-ups.
Closing this research and delivery issue as completed.