@acid-cat/core-ts
@acid-cat/core-ts is an AcidCat core in plain TypeScript. You define capabilities and events once, and the package serves them through the TypeScript, HTTP, MCP, CLI and WebMCP surfaces. It is one implementation of the AcidCat specification.
Use it if you want AcidCat without Effect. A capability is an async function, and an event is an async iterable. Validate inputs with any Standard Schema library, such as Zod, Valibot or ArkType. The application writes its own catalog from its code.
pnpm add @acid-cat/core-ts
Quick start
A command line with one command:
import { cliMain, defineApp, defineCapability, ok } from "@acid-cat/core-ts";
import type { ToJsonSchema } from "@acid-cat/core-ts";
import { z } from "zod";
const lamp = { on: false };
const powerSet = defineCapability({
id: "lamp.power.set",
description: "Turn the lamp on or off.",
audience: ["cli"],
input: z.object({ on: z.boolean() }),
output: z.object({ on: z.boolean() }),
run: ({ on }) => {
lamp.on = on;
return ok({ on });
},
});
const app = defineApp({
title: "Desk lamp",
targets: { cli: { surfaces: ["cli"] } },
capabilities: [powerSet],
});
const toJsonSchema: ToJsonSchema = (schema) => {
if (!(schema instanceof z.ZodType)) throw new Error("Only Zod schemas.");
return z.toJSONSchema(schema, { target: "draft-2020-12" });
};
cliMain(app, { name: "lamp", version: "0.1.0", context: {}, toJsonSchema });
$ node lamp.ts lamp power set --on
{
"on": true
}
To serve the same app over HTTP or MCP, add those surfaces to a target and pass the app to httpHandler or mcpHandler. See Serve capabilities and events.
Write capabilities
import { capabilitiesFor, defineApp, fail, ok } from "@acid-cat/core-ts";
import { z } from "zod";
const Offline = z.object({ _tag: z.literal("Offline") });
const capability = capabilitiesFor<{ unit: Unit }>();
export const aircon = defineApp<{ unit: Unit }>({
title: "Living-room air conditioner",
targets: { cli: { surfaces: ["cli"] }, mcp: { surfaces: ["mcp"] } },
capabilities: [
capability({
id: "aircon.power.set",
description: "Turn the unit on or off.",
audience: ["cli", "mcp"],
input: z.object({ on: z.boolean() }),
failures: { Offline },
run: async ({ on }, { context, signal }) => ((await context.unit.setPower(on, signal)) ? ok(null) : fail({ _tag: "Offline" })),
}),
],
});
No type parameter is required: the types come from the schemas. The only one you may give is the context type, when capabilities need a service from outside, such as unit in the example above. capabilitiesFor<Context>() sets it once for all capabilities, and the same Context goes to defineApp<Context>. The context itself comes from the context option of cliMain, httpHandler and the other entry points.
run(input, { signal, context, target }) gets the decoded input ({} without an input schema), an AbortSignal, the context, and the session's target.
run returns ok(value) or fail(failure). The types check the value against the output schema and the failure against failures. A failure schema describes the whole object, _tag included. If run throws, the call fails as internal.
readOnly, destructive and idempotent are optional hints.
availability is an optional function that returns an observable. The session reads it with getSnapshot when a call arrives, and subscribes only while something listens.
state is an optional { schema, source } for state. The handle exposes it as snapshot.
run, availability and state get the same Context.
defineCapability and capabilitiesFor keep the literal type of id. An application lists only capabilities made by them.
Write events
An event is a kind of thing that happens, which clients can follow. subscribe returns an async iterable with one value per occurrence.
import { eventsFor } from "@acid-cat/core-ts";
const Status = z.object({ on: z.boolean(), celsius: z.number() }).meta({ id: "Status" });
const event = eventsFor<{ unit: Unit }>();
export const statusChanged = event({
id: "aircon.status.changed",
description: "The status of the unit changed.",
audience: ["app", "mcp"],
input: z.object({}),
payload: Status,
async *subscribe(_input, { context, signal }) {
for await (const status of context.unit.changes(signal)) yield { data: status };
},
});
export const aircon = defineApp<{ unit: Unit }>({ targets, capabilities: [powerSet], events: [statusChanged] });
subscribe(input, { signal, context, target, cursor, maxAgeMs }). The signal aborts when the subscription ends, however it ends. Release resources then.
- Each value is
{ data }, with optional eventId, timestamp, cursor and truncated. The session fills in a missing eventId and timestamp as Occurrences says. With no payload schema, data is {}.
- If
subscribe or the iterable throws, or data does not match the payload schema, the subscription fails as internal and the details go to onDefect.
- The session asks for the first value before the
subscribe promise resolves, so an async generator runs to its first await or yield first. Register a listener on the source before that point to see every change after subscribe resolves.
- To support resuming, give a
cursor with each value and honor the cursor and maxAgeMs you receive.
defineEvent and eventsFor keep the literal type of id. Capabilities and events share one set of ids.
Write the catalog
import { writeFile } from "node:fs/promises";
import { renderCatalog } from "@acid-cat/core-ts";
const toJsonSchema = (schema) => z.toJSONSchema(schema, { target: "draft-2020-12" });
await writeFile("acidcat.catalog.json", renderCatalog(aircon, { toJsonSchema })); // canonical form
Standard Schema has no JSON Schema conversion, so pass your schema library's converter as toJsonSchema.
Serve capabilities and events
| Function |
Surface |
Result |
createSession(app, options) |
TypeScript, which maps the programmatic surface |
A session with a handle per capability and an event handle per event |
mcpHandler(app, options) |
MCP over HTTP |
(request: Request) => Promise<Response> |
mcpHandshake(handler) |
MCP, earlier revisions |
The handler, plus the initialize handshake. From @acid-cat/mcp-handshake |
mcpStdioMain(app, options), runMcpStdio(…) |
MCP over stdio |
The process's MCP server, or a promise that resolves when the input ends |
httpHandler(app, options) |
HTTP |
(request: Request) => Promise<Response> |
cliMain(app, options), runCli(…) |
CLI |
The process's command line, or an exit code |
httpClient(url, options) |
CLI |
A client for a server's HTTP surface |
installWebMcp(session) |
WebMCP |
Tools in the page, with a status |
serve(handler, options) from @acid-cat/core-ts/node |
MCP and HTTP |
A Node.js server. See Serve on Node.js |
Options that tune event delivery:
| Option |
Of |
Default |
Meaning |
bufferLimit |
createSession, httpHandler, mcpHandler, runMcpStdio |
256 |
Occurrences kept per subscription for a slow client |
keepaliveMs |
httpHandler |
15 seconds |
Idle time before a comment line on an event stream |
heartbeatMs |
mcpHandler, runMcpStdio |
15 seconds |
Heartbeat interval of events/stream when the request suggests none. A suggestion in params.heartbeatMs gets a grant from 1 to 60 seconds (Push) |
clock |
mcpHandler, runMcpStdio, webhookDelivery |
System clock |
Time and timers for leases, lifetimes and retries. Tests pass their own |
MCP headers
mcpHandler checks the headers of each request of revision 2026-07-28 against its body: Mcp-Method, Mcp-Name, and an Mcp-Param-* header for each property of the input schema of the tool or the event that has x-mcp-header. A mismatch gets 400 and -32020. To annotate a property with Zod, use .meta({ "x-mcp-header": "Region" }).
MCP poll and webhook delivery
mcpHandler and runMcpStdio serve poll delivery. Over HTTP, a lease's session gets the context of the request that started it; over stdio, the process's context. Leases live in memory. handler.close() (or await using) ends every lease and webhook subscription; over stdio, the end of standard input does.
poll option |
Default |
Meaning |
leaseMs |
5 minutes |
Time without a poll before a lease ends |
bufferLimit |
1000 |
Occurrences each lease keeps |
maxEvents |
100 |
Occurrences per result when the request gives no maxEvents |
nextPollMs |
2000 |
The nextPollMs of each result |
The principal(request) option of mcpHandler returns the client's identity, such as a verified token's subject, or undefined. It is part of each lease key and webhook subscription key, so one client cannot read another's lease. Over stdio, leases have no principal.
Webhook delivery is off by default and works only over HTTP. Enable it with the webhooks option and webhookDelivery(options) from @acid-cat/core-ts/node. It needs principal.
import { mcpHandler } from "@acid-cat/core-ts";
import { serve, webhookDelivery } from "@acid-cat/core-ts/node";
const mcp = mcpHandler(aircon, {
name: "aircon",
version: "1.0.0",
allowedOrigins: [],
toJsonSchema,
context: { unit },
principal: (request) => verifiedSubject(request), // string | undefined
webhooks: webhookDelivery({ maxTtlMs: 3_600_000 }),
});
await serve({ "/mcp": mcp });
webhookDelivery option |
Default |
Meaning |
allow(url) |
None |
The allowlist. A URL for which it returns true skips verification |
allowPrivateNetworks |
false |
Also connect to addresses that are not globally routable. For tests and private networks only |
ca |
None |
Extra certificate authorities to trust, in PEM form |
maxTtlMs, minTtlMs |
1 hour, 1 minute |
Bounds on the granted lifetime |
maxSubscriptions |
100 |
Webhook subscriptions per principal |
attempts, retryWindowMs |
5, 15 minutes |
Attempts per delivery, and their time window |
retryDelayMs(attempt) |
10 s, 30 s, 90 s, 270 s |
The wait before the next attempt |
timeoutMs |
5 seconds |
Wait for each response |
rotationGraceMs |
5 minutes |
How long the old secret still signs after a new one |
signingKeys |
None |
Ed25519 keys, as private JWKs, that also sign each request. To change keys, give the new key beside the old one |
egressIpRanges |
None |
The IP ranges from which the server sends, as CIDR text, for the Server Card |
webhookDelivery throws a TypeError for a signing key or an egress range that breaks the rules of webhook delivery.
Verifications are kept in memory while the process runs. The server checks the endpoint's TLS certificate, never logs or returns a secret, and never passes on the endpoint's response text: lastError and CallbackEndpointError carry only a category such as http_4xx.
MCP Server Card
mcpHandler serves an MCP Server Card at the URL of the server and /server-card, for example /mcp/server-card. It is on by default. serverCard: false turns it off.
| Option |
Default |
Use |
serverCard.name |
From the host of the URL and name (Default name) |
The name of the server in a registry. name stays the name that server/discover gives |
serverCard.description |
The description of the catalog, else instructions, else name (Default description) |
|
serverCard.url |
The URL of the request, without /server-card |
Give the https URL when a platform in front of the server ends TLS |
With webhook delivery, the card also gives the public keys of signingKeys and the egressIpRanges. mcpHandshake adds its revisions to the card. A setting that breaks the startup rules of the card, such as a version range with the card on, makes mcpHandler throw a TypeError. The defaults never make it throw.
const mcp = mcpHandler(aircon, {
name: "aircon",
version: "1.0.0",
allowedOrigins: [],
toJsonSchema,
context: { unit },
serverCard: { name: "com.example/aircon" },
principal: (request) => verifiedSubject(request),
webhooks: webhookDelivery({ signingKeys: [signingJwk], egressIpRanges: ["203.0.113.0/24"] }),
});
await serve({ "/mcp": mcpHandshake(mcp) });