From 67c7cb6972c86a2189520287ff4cabe4a2b3c5b0 Mon Sep 17 00:00:00 2001 From: Jonnie Lappen Date: Wed, 18 Nov 2026 15:19:36 -0700 Subject: [PATCH 01/27] feat(mcp-apps): add shared MCP Apps foundation defineMcpApp() serves a tool and its static ui:// HTML resource in both tool modes. apiReader() makes bounded, read-only Cloudflare API and GraphQL reads with the direct tools' refusal explanations and step-up. MCP_APPS is the one list an App is added to, and app-shell/ is the shared browser-side host connection and Kumo base. scripts/build-mcp-apps.ts builds every src//app. --- .gitignore | 1 + .oxfmtrc.json | 3 +- AGENTS.md | 7 + docs/mcp-apps.md | 44 + package-lock.json | 1871 ++++++++++++++++++++++-- package.json | 21 +- scripts/build-mcp-apps.ts | 50 + src/mcp-apps/api-read.ts | 201 +++ src/mcp-apps/app-shell/base.css | 25 + src/mcp-apps/app-shell/mount.tsx | 65 + src/mcp-apps/define.ts | 143 ++ src/mcp-apps/registry.ts | 55 + src/server.ts | 9 +- src/skills/handlers.ts | 41 +- src/tools/forge-tools.ts | 19 +- src/tools/tool-list-response.ts | 10 +- tests/auth/cimd.test.ts | 4 +- tests/auth/oauth-routes.test.ts | 4 +- tests/auth/token-compatibility.test.ts | 5 +- tests/forge-tools-worker.test.ts | 15 +- tests/mcp-apps.test.ts | 276 ++++ tests/mcp-client.test.ts | 9 +- tests/mcp-modern.test.ts | 16 +- tests/skills/server.test.ts | 6 +- tests/tool-list-response.test.ts | 6 +- tsconfig.app.json | 15 + tsconfig.json | 1 + 27 files changed, 2758 insertions(+), 164 deletions(-) create mode 100644 docs/mcp-apps.md create mode 100644 scripts/build-mcp-apps.ts create mode 100644 src/mcp-apps/api-read.ts create mode 100644 src/mcp-apps/app-shell/base.css create mode 100644 src/mcp-apps/app-shell/mount.tsx create mode 100644 src/mcp-apps/define.ts create mode 100644 src/mcp-apps/registry.ts create mode 100644 tests/mcp-apps.test.ts create mode 100644 tsconfig.app.json diff --git a/.gitignore b/.gitignore index 8fa91f764..7d8d81d6e 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ node_modules dist/ *.log .worktrees/ +.mcp-apps-build/ diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 19a7ede2b..855b92549 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -4,6 +4,7 @@ "semi": false, "trailingComma": "none", "ignorePatterns": [ - "src/generated/**" + "src/generated/**", + "src/*/app-html.generated.ts" ] } diff --git a/AGENTS.md b/AGENTS.md index 11236e71f..aa925d332 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,6 +22,7 @@ cloudflare-mcp/ │ ├── mcp-handler.ts # Stateless MCP HTTP handler & deployment guards │ ├── server.ts # MCP server setup & tool registration │ ├── events/ # Stateless MCP Events mapping to ANS policies and Vega automations +│ ├── mcp-apps/ # Shared MCP Apps: defineMcpApp, read-only apiReader, registry, app-shell │ ├── executor.ts # Code executor (Worker Loader API) │ ├── spec-processor.ts # OpenAPI spec $ref resolution & splitting merged paths │ ├── spec-release.ts # The pinned spec release and its artifact names @@ -67,6 +68,7 @@ cloudflare-mcp/ ├── scripts/ │ ├── cloudflare-account.ts # The account scripts run cf against │ ├── seed-r2.ts # Seed skills to R2 (cf r2 objects put) +│ ├── build-mcp-apps.ts # Build every src//app into app-html.generated.ts │ ├── generate-tools.ts # Regenerate src/generated/forge-mcp with forge │ ├── schema-mismatch-report.ts # Response schema mismatches by product, for teams │ └── bench-response-validation.ts # Cost of response schema checks on the generated schemas @@ -103,6 +105,7 @@ Node 22+ required. | `npm run deploy` | Deploy to staging | | `npm run deploy:prod` | Deploy to production by hand (merging to `main` already deploys) | | `npm run deploy:forge-tools` / `deploy:forge-tools:prod` | Deploy the forge tools service to staging / production | +| `npm run app:build` | Build every MCP App's HTML (`-- ` for one) | | `npm run generate:tools` | Regenerate `src/generated/forge-mcp` with the pinned `@cloudflare/forge` | | `npm run types` | Generate worker type definitions | | `npm run typecheck` | TypeScript type checking (no emit) | @@ -163,6 +166,10 @@ The core innovation: instead of 2,500 MCP tools (~244K tokens), two tools handle - `src/events/callback.ts` opens the sealed destination secret ANS presents, checks the KV subscription record and synchronously signs the MCP callback, with no Cloudflare API call. ANS owns retries. - `npm run test:events` runs local workerd coverage with simulated external HTTP endpoints. See `docs/mcp-events.md` for live tests and lifecycle constraints. +### MCP Apps + +`src/mcp-apps/` holds what every MCP App shares: `defineMcpApp()` (a tool plus its static `ui://` HTML resource, served in both tool modes), `apiReader()` (bounded, read-only Cloudflare API and GraphQL reads with the direct tools' refusal explanations and step-up), `MCP_APPS` in `registry.ts` (the one list an App is added to) and `app-shell/` (the browser-side host connection and Kumo base CSS). Each App lives in `src//`, with its React/Kumo view in `src//app/`, built into `app-html.generated.ts` by `npm run app:build`; never hand-edit those. `npm run check` verifies they are fresh and type-checks the view with `tsconfig.app.json`. See `docs/mcp-apps.md`. Keep raw customer prompts, account output and host screenshots outside this public repository. + ### Worker Loader API Code execution uses Cloudflare's Worker Loader API to dynamically create isolated worker instances. The API token is passed via props (never enters user code isolate). A `globalOutbound` service restricts network access. diff --git a/docs/mcp-apps.md b/docs/mcp-apps.md new file mode 100644 index 000000000..61e8415b6 --- /dev/null +++ b/docs/mcp-apps.md @@ -0,0 +1,44 @@ +# MCP Apps + +An MCP App is a tool whose result an [MCP Apps](https://github.com/modelcontextprotocol/ext-apps) host (ChatGPT, Claude) renders with a static HTML resource. Clients without Apps read the same result as JSON text and `structuredContent`, so an App never hides information from the model. + +Every App is served in both tool modes: Code Mode registers it next to `search` and `execute`, and `?codemode=false` lists it after `docs` and `whoami`, before the generated tools. + +## Layout + +``` +src/mcp-apps/ + define.ts defineMcpApp(): tool + resource + result shaping for one App + api-read.ts apiReader(): bounded, read-only Cloudflare API and GraphQL reads + registry.ts MCP_APPS: the one list every App is added to + app-shell/ browser side, shared by every App's HTML + mount.tsx mountMcpApp(): host connection, theme, validated results, fallback states + base.css Kumo + Tailwind base +src// + contract.ts input and output zod schemas, tool name, description + tool.ts defineMcpApp({...}) with the collector + app/index.html the App's entry; anything with this file is built + app/*.tsx, *.css the React/Kumo view + app-html.generated.ts written by npm run app:build; never edit +scripts/build-mcp-apps.ts Vite + Tailwind single-file build for every App +``` + +## Adding an App + +1. `src//contract.ts`: the input schema (`z.strictObject`) and the output schema. The output is the whole contract with the view and the model: give it a `kind` literal, and keep it to what the collector established. Anything it could not establish goes in a `limitations` list rather than being guessed. +2. `src//tool.ts`: `export const myApp = defineMcpApp({ name, title, description, annotations, input, output, resource: { uri: 'ui://cloudflare/.html', name, html: appHtml }, run })`. `run` returns `{ ok: true, value }` or `{ ok: false, text }`, and passes a refused read's `_meta` through so the client can step up. +3. `src//app/`: `index.html` loading a `.tsx` that calls `mountMcpApp({ name, output, render })`, and a CSS file that starts with `@import '../../mcp-apps/app-shell/base.css';` and `@source './.tsx';`. +4. Add the App to `MCP_APPS` in `src/mcp-apps/registry.ts`, then `npm run app:build`. +5. Tests: the collector against MSW, both tool modes through `exports.default.fetch`, and the tool-name lists that name every local tool (search the tests for `'whoami'`). + +## Rules + +- **Read-only unless the user confirms.** Collectors read with `apiReader`: GETs to fixed paths and GraphQL Analytics queries, with the request's credential, from this Worker. An App that offers a write (creating an alert, say) must show exactly what it will send and send it only through a separate, non-read-only tool the user confirms in the host. The App itself never holds a token. +- **No network from the App.** Its CSP allows no connect or resource domains. Everything it renders comes from the tool result, and `mountMcpApp` refuses a result that fails the output schema. +- **Bounded.** One read is at most 1 MB (`MAX_READ_BYTES`); collectors bound their own pagination and say what they skipped. +- **Refusals are explained, not hidden.** `apiReader` throws `ApiReadError` with the same explanation and step-up `_meta` the direct tools give. A GraphQL error with no data is a refusal only when its message names the analytics permission; a quota or query error passes through as Cloudflare's message. +- **Public repository.** Keep real customer prompts, account output and host screenshots out of it. + +## Build and check + +`npm run app:build` builds every App (`npm run app:build -- ` for one). `npm run check` runs `app:check`, which fails when a committed `app-html.generated.ts` is stale, and type-checks the browser code with `tsconfig.app.json`. diff --git a/package-lock.json b/package-lock.json index 23d3f9d75..e848a6d10 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,20 +17,100 @@ }, "devDependencies": { "@cloudflare/forge": "https://pkg.pr.new/cloudflare/forge/@cloudflare/forge@f6720c19250f90fe5b395ef2c38d488aaba31641", + "@cloudflare/kumo": "2.19.0", "@cloudflare/vitest-plugin": "^1.4.9", "@modelcontextprotocol/client": "2.3.1", + "@modelcontextprotocol/ext-apps": "2.0.4", + "@phosphor-icons/react": "2.1.10", + "@tailwindcss/vite": "4.3.5", "@types/node": "^25.0.6", + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", "msw": "^2.14.6", "oxfmt": "^0.74.0", "oxlint": "^1.46.0", + "react": "19.3.1", + "react-dom": "19.3.1", + "tailwindcss": "4.3.5", "tsx": "^4.22.4", "typescript": "^5.7.0", + "vite": "8.3.8", + "vite-plugin-singlefile": "2.3.4", "vitest": "^4.1.12", "workers-oauth-provider-0-10-2": "npm:@cloudflare/workers-oauth-provider@^0.10.2", "workers-oauth-provider-1-1-0": "npm:@cloudflare/workers-oauth-provider@^1.1.0", "wrangler": "^4.154.0" } }, + "node_modules/@babel/runtime": { + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-8.1.2.tgz", + "integrity": "sha512-Ay6HdEKZJAeGs6KKJ/ezCK5ssjFmkvUiR0TEGv/B1abyjLWrQ2RU+M507Ppk0NikhvVFhlEFC1/rHfCiYqSUcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@base-ui/react": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@base-ui/react/-/react-1.9.0.tgz", + "integrity": "sha512-S8CSYosASBKtpL8SWUfS78rFElfLijiCgA7oHOK22jCJ95FULsYyKwBNFOgudt0RA+/7yNc7F81bOvQnRgbBiQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.0", + "@base-ui/utils": "0.5.0", + "@floating-ui/react-dom": "^2.1.9", + "@floating-ui/utils": "^0.2.12", + "use-sync-external-store": "^1.7.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@date-fns/tz": "^1.2.0", + "@types/react": "^17 || ^18 || ^19", + "date-fns": "^4.0.0", + "react": "^17 || ^18 || ^19", + "react-dom": "^17 || ^18 || ^19" + }, + "peerDependenciesMeta": { + "@date-fns/tz": { + "optional": true + }, + "@types/react": { + "optional": true + }, + "date-fns": { + "optional": true + } + } + }, + "node_modules/@base-ui/utils": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@base-ui/utils/-/utils-0.5.0.tgz", + "integrity": "sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.0", + "@floating-ui/utils": "^0.2.12", + "reselect": "^5.3.0", + "use-sync-external-store": "^1.7.0" + }, + "peerDependencies": { + "@types/react": "^17 || ^18 || ^19", + "react": "^17 || ^18 || ^19", + "react-dom": "^17 || ^18 || ^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/@cfworker/json-schema": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz", @@ -58,6 +138,42 @@ } } }, + "node_modules/@cloudflare/kumo": { + "version": "2.19.0", + "resolved": "https://registry.npmjs.org/@cloudflare/kumo/-/kumo-2.19.0.tgz", + "integrity": "sha512-r6fQduVNZzRAIEATQLnIbCkYjbfBiELp51donxYkly2a1JE1GW3y+8HRmzp66s0s7xhwAbk9Wp6xFnZmbf6eoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@base-ui/react": "^1.9.0", + "@shikijs/langs": "^4.0.0", + "@shikijs/themes": "^4.0.0", + "cn": "0.4.0", + "d3-geo": "^3.1.1", + "motion": "^12.34.1", + "react-day-picker": "^9.13.2", + "shiki": "^4.0.0", + "use-sync-external-store": "^1.6.0" + }, + "bin": { + "kumo": "bin/kumo.js" + }, + "peerDependencies": { + "@phosphor-icons/react": "^2.1.10", + "echarts": "^6.0.0", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0", + "zod": "^4.0.0" + }, + "peerDependenciesMeta": { + "echarts": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, "node_modules/@cloudflare/kv-asset-handler": { "version": "0.5.0", "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz", @@ -205,6 +321,25 @@ "node": ">=12" } }, + "node_modules/@date-fns/tz": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.5.0.tgz", + "integrity": "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, "node_modules/@emnapi/runtime": { "version": "1.11.3", "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", @@ -216,6 +351,17 @@ "tslib": "^2.4.0" } }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", @@ -658,6 +804,48 @@ "node": ">=18" } }, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", + "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz", + "integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.8.0", + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz", + "integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.8.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", + "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", + "dev": true, + "license": "MIT" + }, "node_modules/@img/colour": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", @@ -1320,6 +1508,50 @@ } } }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/gen-mapping/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, "node_modules/@jridgewell/resolve-uri": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", @@ -1331,9 +1563,9 @@ } }, "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", "dev": true, "license": "MIT" }, @@ -1379,6 +1611,41 @@ "node": ">=20" } }, + "node_modules/@modelcontextprotocol/ext-apps": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/ext-apps/-/ext-apps-2.0.4.tgz", + "integrity": "sha512-B+PcbuGiaf0e5I3uy4iO5tS3Abo+5w8JvZFzHMzQdq9yVwP836zJkw2+KCGOQ0r4TM1fuQi4JdnbuWjkS4aBvg==", + "dev": true, + "license": "MIT", + "workspaces": [ + "examples/*" + ], + "dependencies": { + "@standard-schema/spec": "^1.1.0" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@modelcontextprotocol/client": "^2.0.0", + "@modelcontextprotocol/core": "^2.0.0", + "@modelcontextprotocol/server": "^2.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0", + "zod": "^4.2.0" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/server": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, "node_modules/@modelcontextprotocol/server": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.3.1.tgz", @@ -1417,6 +1684,28 @@ "dev": true, "license": "MIT" }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, "node_modules/@open-draft/deferred-promise": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/@open-draft/deferred-promise/-/deferred-promise-3.0.0.tgz", @@ -1443,9 +1732,9 @@ "license": "MIT" }, "node_modules/@oxc-project/types": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", - "integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==", + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", "dev": true, "license": "MIT", "funding": { @@ -2122,6 +2411,20 @@ "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/@phosphor-icons/react": { + "version": "2.1.10", + "resolved": "https://registry.npmjs.org/@phosphor-icons/react/-/react-2.1.10.tgz", + "integrity": "sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "react": ">= 16.8", + "react-dom": ">= 16.8" + } + }, "node_modules/@poppinss/colors": { "version": "4.1.6", "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", @@ -2152,9 +2455,9 @@ "license": "MIT" }, "node_modules/@rolldown/binding-android-arm-eabi": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz", - "integrity": "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", "cpu": [ "arm" ], @@ -2169,9 +2472,9 @@ } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.15.tgz", - "integrity": "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", "cpu": [ "arm64" ], @@ -2186,9 +2489,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.15.tgz", - "integrity": "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", "cpu": [ "arm64" ], @@ -2203,9 +2506,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.15.tgz", - "integrity": "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", "cpu": [ "x64" ], @@ -2220,9 +2523,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.15.tgz", - "integrity": "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", "cpu": [ "x64" ], @@ -2237,9 +2540,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.15.tgz", - "integrity": "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", "cpu": [ "arm" ], @@ -2254,9 +2557,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.15.tgz", - "integrity": "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", "cpu": [ "arm64" ], @@ -2274,9 +2577,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.15.tgz", - "integrity": "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", "cpu": [ "arm64" ], @@ -2294,9 +2597,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.15.tgz", - "integrity": "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", "cpu": [ "ppc64" ], @@ -2314,9 +2617,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.15.tgz", - "integrity": "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", "cpu": [ "s390x" ], @@ -2334,9 +2637,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.15.tgz", - "integrity": "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", "cpu": [ "x64" ], @@ -2354,9 +2657,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.15.tgz", - "integrity": "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", "cpu": [ "x64" ], @@ -2374,9 +2677,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.15.tgz", - "integrity": "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", "cpu": [ "arm64" ], @@ -2390,10 +2693,40 @@ "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.15.tgz", - "integrity": "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", "cpu": [ "arm64" ], @@ -2408,9 +2741,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.15.tgz", - "integrity": "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", "cpu": [ "x64" ], @@ -2425,9 +2758,117 @@ } }, "node_modules/@rolldown/pluginutils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", - "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@shikijs/core": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.6.0.tgz", + "integrity": "sha512-bfd4OKgvoyXYiYmMRuleA656P4V7M/Du9lcTl38Ngm6KszMj7bq4J1IGZwSYR4c95Tv5UQALtYNWUwaI9UT3xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/primitive": "4.6.0", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", + "@types/hast": "^3.0.5", + "hast-util-to-html": "^9.0.6" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/engine-javascript": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.6.0.tgz", + "integrity": "sha512-K0oqxFoL+kEMdz89mHLFO15Tsbv3kFZ6WR1cXZKMvLSc+oqaM00A6pyga1qSeXB22dP0tTiSApRcGBaKWsEccg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", + "oniguruma-to-es": "^4.3.6" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/engine-oniguruma": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.6.0.tgz", + "integrity": "sha512-aggd6Q7SuJOXNnsUbfG2XesxBJKBMAw/PDTUo9PyRjMaaJJ2dNrI+q0C+25ARXAK9yLHAlwxc9oRT2u68YKZ7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/langs": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.6.0.tgz", + "integrity": "sha512-1yMEX3oCVV54LUq/ovfpRkDQoYDkcvjSWFFa/YLUDMiSoRzMi2uxLJYbv41ahT8Lu9lFMaa7hecd3Q39trqUyg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.6.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/primitive": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.6.0.tgz", + "integrity": "sha512-c54+TQEo9ToqgfL/AU8FpjnV09+GA9Oa7M5ROkkXteZfp5XzpAJGXjjvZQFQioJOwm/w/6Z3lIzQstAkl8coag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", + "@types/hast": "^3.0.5" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/themes": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.6.0.tgz", + "integrity": "sha512-qHAVAs80RiGD+IRuH9G+JPDOEc9A/kHsng4EzCUCwB9bLzW6Z0y9WETh2YyCcADJBmfrIaJ1Jp7KBNP6FHkgtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.6.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/types": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.6.0.tgz", + "integrity": "sha512-+ENG1adsKt/X7cRYw1Nl7BEpBmPOjmQ7bR/eGmHuMlT8gtOFf3KEi5l31DJYyAWhW6Y6bjP1plU7FmaxWGENFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/vscode-textmate": "^10.1.0", + "@types/hast": "^3.0.5" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/vscode-textmate": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.1.0.tgz", + "integrity": "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ==", "dev": true, "license": "MIT" }, @@ -2458,39 +2899,460 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/chai": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", - "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "node_modules/@tabby_ai/hijri-converter": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@tabby_ai/hijri-converter/-/hijri-converter-1.0.5.tgz", + "integrity": "sha512-r5bClKrcIusDoo049dSL8CawnHR6mRdDwhlQuIgZRNty68q0x8k3Lf1BtPAMxRf/GgnHBnIO4ujd3+GQdLWzxQ==", "dev": true, "license": "MIT", - "dependencies": { - "@types/deep-eql": "*", - "assertion-error": "^2.0.1" + "engines": { + "node": ">=16.0.0" } }, - "node_modules/@types/deep-eql": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", - "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/estree": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", - "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "node_modules/@tailwindcss/node": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.5.tgz", + "integrity": "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==", "dev": true, - "license": "MIT" + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.5", + "jiti": "^2.7.0", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.5" + } }, - "node_modules/@types/node": { - "version": "25.0.6", - "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.6.tgz", - "integrity": "sha512-NNu0sjyNxpoiW3YuVFfNz7mxSQ+S4X2G28uqg2s+CzoqoQjLPsWSbsFFyztIAqt2vb8kfEAsJNepMGPTxFDx3Q==", + "node_modules/@tailwindcss/node/node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~7.16.0" + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.5.tgz", + "integrity": "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-x64": "4.3.5", + "@tailwindcss/oxide-freebsd-x64": "4.3.5", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-x64-musl": "4.3.5", + "@tailwindcss/oxide-wasm32-wasi": "4.3.5", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.5.tgz", + "integrity": "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.5.tgz", + "integrity": "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.5.tgz", + "integrity": "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.5.tgz", + "integrity": "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.5.tgz", + "integrity": "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.5.tgz", + "integrity": "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.5.tgz", + "integrity": "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.5.tgz", + "integrity": "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.5.tgz", + "integrity": "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.5.tgz", + "integrity": "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.11.3", + "@emnapi/runtime": "^1.11.3", + "@emnapi/wasi-threads": "^1.2.3", + "@napi-rs/wasm-runtime": "^1.2.2", + "@tybys/wasm-util": "^0.10.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.2", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", + "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { + "version": "0.10.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { + "version": "2.8.1", + "dev": true, + "inBundle": true, + "license": "0BSD", + "optional": true + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.5.tgz", + "integrity": "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.5.tgz", + "integrity": "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/vite": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.5.tgz", + "integrity": "sha512-BCNiY0a1ZjdOHVqw7kyb7U72BwfMF3dfUuN+tQsLWky/J5JOI/r7abibglXfygrZhVO/3u3V+E25kkKTeMkXaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tailwindcss/node": "4.3.5", + "@tailwindcss/oxide": "4.3.5", + "tailwindcss": "4.3.5" + }, + "peerDependencies": { + "vite": "^5.2.0 || ^6 || ^7 || ^8" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/hast": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz", + "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/mdast": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/node": { + "version": "25.0.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.6.tgz", + "integrity": "sha512-NNu0sjyNxpoiW3YuVFfNz7mxSQ+S4X2G28uqg2s+CzoqoQjLPsWSbsFFyztIAqt2vb8kfEAsJNepMGPTxFDx3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" } }, "node_modules/@types/set-cookie-parser": { @@ -2510,6 +3372,20 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@ungap/structured-clone": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.4.0.tgz", + "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==", + "dev": true, + "license": "ISC" + }, "node_modules/@vitest/expect": { "version": "4.1.12", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.12.tgz", @@ -2666,6 +3542,17 @@ "dev": true, "license": "MIT" }, + "node_modules/ccount": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", + "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/chai": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", @@ -2676,6 +3563,28 @@ "node": ">=18" } }, + "node_modules/character-entities-html4": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", + "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-legacy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", + "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/cjs-module-lexer": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.3.tgz", @@ -2708,6 +3617,19 @@ "node": ">=12" } }, + "node_modules/cn": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/cn/-/cn-0.4.0.tgz", + "integrity": "sha512-qOAeUhPwPzBxx6jaeQdo646XIKliKHc2j1ZF7Ngb1o0pJZKH5gq8FkA0aVdUdPFUDXNXyUCXpCtoJISo6dhizg==", + "dev": true, + "license": "MIT", + "bin": { + "cn": "bin/cn.mjs" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -2728,6 +3650,17 @@ "dev": true, "license": "MIT" }, + "node_modules/comma-separated-tokens": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", + "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -2764,6 +3697,67 @@ "node": ">= 8" } }, + "node_modules/csstype": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz", + "integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/d3-array": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.5.tgz", + "integrity": "sha512-Th8qGXoBalmWsstpkuhmBuTsBQIFqYOJtjlBvNVvBfJ8E3uYusBUwUR8HU20U0qKKQkgCvKyR1YjiozWadk5QA==", + "dev": true, + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-geo": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.2.tgz", + "integrity": "sha512-5R8ZgDQorIxmauv7R6gpE/ndz+Z0qAZssigq0aXFdvPHdY41RqtW02jrRUQAL724NdPABYXo1+gQEGBBr7uKNg==", + "dev": true, + "license": "ISC", + "dependencies": { + "d3-array": "2.5.0 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/date-fns": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz", + "integrity": "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/kossnocorp" + } + }, + "node_modules/date-fns-jalali": { + "version": "4.1.0-0", + "resolved": "https://registry.npmjs.org/date-fns-jalali/-/date-fns-jalali-4.1.0-0.tgz", + "integrity": "sha512-hTIP/z+t+qKwBDcmmsnmjWTduxCg+5KfdqWQvb2X/8C9+knYY6epN/pfxdDuyVlSVeFz0sM5eEfwIUQ70U4ckg==", + "dev": true, + "license": "MIT" + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -2774,6 +3768,20 @@ "node": ">=8" } }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -2781,6 +3789,20 @@ "dev": true, "license": "MIT" }, + "node_modules/enhanced-resolve": { + "version": "5.27.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz", + "integrity": "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/error-stack-parser-es": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz", @@ -2938,6 +3960,34 @@ } } }, + "node_modules/framer-motion": { + "version": "12.43.0", + "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.43.0.tgz", + "integrity": "sha512-1eaL3RvR/kAlbG7UYcpMptEyzPoENO0c6w7ZnB3/hh2vSAz/6uGAFn6fdoqTBguNstf3MsFhJHsD/0DHiclG+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "motion-dom": "^12.43.0", + "motion-utils": "^12.39.0", + "tslib": "^2.4.0" + }, + "peerDependencies": { + "@emotion/is-prop-valid": "*", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/is-prop-valid": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -2963,6 +4013,13 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/graphql": { "version": "16.14.1", "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.14.1.tgz", @@ -2973,6 +4030,44 @@ "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" } }, + "node_modules/hast-util-to-html": { + "version": "9.0.7", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.7.tgz", + "integrity": "sha512-HYNDA3qdnzUPitY/LcQm1nWs8z0cWFNH1Nz09jdI/tXifAqF7h3+jrLl4S/b9Mi4VSjn0Dsn54ctuTV6zhBthA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "comma-separated-tokens": "^2.0.0", + "hast-util-whitespace": "^3.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "stringify-entities": "^4.0.0", + "zwitch": "^2.0.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-whitespace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", + "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/headers-polyfill": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/headers-polyfill/-/headers-polyfill-5.0.1.tgz", @@ -2993,6 +4088,27 @@ "node": ">=16.9.0" } }, + "node_modules/html-void-elements": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", + "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/internmap": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -3017,6 +4133,16 @@ "dev": true, "license": "ISC" }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, "node_modules/jose": { "version": "6.1.3", "resolved": "https://registry.npmjs.org/jose/-/jose-6.1.3.tgz", @@ -3302,24 +4428,140 @@ "os": [ "win32" ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/mdast-util-to-hast": { + "version": "13.2.2", + "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.2.tgz", + "integrity": "sha512-l2pnmOuqs+SGLVpTVXnRLQu5v1AzvDe181404fbXzzqObVxrAnnVxapAP27pUwzLBL/ABIkgUhGlPVU7QSvIFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "trim-lines": "^3.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-util-character": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" } }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "node_modules/micromark-util-encode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], "license": "MIT", "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" } }, + "node_modules/micromark-util-symbol": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.3.tgz", + "integrity": "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, "node_modules/miniflare": { "version": "5.20261023.1-beta", "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261023.1-beta.tgz", @@ -3338,6 +4580,50 @@ "node": ">=22.0.0" } }, + "node_modules/motion": { + "version": "12.43.0", + "resolved": "https://registry.npmjs.org/motion/-/motion-12.43.0.tgz", + "integrity": "sha512-BQgQbSa9Hn3/mtbib0MK53y6JSANa+YKUKlaYnWzAVDH424RYQ5LVpV3pNiWH00BA2z4ojsSdMzqT7g2FQwjuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "framer-motion": "^12.43.0", + "tslib": "^2.4.0" + }, + "peerDependencies": { + "@emotion/is-prop-valid": "*", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/is-prop-valid": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/motion-dom": { + "version": "12.43.0", + "resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-12.43.0.tgz", + "integrity": "sha512-azKON4d9S65PEoFUiQTMTgPheEmzf2QngdRc50AKfJp9Q9mmcBVw22c8eMq9k8kxOFHdL7+WZY7N/5F/lwiDag==", + "dev": true, + "license": "MIT", + "dependencies": { + "motion-utils": "^12.39.0" + } + }, + "node_modules/motion-utils": { + "version": "12.39.0", + "resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-12.39.0.tgz", + "integrity": "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ==", + "dev": true, + "license": "MIT" + }, "node_modules/msw": { "version": "2.14.6", "resolved": "https://registry.npmjs.org/msw/-/msw-2.14.6.tgz", @@ -3426,6 +4712,25 @@ "node": ">=12.20.0" } }, + "node_modules/oniguruma-parser": { + "version": "0.12.2", + "resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.2.tgz", + "integrity": "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw==", + "dev": true, + "license": "MIT" + }, + "node_modules/oniguruma-to-es": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.6.tgz", + "integrity": "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==", + "dev": true, + "license": "MIT", + "dependencies": { + "oniguruma-parser": "^0.12.2", + "regex": "^6.1.0", + "regex-recursion": "^6.0.2" + } + }, "node_modules/outvariant": { "version": "1.4.3", "resolved": "https://registry.npmjs.org/outvariant/-/outvariant-1.4.3.tgz", @@ -3589,9 +4894,9 @@ } }, "node_modules/postcss": { - "version": "8.5.31", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.31.tgz", - "integrity": "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==", + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", "dev": true, "funding": [ { @@ -3617,6 +4922,90 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/property-information": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz", + "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-day-picker": { + "version": "9.14.0", + "resolved": "https://registry.npmjs.org/react-day-picker/-/react-day-picker-9.14.0.tgz", + "integrity": "sha512-tBaoDWjPwe0M5pGrum4H0SR6Lyk+BO9oHnp9JbKpGKW2mlraNPgP9BMfsg5pWpwrssARmeqk7YBl2oXutZTaHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@date-fns/tz": "^1.4.1", + "@tabby_ai/hijri-converter": "1.0.5", + "date-fns": "^4.1.0", + "date-fns-jalali": "4.1.0-0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/gpbl" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/regex/-/regex-6.1.0.tgz", + "integrity": "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-recursion": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz", + "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-utilities": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz", + "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==", + "dev": true, + "license": "MIT" + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -3627,6 +5016,13 @@ "node": ">=0.10.0" } }, + "node_modules/reselect": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.3.0.tgz", + "integrity": "sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg==", + "dev": true, + "license": "MIT" + }, "node_modules/rettime": { "version": "0.11.11", "resolved": "https://registry.npmjs.org/rettime/-/rettime-0.11.11.tgz", @@ -3635,13 +5031,13 @@ "license": "MIT" }, "node_modules/rolldown": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.15.tgz", - "integrity": "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.155.0", + "@oxc-project/types": "=0.156.0", "@rolldown/pluginutils": "^1.0.0" }, "bin": { @@ -3651,22 +5047,30 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm-eabi": "1.2.15", - "@rolldown/binding-android-arm64": "1.2.15", - "@rolldown/binding-darwin-arm64": "1.2.15", - "@rolldown/binding-darwin-x64": "1.2.15", - "@rolldown/binding-freebsd-x64": "1.2.15", - "@rolldown/binding-linux-arm-gnueabihf": "1.2.15", - "@rolldown/binding-linux-arm64-gnu": "1.2.15", - "@rolldown/binding-linux-arm64-musl": "1.2.15", - "@rolldown/binding-linux-ppc64-gnu": "1.2.15", - "@rolldown/binding-linux-s390x-gnu": "1.2.15", - "@rolldown/binding-linux-x64-gnu": "1.2.15", - "@rolldown/binding-linux-x64-musl": "1.2.15", - "@rolldown/binding-openharmony-arm64": "1.2.15", - "@rolldown/binding-win32-arm64-msvc": "1.2.15", - "@rolldown/binding-win32-x64-msvc": "1.2.15" - } + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "dev": true, + "license": "MIT" }, "node_modules/semver": { "version": "7.8.5", @@ -3761,6 +5165,26 @@ "node": ">=8" } }, + "node_modules/shiki": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.6.0.tgz", + "integrity": "sha512-imjLsVHgPuWhvpU3P+zOekvMYqnel7QmKsFC4Sn0fCuAvaaalBsxwKEsrU8Ko5BdFnZA6Go/8a0RzahS634UgA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/core": "4.6.0", + "@shikijs/engine-javascript": "4.6.0", + "@shikijs/engine-oniguruma": "4.6.0", + "@shikijs/langs": "4.6.0", + "@shikijs/themes": "4.6.0", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", + "@types/hast": "^3.0.5" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/siginfo": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", @@ -3782,15 +5206,26 @@ } }, "node_modules/source-map-js": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", - "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.3.tgz", + "integrity": "sha512-xj+WrAkyv5Qp+t7r9N5HvCBu7g1qOe6CKRNpq22X1GGcPEQADFU54v5qsPVs3/vrUFQ7XivFrcAVKA2stI0kWA==", "dev": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" } }, + "node_modules/space-separated-tokens": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", + "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -3837,6 +5272,21 @@ "node": ">=8" } }, + "node_modules/stringify-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", + "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", + "dev": true, + "license": "MIT", + "dependencies": { + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -3876,6 +5326,27 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/tailwindcss": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.5.tgz", + "integrity": "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.4.tgz", + "integrity": "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", @@ -3963,13 +5434,23 @@ "node": ">=16" } }, + "node_modules/trim-lines": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", + "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "dev": true, - "license": "0BSD", - "optional": true + "license": "0BSD" }, "node_modules/tsx": { "version": "4.22.4", @@ -4047,6 +5528,79 @@ "pathe": "^2.0.3" } }, + "node_modules/unist-util-is": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", + "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", + "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.2.0.tgz", + "integrity": "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.1.0.tgz", + "integrity": "sha512-vKXxz6O38sKDj1mtx/k2cWvkkFBuYGx6uGrlzBkVeWCRF/F8sdI0j3Wbkz/5rVNRRuVc8UrgRdbCxNhmYXgP3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/until-async": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/until-async/-/until-async-3.0.2.tgz", @@ -4057,17 +5611,57 @@ "url": "https://github.com/sponsors/kettanaito" } }, + "node_modules/use-sync-external-store": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz", + "integrity": "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/vfile": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", + "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.4.tgz", + "integrity": "sha512-66ycRswIkNmHH9PHku7ADtv5RVwgIrOcuv3J8Svz6h4qgGRrKVa+9/neuKyJZUXyOpYwLTvS+whZ4R2urHHgQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/vite": { - "version": "8.3.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", - "integrity": "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==", + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", "dev": true, "license": "MIT", "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", - "postcss": "^8.5.30", - "rolldown": "~1.2.14", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", "tinyglobby": "^0.2.17" }, "bin": { @@ -4135,6 +5729,28 @@ } } }, + "node_modules/vite-plugin-singlefile": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/vite-plugin-singlefile/-/vite-plugin-singlefile-2.3.4.tgz", + "integrity": "sha512-1FAhlTCL6KJDpSUudrVU+gspapvS+tmKCg70vwNaAU6tyXn3E/C6+NnwQIze06byhBRv7VggZ78K0h+J/Rsdrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^4.0.7" + }, + "engines": { + "node": ">18.0.0" + }, + "peerDependencies": { + "rollup": "^4.59.0", + "vite": "^5.4.21 || ^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, "node_modules/vitest": { "version": "4.1.12", "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.12.tgz", @@ -4458,6 +6074,17 @@ "funding": { "url": "https://github.com/sponsors/colinhacks" } + }, + "node_modules/zwitch": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", + "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } } } } diff --git a/package.json b/package.json index d0f2a322b..4161e03d8 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "deploy:forge-tools:prod": "wrangler deploy -c wrangler.forge-tools.jsonc --env production", "deploy:prod": "wrangler deploy --env production", "types": "wrangler types --env-file .env_example -c wrangler.jsonc -c wrangler.forge-tools.jsonc", - "typecheck": "tsc --noEmit", + "typecheck": "tsc --noEmit && tsc -p tsconfig.app.json", "lint": "oxlint src/ --ignore-pattern 'src/generated/**'", "format": "oxfmt --write src/ tests/ scripts/ vitest.config.ts", "generate:tools": "tsx scripts/generate-tools.ts", @@ -19,10 +19,12 @@ "test:events": "vitest run tests/events-e2e.test.ts tests/ans-bridge.test.ts", "events:receiver": "node scripts/mcp-events-receiver.mjs", "test:watch": "vitest", - "check": "npm run format:check && npm run lint && npm run typecheck && npm run test", + "check": "npm run app:check && npm run format:check && npm run lint && npm run typecheck && npm run test", "seed:staging": "tsx scripts/seed-r2.ts staging", "seed:prod": "tsx scripts/seed-r2.ts production", - "report:schema-mismatches": "tsx scripts/schema-mismatch-report.ts" + "report:schema-mismatches": "tsx scripts/schema-mismatch-report.ts", + "app:build": "tsx scripts/build-mcp-apps.ts", + "app:check": "tsx scripts/build-mcp-apps.ts --check" }, "dependencies": { "@cfworker/json-schema": "^4.1.1", @@ -45,6 +47,17 @@ "vitest": "^4.1.12", "workers-oauth-provider-0-10-2": "npm:@cloudflare/workers-oauth-provider@^0.10.2", "workers-oauth-provider-1-1-0": "npm:@cloudflare/workers-oauth-provider@^1.1.0", - "wrangler": "^4.154.0" + "wrangler": "^4.154.0", + "@cloudflare/kumo": "2.19.0", + "@modelcontextprotocol/ext-apps": "2.0.4", + "@phosphor-icons/react": "2.1.10", + "@tailwindcss/vite": "4.3.5", + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", + "react": "19.3.1", + "react-dom": "19.3.1", + "tailwindcss": "4.3.5", + "vite": "8.3.8", + "vite-plugin-singlefile": "2.3.4" } } diff --git a/scripts/build-mcp-apps.ts b/scripts/build-mcp-apps.ts new file mode 100644 index 000000000..d7da16286 --- /dev/null +++ b/scripts/build-mcp-apps.ts @@ -0,0 +1,50 @@ +import { build } from 'vite' +import tailwindcss from '@tailwindcss/vite' +import { viteSingleFile } from 'vite-plugin-singlefile' +import { readdir, readFile, writeFile } from 'node:fs/promises' +import { existsSync } from 'node:fs' +import path from 'node:path' + +/** + * Build every MCP App into one self-contained HTML file, written as a text + * module the Worker serves (`src//app-html.generated.ts`). + * + * An App is any `src//app/index.html`. `--check` fails when a committed + * module is stale, so `npm run check` catches an App edited without a rebuild. + * + * npm run app:build # every App + * npm run app:build -- # one App, by its src/ directory name + */ +const check = process.argv.includes('--check') +const only = process.argv.slice(2).filter((arg) => !arg.startsWith('--')) + +const apps = (await readdir('src', { withFileTypes: true })) + .filter( + (entry) => entry.isDirectory() && existsSync(path.join('src', entry.name, 'app/index.html')) + ) + .map((entry) => entry.name) + .filter((name) => only.length === 0 || only.includes(name)) + .sort() + +const stale: string[] = [] +for (const name of apps) { + const outDir = path.resolve('.mcp-apps-build', name) + await build({ + configFile: false, + logLevel: 'error', + root: path.join('src', name, 'app'), + plugins: [tailwindcss(), viteSingleFile()], + build: { outDir, emptyOutDir: true, minify: true } + }) + const html = await readFile(path.join(outDir, 'index.html'), 'utf8') + const generated = `// Generated by npm run app:build. Do not edit.\nexport const appHtml = ${JSON.stringify(html)}\n` + const target = path.join('src', name, 'app-html.generated.ts') + if (check) { + const current = existsSync(target) ? await readFile(target, 'utf8') : '' + if (current !== generated) stale.push(target) + } else { + await writeFile(target, generated) + console.log(`built ${target} (${Math.round(html.length / 1024)} KB)`) + } +} +if (stale.length) throw new Error(`Stale MCP App HTML: ${stale.join(', ')}. Run npm run app:build.`) diff --git a/src/mcp-apps/api-read.ts b/src/mcp-apps/api-read.ts new file mode 100644 index 000000000..91452c229 --- /dev/null +++ b/src/mcp-apps/api-read.ts @@ -0,0 +1,201 @@ +import { z } from 'zod' +import { env } from 'cloudflare:workers' +import type { CallToolResult } from '@modelcontextprotocol/server' +import { acceptedPermissions, authorize, explainRefusal, findOperation } from '../api-permissions' +import { getPermissionPaths } from '../isolate-cache' +import { apiCallResult } from '../tools/api-call-result' +import { WWW_AUTHENTICATE_META_KEY } from '../scope-challenge' +import { truncateResponse } from '../truncate' +import { fetchWithRetry } from '../utils/fetch-retry' +import type { AppContext } from './define' + +/** The most an App reads from one response. Apps show summaries, not pages of records. */ +export const MAX_READ_BYTES = 1024 * 1024 + +/** + * Cloudflare refused or failed a read. `result` is the tool error the direct + * tools would give for the same request: method, path, status, Cloudflare's + * errors, an explanation and, for a missing OAuth scope, the step-up `_meta`. + */ +export class ApiReadError extends Error { + constructor(readonly result: CallToolResult) { + super('Cloudflare API read refused or failed') + } + /** The tool error's text. */ + get text(): string { + const text = this.result.content.find((c) => c.type === 'text') + return text?.type === 'text' ? text.text : this.message + } +} + +/** A response larger than {@link MAX_READ_BYTES}, or not JSON. */ +export class ApiReadUnsupported extends Error {} + +/** The GraphQL Analytics API, which the spec doesn't list, and the permission each dataset kind needs. */ +const GRAPHQL_PERMISSIONS = { + zone: ['Analytics Read'], + account: ['Account Analytics Read'] +} as const + +/** + * Whether GraphQL errors say the credential lacks the dataset's analytics + * permission. A zone dataset names the permission; an account dataset says + * only `authorization denied`. Kept in step with `graphqlRefusal` in + * `src/tools/execute.ts`. + */ +export function graphqlRefused( + messages: readonly string[], + dataset: keyof typeof GRAPHQL_PERMISSIONS +): boolean { + return dataset === 'zone' + ? messages.some((m) => m.includes("'com.cloudflare.api.account.zone.analytics.read'")) + : messages.some( + (m) => + /^authorization denied$/i.test(m.trim()) || + m.includes("'com.cloudflare.api.account.analytics.read'") + ) +} + +async function readBounded(response: Response): Promise { + const reader = response.body?.getReader() + const chunks: Uint8Array[] = [] + let bytes = 0 + if (reader) + for (;;) { + const part = await reader.read() + if (part.done) break + bytes += part.value.byteLength + if (bytes > MAX_READ_BYTES) { + await reader.cancel() + throw new ApiReadUnsupported('Response exceeded the 1 MB App read limit.') + } + chunks.push(part.value) + } + const raw = new Uint8Array(bytes) + let offset = 0 + for (const chunk of chunks) { + raw.set(chunk, offset) + offset += chunk.length + } + try { + return JSON.parse(new TextDecoder().decode(raw)) + } catch { + throw new ApiReadUnsupported('Cloudflare returned a non-JSON response.') + } +} + +/** + * Read-only Cloudflare API access for one App call. Every read is a GET to a + * fixed path, or a GraphQL Analytics query (which has no mutations), sent with + * the request's credential from this Worker: the token never reaches the App. + */ +export interface ApiReader { + /** + * GET `path` below the API base and parse its body with `schema`. + * + * @throws {ApiReadError} for a refusal or failure, explained like the direct tools. + * @throws {ApiReadUnsupported} for an oversized or non-JSON body. + * @throws {z.ZodError} when the body doesn't match `schema`. + */ + get(path: string, schema: S): Promise> + /** + * POST a GraphQL Analytics query and parse its `data` with `schema`. + * + * @param dataset - Which permission the query's datasets need: `account` or `zone`. + * @throws {ApiReadError} when it returns errors and no data, explained as a refusal of the analytics permission. + */ + graphql( + query: string, + variables: Record, + dataset: keyof typeof GRAPHQL_PERMISSIONS, + schema: S + ): Promise> +} + +/** + * Create the reader for one App call. + * + * @param context - The request's credential, connection and step-up challenge. + * @param signal - Aborts every read when the call is cancelled. + * @param caller - Names the App in `fetchWithRetry` logs. + */ +export function apiReader(context: AppContext, signal: AbortSignal, caller: string): ApiReader { + const base = env.CLOUDFLARE_API_BASE.replace(/\/$/, '') + const basePath = new URL(base).pathname + const send = (path: string, init: RequestInit) => + fetchWithRetry( + base + path, + { + ...init, + redirect: 'manual', + signal, + headers: { + ...init.headers, + authorization: `Bearer ${context.props.accessToken}`, + accept: 'application/json' + } + }, + { caller } + ) + + return { + async get(path, schema) { + const response = await send(path, { method: 'GET' }) + const body = await readBounded(response) + const requestPath = new URL(base + path).pathname.slice(basePath.length) + const match = findOperation(getPermissionPaths(), 'GET', requestPath) + const result = apiCallResult( + { + method: 'GET', + path: requestPath, + template: match?.template ?? requestPath, + permissions: acceptedPermissions(match?.operation), + status: response.status, + body + }, + [], + { ...context, formatResult: truncateResponse } + ) + if (result.isError) throw new ApiReadError(result) + return schema.parse(body) + }, + + async graphql(query, variables, dataset, schema) { + const response = await send('/graphql', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ query, variables }) + }) + const body = (await readBounded(response)) as { data?: unknown; errors?: unknown } + const errors = Array.isArray(body?.errors) ? (body.errors as { message?: unknown }[]) : [] + if (response.ok && body?.data != null) return schema.parse(body.data) + const messages = errors.map((e) => String(e.message ?? '')).filter(Boolean) + // The API answers a missing permission with 200 and `data: null`, as it + // does a quota or a bad query, so only a permission message is a refusal. + const refused = graphqlRefused(messages, dataset) + const authorization = refused + ? authorize( + context.connection, + { method: 'POST', path: '/graphql' }, + GRAPHQL_PERMISSIONS[dataset] + ) + : undefined + const text = [ + `Cloudflare API error: POST /graphql returned HTTP ${response.status} with no data.`, + truncateResponse(messages), + authorization && explainRefusal(403, authorization) + ] + .filter(Boolean) + .join('\n\n') + const challenge = + authorization?.kind === 'missing' && authorization.scope + ? context.scopeChallenge.require(authorization.scope) + : undefined + throw new ApiReadError({ + isError: true, + content: [{ type: 'text', text }], + ...(challenge ? { _meta: { [WWW_AUTHENTICATE_META_KEY]: [challenge] } } : {}) + }) + } + } +} diff --git a/src/mcp-apps/app-shell/base.css b/src/mcp-apps/app-shell/base.css new file mode 100644 index 000000000..06309ded0 --- /dev/null +++ b/src/mcp-apps/app-shell/base.css @@ -0,0 +1,25 @@ +/* + * Shared base for every MCP App. Each App's own CSS imports this first: + * @import '../../mcp-apps/app-shell/base.css'; + * @source './.tsx'; + * Kumo tokens come from @cloudflare/kumo; the host's theme sets data-mode. + */ +@import '@cloudflare/kumo/styles/tailwind'; +@import 'tailwindcss' source(none); +@source '../../../node_modules/@cloudflare/kumo/dist/**/*.js'; + +html, +body { + margin: 0; + padding: 0; + background: transparent; + color: var(--text-color-kumo-default); + font: + 14px/1.5 ui-sans-serif, + system-ui, + sans-serif; + -webkit-font-smoothing: antialiased; +} +#root { + padding: 12px; +} diff --git a/src/mcp-apps/app-shell/mount.tsx b/src/mcp-apps/app-shell/mount.tsx new file mode 100644 index 000000000..76c0d4175 --- /dev/null +++ b/src/mcp-apps/app-shell/mount.tsx @@ -0,0 +1,65 @@ +import type { ReactNode } from 'react' +import { createRoot } from 'react-dom/client' +import { App } from '@modelcontextprotocol/ext-apps' +import type { z } from 'zod' + +/** How the host's state reaches the App's view. */ +export interface MountedApp { + /** The connected host bridge, for `callServerTool`, `sendMessage` and `updateModelContext`. */ + readonly app: App +} + +export interface MountOptions { + /** Shown to the host in `ui/initialize`. */ + readonly name: string + readonly version?: string + /** The tool's output schema; a result that doesn't match is shown as malformed, never guessed at. */ + readonly output: Output + /** Render a validated result. */ + readonly render: (value: z.output, mounted: MountedApp) => ReactNode + /** Copy for the states no tool result describes. Defaults are generic. */ + readonly copy?: Partial> +} + +function applyTheme(mode: string | undefined) { + if (!mode) return + document.documentElement.dataset.mode = mode + document.documentElement.style.colorScheme = mode +} + +/** + * Mount an MCP App into `#root`: connect to the host, follow its theme, and + * render each tool result that matches the output schema. + * + * Apps hold no credentials and make no network requests; everything they show + * comes from the tool result. A result that fails validation, a cancelled call + * and a lost host connection each get a plain message pointing at the tool's + * text result, which every host shows. + */ +export function mountMcpApp(options: MountOptions): void { + const copy = { + pending: 'Loading…', + cancelled: 'Cancelled.', + malformed: 'This result could not be displayed. Check the tool’s text result.', + disconnected: 'Could not connect to the host. The text result remains available.', + ...options.copy + } + const root = createRoot(document.getElementById('root')!) + const app = new App({ name: options.name, version: options.version ?? '1.0.0' }, {}) + const mounted: MountedApp = { app } + + root.render(

{copy.pending}

) + app.onhostcontextchanged = (context) => applyTheme(context.theme) + app.ontoolresult = (result) => { + applyTheme(app.getHostContext()?.theme) + const parsed = options.output.safeParse(result.structuredContent) + root.render( + parsed.success ? options.render(parsed.data, mounted) :

{copy.malformed}

+ ) + } + app.ontoolcancelled = () => root.render(

{copy.cancelled}

) + app + .connect() + .then(() => applyTheme(app.getHostContext()?.theme)) + .catch(() => root.render(

{copy.disconnected}

)) +} diff --git a/src/mcp-apps/define.ts b/src/mcp-apps/define.ts new file mode 100644 index 000000000..d73830531 --- /dev/null +++ b/src/mcp-apps/define.ts @@ -0,0 +1,143 @@ +import type { + CallToolResult, + ServerContext, + Tool, + ToolAnnotations +} from '@modelcontextprotocol/server' +import { z } from 'zod' +import type { AuthProps } from '../auth/types' +import type { Connection } from '../api-permissions' +import type { ScopeChallenge } from '../scope-challenge' +import type { StaticResource } from '../skills/handlers' +import { withCachedJsonSchema } from '../lib/isolate-json-schema' + +/** The MIME type MCP Apps hosts render as an App. */ +export const MCP_APP_MIME = 'text/html;profile=mcp-app' + +/** What an App's collector gets from the authenticated request. */ +export interface AppContext { + /** The request's validated credential. Its token never reaches the App's HTML. */ + readonly props: AuthProps + /** What the credential may do, for explaining refused API reads. */ + readonly connection: Connection + /** Where a refused read records a missing OAuth scope, for step-up. */ + readonly scopeChallenge: ScopeChallenge +} + +/** What an App's collector returns: its validated result, or a tool error. */ +export type AppOutcome = + | { readonly ok: true; readonly value: Output; readonly meta?: CallToolResult['_meta'] } + | { readonly ok: false; readonly text: string; readonly meta?: CallToolResult['_meta'] } + +/** An App's tool and its HTML resource, served in both tool modes. */ +export interface McpApp { + /** The tool as `tools/list` sends it, for the direct tools' hand-written listing. */ + readonly tool: Tool + /** The App's HTML, served through `resources/list` and `resources/read`. */ + readonly resource: StaticResource + /** The zod schemas Code Mode registers, JSON Schema conversion cached per isolate. */ + readonly inputSchema: z.ZodObject + readonly outputSchema: z.ZodType + /** Validate the arguments, run the collector and shape the result. */ + call(args: unknown, context: AppContext, ctx: ServerContext): Promise +} + +export interface McpAppDefinition { + /** The tool name, such as `workers_deployment_status`. A permanent contract. */ + readonly name: string + readonly title: string + /** When to call the tool, what it reads and what it doesn't prove. Hosts route on this. */ + readonly description: string + readonly annotations: ToolAnnotations + readonly input: Input + readonly output: Output + readonly resource: { + /** `ui://cloudflare/.html`. */ + readonly uri: `ui://${string}` + readonly name: string + /** The self-contained HTML `npm run app:build` generates. */ + readonly html: string + } + /** Collect the result. Reads must stop when `signal` aborts. */ + run( + input: z.output, + context: AppContext, + signal: AbortSignal + ): Promise>> +} + +/** + * The signal a tool call stops on: the MCP request's, and the HTTP request's + * when the client disconnects. + */ +export function toolSignal(ctx: ServerContext): AbortSignal { + return ctx.http?.req + ? AbortSignal.any([ctx.mcpReq.signal, ctx.http.req.signal]) + : ctx.mcpReq.signal +} + +/** + * Define an MCP App: a tool whose result an MCP Apps host renders with a + * static HTML resource, and that clients without Apps read as JSON text and + * `structuredContent`. + * + * Call it once at module scope. The App's HTML holds no account data or + * credentials and makes no network requests (its CSP allows none); everything + * it shows comes from the tool result. + * + * @param definition - The tool's contract, its HTML and its collector. + * @returns The App, for `MCP_APPS` in `src/mcp-apps/registry.ts`. + */ +export function defineMcpApp( + definition: McpAppDefinition +): McpApp { + const { uri, name: resourceName, html } = definition.resource + const meta = { ui: { resourceUri: uri }, 'ui/resourceUri': uri } + const tool: Tool = { + name: definition.name, + title: definition.title, + description: definition.description, + annotations: definition.annotations, + _meta: meta, + inputSchema: z.toJSONSchema(definition.input) as Tool['inputSchema'], + outputSchema: z.toJSONSchema(definition.output) as Tool['outputSchema'] + } + const resource: StaticResource = { + descriptor: { uri, name: resourceName, mimeType: MCP_APP_MIME }, + content: { + uri, + mimeType: MCP_APP_MIME, + text: html, + _meta: { ui: { csp: { connectDomains: [], resourceDomains: [] } } } + } + } + return { + tool, + resource, + inputSchema: withCachedJsonSchema(definition.input), + outputSchema: withCachedJsonSchema(definition.output), + async call(args, context, ctx) { + const parsed = definition.input.safeParse(args) + if (!parsed.success) + return { + isError: true, + content: [ + { + type: 'text', + text: `Invalid arguments for tool ${definition.name}: ${z.prettifyError(parsed.error)}` + } + ] + } + const outcome = await definition.run(parsed.data, context, toolSignal(ctx)) + const meta = outcome.meta ? { _meta: outcome.meta } : {} + if (!outcome.ok) + return { isError: true, content: [{ type: 'text', text: outcome.text }], ...meta } + const value = definition.output.parse(outcome.value) as Record + return { + content: [{ type: 'text', text: JSON.stringify(value) }], + structuredContent: value, + ...meta + } + } + } +} diff --git a/src/mcp-apps/registry.ts b/src/mcp-apps/registry.ts new file mode 100644 index 000000000..89caa2a28 --- /dev/null +++ b/src/mcp-apps/registry.ts @@ -0,0 +1,55 @@ +import type { McpServer, Tool } from '@modelcontextprotocol/server' +import type { StaticResource } from '../skills/handlers' +// App imports, one per line. +import type { AppContext, McpApp } from './define' + +const apps: McpApp[] = [] +// Each App adds its import above and one push here; nothing else in the server +// changes. One statement per App, on either side of this comment, so Apps in +// flight at once merge in any order. See `docs/mcp-apps.md`. + +/** Every MCP App this Worker serves, in listing order. */ +export const MCP_APPS: readonly McpApp[] = apps + +/** The Apps' tools, for the direct tools' hand-written `tools/list`. */ +export const MCP_APP_TOOLS: readonly Tool[] = MCP_APPS.map((app) => app.tool) + +/** The Apps' HTML, served next to the skills' files. */ +export const MCP_APP_RESOURCES: readonly StaticResource[] = MCP_APPS.map((app) => app.resource) + +const BY_NAME: ReadonlyMap = new Map(MCP_APPS.map((app) => [app.tool.name, app])) + +/** The App whose tool is `name`, for the direct tools' `tools/call`. */ +export function mcpAppNamed(name: string): McpApp | undefined { + return BY_NAME.get(name) +} + +/** + * Register every App's tool on a Code Mode server. The direct tools serve + * them through `registerForgeTools` instead. + * + * @param server - The per-request MCP server. + * @param context - The request's credential, connection and step-up challenge. + * @param apps - Defaults to {@link MCP_APPS}; tests pass their own. + */ +export function registerMcpApps( + server: McpServer, + context: AppContext, + apps: readonly McpApp[] = MCP_APPS +): void { + for (const app of apps) { + const { name, title, description, annotations, _meta } = app.tool + server.registerTool( + name, + { + title, + description, + annotations: { ...annotations }, + _meta, + inputSchema: app.inputSchema, + outputSchema: app.outputSchema + }, + (args, ctx) => app.call(args, context, ctx) + ) + } +} diff --git a/src/server.ts b/src/server.ts index 5167f4bdc..87dd3d223 100644 --- a/src/server.ts +++ b/src/server.ts @@ -6,6 +6,7 @@ import { registerExecuteTool } from './tools/execute' import { registerWhoamiTool } from './tools/whoami' import { registerSubmitFeedbackTool } from './tools/submit-feedback' import { registerSkills } from './skills/handlers' +import { MCP_APP_RESOURCES, registerMcpApps } from './mcp-apps/registry' import { attachMetrics } from './metrics' import { SERVER_INFO } from './constants' import { stringifyResponse, truncateResponse } from './truncate' @@ -19,8 +20,8 @@ import { ScopeChallenge } from './scope-challenge' export interface ServerOptions { /** * Register the Code Mode tools (`search`, `execute`). When `false`, register - * the direct tools forge generates, one per API method, instead. `docs` and - * `whoami` are registered in both modes. Defaults to `true`. + * the direct tools forge generates, one per API method, instead. `docs`, + * `whoami` and the MCP Apps (`src/mcp-apps/registry.ts`) are registered in both modes. Defaults to `true`. */ readonly codemode?: boolean /** @@ -79,7 +80,8 @@ export function createServer( // registerTool can default the capability to true. server.server.registerCapabilities({ tools: { listChanged: false } }) // Skills (io.modelcontextprotocol/skills) are served in both tool modes. - registerSkills(server) + // MCP Apps' HTML resources are served next to the skills' files. + registerSkills(server, MCP_APP_RESOURCES) if (events) registerEventMethods(server, events.env, props, events.bearer) if (!codemode) { const formatResult = truncateToolResult ? truncateResponse : stringifyResponse @@ -97,6 +99,7 @@ export function createServer( registerExecuteTool(server, props, truncateToolResult, connection, scopeChallenge) registerWhoamiTool(server, props) registerSubmitFeedbackTool(server, props) + registerMcpApps(server, { props, connection, scopeChallenge }) return server } diff --git a/src/skills/handlers.ts b/src/skills/handlers.ts index 4b18ca877..4c1f154af 100644 --- a/src/skills/handlers.ts +++ b/src/skills/handlers.ts @@ -3,7 +3,9 @@ import { ProtocolError, ProtocolErrorCode, ResourceNotFoundError, - type McpServer + type McpServer, + type ReadResourceResult, + type Resource } from '@modelcontextprotocol/server' import { getSkills, readSkillFile } from '../isolate-cache' import { SKILLS_EXTENSION_ID } from './types' @@ -24,6 +26,17 @@ function toBase64(bytes: Uint8Array): string { return btoa(binary) } +/** + * A resource that ships with the Worker and is the same for every user, such + * as an MCP App's HTML. Served next to the skills' files. + */ +export interface StaticResource { + /** The entry in `resources/list`. */ + readonly descriptor: Resource + /** The content `resources/read` returns for the descriptor's URI. */ + readonly content: ReadResourceResult['contents'][number] +} + const ListSkillsParams = z.looseObject({ cursor: z.string().optional() }).optional() const GetSkillParams = z.looseObject({ uri: z.string() }) @@ -39,8 +52,15 @@ const GetSkillParams = z.looseObject({ uri: z.string() }) * * The capability is declared without `directoryRead`: every entry carries a * complete manifest, which the spec lets hosts answer directory questions from. + * + * @param server - The per-request MCP server. + * @param staticResources - Resources that ship with the Worker, listed and read + * through the same handlers. */ -export function registerSkills(server: McpServer): void { +export function registerSkills( + server: McpServer, + staticResources: readonly StaticResource[] = [] +): void { server.server.registerCapabilities({ resources: {}, extensions: { [SKILLS_EXTENSION_ID]: {} } @@ -66,12 +86,15 @@ export function registerSkills(server: McpServer): void { server.server.setRequestHandler('resources/list', async () => { const { skills } = await getSkills() return { - resources: skills.map((skill) => ({ - uri: skill.uri, - name: skill.frontmatter.name, - description: skill.frontmatter.description, - mimeType: 'text/markdown' - })), + resources: [ + ...skills.map((skill) => ({ + uri: skill.uri, + name: skill.frontmatter.name, + description: skill.frontmatter.description, + mimeType: 'text/markdown' + })), + ...staticResources.map((resource) => resource.descriptor) + ], ...SKILLS_CACHE } }) @@ -83,6 +106,8 @@ export function registerSkills(server: McpServer): void { server.server.setRequestHandler('resources/read', async (request) => { const { uri } = request.params + const shipped = staticResources.find((resource) => resource.descriptor.uri === uri) + if (shipped) return { contents: [shipped.content], ...SKILLS_CACHE } const file = (await getSkills()).filesByUri.get(uri) if (!file) throw new ResourceNotFoundError(uri, `No resource is served at ${uri}`) const bytes = await readSkillFile(file) diff --git a/src/tools/forge-tools.ts b/src/tools/forge-tools.ts index 4b8cf7e53..9cbadf432 100644 --- a/src/tools/forge-tools.ts +++ b/src/tools/forge-tools.ts @@ -1,7 +1,7 @@ import { z } from 'zod' import { env } from 'cloudflare:workers' import { PROTOCOL_VERSION_META_KEY } from '@modelcontextprotocol/server' -import type { McpServer, CallToolResult, ServerContext } from '@modelcontextprotocol/server' +import type { McpServer, CallToolResult, ServerContext, Tool } from '@modelcontextprotocol/server' import type { FormatToolResult } from '../truncate' import { fetchWithRetry } from '../utils/fetch-retry' import { rateLimitHint } from '../rate-limit' @@ -16,6 +16,7 @@ import { checkResponse } from '../response-validation' import { DOCS_TOOL, runDocsTool } from './docs-search' import { WHOAMI_TOOL, WhoamiInputSchema, runWhoamiTool } from './whoami' import { SUBMIT_FEEDBACK_TOOL, feedbackTools, runSubmitFeedbackTool } from './submit-feedback' +import { MCP_APP_TOOLS, mcpAppNamed } from '../mcp-apps/registry' import type { AuthProps } from '../auth/types' import { acceptedPermissions, type Connection } from '../api-permissions' import { apiCallResult } from './api-call-result' @@ -26,6 +27,16 @@ import type { CallPlan } from '../forge-tools/plan' import { FORGE_ACCOUNT_DISCOVERY_GUIDANCE, PERMISSIONS_EXTENSION } from '../forge-tools/policy' import { policyRefusalHint } from '../policy-guards' +/** + * The tools this Worker serves itself in direct mode, listed before the + * generated ones: `docs`, `whoami`, `submit_feedback` when it is configured, + * and the MCP Apps. Both `tools/list` paths + * (the SDK's and `cachedToolListResponse`) send this list. + */ +export function localDirectTools(): Tool[] { + return [DOCS_TOOL, WHOAMI_TOOL, ...feedbackTools(), ...MCP_APP_TOOLS] +} + /** The forge tools service, which holds the generated tools (`src/forge-tools/worker.ts`). */ function forgeTools() { return env.FORGE_TOOLS @@ -58,9 +69,7 @@ export function registerForgeTools( ): void { server.server.setRequestHandler('tools/list', async (_request, ctx) => ({ tools: [ - DOCS_TOOL, - WHOAMI_TOOL, - ...feedbackTools(), + ...localDirectTools(), ...(await getForgeToolList({ outputSchema: outputSchema && isModern(ctx) })) ] })) @@ -83,6 +92,8 @@ export function registerForgeTools( : toolError(`Invalid arguments for tool ${name}: ${parsed.error.message}`) } else if (name === SUBMIT_FEEDBACK_TOOL.name && feedbackTools().length > 0) { result = await runSubmitFeedbackTool(args, 'direct', props) + } else if (mcpAppNamed(name)) { + result = await mcpAppNamed(name)!.call(args, { props, connection, scopeChallenge }, ctx) } else { const sessionAccountId = autoResolvedAccountId(props) const plan = (await forgeTools().plan(name, args, { diff --git a/src/tools/tool-list-response.ts b/src/tools/tool-list-response.ts index 614e6a01c..3c845034e 100644 --- a/src/tools/tool-list-response.ts +++ b/src/tools/tool-list-response.ts @@ -1,8 +1,6 @@ import { isLegacyRequest, SUPPORTED_PROTOCOL_VERSIONS } from '@modelcontextprotocol/server' import type { Tool } from '@modelcontextprotocol/server' -import { DOCS_TOOL } from './docs-search' -import { WHOAMI_TOOL } from './whoami' -import { feedbackTools } from './submit-feedback' +import { localDirectTools } from './forge-tools' import { isolate } from '../lib/isolate' /** @@ -18,7 +16,7 @@ const MAX_BODY_BYTES = 4096 * the stringify this replaces. */ const toolsJson = isolate.derived((tools: readonly Tool[]) => - new TextEncoder().encode(JSON.stringify([DOCS_TOOL, WHOAMI_TOOL, ...feedbackTools(), ...tools])) + new TextEncoder().encode(JSON.stringify([...localDirectTools(), ...tools])) ) /** A lone 2025-era `tools/list` request for the first page, or `undefined` for anything else. */ @@ -64,13 +62,13 @@ async function plainToolListRequestId(request: Request): Promise { 'docs', 'search', 'execute', - 'whoami' + 'whoami', + ...MCP_APP_TOOLS.map((tool) => tool.name) ]) expect(metadataFetches).toBeGreaterThan(0) diff --git a/tests/auth/oauth-routes.test.ts b/tests/auth/oauth-routes.test.ts index a2514bec2..245067431 100644 --- a/tests/auth/oauth-routes.test.ts +++ b/tests/auth/oauth-routes.test.ts @@ -7,6 +7,7 @@ import { clearKv } from '../helpers/kv' import { modernMcpRequest, parseMcpResult } from '../helpers/mcp' import { ALL_SCOPES } from '../../src/auth/scopes' import { server } from '../setup/msw' +import { MCP_APP_TOOLS } from '../../src/mcp-apps/registry' /** * Worker-seam tests for the OAuth route layer (`createAuthHandlers` in @@ -925,7 +926,8 @@ describe('GET /oauth/callback', () => { 'docs', 'search', 'execute', - 'whoami' + 'whoami', + ...MCP_APP_TOOLS.map((tool) => tool.name) ]) expect((await env.OAUTH_KV.list({ prefix: 'client:' })).keys).toHaveLength(1) }) diff --git a/tests/auth/token-compatibility.test.ts b/tests/auth/token-compatibility.test.ts index 84cc22e1b..76d7914cf 100644 --- a/tests/auth/token-compatibility.test.ts +++ b/tests/auth/token-compatibility.test.ts @@ -9,6 +9,7 @@ import { cfAccountsSuccess, cfSuccess } from '../helpers/cloudflare-api' import { clearKv } from '../helpers/kv' import { modernMcpRequest, parseMcpResult } from '../helpers/mcp' import { server } from '../setup/msw' +import { MCP_APP_TOOLS } from '../../src/mcp-apps/registry' /** * Grants and tokens issued before an upgrade keep working after it. Each case issues them with the @@ -211,7 +212,7 @@ describe.each(LEGACY_DEPLOYMENTS)( // The access token issued before the upgrade is accepted as it is. expect(await listTools(legacy.access_token)).toEqual({ status: 200, - tools: ['docs', 'search', 'execute', 'whoami'] + tools: ['docs', 'search', 'execute', 'whoami', ...MCP_APP_TOOLS.map((tool) => tool.name)] }) // The refresh token is too, and the upstream Cloudflare grant rotates with it. @@ -226,7 +227,7 @@ describe.each(LEGACY_DEPLOYMENTS)( expect(upstreamRefreshes()).toEqual(['upstream-refresh-1']) expect(await listTools(tokens.access_token)).toEqual({ status: 200, - tools: ['docs', 'search', 'execute', 'whoami'] + tools: ['docs', 'search', 'execute', 'whoami', ...MCP_APP_TOOLS.map((tool) => tool.name)] }) // The grant is rewritten in the current format (with KV key metadata) and keeps its resource. diff --git a/tests/forge-tools-worker.test.ts b/tests/forge-tools-worker.test.ts index 766764376..402e32e9f 100644 --- a/tests/forge-tools-worker.test.ts +++ b/tests/forge-tools-worker.test.ts @@ -14,6 +14,7 @@ import { toolText } from './helpers/mcp' import { server } from './setup/msw' +import { MCP_APP_TOOLS } from '../src/mcp-apps/registry' /** * The generated direct tools at /mcp?codemode=false, @@ -66,12 +67,13 @@ afterEach(async () => { }) describe('generated direct tools (?codemode=false)', () => { - it('lists docs, whoami and every generated tool, without their request code or response schemas', async () => { + it('lists the local tools and every generated tool, without their request code or response schemas', async () => { const tools = await listForgeTools(ACCOUNT_TOKEN) expect(tools.map((tool) => tool.name)).toEqual([ 'docs', 'whoami', + ...MCP_APP_TOOLS.map((tool) => tool.name), ...generatedTools.map((tool) => tool.name) ]) const d1 = tools.find((tool) => tool.name === 'd1_list')! @@ -424,7 +426,13 @@ describe('generated direct tools (?codemode=false)', () => { const codemode = (await listTools(ACCOUNT_TOKEN, MCP_URL)).map((t) => t.name) expect(direct).toContain('d1_list') - expect(codemode).toEqual(['docs', 'search', 'execute', 'whoami']) + expect(codemode).toEqual([ + 'docs', + 'search', + 'execute', + 'whoami', + ...MCP_APP_TOOLS.map((tool) => tool.name) + ]) }) describe('results', () => { @@ -488,6 +496,7 @@ describe('generated direct tools (?codemode=false)', () => { expect(tools.filter((tool) => tool.outputSchema).map((tool) => tool.name)).toEqual([ 'docs', 'whoami', + ...MCP_APP_TOOLS.map((tool) => tool.name), ...withOutput ]) }) @@ -501,7 +510,7 @@ describe('generated direct tools (?codemode=false)', () => { expect(tools.length).toBeGreaterThan(0) const named = tools.filter((tool) => tool.outputSchema).map((tool) => tool.name) - expect(named.filter((name) => name !== 'docs' && name !== 'whoami')).toEqual([]) + expect(named).toEqual(['docs', 'whoami', ...MCP_APP_TOOLS.map((tool) => tool.name)]) }) describe('calls', () => { diff --git a/tests/mcp-apps.test.ts b/tests/mcp-apps.test.ts new file mode 100644 index 000000000..8e99355f1 --- /dev/null +++ b/tests/mcp-apps.test.ts @@ -0,0 +1,276 @@ +import { env, exports } from 'cloudflare:workers' +import { Client } from '@modelcontextprotocol/client' +import { InMemoryTransport, McpServer } from '@modelcontextprotocol/server' +import { http, HttpResponse } from 'msw' +import { z } from 'zod' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { AUTH_PROPS_VERSION, type AuthProps } from '../src/auth/types' +import { DIRECT_CONNECTION, type Connection } from '../src/api-permissions' +import { ScopeChallenge } from '../src/scope-challenge' +import { defineMcpApp, MCP_APP_MIME, type AppContext } from '../src/mcp-apps/define' +import { + ApiReadError, + ApiReadUnsupported, + apiReader, + graphqlRefused +} from '../src/mcp-apps/api-read' +import { MCP_APPS, registerMcpApps } from '../src/mcp-apps/registry' +import { localDirectTools } from '../src/tools/forge-tools' +import { API_BASE, cfError, cfSuccess, mockIdentityProbe } from './helpers/cloudflare-api' +import { clearKv } from './helpers/kv' +import { MCP_URL, modernMcpRequest, parseMcpResult } from './helpers/mcp' +import { clearSpec, seedSpec } from './helpers/spec' +import { server } from './setup/msw' + +const ACCOUNT_ID = '023e105f4ecef8ad9ca31a8372d0c353' +const props: AuthProps = { + type: 'account_token', + accessToken: 'app-token', + account: { id: ACCOUNT_ID, name: 'Apps Co' } +} + +function context(connection: Connection = DIRECT_CONNECTION): AppContext { + return { props, connection, scopeChallenge: new ScopeChallenge(undefined) } +} + +/** A fixture App: reads the account's Worker names. */ +const fixture = defineMcpApp({ + name: 'fixture_app', + title: 'Fixture App', + description: 'Lists Worker names. Test fixture only.', + annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, + input: z.strictObject({ prefix: z.string().optional() }), + output: z.strictObject({ kind: z.literal('fixture'), names: z.array(z.string()) }), + resource: { uri: 'ui://cloudflare/fixture.html', name: 'Fixture', html: '

fixture

' }, + async run(input, ctx, signal) { + const scripts = await apiReader(ctx, signal, 'fixture_app') + .get( + `/accounts/${ACCOUNT_ID}/workers/scripts`, + z.object({ result: z.array(z.object({ id: z.string() })) }) + ) + .catch((error: unknown) => error) + if (scripts instanceof ApiReadError) + return { ok: false, text: scripts.text, meta: scripts.result._meta } + if (scripts instanceof Error) throw scripts + const names = (scripts as { result: { id: string }[] }).result + .map((s) => s.id) + .filter((id) => !input.prefix || id.startsWith(input.prefix)) + return { ok: true, value: { kind: 'fixture' as const, names } } + } +}) + +async function connected(apps = [fixture]) { + const mcp = new McpServer({ name: 'apps-test', version: '1.0.0' }) + registerMcpApps(mcp, context(), apps) + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair() + const client = new Client({ name: 'test-client', version: '1.0.0' }) + await Promise.all([mcp.connect(serverTransport), client.connect(clientTransport)]) + return client +} + +beforeEach(async () => { + await seedSpec({ + '/accounts/{account_id}/workers/scripts': { + get: { 'x-api-token-group': ['Workers Scripts Read'] } + } + }) +}) + +afterEach(async () => { + await clearSpec() + await clearKv(env.OAUTH_KV) +}) + +describe('defineMcpApp', () => { + it('describes the tool and its App resource', () => { + expect(fixture.tool).toMatchObject({ + name: 'fixture_app', + _meta: { + ui: { resourceUri: 'ui://cloudflare/fixture.html' }, + 'ui/resourceUri': 'ui://cloudflare/fixture.html' + }, + inputSchema: { type: 'object', additionalProperties: false }, + outputSchema: { type: 'object', required: ['kind', 'names'] } + }) + expect(fixture.resource).toEqual({ + descriptor: { uri: 'ui://cloudflare/fixture.html', name: 'Fixture', mimeType: MCP_APP_MIME }, + content: { + uri: 'ui://cloudflare/fixture.html', + mimeType: MCP_APP_MIME, + text: '

fixture

', + _meta: { ui: { csp: { connectDomains: [], resourceDomains: [] } } } + } + }) + }) + + it('lists in Code Mode with the same definition the direct tools send', async () => { + const client = await connected() + const listed = (await client.listTools()).tools + expect(JSON.parse(JSON.stringify(listed))).toEqual([ + expect.objectContaining({ + name: fixture.tool.name, + _meta: fixture.tool._meta, + inputSchema: fixture.tool.inputSchema, + outputSchema: fixture.tool.outputSchema + }) + ]) + }) + + it('returns the validated result as text and structuredContent', async () => { + server.use( + http.get(`${API_BASE}/accounts/${ACCOUNT_ID}/workers/scripts`, () => + HttpResponse.json(cfSuccess([{ id: 'api-mcp' }, { id: 'docs' }])) + ) + ) + const client = await connected() + const result = await client.callTool({ name: 'fixture_app', arguments: { prefix: 'api' } }) + expect(result.structuredContent).toEqual({ kind: 'fixture', names: ['api-mcp'] }) + expect(result.content).toEqual([ + { type: 'text', text: '{"kind":"fixture","names":["api-mcp"]}' } + ]) + }) + + it('refuses invalid arguments without calling the API', async () => { + const result = await fixture.call({ prefix: 1 }, context(), { + mcpReq: { signal: new AbortController().signal } + } as never) + expect(result.isError).toBe(true) + expect(JSON.stringify(result.content)).toContain('Invalid arguments for tool fixture_app') + }) +}) + +describe('apiReader', () => { + const signal = new AbortController().signal + + it('explains a refused read like the direct tools', async () => { + server.use( + http.get(`${API_BASE}/accounts/${ACCOUNT_ID}/workers/scripts`, () => + HttpResponse.json(cfError([{ code: 10000, message: 'Authentication error' }]), { + status: 403 + }) + ) + ) + const error = await apiReader(context({ kind: 'oauth', scopes: [] }), signal, 'test') + .get(`/accounts/${ACCOUNT_ID}/workers/scripts`, z.unknown()) + .catch((e: unknown) => e) + expect(error).toBeInstanceOf(ApiReadError) + const text = (error as ApiReadError).text + expect(text).toContain(`GET /accounts/${ACCOUNT_ID}/workers/scripts returned HTTP 403`) + expect(text).toContain('workers-scripts.read') + }) + + it('sends the credential only to the Cloudflare API', async () => { + let authorization: string | null = null + server.use( + http.get(`${API_BASE}/accounts/${ACCOUNT_ID}/workers/scripts`, ({ request }) => { + authorization = request.headers.get('authorization') + return HttpResponse.json(cfSuccess([])) + }) + ) + await apiReader(context(), signal, 'test').get( + `/accounts/${ACCOUNT_ID}/workers/scripts`, + z.unknown() + ) + expect(authorization).toBe('Bearer app-token') + }) + + it('refuses a body over the read limit', async () => { + server.use( + http.get(`${API_BASE}/accounts/${ACCOUNT_ID}/workers/scripts`, () => + HttpResponse.text('x'.repeat(1024 * 1024 + 1)) + ) + ) + await expect( + apiReader(context(), signal, 'test').get( + `/accounts/${ACCOUNT_ID}/workers/scripts`, + z.unknown() + ) + ).rejects.toBeInstanceOf(ApiReadUnsupported) + }) + + it('parses GraphQL data', async () => { + server.use( + http.post(`${API_BASE}/graphql`, () => + HttpResponse.json({ data: { viewer: { ok: true } }, errors: null }) + ) + ) + const data = await apiReader(context(), signal, 'test').graphql( + '{ viewer { ok } }', + {}, + 'account', + z.object({ viewer: z.object({ ok: z.boolean() }) }) + ) + expect(data).toEqual({ viewer: { ok: true } }) + }) + + it('explains an account GraphQL refusal as missing Account Analytics Read', async () => { + server.use( + http.post(`${API_BASE}/graphql`, () => + HttpResponse.json({ data: null, errors: [{ message: 'authorization denied' }] }) + ) + ) + const error = await apiReader(context({ kind: 'oauth', scopes: [] }), signal, 'test') + .graphql('{ viewer { ok } }', {}, 'account', z.unknown()) + .catch((e: unknown) => e) + expect(error).toBeInstanceOf(ApiReadError) + expect((error as ApiReadError).text).toContain('account-analytics.read') + }) + + it('does not call a GraphQL quota error a refusal', async () => { + const quota = 'cannot request a time range wider than 4w4d' + server.use( + http.post(`${API_BASE}/graphql`, () => + HttpResponse.json({ data: null, errors: [{ message: quota }] }) + ) + ) + const error = await apiReader(context({ kind: 'oauth', scopes: [] }), signal, 'test') + .graphql('{ viewer { ok } }', {}, 'account', z.unknown()) + .catch((e: unknown) => e) + const text = (error as ApiReadError).text + expect(text).toContain(quota) + expect(text).not.toContain('scope') + }) + + it.each([ + [['authorization denied'], 'account', true], + [["does not have permission 'com.cloudflare.api.account.zone.analytics.read'"], 'zone', true], + [['authorization denied'], 'zone', false], + [['unknown field'], 'account', false] + ] as const)('graphqlRefused(%j, %s) is %s', (messages, dataset, refused) => { + expect(graphqlRefused(messages, dataset)).toBe(refused) + }) +}) + +describe('MCP Apps in the worker', () => { + const TOKEN = 'apps-worker-token' + + beforeEach(() => { + mockIdentityProbe({ accounts: [{ id: ACCOUNT_ID, name: 'Apps Co' }] }) + }) + + async function modern(method: string, params: Record = {}, url = MCP_URL) { + const response = await exports.default.fetch(modernMcpRequest(TOKEN, method, params, { url })) + return (await parseMcpResult(response)) as { + result?: { tools?: { name: string }[]; resources?: { uri: string }[] } + } + } + + it('lists every registered App in both tool modes, after docs and whoami', async () => { + const names = MCP_APPS.map((app) => app.tool.name) + const codemode = await modern('tools/list') + expect(codemode.result?.tools?.map((t) => t.name)).toEqual([ + 'docs', + 'search', + 'execute', + 'whoami', + ...names + ]) + expect(localDirectTools().map((t) => t.name)).toEqual(['docs', 'whoami', ...names]) + }) + + it('lists every registered App resource', async () => { + const body = await modern('resources/list') + const uris = body.result?.resources?.map((r) => r.uri) ?? [] + for (const app of MCP_APPS) expect(uris).toContain(app.resource.descriptor.uri) + }) +}) diff --git a/tests/mcp-client.test.ts b/tests/mcp-client.test.ts index 2902344aa..f8d0ba00b 100644 --- a/tests/mcp-client.test.ts +++ b/tests/mcp-client.test.ts @@ -5,6 +5,7 @@ import { mockIdentityProbe } from './helpers/cloudflare-api' import { clearKv } from './helpers/kv' import { MCP_HOST, MCP_URL, MODERN_MCP_VERSION } from './helpers/mcp' import { clearSpec, seedSpec } from './helpers/spec' +import { MCP_APP_TOOLS } from '../src/mcp-apps/registry' const API_TOKEN = 'modern-client-token' const ACCOUNT_ID = '00000000000000000000000000000001' @@ -64,7 +65,13 @@ describe('automatic protocol negotiation', () => { expect(client.getDiscoverResult()?.supportedVersions).toEqual([MODERN_MCP_VERSION]) const listed = await client.listTools() - expect(listed.tools.map((tool) => tool.name)).toEqual(['docs', 'search', 'execute', 'whoami']) + expect(listed.tools.map((tool) => tool.name)).toEqual([ + 'docs', + 'search', + 'execute', + 'whoami', + ...MCP_APP_TOOLS.map((tool) => tool.name) + ]) const called = await client.callTool({ name: 'search', diff --git a/tests/mcp-modern.test.ts b/tests/mcp-modern.test.ts index 9fff04356..709fa8314 100644 --- a/tests/mcp-modern.test.ts +++ b/tests/mcp-modern.test.ts @@ -19,6 +19,7 @@ import { } from './helpers/mcp' import { clearSpec, seedSpec } from './helpers/spec' import { server } from './setup/msw' +import { MCP_APP_TOOLS } from '../src/mcp-apps/registry' const API_TOKEN = 'modern-mcp-token' const ACCOUNT_ID = '00000000000000000000000000000001' @@ -163,7 +164,8 @@ describe('MCP 2026-07-28 stateless handler', () => { 'docs', 'search', 'execute', - 'whoami' + 'whoami', + ...MCP_APP_TOOLS.map((tool) => tool.name) ]) }) @@ -283,10 +285,15 @@ describe('MCP 2026-07-28 stateless handler', () => { 'docs', 'search', 'execute', - 'whoami' + 'whoami', + ...MCP_APP_TOOLS.map((tool) => tool.name) ]) const direct = endpoints.result?.tools?.map((tool) => tool.name) ?? [] - expect(direct.slice(0, 2)).toEqual(['docs', 'whoami']) + expect(direct.slice(0, 2 + MCP_APP_TOOLS.length)).toEqual([ + 'docs', + 'whoami', + ...MCP_APP_TOOLS.map((tool) => tool.name) + ]) expect(direct).toContain('workers_legacy_scripts_list') expect(codemodeResponse.headers.get('mcp-session-id')).toBeNull() expect(endpointResponse.headers.get('mcp-session-id')).toBeNull() @@ -323,7 +330,8 @@ describe('MCP 2026-07-28 stateless handler', () => { 'docs', 'search', 'execute', - 'whoami' + 'whoami', + ...MCP_APP_TOOLS.map((tool) => tool.name) ]) }) diff --git a/tests/skills/server.test.ts b/tests/skills/server.test.ts index 0653b7787..ceccb03ba 100644 --- a/tests/skills/server.test.ts +++ b/tests/skills/server.test.ts @@ -6,6 +6,7 @@ import { MCP_HOST, MCP_URL, modernMcpRequest, parseMcpResult } from '../helpers/ import { clearSpec, seedSpec } from '../helpers/spec' import { seedSkills, skillMarkdown } from '../helpers/skills' import { SKILL_FILES_PREFIX } from '../../src/skills/types' +import { MCP_APP_RESOURCES } from '../../src/mcp-apps/registry' /** * Drives the real worker through `exports.default.fetch`: auth, the MCP @@ -180,7 +181,7 @@ describe('skills extension with a synced catalog', () => { expect(body.error?.code).toBe(-32603) }) - it('lists only SKILL.md files in resources/list', async () => { + it('lists SKILL.md files and the MCP App resources in resources/list', async () => { const body = await modern('resources/list') expect(body.result?.resources).toEqual([ @@ -195,7 +196,8 @@ describe('skills extension with a synced catalog', () => { name: 'wrangler', description: 'Use the Wrangler CLI', mimeType: 'text/markdown' - } + }, + ...MCP_APP_RESOURCES.map((resource) => resource.descriptor) ]) }) diff --git a/tests/tool-list-response.test.ts b/tests/tool-list-response.test.ts index 2f26260a9..0c7b3a030 100644 --- a/tests/tool-list-response.test.ts +++ b/tests/tool-list-response.test.ts @@ -4,6 +4,7 @@ import { mockIdentityProbe } from './helpers/cloudflare-api' import { clearKv } from './helpers/kv' import { clearSpec, seedSpec } from './helpers/spec' import { MCP_HOST, MCP_URL, parseMcpResult } from './helpers/mcp' +import { MCP_APP_TOOLS } from '../src/mcp-apps/registry' /** * The direct-tool `tools/list` fast path (src/tools/tool-list-response.ts) @@ -83,8 +84,9 @@ describe('direct tools/list fast path', () => { expect(fast.response.headers.get('Content-Type')).toBe('application/json') expect(fast.message).toEqual(sdk.message) const tools = (fast.message.result as { tools: Array<{ name: string }> }).tools - expect(tools.slice(0, 2).map((tool) => tool.name)).toEqual(['docs', 'whoami']) - expect(tools.length).toBeGreaterThan(2) + const local = ['docs', 'whoami', ...MCP_APP_TOOLS.map((tool) => tool.name)] + expect(tools.slice(0, local.length).map((tool) => tool.name)).toEqual(local) + expect(tools.length).toBeGreaterThan(local.length) }) } diff --git a/tsconfig.app.json b/tsconfig.app.json new file mode 100644 index 000000000..c2ff3d9a2 --- /dev/null +++ b/tsconfig.app.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2022", "DOM"], + "jsx": "react-jsx", + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "isolatedModules": true, + "esModuleInterop": true + }, + "include": ["src/*/app", "src/mcp-apps/app-shell"] +} diff --git a/tsconfig.json b/tsconfig.json index fccbccb38..33b9da23e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,5 +14,6 @@ "forceConsistentCasingInFileNames": true, "resolveJsonModule": true }, + "exclude": ["src/*/app", "src/mcp-apps/app-shell"], "include": ["src/**/*", "tests/**/*", "worker-configuration.d.ts"] } From 96e80c53127121c62626acbb9c689f685373d7e5 Mon Sep 17 00:00:00 2001 From: Jonnie Lappen Date: Wed, 18 Nov 2026 15:43:07 -0700 Subject: [PATCH 02/27] feat(workers-usage-alert): add Workers usage alert preview MCP App Read-only workers_usage_alert reads this and last month's daily Workers requests and the account's notification policies, and lets the user pick a billing_usage_alert threshold on a chart. It shows the policy it would create but creates nothing; the write will be a separate confirmed tool. --- AGENTS.md | 4 + docs/workers-usage-alert.md | 28 ++ src/mcp-apps/registry.ts | 2 + src/workers-usage-alert/app-html.generated.ts | 2 + src/workers-usage-alert/app/forecast.ts | 53 +++ src/workers-usage-alert/app/index.html | 12 + .../app/usage-alert-app.tsx | 329 ++++++++++++++++++ src/workers-usage-alert/app/usage-alert.css | 195 +++++++++++ src/workers-usage-alert/contract.ts | 68 ++++ src/workers-usage-alert/periods.ts | 50 +++ src/workers-usage-alert/tool.ts | 211 +++++++++++ tests/workers-usage-alert.test.ts | 230 ++++++++++++ 12 files changed, 1184 insertions(+) create mode 100644 docs/workers-usage-alert.md create mode 100644 src/workers-usage-alert/app-html.generated.ts create mode 100644 src/workers-usage-alert/app/forecast.ts create mode 100644 src/workers-usage-alert/app/index.html create mode 100644 src/workers-usage-alert/app/usage-alert-app.tsx create mode 100644 src/workers-usage-alert/app/usage-alert.css create mode 100644 src/workers-usage-alert/contract.ts create mode 100644 src/workers-usage-alert/periods.ts create mode 100644 src/workers-usage-alert/tool.ts create mode 100644 tests/workers-usage-alert.test.ts diff --git a/AGENTS.md b/AGENTS.md index aa925d332..e01fcec23 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -166,6 +166,10 @@ The core innovation: instead of 2,500 MCP tools (~244K tokens), two tools handle - `src/events/callback.ts` opens the sealed destination secret ANS presents, checks the KV subscription record and synchronously signs the MCP callback, with no Cloudflare API call. ANS owns retries. - `npm run test:events` runs local workerd coverage with simulated external HTTP endpoints. See `docs/mcp-events.md` for live tests and lifecycle constraints. +### Workers usage alert App + +`src/workers-usage-alert/` is the `workers_usage_alert` MCP App, registered in `MCP_APPS`. It previews a `billing_usage_alert` on Workers requests from this and last month's GraphQL analytics and the account's existing policies. Read-only: it creates no policy. See `docs/workers-usage-alert.md`. + ### MCP Apps `src/mcp-apps/` holds what every MCP App shares: `defineMcpApp()` (a tool plus its static `ui://` HTML resource, served in both tool modes), `apiReader()` (bounded, read-only Cloudflare API and GraphQL reads with the direct tools' refusal explanations and step-up), `MCP_APPS` in `registry.ts` (the one list an App is added to) and `app-shell/` (the browser-side host connection and Kumo base CSS). Each App lives in `src//`, with its React/Kumo view in `src//app/`, built into `app-html.generated.ts` by `npm run app:build`; never hand-edit those. `npm run check` verifies they are fresh and type-checks the view with `tsconfig.app.json`. See `docs/mcp-apps.md`. Keep raw customer prompts, account output and host screenshots outside this public repository. diff --git a/docs/workers-usage-alert.md b/docs/workers-usage-alert.md new file mode 100644 index 000000000..40aaf7a65 --- /dev/null +++ b/docs/workers-usage-alert.md @@ -0,0 +1,28 @@ +# Workers usage alert App + +`workers_usage_alert` is a read-only MCP App in both tool modes, served at `ui://cloudflare/workers-usage-alert.html`. It previews a `billing_usage_alert` notification policy on Workers requests. The user drags a threshold over this month's and last month's cumulative requests, enters an email, and reviews the policy the App would create. + +**It creates nothing yet.** Review shows the exact `POST /accounts/{account_id}/alerting/v3/policies` body. Creating the policy will be a separate, non-read-only tool that the user confirms in the host (see Rules in `docs/mcp-apps.md`). + +## What it reads + +- `POST /graphql`, `workersInvocationsAdaptive` summed by date: the whole previous UTC month and the current month to date, as two aliases in one query. The dataset refuses ranges wider than about 32 days (`4w4d`, measured), so a single six-week range fails. +- `GET /accounts/{account_id}/alerting/v3/available_alerts`: whether the account can create `billing_usage_alert`. +- `GET /accounts/{account_id}/alerting/v3/policies`: existing billing usage alerts on `worker_requests` (name, enabled, limit), with the other policy types counted. Destinations and email addresses are not returned. + +Usage is required. Without it the call is a tool error, explained as missing Account Analytics Read when GraphQL says so. The alerting reads only add context: a refusal becomes a limitation and `null`, never "no alerts exist". + +## What it doesn't prove + +Months are UTC calendar months, which may not match the account's billing period. Request counts come from Workers analytics, not billing, and are not dollar cost. The projection, shown dashed, is the last seven days' average. The alert sends email and never blocks traffic. + +## Implementation + +- `src/workers-usage-alert/contract.ts`: the input (`account_id`, `as_of`) and the `workers_usage_alert_preview` output. +- `src/workers-usage-alert/periods.ts`: UTC month arithmetic and threshold rounding. +- `src/workers-usage-alert/tool.ts`: `workersUsageAlertApp`, a `defineMcpApp` whose collector reads with `apiReader`. +- `src/workers-usage-alert/app/`: the React/Kumo chart, mounted with `mountMcpApp`. The design reference is the fuzzy-input mockup, kept outside this repository. + +## Verification + +Tests cover both tool modes, period arithmetic, the GraphQL variables, refused and quota GraphQL errors, a refused policy read, missing days and the static resource. Locally, `wrangler dev` served a read-only call against a real account. The built HTML rendered through an `AppBridge` host at 390 and 560 px in light and dark, and keyboard threshold changes and the review payload were checked. diff --git a/src/mcp-apps/registry.ts b/src/mcp-apps/registry.ts index 89caa2a28..8a10d29e0 100644 --- a/src/mcp-apps/registry.ts +++ b/src/mcp-apps/registry.ts @@ -1,12 +1,14 @@ import type { McpServer, Tool } from '@modelcontextprotocol/server' import type { StaticResource } from '../skills/handlers' // App imports, one per line. +import { workersUsageAlertApp } from '../workers-usage-alert/tool' import type { AppContext, McpApp } from './define' const apps: McpApp[] = [] // Each App adds its import above and one push here; nothing else in the server // changes. One statement per App, on either side of this comment, so Apps in // flight at once merge in any order. See `docs/mcp-apps.md`. +apps.push(workersUsageAlertApp) /** Every MCP App this Worker serves, in listing order. */ export const MCP_APPS: readonly McpApp[] = apps diff --git a/src/workers-usage-alert/app-html.generated.ts b/src/workers-usage-alert/app-html.generated.ts new file mode 100644 index 000000000..e8beb483d --- /dev/null +++ b/src/workers-usage-alert/app-html.generated.ts @@ -0,0 +1,2 @@ +// Generated by npm run app:build. Do not edit. +export const appHtml = "\n\n \n \n \n Workers usage alert\n \n \n \n \n
\n \n\n" diff --git a/src/workers-usage-alert/app/forecast.ts b/src/workers-usage-alert/app/forecast.ts new file mode 100644 index 000000000..cfd1af73b --- /dev/null +++ b/src/workers-usage-alert/app/forecast.ts @@ -0,0 +1,53 @@ +import type { UsageAlertPreview } from '../contract' + +/** Cumulative points `[dayOfMonth, total]` for daily rows. */ +export function cumulative(rows: UsageAlertPreview['current']): [number, number][] { + let total = 0 + return rows.map(([date, requests]) => [Number(date.slice(8, 10)), (total += requests)]) +} + +/** The first day a cumulative series reaches `limit`, if it does. */ +export function crossingDay( + series: readonly [number, number][], + limit: number +): number | undefined { + return series.find(([, total]) => total >= limit)?.[0] +} + +/** + * The current month projected to its end from the last seven days' average. + * Starts at the last observed point so the dashed line joins the solid one. + */ +export function projection( + current: readonly [number, number][], + daily: UsageAlertPreview['current'], + daysInMonth: number +): [number, number][] { + const last = current.at(-1) + if (!last) return [] + const recent = daily.slice(-7) + const average = + recent.reduce((sum, [, requests]) => sum + requests, 0) / Math.max(1, recent.length) + const points: [number, number][] = [last] + for (let day = last[0] + 1; day <= daysInMonth; day++) + points.push([day, points[points.length - 1][1] + average]) + return points +} + +/** `2.4B`, `830M`, `12K`. */ +export function compact(n: number): string { + if (n >= 1e9) return `${(n / 1e9).toFixed(1).replace(/\.0$/, '')}B` + if (n >= 1e6) return `${Math.round(n / 1e6)}M` + if (n >= 1e3) return `${Math.round(n / 1e3)}K` + return String(Math.round(n)) +} + +/** `2026-10` → `Oct`. */ +export function monthLabel(month: string): string { + return new Date(`${month}-01T00:00:00Z`).toLocaleString('en', { month: 'short', timeZone: 'UTC' }) +} + +export function daysIn(month: string): number { + const [year, m] = month.split('-').map(Number) + return new Date(Date.UTC(year, m, 0)).getUTCDate() +} diff --git a/src/workers-usage-alert/app/index.html b/src/workers-usage-alert/app/index.html new file mode 100644 index 000000000..9bc30608a --- /dev/null +++ b/src/workers-usage-alert/app/index.html @@ -0,0 +1,12 @@ + + + + + + Workers usage alert + + +
+ + + diff --git a/src/workers-usage-alert/app/usage-alert-app.tsx b/src/workers-usage-alert/app/usage-alert-app.tsx new file mode 100644 index 000000000..1f4a13134 --- /dev/null +++ b/src/workers-usage-alert/app/usage-alert-app.tsx @@ -0,0 +1,329 @@ +import { useMemo, useRef, useState, type KeyboardEvent, type PointerEvent } from 'react' +import { Badge, Button, CloudflareLogo, Input } from '@cloudflare/kumo' +import { mountMcpApp } from '../../mcp-apps/app-shell/mount' +import { UsageAlertPreviewSchema, type UsageAlertPreview } from '../contract' +import { roundLimit } from '../periods' +import { compact, crossingDay, cumulative, daysIn, monthLabel, projection } from './forecast' +import './usage-alert.css' + +const W = 520 +const H = 168 +const PL = 32 +const PR = 4 +const PT = 6 +const PB = 20 +const PRESETS = [1.1, 1.25, 1.5] as const +const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/ + +function UsageAlertCard({ preview: p }: { preview: UsageAlertPreview }) { + const days = daysIn(p.currentMonth) + const prev = useMemo(() => cumulative(p.previous), [p.previous]) + const cur = useMemo(() => cumulative(p.current), [p.current]) + const proj = useMemo(() => projection(cur, p.current, days), [cur, p.current, days]) + const prevTotal = prev.at(-1)?.[1] ?? 0 + const curTotal = cur.at(-1)?.[1] ?? 0 + const projected = proj.at(-1)?.[1] ?? curTotal + const yMax = Math.max(1, Math.ceil((Math.max(prevTotal, projected) * 1.6) / 1e8) * 1e8) + const minLimit = roundLimit(Math.max(1, prevTotal * 0.25)) + const maxLimit = roundLimit(yMax * 0.95) + const clamp = (v: number) => Math.max(minLimit, Math.min(maxLimit, roundLimit(v))) + + const [limit, setLimit] = useState(() => clamp(p.suggestedLimit ?? prevTotal * 1.25)) + const [email, setEmail] = useState('') + const [reviewing, setReviewing] = useState(false) + const svg = useRef(null) + + const prevName = monthLabel(p.previousMonth) + const curName = monthLabel(p.currentMonth) + const x = (d: number) => PL + ((d - 1) / (31 - 1)) * (W - PL - PR) + const y = (v: number) => PT + (1 - v / yMax) * (H - PT - PB) + const path = (pts: readonly [number, number][]) => + pts.map(([d, v], i) => `${i ? 'L' : 'M'}${x(d).toFixed(1)} ${y(v).toFixed(1)}`).join(' ') + const area = (pts: readonly [number, number][]) => + pts.length + ? `${path(pts)} L${x(pts.at(-1)![0]).toFixed(1)} ${y(0)} L${x(pts[0][0]).toFixed(1)} ${y(0)} Z` + : '' + const hy = y(limit) + const prevHit = crossingDay(prev, limit) + const curHit = crossingDay([...cur, ...proj.slice(1)], limit) + const pct = prevTotal ? Math.round((limit / prevTotal - 1) * 20) * 5 : 0 + const vs = + pct === 0 + ? `equal to ${prevName}` + : `about ${Math.abs(pct)}% ${pct > 0 ? 'above' : 'below'} ${prevName}` + const validEmail = EMAIL.test(email.trim()) + const existing = p.existingAlerts ?? [] + + const fromPointer = (e: PointerEvent) => { + const box = svg.current!.getBoundingClientRect() + const py = ((e.clientY - box.top) / box.height) * H + setLimit(clamp((1 - (py - PT) / (H - PT - PB)) * yMax)) + } + const onKey = (e: KeyboardEvent) => { + if (reviewing) return + const step = e.shiftKey ? limit * 0.2 : limit * 0.05 + if (e.key === 'ArrowUp' || e.key === 'ArrowRight') setLimit(clamp(limit + step)) + else if (e.key === 'ArrowDown' || e.key === 'ArrowLeft') setLimit(clamp(limit - step)) + else if (e.key === 'Home') setLimit(minLimit) + else if (e.key === 'End') setLimit(maxLimit) + else return + e.preventDefault() + } + + const label = `Alert ~${compact(limit)}` + const pw = 14 + label.length * 6.4 + 10 + const px = PL + 8 + const py = hy - 22 < PT ? hy + 4 : hy - 22 + const payload = { + name: `Workers requests above ~${compact(limit)}`, + alert_type: 'billing_usage_alert', + enabled: true, + filters: { product: ['worker_requests'], limit: [String(limit)] }, + mechanisms: { email: [{ id: email.trim() || '' }] } + } + + return ( +
+
+
+ + Workers usage alert +
+ + {p.accountName ?? p.accountId} + +
+
+
+ {[ + ['var(--chart-blue)', `${curName} so far`, curTotal, ''], + ['var(--chart-disabled)', `${prevName} total`, prevTotal, ''], + ['var(--chart-warning)', 'Alert at', limit, 'dash'] + ].map(([color, name, value, cls]) => ( +
+
+ + {name} +
+
+ {compact(value as number)} + req +
+
+ ))} +
+ e.buttons === 1 && !reviewing && fromPointer(e)} + > + + + + + + + {[0, 1, 2, 3, 4].map((i) => { + const v = (yMax / 4) * i + return ( + + + + {i ? compact(v) : '0'} + + + ) + })} + {[ + [1, 'Day 1', 'start'], + [15, '15', 'middle'], + [days, String(days), 'end'] + ].map(([d, t, anchor]) => ( + + {t} + + ))} + + + + + + {prevHit && ( + + )} + + { + if (reviewing) return + svg.current?.setPointerCapture(e.pointerId) + fromPointer(e) + }} + > + + + + + {label} + + + +
+ Alert when + {PRESETS.map((m, i) => { + const value = clamp(prevTotal * m) + return ( + + ) + })} +
+

+ Emails you at ~{compact(limit)} requests, {vs}.{' '} + {prevHit + ? `${prevName} would have triggered it on ${prevName} ${prevHit}.` + : `${prevName} never reached it.`}{' '} + {curHit + ? `${curName} is on track to reach it around ${curName} ${curHit}.` + : `${curName} is on track for ${compact(projected)}.`}{' '} + This alert doesn’t block traffic. +

+ {existing.length > 0 && ( +

+ Existing Workers request alert{existing.length > 1 ? 's' : ''}:{' '} + {existing + .map( + (a) => + `${a.name}${a.limit ? ` (~${compact(a.limit)})` : ''}${a.enabled ? '' : ', disabled'}` + ) + .join('; ')} + . +

+ )} + {p.alertAvailable === false && ( +

+ This account can’t create billing usage alerts. +

+ )} +
+ setEmail(e.target.value)} + /> + {reviewing ? ( + + ) : ( + + )} +
+ {reviewing && ( +
+

+ Creating alerts from this card isn’t available yet. This is the policy it would + create: +

+
{`POST /accounts/${p.accountId}/alerting/v3/policies\n${JSON.stringify(payload, null, 2)}`}
+
+ )} +
+

+ Cloudflare API · read {new Date(p.checkedAt).toLocaleString()} · read-only. + {p.limitations.length > 0 && ` ${p.limitations.join(' ')}`} +

+
+ ) +} + +mountMcpApp({ + name: 'Cloudflare Workers usage alert', + output: UsageAlertPreviewSchema, + render: (preview) => , + copy: { + pending: 'Reading Workers usage…', + cancelled: 'Usage check cancelled.', + malformed: 'Workers usage could not be displayed. Check the tool’s text result.' + } +}) diff --git a/src/workers-usage-alert/app/usage-alert.css b/src/workers-usage-alert/app/usage-alert.css new file mode 100644 index 000000000..ef6b73c7b --- /dev/null +++ b/src/workers-usage-alert/app/usage-alert.css @@ -0,0 +1,195 @@ +@import '../../mcp-apps/app-shell/base.css'; +@source './usage-alert-app.tsx'; + +/* Kumo ChartPalette (chart/Color.ts) */ +:root { + --chart-blue: #4290f0; + --chart-warning: #f8a054; + --chart-disabled: light-dark(#cbcbcb, #878787); + --chart-text: light-dark(#6b7280, #9ca3af); + --chart-grid: light-dark(rgb(107 114 128 / 0.2), rgb(156 163 175 / 0.2)); +} + +.card { + container-type: inline-size; + min-width: 0; + border-radius: 8px; + background: var(--color-kumo-elevated); + box-shadow: 0 0 0 1px var(--color-kumo-hairline); + overflow: hidden; +} +header { + display: flex; + justify-content: space-between; + align-items: center; + gap: 8px; + padding: 8px 12px 8px 14px; + min-height: 40px; + flex-wrap: wrap; +} +.title { + display: flex; + gap: 8px; + align-items: center; + min-width: 0; +} +.title strong { + font-weight: 500; +} +.logo { + width: 22px; + flex-shrink: 0; +} +.body { + margin: 0 4px 4px; + border-radius: 6px; + background: var(--color-kumo-base); + box-shadow: + 0 1px 2px 0 oklch(0% 0 0 / 0.05), + 0 0 0 1px var(--color-kumo-line); + padding: 14px 16px 16px; + display: flex; + flex-direction: column; + gap: 12px; +} +.legend { + display: flex; + gap: 20px; + flex-wrap: wrap; +} +.lg { + display: inline-flex; + flex-direction: column; + gap: 4px; +} +.lg .k { + display: flex; + align-items: center; + gap: 6px; + font-size: 12px; + color: var(--text-color-kumo-subtle); + white-space: nowrap; +} +.lg .dot { + width: 8px; + height: 8px; + border-radius: 50%; +} +.lg .dot.dash { + width: 10px; + height: 2px; + border-radius: 1px; +} +.lg .v { + display: flex; + align-items: baseline; + gap: 3px; +} +.lg .v b { + font-size: 16px; + line-height: 1; + font-weight: 500; + font-variant-numeric: tabular-nums; +} +.lg .v span { + font-size: 12px; + color: var(--text-color-kumo-subtle); +} +.chart { + display: block; + width: 100%; + height: auto; + overflow: visible; + touch-action: none; + user-select: none; +} +.tick { + font-size: 10px; + fill: var(--chart-text); +} +.handle { + cursor: ns-resize; + outline: none; +} +.handle .pill { + fill: var(--color-kumo-base); + stroke: var(--color-kumo-line); +} +.handle:focus-visible .pill { + stroke: var(--color-kumo-brand); + stroke-width: 2; +} +.pill-text { + font-size: 11px; + font-weight: 500; + fill: var(--text-color-kumo-default); +} +.pills { + display: flex; + gap: 6px; + flex-wrap: wrap; + align-items: center; +} +.pills .lbl { + font-size: 13px; + color: var(--text-color-kumo-subtle); +} +.pill-btn { + font: inherit; + font-size: 12px; + border-radius: 999px; + padding: 2px 10px; + border: 1px solid var(--color-kumo-line); + background: var(--color-kumo-base); + color: var(--text-color-kumo-default); + cursor: pointer; +} +.pill-btn[aria-pressed='true'] { + background: var(--color-kumo-fill); + border-color: transparent; +} +.pill-btn:focus-visible { + outline: 2px solid var(--color-kumo-brand); + outline-offset: 1px; +} +.pill-btn:disabled { + cursor: default; + opacity: 0.6; +} +.summary { + margin: 0; +} +.subtle, +.observed { + margin: 0; + font-size: 12px; + color: var(--text-color-kumo-subtle); +} +.observed { + padding: 8px 14px 10px; +} +.warn { + margin: 0; + color: var(--text-color-kumo-warning); +} +.foot { + display: flex; + gap: 8px; + align-items: center; +} +.foot > :first-child { + flex: 1; + min-width: 0; +} +.review pre { + margin: 6px 0 0; + padding: 10px; + border-radius: 6px; + background: var(--color-kumo-recessed); + font: + 12px/1.45 ui-monospace, + SFMono-Regular, + Menlo, + monospace; + overflow-x: auto; +} diff --git a/src/workers-usage-alert/contract.ts b/src/workers-usage-alert/contract.ts new file mode 100644 index 000000000..554624c1d --- /dev/null +++ b/src/workers-usage-alert/contract.ts @@ -0,0 +1,68 @@ +import { z } from 'zod' + +export const USAGE_ALERT_RESOURCE_URI = 'ui://cloudflare/workers-usage-alert.html' + +/** The billing product the alert watches. The only one this App supports so far. */ +export const WORKER_REQUESTS_PRODUCT = 'worker_requests' + +export const UsageAlertInputSchema = z.strictObject({ + account_id: z + .string() + .regex(/^[a-f0-9]{32}$/i) + .optional() + .describe('Account to read. Optional when the connection has exactly one account.'), + as_of: z.iso + .date() + .optional() + .describe( + 'Treat this UTC date as today, for reviewing a past month. Defaults to the current date.' + ) +}) +export type UsageAlertInput = z.infer + +/** One day's Workers requests, from the GraphQL Analytics API. */ +export const DailyRequestsSchema = z.tuple([z.iso.date(), z.number().int().nonnegative()]) + +/** A notification policy already on the account, as far as this App needs it. */ +export const ExistingPolicySchema = z.object({ + id: z.string(), + name: z.string(), + enabled: z.boolean(), + /** The `limit` filter, for a `billing_usage_alert` on Workers requests. */ + limit: z.number().optional() +}) + +export const UsageAlertPreviewSchema = z.object({ + kind: z.literal('workers_usage_alert_preview'), + checkedAt: z.iso.datetime(), + accountId: z.string(), + accountName: z.string().optional(), + /** UTC calendar months, `YYYY-MM`. Billing periods may not align with them. */ + currentMonth: z.string(), + previousMonth: z.string(), + /** Daily request counts, oldest first. Days without traffic may be absent. */ + current: z.array(DailyRequestsSchema), + previous: z.array(DailyRequestsSchema), + /** Whether the account can create a `billing_usage_alert`, from `available_alerts`. `null`: not read. */ + alertAvailable: z.boolean().nullable(), + /** The billing usage alerts on Workers requests that already exist. `null`: not read. */ + existingAlerts: z.array(ExistingPolicySchema).nullable(), + /** Every other policy, counted by type, so the view can say what exists without listing it. */ + otherPolicies: z.record(z.string(), z.number().int()), + /** A suggested threshold, 25% over the previous month, rounded. The user picks the real one. */ + suggestedLimit: z.number().int().positive().optional(), + limitations: z.array(z.string()) +}) +export type UsageAlertPreview = z.infer + +export const USAGE_ALERT_TOOL_CONFIG = { + title: 'Workers usage alert', + description: + 'Preview an email alert for when Workers requests this billing period pass a threshold. Use for requests like “tell me if our Workers traffic gets way bigger than normal” or “alert me before Workers usage spikes”. Reads daily Workers requests for this and last month, and the account’s existing notification policies. Read-only: it creates nothing. Displays a chart in MCP Apps hosts where the user picks the threshold; summarize last month’s total and any existing alert rather than repeating the data. Request counts are not dollar cost, and the alert does not block traffic.', + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false + } +} diff --git a/src/workers-usage-alert/periods.ts b/src/workers-usage-alert/periods.ts new file mode 100644 index 000000000..4b2c91f6a --- /dev/null +++ b/src/workers-usage-alert/periods.ts @@ -0,0 +1,50 @@ +/** + * Calendar arithmetic for the alert's two periods, in UTC. Pure, so the view + * and the collector agree and tests need no clock. + */ + +export interface Period { + /** `YYYY-MM`. */ + readonly month: string + /** First day, `YYYY-MM-DD`. */ + readonly start: string + /** Last day read, `YYYY-MM-DD`: the month's last day, or `asOf` for the current month. */ + readonly end: string + /** Days in the whole month. */ + readonly days: number +} + +const iso = (date: Date) => date.toISOString().slice(0, 10) + +function monthOf(year: number, month: number, endDay?: number): Period { + const first = new Date(Date.UTC(year, month, 1)) + const days = new Date(Date.UTC(year, month + 1, 0)).getUTCDate() + return { + month: iso(first).slice(0, 7), + start: iso(first), + end: iso(new Date(Date.UTC(year, month, endDay ?? days))), + days + } +} + +/** + * The current month up to `asOf`, and the whole month before it. + * + * Each fits the GraphQL Analytics API's widest `workersInvocationsAdaptive` + * range (measured at 4w4d, about 32 days), so each is one query. + * + * @param asOf - `YYYY-MM-DD`, treated as today. + */ +export function periodsAsOf(asOf: string): { current: Period; previous: Period } { + const [year, month, day] = asOf.split('-').map(Number) + return { + current: monthOf(year, month - 1, day), + previous: monthOf(year, month - 2) + } +} + +/** Round to a readable threshold: 250 million steps above a billion, 25 million below. */ +export function roundLimit(requests: number): number { + const step = requests >= 1e9 ? 2.5e8 : 2.5e7 + return Math.max(step, Math.round(requests / step) * step) +} diff --git a/src/workers-usage-alert/tool.ts b/src/workers-usage-alert/tool.ts new file mode 100644 index 000000000..fdc846466 --- /dev/null +++ b/src/workers-usage-alert/tool.ts @@ -0,0 +1,211 @@ +import { z } from 'zod' +import { autoResolvedAccountId, missingAccountMessage } from '../auth/account-access' +import type { AuthProps } from '../auth/types' +import { defineMcpApp, type AppContext, type AppOutcome } from '../mcp-apps/define' +import { ApiReadError, ApiReadUnsupported, apiReader } from '../mcp-apps/api-read' +import { + USAGE_ALERT_RESOURCE_URI, + USAGE_ALERT_TOOL_CONFIG, + UsageAlertInputSchema, + UsageAlertPreviewSchema, + WORKER_REQUESTS_PRODUCT, + type UsageAlertInput, + type UsageAlertPreview +} from './contract' +import { periodsAsOf, roundLimit } from './periods' +import { appHtml } from './app-html.generated' + +/** + * Daily Workers requests for both periods in one query. Each alias stays within + * the dataset's widest range, which a single six-week range exceeds. + */ +const DAILY_REQUESTS_QUERY = `query WorkersUsageAlert($account: String!, $previousStart: Date!, $previousEnd: Date!, $currentStart: Date!, $currentEnd: Date!) { + viewer { + accounts(filter: { accountTag: $account }) { + previous: workersInvocationsAdaptive(limit: 100, filter: { date_geq: $previousStart, date_leq: $previousEnd }, orderBy: [date_ASC]) { + sum { requests } + dimensions { date } + } + current: workersInvocationsAdaptive(limit: 100, filter: { date_geq: $currentStart, date_leq: $currentEnd }, orderBy: [date_ASC]) { + sum { requests } + dimensions { date } + } + } + } +}` + +const DailyRows = z.array( + z.object({ + sum: z.object({ requests: z.number() }), + dimensions: z.object({ date: z.iso.date() }) + }) +) +const DailyRequestsData = z.object({ + viewer: z.object({ + accounts: z.array(z.object({ previous: DailyRows, current: DailyRows })).max(1) + }) +}) + +const AvailableAlerts = z.object({ + result: z.record(z.string(), z.array(z.object({ type: z.string() }))) +}) + +const Policies = z.object({ + result: z.array( + z.object({ + id: z.string(), + name: z.string(), + enabled: z.boolean(), + alert_type: z.string(), + filters: z.record(z.string(), z.array(z.string())).optional() + }) + ) +}) + +function accountName(props: AuthProps, accountId: string): string | undefined { + if (props.type === 'account_token') + return props.account.id === accountId ? props.account.name : undefined + return props.accounts.find((account) => account.id === accountId)?.name +} + +const rows = (list: z.output): [string, number][] => + list.map((row) => [row.dimensions.date, Math.round(row.sum.requests)]) + +/** Collects the usage and alerting evidence the preview shows. Read-only. */ +async function collect( + input: UsageAlertInput, + context: AppContext, + signal: AbortSignal +): Promise> { + const accountId = input.account_id ?? autoResolvedAccountId(context.props) + if (!accountId) + return { ok: false, text: missingAccountMessage(context.props, 'Use GET /accounts.') } + + const now = new Date() + const asOf = input.as_of ?? now.toISOString().slice(0, 10) + const { current, previous } = periodsAsOf(asOf) + const reader = apiReader(context, signal, 'workers_usage_alert') + const limitations = [ + 'Months are UTC calendar months; the account’s billing period may start on another day.', + 'Request counts come from Workers analytics, not billing. They are not dollar cost.' + ] + + // Usage is what the App is about: without it there is nothing to preview. + let usage: z.output + try { + usage = await reader.graphql( + DAILY_REQUESTS_QUERY, + { + account: accountId, + previousStart: previous.start, + previousEnd: previous.end, + currentStart: current.start, + currentEnd: current.end + }, + 'account', + DailyRequestsData + ) + } catch (error) { + if (signal.aborted) throw error + if (error instanceof ApiReadError) + return { ok: false, text: error.text, meta: error.result._meta } + if (error instanceof ApiReadUnsupported || error instanceof z.ZodError) + return { ok: false, text: 'Cloudflare returned an unsupported analytics response.' } + throw error + } + const account = usage.viewer.accounts[0] + if (!account) + return { + ok: false, + text: `No Workers analytics were returned for account ${accountId}. Check the account ID and that the connection can read its analytics.` + } + + // Alerting reads only add context. A refusal is noted, not fatal, and never + // reads as "no alerts exist". + let challenge: Record | undefined + const optional = async (read: () => Promise, what: string): Promise => { + try { + return await read() + } catch (error) { + if (signal.aborted) throw error + if (error instanceof ApiReadError) { + challenge ??= error.result._meta + limitations.push(`${what} could not be read: ${error.text}`) + } else if (error instanceof ApiReadUnsupported || error instanceof z.ZodError) { + limitations.push(`${what} could not be read: Cloudflare returned an unsupported response.`) + } else throw error + return null + } + } + const prefix = `/accounts/${accountId}/alerting/v3` + const [available, policies] = await Promise.all([ + optional( + () => reader.get(`${prefix}/available_alerts`, AvailableAlerts), + 'Available alert types' + ), + optional(() => reader.get(`${prefix}/policies`, Policies), 'Existing notification policies') + ]) + + const otherPolicies: Record = {} + const existingAlerts = policies + ? policies.result.flatMap((policy) => { + const product = policy.filters?.product ?? [] + if ( + policy.alert_type === 'billing_usage_alert' && + product.includes(WORKER_REQUESTS_PRODUCT) + ) { + const limit = Number(policy.filters?.limit?.[0]) + return [ + { + id: policy.id, + name: policy.name, + enabled: policy.enabled, + ...(Number.isFinite(limit) ? { limit } : {}) + } + ] + } + otherPolicies[policy.alert_type] = (otherPolicies[policy.alert_type] ?? 0) + 1 + return [] + }) + : null + + const previousRows = rows(account.previous) + const previousTotal = previousRows.reduce((sum, [, requests]) => sum + requests, 0) + if (previousRows.length < previous.days) + limitations.push( + `${previous.month} has ${previousRows.length} of ${previous.days} days of data; its total may be low.` + ) + + const preview: UsageAlertPreview = { + kind: 'workers_usage_alert_preview', + checkedAt: now.toISOString(), + accountId, + ...(accountName(context.props, accountId) + ? { accountName: accountName(context.props, accountId) } + : {}), + currentMonth: current.month, + previousMonth: previous.month, + current: rows(account.current), + previous: previousRows, + alertAvailable: available + ? Object.values(available.result).some((types) => + types.some((type) => type.type === 'billing_usage_alert') + ) + : null, + existingAlerts, + otherPolicies, + ...(previousTotal > 0 ? { suggestedLimit: roundLimit(previousTotal * 1.25) } : {}), + limitations + } + return { ok: true, value: preview, ...(challenge ? { meta: challenge } : {}) } +} + +/** The read-only Workers usage alert preview App, served in both tool modes. */ +export const workersUsageAlertApp = defineMcpApp({ + name: 'workers_usage_alert', + ...USAGE_ALERT_TOOL_CONFIG, + input: UsageAlertInputSchema, + output: UsageAlertPreviewSchema, + resource: { uri: USAGE_ALERT_RESOURCE_URI, name: 'Workers usage alert', html: appHtml }, + run: collect +}) diff --git a/tests/workers-usage-alert.test.ts b/tests/workers-usage-alert.test.ts new file mode 100644 index 000000000..102fe52f5 --- /dev/null +++ b/tests/workers-usage-alert.test.ts @@ -0,0 +1,230 @@ +import { env, exports } from 'cloudflare:workers' +import { http, HttpResponse } from 'msw' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { periodsAsOf, roundLimit } from '../src/workers-usage-alert/periods' +import { API_BASE, cfError, cfSuccess, mockIdentityProbe } from './helpers/cloudflare-api' +import { clearKv } from './helpers/kv' +import { MCP_URL, modernMcpRequest, parseMcpResult } from './helpers/mcp' +import { clearSpec, seedSpec } from './helpers/spec' +import { server } from './setup/msw' + +const ACCOUNT = '023e105f4ecef8ad9ca31a8372d0c353' +const TOKEN = 'usage-alert-token' +const ALERTING = `${API_BASE}/accounts/${ACCOUNT}/alerting/v3` +const ALERTING_PERMISSIONS = { 'x-api-token-group': ['Notifications Read'] } + +const day = (month: string, d: number, requests: number) => ({ + sum: { requests }, + dimensions: { date: `${month}-${String(d).padStart(2, '0')}` } +}) +const october = Array.from({ length: 31 }, (_, i) => day('2026-10', i + 1, 100_000_000)) +const november = Array.from({ length: 18 }, (_, i) => day('2026-11', i + 1, 90_000_000)) + +let graphqlBody: { query?: string; variables?: Record } | undefined + +function mockApi({ + graphql = () => + HttpResponse.json({ + data: { viewer: { accounts: [{ previous: october, current: november }] } }, + errors: null + }), + policies = () => + HttpResponse.json( + cfSuccess([ + { + id: 'p1', + name: 'Workers above 4B', + enabled: true, + alert_type: 'billing_usage_alert', + filters: { product: ['worker_requests'], limit: ['4000000000'] }, + mechanisms: { email: [{ id: 'private@example.com' }] } + }, + { id: 'p2', name: 'errors', enabled: true, alert_type: 'workers_observability_alert' }, + { id: 'p3', name: 'errors 2', enabled: true, alert_type: 'workers_observability_alert' } + ]) + ) +}: { + graphql?: () => Response + policies?: () => Response +} = {}) { + server.use( + http.post(`${API_BASE}/graphql`, async ({ request }) => { + graphqlBody = (await request.json()) as typeof graphqlBody + return graphql() + }), + http.get(`${ALERTING}/available_alerts`, () => + HttpResponse.json( + cfSuccess({ + Billing: [{ type: 'billing_usage_alert', display_name: 'Usage Based Billing' }] + }) + ) + ), + http.get(`${ALERTING}/policies`, policies) + ) +} + +async function call(args: Record = { as_of: '2026-11-18' }, url = MCP_URL) { + const response = await exports.default.fetch( + modernMcpRequest(TOKEN, 'tools/call', { name: 'workers_usage_alert', arguments: args }, { url }) + ) + return ( + (await parseMcpResult(response)) as { + result?: { + isError?: boolean + structuredContent?: Record + content?: { text: string }[] + } + } + ).result +} + +beforeEach(async () => { + graphqlBody = undefined + await seedSpec({ + '/accounts/{account_id}/alerting/v3/available_alerts': { get: ALERTING_PERMISSIONS }, + '/accounts/{account_id}/alerting/v3/policies': { get: ALERTING_PERMISSIONS } + }) + mockIdentityProbe({ accounts: [{ id: ACCOUNT, name: 'Usage Co' }] }) +}) + +afterEach(async () => { + await clearSpec() + await clearKv(env.OAUTH_KV) +}) + +describe('periods', () => { + it('reads the current month to date and the whole previous month', () => { + expect(periodsAsOf('2026-11-18')).toEqual({ + current: { month: '2026-11', start: '2026-11-01', end: '2026-11-18', days: 30 }, + previous: { month: '2026-10', start: '2026-10-01', end: '2026-10-31', days: 31 } + }) + }) + + it('crosses the year', () => { + expect(periodsAsOf('2026-01-05').previous).toEqual({ + month: '2025-12', + start: '2025-12-01', + end: '2025-12-31', + days: 31 + }) + }) + + it.each([ + [3_800_000_000, 3_750_000_000], + [3_900_000_000, 4_000_000_000], + [40_000_000, 50_000_000], + [1, 25_000_000] + ])('roundLimit(%d) is %d', (n, rounded) => { + expect(roundLimit(n)).toBe(rounded) + }) +}) + +describe.each([ + ['Code Mode', MCP_URL], + ['direct tools', `${MCP_URL}?codemode=false`] +])('workers_usage_alert (%s)', (_mode, url) => { + it('previews usage, existing alerts and a suggested limit', async () => { + mockApi() + const result = await call({ as_of: '2026-11-18' }, url) + + expect(result?.isError).toBeUndefined() + expect(result?.structuredContent).toMatchObject({ + kind: 'workers_usage_alert_preview', + accountId: ACCOUNT, + accountName: 'Usage Co', + currentMonth: '2026-11', + previousMonth: '2026-10', + alertAvailable: true, + existingAlerts: [{ id: 'p1', name: 'Workers above 4B', enabled: true, limit: 4_000_000_000 }], + otherPolicies: { workers_observability_alert: 2 }, + // 3.1B in October, plus 25%, rounded. + suggestedLimit: 4_000_000_000 + }) + expect(result?.structuredContent?.previous).toHaveLength(31) + expect(result?.structuredContent?.current).toHaveLength(18) + expect(JSON.stringify(result)).not.toContain('private@example.com') + }) +}) + +describe('workers_usage_alert reads', () => { + it('queries each month separately, within the dataset’s widest range', async () => { + mockApi() + await call() + expect(graphqlBody?.variables).toEqual({ + account: ACCOUNT, + previousStart: '2026-10-01', + previousEnd: '2026-10-31', + currentStart: '2026-11-01', + currentEnd: '2026-11-18' + }) + expect(graphqlBody?.query).toContain('previous: workersInvocationsAdaptive') + }) + + it('is an error when usage cannot be read, naming the missing analytics permission', async () => { + mockApi({ + graphql: () => + HttpResponse.json({ data: null, errors: [{ message: 'authorization denied' }] }) + }) + const result = await call() + expect(result?.isError).toBe(true) + expect(result?.content?.[0].text).toContain('Account Analytics Read') + }) + + it('passes a GraphQL quota error through as Cloudflare’s message', async () => { + mockApi({ + graphql: () => + HttpResponse.json({ + data: null, + errors: [{ message: 'cannot request a time range wider than 4w4d' }] + }) + }) + const result = await call() + expect(result?.isError).toBe(true) + expect(result?.content?.[0].text).toContain('4w4d') + }) + + it('never reports a refused policy read as no existing alerts', async () => { + mockApi({ + policies: () => + HttpResponse.json(cfError([{ code: 10000, message: 'Authentication error' }]), { + status: 403 + }) + }) + const result = await call() + expect(result?.isError).toBeUndefined() + expect(result?.structuredContent).toMatchObject({ existingAlerts: null, alertAvailable: true }) + expect(JSON.stringify(result?.structuredContent?.limitations)).toContain( + 'Existing notification policies could not be read' + ) + }) + + it('notes a previous month with missing days', async () => { + mockApi({ + graphql: () => + HttpResponse.json({ + data: { viewer: { accounts: [{ previous: october.slice(10), current: november }] } } + }) + }) + const result = await call() + expect(JSON.stringify(result?.structuredContent?.limitations)).toContain('21 of 31 days') + }) + + it('is an error when the account returns no analytics', async () => { + mockApi({ graphql: () => HttpResponse.json({ data: { viewer: { accounts: [] } } }) }) + const result = await call() + expect(result?.isError).toBe(true) + expect(result?.content?.[0].text).toContain('No Workers analytics were returned') + }) + + it('serves its App resource without account data', async () => { + const response = await exports.default.fetch( + modernMcpRequest(TOKEN, 'resources/read', { + uri: 'ui://cloudflare/workers-usage-alert.html' + }) + ) + const body = JSON.stringify(await parseMcpResult(response)) + expect(body).toContain('text/html;profile=mcp-app') + expect(body).not.toContain(ACCOUNT) + expect(body).not.toContain(TOKEN) + }) +}) From 2b95d5fbadf68a5e55b6bf72dd125a80c8193fa3 Mon Sep 17 00:00:00 2001 From: Jonnie Lappen Date: Wed, 18 Nov 2026 18:57:00 -0700 Subject: [PATCH 03/27] feat(workers-usage-alert): rebuild the App as the radio-card mockup Three presets and a Custom 5-100% slider over October's Workers requests, an email row prefilled with the user's address for user tokens, and a no-write hand-off: Create alert sends the policy to the chat with sendMessage and updateModelContext, or shows the request it would send. --- src/workers-usage-alert/app-html.generated.ts | 2 +- src/workers-usage-alert/app/forecast.ts | 53 -- src/workers-usage-alert/app/format.ts | 24 + .../app/usage-alert-app.tsx | 570 +++++++++--------- src/workers-usage-alert/app/usage-alert.css | 343 ++++++----- src/workers-usage-alert/contract.ts | 2 + src/workers-usage-alert/tool.ts | 1 + tests/workers-usage-alert.test.ts | 12 + 8 files changed, 511 insertions(+), 496 deletions(-) delete mode 100644 src/workers-usage-alert/app/forecast.ts create mode 100644 src/workers-usage-alert/app/format.ts diff --git a/src/workers-usage-alert/app-html.generated.ts b/src/workers-usage-alert/app-html.generated.ts index e8beb483d..b6f3116c3 100644 --- a/src/workers-usage-alert/app-html.generated.ts +++ b/src/workers-usage-alert/app-html.generated.ts @@ -1,2 +1,2 @@ // Generated by npm run app:build. Do not edit. -export const appHtml = "\n\n \n \n \n Workers usage alert\n \n \n \n \n
\n \n\n" +export const appHtml = "\n\n \n \n \n Workers usage alert\n \n \n \n \n
\n \n\n" diff --git a/src/workers-usage-alert/app/forecast.ts b/src/workers-usage-alert/app/forecast.ts deleted file mode 100644 index cfd1af73b..000000000 --- a/src/workers-usage-alert/app/forecast.ts +++ /dev/null @@ -1,53 +0,0 @@ -import type { UsageAlertPreview } from '../contract' - -/** Cumulative points `[dayOfMonth, total]` for daily rows. */ -export function cumulative(rows: UsageAlertPreview['current']): [number, number][] { - let total = 0 - return rows.map(([date, requests]) => [Number(date.slice(8, 10)), (total += requests)]) -} - -/** The first day a cumulative series reaches `limit`, if it does. */ -export function crossingDay( - series: readonly [number, number][], - limit: number -): number | undefined { - return series.find(([, total]) => total >= limit)?.[0] -} - -/** - * The current month projected to its end from the last seven days' average. - * Starts at the last observed point so the dashed line joins the solid one. - */ -export function projection( - current: readonly [number, number][], - daily: UsageAlertPreview['current'], - daysInMonth: number -): [number, number][] { - const last = current.at(-1) - if (!last) return [] - const recent = daily.slice(-7) - const average = - recent.reduce((sum, [, requests]) => sum + requests, 0) / Math.max(1, recent.length) - const points: [number, number][] = [last] - for (let day = last[0] + 1; day <= daysInMonth; day++) - points.push([day, points[points.length - 1][1] + average]) - return points -} - -/** `2.4B`, `830M`, `12K`. */ -export function compact(n: number): string { - if (n >= 1e9) return `${(n / 1e9).toFixed(1).replace(/\.0$/, '')}B` - if (n >= 1e6) return `${Math.round(n / 1e6)}M` - if (n >= 1e3) return `${Math.round(n / 1e3)}K` - return String(Math.round(n)) -} - -/** `2026-10` → `Oct`. */ -export function monthLabel(month: string): string { - return new Date(`${month}-01T00:00:00Z`).toLocaleString('en', { month: 'short', timeZone: 'UTC' }) -} - -export function daysIn(month: string): number { - const [year, m] = month.split('-').map(Number) - return new Date(Date.UTC(year, m, 0)).getUTCDate() -} diff --git a/src/workers-usage-alert/app/format.ts b/src/workers-usage-alert/app/format.ts new file mode 100644 index 000000000..e93d98aad --- /dev/null +++ b/src/workers-usage-alert/app/format.ts @@ -0,0 +1,24 @@ +/** `12.4B`, `830M`, `12K`. */ +export function compact(n: number): string { + if (n >= 1e9) return `${(n / 1e9).toFixed(1).replace(/\.0$/, '')}B` + if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e8 ? 0 : 1).replace(/\.0$/, '')}M` + if (n >= 1e3) return `${Math.round(n / 1e3)}K` + return String(Math.round(n)) +} + +/** `2026-10` → `October`. */ +export function monthName(month: string): string { + return new Date(`${month}-01T00:00:00Z`).toLocaleString('en', { month: 'long', timeZone: 'UTC' }) +} + +/** + * The request count `percent` above `total`, rounded to two significant + * figures' worth of steps (0.1B for a 9B month), so the label says the round + * number picked: +10% reads "10% more", never "9%". + */ +export function limitAbove(total: number, percent: number): number { + const step = 10 ** Math.max(0, Math.floor(Math.log10(Math.max(total, 1))) - 1) + return Math.max(step, Math.round((total * (1 + percent / 100)) / step) * step) +} + +export const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/ diff --git a/src/workers-usage-alert/app/usage-alert-app.tsx b/src/workers-usage-alert/app/usage-alert-app.tsx index 1f4a13134..ce7555fc7 100644 --- a/src/workers-usage-alert/app/usage-alert-app.tsx +++ b/src/workers-usage-alert/app/usage-alert-app.tsx @@ -1,326 +1,310 @@ -import { useMemo, useRef, useState, type KeyboardEvent, type PointerEvent } from 'react' -import { Badge, Button, CloudflareLogo, Input } from '@cloudflare/kumo' +import { useId, useMemo, useRef, useState, type CSSProperties } from 'react' +import { + Button, + CloudflareLogo, + Collapsible, + Input, + LayerCard, + Radio, + Slider +} from '@cloudflare/kumo' +import type { App } from '@modelcontextprotocol/ext-apps' import { mountMcpApp } from '../../mcp-apps/app-shell/mount' -import { UsageAlertPreviewSchema, type UsageAlertPreview } from '../contract' -import { roundLimit } from '../periods' -import { compact, crossingDay, cumulative, daysIn, monthLabel, projection } from './forecast' +import { + UsageAlertPreviewSchema, + WORKER_REQUESTS_PRODUCT, + type UsageAlertPreview +} from '../contract' +import { EMAIL, compact, limitAbove, monthName } from './format' import './usage-alert.css' -const W = 520 -const H = 168 -const PL = 32 -const PR = 4 -const PT = 6 -const PB = 20 -const PRESETS = [1.1, 1.25, 1.5] as const -const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/ +const PRESETS = [ + { id: 'p10', name: 'A bit busier', percent: 10 }, + { id: 'p25', name: 'Clearly busier', percent: 25 }, + { id: 'p50', name: 'Way out of hand', percent: 50 } +] as const +type Choice = (typeof PRESETS)[number]['id'] | 'custom' +const SLIDER = { min: 5, max: 100, step: 5 } +const PERCENT = { style: 'unit', unit: 'percent', signDisplay: 'exceptZero' } as const -function UsageAlertCard({ preview: p }: { preview: UsageAlertPreview }) { - const days = daysIn(p.currentMonth) - const prev = useMemo(() => cumulative(p.previous), [p.previous]) - const cur = useMemo(() => cumulative(p.current), [p.current]) - const proj = useMemo(() => projection(cur, p.current, days), [cur, p.current, days]) - const prevTotal = prev.at(-1)?.[1] ?? 0 - const curTotal = cur.at(-1)?.[1] ?? 0 - const projected = proj.at(-1)?.[1] ?? curTotal - const yMax = Math.max(1, Math.ceil((Math.max(prevTotal, projected) * 1.6) / 1e8) * 1e8) - const minLimit = roundLimit(Math.max(1, prevTotal * 0.25)) - const maxLimit = roundLimit(yMax * 0.95) - const clamp = (v: number) => Math.max(minLimit, Math.min(maxLimit, roundLimit(v))) +/** + * What "Create alert" did. The App never writes: with a host that takes + * messages it hands the confirmed alert to the chat, where the model proposes + * the write through a tool the user confirms; otherwise it shows the request + * it would send. + */ +type Handoff = 'editing' | 'sending' | 'sent' | 'review' - const [limit, setLimit] = useState(() => clamp(p.suggestedLimit ?? prevTotal * 1.25)) - const [email, setEmail] = useState('') - const [reviewing, setReviewing] = useState(false) - const svg = useRef(null) - - const prevName = monthLabel(p.previousMonth) - const curName = monthLabel(p.currentMonth) - const x = (d: number) => PL + ((d - 1) / (31 - 1)) * (W - PL - PR) - const y = (v: number) => PT + (1 - v / yMax) * (H - PT - PB) - const path = (pts: readonly [number, number][]) => - pts.map(([d, v], i) => `${i ? 'L' : 'M'}${x(d).toFixed(1)} ${y(v).toFixed(1)}`).join(' ') - const area = (pts: readonly [number, number][]) => - pts.length - ? `${path(pts)} L${x(pts.at(-1)![0]).toFixed(1)} ${y(0)} L${x(pts[0][0]).toFixed(1)} ${y(0)} Z` - : '' - const hy = y(limit) - const prevHit = crossingDay(prev, limit) - const curHit = crossingDay([...cur, ...proj.slice(1)], limit) - const pct = prevTotal ? Math.round((limit / prevTotal - 1) * 20) * 5 : 0 - const vs = - pct === 0 - ? `equal to ${prevName}` - : `about ${Math.abs(pct)}% ${pct > 0 ? 'above' : 'below'} ${prevName}` - const validEmail = EMAIL.test(email.trim()) - const existing = p.existingAlerts ?? [] +function Check() { + return ( + + ) +} - const fromPointer = (e: PointerEvent) => { - const box = svg.current!.getBoundingClientRect() - const py = ((e.clientY - box.top) / box.height) * H - setLimit(clamp((1 - (py - PT) / (H - PT - PB)) * yMax)) - } - const onKey = (e: KeyboardEvent) => { - if (reviewing) return - const step = e.shiftKey ? limit * 0.2 : limit * 0.05 - if (e.key === 'ArrowUp' || e.key === 'ArrowRight') setLimit(clamp(limit + step)) - else if (e.key === 'ArrowDown' || e.key === 'ArrowLeft') setLimit(clamp(limit - step)) - else if (e.key === 'Home') setLimit(minLimit) - else if (e.key === 'End') setLimit(maxLimit) - else return - e.preventDefault() - } +function UsageAlertCard({ preview: p, app }: { preview: UsageAlertPreview; app: App }) { + const previousTotal = useMemo(() => p.previous.reduce((sum, [, n]) => sum + n, 0), [p.previous]) + const month = monthName(p.previousMonth) + const [choice, setChoice] = useState('p25') + const [custom, setCustom] = useState(35) + const [email, setEmail] = useState(p.userEmail ?? '') + const [touched, setTouched] = useState(false) + const [handoff, setHandoff] = useState('editing') + const emailRef = useRef(null) + const doneRef = useRef(null) + const ids = { title: useId(), error: useId(), summary: useId() } - const label = `Alert ~${compact(limit)}` - const pw = 14 + label.length * 6.4 + 10 - const px = PL + 8 - const py = hy - 22 < PT ? hy + 4 : hy - 22 - const payload = { - name: `Workers requests above ~${compact(limit)}`, + const percent = choice === 'custom' ? custom : PRESETS.find((o) => o.id === choice)!.percent + const limit = limitAbove(previousTotal, percent) + const address = email.trim() + const validEmail = EMAIL.test(address) + const invalid = touched && !validEmail + const locked = handoff !== 'editing' + const unavailable = p.alertAvailable === false + const existing = p.existingAlerts ?? [] + const describe = (pct: number) => ( + <> + ~{compact(limitAbove(previousTotal, pct))} requests · {pct}% more + than {month} + + ) + const policy = { + name: `Workers requests ${percent}% over ${month} (~${compact(limit)})`, alert_type: 'billing_usage_alert', enabled: true, - filters: { product: ['worker_requests'], limit: [String(limit)] }, - mechanisms: { email: [{ id: email.trim() || '' }] } + filters: { product: [WORKER_REQUESTS_PRODUCT], limit: [String(limit)] }, + mechanisms: { email: [{ id: address }] } + } + const request = `POST /accounts/${p.accountId}/alerting/v3/policies\n${JSON.stringify(policy, null, 2)}` + + const settle = (next: Handoff) => { + setHandoff(next) + requestAnimationFrame(() => doneRef.current?.focus()) + } + const submit = async () => { + setTouched(true) + if (!validEmail) return emailRef.current?.focus() + const caps = app.getHostCapabilities() + if (!caps?.message) return settle('review') + setHandoff('sending') + try { + if (caps.updateModelContext) + await app.updateModelContext({ + content: [ + { + type: 'text', + text: `The user confirmed this Workers usage alert in the workers_usage_alert App. It has not been created. Create it only with a write tool the user confirms:\n${request}` + } + ] + }) + const result = await app.sendMessage({ + role: 'user', + content: [ + { + type: 'text', + text: `Create a Workers usage alert on ${p.accountName ?? p.accountId}: email ${address} when Workers requests pass ${limit.toLocaleString('en')} in a billing period (${percent}% more than ${month}).` + } + ] + }) + settle(result.isError ? 'review' : 'sent') + } catch { + settle('review') + } } return ( -
-
-
- - Workers usage alert -
- - {p.accountName ?? p.accountId} - -
-
-
- {[ - ['var(--chart-blue)', `${curName} so far`, curTotal, ''], - ['var(--chart-disabled)', `${prevName} total`, prevTotal, ''], - ['var(--chart-warning)', 'Alert at', limit, 'dash'] - ].map(([color, name, value, cls]) => ( -
-
- - {name} -
-
- {compact(value as number)} - req -
-
- ))} + } + > + +
+ +

+ How much busier than {month} before I email you? +

- e.buttons === 1 && !reviewing && fromPointer(e)} - > - - - - - - - {[0, 1, 2, 3, 4].map((i) => { - const v = (yMax / 4) * i - return ( - - - - {i ? compact(v) : '0'} - - - ) - })} - {[ - [1, 'Day 1', 'start'], - [15, '15', 'middle'], - [days, String(days), 'end'] - ].map(([d, t, anchor]) => ( - - {t} - - ))} - - - - - - {prevHit && ( - - )} - - { - if (reviewing) return - svg.current?.setPointerCapture(e.pointerId) - fromPointer(e) +
+ + appearance="card" + className="rg" + value={choice} + disabled={locked} + onValueChange={(next) => { + if (next === 'custom' && choice !== 'custom') setCustom(percent) + setChoice(next) }} > - - - Email me when Workers requests are + {PRESETS.map((o) => ( + + key={o.id} + value={o.id} + label={o.name} + description={describe(o.percent)} + /> + ))} + + value="custom" + label="Custom" + className="rc-custom" + description={choice === 'custom' ? describe(custom) : 'Pick your own amount'} /> - - {label} - - - -
- Alert when - {PRESETS.map((m, i) => { - const value = clamp(prevTotal * m) - return ( - - ) - })} -
-

- Emails you at ~{compact(limit)} requests, {vs}.{' '} - {prevHit - ? `${prevName} would have triggered it on ${prevName} ${prevHit}.` - : `${prevName} never reached it.`}{' '} - {curHit - ? `${curName} is on track to reach it around ${curName} ${curHit}.` - : `${curName} is on track for ${compact(projected)}.`}{' '} - This alert doesn’t block traffic. -

- {existing.length > 0 && ( -

- Existing Workers request alert{existing.length > 1 ? 's' : ''}:{' '} - {existing - .map( - (a) => - `${a.name}${a.limit ? ` (~${compact(a.limit)})` : ''}${a.enabled ? '' : ', disabled'}` - ) - .join('; ')} - . -

- )} - {p.alertAvailable === false && ( -

- This account can’t create billing usage alerts. + {/* The slider belongs to the Custom card, as in the design. Its arrow + keys move the slider, not the radio selection. */} +

e.stopPropagation()} + > +
+ + `Percent more than ${month}`} + onValueChange={(v) => setCustom(v as number)} + /> +
+
+ +

+ Emails at about {compact(limit)} Workers requests in a billing period, {percent}% more + than {month}’s {compact(previousTotal)}. This alert doesn’t block traffic.

- )} -
- setEmail(e.target.value)} - /> - {reviewing ? ( - - ) : ( + {existing.length > 0 && ( +

+ Already on this account:{' '} + {existing + .map( + (a) => + `${a.name}${a.limit ? ` (~${compact(a.limit)})` : ''}${a.enabled ? '' : ', disabled'}` + ) + .join('; ')} + . +

+ )} + {unavailable && ( +

+ This account can’t create billing usage alerts. +

+ )} +
+ +
+ {handoff === 'editing' || handoff === 'sending' ? ( + <> + - )} -
- {reviewing && ( -
-

- Creating alerts from this card isn’t available yet. This is the policy it would - create: +

-
{`POST /accounts/${p.accountId}/alerting/v3/policies\n${JSON.stringify(payload, null, 2)}`}
-
+ + ) : ( + <> + + {handoff === 'sent' ? ( + <> + Sent to chat to create: emails {address} at ~{compact(limit)} requests. + + ) : ( + 'Creating alerts from here isn’t available yet.' + )} + + + {handoff === 'review' && ( + + + Show request + + +
{request}
+
+
+ )} + )}
-

- Cloudflare API · read {new Date(p.checkedAt).toLocaleString()} · read-only. - {p.limitations.length > 0 && ` ${p.limitations.join(' ')}`} -

-
+ ) } mountMcpApp({ name: 'Cloudflare Workers usage alert', output: UsageAlertPreviewSchema, - render: (preview) => , + render: (preview, { app }) => ( + + ), copy: { pending: 'Reading Workers usage…', cancelled: 'Usage check cancelled.', diff --git a/src/workers-usage-alert/app/usage-alert.css b/src/workers-usage-alert/app/usage-alert.css index ef6b73c7b..0bebc3162 100644 --- a/src/workers-usage-alert/app/usage-alert.css +++ b/src/workers-usage-alert/app/usage-alert.css @@ -1,195 +1,240 @@ @import '../../mcp-apps/app-shell/base.css'; @source './usage-alert-app.tsx'; -/* Kumo ChartPalette (chart/Color.ts) */ -:root { - --chart-blue: #4290f0; - --chart-warning: #f8a054; - --chart-disabled: light-dark(#cbcbcb, #878787); - --chart-text: light-dark(#6b7280, #9ca3af); - --chart-grid: light-dark(rgb(107 114 128 / 0.2), rgb(156 163 175 / 0.2)); +/* Kumo sizes in rem and assumes a 16px root; the shared base sets html to 14px, + which shrinks every Kumo control by an eighth. Body text stays at 14px. */ +html { + font-size: 16px; +} +body { + font-family: var(--font-sans); + font-size: 14px; } -.card { +/* + * The fuzzy-input design: a LayerDialog-style card. An elevated LayerCard holds + * a Primary layer (glyph, question, card radios with the Custom slider) and an + * actions row beneath it. Kumo renders the parts; this file sets the design's + * spacing where Kumo's defaults differ. + */ +.ld { container-type: inline-size; min-width: 0; + padding: 6px; + border-radius: 12px; + box-shadow: 0 8px 10px -6px rgb(0 0 0 / 0.03); +} +.ld-primary { + gap: 0; + padding: 0; border-radius: 8px; - background: var(--color-kumo-elevated); - box-shadow: 0 0 0 1px var(--color-kumo-hairline); - overflow: hidden; } -header { +.ld-head { display: flex; - justify-content: space-between; - align-items: center; - gap: 8px; - padding: 8px 12px 8px 14px; - min-height: 40px; - flex-wrap: wrap; + gap: 12px; + align-items: flex-start; + padding: 16px 18px; } -.title { - display: flex; - gap: 8px; - align-items: center; - min-width: 0; +.cf { + width: 28px; + flex: none; + margin-top: 5px; } -.title strong { +.ld-title { + margin: 0; + font-size: var(--text-lg); font-weight: 500; + line-height: 1.5; + text-wrap: balance; } -.logo { - width: 22px; - flex-shrink: 0; -} -.body { - margin: 0 4px 4px; - border-radius: 6px; - background: var(--color-kumo-base); - box-shadow: - 0 1px 2px 0 oklch(0% 0 0 / 0.05), - 0 0 0 1px var(--color-kumo-line); - padding: 14px 16px 16px; - display: flex; - flex-direction: column; - gap: 12px; +.ld-body { + padding: 2px 18px 18px; } -.legend { - display: flex; - gap: 20px; - flex-wrap: wrap; +.rg { + min-width: 0; + border: 0; } -.lg { - display: inline-flex; - flex-direction: column; - gap: 4px; +.num { + font-variant-numeric: tabular-nums; } -.lg .k { - display: flex; - align-items: center; - gap: 6px; - font-size: 12px; - color: var(--text-color-kumo-subtle); - white-space: nowrap; + +/* Custom card: the slider panel continues the Custom row, with no divider. */ +.rc-custom { + border-bottom-width: 0; +} +.collapse-panel { + display: grid; + grid-template-rows: 0fr; + opacity: 0; + transition: + grid-template-rows 200ms ease-out, + opacity 200ms ease-out; +} +.collapse-panel[data-open='true'] { + grid-template-rows: 1fr; + opacity: 1; + background: var(--color-kumo-tint); +} +/* The reveal clips while it animates. The track's ring and the thumb's focus + ring draw outside their boxes, so the clip box starts 4px above the track + (padding inside, pulled back up by the same margin): nothing is cut off and + nothing moves. */ +.collapse-panel > div { + min-height: 0; + overflow: hidden; + margin-top: -4px; } -.lg .dot { - width: 8px; - height: 8px; - border-radius: 50%; +.sl { + padding: 4px 12px 12px; + user-select: none; } -.lg .dot.dash { - width: 10px; - height: 2px; - border-radius: 1px; +/* Kumo centres the value badge on the thumb, so at either end it spills past + the track. Slide its anchor across the thumb with the value instead: its + left edge meets the thumb's at the minimum, its right edge at the maximum, + and in between it stays over the thumb. */ +.sl [data-index] > span:nth-of-type(2) { + left: calc(var(--thumb-at, 0.5) * 100%); + translate: calc(var(--thumb-at, 0.5) * -100%) 0; } -.lg .v { - display: flex; - align-items: baseline; - gap: 3px; +/* Room for the value badge under the thumb, above the +5% / +100% ends. */ +.sl > div:last-child { + margin-top: 22px; } -.lg .v b { - font-size: 16px; - line-height: 1; - font-weight: 500; - font-variant-numeric: tabular-nums; + +/* Locked once confirmed: nothing washes out. The rows simply stop responding, + and the unchosen radios recede a little. */ +[data-locked] .rg [data-kumo-part='item-label'] { + opacity: 1; + cursor: default; } -.lg .v span { - font-size: 12px; - color: var(--text-color-kumo-subtle); +[data-locked] .rg [data-kumo-part='item-label']:not(:has([data-checked])) [data-kumo-part='item'] { + opacity: 0.5; } -.chart { - display: block; - width: 100%; - height: auto; - overflow: visible; - touch-action: none; - user-select: none; +[data-locked] .sl { + opacity: 1; } -.tick { - font-size: 10px; - fill: var(--chart-text); +[data-locked] .sl [data-index] { + cursor: default; } -.handle { - cursor: ns-resize; - outline: none; +[data-locked] .sl [data-index] > span:nth-of-type(2) { + background: var(--color-kumo-contrast); + color: var(--text-color-kumo-inverse); } -.handle .pill { - fill: var(--color-kumo-base); - stroke: var(--color-kumo-line); + +/* Preset marks at +10/+25/+50%, over Kumo's track (inset 3px, edge-aligned 16px thumb). */ +.collapse-panel > div { + position: relative; +} +.sl-marks { + position: absolute; + top: 4px; + left: 23px; + right: 23px; + height: 32px; + pointer-events: none; + z-index: 1; +} +.sl-marks span { + position: absolute; + top: 50%; + width: 4px; + height: 4px; + margin: -2px 0 0 -2px; + border-radius: 50%; + background: color-mix(in oklch, var(--color-kumo-contrast) 22%, transparent); } -.handle:focus-visible .pill { - stroke: var(--color-kumo-brand); - stroke-width: 2; +.sl [data-index] { + z-index: 2; } -.pill-text { - font-size: 11px; - font-weight: 500; - fill: var(--text-color-kumo-default); +/* Kumo rings the thumb on any focus; the design shows it only for the keyboard. */ +.sl [data-index]:not(:has(:focus-visible)) { + box-shadow: none; } -.pills { + +.request-disclosure { + flex-basis: 100%; display: flex; + flex-direction: column; gap: 6px; - flex-wrap: wrap; - align-items: center; } -.pills .lbl { - font-size: 13px; +.note { + margin: 10px 0 0; + font-size: var(--text-sm); color: var(--text-color-kumo-subtle); } -.pill-btn { - font: inherit; - font-size: 12px; - border-radius: 999px; - padding: 2px 10px; - border: 1px solid var(--color-kumo-line); - background: var(--color-kumo-base); - color: var(--text-color-kumo-default); - cursor: pointer; -} -.pill-btn[aria-pressed='true'] { - background: var(--color-kumo-fill); - border-color: transparent; -} -.pill-btn:focus-visible { - outline: 2px solid var(--color-kumo-brand); - outline-offset: 1px; -} -.pill-btn:disabled { - cursor: default; - opacity: 0.6; +.note.warn { + color: var(--text-color-kumo-warning); } -.summary { - margin: 0; + +.ld-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 7px 0 0 6px; + min-height: 43px; } -.subtle, -.observed { - margin: 0; - font-size: 12px; +.to { + flex: 1 1 auto; + min-width: 0; + display: flex; + align-items: center; + gap: 8px; + font-size: var(--text-sm); color: var(--text-color-kumo-subtle); } -.observed { - padding: 8px 14px 10px; +.to .email { + flex: 1 1 auto; + min-width: 0; + max-width: 280px; } -.warn { - margin: 0; - color: var(--text-color-kumo-warning); +.err { + flex-basis: 100%; + margin: -2px 0 0; + padding-left: 30px; + font-size: var(--text-sm); + color: var(--text-color-kumo-danger); } -.foot { - display: flex; - gap: 8px; +.saved { + flex: 1 1 0; + min-width: 0; + display: inline-flex; align-items: center; + gap: 6px; + font-size: var(--text-sm); + font-weight: 500; + color: var(--text-color-kumo-success); + outline: none; } -.foot > :first-child { - flex: 1; - min-width: 0; +.saved[data-sent='false'] { + font-weight: 400; + color: var(--text-color-kumo-subtle); } -.review pre { - margin: 6px 0 0; +.saved svg { + flex: none; +} +.request { + margin: 0 6px 0 0; padding: 10px; - border-radius: 6px; + border-radius: 8px; background: var(--color-kumo-recessed); - font: - 12px/1.45 ui-monospace, - SFMono-Regular, - Menlo, - monospace; - overflow-x: auto; + box-shadow: 0 0 0 1px var(--color-kumo-line); + font: 12px/1.45 var(--font-mono); + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +@container (max-width: 480px) { + .ld-head { + padding: 14px; + } + .ld-body { + padding: 2px 14px 14px; + } +} +@media (prefers-reduced-motion: reduce) { + .collapse-panel { + transition: none; + } } diff --git a/src/workers-usage-alert/contract.ts b/src/workers-usage-alert/contract.ts index 554624c1d..37b948963 100644 --- a/src/workers-usage-alert/contract.ts +++ b/src/workers-usage-alert/contract.ts @@ -37,6 +37,8 @@ export const UsageAlertPreviewSchema = z.object({ checkedAt: z.iso.datetime(), accountId: z.string(), accountName: z.string().optional(), + /** The signed-in user's own email, for a user credential: the view's default recipient. */ + userEmail: z.string().optional(), /** UTC calendar months, `YYYY-MM`. Billing periods may not align with them. */ currentMonth: z.string(), previousMonth: z.string(), diff --git a/src/workers-usage-alert/tool.ts b/src/workers-usage-alert/tool.ts index fdc846466..6901b1b02 100644 --- a/src/workers-usage-alert/tool.ts +++ b/src/workers-usage-alert/tool.ts @@ -183,6 +183,7 @@ async function collect( ...(accountName(context.props, accountId) ? { accountName: accountName(context.props, accountId) } : {}), + ...(context.props.type === 'user_token' ? { userEmail: context.props.user.email } : {}), currentMonth: current.month, previousMonth: previous.month, current: rows(account.current), diff --git a/tests/workers-usage-alert.test.ts b/tests/workers-usage-alert.test.ts index 102fe52f5..65cb6c55a 100644 --- a/tests/workers-usage-alert.test.ts +++ b/tests/workers-usage-alert.test.ts @@ -143,6 +143,18 @@ describe.each([ expect(result?.structuredContent?.previous).toHaveLength(31) expect(result?.structuredContent?.current).toHaveLength(18) expect(JSON.stringify(result)).not.toContain('private@example.com') + // An account token has no user, so the view has no default recipient. + expect(result?.structuredContent).not.toHaveProperty('userEmail') + }) + + it('offers a user credential’s own email as the default recipient', async () => { + mockIdentityProbe({ + user: { id: 'u1', email: 'me@example.com' }, + accounts: [{ id: ACCOUNT, name: 'Usage Co' }] + }) + mockApi() + const result = await call({ as_of: '2026-11-18' }, url) + expect(result?.structuredContent).toMatchObject({ userEmail: 'me@example.com' }) }) }) From eac3c2cb73574658d6ed86d76ed34ef2fc7c7ed7 Mon Sep 17 00:00:00 2001 From: Jonnie Lappen Date: Thu, 19 Nov 2026 12:46:40 -0700 Subject: [PATCH 04/27] feat(workers-usage-alert): chart 89 days and preview an hourly 7-day monitor Read 89 days of workersInvocationsAdaptive in one GraphQL query, as three aliased ~30-day windows (the dataset caps one field's span), and preview a custom_analytics monitor on the rolling 7-day request count instead of a monthly billing alert. The App ports the fuzzy-input mockup: a draggable limit over the 89-day chart, the typical week, and an email replay. --- src/workers-usage-alert/app-html.generated.ts | 2 +- src/workers-usage-alert/app/format.ts | 59 +- .../app/usage-alert-app.tsx | 850 ++++++++++++----- src/workers-usage-alert/app/usage-alert.css | 887 +++++++++++++++--- src/workers-usage-alert/contract.ts | 60 +- src/workers-usage-alert/history.ts | 48 + src/workers-usage-alert/model.ts | 283 ++++++ src/workers-usage-alert/periods.ts | 50 - src/workers-usage-alert/tool.ts | 130 +-- tests/workers-usage-alert.test.ts | 219 ++++- 10 files changed, 2014 insertions(+), 574 deletions(-) create mode 100644 src/workers-usage-alert/history.ts create mode 100644 src/workers-usage-alert/model.ts delete mode 100644 src/workers-usage-alert/periods.ts diff --git a/src/workers-usage-alert/app-html.generated.ts b/src/workers-usage-alert/app-html.generated.ts index b6f3116c3..a68e7a4d1 100644 --- a/src/workers-usage-alert/app-html.generated.ts +++ b/src/workers-usage-alert/app-html.generated.ts @@ -1,2 +1,2 @@ // Generated by npm run app:build. Do not edit. -export const appHtml = "\n\n \n \n \n Workers usage alert\n \n \n \n \n
\n \n\n" +export const appHtml = "\n\n \n \n \n Workers usage alert\n \n \n \n \n
\n \n\n" diff --git a/src/workers-usage-alert/app/format.ts b/src/workers-usage-alert/app/format.ts index e93d98aad..2e6a305f8 100644 --- a/src/workers-usage-alert/app/format.ts +++ b/src/workers-usage-alert/app/format.ts @@ -1,24 +1,49 @@ -/** `12.4B`, `830M`, `12K`. */ -export function compact(n: number): string { - if (n >= 1e9) return `${(n / 1e9).toFixed(1).replace(/\.0$/, '')}B` - if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e8 ? 0 : 1).replace(/\.0$/, '')}M` - if (n >= 1e3) return `${Math.round(n / 1e3)}K` - return String(Math.round(n)) +/** + * Counts at any size: K, M, B, T. `fmt` is a value the user picked (a + * multiple of a nice step), in its shortest exact form; `sig` a measured + * value to `n` significant digits; `words` the same for screen readers. + */ +const UNITS = [ + [1e12, 'T', 'trillion'], + [1e9, 'B', 'billion'], + [1e6, 'M', 'million'], + [1e3, 'K', 'thousand'], + [1, '', ''] +] as const +const unitOf = (v: number) => UNITS.find(([u]) => Math.abs(v) >= u * 0.9995) ?? UNITS[4] +const trim = (t: string) => (t.includes('.') ? t.replace(/\.?0+$/, '') : t) + +export function fmt(v: number): string { + if (!v) return '0' + const [u, s] = unitOf(v) + const x = v / u + let d = 0 + while (d < 3 && Math.abs(x * 10 ** d - Math.round(x * 10 ** d)) > 1e-6) d++ + return trim(x.toFixed(d)) + s } -/** `2026-10` → `October`. */ -export function monthName(month: string): string { - return new Date(`${month}-01T00:00:00Z`).toLocaleString('en', { month: 'long', timeZone: 'UTC' }) +export function sig(v: number, n = 2): string { + if (!v) return '0' + const [u, s] = unitOf(v) + const x = v / u + return trim(x.toFixed(Math.max(0, n - 1 - Math.floor(Math.log10(x) + 1e-9)))) + s } -/** - * The request count `percent` above `total`, rounded to two significant - * figures' worth of steps (0.1B for a 9B month), so the label says the round - * number picked: +10% reads "10% more", never "9%". - */ -export function limitAbove(total: number, percent: number): number { - const step = 10 ** Math.max(0, Math.floor(Math.log10(Math.max(total, 1))) - 1) - return Math.max(step, Math.round((total * (1 + percent / 100)) / step) * step) +export function words(v: number): string { + const [u, , w] = unitOf(v) + return (u === 1 ? String(Math.round(v)) : fmt(v).replace(/[KMBT]$/, '')) + (w ? ` ${w}` : '') } +/** `2026-11-03` → `Nov 3`. */ +export const fmtDay = (d: string) => + new Date(`${d}T00:00:00Z`).toLocaleString('en', { + month: 'short', + day: 'numeric', + timeZone: 'UTC' + }) + +/** `2026-11` → `Nov`. */ +export const monthShort = (k: string) => + new Date(`${k}-15T00:00:00Z`).toLocaleString('en', { month: 'short', timeZone: 'UTC' }) + export const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/ diff --git a/src/workers-usage-alert/app/usage-alert-app.tsx b/src/workers-usage-alert/app/usage-alert-app.tsx index ce7555fc7..19de6f2d6 100644 --- a/src/workers-usage-alert/app/usage-alert-app.tsx +++ b/src/workers-usage-alert/app/usage-alert-app.tsx @@ -1,106 +1,419 @@ -import { useId, useMemo, useRef, useState, type CSSProperties } from 'react' import { - Button, - CloudflareLogo, - Collapsible, - Input, - LayerCard, - Radio, - Slider -} from '@cloudflare/kumo' + useCallback, + useEffect, + useId, + useLayoutEffect, + useMemo, + useRef, + useState, + type CSSProperties, + type KeyboardEvent, + type PointerEvent +} from 'react' +import { Button, CloudflareLogo, Collapsible, LayerCard } from '@cloudflare/kumo' import type { App } from '@modelcontextprotocol/ext-apps' import { mountMcpApp } from '../../mcp-apps/app-shell/mount' +import { UsageAlertPreviewSchema, type UsageAlertPreview } from '../contract' import { - UsageAlertPreviewSchema, - WORKER_REQUESTS_PRODUCT, - type UsageAlertPreview -} from '../contract' -import { EMAIL, compact, limitAbove, monthName } from './format' + clamp, + deriveModel, + fitTop, + monitorPolicy, + replayEmails, + snapTo, + stepOf, + tickOf, + type Model, + type Week +} from '../model' +import { EMAIL, fmt, fmtDay, monthShort, sig, words } from './format' import './usage-alert.css' -const PRESETS = [ - { id: 'p10', name: 'A bit busier', percent: 10 }, - { id: 'p25', name: 'Clearly busier', percent: 25 }, - { id: 'p50', name: 'Way out of hand', percent: 50 } -] as const -type Choice = (typeof PRESETS)[number]['id'] | 'custom' -const SLIDER = { min: 5, max: 100, step: 5 } -const PERCENT = { style: 'unit', unit: 'percent', signDisplay: 'exceptZero' } as const - /** * What "Create alert" did. The App never writes: with a host that takes - * messages it hands the confirmed alert to the chat, where the model proposes - * the write through a tool the user confirms; otherwise it shows the request - * it would send. + * messages it hands the alert to the chat, where the model proposes the write + * through a tool the user approves; otherwise it shows the request. */ -type Handoff = 'editing' | 'sending' | 'sent' | 'review' +type Phase = 'editing' | 'sending' | 'sent' | 'review' +type Tone = '' | 'hit' | 'now' | 'warn' +type Fact = readonly [Tone, string] + +const reduceMotion = () => matchMedia('(prefers-reduced-motion: reduce)').matches +const canHover = () => matchMedia('(hover: hover) and (pointer: fine)').matches +// Drag past an edge to grow or shrink the axis, like a list scrolling when you drag past its end: +// px zone inside each edge, px to full speed, e-folds per second. Settling eases with time constant TAU (s). +const EDGE = 10 +const RAMP = 110 +const GROW = 1.8 +const TAU = 0.055 + +/** Two short facts under the title, each sized to fit one line at 320px. */ +function outcome(m: Model, limit: number): [Fact, Fact] { + const sent = replayEmails(m.days, m.rolling, limit) + const first = sent.find((e) => e.first) + const past: Fact = + m.typical && limit < m.typical + ? ['warn', `Below a typical week (~${sig(m.typical)})`] + : sent.length && first + ? [ + 'hit', + `${sent.length} past ${sent.length === 1 ? 'email' : 'emails'}, first ${fmtDay(first.date)}` + ] + : limit >= 2 * m.peak + ? ['', `No past emails; ${sig(limit / m.peak)}× busiest week`] + : ['', `No past emails; busiest week ${sig(m.peak)}`] + const now: Fact = + m.last7 >= limit + ? ['warn', 'Already over: emails within the hour'] + : ['now', `Last 7 days: ${sig(m.last7)}`] + return [past, now] +} -function Check() { +function FactLine({ fact }: { fact: Fact }) { return ( - + +