@cargo-ai/worker-sdk
v1.0.6
Published
Build Cargo Hosting workers (edge HTTP handlers) with automatic OpenAPI generation via Hono + Chanfana.
Readme
@cargo-ai/worker-sdk
Build Cargo Hosting workers — serverless edge HTTP handlers running on *.worker.getcargo.run — with automatic OpenAPI 3.1 generation. Hono + Chanfana + Zod are wrapped in two opinionated factories so you define routes once and get runtime validation, a Cargo-native manifest, and live OpenAPI docs for free.
Install
npm install @cargo-ai/worker-sdkWrite a worker
import { type Context, createWorker, OpenAPIRoute } from "@cargo-ai/worker-sdk";
import { z } from "zod";
const { app, openapi } = createWorker({ title: "my-worker" });
class GetHello extends OpenAPIRoute {
override schema = {
request: {
query: z.object({ name: z.string().default("world") }),
},
responses: {
"200": {
description: "Greeting.",
content: {
"application/json": {
schema: z.object({ message: z.string() }),
},
},
},
},
};
override async handle(c: Context): Promise<Response> {
const { query } = await this.getValidatedData<typeof this.schema>();
return c.json({ message: `Hello, ${query.name}!` });
}
}
openapi.get("/hello", GetHello);
export default app;createWorker gives you:
GET /openapi.json— OpenAPI 3.1 spec derived from every route's Zod schema.GET /docs— Swagger UI.
Call the Cargo API
Create a workspace API token in Cargo and add it to the worker as a CARGO_API_TOKEN secret environment variable. createCargoApi(env) then returns the fully-typed @cargo-ai/api client, connected to your workspace — the Cargo API host is allowed automatically, no outboundAllowlist entry needed:
import { createCargoApi } from "@cargo-ai/worker-sdk";
app.get("/workers", async (c) => {
const api = createCargoApi(c.env);
const { workers } = await api.hosting.worker.list();
return c.json(workers);
});Cron triggers
A worker can be called on a schedule. Each trigger — configured on the worker from the Cargo app, cargo-ai hosting worker create/update --triggers, or defineWorker in the CDK — describes the full request Cargo fires: cron, path, method, JSON body, and headers. Set an authorization header on the trigger and guard the route:
import { bearerAuth } from "hono/bearer-auth";
app.use("/cron/*", bearerAuth({ token: "<something-strong>" }));
app.post("/cron/sync", async (c) => {
// ... scheduled work ...
return c.json({ ok: true });
});Ticks only fire once the worker has a promoted deployment.
Write a custom integration
createCustomIntegration({ info, connector, authenticate, actions, extractors, ... }) builds a worker that implements the Cargo Custom Integration HTTP contract from a single declarative spec. The same Zod schemas feed GET /manifest (Cargo-native wire format) and GET /openapi.json. See templates/custom-integration/.
Integration-domain types (IntegrationActionExecutePayload, IntegrationExtractorFetchResult, …) live in @cargo-ai/types under the ConnectionTypes namespace — you rarely need to import them directly because the SDK's CustomIntegrationAction / CustomIntegrationExtractor types wire them in for you.
Scaffold a project
You almost never want to wire this from scratch. Use the CLI:
# Blank edge handler
npx @cargo-ai/cli hosting worker init my-worker --template blank
# Worker that implements the Cargo Custom Integration HTTP contract
npx @cargo-ai/cli hosting worker init my-integration --template custom-integrationThe CLI copies the matching template from @cargo-ai/worker-sdk/templates/<slug>/ into your target directory.
Deploy
You author in TypeScript and deploy the source directory as-is — no local build step. The uploaded source is the project root (with src/index.ts, manifest.json, package.json, package-lock.json):
npm install
cargo-ai hosting deployment create --worker-uuid <workerUuid> --source ./
cargo-ai hosting deployment promote --uuid <deploymentUuid>The Cargo Hosting build pipeline runs npm ci then esbuild src/index.ts --bundle --format=esm --platform=neutral --target=es2022 (esbuild transpiles TypeScript natively) to produce the final edge bundle. So you can ship multi-file TypeScript projects — esbuild tree-shakes everything into a single ESM file at deploy time. (A pre-built index.js at the root is still accepted for backwards compatibility.)
Available templates
blank— a ready-to-extend Hono app built bycreateWorker(), with one sample route and/openapi.json+/docsout of the box. Use this when the worker just responds to inbound HTTP and doesn't need to integrate into the Cargo connector catalog.custom-integration— a ready-to-extend spec passed tocreateCustomIntegration(). Handles/manifest,/openapi.json,/docs,/authenticate,/actions/<slug>/execute,/extractors/<slug>/{fetch,count},/autocompletes/<slug>,/dynamicSchemas/<slug>,/completeOauth,/listUsersfrom a single declaration. Edge-native equivalent ofgetcargohq/dummy-integration. Register it in the connector catalog withdefineCustomIntegrationin the CDK, orcargo-ai connection custom-integration create --kind worker --worker-uuid <workerUuid>.
See each template's own README.md for the file layout and how to extend it.
