[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6GVDA0PC6FQV9H3MVM52J57":3,"skill-same:01M6GVDA0PC6FQV9H3MVM52J57":87},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":40,"linkOnly":41,"markdownContent":42,"markdownBody":43,"frontMatter":44,"refName":50,"commitSha":51,"skillDirectory":52,"forksCount":53,"repositoryHtmlUrl":54,"repositoryHomepageUrl":6,"ownerHtmlUrl":55,"ownerBlogUrl":56,"ownerDescription":57,"updatedAt":58,"install":59,"resources":72},"01M6GVDA0PC6FQV9H3MVM52J57","api-workers",null,"Cloudflare Workers deployment using `createWorkerHandler` from `@cyanheads\u002Fmcp-ts-core\u002Fworker`. Covers the full handler signature, binding types, CloudflareBindings extensibility, runtime compatibility guards, and wrangler.toml requirements.","jiayaoqijia\u002Fcryptoskill","jiayaoqijia","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1453879?v=4","01M6GMYTX7Q7S504VC6E756ENR","YQ","01M6GMYV1QKJ1CC75MTTGT9PR0",81,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fcyanheads-api-workers\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fcyanheads-api-workers\u002FSKILL.md",[],[20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39],"api workers","api","workers","full","handler","extensibility","types","binding","toml","runtime","worker","requirements","MCP","compatibility","reference","cloudflare workers","wrangler","cloudflare","core","deployment","2026-11-10 10:12:30",false,"---\nname: api-workers\ndescription: >\n  Cloudflare Workers deployment using `createWorkerHandler` from `@cyanheads\u002Fmcp-ts-core\u002Fworker`. Covers the full handler signature, binding types, CloudflareBindings extensibility, runtime compatibility guards, and wrangler.toml requirements.\nmetadata:\n  author: cyanheads\n  version: \"1.9\"\n  audience: external\n  type: reference\n---\n\n## Overview\n\n`@cyanheads\u002Fmcp-ts-core\u002Fworker` exports `createWorkerHandler` — the Workers entry point. It wraps tool\u002Fresource\u002Fprompt registries into a per-request `McpServer` factory that integrates with the Cloudflare Workers runtime.\n\n---\n\n## `createWorkerHandler(options)`\n\n```ts\nimport { createWorkerHandler } from '@cyanheads\u002Fmcp-ts-core\u002Fworker';\nimport { echoTool } from '.\u002Fmcp-server\u002Ftools\u002Fdefinitions\u002Fecho.tool.js';\nimport { echoResource } from '.\u002Fmcp-server\u002Fresources\u002Fdefinitions\u002Fecho.resource.js';\nimport { echoPrompt } from '.\u002Fmcp-server\u002Fprompts\u002Fdefinitions\u002Fecho.prompt.js';\nimport { initMyService } from '.\u002Fservices\u002Fmy-domain\u002Fmy-service.js';\n\nexport default createWorkerHandler({\n  tools: [echoTool],\n  resources: [echoResource],\n  prompts: [echoPrompt],\n  setup(core) {\n    initMyService(core.config, core.storage);\n  },\n  extraEnvBindings: [['MY_API_KEY', 'MY_API_KEY']],\n  extraObjectBindings: [['MY_CUSTOM_KV', 'MY_CUSTOM_KV']],\n  onScheduled: async (controller, env, ctx) => {\n    \u002F\u002F Cloudflare cron trigger handler\n  },\n});\n```\n\nFresh scaffolds register definitions directly in the entry point as shown above. If your project later adds barrel files for definitions, importing arrays from those barrels is also fine.\n\n### Options\n\n| Option | Type | Purpose |\n|:-------|:-----|:--------|\n| `tools` | `AnyToolDefinition[]` | Tool definitions to register |\n| `resources` | `AnyResourceDefinition[]` | Resource definitions to register |\n| `prompts` | `PromptDefinition[]` | Prompt definitions to register |\n| `extensions` | `Record\u003Cstring, object>` | SEP-2133 extensions to advertise in server capabilities |\n| `instructions` | `string \\| (env: CloudflareBindings) => string` | Server-level orientation forwarded to the model on every `initialize`. Resolver form runs inside `initializeApp(env)` so env-derived text is available (see Workers-specific warnings). Empty string treated as unset. |\n| `setup` | `(core: CoreServices) => void \\| Promise\u003Cvoid>` | Runs after core services are ready, during the first request (lazy init inside the fetch handler) |\n| `extraEnvBindings` | `[bindingKey: string, processEnvKey: string][]` | Maps CF string bindings to `process.env` keys |\n| `extraObjectBindings` | `[bindingKey: string, globalKey: string][]` | Maps CF object bindings (KV, R2, D1, AI) to `globalThis` keys |\n| `onScheduled` | `(controller, env, ctx) => Promise\u003Cvoid>` | Cloudflare cron trigger handler |\n\n### Key design points\n\n- **Per-request `McpServer` factory**: a new server instance is created for each request. Required by SDK security advisory GHSA-345p-7cg4-v4c7.\n- **Env bindings refreshed per-request**: Cloudflare may rotate binding object references between requests; the handler re-injects them on every call.\n- **OTel NodeSDK is disabled in Workers** — `canUseNodeSDK()` returns `false` for V8 isolates, so no OTLP spans or metrics are emitted. Structured logs via `ctx.log` still work. `OTEL_ENABLED=true` has no effect in Workers. `ctx.waitUntil()` is received and passed through to `app.fetch` and `onScheduled` but not called by the framework (nothing to flush asynchronously).\n- **Singleton app promise with retry-on-failure**: the framework init runs once; if it fails, the next request retries rather than leaving the Worker in a permanently broken state.\n\n---\n\n## Binding types\n\nCloudflare Workers bindings come in two kinds with different injection mechanisms:\n\n| Type | Examples | Injection mechanism | Runtime access |\n|:-----|:---------|:--------------------|:---------------|\n| String values | API keys, base URLs, feature flags | `injectEnvVars()` → `process.env` | `process.env.MY_API_KEY` |\n| Object bindings | KV namespace, R2 bucket, D1 database, AI | `storeBindings()` → `globalThis` | `(globalThis as any).MY_CUSTOM_KV` |\n\n**`extraEnvBindings`**: array of `[bindingKey, processEnvKey]` tuples. The value of `env[bindingKey]` is assigned to `process.env[processEnvKey]` at request time.\n\n**`extraObjectBindings`**: array of `[bindingKey, globalKey]` tuples. The object at `env[bindingKey]` is stored on `globalThis[globalKey]` at request time.\n\nBoth are refreshed on every request. Never cache binding references between requests.\n\n---\n\n## `CloudflareBindings` extensibility\n\nCore defines `CloudflareBindings` without an index signature, so servers extend it via intersection rather than module augmentation:\n\n```ts\nimport type { CloudflareBindings as CoreBindings } from '@cyanheads\u002Fmcp-ts-core\u002Fworker';\n\ninterface MyBindings extends CoreBindings {\n  MY_CUSTOM_KV: KVNamespace;\n  MY_R2_BUCKET: R2Bucket;\n}\n```\n\nPass `MyBindings` as a type parameter where the framework accepts a generic env type (e.g., Hono route handlers, `onScheduled`).\n\n---\n\n## Runtime compatibility\n\n### `runtimeCaps` feature detection\n\n```ts\nimport { runtimeCaps } from '@cyanheads\u002Fmcp-ts-core\u002Futils';\n\nif (runtimeCaps.isWorkerLike) {\n  \u002F\u002F Workers-specific path\n}\n\nif (runtimeCaps.isNode) {\n  \u002F\u002F Node.js-specific path (e.g., filesystem access)\n}\n```\n\n`runtimeCaps` is a snapshot taken at import time. Fields: `isNode`, `isBun`, `isWorkerLike`, `isBrowserLike`, `hasProcess`, `hasBuffer`, `hasTextEncoder`, `hasPerformanceNow`. All booleans, never throw.\n\n### Serverless storage whitelist\n\nIn Workers, only these storage providers are allowed:\n\n| Provider | Notes |\n|:---------|:------|\n| `in-memory` | Default — data lost on cold start, no persistence |\n| `cloudflare-kv` | KV namespace binding — eventually consistent |\n| `cloudflare-r2` | R2 bucket binding — object storage |\n| `cloudflare-d1` | D1 database binding — SQLite-compatible |\n\n`filesystem`, `supabase`, and unknown provider types are not on the whitelist:\n\n- **`filesystem`** and unknown types throw `ConfigurationError` in serverless environments.\n- **`supabase`** does **not** silently fall back. The serverless provider whitelist check fires immediately at the top of `createStorageProvider()` — Supabase credentials are never validated. Worker startup fails with `ConfigurationError` because Supabase is not on the serverless whitelist. Do not set `STORAGE_PROVIDER_TYPE=supabase` in a Worker.\n\nSet `STORAGE_PROVIDER_TYPE` to one of the four whitelisted values to avoid unexpected behavior.\n\n---\n\n## `wrangler.toml` requirements\n\n```toml\ncompatibility_flags = [\"nodejs_compat\"]\ncompatibility_date = \"2025-09-01\"  # must be >= 2025-09-01\n\n# Built-in storage providers require these exact binding names:\n[[kv_namespaces]]\nbinding = \"KV_NAMESPACE\"       # required for cloudflare-kv storage\nid = \"...\"\n\n[[r2_buckets]]\nbinding = \"R2_BUCKET\"          # required for cloudflare-r2 storage\nbucket_name = \"...\"\n\n[[d1_databases]]\nbinding = \"DB\"                 # required for cloudflare-d1 storage\ndatabase_id = \"...\"\n```\n\n`nodejs_compat` is required for Node.js API shims (e.g., `process.env`, `Buffer`, `crypto`). The minimum `compatibility_date` activates the required shim set.\n\n**Binding names for core storage are hardcoded** — the storage factory looks for `KV_NAMESPACE`, `R2_BUCKET`, and `DB` on `globalThis`. Using different binding names will cause a `ConfigurationError`. For custom (non-storage) bindings, use `extraObjectBindings` to map arbitrary binding names to `globalThis` keys.\n\n**Bundling requires a `@duckdb\u002Fnode-api` alias.** Wrangler's esbuild step follows the framework's lazy `import('@duckdb\u002Fnode-api')` (the DataCanvas DuckDB provider) even though that path never executes on Workers, and fails on DuckDB's native platform bindings (`Could not resolve \"@duckdb\u002Fnode-bindings-*\u002Fduckdb.node\"`). Alias the module to a local stub:\n\n```toml\n[alias]\n\"@duckdb\u002Fnode-api\" = \".\u002Fduckdb-stub.ts\"\n```\n\n```ts\n\u002F\u002F duckdb-stub.ts — rejects the lazy import if a misconfigured Worker ever reaches it\nthrow new Error('@duckdb\u002Fnode-api is not available in Cloudflare Workers.');\nexport {};\n```\n\n---\n\n## Workers-specific warnings\n\n**`instructions` resolver runs after env injection.** When `instructions` is a function, it runs inside `initializeApp(env)` — after `injectEnvVars()` — so env-derived text reaches the model without fighting the Workers module-load lifecycle:\n\n```ts\nexport default createWorkerHandler({\n  tools: [echoTool],\n  instructions: (env) =>\n    `Region: ${env.ENVIRONMENT ?? 'production'}.` +\n    (env.MAINTENANCE_MODE ? ' Read-only mode — writes disabled.' : ''),\n});\n```\n\nPlain strings work the same as on `createApp`. Type extends `Omit\u003CCreateAppOptions, 'instructions'>`, so this is the only option whose shape differs between Node and Worker entry points.\n\n**Lazy env parsing is mandatory.** Cloudflare injects env bindings at request time via `injectEnvVars()`, after all static module imports complete. Never parse `process.env` at module top-level in Workers:\n\n```ts\n\u002F\u002F WRONG — parsed before env is injected\nconst apiKey = process.env.MY_API_KEY;  \u002F\u002F undefined in Workers\n\n\u002F\u002F CORRECT — lazy parse inside a function or getter\nexport function getServerConfig() {\n  return ServerConfigSchema.parse({ apiKey: process.env.MY_API_KEY });\n}\n```\n\n**`in-memory` storage is volatile.** Data stored with the `in-memory` provider is lost between cold starts and is not shared across Worker instances. Use `cloudflare-kv`, `cloudflare-r2`, or `cloudflare-d1` for any state that must persist or be shared.\n\n**Multi-round-trip retries land on any isolate.** Each 2026-07-28 request builds its own `McpServer`, and the retry after an `input_required` result can be routed to a different isolate. Set `MCP_REQUEST_STATE_KEY` (≥ 32 bytes) as a Worker secret — it is a core binding, injected like the rest — so every isolate seals and verifies `requestState` with the same key, and keep a consent gate's record (`api-context` § *Consent gates*) in `cloudflare-d1`. `in-memory` loses it to the next isolate, so the retry asks again. Never `cloudflare-kv`: it is eventually consistent, so a retry served elsewhere may not see the record yet, and a deletion may not yet stop an immediate replay — it widens the window concurrent retries already have, since redeeming is not atomic on any provider until `ctx.state` gains a `take` ([#593](https:\u002F\u002Fgithub.com\u002Fcyanheads\u002Fmcp-ts-core\u002Fissues\u002F593)).\n\n**Node-only utilities throw in Workers.** `scheduler` (`node-cron`), `sanitizePath` (fs-based), and `filesystem` storage provider all throw `ConfigurationError` when called from a Worker. Guard with `runtimeCaps.isNode` or avoid entirely.\n\n**DataCanvas is unavailable in Workers.** DuckDB has no V8-isolate build, so `core.canvas` is always `undefined` on Workers. Setting `CANVAS_PROVIDER_TYPE=duckdb` (the only non-default value) in `wrangler.toml` triggers a fail-closed `ConfigurationError` at init time:\n\n> `DuckDB canvas requires Node.js or Bun. Set CANVAS_PROVIDER_TYPE=none or omit it for Cloudflare Workers deployment.`\n\nLeave the env unset (or set to `none`) for Worker deployments. Tools that conditionally use canvas should check the module-level accessor (`if (!getCanvas()) { ... }`) and surface a clear \"feature unavailable on this deployment\" message. See `api-canvas` for the full DataCanvas reference and setup wiring pattern.\n\n**The default notification bus is per-isolate.** `core.notify` and the modern era's `subscriptions\u002Flisten` streams share a change-event bus that defaults to in-process — which on Workers means one bus per isolate, so a background emission reaches only the listeners that happen to live in the isolate that produced it. Handler-time `ctx.notify*` is unaffected (the listen stream and the handler are the same request). For fan-out that must cross isolates, supply a bus of your own, backed by a Durable Object or another shared channel:\n\n```ts\ncreateWorkerHandler({ tools, eventBus: myDurableObjectBackedBus });\n```\n\nThe interface is the SDK's `ServerEventBus` — `publish(event)` and `subscribe(listener)`. See `api-context`'s notification section for what publishes onto it.\n\n---\n\n## Testing Workers with miniflare\n\n`bun run test:worker` runs the worker suite under `tests\u002Fconfig\u002Fvitest.worker.ts` (using `@cloudflare\u002Fvitest-pool-workers` + miniflare). Each test **file** gets its own fresh V8 isolate — module scope (including `createWorkerHandler`'s `appPromise` singleton) is reset between files.\n\n### tests\u002Fconfig\u002Fvitest.worker.ts miniflare bindings\n\nDeclare all storage bindings used in the suite:\n\n```ts\ncloudflareTest({\n  main: '.\u002Ftests\u002Ffixtures\u002Fworker-runtime.fixture.ts',\n  miniflare: {\n    bindings: { STORAGE_PROVIDER_TYPE: 'cloudflare-kv', ... },\n    kvNamespaces: ['KV_NAMESPACE', 'CUSTOM_KV'],\n    r2Buckets:    ['R2_BUCKET'],\n    d1Databases:  ['DB'],\n  },\n})\n```\n\nBinding names must match the hardcoded names in `storageFactory.ts` (`KV_NAMESPACE`, `R2_BUCKET`, `DB`).\n\n### Per-provider test isolation\n\n`bindings.STORAGE_PROVIDER_TYPE` is a global default. Per-provider test files override it by passing a modified env to `worker.fetch()`:\n\n```ts\nimport { env } from 'cloudflare:workers';\n\n\u002F\u002F Fresh isolate per file — appPromise starts null.\n\u002F\u002F First fetch initialises the singleton with the overridden provider type.\nconst r2Env = { ...env, STORAGE_PROVIDER_TYPE: 'cloudflare-r2' };\nawait worker.fetch(request, r2Env, ctx);\n```\n\nUse `reset()` from `cloudflare:test` in `afterEach` to clear binding state between tests. For D1, re-apply migrations immediately after each `reset()` (reset wipes the schema):\n\n```ts\nimport { applyD1Migrations, reset } from 'cloudflare:test';\n\nafterEach(async () => {\n  await reset();\n  await applyD1Migrations(env.DB, [{ name: '0001_schema', queries: [CREATE_TABLE_SQL] }]);\n});\n```\n\n### D1 schema setup\n\nThe `cloudflare-d1` provider requires the `kv_store` table before any operations. Apply it in `beforeAll` via `applyD1Migrations`:\n\n```ts\nconst KV_STORE_MIGRATION = `\nCREATE TABLE IF NOT EXISTS kv_store (\n  tenant_id TEXT NOT NULL,\n  key       TEXT NOT NULL,\n  value     TEXT NOT NULL,\n  expires_at INTEGER,\n  PRIMARY KEY (tenant_id, key)\n)`;\n\nbeforeAll(async () => {\n  await applyD1Migrations(env.DB, [\n    { name: '0001_create_kv_store', queries: [KV_STORE_MIGRATION] },\n  ]);\n  sessionId = await openSession(d1Env);\n});\n```\n\n### R2 list limit\n\nThe R2 provider fetches `limit + 1` objects to detect further pages. Miniflare caps R2 `MaxKeys` at 1000, so the default `limit=1000` → request 1001 → error. Pass `limit: 100` (or any value ≤ 999) to `ctx.state.list()` in test fixtures to stay under the cap:\n\n```ts\nconst result = await ctx.state.list(prefix, { limit: 100 });\n```\n\n### Storage probe pattern\n\nExpose storage operations as MCP tools in the fixture to test them through the real HTTP surface:\n\n```ts\nconst storageSetTool = tool('storage_set', {\n  input: z.object({ key: z.string().describe('...'), value: z.string().describe('...') }),\n  output: z.object({ ok: z.boolean().describe('Always true on success') }),\n  async handler(input, ctx) {\n    await ctx.state.set(input.key, input.value);\n    return { ok: true };\n  },\n  format: (r) => [{ type: 'text', text: `ok=${r.ok}` }],\n});\n```\n\nCall via `tools\u002Fcall` over MCP JSON-RPC and assert on `structuredContent`. See `tests\u002Fworker\u002Fstorage-r2.worker.test.ts` and `tests\u002Fworker\u002Fstorage-d1.worker.test.ts` for the full pattern.\n","## Overview\n\n`@cyanheads\u002Fmcp-ts-core\u002Fworker` exports `createWorkerHandler` — the Workers entry point. It wraps tool\u002Fresource\u002Fprompt registries into a per-request `McpServer` factory that integrates with the Cloudflare Workers runtime.\n\n---\n\n## `createWorkerHandler(options)`\n\n```ts\nimport { createWorkerHandler } from '@cyanheads\u002Fmcp-ts-core\u002Fworker';\nimport { echoTool } from '.\u002Fmcp-server\u002Ftools\u002Fdefinitions\u002Fecho.tool.js';\nimport { echoResource } from '.\u002Fmcp-server\u002Fresources\u002Fdefinitions\u002Fecho.resource.js';\nimport { echoPrompt } from '.\u002Fmcp-server\u002Fprompts\u002Fdefinitions\u002Fecho.prompt.js';\nimport { initMyService } from '.\u002Fservices\u002Fmy-domain\u002Fmy-service.js';\n\nexport default createWorkerHandler({\n  tools: [echoTool],\n  resources: [echoResource],\n  prompts: [echoPrompt],\n  setup(core) {\n    initMyService(core.config, core.storage);\n  },\n  extraEnvBindings: [['MY_API_KEY', 'MY_API_KEY']],\n  extraObjectBindings: [['MY_CUSTOM_KV', 'MY_CUSTOM_KV']],\n  onScheduled: async (controller, env, ctx) => {\n    \u002F\u002F Cloudflare cron trigger handler\n  },\n});\n```\n\nFresh scaffolds register definitions directly in the entry point as shown above. If your project later adds barrel files for definitions, importing arrays from those barrels is also fine.\n\n### Options\n\n| Option | Type | Purpose |\n|:-------|:-----|:--------|\n| `tools` | `AnyToolDefinition[]` | Tool definitions to register |\n| `resources` | `AnyResourceDefinition[]` | Resource definitions to register |\n| `prompts` | `PromptDefinition[]` | Prompt definitions to register |\n| `extensions` | `Record\u003Cstring, object>` | SEP-2133 extensions to advertise in server capabilities |\n| `instructions` | `string \\| (env: CloudflareBindings) => string` | Server-level orientation forwarded to the model on every `initialize`. Resolver form runs inside `initializeApp(env)` so env-derived text is available (see Workers-specific warnings). Empty string treated as unset. |\n| `setup` | `(core: CoreServices) => void \\| Promise\u003Cvoid>` | Runs after core services are ready, during the first request (lazy init inside the fetch handler) |\n| `extraEnvBindings` | `[bindingKey: string, processEnvKey: string][]` | Maps CF string bindings to `process.env` keys |\n| `extraObjectBindings` | `[bindingKey: string, globalKey: string][]` | Maps CF object bindings (KV, R2, D1, AI) to `globalThis` keys |\n| `onScheduled` | `(controller, env, ctx) => Promise\u003Cvoid>` | Cloudflare cron trigger handler |\n\n### Key design points\n\n- **Per-request `McpServer` factory**: a new server instance is created for each request. Required by SDK security advisory GHSA-345p-7cg4-v4c7.\n- **Env bindings refreshed per-request**: Cloudflare may rotate binding object references between requests; the handler re-injects them on every call.\n- **OTel NodeSDK is disabled in Workers** — `canUseNodeSDK()` returns `false` for V8 isolates, so no OTLP spans or metrics are emitted. Structured logs via `ctx.log` still work. `OTEL_ENABLED=true` has no effect in Workers. `ctx.waitUntil()` is received and passed through to `app.fetch` and `onScheduled` but not called by the framework (nothing to flush asynchronously).\n- **Singleton app promise with retry-on-failure**: the framework init runs once; if it fails, the next request retries rather than leaving the Worker in a permanently broken state.\n\n---\n\n## Binding types\n\nCloudflare Workers bindings come in two kinds with different injection mechanisms:\n\n| Type | Examples | Injection mechanism | Runtime access |\n|:-----|:---------|:--------------------|:---------------|\n| String values | API keys, base URLs, feature flags | `injectEnvVars()` → `process.env` | `process.env.MY_API_KEY` |\n| Object bindings | KV namespace, R2 bucket, D1 database, AI | `storeBindings()` → `globalThis` | `(globalThis as any).MY_CUSTOM_KV` |\n\n**`extraEnvBindings`**: array of `[bindingKey, processEnvKey]` tuples. The value of `env[bindingKey]` is assigned to `process.env[processEnvKey]` at request time.\n\n**`extraObjectBindings`**: array of `[bindingKey, globalKey]` tuples. The object at `env[bindingKey]` is stored on `globalThis[globalKey]` at request time.\n\nBoth are refreshed on every request. Never cache binding references between requests.\n\n---\n\n## `CloudflareBindings` extensibility\n\nCore defines `CloudflareBindings` without an index signature, so servers extend it via intersection rather than module augmentation:\n\n```ts\nimport type { CloudflareBindings as CoreBindings } from '@cyanheads\u002Fmcp-ts-core\u002Fworker';\n\ninterface MyBindings extends CoreBindings {\n  MY_CUSTOM_KV: KVNamespace;\n  MY_R2_BUCKET: R2Bucket;\n}\n```\n\nPass `MyBindings` as a type parameter where the framework accepts a generic env type (e.g., Hono route handlers, `onScheduled`).\n\n---\n\n## Runtime compatibility\n\n### `runtimeCaps` feature detection\n\n```ts\nimport { runtimeCaps } from '@cyanheads\u002Fmcp-ts-core\u002Futils';\n\nif (runtimeCaps.isWorkerLike) {\n  \u002F\u002F Workers-specific path\n}\n\nif (runtimeCaps.isNode) {\n  \u002F\u002F Node.js-specific path (e.g., filesystem access)\n}\n```\n\n`runtimeCaps` is a snapshot taken at import time. Fields: `isNode`, `isBun`, `isWorkerLike`, `isBrowserLike`, `hasProcess`, `hasBuffer`, `hasTextEncoder`, `hasPerformanceNow`. All booleans, never throw.\n\n### Serverless storage whitelist\n\nIn Workers, only these storage providers are allowed:\n\n| Provider | Notes |\n|:---------|:------|\n| `in-memory` | Default — data lost on cold start, no persistence |\n| `cloudflare-kv` | KV namespace binding — eventually consistent |\n| `cloudflare-r2` | R2 bucket binding — object storage |\n| `cloudflare-d1` | D1 database binding — SQLite-compatible |\n\n`filesystem`, `supabase`, and unknown provider types are not on the whitelist:\n\n- **`filesystem`** and unknown types throw `ConfigurationError` in serverless environments.\n- **`supabase`** does **not** silently fall back. The serverless provider whitelist check fires immediately at the top of `createStorageProvider()` — Supabase credentials are never validated. Worker startup fails with `ConfigurationError` because Supabase is not on the serverless whitelist. Do not set `STORAGE_PROVIDER_TYPE=supabase` in a Worker.\n\nSet `STORAGE_PROVIDER_TYPE` to one of the four whitelisted values to avoid unexpected behavior.\n\n---\n\n## `wrangler.toml` requirements\n\n```toml\ncompatibility_flags = [\"nodejs_compat\"]\ncompatibility_date = \"2025-09-01\"  # must be >= 2025-09-01\n\n# Built-in storage providers require these exact binding names:\n[[kv_namespaces]]\nbinding = \"KV_NAMESPACE\"       # required for cloudflare-kv storage\nid = \"...\"\n\n[[r2_buckets]]\nbinding = \"R2_BUCKET\"          # required for cloudflare-r2 storage\nbucket_name = \"...\"\n\n[[d1_databases]]\nbinding = \"DB\"                 # required for cloudflare-d1 storage\ndatabase_id = \"...\"\n```\n\n`nodejs_compat` is required for Node.js API shims (e.g., `process.env`, `Buffer`, `crypto`). The minimum `compatibility_date` activates the required shim set.\n\n**Binding names for core storage are hardcoded** — the storage factory looks for `KV_NAMESPACE`, `R2_BUCKET`, and `DB` on `globalThis`. Using different binding names will cause a `ConfigurationError`. For custom (non-storage) bindings, use `extraObjectBindings` to map arbitrary binding names to `globalThis` keys.\n\n**Bundling requires a `@duckdb\u002Fnode-api` alias.** Wrangler's esbuild step follows the framework's lazy `import('@duckdb\u002Fnode-api')` (the DataCanvas DuckDB provider) even though that path never executes on Workers, and fails on DuckDB's native platform bindings (`Could not resolve \"@duckdb\u002Fnode-bindings-*\u002Fduckdb.node\"`). Alias the module to a local stub:\n\n```toml\n[alias]\n\"@duckdb\u002Fnode-api\" = \".\u002Fduckdb-stub.ts\"\n```\n\n```ts\n\u002F\u002F duckdb-stub.ts — rejects the lazy import if a misconfigured Worker ever reaches it\nthrow new Error('@duckdb\u002Fnode-api is not available in Cloudflare Workers.');\nexport {};\n```\n\n---\n\n## Workers-specific warnings\n\n**`instructions` resolver runs after env injection.** When `instructions` is a function, it runs inside `initializeApp(env)` — after `injectEnvVars()` — so env-derived text reaches the model without fighting the Workers module-load lifecycle:\n\n```ts\nexport default createWorkerHandler({\n  tools: [echoTool],\n  instructions: (env) =>\n    `Region: ${env.ENVIRONMENT ?? 'production'}.` +\n    (env.MAINTENANCE_MODE ? ' Read-only mode — writes disabled.' : ''),\n});\n```\n\nPlain strings work the same as on `createApp`. Type extends `Omit\u003CCreateAppOptions, 'instructions'>`, so this is the only option whose shape differs between Node and Worker entry points.\n\n**Lazy env parsing is mandatory.** Cloudflare injects env bindings at request time via `injectEnvVars()`, after all static module imports complete. Never parse `process.env` at module top-level in Workers:\n\n```ts\n\u002F\u002F WRONG — parsed before env is injected\nconst apiKey = process.env.MY_API_KEY;  \u002F\u002F undefined in Workers\n\n\u002F\u002F CORRECT — lazy parse inside a function or getter\nexport function getServerConfig() {\n  return ServerConfigSchema.parse({ apiKey: process.env.MY_API_KEY });\n}\n```\n\n**`in-memory` storage is volatile.** Data stored with the `in-memory` provider is lost between cold starts and is not shared across Worker instances. Use `cloudflare-kv`, `cloudflare-r2`, or `cloudflare-d1` for any state that must persist or be shared.\n\n**Multi-round-trip retries land on any isolate.** Each 2026-07-28 request builds its own `McpServer`, and the retry after an `input_required` result can be routed to a different isolate. Set `MCP_REQUEST_STATE_KEY` (≥ 32 bytes) as a Worker secret — it is a core binding, injected like the rest — so every isolate seals and verifies `requestState` with the same key, and keep a consent gate's record (`api-context` § *Consent gates*) in `cloudflare-d1`. `in-memory` loses it to the next isolate, so the retry asks again. Never `cloudflare-kv`: it is eventually consistent, so a retry served elsewhere may not see the record yet, and a deletion may not yet stop an immediate replay — it widens the window concurrent retries already have, since redeeming is not atomic on any provider until `ctx.state` gains a `take` ([#593](https:\u002F\u002Fgithub.com\u002Fcyanheads\u002Fmcp-ts-core\u002Fissues\u002F593)).\n\n**Node-only utilities throw in Workers.** `scheduler` (`node-cron`), `sanitizePath` (fs-based), and `filesystem` storage provider all throw `ConfigurationError` when called from a Worker. Guard with `runtimeCaps.isNode` or avoid entirely.\n\n**DataCanvas is unavailable in Workers.** DuckDB has no V8-isolate build, so `core.canvas` is always `undefined` on Workers. Setting `CANVAS_PROVIDER_TYPE=duckdb` (the only non-default value) in `wrangler.toml` triggers a fail-closed `ConfigurationError` at init time:\n\n> `DuckDB canvas requires Node.js or Bun. Set CANVAS_PROVIDER_TYPE=none or omit it for Cloudflare Workers deployment.`\n\nLeave the env unset (or set to `none`) for Worker deployments. Tools that conditionally use canvas should check the module-level accessor (`if (!getCanvas()) { ... }`) and surface a clear \"feature unavailable on this deployment\" message. See `api-canvas` for the full DataCanvas reference and setup wiring pattern.\n\n**The default notification bus is per-isolate.** `core.notify` and the modern era's `subscriptions\u002Flisten` streams share a change-event bus that defaults to in-process — which on Workers means one bus per isolate, so a background emission reaches only the listeners that happen to live in the isolate that produced it. Handler-time `ctx.notify*` is unaffected (the listen stream and the handler are the same request). For fan-out that must cross isolates, supply a bus of your own, backed by a Durable Object or another shared channel:\n\n```ts\ncreateWorkerHandler({ tools, eventBus: myDurableObjectBackedBus });\n```\n\nThe interface is the SDK's `ServerEventBus` — `publish(event)` and `subscribe(listener)`. See `api-context`'s notification section for what publishes onto it.\n\n---\n\n## Testing Workers with miniflare\n\n`bun run test:worker` runs the worker suite under `tests\u002Fconfig\u002Fvitest.worker.ts` (using `@cloudflare\u002Fvitest-pool-workers` + miniflare). Each test **file** gets its own fresh V8 isolate — module scope (including `createWorkerHandler`'s `appPromise` singleton) is reset between files.\n\n### tests\u002Fconfig\u002Fvitest.worker.ts miniflare bindings\n\nDeclare all storage bindings used in the suite:\n\n```ts\ncloudflareTest({\n  main: '.\u002Ftests\u002Ffixtures\u002Fworker-runtime.fixture.ts',\n  miniflare: {\n    bindings: { STORAGE_PROVIDER_TYPE: 'cloudflare-kv', ... },\n    kvNamespaces: ['KV_NAMESPACE', 'CUSTOM_KV'],\n    r2Buckets:    ['R2_BUCKET'],\n    d1Databases:  ['DB'],\n  },\n})\n```\n\nBinding names must match the hardcoded names in `storageFactory.ts` (`KV_NAMESPACE`, `R2_BUCKET`, `DB`).\n\n### Per-provider test isolation\n\n`bindings.STORAGE_PROVIDER_TYPE` is a global default. Per-provider test files override it by passing a modified env to `worker.fetch()`:\n\n```ts\nimport { env } from 'cloudflare:workers';\n\n\u002F\u002F Fresh isolate per file — appPromise starts null.\n\u002F\u002F First fetch initialises the singleton with the overridden provider type.\nconst r2Env = { ...env, STORAGE_PROVIDER_TYPE: 'cloudflare-r2' };\nawait worker.fetch(request, r2Env, ctx);\n```\n\nUse `reset()` from `cloudflare:test` in `afterEach` to clear binding state between tests. For D1, re-apply migrations immediately after each `reset()` (reset wipes the schema):\n\n```ts\nimport { applyD1Migrations, reset } from 'cloudflare:test';\n\nafterEach(async () => {\n  await reset();\n  await applyD1Migrations(env.DB, [{ name: '0001_schema', queries: [CREATE_TABLE_SQL] }]);\n});\n```\n\n### D1 schema setup\n\nThe `cloudflare-d1` provider requires the `kv_store` table before any operations. Apply it in `beforeAll` via `applyD1Migrations`:\n\n```ts\nconst KV_STORE_MIGRATION = `\nCREATE TABLE IF NOT EXISTS kv_store (\n  tenant_id TEXT NOT NULL,\n  key       TEXT NOT NULL,\n  value     TEXT NOT NULL,\n  expires_at INTEGER,\n  PRIMARY KEY (tenant_id, key)\n)`;\n\nbeforeAll(async () => {\n  await applyD1Migrations(env.DB, [\n    { name: '0001_create_kv_store', queries: [KV_STORE_MIGRATION] },\n  ]);\n  sessionId = await openSession(d1Env);\n});\n```\n\n### R2 list limit\n\nThe R2 provider fetches `limit + 1` objects to detect further pages. Miniflare caps R2 `MaxKeys` at 1000, so the default `limit=1000` → request 1001 → error. Pass `limit: 100` (or any value ≤ 999) to `ctx.state.list()` in test fixtures to stay under the cap:\n\n```ts\nconst result = await ctx.state.list(prefix, { limit: 100 });\n```\n\n### Storage probe pattern\n\nExpose storage operations as MCP tools in the fixture to test them through the real HTTP surface:\n\n```ts\nconst storageSetTool = tool('storage_set', {\n  input: z.object({ key: z.string().describe('...'), value: z.string().describe('...') }),\n  output: z.object({ ok: z.boolean().describe('Always true on success') }),\n  async handler(input, ctx) {\n    await ctx.state.set(input.key, input.value);\n    return { ok: true };\n  },\n  format: (r) => [{ type: 'text', text: `ok=${r.ok}` }],\n});\n```\n\nCall via `tools\u002Fcall` over MCP JSON-RPC and assert on `structuredContent`. See `tests\u002Fworker\u002Fstorage-r2.worker.test.ts` and `tests\u002Fworker\u002Fstorage-d1.worker.test.ts` for the full pattern.\n",{"name":5,"metadata":45,"description":49},{"type":34,"author":46,"version":47,"audience":48},"cyanheads","1.9","external","Cloudflare Workers deployment using `createWorkerHandler` from `@cyanheads\u002Fmcp-ts-core\u002Fworker`. Covers the full handler signature, binding types, CloudflareBindings extensibility, runtime compatibility guards, and wrangler.toml requirements.\n","main","3df1d0d67b30ff15236561f8c0f9f06d33f42dfd","skills\u002Fmcp-servers\u002Fcyanheads-api-workers",17,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia","https:\u002F\u002Feth2030.com","Hardcore infra. Building @alt-research and applied cryptography.","2026-11-15 02:28:10",{"source":8,"skillName":5,"commands":60,"prompt":70,"zipAvailable":71},[61,64,67],{"tool":62,"command":63},"npx","npx skills add jiayaoqijia\u002Fcryptoskill --skill api-workers",{"tool":65,"command":66},"bunx","bunx skills add jiayaoqijia\u002Fcryptoskill --skill api-workers",{"tool":68,"command":69},"pnpm","pnpm dlx skills add jiayaoqijia\u002Fcryptoskill --skill api-workers","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fcyanheads-api-workers\u002FSKILL.md",true,[73,77,83],{"path":74,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":76,"sourceHtmlUrl":16},"LICENSE","许可证",11317,{"path":78,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":81,"sourceHtmlUrl":82},"SOURCE.md","REFERENCE","参考文档",370,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fcyanheads-api-workers\u002FSOURCE.md",{"path":84,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":85,"sourceHtmlUrl":86},"TRUST.auto.yaml",2217,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fcyanheads-api-workers\u002FTRUST.auto.yaml",[88,98,106,114,122,130],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":92,"licenseFileUrl":93,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":97},"01M7DTKCERMV0RNX3HZJP4CZ26","troves","Deposit and withdraw from Troves DeFi yield vault strategies on Starknet. View available strategies, check positions, and manage vault deposits. Use this skill when the user mentions Troves, vault, yield vault, DeFi vault, strategy, yield farming, vault deposit, vault withdraw, earning yield through vaults, passive yield strategies, or wants to deposit into or withdraw from a yield strategy — even if they don't say \"Troves\" explicitly.","MIT","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-troves\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-troves\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":92,"licenseFileUrl":102,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":97},"01M7DTK6CJSMGC8KCQHGNYFZBD","trade","Swap tokens on Starknet via Fibrous DEX aggregator. Supports per-provider selection (avnu, ekubo, or auto to race all). Use this skill when the user wants to swap, exchange, trade, convert, buy, or sell one token for another on Starknet. Also use when the user asks about token prices, exchange rates, DEX routing, best swap route, or wants to check how much they would receive for a given amount — even if they don't explicitly say \"swap\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-trade\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-trade\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":92,"licenseFileUrl":110,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":97},"01M7DTJZ6A0X4PAW3Y8W4J9K64","staking","Stake, unstake, claim, and compound rewards for STRK, WBTC, tBTC, SolvBTC, and LBTC on Starknet. View validators, pools, and staking positions. Use this skill when the user mentions staking, delegating, validators, staking pools, rewards, compounding, unstaking, earning yield, passive income on crypto, or wants to earn on their STRK or BTC tokens — even if they don't say \"stake\" explicitly.","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-staking\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-staking\u002FSKILL.md",[],[],{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":92,"licenseFileUrl":118,"sourceHtmlUrl":119,"categories":120,"keywords":121,"publishedAt":97},"01M7DTJSDZJKCDMW7GHRF4BRH5","send","Send STRK, ETH, or any ERC-20 token to a Starknet address. Supports simulation (dry-run) before execution. Use this skill when the user wants to send, transfer, pay, tip, or move tokens to another wallet address on Starknet. Also trigger when the user mentions sending funds to someone, making a payment, transferring assets, or moving crypto to a specific address — even if they just say \"pay 10 STRK to 0x...\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-send\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-send\u002FSKILL.md",[],[],{"skillNo":123,"name":124,"nameZh":6,"description":125,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":92,"licenseFileUrl":126,"sourceHtmlUrl":127,"categories":128,"keywords":129,"publishedAt":97},"01M7DTJG1E480D51ZQ7WKDQ26K","portfolio","View a comprehensive DeFi portfolio dashboard and optimize portfolio allocation via automated rebalancing. Use this skill when the user wants an overview, summary, dashboard, total value, net worth, portfolio rebalancing, target allocation, or wants to see all their DeFi positions across Starknet at once. Also trigger when the user asks \"what do I have\", \"show me everything\", \"how much am I worth\", \"my positions\", \"my investments\", \"rebalance my portfolio\", \"I want 50% ETH\", \"optimize my holdings\", or any request for a holistic view of their Starknet holdings — even if they don't explicitly say \"portfolio\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-portfolio\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-portfolio\u002FSKILL.md",[],[],{"skillNo":131,"name":132,"nameZh":6,"description":133,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":92,"licenseFileUrl":134,"sourceHtmlUrl":135,"categories":136,"keywords":137,"publishedAt":97},"01M7DTJ7M8TE9R2N36HFBZDGVD","multi-swap","Execute multiple token swaps in a single Starknet transaction via Fibrous (default). Supports per-provider selection (avnu, ekubo, or auto to race all). Supports 2-3 swap pairs bundled into one multicall. Use this skill when the user wants to swap multiple token pairs at once, do batch swaps, execute several trades simultaneously, perform parallel swaps, or do bulk trading in one transaction. Also trigger when the user mentions \"two swaps\", \"three swaps\", \"swap X and Y at the same time\", or wants to convert multiple tokens in a single call.","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-multi-swap\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-multi-swap\u002FSKILL.md",[],[]]