From 5df3ac408781d0fbfd125c9f7aa445381d2aa19e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Igor=20=C5=A0=C4=87eki=C4=87?= Date: Thu, 10 Sep 2026 00:58:20 +0000 Subject: [PATCH 01/11] feat(kilo-mcp): remote MCP worker with hybrid catalog search, tRPC calls, and OAuth 2.1 sign-in (part 1/1) https://github.com/Kilo-Org/cloud/pull/6030 --- .github/workflows/kilo-mcp-catalog.yml | 242 + .oxfmtrc.json | 2 +- apps/web/jest.config.ts | 4 +- .../src/scripts/mcp-catalog/catalog.test.ts | 402 + apps/web/src/scripts/mcp-catalog/catalog.ts | 703 + apps/web/src/scripts/mcp-catalog/dump.ts | 158 + pnpm-lock.yaml | 47 +- scripts/kilo-mcp-catalog.test.mjs | 303 + services/kilo-mcp/catalog.json | 10242 +++++++++++ services/kilo-mcp/drizzle.config.ts | 8 + .../kilo-mcp/drizzle/0000_happy_zaladane.sql | 43 + .../drizzle/0001_cynical_karen_page.sql | 2 + .../kilo-mcp/drizzle/meta/0000_snapshot.json | 284 + .../kilo-mcp/drizzle/meta/0001_snapshot.json | 298 + services/kilo-mcp/drizzle/meta/_journal.json | 20 + services/kilo-mcp/drizzle/migrations.d.ts | 12 + services/kilo-mcp/drizzle/migrations.js | 11 + services/kilo-mcp/package.json | 30 + services/kilo-mcp/scripts/embed-catalog.ts | 280 + services/kilo-mcp/src/auth.test.ts | 165 + services/kilo-mcp/src/auth.ts | 83 + services/kilo-mcp/src/auth/authorize.test.ts | 312 + services/kilo-mcp/src/auth/authorize.ts | 262 + services/kilo-mcp/src/auth/dcr.test.ts | 229 + services/kilo-mcp/src/auth/dcr.ts | 256 + services/kilo-mcp/src/auth/http.ts | 132 + services/kilo-mcp/src/auth/jwt.ts | 82 + services/kilo-mcp/src/auth/metadata.test.ts | 81 + services/kilo-mcp/src/auth/metadata.ts | 75 + services/kilo-mcp/src/auth/pkce.test.ts | 47 + services/kilo-mcp/src/auth/pkce.ts | 67 + services/kilo-mcp/src/auth/token.test.ts | 697 + services/kilo-mcp/src/auth/token.ts | 409 + services/kilo-mcp/src/auth/verify.test.ts | 116 + services/kilo-mcp/src/auth/verify.ts | 83 + services/kilo-mcp/src/call.test.ts | 242 + services/kilo-mcp/src/call.ts | 200 + services/kilo-mcp/src/db/sqlite-schema.ts | 93 + .../kilo-mcp/src/embed-catalog-script.test.ts | 195 + services/kilo-mcp/src/embedding.ts | 21 + services/kilo-mcp/src/index.test.ts | 993 + services/kilo-mcp/src/index.ts | 443 + .../src/oauth-pages/authorize-page.test.ts | 366 + .../src/oauth-pages/authorize-page.ts | 207 + .../src/oauth-pages/org-picker.test.ts | 446 + .../kilo-mcp/src/oauth-pages/org-picker.ts | 296 + services/kilo-mcp/src/search-knn.test.ts | 96 + services/kilo-mcp/src/search-knn.ts | 55 + services/kilo-mcp/src/search.test.ts | 179 + services/kilo-mcp/src/search.ts | 152 + services/kilo-mcp/src/sql.d.ts | 8 + .../kilo-mcp/src/store/oauth-store.test.ts | 489 + services/kilo-mcp/src/store/oauth-store.ts | 525 + services/kilo-mcp/src/types.ts | 76 + services/kilo-mcp/tsconfig.json | 18 + services/kilo-mcp/vitest.config.ts | 31 + services/kilo-mcp/worker-configuration.d.ts | 15295 ++++++++++++++++ services/kilo-mcp/wrangler.jsonc | 92 + 58 files changed, 36699 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/kilo-mcp-catalog.yml create mode 100644 apps/web/src/scripts/mcp-catalog/catalog.test.ts create mode 100644 apps/web/src/scripts/mcp-catalog/catalog.ts create mode 100644 apps/web/src/scripts/mcp-catalog/dump.ts create mode 100644 scripts/kilo-mcp-catalog.test.mjs create mode 100644 services/kilo-mcp/catalog.json create mode 100644 services/kilo-mcp/drizzle.config.ts create mode 100644 services/kilo-mcp/drizzle/0000_happy_zaladane.sql create mode 100644 services/kilo-mcp/drizzle/0001_cynical_karen_page.sql create mode 100644 services/kilo-mcp/drizzle/meta/0000_snapshot.json create mode 100644 services/kilo-mcp/drizzle/meta/0001_snapshot.json create mode 100644 services/kilo-mcp/drizzle/meta/_journal.json create mode 100644 services/kilo-mcp/drizzle/migrations.d.ts create mode 100644 services/kilo-mcp/drizzle/migrations.js create mode 100644 services/kilo-mcp/package.json create mode 100644 services/kilo-mcp/scripts/embed-catalog.ts create mode 100644 services/kilo-mcp/src/auth.test.ts create mode 100644 services/kilo-mcp/src/auth.ts create mode 100644 services/kilo-mcp/src/auth/authorize.test.ts create mode 100644 services/kilo-mcp/src/auth/authorize.ts create mode 100644 services/kilo-mcp/src/auth/dcr.test.ts create mode 100644 services/kilo-mcp/src/auth/dcr.ts create mode 100644 services/kilo-mcp/src/auth/http.ts create mode 100644 services/kilo-mcp/src/auth/jwt.ts create mode 100644 services/kilo-mcp/src/auth/metadata.test.ts create mode 100644 services/kilo-mcp/src/auth/metadata.ts create mode 100644 services/kilo-mcp/src/auth/pkce.test.ts create mode 100644 services/kilo-mcp/src/auth/pkce.ts create mode 100644 services/kilo-mcp/src/auth/token.test.ts create mode 100644 services/kilo-mcp/src/auth/token.ts create mode 100644 services/kilo-mcp/src/auth/verify.test.ts create mode 100644 services/kilo-mcp/src/auth/verify.ts create mode 100644 services/kilo-mcp/src/call.test.ts create mode 100644 services/kilo-mcp/src/call.ts create mode 100644 services/kilo-mcp/src/db/sqlite-schema.ts create mode 100644 services/kilo-mcp/src/embed-catalog-script.test.ts create mode 100644 services/kilo-mcp/src/embedding.ts create mode 100644 services/kilo-mcp/src/index.test.ts create mode 100644 services/kilo-mcp/src/index.ts create mode 100644 services/kilo-mcp/src/oauth-pages/authorize-page.test.ts create mode 100644 services/kilo-mcp/src/oauth-pages/authorize-page.ts create mode 100644 services/kilo-mcp/src/oauth-pages/org-picker.test.ts create mode 100644 services/kilo-mcp/src/oauth-pages/org-picker.ts create mode 100644 services/kilo-mcp/src/search-knn.test.ts create mode 100644 services/kilo-mcp/src/search-knn.ts create mode 100644 services/kilo-mcp/src/search.test.ts create mode 100644 services/kilo-mcp/src/search.ts create mode 100644 services/kilo-mcp/src/sql.d.ts create mode 100644 services/kilo-mcp/src/store/oauth-store.test.ts create mode 100644 services/kilo-mcp/src/store/oauth-store.ts create mode 100644 services/kilo-mcp/src/types.ts create mode 100644 services/kilo-mcp/tsconfig.json create mode 100644 services/kilo-mcp/vitest.config.ts create mode 100644 services/kilo-mcp/worker-configuration.d.ts create mode 100644 services/kilo-mcp/wrangler.jsonc diff --git a/.github/workflows/kilo-mcp-catalog.yml b/.github/workflows/kilo-mcp-catalog.yml new file mode 100644 index 0000000000..66f5471d73 --- /dev/null +++ b/.github/workflows/kilo-mcp-catalog.yml @@ -0,0 +1,242 @@ +name: Kilo MCP catalog + +# Keeps services/kilo-mcp/catalog.json in lockstep with the tRPC router graph. +# +# - PR job: regenerates the catalog with the real dump script. Same-repo PRs get +# the refreshed catalog.json committed back to the PR branch (requirement 5); +# fork PRs cannot be pushed to, so the diff ships as a `catalog.patch` +# artifact, a one-line PR comment points at it, and the job fails +# (requirement 6). A fork PR also gets no LLM secret (GitHub withholds +# secrets from fork events), so when the dump itself cannot run, a dedicated +# step posts the credential-free recovery — hand-written summaries in +# catalog.json, which the keep-edit rule preserves — and fails the job, so +# requirement 6 holds on that path too. The PR job never touches Vectorize or +# the embed script +# (requirement 10) and never generates summaries at runtime — only the dump +# does, and it preserves author-edited summaries (requirement 2, s1 keep-edit +# rule). +# - Merge job: gated to main pushes only, so PRs structurally cannot reach it +# (requirement 10). Re-runs the dump to fill any summaries that slipped +# through (requirement 8), then upserts the Vectorize index (requirement 9). +# Production deploys from main, so the committed bundled catalog and the +# upserted index stay in lockstep (requirement 22). +# +# The CI wiring of this file is asserted by scripts/kilo-mcp-catalog.test.mjs +# (same pattern as scripts/stacked-ci.test.mjs in .github/workflows/ci.yml). + +on: + pull_request: + paths: + - 'apps/web/src/**' + - 'services/kilo-mcp/**' + - '.github/workflows/kilo-mcp-catalog.yml' + - 'scripts/kilo-mcp-catalog.test.mjs' + push: + branches: [main] + paths: + - 'apps/web/src/**' + - 'services/kilo-mcp/**' + +# New commits to the same PR supersede in-progress runs; a main push must not +# be cancelled mid-Vectorize-upsert. +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: read + +jobs: + catalog-pr: + name: catalog (PR) + if: github.event_name == 'pull_request' + runs-on: ${{ vars.RUNNER_DEFAULT_LABEL || 'ubuntu-latest' }} + timeout-minutes: 20 + # contents: write lets the bot commit the refreshed catalog back to a + # same-repo PR branch; pull-requests: write lets it comment on fork PRs. + permissions: + contents: write + pull-requests: write + steps: + - uses: useblacksmith/checkout@41cdeedae8edb2e684ba22896a5fd2a3cb85db6b # v1 + + - name: Setup pnpm + uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v4.4.0 + + - name: Setup Node + uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 + with: + node-version-file: '.nvmrc' + cache: 'pnpm' + + - name: Install root dependencies + run: pnpm --filter kilocode-monorepo install --frozen-lockfile --ignore-scripts + + - name: Check catalog workflow wiring + run: node --test scripts/kilo-mcp-catalog.test.mjs + + - name: Install web dependencies + run: pnpm install --frozen-lockfile --filter web... + + # Same dummies the jest suite already tolerates (ci.yml does the same for + # the production build). The dump itself layers apps/web/.env.test under + # any real env, and dotenv never overrides exported values, so the LLM + # key below always wins over the .env.test placeholder. + - name: Setup dummy env + working-directory: apps/web + run: cp .env.test .env + + - name: Regenerate catalog.json + id: dump + # Fork PRs never receive MCP_CATALOG_LLM_API_KEY (GitHub withholds + # secrets from fork pull_request events), so a fork PR that adds a + # query without committed summaries always fails the dump here. + # Tolerate that on forks so the guidance step below can still honour + # requirement 6; a same-repo dump failure stays fatal. + continue-on-error: ${{ github.event.pull_request.head.repo.fork == true }} + env: + OPENROUTER_API_KEY: ${{ secrets.MCP_CATALOG_LLM_API_KEY }} + run: pnpm --filter web script src/scripts/mcp-catalog/dump.ts + + # Requirement 6 when the dump itself cannot run: the drift-gated fork + # steps below never see a diff (the dump exits without writing), so this + # step posts the recovery that works without CI credentials — the + # keep-edit rule preserves hand-written summaries in the committed + # catalog — and fails the job. Must run before drift detection. + - name: Guide fork PR past an un-runnable catalog dump + if: steps.dump.outcome == 'failure' && github.event.pull_request.head.repo.fork == true + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + COMMENT_BODY: >- + The MCP catalog dump failed on this fork PR. Fork PRs never get + CI's LLM credentials (GitHub withholds secrets from fork events), + so summaries for new query paths cannot be generated here. To + recover, hand-write a summary for each new path in + `services/kilo-mcp/catalog.json` (committed summaries are kept by + the dump), or run + `pnpm --filter web script src/scripts/mcp-catalog/dump.ts` + locally with your own `OPENROUTER_API_KEY` and push. If the log + shows a different error than missing credentials, fix that and + push. + run: | + gh pr comment "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" --body "$COMMENT_BODY" || true + echo "::error::The MCP catalog dump failed on this fork PR (fork PRs get no LLM credentials). Hand-write a summary for each new path in services/kilo-mcp/catalog.json — the dump keeps committed summaries — or run the dump locally with OPENROUTER_API_KEY and push." + exit 1 + + - name: Detect catalog drift + id: drift + run: | + if git diff --exit-code -- services/kilo-mcp/catalog.json > /dev/null; then + echo "changed=false" >> "$GITHUB_OUTPUT" + else + echo "changed=true" >> "$GITHUB_OUTPUT" + fi + + # Same-repo PR: commit ONLY catalog.json to the PR branch under the + # actions-bot identity (requirement 5). The dump's keep-edit rule means + # an author-edited summary in the committed file survives the regen, so + # this push never reverts a human edit. + - name: Commit catalog to PR branch + if: steps.drift.outputs.changed == 'true' && github.event.pull_request.head.repo.fork == false + env: + GH_TOKEN: ${{ github.token }} + HEAD_BRANCH: ${{ github.head_ref }} + run: | + set -euo pipefail + cp services/kilo-mcp/catalog.json /tmp/catalog.json + # apps/web/.env is tracked and the dummy-env copy dirties it; reset + # the worktree so the branch switch below cannot be refused. + git checkout -- services/kilo-mcp/catalog.json apps/web/.env + git fetch --no-tags origin "refs/heads/$HEAD_BRANCH" + git checkout -B "$HEAD_BRANCH" FETCH_HEAD + cp /tmp/catalog.json services/kilo-mcp/catalog.json + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add services/kilo-mcp/catalog.json + git diff --cached --quiet || git commit -m "chore(kilo-mcp): refresh catalog.json from CI" + git push origin "HEAD:$HEAD_BRANCH" + + # Fork PR: GITHUB_TOKEN cannot push to the fork, so hand the author the + # patch and fail loudly instead of silently leaving the catalog stale + # (requirement 6). + - name: Export catalog patch (fork PRs) + if: steps.drift.outputs.changed == 'true' && github.event.pull_request.head.repo.fork == true + run: git diff -- services/kilo-mcp/catalog.json > catalog.patch + + - name: Upload catalog patch artifact + if: steps.drift.outputs.changed == 'true' && github.event.pull_request.head.repo.fork == true + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 + with: + name: catalog.patch + path: catalog.patch + + # Best-effort: GitHub forces GITHUB_TOKEN read-only on fork PR events, + # so this 403s unless a write-capable token is configured. continue-on-error + # keeps the job failing with the deliberate ::error annotation below rather + # than with a raw comment-permission failure. + - name: Comment on fork PR + if: steps.drift.outputs.changed == 'true' && github.event.pull_request.head.repo.fork == true + continue-on-error: true + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + COMMENT_BODY: >- + MCP catalog is stale and this PR comes from a fork, so CI cannot + commit it: download the `catalog.patch` artifact of + ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + and apply it, or run + `pnpm --filter web script src/scripts/mcp-catalog/dump.ts` locally + and push. + run: gh pr comment "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" --body "$COMMENT_BODY" + + - name: Fail fork PR with stale catalog + if: steps.drift.outputs.changed == 'true' && github.event.pull_request.head.repo.fork == true + run: | + echo "::error::services/kilo-mcp/catalog.json is stale and cannot be committed from a fork PR. Apply the catalog.patch artifact attached to this run, or run the dump locally and push." + exit 1 + + catalog-merge: + name: catalog + Vectorize (main) + # Main pushes only — a pull_request run can never reach this job, so no PR + # writes to Vectorize (requirement 10). + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + runs-on: ${{ vars.RUNNER_DEFAULT_LABEL || 'ubuntu-latest' }} + timeout-minutes: 20 + permissions: + contents: read + steps: + - uses: useblacksmith/checkout@41cdeedae8edb2e684ba22896a5fd2a3cb85db6b # v1 + + - name: Setup pnpm + uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v4.4.0 + + - name: Setup Node + uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 + with: + node-version-file: '.nvmrc' + cache: 'pnpm' + + - name: Install web dependencies + run: pnpm install --frozen-lockfile --filter web... + + - name: Setup dummy env + working-directory: apps/web + run: cp .env.test .env + + # Fill any summaries that slipped through before the index is updated + # (requirement 8); keep-edit semantics leave author edits alone. + - name: Regenerate catalog.json + env: + OPENROUTER_API_KEY: ${{ secrets.MCP_CATALOG_LLM_API_KEY }} + run: pnpm --filter web script src/scripts/mcp-catalog/dump.ts + + # Vectorize upsert (requirement 9). The index name and account id match + # the production bindings in services/kilo-mcp/wrangler.jsonc; the + # account id is not a secret (it is committed there). + - name: Upsert Vectorize index + run: node services/kilo-mcp/scripts/embed-catalog.ts upsert + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: e115e769bcdd4c3d66af59d3332cb394 + VECTORIZE_INDEX_NAME: kilo-mcp-catalog diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 7baf1ac50d..8fd6bcdbc8 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -9,5 +9,5 @@ "arrowParens": "avoid", "endOfLine": "lf", "sortPackageJson": false, - "ignorePatterns": [] + "ignorePatterns": ["services/kilo-mcp/catalog.json"] } diff --git a/apps/web/jest.config.ts b/apps/web/jest.config.ts index 680f62f670..81399a2cea 100644 --- a/apps/web/jest.config.ts +++ b/apps/web/jest.config.ts @@ -48,7 +48,9 @@ const config: Config = { '/../../services/kiloclaw/', '/../../packages/encryption/', '/../../packages/worker-utils/', - '/src/scripts/', + // Script tests are DB-backed and run via `pnpm script`, not jest — except + // the mcp-catalog unit tests, which only exercise pure library code. + '/src/scripts/(?!mcp-catalog/)', '/../../.worktrees/', ], modulePathIgnorePatterns: ['/../../.worktrees/'], diff --git a/apps/web/src/scripts/mcp-catalog/catalog.test.ts b/apps/web/src/scripts/mcp-catalog/catalog.test.ts new file mode 100644 index 0000000000..726387b0a8 --- /dev/null +++ b/apps/web/src/scripts/mcp-catalog/catalog.test.ts @@ -0,0 +1,402 @@ +/** + * Unit tests for the MCP catalog dump library (src/scripts/mcp-catalog). + * + * The enumeration test imports the real rootRouter: it asserts the walk + * yields leaves and that a known nested query path from the OpenAPI registry + * (apps/web/src/lib/openapi/trpc-registry.ts) is present, so a refactor that + * breaks router flattening fails here instead of shipping an empty catalog. + */ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { z } from 'zod'; +import { rootRouter } from '@/routers/root-router'; +import { + CATALOG_JSON_DISPLAY_PATH, + CATALOG_JSON_PATH, + DENYLISTED_TOP_LEVEL_SEGMENTS, + SUMMARY_INSTRUCTION, + buildCatalogJson, + buildCatalogRows, + collectCatalogLeaves, + generateMissingSummaries, + readCommittedSummaries, + type CatalogLeaf, +} from './catalog'; + +const queryLeaf = (path: string, firstInput?: CatalogLeaf['firstInput']): CatalogLeaf => ({ + path, + type: 'query', + firstInput, +}); + +describe('mcp-catalog catalog', () => { + describe('collectCatalogLeaves', () => { + it('yields leaves from the real rootRouter', () => { + const leaves = collectCatalogLeaves(rootRouter); + expect(leaves.length).toBeGreaterThan(0); + for (const leaf of leaves) { + expect(['query', 'mutation', 'subscription']).toContain(leaf.type); + } + }); + + it('contains the known nested usageAnalytics query path', () => { + const leaves = collectCatalogLeaves(rootRouter); + const summary = leaves.find(leaf => leaf.path === 'usageAnalytics.getSummary'); + expect(summary).toBeDefined(); + expect(summary?.type).toBe('query'); + }); + }); + + describe('buildCatalogRows', () => { + it('keeps only queries and drops denylisted top-level segments', () => { + const { rows, missing } = buildCatalogRows([ + queryLeaf('admin.users.list'), + queryLeaf('debug.ping'), + queryLeaf('test.echo'), + { path: 'user.deleteAccount', type: 'mutation', firstInput: undefined }, + { path: 'user.onEvent', type: 'subscription', firstInput: undefined }, + queryLeaf('user.getProfile'), + ]); + expect(rows.map(row => row.path)).toEqual([]); + expect(missing.map(leaf => leaf.path)).toEqual(['user.getProfile']); + }); + + it('locks the denylist constant to the internal-only segments', () => { + expect([...DENYLISTED_TOP_LEVEL_SEGMENTS].sort()).toEqual(['admin', 'debug', 'test']); + }); + + it('fails on a zero-query catalog instead of emitting an empty one', () => { + expect(() => buildCatalogRows([queryLeaf('admin.nothing')])).toThrow(/zero query rows/); + expect(() => buildCatalogRows([])).toThrow(/zero query rows/); + }); + + it('shapes rows with derived tags, input schema and search blob', () => { + const { rows } = buildCatalogRows( + [queryLeaf('user.getProfile', z.object({ userId: z.string() }))], + new Map([['user.getProfile', 'Returns the profile of a user.']]) + ); + const row = rows[0]; + expect(row).toEqual({ + path: 'user.getProfile', + kind: 'query', + summary: 'Returns the profile of a user.', + inputSchema: expect.objectContaining({ + type: 'object', + properties: { userId: { type: 'string' } }, + }), + tags: ['user', 'getprofile', 'userid'], + searchBlob: 'user.getProfile Returns the profile of a user. user getprofile userid userId', + }); + expect(row?.summary).toContain('profile'); + }); + + it('emits an empty input schema for procedures without input', () => { + const { rows } = buildCatalogRows( + [queryLeaf('user.listSessions')], + new Map([['user.listSessions', 'Lists active sessions.']]) + ); + expect(rows[0]?.inputSchema).toEqual({}); + }); + + it('keeps committed summaries byte-for-byte, including whitespace', () => { + const summary = ' Returns the user profile. '; + const { rows } = buildCatalogRows( + [queryLeaf('user.getProfile')], + new Map([['user.getProfile', summary]]) + ); + expect(rows[0]?.summary).toBe(summary); + }); + }); + + describe('CATALOG_JSON_DISPLAY_PATH', () => { + it('is the repo-relative catalog path, stable across checkouts', () => { + expect(CATALOG_JSON_DISPLAY_PATH).toBe('services/kilo-mcp/catalog.json'); + expect(CATALOG_JSON_PATH.endsWith(CATALOG_JSON_DISPLAY_PATH)).toBe(true); + }); + }); + + describe('buildCatalogJson', () => { + it('sorts rows by path and ends with a trailing newline', () => { + const { rows } = buildCatalogRows( + [queryLeaf('b.b'), queryLeaf('a.a')], + new Map([ + ['a.a', 'A'], + ['b.b', 'B'], + ]) + ); + const json = buildCatalogJson(rows); + expect(json.endsWith('\n')).toBe(true); + expect(json.indexOf('"a.a"')).toBeGreaterThan(-1); + expect(json.indexOf('"a.a"')).toBeLessThan(json.indexOf('"b.b"')); + expect(json).toBe(`${JSON.stringify({ 'a.a': rows[1], 'b.b': rows[0] }, null, 2)}\n`); + }); + }); + + describe('readCommittedSummaries', () => { + let tmpDir: string; + + beforeAll(() => { + tmpDir = mkdtempSync(join(tmpdir(), 'mcp-catalog-test-')); + }); + + afterAll(() => { + rmSync(tmpDir, { recursive: true, force: true }); + }); + + const writeCatalog = (name: string, content: string): string => { + const path = join(tmpDir, name); + writeFileSync(path, content); + return path; + }; + + it('returns an empty Map when the committed catalog does not exist (first generation)', () => { + const summaries = readCommittedSummaries(join(tmpDir, 'does-not-exist.json')); + expect(summaries).toBeInstanceOf(Map); + expect(summaries.size).toBe(0); + }); + + it('reads the summaries of a valid committed catalog, skipping empty ones', () => { + const path = writeCatalog( + 'valid.json', + JSON.stringify({ + 'user.getProfile': { summary: 'Returns the profile of a user.' }, + 'user.listSessions': { summary: '' }, + 'kiloChat.ping': {}, + }) + ); + expect([...readCommittedSummaries(path).entries()]).toEqual([ + ['user.getProfile', 'Returns the profile of a user.'], + ]); + }); + + it('throws naming the path when the committed catalog carries merge-conflict markers', () => { + const path = writeCatalog( + 'conflict.json', + '{\n "user.getProfile": {\n "summary": "edited by hand"\n }\n<<<<<<< HEAD\n}\n=======\n}\n>>>>>>> feature/x\n' + ); + expect(() => readCommittedSummaries(path)).toThrow(path); + // The throw must explain the harm: an empty Map here would read as + // "first generation" and silently regenerate every author edit. + expect(() => readCommittedSummaries(path)).toThrow(/not valid JSON/); + }); + + it('throws naming the path when the committed catalog is truncated JSON', () => { + const path = writeCatalog('truncated.json', '{"user.getProfile": {"summary": "Retu'); + expect(() => readCommittedSummaries(path)).toThrow(path); + }); + + it('throws naming the path when the committed catalog parses to a non-object', () => { + const path = writeCatalog('not-an-object.json', 'null\n'); + expect(() => readCommittedSummaries(path)).toThrow(path); + }); + + it('throws naming the path when the committed catalog exists but cannot be read', () => { + const dirPath = join(tmpDir, 'directory.json'); + mkdirSync(dirPath); + expect(() => readCommittedSummaries(dirPath)).toThrow(dirPath); + }); + }); + + describe('committed catalog regeneration', () => { + it('regenerates the committed catalog byte-for-byte with no missing summaries', () => { + const onDisk = readFileSync(CATALOG_JSON_PATH, 'utf8'); + const committed = readCommittedSummaries(); + expect(committed.size).toBeGreaterThan(0); + const { rows, missing } = buildCatalogRows(collectCatalogLeaves(rootRouter), committed); + expect(missing.map(leaf => leaf.path)).toEqual([]); + expect(buildCatalogJson(rows)).toBe(onDisk); + }); + }); + + describe('generateMissingSummaries', () => { + const ENV_KEYS = ['OPENROUTER_API_KEY', 'ANTHROPIC_API_KEY'] as const; + let savedEnv: Record; + + beforeEach(() => { + savedEnv = Object.fromEntries(ENV_KEYS.map(key => [key, process.env[key]])); + }); + + afterEach(() => { + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }); + + const failingFetch = jest.fn(async () => { + throw new Error('network must not be reached'); + }) as unknown as typeof fetch; + + it('resolves immediately when nothing is missing', async () => { + await expect(generateMissingSummaries([], failingFetch)).resolves.toEqual(new Map()); + expect(failingFetch).not.toHaveBeenCalled(); + }); + + it('fails without retry when no LLM key is configured', async () => { + delete process.env.OPENROUTER_API_KEY; + delete process.env.ANTHROPIC_API_KEY; + const attempt = generateMissingSummaries([queryLeaf('usageAnalytics.probe')], failingFetch); + await expect(attempt).rejects.toThrow(/OPENROUTER_API_KEY|ANTHROPIC_API_KEY/); + // Fork PRs never get the CI key, so the error must also name the + // credential-free self-service path (requirement 6's guidance). + await expect(attempt).rejects.toThrow( + /hand-write a summary for each new path in services\/kilo-mcp\/catalog\.json/ + ); + expect(failingFetch).not.toHaveBeenCalled(); + }); + + it('marks provider outages as retryable and names the failed batch', async () => { + process.env.OPENROUTER_API_KEY = 'test-key'; + delete process.env.ANTHROPIC_API_KEY; + const fetchImpl = jest.fn(async () => ({ + ok: false, + status: 503, + text: async () => 'upstream unavailable', + json: async () => ({}), + })) as unknown as typeof fetch; + + await expect( + generateMissingSummaries([queryLeaf('usageAnalytics.probe')], fetchImpl) + ).rejects.toMatchObject({ + retryable: true, + message: expect.stringMatching(/usage-analytics-router\.ts/), + }); + }); + + it('marks provider auth rejections as non-retryable', async () => { + process.env.OPENROUTER_API_KEY = 'test-key'; + delete process.env.ANTHROPIC_API_KEY; + const fetchImpl = jest.fn(async () => ({ + ok: false, + status: 401, + text: async () => 'invalid key', + json: async () => ({}), + })) as unknown as typeof fetch; + + await expect( + generateMissingSummaries([queryLeaf('usageAnalytics.probe')], fetchImpl) + ).rejects.toMatchObject({ + retryable: false, + }); + }); + + it('batches one request per router file and parses the summaries', async () => { + process.env.OPENROUTER_API_KEY = 'test-key'; + delete process.env.ANTHROPIC_API_KEY; + const calls: Array<{ url: string; body: Record }> = []; + const fetchImpl = jest.fn(async (url: unknown, init?: { body?: string }) => { + const body = JSON.parse(init?.body ?? '{}') as Record; + calls.push({ url: String(url), body }); + const content = + (body as { messages?: Array<{ content?: string }> }).messages?.[0]?.content ?? ''; + // Echo one summary per procedure the batch requested. + const out: Record = {}; + for (const match of content.matchAll(/^- ([A-Za-z0-9_.]+)$/gm)) + out[match[1]!] = `Summary for ${match[1]}.`; + return { + ok: true, + status: 200, + json: async () => ({ choices: [{ message: { content: JSON.stringify(out) } }] }), + }; + }) as unknown as typeof fetch; + + const summaries = await generateMissingSummaries( + [queryLeaf('usageAnalytics.probe'), queryLeaf('kiloChat.probe')], + fetchImpl + ); + expect(summaries.get('usageAnalytics.probe')).toBe('Summary for usageAnalytics.probe.'); + expect(summaries.get('kiloChat.probe')).toBe('Summary for kiloChat.probe.'); + expect(calls).toHaveLength(2); // one per router file, batched + const prompt = JSON.stringify(calls[0]?.body); + expect(prompt).toContain(SUMMARY_INSTRUCTION); + expect(prompt).toContain('usageAnalytics.probe'); + }); + + it('logs a progress line naming each router-file batch as it starts', async () => { + process.env.OPENROUTER_API_KEY = 'test-key'; + delete process.env.ANTHROPIC_API_KEY; + const events: string[] = []; + const fetchImpl = jest.fn(async (_url: unknown, init?: { body?: string }) => { + events.push('fetch'); + const body = JSON.parse(init?.body ?? '{}') as { + messages?: Array<{ content?: string }>; + }; + const out: Record = {}; + for (const match of (body.messages?.[0]?.content ?? '').matchAll(/^- ([A-Za-z0-9_.]+)$/gm)) + out[match[1]!] = `Summary for ${match[1]}.`; + return { + ok: true, + status: 200, + json: async () => ({ choices: [{ message: { content: JSON.stringify(out) } }] }), + }; + }) as unknown as typeof fetch; + + await generateMissingSummaries( + [queryLeaf('usageAnalytics.probe'), queryLeaf('kiloChat.probe')], + fetchImpl, + message => events.push(message) + ); + // Each batch is named (router file + count) before its request starts. + expect(events).toEqual([ + expect.stringContaining('usage-analytics-router.ts'), + 'fetch', + expect.stringContaining('kilo-chat-router.ts'), + 'fetch', + ]); + expect(events[0]).toContain('1/2'); + expect(events[0]).toContain('1 summary'); + expect(events[2]).toContain('2/2'); + }); + + it('rejects unusable LLM output as non-retryable', async () => { + process.env.OPENROUTER_API_KEY = 'test-key'; + delete process.env.ANTHROPIC_API_KEY; + const fetchImpl = jest.fn(async () => ({ + ok: true, + status: 200, + json: async () => ({ + choices: [{ message: { content: '{"some.other.path": "wrong key"}' } }], + }), + })) as unknown as typeof fetch; + + await expect( + generateMissingSummaries([queryLeaf('usageAnalytics.probe')], fetchImpl) + ).rejects.toMatchObject({ + retryable: false, + message: expect.stringContaining('usageAnalytics.probe'), + }); + }); + + it('extracts the enclosing handler source for a real procedure', async () => { + process.env.OPENROUTER_API_KEY = 'test-key'; + delete process.env.ANTHROPIC_API_KEY; + const bodies: string[] = []; + const fetchImpl = jest.fn(async (_url: unknown, init?: { body?: string }) => { + bodies.push(init?.body ?? ''); + return { + ok: true, + status: 200, + json: async () => ({ + choices: [ + { + message: { + content: JSON.stringify({ + 'usageAnalytics.getSummary': 'Returns aggregate usage KPI metrics.', + }), + }, + }, + ], + }), + }; + }) as unknown as typeof fetch; + + await generateMissingSummaries([queryLeaf('usageAnalytics.getSummary')], fetchImpl); + const parsed = JSON.parse(bodies[0] ?? '{}') as { messages: Array<{ content: string }> }; + const content = parsed.messages[0]?.content ?? ''; + // The extracted block should include the real handler, not just the path. + expect(content).toMatch(/getSummary/); + expect(content.length).toBeGreaterThan(200); + }); + }); +}); diff --git a/apps/web/src/scripts/mcp-catalog/catalog.ts b/apps/web/src/scripts/mcp-catalog/catalog.ts new file mode 100644 index 0000000000..5e397484ab --- /dev/null +++ b/apps/web/src/scripts/mcp-catalog/catalog.ts @@ -0,0 +1,703 @@ +/** + * Library for the Kilo MCP tRPC query catalog dump. + * + * Enumerates every procedure from the live `rootRouter` (never a hand-written + * list), shapes deterministic catalog rows, preserves author-edited summaries + * from the committed `services/kilo-mcp/catalog.json`, and generates missing + * summaries via an LLM (OpenRouter or Anthropic, plain fetch). Summaries are + * never generated at MCP runtime: the committed catalog is the only runtime + * artifact, and authors edit its summaries by hand. See dump.ts for the CLI + * entry point. + */ +import { readFileSync, statSync } from 'node:fs'; +import { basename, dirname, join, relative, resolve } from 'node:path'; +import { z } from 'zod'; + +/** Repository root: five levels above apps/web/src/scripts/mcp-catalog. */ +const REPO_ROOT = join(__dirname, '..', '..', '..', '..', '..'); + +/** Absolute path of the committed catalog consumed by services/kilo-mcp. */ +export const CATALOG_JSON_PATH = join(REPO_ROOT, 'services', 'kilo-mcp', 'catalog.json'); + +/** + * Repo-relative display form of the catalog path for CLI output. The absolute + * path leaks the machine-specific checkout directory into logs and CI + * comments and is long enough to be quoted only in abbreviated form; the + * repo-relative form is stable in every checkout and matches how docs and CI + * refer to the file. + */ +export const CATALOG_JSON_DISPLAY_PATH = relative(REPO_ROOT, CATALOG_JSON_PATH); + +/** Source of truth for the enumeration; imported dynamically by dump.ts. */ +export const ROOT_ROUTER_PATH = join(__dirname, '..', '..', 'routers', 'root-router.ts'); + +/** + * Top-level router segments that stay internal-only. This is a denylist: + * every other query procedure is exported, individual procedures cannot opt + * back in, and mutations are never exported. + */ +export const DENYLISTED_TOP_LEVEL_SEGMENTS = ['admin', 'debug', 'test'] as const; + +/** Instruction every generated summary must follow. */ +export const SUMMARY_INSTRUCTION = + 'Write a 1-2 sentence search-friendly summary of what this call does, in words an agent would type to find it. No implementation detail. Not a restatement of the path.'; + +const CONTEXT_CHAR_LIMIT = 4_000; +const FILE_CONTEXT_CHAR_LIMIT = 60_000; +const SUMMARY_COMPLETION_TOKENS = 8_192; +const OPENROUTER_CHAT_COMPLETIONS_URL = 'https://openrouter.ai/api/v1/chat/completions'; +const ANTHROPIC_MESSAGES_URL = 'https://api.anthropic.com/v1/messages'; +const OPENROUTER_MODEL = 'anthropic/claude-sonnet-4.5'; +const ANTHROPIC_MODEL = 'claude-sonnet-4-5'; + +export type CatalogLeaf = { + path: string; + type: string; + /** First Zod input schema of the procedure, or undefined when it takes none. */ + firstInput: unknown; +}; + +export type CatalogRow = { + path: string; + kind: 'query'; + summary: string; + inputSchema: Record; + tags: string[]; + searchBlob: string; +}; + +/** Failure while generating summaries. `retryable` failures name the failed batch. */ +export class CatalogSummaryError extends Error { + readonly retryable: boolean; + + constructor(message: string, options: { retryable: boolean }) { + super(message); + this.name = 'CatalogSummaryError'; + this.retryable = options.retryable; + } +} + +type LooseProcedure = { _def?: { type?: unknown; inputs?: unknown[] } }; + +/** + * Flattens a tRPC router into leaves. tRPC merges sub-routers into + * `_def.procedures` keyed by the full dotted path; each entry exposes + * `_def.type` ('query' | 'mutation' | 'subscription') and `_def.inputs`, the + * list of Zod schemas passed to `.input()` (empty when the procedure takes + * no input). + */ +export function collectCatalogLeaves(router: { _def?: unknown }): CatalogLeaf[] { + const procedures = (router?._def as { procedures?: unknown } | undefined)?.procedures; + if (!procedures || typeof procedures !== 'object') { + throw new Error('rootRouter exposed no procedures record — cannot enumerate the catalog'); + } + const leaves: CatalogLeaf[] = []; + for (const [path, entry] of Object.entries(procedures as Record)) { + const def = (entry as LooseProcedure | undefined)?._def; + if (!def) continue; + const inputs = Array.isArray(def.inputs) ? def.inputs : []; + leaves.push({ + path, + type: typeof def.type === 'string' ? def.type : '', + firstInput: inputs[0], + }); + } + if (leaves.length === 0) { + throw new Error('rootRouter exposed zero procedures — cannot enumerate the catalog'); + } + return leaves; +} + +function toInputSchema(firstInput: unknown): Record { + if (!firstInput) return {}; + // `io: 'input'` keeps the schema faithful for callers that build a request; + // `unrepresentable: 'any'` keeps rare schemas (z.any(), z.date(), …) from + // failing the whole dump. + return z.toJSONSchema(firstInput as z.ZodType, { + io: 'input', + unrepresentable: 'any', + }) as Record; +} + +function topSchemaKeys(inputSchema: Record): string[] { + const properties = inputSchema.properties; + return properties && typeof properties === 'object' && !Array.isArray(properties) + ? Object.keys(properties) + : []; +} + +/** + * Tags are derived only from the path segments plus the top-level input + * schema property keys: lowercased, deduped, never authored. + */ +function deriveTags(segments: string[], schemaKeys: string[]): string[] { + const tags: string[] = []; + for (const segment of [...segments, ...schemaKeys]) { + const tag = segment.toLowerCase(); + if (tag !== '' && !tags.includes(tag)) tags.push(tag); + } + return tags; +} + +function shapeRow(leaf: CatalogLeaf, summary: string): CatalogRow { + const segments = leaf.path.split('.'); + const inputSchema = toInputSchema(leaf.firstInput); + const schemaKeys = topSchemaKeys(inputSchema); + const tags = deriveTags(segments, schemaKeys); + return { + path: leaf.path, + kind: 'query', + summary, + inputSchema, + tags, + searchBlob: [leaf.path, summary, ...tags, ...schemaKeys].filter(Boolean).join(' '), + }; +} + +/** + * Filters the leaves down to the exported catalog: queries only, denylisted + * top-level segments dropped. Rows whose summary is provided keep it + * byte-for-byte; the rest come back as `missing` for LLM generation. + */ +export function buildCatalogRows( + leaves: CatalogLeaf[], + summaries: Map = new Map() +): { rows: CatalogRow[]; missing: CatalogLeaf[] } { + const denylisted = new Set(DENYLISTED_TOP_LEVEL_SEGMENTS); + const rows: CatalogRow[] = []; + const missing: CatalogLeaf[] = []; + for (const leaf of leaves) { + if (leaf.type !== 'query') continue; + if (denylisted.has(leaf.path.split('.')[0] ?? '')) continue; + const summary = summaries.get(leaf.path); + if (typeof summary === 'string' && summary !== '') { + rows.push(shapeRow(leaf, summary)); + } else { + missing.push(leaf); + } + } + if (rows.length === 0 && missing.length === 0) { + throw new Error( + 'Catalog enumeration produced zero query rows — refusing to emit an empty catalog' + ); + } + return { rows, missing }; +} + +/** + * Reads the committed catalog and returns its summaries keyed by path. + * Only a missing file (ENOENT) means "first generation": no committed + * summaries exist yet. A file that exists but cannot be read or parsed + * throws with the path — a merge conflict or a truncated write must fail + * the dump loudly, because treating it as first generation would + * regenerate every row via the LLM and silently overwrite all + * author-edited summaries (requirement 5's keep-edit rule). + */ +export function readCommittedSummaries( + catalogPath: string = CATALOG_JSON_PATH +): Map { + let raw: string; + try { + raw = readFileSync(catalogPath, 'utf8'); + } catch (error) { + if ((error as { code?: unknown }).code === 'ENOENT') return new Map(); + const reason = error instanceof Error ? error.message : String(error); + throw new Error( + `The committed MCP catalog at ${catalogPath} exists but cannot be read (${reason}). ` + + 'Fix or remove the file before regenerating — the dump refuses to continue, ' + + 'because reading it as "no committed summaries" would discard every author edit.' + ); + } + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + throw new Error( + `The committed MCP catalog at ${catalogPath} is not valid JSON (${reason}). ` + + 'Fix or remove the file before regenerating — the dump refuses to continue, ' + + 'because reading it as "no committed summaries" would discard every author edit.' + ); + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error( + `The committed MCP catalog at ${catalogPath} is not a JSON object keyed by procedure path. ` + + 'Fix or remove the file before regenerating — the dump refuses to continue, ' + + 'because reading it as "no committed summaries" would discard every author edit.' + ); + } + const summaries = new Map(); + for (const [path, row] of Object.entries(parsed as Record)) { + const summary = (row as { summary?: unknown } | null)?.summary; + if (typeof summary === 'string' && summary !== '') summaries.set(path, summary); + } + return summaries; +} + +/** + * Serializes the catalog deterministically: one object keyed by path, keys + * sorted, row fields in a stable order, 2-space indent, trailing newline. + */ +export function buildCatalogJson(rows: CatalogRow[]): string { + const sorted = [...rows].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); + const keyed: Record = {}; + for (const row of sorted) keyed[row.path] = row; + return `${JSON.stringify(keyed, null, 2)}\n`; +} + +// ── Static source extraction ──────────────────────────────────────────────── +// +// The LLM summarizer needs the enclosing handler source for each procedure. +// It is extracted statically: root-router.ts imports are mapped to router +// files, procedure keys are located in those files, and the value expression +// after the key is captured with a string/comment-aware bracket scanner. +// Anything that fails to resolve falls back to the whole router file. + +const SCRIPTS_DIR = join(__dirname, '..'); // apps/web/src/scripts +const SRC_DIR = join(SCRIPTS_DIR, '..'); // apps/web/src + +type RouterFileMap = Map; // top-level segment → absolute router file path + +function resolveImportSpecifier(specifier: string, fromDir: string): string | null { + const withoutQuery = specifier.split('?')[0] ?? specifier; + let candidate: string; + if (withoutQuery.startsWith('@/')) { + candidate = join(SRC_DIR, withoutQuery.slice(2)); + } else if (withoutQuery.startsWith('./') || withoutQuery.startsWith('../')) { + candidate = resolve(fromDir, withoutQuery); + } else { + return null; + } + for (const candidatePath of [candidate, `${candidate}.ts`, join(candidate, 'index.ts')]) { + try { + if (statSync(candidatePath).isFile()) return candidatePath; + } catch { + // try the next candidate + } + } + return null; +} + +function importedSymbols(source: string, fromDir: string): Map { + const symbols = new Map(); + const importRe = /import\s*\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g; + for (const match of source.matchAll(importRe)) { + const resolved = resolveImportSpecifier(match[2]?.trim() ?? '', fromDir); + if (!resolved) continue; + for (const piece of (match[1] ?? '').split(',')) { + const symbol = piece + .split(/\s+as\s+/) + .pop() + ?.trim(); + if (symbol) symbols.set(symbol, resolved); + } + } + return symbols; +} + +function skipString(source: string, start: number, quote: string): number { + let i = start + 1; + while (i < source.length) { + const char = source[i]; + if (char === '\\') { + i += 2; + continue; + } + if (char === quote) return i + 1; + i += 1; + } + return i; +} + +function skipTemplate(source: string, start: number): number { + let i = start + 1; + while (i < source.length) { + const char = source[i]; + if (char === '\\') { + i += 2; + continue; + } + if (char === '`') return i + 1; + if (char === '$' && source[i + 1] === '{') { + i += 2; + let depth = 1; + while (i < source.length && depth > 0) { + const inner = source[i]; + if (inner === '\\') { + i += 2; + continue; + } + if (inner === "'" || inner === '"') { + i = skipString(source, i, inner); + continue; + } + if (inner === '`') { + i = skipTemplate(source, i); + continue; + } + if (inner === '{') depth += 1; + else if (inner === '}') depth -= 1; + i += 1; + } + continue; + } + i += 1; + } + return i; +} + +/** + * Scans a value expression from `start` and returns the index just past its + * end: the first top-level `,`, the closing brace of the enclosing object + * literal, or the end of the source. Strings, template literals (including + * `${…}` nesting) and comments are skipped so braces inside them do not + * count. + */ +function findExpressionEnd(source: string, start: number): number { + let depth = 0; + let i = start; + while (i < source.length) { + const char = source[i]; + if (char === '/' && source[i + 1] === '/') { + const newline = source.indexOf('\n', i); + if (newline === -1) return source.length; + i = newline + 1; + continue; + } + if (char === '/' && source[i + 1] === '*') { + const close = source.indexOf('*/', i + 2); + i = close === -1 ? source.length : close + 2; + continue; + } + if (char === "'" || char === '"') { + i = skipString(source, i, char); + continue; + } + if (char === '`') { + i = skipTemplate(source, i); + continue; + } + if (char === '(' || char === '[' || char === '{') depth += 1; + else if (char === ')' || char === ']') depth -= 1; + else if (char === '}') { + if (depth === 0) return i; + depth -= 1; + } else if (char === ',' && depth === 0) return i; + i += 1; + } + return -1; +} + +function valueExpressionFrom(source: string, afterColon: number): string | null { + let start = afterColon; + while (start < source.length && /\s/.test(source[start] ?? '')) start += 1; + const end = findExpressionEnd(source, start); + if (end === -1) return null; + return source.slice(start, end).trim(); +} + +/** + * Finds the value expression for an object key. When the key exists several + * times, the first value that looks like a procedure (`.query(`/`.mutation(` + * or a `*Procedure` chain) wins. + */ +function extractValueAfterKey(source: string, key: string): string | null { + const keyRe = new RegExp(`(^|[,{;\\n])\\s*${escapeRegExp(key)}\\s*:`, 'g'); + let first: string | null = null; + for (const match of source.matchAll(keyRe)) { + const value = valueExpressionFrom(source, (match.index ?? 0) + match[0].length); + if (value === null || value === '') continue; + if (first === null) first = value; + if (/rocedure|\.query\(|\.mutation\(/.test(value)) return value; + } + return first; +} + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +/** Maps each top-level `createTRPCRouter` key of root-router.ts to its file. */ +export function extractTopLevelRouterFiles( + rootRouterPath: string = ROOT_ROUTER_PATH +): RouterFileMap { + const source = readFileSync(rootRouterPath, 'utf8'); + const symbols = importedSymbols(source, dirname(rootRouterPath)); + const bodyStart = source.indexOf('createTRPCRouter('); + if (bodyStart === -1) return new Map(); + const openBrace = source.indexOf('{', bodyStart); + const bodyEnd = findExpressionEnd(source, openBrace); + const body = bodyEnd === -1 ? source.slice(openBrace) : source.slice(openBrace, bodyEnd); + const files: RouterFileMap = new Map(); + const pairRe = /([A-Za-z0-9_$]+)\s*:\s*([A-Za-z0-9_$]+)/g; + for (const match of body.matchAll(pairRe)) { + const file = symbols.get(match[2] ?? ''); + if (file && !files.has(match[1] ?? '')) files.set(match[1] ?? '', file); + } + return files; +} + +/** + * Extracts the source of a procedure's value expression (the full + * `protectedProcedure…query(…)` chain) for a dotted procedure path, walking + * sub-router keys across files. Returns null when the walk cannot be resolved + * statically; callers then fall back to the whole router file. + */ +export function extractProcedureSource( + path: string, + topLevelFiles: RouterFileMap +): { file: string; source: string } | null { + const segments = path.split('.'); + const topFile = topLevelFiles.get(segments[0] ?? ''); + if (!topFile || segments.length < 2) return null; + let currentFile = topFile; + let source = readFileSync(currentFile, 'utf8'); + for (let depth = 1; depth < segments.length - 1; depth += 1) { + const value = extractValueAfterKey(source, segments[depth] ?? ''); + if (value === null) return null; + if (/^[A-Za-z0-9_$]+$/.test(value)) { + const imported = importedSymbols(source, dirname(currentFile)).get(value); + if (!imported) continue; // locally defined sub-router: stay in this file + currentFile = imported; + source = readFileSync(currentFile, 'utf8'); + continue; + } + if (value.startsWith('createTRPCRouter') || value.startsWith('{')) continue; + return null; + } + const block = extractValueAfterKey(source, segments[segments.length - 1] ?? ''); + if (!block) return null; + return { file: currentFile, source: block }; +} + +function capContext(text: string, limit: number): string { + return text.length <= limit ? text : `${text.slice(0, limit)}\n// … truncated`; +} + +// ── LLM summary generation ────────────────────────────────────────────────── + +type LlmProvider = { name: 'openrouter' | 'anthropic'; apiKey: string; model: string }; + +type SummaryBatch = { + file: string; + /** Name used in progress and failure messages. */ + label: string; + items: Array<{ path: string; source: string }>; + /** Whole router file, included once when any extraction in the batch failed. */ + wholeFile?: string; +}; + +function resolveLlmProvider(): LlmProvider | null { + const openrouterKey = process.env.OPENROUTER_API_KEY; + if (openrouterKey) return { name: 'openrouter', apiKey: openrouterKey, model: OPENROUTER_MODEL }; + const anthropicKey = process.env.ANTHROPIC_API_KEY; + if (anthropicKey) return { name: 'anthropic', apiKey: anthropicKey, model: ANTHROPIC_MODEL }; + return null; +} + +function buildSummaryBatch( + segment: string, + leaves: CatalogLeaf[], + topLevelFiles: RouterFileMap +): SummaryBatch { + const file = topLevelFiles.get(segment) ?? ROOT_ROUTER_PATH; + const items: SummaryBatch['items'] = []; + let needsWholeFile = false; + for (const leaf of leaves) { + const extracted = extractProcedureSource(leaf.path, topLevelFiles); + if (extracted) { + items.push({ path: leaf.path, source: capContext(extracted.source, CONTEXT_CHAR_LIMIT) }); + } else { + // Keep the leaf listed so the model knows the path exists in the file + // source below; the whole file is attached as its extraction context. + items.push({ path: leaf.path, source: '' }); + needsWholeFile = true; + } + } + const wholeFile = needsWholeFile + ? capContext(readFileSync(file, 'utf8'), FILE_CONTEXT_CHAR_LIMIT) + : undefined; + return { file, label: basename(file), items, wholeFile }; +} + +function buildSummaryPrompt(batch: SummaryBatch): string { + const lines = [ + "You are writing summaries for an MCP tool catalog built from a web app's tRPC query procedures.", + `For each procedure path below, ${SUMMARY_INSTRUCTION}`, + 'Respond with ONLY a JSON object mapping each procedure path to its summary string. Every listed path must appear exactly once.', + '', + `Source file: ${batch.file}`, + '', + 'Procedures to summarize:', + ]; + for (const item of batch.items) lines.push(`- ${item.path}`); + if (batch.wholeFile) { + lines.push('', 'Full file source (may be truncated):', '```ts', batch.wholeFile, '```'); + } + for (const item of batch.items) { + lines.push( + '', + `### ${item.path}`, + '```ts', + item.source || '(source not extracted; use the file source above)', + '```' + ); + } + return lines.join('\n'); +} + +async function requestSummaryCompletion( + provider: LlmProvider, + prompt: string, + batchLabel: string, + fetchImpl: typeof fetch +): Promise { + const isAnthropic = provider.name === 'anthropic'; + const headers: Record = isAnthropic + ? { + 'content-type': 'application/json', + 'x-api-key': provider.apiKey, + 'anthropic-version': '2023-06-01', + } + : { + 'content-type': 'application/json', + authorization: `Bearer ${provider.apiKey}`, + }; + const messages = [{ role: 'user', content: prompt }]; + const body = isAnthropic + ? { model: provider.model, max_tokens: SUMMARY_COMPLETION_TOKENS, temperature: 0, messages } + : { model: provider.model, max_tokens: SUMMARY_COMPLETION_TOKENS, temperature: 0, messages }; + + let response: Response; + try { + response = await fetchImpl( + isAnthropic ? ANTHROPIC_MESSAGES_URL : OPENROUTER_CHAT_COMPLETIONS_URL, + { + method: 'POST', + headers, + body: JSON.stringify(body), + } + ); + } catch (error) { + throw new CatalogSummaryError( + `LLM request for ${batchLabel} failed: ${error instanceof Error ? error.message : String(error)}`, + { retryable: true } + ); + } + if (!response.ok) { + const detail = (await response.text().catch(() => '')).slice(0, 300); + throw new CatalogSummaryError( + `Summary generation failed for ${batchLabel}: HTTP ${response.status}${detail ? ` — ${detail}` : ''}`, + // A rejected key will never succeed on retry; transient statuses might. + { retryable: response.status !== 401 && response.status !== 403 } + ); + } + const payload = (await response.json().catch(() => null)) as { + choices?: Array<{ message?: { content?: string } }>; + content?: Array<{ text?: string }>; + } | null; + if (!payload) { + throw new CatalogSummaryError(`LLM response for ${batchLabel} is not valid JSON`, { + retryable: true, + }); + } + const content = isAnthropic + ? (payload.content ?? []).map(part => part.text ?? '').join('') + : (payload.choices?.[0]?.message?.content ?? ''); + if (!content.trim()) { + throw new CatalogSummaryError(`LLM returned an empty completion for ${batchLabel}`, { + retryable: true, + }); + } + return content; +} + +function parseSummaries( + content: string, + requestedPaths: string[], + batchLabel: string +): Map { + const unfenced = content + .trim() + .replace(/^```(?:json)?\s*/i, '') + .replace(/```\s*$/i, '') + .trim(); + const start = unfenced.indexOf('{'); + const end = unfenced.lastIndexOf('}'); + const candidate = start !== -1 && end > start ? unfenced.slice(start, end + 1) : unfenced; + let parsed: unknown; + try { + parsed = JSON.parse(candidate); + } catch { + throw new CatalogSummaryError(`LLM response for ${batchLabel} is not valid JSON`, { + retryable: false, + }); + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new CatalogSummaryError(`LLM response for ${batchLabel} is not a JSON object`, { + retryable: false, + }); + } + const summaries = new Map(); + const missing: string[] = []; + for (const path of requestedPaths) { + const summary = (parsed as Record)[path]; + if (typeof summary === 'string' && summary.trim() !== '') summaries.set(path, summary); + else missing.push(path); + } + if (missing.length > 0) { + throw new CatalogSummaryError( + `LLM response for ${batchLabel} is missing usable summaries for: ${missing.join(', ')}`, + { retryable: false } + ); + } + return summaries; +} + +/** + * Generates summaries for the given leaves, one chat completion per router + * file with all of that file's missing summaries batched into it. Calls + * `log` with a progress line naming each router-file batch as it starts, so + * a long generation shows where it is instead of going silent. Throws + * `CatalogSummaryError` (with `retryable` set) when a batch fails. Never logs + * credentials. + */ +export async function generateMissingSummaries( + missing: CatalogLeaf[], + fetchImpl: typeof fetch = fetch, + log: (message: string) => void = () => {} +): Promise> { + if (missing.length === 0) return new Map(); + const provider = resolveLlmProvider(); + if (!provider) { + throw new CatalogSummaryError( + 'No LLM credentials configured: set OPENROUTER_API_KEY (or ANTHROPIC_API_KEY) so the missing summaries can be generated, or hand-write a summary for each new path in services/kilo-mcp/catalog.json — committed summaries are kept by the dump. Summaries are never generated at MCP runtime, and an incomplete catalog is never written.', + { retryable: false } + ); + } + const topLevelFiles = extractTopLevelRouterFiles(); + const bySegment = new Map(); + for (const leaf of missing) { + const segment = leaf.path.split('.')[0] ?? ''; + const group = bySegment.get(segment); + if (group) group.push(leaf); + else bySegment.set(segment, [leaf]); + } + const generated = new Map(); + const batches = [...bySegment.entries()]; + for (const [batchIndex, [segment, leaves]] of batches.entries()) { + const batch = buildSummaryBatch(segment, leaves, topLevelFiles); + log( + ` batch ${batchIndex + 1}/${batches.length} ${batch.label}: generating ${leaves.length} ${leaves.length === 1 ? 'summary' : 'summaries'}…` + ); + const prompt = buildSummaryPrompt(batch); + const content = await requestSummaryCompletion(provider, prompt, batch.label, fetchImpl); + const summaries = parseSummaries( + content, + leaves.map(leaf => leaf.path), + batch.label + ); + for (const [path, summary] of summaries) generated.set(path, summary); + } + return generated; +} diff --git a/apps/web/src/scripts/mcp-catalog/dump.ts b/apps/web/src/scripts/mcp-catalog/dump.ts new file mode 100644 index 0000000000..5709beafa5 --- /dev/null +++ b/apps/web/src/scripts/mcp-catalog/dump.ts @@ -0,0 +1,158 @@ +/** + * CLI entry point: dumps the tRPC query catalog to services/kilo-mcp/catalog.json. + * + * Usage (from apps/web): + * pnpm script src/scripts/mcp-catalog/dump.ts # write or regenerate + * pnpm script src/scripts/mcp-catalog/dump.ts -- --check # exit 0 iff regenerating is byte-identical + * pnpm script src/scripts/mcp-catalog/dump.ts -- --dry-run # print row counts only + * + * Summaries come from the committed catalog when present (authors edit them + * there; this script never clobbers them) and are generated via LLM for new + * procedures. Without LLM credentials and missing summaries the dump fails + * rather than writing an incomplete catalog. + */ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { config as loadEnvFile } from 'dotenv'; +import '../../lib/load-env'; +import { + CATALOG_JSON_DISPLAY_PATH, + CATALOG_JSON_PATH, + CatalogSummaryError, + buildCatalogJson, + buildCatalogRows, + collectCatalogLeaves, + generateMissingSummaries, + readCommittedSummaries, +} from './catalog'; + +// The dump imports the whole router graph, so it needs the app's import-time +// env. Jest solves the same need by layering .env.test in globalSetup; mirror +// that here without overriding .env / .env.local, so a real developer +// environment always wins and the dump runs in any checkout. +loadEnvFile({ path: join(__dirname, '..', '..', '..', '.env.test') }); + +// IS_SCRIPT mode (set by `pnpm script`) demands a dedicated script DB URL; +// the dump never touches the database, so a placeholder suffices when unset. +if (!process.env.POSTGRES_SCRIPT_URL) { + process.env.POSTGRES_SCRIPT_URL = 'postgres://catalog-dump.invalid:5432/catalog'; +} + +/** + * The dump only imports the router graph to enumerate it statically — it never + * calls the app, the database, or any worker. + */ + +function diffPaths( + before: string, + after: string +): { added: string[]; removed: string[]; changed: string[] } { + const parse = (json: string): Record => { + try { + const parsed = JSON.parse(json) as unknown; + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) + ? (parsed as Record) + : {}; + } catch { + return {}; + } + }; + const beforeRows = parse(before); + const afterRows = parse(after); + const added: string[] = []; + const removed: string[] = []; + const changed: string[] = []; + for (const [path, row] of Object.entries(afterRows)) { + if (!(path in beforeRows)) added.push(path); + else if (JSON.stringify(beforeRows[path]) !== JSON.stringify(row)) changed.push(path); + } + for (const path of Object.keys(beforeRows)) { + if (!(path in afterRows)) removed.push(path); + } + return { added, removed, changed }; +} + +async function main(): Promise { + const args = process.argv.slice(2); + const check = args.includes('--check'); + const dryRun = args.includes('--dry-run'); + if (check && dryRun) { + console.error('❌ --check and --dry-run are mutually exclusive'); + process.exit(1); + } + + const { rootRouter } = await import('@/routers/root-router'); + + const leaves = collectCatalogLeaves(rootRouter); + const committed = readCommittedSummaries(); + const { rows: committedRows, missing } = buildCatalogRows(leaves, committed); + let rows = committedRows; + + if (dryRun) { + console.log(`Catalog dry run for ${CATALOG_JSON_DISPLAY_PATH}`); + console.log(` procedures enumerated: ${leaves.length}`); + console.log(` catalog rows (queries): ${rows.length + missing.length}`); + console.log(` with committed summary: ${rows.length}`); + console.log(` missing summary (LLM): ${missing.length}`); + return; + } + + if (missing.length > 0) { + console.log(`🧠 Generating ${missing.length} missing summaries via LLM…`); + const generated = await generateMissingSummaries(missing, fetch, message => + console.log(message) + ); + // Rebuild from the full leaf set so every row carries its final summary. + ({ rows } = buildCatalogRows(leaves, new Map([...committed, ...generated]))); + } + + const json = buildCatalogJson(rows); + + if (check) { + if (!existsSync(CATALOG_JSON_PATH)) { + console.error( + `❌ ${CATALOG_JSON_DISPLAY_PATH} does not exist — run the dump without --check first` + ); + process.exit(1); + } + const onDisk = readFileSync(CATALOG_JSON_PATH, 'utf8'); + if (onDisk === json) { + console.log(`✅ ${CATALOG_JSON_DISPLAY_PATH} is up to date (${rows.length} rows)`); + return; + } + const { added, removed, changed } = diffPaths(onDisk, json); + console.error( + `❌ ${CATALOG_JSON_DISPLAY_PATH} is stale: regenerating produces a different file` + ); + if (added.length > 0) + console.error( + ` added paths: ${added.slice(0, 10).join(', ')}${added.length > 10 ? ` … (+${added.length - 10} more)` : ''}` + ); + if (removed.length > 0) + console.error( + ` removed paths: ${removed.slice(0, 10).join(', ')}${removed.length > 10 ? ` … (+${removed.length - 10} more)` : ''}` + ); + if (changed.length > 0) + console.error( + ` changed rows: ${changed.slice(0, 10).join(', ')}${changed.length > 10 ? ` … (+${changed.length - 10} more)` : ''}` + ); + process.exit(1); + } + + mkdirSync(dirname(CATALOG_JSON_PATH), { recursive: true }); + writeFileSync(CATALOG_JSON_PATH, json); + console.log(`✅ wrote ${CATALOG_JSON_DISPLAY_PATH} (${rows.length} query rows)`); +} + +main().catch((error: unknown) => { + if (error instanceof CatalogSummaryError && error.retryable) { + console.error(`⏳ ${error.message}`); + console.error(' This looks transient — retry the command once the provider is reachable.'); + } else if (error instanceof Error) { + console.error('❌', error.message); + if (error.stack) console.error(error.stack); + } else { + console.error('❌', error); + } + process.exit(1); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 75b258dcbd..76b6521407 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2688,6 +2688,40 @@ importers: specifier: 'catalog:' version: 4.127.1(@cloudflare/workers-types@4.20260605.1)(@types/node@24.12.4)(bufferutil@4.1.0)(utf-8-validate@6.0.6) + services/kilo-mcp: + dependencies: + ajv: + specifier: 8.20.0 + version: 8.20.0 + ajv-formats: + specifier: 3.0.1 + version: 3.0.1(ajv@8.20.0) + drizzle-orm: + specifier: 0.45.2 + version: 0.45.2(@cloudflare/workers-types@4.20260605.1)(@opentelemetry/api@1.9.1)(@types/pg@8.18.0)(@upstash/redis@1.38.0)(bun-types@1.3.14)(expo-sqlite@57.0.1(expo@57.0.15)(react-native@0.86.2(@types/react@19.2.14)(bufferutil@4.1.0)(react@19.2.6)(utf-8-validate@6.0.6))(react@19.2.6))(kysely@0.29.2)(pg@8.20.0) + devDependencies: + '@cloudflare/workers-types': + specifier: 'catalog:' + version: 4.20260605.1 + '@types/node': + specifier: 'catalog:' + version: 24.12.4 + '@typescript/native-preview': + specifier: 'catalog:' + version: 7.0.0-dev.20260514.1 + drizzle-kit: + specifier: 'catalog:' + version: 0.31.10 + typescript: + specifier: 'catalog:' + version: 5.9.3 + vitest: + specifier: 'catalog:' + version: 4.1.6(@opentelemetry/api@1.9.1)(@types/node@24.12.4)(@vitest/coverage-v8@4.1.6)(@vitest/ui@4.1.6)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@29.1.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.4) + wrangler: + specifier: 'catalog:' + version: 4.127.1(@cloudflare/workers-types@4.20260605.1)(@types/node@24.12.4)(bufferutil@4.1.0)(utf-8-validate@6.0.6) + services/kilo-ops: dependencies: '@cloudflare/containers': @@ -11002,6 +11036,11 @@ packages: ajv-formats@3.0.1: resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true ajv-keywords@3.5.2: resolution: {integrity: sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==} @@ -23888,7 +23927,7 @@ snapshots: dependencies: '@hono/node-server': 1.19.17(hono@4.12.34) ajv: 8.20.0 - ajv-formats: 3.0.1 + ajv-formats: 3.0.1(ajv@8.20.0) content-type: 1.0.5 cors: 2.8.6 cross-spawn: 7.0.6 @@ -23910,7 +23949,7 @@ snapshots: dependencies: '@hono/node-server': 2.0.10(hono@4.12.34) ajv: 8.20.0 - ajv-formats: 3.0.1 + ajv-formats: 3.0.1(ajv@8.20.0) content-type: 1.0.5 cors: 2.8.6 cross-spawn: 7.0.6 @@ -28720,8 +28759,8 @@ snapshots: dependencies: ajv: 8.20.0 - ajv-formats@3.0.1: - dependencies: + ajv-formats@3.0.1(ajv@8.20.0): + optionalDependencies: ajv: 8.20.0 ajv-keywords@3.5.2(ajv@6.14.0): diff --git a/scripts/kilo-mcp-catalog.test.mjs b/scripts/kilo-mcp-catalog.test.mjs new file mode 100644 index 0000000000..b01f285f78 --- /dev/null +++ b/scripts/kilo-mcp-catalog.test.mjs @@ -0,0 +1,303 @@ +import assert from 'node:assert/strict'; +import { existsSync, readFileSync } from 'node:fs'; +import test from 'node:test'; + +import { load } from 'js-yaml'; + +const workflowPath = '.github/workflows/kilo-mcp-catalog.yml'; +const testPath = 'scripts/kilo-mcp-catalog.test.mjs'; +const prJobName = 'catalog-pr'; +const mergeJobName = 'catalog-merge'; +const dumpCommand = 'pnpm --filter web script src/scripts/mcp-catalog/dump.ts'; +const embedCommand = 'node services/kilo-mcp/scripts/embed-catalog.ts upsert'; +const mergeGate = "github.event_name == 'push' && github.ref == 'refs/heads/main'"; +const forkCondition = 'github.event.pull_request.head.repo.fork == true'; +const sameRepoCondition = 'github.event.pull_request.head.repo.fork == false'; +const prPaths = ['apps/web/src/**', 'services/kilo-mcp/**', workflowPath, testPath]; + +function readWorkflow() { + return load(readFileSync(new URL(`../${workflowPath}`, import.meta.url), 'utf8')); +} + +function stepText(step) { + return `${step.run ?? ''} ${step.uses ?? ''} ${JSON.stringify(step.with ?? {})}`; +} + +function findStep(job, predicate, what) { + const step = job.steps.find(predicate); + assert.ok(step, `${job.name ?? 'job'}: ${what} must exist`); + return step; +} + +function validate(workflow) { + assert.deepEqual(Object.keys(workflow.jobs), [prJobName, mergeJobName], 'exactly two jobs'); + const pr = workflow.jobs[prJobName]; + const merge = workflow.jobs[mergeJobName]; + + // Triggers: PRs on the catalog's source paths; pushes on main only. + assert.equal(pr.if, "github.event_name == 'pull_request'", `${prJobName}: PR-event only`); + assert.equal(merge.if, mergeGate, `${mergeJobName}: gated to main pushes only (requirement 10)`); + assert.deepEqual( + workflow.on.pull_request.paths, + prPaths, + 'pull_request admits the catalog paths' + ); + assert.deepEqual(workflow.on.push.branches, ['main'], 'push stays main-only'); + + // The PR job runs the real dump script with the LLM key so missing + // summaries get filled (requirement 2), and keeps author edits through the + // dump's own keep-edit rule (requirement 5). + const prDump = findStep(pr, step => step.run === dumpCommand, 'PR job runs the real dump script'); + assert.equal( + prDump.env?.OPENROUTER_API_KEY, + '${{ secrets.MCP_CATALOG_LLM_API_KEY }}', + 'PR dump exports the LLM key from the repo secret' + ); + + // Fork PRs never receive the LLM secret (GitHub withholds secrets from fork + // pull_request events), so a fork that adds a query cannot run the dump at + // all. Requirement 6 must still fire: the dump is continue-on-error on + // forks only, and a fork-conditioned follow-up step posts the self-service + // guidance and fails the job before drift detection could silently pass. + assert.equal(prDump.id, 'dump', 'PR dump exposes its outcome to later steps'); + assert.equal( + prDump['continue-on-error'], + '${{ github.event.pull_request.head.repo.fork == true }}', + 'PR dump tolerates failure only on fork PRs' + ); + const dumpGuidance = findStep( + pr, + step => + (step.if ?? '').includes("steps.dump.outcome == 'failure'") && + (step.if ?? '').includes(forkCondition), + 'fork dump-failure guidance step' + ); + assert.match(dumpGuidance.run ?? '', /gh pr comment/, 'guidance posts a PR comment'); + assert.match(dumpGuidance.run ?? '', /exit 1/, 'guidance fails the job'); + assert.match( + dumpGuidance.env?.COMMENT_BODY ?? '', + /hand-write a summary[\s\S]*services\/kilo-mcp\/catalog\.json/, + 'guidance names the self-service path in the committed catalog' + ); + const drift = findStep(pr, step => step.id === 'drift', 'drift detection step'); + assert.ok( + pr.steps.indexOf(dumpGuidance) < pr.steps.indexOf(drift), + 'dump-failure guidance must run before drift detection, or a failed fork dump could pass silently' + ); + + // PR jobs never touch Vectorize or the embed script (requirement 10). + for (const step of pr.steps) { + assert.doesNotMatch( + stepText(step), + /embed-catalog|catalog:embed|vectorize|CLOUDFLARE/i, + `${prJobName}: no PR-triggered step may reference the embed script or Vectorize` + ); + } + + // Same-repo drift is committed back under the bot identity, catalog.json + // only (requirement 5). + const commit = findStep( + pr, + step => (step.if ?? '').includes(sameRepoCondition), + 'same-repo commit step' + ); + assert.match(commit.run, /git add services\/kilo-mcp\/catalog\.json/, 'commit only catalog.json'); + assert.match(commit.run, /github-actions\[bot\]/, 'bot identity on the commit'); + assert.match(commit.run, /git push/, 'the commit is pushed to the PR branch'); + + // Fork drift: patch artifact + one-line PR comment + non-zero exit + // (requirement 6). + const patch = findStep( + pr, + step => (step.if ?? '').includes(forkCondition) && /git diff/.test(step.run ?? ''), + 'fork catalog.patch export step' + ); + assert.match(patch.run, /catalog\.patch/, 'diff is written to catalog.patch'); + const artifact = findStep( + pr, + step => (step.uses ?? '').startsWith('actions/upload-artifact@'), + 'fork patch artifact upload' + ); + assert.equal(artifact.with.name, 'catalog.patch', 'artifact carries the patch'); + const comment = findStep( + pr, + step => + (step.if ?? '').includes('steps.drift.outputs.changed') && + /gh pr comment/.test(step.run ?? ''), + 'fork PR comment step' + ); + assert.match(comment.env.COMMENT_BODY, /catalog\.patch/, 'comment points at the patch'); + assert.match( + comment.env.COMMENT_BODY, + new RegExp(dumpCommand.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), + 'comment gives the run command' + ); + const fail = findStep( + pr, + step => + (step.if ?? '').includes('steps.drift.outputs.changed') && /exit 1/.test(step.run ?? ''), + 'fork job must fail' + ); + assert.ok(fail, 'fork drift exits non-zero'); + + // Merge job: dump fills stragglers (requirement 8), then the embed script + // upserts Vectorize with the Cloudflare credentials (requirement 9). + const mergeDump = findStep(merge, step => step.run === dumpCommand, 'merge job runs the dump'); + assert.equal( + mergeDump.env?.OPENROUTER_API_KEY, + '${{ secrets.MCP_CATALOG_LLM_API_KEY }}', + 'merge dump exports the LLM key' + ); + const upsert = findStep(merge, step => step.run === embedCommand, 'merge job upserts Vectorize'); + assert.equal( + upsert.env?.CLOUDFLARE_API_TOKEN, + '${{ secrets.CLOUDFLARE_API_TOKEN }}', + 'upsert uses the Cloudflare API token secret' + ); + assert.ok(upsert.env?.CLOUDFLARE_ACCOUNT_ID, 'upsert gets the Cloudflare account id'); + assert.equal( + upsert.env.VECTORIZE_INDEX_NAME, + 'kilo-mcp-catalog', + 'upsert targets the prod index' + ); +} + +test('workflow file exists', () => { + assert.ok( + existsSync(new URL(`../${workflowPath}`, import.meta.url)), + `${workflowPath} must exist` + ); +}); + +test('catalog workflow wiring is valid', () => { + validate(readWorkflow()); +}); + +for (const [name, defect] of [ + [ + 'dump step removed', + workflow => dropStep(workflow, prJobName, step => step.run === dumpCommand), + ], + [ + 'embed script referenced from a PR step', + workflow => addStep(workflow, prJobName, { run: embedCommand }), + ], + [ + 'Vectorize referenced from a PR step', + workflow => addStep(workflow, prJobName, { run: 'echo VECTORIZE' }), + ], + ['merge job ungated', workflow => (workflow.jobs[mergeJobName].if = undefined)], + [ + 'merge job opened to pull_request', + workflow => (workflow.jobs[mergeJobName].if = "github.event_name == 'pull_request'"), + ], + [ + 'fork patch artifact removed', + workflow => + dropStep(workflow, prJobName, step => + (step.uses ?? '').startsWith('actions/upload-artifact@') + ), + ], + [ + 'fork comment removed', + workflow => + dropStep( + workflow, + prJobName, + step => + (step.if ?? '').includes('steps.drift.outputs.changed') && + /gh pr comment/.test(step.run ?? '') + ), + ], + [ + 'fork failure removed', + workflow => + dropStep( + workflow, + prJobName, + step => + (step.if ?? '').includes('steps.drift.outputs.changed') && /exit 1/.test(step.run ?? '') + ), + ], + [ + 'fork dump-failure guidance removed', + workflow => + dropStep(workflow, prJobName, step => + (step.if ?? '').includes("steps.dump.outcome == 'failure'") + ), + ], + [ + 'fork dump-failure guidance not fatal', + workflow => { + const step = workflow.jobs[prJobName].steps.find(item => + (item.if ?? '').includes("steps.dump.outcome == 'failure'") + ); + step.run = step.run.replace(/exit 1/, 'exit 0'); + }, + ], + [ + 'fork dump-failure guidance missing the self-service path', + workflow => { + const step = workflow.jobs[prJobName].steps.find(item => + (item.if ?? '').includes("steps.dump.outcome == 'failure'") + ); + step.env.COMMENT_BODY = 'The catalog dump failed on this fork PR.'; + }, + ], + [ + 'fork dump-failure guidance runs after drift detection', + workflow => { + const steps = workflow.jobs[prJobName].steps; + const guidance = steps.find(step => + (step.if ?? '').includes("steps.dump.outcome == 'failure'") + ); + const driftIndex = steps.findIndex(step => step.id === 'drift'); + steps.splice(steps.indexOf(guidance), 1); + steps.splice(driftIndex + 1, 0, guidance); + }, + ], + [ + 'dump step fatal on forks too', + workflow => { + const step = workflow.jobs[prJobName].steps.find(item => item.run === dumpCommand); + delete step['continue-on-error']; + }, + ], + [ + 'dump step outcome not exposed', + workflow => { + const step = workflow.jobs[prJobName].steps.find(item => item.run === dumpCommand); + delete step.id; + }, + ], + [ + 'bot identity stripped from the commit', + workflow => { + const step = workflow.jobs[prJobName].steps.find(item => + (item.if ?? '').includes(sameRepoCondition) + ); + step.run = step.run.replace(/github-actions\[bot\]/g, 'someone'); + }, + ], + [ + 'merge upsert removed', + workflow => dropStep(workflow, mergeJobName, step => step.run === embedCommand), + ], +]) { + test(`wiring check rejects: ${name}`, () => { + const workflow = readWorkflow(); + defect(workflow); + assert.throws(() => validate(workflow), assert.AssertionError); + }); +} + +function dropStep(workflow, jobName, predicate) { + const job = workflow.jobs[jobName]; + const index = job.steps.findIndex(predicate); + assert.ok(index >= 0, `mutation target exists in ${jobName}`); + job.steps.splice(index, 1); +} + +function addStep(workflow, jobName, step) { + workflow.jobs[jobName].steps.push(step); +} diff --git a/services/kilo-mcp/catalog.json b/services/kilo-mcp/catalog.json new file mode 100644 index 0000000000..6da4af8c7f --- /dev/null +++ b/services/kilo-mcp/catalog.json @@ -0,0 +1,10242 @@ +{ + "activeSessions.getToken": { + "path": "activeSessions.getToken", + "kind": "query", + "summary": "Get a short-lived authentication ticket/token for the current user to use with the web session.", + "inputSchema": {}, + "tags": [ + "activesessions", + "gettoken" + ], + "searchBlob": "activeSessions.getToken Get a short-lived authentication ticket/token for the current user to use with the web session. activesessions gettoken" + }, + "activeSessions.list": { + "path": "activeSessions.list", + "kind": "query", + "summary": "List the user's currently active sessions, optionally scoped to a specific organization and optionally including cloud agent sessions.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + }, + "includeCloudAgentSessions": { + "type": "boolean" + } + } + }, + "tags": [ + "activesessions", + "list", + "organizationid", + "includecloudagentsessions" + ], + "searchBlob": "activeSessions.list List the user's currently active sessions, optionally scoped to a specific organization and optionally including cloud agent sessions. activesessions list organizationid includecloudagentsessions organizationId includeCloudAgentSessions" + }, + "activeSessions.listInstances": { + "path": "activeSessions.listInstances", + "kind": "query", + "summary": "List the currently active/connected agent instances or devices from the session ingest worker.", + "inputSchema": {}, + "tags": [ + "activesessions", + "listinstances" + ], + "searchBlob": "activeSessions.listInstances List the currently active/connected agent instances or devices from the session ingest worker. activesessions listinstances" + }, + "agentProfiles.get": { + "path": "agentProfiles.get", + "kind": "query", + "summary": "Fetch a single agent profile's full details by ID, scoped to the current user or an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "profileId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "profileId" + ] + }, + "tags": [ + "agentprofiles", + "get", + "profileid", + "organizationid" + ], + "searchBlob": "agentProfiles.get Fetch a single agent profile's full details by ID, scoped to the current user or an organization. agentprofiles get profileid organizationid profileId organizationId" + }, + "agentProfiles.list": { + "path": "agentProfiles.list", + "kind": "query", + "summary": "List agent profiles owned by the current user or a given organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "agentprofiles", + "list", + "organizationid" + ], + "searchBlob": "agentProfiles.list List agent profiles owned by the current user or a given organization. agentprofiles list organizationid organizationId" + }, + "agentProfiles.listCombined": { + "path": "agentProfiles.listCombined", + "kind": "query", + "summary": "Get both an organization's agent profiles and the user's personal profiles in one call, including which profile is the active default.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "agentprofiles", + "listcombined", + "organizationid" + ], + "searchBlob": "agentProfiles.listCombined Get both an organization's agent profiles and the user's personal profiles in one call, including which profile is the active default. agentprofiles listcombined organizationid organizationId" + }, + "agentProfiles.listRepoBindings": { + "path": "agentProfiles.listRepoBindings", + "kind": "query", + "summary": "List repository bindings that associate repos with agent profiles for the current user or an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "agentprofiles", + "listrepobindings", + "organizationid" + ], + "searchBlob": "agentProfiles.listRepoBindings List repository bindings that associate repos with agent profiles for the current user or an organization. agentprofiles listrepobindings organizationid organizationId" + }, + "appBuilder.canMigrateToGitHub": { + "path": "appBuilder.canMigrateToGitHub", + "kind": "query", + "summary": "Check whether an app builder project can be migrated or exported to a GitHub repository.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "projectId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "projectId" + ] + }, + "tags": [ + "appbuilder", + "canmigratetogithub", + "projectid" + ], + "searchBlob": "appBuilder.canMigrateToGitHub Check whether an app builder project can be migrated or exported to a GitHub repository. appbuilder canmigratetogithub projectid projectId" + }, + "appBuilder.checkEligibility": { + "path": "appBuilder.checkEligibility", + "kind": "query", + "summary": "Check whether the current user's account balance is sufficient to use the app builder feature.", + "inputSchema": {}, + "tags": [ + "appbuilder", + "checkeligibility" + ], + "searchBlob": "appBuilder.checkEligibility Check whether the current user's account balance is sufficient to use the app builder feature. appbuilder checkeligibility" + }, + "appBuilder.getLegacySessionMessages": { + "path": "appBuilder.getLegacySessionMessages", + "kind": "query", + "summary": "Retrieve the chat or session messages associated with an app builder project and a cloud agent session.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "projectId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "cloudAgentSessionId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "projectId", + "cloudAgentSessionId" + ] + }, + "tags": [ + "appbuilder", + "getlegacysessionmessages", + "projectid", + "cloudagentsessionid" + ], + "searchBlob": "appBuilder.getLegacySessionMessages Retrieve the chat or session messages associated with an app builder project and a cloud agent session. appbuilder getlegacysessionmessages projectid cloudagentsessionid projectId cloudAgentSessionId" + }, + "appBuilder.getPreviewUrl": { + "path": "appBuilder.getPreviewUrl", + "kind": "query", + "summary": "Get the preview URL for an app builder project so it can be opened or embedded in a browser.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "projectId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "projectId" + ] + }, + "tags": [ + "appbuilder", + "getpreviewurl", + "projectid" + ], + "searchBlob": "appBuilder.getPreviewUrl Get the preview URL for an app builder project so it can be opened or embedded in a browser. appbuilder getpreviewurl projectid projectId" + }, + "appBuilder.getProject": { + "path": "appBuilder.getProject", + "kind": "query", + "summary": "Fetch a full app builder project by ID, including its configuration and data, authenticated for the current user.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "projectId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "projectId" + ] + }, + "tags": [ + "appbuilder", + "getproject", + "projectid" + ], + "searchBlob": "appBuilder.getProject Fetch a full app builder project by ID, including its configuration and data, authenticated for the current user. appbuilder getproject projectid projectId" + }, + "appBuilder.listProjects": { + "path": "appBuilder.listProjects", + "kind": "query", + "summary": "List all app builder projects owned by the current user.", + "inputSchema": {}, + "tags": [ + "appbuilder", + "listprojects" + ], + "searchBlob": "appBuilder.listProjects List all app builder projects owned by the current user. appbuilder listprojects" + }, + "autoFix.getConfig": { + "path": "autoFix.getConfig", + "kind": "query", + "summary": "Get the auto-fix configuration for an organization, including whether auto-fix is enabled and its current settings.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "autofix", + "getconfig", + "organizationid" + ], + "searchBlob": "autoFix.getConfig Get the auto-fix configuration for an organization, including whether auto-fix is enabled and its current settings. autofix getconfig organizationid organizationId" + }, + "autoFix.getTicket": { + "path": "autoFix.getTicket", + "kind": "query", + "summary": "Fetch a single auto-fix ticket by its ID, with authorization checks for organization members or personal ownership.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "ticketId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "ticketId" + ] + }, + "tags": [ + "autofix", + "getticket", + "ticketid" + ], + "searchBlob": "autoFix.getTicket Fetch a single auto-fix ticket by its ID, with authorization checks for organization members or personal ownership. autofix getticket ticketid ticketId" + }, + "autoFix.listTicketsForOrganization": { + "path": "autoFix.listTicketsForOrganization", + "kind": "query", + "summary": "List auto-fix tickets for an organization, with optional filtering by status, classification, or repository, plus pagination.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "autofix", + "listticketsfororganization", + "organizationid" + ], + "searchBlob": "autoFix.listTicketsForOrganization List auto-fix tickets for an organization, with optional filtering by status, classification, or repository, plus pagination. autofix listticketsfororganization organizationid organizationId" + }, + "autoFix.listTicketsForUser": { + "path": "autoFix.listTicketsForUser", + "kind": "query", + "summary": "List a user's own auto-fix tickets, with optional filtering by status, classification, or repository, plus pagination.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "limit": { + "default": 20, + "type": "integer", + "minimum": 1, + "maximum": 100 + }, + "offset": { + "default": 0, + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "pending", + "running", + "completed", + "failed", + "cancelled" + ] + }, + "classification": { + "type": "string", + "enum": [ + "bug", + "feature", + "question", + "unclear" + ] + }, + "repoFullName": { + "type": "string" + } + } + }, + "tags": [ + "autofix", + "listticketsforuser", + "limit", + "offset", + "status", + "classification", + "repofullname" + ], + "searchBlob": "autoFix.listTicketsForUser List a user's own auto-fix tickets, with optional filtering by status, classification, or repository, plus pagination. autofix listticketsforuser limit offset status classification repofullname limit offset status classification repoFullName" + }, + "autoTriage.getConfig": { + "path": "autoTriage.getConfig", + "kind": "query", + "summary": "Get the organization's auto-triage agent configuration, returning defaults and an isEnabled flag when no saved config exists.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "autotriage", + "getconfig", + "organizationid" + ], + "searchBlob": "autoTriage.getConfig Get the organization's auto-triage agent configuration, returning defaults and an isEnabled flag when no saved config exists. autotriage getconfig organizationid organizationId" + }, + "autoTriage.getTicket": { + "path": "autoTriage.getTicket", + "kind": "query", + "summary": "Fetch a single auto-triage ticket by ID, verifying that the caller is an organization member or the personal ticket owner.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "ticketId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "ticketId" + ] + }, + "tags": [ + "autotriage", + "getticket", + "ticketid" + ], + "searchBlob": "autoTriage.getTicket Fetch a single auto-triage ticket by ID, verifying that the caller is an organization member or the personal ticket owner. autotriage getticket ticketid ticketId" + }, + "autoTriage.listTicketsForOrganization": { + "path": "autoTriage.listTicketsForOrganization", + "kind": "query", + "summary": "List auto-triage tickets for an organization, with pagination, status, classification, and repository filters, including total count and whether more results exist.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "autotriage", + "listticketsfororganization", + "organizationid" + ], + "searchBlob": "autoTriage.listTicketsForOrganization List auto-triage tickets for an organization, with pagination, status, classification, and repository filters, including total count and whether more results exist. autotriage listticketsfororganization organizationid organizationId" + }, + "autoTriage.listTicketsForUser": { + "path": "autoTriage.listTicketsForUser", + "kind": "query", + "summary": "List a user's own auto-triage tickets with pagination, status, classification, and repository filters, including total count and has-more flag.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "limit": { + "default": 50, + "type": "integer", + "minimum": 1, + "maximum": 100 + }, + "offset": { + "default": 0, + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "pending", + "analyzing", + "actioned", + "failed", + "skipped" + ] + }, + "classification": { + "type": "string", + "enum": [ + "bug", + "feature", + "question", + "duplicate", + "unclear" + ] + }, + "repoFullName": { + "type": "string" + } + } + }, + "tags": [ + "autotriage", + "listticketsforuser", + "limit", + "offset", + "status", + "classification", + "repofullname" + ], + "searchBlob": "autoTriage.listTicketsForUser List a user's own auto-triage tickets with pagination, status, classification, and repository filters, including total count and has-more flag. autotriage listticketsforuser limit offset status classification repofullname limit offset status classification repoFullName" + }, + "byok.list": { + "path": "byok.list", + "kind": "query", + "summary": "List all saved bring-your-own-key (BYOK) API keys for the current user or a specified organization, including provider, enabled status, and management source.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "byok", + "list", + "organizationid" + ], + "searchBlob": "byok.list List all saved bring-your-own-key (BYOK) API keys for the current user or a specified organization, including provider, enabled status, and management source. byok list organizationid organizationId" + }, + "byok.listSupportedModels": { + "path": "byok.listSupportedModels", + "kind": "query", + "summary": "Get the list of supported models per provider for bring-your-own-key (BYOK) usage, showing which model IDs each provider offers.", + "inputSchema": {}, + "tags": [ + "byok", + "listsupportedmodels" + ], + "searchBlob": "byok.listSupportedModels Get the list of supported models per provider for bring-your-own-key (BYOK) usage, showing which model IDs each provider offers. byok listsupportedmodels" + }, + "cliSessions.get": { + "path": "cliSessions.get", + "kind": "query", + "summary": "Fetch a single CLI session record by session id, optionally including URLs to session blob data like messages or git state.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "session_id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "include_blob_urls": { + "default": false, + "type": "boolean" + } + }, + "required": [ + "session_id" + ] + }, + "tags": [ + "clisessions", + "get", + "session_id", + "include_blob_urls" + ], + "searchBlob": "cliSessions.get Fetch a single CLI session record by session id, optionally including URLs to session blob data like messages or git state. clisessions get session_id include_blob_urls session_id include_blob_urls" + }, + "cliSessions.getByCloudAgentSessionId": { + "path": "cliSessions.getByCloudAgentSessionId", + "kind": "query", + "summary": "Look up a CLI/kilo session record by the cloud-agent session id it is associated with.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cloud_agent_session_id": { + "type": "string", + "minLength": 1, + "maxLength": 255 + } + }, + "required": [ + "cloud_agent_session_id" + ] + }, + "tags": [ + "clisessions", + "getbycloudagentsessionid", + "cloud_agent_session_id" + ], + "searchBlob": "cliSessions.getByCloudAgentSessionId Look up a CLI/kilo session record by the cloud-agent session id it is associated with. clisessions getbycloudagentsessionid cloud_agent_session_id cloud_agent_session_id" + }, + "cliSessions.getSessionApiConversationHistory": { + "path": "cliSessions.getSessionApiConversationHistory", + "kind": "query", + "summary": "Return the recorded API conversation history for a CLI session, reading it from the session's blob storage.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "session_id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "session_id" + ] + }, + "tags": [ + "clisessions", + "getsessionapiconversationhistory", + "session_id" + ], + "searchBlob": "cliSessions.getSessionApiConversationHistory Return the recorded API conversation history for a CLI session, reading it from the session's blob storage. clisessions getsessionapiconversationhistory session_id session_id" + }, + "cliSessions.getSessionGitState": { + "path": "cliSessions.getSessionGitState", + "kind": "query", + "summary": "Fetch the captured git state (branches, diffs, status) for a given CLI session from its stored blob.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "session_id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "session_id" + ] + }, + "tags": [ + "clisessions", + "getsessiongitstate", + "session_id" + ], + "searchBlob": "cliSessions.getSessionGitState Fetch the captured git state (branches, diffs, status) for a given CLI session from its stored blob. clisessions getsessiongitstate session_id session_id" + }, + "cliSessions.getSessionMessages": { + "path": "cliSessions.getSessionMessages", + "kind": "query", + "summary": "Retrieve the chat messages for a given CLI session, loading them from the session's stored blob content.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "session_id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "session_id" + ] + }, + "tags": [ + "clisessions", + "getsessionmessages", + "session_id" + ], + "searchBlob": "cliSessions.getSessionMessages Retrieve the chat messages for a given CLI session, loading them from the session's stored blob content. clisessions getsessionmessages session_id session_id" + }, + "cliSessions.list": { + "path": "cliSessions.list", + "kind": "query", + "summary": "List a user's CLI/kilo sessions with pagination, filtering by creation platform or organization, and sorting by created or updated date.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cursor": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "limit": { + "default": 10, + "type": "number", + "minimum": 1, + "maximum": 50 + }, + "createdOnPlatform": { + "anyOf": [ + { + "type": "string" + }, + { + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "orderBy": { + "default": "updated_at", + "type": "string", + "enum": [ + "created_at", + "updated_at" + ] + }, + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + } + } + }, + "tags": [ + "clisessions", + "list", + "cursor", + "limit", + "createdonplatform", + "orderby", + "organizationid" + ], + "searchBlob": "cliSessions.list List a user's CLI/kilo sessions with pagination, filtering by creation platform or organization, and sorting by created or updated date. clisessions list cursor limit createdonplatform orderby organizationid cursor limit createdOnPlatform orderBy organizationId" + }, + "cliSessions.search": { + "path": "cliSessions.search", + "kind": "query", + "summary": "Search a user's CLI sessions by title or session id with full-text style matching, pagination, and total result count.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "search_string": { + "type": "string", + "minLength": 1 + }, + "limit": { + "default": 10, + "type": "number", + "minimum": 1, + "maximum": 50 + }, + "offset": { + "default": 0, + "type": "number", + "minimum": 0 + }, + "createdOnPlatform": { + "anyOf": [ + { + "type": "string" + }, + { + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "search_string" + ] + }, + "tags": [ + "clisessions", + "search", + "search_string", + "limit", + "offset", + "createdonplatform", + "organizationid" + ], + "searchBlob": "cliSessions.search Search a user's CLI sessions by title or session id with full-text style matching, pagination, and total result count. clisessions search search_string limit offset createdonplatform organizationid search_string limit offset createdOnPlatform organizationId" + }, + "cliSessionsV2.get": { + "path": "cliSessionsV2.get", + "kind": "query", + "summary": "Fetch a single CLI session record by its session ID, checking ownership and organization access.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "session_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "session_id" + ] + }, + "tags": [ + "clisessionsv2", + "get", + "session_id" + ], + "searchBlob": "cliSessionsV2.get Fetch a single CLI session record by its session ID, checking ownership and organization access. clisessionsv2 get session_id session_id" + }, + "cliSessionsV2.getByCloudAgentSessionId": { + "path": "cliSessionsV2.getByCloudAgentSessionId", + "kind": "query", + "summary": "Look up a user's CLI session record by the underlying cloud agent session ID.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cloud_agent_session_id": { + "type": "string", + "minLength": 1, + "maxLength": 255 + } + }, + "required": [ + "cloud_agent_session_id" + ] + }, + "tags": [ + "clisessionsv2", + "getbycloudagentsessionid", + "cloud_agent_session_id" + ], + "searchBlob": "cliSessionsV2.getByCloudAgentSessionId Look up a user's CLI session record by the underlying cloud agent session ID. clisessionsv2 getbycloudagentsessionid cloud_agent_session_id cloud_agent_session_id" + }, + "cliSessionsV2.getSessionMessages": { + "path": "cliSessionsV2.getSessionMessages", + "kind": "query", + "summary": "Get the full message history and transcript info for a session, grouped and reordered for cloud-agent worktree sessions.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "session_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "session_id" + ] + }, + "tags": [ + "clisessionsv2", + "getsessionmessages", + "session_id" + ], + "searchBlob": "cliSessionsV2.getSessionMessages Get the full message history and transcript info for a session, grouped and reordered for cloud-agent worktree sessions. clisessionsv2 getsessionmessages session_id session_id" + }, + "cliSessionsV2.getSessionMessagesPage": { + "path": "cliSessionsV2.getSessionMessagesPage", + "kind": "query", + "summary": "Fetch a paginated page of a session's message history for incremental loading, including an event watermark when starting a fresh read.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "session_id": { + "type": "string", + "minLength": 1 + }, + "limit": { + "default": 50, + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 100 + }, + "cursor": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "session_id" + ] + }, + "tags": [ + "clisessionsv2", + "getsessionmessagespage", + "session_id", + "limit", + "cursor" + ], + "searchBlob": "cliSessionsV2.getSessionMessagesPage Fetch a paginated page of a session's message history for incremental loading, including an event watermark when starting a fresh read. clisessionsv2 getsessionmessagespage session_id limit cursor session_id limit cursor" + }, + "cliSessionsV2.getWithRuntimeState": { + "path": "cliSessionsV2.getWithRuntimeState", + "kind": "query", + "summary": "Get a session record together with its current cloud agent runtime state and any associated GitHub pull request metadata for the session's branch.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "session_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "session_id" + ] + }, + "tags": [ + "clisessionsv2", + "getwithruntimestate", + "session_id" + ], + "searchBlob": "cliSessionsV2.getWithRuntimeState Get a session record together with its current cloud agent runtime state and any associated GitHub pull request metadata for the session's branch. clisessionsv2 getwithruntimestate session_id session_id" + }, + "cliSessionsV2.list": { + "path": "cliSessionsV2.list", + "kind": "query", + "summary": "List the current user's CLI/agent sessions with pagination, filtering by organization, worktree, git URL, platform, shared/public status, version, or recent updates.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cursor": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "limit": { + "default": 10, + "type": "number", + "minimum": 1, + "maximum": 200 + }, + "orderBy": { + "default": "updated_at", + "type": "string", + "enum": [ + "created_at", + "updated_at" + ] + }, + "includeChildren": { + "default": false, + "type": "boolean" + }, + "sharedOnly": { + "default": false, + "type": "boolean" + }, + "createdOnPlatform": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + { + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 100 + } + } + ] + }, + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + }, + "worktreeId": { + "type": "string", + "pattern": "^worktree_([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "gitUrl": { + "anyOf": [ + { + "type": "string" + }, + { + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "updatedSince": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "version": { + "type": "number" + }, + "fetchReviewDecision": { + "default": false, + "type": "boolean" + } + } + }, + "tags": [ + "clisessionsv2", + "list", + "cursor", + "limit", + "orderby", + "includechildren", + "sharedonly", + "createdonplatform", + "organizationid", + "worktreeid", + "giturl", + "updatedsince", + "version", + "fetchreviewdecision" + ], + "searchBlob": "cliSessionsV2.list List the current user's CLI/agent sessions with pagination, filtering by organization, worktree, git URL, platform, shared/public status, version, or recent updates. clisessionsv2 list cursor limit orderby includechildren sharedonly createdonplatform organizationid worktreeid giturl updatedsince version fetchreviewdecision cursor limit orderBy includeChildren sharedOnly createdOnPlatform organizationId worktreeId gitUrl updatedSince version fetchReviewDecision" + }, + "cliSessionsV2.recentRepositories": { + "path": "cliSessionsV2.recentRepositories", + "kind": "query", + "summary": "Return the user's most recently active git repositories based on session activity since a given timestamp.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + }, + "updatedSince": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + } + }, + "required": [ + "updatedSince" + ] + }, + "tags": [ + "clisessionsv2", + "recentrepositories", + "organizationid", + "updatedsince" + ], + "searchBlob": "cliSessionsV2.recentRepositories Return the user's most recently active git repositories based on session activity since a given timestamp. clisessionsv2 recentrepositories organizationid updatedsince organizationId updatedSince" + }, + "cliSessionsV2.search": { + "path": "cliSessionsV2.search", + "kind": "query", + "summary": "Search the user's sessions by case-insensitive text across title, session ID, git URL/branch, worktree name, and PR title or number, with pagination and the same filters as list.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "search_string": { + "type": "string", + "minLength": 1 + }, + "limit": { + "default": 10, + "type": "number", + "minimum": 1, + "maximum": 50 + }, + "offset": { + "default": 0, + "type": "number", + "minimum": 0 + }, + "cursor": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "orderBy": { + "default": "updated_at", + "type": "string", + "enum": [ + "created_at", + "updated_at" + ] + }, + "createdOnPlatform": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + { + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 100 + } + } + ] + }, + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + }, + "worktreeId": { + "type": "string", + "pattern": "^worktree_([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "includeChildren": { + "default": false, + "type": "boolean" + }, + "sharedOnly": { + "default": false, + "type": "boolean" + }, + "gitUrl": { + "anyOf": [ + { + "type": "string" + }, + { + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + } + ] + } + }, + "required": [ + "search_string" + ] + }, + "tags": [ + "clisessionsv2", + "search", + "search_string", + "limit", + "offset", + "cursor", + "orderby", + "createdonplatform", + "organizationid", + "worktreeid", + "includechildren", + "sharedonly", + "giturl" + ], + "searchBlob": "cliSessionsV2.search Search the user's sessions by case-insensitive text across title, session ID, git URL/branch, worktree name, and PR title or number, with pagination and the same filters as list. clisessionsv2 search search_string limit offset cursor orderby createdonplatform organizationid worktreeid includechildren sharedonly giturl search_string limit offset cursor orderBy createdOnPlatform organizationId worktreeId includeChildren sharedOnly gitUrl" + }, + "cliSessionsV2.worktreeDetails": { + "path": "cliSessionsV2.worktreeDetails", + "kind": "query", + "summary": "Fetch summary details for a set of cloud agent worktrees, including the session that started each one, active PR info, and per-worktree session activity/status.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "worktreeIds": { + "maxItems": 200, + "type": "array", + "items": { + "type": "string", + "pattern": "^worktree_([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "worktreeIds", + "organizationId" + ] + }, + "tags": [ + "clisessionsv2", + "worktreedetails", + "worktreeids", + "organizationid" + ], + "searchBlob": "cliSessionsV2.worktreeDetails Fetch summary details for a set of cloud agent worktrees, including the session that started each one, active PR info, and per-worktree session activity/status. clisessionsv2 worktreedetails worktreeids organizationid worktreeIds organizationId" + }, + "cloudAgentNext.checkEligibility": { + "path": "cloudAgentNext.checkEligibility", + "kind": "query", + "summary": "Check whether the current user is eligible to use cloud agents based on their account balance.", + "inputSchema": {}, + "tags": [ + "cloudagentnext", + "checkeligibility" + ], + "searchBlob": "cloudAgentNext.checkEligibility Check whether the current user is eligible to use cloud agents based on their account balance. cloudagentnext checkeligibility" + }, + "cloudAgentNext.getComputeBillingStatus": { + "path": "cloudAgentNext.getComputeBillingStatus", + "kind": "query", + "summary": "Get billing status and compute usage information for a cloud agent session.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cloudAgentSessionId": { + "type": "string" + } + }, + "required": [ + "cloudAgentSessionId" + ] + }, + "tags": [ + "cloudagentnext", + "getcomputebillingstatus", + "cloudagentsessionid" + ], + "searchBlob": "cloudAgentNext.getComputeBillingStatus Get billing status and compute usage information for a cloud agent session. cloudagentnext getcomputebillingstatus cloudagentsessionid cloudAgentSessionId" + }, + "cloudAgentNext.getSandboxStatus": { + "path": "cloudAgentNext.getSandboxStatus", + "kind": "query", + "summary": "Check whether the sandbox for a cloud agent session is running and its current state.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cloudAgentSessionId": { + "type": "string", + "allOf": [ + { + "pattern": "^(agent|workspace)_[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" + }, + { + "pattern": "^workspace_.*" + } + ] + } + }, + "required": [ + "cloudAgentSessionId" + ], + "additionalProperties": false + }, + "tags": [ + "cloudagentnext", + "getsandboxstatus", + "cloudagentsessionid" + ], + "searchBlob": "cloudAgentNext.getSandboxStatus Check whether the sandbox for a cloud agent session is running and its current state. cloudagentnext getsandboxstatus cloudagentsessionid cloudAgentSessionId" + }, + "cloudAgentNext.getSession": { + "path": "cloudAgentNext.getSession", + "kind": "query", + "summary": "Retrieve the current status and details of a cloud agent session.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cloudAgentSessionId": { + "type": "string" + } + }, + "required": [ + "cloudAgentSessionId" + ] + }, + "tags": [ + "cloudagentnext", + "getsession", + "cloudagentsessionid" + ], + "searchBlob": "cloudAgentNext.getSession Retrieve the current status and details of a cloud agent session. cloudagentnext getsession cloudagentsessionid cloudAgentSessionId" + }, + "cloudAgentNext.getWorktreeChanges": { + "path": "cloudAgentNext.getWorktreeChanges", + "kind": "query", + "summary": "Fetch the list of uncommitted file changes in a cloud agent session's git worktree.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cloudAgentSessionId": { + "type": "string", + "pattern": "^workspace_[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" + } + }, + "required": [ + "cloudAgentSessionId" + ], + "additionalProperties": false + }, + "tags": [ + "cloudagentnext", + "getworktreechanges", + "cloudagentsessionid" + ], + "searchBlob": "cloudAgentNext.getWorktreeChanges Fetch the list of uncommitted file changes in a cloud agent session's git worktree. cloudagentnext getworktreechanges cloudagentsessionid cloudAgentSessionId" + }, + "cloudAgentNext.getWorktreeFile": { + "path": "cloudAgentNext.getWorktreeFile", + "kind": "query", + "summary": "Read a single file from a cloud agent session's worktree snapshot, returning its diff, content, and revision metadata for the expected revision.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + "expectedRevision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "cloudAgentSessionId": { + "type": "string", + "pattern": "^workspace_[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" + } + }, + "required": [ + "path", + "expectedRevision", + "cloudAgentSessionId" + ], + "additionalProperties": false + }, + "tags": [ + "cloudagentnext", + "getworktreefile", + "path", + "expectedrevision", + "cloudagentsessionid" + ], + "searchBlob": "cloudAgentNext.getWorktreeFile Read a single file from a cloud agent session's worktree snapshot, returning its diff, content, and revision metadata for the expected revision. cloudagentnext getworktreefile path expectedrevision cloudagentsessionid path expectedRevision cloudAgentSessionId" + }, + "cloudAgentNext.listGitHubRepositories": { + "path": "cloudAgentNext.listGitHubRepositories", + "kind": "query", + "summary": "List the user's GitHub repositories available for cloud agent use, with optional refresh.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "forceRefresh": { + "default": false, + "type": "boolean" + } + } + }, + "tags": [ + "cloudagentnext", + "listgithubrepositories", + "forcerefresh" + ], + "searchBlob": "cloudAgentNext.listGitHubRepositories List the user's GitHub repositories available for cloud agent use, with optional refresh. cloudagentnext listgithubrepositories forcerefresh forceRefresh" + }, + "cloudAgentNext.listGitLabRepositories": { + "path": "cloudAgentNext.listGitLabRepositories", + "kind": "query", + "summary": "List the user's GitLab repositories available for cloud agent use, with optional refresh.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "forceRefresh": { + "default": false, + "type": "boolean" + } + } + }, + "tags": [ + "cloudagentnext", + "listgitlabrepositories", + "forcerefresh" + ], + "searchBlob": "cloudAgentNext.listGitLabRepositories List the user's GitLab repositories available for cloud agent use, with optional refresh. cloudagentnext listgitlabrepositories forcerefresh forceRefresh" + }, + "codeIndexing.admin.getClusterStatus": { + "path": "codeIndexing.admin.getClusterStatus", + "kind": "query", + "summary": "Admin-only health and telemetry report for the vector database cluster powering code indexing, covering Qdrant version, CPU/RAM/disk usage, collection points, and consensus status.", + "inputSchema": {}, + "tags": [ + "codeindexing", + "admin", + "getclusterstatus" + ], + "searchBlob": "codeIndexing.admin.getClusterStatus Admin-only health and telemetry report for the vector database cluster powering code indexing, covering Qdrant version, CPU/RAM/disk usage, collection points, and consensus status. codeindexing admin getclusterstatus" + }, + "codeIndexing.admin.getSummaryStats": { + "path": "codeIndexing.admin.getSummaryStats", + "kind": "query", + "summary": "Admin-only paginated overview of code indexing usage aggregated per organization, showing chunk/file counts, storage size, and percentage share of total indexed rows.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "page": { + "default": 1, + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "pageSize": { + "default": 20, + "type": "integer", + "minimum": 1, + "maximum": 100 + }, + "sortBy": { + "default": "size_kb", + "type": "string", + "enum": [ + "organization_name", + "chunk_count", + "project_count", + "branch_count", + "percentage_of_rows", + "size_kb", + "last_modified" + ] + }, + "sortOrder": { + "default": "desc", + "type": "string", + "enum": [ + "asc", + "desc" + ] + } + } + }, + "tags": [ + "codeindexing", + "admin", + "getsummarystats", + "page", + "pagesize", + "sortby", + "sortorder" + ], + "searchBlob": "codeIndexing.admin.getSummaryStats Admin-only paginated overview of code indexing usage aggregated per organization, showing chunk/file counts, storage size, and percentage share of total indexed rows. codeindexing admin getsummarystats page pagesize sortby sortorder page pageSize sortBy sortOrder" + }, + "codeIndexing.admin.getUserSummaryStats": { + "path": "codeIndexing.admin.getUserSummaryStats", + "kind": "query", + "summary": "Admin-only paginated overview of code indexing usage aggregated per user, showing each user's indexed chunk and file counts, project/branch totals, and storage usage.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "page": { + "default": 1, + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "pageSize": { + "default": 20, + "type": "integer", + "minimum": 1, + "maximum": 100 + }, + "sortBy": { + "default": "size_kb", + "type": "string", + "enum": [ + "user_email", + "chunk_count", + "project_count", + "branch_count", + "percentage_of_rows", + "size_kb", + "last_modified" + ] + }, + "sortOrder": { + "default": "desc", + "type": "string", + "enum": [ + "asc", + "desc" + ] + } + } + }, + "tags": [ + "codeindexing", + "admin", + "getusersummarystats", + "page", + "pagesize", + "sortby", + "sortorder" + ], + "searchBlob": "codeIndexing.admin.getUserSummaryStats Admin-only paginated overview of code indexing usage aggregated per user, showing each user's indexed chunk and file counts, project/branch totals, and storage usage. codeindexing admin getusersummarystats page pagesize sortby sortorder page pageSize sortBy sortOrder" + }, + "codeIndexing.getManifest": { + "path": "codeIndexing.getManifest", + "kind": "query", + "summary": "Retrieve the indexing manifest for a project and git branch, listing all files that have been indexed into the codebase.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + }, + "projectId": { + "type": "string" + }, + "gitBranch": { + "type": "string" + } + }, + "required": [ + "projectId", + "gitBranch" + ] + }, + "tags": [ + "codeindexing", + "getmanifest", + "organizationid", + "projectid", + "gitbranch" + ], + "searchBlob": "codeIndexing.getManifest Retrieve the indexing manifest for a project and git branch, listing all files that have been indexed into the codebase. codeindexing getmanifest organizationid projectid gitbranch organizationId projectId gitBranch" + }, + "codeIndexing.getOrganizationStats": { + "path": "codeIndexing.getOrganizationStats", + "kind": "query", + "summary": "Aggregate indexing statistics for an organization broken down by project, including file and chunk counts, storage size, last modified date, and per-branch breakdowns.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + }, + "overrideUser": { + "type": "string" + } + } + }, + "tags": [ + "codeindexing", + "getorganizationstats", + "organizationid", + "overrideuser" + ], + "searchBlob": "codeIndexing.getOrganizationStats Aggregate indexing statistics for an organization broken down by project, including file and chunk counts, storage size, last modified date, and per-branch breakdowns. codeindexing getorganizationstats organizationid overrideuser organizationId overrideUser" + }, + "codeIndexing.getProjectFiles": { + "path": "codeIndexing.getProjectFiles", + "kind": "query", + "summary": "List indexed files within a project with pagination, search, and branch filtering, showing per-file chunk count, size, branches, line counts, and percentage of AI-generated lines.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + }, + "projectId": { + "type": "string" + }, + "gitBranch": { + "type": "string" + }, + "fileSearch": { + "type": "string" + }, + "page": { + "default": 1, + "type": "number", + "minimum": 1 + }, + "pageSize": { + "default": 20, + "type": "number", + "minimum": 1, + "maximum": 50 + }, + "overrideUser": { + "type": "string" + } + }, + "required": [ + "projectId" + ] + }, + "tags": [ + "codeindexing", + "getprojectfiles", + "organizationid", + "projectid", + "gitbranch", + "filesearch", + "page", + "pagesize", + "overrideuser" + ], + "searchBlob": "codeIndexing.getProjectFiles List indexed files within a project with pagination, search, and branch filtering, showing per-file chunk count, size, branches, line counts, and percentage of AI-generated lines. codeindexing getprojectfiles organizationid projectid gitbranch filesearch page pagesize overrideuser organizationId projectId gitBranch fileSearch page pageSize overrideUser" + }, + "codeIndexing.getRecentSearches": { + "path": "codeIndexing.getRecentSearches", + "kind": "query", + "summary": "List the most recent code-indexing search queries made by members of an organization, with timestamps, project, and result counts.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "codeindexing", + "getrecentsearches", + "organizationid" + ], + "searchBlob": "codeIndexing.getRecentSearches List the most recent code-indexing search queries made by members of an organization, with timestamps, project, and result counts. codeindexing getrecentsearches organizationid organizationId" + }, + "codeIndexing.search": { + "path": "codeIndexing.search", + "kind": "query", + "summary": "Semantic search over an indexed codebase, returning relevant files and chunks for a natural language query scoped to a project (optionally restricted to a path, branch, and excluded files).", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + }, + "query": { + "type": "string", + "minLength": 1 + }, + "path": { + "type": "string" + }, + "projectId": { + "type": "string" + }, + "preferBranch": { + "type": "string" + }, + "fallbackBranch": { + "default": "main", + "type": "string" + }, + "excludeFiles": { + "default": [], + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "query", + "projectId" + ] + }, + "tags": [ + "codeindexing", + "search", + "organizationid", + "query", + "path", + "projectid", + "preferbranch", + "fallbackbranch", + "excludefiles" + ], + "searchBlob": "codeIndexing.search Semantic search over an indexed codebase, returning relevant files and chunks for a natural language query scoped to a project (optionally restricted to a path, branch, and excluded files). codeindexing search organizationid query path projectid preferbranch fallbackbranch excludefiles organizationId query path projectId preferBranch fallbackBranch excludeFiles" + }, + "codeReviews.analytics.getDashboard": { + "path": "codeReviews.analytics.getDashboard", + "kind": "query", + "summary": "Get organization code review analytics and metrics dashboard for a selected time window, platform, and repository, including spend and usage stats gated by role.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "platform": { + "type": "string", + "enum": [ + "github", + "gitlab" + ] + }, + "periodDays": { + "anyOf": [ + { + "type": "number", + "const": 7 + }, + { + "type": "number", + "const": 30 + }, + { + "type": "number", + "const": 90 + } + ] + }, + "repository": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "organizationId", + "platform", + "periodDays" + ] + }, + "tags": [ + "codereviews", + "analytics", + "getdashboard", + "organizationid", + "platform", + "perioddays", + "repository" + ], + "searchBlob": "codeReviews.analytics.getDashboard Get organization code review analytics and metrics dashboard for a selected time window, platform, and repository, including spend and usage stats gated by role. codereviews analytics getdashboard organizationid platform perioddays repository organizationId platform periodDays repository" + }, + "codeReviews.get": { + "path": "codeReviews.get", + "kind": "query", + "summary": "Fetch full details of a single code review by ID, including its attempts, token usage and billing, selected model, and council result, after enforcing ownership or org access.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "reviewId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "reviewId" + ] + }, + "tags": [ + "codereviews", + "get", + "reviewid" + ], + "searchBlob": "codeReviews.get Fetch full details of a single code review by ID, including its attempts, token usage and billing, selected model, and council result, after enforcing ownership or org access. codereviews get reviewid reviewId" + }, + "codeReviews.getReviewStreamInfo": { + "path": "codeReviews.getReviewStreamInfo", + "kind": "query", + "summary": "Get stream connection info for a code review or attempt, such as the cloud agent session ID, organization, status, and agent version, used to hook up the live review stream.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "reviewId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "attemptId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "reviewId" + ] + }, + "tags": [ + "codereviews", + "getreviewstreaminfo", + "reviewid", + "attemptid" + ], + "searchBlob": "codeReviews.getReviewStreamInfo Get stream connection info for a code review or attempt, such as the cloud agent session ID, organization, status, and agent version, used to hook up the live review stream. codereviews getreviewstreaminfo reviewid attemptid reviewId attemptId" + }, + "codeReviews.getSessionMessages": { + "path": "codeReviews.getSessionMessages", + "kind": "query", + "summary": "Get the underlying agent session's message log entries for a code review or specific attempt, returned as formatted log entries from v1 blob or v2 snapshot sources.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "reviewId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "attemptId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "reviewId" + ] + }, + "tags": [ + "codereviews", + "getsessionmessages", + "reviewid", + "attemptid" + ], + "searchBlob": "codeReviews.getSessionMessages Get the underlying agent session's message log entries for a code review or specific attempt, returned as formatted log entries from v1 blob or v2 snapshot sources. codereviews getsessionmessages reviewid attemptid reviewId attemptId" + }, + "codeReviews.listForOrganization": { + "path": "codeReviews.listForOrganization", + "kind": "query", + "summary": "List code reviews belonging to an organization with pagination and filtering by status, repository, and platform, redacting internal session IDs for non-admin members.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "codereviews", + "listfororganization", + "organizationid" + ], + "searchBlob": "codeReviews.listForOrganization List code reviews belonging to an organization with pagination and filtering by status, repository, and platform, redacting internal session IDs for non-admin members. codereviews listfororganization organizationid organizationId" + }, + "codeReviews.listForUser": { + "path": "codeReviews.listForUser", + "kind": "query", + "summary": "List the signed-in user's own code reviews with pagination and filtering by status, repository, and platform.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "limit": { + "default": 50, + "type": "integer", + "minimum": 1, + "maximum": 100 + }, + "offset": { + "default": 0, + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "pending", + "queued", + "running", + "completed", + "failed", + "cancelled", + "interrupted" + ] + }, + "repoFullName": { + "type": "string" + }, + "platform": { + "type": "string", + "enum": [ + "github", + "gitlab", + "bitbucket" + ] + } + } + }, + "tags": [ + "codereviews", + "listforuser", + "limit", + "offset", + "status", + "repofullname", + "platform" + ], + "searchBlob": "codeReviews.listForUser List the signed-in user's own code reviews with pagination and filtering by status, repository, and platform. codereviews listforuser limit offset status repofullname platform limit offset status repoFullName platform" + }, + "codingPlans.adminAvailabilityIntentCounts": { + "path": "codingPlans.adminAvailabilityIntentCounts", + "kind": "query", + "summary": "Admin-only: get counts of user availability request intents for each coding plan", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": {} + }, + "tags": [ + "codingplans", + "adminavailabilityintentcounts" + ], + "searchBlob": "codingPlans.adminAvailabilityIntentCounts Admin-only: get counts of user availability request intents for each coding plan codingplans adminavailabilityintentcounts" + }, + "codingPlans.adminInsights": { + "path": "codingPlans.adminInsights", + "kind": "query", + "summary": "Admin-only: fetch coding plan insights and analytics for a configurable number of lookback days", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "rangeDays": { + "default": 7, + "anyOf": [ + { + "type": "number", + "const": 7 + }, + { + "type": "number", + "const": 14 + }, + { + "type": "number", + "const": 30 + } + ] + } + } + }, + "tags": [ + "codingplans", + "admininsights", + "rangedays" + ], + "searchBlob": "codingPlans.adminInsights Admin-only: fetch coding plan insights and analytics for a configurable number of lookback days codingplans admininsights rangedays rangeDays" + }, + "codingPlans.adminKeyInventory": { + "path": "codingPlans.adminKeyInventory", + "kind": "query", + "summary": "Admin-only: view counts of license or key inventory per coding plan", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "planId": { + "type": "string", + "enum": [ + "minimax-token-plan-plus", + "minimax-token-plan-max", + "minimax-token-plan-ultra", + "byteplus-coding-plan-team-lite", + "byteplus-coding-plan-team-pro" + ] + } + } + }, + "tags": [ + "codingplans", + "adminkeyinventory", + "planid" + ], + "searchBlob": "codingPlans.adminKeyInventory Admin-only: view counts of license or key inventory per coding plan codingplans adminkeyinventory planid planId" + }, + "codingPlans.adminListSubscriptions": { + "path": "codingPlans.adminListSubscriptions", + "kind": "query", + "summary": "Admin-only: list coding plan subscriptions across all users with search and status filtering, including pagination, totals, and the linked user and inventory key info", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "page": { + "default": 1, + "type": "integer", + "minimum": 1, + "maximum": 10000 + }, + "search": { + "type": "string", + "maxLength": 200 + }, + "status": { + "type": "string", + "enum": [ + "active", + "pending_cancellation", + "past_due", + "canceled" + ] + } + } + }, + "tags": [ + "codingplans", + "adminlistsubscriptions", + "page", + "search", + "status" + ], + "searchBlob": "codingPlans.adminListSubscriptions Admin-only: list coding plan subscriptions across all users with search and status filtering, including pagination, totals, and the linked user and inventory key info codingplans adminlistsubscriptions page search status page search status" + }, + "codingPlans.adminRevocationQueue": { + "path": "codingPlans.adminRevocationQueue", + "kind": "query", + "summary": "Admin-only: list the queue of manual credential revocations, optionally filtered by plan and revocation status", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "planId": { + "type": "string", + "enum": [ + "minimax-token-plan-plus", + "minimax-token-plan-max", + "minimax-token-plan-ultra", + "byteplus-coding-plan-team-lite", + "byteplus-coding-plan-team-pro" + ] + }, + "status": { + "type": "string", + "enum": [ + "revocation_pending", + "revocation_failed" + ] + } + } + }, + "tags": [ + "codingplans", + "adminrevocationqueue", + "planid", + "status" + ], + "searchBlob": "codingPlans.adminRevocationQueue Admin-only: list the queue of manual credential revocations, optionally filtered by plan and revocation status codingplans adminrevocationqueue planid status planId status" + }, + "codingPlans.adminSubscriptionOverview": { + "path": "codingPlans.adminSubscriptionOverview", + "kind": "query", + "summary": "Admin-only: fetch a summary overview of coding plan subscription metrics across all users", + "inputSchema": {}, + "tags": [ + "codingplans", + "adminsubscriptionoverview" + ], + "searchBlob": "codingPlans.adminSubscriptionOverview Admin-only: fetch a summary overview of coding plan subscription metrics across all users codingplans adminsubscriptionoverview" + }, + "codingPlans.catalog": { + "path": "codingPlans.catalog", + "kind": "query", + "summary": "Get the catalog of available coding plan subscriptions, including pricing in Kilo credits, billing period, availability status, and which plans the user has requested availability notifications for", + "inputSchema": {}, + "tags": [ + "codingplans", + "catalog" + ], + "searchBlob": "codingPlans.catalog Get the catalog of available coding plan subscriptions, including pricing in Kilo credits, billing period, availability status, and which plans the user has requested availability notifications for codingplans catalog" + }, + "codingPlans.getBillingHistory": { + "path": "codingPlans.getBillingHistory", + "kind": "query", + "summary": "Get the paginated billing history and credit transactions for one of the current user's coding plan subscriptions", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "subscriptionId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "cursor": { + "type": "string" + } + }, + "required": [ + "subscriptionId" + ] + }, + "tags": [ + "codingplans", + "getbillinghistory", + "subscriptionid", + "cursor" + ], + "searchBlob": "codingPlans.getBillingHistory Get the paginated billing history and credit transactions for one of the current user's coding plan subscriptions codingplans getbillinghistory subscriptionid cursor subscriptionId cursor" + }, + "codingPlans.getSubscriptionDetail": { + "path": "codingPlans.getSubscriptionDetail", + "kind": "query", + "summary": "Get full details of a single coding plan subscription owned by the current user by subscription id", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "subscriptionId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "subscriptionId" + ] + }, + "tags": [ + "codingplans", + "getsubscriptiondetail", + "subscriptionid" + ], + "searchBlob": "codingPlans.getSubscriptionDetail Get full details of a single coding plan subscription owned by the current user by subscription id codingplans getsubscriptiondetail subscriptionid subscriptionId" + }, + "codingPlans.getUsage": { + "path": "codingPlans.getUsage", + "kind": "query", + "summary": "Get current usage statistics and limits for the current user's coding plan subscription by subscription id", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "subscriptionId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "subscriptionId" + ] + }, + "tags": [ + "codingplans", + "getusage", + "subscriptionid" + ], + "searchBlob": "codingPlans.getUsage Get current usage statistics and limits for the current user's coding plan subscription by subscription id codingplans getusage subscriptionid subscriptionId" + }, + "codingPlans.listSubscriptions": { + "path": "codingPlans.listSubscriptions", + "kind": "query", + "summary": "List all coding plan subscriptions owned by the current user", + "inputSchema": {}, + "tags": [ + "codingplans", + "listsubscriptions" + ], + "searchBlob": "codingPlans.listSubscriptions List all coding plan subscriptions owned by the current user codingplans listsubscriptions" + }, + "deployments.checkDeploymentEligibility": { + "path": "deployments.checkDeploymentEligibility", + "kind": "query", + "summary": "Check whether the current user has ever made a payment and is eligible to create a deployment.", + "inputSchema": {}, + "tags": [ + "deployments", + "checkdeploymenteligibility" + ], + "searchBlob": "deployments.checkDeploymentEligibility Check whether the current user has ever made a payment and is eligible to create a deployment. deployments checkdeploymenteligibility" + }, + "deployments.checkSlugAvailability": { + "path": "deployments.checkSlugAvailability", + "kind": "query", + "summary": "Check whether a proposed deployment slug is available for use.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "slug": { + "type": "string", + "minLength": 3, + "maxLength": 63, + "pattern": "^[a-z0-9]([a-z0-9-]*[a-z0-9])?$" + } + }, + "required": [ + "slug" + ] + }, + "tags": [ + "deployments", + "checkslugavailability", + "slug" + ], + "searchBlob": "deployments.checkSlugAvailability Check whether a proposed deployment slug is available for use. deployments checkslugavailability slug slug" + }, + "deployments.getBuildEvents": { + "path": "deployments.getBuildEvents", + "kind": "query", + "summary": "Retrieve a paginated list of build log events for a deployment and build, optionally continuing after a given event ID.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "deploymentId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "buildId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "limit": { + "default": 100, + "type": "number", + "minimum": 1, + "maximum": 1000 + }, + "afterEventId": { + "type": "number" + } + }, + "required": [ + "deploymentId", + "buildId" + ] + }, + "tags": [ + "deployments", + "getbuildevents", + "deploymentid", + "buildid", + "limit", + "aftereventid" + ], + "searchBlob": "deployments.getBuildEvents Retrieve a paginated list of build log events for a deployment and build, optionally continuing after a given event ID. deployments getbuildevents deploymentid buildid limit aftereventid deploymentId buildId limit afterEventId" + }, + "deployments.getDeployment": { + "path": "deployments.getDeployment", + "kind": "query", + "summary": "Fetch a single deployment's details by its ID for the current user.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "id" + ] + }, + "tags": [ + "deployments", + "getdeployment", + "id" + ], + "searchBlob": "deployments.getDeployment Fetch a single deployment's details by its ID for the current user. deployments getdeployment id id" + }, + "deployments.listDeployments": { + "path": "deployments.listDeployments", + "kind": "query", + "summary": "List all deployments belonging to the current user.", + "inputSchema": {}, + "tags": [ + "deployments", + "listdeployments" + ], + "searchBlob": "deployments.listDeployments List all deployments belonging to the current user. deployments listdeployments" + }, + "deployments.listEnvVars": { + "path": "deployments.listEnvVars", + "kind": "query", + "summary": "List the environment variables configured for a given deployment owned by the current user.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "deploymentId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "deploymentId" + ] + }, + "tags": [ + "deployments", + "listenvvars", + "deploymentid" + ], + "searchBlob": "deployments.listEnvVars List the environment variables configured for a given deployment owned by the current user. deployments listenvvars deploymentid deploymentId" + }, + "discord.getInstallation": { + "path": "discord.getInstallation", + "kind": "query", + "summary": "Check whether the Discord integration is installed for the current organization or owner, returning the guild (server) ID, name, granted scopes, installation date, and the configured model slug, or indicating it is not installed.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "discord", + "getinstallation", + "organizationid" + ], + "searchBlob": "discord.getInstallation Check whether the Discord integration is installed for the current organization or owner, returning the guild (server) ID, name, granted scopes, installation date, and the configured model slug, or indicating it is not installed. discord getinstallation organizationid organizationId" + }, + "dolthub.getInstallation": { + "path": "dolthub.getInstallation", + "kind": "query", + "summary": "Check whether DoltHub integration is installed and active for the current user or organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "dolthub", + "getinstallation", + "organizationid" + ], + "searchBlob": "dolthub.getInstallation Check whether DoltHub integration is installed and active for the current user or organization. dolthub getinstallation organizationid organizationId" + }, + "dolthub.getInstallationCredentials": { + "path": "dolthub.getInstallationCredentials", + "kind": "query", + "summary": "Get the current DoltHub API token and connected username for an active installation.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "dolthub", + "getinstallationcredentials", + "organizationid" + ], + "searchBlob": "dolthub.getInstallationCredentials Get the current DoltHub API token and connected username for an active installation. dolthub getinstallationcredentials organizationid organizationId" + }, + "dolthub.resolveUsername": { + "path": "dolthub.resolveUsername", + "kind": "query", + "summary": "Get the DoltHub username associated with the active installation for the current user or organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "dolthub", + "resolveusername", + "organizationid" + ], + "searchBlob": "dolthub.resolveUsername Get the DoltHub username associated with the active installation for the current user or organization. dolthub resolveusername organizationid organizationId" + }, + "dolthub.verifyUpstream": { + "path": "dolthub.verifyUpstream", + "kind": "query", + "summary": "Verify that a DoltHub upstream repository (owner/repo) exists and is accessible.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "upstream": { + "type": "string", + "pattern": "^[a-zA-Z0-9_-]+\\/[a-zA-Z0-9_.-]+$" + } + }, + "required": [ + "upstream" + ] + }, + "tags": [ + "dolthub", + "verifyupstream", + "organizationid", + "upstream" + ], + "searchBlob": "dolthub.verifyUpstream Verify that a DoltHub upstream repository (owner/repo) exists and is accessible. dolthub verifyupstream organizationid upstream organizationId upstream" + }, + "githubApps.checkUserPendingInstallation": { + "path": "githubApps.checkUserPendingInstallation", + "kind": "query", + "summary": "Check whether the current user has a pending GitHub app installation awaiting approval.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "githubapps", + "checkuserpendinginstallation", + "organizationid" + ], + "searchBlob": "githubApps.checkUserPendingInstallation Check whether the current user has a pending GitHub app installation awaiting approval. githubapps checkuserpendinginstallation organizationid organizationId" + }, + "githubApps.getAppType": { + "path": "githubApps.getAppType", + "kind": "query", + "summary": "Get the type of GitHub app configured for a user or organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "githubapps", + "getapptype", + "organizationid" + ], + "searchBlob": "githubApps.getAppType Get the type of GitHub app configured for a user or organization. githubapps getapptype organizationid organizationId" + }, + "githubApps.getConnectionAttempt": { + "path": "githubApps.getConnectionAttempt", + "kind": "query", + "summary": "Get details of a specific GitHub connection attempt for an organization, verifying it exists and belongs to the org.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "attemptId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "attemptId", + "organizationId" + ] + }, + "tags": [ + "githubapps", + "getconnectionattempt", + "attemptid", + "organizationid" + ], + "searchBlob": "githubApps.getConnectionAttempt Get details of a specific GitHub connection attempt for an organization, verifying it exists and belongs to the org. githubapps getconnectionattempt attemptid organizationid attemptId organizationId" + }, + "githubApps.getInstallation": { + "path": "githubApps.getInstallation", + "kind": "query", + "summary": "Get the GitHub app installation for the current user or organization, including install status, permissions, and repositories.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "githubapps", + "getinstallation", + "organizationid" + ], + "searchBlob": "githubApps.getInstallation Get the GitHub app installation for the current user or organization, including install status, permissions, and repositories. githubapps getinstallation organizationid organizationId" + }, + "githubApps.getRepositoryCustomizations": { + "path": "githubApps.getRepositoryCustomizations", + "kind": "query", + "summary": "Fetch custom repository settings and configurations for a GitHub app integration.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "integrationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "integrationId" + ] + }, + "tags": [ + "githubapps", + "getrepositorycustomizations", + "organizationid", + "integrationid" + ], + "searchBlob": "githubApps.getRepositoryCustomizations Fetch custom repository settings and configurations for a GitHub app integration. githubapps getrepositorycustomizations organizationid integrationid organizationId integrationId" + }, + "githubApps.getUserAuthorization": { + "path": "githubApps.getUserAuthorization", + "kind": "query", + "summary": "Check whether the current user has authorized the GitHub app connection.", + "inputSchema": {}, + "tags": [ + "githubapps", + "getuserauthorization" + ], + "searchBlob": "githubApps.getUserAuthorization Check whether the current user has authorized the GitHub app connection. githubapps getuserauthorization" + }, + "githubApps.listBranches": { + "path": "githubApps.listBranches", + "kind": "query", + "summary": "List the branches of a GitHub repository accessible through a GitHub app integration.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "integrationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "repositoryFullName": { + "type": "string" + } + }, + "required": [ + "integrationId", + "repositoryFullName" + ] + }, + "tags": [ + "githubapps", + "listbranches", + "organizationid", + "integrationid", + "repositoryfullname" + ], + "searchBlob": "githubApps.listBranches List the branches of a GitHub repository accessible through a GitHub app integration. githubapps listbranches organizationid integrationid repositoryfullname organizationId integrationId repositoryFullName" + }, + "githubApps.listIntegrations": { + "path": "githubApps.listIntegrations", + "kind": "query", + "summary": "List the GitHub app integrations available to the current user or a specified organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "githubapps", + "listintegrations", + "organizationid" + ], + "searchBlob": "githubApps.listIntegrations List the GitHub app integrations available to the current user or a specified organization. githubapps listintegrations organizationid organizationId" + }, + "githubApps.listOrganizationInstallations": { + "path": "githubApps.listOrganizationInstallations", + "kind": "query", + "summary": "List GitHub app installations for an organization with connection status, repository selection, and management permissions.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "githubapps", + "listorganizationinstallations", + "organizationid" + ], + "searchBlob": "githubApps.listOrganizationInstallations List GitHub app installations for an organization with connection status, repository selection, and management permissions. githubapps listorganizationinstallations organizationid organizationId" + }, + "githubApps.listRepositories": { + "path": "githubApps.listRepositories", + "kind": "query", + "summary": "List the GitHub repositories accessible through a GitHub app integration, optionally forcing a refresh.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "integrationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "forceRefresh": { + "default": false, + "type": "boolean" + } + }, + "required": [ + "integrationId" + ] + }, + "tags": [ + "githubapps", + "listrepositories", + "organizationid", + "integrationid", + "forcerefresh" + ], + "searchBlob": "githubApps.listRepositories List the GitHub repositories accessible through a GitHub app integration, optionally forcing a refresh. githubapps listrepositories organizationid integrationid forcerefresh organizationId integrationId forceRefresh" + }, + "githubPrReview.getFileLines": { + "path": "githubPrReview.getFileLines", + "kind": "query", + "summary": "Get the raw content of a specific file at a given ref, sliced to a requested line range, for viewing diff context or line-level review.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "owner": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]+$" + }, + "repo": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]+$" + }, + "ref": { + "type": "string", + "minLength": 1, + "maxLength": 255 + }, + "path": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + }, + "startLine": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "endLine": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "owner", + "repo", + "ref", + "path", + "startLine", + "endLine" + ], + "additionalProperties": false + }, + "tags": [ + "githubprreview", + "getfilelines", + "owner", + "repo", + "ref", + "path", + "startline", + "endline" + ], + "searchBlob": "githubPrReview.getFileLines Get the raw content of a specific file at a given ref, sliced to a requested line range, for viewing diff context or line-level review. githubprreview getfilelines owner repo ref path startline endline owner repo ref path startLine endLine" + }, + "githubPrReview.getPullRequest": { + "path": "githubPrReview.getPullRequest", + "kind": "query", + "summary": "Fetch an overview of a single pull request, combining the PR details, its repository, and related metadata into one summary object.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "owner": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]+$" + }, + "repo": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]+$" + }, + "number": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "owner", + "repo", + "number" + ], + "additionalProperties": false + }, + "tags": [ + "githubprreview", + "getpullrequest", + "owner", + "repo", + "number" + ], + "searchBlob": "githubPrReview.getPullRequest Fetch an overview of a single pull request, combining the PR details, its repository, and related metadata into one summary object. githubprreview getpullrequest owner repo number owner repo number" + }, + "githubPrReview.listChecks": { + "path": "githubPrReview.listChecks", + "kind": "query", + "summary": "List all CI check runs and commit statuses for a given branch or commit ref, paginated, so you can see whether a pull request passed or failed its checks.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "owner": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]+$" + }, + "repo": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]+$" + }, + "ref": { + "type": "string", + "minLength": 1, + "maxLength": 255 + } + }, + "required": [ + "owner", + "repo", + "ref" + ], + "additionalProperties": false + }, + "tags": [ + "githubprreview", + "listchecks", + "owner", + "repo", + "ref" + ], + "searchBlob": "githubPrReview.listChecks List all CI check runs and commit statuses for a given branch or commit ref, paginated, so you can see whether a pull request passed or failed its checks. githubprreview listchecks owner repo ref owner repo ref" + }, + "githubPrReview.listFiles": { + "path": "githubPrReview.listFiles", + "kind": "query", + "summary": "List the files changed in a pull request, with pagination support for walking through large PRs.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "owner": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]+$" + }, + "repo": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]+$" + }, + "number": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "cursor": { + "type": "integer", + "minimum": 1, + "maximum": 60 + }, + "direction": { + "type": "string", + "enum": [ + "forward", + "backward" + ] + } + }, + "required": [ + "owner", + "repo", + "number" + ], + "additionalProperties": false + }, + "tags": [ + "githubprreview", + "listfiles", + "owner", + "repo", + "number", + "cursor", + "direction" + ], + "searchBlob": "githubPrReview.listFiles List the files changed in a pull request, with pagination support for walking through large PRs. githubprreview listfiles owner repo number cursor direction owner repo number cursor direction" + }, + "githubPrReview.listInbox": { + "path": "githubPrReview.listInbox", + "kind": "query", + "summary": "List pull requests in the user's review inbox, pulled from a GitHub search query and paginated by cursor.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cursor": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "direction": { + "type": "string", + "enum": [ + "forward", + "backward" + ] + } + }, + "additionalProperties": false + }, + "tags": [ + "githubprreview", + "listinbox", + "cursor", + "direction" + ], + "searchBlob": "githubPrReview.listInbox List pull requests in the user's review inbox, pulled from a GitHub search query and paginated by cursor. githubprreview listinbox cursor direction cursor direction" + }, + "githubPrReview.listReviewThreads": { + "path": "githubPrReview.listReviewThreads", + "kind": "query", + "summary": "List review threads (inline comment conversations) on a pull request with pagination, including general conversation comments on the first page.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "owner": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]+$" + }, + "repo": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]+$" + }, + "number": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "cursor": { + "type": "string", + "minLength": 1 + }, + "direction": { + "type": "string", + "enum": [ + "forward", + "backward" + ] + } + }, + "required": [ + "owner", + "repo", + "number" + ], + "additionalProperties": false + }, + "tags": [ + "githubprreview", + "listreviewthreads", + "owner", + "repo", + "number", + "cursor", + "direction" + ], + "searchBlob": "githubPrReview.listReviewThreads List review threads (inline comment conversations) on a pull request with pagination, including general conversation comments on the first page. githubprreview listreviewthreads owner repo number cursor direction owner repo number cursor direction" + }, + "gitlab.getInstallation": { + "path": "gitlab.getInstallation", + "kind": "query", + "summary": "Check whether a GitLab integration is installed for the current user or organization, and get details like instance URL, auth type, token expiration, and synced repositories.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "gitlab", + "getinstallation", + "organizationid" + ], + "searchBlob": "gitlab.getInstallation Check whether a GitLab integration is installed for the current user or organization, and get details like instance URL, auth type, token expiration, and synced repositories. gitlab getinstallation organizationid organizationId" + }, + "gitlab.listBranches": { + "path": "gitlab.listBranches", + "kind": "query", + "summary": "List the branches for a specific GitLab project, identified by its project path, using the user's GitLab integration.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "integrationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "projectPath": { + "type": "string" + } + }, + "required": [ + "integrationId", + "projectPath" + ] + }, + "tags": [ + "gitlab", + "listbranches", + "organizationid", + "integrationid", + "projectpath" + ], + "searchBlob": "gitlab.listBranches List the branches for a specific GitLab project, identified by its project path, using the user's GitLab integration. gitlab listbranches organizationid integrationid projectpath organizationId integrationId projectPath" + }, + "gitlab.listRepositories": { + "path": "gitlab.listRepositories", + "kind": "query", + "summary": "List the repositories available through a connected GitLab integration, with an option to force a refresh of the cached repository list.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "integrationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "forceRefresh": { + "default": false, + "type": "boolean" + } + }, + "required": [ + "integrationId" + ] + }, + "tags": [ + "gitlab", + "listrepositories", + "organizationid", + "integrationid", + "forcerefresh" + ], + "searchBlob": "gitlab.listRepositories List the repositories available through a connected GitLab integration, with an option to force a refresh of the cached repository list. gitlab listrepositories organizationid integrationid forcerefresh organizationId integrationId forceRefresh" + }, + "kiloChat.getToken": { + "path": "kiloChat.getToken", + "kind": "query", + "summary": "Get an authentication token for the Kilo chat service for the current user.", + "inputSchema": {}, + "tags": [ + "kilochat", + "gettoken" + ], + "searchBlob": "kiloChat.getToken Get an authentication token for the Kilo chat service for the current user. kilochat gettoken" + }, + "kiloPass.getAverageMonthlyUsageLast3Months": { + "path": "kiloPass.getAverageMonthlyUsageLast3Months", + "kind": "query", + "summary": "Get the user's average monthly Kilo Pass spend (in USD) based on usage over the last 3 months.", + "inputSchema": {}, + "tags": [ + "kilopass", + "getaveragemonthlyusagelast3months" + ], + "searchBlob": "kiloPass.getAverageMonthlyUsageLast3Months Get the user's average monthly Kilo Pass spend (in USD) based on usage over the last 3 months. kilopass getaveragemonthlyusagelast3months" + }, + "kiloPass.getBillingHistory": { + "path": "kiloPass.getBillingHistory", + "kind": "query", + "summary": "Get paginated Stripe invoice billing history for the user's Kilo Pass subscription.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + } + }, + "tags": [ + "kilopass", + "getbillinghistory", + "cursor", + "limit" + ], + "searchBlob": "kiloPass.getBillingHistory Get paginated Stripe invoice billing history for the user's Kilo Pass subscription. kilopass getbillinghistory cursor limit cursor limit" + }, + "kiloPass.getCheckoutReturnState": { + "path": "kiloPass.getCheckoutReturnState", + "kind": "query", + "summary": "After returning from a Kilo Pass checkout session, get whether the subscription was settled, if credits were awarded, the hosting intent, and promo fingerprint status.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "sessionId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "sessionId" + ] + }, + "tags": [ + "kilopass", + "getcheckoutreturnstate", + "sessionid" + ], + "searchBlob": "kiloPass.getCheckoutReturnState After returning from a Kilo Pass checkout session, get whether the subscription was settled, if credits were awarded, the hosting intent, and promo fingerprint status. kilopass getcheckoutreturnstate sessionid sessionId" + }, + "kiloPass.getChurnkeyAuthHash": { + "path": "kiloPass.getChurnkeyAuthHash", + "kind": "query", + "summary": "Get a Churnkey authentication hash and Stripe customer ID used to secure the dunning / payment failure flow.", + "inputSchema": {}, + "tags": [ + "kilopass", + "getchurnkeyauthhash" + ], + "searchBlob": "kiloPass.getChurnkeyAuthHash Get a Churnkey authentication hash and Stripe customer ID used to secure the dunning / payment failure flow. kilopass getchurnkeyauthhash" + }, + "kiloPass.getCreditHistory": { + "path": "kiloPass.getCreditHistory", + "kind": "query", + "summary": "Get paginated credit history entries for the user's Kilo Pass subscription, including issuance and store upgrade credits.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + } + }, + "tags": [ + "kilopass", + "getcredithistory", + "cursor", + "limit" + ], + "searchBlob": "kiloPass.getCreditHistory Get paginated credit history entries for the user's Kilo Pass subscription, including issuance and store upgrade credits. kilopass getcredithistory cursor limit cursor limit" + }, + "kiloPass.getMobileStoreProducts": { + "path": "kiloPass.getMobileStoreProducts", + "kind": "query", + "summary": "Get the available Kilo Pass products and app store account token for in-app / mobile store purchases.", + "inputSchema": {}, + "tags": [ + "kilopass", + "getmobilestoreproducts" + ], + "searchBlob": "kiloPass.getMobileStoreProducts Get the available Kilo Pass products and app store account token for in-app / mobile store purchases. kilopass getmobilestoreproducts" + }, + "kiloPass.getPurchasePresentation": { + "path": "kiloPass.getPurchasePresentation", + "kind": "query", + "summary": "Get the purchase presentation details (pricing, terms) for a Kilo Pass product on a given platform, storefront, and program.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "platform": { + "anyOf": [ + { + "type": "string", + "enum": [ + "ios", + "android" + ] + }, + { + "type": "null" + } + ] + }, + "storefront": { + "anyOf": [ + { + "type": "string", + "enum": [ + "app_store", + "play", + "web" + ] + }, + { + "type": "null" + } + ] + }, + "product": { + "type": "string", + "enum": [ + "kilo_pass", + "credits" + ] + }, + "program": { + "anyOf": [ + { + "type": "string", + "maxLength": 64 + }, + { + "type": "null" + } + ] + }, + "supportsNativePlayKiloPass": { + "type": "boolean" + } + }, + "required": [ + "product" + ] + }, + "tags": [ + "kilopass", + "getpurchasepresentation", + "platform", + "storefront", + "product", + "program", + "supportsnativeplaykilopass" + ], + "searchBlob": "kiloPass.getPurchasePresentation Get the purchase presentation details (pricing, terms) for a Kilo Pass product on a given platform, storefront, and program. kilopass getpurchasepresentation platform storefront product program supportsnativeplaykilopass platform storefront product program supportsNativePlayKiloPass" + }, + "kiloPass.getReferralRewardSummary": { + "path": "kiloPass.getReferralRewardSummary", + "kind": "query", + "summary": "Get the user's Kilo Pass referral rewards summary, including totals for earned, pending, and applied rewards and how close they are to the referrer reward cap.", + "inputSchema": {}, + "tags": [ + "kilopass", + "getreferralrewardsummary" + ], + "searchBlob": "kiloPass.getReferralRewardSummary Get the user's Kilo Pass referral rewards summary, including totals for earned, pending, and applied rewards and how close they are to the referrer reward cap. kilopass getreferralrewardsummary" + }, + "kiloPass.getScheduledChange": { + "path": "kiloPass.getScheduledChange", + "kind": "query", + "summary": "Get the user's scheduled Kilo Pass tier or cadence change, reconciling overdue schedule status with Stripe when needed.", + "inputSchema": {}, + "tags": [ + "kilopass", + "getscheduledchange" + ], + "searchBlob": "kiloPass.getScheduledChange Get the user's scheduled Kilo Pass tier or cadence change, reconciling overdue schedule status with Stripe when needed. kilopass getscheduledchange" + }, + "kiloPass.getSidebarPromoEligibility": { + "path": "kiloPass.getSidebarPromoEligibility", + "kind": "query", + "summary": "Check whether the user should see a Kilo Pass promo banner in the sidebar (no active subscription or an expired Stripe subscription).", + "inputSchema": {}, + "tags": [ + "kilopass", + "getsidebarpromoeligibility" + ], + "searchBlob": "kiloPass.getSidebarPromoEligibility Check whether the user should see a Kilo Pass promo banner in the sidebar (no active subscription or an expired Stripe subscription). kilopass getsidebarpromoeligibility" + }, + "kiloPass.getState": { + "path": "kiloPass.getState", + "kind": "query", + "summary": "Get the user's current Kilo Pass subscription state, including billing period, next billing date, spend window, and whether they qualify for a first-month promo.", + "inputSchema": {}, + "tags": [ + "kilopass", + "getstate" + ], + "searchBlob": "kiloPass.getState Get the user's current Kilo Pass subscription state, including billing period, next billing date, spend window, and whether they qualify for a first-month promo. kilopass getstate" + }, + "kiloclaw.controllerVersion": { + "path": "kiloclaw.controllerVersion", + "kind": "query", + "summary": "Get the controller software version running on the user's active KiloClaw instance", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "controllerversion" + ], + "searchBlob": "kiloclaw.controllerVersion Get the controller software version running on the user's active KiloClaw instance kiloclaw controllerversion" + }, + "kiloclaw.fileTree": { + "path": "kiloclaw.fileTree", + "kind": "query", + "summary": "List the directory and file tree of the user's active KiloClaw instance, optionally at a given path", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 4096 + } + } + }, + "tags": [ + "kiloclaw", + "filetree", + "path" + ], + "searchBlob": "kiloclaw.fileTree List the directory and file tree of the user's active KiloClaw instance, optionally at a given path kiloclaw filetree path path" + }, + "kiloclaw.gatewayReady": { + "path": "kiloclaw.gatewayReady", + "kind": "query", + "summary": "Check whether the gateway is ready for the user's active KiloClaw instance", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "gatewayready" + ], + "searchBlob": "kiloclaw.gatewayReady Check whether the gateway is ready for the user's active KiloClaw instance kiloclaw gatewayready" + }, + "kiloclaw.gatewayStatus": { + "path": "kiloclaw.gatewayStatus", + "kind": "query", + "summary": "Get the gateway connection or control status for the user's active KiloClaw instance", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "gatewaystatus" + ], + "searchBlob": "kiloclaw.gatewayStatus Get the gateway connection or control status for the user's active KiloClaw instance kiloclaw gatewaystatus" + }, + "kiloclaw.getActiveInstanceId": { + "path": "kiloclaw.getActiveInstanceId", + "kind": "query", + "summary": "Return the id of the user's active KiloClaw instance, or null if none exists", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getactiveinstanceid" + ], + "searchBlob": "kiloclaw.getActiveInstanceId Return the id of the user's active KiloClaw instance, or null if none exists kiloclaw getactiveinstanceid" + }, + "kiloclaw.getActivePersonalBillingStatus": { + "path": "kiloclaw.getActivePersonalBillingStatus", + "kind": "query", + "summary": "Get the user's current active personal KiloClaw billing status", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getactivepersonalbillingstatus" + ], + "searchBlob": "kiloclaw.getActivePersonalBillingStatus Get the user's current active personal KiloClaw billing status kiloclaw getactivepersonalbillingstatus" + }, + "kiloclaw.getAgent": { + "path": "kiloclaw.getAgent", + "kind": "query", + "summary": "Fetch the details of a single agent by id from the user's active KiloClaw instance", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "agentId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + }, + "required": [ + "agentId" + ] + }, + "tags": [ + "kiloclaw", + "getagent", + "agentid" + ], + "searchBlob": "kiloclaw.getAgent Fetch the details of a single agent by id from the user's active KiloClaw instance kiloclaw getagent agentid agentId" + }, + "kiloclaw.getBillingHistory": { + "path": "kiloclaw.getBillingHistory", + "kind": "query", + "summary": "Get paginated billing and invoice history for the user's personal KiloClaw subscription for a given instance", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "instanceId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "cursor": { + "type": "string" + } + }, + "required": [ + "instanceId" + ] + }, + "tags": [ + "kiloclaw", + "getbillinghistory", + "instanceid", + "cursor" + ], + "searchBlob": "kiloclaw.getBillingHistory Get paginated billing and invoice history for the user's personal KiloClaw subscription for a given instance kiloclaw getbillinghistory instanceid cursor instanceId cursor" + }, + "kiloclaw.getBillingStatus": { + "path": "kiloclaw.getBillingStatus", + "kind": "query", + "summary": "Get the user's personal KiloClaw billing status", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getbillingstatus" + ], + "searchBlob": "kiloclaw.getBillingStatus Get the user's personal KiloClaw billing status kiloclaw getbillingstatus" + }, + "kiloclaw.getChangelog": { + "path": "kiloclaw.getChangelog", + "kind": "query", + "summary": "List the latest KiloClaw changelog or release notes entries shown in the app", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getchangelog" + ], + "searchBlob": "kiloclaw.getChangelog List the latest KiloClaw changelog or release notes entries shown in the app kiloclaw getchangelog" + }, + "kiloclaw.getChannelCatalog": { + "path": "kiloclaw.getChannelCatalog", + "kind": "query", + "summary": "Get the catalog of available messaging channels with their config fields and which ones are already configured", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getchannelcatalog" + ], + "searchBlob": "kiloclaw.getChannelCatalog Get the catalog of available messaging channels with their config fields and which ones are already configured kiloclaw getchannelcatalog" + }, + "kiloclaw.getConfig": { + "path": "kiloclaw.getConfig", + "kind": "query", + "summary": "Fetch the full runtime configuration of the user's active KiloClaw instance", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getconfig" + ], + "searchBlob": "kiloclaw.getConfig Fetch the full runtime configuration of the user's active KiloClaw instance kiloclaw getconfig" + }, + "kiloclaw.getDiskUsage": { + "path": "kiloclaw.getDiskUsage", + "kind": "query", + "summary": "Get the disk usage of the user's active KiloClaw instance sandbox", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getdiskusage" + ], + "searchBlob": "kiloclaw.getDiskUsage Get the disk usage of the user's active KiloClaw instance sandbox kiloclaw getdiskusage" + }, + "kiloclaw.getEarlybirdStatus": { + "path": "kiloclaw.getEarlybirdStatus", + "kind": "query", + "summary": "Check whether the user purchased the KiloClaw earlybird offer", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getearlybirdstatus" + ], + "searchBlob": "kiloclaw.getEarlybirdStatus Check whether the user purchased the KiloClaw earlybird offer kiloclaw getearlybirdstatus" + }, + "kiloclaw.getGoogleSetupCommand": { + "path": "kiloclaw.getGoogleSetupCommand", + "kind": "query", + "summary": "Generate the docker run command the user executes to set up Google or Gmail integration for their instance", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getgooglesetupcommand" + ], + "searchBlob": "kiloclaw.getGoogleSetupCommand Generate the docker run command the user executes to set up Google or Gmail integration for their instance kiloclaw getgooglesetupcommand" + }, + "kiloclaw.getKiloCliRunStatus": { + "path": "kiloclaw.getKiloCliRunStatus", + "kind": "query", + "summary": "Get the status of a specific kilo CLI run by its run id", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "runId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "runId" + ] + }, + "tags": [ + "kiloclaw", + "getkiloclirunstatus", + "runid" + ], + "searchBlob": "kiloclaw.getKiloCliRunStatus Get the status of a specific kilo CLI run by its run id kiloclaw getkiloclirunstatus runid runId" + }, + "kiloclaw.getMorningBriefingStatus": { + "path": "kiloclaw.getMorningBriefingStatus", + "kind": "query", + "summary": "Check the status of the daily morning briefing for the user's active KiloClaw instance", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getmorningbriefingstatus" + ], + "searchBlob": "kiloclaw.getMorningBriefingStatus Check the status of the daily morning briefing for the user's active KiloClaw instance kiloclaw getmorningbriefingstatus" + }, + "kiloclaw.getMyPin": { + "path": "kiloclaw.getMyPin", + "kind": "query", + "summary": "Get the pinned version for the user's active KiloClaw instance and whether the user pinned it themselves", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getmypin" + ], + "searchBlob": "kiloclaw.getMyPin Get the pinned version for the user's active KiloClaw instance and whether the user pinned it themselves kiloclaw getmypin" + }, + "kiloclaw.getNavState": { + "path": "kiloclaw.getNavState", + "kind": "query", + "summary": "Check whether the user has an active KiloClaw instance and an active personal subscription to drive navigation UI state", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getnavstate" + ], + "searchBlob": "kiloclaw.getNavState Check whether the user has an active KiloClaw instance and an active personal subscription to drive navigation UI state kiloclaw getnavstate" + }, + "kiloclaw.getPersonalBillingSummary": { + "path": "kiloclaw.getPersonalBillingSummary", + "kind": "query", + "summary": "Get a summarized view of the user's personal KiloClaw billing status", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getpersonalbillingsummary" + ], + "searchBlob": "kiloclaw.getPersonalBillingSummary Get a summarized view of the user's personal KiloClaw billing status kiloclaw getpersonalbillingsummary" + }, + "kiloclaw.getSecretCatalog": { + "path": "kiloclaw.getSecretCatalog", + "kind": "query", + "summary": "Get the catalog of tools or secrets with their config fields and which ones are already configured", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getsecretcatalog" + ], + "searchBlob": "kiloclaw.getSecretCatalog Get the catalog of tools or secrets with their config fields and which ones are already configured kiloclaw getsecretcatalog" + }, + "kiloclaw.getStatus": { + "path": "kiloclaw.getStatus", + "kind": "query", + "summary": "Fetch the overall dashboard status for the user's active KiloClaw instance, including worker URL, name, inbound email address, and scheduled action", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "getstatus" + ], + "searchBlob": "kiloclaw.getStatus Fetch the overall dashboard status for the user's active KiloClaw instance, including worker URL, name, inbound email address, and scheduled action kiloclaw getstatus" + }, + "kiloclaw.getSubscriptionDetail": { + "path": "kiloclaw.getSubscriptionDetail", + "kind": "query", + "summary": "Get the full details of a single personal KiloClaw subscription for a given instance", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "instanceId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "instanceId" + ] + }, + "tags": [ + "kiloclaw", + "getsubscriptiondetail", + "instanceid" + ], + "searchBlob": "kiloclaw.getSubscriptionDetail Get the full details of a single personal KiloClaw subscription for a given instance kiloclaw getsubscriptiondetail instanceid instanceId" + }, + "kiloclaw.latestVersion": { + "path": "kiloclaw.latestVersion", + "kind": "query", + "summary": "Get the newest available KiloClaw version, optionally relative to the user's active instance and current image tag", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "currentImageTag": { + "type": "string", + "minLength": 1 + } + } + }, + "tags": [ + "kiloclaw", + "latestversion", + "currentimagetag" + ], + "searchBlob": "kiloclaw.latestVersion Get the newest available KiloClaw version, optionally relative to the user's active instance and current image tag kiloclaw latestversion currentimagetag currentImageTag" + }, + "kiloclaw.listAgents": { + "path": "kiloclaw.listAgents", + "kind": "query", + "summary": "List the agents defined in the user's active KiloClaw instance", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "listagents" + ], + "searchBlob": "kiloclaw.listAgents List the agents defined in the user's active KiloClaw instance kiloclaw listagents" + }, + "kiloclaw.listAllInstances": { + "path": "kiloclaw.listAllInstances", + "kind": "query", + "summary": "List all of the user's active KiloClaw instances with their organization names and live worker status, bot name, and bot emoji", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "listallinstances" + ], + "searchBlob": "kiloclaw.listAllInstances List all of the user's active KiloClaw instances with their organization names and live worker status, bot name, and bot emoji kiloclaw listallinstances" + }, + "kiloclaw.listAvailableVersions": { + "path": "kiloclaw.listAvailableVersions", + "kind": "query", + "summary": "List available KiloClaw image versions and variants with pagination", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "offset": { + "default": 0, + "type": "number", + "minimum": 0 + }, + "limit": { + "default": 25, + "type": "number", + "minimum": 1, + "maximum": 100 + } + } + }, + "tags": [ + "kiloclaw", + "listavailableversions", + "offset", + "limit" + ], + "searchBlob": "kiloclaw.listAvailableVersions List available KiloClaw image versions and variants with pagination kiloclaw listavailableversions offset limit offset limit" + }, + "kiloclaw.listDevicePairingRequests": { + "path": "kiloclaw.listDevicePairingRequests", + "kind": "query", + "summary": "List pending device pairing requests for the user's active KiloClaw instance, optionally forcing a refresh", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "refresh": { + "type": "boolean" + } + } + }, + "tags": [ + "kiloclaw", + "listdevicepairingrequests", + "refresh" + ], + "searchBlob": "kiloclaw.listDevicePairingRequests List pending device pairing requests for the user's active KiloClaw instance, optionally forcing a refresh kiloclaw listdevicepairingrequests refresh refresh" + }, + "kiloclaw.listKiloCliRuns": { + "path": "kiloclaw.listKiloCliRuns", + "kind": "query", + "summary": "List the user's most recent kilo CLI runs, newest first, with an optional result limit", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "limit": { + "default": 10, + "type": "number", + "minimum": 1, + "maximum": 50 + } + } + }, + "tags": [ + "kiloclaw", + "listkilocliruns", + "limit" + ], + "searchBlob": "kiloclaw.listKiloCliRuns List the user's most recent kilo CLI runs, newest first, with an optional result limit kiloclaw listkilocliruns limit limit" + }, + "kiloclaw.listPairingRequests": { + "path": "kiloclaw.listPairingRequests", + "kind": "query", + "summary": "List pending pairing or connection requests for the user's active KiloClaw instance, optionally forcing a refresh", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "refresh": { + "type": "boolean" + } + } + }, + "tags": [ + "kiloclaw", + "listpairingrequests", + "refresh" + ], + "searchBlob": "kiloclaw.listPairingRequests List pending pairing or connection requests for the user's active KiloClaw instance, optionally forcing a refresh kiloclaw listpairingrequests refresh refresh" + }, + "kiloclaw.listPersonalSubscriptions": { + "path": "kiloclaw.listPersonalSubscriptions", + "kind": "query", + "summary": "List the user's personal KiloClaw subscriptions and whether a commit plan can currently be selected", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "listpersonalsubscriptions" + ], + "searchBlob": "kiloclaw.listPersonalSubscriptions List the user's personal KiloClaw subscriptions and whether a commit plan can currently be selected kiloclaw listpersonalsubscriptions" + }, + "kiloclaw.myEarlyAccess": { + "path": "kiloclaw.myEarlyAccess", + "kind": "query", + "summary": "Check whether the current user has KiloClaw early access enabled", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "myearlyaccess" + ], + "searchBlob": "kiloclaw.myEarlyAccess Check whether the current user has KiloClaw early access enabled kiloclaw myearlyaccess" + }, + "kiloclaw.readFile": { + "path": "kiloclaw.readFile", + "kind": "query", + "summary": "Read the contents of a file at a given path in the user's active KiloClaw instance", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 4096 + } + }, + "required": [ + "path" + ] + }, + "tags": [ + "kiloclaw", + "readfile", + "path" + ], + "searchBlob": "kiloclaw.readFile Read the contents of a file at a given path in the user's active KiloClaw instance kiloclaw readfile path path" + }, + "kiloclaw.readMorningBriefing": { + "path": "kiloclaw.readMorningBriefing", + "kind": "query", + "summary": "Read the content of today's or yesterday's morning briefing from the user's active KiloClaw instance", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "day": { + "type": "string", + "enum": [ + "today", + "yesterday" + ] + } + }, + "required": [ + "day" + ] + }, + "tags": [ + "kiloclaw", + "readmorningbriefing", + "day" + ], + "searchBlob": "kiloclaw.readMorningBriefing Read the content of today's or yesterday's morning briefing from the user's active KiloClaw instance kiloclaw readmorningbriefing day day" + }, + "kiloclaw.serviceDegraded": { + "path": "kiloclaw.serviceDegraded", + "kind": "query", + "summary": "Check whether the KiloClaw service is currently reporting a degraded status or outage", + "inputSchema": {}, + "tags": [ + "kiloclaw", + "servicedegraded" + ], + "searchBlob": "kiloclaw.serviceDegraded Check whether the KiloClaw service is currently reporting a degraded status or outage kiloclaw servicedegraded" + }, + "linear.getInstallation": { + "path": "linear.getInstallation", + "kind": "query", + "summary": "Check whether the Linear integration is installed for the current or specified organization, returning installation status and details like workspace name, scopes, and configured model.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "linear", + "getinstallation", + "organizationid" + ], + "searchBlob": "linear.getInstallation Check whether the Linear integration is installed for the current or specified organization, returning installation status and details like workspace name, scopes, and configured model. linear getinstallation organizationid organizationId" + }, + "mcpGateway.getOrganization": { + "path": "mcpGateway.getOrganization", + "kind": "query", + "summary": "Fetches details of a single MCP gateway configuration belonging to an organization by config ID, restricted to organization managers.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "configId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId", + "configId" + ] + }, + "tags": [ + "mcpgateway", + "getorganization", + "organizationid", + "configid" + ], + "searchBlob": "mcpGateway.getOrganization Fetches details of a single MCP gateway configuration belonging to an organization by config ID, restricted to organization managers. mcpgateway getorganization organizationid configid organizationId configId" + }, + "mcpGateway.getPersonal": { + "path": "mcpGateway.getPersonal", + "kind": "query", + "summary": "Fetches details of a single personal MCP gateway configuration owned by the current user by its config ID.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "configId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "configId" + ] + }, + "tags": [ + "mcpgateway", + "getpersonal", + "configid" + ], + "searchBlob": "mcpGateway.getPersonal Fetches details of a single personal MCP gateway configuration owned by the current user by its config ID. mcpgateway getpersonal configid configId" + }, + "mcpGateway.listOrganization": { + "path": "mcpGateway.listOrganization", + "kind": "query", + "summary": "Lists MCP gateway configurations for an organization, accessible only to organization managers, returning the org's configured servers.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "mcpgateway", + "listorganization", + "organizationid" + ], + "searchBlob": "mcpGateway.listOrganization Lists MCP gateway configurations for an organization, accessible only to organization managers, returning the org's configured servers. mcpgateway listorganization organizationid organizationId" + }, + "mcpGateway.listPersonal": { + "path": "mcpGateway.listPersonal", + "kind": "query", + "summary": "Lists MCP gateway configurations owned by the current user (personal scope), returning all servers the user has configured.", + "inputSchema": {}, + "tags": [ + "mcpgateway", + "listpersonal" + ], + "searchBlob": "mcpGateway.listPersonal Lists MCP gateway configurations owned by the current user (personal scope), returning all servers the user has configured. mcpgateway listpersonal" + }, + "mcpGatewayAuthorizations.listMine": { + "path": "mcpGatewayAuthorizations.listMine", + "kind": "query", + "summary": "List the MCP gateway authorizations granted to the current user, optionally filtered by personal vs organization scope or a specific organization, returning active grants with client, connection, context, and scope details.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "ownerScope": { + "type": "string", + "enum": [ + "personal", + "organization" + ] + }, + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "mcpgatewayauthorizations", + "listmine", + "ownerscope", + "organizationid" + ], + "searchBlob": "mcpGatewayAuthorizations.listMine List the MCP gateway authorizations granted to the current user, optionally filtered by personal vs organization scope or a specific organization, returning active grants with client, connection, context, and scope details. mcpgatewayauthorizations listmine ownerscope organizationid ownerScope organizationId" + }, + "modelPreferences.get": { + "path": "modelPreferences.get", + "kind": "query", + "summary": "Fetch the current user's favorite model IDs and last selected model, filtered to only models they are permitted to use in their organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "minLength": 1 + } + } + }, + "tags": [ + "modelpreferences", + "get", + "organizationid" + ], + "searchBlob": "modelPreferences.get Fetch the current user's favorite model IDs and last selected model, filtered to only models they are permitted to use in their organization. modelpreferences get organizationid organizationId" + }, + "models.list": { + "path": "models.list", + "kind": "query", + "summary": "List all available OpenRouter AI models with their ids, names, vision support, and which ones are marked as preferred.", + "inputSchema": {}, + "tags": [ + "models", + "list" + ], + "searchBlob": "models.list List all available OpenRouter AI models with their ids, names, vision support, and which ones are marked as preferred. models list" + }, + "moderation.getReportReceipt": { + "path": "moderation.getReportReceipt", + "kind": "query", + "summary": "Fetch the receipt details for a user's content report, including its triage status and appeal status.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "receiptId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "receiptId" + ] + }, + "tags": [ + "moderation", + "getreportreceipt", + "receiptid" + ], + "searchBlob": "moderation.getReportReceipt Fetch the receipt details for a user's content report, including its triage status and appeal status. moderation getreportreceipt receiptid receiptId" + }, + "moderation.getTermsStatus": { + "path": "moderation.getTermsStatus", + "kind": "query", + "summary": "Check whether the current user has accepted the latest UGC terms, showing the accepted version and age posture.", + "inputSchema": {}, + "tags": [ + "moderation", + "gettermsstatus" + ], + "searchBlob": "moderation.getTermsStatus Check whether the current user has accepted the latest UGC terms, showing the accepted version and age posture. moderation gettermsstatus" + }, + "moderation.listHiddenUsers": { + "path": "moderation.listHiddenUsers", + "kind": "query", + "summary": "List the GitHub logins of all users the current user has blocked and muted.", + "inputSchema": {}, + "tags": [ + "moderation", + "listhiddenusers" + ], + "searchBlob": "moderation.listHiddenUsers List the GitHub logins of all users the current user has blocked and muted. moderation listhiddenusers" + }, + "organizations.admin.creditTransactions": { + "path": "organizations.admin.creditTransactions", + "kind": "query", + "summary": "Admin lookup of all credit transactions for an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "admin", + "credittransactions", + "organizationid" + ], + "searchBlob": "organizations.admin.creditTransactions Admin lookup of all credit transactions for an organization. organizations admin credittransactions organizationid organizationId" + }, + "organizations.admin.getDetails": { + "path": "organizations.admin.getDetails", + "kind": "query", + "summary": "Admin view of a single organization's details including credit totals and counts of active platform integrations.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "admin", + "getdetails", + "organizationid" + ], + "searchBlob": "organizations.admin.getDetails Admin view of a single organization's details including credit totals and counts of active platform integrations. organizations admin getdetails organizationid organizationId" + }, + "organizations.admin.getHierarchy": { + "path": "organizations.admin.getHierarchy", + "kind": "query", + "summary": "Get an organization's parent, ancestor chain, and child organizations for admin views.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "admin", + "gethierarchy", + "organizationid" + ], + "searchBlob": "organizations.admin.getHierarchy Get an organization's parent, ancestor chain, and child organizations for admin views. organizations admin gethierarchy organizationid organizationId" + }, + "organizations.admin.getKiloPassSummary": { + "path": "organizations.admin.getKiloPassSummary", + "kind": "query", + "summary": "Admin summary of an organization's Kilo Pass agreement including tier, state, cadence, and paid capacity.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "admin", + "getkilopasssummary", + "organizationid" + ], + "searchBlob": "organizations.admin.getKiloPassSummary Admin summary of an organization's Kilo Pass agreement including tier, state, cadence, and paid capacity. organizations admin getkilopasssummary organizationid organizationId" + }, + "organizations.admin.getMetrics": { + "path": "organizations.admin.getMetrics", + "kind": "query", + "summary": "Admin metrics counting active paying organizations by plan (teams/enterprise) and total seats.", + "inputSchema": {}, + "tags": [ + "organizations", + "admin", + "getmetrics" + ], + "searchBlob": "organizations.admin.getMetrics Admin metrics counting active paying organizations by plan (teams/enterprise) and total seats. organizations admin getmetrics" + }, + "organizations.admin.list": { + "path": "organizations.admin.list", + "kind": "query", + "summary": "Admin paginated list of organizations with filtering by search, plan, usage, trial, Stripe status, and integration presence.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "page": { + "default": 1, + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "limit": { + "default": 25, + "type": "integer", + "minimum": 1, + "maximum": 100000 + }, + "sortBy": { + "default": "name", + "type": "string", + "enum": [ + "name", + "microdollars_used", + "balance", + "member_count", + "plan", + "kilo_pass_tier", + "latest_stripe_status", + "subscription_amount_usd" + ] + }, + "sortOrder": { + "default": "desc", + "type": "string", + "enum": [ + "asc", + "desc" + ] + }, + "search": { + "default": "", + "type": "string" + }, + "mode": { + "default": "paying", + "type": "string", + "enum": [ + "paying", + "trial", + "all" + ] + }, + "include_deleted": { + "default": false, + "type": "boolean" + }, + "stripe_status": { + "anyOf": [ + { + "type": "string", + "enum": [ + "active", + "past_due", + "canceled", + "ended", + "incomplete", + "incomplete_expired", + "trialing", + "unpaid", + "paused" + ] + }, + { + "type": "string", + "const": "" + } + ] + }, + "plan": { + "type": "string", + "enum": [ + "enterprise", + "teams", + "" + ] + }, + "has_usage": { + "default": false, + "type": "boolean" + }, + "has_multiple_users": { + "default": false, + "type": "boolean" + }, + "trial_ending_in_future": { + "default": false, + "type": "boolean" + } + } + }, + "tags": [ + "organizations", + "admin", + "list", + "page", + "limit", + "sortby", + "sortorder", + "search", + "mode", + "include_deleted", + "stripe_status", + "plan", + "has_usage", + "has_multiple_users", + "trial_ending_in_future" + ], + "searchBlob": "organizations.admin.list Admin paginated list of organizations with filtering by search, plan, usage, trial, Stripe status, and integration presence. organizations admin list page limit sortby sortorder search mode include_deleted stripe_status plan has_usage has_multiple_users trial_ending_in_future page limit sortBy sortOrder search mode include_deleted stripe_status plan has_usage has_multiple_users trial_ending_in_future" + }, + "organizations.admin.nextCreditExpiration": { + "path": "organizations.admin.nextCreditExpiration", + "kind": "query", + "summary": "Get when an organization's next credits expire and the amount expiring at that time.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "admin", + "nextcreditexpiration", + "organizationid" + ], + "searchBlob": "organizations.admin.nextCreditExpiration Get when an organization's next credits expire and the amount expiring at that time. organizations admin nextcreditexpiration organizationid organizationId" + }, + "organizations.admin.search": { + "path": "organizations.admin.search", + "kind": "query", + "summary": "Admin search for organizations by name or ID, optionally limited to direct children eligible as sub-organizations.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "search": { + "type": "string", + "minLength": 1 + }, + "limit": { + "default": 10, + "type": "integer", + "minimum": 1, + "maximum": 50 + }, + "childOfOrganizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "search" + ] + }, + "tags": [ + "organizations", + "admin", + "search", + "limit", + "childoforganizationid" + ], + "searchBlob": "organizations.admin.search Admin search for organizations by name or ID, optionally limited to direct children eligible as sub-organizations. organizations admin search limit childoforganizationid search limit childOfOrganizationId" + }, + "organizations.appBuilder.canMigrateToGitHub": { + "path": "organizations.appBuilder.canMigrateToGitHub", + "kind": "query", + "summary": "Check whether an App Builder project can be migrated to GitHub.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "appbuilder", + "canmigratetogithub", + "organizationid" + ], + "searchBlob": "organizations.appBuilder.canMigrateToGitHub Check whether an App Builder project can be migrated to GitHub. organizations appbuilder canmigratetogithub organizationid organizationId" + }, + "organizations.appBuilder.checkEligibility": { + "path": "organizations.appBuilder.checkEligibility", + "kind": "query", + "summary": "Check whether a user in the organization is eligible to use App Builder based on their credit balance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "appbuilder", + "checkeligibility", + "organizationid" + ], + "searchBlob": "organizations.appBuilder.checkEligibility Check whether a user in the organization is eligible to use App Builder based on their credit balance. organizations appbuilder checkeligibility organizationid organizationId" + }, + "organizations.appBuilder.getLegacySessionMessages": { + "path": "organizations.appBuilder.getLegacySessionMessages", + "kind": "query", + "summary": "Get messages from a legacy cloud agent session associated with an App Builder project.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "appbuilder", + "getlegacysessionmessages", + "organizationid" + ], + "searchBlob": "organizations.appBuilder.getLegacySessionMessages Get messages from a legacy cloud agent session associated with an App Builder project. organizations appbuilder getlegacysessionmessages organizationid organizationId" + }, + "organizations.appBuilder.getPreviewUrl": { + "path": "organizations.appBuilder.getPreviewUrl", + "kind": "query", + "summary": "Get the preview URL for an organization's App Builder project.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "appbuilder", + "getpreviewurl", + "organizationid" + ], + "searchBlob": "organizations.appBuilder.getPreviewUrl Get the preview URL for an organization's App Builder project. organizations appbuilder getpreviewurl organizationid organizationId" + }, + "organizations.appBuilder.getProject": { + "path": "organizations.appBuilder.getProject", + "kind": "query", + "summary": "Get App Builder project details for an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "appbuilder", + "getproject", + "organizationid" + ], + "searchBlob": "organizations.appBuilder.getProject Get App Builder project details for an organization. organizations appbuilder getproject organizationid organizationId" + }, + "organizations.appBuilder.listProjects": { + "path": "organizations.appBuilder.listProjects", + "kind": "query", + "summary": "List all App Builder projects belonging to an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "appbuilder", + "listprojects", + "organizationid" + ], + "searchBlob": "organizations.appBuilder.listProjects List all App Builder projects belonging to an organization. organizations appbuilder listprojects organizationid organizationId" + }, + "organizations.appBuilder.listUserProjects": { + "path": "organizations.appBuilder.listUserProjects", + "kind": "query", + "summary": "List App Builder projects within the organization that were created by the current user.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "appbuilder", + "listuserprojects", + "organizationid" + ], + "searchBlob": "organizations.appBuilder.listUserProjects List App Builder projects within the organization that were created by the current user. organizations appbuilder listuserprojects organizationid organizationId" + }, + "organizations.auditLogs.getActionTypes": { + "path": "organizations.auditLogs.getActionTypes", + "kind": "query", + "summary": "Get the list of all possible audit log action types.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "auditlogs", + "getactiontypes", + "organizationid" + ], + "searchBlob": "organizations.auditLogs.getActionTypes Get the list of all possible audit log action types. organizations auditlogs getactiontypes organizationid organizationId" + }, + "organizations.auditLogs.getSummary": { + "path": "organizations.auditLogs.getSummary", + "kind": "query", + "summary": "Get summary statistics for an organization's audit log such as total events and earliest/latest timestamps.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "auditlogs", + "getsummary", + "organizationid" + ], + "searchBlob": "organizations.auditLogs.getSummary Get summary statistics for an organization's audit log such as total events and earliest/latest timestamps. organizations auditlogs getsummary organizationid organizationId" + }, + "organizations.auditLogs.list": { + "path": "organizations.auditLogs.list", + "kind": "query", + "summary": "List an organization's audit log events with filters for action, actor, time range, and fuzzy text search, plus pagination.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "auditlogs", + "list", + "organizationid" + ], + "searchBlob": "organizations.auditLogs.list List an organization's audit log events with filters for action, actor, time range, and fuzzy text search, plus pagination. organizations auditlogs list organizationid organizationId" + }, + "organizations.autoFix.getAutoFixConfig": { + "path": "organizations.autoFix.getAutoFixConfig", + "kind": "query", + "summary": "Get the auto-fix configuration for the organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "autofix", + "getautofixconfig", + "organizationid" + ], + "searchBlob": "organizations.autoFix.getAutoFixConfig Get the auto-fix configuration for the organization. organizations autofix getautofixconfig organizationid organizationId" + }, + "organizations.autoFix.listGitHubRepositories": { + "path": "organizations.autoFix.listGitHubRepositories", + "kind": "query", + "summary": "List GitHub repositories available to the auto-fix feature.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "autofix", + "listgithubrepositories", + "organizationid" + ], + "searchBlob": "organizations.autoFix.listGitHubRepositories List GitHub repositories available to the auto-fix feature. organizations autofix listgithubrepositories organizationid organizationId" + }, + "organizations.autoFix.listTickets": { + "path": "organizations.autoFix.listTickets", + "kind": "query", + "summary": "List auto-fix tickets with optional filtering by status, classification, repository, and pagination.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "autofix", + "listtickets", + "organizationid" + ], + "searchBlob": "organizations.autoFix.listTickets List auto-fix tickets with optional filtering by status, classification, repository, and pagination. organizations autofix listtickets organizationid organizationId" + }, + "organizations.autoTopUp.getConfig": { + "path": "organizations.autoTopUp.getConfig", + "kind": "query", + "summary": "Get the organization's auto top-up configuration including enabled state, amount, and payment method.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "autotopup", + "getconfig", + "organizationid" + ], + "searchBlob": "organizations.autoTopUp.getConfig Get the organization's auto top-up configuration including enabled state, amount, and payment method. organizations autotopup getconfig organizationid organizationId" + }, + "organizations.autoTriage.getAutoTriageConfig": { + "path": "organizations.autoTriage.getAutoTriageConfig", + "kind": "query", + "summary": "Get the auto-triage configuration for the organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "autotriage", + "getautotriageconfig", + "organizationid" + ], + "searchBlob": "organizations.autoTriage.getAutoTriageConfig Get the auto-triage configuration for the organization. organizations autotriage getautotriageconfig organizationid organizationId" + }, + "organizations.autoTriage.getGitHubStatus": { + "path": "organizations.autoTriage.getGitHubStatus", + "kind": "query", + "summary": "Check GitHub integration status for the auto-triage feature.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "autotriage", + "getgithubstatus", + "organizationid" + ], + "searchBlob": "organizations.autoTriage.getGitHubStatus Check GitHub integration status for the auto-triage feature. organizations autotriage getgithubstatus organizationid organizationId" + }, + "organizations.autoTriage.listGitHubRepositories": { + "path": "organizations.autoTriage.listGitHubRepositories", + "kind": "query", + "summary": "List GitHub repositories available for auto-triage scanning.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "autotriage", + "listgithubrepositories", + "organizationid" + ], + "searchBlob": "organizations.autoTriage.listGitHubRepositories List GitHub repositories available for auto-triage scanning. organizations autotriage listgithubrepositories organizationid organizationId" + }, + "organizations.autoTriage.listTickets": { + "path": "organizations.autoTriage.listTickets", + "kind": "query", + "summary": "List issue tickets processed by the auto-triage feature.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "autotriage", + "listtickets", + "organizationid" + ], + "searchBlob": "organizations.autoTriage.listTickets List issue tickets processed by the auto-triage feature. organizations autotriage listtickets organizationid organizationId" + }, + "organizations.bitbucket.getStatus": { + "path": "organizations.bitbucket.getStatus", + "kind": "query", + "summary": "Get the organization's Bitbucket integration status including workspace access token and OAuth connection state.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "bitbucket", + "getstatus", + "organizationid" + ], + "searchBlob": "organizations.bitbucket.getStatus Get the organization's Bitbucket integration status including workspace access token and OAuth connection state. organizations bitbucket getstatus organizationid organizationId" + }, + "organizations.childOrganizations": { + "path": "organizations.childOrganizations", + "kind": "query", + "summary": "List the child organizations of an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "childorganizations", + "organizationid" + ], + "searchBlob": "organizations.childOrganizations List the child organizations of an organization. organizations childorganizations organizationid organizationId" + }, + "organizations.cloudAgentNext.checkEligibility": { + "path": "organizations.cloudAgentNext.checkEligibility", + "kind": "query", + "summary": "Check whether a user in the organization is eligible to use Cloud Agent based on their credit balance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "cloudagentnext", + "checkeligibility", + "organizationid" + ], + "searchBlob": "organizations.cloudAgentNext.checkEligibility Check whether a user in the organization is eligible to use Cloud Agent based on their credit balance. organizations cloudagentnext checkeligibility organizationid organizationId" + }, + "organizations.cloudAgentNext.getComputeBillingStatus": { + "path": "organizations.cloudAgentNext.getComputeBillingStatus", + "kind": "query", + "summary": "Get the compute billing status for an organization's cloud agent session.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "cloudagentnext", + "getcomputebillingstatus", + "organizationid" + ], + "searchBlob": "organizations.cloudAgentNext.getComputeBillingStatus Get the compute billing status for an organization's cloud agent session. organizations cloudagentnext getcomputebillingstatus organizationid organizationId" + }, + "organizations.cloudAgentNext.getSandboxStatus": { + "path": "organizations.cloudAgentNext.getSandboxStatus", + "kind": "query", + "summary": "Get the sandbox status of an organization cloud agent session.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cloudAgentSessionId": { + "type": "string", + "allOf": [ + { + "pattern": "^(agent|workspace)_[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" + }, + { + "pattern": "^workspace_.*" + } + ] + }, + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "cloudAgentSessionId", + "organizationId" + ], + "additionalProperties": false + }, + "tags": [ + "organizations", + "cloudagentnext", + "getsandboxstatus", + "cloudagentsessionid", + "organizationid" + ], + "searchBlob": "organizations.cloudAgentNext.getSandboxStatus Get the sandbox status of an organization cloud agent session. organizations cloudagentnext getsandboxstatus cloudagentsessionid organizationid cloudAgentSessionId organizationId" + }, + "organizations.cloudAgentNext.getSession": { + "path": "organizations.cloudAgentNext.getSession", + "kind": "query", + "summary": "Get details of an organization cloud agent session by session ID.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "cloudagentnext", + "getsession", + "organizationid" + ], + "searchBlob": "organizations.cloudAgentNext.getSession Get details of an organization cloud agent session by session ID. organizations cloudagentnext getsession organizationid organizationId" + }, + "organizations.cloudAgentNext.getWorktreeChanges": { + "path": "organizations.cloudAgentNext.getWorktreeChanges", + "kind": "query", + "summary": "Get the file changes in the worktree of an organization cloud agent session.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "cloudagentnext", + "getworktreechanges", + "organizationid" + ], + "searchBlob": "organizations.cloudAgentNext.getWorktreeChanges Get the file changes in the worktree of an organization cloud agent session. organizations cloudagentnext getworktreechanges organizationid organizationId" + }, + "organizations.cloudAgentNext.getWorktreeFile": { + "path": "organizations.cloudAgentNext.getWorktreeFile", + "kind": "query", + "summary": "Read a single file from an organization's cloud agent session worktree snapshot, returning its diff, content, and revision metadata for the expected revision.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "cloudagentnext", + "getworktreefile", + "organizationid" + ], + "searchBlob": "organizations.cloudAgentNext.getWorktreeFile Read a single file from an organization's cloud agent session worktree snapshot, returning its diff, content, and revision metadata for the expected revision. organizations cloudagentnext getworktreefile organizationid organizationId" + }, + "organizations.cloudAgentNext.listBitbucketRepositories": { + "path": "organizations.cloudAgentNext.listBitbucketRepositories", + "kind": "query", + "summary": "List Bitbucket repositories available to the organization for Cloud Agent, ordered by recent usage.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "cloudagentnext", + "listbitbucketrepositories", + "organizationid" + ], + "searchBlob": "organizations.cloudAgentNext.listBitbucketRepositories List Bitbucket repositories available to the organization for Cloud Agent, ordered by recent usage. organizations cloudagentnext listbitbucketrepositories organizationid organizationId" + }, + "organizations.cloudAgentNext.listGitHubRepositories": { + "path": "organizations.cloudAgentNext.listGitHubRepositories", + "kind": "query", + "summary": "List GitHub repositories available to the organization for Cloud Agent, ordered by recent usage.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "cloudagentnext", + "listgithubrepositories", + "organizationid" + ], + "searchBlob": "organizations.cloudAgentNext.listGitHubRepositories List GitHub repositories available to the organization for Cloud Agent, ordered by recent usage. organizations cloudagentnext listgithubrepositories organizationid organizationId" + }, + "organizations.cloudAgentNext.listGitLabRepositories": { + "path": "organizations.cloudAgentNext.listGitLabRepositories", + "kind": "query", + "summary": "List GitLab repositories available to the organization for Cloud Agent, ordered by recent usage.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "cloudagentnext", + "listgitlabrepositories", + "organizationid" + ], + "searchBlob": "organizations.cloudAgentNext.listGitLabRepositories List GitLab repositories available to the organization for Cloud Agent, ordered by recent usage. organizations cloudagentnext listgitlabrepositories organizationid organizationId" + }, + "organizations.creditTransactions": { + "path": "organizations.creditTransactions", + "kind": "query", + "summary": "Get the credit transactions for an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "credittransactions", + "organizationid" + ], + "searchBlob": "organizations.creditTransactions Get the credit transactions for an organization. organizations credittransactions organizationid organizationId" + }, + "organizations.creditTransactionsPage": { + "path": "organizations.creditTransactionsPage", + "kind": "query", + "summary": "Get a page of credit transactions for an organization using cursor pagination.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "credittransactionspage", + "organizationid" + ], + "searchBlob": "organizations.creditTransactionsPage Get a page of credit transactions for an organization using cursor pagination. organizations credittransactionspage organizationid organizationId" + }, + "organizations.deployments.checkDeploymentEligibility": { + "path": "organizations.deployments.checkDeploymentEligibility", + "kind": "query", + "summary": "Check whether an organization is allowed to create a deployment because it has previously paid.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "deployments", + "checkdeploymenteligibility", + "organizationid" + ], + "searchBlob": "organizations.deployments.checkDeploymentEligibility Check whether an organization is allowed to create a deployment because it has previously paid. organizations deployments checkdeploymenteligibility organizationid organizationId" + }, + "organizations.deployments.checkSlugAvailability": { + "path": "organizations.deployments.checkSlugAvailability", + "kind": "query", + "summary": "Check whether a deployment slug is available for use.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "deployments", + "checkslugavailability", + "organizationid" + ], + "searchBlob": "organizations.deployments.checkSlugAvailability Check whether a deployment slug is available for use. organizations deployments checkslugavailability organizationid organizationId" + }, + "organizations.deployments.getBuildEvents": { + "path": "organizations.deployments.getBuildEvents", + "kind": "query", + "summary": "Get paginated build log events for a specific deployment build.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "deployments", + "getbuildevents", + "organizationid" + ], + "searchBlob": "organizations.deployments.getBuildEvents Get paginated build log events for a specific deployment build. organizations deployments getbuildevents organizationid organizationId" + }, + "organizations.deployments.getDeployment": { + "path": "organizations.deployments.getDeployment", + "kind": "query", + "summary": "Get details for one of an organization's deployments by ID.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "deployments", + "getdeployment", + "organizationid" + ], + "searchBlob": "organizations.deployments.getDeployment Get details for one of an organization's deployments by ID. organizations deployments getdeployment organizationid organizationId" + }, + "organizations.deployments.getPasswordStatus": { + "path": "organizations.deployments.getPasswordStatus", + "kind": "query", + "summary": "Get the password protection status for a deployment, keyed by its internal worker name.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "deployments", + "getpasswordstatus", + "organizationid" + ], + "searchBlob": "organizations.deployments.getPasswordStatus Get the password protection status for a deployment, keyed by its internal worker name. organizations deployments getpasswordstatus organizationid organizationId" + }, + "organizations.deployments.listDeployments": { + "path": "organizations.deployments.listDeployments", + "kind": "query", + "summary": "List all deployments belonging to an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "deployments", + "listdeployments", + "organizationid" + ], + "searchBlob": "organizations.deployments.listDeployments List all deployments belonging to an organization. organizations deployments listdeployments organizationid organizationId" + }, + "organizations.deployments.listEnvVars": { + "path": "organizations.deployments.listEnvVars", + "kind": "query", + "summary": "List the environment variables configured for an organization's deployment.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "deployments", + "listenvvars", + "organizationid" + ], + "searchBlob": "organizations.deployments.listEnvVars List the environment variables configured for an organization's deployment. organizations deployments listenvvars organizationid organizationId" + }, + "organizations.funds.childBalances": { + "path": "organizations.funds.childBalances", + "kind": "query", + "summary": "Get the credit balances of the parent organization and each of its child organizations.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "funds", + "childbalances", + "organizationid" + ], + "searchBlob": "organizations.funds.childBalances Get the credit balances of the parent organization and each of its child organizations. organizations funds childbalances organizationid organizationId" + }, + "organizations.getCreditBlocks": { + "path": "organizations.getCreditBlocks", + "kind": "query", + "summary": "Get the organization's credits broken into blocks with amounts and expiration dates.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "getcreditblocks", + "organizationid" + ], + "searchBlob": "organizations.getCreditBlocks Get the organization's credits broken into blocks with amounts and expiration dates. organizations getcreditblocks organizationid organizationId" + }, + "organizations.getOnboardingChecklist": { + "path": "organizations.getOnboardingChecklist", + "kind": "query", + "summary": "Get the onboarding checklist state for an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "getonboardingchecklist", + "organizationid" + ], + "searchBlob": "organizations.getOnboardingChecklist Get the onboarding checklist state for an organization. organizations getonboardingchecklist organizationid organizationId" + }, + "organizations.getOnboardingSummary": { + "path": "organizations.getOnboardingSummary", + "kind": "query", + "summary": "Get an onboarding summary for an organization including credit balance and digest settings.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "getonboardingsummary", + "organizationid" + ], + "searchBlob": "organizations.getOnboardingSummary Get an onboarding summary for an organization including credit balance and digest settings. organizations getonboardingsummary organizationid organizationId" + }, + "organizations.groups.get": { + "path": "organizations.groups.get", + "kind": "query", + "summary": "Get a single organization group by ID.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "groups", + "get", + "organizationid" + ], + "searchBlob": "organizations.groups.get Get a single organization group by ID. organizations groups get organizationid organizationId" + }, + "organizations.groups.getPolicyEditorData": { + "path": "organizations.groups.getPolicyEditorData", + "kind": "query", + "summary": "Get data needed to render the policy editor for a group policy type such as model access.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "groups", + "getpolicyeditordata", + "organizationid" + ], + "searchBlob": "organizations.groups.getPolicyEditorData Get data needed to render the policy editor for a group policy type such as model access. organizations groups getpolicyeditordata organizationid organizationId" + }, + "organizations.groups.getPolicySettings": { + "path": "organizations.groups.getPolicySettings", + "kind": "query", + "summary": "Get the group policy settings for an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "groups", + "getpolicysettings", + "organizationid" + ], + "searchBlob": "organizations.groups.getPolicySettings Get the group policy settings for an organization. organizations groups getpolicysettings organizationid organizationId" + }, + "organizations.groups.list": { + "path": "organizations.groups.list", + "kind": "query", + "summary": "List the groups in an organization, showing manager or member views depending on the caller's role.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "groups", + "list", + "organizationid" + ], + "searchBlob": "organizations.groups.list List the groups in an organization, showing manager or member views depending on the caller's role. organizations groups list organizationid organizationId" + }, + "organizations.invoices": { + "path": "organizations.invoices", + "kind": "query", + "summary": "Get Stripe invoices for an organization within a time period.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "invoices", + "organizationid" + ], + "searchBlob": "organizations.invoices Get Stripe invoices for an organization within a time period. organizations invoices organizationid organizationId" + }, + "organizations.invoicesPage": { + "path": "organizations.invoicesPage", + "kind": "query", + "summary": "Get a cursor-paginated page of Stripe invoices for an organization within a time period.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "invoicespage", + "organizationid" + ], + "searchBlob": "organizations.invoicesPage Get a cursor-paginated page of Stripe invoices for an organization within a time period. organizations invoicespage organizationid organizationId" + }, + "organizations.kiloPass.billingHistory": { + "path": "organizations.kiloPass.billingHistory", + "kind": "query", + "summary": "Get paginated billing history of Kilo Pass invoices for the organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kilopass", + "billinghistory", + "organizationid" + ], + "searchBlob": "organizations.kiloPass.billingHistory Get paginated billing history of Kilo Pass invoices for the organization. organizations kilopass billinghistory organizationid organizationId" + }, + "organizations.kiloPass.detail": { + "path": "organizations.kiloPass.detail", + "kind": "query", + "summary": "Get detailed information about the organization's Kilo Pass agreement.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kilopass", + "detail", + "organizationid" + ], + "searchBlob": "organizations.kiloPass.detail Get detailed information about the organization's Kilo Pass agreement. organizations kilopass detail organizationid organizationId" + }, + "organizations.kiloPass.setup": { + "path": "organizations.kiloPass.setup", + "kind": "query", + "summary": "Get Kilo Pass setup details and requirements for the organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kilopass", + "setup", + "organizationid" + ], + "searchBlob": "organizations.kiloPass.setup Get Kilo Pass setup details and requirements for the organization. organizations kilopass setup organizationid organizationId" + }, + "organizations.kiloPass.summary": { + "path": "organizations.kiloPass.summary", + "kind": "query", + "summary": "Get a summary of the organization's Kilo Pass plan.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kilopass", + "summary", + "organizationid" + ], + "searchBlob": "organizations.kiloPass.summary Get a summary of the organization's Kilo Pass plan. organizations kilopass summary organizationid organizationId" + }, + "organizations.kiloPass.usage": { + "path": "organizations.kiloPass.usage", + "kind": "query", + "summary": "Get usage details for the organization's Kilo Pass.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kilopass", + "usage", + "organizationid" + ], + "searchBlob": "organizations.kiloPass.usage Get usage details for the organization's Kilo Pass. organizations kilopass usage organizationid organizationId" + }, + "organizations.kiloclaw.controllerVersion": { + "path": "organizations.kiloclaw.controllerVersion", + "kind": "query", + "summary": "Get the controller version running on the organization's Kilo Claw instance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "controllerversion", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.controllerVersion Get the controller version running on the organization's Kilo Claw instance. organizations kiloclaw controllerversion organizationid organizationId" + }, + "organizations.kiloclaw.fileTree": { + "path": "organizations.kiloclaw.fileTree", + "kind": "query", + "summary": "Get the file tree of the organization's Kilo Claw instance at a given path.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "filetree", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.fileTree Get the file tree of the organization's Kilo Claw instance at a given path. organizations kiloclaw filetree organizationid organizationId" + }, + "organizations.kiloclaw.gatewayReady": { + "path": "organizations.kiloclaw.gatewayReady", + "kind": "query", + "summary": "Check whether the gateway of the organization's Kilo Claw instance is ready.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "gatewayready", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.gatewayReady Check whether the gateway of the organization's Kilo Claw instance is ready. organizations kiloclaw gatewayready organizationid organizationId" + }, + "organizations.kiloclaw.gatewayStatus": { + "path": "organizations.kiloclaw.gatewayStatus", + "kind": "query", + "summary": "Get the gateway status of the organization's Kilo Claw instance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "gatewaystatus", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.gatewayStatus Get the gateway status of the organization's Kilo Claw instance. organizations kiloclaw gatewaystatus organizationid organizationId" + }, + "organizations.kiloclaw.getAgent": { + "path": "organizations.kiloclaw.getAgent", + "kind": "query", + "summary": "Get details of a single agent on the organization's Kilo Claw instance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "getagent", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.getAgent Get details of a single agent on the organization's Kilo Claw instance. organizations kiloclaw getagent organizationid organizationId" + }, + "organizations.kiloclaw.getChangelog": { + "path": "organizations.kiloclaw.getChangelog", + "kind": "query", + "summary": "Get the changelog entries for the Kilo Claw product.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "getchangelog", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.getChangelog Get the changelog entries for the Kilo Claw product. organizations kiloclaw getchangelog organizationid organizationId" + }, + "organizations.kiloclaw.getChannelCatalog": { + "path": "organizations.kiloclaw.getChannelCatalog", + "kind": "query", + "summary": "Get the catalog of Kilo Claw channels with their configuration fields and which are configured.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "getchannelcatalog", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.getChannelCatalog Get the catalog of Kilo Claw channels with their configuration fields and which are configured. organizations kiloclaw getchannelcatalog organizationid organizationId" + }, + "organizations.kiloclaw.getConfig": { + "path": "organizations.kiloclaw.getConfig", + "kind": "query", + "summary": "Get the Kilo Claw configuration for the organization's instance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "getconfig", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.getConfig Get the Kilo Claw configuration for the organization's instance. organizations kiloclaw getconfig organizationid organizationId" + }, + "organizations.kiloclaw.getDiskUsage": { + "path": "organizations.kiloclaw.getDiskUsage", + "kind": "query", + "summary": "Get disk usage for the organization's Kilo Claw instance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "getdiskusage", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.getDiskUsage Get disk usage for the organization's Kilo Claw instance. organizations kiloclaw getdiskusage organizationid organizationId" + }, + "organizations.kiloclaw.getGoogleSetupCommand": { + "path": "organizations.kiloclaw.getGoogleSetupCommand", + "kind": "query", + "summary": "Get the docker command used to run the Google setup container for the organization's Kilo Claw instance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "getgooglesetupcommand", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.getGoogleSetupCommand Get the docker command used to run the Google setup container for the organization's Kilo Claw instance. organizations kiloclaw getgooglesetupcommand organizationid organizationId" + }, + "organizations.kiloclaw.getKiloCliRunStatus": { + "path": "organizations.kiloclaw.getKiloCliRunStatus", + "kind": "query", + "summary": "Get the status of a specific Kilo CLI run on the organization's instance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "getkiloclirunstatus", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.getKiloCliRunStatus Get the status of a specific Kilo CLI run on the organization's instance. organizations kiloclaw getkiloclirunstatus organizationid organizationId" + }, + "organizations.kiloclaw.getMorningBriefingStatus": { + "path": "organizations.kiloclaw.getMorningBriefingStatus", + "kind": "query", + "summary": "Get whether the morning briefing is enabled for the organization's Kilo Claw instance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "getmorningbriefingstatus", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.getMorningBriefingStatus Get whether the morning briefing is enabled for the organization's Kilo Claw instance. organizations kiloclaw getmorningbriefingstatus organizationid organizationId" + }, + "organizations.kiloclaw.getMyPin": { + "path": "organizations.kiloclaw.getMyPin", + "kind": "query", + "summary": "Get the current user's pinned Kilo Claw version for the organization's instance, if any.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "getmypin", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.getMyPin Get the current user's pinned Kilo Claw version for the organization's instance, if any. organizations kiloclaw getmypin organizationid organizationId" + }, + "organizations.kiloclaw.getNavState": { + "path": "organizations.kiloclaw.getNavState", + "kind": "query", + "summary": "Check whether the organization has an active Kilo Claw instance and a current subscription.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "getnavstate", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.getNavState Check whether the organization has an active Kilo Claw instance and a current subscription. organizations kiloclaw getnavstate organizationid organizationId" + }, + "organizations.kiloclaw.getSecretCatalog": { + "path": "organizations.kiloclaw.getSecretCatalog", + "kind": "query", + "summary": "Get the catalog of Kilo Claw tools/secrets with their configuration fields and which are configured.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "getsecretcatalog", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.getSecretCatalog Get the catalog of Kilo Claw tools/secrets with their configuration fields and which are configured. organizations kiloclaw getsecretcatalog organizationid organizationId" + }, + "organizations.kiloclaw.getStatus": { + "path": "organizations.kiloclaw.getStatus", + "kind": "query", + "summary": "Get the full dashboard status of the organization's Kilo Claw instance including runtime, region, and connectivity.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "getstatus", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.getStatus Get the full dashboard status of the organization's Kilo Claw instance including runtime, region, and connectivity. organizations kiloclaw getstatus organizationid organizationId" + }, + "organizations.kiloclaw.latestVersion": { + "path": "organizations.kiloclaw.latestVersion", + "kind": "query", + "summary": "Get the latest available Kilo Claw version, or the latest suitable for the organization's instance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "latestversion", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.latestVersion Get the latest available Kilo Claw version, or the latest suitable for the organization's instance. organizations kiloclaw latestversion organizationid organizationId" + }, + "organizations.kiloclaw.listActiveInstances": { + "path": "organizations.kiloclaw.listActiveInstances", + "kind": "query", + "summary": "List active Kilo Claw instances for the organization with owner email and subscription suspension state.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "listactiveinstances", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.listActiveInstances List active Kilo Claw instances for the organization with owner email and subscription suspension state. organizations kiloclaw listactiveinstances organizationid organizationId" + }, + "organizations.kiloclaw.listAgents": { + "path": "organizations.kiloclaw.listAgents", + "kind": "query", + "summary": "List the agents configured on the organization's Kilo Claw instance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "listagents", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.listAgents List the agents configured on the organization's Kilo Claw instance. organizations kiloclaw listagents organizationid organizationId" + }, + "organizations.kiloclaw.listAvailableVersions": { + "path": "organizations.kiloclaw.listAvailableVersions", + "kind": "query", + "summary": "List available Kilo Claw image versions with pagination.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "listavailableversions", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.listAvailableVersions List available Kilo Claw image versions with pagination. organizations kiloclaw listavailableversions organizationid organizationId" + }, + "organizations.kiloclaw.listDevicePairingRequests": { + "path": "organizations.kiloclaw.listDevicePairingRequests", + "kind": "query", + "summary": "List device pairing requests for the organization's Kilo Claw instance, with optional refresh.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "listdevicepairingrequests", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.listDevicePairingRequests List device pairing requests for the organization's Kilo Claw instance, with optional refresh. organizations kiloclaw listdevicepairingrequests organizationid organizationId" + }, + "organizations.kiloclaw.listKiloCliRuns": { + "path": "organizations.kiloclaw.listKiloCliRuns", + "kind": "query", + "summary": "List recent Kilo CLI runs performed by the current user on the organization's instance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "listkilocliruns", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.listKiloCliRuns List recent Kilo CLI runs performed by the current user on the organization's instance. organizations kiloclaw listkilocliruns organizationid organizationId" + }, + "organizations.kiloclaw.listPairingRequests": { + "path": "organizations.kiloclaw.listPairingRequests", + "kind": "query", + "summary": "List Kilo Claw pairing requests for the organization's instance, with optional refresh.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "listpairingrequests", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.listPairingRequests List Kilo Claw pairing requests for the organization's instance, with optional refresh. organizations kiloclaw listpairingrequests organizationid organizationId" + }, + "organizations.kiloclaw.readFile": { + "path": "organizations.kiloclaw.readFile", + "kind": "query", + "summary": "Read the contents of a file on the organization's Kilo Claw instance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "readfile", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.readFile Read the contents of a file on the organization's Kilo Claw instance. organizations kiloclaw readfile organizationid organizationId" + }, + "organizations.kiloclaw.readMorningBriefing": { + "path": "organizations.kiloclaw.readMorningBriefing", + "kind": "query", + "summary": "Read the morning briefing content for today or yesterday from the organization's Kilo Claw instance.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "readmorningbriefing", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.readMorningBriefing Read the morning briefing content for today or yesterday from the organization's Kilo Claw instance. organizations kiloclaw readmorningbriefing organizationid organizationId" + }, + "organizations.kiloclaw.serviceDegraded": { + "path": "organizations.kiloclaw.serviceDegraded", + "kind": "query", + "summary": "Check the Kilo status page to see whether the service is currently degraded.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "kiloclaw", + "servicedegraded", + "organizationid" + ], + "searchBlob": "organizations.kiloclaw.serviceDegraded Check the Kilo status page to see whether the service is currently degraded. organizations kiloclaw servicedegraded organizationid organizationId" + }, + "organizations.list": { + "path": "organizations.list", + "kind": "query", + "summary": "List the organizations the current user belongs to along with any inherited child organizations.", + "inputSchema": {}, + "tags": [ + "organizations", + "list" + ], + "searchBlob": "organizations.list List the organizations the current user belongs to along with any inherited child organizations. organizations list" + }, + "organizations.members.listPublic": { + "path": "organizations.members.listPublic", + "kind": "query", + "summary": "List the active members of an organization with their names and emails for public member display.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "members", + "listpublic", + "organizationid" + ], + "searchBlob": "organizations.members.listPublic List the active members of an organization with their names and emails for public member display. organizations members listpublic organizationid organizationId" + }, + "organizations.modes.getById": { + "path": "organizations.modes.getById", + "kind": "query", + "summary": "Get a single custom mode by its ID within an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "modes", + "getbyid", + "organizationid" + ], + "searchBlob": "organizations.modes.getById Get a single custom mode by its ID within an organization. organizations modes getbyid organizationid organizationId" + }, + "organizations.modes.list": { + "path": "organizations.modes.list", + "kind": "query", + "summary": "List all custom modes defined for an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "modes", + "list", + "organizationid" + ], + "searchBlob": "organizations.modes.list List all custom modes defined for an organization. organizations modes list organizationid organizationId" + }, + "organizations.reviewAgent.getBitbucketReadiness": { + "path": "organizations.reviewAgent.getBitbucketReadiness", + "kind": "query", + "summary": "Get Bitbucket code review readiness and whether the caller can manage the review agent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "reviewagent", + "getbitbucketreadiness", + "organizationid" + ], + "searchBlob": "organizations.reviewAgent.getBitbucketReadiness Get Bitbucket code review readiness and whether the caller can manage the review agent. organizations reviewagent getbitbucketreadiness organizationid organizationId" + }, + "organizations.reviewAgent.getCouncilEntitlement": { + "path": "organizations.reviewAgent.getCouncilEntitlement", + "kind": "query", + "summary": "Check whether an organization is entitled to the review council feature.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "reviewagent", + "getcouncilentitlement", + "organizationid" + ], + "searchBlob": "organizations.reviewAgent.getCouncilEntitlement Check whether an organization is entitled to the review council feature. organizations reviewagent getcouncilentitlement organizationid organizationId" + }, + "organizations.reviewAgent.getGitHubStatus": { + "path": "organizations.reviewAgent.getGitHubStatus", + "kind": "query", + "summary": "Check whether the organization's GitHub integration is healthy and connected for the review agent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "reviewagent", + "getgithubstatus", + "organizationid" + ], + "searchBlob": "organizations.reviewAgent.getGitHubStatus Check whether the organization's GitHub integration is healthy and connected for the review agent. organizations reviewagent getgithubstatus organizationid organizationId" + }, + "organizations.reviewAgent.getGitLabStatus": { + "path": "organizations.reviewAgent.getGitLabStatus", + "kind": "query", + "summary": "Check the organization's GitLab integration connection status for the review agent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "reviewagent", + "getgitlabstatus", + "organizationid" + ], + "searchBlob": "organizations.reviewAgent.getGitLabStatus Check the organization's GitLab integration connection status for the review agent. organizations reviewagent getgitlabstatus organizationid organizationId" + }, + "organizations.reviewAgent.getReviewConfig": { + "path": "organizations.reviewAgent.getReviewConfig", + "kind": "query", + "summary": "Get the code review agent configuration for an organization and platform (GitHub, GitLab, or Bitbucket).", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "reviewagent", + "getreviewconfig", + "organizationid" + ], + "searchBlob": "organizations.reviewAgent.getReviewConfig Get the code review agent configuration for an organization and platform (GitHub, GitLab, or Bitbucket). organizations reviewagent getreviewconfig organizationid organizationId" + }, + "organizations.reviewAgent.listGitHubRepositories": { + "path": "organizations.reviewAgent.listGitHubRepositories", + "kind": "query", + "summary": "List GitHub repositories accessible to the organization's review agent, with optional forced refresh.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "reviewagent", + "listgithubrepositories", + "organizationid" + ], + "searchBlob": "organizations.reviewAgent.listGitHubRepositories List GitHub repositories accessible to the organization's review agent, with optional forced refresh. organizations reviewagent listgithubrepositories organizationid organizationId" + }, + "organizations.reviewAgent.listGitLabRepositories": { + "path": "organizations.reviewAgent.listGitLabRepositories", + "kind": "query", + "summary": "List GitLab repositories accessible to the organization's review agent, with optional forced refresh.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "reviewagent", + "listgitlabrepositories", + "organizationid" + ], + "searchBlob": "organizations.reviewAgent.listGitLabRepositories List GitLab repositories accessible to the organization's review agent, with optional forced refresh. organizations reviewagent listgitlabrepositories organizationid organizationId" + }, + "organizations.seatPurchases": { + "path": "organizations.seatPurchases", + "kind": "query", + "summary": "Get the seat purchase records for an organization ordered newest first.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "seatpurchases", + "organizationid" + ], + "searchBlob": "organizations.seatPurchases Get the seat purchase records for an organization ordered newest first. organizations seatpurchases organizationid organizationId" + }, + "organizations.seats": { + "path": "organizations.seats", + "kind": "query", + "summary": "Get the total and used seat counts for an organization's subscription.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "seats", + "organizationid" + ], + "searchBlob": "organizations.seats Get the total and used seat counts for an organization's subscription. organizations seats organizationid organizationId" + }, + "organizations.securityAgent.getAnalysis": { + "path": "organizations.securityAgent.getAnalysis", + "kind": "query", + "summary": "Get a code analysis result from the organization's security agent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "getanalysis", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.getAnalysis Get a code analysis result from the organization's security agent. organizations securityagent getanalysis organizationid organizationId" + }, + "organizations.securityAgent.getAuditReport": { + "path": "organizations.securityAgent.getAuditReport", + "kind": "query", + "summary": "Generate a security audit report for the organization (billing gated).", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "getauditreport", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.getAuditReport Generate a security audit report for the organization (billing gated). organizations securityagent getauditreport organizationid organizationId" + }, + "organizations.securityAgent.getAutoDismissEligible": { + "path": "organizations.securityAgent.getAutoDismissEligible", + "kind": "query", + "summary": "Get findings eligible for automatic dismissal in the security agent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "getautodismisseligible", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.getAutoDismissEligible Get findings eligible for automatic dismissal in the security agent. organizations securityagent getautodismisseligible organizationid organizationId" + }, + "organizations.securityAgent.getCommandStatus": { + "path": "organizations.securityAgent.getCommandStatus", + "kind": "query", + "summary": "Get the status of a security scan command run by the organization's security agent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "getcommandstatus", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.getCommandStatus Get the status of a security scan command run by the organization's security agent. organizations securityagent getcommandstatus organizationid organizationId" + }, + "organizations.securityAgent.getCommandStatuses": { + "path": "organizations.securityAgent.getCommandStatuses", + "kind": "query", + "summary": "Get statuses for multiple security agent commands.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "getcommandstatuses", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.getCommandStatuses Get statuses for multiple security agent commands. organizations securityagent getcommandstatuses organizationid organizationId" + }, + "organizations.securityAgent.getConfig": { + "path": "organizations.securityAgent.getConfig", + "kind": "query", + "summary": "Get the security agent configuration for the organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "getconfig", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.getConfig Get the security agent configuration for the organization. organizations securityagent getconfig organizationid organizationId" + }, + "organizations.securityAgent.getDashboardStats": { + "path": "organizations.securityAgent.getDashboardStats", + "kind": "query", + "summary": "Get dashboard-level statistics for the organization's security agent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "getdashboardstats", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.getDashboardStats Get dashboard-level statistics for the organization's security agent. organizations securityagent getdashboardstats organizationid organizationId" + }, + "organizations.securityAgent.getFinding": { + "path": "organizations.securityAgent.getFinding", + "kind": "query", + "summary": "Get a single security finding by ID.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "getfinding", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.getFinding Get a single security finding by ID. organizations securityagent getfinding organizationid organizationId" + }, + "organizations.securityAgent.getLastSyncTime": { + "path": "organizations.securityAgent.getLastSyncTime", + "kind": "query", + "summary": "Get the time of the organization's last security scan or data sync.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "getlastsynctime", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.getLastSyncTime Get the time of the organization's last security scan or data sync. organizations securityagent getlastsynctime organizationid organizationId" + }, + "organizations.securityAgent.getOrphanedRepositories": { + "path": "organizations.securityAgent.getOrphanedRepositories", + "kind": "query", + "summary": "List repositories that are orphaned or no longer accessible to the security agent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "getorphanedrepositories", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.getOrphanedRepositories List repositories that are orphaned or no longer accessible to the security agent. organizations securityagent getorphanedrepositories organizationid organizationId" + }, + "organizations.securityAgent.getPermissionStatus": { + "path": "organizations.securityAgent.getPermissionStatus", + "kind": "query", + "summary": "Get the permission status for the organization's security agent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "getpermissionstatus", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.getPermissionStatus Get the permission status for the organization's security agent. organizations securityagent getpermissionstatus organizationid organizationId" + }, + "organizations.securityAgent.getRepositories": { + "path": "organizations.securityAgent.getRepositories", + "kind": "query", + "summary": "List repositories connected to the organization's security agent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "getrepositories", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.getRepositories List repositories connected to the organization's security agent. organizations securityagent getrepositories organizationid organizationId" + }, + "organizations.securityAgent.getStats": { + "path": "organizations.securityAgent.getStats", + "kind": "query", + "summary": "Get summary statistics for the organization's security agent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "getstats", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.getStats Get summary statistics for the organization's security agent. organizations securityagent getstats organizationid organizationId" + }, + "organizations.securityAgent.listActiveCommands": { + "path": "organizations.securityAgent.listActiveCommands", + "kind": "query", + "summary": "List commands currently running in the organization's security agent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "listactivecommands", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.listActiveCommands List commands currently running in the organization's security agent. organizations securityagent listactivecommands organizationid organizationId" + }, + "organizations.securityAgent.listFindings": { + "path": "organizations.securityAgent.listFindings", + "kind": "query", + "summary": "List security findings detected by the organization's security agent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityagent", + "listfindings", + "organizationid" + ], + "searchBlob": "organizations.securityAgent.listFindings List security findings detected by the organization's security agent. organizations securityagent listfindings organizationid organizationId" + }, + "organizations.securityAuditLog.getActionTypes": { + "path": "organizations.securityAuditLog.getActionTypes", + "kind": "query", + "summary": "Get the list of all possible security audit log action types.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityauditlog", + "getactiontypes", + "organizationid" + ], + "searchBlob": "organizations.securityAuditLog.getActionTypes Get the list of all possible security audit log action types. organizations securityauditlog getactiontypes organizationid organizationId" + }, + "organizations.securityAuditLog.getSummary": { + "path": "organizations.securityAuditLog.getSummary", + "kind": "query", + "summary": "Get summary statistics for an organization's security audit log such as total events and date range.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityauditlog", + "getsummary", + "organizationid" + ], + "searchBlob": "organizations.securityAuditLog.getSummary Get summary statistics for an organization's security audit log such as total events and date range. organizations securityauditlog getsummary organizationid organizationId" + }, + "organizations.securityAuditLog.list": { + "path": "organizations.securityAuditLog.list", + "kind": "query", + "summary": "List an organization's security audit log entries with filtering by action, actor, resource, and time range.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "securityauditlog", + "list", + "organizationid" + ], + "searchBlob": "organizations.securityAuditLog.list List an organization's security audit log entries with filtering by action, actor, resource, and time range. organizations securityauditlog list organizationid organizationId" + }, + "organizations.settings.listAvailableModels": { + "path": "organizations.settings.listAvailableModels", + "kind": "query", + "summary": "List the AI models available to an organization's members according to its model access policy.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "settings", + "listavailablemodels", + "organizationid" + ], + "searchBlob": "organizations.settings.listAvailableModels List the AI models available to an organization's members according to its model access policy. organizations settings listavailablemodels organizationid organizationId" + }, + "organizations.sso.getConfig": { + "path": "organizations.sso.getConfig", + "kind": "query", + "summary": "Get an organization's SSO configuration including domain verification status and whether SSO connections exist.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "sso", + "getconfig", + "organizationid" + ], + "searchBlob": "organizations.sso.getConfig Get an organization's SSO configuration including domain verification status and whether SSO connections exist. organizations sso getconfig organizationid organizationId" + }, + "organizations.subOrganizations.credits": { + "path": "organizations.subOrganizations.credits", + "kind": "query", + "summary": "Get credit balances and Kilo Pass credit state for an organization's sub-organizations.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "suborganizations", + "credits", + "organizationid" + ], + "searchBlob": "organizations.subOrganizations.credits Get credit balances and Kilo Pass credit state for an organization's sub-organizations. organizations suborganizations credits organizationid organizationId" + }, + "organizations.subOrganizations.modelPolicy": { + "path": "organizations.subOrganizations.modelPolicy", + "kind": "query", + "summary": "Get the model access policy state across the parent organization and its sub-organizations.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "suborganizations", + "modelpolicy", + "organizationid" + ], + "searchBlob": "organizations.subOrganizations.modelPolicy Get the model access policy state across the parent organization and its sub-organizations. organizations suborganizations modelpolicy organizationid organizationId" + }, + "organizations.subOrganizations.overview": { + "path": "organizations.subOrganizations.overview", + "kind": "query", + "summary": "Get an overview of an organization's sub-organizations including membership counts, invitations, and credit balances.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "suborganizations", + "overview", + "organizationid" + ], + "searchBlob": "organizations.subOrganizations.overview Get an overview of an organization's sub-organizations including membership counts, invitations, and credit balances. organizations suborganizations overview organizationid organizationId" + }, + "organizations.subOrganizations.people": { + "path": "organizations.subOrganizations.people", + "kind": "query", + "summary": "Get people (members and roles) across the parent organization and its sub-organizations with filtering and search.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "suborganizations", + "people", + "organizationid" + ], + "searchBlob": "organizations.subOrganizations.people Get people (members and roles) across the parent organization and its sub-organizations with filtering and search. organizations suborganizations people organizationid organizationId" + }, + "organizations.subOrganizations.permissions": { + "path": "organizations.subOrganizations.permissions", + "kind": "query", + "summary": "Get roles, permissions, and SSO/feature settings across the organization's sub-organizations.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "suborganizations", + "permissions", + "organizationid" + ], + "searchBlob": "organizations.subOrganizations.permissions Get roles, permissions, and SSO/feature settings across the organization's sub-organizations. organizations suborganizations permissions organizationid organizationId" + }, + "organizations.subscription.get": { + "path": "organizations.subscription.get", + "kind": "query", + "summary": "Fetch an organization's subscription details including Stripe subscription data, seats used, total seats, and any scheduled seat changes.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "subscription", + "get", + "organizationid" + ], + "searchBlob": "organizations.subscription.get Fetch an organization's subscription details including Stripe subscription data, seats used, total seats, and any scheduled seat changes. organizations subscription get organizationid organizationId" + }, + "organizations.subscription.getBillingHistory": { + "path": "organizations.subscription.getBillingHistory", + "kind": "query", + "summary": "Return paginated billing history (invoices) for an organization's current seat subscription.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "subscription", + "getbillinghistory", + "organizationid" + ], + "searchBlob": "organizations.subscription.getBillingHistory Return paginated billing history (invoices) for an organization's current seat subscription. organizations subscription getbillinghistory organizationid organizationId" + }, + "organizations.subscription.getByStripeSessionId": { + "path": "organizations.subscription.getByStripeSessionId", + "kind": "query", + "summary": "Verify that a Stripe checkout session was paid for and that its subscription exists.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "sessionId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "sessionId" + ] + }, + "tags": [ + "organizations", + "subscription", + "getbystripesessionid", + "sessionid" + ], + "searchBlob": "organizations.subscription.getByStripeSessionId Verify that a Stripe checkout session was paid for and that its subscription exists. organizations subscription getbystripesessionid sessionid sessionId" + }, + "organizations.subscription.getLatestSeatPurchaseStatus": { + "path": "organizations.subscription.getLatestSeatPurchaseStatus", + "kind": "query", + "summary": "Check the subscription status of an organization's most recent seat purchase.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "subscription", + "getlatestseatpurchasestatus", + "organizationid" + ], + "searchBlob": "organizations.subscription.getLatestSeatPurchaseStatus Check the subscription status of an organization's most recent seat purchase. organizations subscription getlatestseatpurchasestatus organizationid organizationId" + }, + "organizations.subscription.getResubscribeDefaults": { + "path": "organizations.subscription.getResubscribeDefaults", + "kind": "query", + "summary": "Get recommended default seat count and billing cycle to offer when an organization resubscribes after its subscription ended.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "subscription", + "getresubscribedefaults", + "organizationid" + ], + "searchBlob": "organizations.subscription.getResubscribeDefaults Get recommended default seat count and billing cycle to offer when an organization resubscribes after its subscription ended. organizations subscription getresubscribedefaults organizationid organizationId" + }, + "organizations.usageDetails.getAIAdoptionTimeseries": { + "path": "organizations.usageDetails.getAIAdoptionTimeseries", + "kind": "query", + "summary": "Get daily AI adoption timeseries, weekly trends, and per-user adoption scores across an organization over a date range.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "usagedetails", + "getaiadoptiontimeseries", + "organizationid" + ], + "searchBlob": "organizations.usageDetails.getAIAdoptionTimeseries Get daily AI adoption timeseries, weekly trends, and per-user adoption scores across an organization over a date range. organizations usagedetails getaiadoptiontimeseries organizationid organizationId" + }, + "organizations.usageDetails.getFeatureAdoption": { + "path": "organizations.usageDetails.getFeatureAdoption", + "kind": "query", + "summary": "Get feature adoption check results for an organization (Enterprise plan only).", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "usagedetails", + "getfeatureadoption", + "organizationid" + ], + "searchBlob": "organizations.usageDetails.getFeatureAdoption Get feature adoption check results for an organization (Enterprise plan only). organizations usagedetails getfeatureadoption organizationid organizationId" + }, + "organizations.usageDetails.getRecommendations": { + "path": "organizations.usageDetails.getRecommendations", + "kind": "query", + "summary": "Get feature adoption recommendations for an organization based on adoption checks (Enterprise plan only).", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "usagedetails", + "getrecommendations", + "organizationid" + ], + "searchBlob": "organizations.usageDetails.getRecommendations Get feature adoption recommendations for an organization based on adoption checks (Enterprise plan only). organizations usagedetails getrecommendations organizationid organizationId" + }, + "organizations.usageStats": { + "path": "organizations.usageStats", + "kind": "query", + "summary": "Get an organization's usage totals (cost, requests, tokens) over the last 30 days.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "usagestats", + "organizationid" + ], + "searchBlob": "organizations.usageStats Get an organization's usage totals (cost, requests, tokens) over the last 30 days. organizations usagestats organizationid organizationId" + }, + "organizations.verifiedDomains.list": { + "path": "organizations.verifiedDomains.list", + "kind": "query", + "summary": "List the verified domain claims for an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "verifieddomains", + "list", + "organizationid" + ], + "searchBlob": "organizations.verifiedDomains.list List the verified domain claims for an organization. organizations verifieddomains list organizationid organizationId" + }, + "organizations.withMembers": { + "path": "organizations.withMembers", + "kind": "query", + "summary": "Get an organization with its members, SSO policy, and child organization memberships.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "organizations", + "withmembers", + "organizationid" + ], + "searchBlob": "organizations.withMembers Get an organization with its members, SSO policy, and child organization memberships. organizations withmembers organizationid organizationId" + }, + "personalAutoFix.getAutoFixConfig": { + "path": "personalAutoFix.getAutoFixConfig", + "kind": "query", + "summary": "Retrieves the user's personal auto-fix agent settings, including whether it is enabled, returning defaults if none exist.", + "inputSchema": {}, + "tags": [ + "personalautofix", + "getautofixconfig" + ], + "searchBlob": "personalAutoFix.getAutoFixConfig Retrieves the user's personal auto-fix agent settings, including whether it is enabled, returning defaults if none exist. personalautofix getautofixconfig" + }, + "personalAutoFix.listGitHubRepositories": { + "path": "personalAutoFix.listGitHubRepositories", + "kind": "query", + "summary": "Lists the GitHub repositories associated with the current user's account.", + "inputSchema": {}, + "tags": [ + "personalautofix", + "listgithubrepositories" + ], + "searchBlob": "personalAutoFix.listGitHubRepositories Lists the GitHub repositories associated with the current user's account. personalautofix listgithubrepositories" + }, + "personalAutoFix.listTickets": { + "path": "personalAutoFix.listTickets", + "kind": "query", + "summary": "Lists auto-fix tickets for the current user with optional filtering by status, classification, repository, and pagination.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "limit": { + "type": "number" + }, + "offset": { + "type": "number" + }, + "status": { + "type": "string", + "enum": [ + "pending", + "running", + "completed", + "failed", + "cancelled" + ] + }, + "classification": { + "type": "string", + "enum": [ + "bug", + "feature", + "question", + "unclear" + ] + }, + "repoFullName": { + "type": "string" + } + } + }, + "tags": [ + "personalautofix", + "listtickets", + "limit", + "offset", + "status", + "classification", + "repofullname" + ], + "searchBlob": "personalAutoFix.listTickets Lists auto-fix tickets for the current user with optional filtering by status, classification, repository, and pagination. personalautofix listtickets limit offset status classification repofullname limit offset status classification repoFullName" + }, + "personalAutoTriage.getAutoTriageConfig": { + "path": "personalAutoTriage.getAutoTriageConfig", + "kind": "query", + "summary": "Get your current personal auto-triage agent settings, such as whether it is enabled, which repositories and labels it applies to, thresholds, and the model and custom instructions in use.", + "inputSchema": {}, + "tags": [ + "personalautotriage", + "getautotriageconfig" + ], + "searchBlob": "personalAutoTriage.getAutoTriageConfig Get your current personal auto-triage agent settings, such as whether it is enabled, which repositories and labels it applies to, thresholds, and the model and custom instructions in use. personalautotriage getautotriageconfig" + }, + "personalAutoTriage.getGitHubStatus": { + "path": "personalAutoTriage.getGitHubStatus", + "kind": "query", + "summary": "Check whether your personal GitHub integration is connected and active for the auto-triage feature, including which account is linked, its repository access, and whether the installation is still valid.", + "inputSchema": {}, + "tags": [ + "personalautotriage", + "getgithubstatus" + ], + "searchBlob": "personalAutoTriage.getGitHubStatus Check whether your personal GitHub integration is connected and active for the auto-triage feature, including which account is linked, its repository access, and whether the installation is still valid. personalautotriage getgithubstatus" + }, + "personalAutoTriage.listGitHubRepositories": { + "path": "personalAutoTriage.listGitHubRepositories", + "kind": "query", + "summary": "List the GitHub repositories your connected personal GitHub integration can access for auto-triage.", + "inputSchema": {}, + "tags": [ + "personalautotriage", + "listgithubrepositories" + ], + "searchBlob": "personalAutoTriage.listGitHubRepositories List the GitHub repositories your connected personal GitHub integration can access for auto-triage. personalautotriage listgithubrepositories" + }, + "personalAutoTriage.listTickets": { + "path": "personalAutoTriage.listTickets", + "kind": "query", + "summary": "List your personal auto-triage tickets with pagination, optionally filtering by status, classification, or repository.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "limit": { + "default": 10, + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 100 + }, + "offset": { + "default": 0, + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "pending", + "analyzing", + "actioned", + "failed", + "skipped" + ] + }, + "classification": { + "type": "string", + "enum": [ + "bug", + "feature", + "question", + "duplicate", + "unclear" + ] + }, + "repoFullName": { + "type": "string" + } + } + }, + "tags": [ + "personalautotriage", + "listtickets", + "limit", + "offset", + "status", + "classification", + "repofullname" + ], + "searchBlob": "personalAutoTriage.listTickets List your personal auto-triage tickets with pagination, optionally filtering by status, classification, or repository. personalautotriage listtickets limit offset status classification repofullname limit offset status classification repoFullName" + }, + "personalReviewAgent.getGitHubStatus": { + "path": "personalReviewAgent.getGitHubStatus", + "kind": "query", + "summary": "Check whether the current user's personal GitHub integration is connected and active, returning account login, repo access scope, install date, and validity.", + "inputSchema": {}, + "tags": [ + "personalreviewagent", + "getgithubstatus" + ], + "searchBlob": "personalReviewAgent.getGitHubStatus Check whether the current user's personal GitHub integration is connected and active, returning account login, repo access scope, install date, and validity. personalreviewagent getgithubstatus" + }, + "personalReviewAgent.getGitLabStatus": { + "path": "personalReviewAgent.getGitLabStatus", + "kind": "query", + "summary": "Check whether the current user's GitLab integration is connected and active, returning account login, repo access scope, and the GitLab instance URL.", + "inputSchema": {}, + "tags": [ + "personalreviewagent", + "getgitlabstatus" + ], + "searchBlob": "personalReviewAgent.getGitLabStatus Check whether the current user's GitLab integration is connected and active, returning account login, repo access scope, and the GitLab instance URL. personalreviewagent getgitlabstatus" + }, + "personalReviewAgent.getReviewConfig": { + "path": "personalReviewAgent.getReviewConfig", + "kind": "query", + "summary": "Get the current user's personal code review agent settings for a given platform (GitHub or GitLab), including enabled state, review style, focus areas, model choice, repository selection, and defaults when no config exists.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "platform": { + "default": "github", + "type": "string", + "enum": [ + "github", + "gitlab" + ] + } + } + }, + "tags": [ + "personalreviewagent", + "getreviewconfig", + "platform" + ], + "searchBlob": "personalReviewAgent.getReviewConfig Get the current user's personal code review agent settings for a given platform (GitHub or GitLab), including enabled state, review style, focus areas, model choice, repository selection, and defaults when no config exists. personalreviewagent getreviewconfig platform platform" + }, + "personalReviewAgent.listGitHubRepositories": { + "path": "personalReviewAgent.listGitHubRepositories", + "kind": "query", + "summary": "Fetch the list of GitHub repositories the current user can have reviewed, with an optional force refresh to bypass cached results.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "forceRefresh": { + "default": false, + "type": "boolean" + } + } + }, + "tags": [ + "personalreviewagent", + "listgithubrepositories", + "forcerefresh" + ], + "searchBlob": "personalReviewAgent.listGitHubRepositories Fetch the list of GitHub repositories the current user can have reviewed, with an optional force refresh to bypass cached results. personalreviewagent listgithubrepositories forcerefresh forceRefresh" + }, + "personalReviewAgent.listGitLabRepositories": { + "path": "personalReviewAgent.listGitLabRepositories", + "kind": "query", + "summary": "Fetch the list of GitLab repositories available to the current user for reviews, with an optional force refresh to bypass cached results.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "forceRefresh": { + "default": false, + "type": "boolean" + } + } + }, + "tags": [ + "personalreviewagent", + "listgitlabrepositories", + "forcerefresh" + ], + "searchBlob": "personalReviewAgent.listGitLabRepositories Fetch the list of GitLab repositories available to the current user for reviews, with an optional force refresh to bypass cached results. personalreviewagent listgitlabrepositories forcerefresh forceRefresh" + }, + "platformIntegrations.listSetupStatus": { + "path": "platformIntegrations.listSetupStatus", + "kind": "query", + "summary": "Check which platform integrations (e.g. GitHub, GitLab, Bitbucket) are already configured or missing so you know what setup steps remain for an organization.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "platformintegrations", + "listsetupstatus", + "organizationid" + ], + "searchBlob": "platformIntegrations.listSetupStatus Check which platform integrations (e.g. GitHub, GitLab, Bitbucket) are already configured or missing so you know what setup steps remain for an organization. platformintegrations listsetupstatus organizationid organizationId" + }, + "quickChat.listMessages": { + "path": "quickChat.listMessages", + "kind": "query", + "summary": "Paginated fetch of a user's quick chat message history within an organization/thread scope, returning messages newest-first with cursor-based pagination.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + }, + "cursor": { + "type": "string", + "minLength": 1 + }, + "limit": { + "default": 50, + "type": "number", + "minimum": 1, + "maximum": 50 + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "quickchat", + "listmessages", + "organizationid", + "cursor", + "limit" + ], + "searchBlob": "quickChat.listMessages Paginated fetch of a user's quick chat message history within an organization/thread scope, returning messages newest-first with cursor-based pagination. quickchat listmessages organizationid cursor limit organizationId cursor limit" + }, + "reviewMemory.getDashboardSummary": { + "path": "reviewMemory.getDashboardSummary", + "kind": "query", + "summary": "Get the code review memory dashboard summary showing whether review memory is enabled, which repositories have recent feedback, and the number of open proposals.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "platform": { + "type": "string", + "enum": [ + "github" + ] + } + }, + "required": [ + "platform" + ] + }, + "tags": [ + "reviewmemory", + "getdashboardsummary", + "organizationid", + "platform" + ], + "searchBlob": "reviewMemory.getDashboardSummary Get the code review memory dashboard summary showing whether review memory is enabled, which repositories have recent feedback, and the number of open proposals. reviewmemory getdashboardsummary organizationid platform organizationId platform" + }, + "reviewMemory.listProposals": { + "path": "reviewMemory.listProposals", + "kind": "query", + "summary": "List code review proposals, optionally filtered by repository, status, and a maximum result limit.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "platform": { + "type": "string", + "enum": [ + "github" + ] + }, + "repoFullName": { + "type": "string", + "minLength": 1 + }, + "statuses": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "open", + "edited", + "rejected", + "opening_change_request", + "change_request_opened", + "change_request_failed", + "superseded" + ] + } + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + "required": [ + "platform" + ] + }, + "tags": [ + "reviewmemory", + "listproposals", + "organizationid", + "platform", + "repofullname", + "statuses", + "limit" + ], + "searchBlob": "reviewMemory.listProposals List code review proposals, optionally filtered by repository, status, and a maximum result limit. reviewmemory listproposals organizationid platform repofullname statuses limit organizationId platform repoFullName statuses limit" + }, + "reviewMemory.listProposalsPage": { + "path": "reviewMemory.listProposalsPage", + "kind": "query", + "summary": "Fetch a paginated page of code review proposals, optionally filtered by repository and status, using a cursor for navigation.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "platform": { + "type": "string", + "enum": [ + "github" + ] + }, + "repoFullName": { + "type": "string", + "minLength": 1 + }, + "statuses": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "open", + "edited", + "rejected", + "opening_change_request", + "change_request_opened", + "change_request_failed", + "superseded" + ] + } + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 100 + }, + "cursor": { + "type": "string" + } + }, + "required": [ + "platform" + ] + }, + "tags": [ + "reviewmemory", + "listproposalspage", + "organizationid", + "platform", + "repofullname", + "statuses", + "limit", + "cursor" + ], + "searchBlob": "reviewMemory.listProposalsPage Fetch a paginated page of code review proposals, optionally filtered by repository and status, using a cursor for navigation. reviewmemory listproposalspage organizationid platform repofullname statuses limit cursor organizationId platform repoFullName statuses limit cursor" + }, + "securityAgent.getAnalysis": { + "path": "securityAgent.getAnalysis", + "kind": "query", + "summary": "Retrieve a security analysis or scan report for a specific repository.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "findingId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "findingId" + ] + }, + "tags": [ + "securityagent", + "getanalysis", + "findingid" + ], + "searchBlob": "securityAgent.getAnalysis Retrieve a security analysis or scan report for a specific repository. securityagent getanalysis findingid findingId" + }, + "securityAgent.getAuditReport": { + "path": "securityAgent.getAuditReport", + "kind": "query", + "summary": "Generate or retrieve a security audit report, typically for a specific repository.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "startDate": { + "type": "string", + "pattern": "^\\d{4}-\\d{2}-\\d{2}$" + }, + "endDate": { + "type": "string", + "pattern": "^\\d{4}-\\d{2}-\\d{2}$" + } + } + }, + "tags": [ + "securityagent", + "getauditreport", + "startdate", + "enddate" + ], + "searchBlob": "securityAgent.getAuditReport Generate or retrieve a security audit report, typically for a specific repository. securityagent getauditreport startdate enddate startDate endDate" + }, + "securityAgent.getAutoDismissEligible": { + "path": "securityAgent.getAutoDismissEligible", + "kind": "query", + "summary": "Get findings that are eligible to be automatically dismissed based on current rules.", + "inputSchema": {}, + "tags": [ + "securityagent", + "getautodismisseligible" + ], + "searchBlob": "securityAgent.getAutoDismissEligible Get findings that are eligible to be automatically dismissed based on current rules. securityagent getautodismisseligible" + }, + "securityAgent.getCommandStatus": { + "path": "securityAgent.getCommandStatus", + "kind": "query", + "summary": "Check the status and result of a single security agent command by ID.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "commandId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "commandId" + ] + }, + "tags": [ + "securityagent", + "getcommandstatus", + "commandid" + ], + "searchBlob": "securityAgent.getCommandStatus Check the status and result of a single security agent command by ID. securityagent getcommandstatus commandid commandId" + }, + "securityAgent.getCommandStatuses": { + "path": "securityAgent.getCommandStatuses", + "kind": "query", + "summary": "Get the status of multiple security agent commands at once, such as scans or remediation actions.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "commandIds": { + "minItems": 1, + "maxItems": 100, + "type": "array", + "items": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "required": [ + "commandIds" + ] + }, + "tags": [ + "securityagent", + "getcommandstatuses", + "commandids" + ], + "searchBlob": "securityAgent.getCommandStatuses Get the status of multiple security agent commands at once, such as scans or remediation actions. securityagent getcommandstatuses commandids commandIds" + }, + "securityAgent.getConfig": { + "path": "securityAgent.getConfig", + "kind": "query", + "summary": "Retrieve the current security agent configuration and settings.", + "inputSchema": {}, + "tags": [ + "securityagent", + "getconfig" + ], + "searchBlob": "securityAgent.getConfig Retrieve the current security agent configuration and settings. securityagent getconfig" + }, + "securityAgent.getDashboardStats": { + "path": "securityAgent.getDashboardStats", + "kind": "query", + "summary": "Get statistics and metrics for displaying on a security dashboard.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "repoFullName": { + "type": "string" + } + } + }, + "tags": [ + "securityagent", + "getdashboardstats", + "repofullname" + ], + "searchBlob": "securityAgent.getDashboardStats Get statistics and metrics for displaying on a security dashboard. securityagent getdashboardstats repofullname repoFullName" + }, + "securityAgent.getFinding": { + "path": "securityAgent.getFinding", + "kind": "query", + "summary": "Fetch the full details of a single security finding by its ID.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "id" + ] + }, + "tags": [ + "securityagent", + "getfinding", + "id" + ], + "searchBlob": "securityAgent.getFinding Fetch the full details of a single security finding by its ID. securityagent getfinding id id" + }, + "securityAgent.getLastSyncTime": { + "path": "securityAgent.getLastSyncTime", + "kind": "query", + "summary": "Get the last time the security agent synced data for a given repository.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "repoFullName": { + "type": "string" + } + } + }, + "tags": [ + "securityagent", + "getlastsynctime", + "repofullname" + ], + "searchBlob": "securityAgent.getLastSyncTime Get the last time the security agent synced data for a given repository. securityagent getlastsynctime repofullname repoFullName" + }, + "securityAgent.getOrphanedRepositories": { + "path": "securityAgent.getOrphanedRepositories", + "kind": "query", + "summary": "Find repositories that are no longer connected or have been orphaned by the security agent.", + "inputSchema": {}, + "tags": [ + "securityagent", + "getorphanedrepositories" + ], + "searchBlob": "securityAgent.getOrphanedRepositories Find repositories that are no longer connected or have been orphaned by the security agent. securityagent getorphanedrepositories" + }, + "securityAgent.getPermissionStatus": { + "path": "securityAgent.getPermissionStatus", + "kind": "query", + "summary": "Check what permissions the security agent has, such as repository access, write access, or approval permissions.", + "inputSchema": {}, + "tags": [ + "securityagent", + "getpermissionstatus" + ], + "searchBlob": "securityAgent.getPermissionStatus Check what permissions the security agent has, such as repository access, write access, or approval permissions. securityagent getpermissionstatus" + }, + "securityAgent.getRepositories": { + "path": "securityAgent.getRepositories", + "kind": "query", + "summary": "List all repositories connected to or managed by the security agent.", + "inputSchema": {}, + "tags": [ + "securityagent", + "getrepositories" + ], + "searchBlob": "securityAgent.getRepositories List all repositories connected to or managed by the security agent. securityagent getrepositories" + }, + "securityAgent.getStats": { + "path": "securityAgent.getStats", + "kind": "query", + "summary": "Get overall summary statistics for the security agent's activity and findings.", + "inputSchema": {}, + "tags": [ + "securityagent", + "getstats" + ], + "searchBlob": "securityAgent.getStats Get overall summary statistics for the security agent's activity and findings. securityagent getstats" + }, + "securityAgent.listActiveCommands": { + "path": "securityAgent.listActiveCommands", + "kind": "query", + "summary": "List all security agent commands that are currently running or pending.", + "inputSchema": {}, + "tags": [ + "securityagent", + "listactivecommands" + ], + "searchBlob": "securityAgent.listActiveCommands List all security agent commands that are currently running or pending. securityagent listactivecommands" + }, + "securityAgent.listFindings": { + "path": "securityAgent.listFindings", + "kind": "query", + "summary": "List security findings or vulnerabilities, optionally filtered by repository, severity, or status.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "repoFullName": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "open", + "fixed", + "ignored", + "closed" + ] + }, + "severity": { + "type": "string", + "enum": [ + "critical", + "high", + "medium", + "low" + ] + }, + "outcomeFilter": { + "type": "string", + "enum": [ + "all", + "not_analyzed", + "analyzing", + "failed", + "exploitable", + "not_exploitable", + "safe_to_dismiss", + "needs_review", + "triage_complete", + "fixed", + "dismissed" + ] + }, + "overdue": { + "type": "boolean" + }, + "sortBy": { + "default": "severity_desc", + "type": "string", + "enum": [ + "severity_desc", + "severity_asc", + "sla_due_at_asc" + ] + }, + "limit": { + "default": 50, + "type": "number", + "minimum": 1, + "maximum": 100 + }, + "offset": { + "default": 0, + "type": "number", + "minimum": 0 + } + } + }, + "tags": [ + "securityagent", + "listfindings", + "repofullname", + "status", + "severity", + "outcomefilter", + "overdue", + "sortby", + "limit", + "offset" + ], + "searchBlob": "securityAgent.listFindings List security findings or vulnerabilities, optionally filtered by repository, severity, or status. securityagent listfindings repofullname status severity outcomefilter overdue sortby limit offset repoFullName status severity outcomeFilter overdue sortBy limit offset" + }, + "securityAuditLog.getActionTypes": { + "path": "securityAuditLog.getActionTypes", + "kind": "query", + "summary": "Get the list of all possible security audit log action types an entry can have.", + "inputSchema": {}, + "tags": [ + "securityauditlog", + "getactiontypes" + ], + "searchBlob": "securityAuditLog.getActionTypes Get the list of all possible security audit log action types an entry can have. securityauditlog getactiontypes" + }, + "securityAuditLog.getSummary": { + "path": "securityAuditLog.getSummary", + "kind": "query", + "summary": "Get an overview of the security audit log, including the total number of events and the earliest and latest event timestamps.", + "inputSchema": {}, + "tags": [ + "securityauditlog", + "getsummary" + ], + "searchBlob": "securityAuditLog.getSummary Get an overview of the security audit log, including the total number of events and the earliest and latest event timestamps. securityauditlog getsummary" + }, + "securityAuditLog.list": { + "path": "securityAuditLog.list", + "kind": "query", + "summary": "Search and paginate security audit log entries, filtering by action type, actor email, resource type or ID, free-text metadata search, and a time range or cursor window.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "before": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "after": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "action": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "security.finding.created", + "security.finding.severity_changed", + "security.finding.status_change", + "security.finding.dismissed", + "security.finding.auto_dismissed", + "security.finding.superseded", + "security.finding.analysis_started", + "security.finding.analysis_completed", + "security.finding.analysis_failed", + "security.remediation.queued", + "security.remediation.started", + "security.remediation.pr_opened", + "security.remediation.failed", + "security.remediation.blocked", + "security.remediation.no_changes_needed", + "security.remediation.cancelled", + "security.remediation.retried", + "security.finding.deleted", + "security.config.enabled", + "security.config.disabled", + "security.config.updated", + "security.sync.triggered", + "security.sync.completed", + "security.audit_log.exported", + "security.audit_report.generated" + ] + } + }, + "actorEmail": { + "type": "string", + "format": "email", + "pattern": "^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$" + }, + "resourceType": { + "type": "string", + "maxLength": 100 + }, + "resourceId": { + "type": "string", + "maxLength": 500 + }, + "fuzzySearch": { + "type": "string", + "maxLength": 200 + }, + "startTime": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "endTime": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + } + } + }, + "tags": [ + "securityauditlog", + "list", + "before", + "after", + "action", + "actoremail", + "resourcetype", + "resourceid", + "fuzzysearch", + "starttime", + "endtime" + ], + "searchBlob": "securityAuditLog.list Search and paginate security audit log entries, filtering by action type, actor email, resource type or ID, free-text metadata search, and a time range or cursor window. securityauditlog list before after action actoremail resourcetype resourceid fuzzysearch starttime endtime before after action actorEmail resourceType resourceId fuzzySearch startTime endTime" + }, + "slack.getInstallation": { + "path": "slack.getInstallation", + "kind": "query", + "summary": "Check whether the Slack integration is installed for the current organization or workspace, and retrieve installation details like team ID, team name, installation status, scopes, missing scopes, and installed date.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "slack", + "getinstallation", + "organizationid" + ], + "searchBlob": "slack.getInstallation Check whether the Slack integration is installed for the current organization or workspace, and retrieve installation details like team ID, team name, installation status, scopes, missing scopes, and installed date. slack getinstallation organizationid organizationId" + }, + "unifiedSessions.list": { + "path": "unifiedSessions.list", + "kind": "query", + "summary": "List CLI sessions (across both session storage versions) with pagination, filtering by platform, organization, repository git URL, or sub-session inclusion, plus ordering and optional time-bounded recent results. Use to page through a user's session history or fetch sessions updated since a timestamp.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cursor": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "limit": { + "default": 10, + "type": "number", + "minimum": 1, + "maximum": 50 + }, + "createdOnPlatform": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + { + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 100 + } + } + ] + }, + "orderBy": { + "default": "updated_at", + "type": "string", + "enum": [ + "created_at", + "updated_at" + ] + }, + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + }, + "includeSubSessions": { + "default": false, + "type": "boolean" + }, + "gitUrl": { + "anyOf": [ + { + "type": "string" + }, + { + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "updatedSince": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + } + } + }, + "tags": [ + "unifiedsessions", + "list", + "cursor", + "limit", + "createdonplatform", + "orderby", + "organizationid", + "includesubsessions", + "giturl", + "updatedsince" + ], + "searchBlob": "unifiedSessions.list List CLI sessions (across both session storage versions) with pagination, filtering by platform, organization, repository git URL, or sub-session inclusion, plus ordering and optional time-bounded recent results. Use to page through a user's session history or fetch sessions updated since a timestamp. unifiedsessions list cursor limit createdonplatform orderby organizationid includesubsessions giturl updatedsince cursor limit createdOnPlatform orderBy organizationId includeSubSessions gitUrl updatedSince" + }, + "unifiedSessions.recentRepositories": { + "path": "unifiedSessions.recentRepositories", + "kind": "query", + "summary": "Get the most recently used git repositories for the current user or an organization, deduplicated by git URL and ranked by last session update, optionally filtered to sessions updated since a given time. Use to show a picker of recently worked-on repos.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + }, + "updatedSince": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + } + }, + "required": [ + "updatedSince" + ] + }, + "tags": [ + "unifiedsessions", + "recentrepositories", + "organizationid", + "updatedsince" + ], + "searchBlob": "unifiedSessions.recentRepositories Get the most recently used git repositories for the current user or an organization, deduplicated by git URL and ranked by last session update, optionally filtered to sessions updated since a given time. Use to show a picker of recently worked-on repos. unifiedsessions recentrepositories organizationid updatedsince organizationId updatedSince" + }, + "unifiedSessions.search": { + "path": "unifiedSessions.search", + "kind": "query", + "summary": "Full-text search over a user's CLI sessions (title or session ID substring match) with optional scoping by organization, platform, git URL, or sub-session inclusion, returning paginated results plus total match count. Use for keyword lookup of past sessions.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "search_string": { + "type": "string", + "minLength": 1 + }, + "limit": { + "default": 10, + "type": "number", + "minimum": 1, + "maximum": 50 + }, + "offset": { + "default": 0, + "type": "number", + "minimum": 0 + }, + "createdOnPlatform": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + { + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 100 + } + } + ] + }, + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + }, + "includeSubSessions": { + "default": false, + "type": "boolean" + }, + "gitUrl": { + "anyOf": [ + { + "type": "string" + }, + { + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + } + ] + } + }, + "required": [ + "search_string" + ] + }, + "tags": [ + "unifiedsessions", + "search", + "search_string", + "limit", + "offset", + "createdonplatform", + "organizationid", + "includesubsessions", + "giturl" + ], + "searchBlob": "unifiedSessions.search Full-text search over a user's CLI sessions (title or session ID substring match) with optional scoping by organization, platform, git URL, or sub-session inclusion, returning paginated results plus total match count. Use for keyword lookup of past sessions. unifiedsessions search search_string limit offset createdonplatform organizationid includesubsessions giturl search_string limit offset createdOnPlatform organizationId includeSubSessions gitUrl" + }, + "usageAnalytics.getBreakdown": { + "path": "usageAnalytics.getBreakdown", + "kind": "query", + "summary": "Rank a dimension (model, feature, project, provider, user, mode) by an aggregate metric to show top contributors and their percentages.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "startDate": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "endDate": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "granularity": { + "type": "string", + "enum": [ + "hour", + "day", + "week", + "month" + ] + }, + "costSource": { + "default": "cost", + "type": "string", + "enum": [ + "cost", + "market" + ] + }, + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "organizationIds": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "personalScope": { + "default": "personal-only", + "type": "string", + "enum": [ + "personal-only", + "include-orgs" + ] + }, + "viewAs": { + "default": "self", + "type": "string", + "enum": [ + "self", + "org-wide" + ] + }, + "features": { + "type": "array", + "items": { + "type": "string" + } + }, + "models": { + "type": "array", + "items": { + "type": "string" + } + }, + "modes": { + "type": "array", + "items": { + "type": "string" + } + }, + "userIds": { + "type": "array", + "items": { + "type": "string" + } + }, + "providers": { + "type": "array", + "items": { + "type": "string" + } + }, + "projects": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedFeatures": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedModels": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedModes": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedUserIds": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedProviders": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedProjects": { + "type": "array", + "items": { + "type": "string" + } + }, + "dimension": { + "type": "string", + "enum": [ + "feature", + "model", + "mode", + "user", + "provider", + "project", + "organization" + ] + }, + "metric": { + "type": "string", + "enum": [ + "cost", + "requests", + "tokens" + ] + }, + "limit": { + "default": 15, + "type": "integer", + "minimum": 1, + "maximum": 1000 + } + }, + "required": [ + "startDate", + "endDate", + "granularity", + "dimension", + "metric" + ] + }, + "tags": [ + "usageanalytics", + "getbreakdown", + "startdate", + "enddate", + "granularity", + "costsource", + "organizationid", + "organizationids", + "personalscope", + "viewas", + "features", + "models", + "modes", + "userids", + "providers", + "projects", + "excludedfeatures", + "excludedmodels", + "excludedmodes", + "excludeduserids", + "excludedproviders", + "excludedprojects", + "dimension", + "metric", + "limit" + ], + "searchBlob": "usageAnalytics.getBreakdown Rank a dimension (model, feature, project, provider, user, mode) by an aggregate metric to show top contributors and their percentages. usageanalytics getbreakdown startdate enddate granularity costsource organizationid organizationids personalscope viewas features models modes userids providers projects excludedfeatures excludedmodels excludedmodes excludeduserids excludedproviders excludedprojects dimension metric limit startDate endDate granularity costSource organizationId organizationIds personalScope viewAs features models modes userIds providers projects excludedFeatures excludedModels excludedModes excludedUserIds excludedProviders excludedProjects dimension metric limit" + }, + "usageAnalytics.getScopeOrganizations": { + "path": "usageAnalytics.getScopeOrganizations", + "kind": "query", + "summary": "List an organization and its non-deleted child organizations available as a usage analytics scope filter.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "usageanalytics", + "getscopeorganizations", + "organizationid" + ], + "searchBlob": "usageAnalytics.getScopeOrganizations List an organization and its non-deleted child organizations available as a usage analytics scope filter. usageanalytics getscopeorganizations organizationid organizationId" + }, + "usageAnalytics.getSummary": { + "path": "usageAnalytics.getSummary", + "kind": "query", + "summary": "Fetch aggregate usage totals (cost, requests, tokens, errors, latency, active users) over a date range for a user or organization, optionally filtered by model/feature/project/provider.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "startDate": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "endDate": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "granularity": { + "type": "string", + "enum": [ + "hour", + "day", + "week", + "month" + ] + }, + "costSource": { + "default": "cost", + "type": "string", + "enum": [ + "cost", + "market" + ] + }, + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "organizationIds": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "personalScope": { + "default": "personal-only", + "type": "string", + "enum": [ + "personal-only", + "include-orgs" + ] + }, + "viewAs": { + "default": "self", + "type": "string", + "enum": [ + "self", + "org-wide" + ] + }, + "features": { + "type": "array", + "items": { + "type": "string" + } + }, + "models": { + "type": "array", + "items": { + "type": "string" + } + }, + "modes": { + "type": "array", + "items": { + "type": "string" + } + }, + "userIds": { + "type": "array", + "items": { + "type": "string" + } + }, + "providers": { + "type": "array", + "items": { + "type": "string" + } + }, + "projects": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedFeatures": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedModels": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedModes": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedUserIds": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedProviders": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedProjects": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "startDate", + "endDate", + "granularity" + ] + }, + "tags": [ + "usageanalytics", + "getsummary", + "startdate", + "enddate", + "granularity", + "costsource", + "organizationid", + "organizationids", + "personalscope", + "viewas", + "features", + "models", + "modes", + "userids", + "providers", + "projects", + "excludedfeatures", + "excludedmodels", + "excludedmodes", + "excludeduserids", + "excludedproviders", + "excludedprojects" + ], + "searchBlob": "usageAnalytics.getSummary Fetch aggregate usage totals (cost, requests, tokens, errors, latency, active users) over a date range for a user or organization, optionally filtered by model/feature/project/provider. usageanalytics getsummary startdate enddate granularity costsource organizationid organizationids personalscope viewas features models modes userids providers projects excludedfeatures excludedmodels excludedmodes excludeduserids excludedproviders excludedprojects startDate endDate granularity costSource organizationId organizationIds personalScope viewAs features models modes userIds providers projects excludedFeatures excludedModels excludedModes excludedUserIds excludedProviders excludedProjects" + }, + "usageAnalytics.getTable": { + "path": "usageAnalytics.getTable", + "kind": "query", + "summary": "Return a tabular grid of usage rows (cost, tokens, errors) grouped by any combination of feature, model, mode, user, provider, and project dimensions over time.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "startDate": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "endDate": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "granularity": { + "type": "string", + "enum": [ + "hour", + "day", + "week", + "month" + ] + }, + "costSource": { + "default": "cost", + "type": "string", + "enum": [ + "cost", + "market" + ] + }, + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "organizationIds": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "personalScope": { + "default": "personal-only", + "type": "string", + "enum": [ + "personal-only", + "include-orgs" + ] + }, + "viewAs": { + "default": "self", + "type": "string", + "enum": [ + "self", + "org-wide" + ] + }, + "features": { + "type": "array", + "items": { + "type": "string" + } + }, + "models": { + "type": "array", + "items": { + "type": "string" + } + }, + "modes": { + "type": "array", + "items": { + "type": "string" + } + }, + "userIds": { + "type": "array", + "items": { + "type": "string" + } + }, + "providers": { + "type": "array", + "items": { + "type": "string" + } + }, + "projects": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedFeatures": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedModels": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedModes": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedUserIds": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedProviders": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedProjects": { + "type": "array", + "items": { + "type": "string" + } + }, + "groupBy": { + "maxItems": 3, + "type": "array", + "items": { + "type": "string", + "enum": [ + "feature", + "model", + "mode", + "user", + "provider", + "project" + ] + } + }, + "limit": { + "default": 1000, + "type": "integer", + "minimum": 1, + "maximum": 10000 + } + }, + "required": [ + "startDate", + "endDate", + "granularity", + "groupBy" + ] + }, + "tags": [ + "usageanalytics", + "gettable", + "startdate", + "enddate", + "granularity", + "costsource", + "organizationid", + "organizationids", + "personalscope", + "viewas", + "features", + "models", + "modes", + "userids", + "providers", + "projects", + "excludedfeatures", + "excludedmodels", + "excludedmodes", + "excludeduserids", + "excludedproviders", + "excludedprojects", + "groupby", + "limit" + ], + "searchBlob": "usageAnalytics.getTable Return a tabular grid of usage rows (cost, tokens, errors) grouped by any combination of feature, model, mode, user, provider, and project dimensions over time. usageanalytics gettable startdate enddate granularity costsource organizationid organizationids personalscope viewas features models modes userids providers projects excludedfeatures excludedmodels excludedmodes excludeduserids excludedproviders excludedprojects groupby limit startDate endDate granularity costSource organizationId organizationIds personalScope viewAs features models modes userIds providers projects excludedFeatures excludedModels excludedModes excludedUserIds excludedProviders excludedProjects groupBy limit" + }, + "usageAnalytics.getTimeseries": { + "path": "usageAnalytics.getTimeseries", + "kind": "query", + "summary": "Get a metric (requests, cost, tokens, latency, etc.) bucketed over time for a date range, optionally split into per-dimension series.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "startDate": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "endDate": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$" + }, + "granularity": { + "type": "string", + "enum": [ + "hour", + "day", + "week", + "month" + ] + }, + "costSource": { + "default": "cost", + "type": "string", + "enum": [ + "cost", + "market" + ] + }, + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "organizationIds": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "personalScope": { + "default": "personal-only", + "type": "string", + "enum": [ + "personal-only", + "include-orgs" + ] + }, + "viewAs": { + "default": "self", + "type": "string", + "enum": [ + "self", + "org-wide" + ] + }, + "features": { + "type": "array", + "items": { + "type": "string" + } + }, + "models": { + "type": "array", + "items": { + "type": "string" + } + }, + "modes": { + "type": "array", + "items": { + "type": "string" + } + }, + "userIds": { + "type": "array", + "items": { + "type": "string" + } + }, + "providers": { + "type": "array", + "items": { + "type": "string" + } + }, + "projects": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedFeatures": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedModels": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedModes": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedUserIds": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedProviders": { + "type": "array", + "items": { + "type": "string" + } + }, + "excludedProjects": { + "type": "array", + "items": { + "type": "string" + } + }, + "metric": { + "type": "string", + "enum": [ + "cost", + "requests", + "tokens", + "inputTokens", + "outputTokens", + "errorRate", + "avgLatencyMs", + "avgGenerationTimeMs", + "costPerRequest", + "tokensPerRequest", + "cacheHitRatio", + "outputInputRatio" + ] + }, + "splitBy": { + "type": "string", + "enum": [ + "feature", + "model", + "mode", + "user", + "provider", + "project" + ] + } + }, + "required": [ + "startDate", + "endDate", + "granularity", + "metric" + ] + }, + "tags": [ + "usageanalytics", + "gettimeseries", + "startdate", + "enddate", + "granularity", + "costsource", + "organizationid", + "organizationids", + "personalscope", + "viewas", + "features", + "models", + "modes", + "userids", + "providers", + "projects", + "excludedfeatures", + "excludedmodels", + "excludedmodes", + "excludeduserids", + "excludedproviders", + "excludedprojects", + "metric", + "splitby" + ], + "searchBlob": "usageAnalytics.getTimeseries Get a metric (requests, cost, tokens, latency, etc.) bucketed over time for a date range, optionally split into per-dimension series. usageanalytics gettimeseries startdate enddate granularity costsource organizationid organizationids personalscope viewas features models modes userids providers projects excludedfeatures excludedmodels excludedmodes excludeduserids excludedproviders excludedprojects metric splitby startDate endDate granularity costSource organizationId organizationIds personalScope viewAs features models modes userIds providers projects excludedFeatures excludedModels excludedModes excludedUserIds excludedProviders excludedProjects metric splitBy" + }, + "usageAnalytics.resolveOrgUsers": { + "path": "usageAnalytics.resolveOrgUsers", + "kind": "query", + "summary": "Resolve user IDs to names and emails, restricted to members of the given organizations (full list only for owners/billing managers).", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationIds": { + "minItems": 1, + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "userIds": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "organizationIds", + "userIds" + ] + }, + "tags": [ + "usageanalytics", + "resolveorgusers", + "organizationids", + "userids" + ], + "searchBlob": "usageAnalytics.resolveOrgUsers Resolve user IDs to names and emails, restricted to members of the given organizations (full list only for owners/billing managers). usageanalytics resolveorgusers organizationids userids organizationIds userIds" + }, + "user.getAuthProviders": { + "path": "user.getAuthProviders", + "kind": "query", + "summary": "List all auth providers (Google, Discord, etc.) linked to the current user, with email, avatar, and hosted domain for each.", + "inputSchema": {}, + "tags": [ + "user", + "getauthproviders" + ], + "searchBlob": "user.getAuthProviders List all auth providers (Google, Discord, etc.) linked to the current user, with email, avatar, and hosted domain for each. user getauthproviders" + }, + "user.getAutoTopUpPaymentMethod": { + "path": "user.getAutoTopUpPaymentMethod", + "kind": "query", + "summary": "Get the user's auto top-up settings, including whether it's enabled, the top-up amount, and the saved payment method details.", + "inputSchema": {}, + "tags": [ + "user", + "getautotopuppaymentmethod" + ], + "searchBlob": "user.getAutoTopUpPaymentMethod Get the user's auto top-up settings, including whether it's enabled, the top-up amount, and the saved payment method details. user getautotopuppaymentmethod" + }, + "user.getAutocompleteMetrics": { + "path": "user.getAutocompleteMetrics", + "kind": "query", + "summary": "Get aggregated usage metrics (cost, request count, tokens) for the autocomplete model over a time period, scoped to personal or organization view.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "viewType": { + "default": "personal", + "anyOf": [ + { + "type": "string", + "const": "personal" + }, + { + "type": "string", + "const": "all" + }, + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + ] + }, + "period": { + "default": "week", + "type": "string", + "enum": [ + "week", + "month", + "year", + "all" + ] + } + } + }, + "tags": [ + "user", + "getautocompletemetrics", + "viewtype", + "period" + ], + "searchBlob": "user.getAutocompleteMetrics Get aggregated usage metrics (cost, request count, tokens) for the autocomplete model over a time period, scoped to personal or organization view. user getautocompletemetrics viewtype period viewType period" + }, + "user.getBalance": { + "path": "user.getBalance", + "kind": "query", + "summary": "Get the current user's overall credit balance and whether it is depleted.", + "inputSchema": {}, + "tags": [ + "user", + "getbalance" + ], + "searchBlob": "user.getBalance Get the current user's overall credit balance and whether it is depleted. user getbalance" + }, + "user.getContextBalance": { + "path": "user.getContextBalance", + "kind": "query", + "summary": "Get the credit balance for a given organization context (or personal balance if no organization), including depletion status.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "user", + "getcontextbalance", + "organizationid" + ], + "searchBlob": "user.getContextBalance Get the credit balance for a given organization context (or personal balance if no organization), including depletion status. user getcontextbalance organizationid organizationId" + }, + "user.getCreditBlocks": { + "path": "user.getCreditBlocks", + "kind": "query", + "summary": "Get the current user's credit balance breakdown, including credit blocks, deductions enriched with instance names, and auto top-up status.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": {} + }, + "tags": [ + "user", + "getcreditblocks" + ], + "searchBlob": "user.getCreditBlocks Get the current user's credit balance breakdown, including credit blocks, deductions enriched with instance names, and auto top-up status. user getcreditblocks" + }, + "user.getCreditPurchaseConfirmation": { + "path": "user.getCreditPurchaseConfirmation", + "kind": "query", + "summary": "Get confirmation details for a specific personal credit purchase transaction by ID, including amount and purchase time.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "transactionId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "transactionId" + ] + }, + "tags": [ + "user", + "getcreditpurchaseconfirmation", + "transactionid" + ], + "searchBlob": "user.getCreditPurchaseConfirmation Get confirmation details for a specific personal credit purchase transaction by ID, including amount and purchase time. user getcreditpurchaseconfirmation transactionid transactionId" + }, + "user.getCreditPurchaseHistory": { + "path": "user.getCreditPurchaseHistory", + "kind": "query", + "summary": "Fetch a paginated history of the user's personal credit purchases and automatic top-ups with amounts and dates.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cursor": { + "default": 0, + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + } + }, + "tags": [ + "user", + "getcreditpurchasehistory", + "cursor" + ], + "searchBlob": "user.getCreditPurchaseHistory Fetch a paginated history of the user's personal credit purchases and automatic top-ups with amounts and dates. user getcreditpurchasehistory cursor cursor" + }, + "user.getDiscordGuildStatus": { + "path": "user.getDiscordGuildStatus", + "kind": "query", + "summary": "Check whether the user has linked their Discord account and has verified Discord server membership, with avatar and display name.", + "inputSchema": {}, + "tags": [ + "user", + "getdiscordguildstatus" + ], + "searchBlob": "user.getDiscordGuildStatus Check whether the user has linked their Discord account and has verified Discord server membership, with avatar and display name. user getdiscordguildstatus" + }, + "user.getMe": { + "path": "user.getMe", + "kind": "query", + "summary": "Get the currently logged-in user's basic info, including their ID and Google account email.", + "inputSchema": {}, + "tags": [ + "user", + "getme" + ], + "searchBlob": "user.getMe Get the currently logged-in user's basic info, including their ID and Google account email. user getme" + }, + "user.getMyPushTokens": { + "path": "user.getMyPushTokens", + "kind": "query", + "summary": "List all push notification tokens registered for the current user across platforms, with their locale.", + "inputSchema": {}, + "tags": [ + "user", + "getmypushtokens" + ], + "searchBlob": "user.getMyPushTokens List all push notification tokens registered for the current user across platforms, with their locale. user getmypushtokens" + }, + "user.getNotificationPreferences": { + "path": "user.getNotificationPreferences", + "kind": "query", + "summary": "Get the current user's notification preferences for push notifications, chat messages, balance alerts, security findings, and more.", + "inputSchema": {}, + "tags": [ + "user", + "getnotificationpreferences" + ], + "searchBlob": "user.getNotificationPreferences Get the current user's notification preferences for push notifications, chat messages, balance alerts, security findings, and more. user getnotificationpreferences" + }, + "user.listDeviceSessions": { + "path": "user.listDeviceSessions", + "kind": "query", + "summary": "List the current user's active device sessions with user agent and activity timestamps, marking which one is the current device.", + "inputSchema": {}, + "tags": [ + "user", + "listdevicesessions" + ], + "searchBlob": "user.listDeviceSessions List the current user's active device sessions with user agent and activity timestamps, marking which one is the current device. user listdevicesessions" + }, + "userExports.exportableOrganizations": { + "path": "userExports.exportableOrganizations", + "kind": "query", + "summary": "Get the list of organizations the current user is allowed to export data for.", + "inputSchema": {}, + "tags": [ + "userexports", + "exportableorganizations" + ], + "searchBlob": "userExports.exportableOrganizations Get the list of organizations the current user is allowed to export data for. userexports exportableorganizations" + }, + "userExports.list": { + "path": "userExports.list", + "kind": "query", + "summary": "List data exports visible to the current user — their own export requests plus exports belonging to organizations they can export from — with cursor-based pagination ordered newest first.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cursor": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "userexports", + "list", + "cursor" + ], + "searchBlob": "userExports.list List data exports visible to the current user — their own export requests plus exports belonging to organizations they can export from — with cursor-based pagination ordered newest first. userexports list cursor cursor" + }, + "userExports.uiAccess": { + "path": "userExports.uiAccess", + "kind": "query", + "summary": "Check whether cloud data export is enabled for the current user's account, returning an enabled flag and the user's email.", + "inputSchema": {}, + "tags": [ + "userexports", + "uiaccess" + ], + "searchBlob": "userExports.uiAccess Check whether cloud data export is enabled for the current user's account, returning an enabled flag and the user's email. userexports uiaccess" + }, + "webhookTriggers.capabilities": { + "path": "webhookTriggers.capabilities", + "kind": "query", + "summary": "Check which webhook trigger features the current user is allowed to use, such as whether they can set sandbox allocation limits.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "tags": [ + "webhooktriggers", + "capabilities", + "organizationid" + ], + "searchBlob": "webhookTriggers.capabilities Check which webhook trigger features the current user is allowed to use, such as whether they can set sandbox allocation limits. webhooktriggers capabilities organizationid organizationId" + }, + "webhookTriggers.get": { + "path": "webhookTriggers.get", + "kind": "query", + "summary": "Get the full configuration and inbound webhook URL for a single webhook trigger by its trigger ID.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "triggerId": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "^[a-z0-9-]+$" + }, + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "triggerId" + ] + }, + "tags": [ + "webhooktriggers", + "get", + "triggerid", + "organizationid" + ], + "searchBlob": "webhookTriggers.get Get the full configuration and inbound webhook URL for a single webhook trigger by its trigger ID. webhooktriggers get triggerid organizationid triggerId organizationId" + }, + "webhookTriggers.list": { + "path": "webhookTriggers.list", + "kind": "query", + "summary": "List webhook triggers owned by the current user or organization, with optional filtering by target type or activation mode, including their inbound webhook URLs.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "targetType": { + "type": "string", + "enum": [ + "cloud_agent", + "kiloclaw_chat" + ] + }, + "activationMode": { + "type": "string", + "enum": [ + "webhook", + "scheduled" + ] + } + } + }, + "tags": [ + "webhooktriggers", + "list", + "organizationid", + "targettype", + "activationmode" + ], + "searchBlob": "webhookTriggers.list List webhook triggers owned by the current user or organization, with optional filtering by target type or activation mode, including their inbound webhook URLs. webhooktriggers list organizationid targettype activationmode organizationId targetType activationMode" + }, + "webhookTriggers.listRequests": { + "path": "webhookTriggers.listRequests", + "kind": "query", + "summary": "List recent captured inbound requests for a specific webhook trigger, with an option to limit the number returned and enriched session identifiers.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "triggerId": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "^[a-z0-9-]+$" + }, + "organizationId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "limit": { + "default": 50, + "type": "number", + "minimum": 1, + "maximum": 100 + } + }, + "required": [ + "triggerId" + ] + }, + "tags": [ + "webhooktriggers", + "listrequests", + "triggerid", + "organizationid", + "limit" + ], + "searchBlob": "webhookTriggers.listRequests List recent captured inbound requests for a specific webhook trigger, with an option to limit the number returned and enriched session identifiers. webhooktriggers listrequests triggerid organizationid limit triggerId organizationId limit" + }, + "workspaceFolders.list": { + "path": "workspaceFolders.list", + "kind": "query", + "summary": "List the signed-in user's workspace folders, optionally scoped to an organization, including each folder's name, color, and assigned worktrees.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "organizationId": { + "anyOf": [ + { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "organizationId" + ] + }, + "tags": [ + "workspacefolders", + "list", + "organizationid" + ], + "searchBlob": "workspaceFolders.list List the signed-in user's workspace folders, optionally scoped to an organization, including each folder's name, color, and assigned worktrees. workspacefolders list organizationid organizationId" + } +} diff --git a/services/kilo-mcp/drizzle.config.ts b/services/kilo-mcp/drizzle.config.ts new file mode 100644 index 0000000000..27cf9ffb72 --- /dev/null +++ b/services/kilo-mcp/drizzle.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'drizzle-kit'; + +export default defineConfig({ + out: './drizzle', + schema: './src/db/sqlite-schema.ts', + dialect: 'sqlite', + driver: 'durable-sqlite', +}); diff --git a/services/kilo-mcp/drizzle/0000_happy_zaladane.sql b/services/kilo-mcp/drizzle/0000_happy_zaladane.sql new file mode 100644 index 0000000000..dbdd5feb69 --- /dev/null +++ b/services/kilo-mcp/drizzle/0000_happy_zaladane.sql @@ -0,0 +1,43 @@ +CREATE TABLE `oauth_clients` ( + `client_id` text PRIMARY KEY NOT NULL, + `redirect_uris` text NOT NULL, + `client_name` text NOT NULL, + `created_at` text NOT NULL +); +--> statement-breakpoint +CREATE TABLE `oauth_codes` ( + `code` text PRIMARY KEY NOT NULL, + `client_id` text NOT NULL, + `redirect_uri` text NOT NULL, + `code_challenge` text NOT NULL, + `resource` text NOT NULL, + `scope` text NOT NULL, + `state` text, + `device_auth_code` text NOT NULL, + `status` text NOT NULL, + `kilo_user_id` text, + `organization_id` text, + `created_at` text NOT NULL, + `expires_at` text NOT NULL +); +--> statement-breakpoint +CREATE UNIQUE INDEX `uq_oauth_codes_device_auth_code` ON `oauth_codes` (`device_auth_code`);--> statement-breakpoint +CREATE TABLE `oauth_refresh_tokens` ( + `id` text PRIMARY KEY NOT NULL, + `token_hash` text NOT NULL, + `client_id` text NOT NULL, + `kilo_user_id` text NOT NULL, + `organization_id` text, + `resource` text NOT NULL, + `scope` text NOT NULL, + `created_at` text NOT NULL, + `expires_at` text NOT NULL, + `revoked_at` text +); +--> statement-breakpoint +CREATE UNIQUE INDEX `uq_oauth_refresh_tokens_hash` ON `oauth_refresh_tokens` (`token_hash`);--> statement-breakpoint +CREATE TABLE `oauth_revoked_jtis` ( + `jti` text PRIMARY KEY NOT NULL, + `expires_at` text NOT NULL, + `revoked_at` text NOT NULL +); diff --git a/services/kilo-mcp/drizzle/0001_cynical_karen_page.sql b/services/kilo-mcp/drizzle/0001_cynical_karen_page.sql new file mode 100644 index 0000000000..074d2f8fb1 --- /dev/null +++ b/services/kilo-mcp/drizzle/0001_cynical_karen_page.sql @@ -0,0 +1,2 @@ +ALTER TABLE `oauth_codes` ADD `kilo_token` text;--> statement-breakpoint +ALTER TABLE `oauth_refresh_tokens` ADD `kilo_token` text; \ No newline at end of file diff --git a/services/kilo-mcp/drizzle/meta/0000_snapshot.json b/services/kilo-mcp/drizzle/meta/0000_snapshot.json new file mode 100644 index 0000000000..92df827853 --- /dev/null +++ b/services/kilo-mcp/drizzle/meta/0000_snapshot.json @@ -0,0 +1,284 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "0c134f8b-e982-425f-b22f-9c5dd87fae5a", + "prevId": "00000000-0000-0000-0000-000000000000", + "tables": { + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_name": { + "name": "client_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code": { + "name": "code", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "resource": { + "name": "resource", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "device_auth_code": { + "name": "device_auth_code", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "uq_oauth_codes_device_auth_code": { + "name": "uq_oauth_codes_device_auth_code", + "columns": [ + "device_auth_code" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_refresh_tokens": { + "name": "oauth_refresh_tokens", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resource": { + "name": "resource", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "uq_oauth_refresh_tokens_hash": { + "name": "uq_oauth_refresh_tokens_hash", + "columns": [ + "token_hash" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_revoked_jtis": { + "name": "oauth_revoked_jtis", + "columns": { + "jti": { + "name": "jti", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/services/kilo-mcp/drizzle/meta/0001_snapshot.json b/services/kilo-mcp/drizzle/meta/0001_snapshot.json new file mode 100644 index 0000000000..d3d3346185 --- /dev/null +++ b/services/kilo-mcp/drizzle/meta/0001_snapshot.json @@ -0,0 +1,298 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "de5fdd44-ee26-4954-aa42-e1860ad7acf8", + "prevId": "0c134f8b-e982-425f-b22f-9c5dd87fae5a", + "tables": { + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_name": { + "name": "client_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code": { + "name": "code", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "resource": { + "name": "resource", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "device_auth_code": { + "name": "device_auth_code", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kilo_token": { + "name": "kilo_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "uq_oauth_codes_device_auth_code": { + "name": "uq_oauth_codes_device_auth_code", + "columns": [ + "device_auth_code" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_refresh_tokens": { + "name": "oauth_refresh_tokens", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kilo_token": { + "name": "kilo_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resource": { + "name": "resource", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "uq_oauth_refresh_tokens_hash": { + "name": "uq_oauth_refresh_tokens_hash", + "columns": [ + "token_hash" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_revoked_jtis": { + "name": "oauth_revoked_jtis", + "columns": { + "jti": { + "name": "jti", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/services/kilo-mcp/drizzle/meta/_journal.json b/services/kilo-mcp/drizzle/meta/_journal.json new file mode 100644 index 0000000000..98f14d350e --- /dev/null +++ b/services/kilo-mcp/drizzle/meta/_journal.json @@ -0,0 +1,20 @@ +{ + "version": "7", + "dialect": "sqlite", + "entries": [ + { + "idx": 0, + "version": "6", + "when": 1788968431745, + "tag": "0000_happy_zaladane", + "breakpoints": true + }, + { + "idx": 1, + "version": "6", + "when": 1788976576814, + "tag": "0001_cynical_karen_page", + "breakpoints": true + } + ] +} \ No newline at end of file diff --git a/services/kilo-mcp/drizzle/migrations.d.ts b/services/kilo-mcp/drizzle/migrations.d.ts new file mode 100644 index 0000000000..d3e1b09f9c --- /dev/null +++ b/services/kilo-mcp/drizzle/migrations.d.ts @@ -0,0 +1,12 @@ +declare const migrations: { + journal: { + entries: Array<{ + idx: number; + when: number; + tag: string; + breakpoints: boolean; + }>; + }; + migrations: Record; +}; +export default migrations; diff --git a/services/kilo-mcp/drizzle/migrations.js b/services/kilo-mcp/drizzle/migrations.js new file mode 100644 index 0000000000..bc2628e46a --- /dev/null +++ b/services/kilo-mcp/drizzle/migrations.js @@ -0,0 +1,11 @@ +import journal from './meta/_journal.json'; +import m0000 from './0000_happy_zaladane.sql'; +import m0001 from './0001_cynical_karen_page.sql'; + +export default { + journal, + migrations: { + m0000, + m0001, + }, +}; diff --git a/services/kilo-mcp/package.json b/services/kilo-mcp/package.json new file mode 100644 index 0000000000..ed02734609 --- /dev/null +++ b/services/kilo-mcp/package.json @@ -0,0 +1,30 @@ +{ + "name": "kilo-mcp", + "private": true, + "type": "module", + "description": "Kilo remote MCP worker: catalog search + tRPC call proxy over MCP Streamable HTTP", + "scripts": { + "dev": "wrangler dev --env dev", + "deploy": "wrangler deploy", + "cf-typegen": "wrangler types", + "catalog:ensure-index": "node scripts/embed-catalog.ts ensure-index", + "catalog:embed": "node scripts/embed-catalog.ts", + "typecheck": "tsgo --noEmit", + "lint": "pnpm -w exec oxlint --config .oxlintrc.json services/kilo-mcp/src", + "test": "vitest run" + }, + "dependencies": { + "ajv": "8.20.0", + "ajv-formats": "3.0.1", + "drizzle-orm": "catalog:" + }, + "devDependencies": { + "@cloudflare/workers-types": "catalog:", + "@types/node": "catalog:", + "@typescript/native-preview": "catalog:", + "drizzle-kit": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:", + "wrangler": "catalog:" + } +} diff --git a/services/kilo-mcp/scripts/embed-catalog.ts b/services/kilo-mcp/scripts/embed-catalog.ts new file mode 100644 index 0000000000..87016c4c91 --- /dev/null +++ b/services/kilo-mcp/scripts/embed-catalog.ts @@ -0,0 +1,280 @@ +/// +/** + * Embed the Kilo catalog and upsert it into Vectorize. + * + * Reads services/kilo-mcp/catalog.json, embeds every row's searchBlob via the + * Cloudflare REST API (Workers AI run endpoint), and upserts the vectors with + * the procedure path as vector id (requirement 9) and {path, kind, tags} as + * metadata. Batches at ≤64 rows per request. + * + * Subcommands: + * (none)|upsert embed + upsert every catalog row + * ensure-index create the Vectorize index idempotently (pinned dimensions + * and metric from src/embedding.ts), then exit + * + * Referenced ONLY by the main-branch merge job and the one-time bootstrap — + * never by PR jobs (requirement 10). + * + * Env (all required): + * CLOUDFLARE_ACCOUNT_ID Cloudflare account id + * CLOUDFLARE_API_TOKEN API token with Workers AI + Vectorize permissions + * VECTORIZE_INDEX_NAME index name, e.g. kilo-mcp-catalog-dev + * + * Usage (from services/kilo-mcp): + * node scripts/embed-catalog.ts ensure-index + * node scripts/embed-catalog.ts upsert + */ +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +import { EMBEDDING_DIMENSIONS, EMBEDDING_METRIC, EMBEDDING_MODEL } from '../src/embedding.ts'; +import type { Catalog } from '../src/types.ts'; + +/** Cloudflare REST API root. */ +const API_ROOT = 'https://api.cloudflare.com/client/v4'; + +/** Rows per AI-embed / Vectorize-upsert request (requirement: batch ≤64). */ +export const EMBED_BATCH_SIZE = 64; + +/** One upsert record: vector id = procedure path, values = embedding, metadata. */ +type UpsertRecord = { + id: string; + values: number[]; + metadata: { path: string; kind: string; tags: string[] }; +}; + +type EmbedEnv = { + CLOUDFLARE_ACCOUNT_ID: string; + CLOUDFLARE_API_TOKEN: string; + VECTORIZE_INDEX_NAME: string; +}; + +type FetchLike = ( + url: string, + init?: { method?: string; headers?: Record; body?: string } +) => Promise<{ + ok: boolean; + status: number; + json(): Promise; +}>; + +type EmbedOptions = EmbedEnv & { + catalog: Catalog; + fetchImpl?: FetchLike; + log?: (message: string) => void; +}; + +/** Cloudflare REST envelope: `{success, errors, messages, result}`. */ +type CfEnvelope = { + success?: boolean; + errors?: Array<{ code?: number; message?: string }>; + result?: unknown; +}; + +function defaultFetch(): FetchLike { + return (url, init) => fetch(url, init); +} + +async function cfRequest( + fetchImpl: FetchLike, + env: EmbedEnv, + path: string, + init?: { method?: string; headers?: Record; body?: string } +): Promise { + const response = await fetchImpl(`${API_ROOT}${path}`, { + ...init, + headers: { + Authorization: `Bearer ${env.CLOUDFLARE_API_TOKEN}`, + 'Content-Type': 'application/json', + ...init?.headers, + }, + }); + let body: CfEnvelope = {}; + try { + body = (await response.json()) as CfEnvelope; + } catch { + // A non-JSON body is reported through the status check below. + } + if (!response.ok || body.success === false) { + const detail = (body.errors ?? []).map(error => error.message ?? String(error.code)).join('; '); + throw new CfApiError( + `Cloudflare API ${init?.method ?? 'GET'} ${path} failed (HTTP ${response.status}): ${detail || 'no error detail'}`, + response.status + ); + } + return body.result; +} + +/** Like cfRequest but maps HTTP 404 to null (index lookups). */ +async function cfRequestOptional( + fetchImpl: FetchLike, + env: EmbedEnv, + path: string +): Promise { + try { + return await cfRequest(fetchImpl, env, path); + } catch (error) { + if (error instanceof CfApiError && error.status === 404) return null; + throw error; + } +} + +/** Error carrying the HTTP status of a failed Cloudflare API call. */ +export class CfApiError extends Error { + readonly status: number; + constructor(message: string, status: number) { + super(message); + this.name = 'CfApiError'; + this.status = status; + } +} + +/** + * Create the Vectorize index idempotently: GET the index first; when it does + * not exist (HTTP 404), create it with the pinned dimensions and metric. + * An existing index is reported and left untouched. + */ +export async function ensureIndex( + options: EmbedOptions +): Promise<{ created: boolean; indexName: string }> { + const fetchImpl = options.fetchImpl ?? defaultFetch(); + const log = options.log ?? (() => {}); + const indexName = options.VECTORIZE_INDEX_NAME; + + const existing = await cfRequestOptional( + fetchImpl, + options, + `/accounts/${options.CLOUDFLARE_ACCOUNT_ID}/vectorize/v2/indexes/${indexName}` + ); + if (existing !== null) { + log(`✅ index "${indexName}" already exists`); + return { created: false, indexName }; + } + await cfRequest( + fetchImpl, + options, + `/accounts/${options.CLOUDFLARE_ACCOUNT_ID}/vectorize/v2/indexes`, + { + method: 'POST', + body: JSON.stringify({ + name: indexName, + config: { dimensions: EMBEDDING_DIMENSIONS, metric: EMBEDDING_METRIC }, + description: 'Kilo API catalog semantic index (kilo-mcp hybrid search)', + }), + } + ); + log( + `✅ created index "${indexName}" (dimensions=${EMBEDDING_DIMENSIONS}, metric=${EMBEDDING_METRIC})` + ); + return { created: true, indexName }; +} + +/** + * Embed every catalog row's searchBlob and upsert it into the index. + * Returns the number of vectors written. + */ +export async function embedAndUpsert(options: EmbedOptions): Promise<{ vectors: number }> { + const fetchImpl = options.fetchImpl ?? defaultFetch(); + const log = options.log ?? (() => {}); + + const rows = Object.values(options.catalog); + if (rows.length === 0) { + log('catalog is empty; nothing to embed'); + return { vectors: 0 }; + } + + let vectors = 0; + for (let start = 0; start < rows.length; start += EMBED_BATCH_SIZE) { + const batch = rows.slice(start, start + EMBED_BATCH_SIZE); + const result = (await cfRequest( + fetchImpl, + options, + `/accounts/${options.CLOUDFLARE_ACCOUNT_ID}/ai/run/${EMBEDDING_MODEL}`, + { method: 'POST', body: JSON.stringify({ text: batch.map(row => row.searchBlob) }) } + )) as { data?: number[][] }; + + const embeddings = result.data; + if (!Array.isArray(embeddings) || embeddings.length !== batch.length) { + throw new Error( + `embedding model ${EMBEDDING_MODEL} returned ${embeddings?.length ?? 'no'} vectors for a batch of ${batch.length}` + ); + } + + const records: UpsertRecord[] = batch.map((row, index) => ({ + id: row.path, + values: embeddings[index], + metadata: { path: row.path, kind: row.kind, tags: row.tags }, + })); + // Vectorize v2 upsert accepts NDJSON (one record per line). + const ndjson = records.map(record => JSON.stringify(record)).join('\n'); + const upsert = (await cfRequest( + fetchImpl, + options, + `/accounts/${options.CLOUDFLARE_ACCOUNT_ID}/vectorize/v2/indexes/${options.VECTORIZE_INDEX_NAME}/upsert`, + { method: 'POST', headers: { 'Content-Type': 'application/x-ndjson' }, body: ndjson } + )) as { count?: number }; + vectors += upsert.count ?? records.length; + log( + ` batch ${Math.floor(start / EMBED_BATCH_SIZE) + 1}/${Math.ceil(rows.length / EMBED_BATCH_SIZE)}: embedded + upserted ${batch.length} vectors` + ); + } + + log( + `✅ upserted ${vectors} vectors into "${options.VECTORIZE_INDEX_NAME}" (${rows.length} catalog rows)` + ); + return { vectors }; +} + +function envFromProcess(): EmbedEnv { + const missing = ['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN', 'VECTORIZE_INDEX_NAME'].filter( + name => !process.env[name] + ); + if (missing.length > 0) { + throw new Error(`missing required env: ${missing.join(', ')}`); + } + const read = (name: string): string => process.env[name] ?? ''; + return { + CLOUDFLARE_ACCOUNT_ID: read('CLOUDFLARE_ACCOUNT_ID'), + CLOUDFLARE_API_TOKEN: read('CLOUDFLARE_API_TOKEN'), + VECTORIZE_INDEX_NAME: read('VECTORIZE_INDEX_NAME'), + }; +} + +/** Read the committed catalog.json that sits next to this script's package. */ +export function loadCatalog(): Catalog { + // import.meta.url is ALREADY a file URL: decode it with fileURLToPath — + // pathToFileURL(import.meta.url) double-encodes and yields an ENOENT path. + const catalogPath = join(dirname(fileURLToPath(import.meta.url)), '..', 'catalog.json'); + return JSON.parse(readFileSync(catalogPath, 'utf8')) as Catalog; +} + +async function main(): Promise { + const env = envFromProcess(); + const options: EmbedOptions = { + ...env, + catalog: loadCatalog(), + log: message => console.log(message), + }; + const subcommand = process.argv[2]; + if (subcommand === 'ensure-index') { + await ensureIndex(options); + return; + } + // "upsert" is the explicit name of the default behavior, used by the + // main-branch merge job so the workflow line reads as what it does. + if (subcommand !== undefined && subcommand !== 'upsert') { + throw new Error( + `unknown subcommand "${subcommand}" (expected "upsert", "ensure-index", or none)` + ); + } + await embedAndUpsert(options); +} + +const isMain = Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href; +if (isMain) { + main().catch((error: unknown) => { + console.error('❌', error instanceof Error ? error.message : error); + process.exit(1); + }); +} diff --git a/services/kilo-mcp/src/auth.test.ts b/services/kilo-mcp/src/auth.test.ts new file mode 100644 index 0000000000..3feabd30f0 --- /dev/null +++ b/services/kilo-mcp/src/auth.test.ts @@ -0,0 +1,165 @@ +import { describe, expect, it } from 'vitest'; +import { authenticate, ORGANIZATION_ID_HEADER } from './auth'; +import { signJwt } from './auth/jwt'; + +const SECRET = 'unit-test-hmac-secret-32-bytes!!'; +const ISSUER = 'https://kilo-mcp.test'; +const RESOURCE = `${ISSUER}/mcp`; + +function requestWith(headers: Record): Request { + return new Request('https://kilo-mcp.test/mcp', { method: 'POST', headers }); +} + +async function mcpAccessToken(overrides: Record = {}): Promise { + return signJwt( + { + iss: ISSUER, + sub: 'kilo-user-1', + org: 'org-uuid-1', + aud: RESOURCE, + client_id: 'client-1', + exp: Math.floor(Date.now() / 1000) + 3600, + jti: 'jti-1', + ...overrides, + }, + SECRET + ); +} + +const mcpToken = { tokenSecret: SECRET, issuer: ISSUER, resource: RESOURCE }; + +function bearerRequest(token: string, extra: Record = {}): Request { + return requestWith({ Authorization: `Bearer ${token}`, ...extra }); +} + +describe('authenticate (s2 passthrough)', () => { + it('returns null when there is no Authorization header', async () => { + expect(await authenticate(requestWith({ 'Content-Type': 'application/json' }))).toBeNull(); + }); + + it('returns null when the Authorization header is not a bearer token', async () => { + expect(await authenticate(requestWith({ Authorization: 'Basic dXNlcjpwYXNz' }))).toBeNull(); + expect(await authenticate(requestWith({ Authorization: 'Bearer' }))).toBeNull(); + expect(await authenticate(requestWith({ Authorization: 'Bearer ' }))).toBeNull(); + }); + + it('forwards the bearer token and org header to apps/web', async () => { + const auth = await authenticate( + requestWith({ + Authorization: 'Bearer tok_123', + [ORGANIZATION_ID_HEADER]: 'org-uuid-1', + }) + ); + expect(auth).toEqual({ authorization: 'Bearer tok_123', organizationId: 'org-uuid-1' }); + }); + + it('accepts a bearer token without an organization header', async () => { + const auth = await authenticate(requestWith({ Authorization: 'Bearer tok_123' })); + expect(auth).toEqual({ authorization: 'Bearer tok_123', organizationId: undefined }); + }); + + it('is case-insensitive on the scheme and header name', async () => { + const auth = await authenticate( + new Request('https://kilo-mcp.test/mcp', { + method: 'POST', + headers: { authorization: 'bearer tok_123' }, + }) + ); + expect(auth?.authorization).toBe('bearer tok_123'); + }); + + it('without MCP deps, any bearer keeps the s2 passthrough', async () => { + const token = await mcpAccessToken(); + const auth = await authenticate(bearerRequest(token)); + expect(auth).toEqual({ authorization: `Bearer ${token}`, organizationId: undefined }); + expect(auth?.mcpIdentity).toBeUndefined(); + }); +}); + +describe('authenticate (s5 verify + s6 enforcement: only MCP tokens)', () => { + const withKilo = { + mcpToken, + resolveKiloToken: async (identity: { kiloUserId: string; clientId: string }) => + identity.kiloUserId === 'kilo-user-1' && identity.clientId === 'client-1' + ? 'kilo-app-token' + : null, + }; + + it('verifies an MCP token and forwards the bound Kilo credential + org from its claims', async () => { + const token = await mcpAccessToken(); + const auth = await authenticate( + bearerRequest(token, { [ORGANIZATION_ID_HEADER]: 'spoofed' }), + withKilo + ); + expect(auth).not.toBeNull(); + // apps/web cannot verify this worker's JWT: the forwarded bearer is the + // Kilo token the grant was minted from, not the MCP token. + expect(auth?.authorization).toBe('Bearer kilo-app-token'); + expect(auth?.organizationId).toBe('org-uuid-1'); + expect(auth?.mcpIdentity).toMatchObject({ + kiloUserId: 'kilo-user-1', + organizationId: 'org-uuid-1', + clientId: 'client-1', + }); + }); + + it('the caller-supplied organization header is ignored; the org claim wins', async () => { + const token = await mcpAccessToken({ org: null }); + const auth = await authenticate( + bearerRequest(token, { [ORGANIZATION_ID_HEADER]: 'attacker-org' }), + withKilo + ); + expect(auth?.organizationId).toBeUndefined(); + expect(auth?.mcpIdentity?.organizationId).toBeNull(); + }); + + it('personal (org-less) tokens verify with no organization', async () => { + const token = await mcpAccessToken({ org: null }); + const auth = await authenticate(bearerRequest(token), withKilo); + expect(auth?.organizationId).toBeUndefined(); + expect(auth?.mcpIdentity?.organizationId).toBeNull(); + }); + + it('an expired MCP token is rejected, not forwarded', async () => { + const token = await mcpAccessToken({ exp: Math.floor(Date.now() / 1000) - 10 }); + expect(await authenticate(bearerRequest(token), withKilo)).toBeNull(); + }); + + it('a revoked MCP token is rejected', async () => { + const token = await mcpAccessToken({ jti: 'revoked-jti' }); + const auth = await authenticate(bearerRequest(token), { + ...withKilo, + mcpToken: { ...mcpToken, isJtiRevoked: async (jti: string) => jti === 'revoked-jti' }, + }); + expect(auth).toBeNull(); + }); + it('a token for a different audience is rejected', async () => { + const token = await mcpAccessToken({ aud: 'https://other-mcp.test/mcp' }); + expect(await authenticate(bearerRequest(token), withKilo)).toBeNull(); + }); + + it('a token signed with a different secret is rejected — no passthrough', async () => { + const token = await signJwt( + { + iss: ISSUER, + sub: 'x', + org: null, + aud: RESOURCE, + client_id: 'c', + exp: Math.floor(Date.now() / 1000) + 60, + jti: 'j', + }, + 'another-secret-not-ours-at-all!!' + ); + expect(await authenticate(bearerRequest(token), withKilo)).toBeNull(); + }); + + it('a non-JWT bearer (an apps/web app token) is rejected — only MCP tokens pass', async () => { + expect(await authenticate(bearerRequest('tok_app_123'), withKilo)).toBeNull(); + }); + + it('a valid MCP token whose grant lost its Kilo credential is rejected (reconnect)', async () => { + const token = await mcpAccessToken({ sub: 'user-without-grant' }); + expect(await authenticate(bearerRequest(token), withKilo)).toBeNull(); + }); +}); diff --git a/services/kilo-mcp/src/auth.ts b/services/kilo-mcp/src/auth.ts new file mode 100644 index 0000000000..131efc075f --- /dev/null +++ b/services/kilo-mcp/src/auth.ts @@ -0,0 +1,83 @@ +import { + verifyMcpAccessToken, + type VerifyMcpTokenDeps, + type VerifiedMcpToken, +} from './auth/verify'; +import type { ForwardedAuth } from './types'; + +/** + * Organization header name. Mirrors ORGANIZATION_ID_HEADER in + * apps/web/src/lib/constants.ts:19 — apps/web reads it to scope identity to an + * org (apps/web/src/lib/user/server.ts). Keep in sync if the web constant ever + * changes. + */ +export const ORGANIZATION_ID_HEADER = 'x-kilocode-organizationid'; + +export type AuthenticateDeps = { + /** + * MCP token verification (s5). When present, /mcp accepts ONLY a bearer that + * verifies as this worker's own MCP access token (s6 enforcement): a foreign + * bearer, an expired/revoked/wrong-audience MCP token, or a malformed token + * is rejected (no passthrough). The forwarded identity — bearer + org — + * comes entirely from the verified token's claims; the caller-supplied + * organization header is ignored. Without this dep (a worker missing its + * OAuth bindings) the s2 passthrough stays so the misconfigured worker still + * answers. + */ + mcpToken?: VerifyMcpTokenDeps; + /** + * Resolve the Kilo API token to forward for a verified MCP identity (s6). + * apps/web cannot verify this worker's MCP JWT, so a verified token is + * exchanged for the Kilo credential its grant was minted from. Null when no + * live grant holds one (the user must reconnect) — treated as a rejection. + */ + resolveKiloToken?: (identity: VerifiedMcpToken) => Promise; +}; + +/** + * Extract the credentials to forward to apps/web. Returns null when the + * request has no usable bearer (or, with MCP verification on, when the bearer + * is not a live MCP token), which the transport answers with 401 before any + * upstream request is made. + * + * Never log the returned values; they embed a live token. + */ +export async function authenticate( + request: Request, + deps?: AuthenticateDeps +): Promise { + const authorization = request.headers.get('Authorization'); + if (!authorization || !/^Bearer\s+\S+/i.test(authorization)) { + return null; + } + + if (deps?.mcpToken) { + const bearer = authorization.replace(/^Bearer\s+/i, ''); + const verification = await verifyMcpAccessToken(bearer, deps.mcpToken); + if (!verification.ok) { + // s6: only MCP tokens reach the catalog. Any non-verified bearer — + // foreign, malformed, expired, revoked, wrong audience — is rejected. + return null; + } + // The token is bound to user + org + this MCP (requirement 18); the org + // claim is authoritative and the caller-supplied header is ignored. + const kiloToken = deps.resolveKiloToken + ? await deps.resolveKiloToken(verification.token) + : null; + if (!kiloToken) { + // A live MCP token whose grant no longer carries a Kilo credential: the + // user must reconnect. Reject before any catalog or upstream work. + return null; + } + return { + authorization: `Bearer ${kiloToken}`, + organizationId: verification.token.organizationId ?? undefined, + mcpIdentity: verification.token, + }; + } + + // Unconfigured worker (no OAuth bindings): s2 passthrough of the caller's + // bearer and organization header. + const headerOrganizationId = request.headers.get(ORGANIZATION_ID_HEADER) ?? undefined; + return { authorization, organizationId: headerOrganizationId }; +} diff --git a/services/kilo-mcp/src/auth/authorize.test.ts b/services/kilo-mcp/src/auth/authorize.test.ts new file mode 100644 index 0000000000..92bd3b575e --- /dev/null +++ b/services/kilo-mcp/src/auth/authorize.test.ts @@ -0,0 +1,312 @@ +import { describe, expect, it, vi } from 'vitest'; +import { handleAuthorize } from './authorize'; +import { codeChallengeFromVerifier, generateCodeVerifier } from './pkce'; +import type { + NewOAuthCode, + OAuthCodeRecord, + OAuthStoreApi, + StoredClient, +} from '../store/oauth-store'; + +/** + * In-memory OAuthStoreApi for these endpoint tests. Methods these tests never + * reach throw, so a new handler dependency fails loudly instead of silently. + */ +function createFakeOAuthStore(): OAuthStoreApi & { + clients: Map; + codes: Map; +} { + const clients = new Map(); + const codes = new Map(); + const unused = (): never => { + throw new Error('not reachable from these tests'); + }; + return { + clients, + codes, + async registerClient(input) { + clients.set(input.clientId, { ...input, redirectUris: [...input.redirectUris] }); + }, + async getClient(clientId) { + const client = clients.get(clientId); + return client ? { ...client, redirectUris: [...client.redirectUris] } : null; + }, + async createCode(input: NewOAuthCode) { + codes.set(input.code, { + ...input, + status: 'pending', + kiloUserId: null, + organizationId: null, + kiloToken: null, + }); + }, + async getCode(code) { + const record = codes.get(code); + return record ? { ...record } : null; + }, + recordPairingApproval: unused, + denyCode: unused, + async approveCode(deviceAuthCode, identity, nowIso) { + for (const [code, record] of codes) { + if ( + record.deviceAuthCode === deviceAuthCode && + record.status === 'pending' && + record.expiresAt > nowIso + ) { + codes.set(code, { + ...record, + status: 'approved', + kiloUserId: identity.kiloUserId, + organizationId: identity.organizationId, + }); + return true; + } + } + return false; + }, + consumeCode: unused, + saveRefreshToken: unused, + getRefreshTokenByHash: unused, + rotateRefreshToken: unused, + getKiloToken: unused, + revokeGrant: unused, + revokeJti: unused, + async isJtiRevoked() { + return false; + }, + purgeExpired: unused, + }; +} + +const ISSUER = 'https://kilo-mcp.test'; +const WEB = 'https://app.kilo.test'; +const CLIENT_ID = 'client-abc'; +const REDIRECT = 'https://client.test/cb'; +const RESOURCE = `${ISSUER}/mcp`; + +const verifier = generateCodeVerifier(); + +function storeWithClient(): ReturnType { + const store = createFakeOAuthStore(); + store.clients.set(CLIENT_ID, { + clientId: CLIENT_ID, + redirectUris: [REDIRECT], + clientName: 'Test Client', + createdAt: '2026-09-09T00:00:00.000Z', + }); + return store; +} + +function authorizeUrl(params: Record): string { + const url = new URL(`${ISSUER}/authorize`); + for (const [key, value] of Object.entries(params)) { + if (value !== undefined) url.searchParams.set(key, value); + } + return url.toString(); +} + +function deviceAuthFetch(code = 'PAIR-1234') { + return vi.fn(async () => + Response.json({ + code, + user_code: code, + device_code: 'dev-secret', + verificationUrl: `${WEB}/device-auth?code=${code}`, + expiresIn: 600, + }) + ); +} + +async function authorize( + overrides: Record = {}, + deps: { store?: OAuthStoreApi; fetchImpl?: typeof fetch } = {} +): Promise<{ response: Response; store: ReturnType }> { + const store = deps.store ?? storeWithClient(); + const response = await handleAuthorize( + new Request( + authorizeUrl({ + client_id: CLIENT_ID, + redirect_uri: REDIRECT, + response_type: 'code', + scope: 'mcp', + state: 'st-1', + code_challenge: await codeChallengeFromVerifier(verifier), + code_challenge_method: 'S256', + resource: RESOURCE, + ...overrides, + }) + ), + { + store, + webBaseUrl: WEB, + fetchImpl: (deps.fetchImpl ?? deviceAuthFetch()) as typeof fetch, + } + ); + return { response, store: store as ReturnType }; +} + +describe('GET /authorize (happy)', () => { + it('creates the pairing record and links the user to the Kilo device-auth page', async () => { + const fetchImpl = deviceAuthFetch('PAIR-9999'); + const { response, store } = await authorize({}, { fetchImpl }); + expect(response.status).toBe(200); + expect(response.headers.get('Content-Type')).toContain('text/html'); + + expect(fetchImpl).toHaveBeenCalledTimes(1); + const [calledUrl, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit]; + expect(calledUrl).toBe(`${WEB}/api/device-auth/codes`); + expect(init.method).toBe('POST'); + + expect(store.codes.size).toBe(1); + const record = [...store.codes.values()][0]; + expect(record).toMatchObject({ + clientId: CLIENT_ID, + redirectUri: REDIRECT, + resource: RESOURCE, + scope: 'mcp', + state: 'st-1', + status: 'pending', + deviceAuthCode: 'PAIR-9999', + }); + expect(record.code.length).toBeGreaterThanOrEqual(43); + expect(new Date(record.expiresAt).getTime() - Date.now()).toBeGreaterThan(9 * 60_000); + + const html = await response.text(); + expect(html).toContain(`${WEB}/device-auth?code=PAIR-9999`); + expect(html).toContain('Test Client'); + expect(html).toContain('/authorize/status?code='); + // s6: the page shows the requested scope and offers a restart (fresh + // authorize) when the pairing fails. + expect(html).toContain('Requested access'); + expect(html).toContain('mcp'); + const restart = new URL( + html.match(/ { + const fetchImpl = deviceAuthFetch(); + const response = await handleAuthorize( + new Request( + authorizeUrl({ + client_id: CLIENT_ID, + redirect_uri: REDIRECT, + response_type: 'code', + code_challenge: await codeChallengeFromVerifier(verifier), + code_challenge_method: 'S256', + }), + { headers: { 'CF-Connecting-IP': '203.0.113.7', 'user-agent': 'MCPTest/1.0' } } + ), + { + store: storeWithClient(), + webBaseUrl: WEB, + fetchImpl: fetchImpl as unknown as typeof fetch, + } + ); + expect(response.status).toBe(200); + const [, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit]; + const headers = init.headers as Record; + expect(headers['x-forwarded-for']).toBe('203.0.113.7'); + expect(headers['user-agent']).toBe('MCPTest/1.0'); + }); + + it('defaults the scope to mcp and the resource to this MCP when omitted', async () => { + const { store } = await authorize({ scope: undefined, resource: undefined }); + const record = [...store.codes.values()][0]; + expect(record.scope).toBe('mcp'); + expect(record.resource).toBe(RESOURCE); + }); +}); + +describe('GET /authorize (non-retryable unhappy: explicit errors, no token path)', () => { + it('unknown client_id renders an error page and never redirects', async () => { + const { response } = await authorize({ client_id: 'ghost' }); + expect(response.status).toBe(400); + expect(response.headers.get('Location')).toBeNull(); + const html = await response.text(); + expect(html).toMatch(/Unknown client_id/); + }); + + it('redirect_uri mismatch renders an error page (exact match required)', async () => { + const { response } = await authorize({ redirect_uri: 'https://client.test/cb?next=1' }); + expect(response.status).toBe(400); + const html = await response.text(); + expect(html).toMatch(/does not exactly match/); + }); + + it('missing PKCE redirects the client with invalid_request', async () => { + const { response } = await authorize({ + code_challenge: undefined, + code_challenge_method: undefined, + }); + expect(response.status).toBe(302); + const location = new URL(response.headers.get('Location')!); + expect(location.origin + location.pathname).toBe(REDIRECT); + expect(location.searchParams.get('error')).toBe('invalid_request'); + expect(location.searchParams.get('state')).toBe('st-1'); + }); + + it('plain (non-S256) PKCE is rejected', async () => { + const { response } = await authorize({ code_challenge_method: 'plain' }); + expect(response.status).toBe(302); + expect(new URL(response.headers.get('Location')!).searchParams.get('error')).toBe( + 'invalid_request' + ); + }); + + it('a foreign resource indicator redirects with invalid_target', async () => { + const { response } = await authorize({ resource: 'https://other-mcp.test/mcp' }); + expect(response.status).toBe(302); + expect(new URL(response.headers.get('Location')!).searchParams.get('error')).toBe( + 'invalid_target' + ); + }); + + it('an unknown scope redirects with invalid_scope', async () => { + const { response } = await authorize({ scope: 'admin' }); + expect(response.status).toBe(302); + expect(new URL(response.headers.get('Location')!).searchParams.get('error')).toBe( + 'invalid_scope' + ); + }); + + it('only response_type=code is supported', async () => { + const { response } = await authorize({ response_type: 'token' }); + expect(response.status).toBe(302); + expect(new URL(response.headers.get('Location')!).searchParams.get('error')).toBe( + 'unsupported_response_type' + ); + }); +}); + +describe('GET /authorize (retryable unhappy: Kilo pairing unavailable)', () => { + it('a web rate-limit (429) renders a wait-and-retry message and stores no record', async () => { + const fetchImpl = vi.fn(async () => Response.json({ error: 'too many' }, { status: 429 })); + const { response, store } = await authorize( + {}, + { fetchImpl: fetchImpl as unknown as typeof fetch } + ); + expect(response.status).toBe(503); + const html = await response.text(); + expect(html).toMatch(/Wait a few minutes/); + expect(store.codes.size).toBe(0); + }); + + it('an unreachable web renders a retry message and stores no record', async () => { + const fetchImpl = vi.fn(async () => { + throw new Error('network down'); + }); + const { response, store } = await authorize( + {}, + { fetchImpl: fetchImpl as unknown as typeof fetch } + ); + expect(response.status).toBe(503); + const html = await response.text(); + expect(html).toMatch(/could not be reached/); + expect(store.codes.size).toBe(0); + }); +}); diff --git a/services/kilo-mcp/src/auth/authorize.ts b/services/kilo-mcp/src/auth/authorize.ts new file mode 100644 index 0000000000..3fad541132 --- /dev/null +++ b/services/kilo-mcp/src/auth/authorize.ts @@ -0,0 +1,262 @@ +/** + * GET /authorize — the OAuth authorization endpoint for THIS MCP. + * + * The worker has no user session of its own: apps/web stays the user-identity + * provider. So /authorize validates the request strictly (registered client, + * exact redirect_uri, mandatory S256 PKCE, RFC 8707 resource indicator, + * scope), creates a short-lived single-use pairing record, opens a Kilo + * device-auth pairing via apps/web, and returns the consent page (rendered by + * src/oauth-pages/authorize-page.ts) that links the user to + * `{WEB_BASE_URL}/device-auth?code=` and polls this worker for + * pairing status until the user signs in, picks an org, and the client is + * redirected with the code (s6). + */ +import { base64UrlEncode, isValidCodeChallenge } from './pkce'; +import { mcpResourceUrl } from './metadata'; +import { MCP_SCOPE, errorPage, redirectToClientError } from './http'; +import { consentPage } from '../oauth-pages/authorize-page'; +import type { OAuthStoreApi, StoredClient } from '../store/oauth-store'; + +export type AuthorizeDeps = { + store: OAuthStoreApi; + /** apps/web base URL — the user-identity provider (sign-in-with-Kilo page). */ + webBaseUrl: string; + fetchImpl?: typeof fetch; + now?: () => Date; +}; + +/** Pairing records are short-lived: 10 minutes to complete sign-in. */ +export const CODE_TTL_SECONDS = 600; +const MAX_STATE_LENGTH = 512; + +/** Redirect-with-error for failures after client + redirect_uri are trusted (RFC 6749 §4.1.2.1). */ +class AuthorizeRedirectError extends Error { + constructor( + readonly redirectUri: string, + readonly error: string, + readonly description: string, + readonly state: string | null + ) { + super(error); + this.name = 'AuthorizeRedirectError'; + } +} + +/** Non-redirectable validation failure — rendered as an error page. */ +class AuthorizePageError extends Error { + constructor(message: string) { + super(message); + this.name = 'AuthorizePageError'; + } +} + +export type ValidatedAuthorizeRequest = { + client: StoredClient; + redirectUri: string; + codeChallenge: string; + resource: string; + scope: string; + state: string | null; +}; + +/** + * Validate an authorization request. Client_id / redirect_uri failures return + * an error page (never a redirect — an unvalidated redirect target is a + * phishing vector, RFC 6749 §4.1.2.1); protocol failures after the client is + * trusted throw AuthorizeRedirectError so the caller can send the client home + * with `?error=`. + */ +export async function validateAuthorizeRequest( + url: URL, + store: OAuthStoreApi, + issuer: string +): Promise { + const params = url.searchParams; + const clientId = params.get('client_id'); + const redirectUri = params.get('redirect_uri'); + const state = params.get('state'); + + if (!clientId) { + throw new AuthorizePageError( + 'Missing client_id. Register this client through /register first.' + ); + } + const client = await store.getClient(clientId); + if (!client) { + throw new AuthorizePageError( + 'Unknown client_id. Register this client through /register before starting sign-in.' + ); + } + if (!redirectUri) { + throw new AuthorizePageError('Missing redirect_uri.'); + } + if (!client.redirectUris.includes(redirectUri)) { + throw new AuthorizePageError( + "redirect_uri does not exactly match one of this client's registered redirect URIs." + ); + } + // From here on the redirect target is trusted: errors ride the redirect. + const fail = (error: string, description: string): never => { + throw new AuthorizeRedirectError(redirectUri, error, description, state); + }; + + if (params.get('response_type') !== 'code') { + fail('unsupported_response_type', 'Only response_type=code is supported.'); + } + const codeChallenge = params.get('code_challenge'); + if (!isValidCodeChallenge(codeChallenge) || params.get('code_challenge_method') !== 'S256') { + // PKCE is mandatory and S256 is the only accepted method (requirement 16). + fail( + 'invalid_request', + 'PKCE is required: send code_challenge (43..128 base64url chars) with code_challenge_method=S256.' + ); + } + const resource = mcpResourceUrl(issuer); + const requestedResource = params.get('resource'); + if (requestedResource !== null && !sameResource(requestedResource, resource)) { + fail('invalid_target', 'The resource indicator must identify this MCP server.'); + } + const scope = params.get('scope'); + if (scope !== null && !validScope(scope)) { + fail('invalid_scope', `Only the "${MCP_SCOPE}" scope is available.`); + } + if (state !== null && state.length > MAX_STATE_LENGTH) { + fail('invalid_request', `state must be at most ${MAX_STATE_LENGTH} characters.`); + } + + return { + client, + redirectUri, + codeChallenge: codeChallenge as string, + resource, + scope: scope !== null && scope.trim().length > 0 ? normalizeScope(scope) : MCP_SCOPE, + state, + }; +} + +/** Trailing-slash-tolerant comparison against the canonical resource URL. */ +export function sameResource(candidate: string, canonical: string): boolean { + if (candidate === canonical) return true; + try { + const a = new URL(candidate); + const b = new URL(canonical); + if ( + a.origin !== b.origin || + a.search !== '' || + a.hash !== '' || + b.search !== '' || + b.hash !== '' + ) { + return false; + } + return a.pathname === b.pathname || a.pathname === `${b.pathname}/`; + } catch { + return false; + } +} + +function validScope(scope: string): boolean { + const tokens = scope.split(' ').filter(token => token.length > 0); + return tokens.length === 0 || tokens.every(token => token === MCP_SCOPE); +} + +function normalizeScope(scope: string): string { + return [...new Set(scope.split(' ').filter(token => token.length > 0))].join(' '); +} + +export type KiloPairingFailure = 'rate_limited' | 'unreachable'; + +/** + * Create the Kilo device-auth pairing on apps/web + * (`POST /api/device-auth/codes`, apps/web/src/app/api/device-auth/codes/route.ts). + * apps/web rate-limits pending pairings per IP and requires the client IP in + * production, so the incoming request's IP and user-agent are forwarded. + */ +export async function createKiloPairing( + deps: AuthorizeDeps, + request: Request +): Promise<{ ok: true; pairingCode: string } | { ok: false; kind: KiloPairingFailure }> { + const fetchImpl = deps.fetchImpl ?? fetch; + const url = `${deps.webBaseUrl.replace(/\/$/, '')}/api/device-auth/codes`; + const headers: Record = { 'content-type': 'application/json' }; + const clientIp = + request.headers.get('CF-Connecting-IP') ?? request.headers.get('x-forwarded-for'); + if (clientIp) headers['x-forwarded-for'] = clientIp; + const userAgent = request.headers.get('user-agent'); + if (userAgent) headers['user-agent'] = userAgent; + + let response: Response; + try { + response = await fetchImpl(url, { method: 'POST', headers, body: '{}' }); + } catch { + return { ok: false, kind: 'unreachable' }; + } + if (response.status === 429) return { ok: false, kind: 'rate_limited' }; + if (!response.ok) return { ok: false, kind: 'unreachable' }; + + const body: unknown = await response.json().catch(() => null); + const code = + typeof body === 'object' && body !== null ? (body as { code?: unknown }).code : undefined; + if (typeof code !== 'string' || code.length === 0) { + return { ok: false, kind: 'unreachable' }; + } + return { ok: true, pairingCode: code }; +} + +/** GET /authorize — consent page for a valid authorization request. */ +export async function handleAuthorize(request: Request, deps: AuthorizeDeps): Promise { + if (request.method !== 'GET') { + return errorPage('invalid_request', 'Use GET for /authorize.'); + } + const url = new URL(request.url); + const issuer = url.origin; + + let validated: ValidatedAuthorizeRequest; + try { + validated = await validateAuthorizeRequest(url, deps.store, issuer); + } catch (error) { + if (error instanceof AuthorizePageError) { + return errorPage('invalid_request', error.message); + } + if (error instanceof AuthorizeRedirectError) { + return redirectToClientError(error.redirectUri, error.error, error.description, error.state); + } + throw error; + } + + const pairing = await createKiloPairing(deps, request); + if (!pairing.ok) { + // Retryable unhappy path: nothing was created; tell the user exactly what + // to do (wait vs check connection) and send them back to the client. + const description = + pairing.kind === 'rate_limited' + ? 'Too many pending Kilo sign-in requests from your network right now. Wait a few minutes, then retry from your MCP client.' + : 'Kilo sign-in could not be reached. Check your connection, then retry from your MCP client.'; + return errorPage('temporarily_unavailable', description, 503); + } + + const now = deps.now?.() ?? new Date(); + const code = base64UrlEncode(crypto.getRandomValues(new Uint8Array(32))); + await deps.store.createCode({ + code, + clientId: validated.client.clientId, + redirectUri: validated.redirectUri, + codeChallenge: validated.codeChallenge, + resource: validated.resource, + scope: validated.scope, + state: validated.state, + deviceAuthCode: pairing.pairingCode, + createdAt: now.toISOString(), + expiresAt: new Date(now.getTime() + CODE_TTL_SECONDS * 1000).toISOString(), + }); + + return consentPage({ + clientName: validated.client.clientName, + scope: validated.scope, + webSignInUrl: `${deps.webBaseUrl.replace(/\/$/, '')}/device-auth?code=${encodeURIComponent(pairing.pairingCode)}`, + statusUrl: `/authorize/status?code=${encodeURIComponent(code)}`, + // Restarting means re-running this exact authorization request: it mints + // a fresh pairing and a fresh consent page. + restartUrl: request.url, + }); +} diff --git a/services/kilo-mcp/src/auth/dcr.test.ts b/services/kilo-mcp/src/auth/dcr.test.ts new file mode 100644 index 0000000000..fe53c45300 --- /dev/null +++ b/services/kilo-mcp/src/auth/dcr.test.ts @@ -0,0 +1,229 @@ +import { describe, expect, it } from 'vitest'; +import { handleRegistration, validateRedirectUri } from './dcr'; +import type { OAuthStoreApi, StoredClient } from '../store/oauth-store'; + +/** + * In-memory OAuthStoreApi for these endpoint tests. Methods these tests never + * reach throw, so a new handler dependency fails loudly instead of silently. + */ +function createFakeOAuthStore(): OAuthStoreApi & { clients: Map } { + const clients = new Map(); + const unused = (): never => { + throw new Error('not reachable from these tests'); + }; + return { + clients, + async registerClient(input) { + clients.set(input.clientId, { ...input, redirectUris: [...input.redirectUris] }); + }, + async getClient(clientId) { + const client = clients.get(clientId); + return client ? { ...client, redirectUris: [...client.redirectUris] } : null; + }, + createCode: unused, + getCode: unused, + recordPairingApproval: unused, + denyCode: unused, + approveCode: unused, + consumeCode: unused, + saveRefreshToken: unused, + getRefreshTokenByHash: unused, + rotateRefreshToken: unused, + getKiloToken: unused, + revokeGrant: unused, + revokeJti: unused, + async isJtiRevoked() { + return false; + }, + purgeExpired: unused, + }; +} + +const NOW = new Date('2026-09-09T12:00:00.000Z'); + +function registrationRequest(body: unknown, method = 'POST'): Request { + return new Request('https://kilo-mcp.test/register', { + method, + headers: { 'content-type': 'application/json' }, + body: typeof body === 'string' ? body : JSON.stringify(body), + }); +} + +/** Shape of the /register JSON responses asserted below. */ +type RegistrationBody = { + client_id: string; + client_secret?: string; + token_endpoint_auth_method?: string; + redirect_uris?: string[]; + client_name?: string; + grant_types?: string[]; + scope?: string; + error?: string; + error_description?: string; +}; + +async function handle(body: unknown) { + const store = createFakeOAuthStore(); + const response = await handleRegistration(registrationRequest(body), { store, now: () => NOW }); + return { store, response }; +} + +describe('validateRedirectUri', () => { + it('accepts https URIs', () => { + expect(validateRedirectUri('https://client.test/callback').ok).toBe(true); + expect(validateRedirectUri('https://client.test:8443/cb?x=1').ok).toBe(true); + }); + + it('accepts loopback http (native apps, RFC 8252)', () => { + expect(validateRedirectUri('http://localhost:8765/callback').ok).toBe(true); + expect(validateRedirectUri('http://127.0.0.1:33411/').ok).toBe(true); + expect(validateRedirectUri('http://127.0.0.53:9/cb').ok).toBe(true); + expect(validateRedirectUri('http://[::1]:8080/cb').ok).toBe(true); + }); + + it('rejects non-loopback http, other schemes, fragments, userinfo, and junk', () => { + expect(validateRedirectUri('http://evil.test/cb').ok).toBe(false); + expect(validateRedirectUri('myapp://callback').ok).toBe(false); + expect(validateRedirectUri('https://client.test/cb#frag').ok).toBe(false); + expect(validateRedirectUri('https://user:pw@client.test/cb').ok).toBe(false); + expect(validateRedirectUri('not-a-url').ok).toBe(false); + expect(validateRedirectUri(42).ok).toBe(false); + expect(validateRedirectUri('').ok).toBe(false); + }); +}); + +describe('POST /register (happy)', () => { + it('persists the client and answers 201 with client_id and no secret', async () => { + const { store, response } = await handle({ + client_name: 'Kilo CLI', + redirect_uris: ['https://client.test/cb', 'http://localhost:1234/cb'], + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'none', + }); + const body = (await response.json()) as RegistrationBody; + expect(response.status).toBe(201); + expect(typeof body.client_id).toBe('string'); + expect(body.client_id.length).toBeGreaterThanOrEqual(43); + expect(body.client_secret).toBeUndefined(); + expect(body.token_endpoint_auth_method).toBe('none'); + expect(body.redirect_uris).toEqual(['https://client.test/cb', 'http://localhost:1234/cb']); + expect(body.client_name).toBe('Kilo CLI'); + + const stored = await store.getClient(body.client_id); + expect(stored).toMatchObject({ clientName: 'Kilo CLI', createdAt: NOW.toISOString() }); + expect(stored?.redirectUris).toEqual(['https://client.test/cb', 'http://localhost:1234/cb']); + }); + + it('defaults client_name, grants, and scope when omitted', async () => { + const { response } = await handle({ redirect_uris: ['https://client.test/cb'] }); + const body = (await response.json()) as RegistrationBody; + expect(response.status).toBe(201); + expect(body.client_name).toBe('Unnamed client'); + expect(body.grant_types).toEqual(['authorization_code', 'refresh_token']); + expect(body.scope).toBe('mcp'); + }); + + it('deduplicates repeated redirect URIs', async () => { + const { response } = await handle({ + redirect_uris: ['https://a.test/cb', 'https://a.test/cb'], + }); + const body = (await response.json()) as RegistrationBody; + expect(body.redirect_uris).toEqual(['https://a.test/cb']); + }); + + it('issues distinct client ids per registration', async () => { + const { response: first } = await handle({ redirect_uris: ['https://a.test/cb'] }); + const { response: second } = await handle({ redirect_uris: ['https://a.test/cb'] }); + expect(((await first.json()) as RegistrationBody).client_id).not.toBe( + ((await second.json()) as RegistrationBody).client_id + ); + }); +}); + +describe('POST /register (input validation)', () => { + it('the empty registry input: no redirect_uris gets its own error message', async () => { + const { response } = await handle({ client_name: 'ghost' }); + expect(response.status).toBe(400); + const body = (await response.json()) as RegistrationBody; + expect(body.error).toBe('invalid_client_metadata'); + expect(body.error_description).toMatch(/redirect_uris is required/); + }); + + it('rejects an empty redirect_uris array', async () => { + const { response } = await handle({ redirect_uris: [] }); + const body = (await response.json()) as RegistrationBody; + expect(response.status).toBe(400); + expect(body.error).toBe('invalid_redirect_uri'); + }); + + it('rejects a non-https, non-loopback redirect', async () => { + const { response } = await handle({ redirect_uris: ['http://example.com/cb'] }); + const body = (await response.json()) as RegistrationBody; + expect(body.error).toBe('invalid_redirect_uri'); + }); + + it('rejects more than the redirect cap', async () => { + const uris = Array.from({ length: 11 }, (_, i) => `https://a.test/cb${i}`); + const { response } = await handle({ redirect_uris: uris }); + const body = (await response.json()) as RegistrationBody; + expect(body.error).toBe('invalid_redirect_uri'); + }); + + it('rejects confidential clients: token_endpoint_auth_method must be none', async () => { + const { response } = await handle({ + redirect_uris: ['https://a.test/cb'], + token_endpoint_auth_method: 'client_secret_basic', + }); + const body = (await response.json()) as RegistrationBody; + expect(body.error).toBe('invalid_client_metadata'); + expect(body.error_description).toMatch(/public clients/); + }); + + it('rejects unknown grant_types and response_types', async () => { + const { response: grants } = await handle({ + redirect_uris: ['https://a.test/cb'], + grant_types: ['password'], + }); + expect(((await grants.json()) as RegistrationBody).error).toBe('invalid_client_metadata'); + const { response: types } = await handle({ + redirect_uris: ['https://a.test/cb'], + response_types: ['token'], + }); + expect(((await types.json()) as RegistrationBody).error).toBe('invalid_client_metadata'); + }); + + it('rejects scopes outside mcp', async () => { + const { response } = await handle({ redirect_uris: ['https://a.test/cb'], scope: 'mcp admin' }); + const body = (await response.json()) as RegistrationBody; + expect(body.error).toBe('invalid_client_metadata'); + }); + + it('rejects oversized and malformed bodies', async () => { + const junk = await handleRegistration(registrationRequest('{not json'), { + store: createFakeOAuthStore(), + }); + expect(((await junk.json()) as RegistrationBody).error).toBe('invalid_client_metadata'); + + const huge = await handleRegistration( + registrationRequest( + JSON.stringify({ redirect_uris: ['https://a.test/cb'], pad: 'x'.repeat(20_000) }) + ), + { store: createFakeOAuthStore() } + ); + expect(huge.status).toBe(400); + + const { response: arrayResponse } = await handle([]); + expect(((await arrayResponse.json()) as RegistrationBody).error).toBe( + 'invalid_client_metadata' + ); + }); + + it('rejects non-POST', async () => { + const response = await handleRegistration( + new Request('https://kilo-mcp.test/register', { method: 'GET' }), + { store: createFakeOAuthStore() } + ); + expect(response.status).toBe(405); + }); +}); diff --git a/services/kilo-mcp/src/auth/dcr.ts b/services/kilo-mcp/src/auth/dcr.ts new file mode 100644 index 0000000000..10fb6f0cb6 --- /dev/null +++ b/services/kilo-mcp/src/auth/dcr.ts @@ -0,0 +1,256 @@ +/** + * RFC 7591 dynamic client registration for public clients (requirement 16). + * + * This MCP only ever issues `code` + PKCE + refresh tokens to public clients: + * `token_endpoint_auth_method` must be `none` (or omitted) and no client + * secret is ever created. Redirect URIs are https, or http only on loopback + * (RFC 8252 §7.3 native apps). Registration is capped in size and count so a + * single worker cannot be filled with junk. + * + * The clientless registry is the input state of this endpoint: a registration + * without any usable `redirect_uris` gets its own explicit error message. + */ +import { base64UrlEncode } from './pkce'; +import { MCP_SCOPE, oauthErrorResponse, authJsonResponse } from './http'; +import type { OAuthStoreApi } from '../store/oauth-store'; + +export type DcrDeps = { + store: OAuthStoreApi; + now?: () => Date; +}; + +/** Hard caps on one registration. */ +const MAX_BODY_BYTES = 16 * 1024; +const MAX_REDIRECT_URIS = 10; +const MAX_REDIRECT_URI_LENGTH = 2048; +const MAX_CLIENT_NAME_LENGTH = 255; + +const ALLOWED_GRANT_TYPES = new Set(['authorization_code', 'refresh_token']); + +type RedirectUriCheck = { ok: true } | { ok: false; reason: string }; + +/** https anywhere; http only to loopback (localhost, 127.0.0.0/8, ::1). */ +export function validateRedirectUri(value: unknown): RedirectUriCheck { + if (typeof value !== 'string' || value.length === 0 || value.length > MAX_REDIRECT_URI_LENGTH) { + return { ok: false, reason: 'each redirect_uri must be a non-empty string' }; + } + let url: URL; + try { + url = new URL(value); + } catch { + return { ok: false, reason: `"${value}" is not an absolute URL` }; + } + if (url.username || url.password) { + return { ok: false, reason: 'redirect_uri must not carry userinfo' }; + } + if (url.hash) { + return { ok: false, reason: 'redirect_uri must not carry a fragment' }; + } + if (url.protocol === 'https:') return { ok: true }; + if (url.protocol === 'http:') { + const host = url.hostname; + // WHATWG URL keeps the brackets on an IPv6 hostname. + const loopback = + host === 'localhost' || host === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host); + if (!loopback) { + return { + ok: false, + reason: 'plain http redirect_uri is only allowed on loopback (native apps)', + }; + } + return { ok: true }; + } + return { ok: false, reason: 'redirect_uri scheme must be https or loopback http' }; +} + +type RegistrationBody = { + redirectUris: string[]; + clientName: string; + grantTypes: string[]; + responseTypes: string[]; + scope: string; +}; + +/** Parse + validate the client-supplied registration document. */ +export function parseRegistration( + body: unknown +): { ok: true; client: RegistrationBody } | { ok: false; error: string; description: string } { + if (typeof body !== 'object' || body === null || Array.isArray(body)) { + return { + ok: false, + error: 'invalid_client_metadata', + description: 'Registration body must be a JSON object.', + }; + } + const record = body as Record; + + const rawUris = record['redirect_uris']; + if (rawUris === undefined) { + return { + ok: false, + error: 'invalid_client_metadata', + description: + 'redirect_uris is required: a public client must register at least one redirect URI.', + }; + } + if (!Array.isArray(rawUris)) { + return { + ok: false, + error: 'invalid_redirect_uri', + description: 'redirect_uris must be an array of URLs.', + }; + } + if (rawUris.length === 0 || rawUris.length > MAX_REDIRECT_URIS) { + return { + ok: false, + error: 'invalid_redirect_uri', + description: `redirect_uris must contain between 1 and ${MAX_REDIRECT_URIS} entries.`, + }; + } + for (const uri of rawUris) { + const check = validateRedirectUri(uri); + if (!check.ok) { + return { + ok: false, + error: 'invalid_redirect_uri', + description: `Invalid redirect_uri: ${check.reason}.`, + }; + } + } + const redirectUris = [...new Set(rawUris as string[])]; + + const authMethod = record['token_endpoint_auth_method']; + if (authMethod !== undefined && authMethod !== 'none') { + return { + ok: false, + error: 'invalid_client_metadata', + description: + "This authorization server only issues to public clients: token_endpoint_auth_method must be 'none'.", + }; + } + + const grantTypes = record['grant_types']; + if (grantTypes !== undefined) { + if ( + !Array.isArray(grantTypes) || + grantTypes.length === 0 || + !grantTypes.every(g => typeof g === 'string' && ALLOWED_GRANT_TYPES.has(g)) + ) { + return { + ok: false, + error: 'invalid_client_metadata', + description: `grant_types must be a non-empty subset of ${[...ALLOWED_GRANT_TYPES].join(', ')}.`, + }; + } + } + + const responseTypes = record['response_types']; + if (responseTypes !== undefined) { + if ( + !Array.isArray(responseTypes) || + responseTypes.length === 0 || + !responseTypes.every(t => t === 'code') + ) { + return { + ok: false, + error: 'invalid_client_metadata', + description: + 'response_types must be ["code"] — this server only issues authorization codes.', + }; + } + } + + const clientName = record['client_name']; + if ( + clientName !== undefined && + (typeof clientName !== 'string' || + clientName.length === 0 || + clientName.length > MAX_CLIENT_NAME_LENGTH) + ) { + return { + ok: false, + error: 'invalid_client_metadata', + description: `client_name must be a string of 1..${MAX_CLIENT_NAME_LENGTH} characters.`, + }; + } + + const scope = record['scope']; + if (scope !== undefined && (typeof scope !== 'string' || !validScopeString(scope))) { + return { + ok: false, + error: 'invalid_client_metadata', + description: `scope must be a space-separated subset of "${MCP_SCOPE}".`, + }; + } + + return { + ok: true, + client: { + redirectUris, + clientName: typeof clientName === 'string' ? clientName : 'Unnamed client', + grantTypes: Array.isArray(grantTypes) + ? (grantTypes as string[]) + : ['authorization_code', 'refresh_token'], + responseTypes: ['code'], + scope: typeof scope === 'string' && scope.length > 0 ? scope : MCP_SCOPE, + }, + }; +} + +function validScopeString(scope: string): boolean { + const tokens = scope.split(' ').filter(t => t.length > 0); + return tokens.length > 0 && tokens.every(t => t === MCP_SCOPE); +} + +/** POST /register — RFC 7591. 201 with a client_id and no client_secret. */ +export async function handleRegistration(request: Request, deps: DcrDeps): Promise { + if (request.method !== 'POST') { + return oauthErrorResponse(405, 'invalid_request', 'Use POST to register a client.'); + } + const text = await request.text(); + if (text.length > MAX_BODY_BYTES) { + return oauthErrorResponse( + 400, + 'invalid_client_metadata', + `Registration body exceeds ${MAX_BODY_BYTES} bytes.` + ); + } + let body: unknown; + try { + body = JSON.parse(text) as unknown; + } catch { + return oauthErrorResponse( + 400, + 'invalid_client_metadata', + 'Registration body is not valid JSON.' + ); + } + + const parsed = parseRegistration(body); + if (!parsed.ok) { + return oauthErrorResponse(400, parsed.error, parsed.description); + } + + const now = deps.now?.() ?? new Date(); + const clientId = base64UrlEncode(crypto.getRandomValues(new Uint8Array(32))); + await deps.store.registerClient({ + clientId, + redirectUris: parsed.client.redirectUris, + clientName: parsed.client.clientName, + createdAt: now.toISOString(), + }); + + return authJsonResponse( + { + client_id: clientId, + client_id_issued_at: Math.floor(now.getTime() / 1000), + client_name: parsed.client.clientName, + redirect_uris: parsed.client.redirectUris, + grant_types: parsed.client.grantTypes, + response_types: parsed.client.responseTypes, + token_endpoint_auth_method: 'none', + scope: parsed.client.scope, + }, + 201 + ); +} diff --git a/services/kilo-mcp/src/auth/http.ts b/services/kilo-mcp/src/auth/http.ts new file mode 100644 index 0000000000..de9af76714 --- /dev/null +++ b/services/kilo-mcp/src/auth/http.ts @@ -0,0 +1,132 @@ +/** + * Shared HTTP plumbing for the OAuth endpoints (metadata, DCR, authorize, + * token): CORS, RFC 6749 §5.2 error bodies, HTML error/consent surfaces, and + * the endpoint path constants every module routes against. + */ + +/** The only scope this MCP issues; PKCE + DCR + resource indicator ride on it (requirement 16). */ +export const MCP_SCOPE = 'mcp'; + +/** Routes served by the auth endpoints, shared by index.ts routing and metadata. */ +export const AUTH_PATHS = { + authorize: '/authorize', + pairingStatus: '/authorize/status', + orgPicker: '/authorize/org', + token: '/token', + register: '/register', + mcp: '/mcp', + authorizationServerMetadata: '/.well-known/oauth-authorization-server', + authorizationServerMetadataScoped: '/.well-known/oauth-authorization-server/mcp', + protectedResourceMetadata: '/.well-known/oauth-protected-resource', + protectedResourceMetadataScoped: '/.well-known/oauth-protected-resource/mcp', +} as const; + +/** How often the consent page re-checks pairing status (s5; rendered by s6's page). */ +export const PAIRING_POLL_INTERVAL_MS = 2000; + +const AUTH_CORS_HEADERS: Record = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Mcp-Session-Id', + 'Access-Control-Max-Age': '86400', +}; + +export function withAuthCors(response: Response): Response { + for (const [key, value] of Object.entries(AUTH_CORS_HEADERS)) { + response.headers.set(key, value); + } + return response; +} + +export function authJsonResponse( + body: unknown, + status = 200, + extraHeaders: HeadersInit = {} +): Response { + return withAuthCors( + new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json', ...extraHeaders }, + }) + ); +} + +/** RFC 6749 §5.2 error object. `error_description` is operator-facing prose. */ +export function oauthErrorResponse( + status: number, + error: string, + errorDescription?: string +): Response { + return authJsonResponse( + { error, ...(errorDescription ? { error_description: errorDescription } : {}) }, + status, + { 'Cache-Control': 'no-store' } + ); +} + +export function htmlResponse(body: string, status = 200): Response { + return withAuthCors( + new Response(body, { status, headers: { 'Content-Type': 'text/html; charset=utf-8' } }) + ); +} + +export function escapeHtml(value: string): string { + return value + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll("'", '''); +} + +const PAGE_STYLE = + 'body{font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;' + + 'background:#0b0d12;color:#e6e8ee;display:flex;justify-content:center;padding:48px 16px}' + + '.card{max-width:480px;width:100%}h1{font-size:20px;margin:0 0 12px}p{line-height:1.5;color:#aeb4c2}' + + 'code{background:#171a21;padding:2px 6px;border-radius:4px}' + + 'a.cta{display:inline-block;margin-top:16px;padding:12px 20px;border-radius:8px;' + + 'background:#5b5bd6;color:#fff;text-decoration:none;font-weight:600}' + + // an author display rule beats the UA [hidden] rule; keep hidden actually hidden. + '[hidden]{display:none !important}'; + +/** + * Minimal standalone page shell (the worker has no shared UI kit). `bodyHtml` + * must already be escaped; only static markup is interpolated here. + */ +export function authPage(title: string, bodyHtml: string): string { + return ( + `` + + `` + + `` + + `${escapeHtml(title)}` + + `
${bodyHtml}
` + ); +} + +/** OAuth error rendered for the browser that opened /authorize. */ +export function errorPage(error: string, description: string, status = 400): Response { + return htmlResponse( + authPage( + 'Authorization request failed', + `

Authorization request failed

${escapeHtml(description)}

` + + `

Reason: ${escapeHtml(error)}. Close this tab and retry from your MCP client.

` + ), + status + ); +} + +/** Redirect to the client with `error` params (RFC 6749 §4.1.2.1), only after client + redirect_uri validated. */ +export function redirectToClientError( + redirectUri: string, + error: string, + description: string, + state: string | null +): Response { + const url = new URL(redirectUri); + url.searchParams.set('error', error); + url.searchParams.set('error_description', description); + if (state) url.searchParams.set('state', state); + // `Response.redirect` yields immutable headers, which withAuthCors cannot + // extend; a plain 302 with a Location header stays mutable. + return withAuthCors(new Response(null, { status: 302, headers: { Location: url.toString() } })); +} diff --git a/services/kilo-mcp/src/auth/jwt.ts b/services/kilo-mcp/src/auth/jwt.ts new file mode 100644 index 0000000000..f7a649ac8a --- /dev/null +++ b/services/kilo-mcp/src/auth/jwt.ts @@ -0,0 +1,82 @@ +/** + * Minimal HS256 (HMAC-SHA256) JWT primitives over WebCrypto — the only + * asymmetric-free signature the MCP access token needs (the worker both mints + * and verifies it). Deliberately not a general JWT library: single header, + * single algorithm, strict parsing. + */ +import { base64UrlDecode, base64UrlEncode, constantTimeBytesEqual } from './pkce'; + +const JWT_HEADER = { alg: 'HS256', typ: 'JWT' } as const; + +async function hmacKey(secret: string): Promise { + return crypto.subtle.importKey( + 'raw', + new TextEncoder().encode(secret), + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['sign'] + ); +} + +async function signSegments(signingInput: string, secret: string): Promise { + const signature = await crypto.subtle.sign( + 'HMAC', + await hmacKey(secret), + new TextEncoder().encode(signingInput) + ); + return new Uint8Array(signature); +} + +/** Compact HS256 JWT for the given claims. Never log the result: it is a bearer token. */ +export async function signJwt(claims: Record, secret: string): Promise { + const header = base64UrlEncode(new TextEncoder().encode(JSON.stringify(JWT_HEADER))); + const payload = base64UrlEncode(new TextEncoder().encode(JSON.stringify(claims))); + const signature = await signSegments(`${header}.${payload}`, secret); + return `${header}.${payload}.${base64UrlEncode(signature)}`; +} + +export type DecodedJwt = { + header: Record; + payload: Record; + signingInput: string; + signature: Uint8Array; +}; + +/** Strict compact-JWS parse. Returns null on any shape violation (no throw on hostile input). */ +export function decodeJwt(token: string): DecodedJwt | null { + const parts = token.split('.'); + if (parts.length !== 3) return null; + const [headerB64, payloadB64, signatureB64] = parts; + const headerBytes = base64UrlDecode(headerB64); + const payloadBytes = base64UrlDecode(payloadB64); + const signature = signatureBytes(signatureB64); + if (!headerBytes || !payloadBytes || !signature) return null; + let header: unknown; + let payload: unknown; + try { + header = JSON.parse(new TextDecoder().decode(headerBytes)); + payload = JSON.parse(new TextDecoder().decode(payloadBytes)); + } catch { + return null; + } + if (!isPlainObject(header) || !isPlainObject(payload)) return null; + if (header.alg !== 'HS256' || header.typ !== 'JWT') return null; + return { header, payload, signingInput: `${headerB64}.${payloadB64}`, signature }; +} + +/** Recompute the HMAC and compare in constant time. */ +export async function verifyJwtSignature(decoded: DecodedJwt, secret: string): Promise { + const expected = await signSegments(decoded.signingInput, secret); + return constantTimeBytesEqual(expected, decoded.signature); +} + +function signatureBytes(value: string): Uint8Array | null { + // An HS256 signature is exactly 32 bytes; reject anything else before parsing. + const bytes = base64UrlDecode(value); + if (!bytes || bytes.length !== 32) return null; + return bytes; +} + +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/services/kilo-mcp/src/auth/metadata.test.ts b/services/kilo-mcp/src/auth/metadata.test.ts new file mode 100644 index 0000000000..5a45c4f3d4 --- /dev/null +++ b/services/kilo-mcp/src/auth/metadata.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from 'vitest'; +import { + authorizationServerMetadata, + handleAuthorizationServerMetadata, + handleProtectedResourceMetadata, + mcpResourceUrl, + protectedResourceMetadata, +} from './metadata'; + +const ISSUER = 'https://kilo-mcp.test'; + +describe('authorizationServerMetadata', () => { + it('advertises this worker as the issuer with the four OAuth endpoints', () => { + const doc = authorizationServerMetadata(ISSUER); + expect(doc).toMatchObject({ + issuer: ISSUER, + authorization_endpoint: `${ISSUER}/authorize`, + token_endpoint: `${ISSUER}/token`, + registration_endpoint: `${ISSUER}/register`, + }); + }); + + it('declares the MCP OAuth 2.1 profile: code-only, S256-only, public clients (requirement 16)', () => { + const doc = authorizationServerMetadata(ISSUER); + expect(doc['response_types_supported']).toEqual(['code']); + expect(doc['code_challenge_methods_supported']).toEqual(['S256']); + expect(doc['grant_types_supported']).toEqual(['authorization_code', 'refresh_token']); + expect(doc['scopes_supported']).toEqual(['mcp']); + expect(doc['token_endpoint_auth_methods_supported']).toEqual(['none']); + }); +}); + +describe('protectedResourceMetadata', () => { + it('advertises the resource name and the authorization servers list (RFC 9728)', () => { + const doc = protectedResourceMetadata(ISSUER, mcpResourceUrl(ISSUER)); + expect(doc).toMatchObject({ + resource: `${ISSUER}/mcp`, + resource_name: 'Kilo MCP', + authorization_servers: [ISSUER], + scopes_supported: ['mcp'], + }); + }); +}); + +describe('metadata handlers', () => { + it('serves the authorization-server document on GET', async () => { + const response = handleAuthorizationServerMetadata( + new Request(`${ISSUER}/.well-known/oauth-authorization-server`), + { issuer: ISSUER } + ); + expect(response.status).toBe(200); + expect(response.headers.get('Content-Type')).toContain('application/json'); + await expect(response.json()).resolves.toMatchObject({ issuer: ISSUER }); + }); + + it('serves the protected-resource document on GET', async () => { + const response = handleProtectedResourceMetadata( + new Request(`${ISSUER}/.well-known/oauth-protected-resource/mcp`), + { issuer: ISSUER } + ); + expect(response.status).toBe(200); + await expect(response.json()).resolves.toMatchObject({ resource: `${ISSUER}/mcp` }); + }); + + it('rejects non-GET with an RFC error object', async () => { + const response = handleAuthorizationServerMetadata( + new Request(`${ISSUER}/.well-known/oauth-authorization-server`, { method: 'POST' }), + { issuer: ISSUER } + ); + expect(response.status).toBe(405); + await expect(response.json()).resolves.toMatchObject({ error: 'invalid_request' }); + }); + + it('carries CORS so MCP clients can fetch discovery from any origin', async () => { + const response = handleProtectedResourceMetadata( + new Request(`${ISSUER}/.well-known/oauth-protected-resource`), + { issuer: ISSUER } + ); + expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*'); + }); +}); diff --git a/services/kilo-mcp/src/auth/metadata.ts b/services/kilo-mcp/src/auth/metadata.ts new file mode 100644 index 0000000000..b3bf7b2a86 --- /dev/null +++ b/services/kilo-mcp/src/auth/metadata.ts @@ -0,0 +1,75 @@ +/** + * OAuth 2.1 / MCP discovery metadata (requirement 16): + * + * - `/.well-known/oauth-authorization-server` (+ the `/mcp`-scoped variant MCP + * clients probe first) — this worker is the authorization server for THIS + * MCP: PKCE S256 mandatory, `response_types: ['code']`, DCR + authorization + * code + refresh_token grants, public clients only (`token_endpoint_auth_method: none`). + * - `/.well-known/oauth-protected-resource` (+ scoped variant) — RFC 9728: + * the resource name and the list of authorization servers that can mint + * tokens for it. + * + * The issuer is always the URL this worker is reached at, so dev and prod + * advertise themselves without extra configuration. + */ +import { AUTH_PATHS, authJsonResponse, MCP_SCOPE, oauthErrorResponse } from './http'; + +export type MetadataDeps = { + /** Origin of this worker for this request, e.g. `https://kilo-mcp.users.workers.dev`. */ + issuer: string; +}; + +/** The canonical RFC 8707 resource indicator for the MCP endpoint at `/mcp`. */ +export function mcpResourceUrl(issuer: string): string { + return `${issuer}/mcp`; +} + +/** RFC 9728: the protected-resource metadata URL a 401 challenge points at. */ +export function protectedResourceMetadataUrl(issuer: string): string { + return `${issuer}${AUTH_PATHS.protectedResourceMetadata}`; +} + +export function authorizationServerMetadata(issuer: string): Record { + return { + issuer, + authorization_endpoint: `${issuer}/authorize`, + token_endpoint: `${issuer}/token`, + registration_endpoint: `${issuer}/register`, + response_types_supported: ['code'], + grant_types_supported: ['authorization_code', 'refresh_token'], + scopes_supported: [MCP_SCOPE], + // PKCE is mandatory and S256 is the only accepted method. + code_challenge_methods_supported: ['S256'], + // Dynamic clients are public: no client secret is ever issued. + token_endpoint_auth_methods_supported: ['none'], + }; +} + +export function protectedResourceMetadata( + issuer: string, + resource: string +): Record { + return { + resource, + resource_name: 'Kilo MCP', + authorization_servers: [issuer], + scopes_supported: [MCP_SCOPE], + bearer_methods_supported: ['header'], + }; +} + +/** GET handler for both authorization-server metadata URLs. */ +export function handleAuthorizationServerMetadata(request: Request, deps: MetadataDeps): Response { + if (request.method !== 'GET') { + return oauthErrorResponse(405, 'invalid_request', 'Use GET for discovery metadata.'); + } + return authJsonResponse(authorizationServerMetadata(deps.issuer)); +} + +/** GET handler for both protected-resource metadata URLs (RFC 9728). */ +export function handleProtectedResourceMetadata(request: Request, deps: MetadataDeps): Response { + if (request.method !== 'GET') { + return oauthErrorResponse(405, 'invalid_request', 'Use GET for discovery metadata.'); + } + return authJsonResponse(protectedResourceMetadata(deps.issuer, mcpResourceUrl(deps.issuer))); +} diff --git a/services/kilo-mcp/src/auth/pkce.test.ts b/services/kilo-mcp/src/auth/pkce.test.ts new file mode 100644 index 0000000000..56c91b8388 --- /dev/null +++ b/services/kilo-mcp/src/auth/pkce.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest'; +import { + codeChallengeFromVerifier, + generateCodeVerifier, + isValidCodeChallenge, + isValidCodeVerifier, + verifyPkceS256, +} from './pkce'; + +describe('PKCE S256 (RFC 7636)', () => { + it('matches the RFC 7636 appendix B known vector', async () => { + const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'; + const challenge = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM'; + expect(await codeChallengeFromVerifier(verifier)).toBe(challenge); + expect(await verifyPkceS256(verifier, challenge)).toBe(true); + }); + + it('rejects a wrong verifier', async () => { + const challenge = await codeChallengeFromVerifier(generateCodeVerifier()); + expect(await verifyPkceS256(generateCodeVerifier(), challenge)).toBe(false); + }); + + it('accepts only the RFC charset and 43..128 length', () => { + expect(isValidCodeVerifier('a'.repeat(43))).toBe(true); + expect(isValidCodeVerifier('a'.repeat(128))).toBe(true); + expect(isValidCodeVerifier('a'.repeat(42))).toBe(false); + expect(isValidCodeVerifier('a'.repeat(129))).toBe(false); + expect(isValidCodeVerifier('has space')).toBe(false); + expect(isValidCodeVerifier('unsafe+char/')).toBe(false); + expect(isValidCodeVerifier(`~tilde.dot-dash_ok${'x'.repeat(43)}`)).toBe(true); + expect(isValidCodeVerifier(null)).toBe(false); + }); + + it('challenge validation accepts base64url only (S256 output shape)', () => { + expect(isValidCodeChallenge('E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM')).toBe(true); + expect(isValidCodeChallenge('short')).toBe(false); + expect(isValidCodeChallenge('has=padding+plus/slash')).toBe(false); + expect(isValidCodeChallenge(null)).toBe(false); + }); + + it('generated verifier/challenge round-trips', async () => { + const verifier = generateCodeVerifier(); + const challenge = await codeChallengeFromVerifier(verifier); + expect(isValidCodeChallenge(challenge)).toBe(true); + expect(await verifyPkceS256(verifier, challenge)).toBe(true); + }); +}); diff --git a/services/kilo-mcp/src/auth/pkce.ts b/services/kilo-mcp/src/auth/pkce.ts new file mode 100644 index 0000000000..2888c96a51 --- /dev/null +++ b/services/kilo-mcp/src/auth/pkce.ts @@ -0,0 +1,67 @@ +/** + * PKCE (RFC 7636) primitives for the MCP OAuth flow. S256 is the only + * challenge method this server accepts (MCP requires PKCE with S256). + * + * Digests go through WebCrypto; comparisons are constant-time so a failed + * verifier leaks no byte-level timing signal. + */ + +/** code_challenge: base64url of a SHA-256 digest — 43 chars; length 43..128 tolerated per RFC 7636 §4.2. */ +const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43,128}$/; + +/** code_verifier: [A-Za-z0-9\-._~], 43..128 chars (RFC 7636 §4.1). */ +const CODE_VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/; + +export function isValidCodeChallenge(challenge: string | null | undefined): challenge is string { + return typeof challenge === 'string' && CODE_CHALLENGE_PATTERN.test(challenge); +} + +export function isValidCodeVerifier(verifier: string | null | undefined): verifier is string { + return typeof verifier === 'string' && CODE_VERIFIER_PATTERN.test(verifier); +} + +/** BASE64URL(SHA-256(verifier)) — the S256 transformation. */ +export async function codeChallengeFromVerifier(verifier: string): Promise { + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)); + return base64UrlEncode(new Uint8Array(digest)); +} + +/** True when `verifier` hashes to `challenge` under S256. */ +export async function verifyPkceS256(verifier: string, challenge: string): Promise { + const computed = await codeChallengeFromVerifier(verifier); + const encoder = new TextEncoder(); + return constantTimeBytesEqual(encoder.encode(challenge), encoder.encode(computed)); +} + +/** Cryptographically random PKCE verifier (test helpers + future client-side use). */ +export function generateCodeVerifier(byteLength = 32): string { + const bytes = crypto.getRandomValues(new Uint8Array(byteLength)); + return base64UrlEncode(bytes); +} + +export function base64UrlEncode(bytes: Uint8Array): string { + let binary = ''; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', ''); +} + +export function base64UrlDecode(value: string): Uint8Array | null { + if (!/^[A-Za-z0-9_-]+$/.test(value)) return null; + const padded = value.replaceAll('-', '+').replaceAll('_', '/'); + try { + const binary = atob(padded + '='.repeat((4 - (padded.length % 4)) % 4)); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; + } catch { + return null; + } +} + +/** Length-checked constant-time byte equality (no `crypto.subtle.timingSafeEqual` dependency). */ +export function constantTimeBytesEqual(a: Uint8Array, b: Uint8Array): boolean { + if (a.length !== b.length) return false; + let diff = 0; + for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i]; + return diff === 0; +} diff --git a/services/kilo-mcp/src/auth/token.test.ts b/services/kilo-mcp/src/auth/token.test.ts new file mode 100644 index 0000000000..e716742715 --- /dev/null +++ b/services/kilo-mcp/src/auth/token.test.ts @@ -0,0 +1,697 @@ +import { describe, expect, it } from 'vitest'; +import { handleToken, ACCESS_TOKEN_TTL_SECONDS } from './token'; +import { decodeJwt } from './jwt'; +import { codeChallengeFromVerifier, generateCodeVerifier } from './pkce'; +import type { + NewRefreshToken, + NewOAuthCode, + OAuthCodeRecord, + OAuthStoreApi, + RefreshTokenRecord, + StoredClient, +} from '../store/oauth-store'; + +/** + * In-memory OAuthStoreApi for these endpoint tests. Methods these tests never + * reach throw, so a new handler dependency fails loudly instead of silently. + */ +function createFakeOAuthStore(): OAuthStoreApi & { + clients: Map; + codes: Map; + refreshTokens: Map; +} { + const clients = new Map(); + const codes = new Map(); + const refreshTokens = new Map(); + const unused = (): never => { + throw new Error('not reachable from these tests'); + }; + return { + clients, + codes, + refreshTokens, + registerClient: unused, + async getClient(clientId) { + const client = clients.get(clientId); + return client ? { ...client, redirectUris: [...client.redirectUris] } : null; + }, + async createCode(input: NewOAuthCode) { + codes.set(input.code, { + ...input, + status: 'pending', + kiloUserId: null, + organizationId: null, + kiloToken: null, + }); + }, + async getCode(code) { + const record = codes.get(code); + return record ? { ...record } : null; + }, + async recordPairingApproval(deviceAuthCode, identity, nowIso) { + for (const [code, record] of codes) { + if ( + record.deviceAuthCode === deviceAuthCode && + record.status === 'pending' && + record.kiloUserId === null && + record.expiresAt > nowIso + ) { + codes.set(code, { + ...record, + kiloUserId: identity.kiloUserId, + kiloToken: identity.kiloToken, + }); + return true; + } + } + return false; + }, + denyCode: unused, + async approveCode(deviceAuthCode, identity, nowIso) { + for (const [code, record] of codes) { + if ( + record.deviceAuthCode === deviceAuthCode && + record.status === 'pending' && + record.expiresAt > nowIso + ) { + codes.set(code, { + ...record, + status: 'approved', + kiloUserId: identity.kiloUserId, + organizationId: identity.organizationId, + }); + return true; + } + } + return false; + }, + async consumeCode(code, nowIso) { + const record = codes.get(code); + if (!record || record.status !== 'approved' || record.expiresAt <= nowIso) return null; + const used: OAuthCodeRecord = { ...record, status: 'used' }; + codes.set(code, used); + return { ...used }; + }, + async saveRefreshToken(input: NewRefreshToken) { + refreshTokens.set(input.tokenHash, { ...input, revokedAt: null }); + }, + async getRefreshTokenByHash(tokenHash) { + const record = refreshTokens.get(tokenHash); + return record ? { ...record } : null; + }, + async rotateRefreshToken(oldId, input, nowIso) { + const old = [...refreshTokens.values()].find(record => record.id === oldId); + if (!old || old.revokedAt !== null || old.expiresAt <= nowIso) return false; + refreshTokens.set(old.tokenHash, { ...old, revokedAt: nowIso }); + refreshTokens.set(input.tokenHash, { ...input, revokedAt: null }); + return true; + }, + async revokeGrant(grant, nowIso) { + let revoked = 0; + for (const [hash, record] of refreshTokens) { + if ( + record.clientId === grant.clientId && + record.kiloUserId === grant.kiloUserId && + record.resource === grant.resource && + (record.organizationId ?? null) === grant.organizationId && + record.revokedAt === null && + record.expiresAt > nowIso + ) { + refreshTokens.set(hash, { ...record, revokedAt: nowIso }); + revoked += 1; + } + } + return revoked; + }, + revokeJti: unused, + async isJtiRevoked() { + return false; + }, + getKiloToken: unused, + purgeExpired: unused, + }; +} + +const SECRET = 'token-test-secret-32-bytes-here!!'; +const ISSUER = 'https://kilo-mcp.test'; +const RESOURCE = `${ISSUER}/mcp`; +const CLIENT_ID = 'client-abc'; +const REDIRECT = 'https://client.test/cb'; +const NOW = new Date('2026-09-09T12:00:00.000Z'); + +const verifier = generateCodeVerifier(); + +function storeWithClient(): ReturnType { + const store = createFakeOAuthStore(); + store.clients.set(CLIENT_ID, { + clientId: CLIENT_ID, + redirectUris: [REDIRECT], + clientName: 'Test Client', + createdAt: NOW.toISOString(), + }); + return store; +} + +async function seedApprovedCode( + store: OAuthStoreApi, + overrides: { + challenge?: string; + expiresAt?: string; + status?: 'pending' | 'approved' | 'used' | 'denied'; + /** Set to null to model a record whose pairing approval never landed. */ + kiloToken?: string | null; + } = {} +): Promise { + const code = 'test-authorization-code-value-0000000000000000000000'; + await store.createCode({ + code, + clientId: CLIENT_ID, + redirectUri: REDIRECT, + codeChallenge: overrides.challenge ?? (await codeChallengeFromVerifier(verifier)), + resource: RESOURCE, + scope: 'mcp', + state: null, + deviceAuthCode: 'PAIR-1', + createdAt: NOW.toISOString(), + expiresAt: overrides.expiresAt ?? new Date(NOW.getTime() + 600_000).toISOString(), + }); + // s6 order: the pairing approval (Kilo token) lands first, then the org + // picker approves the code with the chosen organization. + if (overrides.kiloToken !== null) { + await store.recordPairingApproval( + 'PAIR-1', + { kiloUserId: 'kilo-user-1', kiloToken: overrides.kiloToken ?? 'kilo-token-1' }, + NOW.toISOString() + ); + } + if ((overrides.status ?? 'approved') === 'approved') { + await store.approveCode( + 'PAIR-1', + { kiloUserId: 'kilo-user-1', organizationId: 'org-1' }, + NOW.toISOString() + ); + } else if (overrides.status === 'used') { + await store.approveCode( + 'PAIR-1', + { kiloUserId: 'kilo-user-1', organizationId: 'org-1' }, + NOW.toISOString() + ); + await store.consumeCode(code, NOW.toISOString()); + } + return code; +} + +function tokenRequest(form: Record): Request { + return new Request(`${ISSUER}/token`, { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams(form).toString(), + }); +} + +function handle(form: Record, store: OAuthStoreApi) { + return handleToken(tokenRequest(form), { + store, + tokenSecret: SECRET, + issuer: ISSUER, + now: () => NOW, + }); +} + +/** Shape of the /token JSON responses asserted below. */ +type TokenBody = { + token_type?: string; + access_token?: string; + refresh_token?: string; + scope?: string; + expires_in?: number; + error?: string; + error_description?: string; +}; + +describe('POST /token authorization_code (happy)', () => { + it('exchanges the code and issues tokens bound to user + org + this MCP (requirement 18)', async () => { + const store = storeWithClient(); + const code = await seedApprovedCode(store); + const response = await handle( + { + grant_type: 'authorization_code', + code, + client_id: CLIENT_ID, + redirect_uri: REDIRECT, + code_verifier: verifier, + resource: RESOURCE, + }, + store + ); + expect(response.status).toBe(200); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + const body = (await response.json()) as TokenBody; + expect(body.token_type).toBe('Bearer'); + expect(body.scope).toBe('mcp'); + expect(body.expires_in).toBe(ACCESS_TOKEN_TTL_SECONDS); + expect(typeof body.refresh_token).toBe('string'); + + const decoded = decodeJwt(body.access_token!); + expect(decoded).not.toBeNull(); + expect(decoded!.payload).toEqual({ + iss: ISSUER, + sub: 'kilo-user-1', + org: 'org-1', + aud: RESOURCE, + client_id: CLIENT_ID, + exp: Math.floor(NOW.getTime() / 1000) + ACCESS_TOKEN_TTL_SECONDS, + jti: expect.any(String), + }); + + // The refresh token is stored only as a hash. + expect(store.refreshTokens.has(body.refresh_token!)).toBe(false); + const stored = [...store.refreshTokens.values()][0]; + expect(stored.kiloUserId).toBe('kilo-user-1'); + expect(stored.tokenHash).not.toBe(body.refresh_token); + expect(stored.tokenHash).toMatch(/^[0-9a-f]{64}$/); + // s6: the grant carries the Kilo credential the worker forwards with. + expect(stored.kiloToken).toBe('kilo-token-1'); + }); + + it('a code whose pairing approval never landed is refused (no forwardable identity)', async () => { + const store = storeWithClient(); + const code = await seedApprovedCode(store, { kiloToken: null }); + const response = await handle( + { + grant_type: 'authorization_code', + code, + client_id: CLIENT_ID, + redirect_uri: REDIRECT, + code_verifier: verifier, + }, + store + ); + expect(response.status).toBe(400); + const body = (await response.json()) as TokenBody; + expect(body.error).toBe('invalid_grant'); + expect(body.error_description).toMatch(/missing its Kilo session/); + // The code stays exchangeable-pending: nothing was consumed or stored. + expect(store.codes.get(code)!.status).toBe('approved'); + expect(store.refreshTokens.size).toBe(0); + }); + + it('marks the code used', async () => { + const store = storeWithClient(); + const code = await seedApprovedCode(store); + await handle( + { + grant_type: 'authorization_code', + code, + client_id: CLIENT_ID, + redirect_uri: REDIRECT, + code_verifier: verifier, + }, + store + ); + expect(store.codes.get(code)!.status).toBe('used'); + }); +}); + +describe('POST /token authorization_code (retryable unhappy)', () => { + it('a used code gets invalid_grant telling the client to start a new authorization', async () => { + const store = storeWithClient(); + const code = await seedApprovedCode(store, { status: 'used' }); + const response = await handle( + { + grant_type: 'authorization_code', + code, + client_id: CLIENT_ID, + redirect_uri: REDIRECT, + code_verifier: verifier, + }, + store + ); + expect(response.status).toBe(400); + const body = (await response.json()) as TokenBody; + expect(body.error).toBe('invalid_grant'); + expect(body.error_description).toMatch(/already been used/); + }); + + it('an expired code gets invalid_grant with a retry hint', async () => { + const store = storeWithClient(); + const code = await seedApprovedCode(store); + // approveCode refuses expired codes, so model the reachable state + // directly: approved while alive, then expired before redemption. + store.codes.set(code, { + ...store.codes.get(code)!, + expiresAt: new Date(NOW.getTime() - 1000).toISOString(), + }); + const response = await handle( + { + grant_type: 'authorization_code', + code, + client_id: CLIENT_ID, + redirect_uri: REDIRECT, + code_verifier: verifier, + }, + store + ); + const body = (await response.json()) as TokenBody; + expect(body.error).toBe('invalid_grant'); + expect(body.error_description).toMatch(/expired/); + }); + + it('a not-yet-approved (pending) code gets invalid_grant to poll after approval', async () => { + const store = storeWithClient(); + const code = await seedApprovedCode(store, { status: 'pending' }); + const response = await handle( + { + grant_type: 'authorization_code', + code, + client_id: CLIENT_ID, + redirect_uri: REDIRECT, + code_verifier: verifier, + }, + store + ); + const body = (await response.json()) as TokenBody; + expect(body.error).toBe('invalid_grant'); + expect(body.error_description).toMatch(/not completed sign-in/); + }); +}); + +describe('POST /token authorization_code (non-retryable unhappy)', () => { + it('a wrong PKCE verifier gets an explicit error and no token', async () => { + const store = storeWithClient(); + const code = await seedApprovedCode(store); + const response = await handle( + { + grant_type: 'authorization_code', + code, + client_id: CLIENT_ID, + redirect_uri: REDIRECT, + code_verifier: generateCodeVerifier(), + }, + store + ); + const body = (await response.json()) as TokenBody; + expect(response.status).toBe(400); + expect(body.error).toBe('invalid_grant'); + expect(body.error_description).toMatch(/PKCE/); + expect(store.codes.get(code)!.status).toBe('approved'); + }); + + it('a wrong redirect_uri gets invalid_grant', async () => { + const store = storeWithClient(); + const code = await seedApprovedCode(store); + const response = await handle( + { + grant_type: 'authorization_code', + code, + client_id: CLIENT_ID, + redirect_uri: 'https://client.test/other', + code_verifier: verifier, + }, + store + ); + const body = (await response.json()) as TokenBody; + expect(body.error).toBe('invalid_grant'); + expect(body.error_description).toMatch(/redirect_uri/); + }); + + it('a wrong resource indicator gets invalid_target', async () => { + const store = storeWithClient(); + const code = await seedApprovedCode(store); + const response = await handle( + { + grant_type: 'authorization_code', + code, + client_id: CLIENT_ID, + redirect_uri: REDIRECT, + code_verifier: verifier, + resource: 'https://attacker.test/mcp', + }, + store + ); + const body = (await response.json()) as TokenBody; + expect(body.error).toBe('invalid_target'); + }); + + it('an unknown client_id gets invalid_client', async () => { + const store = storeWithClient(); + const code = await seedApprovedCode(store); + const response = await handle( + { + grant_type: 'authorization_code', + code, + client_id: 'ghost', + redirect_uri: REDIRECT, + code_verifier: verifier, + }, + store + ); + expect(((await response.json()) as TokenBody).error).toBe('invalid_client'); + }); + + it('a code issued to another client cannot be redeemed', async () => { + const store = storeWithClient(); + store.clients.set('other', { + clientId: 'other', + redirectUris: [REDIRECT], + clientName: 'Other', + createdAt: NOW.toISOString(), + }); + const code = await seedApprovedCode(store); + const response = await handle( + { + grant_type: 'authorization_code', + code, + client_id: 'other', + redirect_uri: REDIRECT, + code_verifier: verifier, + }, + store + ); + expect(((await response.json()) as TokenBody).error).toBe('invalid_grant'); + }); + + it('a denied code gets invalid_grant', async () => { + const store = storeWithClient(); + const code = await seedApprovedCode(store); + store.codes.set(code, { ...store.codes.get(code)!, status: 'denied' }); + const response = await handle( + { + grant_type: 'authorization_code', + code, + client_id: CLIENT_ID, + redirect_uri: REDIRECT, + code_verifier: verifier, + }, + store + ); + expect(((await response.json()) as TokenBody).error).toBe('invalid_grant'); + }); +}); + +describe('POST /token grant plumbing', () => { + it('missing parameters get invalid_request', async () => { + const store = storeWithClient(); + const response = await handle({ grant_type: 'authorization_code', code: 'x' }, store); + expect(((await response.json()) as TokenBody).error).toBe('invalid_request'); + }); + + it('an unsupported grant type gets unsupported_grant_type', async () => { + const store = storeWithClient(); + const response = await handle({ grant_type: 'password', username: 'u' }, store); + expect(((await response.json()) as TokenBody).error).toBe('unsupported_grant_type'); + }); + + it('a non-form body gets invalid_request', async () => { + const store = storeWithClient(); + const response = await handleToken( + new Request(`${ISSUER}/token`, { method: 'POST', body: 'garbage not urlencoded' }), + { store, tokenSecret: SECRET, issuer: ISSUER, now: () => NOW } + ); + expect(((await response.json()) as TokenBody).error).toBe('invalid_request'); + }); +}); + +describe('POST /token refresh_token (rotation)', () => { + async function seedRefresh(store: OAuthStoreApi): Promise { + const refreshToken = 'opaque-refresh-token-value-0000000000000000000000000000'; + await store.saveRefreshToken({ + id: 'rt-1', + tokenHash: await sha256HexTest(refreshToken), + clientId: CLIENT_ID, + kiloUserId: 'kilo-user-1', + organizationId: 'org-1', + kiloToken: 'kilo-token-1', + resource: RESOURCE, + scope: 'mcp', + createdAt: NOW.toISOString(), + expiresAt: new Date(NOW.getTime() + 30 * 24 * 3600_000).toISOString(), + }); + return refreshToken; + } + + it('rotates the refresh token and mints a new bound access token', async () => { + const store = storeWithClient(); + const refreshToken = await seedRefresh(store); + const response = await handle( + { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: CLIENT_ID }, + store + ); + expect(response.status).toBe(200); + const body = (await response.json()) as TokenBody; + expect(body.refresh_token).not.toBe(refreshToken); + const decoded = decodeJwt(body.access_token!)!; + expect(decoded.payload).toMatchObject({ + sub: 'kilo-user-1', + org: 'org-1', + aud: RESOURCE, + client_id: CLIENT_ID, + }); + + // old token revoked, new one stored + const oldHash = await sha256HexTest(refreshToken); + expect([...store.refreshTokens.values()].find(r => r.tokenHash === oldHash)!.revokedAt).toBe( + NOW.toISOString() + ); + // s6: the forwarding credential survives rotation. + const rotated = [...store.refreshTokens.values()].find(r => r.tokenHash !== oldHash)!; + expect(rotated.kiloToken).toBe('kilo-token-1'); + }); + + it('the old refresh token is rejected after rotation', async () => { + const store = storeWithClient(); + const refreshToken = await seedRefresh(store); + await handle( + { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: CLIENT_ID }, + store + ); + const response = await handle( + { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: CLIENT_ID }, + store + ); + expect(response.status).toBe(400); + expect(((await response.json()) as TokenBody).error).toBe('invalid_grant'); + }); + + it('a replayed rotated-away token revokes the whole grant (RFC 9700 §2.2.2)', async () => { + const store = storeWithClient(); + const refreshToken = await seedRefresh(store); + const first = await handle( + { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: CLIENT_ID }, + store + ); + const stolenToken = ((await first.json()) as TokenBody).refresh_token!; + + // The thief replays the rotated-away original: the grant's newest rotation + // (held by the legitimate client) must be revoked along with it. + const replay = await handle( + { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: CLIENT_ID }, + store + ); + expect(replay.status).toBe(400); + expect(((await replay.json()) as TokenBody).error).toBe('invalid_grant'); + const stolenHash = await sha256HexTest(stolenToken); + expect( + [...store.refreshTokens.values()].find(record => record.tokenHash === stolenHash)!.revokedAt + ).toBe(NOW.toISOString()); + + // The stolen newest token no longer refreshes either. + const thief = await handle( + { grant_type: 'refresh_token', refresh_token: stolenToken, client_id: CLIENT_ID }, + store + ); + expect(((await thief.json()) as TokenBody).error).toBe('invalid_grant'); + }); + + it('a replayed rotated-away token leaves the user grants of other orgs live', async () => { + const store = storeWithClient(); + const refreshToken = await seedRefresh(store); + await handle( + { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: CLIENT_ID }, + store + ); + // The user also granted this client a token scoped to another org. + await store.saveRefreshToken({ + id: 'rt-sibling', + tokenHash: await sha256HexTest('sibling-refresh-token-value'), + clientId: CLIENT_ID, + kiloUserId: 'kilo-user-1', + organizationId: 'org-2', + kiloToken: 'kilo-token-1', + resource: RESOURCE, + scope: 'mcp', + createdAt: NOW.toISOString(), + expiresAt: new Date(NOW.getTime() + 30 * 24 * 3600_000).toISOString(), + }); + + const replay = await handle( + { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: CLIENT_ID }, + store + ); + expect(((await replay.json()) as TokenBody).error).toBe('invalid_grant'); + const siblingHash = await sha256HexTest('sibling-refresh-token-value'); + expect( + [...store.refreshTokens.values()].find(record => record.tokenHash === siblingHash)!.revokedAt + ).toBeNull(); + }); + + it('an unknown refresh token gets invalid_grant', async () => { + const store = storeWithClient(); + const response = await handle( + { grant_type: 'refresh_token', refresh_token: 'never-issued', client_id: CLIENT_ID }, + store + ); + expect(((await response.json()) as TokenBody).error).toBe('invalid_grant'); + }); + + it('a refresh token presented by another registered client gets invalid_grant', async () => { + const store = storeWithClient(); + const refreshToken = await seedRefresh(store); + store.clients.set('other-client', { + clientId: 'other-client', + redirectUris: [REDIRECT], + clientName: 'Other', + createdAt: NOW.toISOString(), + }); + const response = await handle( + { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: 'other-client' }, + store + ); + expect(((await response.json()) as TokenBody).error).toBe('invalid_grant'); + }); + + it('an expired refresh token gets invalid_grant', async () => { + const store = storeWithClient(); + const refreshToken = await seedRefresh(store); + const hash = await sha256HexTest(refreshToken); + store.refreshTokens.set(hash, { + ...store.refreshTokens.get(hash)!, + expiresAt: new Date(NOW.getTime() - 1).toISOString(), + }); + const response = await handle( + { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: CLIENT_ID }, + store + ); + expect(((await response.json()) as TokenBody).error).toBe('invalid_grant'); + }); + + it('a wrong resource indicator during refresh gets invalid_target', async () => { + const store = storeWithClient(); + const refreshToken = await seedRefresh(store); + const response = await handle( + { + grant_type: 'refresh_token', + refresh_token: refreshToken, + client_id: CLIENT_ID, + resource: 'https://other.test/mcp', + }, + store + ); + expect(((await response.json()) as TokenBody).error).toBe('invalid_target'); + }); +}); + +async function sha256HexTest(value: string): Promise { + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)); + return [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, '0')).join(''); +} diff --git a/services/kilo-mcp/src/auth/token.ts b/services/kilo-mcp/src/auth/token.ts new file mode 100644 index 0000000000..2210be6b2f --- /dev/null +++ b/services/kilo-mcp/src/auth/token.ts @@ -0,0 +1,409 @@ +/** + * POST /token — the OAuth token endpoint for THIS MCP (RFC 6749 + RFC 8707). + * + * `authorization_code` grant: single-use code (atomically consumed), PKCE + * S256 verifier check, client_id + redirect_uri match against the stored + * record, resource-indicator binding. Issues an HMAC-signed JWT access token + * bound to user + org + this MCP (requirement 18): + * `{ iss, sub, org, aud, client_id, exp, jti }`. + * + * `refresh_token` grant: the opaque refresh token is stored only as a + * SHA-256 hash and rotated on every use (the old row is revoked atomically). + * Replaying a rotated-away token revokes the whole grant (RFC 9700 §2.2.2). + * + * Errors follow RFC 6749 §5.2: `invalid_request`, `invalid_client`, + * `invalid_grant`, `unsupported_grant_type`, plus `invalid_target` (RFC 8707) + * for a wrong resource indicator. Responses are `Cache-Control: no-store`. + * Never log a token from this module. + */ +import { signJwt } from './jwt'; +import { base64UrlEncode, isValidCodeVerifier, verifyPkceS256 } from './pkce'; +import { MCP_SCOPE, oauthErrorResponse, authJsonResponse } from './http'; +import type { OAuthStoreApi } from '../store/oauth-store'; + +export type TokenDeps = { + store: OAuthStoreApi; + /** HMAC secret for signing access tokens (wrangler secret, never logged). */ + tokenSecret: string; + /** This worker's origin for the current request — the JWT `iss`. */ + issuer: string; + now?: () => Date; +}; + +/** Access tokens are short-lived; revocation is via the jti registry. */ +export const ACCESS_TOKEN_TTL_SECONDS = 3600; +/** Refresh tokens live for 30 days and rotate on every use. */ +export const REFRESH_TOKEN_TTL_DAYS = 30; + +type GrantParams = Record; + +/** Accept RFC 6749 form-encoding; tolerate JSON bodies from spec-lax clients. */ +export async function parseTokenRequest(request: Request): Promise { + const text = await request.text(); + const contentType = request.headers.get('content-type') ?? ''; + if (contentType.includes('application/json')) { + try { + const body: unknown = JSON.parse(text); + if (typeof body !== 'object' || body === null || Array.isArray(body)) return null; + const params: GrantParams = {}; + for (const [key, value] of Object.entries(body as Record)) { + if (typeof value === 'string') params[key] = value; + } + return params; + } catch { + return null; + } + } + try { + const form = new URLSearchParams(text); + if (![...form.keys()].some(key => key === 'grant_type')) return null; + const params: GrantParams = {}; + for (const [key, value] of form.entries()) params[key] = value; + return params; + } catch { + return null; + } +} + +async function sha256Hex(value: string): Promise { + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)); + return [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, '0')).join(''); +} + +function opaqueToken(byteLength: number): string { + return base64UrlEncode(crypto.getRandomValues(new Uint8Array(byteLength))); +} + +type IssuedTokenPair = { + access_token: string; + token_type: 'Bearer'; + expires_in: number; + refresh_token: string; + scope: string; +}; + +type TokenGrant = { + kiloUserId: string; + organizationId: string | null; + /** The Kilo credential this grant forwards as (s6); carried across rotations. */ + kiloToken: string | null; + clientId: string; + resource: string; + scope: string; +}; + +/** Mint the HMAC-signed MCP access token (claims per requirement 18). */ +async function signAccessToken(deps: TokenDeps, grant: TokenGrant, now: Date): Promise { + const expiresAt = new Date(now.getTime() + ACCESS_TOKEN_TTL_SECONDS * 1000); + return signJwt( + { + iss: deps.issuer, + sub: grant.kiloUserId, + org: grant.organizationId, + aud: grant.resource, + client_id: grant.clientId, + exp: Math.floor(expiresAt.getTime() / 1000), + jti: opaqueToken(16), + }, + deps.tokenSecret + ); +} + +/** Store the opaque refresh token (hashed) and build the client-facing pair. */ +async function issueTokenPair( + deps: TokenDeps, + grant: TokenGrant, + refreshToken: string, + now: Date +): Promise { + await deps.store.saveRefreshToken({ + id: opaqueToken(16), + tokenHash: await sha256Hex(refreshToken), + clientId: grant.clientId, + kiloUserId: grant.kiloUserId, + organizationId: grant.organizationId, + kiloToken: grant.kiloToken, + resource: grant.resource, + scope: grant.scope, + createdAt: now.toISOString(), + expiresAt: refreshExpiresAt(now), + }); + return { + access_token: await signAccessToken(deps, grant, now), + token_type: 'Bearer', + expires_in: ACCESS_TOKEN_TTL_SECONDS, + refresh_token: refreshToken, + scope: grant.scope, + }; +} + +function refreshExpiresAt(now: Date): string { + return new Date(now.getTime() + REFRESH_TOKEN_TTL_DAYS * 24 * 60 * 60 * 1000).toISOString(); +} + +/** `resource` must equal the stored indicator when present (RFC 8707). */ +function checkResourceBinding(params: GrantParams, boundResource: string): Response | null { + const requested = params['resource']; + if (requested !== undefined && requested !== boundResource) { + return oauthErrorResponse( + 400, + 'invalid_target', + 'The resource indicator does not match the resource this grant was bound to.' + ); + } + return null; +} + +async function exchangeAuthorizationCode( + deps: TokenDeps, + params: GrantParams, + now: Date +): Promise { + const code = params['code']; + const clientId = params['client_id']; + const redirectUri = params['redirect_uri']; + const verifier = params['code_verifier']; + if (!code || !clientId || !redirectUri || !verifier) { + return oauthErrorResponse( + 400, + 'invalid_request', + 'code, client_id, redirect_uri and code_verifier are all required for the authorization_code grant.' + ); + } + const client = await deps.store.getClient(clientId); + if (!client) { + return oauthErrorResponse(400, 'invalid_client', 'Unknown client_id.'); + } + + const record = await deps.store.getCode(code); + if (!record) { + return oauthErrorResponse(400, 'invalid_grant', 'Unknown authorization code.'); + } + if (record.clientId !== clientId) { + return oauthErrorResponse( + 400, + 'invalid_grant', + 'This authorization code was issued to a different client.' + ); + } + const resourceError = checkResourceBinding(params, record.resource); + if (resourceError) return resourceError; + if (record.redirectUri !== redirectUri) { + return oauthErrorResponse( + 400, + 'invalid_grant', + 'redirect_uri does not match the authorization request.' + ); + } + if (record.status === 'pending') { + return oauthErrorResponse( + 400, + 'invalid_grant', + 'The user has not completed sign-in for this request yet. Retry after the user approves.' + ); + } + if (record.status === 'denied') { + return oauthErrorResponse(400, 'invalid_grant', 'The user denied this authorization request.'); + } + const nowIso = now.toISOString(); + if (record.status === 'used') { + // Retryable unhappy path: the client must run a fresh /authorize. + return oauthErrorResponse( + 400, + 'invalid_grant', + 'This authorization code has already been used. Start a new authorization.' + ); + } + if (record.expiresAt <= nowIso) { + return oauthErrorResponse( + 400, + 'invalid_grant', + 'This authorization code has expired. Start a new authorization.' + ); + } + if (!isValidCodeVerifier(verifier) || !(await verifyPkceS256(verifier, record.codeChallenge))) { + return oauthErrorResponse(400, 'invalid_grant', 'PKCE verification failed.'); + } + if (!record.kiloUserId) { + return oauthErrorResponse( + 400, + 'invalid_grant', + 'This authorization code has no approved identity.' + ); + } + if (!record.kiloToken) { + // s6: the pairing approval always records the Kilo credential; without it + // the issued token could never forward, so refuse to mint it. + return oauthErrorResponse( + 400, + 'invalid_grant', + 'This authorization code is missing its Kilo session. Start a new authorization.' + ); + } + + // Atomic single-use consumption; a concurrent exchange loses here. + const consumed = await deps.store.consumeCode(code, nowIso); + if (!consumed) { + return oauthErrorResponse( + 400, + 'invalid_grant', + 'This authorization code has already been used. Start a new authorization.' + ); + } + + const pair = await issueTokenPair( + deps, + { + kiloUserId: consumed.kiloUserId ?? record.kiloUserId, + organizationId: consumed.organizationId, + clientId, + kiloToken: consumed.kiloToken ?? record.kiloToken, + resource: consumed.resource, + scope: consumed.scope, + }, + opaqueToken(48), + now + ); + return authJsonResponse(pair, 200, { 'Cache-Control': 'no-store' }); +} + +async function redeemRefreshToken( + deps: TokenDeps, + params: GrantParams, + now: Date +): Promise { + const refreshToken = params['refresh_token']; + const clientId = params['client_id']; + if (!refreshToken || !clientId) { + return oauthErrorResponse( + 400, + 'invalid_request', + 'refresh_token and client_id are required for the refresh_token grant.' + ); + } + const client = await deps.store.getClient(clientId); + if (!client) { + return oauthErrorResponse(400, 'invalid_client', 'Unknown client_id.'); + } + const record = await deps.store.getRefreshTokenByHash(await sha256Hex(refreshToken)); + if (!record || record.clientId !== clientId) { + return oauthErrorResponse(400, 'invalid_grant', 'Unknown refresh token.'); + } + const resourceError = checkResourceBinding(params, record.resource); + if (resourceError) return resourceError; + const scope = params['scope']; + if (scope !== undefined) { + const wanted = scope.split(' ').filter(token => token.length > 0); + const granted = record.scope.split(' ').filter(token => token.length > 0); + if (wanted.length === 0 || !wanted.every(token => granted.includes(token))) { + return oauthErrorResponse( + 400, + 'invalid_scope', + `Requested scope exceeds the granted "${MCP_SCOPE}" scope.` + ); + } + } + const nowIso = now.toISOString(); + if (record.revokedAt || record.expiresAt <= nowIso) { + // Rotated-away-with or expired token: retryable only with a fresh login. + // A replayed rotated-away token is evidence the grant was stolen (the + // legitimate client only ever holds the newest rotation), so RFC 9700 + // §2.2.2 requires revoking the whole grant: the thief's newer tokens die + // with the replay, and resolveKiloToken finds no live grant left. A merely + // expired token is not theft evidence, so the family stays intact. + if (record.revokedAt) { + await deps.store.revokeGrant( + { + clientId: record.clientId, + kiloUserId: record.kiloUserId, + organizationId: record.organizationId, + resource: record.resource, + }, + nowIso + ); + } + return oauthErrorResponse( + 400, + 'invalid_grant', + 'This refresh token is no longer valid. Reconnect to start a new authorization.' + ); + } + + const newRefreshToken = opaqueToken(48); + const rotated = await deps.store.rotateRefreshToken( + record.id, + { + id: opaqueToken(16), + tokenHash: await sha256Hex(newRefreshToken), + clientId: record.clientId, + kiloUserId: record.kiloUserId, + organizationId: record.organizationId, + // The forward credential survives rotation (s6). + kiloToken: record.kiloToken, + resource: record.resource, + scope: record.scope, + createdAt: nowIso, + expiresAt: new Date( + now.getTime() + REFRESH_TOKEN_TTL_DAYS * 24 * 60 * 60 * 1000 + ).toISOString(), + }, + nowIso + ); + if (!rotated) { + return oauthErrorResponse( + 400, + 'invalid_grant', + 'This refresh token was already rotated. Use the latest token.' + ); + } + + // rotateRefreshToken already stored the new refresh row; only the access + // token is minted here. + const pair: IssuedTokenPair = { + access_token: await signAccessToken( + deps, + { + kiloUserId: record.kiloUserId, + organizationId: record.organizationId, + kiloToken: record.kiloToken, + clientId: record.clientId, + resource: record.resource, + scope: record.scope, + }, + now + ), + token_type: 'Bearer', + expires_in: ACCESS_TOKEN_TTL_SECONDS, + refresh_token: newRefreshToken, + scope: record.scope, + }; + return authJsonResponse(pair, 200, { 'Cache-Control': 'no-store' }); +} + +/** POST /token. */ +export async function handleToken(request: Request, deps: TokenDeps): Promise { + if (request.method !== 'POST') { + return oauthErrorResponse(405, 'invalid_request', 'Use POST for /token.'); + } + const params = await parseTokenRequest(request); + if (!params) { + return oauthErrorResponse( + 400, + 'invalid_request', + 'Body must be a form-encoded (or JSON) OAuth parameter set.' + ); + } + const now = deps.now?.() ?? new Date(); + switch (params['grant_type']) { + case 'authorization_code': + return exchangeAuthorizationCode(deps, params, now); + case 'refresh_token': + return redeemRefreshToken(deps, params, now); + default: + return oauthErrorResponse( + 400, + 'unsupported_grant_type', + 'Only authorization_code and refresh_token grants are supported.' + ); + } +} diff --git a/services/kilo-mcp/src/auth/verify.test.ts b/services/kilo-mcp/src/auth/verify.test.ts new file mode 100644 index 0000000000..118235d06b --- /dev/null +++ b/services/kilo-mcp/src/auth/verify.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it } from 'vitest'; +import { signJwt } from './jwt'; +import { verifyMcpAccessToken } from './verify'; + +const SECRET = 'verify-test-secret-32-bytes!!!'; +const ISSUER = 'https://kilo-mcp.test'; +const RESOURCE = `${ISSUER}/mcp`; + +function nowSeconds(): number { + return Math.floor(Date.now() / 1000); +} + +async function token(overrides: Record = {}, secret = SECRET): Promise { + return signJwt( + { + iss: ISSUER, + sub: 'kilo-user-1', + org: 'org-1', + aud: RESOURCE, + client_id: 'client-1', + exp: nowSeconds() + 3600, + jti: 'jti-1', + ...overrides, + }, + secret + ); +} + +const deps = { tokenSecret: SECRET, issuer: ISSUER, resource: RESOURCE }; + +describe('verifyMcpAccessToken', () => { + it('returns the bound identity for a valid token', async () => { + const result = await verifyMcpAccessToken(await token(), deps); + expect(result).toEqual({ + ok: true, + token: { + kiloUserId: 'kilo-user-1', + organizationId: 'org-1', + clientId: 'client-1', + expiresAt: expect.any(Number), + }, + }); + }); + + it('accepts a null org (personal identity)', async () => { + const result = await verifyMcpAccessToken(await token({ org: null }), deps); + expect(result.ok && result.token.organizationId).toBeNull(); + }); + + it('rejects a wrong signature without claiming ownership (passthrough stays possible)', async () => { + const result = await verifyMcpAccessToken( + await token({}, 'other-secret-32-bytes-absolute!!'), + deps + ); + expect(result).toEqual({ ok: false, mine: false, reason: 'signature' }); + }); + + it('rejects non-JWT bearers as foreign', async () => { + const result = await verifyMcpAccessToken('tok_app_123', deps); + expect(result).toMatchObject({ ok: false, mine: false, reason: 'malformed' }); + }); + + it('rejects an expired token (mine: true)', async () => { + const result = await verifyMcpAccessToken(await token({ exp: nowSeconds() - 1 }), deps); + expect(result).toEqual({ ok: false, mine: true, reason: 'expired' }); + }); + + it('rejects a revoked jti (mine: true)', async () => { + const result = await verifyMcpAccessToken(await token({ jti: 'bad-jti' }), { + ...deps, + isJtiRevoked: async jti => jti === 'bad-jti', + }); + expect(result).toEqual({ ok: false, mine: true, reason: 'revoked' }); + }); + + it('rejects a token not revoked when the registry says no', async () => { + const result = await verifyMcpAccessToken(await token({ jti: 'fine-jti' }), { + ...deps, + isJtiRevoked: async () => false, + }); + expect(result.ok).toBe(true); + }); + + it('rejects the wrong issuer (mine: true)', async () => { + const result = await verifyMcpAccessToken(await token({ iss: 'https://evil.test' }), deps); + expect(result).toEqual({ ok: false, mine: true, reason: 'issuer' }); + }); + + it('rejects the wrong audience — a token for another MCP resource (requirement 18)', async () => { + const result = await verifyMcpAccessToken( + await token({ aud: 'https://kilo-mcp.test/other' }), + deps + ); + expect(result).toEqual({ ok: false, mine: true, reason: 'audience' }); + }); + + it('rejects missing claim types', async () => { + const noJti = await verifyMcpAccessToken(await token({ jti: undefined }), deps); + expect(noJti).toMatchObject({ ok: false, mine: true, reason: 'claims' }); + const badExp = await verifyMcpAccessToken(await token({ exp: 'soon' }), deps); + expect(badExp).toMatchObject({ ok: false, mine: true, reason: 'expired' }); + }); + + it('rejects alg=none and foreign header shapes', async () => { + const header = btoa(JSON.stringify({ alg: 'none', typ: 'JWT' })) + .replaceAll('+', '-') + .replaceAll('/', '_') + .replaceAll('=', ''); + const payload = btoa(JSON.stringify({ iss: ISSUER, aud: RESOURCE, exp: nowSeconds() + 60 })) + .replaceAll('+', '-') + .replaceAll('/', '_') + .replaceAll('=', ''); + const result = await verifyMcpAccessToken(`${header}.${payload}.`, deps); + expect(result).toMatchObject({ ok: false, mine: false, reason: 'malformed' }); + }); +}); diff --git a/services/kilo-mcp/src/auth/verify.ts b/services/kilo-mcp/src/auth/verify.ts new file mode 100644 index 0000000000..de9d3a260a --- /dev/null +++ b/services/kilo-mcp/src/auth/verify.ts @@ -0,0 +1,83 @@ +/** + * Access-token verification for the MCP endpoint (requirement 18). + * + * `verifyMcpAccessToken` checks the HS256 signature, `iss`, `exp`, the + * resource-indicator `aud`, and the jti revocation registry, and returns the + * bound identity `{ kiloUserId, organizationId }`. + * + * The result carries `mine`: whether the token passed THIS worker's HMAC + * check. A foreign bearer (an apps/web token, some other issuer's JWT) is not + * ours and the caller may fall back to passthrough; a token that bears our + * signature but fails claims (expired, revoked, wrong audience) is ours and + * must be rejected outright. + */ +import { decodeJwt, verifyJwtSignature } from './jwt'; + +export type VerifiedMcpToken = { + kiloUserId: string; + organizationId: string | null; + clientId: string; + /** Seconds (JWT `exp`), for callers that want to cache the verify result. */ + expiresAt: number; +}; + +export type VerifyMcpTokenDeps = { + tokenSecret: string; + /** This worker's origin — the `iss` the token must carry. */ + issuer: string; + /** The canonical `/mcp` resource URL — the `aud` the token must carry. */ + resource: string; + /** jti revocation lookup (the KiloMcpOAuthStore registry). */ + isJtiRevoked?: (jti: string) => Promise; + now?: () => number; +}; + +export type McpTokenVerification = + | { ok: true; token: VerifiedMcpToken } + | { + ok: false; + mine: boolean; + reason: 'malformed' | 'signature' | 'expired' | 'revoked' | 'issuer' | 'audience' | 'claims'; + }; + +export async function verifyMcpAccessToken( + bearer: string, + deps: VerifyMcpTokenDeps +): Promise { + const decoded = decodeJwt(bearer); + if (!decoded) return { ok: false, mine: false, reason: 'malformed' }; + if (!(await verifyJwtSignature(decoded, deps.tokenSecret))) { + return { ok: false, mine: false, reason: 'signature' }; + } + // From here the token is definitely ours: every failure below is `mine: true`. + const { payload } = decoded; + if (payload['iss'] !== deps.issuer) return { ok: false, mine: true, reason: 'issuer' }; + if (payload['aud'] !== deps.resource) return { ok: false, mine: true, reason: 'audience' }; + const exp = payload['exp']; + if (typeof exp !== 'number' || exp * 1000 <= (deps.now?.() ?? Date.now())) { + return { ok: false, mine: true, reason: 'expired' }; + } + const sub = payload['sub']; + const clientId = payload['client_id']; + if (typeof sub !== 'string' || typeof clientId !== 'string') { + return { ok: false, mine: true, reason: 'claims' }; + } + const org = payload['org']; + if (org !== null && org !== undefined && typeof org !== 'string') { + return { ok: false, mine: true, reason: 'claims' }; + } + const jti = payload['jti']; + if (typeof jti !== 'string') return { ok: false, mine: true, reason: 'claims' }; + if (deps.isJtiRevoked && (await deps.isJtiRevoked(jti))) { + return { ok: false, mine: true, reason: 'revoked' }; + } + return { + ok: true, + token: { + kiloUserId: sub, + organizationId: typeof org === 'string' ? org : null, + clientId, + expiresAt: exp, + }, + }; +} diff --git a/services/kilo-mcp/src/call.test.ts b/services/kilo-mcp/src/call.test.ts new file mode 100644 index 0000000000..e070b8a25b --- /dev/null +++ b/services/kilo-mcp/src/call.test.ts @@ -0,0 +1,242 @@ +import { describe, expect, it, vi } from 'vitest'; +import { callCatalogEndpoint, MAX_RESULT_BYTES, serializeWithCap, TRUNCATION_MARKER } from './call'; +import { JsonRpcFailure, type Catalog, type ForwardedAuth } from './types'; + +/** Inline test catalog (no committed fixture; tests never depend on catalog drift). */ +const testCatalog: Catalog = { + 'organizations.list': { + path: 'organizations.list', + kind: 'query', + summary: 'List the organizations the user belongs to.', + inputSchema: {}, + tags: ['organizations'], + searchBlob: 'organizations.list List the organizations the user belongs to. organizations list', + }, + 'cliSessions.search': { + path: 'cliSessions.search', + kind: 'query', + summary: 'Search the user CLI sessions by keyword.', + inputSchema: { + $schema: 'https://json-schema.org/draft/2020-12/schema', + type: 'object', + properties: { + query: { type: 'string', minLength: 1 }, + limit: { type: 'integer', minimum: 1, maximum: 50 }, + }, + required: ['query'], + additionalProperties: false, + }, + tags: ['clisessions'], + searchBlob: + 'cliSessions.search Search the user CLI sessions by keyword. clisessions search query limit', + }, +}; + +const auth: ForwardedAuth = { authorization: 'Bearer tok_123', organizationId: 'org-uuid-1' }; +const WEB_BASE_URL = 'https://app.kilo.ai'; + +function upstreamResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +describe('callCatalogEndpoint', () => { + it('rejects a path outside the catalog with a JSON-RPC error and NO upstream request', async () => { + const fetchImpl = vi.fn(); + const error = await callCatalogEndpoint({ + catalog: testCatalog, + path: 'secrets.deleteAll', + input: undefined, + auth, + webBaseUrl: WEB_BASE_URL, + fetchImpl, + }).catch((e: unknown) => e); + expect(error).toBeInstanceOf(JsonRpcFailure); + expect((error as JsonRpcFailure).code).toBe(-32602); + expect((error as Error).message).toMatch(/catalog/); + expect((error as Error).message).toMatch(/search/); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it('does not resolve prototype keys as catalog paths', async () => { + const fetchImpl = vi.fn(); + await expect( + callCatalogEndpoint({ + catalog: testCatalog, + path: '__proto__', + input: undefined, + auth, + webBaseUrl: WEB_BASE_URL, + fetchImpl, + }) + ).rejects.toBeInstanceOf(JsonRpcFailure); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it('lists schema violations and skips the upstream when input is invalid', async () => { + const fetchImpl = vi.fn(); + const error = await callCatalogEndpoint({ + catalog: testCatalog, + path: 'cliSessions.search', + input: { query: '', limit: 999 }, + auth, + webBaseUrl: WEB_BASE_URL, + fetchImpl, + }).catch((e: unknown) => e); + expect(error).toBeInstanceOf(JsonRpcFailure); + expect((error as JsonRpcFailure).code).toBe(-32602); + const violations = (error as JsonRpcFailure).data?.['violations'] as string[]; + expect(violations.join('; ')).toContain('minLength'); + expect(violations.join('; ')).toContain('maximum'); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it('rejects a missing input for a procedure with required fields before any request', async () => { + const fetchImpl = vi.fn(); + await expect( + callCatalogEndpoint({ + catalog: testCatalog, + path: 'cliSessions.search', + input: undefined, + auth, + webBaseUrl: WEB_BASE_URL, + fetchImpl, + }) + ).rejects.toThrow(/input is required/); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it('forwards a valid call as a GET to the tRPC endpoint with auth passthrough', async () => { + const fetchImpl = vi.fn(async () => upstreamResponse({ result: { data: { sessions: [] } } })); + const outcome = await callCatalogEndpoint({ + catalog: testCatalog, + path: 'cliSessions.search', + input: { query: 'deploy' }, + auth, + webBaseUrl: WEB_BASE_URL, + fetchImpl, + }); + expect(outcome).toEqual({ text: '{"sessions":[]}', truncated: false }); + expect(fetchImpl).toHaveBeenCalledTimes(1); + const [url, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit]; + const parsed = new URL(url); + expect(parsed.origin).toBe(WEB_BASE_URL); + expect(parsed.pathname).toBe('/api/trpc/cliSessions.search'); + expect(parsed.searchParams.get('input')).toBe('{"query":"deploy"}'); + expect(init.method).toBe('GET'); + const headers = init.headers as Record; + expect(headers['Authorization']).toBe('Bearer tok_123'); + expect(headers['x-kilocode-organizationid']).toBe('org-uuid-1'); + }); + + it('omits the input param for a no-input procedure called without input', async () => { + const fetchImpl = vi.fn(async () => upstreamResponse({ result: { data: [{ id: 'org-1' }] } })); + const outcome = await callCatalogEndpoint({ + catalog: testCatalog, + path: 'organizations.list', + input: undefined, + auth: { authorization: 'Bearer tok_123' }, + webBaseUrl: WEB_BASE_URL, + fetchImpl, + }); + expect(outcome.text).toBe('[{"id":"org-1"}]'); + const [url, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit]; + expect(new URL(url).searchParams.has('input')).toBe(false); + const headers = init.headers as Record; + expect(headers['Authorization']).toBe('Bearer tok_123'); + expect('x-kilocode-organizationid' in headers).toBe(false); + }); + + it('maps a tRPC error body to a JSON-RPC error preserving code and httpStatus (retryable)', async () => { + const fetchImpl = vi.fn(async () => + upstreamResponse( + { + error: { + message: 'No such organization', + code: -32004, + data: { code: 'NOT_FOUND', httpStatus: 404, path: 'organizations.list' }, + }, + }, + 404 + ) + ); + const error = await callCatalogEndpoint({ + catalog: testCatalog, + path: 'organizations.list', + input: undefined, + auth, + webBaseUrl: WEB_BASE_URL, + fetchImpl, + }).catch((e: unknown) => e); + expect(error).toBeInstanceOf(JsonRpcFailure); + expect((error as JsonRpcFailure).message).toBe('No such organization'); + expect((error as JsonRpcFailure).data).toMatchObject({ + trpcCode: 'NOT_FOUND', + httpStatus: 404, + }); + // a corrected retry succeeds + const retryFetch = vi.fn(async () => upstreamResponse({ result: { data: [] } })); + await expect( + callCatalogEndpoint({ + catalog: testCatalog, + path: 'organizations.list', + input: undefined, + auth, + webBaseUrl: WEB_BASE_URL, + fetchImpl: retryFetch, + }) + ).resolves.toEqual({ text: '[]', truncated: false }); + }); + + it('surfaces a network failure as a retryable JSON-RPC error without leaking the token', async () => { + const fetchImpl = vi.fn(async () => { + throw new TypeError('fetch failed: https://tok_123@secret.invalid'); + }); + const error = await callCatalogEndpoint({ + catalog: testCatalog, + path: 'organizations.list', + input: undefined, + auth, + webBaseUrl: WEB_BASE_URL, + fetchImpl, + }).catch((e: unknown) => e); + expect(error).toBeInstanceOf(JsonRpcFailure); + expect((error as JsonRpcFailure).data).toMatchObject({ retryable: true }); + expect((error as Error).message).not.toContain('tok_123'); + }); + + it('rejects a 200 response without a tRPC result body', async () => { + const fetchImpl = vi.fn(async () => upstreamResponse({ nonsense: true })); + await expect( + callCatalogEndpoint({ + catalog: testCatalog, + path: 'organizations.list', + input: undefined, + auth, + webBaseUrl: WEB_BASE_URL, + fetchImpl, + }) + ).rejects.toThrow(/without a tRPC result body/); + }); +}); + +describe('serializeWithCap', () => { + it('passes small payloads through untouched', () => { + expect(serializeWithCap({ a: 1 })).toEqual({ text: '{"a":1}', truncated: false }); + }); + + it('cuts payloads over the cap, appends the marker, and stays within 16 KiB', () => { + const { text, truncated } = serializeWithCap({ blob: 'x'.repeat(MAX_RESULT_BYTES * 2) }); + expect(truncated).toBe(true); + expect(text.endsWith(TRUNCATION_MARKER)).toBe(true); + expect(new TextEncoder().encode(text).byteLength).toBeLessThanOrEqual(MAX_RESULT_BYTES); + }); + + it('never splits a multi-byte code point at the cut', () => { + const { text } = serializeWithCap({ blob: 'é'.repeat(MAX_RESULT_BYTES) }); + expect(text).not.toContain('\uFFFD'); + expect(text.endsWith(TRUNCATION_MARKER)).toBe(true); + }); +}); diff --git a/services/kilo-mcp/src/call.ts b/services/kilo-mcp/src/call.ts new file mode 100644 index 0000000000..179249e1c6 --- /dev/null +++ b/services/kilo-mcp/src/call.ts @@ -0,0 +1,200 @@ +import Ajv2020, { type ValidateFunction } from 'ajv/dist/2020.js'; +import addFormats from 'ajv-formats'; +import { ORGANIZATION_ID_HEADER } from './auth'; +import { JsonRpcFailure, type Catalog, type ForwardedAuth } from './types'; + +/** JSON-RPC error codes (see https://www.jsonrpc.org/specification). */ +const INVALID_PARAMS = -32602; +const INTERNAL_ERROR = -32000; + +/** Cap for a serialized tool result; over the cap the text is cut and marked. */ +export const MAX_RESULT_BYTES = 16 * 1024; +export const TRUNCATION_MARKER = '[truncated]'; + +const ajv = new Ajv2020({ strict: true, allErrors: true }); +addFormats(ajv); + +/** Compiled validators, cached per schema object (the schema is the cache key). */ +const validatorCache = new WeakMap(); + +function validatorFor(inputSchema: Record): ValidateFunction { + const cached = validatorCache.get(inputSchema); + if (cached) return cached; + let validate: ValidateFunction; + try { + validate = ajv.compile(inputSchema); + } catch (error) { + throw new JsonRpcFailure( + INTERNAL_ERROR, + `The published input schema for this endpoint is not a valid JSON Schema: ${ + error instanceof Error ? error.message : String(error) + }` + ); + } + validatorCache.set(inputSchema, validate); + return validate; +} + +function isNoInputSchema(inputSchema: Record): boolean { + return Object.keys(inputSchema).filter(key => key !== '$schema').length === 0; +} + +function describeViolations(validate: ValidateFunction): string[] { + return (validate.errors ?? []).map(error => { + const missing = (error.params as { missingProperty?: unknown }).missingProperty; + const where = error.instancePath || (typeof missing === 'string' ? missing : '') || '(root)'; + return `${where} (${error.keyword}): ${error.message ?? 'invalid'}`; + }); +} + +/** + * Serialize `data` for the tool result, capped at `maxBytes`. Over the cap the + * JSON is cut at a byte boundary (partial trailing code points dropped) and the + * `[truncated]` marker is appended so the total stays within the cap. + */ +export function serializeWithCap( + data: unknown, + maxBytes = MAX_RESULT_BYTES +): { + text: string; + truncated: boolean; +} { + const full = JSON.stringify(data) ?? 'null'; + const encoded = new TextEncoder().encode(full); + if (encoded.byteLength <= maxBytes) { + return { text: full, truncated: false }; + } + const marker = `\n${TRUNCATION_MARKER}`; + const budget = Math.max(0, maxBytes - new TextEncoder().encode(marker).byteLength); + // Cut at a code-point boundary: TextDecoder defaults to non-fatal UTF-8, + // then drop a trailing replacement character left by a split multi-byte + // sequence. + const decoder = new TextDecoder(); + const cut = decoder.decode(encoded.subarray(0, budget)).replace(/\uFFFD+$/, ''); + return { text: `${cut}${marker}`, truncated: true }; +} + +type TrpcErrorBody = { + error?: { + message?: unknown; + code?: unknown; + data?: { code?: unknown; httpStatus?: unknown; path?: unknown }; + }; +}; + +function toTrpcFailure(status: number, body: TrpcErrorBody | null, path: string): JsonRpcFailure { + const json = body?.error ?? {}; + const data = json.data ?? {}; + const message = + typeof json.message === 'string' && json.message.length > 0 + ? json.message + : `Upstream Kilo request for "${path}" failed with HTTP ${status}`; + return new JsonRpcFailure(INTERNAL_ERROR, message, { + path, + trpcCode: typeof data.code === 'string' ? data.code : undefined, + httpStatus: typeof data.httpStatus === 'number' ? data.httpStatus : status, + }); +} + +/** + * Validate `input` against the endpoint's published schema and forward the + * call to apps/web over its public tRPC GET transport: + * `{WEB_BASE_URL}/api/trpc/{path}?input=`. apps/web resolves + * identity from the forwarded bearer and the organization header — with the + * s6 flow both come from the verified MCP token: the bearer is the Kilo + * credential bound to the token's identity, and the organization header is + * set from the token's org claim (never from a caller-supplied header). + * + * Every rejection that can be decided locally (unknown path, schema-invalid + * input) throws a JsonRpcFailure BEFORE any upstream request is made. + */ +export async function callCatalogEndpoint(options: { + catalog: Catalog; + path: string; + input: unknown; + auth: ForwardedAuth; + webBaseUrl: string; + fetchImpl?: typeof fetch; +}): Promise<{ text: string; truncated: boolean }> { + const { catalog, path, input, auth, webBaseUrl } = options; + const row = Object.prototype.hasOwnProperty.call(catalog, path) ? catalog[path] : undefined; + if (!row) { + throw new JsonRpcFailure( + INVALID_PARAMS, + `Unknown path "${path}". The call tool only accepts paths published in the Kilo catalog — run the search tool first and call one of the paths it returns.`, + { path } + ); + } + + const schemaIsEmpty = isNoInputSchema(row.inputSchema); + const sendInput = input !== undefined && input !== null; + if (sendInput && !schemaIsEmpty) { + const validate = validatorFor(row.inputSchema); + if (!validate(input)) { + const violations = describeViolations(validate); + throw new JsonRpcFailure( + INVALID_PARAMS, + `Input does not match the published schema for "${path}": ${violations.join('; ')}`, + { path, violations } + ); + } + } + if (!sendInput && !schemaIsEmpty) { + const required = Array.isArray(row.inputSchema['required']) ? row.inputSchema['required'] : []; + if (required.length > 0) { + throw new JsonRpcFailure( + INVALID_PARAMS, + `Input does not match the published schema for "${path}": (root): input is required (missing ${required + .map(key => String(key)) + .join(', ')})`, + { path, violations: ['(root): input is required'] } + ); + } + } + + const url = new URL(`/api/trpc/${row.path}`, webBaseUrl); + if (sendInput) { + url.searchParams.set('input', JSON.stringify(input)); + } + const headers: Record = { + Accept: 'application/json', + Authorization: auth.authorization, + }; + if (auth.organizationId) { + headers[ORGANIZATION_ID_HEADER] = auth.organizationId; + } + + const fetchImpl = options.fetchImpl ?? fetch; + let response: Response; + try { + response = await fetchImpl(url.toString(), { method: 'GET', headers }); + } catch { + // Network-level failure: retryable, and safe to surface — no token in it. + throw new JsonRpcFailure( + INTERNAL_ERROR, + `Could not reach the Kilo API for "${path}". Retry the call.`, + { path, retryable: true } + ); + } + + let body: unknown = null; + try { + body = await response.json(); + } catch { + body = null; + } + + if (!response.ok) { + throw toTrpcFailure(response.status, body as TrpcErrorBody, path); + } + + const result = (body as { result?: { data?: unknown } } | null)?.result; + if (!result || !Object.prototype.hasOwnProperty.call(result, 'data')) { + throw new JsonRpcFailure( + INTERNAL_ERROR, + `The Kilo API replied to "${path}" without a tRPC result body.`, + { path } + ); + } + return serializeWithCap(result.data); +} diff --git a/services/kilo-mcp/src/db/sqlite-schema.ts b/services/kilo-mcp/src/db/sqlite-schema.ts new file mode 100644 index 0000000000..035aa15ba9 --- /dev/null +++ b/services/kilo-mcp/src/db/sqlite-schema.ts @@ -0,0 +1,93 @@ +import { sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core'; + +/** + * DO SQLite schema for the KiloMcpOAuthStore Durable Object (s5, migration tag v1). + * + * All timestamps are ISO-8601 strings (UTC) so they compare correctly with + * `>` / `<` in SQLite and clone cleanly over DO RPC. + */ + +/** RFC 7591 dynamic client registrations (public clients only — no secret column). */ +export const oauthClients = sqliteTable('oauth_clients', { + client_id: text('client_id').primaryKey(), + /** JSON-encoded string array of registered redirect URIs. */ + redirect_uris: text('redirect_uris').notNull(), + client_name: text('client_name').notNull(), + created_at: text('created_at').notNull(), +}); + +/** + * Authorization codes, created as short-lived single-use pairing records by + * GET /authorize (status 'pending') and filled with the Kilo identity when the + * user approves the device-auth pairing (status 'approved'). The token + * endpoint consumes a code atomically (approved -> 'used'). + */ +export const oauthCodes = sqliteTable( + 'oauth_codes', + { + /** The authorization code itself: 256-bit random, single-use, TTL-bound. */ + code: text('code').primaryKey(), + client_id: text('client_id').notNull(), + redirect_uri: text('redirect_uri').notNull(), + /** PKCE S256 challenge (the only method this server accepts). */ + code_challenge: text('code_challenge').notNull(), + /** RFC 8707 resource indicator this code is bound to. */ + resource: text('resource').notNull(), + scope: text('scope').notNull(), + /** Opaque CSRF state echoed back to the client on redirect. */ + state: text('state'), + /** The apps/web device-auth pairing code (`code` from POST /api/device-auth/codes). */ + device_auth_code: text('device_auth_code').notNull(), + status: text('status', { enum: ['pending', 'approved', 'used', 'denied'] }).notNull(), + /** Set when the user approves the pairing; until then the code cannot be exchanged. */ + kilo_user_id: text('kilo_user_id'), + /** Null for personal (org-less) identities. */ + organization_id: text('organization_id'), + /** + * The Kilo API token returned when the device-auth pairing was approved + * (s6). Single-use upstream: it is persisted the moment the worker learns + * of the approval so no second poll is ever needed. Never logged. + */ + kilo_token: text('kilo_token'), + created_at: text('created_at').notNull(), + expires_at: text('expires_at').notNull(), + }, + table => [uniqueIndex('uq_oauth_codes_device_auth_code').on(table.device_auth_code)] +); + +/** Opaque refresh tokens, stored only as SHA-256 hashes; rotation revokes the old row. */ +export const oauthRefreshTokens = sqliteTable( + 'oauth_refresh_tokens', + { + id: text('id').primaryKey(), + /** Hex SHA-256 of the opaque refresh token handed to the client. */ + token_hash: text('token_hash').notNull(), + client_id: text('client_id').notNull(), + kilo_user_id: text('kilo_user_id').notNull(), + organization_id: text('organization_id'), + /** + * The Kilo API token this grant was minted from (s6): the credential the + * worker forwards to apps/web when the bearer presenting an MCP access + * token calls a procedure. Copied forward across rotations. Never logged. + */ + kilo_token: text('kilo_token'), + resource: text('resource').notNull(), + scope: text('scope').notNull(), + created_at: text('created_at').notNull(), + expires_at: text('expires_at').notNull(), + revoked_at: text('revoked_at'), + }, + table => [uniqueIndex('uq_oauth_refresh_tokens_hash').on(table.token_hash)] +); + +/** + * Registry of revoked access-token jtis. verify.ts rejects any token whose jti + * appears here; rows are purged once the token's own expiry has passed (a + * revoked-but-expired token is already useless). + */ +export const oauthRevokedJtis = sqliteTable('oauth_revoked_jtis', { + jti: text('jti').primaryKey(), + /** Expiry of the access token this jti belonged to (ISO string). */ + expires_at: text('expires_at').notNull(), + revoked_at: text('revoked_at').notNull(), +}); diff --git a/services/kilo-mcp/src/embed-catalog-script.test.ts b/services/kilo-mcp/src/embed-catalog-script.test.ts new file mode 100644 index 0000000000..f3c444dfc9 --- /dev/null +++ b/services/kilo-mcp/src/embed-catalog-script.test.ts @@ -0,0 +1,195 @@ +import { describe, expect, it, vi } from 'vitest'; +import { EMBEDDING_DIMENSIONS, EMBEDDING_METRIC, EMBEDDING_MODEL } from '../src/embedding'; +import type { Catalog } from '../src/types'; +import { + CfApiError, + EMBED_BATCH_SIZE, + embedAndUpsert, + ensureIndex, + loadCatalog, +} from '../scripts/embed-catalog.ts'; + +const ENV = { + CLOUDFLARE_ACCOUNT_ID: 'acct123', + CLOUDFLARE_API_TOKEN: 'token-secret', + VECTORIZE_INDEX_NAME: 'kilo-mcp-catalog-dev', +}; + +/** A minimal catalog of `count` rows. */ +function catalogOf(count: number): Catalog { + return Object.fromEntries( + Array.from({ length: count }, (_, i) => [ + `proc${i}.list`, + { + path: `proc${i}.list`, + kind: 'query', + summary: `Summary ${i}`, + inputSchema: {}, + tags: [`tag${i}`], + searchBlob: `proc${i}.list Summary ${i} tag${i}`, + }, + ]) + ); +} + +type RecordedCall = { + url: string; + method?: string; + headers?: Record; + body?: string; +}; + +/** A fetch fake that records calls and answers each route via `routes`. */ +function fetchFake(routes: Array<(call: RecordedCall) => unknown | undefined>): { + fetchImpl: ( + url: string, + init?: Record + ) => Promise<{ ok: boolean; status: number; json(): Promise }>; + calls: RecordedCall[]; +} { + const calls: RecordedCall[] = []; + const fetchImpl = async (url: string, init?: Record) => { + const call: RecordedCall = { + url, + method: init?.['method'] as string | undefined, + headers: init?.['headers'] as Record | undefined, + body: init?.['body'] as string | undefined, + }; + calls.push(call); + for (const route of routes) { + const result = route(call); + if (result !== undefined) { + return { ok: true, status: 200, json: async () => ({ success: true, result }) }; + } + } + return { + ok: false, + status: 404, + json: async () => ({ success: false, errors: [{ code: 7000, message: 'index not found' }] }), + }; + }; + return { fetchImpl, calls }; +} + +describe('ensureIndex', () => { + it('creates the index with the pinned dimensions and metric when it does not exist', async () => { + const { fetchImpl, calls } = fetchFake([ + call => + call.url.endsWith(`/vectorize/v2/indexes/${ENV.VECTORIZE_INDEX_NAME}`) ? null : undefined, + call => (call.url.endsWith('/vectorize/v2/indexes') ? {} : undefined), + ]); + const log = vi.fn(); + const outcome = await ensureIndex({ + ...ENV, + catalog: {}, + fetchImpl, + log, + }); + expect(outcome).toEqual({ created: true, indexName: 'kilo-mcp-catalog-dev' }); + const create = calls.find(call => call.method === 'POST'); + expect(create?.url).toBe( + `https://api.cloudflare.com/client/v4/accounts/${ENV.CLOUDFLARE_ACCOUNT_ID}/vectorize/v2/indexes` + ); + expect(JSON.parse(create!.body!)).toEqual({ + name: 'kilo-mcp-catalog-dev', + config: { dimensions: EMBEDDING_DIMENSIONS, metric: EMBEDDING_METRIC }, + description: expect.any(String), + }); + expect(log).toHaveBeenCalledWith(expect.stringContaining('created index')); + }); + + it('leaves an existing index untouched (idempotent)', async () => { + const { fetchImpl, calls } = fetchFake([ + call => + call.url.endsWith(`/vectorize/v2/indexes/${ENV.VECTORIZE_INDEX_NAME}`) + ? { name: ENV.VECTORIZE_INDEX_NAME } + : undefined, + ]); + const outcome = await ensureIndex({ ...ENV, catalog: {}, fetchImpl }); + expect(outcome).toEqual({ created: false, indexName: 'kilo-mcp-catalog-dev' }); + expect(calls.filter(call => call.method === 'POST')).toHaveLength(0); + }); + + it('surfaces API errors with their HTTP status', async () => { + const fetchImpl = async () => ({ + ok: false, + status: 403, + json: async () => ({ + success: false, + errors: [{ code: 10000, message: 'authentication error' }], + }), + }); + await expect(ensureIndex({ ...ENV, catalog: {}, fetchImpl })).rejects.toThrow(CfApiError); + await expect(ensureIndex({ ...ENV, catalog: {}, fetchImpl })).rejects.toThrow( + 'authentication error' + ); + }); +}); + +describe('embedAndUpsert', () => { + it('embeds searchBlobs with the pinned model and upserts vector id = path with {path, kind, tags} metadata', async () => { + const vector = Array.from({ length: EMBEDDING_DIMENSIONS }, () => 0.5); + const { fetchImpl, calls } = fetchFake([ + call => (call.url.includes('/ai/run/') ? { data: [vector] } : undefined), + call => (call.url.includes('/upsert') ? { count: 1, mutationId: 'm1' } : undefined), + ]); + const outcome = await embedAndUpsert({ ...ENV, catalog: catalogOf(1), fetchImpl }); + expect(outcome).toEqual({ vectors: 1 }); + + const embed = calls.find(call => call.url.includes('/ai/run/'))!; + expect(embed.url).toBe( + `https://api.cloudflare.com/client/v4/accounts/${ENV.CLOUDFLARE_ACCOUNT_ID}/ai/run/${EMBEDDING_MODEL}` + ); + expect(JSON.parse(embed.body!)).toEqual({ text: ['proc0.list Summary 0 tag0'] }); + + const upsert = calls.find(call => call.url.includes('/upsert'))!; + expect(upsert.headers?.['Content-Type']).toBe('application/x-ndjson'); + const record = JSON.parse(upsert.body!.split('\n')[0]!); + expect(record.id).toBe('proc0.list'); + expect(record.values).toEqual(vector); + expect(record.metadata).toEqual({ path: 'proc0.list', kind: 'query', tags: ['tag0'] }); + }); + + it('batches at most 64 rows per embed and upsert request', async () => { + const vector = Array.from({ length: EMBEDDING_DIMENSIONS }, () => 0.25); + const count = EMBED_BATCH_SIZE * 2 + 5; + const { fetchImpl, calls } = fetchFake([ + call => { + if (!call.url.includes('/ai/run/')) return undefined; + const requested = (JSON.parse(call.body!) as { text: string[] }).text.length; + return { data: Array.from({ length: requested }, () => vector) }; + }, + call => (call.url.includes('/upsert') ? { count: call.body!.split('\n').length } : undefined), + ]); + const outcome = await embedAndUpsert({ ...ENV, catalog: catalogOf(count), fetchImpl }); + const embedCalls = calls.filter(call => call.url.includes('/ai/run/')); + expect(embedCalls).toHaveLength(3); + const batchSizes = embedCalls.map( + call => (JSON.parse(call.body!) as { text: string[] }).text.length + ); + expect(batchSizes).toEqual([EMBED_BATCH_SIZE, EMBED_BATCH_SIZE, 5]); + expect(outcome.vectors).toBe(count); + }); + + it('fails loudly when the embedding API returns fewer vectors than rows sent', async () => { + const { fetchImpl } = fetchFake([ + call => (call.url.includes('/ai/run/') ? { data: [] } : undefined), + ]); + await expect(embedAndUpsert({ ...ENV, catalog: catalogOf(2), fetchImpl })).rejects.toThrow( + 'returned 0 vectors for a batch of 2' + ); + }); +}); + +describe('loadCatalog', () => { + it('reads the committed catalog.json beside the script (regression: double-encoded import.meta.url ENOENT)', () => { + const catalog = loadCatalog(); + const rows = Object.values(catalog); + expect(rows.length).toBeGreaterThan(0); + for (const row of rows) { + expect(row.path).toBeTruthy(); + expect(typeof row.searchBlob).toBe('string'); + expect(row.searchBlob.length).toBeGreaterThan(0); + } + }); +}); diff --git a/services/kilo-mcp/src/embedding.ts b/services/kilo-mcp/src/embedding.ts new file mode 100644 index 0000000000..aa46846386 --- /dev/null +++ b/services/kilo-mcp/src/embedding.ts @@ -0,0 +1,21 @@ +/** + * The ONE pinned embedding model for the Kilo catalog semantic index, shared + * by the worker (query embedding, src/search-knn.ts) and the embed script + * (scripts/embed-catalog.ts). Pinning here keeps the index and query + * embeddings from ever drifting: the Vectorize index is created with exactly + * these dimensions and metric, and every embedding call uses exactly this + * model. + * + * Embedding happens only at dump/embed time. Nothing embeds catalog content + * per `call`; per request the ONLY text embedded is the search QUERY inside + * `search` (via the AI binding below). + */ + +/** Workers AI embedding model id (Cloudflare catalog: BAAI bge-base-en-v1.5). */ +export const EMBEDDING_MODEL = '@cf/baai/bge-base-en-v1.5'; + +/** Output dimensionality of EMBEDDING_MODEL; the Vectorize index is created with it. */ +export const EMBEDDING_DIMENSIONS = 768; + +/** Similarity metric of the Vectorize index. */ +export const EMBEDDING_METRIC = 'cosine' as const; diff --git a/services/kilo-mcp/src/index.test.ts b/services/kilo-mcp/src/index.test.ts new file mode 100644 index 0000000000..d343245a08 --- /dev/null +++ b/services/kilo-mcp/src/index.test.ts @@ -0,0 +1,993 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import worker, { createMcpHandler } from './index'; +import { ORGANIZATION_ID_HEADER } from './auth'; +import { decodeJwt, signJwt } from './auth/jwt'; +import type { + OAuthCodeRecord, + OAuthStoreApi, + RefreshTokenRecord, + StoredClient, +} from './store/oauth-store'; +import type { Catalog } from './types'; + +// `cloudflare:workers` does not exist under plain node vitest; the DO import +// only extends its base class, so a stub base is enough. Vitest hoists this +// above the static imports, and the factory closes over nothing. +vi.mock('cloudflare:workers', () => ({ + DurableObject: class { + ctx: unknown; + env: unknown; + constructor(ctx: unknown, env: unknown) { + this.ctx = ctx; + this.env = env; + } + }, +})); + +/** Inline test catalog (no committed fixture; tests never depend on catalog drift). */ +const testCatalog: Catalog = { + 'organizations.list': { + path: 'organizations.list', + kind: 'query', + summary: 'List the organizations the user belongs to.', + inputSchema: {}, + tags: ['organizations'], + searchBlob: 'organizations.list List the organizations the user belongs to. organizations list', + }, + 'cliSessions.search': { + path: 'cliSessions.search', + kind: 'query', + summary: 'Search the user CLI sessions by keyword.', + inputSchema: { + $schema: 'https://json-schema.org/draft/2020-12/schema', + type: 'object', + properties: { query: { type: 'string', minLength: 1 } }, + required: ['query'], + }, + tags: ['clisessions'], + searchBlob: + 'cliSessions.search Search the user CLI sessions by keyword. clisessions search query', + }, +}; + +const AUTH_HEADERS = { + Authorization: 'Bearer tok_123', + 'Content-Type': 'application/json', +}; + +function makeHandler(fetchImpl?: typeof fetch) { + return createMcpHandler({ + catalog: testCatalog, + webBaseUrl: 'https://app.kilo.ai', + ...(fetchImpl ? { fetchImpl } : {}), + }); +} + +async function rpc( + handler: ReturnType, + body: unknown, + headers: Record = AUTH_HEADERS +) { + const response = await handler( + new Request('https://kilo-mcp.test/mcp', { + method: 'POST', + headers, + body: JSON.stringify(body), + }) + ); + return response; +} + +async function rpcResult(body: unknown, fetchImpl?: typeof fetch) { + const response = await rpc(makeHandler(fetchImpl), body); + return { response, json: (await response.json()) as Record }; +} + +describe('routing and transport', () => { + const env = { WEB_BASE_URL: 'https://app.kilo.ai' } as Env; + + it('serves MCP only at /mcp: unknown routes are 404', async () => { + const response = await worker.fetch(new Request('https://kilo-mcp.test/other'), env); + expect(response.status).toBe(404); + }); + + it('answers CORS preflight with the shared header set', async () => { + const response = await worker.fetch( + new Request('https://kilo-mcp.test/mcp', { method: 'OPTIONS' }), + env + ); + expect(response.status).toBe(204); + expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*'); + expect(response.headers.get('Access-Control-Allow-Headers')).toContain('Authorization'); + }); + + it('is stateless POST-only: GET /mcp is 405', async () => { + const response = await worker.fetch( + new Request('https://kilo-mcp.test/mcp', { method: 'GET' }), + env + ); + expect(response.status).toBe(405); + }); + + it('requires a bearer token: 401 before any catalog or upstream work', async () => { + const handler = makeHandler(); + const response = await handler( + new Request('https://kilo-mcp.test/mcp', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize' }), + }) + ); + expect(response.status).toBe(401); + expect(response.headers.get('WWW-Authenticate')).toBe( + 'Bearer error="invalid_token", resource_metadata="https://kilo-mcp.test/.well-known/oauth-protected-resource"' + ); + const json = (await response.json()) as { error: { code: number } }; + expect(json.error.code).toBe(-32001); + }); + + it('rejects a parse error and a batch request', async () => { + const handler = makeHandler(); + const bad = await handler( + new Request('https://kilo-mcp.test/mcp', { + method: 'POST', + headers: AUTH_HEADERS, + body: '{not json', + }) + ); + expect(bad.status).toBe(200); + expect(((await bad.json()) as { error: { code: number } }).error.code).toBe(-32700); + + const batch = await rpc(handler, [ + { jsonrpc: '2.0', id: 1, method: 'ping' }, + { jsonrpc: '2.0', id: 2, method: 'ping' }, + ]); + expect(((await batch.json()) as { error: { code: number } }).error.code).toBe(-32600); + }); + + it('answers notifications with 202 and no body', async () => { + const response = await rpc(makeHandler(), { + jsonrpc: '2.0', + method: 'notifications/initialized', + }); + expect(response.status).toBe(202); + expect(await response.text()).toBe(''); + }); + + it('rejects unknown methods with -32601', async () => { + const { json } = await rpcResult({ jsonrpc: '2.0', id: 7, method: 'resources/list' }); + expect((json as { error: { code: number } }).error.code).toBe(-32601); + expect((json as { id: number }).id).toBe(7); + }); +}); + +describe('initialize / ping / tools/list', () => { + it('initialize echoes the protocol version and advertises tools', async () => { + const { json } = await rpcResult({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { protocolVersion: '2025-06-18', capabilities: {} }, + }); + const result = (json as { result: Record }).result; + expect(result['protocolVersion']).toBe('2025-06-18'); + expect(result['serverInfo']).toMatchObject({ name: 'kilo-mcp' }); + expect(result['capabilities']).toMatchObject({ tools: {} }); + }); + + it('ping returns an empty result', async () => { + const { json } = await rpcResult({ jsonrpc: '2.0', id: 2, method: 'ping' }); + expect((json as { result: unknown }).result).toEqual({}); + }); + + it('tools/list returns exactly search and call, each telling the agent to search first', async () => { + const { json } = await rpcResult({ jsonrpc: '2.0', id: 3, method: 'tools/list' }); + const tools = ( + json as { + result: { + tools: Array<{ name: string; description: string; inputSchema: Record }>; + }; + } + ).result.tools; + expect(tools.map(tool => tool.name)).toEqual(['search', 'call']); + expect(tools[0]!.description.toLowerCase()).toContain('search'); + expect(tools[1]!.description.toLowerCase()).toContain('search'); + expect(tools[0]!.inputSchema).toMatchObject({ + type: 'object', + properties: { query: { type: 'string' }, limit: { type: 'integer' } }, + required: ['query'], + }); + expect(tools[1]!.inputSchema).toMatchObject({ + type: 'object', + properties: { path: { type: 'string' }, input: { type: 'object' } }, + required: ['path'], + }); + }); +}); + +describe('tools/call search', () => { + it('happy: returns catalog rows for a matching query', async () => { + const { json } = await rpcResult({ + jsonrpc: '2.0', + id: 4, + method: 'tools/call', + params: { name: 'search', arguments: { query: 'organizations list' } }, + }); + const content = (json as { result: { content: Array<{ type: string; text: string }> } }).result + .content; + const payload = JSON.parse(content[0]!.text) as { + results: Array<{ + path: string; + kind: string; + summary: string; + tags: string[]; + score: number; + }>; + }; + expect(payload.results[0]?.path).toBe('organizations.list'); + expect(payload.results[0]).toMatchObject({ kind: 'query', tags: ['organizations'] }); + }); + + it('empty: no matches is a zero-row result with a refine-your-query message, not an error', async () => { + const { json } = await rpcResult({ + jsonrpc: '2.0', + id: 5, + method: 'tools/call', + params: { name: 'search', arguments: { query: 'zzqqx nothing' } }, + }); + expect('error' in (json as Record)).toBe(false); + const text = (json as { result: { content: Array<{ text: string }> } }).result.content[0]!.text; + const payload = JSON.parse(text) as { results: unknown[]; message: string }; + expect(payload.results).toEqual([]); + expect(payload.message.toLowerCase()).toContain('refine your query'); + }); + + it('invalid arguments are a JSON-RPC invalid-params error', async () => { + const { json } = await rpcResult({ + jsonrpc: '2.0', + id: 6, + method: 'tools/call', + params: { name: 'search', arguments: {} }, + }); + expect((json as { error: { code: number } }).error.code).toBe(-32602); + }); + + it('unknown tool names are rejected', async () => { + const { json } = await rpcResult({ + jsonrpc: '2.0', + id: 8, + method: 'tools/call', + params: { name: 'delete', arguments: {} }, + }); + expect((json as { error: { code: number; message: string } }).error.message).toContain( + 'Unknown tool' + ); + }); +}); + +describe('tools/call call', () => { + it('happy: forwards a valid call and returns the unwrapped tRPC data', async () => { + const fetchImpl = vi.fn( + async () => + new Response(JSON.stringify({ result: { data: { balance: 42 } } }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) + ); + const { json } = await rpcResult( + { + jsonrpc: '2.0', + id: 9, + method: 'tools/call', + params: { name: 'call', arguments: { path: 'organizations.list' } }, + }, + fetchImpl + ); + const text = (json as { result: { content: Array<{ text: string }> } }).result.content[0]!.text; + expect(text).toBe('{"balance":42}'); + const [url, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit]; + expect(url).toBe('https://app.kilo.ai/api/trpc/organizations.list'); + expect(init.method).toBe('GET'); + expect((init.headers as Record)['Authorization']).toBe('Bearer tok_123'); + }); + + it('passes the organization header through to apps/web', async () => { + const fetchImpl = vi.fn( + async () => + new Response(JSON.stringify({ result: { data: [] } }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) + ); + await rpc( + makeHandler(fetchImpl), + { + jsonrpc: '2.0', + id: 10, + method: 'tools/call', + params: { name: 'call', arguments: { path: 'organizations.list' } }, + }, + { ...AUTH_HEADERS, [ORGANIZATION_ID_HEADER]: 'org-uuid-1' } + ); + const [, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit]; + expect((init.headers as Record)[ORGANIZATION_ID_HEADER]).toBe('org-uuid-1'); + }); + + it('non-retryable: unknown path is a JSON-RPC error before any upstream request', async () => { + const fetchImpl = vi.fn(); + const { json } = await rpcResult( + { + jsonrpc: '2.0', + id: 11, + method: 'tools/call', + params: { name: 'call', arguments: { path: 'nope.goes.here' } }, + }, + fetchImpl + ); + expect((json as { error: { code: number } }).error.code).toBe(-32602); + expect((json as { error: { message: string } }).error.message).toMatch(/catalog/); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it('non-retryable: schema-invalid input is a JSON-RPC error listing violations, no upstream', async () => { + const fetchImpl = vi.fn(); + const { json } = await rpcResult( + { + jsonrpc: '2.0', + id: 12, + method: 'tools/call', + params: { name: 'call', arguments: { path: 'cliSessions.search', input: { query: 12 } } }, + }, + fetchImpl + ); + expect((json as { error: { code: number } }).error.code).toBe(-32602); + expect((json as { error: { message: string } }).error.message).toContain('query'); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + + it('retryable: an upstream tRPC error becomes a JSON-RPC error carrying code and httpStatus, and a corrected retry succeeds', async () => { + const failing = vi.fn( + async () => + new Response( + JSON.stringify({ + error: { + message: 'You are not signed in', + code: -32001, + data: { code: 'UNAUTHORIZED', httpStatus: 401 }, + }, + }), + { status: 401, headers: { 'Content-Type': 'application/json' } } + ) + ); + const { json } = await rpcResult( + { + jsonrpc: '2.0', + id: 13, + method: 'tools/call', + params: { name: 'call', arguments: { path: 'organizations.list' } }, + }, + failing + ); + const error = ( + json as { error: { code: number; message: string; data: Record } } + ).error; + expect(error.code).toBe(-32000); + expect(error.message).toBe('You are not signed in'); + expect(error.data).toMatchObject({ trpcCode: 'UNAUTHORIZED', httpStatus: 401 }); + + const retry = vi.fn( + async () => + new Response(JSON.stringify({ result: { data: [{ id: 'org-1' }] } }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) + ); + const ok = await rpcResult( + { + jsonrpc: '2.0', + id: 14, + method: 'tools/call', + params: { name: 'call', arguments: { path: 'organizations.list' } }, + }, + retry + ); + expect('result' in (ok.json as Record)).toBe(true); + }); + + it('truncates results over 16 KiB with a marker and truncated metadata', async () => { + const big = 'y'.repeat(20_000); + const fetchImpl = vi.fn( + async () => + new Response(JSON.stringify({ result: { data: { blob: big } } }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) + ); + const { json } = await rpcResult( + { + jsonrpc: '2.0', + id: 15, + method: 'tools/call', + params: { name: 'call', arguments: { path: 'organizations.list' } }, + }, + fetchImpl + ); + const result = (json as { result: { content: Array<{ text: string }>; truncated?: boolean } }) + .result; + expect(result.truncated).toBe(true); + expect(result.content[0]!.text.endsWith('[truncated]')).toBe(true); + expect(new TextEncoder().encode(result.content[0]!.text).byteLength).toBeLessThanOrEqual( + 16 * 1024 + ); + }); +}); + +/** + * s5 auth-endpoint routing: the default fetch handler wires every OAuth route + * (discovery metadata, DCR, authorize + pairing status, token) and verifies + * MCP tokens on /mcp when the worker carries the OAuth bindings. + */ +describe('auth endpoint routing (s5)', () => { + const ISSUER = 'https://kilo-mcp.test'; + const SECRET = 'routing-test-secret'; + /** RFC 7636 appendix B test vector — a valid 43-char S256 challenge. */ + const CHALLENGE = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM'; + + function createRoutingStore(): OAuthStoreApi & { + clients: Map; + codes: Map; + refreshTokens: Map; + } { + const clients = new Map(); + const codes = new Map(); + const refreshTokens = new Map(); + const unused = (): never => { + throw new Error('not reachable from routing tests'); + }; + return { + clients, + codes, + refreshTokens, + async registerClient(input) { + clients.set(input.clientId, { ...input, redirectUris: [...input.redirectUris] }); + }, + async getClient(clientId) { + const client = clients.get(clientId); + return client ? { ...client, redirectUris: [...client.redirectUris] } : null; + }, + async createCode(input) { + codes.set(input.code, { + ...input, + status: 'pending', + kiloUserId: null, + organizationId: null, + kiloToken: null, + }); + }, + async getCode(code) { + const record = codes.get(code); + return record ? { ...record } : null; + }, + async recordPairingApproval(deviceAuthCode, identity, nowIso) { + for (const [code, record] of codes) { + if ( + record.deviceAuthCode === deviceAuthCode && + record.status === 'pending' && + record.kiloUserId === null && + record.expiresAt > nowIso + ) { + codes.set(code, { + ...record, + kiloUserId: identity.kiloUserId, + kiloToken: identity.kiloToken, + }); + return true; + } + } + return false; + }, + async denyCode(deviceAuthCode, nowIso) { + for (const [code, record] of codes) { + if ( + record.deviceAuthCode === deviceAuthCode && + record.status === 'pending' && + record.expiresAt > nowIso + ) { + codes.set(code, { ...record, status: 'denied' }); + return true; + } + } + return false; + }, + async approveCode(deviceAuthCode, identity, nowIso) { + for (const [code, record] of codes) { + if ( + record.deviceAuthCode === deviceAuthCode && + record.status === 'pending' && + record.expiresAt > nowIso + ) { + codes.set(code, { + ...record, + status: 'approved', + kiloUserId: identity.kiloUserId, + organizationId: identity.organizationId, + }); + return true; + } + } + return false; + }, + async consumeCode(code, nowIso) { + const record = codes.get(code); + if (!record || record.status !== 'approved' || record.expiresAt <= nowIso) return null; + const used: OAuthCodeRecord = { ...record, status: 'used' }; + codes.set(code, used); + return { ...used }; + }, + async saveRefreshToken(input) { + refreshTokens.set(input.id, { ...input, revokedAt: null }); + }, + async getRefreshTokenByHash(tokenHash) { + const record = [...refreshTokens.values()].find(r => r.tokenHash === tokenHash); + return record ? { ...record } : null; + }, + async rotateRefreshToken(oldId, input, nowIso) { + const old = refreshTokens.get(oldId); + if (!old || old.revokedAt !== null || old.expiresAt <= nowIso) return false; + refreshTokens.set(oldId, { ...old, revokedAt: nowIso }); + refreshTokens.set(input.id, { ...input, revokedAt: null }); + return true; + }, + async getKiloToken(kiloUserId, clientId) { + for (const grant of [...refreshTokens.values()].reverse()) { + if ( + grant.kiloUserId === kiloUserId && + grant.clientId === clientId && + grant.revokedAt === null && + grant.kiloToken + ) { + return grant.kiloToken; + } + } + // The s5 verification tests mint tokens for user-1/c-1 without going + // through the exchange; that pair keeps a standing credential. + return kiloUserId === 'user-1' && clientId === 'c-1' ? 'kilo-forward-me' : null; + }, + revokeGrant: unused, + revokeJti: unused, + async isJtiRevoked() { + return false; + }, + purgeExpired: unused, + }; + } + + function oauthEnv(store: OAuthStoreApi, bindings: 'required' | 'absent' = 'required'): Env { + return { + WEB_BASE_URL: 'https://app.kilo.ai', + ...(bindings === 'required' + ? { + MCP_TOKEN_SECRET: SECRET, + KILO_MCP_OAUTH_STORE: { + getByName: (name: string) => { + expect(name).toBe('kilo-mcp-oauth'); + return store; + }, + }, + } + : {}), + } as unknown as Env; + } + + async function fetchJson(path: string, init?: RequestInit) { + const response = await worker.fetch( + new Request(`${ISSUER}${path}`, init), + oauthEnv(createRoutingStore()) + ); + return { response, json: (await response.json()) as Record }; + } + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it('serves authorization-server metadata at both well-known URLs', async () => { + for (const path of [ + '/.well-known/oauth-authorization-server', + '/.well-known/oauth-authorization-server/mcp', + ]) { + const { response, json } = await fetchJson(path); + expect(response.status).toBe(200); + expect(json.issuer).toBe(ISSUER); + expect(json.authorization_endpoint).toBe(`${ISSUER}/authorize`); + expect(json.token_endpoint).toBe(`${ISSUER}/token`); + expect(json.registration_endpoint).toBe(`${ISSUER}/register`); + expect(json.response_types_supported).toEqual(['code']); + expect(json.code_challenge_methods_supported).toEqual(['S256']); + expect(json.grant_types_supported).toEqual(['authorization_code', 'refresh_token']); + expect(json.scopes_supported).toEqual(['mcp']); + expect(json.token_endpoint_auth_methods_supported).toEqual(['none']); + } + }); + + it('serves protected-resource metadata advertising this MCP and its authorization server', async () => { + for (const path of [ + '/.well-known/oauth-protected-resource', + '/.well-known/oauth-protected-resource/mcp', + ]) { + const { response, json } = await fetchJson(path); + expect(response.status).toBe(200); + expect(json.resource).toBe(`${ISSUER}/mcp`); + expect(json.resource_name).toBe('Kilo MCP'); + expect(json.authorization_servers).toEqual([ISSUER]); + expect(json.scopes_supported).toEqual(['mcp']); + } + }); + + it('POST /register persists a public client and answers 201 without a secret', async () => { + const store = createRoutingStore(); + const response = await worker.fetch( + new Request(`${ISSUER}/register`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ redirect_uris: ['https://client.test/cb'], client_name: 'Router' }), + }), + oauthEnv(store) + ); + expect(response.status).toBe(201); + const json = (await response.json()) as Record; + expect(typeof json.client_id).toBe('string'); + expect(json.client_secret).toBeUndefined(); + expect(json.token_endpoint_auth_method).toBe('none'); + expect(store.clients.get(json.client_id as string)?.clientName).toBe('Router'); + }); + + it('GET /authorize creates the pending pairing record and links to Kilo sign-in', async () => { + const store = createRoutingStore(); + await store.registerClient({ + clientId: 'c-1', + redirectUris: ['https://client.test/cb'], + clientName: 'Router', + createdAt: new Date().toISOString(), + }); + const deviceAuthFetch = vi.fn(async () => Response.json({ code: 'PAIR-777' })); + vi.stubGlobal('fetch', deviceAuthFetch); + + const url = new URL(`${ISSUER}/authorize`); + url.searchParams.set('response_type', 'code'); + url.searchParams.set('client_id', 'c-1'); + url.searchParams.set('redirect_uri', 'https://client.test/cb'); + url.searchParams.set('code_challenge', CHALLENGE); + url.searchParams.set('code_challenge_method', 'S256'); + url.searchParams.set('resource', `${ISSUER}/mcp`); + url.searchParams.set('state', 'st-1'); + const response = await worker.fetch(new Request(url.toString()), oauthEnv(store)); + + expect(response.status).toBe(200); + expect(response.headers.get('content-type')).toContain('text/html'); + const html = await response.text(); + expect(html).toContain('https://app.kilo.ai/device-auth?code=PAIR-777'); + expect(deviceAuthFetch).toHaveBeenCalledTimes(1); + const [calledUrl] = deviceAuthFetch.mock.calls[0] as unknown as [string]; + expect(String(calledUrl)).toBe('https://app.kilo.ai/api/device-auth/codes'); + + expect(store.codes.size).toBe(1); + const record = [...store.codes.values()][0]!; + expect(record.clientId).toBe('c-1'); + expect(record.status).toBe('pending'); + expect(record.codeChallenge).toBe(CHALLENGE); + expect(record.resource).toBe(`${ISSUER}/mcp`); + expect(record.deviceAuthCode).toBe('PAIR-777'); + + // The consent page polls this same worker for pairing status. + const status = await fetchJsonOn(store, `/authorize/status?code=${record.code}`); + expect(status.json).toEqual({ status: 'pending' }); + }); + + async function fetchJsonOn(store: OAuthStoreApi, path: string) { + const response = await worker.fetch(new Request(`${ISSUER}${path}`), oauthEnv(store)); + return { response, json: (await response.json()) as Record }; + } + + it('GET /authorize/status cannot be used to probe pairing codes', async () => { + const store = createRoutingStore(); + const unknown = await fetchJsonOn(store, '/authorize/status?code=does-not-exist'); + expect(unknown.response.status).toBe(200); + expect(unknown.json).toEqual({ status: 'unknown' }); + }); + + it('browser flow end to end: consent -> pairing -> org picker -> token -> call AS the chosen identity', async () => { + const store = createRoutingStore(); + await store.registerClient({ + clientId: 'c-1', + redirectUris: ['https://client.test/cb'], + clientName: 'Router', + createdAt: new Date().toISOString(), + }); + let pairingApproved = false; + const calls: Array<{ url: string; headers: Record }> = []; + const fetchImpl = vi.fn(async (input: string | URL, init?: RequestInit) => { + const url = String(input); + const headers = (init?.headers ?? {}) as Record; + calls.push({ url, headers }); + if (url === 'https://app.kilo.ai/api/device-auth/codes') + return Response.json({ code: 'PAIR-E2E' }); + if (url === 'https://app.kilo.ai/api/device-auth/codes/PAIR-E2E') { + return pairingApproved + ? Response.json({ status: 'approved', token: 'kilo-e2e-token', userId: 'user-e2e' }) + : Response.json({ status: 'pending' }, { status: 202 }); + } + if (url.startsWith('https://app.kilo.ai/api/trpc/organizations.list')) { + return Response.json({ + result: { data: [{ organizationId: 'org-e2e', organizationName: 'E2E Org' }] }, + }); + } + // The call step: echo what apps/web actually received as identity. + if (url.startsWith('https://app.kilo.ai/api/trpc/user.getBalance')) { + return Response.json({ + result: { + data: { + balance: 42, + seenAuthorization: headers['Authorization'], + seenOrganization: headers[ORGANIZATION_ID_HEADER], + }, + }, + }); + } + return Response.json({ error: { message: `stub: unexpected ${url}` } }, { status: 500 }); + }); + vi.stubGlobal('fetch', fetchImpl); + const env = oauthEnv(store); + + // 1. GET /authorize -> consent page + pending pairing record. + const authorizeUrl = new URL(`${ISSUER}/authorize`); + authorizeUrl.searchParams.set('response_type', 'code'); + authorizeUrl.searchParams.set('client_id', 'c-1'); + authorizeUrl.searchParams.set('redirect_uri', 'https://client.test/cb'); + authorizeUrl.searchParams.set('code_challenge', CHALLENGE); + authorizeUrl.searchParams.set('code_challenge_method', 'S256'); + authorizeUrl.searchParams.set('resource', `${ISSUER}/mcp`); + authorizeUrl.searchParams.set('state', 'st-1'); + const consent = await worker.fetch(new Request(authorizeUrl.toString()), env); + expect(consent.status).toBe(200); + const record = [...store.codes.values()][0]!; + + // 2. Polling before the user approves: still pending. + const pollUrl = `${ISSUER}/authorize/status?code=${record.code}`; + expect(await (await worker.fetch(new Request(pollUrl), env)).json()).toEqual({ + status: 'pending', + }); + + // 3. User approves the Kilo sign-in -> the worker holds the pairing and + // sends the page to the org picker. + pairingApproved = true; + expect(await (await worker.fetch(new Request(pollUrl), env)).json()).toEqual({ + status: 'needs_org', + picker_url: `/authorize/org?code=${record.code}`, + }); + // The single-use approved answer is never polled again. + const pollCalls = calls.filter(c => c.url.includes('/api/device-auth/codes/')).length; + expect(pollCalls).toBe(2); + + // 4. GET the picker: personal + the user's organization. + const picker = await worker.fetch( + new Request(`${ISSUER}/authorize/org?code=${record.code}`), + env + ); + const pickerHtml = await picker.text(); + expect(pickerHtml).toContain('E2E Org'); + expect(pickerHtml).toContain('Personal account'); + + // 5. POST the selection -> authorize completes with a client redirect. + const done = await worker.fetch( + new Request(`${ISSUER}/authorize/org?code=${record.code}`, { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ organization_id: 'org-e2e' }).toString(), + }), + env + ); + expect(done.status).toBe(302); + const location = new URL(done.headers.get('Location')!); + expect(location.origin + location.pathname).toBe('https://client.test/cb'); + expect(location.searchParams.get('code')).toBe(record.code); + expect(location.searchParams.get('state')).toBe('st-1'); + + // 6. Token exchange (PKCE verifier = the RFC 7636 Appendix B vector). + const tokenResponse = await worker.fetch( + new Request(`${ISSUER}/token`, { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'authorization_code', + code: record.code, + client_id: 'c-1', + redirect_uri: 'https://client.test/cb', + code_verifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk', + resource: `${ISSUER}/mcp`, + }).toString(), + }), + env + ); + expect(tokenResponse.status).toBe(200); + const tokens = (await tokenResponse.json()) as { access_token: string }; + const claims = decodeJwt(tokens.access_token)!.payload; + expect(claims).toMatchObject({ sub: 'user-e2e', org: 'org-e2e', aud: `${ISSUER}/mcp` }); + + // 7. tools/call with the MCP token: apps/web sees the Kilo bearer and the + // org from the token claims — the picked identity, end to end. + calls.length = 0; + const call = await worker.fetch( + new Request(`${ISSUER}/mcp`, { + method: 'POST', + headers: { + Authorization: `Bearer ${tokens.access_token}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { name: 'call', arguments: { path: 'user.getBalance' } }, + }), + }), + env + ); + const callJson = (await call.json()) as { result: { content: Array<{ text: string }> } }; + expect(JSON.parse(callJson.result.content[0]!.text)).toMatchObject({ + balance: 42, + seenAuthorization: 'Bearer kilo-e2e-token', + seenOrganization: 'org-e2e', + }); + // A spoofed caller org header changes nothing: the claim wins. + const spoofed = await worker.fetch( + new Request(`${ISSUER}/mcp`, { + method: 'POST', + headers: { + Authorization: `Bearer ${tokens.access_token}`, + 'content-type': 'application/json', + [ORGANIZATION_ID_HEADER]: 'attacker-org', + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 3, + method: 'tools/call', + params: { name: 'call', arguments: { path: 'user.getBalance' } }, + }), + }), + env + ); + const spoofedJson = (await spoofed.json()) as { result: { content: Array<{ text: string }> } }; + expect(JSON.parse(spoofedJson.result.content[0]!.text)).toMatchObject({ + seenOrganization: 'org-e2e', + }); + + // 8. search runs under the same enforced token. + const search = await worker.fetch( + new Request(`${ISSUER}/mcp`, { + method: 'POST', + headers: { + Authorization: `Bearer ${tokens.access_token}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 4, + method: 'tools/call', + params: { name: 'search', arguments: { query: 'credit balance' } }, + }), + }), + env + ); + expect(search.status).toBe(200); + const searchJson = (await search.json()) as { result: { content: Array<{ text: string }> } }; + expect(searchJson.result.content[0]!.text).toContain('user.getBalance'); + }); + + it('POST /token answers RFC 6749 errors through the route', async () => { + const unsupported = await fetchJson('/token', { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ grant_type: 'password' }).toString(), + }); + expect(unsupported.response.status).toBe(400); + expect(unsupported.json.error).toBe('unsupported_grant_type'); + + const garbage = await fetchJson('/token', { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: 'not-an-oauth-body', + }); + expect(garbage.json.error).toBe('invalid_request'); + }); + + it('/mcp verifies this worker MCP tokens when the OAuth bindings are present', async () => { + const store = createRoutingStore(); + const env = oauthEnv(store); + const claims = { + iss: ISSUER, + sub: 'user-1', + org: 'org-1', + aud: `${ISSUER}/mcp`, + client_id: 'c-1', + jti: 'j-1', + }; + const live = await signJwt({ ...claims, exp: Math.floor(Date.now() / 1000) + 60 }, SECRET); + const expired = await signJwt({ ...claims, exp: Math.floor(Date.now() / 1000) - 60 }, SECRET); + const rpc = { jsonrpc: '2.0', id: 1, method: 'tools/list' }; + + const ok = await worker.fetch( + new Request(`${ISSUER}/mcp`, { + method: 'POST', + headers: { Authorization: `Bearer ${live}`, 'content-type': 'application/json' }, + body: JSON.stringify(rpc), + }), + env + ); + expect(ok.status).toBe(200); + + const rejected = await worker.fetch( + new Request(`${ISSUER}/mcp`, { + method: 'POST', + headers: { Authorization: `Bearer ${expired}`, 'content-type': 'application/json' }, + body: JSON.stringify(rpc), + }), + env + ); + expect(rejected.status).toBe(401); + + // s6 enforcement: a foreign bearer is rejected outright — /mcp accepts + // ONLY MCP tokens signed by this worker. + const foreign = await worker.fetch( + new Request(`${ISSUER}/mcp`, { + method: 'POST', + headers: { Authorization: 'Bearer tok_123', 'content-type': 'application/json' }, + body: JSON.stringify(rpc), + }), + env + ); + expect(foreign.status).toBe(401); + expect(foreign.headers.get('WWW-Authenticate')).toBe( + `Bearer error="invalid_token", resource_metadata="${ISSUER}/.well-known/oauth-protected-resource"` + ); + }); + + it('a live MCP token whose grant lost its Kilo credential is rejected (reconnect)', async () => { + const store = createRoutingStore(); + const env = oauthEnv(store); + // user-2 has no getKiloToken mapping in the routing fake. + const token = await signJwt( + { + iss: ISSUER, + sub: 'user-2', + org: 'org-1', + aud: `${ISSUER}/mcp`, + client_id: 'c-1', + jti: 'j-2', + exp: Math.floor(Date.now() / 1000) + 60, + }, + SECRET + ); + const response = await worker.fetch( + new Request(`${ISSUER}/mcp`, { + method: 'POST', + headers: { Authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }), + }), + env + ); + expect(response.status).toBe(401); + }); + + it('/mcp refuses every bearer on a worker without the OAuth bindings (s6: no unverified passthrough)', async () => { + const response = await worker.fetch( + new Request(`${ISSUER}/mcp`, { + method: 'POST', + headers: { Authorization: 'Bearer tok_123', 'content-type': 'application/json' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }), + }), + oauthEnv(createRoutingStore(), 'absent') + ); + expect(response.status).toBe(503); + }); +}); diff --git a/services/kilo-mcp/src/index.ts b/services/kilo-mcp/src/index.ts new file mode 100644 index 0000000000..e3f99127ea --- /dev/null +++ b/services/kilo-mcp/src/index.ts @@ -0,0 +1,443 @@ +import catalogJson from '../catalog.json'; +import { authenticate } from './auth'; +import { handleAuthorize } from './auth/authorize'; +import { handleRegistration } from './auth/dcr'; +import { AUTH_PATHS } from './auth/http'; +import { + handleAuthorizationServerMetadata, + handleProtectedResourceMetadata, + protectedResourceMetadataUrl, +} from './auth/metadata'; +import { handleToken } from './auth/token'; +import { callCatalogEndpoint } from './call'; +import { getKiloMcpOAuthStoreStub, type OAuthStoreApi } from './store/oauth-store'; +import { handlePairingStatus } from './oauth-pages/authorize-page'; +import { handleOrgPicker } from './oauth-pages/org-picker'; +import { DEFAULT_SEARCH_LIMIT, noSemanticCandidates, searchCatalog } from './search'; +import { createSemanticCandidates } from './search-knn'; +import { JsonRpcFailure, type Catalog, type ForwardedAuth, type SemanticCandidates } from './types'; + +/** The Durable Object class must stay exported from the entry module for wrangler. */ +export { KiloMcpOAuthStore } from './store/oauth-store'; + +/** The bundled catalog dumped by apps/web/src/scripts/mcp-catalog (s1). */ +const catalog = catalogJson as unknown as Catalog; + +/** The token endpoint cannot mint unsigned tokens: fail loudly if unconfigured. */ +function requireMcpTokenSecret(env: Env): string { + if (!env.MCP_TOKEN_SECRET) { + throw new Error('MCP_TOKEN_SECRET is not configured (wrangler secret put MCP_TOKEN_SECRET).'); + } + return env.MCP_TOKEN_SECRET; +} + +/** JSON-RPC 2.0 error codes (https://www.jsonrpc.org/specification). */ +const PARSE_ERROR = -32700; +const INVALID_REQUEST = -32600; +const METHOD_NOT_FOUND = -32601; +const INVALID_PARAMS = -32602; +/** Bearer token required before this slice's OAuth flow (s5/s6) lands. */ +const UNAUTHORIZED = -32001; + +const PROTOCOL_VERSION = '2025-06-18'; +const SERVER_INFO = { name: 'kilo-mcp', version: '1.0.0' } as const; + +const CORS_HEADERS: Record = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'POST, OPTIONS', + 'Access-Control-Allow-Headers': 'Authorization, Content-Type, Accept, Mcp-Session-Id', + 'Access-Control-Expose-Headers': 'Mcp-Session-Id', +}; + +function withCorsHeaders(response: Response): Response { + for (const [key, value] of Object.entries(CORS_HEADERS)) { + response.headers.set(key, value); + } + return response; +} + +function jsonResponse(body: unknown, status = 200): Response { + return withCorsHeaders( + new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }) + ); +} + +function jsonRpcResult(id: string | number, result: unknown): Response { + return jsonResponse({ jsonrpc: '2.0', id, result }); +} + +function jsonRpcError( + id: string | number | null, + code: number, + message: string, + data?: Record +): Response { + return jsonResponse({ jsonrpc: '2.0', id, error: { code, message, ...(data ? { data } : {}) } }); +} + +const TOOLS = [ + { + name: 'search', + description: + 'Search the Kilo API catalog for endpoints that match a task. ALWAYS run search first: the call tool only accepts paths this catalog publishes, and search returns the path, summary, and input schema you need for the call.', + inputSchema: { + type: 'object', + properties: { + query: { + type: 'string', + description: 'What you want to do, in the words an agent would type.', + }, + limit: { + type: 'integer', + minimum: 1, + maximum: 50, + description: `Maximum number of results (default ${DEFAULT_SEARCH_LIMIT}).`, + }, + }, + required: ['query'], + additionalProperties: false, + }, + }, + { + name: 'call', + description: + 'Call a Kilo API endpoint by its catalog path. Run search first to find a valid path and its input schema — paths outside the catalog and inputs that violate the published schema are rejected before any request is made.', + inputSchema: { + type: 'object', + properties: { + path: { + type: 'string', + description: 'A catalog endpoint path returned by search, e.g. "organizations.list".', + }, + input: { + type: 'object', + description: + 'Arguments matching the endpoint input schema from search. Omit for endpoints that take no input.', + additionalProperties: true, + }, + }, + required: ['path'], + additionalProperties: false, + }, + }, +] as const; + +type RpcMessage = { + jsonrpc?: unknown; + id?: string | number | null; + method?: unknown; + params?: unknown; +}; + +type McpHandlerDeps = { + catalog: Catalog; + webBaseUrl: string; + fetchImpl?: typeof fetch; + /** Vectorize kNN hook; token-only search when omitted. */ + semanticCandidates?: SemanticCandidates; + /** + * MCP OAuth verification (s5) + enforcement (s6). When present, /mcp + * accepts ONLY a bearer signed by this worker (signature/exp/iss/aud/jti + * checked) and forwards the Kilo credential bound to the verified identity; + * foreign bearers are rejected. Omitted in tests without the OAuth flow. + */ + mcpAuth?: { tokenSecret: string; store: OAuthStoreApi }; +}; + +/** An MCP tools/call success payload. */ +type ToolResult = { + content: Array<{ type: 'text'; text: string }>; + truncated?: true; +}; + +function textResult(text: string): ToolResult { + return { content: [{ type: 'text', text }] }; +} + +async function runTool( + name: string, + args: Record, + auth: ForwardedAuth, + deps: McpHandlerDeps +): Promise { + if (name === 'search') { + const query = args['query']; + if (typeof query !== 'string' || query.trim().length === 0) { + throw new JsonRpcFailure(INVALID_PARAMS, 'search requires a non-empty string "query".'); + } + const limit = args['limit']; + if (limit !== undefined && (typeof limit !== 'number' || !Number.isInteger(limit))) { + throw new JsonRpcFailure(INVALID_PARAMS, 'search "limit" must be an integer.'); + } + const results = await searchCatalog(query, { + catalog: deps.catalog, + limit, + semanticCandidates: deps.semanticCandidates ?? noSemanticCandidates, + }); + if (results.length === 0) { + // Empty state, not an error: tell the agent how to recover. + return textResult( + JSON.stringify({ + results: [], + message: `No endpoints matched "${query.trim()}". Refine your query: use fewer or different keywords, or describe the task in plain language.`, + }) + ); + } + return textResult(JSON.stringify({ results })); + } + if (name === 'call') { + const path = args['path']; + if (typeof path !== 'string' || path.length === 0) { + throw new JsonRpcFailure( + INVALID_PARAMS, + 'call requires a string "path" — run search first to find one.' + ); + } + const input = args['input']; + if (input !== undefined && (typeof input !== 'object' || input === null)) { + throw new JsonRpcFailure(INVALID_PARAMS, 'call "input" must be an object when present.'); + } + const outcome = await callCatalogEndpoint({ + catalog: deps.catalog, + path, + input, + auth, + webBaseUrl: deps.webBaseUrl, + ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}), + }); + return { + content: [{ type: 'text', text: outcome.text }], + ...(outcome.truncated ? { truncated: true as const } : {}), + }; + } + throw new JsonRpcFailure( + INVALID_PARAMS, + `Unknown tool "${name}". Available tools: search, call.` + ); +} + +async function handleRpcMessage( + message: RpcMessage, + auth: ForwardedAuth, + deps: McpHandlerDeps +): Promise { + const id = typeof message.id === 'string' || typeof message.id === 'number' ? message.id : null; + const method = typeof message.method === 'string' ? message.method : ''; + + // Notifications carry no id and get no JSON-RPC response body. + if (id === null && method.startsWith('notifications/')) { + return withCorsHeaders(new Response(null, { status: 202 })); + } + + try { + switch (method) { + case 'initialize': { + const params = (message.params ?? {}) as { protocolVersion?: unknown }; + return jsonRpcResult(id ?? 0, { + protocolVersion: + typeof params.protocolVersion === 'string' ? params.protocolVersion : PROTOCOL_VERSION, + capabilities: { tools: {} }, + serverInfo: SERVER_INFO, + instructions: + 'This server exposes the Kilo API through two tools: search (find catalog endpoints) and call (invoke one by path). Search before every call.', + }); + } + case 'ping': + return jsonRpcResult(id ?? 0, {}); + case 'tools/list': + return jsonRpcResult(id ?? 0, { tools: TOOLS }); + case 'tools/call': { + const params = (message.params ?? {}) as { name?: unknown; arguments?: unknown }; + if (typeof params.name !== 'string') { + throw new JsonRpcFailure(INVALID_PARAMS, 'tools/call requires a string "name".'); + } + const args = (params.arguments ?? {}) as Record; + const result = await runTool(params.name, args, auth, deps); + return jsonRpcResult(id ?? 0, result); + } + default: + return jsonRpcError(id, METHOD_NOT_FOUND, `Unknown method "${method}".`); + } + } catch (error) { + if (error instanceof JsonRpcFailure) { + return jsonRpcError(id ?? 0, error.code, error.message, error.data); + } + throw error; + } +} + +/** + * The MCP Streamable HTTP endpoint: stateless JSON POST responses for + * initialize, notifications/initialized, tools/list, tools/call, and ping. + * Exported for tests with an injectable catalog and web base URL; the default + * fetch handler wires in the bundled catalog and env. + */ +export function createMcpHandler(deps: McpHandlerDeps) { + return async function handleMcp(request: Request): Promise { + if (request.method === 'OPTIONS') { + return new Response(null, { status: 204, headers: CORS_HEADERS }); + } + if (request.method !== 'POST') { + return withCorsHeaders(new Response('Method not allowed', { status: 405 })); + } + + // The issuer is always the URL this worker is reached at (dev vs prod + // advertise themselves); the access token's `aud` is the `/mcp` resource. + const issuer = new URL(request.url).origin; + + // s6 enforcement: with the OAuth deps present, /mcp accepts ONLY MCP + // tokens signed by this worker; the forwarded bearer + org come from the + // verified claims. Without them (unconfigured worker) the s2 passthrough + // stays — see the fetch router for the binding check. + const mcpAuth = deps.mcpAuth; + const auth = await authenticate( + request, + mcpAuth + ? { + mcpToken: { + tokenSecret: mcpAuth.tokenSecret, + issuer, + resource: `${issuer}/mcp`, + isJtiRevoked: jti => mcpAuth.store.isJtiRevoked(jti), + }, + resolveKiloToken: identity => + mcpAuth.store.getKiloToken( + identity.kiloUserId, + identity.clientId, + new Date().toISOString() + ), + } + : undefined + ); + if (!auth) { + // HTTP 401 alongside a JSON-RPC error body; rejected before any + // catalog lookup or upstream request. The challenge names this + // server's protected-resource metadata (RFC 9728) so the MCP client + // discovers the authorization server and runs the browser flow. + return withCorsHeaders( + new Response( + JSON.stringify({ + jsonrpc: '2.0', + id: null, + error: { + code: UNAUTHORIZED, + message: + 'A valid Kilo MCP access token is required in the Authorization header. Reconnect the Kilo MCP server and sign in.', + }, + }), + { + status: 401, + headers: { + 'Content-Type': 'application/json', + 'WWW-Authenticate': `Bearer error="invalid_token", resource_metadata="${protectedResourceMetadataUrl(issuer)}"`, + }, + } + ) + ); + } + + let message: unknown; + try { + message = await request.json(); + } catch { + return jsonRpcError(null, PARSE_ERROR, 'Request body is not valid JSON.'); + } + if (Array.isArray(message)) { + return jsonRpcError( + null, + INVALID_REQUEST, + 'Batch requests are not supported; send one JSON-RPC message per request.' + ); + } + const rpc = message as RpcMessage; + if (typeof rpc !== 'object' || rpc === null || typeof rpc.method !== 'string') { + return jsonRpcError( + typeof rpc?.id === 'number' || typeof rpc?.id === 'string' ? rpc.id : null, + INVALID_REQUEST, + 'Expected a JSON-RPC 2.0 request with a string "method".' + ); + } + return handleRpcMessage(rpc, auth, deps); + }; +} + +export default { + async fetch(request: Request, env: Env): Promise { + const url = new URL(request.url); + const issuer = url.origin; + + switch (url.pathname) { + case AUTH_PATHS.mcp: { + // s6 enforcement: with the OAuth bindings present, /mcp accepts only + // MCP tokens signed by this worker. Without them the worker cannot + // verify anything, so it must not forward unverified bearers either — + // POSTs are refused outright (transport replies stay available). + if (!env.MCP_TOKEN_SECRET || !env.KILO_MCP_OAUTH_STORE) { + if (request.method !== 'OPTIONS' && request.method !== 'GET') { + return withCorsHeaders( + new Response( + JSON.stringify({ + jsonrpc: '2.0', + id: null, + error: { + code: -32000, + message: + 'This Kilo MCP deployment is missing its token-verification bindings (MCP_TOKEN_SECRET / OAuth store). Contact the operator.', + }, + }), + { status: 503, headers: { 'Content-Type': 'application/json' } } + ) + ); + } + const transportOnly = createMcpHandler({ + catalog, + webBaseUrl: env.WEB_BASE_URL, + semanticCandidates: createSemanticCandidates(env), + }); + return transportOnly(request); + } + const handler = createMcpHandler({ + catalog, + webBaseUrl: env.WEB_BASE_URL, + semanticCandidates: createSemanticCandidates(env), + mcpAuth: { tokenSecret: env.MCP_TOKEN_SECRET, store: getKiloMcpOAuthStoreStub(env) }, + }); + return handler(request); + } + case AUTH_PATHS.authorizationServerMetadata: + case AUTH_PATHS.authorizationServerMetadataScoped: + return handleAuthorizationServerMetadata(request, { issuer }); + case AUTH_PATHS.protectedResourceMetadata: + case AUTH_PATHS.protectedResourceMetadataScoped: + return handleProtectedResourceMetadata(request, { issuer }); + case AUTH_PATHS.register: + return handleRegistration(request, { store: getKiloMcpOAuthStoreStub(env) }); + case AUTH_PATHS.authorize: + return handleAuthorize(request, { + store: getKiloMcpOAuthStoreStub(env), + webBaseUrl: env.WEB_BASE_URL, + }); + case AUTH_PATHS.pairingStatus: + return handlePairingStatus(request, { + store: getKiloMcpOAuthStoreStub(env), + webBaseUrl: env.WEB_BASE_URL, + }); + case AUTH_PATHS.orgPicker: + return handleOrgPicker(request, { + store: getKiloMcpOAuthStoreStub(env), + webBaseUrl: env.WEB_BASE_URL, + }); + case AUTH_PATHS.token: + return handleToken(request, { + store: getKiloMcpOAuthStoreStub(env), + tokenSecret: requireMcpTokenSecret(env), + issuer, + }); + default: + return withCorsHeaders(new Response('Not found', { status: 404 })); + } + }, +} satisfies ExportedHandler; diff --git a/services/kilo-mcp/src/oauth-pages/authorize-page.test.ts b/services/kilo-mcp/src/oauth-pages/authorize-page.test.ts new file mode 100644 index 0000000000..45a0b92fbf --- /dev/null +++ b/services/kilo-mcp/src/oauth-pages/authorize-page.test.ts @@ -0,0 +1,366 @@ +import { describe, expect, it, vi } from 'vitest'; +import { consentPage, handlePairingStatus, pollKiloPairing } from './authorize-page'; +import type { + NewOAuthCode, + OAuthCodeRecord, + OAuthStoreApi, + StoredClient, +} from '../store/oauth-store'; + +/** + * In-memory OAuthStoreApi for the consent-page pairing endpoint. Methods these + * tests never reach throw, so a new handler dependency fails loudly. + */ +function createFakeOAuthStore(): OAuthStoreApi & { + clients: Map; + codes: Map; +} { + const clients = new Map(); + const codes = new Map(); + const unused = (): never => { + throw new Error('not reachable from these tests'); + }; + return { + clients, + codes, + registerClient: unused, + async getClient(clientId) { + const client = clients.get(clientId); + return client ? { ...client, redirectUris: [...client.redirectUris] } : null; + }, + async createCode(input: NewOAuthCode) { + codes.set(input.code, { + ...input, + status: 'pending', + kiloUserId: null, + organizationId: null, + kiloToken: null, + }); + }, + async getCode(code) { + const record = codes.get(code); + return record ? { ...record } : null; + }, + async recordPairingApproval(deviceAuthCode, identity, nowIso) { + for (const [code, record] of codes) { + if ( + record.deviceAuthCode === deviceAuthCode && + record.status === 'pending' && + record.kiloUserId === null && + record.expiresAt > nowIso + ) { + codes.set(code, { + ...record, + kiloUserId: identity.kiloUserId, + kiloToken: identity.kiloToken, + }); + return true; + } + } + return false; + }, + async denyCode(deviceAuthCode, nowIso) { + for (const [code, record] of codes) { + if ( + record.deviceAuthCode === deviceAuthCode && + record.status === 'pending' && + record.expiresAt > nowIso + ) { + codes.set(code, { ...record, status: 'denied' }); + return true; + } + } + return false; + }, + async approveCode(deviceAuthCode, identity, nowIso) { + for (const [code, record] of codes) { + if ( + record.deviceAuthCode === deviceAuthCode && + record.status === 'pending' && + record.expiresAt > nowIso + ) { + codes.set(code, { + ...record, + status: 'approved', + kiloUserId: identity.kiloUserId, + organizationId: identity.organizationId, + }); + return true; + } + } + return false; + }, + consumeCode: unused, + saveRefreshToken: unused, + getRefreshTokenByHash: unused, + rotateRefreshToken: unused, + getKiloToken: unused, + revokeGrant: unused, + revokeJti: unused, + async isJtiRevoked() { + return false; + }, + purgeExpired: unused, + }; +} + +const ISSUER = 'https://kilo-mcp.test'; +const WEB = 'https://app.kilo.test'; +const REDIRECT = 'https://client.test/cb'; + +function seedPendingCode(store: ReturnType): OAuthCodeRecord { + const input: NewOAuthCode = { + code: 'auth-code-value-00000000000000000000000000000000000', + clientId: 'client-abc', + redirectUri: REDIRECT, + codeChallenge: 'challenge-value-000000000000000000000000000000', + resource: `${ISSUER}/mcp`, + scope: 'mcp', + state: 'st-1', + deviceAuthCode: 'PAIR-1', + createdAt: new Date(Date.now() - 1000).toISOString(), + expiresAt: new Date(Date.now() + 600_000).toISOString(), + }; + void store.createCode(input); + return { ...input, status: 'pending', kiloUserId: null, organizationId: null, kiloToken: null }; +} + +function statusRequest(code: string): Request { + return new Request(`${ISSUER}/authorize/status?code=${encodeURIComponent(code)}`); +} + +/** apps/web poll response factory (statuses per codes/[code]/route.ts). */ +function upstreamFetch(handler: (url: string) => Response | Promise): typeof fetch { + return vi.fn(async (input: string | URL) => handler(String(input))) as unknown as typeof fetch; +} + +describe('pollKiloPairing (apps/web relay)', () => { + const deps = { webBaseUrl: WEB }; + + it('maps 202/403/410 to pending/denied/expired and calls the poll URL', async () => { + const calls: string[] = []; + const outcomes = [ + { + response: Response.json({ status: 'pending' }, { status: 202 }), + expect: { status: 'pending' }, + }, + { + response: Response.json({ status: 'denied' }, { status: 403 }), + expect: { status: 'denied' }, + }, + { + response: Response.json({ status: 'expired' }, { status: 410 }), + expect: { status: 'expired' }, + }, + ]; + for (const { response, expect: expected } of outcomes) { + const fetchImpl = upstreamFetch(url => { + calls.push(url); + return response; + }); + await expect(pollKiloPairing({ ...deps, fetchImpl }, 'PAIR-9')).resolves.toEqual(expected); + } + expect(calls).toEqual([ + `${WEB}/api/device-auth/codes/PAIR-9`, + `${WEB}/api/device-auth/codes/PAIR-9`, + `${WEB}/api/device-auth/codes/PAIR-9`, + ]); + }); + + it('returns token + userId on an approved pairing', async () => { + const fetchImpl = upstreamFetch(() => + Response.json({ status: 'approved', token: 'kilo-jwt', userId: 'u-7', userEmail: 'a@b.c' }) + ); + await expect(pollKiloPairing({ ...deps, fetchImpl }, 'PAIR-9')).resolves.toEqual({ + status: 'approved', + token: 'kilo-jwt', + userId: 'u-7', + }); + }); + + it('a transport failure or a malformed approved body is unreachable, never a crash', async () => { + await expect( + pollKiloPairing( + { ...deps, fetchImpl: upstreamFetch(() => Promise.reject(new Error('down'))) }, + 'P' + ) + ).resolves.toEqual({ status: 'unreachable' }); + await expect( + pollKiloPairing( + { ...deps, fetchImpl: upstreamFetch(() => Response.json({ status: 'approved' })) }, + 'P' + ) + ).resolves.toEqual({ status: 'unreachable' }); + await expect( + pollKiloPairing( + { ...deps, fetchImpl: upstreamFetch(() => Response.json({}, { status: 500 })) }, + 'P' + ) + ).resolves.toEqual({ status: 'unreachable' }); + }); +}); + +describe('GET /authorize/status (consent-page pairing poll)', () => { + it('reports pending while the user has not approved upstream, and keeps the next poll alive', async () => { + const store = createFakeOAuthStore(); + const record = seedPendingCode(store); + const fetchImpl = upstreamFetch(() => Response.json({ status: 'pending' }, { status: 202 })); + const response = await handlePairingStatus(statusRequest(record.code), { + store, + webBaseUrl: WEB, + fetchImpl, + }); + expect(response.status).toBe(200); + await expect(response.json()).resolves.toEqual({ status: 'pending' }); + }); + + it('an approved pairing is persisted once and answered with the org picker', async () => { + const store = createFakeOAuthStore(); + const record = seedPendingCode(store); + let approvedAnswers = 0; + const fetchImpl = upstreamFetch(() => { + approvedAnswers += 1; + // Single-use upstream: only the first poll ever sees `approved`. + if (approvedAnswers === 1) { + return Response.json({ status: 'approved', token: 'kilo-tok-1', userId: 'u-1' }); + } + return Response.json({ status: 'expired' }, { status: 410 }); + }); + const deps = { store, webBaseUrl: WEB, fetchImpl }; + + await expect( + handlePairingStatus(statusRequest(record.code), deps).then(r => r.json()) + ).resolves.toEqual({ + status: 'needs_org', + picker_url: `/authorize/org?code=${record.code}`, + }); + const stored = store.codes.get(record.code); + expect(stored).toMatchObject({ kiloUserId: 'u-1', kiloToken: 'kilo-tok-1', status: 'pending' }); + + // Second poll: the token is held locally; apps/web is never asked again. + await expect( + handlePairingStatus(statusRequest(record.code), deps).then(r => r.json()) + ).resolves.toEqual({ + status: 'needs_org', + picker_url: `/authorize/org?code=${record.code}`, + }); + // Exactly one upstream poll per pending record: the single-use approved + // answer is never replayed against the (now consumed) pairing. + expect(approvedAnswers).toBe(1); + }); + + it('a denied pairing is persisted and reported as denied', async () => { + const store = createFakeOAuthStore(); + const record = seedPendingCode(store); + const fetchImpl = upstreamFetch(() => Response.json({ status: 'denied' }, { status: 403 })); + await expect( + handlePairingStatus(statusRequest(record.code), { store, webBaseUrl: WEB, fetchImpl }).then( + r => r.json() + ) + ).resolves.toEqual({ status: 'denied' }); + expect(store.codes.get(record.code)?.status).toBe('denied'); + // Terminal: no further upstream polls. + await handlePairingStatus(statusRequest(record.code), { store, webBaseUrl: WEB, fetchImpl }); + expect(fetchImpl).toHaveBeenCalledTimes(1); + }); + + it('an expired upstream pairing reports expired (retryable via restart)', async () => { + const store = createFakeOAuthStore(); + const record = seedPendingCode(store); + const fetchImpl = upstreamFetch(() => Response.json({ status: 'expired' }, { status: 410 })); + await expect( + handlePairingStatus(statusRequest(record.code), { store, webBaseUrl: WEB, fetchImpl }).then( + r => r.json() + ) + ).resolves.toEqual({ status: 'expired' }); + // The local record stays pending (no terminal store state for upstream + // expiry) so the page can still restart before its own TTL. + expect(store.codes.get(record.code)?.status).toBe('pending'); + }); + + it('an unreachable upstream keeps the page waiting instead of failing the flow', async () => { + const store = createFakeOAuthStore(); + const record = seedPendingCode(store); + const fetchImpl = upstreamFetch(() => Promise.reject(new Error('network'))); + await expect( + handlePairingStatus(statusRequest(record.code), { store, webBaseUrl: WEB, fetchImpl }).then( + r => r.json() + ) + ).resolves.toEqual({ status: 'pending' }); + }); + + it('returns the client redirect (code + state) once the org is chosen', async () => { + const store = createFakeOAuthStore(); + const record = seedPendingCode(store); + await store.recordPairingApproval( + record.deviceAuthCode, + { kiloUserId: 'u1', kiloToken: 'k' }, + new Date().toISOString() + ); + await store.approveCode( + record.deviceAuthCode, + { kiloUserId: 'u1', organizationId: 'o1' }, + new Date().toISOString() + ); + const response = await handlePairingStatus(statusRequest(record.code), { + store, + webBaseUrl: WEB, + fetchImpl: upstreamFetch(() => Promise.reject(new Error('must not poll'))), + }); + const body = (await response.json()) as { status: string; redirect_url: string }; + expect(body.status).toBe('approved'); + const redirect = new URL(body.redirect_url); + expect(redirect.origin + redirect.pathname).toBe(REDIRECT); + expect(redirect.searchParams.get('code')).toBe(record.code); + expect(redirect.searchParams.get('state')).toBe('st-1'); + }); + + it('expired, used, and unknown codes answer identically (no probing oracle)', async () => { + const store = createFakeOAuthStore(); + const record = seedPendingCode(store); + const future = new Date(Date.now() + 600_000).toISOString(); + for (const probe of [record.code, 'never-seen']) { + const response = await handlePairingStatus(statusRequest(probe), { + store, + webBaseUrl: WEB, + fetchImpl: upstreamFetch(() => Promise.reject(new Error('must not poll'))), + now: () => new Date(future), + }); + await expect(response.json()).resolves.toEqual({ status: 'unknown' }); + } + }); + + it('rejects non-GET', async () => { + const store = createFakeOAuthStore(); + const response = await handlePairingStatus( + new Request(`${ISSUER}/authorize/status`, { method: 'POST' }), + { store, webBaseUrl: WEB } + ); + expect(response.status).toBe(405); + }); +}); + +describe('consentPage (s6 contract)', () => { + it('escapes the client name and carries needs_org/expired/unknown into failure copy with restart', async () => { + const response = consentPage({ + clientName: '', + scope: 'mcp', + webSignInUrl: `${WEB}/device-auth?code=PAIR-1`, + statusUrl: '/authorize/status?code=abc', + restartUrl: `${ISSUER}/authorize?client_id=c`, + }); + const html = await response.text(); + expect(html).not.toContain(''); + expect(html).toContain('<script>'); + expect(html).toContain('Requested access'); + expect(html).toContain('needs_org'); + expect(html).toContain('expired'); + expect(html).toContain('Start sign-in again'); + expect(html).toContain(`${ISSUER}/authorize?client_id=c`); + // The restart CTA stays hidden while the page is still waiting, and the + // stylesheet must not defeat the hidden attribute (an author display rule + // beats the UA [hidden] rule — see PAGE_STYLE). + expect(html).toMatch(/id="restart"[^>]*\shidden/); + expect(html).toContain('[hidden]{display:none !important}'); + }); +}); diff --git a/services/kilo-mcp/src/oauth-pages/authorize-page.ts b/services/kilo-mcp/src/oauth-pages/authorize-page.ts new file mode 100644 index 0000000000..8043a137ce --- /dev/null +++ b/services/kilo-mcp/src/oauth-pages/authorize-page.ts @@ -0,0 +1,207 @@ +/** + * The consent page served at GET /authorize (s6, continuing s5's record) and + * the worker endpoint that page polls for pairing completion. + * + * apps/web stays the identity provider: the page's Continue button opens + * `{WEB_BASE_URL}/device-auth?code=` (the existing Kilo sign-in + + * approval page — zero changes to apps/web), and this endpoint relays the + * pairing outcome the page polls for. The upstream poll + * (apps/web/src/app/api/device-auth/codes/[code]/route.ts) is SINGLE-USE: + * its first `approved` answer consumes the pairing and mints the Kilo token, + * so the token + userId are persisted via `recordPairingApproval` the moment + * they are seen and the endpoint never asks apps/web twice for one pairing. + * + * Once the pairing is approved the user still has to pick an organization, so + * the page is pointed at the org picker (`needs_org`); after the org is bound + * the record is `approved` and the page follows the client redirect. + * + * States: pending -> keep waiting; needs_org -> redirect to the picker; + * denied / expired / unknown -> failure copy + a restart link that re-runs the + * exact original /authorize request (fresh pairing). Upstream hiccups + * (`unreachable`) keep the page waiting — the next poll retries. + */ +import { + authJsonResponse, + authPage, + escapeHtml, + htmlResponse, + PAIRING_POLL_INTERVAL_MS, +} from '../auth/http'; +import type { OAuthStoreApi } from '../store/oauth-store'; + +export type PairingStatusDeps = { + store: OAuthStoreApi; + /** apps/web base URL — polled for the device-auth pairing outcome. */ + webBaseUrl: string; + fetchImpl?: typeof fetch; + now?: () => Date; +}; + +/** The consent HTML: sign-in link + status polling until the flow resolves. */ +export function consentPage(input: { + clientName: string; + scope: string; + webSignInUrl: string; + statusUrl: string; + /** The original /authorize URL; the failure states offer to restart from it. */ + restartUrl: string; +}): Response { + const body = + `

Sign in to Kilo MCP

` + + `

${escapeHtml(input.clientName)} is asking to connect to Kilo MCP ` + + `with your Kilo account.

` + + `

Requested access: ${escapeHtml(input.scope)}

` + + `

Continue with Kilo sign-in

` + + `

Waiting for you to finish sign-in…

` + + `

` + + ``; + return htmlResponse(authPage('Sign in to Kilo MCP', body)); +} + +export type KiloPollOutcome = + | { status: 'pending' } + | { status: 'approved'; token: string; userId: string } + | { status: 'denied' } + | { status: 'expired' } + | { status: 'unreachable' }; + +/** + * Relay one pairing-status question to apps/web + * (`GET /api/device-auth/codes/{code}` — statuses pending/approved/denied/ + * expired, apps/web/src/app/api/device-auth/codes/[code]/route.ts). Any + * transport-level or shape surprise is `unreachable`: the caller keeps the + * user waiting and lets the next poll retry rather than failing the flow. + */ +export async function pollKiloPairing( + deps: Pick, + deviceAuthCode: string +): Promise { + const fetchImpl = deps.fetchImpl ?? fetch; + const url = `${deps.webBaseUrl.replace(/\/$/, '')}/api/device-auth/codes/${encodeURIComponent(deviceAuthCode)}`; + let response: Response; + try { + response = await fetchImpl(url, { method: 'GET', headers: { Accept: 'application/json' } }); + } catch { + return { status: 'unreachable' }; + } + if (response.status === 202) return { status: 'pending' }; + if (response.status === 403) return { status: 'denied' }; + if (response.status === 410) return { status: 'expired' }; + if (!response.ok) return { status: 'unreachable' }; + const body: unknown = await response.json().catch(() => null); + if (typeof body !== 'object' || body === null) return { status: 'unreachable' }; + const record = body as { status?: unknown; token?: unknown; userId?: unknown }; + if (record.status !== 'approved') return { status: 'unreachable' }; + if (typeof record.token !== 'string' || record.token.length === 0) + return { status: 'unreachable' }; + if (typeof record.userId !== 'string' || record.userId.length === 0) + return { status: 'unreachable' }; + return { status: 'approved', token: record.token, userId: record.userId }; +} + +export type PairingStatus = + | { status: 'pending' } + | { status: 'needs_org'; picker_url: string } + | { status: 'approved'; redirect_url: string } + | { status: 'denied' } + | { status: 'expired' } + | { status: 'unknown' }; + +function needsOrg(code: string): Response { + return authJsonResponse({ + status: 'needs_org', + picker_url: `/authorize/org?code=${encodeURIComponent(code)}`, + } satisfies PairingStatus); +} + +function clientRedirect(record: { + redirectUri: string; + code: string; + state: string | null; +}): Response { + const redirect = new URL(record.redirectUri); + redirect.searchParams.set('code', record.code); + if (record.state) redirect.searchParams.set('state', record.state); + return authJsonResponse({ + status: 'approved', + redirect_url: redirect.toString(), + } satisfies PairingStatus); +} + +/** + * GET /authorize/status?code= — what the consent page polls. Unknown, + * expired, and already-redeemed codes answer identically so the endpoint + * cannot be used to probe which pairing codes exist. While the record is + * pending this endpoint drives the apps/web relay; a denial is persisted so + * the token endpoint reports it too. + */ +export async function handlePairingStatus( + request: Request, + deps: PairingStatusDeps +): Promise { + if (request.method !== 'GET') { + return authJsonResponse({ error: 'invalid_request' }, 405); + } + const url = new URL(request.url); + const code = url.searchParams.get('code'); + if (!code) { + return authJsonResponse({ status: 'unknown' } satisfies PairingStatus); + } + const now = deps.now?.() ?? new Date(); + const nowIso = now.toISOString(); + const record = await deps.store.getCode(code); + if (!record || record.expiresAt <= nowIso || record.status === 'used') { + return authJsonResponse({ status: 'unknown' } satisfies PairingStatus); + } + if (record.status === 'denied') { + return authJsonResponse({ status: 'denied' } satisfies PairingStatus); + } + if (record.status === 'approved') { + return clientRedirect(record); + } + // status 'pending': pairing approved upstream but not recorded yet? + if (record.kiloUserId && record.kiloToken) { + return needsOrg(code); + } + + const upstream = await pollKiloPairing(deps, record.deviceAuthCode); + switch (upstream.status) { + case 'pending': + case 'unreachable': + // Transient upstream failure keeps the page waiting; its next poll retries. + return authJsonResponse({ status: 'pending' } satisfies PairingStatus); + case 'denied': { + await deps.store.denyCode(record.deviceAuthCode, nowIso); + return authJsonResponse({ status: 'denied' } satisfies PairingStatus); + } + case 'expired': + return authJsonResponse({ status: 'expired' } satisfies PairingStatus); + case 'approved': { + // Persist BEFORE any further poll: the upstream answer is single-use. + await deps.store.recordPairingApproval( + record.deviceAuthCode, + { kiloUserId: upstream.userId, kiloToken: upstream.token }, + nowIso + ); + const updated = await deps.store.getCode(code); + if (updated?.kiloUserId && updated.kiloToken) { + return needsOrg(code); + } + // The record moved to a terminal state while we polled. + if (updated?.status === 'approved') return clientRedirect(updated); + if (updated?.status === 'denied') { + return authJsonResponse({ status: 'denied' } satisfies PairingStatus); + } + return authJsonResponse({ status: 'unknown' } satisfies PairingStatus); + } + } +} diff --git a/services/kilo-mcp/src/oauth-pages/org-picker.test.ts b/services/kilo-mcp/src/oauth-pages/org-picker.test.ts new file mode 100644 index 0000000000..a93473a65d --- /dev/null +++ b/services/kilo-mcp/src/oauth-pages/org-picker.test.ts @@ -0,0 +1,446 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + fetchOrgOptions, + handleOrgPicker, + ORG_LIST_QUERY_PATH, + PERSONAL_ORG_ID, +} from './org-picker'; +import type { + NewOAuthCode, + OAuthCodeRecord, + OAuthStoreApi, + StoredClient, +} from '../store/oauth-store'; + +function createFakeOAuthStore(): OAuthStoreApi & { + clients: Map; + codes: Map; +} { + const clients = new Map(); + const codes = new Map(); + const unused = (): never => { + throw new Error('not reachable from these tests'); + }; + return { + clients, + codes, + registerClient: unused, + async getClient(clientId) { + return clients.get(clientId) ?? null; + }, + async createCode(input: NewOAuthCode) { + codes.set(input.code, { + ...input, + status: 'pending', + kiloUserId: null, + organizationId: null, + kiloToken: null, + }); + }, + async getCode(code) { + return codes.get(code) ?? null; + }, + async recordPairingApproval(deviceAuthCode, identity, nowIso) { + for (const [code, record] of codes) { + if ( + record.deviceAuthCode === deviceAuthCode && + record.status === 'pending' && + record.kiloUserId === null && + record.expiresAt > nowIso + ) { + codes.set(code, { + ...record, + kiloUserId: identity.kiloUserId, + kiloToken: identity.kiloToken, + }); + return true; + } + } + return false; + }, + denyCode: unused, + async approveCode(deviceAuthCode, identity, nowIso) { + for (const [code, record] of codes) { + if ( + record.deviceAuthCode === deviceAuthCode && + record.status === 'pending' && + record.expiresAt > nowIso + ) { + codes.set(code, { + ...record, + status: 'approved', + kiloUserId: identity.kiloUserId, + organizationId: identity.organizationId, + }); + return true; + } + } + return false; + }, + consumeCode: unused, + saveRefreshToken: unused, + getRefreshTokenByHash: unused, + rotateRefreshToken: unused, + getKiloToken: unused, + revokeGrant: unused, + revokeJti: unused, + async isJtiRevoked() { + return false; + }, + purgeExpired: unused, + }; +} + +const ISSUER = 'https://kilo-mcp.test'; +const WEB = 'https://app.kilo.test'; +const CLIENT_ID = 'client-abc'; +const REDIRECT = 'https://client.test/cb'; + +function seedPairedCode(store: ReturnType): OAuthCodeRecord { + const input: NewOAuthCode = { + code: 'auth-code-value-00000000000000000000000000000000000', + clientId: CLIENT_ID, + redirectUri: REDIRECT, + codeChallenge: 'challenge-value-000000000000000000000000000000', + resource: `${ISSUER}/mcp`, + scope: 'mcp', + state: 'st-1', + deviceAuthCode: 'PAIR-1', + createdAt: new Date(Date.now() - 1000).toISOString(), + expiresAt: new Date(Date.now() + 600_000).toISOString(), + }; + void store.createCode(input); + void store.recordPairingApproval( + input.deviceAuthCode, + { kiloUserId: 'u-1', kiloToken: 'kilo-tok-1' }, + new Date().toISOString() + ); + store.clients.set(CLIENT_ID, { + clientId: CLIENT_ID, + redirectUris: [REDIRECT], + clientName: 'Test Client', + createdAt: '2026-09-09T00:00:00.000Z', + }); + return { ...store.codes.get(input.code)! }; +} + +function trpcOrgFetch(orgs: Array<{ organizationId: string; organizationName: string }>) { + return vi.fn(async () => Response.json({ result: { data: orgs } })); +} + +function pickerUrl(code: string): string { + return `${ISSUER}/authorize/org?code=${encodeURIComponent(code)}`; +} + +describe('fetchOrgOptions (organizations.list via the Kilo bearer)', () => { + it('calls the catalog query with the Kilo bearer and lists personal first', async () => { + const fetchImpl = trpcOrgFetch([ + { organizationId: 'org-1', organizationName: 'Acme' }, + { organizationId: 'org-2', organizationName: 'Nova' }, + ]); + const options = await fetchOrgOptions({ webBaseUrl: WEB, fetchImpl }, 'kilo-tok-1'); + expect(options).toEqual([ + { id: PERSONAL_ORG_ID, name: 'Personal account' }, + { id: 'org-1', name: 'Acme' }, + { id: 'org-2', name: 'Nova' }, + ]); + const [calledUrl, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit]; + expect(calledUrl).toBe(`${WEB}/api/trpc/${ORG_LIST_QUERY_PATH}`); + expect((init.headers as Record).Authorization).toBe('Bearer kilo-tok-1'); + }); + + it('dedupes ids and skips malformed rows', async () => { + const fetchImpl = trpcOrgFetch([ + { organizationId: 'org-1', organizationName: 'Acme' }, + { organizationId: 'org-1', organizationName: 'dup' }, + { organizationName: 'no id' }, + 'garbage', + ] as never); + const options = await fetchOrgOptions({ webBaseUrl: WEB, fetchImpl }, 'k'); + expect(options.map(o => o.id)).toEqual([PERSONAL_ORG_ID, 'org-1']); + }); + + it('throws on a non-OK or unexpected upstream (caller renders a retry)', async () => { + await expect( + fetchOrgOptions( + { + webBaseUrl: WEB, + fetchImpl: vi.fn(async () => Response.json({}, { status: 500 })) as never, + }, + 'k' + ) + ).rejects.toThrow(); + await expect( + fetchOrgOptions( + { webBaseUrl: WEB, fetchImpl: vi.fn(async () => Response.json({ nope: 1 })) as never }, + 'k' + ) + ).rejects.toThrow(); + }); +}); + +describe('GET /authorize/org (picker render)', () => { + it('renders the personal context plus each of the user organizations', async () => { + const store = createFakeOAuthStore(); + const record = seedPairedCode(store); + const response = await handleOrgPicker(new Request(pickerUrl(record.code)), { + store, + webBaseUrl: WEB, + fetchImpl: trpcOrgFetch([ + { organizationId: 'org-1', organizationName: 'Acme' }, + ]) as unknown as typeof fetch, + }); + expect(response.status).toBe(200); + expect(response.headers.get('Content-Type')).toContain('text/html'); + const html = await response.text(); + expect(html).toContain('Choose a Kilo organization'); + expect(html).toContain('Test Client'); + expect(html).toContain('Personal account'); + expect(html).toContain('Acme'); + expect(html).toContain(`value="${PERSONAL_ORG_ID}"`); + expect(html).toContain('value="org-1"'); + expect(html).toContain(`action="/authorize/org?code=${record.code}"`); + }); + + it('escapes an organization name', async () => { + const store = createFakeOAuthStore(); + const record = seedPairedCode(store); + const response = await handleOrgPicker(new Request(pickerUrl(record.code)), { + store, + webBaseUrl: WEB, + fetchImpl: trpcOrgFetch([ + { organizationId: 'o', organizationName: 'x' }, + ]) as unknown as typeof fetch, + }); + const html = await response.text(); + expect(html).toContain('<b>x</b>'); + expect(html).not.toContain('x'); + }); + + it('offers a retry with the personal context when the org list fails', async () => { + const store = createFakeOAuthStore(); + const record = seedPairedCode(store); + const response = await handleOrgPicker(new Request(pickerUrl(record.code)), { + store, + webBaseUrl: WEB, + fetchImpl: vi.fn(async () => { + throw new Error('upstream down'); + }) as unknown as typeof fetch, + }); + expect(response.status).toBe(200); + const html = await response.text(); + expect(html).toMatch(/Could not load your organizations/); + expect(html).toContain('Personal account'); + }); + + it('completes the client redirect when the org was already chosen', async () => { + const store = createFakeOAuthStore(); + const record = seedPairedCode(store); + await store.approveCode( + record.deviceAuthCode, + { kiloUserId: 'u-1', organizationId: 'org-1' }, + new Date().toISOString() + ); + const response = await handleOrgPicker(new Request(pickerUrl(record.code)), { + store, + webBaseUrl: WEB, + fetchImpl: vi.fn(() => + Promise.reject(new Error('must not fetch')) + ) as unknown as typeof fetch, + }); + expect(response.status).toBe(302); + const location = new URL(response.headers.get('Location')!); + expect(location.origin + location.pathname).toBe(REDIRECT); + expect(location.searchParams.get('code')).toBe(record.code); + expect(location.searchParams.get('state')).toBe('st-1'); + }); + + it('sends an unpaired code back through the consent page', async () => { + const store = createFakeOAuthStore(); + const record = seedPairedCode(store); + // Roll the identity back: pairing not finished upstream yet. + store.codes.set(record.code, { ...record, kiloUserId: null, kiloToken: null }); + const response = await handleOrgPicker(new Request(pickerUrl(record.code)), { + store, + webBaseUrl: WEB, + fetchImpl: vi.fn(() => + Promise.reject(new Error('must not fetch')) + ) as unknown as typeof fetch, + }); + expect(response.status).toBe(200); + const html = await response.text(); + expect(html).toContain('Sign in to Kilo MCP'); + expect(html).toContain(`${WEB}/device-auth?code=${record.deviceAuthCode}`); + }); + + it('rejects unknown, expired, used, and denied codes with an error page', async () => { + const store = createFakeOAuthStore(); + const record = seedPairedCode(store); + const fetchImpl = vi.fn(() => + Promise.reject(new Error('must not fetch')) + ) as unknown as typeof fetch; + const deps = { store, webBaseUrl: WEB, fetchImpl }; + await expect( + handleOrgPicker(new Request(pickerUrl('ghost')), deps).then(r => r.status) + ).resolves.toBe(400); + store.codes.set(record.code, { ...record, status: 'denied' }); + await expect( + handleOrgPicker(new Request(pickerUrl(record.code)), deps).then(r => r.status) + ).resolves.toBe(400); + store.codes.set(record.code, { ...record, status: 'used' }); + await expect( + handleOrgPicker(new Request(pickerUrl(record.code)), deps).then(r => r.status) + ).resolves.toBe(400); + store.codes.set(record.code, { + ...record, + expiresAt: new Date(Date.now() - 1000).toISOString(), + }); + await expect( + handleOrgPicker(new Request(pickerUrl(record.code)), deps).then(r => r.status) + ).resolves.toBe(400); + }); +}); + +describe('POST /authorize/org (bind the org and complete)', () => { + async function post( + store: ReturnType, + record: OAuthCodeRecord, + organizationId: string | null, + orgs: Array<{ organizationId: string; organizationName: string }> + ) { + const form = new URLSearchParams(); + if (organizationId !== null) form.set('organization_id', organizationId); + const response = await handleOrgPicker( + new Request(pickerUrl(record.code), { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: form.toString(), + }), + { store, webBaseUrl: WEB, fetchImpl: trpcOrgFetch(orgs) as unknown as typeof fetch } + ); + return response; + } + + it('binds a member organization into the authorization and redirects with the code', async () => { + const store = createFakeOAuthStore(); + const record = seedPairedCode(store); + const response = await post(store, record, 'org-2', [ + { organizationId: 'org-1', organizationName: 'Acme' }, + { organizationId: 'org-2', organizationName: 'Nova' }, + ]); + expect(response.status).toBe(302); + const location = new URL(response.headers.get('Location')!); + expect(location.origin + location.pathname).toBe(REDIRECT); + expect(location.searchParams.get('code')).toBe(record.code); + expect(location.searchParams.get('state')).toBe('st-1'); + const approved = store.codes.get(record.code); + expect(approved).toMatchObject({ + status: 'approved', + kiloUserId: 'u-1', + organizationId: 'org-2', + }); + }); + + it('the personal context authorizes with a null organization', async () => { + const store = createFakeOAuthStore(); + const record = seedPairedCode(store); + const response = await post(store, record, PERSONAL_ORG_ID, [ + { organizationId: 'org-1', organizationName: 'Acme' }, + ]); + expect(response.status).toBe(302); + expect(store.codes.get(record.code)).toMatchObject({ + status: 'approved', + organizationId: null, + }); + }); + + it('the personal selection completes even when the org list fetch fails (no dead-end retry loop)', async () => { + const store = createFakeOAuthStore(); + const record = seedPairedCode(store); + const response = await handleOrgPicker( + new Request(pickerUrl(record.code), { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ organization_id: PERSONAL_ORG_ID }).toString(), + }), + { + store, + webBaseUrl: WEB, + fetchImpl: vi.fn(async () => { + throw new Error('upstream down'); + }) as unknown as typeof fetch, + } + ); + // The personal context is always valid for an approved Kilo login: the + // submit must complete, not be discarded behind the failed membership read. + expect(response.status).toBe(302); + const location = new URL(response.headers.get('Location')!); + expect(location.origin + location.pathname).toBe(REDIRECT); + expect(location.searchParams.get('code')).toBe(record.code); + expect(store.codes.get(record.code)).toMatchObject({ + status: 'approved', + organizationId: null, + }); + }); + + it('a concrete org selection with a failed org list fetch stays retryable (no approval)', async () => { + const store = createFakeOAuthStore(); + const record = seedPairedCode(store); + const response = await handleOrgPicker( + new Request(pickerUrl(record.code), { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ organization_id: 'org-1' }).toString(), + }), + { + store, + webBaseUrl: WEB, + fetchImpl: vi.fn(async () => { + throw new Error('upstream down'); + }) as unknown as typeof fetch, + } + ); + // Membership cannot be verified without the live read, so the concrete org + // is refused retryably and only the (still valid) personal context is offered. + expect(response.status).toBe(200); + const html = await response.text(); + expect(html).toMatch(/Could not load your organizations/); + expect(html).toContain('Personal account'); + expect(store.codes.get(record.code)?.status).toBe('pending'); + }); + + it('refuses an organization the user is not a member of (edited form)', async () => { + const store = createFakeOAuthStore(); + const record = seedPairedCode(store); + const response = await post(store, record, 'org-victim', [ + { organizationId: 'org-1', organizationName: 'Acme' }, + ]); + expect(response.status).toBe(200); + const html = await response.text(); + expect(html).toMatch(/not available for this account/); + expect(store.codes.get(record.code)?.status).toBe('pending'); + }); + + it('a missing selection re-renders the picker with a prompt', async () => { + const store = createFakeOAuthStore(); + const record = seedPairedCode(store); + const response = await post(store, record, null, [ + { organizationId: 'org-1', organizationName: 'Acme' }, + ]); + expect(response.status).toBe(200); + const html = await response.text(); + expect(html).toMatch(/Choose an account/); + expect(store.codes.get(record.code)?.status).toBe('pending'); + }); + + it('a lost race to expiry/denial does not redirect', async () => { + const store = createFakeOAuthStore(); + const record = seedPairedCode(store); + // Simulate a concurrent denial between render and submit. + store.codes.set(record.code, { ...record, status: 'denied' }); + const response = await post(store, record, 'org-1', [ + { organizationId: 'org-1', organizationName: 'Acme' }, + ]); + expect(response.status).toBe(400); + }); +}); diff --git a/services/kilo-mcp/src/oauth-pages/org-picker.ts b/services/kilo-mcp/src/oauth-pages/org-picker.ts new file mode 100644 index 0000000000..9d34d2cd5d --- /dev/null +++ b/services/kilo-mcp/src/oauth-pages/org-picker.ts @@ -0,0 +1,296 @@ +/** + * The org picker served at GET/POST /authorize/org (s6). + * + * Reached once the consent page's poll reports `needs_org`: the device-auth + * pairing is approved and this worker already holds the approved Kilo token + + * userId (recordPairingApproval persisted them). The picker asks apps/web + * which organizations that Kilo identity belongs to — by calling the + * read-only `organizations.list` catalog query with the Kilo bearer — renders + * them (plus the personal, org-less context), and on selection completes the + * MCP authorization: binds the chosen org into the pending code and redirects + * to the client's redirect_uri with the authorization code. + * + * The org choice is stored with the authorization (approveCode) and lands in + * the token claims (token.ts reads the consumed record's organizationId), + * which is what requirement 17/18 asks for: the token is bound to + * user + org + this MCP. + * + * Trust boundary: a concrete organizationId submitted by the form is validated + * against the freshly-fetched membership list — a client cannot authorize an + * org it is not a member of by editing the form. The personal context needs no + * such check: it authorizes the already-paired Kilo user with no org, so the + * submit must complete even when the membership read is down. + */ +import { consentPage } from './authorize-page'; +import { + AUTH_PATHS, + authPage, + escapeHtml, + errorPage, + htmlResponse, + withAuthCors, +} from '../auth/http'; +import type { OAuthCodeRecord, OAuthStoreApi } from '../store/oauth-store'; + +export type OrgPickerDeps = { + store: OAuthStoreApi; + /** apps/web base URL — the tRPC executor queried for the org list. */ + webBaseUrl: string; + fetchImpl?: typeof fetch; + now?: () => Date; +}; + +/** A selectable organization; `id` is the value posted back to the worker. */ +export type OrgOption = { id: string; name: string }; + +/** The personal (org-less) context: always available for a Kilo login. */ +export const PERSONAL_ORG_ID = 'personal'; + +/** The catalog query used to list the caller's orgs (read-only, in the dump). */ +export const ORG_LIST_QUERY_PATH = 'organizations.list'; + +const PICKER_STYLE = + '.org{display:flex;align-items:center;gap:10px;padding:12px 14px;margin:8px 0;' + + 'border:1px solid #262a34;border-radius:10px;cursor:pointer}' + + '.org input{accent-color:#5b5bd6}' + + // the shared shell styles a.cta only; the submit button gets the same CTA look. + 'button.cta{display:inline-block;margin-top:16px;padding:12px 20px;border-radius:8px;' + + 'background:#5b5bd6;color:#fff;font-weight:600;border:0;cursor:pointer}' + + '.err{color:#f87171}'; + +/** + * Fetch the Kilo identity's organizations by calling the catalog tRPC query + * with the approved Kilo bearer. Returns the selectable options with the + * personal context first (an approved Kilo login always has it, so the picker + * is never empty). Throws on any upstream failure — the caller renders a + * retryable error. + */ +export async function fetchOrgOptions( + deps: Pick, + kiloToken: string +): Promise { + const fetchImpl = deps.fetchImpl ?? fetch; + const url = new URL(`/api/trpc/${ORG_LIST_QUERY_PATH}`, deps.webBaseUrl); + let response: Response; + try { + response = await fetchImpl(url.toString(), { + method: 'GET', + headers: { Accept: 'application/json', Authorization: `Bearer ${kiloToken}` }, + }); + } catch { + throw new Error('org list upstream unreachable'); + } + if (!response.ok) { + throw new Error(`org list upstream returned ${response.status}`); + } + const body: unknown = await response.json().catch(() => null); + const data = (body as { result?: { data?: unknown } } | null)?.result?.data; + if (!Array.isArray(data)) { + throw new Error('org list upstream returned an unexpected shape'); + } + const options: OrgOption[] = [{ id: PERSONAL_ORG_ID, name: 'Personal account' }]; + const seen = new Set([PERSONAL_ORG_ID]); + for (const row of data) { + if (typeof row !== 'object' || row === null) continue; + const id = (row as { organizationId?: unknown }).organizationId; + const name = (row as { organizationName?: unknown }).organizationName; + if (typeof id !== 'string' || id.length === 0 || seen.has(id)) continue; + seen.add(id); + options.push({ id, name: typeof name === 'string' && name.length > 0 ? name : id }); + } + return options; +} + +/** A paired-but-not-yet-approved code is exactly what the picker handles. */ +type PickerRecord = OAuthCodeRecord & { kiloUserId: string; kiloToken: string }; + +function isReadyForPicker(record: OAuthCodeRecord, nowIso: string): record is PickerRecord { + return ( + record.status === 'pending' && + record.expiresAt > nowIso && + typeof record.kiloUserId === 'string' && + record.kiloUserId.length > 0 && + typeof record.kiloToken === 'string' && + record.kiloToken.length > 0 + ); +} + +/** Rebuild the client's original /authorize request from the stored record. */ +function restartAuthorizeUrl(request: Request, record: OAuthCodeRecord): string { + const url = new URL(AUTH_PATHS.authorize, new URL(request.url).origin); + url.searchParams.set('client_id', record.clientId); + url.searchParams.set('redirect_uri', record.redirectUri); + url.searchParams.set('response_type', 'code'); + url.searchParams.set('code_challenge', record.codeChallenge); + url.searchParams.set('code_challenge_method', 'S256'); + url.searchParams.set('resource', record.resource); + url.searchParams.set('scope', record.scope); + if (record.state) url.searchParams.set('state', record.state); + return url.toString(); +} + +/** The picker HTML: one radio per selectable context + a Connect button. */ +export function orgPickerPage(input: { + clientName: string; + actionUrl: string; + options: OrgOption[]; + error: string | null; +}): Response { + const optionsHtml = input.options + .map( + (option, index) => + `` + ) + .join(''); + const errorHtml = input.error + ? `` + : ''; + const body = + `

Choose a Kilo organization

` + + `

${escapeHtml(input.clientName)} is connecting to Kilo MCP. ` + + `Pick the account to use.

` + + errorHtml + + `
` + + `
${optionsHtml}
` + + `` + + `
`; + const page = authPage('Choose a Kilo organization', body); + // The picker needs radio-list layout the shared shell does not carry. + return htmlResponse(page.replace('', ``)); +} + +function redirectWithCode(record: OAuthCodeRecord): Response { + const redirect = new URL(record.redirectUri); + redirect.searchParams.set('code', record.code); + if (record.state) redirect.searchParams.set('state', record.state); + // Plain 302 (not Response.redirect) so withAuthCors can extend the headers. + return withAuthCors( + new Response(null, { status: 302, headers: { Location: redirect.toString() } }) + ); +} + +/** + * GET/POST /authorize/org. GET renders the picker; POST binds the chosen org + * (validated against a fresh membership fetch) and redirects to the client. + */ +export async function handleOrgPicker(request: Request, deps: OrgPickerDeps): Promise { + if (request.method !== 'GET' && request.method !== 'POST') { + return errorPage('invalid_request', 'Use GET or POST for /authorize/org.'); + } + const url = new URL(request.url); + const code = url.searchParams.get('code'); + if (!code) { + return errorPage('invalid_request', 'Missing authorization code.'); + } + const now = deps.now?.() ?? new Date(); + const nowIso = now.toISOString(); + const record = await deps.store.getCode(code); + if ( + !record || + record.expiresAt <= nowIso || + record.status === 'used' || + record.status === 'denied' + ) { + return errorPage( + 'invalid_request', + 'This request is no longer valid. Close this tab and retry from your MCP client.' + ); + } + // Already approved (double submit, or the picker reopened after success): + // complete the client redirect instead of asking again. + if (record.status === 'approved') { + return redirectWithCode(record); + } + if (!isReadyForPicker(record, nowIso)) { + // Kilo sign-in not finished for this record: send the user back through + // the consent page for the SAME pairing (the device-auth code is stored). + const client = await deps.store.getClient(record.clientId); + return consentPage({ + clientName: client?.clientName ?? 'your MCP client', + scope: record.scope, + webSignInUrl: `${deps.webBaseUrl.replace(/\/$/, '')}/device-auth?code=${encodeURIComponent(record.deviceAuthCode)}`, + statusUrl: `/authorize/status?code=${encodeURIComponent(record.code)}`, + restartUrl: restartAuthorizeUrl(request, record), + }); + } + + const client = await deps.store.getClient(record.clientId); + const clientName = client?.clientName ?? 'your MCP client'; + const actionUrl = `${AUTH_PATHS.orgPicker}?code=${encodeURIComponent(record.code)}`; + + /** Render the picker offering only the personal context with a retry message. */ + const personalOnlyPage = (error: string) => + orgPickerPage({ + clientName, + actionUrl, + options: [{ id: PERSONAL_ORG_ID, name: 'Personal account' }], + error, + }); + + /** Bind the chosen context and complete the authorize; stops on a lost race. */ + const approveAndRedirect = async (organizationId: string | null): Promise => { + const approved = await deps.store.approveCode( + record.deviceAuthCode, + { kiloUserId: record.kiloUserId, organizationId }, + nowIso + ); + if (!approved) { + // Lost the race to an expiry or a concurrent denial: stop, do not redirect. + return errorPage( + 'invalid_request', + 'This request is no longer valid. Close this tab and retry from your MCP client.' + ); + } + return redirectWithCode({ ...record, organizationId }); + }; + + if (request.method === 'GET') { + let options: OrgOption[]; + try { + options = await fetchOrgOptions(deps, record.kiloToken); + } catch { + // Retryable unhappy: the org list is a live read, so the personal context + // stays selectable and the same submit completes the flow on retry. + return personalOnlyPage( + 'Could not load your organizations right now — only the personal account is offered. Choose it, or retry.' + ); + } + return orgPickerPage({ clientName, actionUrl, options, error: null }); + } + + // POST. The personal context is always valid for an approved Kilo login (the + // userId already sits on the record), so it must not depend on the live + // membership read — otherwise the retry copy above points at a dead end. + const form = await request.formData().catch(() => null); + const submitted = form?.get('organization_id'); + if (typeof submitted !== 'string' || submitted.length === 0) { + const options = await fetchOrgOptions(deps, record.kiloToken).catch(() => null); + return options + ? orgPickerPage({ clientName, actionUrl, options, error: 'Choose an account to continue.' }) + : personalOnlyPage('Choose an account to continue.'); + } + if (submitted === PERSONAL_ORG_ID) { + return approveAndRedirect(null); + } + // Concrete orgs stay validated against the freshly-fetched membership list: + // a client cannot authorize an org it is not a member of by editing the form. + let options: OrgOption[]; + try { + options = await fetchOrgOptions(deps, record.kiloToken); + } catch { + return personalOnlyPage( + 'Could not load your organizations right now — only the personal account is offered. Choose it, or retry.' + ); + } + const chosen = options.find(option => option.id === submitted); + if (!chosen) { + return orgPickerPage({ + clientName, + actionUrl, + options, + error: 'That organization is not available for this account.', + }); + } + return approveAndRedirect(chosen.id === PERSONAL_ORG_ID ? null : chosen.id); +} diff --git a/services/kilo-mcp/src/search-knn.test.ts b/services/kilo-mcp/src/search-knn.test.ts new file mode 100644 index 0000000000..ea5ce47ef9 --- /dev/null +++ b/services/kilo-mcp/src/search-knn.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it, vi } from 'vitest'; +import { EMBEDDING_DIMENSIONS, EMBEDDING_MODEL } from './embedding'; +import { createSemanticCandidates, type SearchKnnEnv } from './search-knn'; + +const VECTOR_768 = Array.from({ length: EMBEDDING_DIMENSIONS }, (_, i) => (i % 97) / 97); + +type RunFn = SearchKnnEnv['AI']['run']; +type QueryFn = SearchKnnEnv['VECTORIZE']['query']; + +function fakeEnv(overrides?: { run?: RunFn; query?: QueryFn }): { + env: SearchKnnEnv; + run: ReturnType>; + query: ReturnType>; +} { + const run = vi.fn( + overrides?.run ?? (async () => ({ data: [VECTOR_768], shape: [1, EMBEDDING_DIMENSIONS] })) + ); + const query = vi.fn( + overrides?.query ?? + (async () => ({ matches: [{ id: 'user.getBalance', score: 0.9 }], count: 1 })) + ); + return { env: { AI: { run }, VECTORIZE: { query } }, run, query }; +} + +describe('createSemanticCandidates', () => { + it('embeds the search query with the pinned model and queries the index with that vector', async () => { + const { env, run, query } = fakeEnv(); + const candidates = createSemanticCandidates(env); + await candidates('refund the user balance', 10); + expect(run).toHaveBeenCalledWith(EMBEDDING_MODEL, { text: 'refund the user balance' }); + expect(query).toHaveBeenCalledWith(VECTOR_768, { topK: 20, returnMetadata: 'none' }); + }); + + it('maps match ids (procedure paths) to candidates with their kNN scores', async () => { + const { env } = fakeEnv({ + query: async () => ({ + matches: [ + { id: 'user.getBalance', score: 0.92 }, + { id: 'organizations.list', score: 0.41 }, + ], + }), + }); + const candidates = createSemanticCandidates(env); + expect(await candidates('balance', 10)).toEqual([ + { path: 'user.getBalance', score: 0.92 }, + { path: 'organizations.list', score: 0.41 }, + ]); + }); + + it('requests at least 20 and at most 100 candidates regardless of the caller limit', async () => { + const low = fakeEnv(); + await createSemanticCandidates(low.env)('q', 3); + expect(low.query).toHaveBeenCalledWith(expect.anything(), { topK: 20, returnMetadata: 'none' }); + const high = fakeEnv(); + await createSemanticCandidates(high.env)('q', 500); + expect(high.query).toHaveBeenCalledWith(expect.anything(), { + topK: 100, + returnMetadata: 'none', + }); + }); + + it('raises on an embedding failure so the search degrades to token-only', async () => { + const { env } = fakeEnv({ + run: async () => { + throw new Error('AI binding unavailable'); + }, + }); + await expect(createSemanticCandidates(env)('q', 10)).rejects.toThrow('AI binding unavailable'); + }); + + it('raises on an empty embedding vector', async () => { + const { env } = fakeEnv({ run: async () => ({ data: [] }) }); + await expect(createSemanticCandidates(env)('q', 10)).rejects.toThrow('empty vector'); + }); + + it('raises on a Vectorize failure so the search degrades to token-only', async () => { + const { env } = fakeEnv({ + query: async () => { + throw new Error('index unavailable'); + }, + }); + await expect(createSemanticCandidates(env)('q', 10)).rejects.toThrow('index unavailable'); + }); + + it('logs a non-fatal note and returns no candidates when the index is empty or unpopulated', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + const { env } = fakeEnv({ query: async () => ({ matches: [] }) }); + await expect(createSemanticCandidates(env)('q', 10)).resolves.toEqual([]); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('no candidates')); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('token-only results')); + } finally { + warn.mockRestore(); + } + }); +}); diff --git a/services/kilo-mcp/src/search-knn.ts b/services/kilo-mcp/src/search-knn.ts new file mode 100644 index 0000000000..2d407dd155 --- /dev/null +++ b/services/kilo-mcp/src/search-knn.ts @@ -0,0 +1,55 @@ +import { EMBEDDING_MODEL } from './embedding'; +import type { SemanticCandidates } from './types'; + +/** Minimum kNN candidates fetched regardless of the caller's limit. */ +const MIN_TOP_K = 20; + +/** Vectorize caps a single query at 100 results. */ +const MAX_TOP_K = 100; + +/** + * The slice of the worker Env that semantic search needs: Workers AI for the + * query embedding, Vectorize for the kNN lookup. Structural so tests can + * inject fakes; the worker passes the real `Env`. + */ +export type SearchKnnEnv = { + AI: { + run(model: string, input: { text: string }): Promise<{ data: number[][]; shape?: number[] }>; + }; + VECTORIZE: { + query( + vector: number[], + options: { topK: number; returnMetadata: 'none' } + ): Promise<{ matches: Array<{ id: string; score: number }>; count?: number }>; + }; +}; + +/** + * Vectorize-backed semantic candidates for hybrid search. The search QUERY is + * the only text embedded per request; the index itself was embedded offline by + * scripts/embed-catalog.ts, whose vector ids are the procedure paths, so each + * match id is the catalog path (requirement 9). + * + * Raises on any failure (binding missing, embedding error, index error): the + * caller — searchCatalog — degrades to token-only results with a logged note + * instead of failing the search. + */ +export function createSemanticCandidates(env: SearchKnnEnv): SemanticCandidates { + return async (query: string, limit: number) => { + const embedding = await env.AI.run(EMBEDDING_MODEL, { text: query }); + const vector = embedding.data[0]; + if (!vector || vector.length === 0) { + throw new Error(`embedding model ${EMBEDDING_MODEL} returned an empty vector`); + } + const topK = Math.min(Math.max(limit, MIN_TOP_K), MAX_TOP_K); + const result = await env.VECTORIZE.query(vector, { topK, returnMetadata: 'none' }); + if (result.matches.length === 0) { + // Empty index (embed job not yet run) or no similar rows: not an error, + // but say so — the results the caller sees are token-only. + console.warn( + '[kilo-mcp] semantic index returned no candidates (index may be empty or unpopulated); continuing with token-only results' + ); + } + return result.matches.map(match => ({ path: match.id, score: match.score })); + }; +} diff --git a/services/kilo-mcp/src/search.test.ts b/services/kilo-mcp/src/search.test.ts new file mode 100644 index 0000000000..4845f25009 --- /dev/null +++ b/services/kilo-mcp/src/search.test.ts @@ -0,0 +1,179 @@ +import { describe, expect, it, vi } from 'vitest'; +import { noSemanticCandidates, searchCatalog, tokenize } from './search'; +import type { Catalog } from './types'; + +/** + * Test catalog mirroring the shape of services/kilo-mcp/catalog.json. It is + * inline (not a committed fixture) so unit tests never depend on catalog + * regeneration drift. + */ +export const testCatalog: Catalog = { + 'organizations.list': { + path: 'organizations.list', + kind: 'query', + summary: 'List the organizations the user belongs to.', + inputSchema: {}, + tags: ['organizations', 'list'], + searchBlob: 'organizations.list List the organizations the user belongs to. organizations list', + }, + 'cliSessions.search': { + path: 'cliSessions.search', + kind: 'query', + summary: 'Search the user CLI sessions by keyword.', + inputSchema: { + type: 'object', + properties: { query: { type: 'string' } }, + required: ['query'], + }, + tags: ['clisessions', 'search'], + searchBlob: + 'cliSessions.search Search the user CLI sessions by keyword. clisessions search query', + }, + 'user.getBalance': { + path: 'user.getBalance', + kind: 'query', + summary: 'Get the user credit balance.', + inputSchema: {}, + tags: ['user', 'balance'], + searchBlob: 'user.getBalance Get the user credit balance. user getbalance balance credit', + }, + 'usageAnalytics.getSummary': { + path: 'usageAnalytics.getSummary', + kind: 'query', + summary: 'Get usage summary analytics for a scope.', + inputSchema: {}, + tags: ['usageanalytics', 'summary'], + searchBlob: + 'usageAnalytics.getSummary Get usage summary analytics for a scope. usageanalytics getsummary usage summary', + }, + 'organizations.members.listPublic': { + path: 'organizations.members.listPublic', + kind: 'query', + summary: 'List public members of an organization.', + inputSchema: {}, + tags: ['organizations', 'members'], + searchBlob: + 'organizations.members.listPublic List public members of an organization. organizations members listpublic list public', + }, +}; + +describe('tokenize', () => { + it('splits camelCase, dots, and prose into lowercase tokens', () => { + expect(tokenize('activeSessions.getToken')).toEqual(['active', 'sessions', 'get', 'token']); + expect(tokenize('List the user!')).toEqual(['list', 'the', 'user']); + expect(tokenize(' ')).toEqual([]); + }); +}); + +describe('searchCatalog', () => { + it('ranks an exact full path above a path-sequence match and single-token overlaps', async () => { + const results = await searchCatalog('organizations.list', { catalog: testCatalog }); + expect(results[0]?.path).toBe('organizations.list'); + // exact path match beats plain token overlap; a row with no query token + // in its blob drops out entirely + const scores = Object.fromEntries(results.map(row => [row.path, row.score])); + expect(scores['organizations.list']).toBeGreaterThan( + scores['organizations.members.listPublic'] + ); + expect('user.getBalance' in scores).toBe(false); + }); + + it('weights a contiguous query sequence in the path above scattered single-token hits', async () => { + // "list public" is a contiguous sequence in organizations.members.listPublic + // and only scattered tokens elsewhere. + const results = await searchCatalog('list public', { catalog: testCatalog }); + expect(results[0]?.path).toBe('organizations.members.listPublic'); + }); + + it('is deterministic: equal scores tie-break by path ascending', async () => { + // both rows hit only the token "list" at the same overlap score + const a = await searchCatalog('list', { catalog: testCatalog }); + const b = await searchCatalog('list', { catalog: testCatalog }); + expect(a.map(row => row.path)).toEqual(b.map(row => row.path)); + expect(a.length).toBeGreaterThan(1); + expect(a.every(row => row.score === a[0]?.score)).toBe(true); + expect(a[0]?.path).toBe('organizations.list'); + expect(a[1]?.path).toBe('organizations.members.listPublic'); + }); + + it('honors limit and returns the shape {path, kind, summary, tags, score}', async () => { + const results = await searchCatalog('list', { catalog: testCatalog, limit: 1 }); + expect(results).toHaveLength(1); + expect(Object.keys(results[0]!).sort()).toEqual(['kind', 'path', 'score', 'summary', 'tags']); + expect(results[0]).toMatchObject({ kind: 'query' }); + }); + + it('returns zero rows for a query that matches nothing (empty state, not an error)', async () => { + expect(await searchCatalog('zzqqx nonexistent', { catalog: testCatalog })).toEqual([]); + }); + + it('returns zero rows for a blank query', async () => { + expect(await searchCatalog(' ', { catalog: testCatalog })).toEqual([]); + }); + + it('defaults the semantic hook to no candidates', async () => { + expect(await noSemanticCandidates('anything', 10)).toEqual([]); + }); + + it('blends injected semantic candidates into the ranking (s3 hook)', async () => { + const semantic = vi.fn(async () => [{ path: 'user.getBalance', score: 1 }]); + const results = await searchCatalog('balance', { + catalog: testCatalog, + semanticCandidates: semantic, + }); + expect(semantic).toHaveBeenCalledWith('balance', 10); + expect(results[0]?.path).toBe('user.getBalance'); + // lexical 10 (full overlap) + semantic 1*5 + expect(results[0]?.score).toBeCloseTo(15); + }); + + it('admits a semantic-only row and ignores candidates outside the catalog', async () => { + const results = await searchCatalog('zzqqx', { + catalog: testCatalog, + semanticCandidates: async () => [ + { path: 'usageAnalytics.getSummary', score: 0.9 }, + { path: 'not.in.catalog', score: 1 }, + ], + }); + expect(results).toHaveLength(1); + expect(results[0]?.path).toBe('usageAnalytics.getSummary'); + }); + + it('ranks every token/exact hit above a semantic-only hit (requirement 1)', async () => { + // A nine-token query: three rows match exactly one token ("user"), scoring + // the minimum lexical score. A full-similarity semantic-only candidate + // (no lexical overlap at all) must stay below that weakest lexical hit. + const longQuery = 'refund invoice export csv quarterly revenue breakdown user report'; + const results = await searchCatalog(longQuery, { + catalog: testCatalog, + semanticCandidates: async () => [{ path: 'usageAnalytics.getSummary', score: 1 }], + }); + expect(results[results.length - 1]?.path).toBe('usageAnalytics.getSummary'); + const semanticOnly = results.find(row => row.path === 'usageAnalytics.getSummary'); + const lexicalScores = results + .filter(row => row.path !== 'usageAnalytics.getSummary') + .map(row => row.score); + expect(lexicalScores.length).toBe(3); + expect(semanticOnly?.score).toBeLessThan(Math.min(...lexicalScores)); + }); + + it('degrades to token-only results with a logged note when semantic search fails', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + const results = await searchCatalog('balance', { + catalog: testCatalog, + semanticCandidates: async () => { + throw new Error('Vectorize unavailable'); + }, + }); + expect(results.length).toBeGreaterThan(0); + expect(results.map(row => row.path)).toContain('user.getBalance'); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('semantic search degraded to token-only results') + ); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('Vectorize unavailable')); + } finally { + warn.mockRestore(); + } + }); +}); diff --git a/services/kilo-mcp/src/search.ts b/services/kilo-mcp/src/search.ts new file mode 100644 index 0000000000..9a9e738ea7 --- /dev/null +++ b/services/kilo-mcp/src/search.ts @@ -0,0 +1,152 @@ +import type { Catalog, CatalogRow, SearchResult, SemanticCandidates } from './types'; + +/** Default number of search rows returned when the caller omits `limit`. */ +export const DEFAULT_SEARCH_LIMIT = 10; + +/** + * Hybrid-ready scoring weights. A single-token overlap contributes at most + * OVERLAP_WEIGHT; a contiguous query-token sequence found in the endpoint's + * own path scores above that; an exact full-path match scores above the + * sequence hit. Semantic (Vectorize) scores are blended in additively at + * SEMANTIC_WEIGHT times the candidate's 0..1 similarity; rows admitted by + * semantics alone are rescaled below the smallest score a lexical hit can + * reach (requirement 1: any token/exact hit outranks a semantic-only hit). + */ +const OVERLAP_WEIGHT = 10; +const PATH_SEQUENCE_BONUS = 50; +const EXACT_PATH_BONUS = 100; +const SEMANTIC_WEIGHT = 5; + +/** s2 ships without Vectorize: the kNN hook defaults to "no semantic candidates". */ +export const noSemanticCandidates: SemanticCandidates = async () => []; + +/** + * Splits identifiers and prose into comparable lowercase tokens: camelCase + * boundaries ("activeSessions" -> active, sessions), dots, and any other + * non-alphanumeric separator. + */ +export function tokenize(text: string): string[] { + return text + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter(token => token.length > 0); +} + +function isContiguousSequence(needles: string[], haystack: string[]): boolean { + if (needles.length === 0 || needles.length > haystack.length) return false; + outer: for (let start = 0; start + needles.length <= haystack.length; start += 1) { + for (let offset = 0; offset < needles.length; offset += 1) { + if (haystack[start + offset] !== needles[offset]) continue outer; + } + return true; + } + return false; +} + +function lexicalScore( + queryTokens: string[], + normalizedQuery: string, + row: CatalogRow, + blobTokens: Set +): number { + const uniqueQuery = new Set(queryTokens); + let matched = 0; + for (const token of uniqueQuery) { + if (blobTokens.has(token)) matched += 1; + } + const overlap = uniqueQuery.size === 0 ? 0 : matched / uniqueQuery.size; + let score = overlap * OVERLAP_WEIGHT; + // A sequence bonus needs at least two tokens; a lone token is a plain + // single-token hit and must not outrank a real path-sequence match. + if (queryTokens.length >= 2 && isContiguousSequence(queryTokens, tokenize(row.path))) { + score += PATH_SEQUENCE_BONUS; + } + if (normalizedQuery.length > 0 && normalizedQuery === row.path.toLowerCase()) { + score += EXACT_PATH_BONUS; + } + return score; +} + +/** + * Token-overlap search over the bundled catalog, deterministic: rows are + * ordered by score descending, then by path ascending. Rows with a zero score + * are dropped. The `semanticCandidates` hook is where s3 plugs in Vectorize + * kNN; its 0..1 scores are blended in additively. + */ +export async function searchCatalog( + query: string, + options: { + catalog: Catalog; + limit?: number; + semanticCandidates?: SemanticCandidates; + } +): Promise { + const { catalog, semanticCandidates = noSemanticCandidates } = options; + const limit = Math.max(1, Math.floor(options.limit ?? DEFAULT_SEARCH_LIMIT)); + const queryTokens = tokenize(query); + const normalizedQuery = query.trim().toLowerCase(); + if (queryTokens.length === 0) return []; + + type ScoredRow = SearchResult & { blobTokens: Set }; + const rows: ScoredRow[] = []; + const byPath = new Map(); + for (const row of Object.values(catalog)) { + const blobTokens = new Set(tokenize(row.searchBlob)); + const score = lexicalScore(queryTokens, normalizedQuery, row, blobTokens); + if (score <= 0) continue; + const scored: ScoredRow = { + path: row.path, + kind: row.kind, + summary: row.summary, + tags: row.tags, + score, + blobTokens, + }; + rows.push(scored); + byPath.set(row.path, scored); + } + + // Blend in semantic candidates. A semantic hit on a row the lexical pass + // missed is admitted at a score strictly below the token band: the smallest + // lexical score reachable for this query is OVERLAP_WEIGHT / unique tokens + // (one token matched), so a semantic-only row is scaled to half of that at + // full similarity and stays below every token/exact hit. An injection or + // Vectorize failure degrades to token-only results with a logged note — + // search must keep serving (retryable unhappy state). + let candidates: Array<{ path: string; score: number }> = []; + try { + candidates = await semanticCandidates(query, limit); + } catch (error) { + console.warn( + `[kilo-mcp] semantic search degraded to token-only results: ${ + error instanceof Error ? error.message : String(error) + }` + ); + } + const minLexicalScore = OVERLAP_WEIGHT / Math.max(1, new Set(queryTokens).size); + for (const candidate of candidates) { + const row = catalog[candidate.path]; + if (!row) continue; + const existing = byPath.get(row.path); + if (existing) { + existing.score += candidate.score * SEMANTIC_WEIGHT; + } else { + const admitted: ScoredRow = { + path: row.path, + kind: row.kind, + summary: row.summary, + tags: row.tags, + score: candidate.score * minLexicalScore * 0.5, + blobTokens: new Set(), + }; + if (admitted.score > 0) { + rows.push(admitted); + byPath.set(row.path, admitted); + } + } + } + + rows.sort((a, b) => (b.score !== a.score ? b.score - a.score : a.path.localeCompare(b.path))); + return rows.map(({ blobTokens: _blobTokens, ...result }) => result).slice(0, limit); +} diff --git a/services/kilo-mcp/src/sql.d.ts b/services/kilo-mcp/src/sql.d.ts new file mode 100644 index 0000000000..3b71ad932e --- /dev/null +++ b/services/kilo-mcp/src/sql.d.ts @@ -0,0 +1,8 @@ +/** + * `.sql` imports are text at the Worker edge (esbuild's text loader) and raw + * strings under Vitest (see the `raw-sql` plugin in vitest.config.ts). + */ +declare module '*.sql' { + const content: string; + export default content; +} diff --git a/services/kilo-mcp/src/store/oauth-store.test.ts b/services/kilo-mcp/src/store/oauth-store.test.ts new file mode 100644 index 0000000000..b8904dc5ad --- /dev/null +++ b/services/kilo-mcp/src/store/oauth-store.test.ts @@ -0,0 +1,489 @@ +/// +import { DatabaseSync } from 'node:sqlite'; +import { beforeAll, describe, expect, it, vi } from 'vitest'; +import type { NewRefreshToken } from './oauth-store'; + +// `cloudflare:workers` does not exist under plain node vitest; the DO under +// test only extends its DurableObject base, so a stub base class is enough. +// Hoist-safe: the factory closes over nothing. +vi.mock('cloudflare:workers', () => ({ + DurableObject: class { + ctx: unknown; + env: unknown; + constructor(ctx: unknown, env: unknown) { + this.ctx = ctx; + this.env = env; + } + }, +})); + +const { KiloMcpOAuthStore } = await import('./oauth-store'); + +// Test support, inlined: a fake `DurableObjectStorage` whose `sql.exec` +// delegates to a real `node:sqlite` database, so these tests run the REAL +// drizzle durable-sqlite driver, the REAL generated migration SQL, and real +// SQLite semantics inside plain node vitest. +type CursorRow = Record; + +function toSqliteParam(value: unknown): string | number | bigint | null | Uint8Array { + if (value === undefined) return null; + if (typeof value === 'boolean') return value ? 1 : 0; + return value as string | number | bigint | Uint8Array | null; +} + +function sqlExec(db: DatabaseSync, query: string, ...params: unknown[]) { + const rows = db.prepare(query).all(...params.map(toSqliteParam)) as CursorRow[]; + const arrays = rows.map(row => Object.values(row)); + let index = 0; + const iterator = { + next: (): IteratorResult => + index < rows.length + ? { value: rows[index++], done: false } + : { value: undefined as never, done: true }, + }; + return { + toArray: () => rows, + one: () => rows[0], + raw: () => ({ toArray: () => arrays, one: () => arrays[0] }), + next: () => iterator.next(), + [Symbol.iterator]: () => iterator, + }; +} + +/** A `DurableObjectState`-shaped fake for constructing the DO under test. */ +function createFakeDoState(db: DatabaseSync) { + const kv = new Map(); + return { + storage: { + sql: { + exec: (query: string, ...params: unknown[]) => sqlExec(db, query, ...params), + }, + transactionSync: (callback: () => T): T => callback(), + get: async (key: string) => kv.get(key), + put: async (key: string, value: unknown) => { + kv.set(key, value); + }, + getAlarm: async () => null as number | Date | null, + setAlarm: async (_time: number | Date | string) => {}, + }, + blockConcurrencyWhile: (callback: () => Promise): Promise => callback(), + }; +} + +const NOW = '2026-09-09T12:00:00.000Z'; +const LATER = '2026-09-09T12:05:00.000Z'; +const EXPIRED = '2026-09-09T11:00:00.000Z'; + +function createStore(db: DatabaseSync): InstanceType { + return new KiloMcpOAuthStore(createFakeDoState(db) as never, {} as never); +} + +describe('KiloMcpOAuthStore (real drizzle durable-sqlite over node:sqlite)', () => { + let db: DatabaseSync; + let store: InstanceType; + + beforeAll(async () => { + db = new DatabaseSync(':memory:'); + store = createStore(db); + }); + + describe('migration tracking', () => { + it('applies the v1 schema and records it in __drizzle_migrations', () => { + const tables = db + .prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name") + .all() as Array<{ name: string }>; + expect(tables.map(t => t.name)).toEqual( + expect.arrayContaining([ + '__drizzle_migrations', + 'oauth_clients', + 'oauth_codes', + 'oauth_refresh_tokens', + 'oauth_revoked_jtis', + ]) + ); + const applied = db.prepare('SELECT COUNT(*) AS n FROM __drizzle_migrations').get() as { + n: number; + }; + expect(applied.n).toBe(2); + }); + + it('a second DO instance over the same storage does not re-apply the migration', async () => { + createStore(db); + const applied = db.prepare('SELECT COUNT(*) AS n FROM __drizzle_migrations').get() as { + n: number; + }; + expect(applied.n).toBe(2); + }); + }); + + describe('clients', () => { + it('persists and retrieves a registration; unknown ids return null', async () => { + await store.registerClient({ + clientId: 'c-1', + redirectUris: ['https://a.test/cb', 'http://localhost:1/cb'], + clientName: 'CLI', + createdAt: NOW, + }); + expect(await store.getClient('c-1')).toEqual({ + clientId: 'c-1', + redirectUris: ['https://a.test/cb', 'http://localhost:1/cb'], + clientName: 'CLI', + createdAt: NOW, + }); + expect(await store.getClient('ghost')).toBeNull(); + }); + + it('rejects a duplicate client_id (primary key)', async () => { + await expect( + store.registerClient({ + clientId: 'c-1', + redirectUris: ['https://a.test/cb'], + clientName: 'dup', + createdAt: NOW, + }) + ).rejects.toThrow(); + }); + }); + + describe('codes: TTL + single use', () => { + const codeInput = { + code: 'code-1', + clientId: 'c-1', + redirectUri: 'https://a.test/cb', + codeChallenge: 'challenge-value-000000000000000000000000000000', + resource: 'https://mcp.test/mcp', + scope: 'mcp', + state: 'st', + deviceAuthCode: 'PAIR-1', + createdAt: NOW, + expiresAt: LATER, + }; + + it('creates a pending record and approves it exactly once', async () => { + await store.createCode(codeInput); + expect((await store.getCode('code-1'))?.status).toBe('pending'); + expect( + await store.approveCode('PAIR-1', { kiloUserId: 'u-1', organizationId: 'o-1' }, NOW) + ).toBe(true); + // already approved — a second approval changes nothing + expect( + await store.approveCode('PAIR-1', { kiloUserId: 'u-2', organizationId: null }, NOW) + ).toBe(false); + const approved = await store.getCode('code-1'); + expect(approved?.kiloUserId).toBe('u-1'); + expect(approved?.organizationId).toBe('o-1'); + }); + + it('consumes the code atomically and rejects reuse', async () => { + const consumed = await store.consumeCode('code-1', NOW); + expect(consumed).toMatchObject({ code: 'code-1', status: 'used', kiloUserId: 'u-1' }); + expect(await store.consumeCode('code-1', LATER)).toBeNull(); + }); + + it('refuses to consume an expired code', async () => { + await store.createCode({ ...codeInput, code: 'code-expired', deviceAuthCode: 'PAIR-X' }); + // Approved while still alive (11:00 < expiresAt 12:05), redeemed after expiry. + await store.approveCode('PAIR-X', { kiloUserId: 'u-1', organizationId: null }, EXPIRED); + expect(await store.consumeCode('code-expired', LATER)).toBeNull(); + expect((await store.getCode('code-expired'))?.status).toBe('approved'); + }); + + it('refuses to consume a pending (unapproved) code', async () => { + await store.createCode({ ...codeInput, code: 'code-pending', deviceAuthCode: 'PAIR-P' }); + expect(await store.consumeCode('code-pending', NOW)).toBeNull(); + }); + + it('enforces the unique device_auth_code index', async () => { + // code-1 already holds device_auth_code PAIR-1. + await expect(store.createCode({ ...codeInput, code: 'code-dup-device' })).rejects.toThrow(); + }); + }); + + describe('pairing approval + denial (s6)', () => { + const pairInput = { + code: 's6-code-1', + clientId: 'c-1', + redirectUri: 'https://a.test/cb', + codeChallenge: 'challenge-value-000000000000000000000000000000', + resource: 'https://mcp.test/mcp', + scope: 'mcp', + state: null, + deviceAuthCode: 'PAIR-S6', + createdAt: NOW, + expiresAt: LATER, + }; + + it('records the approved pairing without changing the status (org comes later)', async () => { + await store.createCode(pairInput); + expect( + await store.recordPairingApproval( + 'PAIR-S6', + { kiloUserId: 'u-9', kiloToken: 'kilo-s6' }, + NOW + ) + ).toBe(true); + const record = await store.getCode('s6-code-1'); + expect(record).toMatchObject({ + status: 'pending', + kiloUserId: 'u-9', + organizationId: null, + kiloToken: 'kilo-s6', + }); + }); + + it('the first approval wins: a second poll can never overwrite the stored credential', async () => { + await store.recordPairingApproval( + 'PAIR-S6', + { kiloUserId: 'u-other', kiloToken: 'kilo-stolen' }, + NOW + ); + const record = await store.getCode('s6-code-1'); + expect(record).toMatchObject({ kiloUserId: 'u-9', kiloToken: 'kilo-s6' }); + }); + + it('refuses to record for unknown, expired, or non-pending pairings', async () => { + expect( + await store.recordPairingApproval('PAIR-GHOST', { kiloUserId: 'u', kiloToken: 't' }, NOW) + ).toBe(false); + await store.createCode({ ...pairInput, code: 's6-expired', deviceAuthCode: 'PAIR-S6X' }); + expect( + await store.recordPairingApproval('PAIR-S6X', { kiloUserId: 'u', kiloToken: 't' }, LATER) + ).toBe(false); + await store.approveCode('PAIR-S6X', { kiloUserId: 'u', organizationId: null }, NOW); + expect( + await store.recordPairingApproval('PAIR-S6X', { kiloUserId: 'u', kiloToken: 't' }, NOW) + ).toBe(false); + }); + + it('approveCode keeps the recorded Kilo token', async () => { + await store.createCode({ ...pairInput, code: 's6-code-2', deviceAuthCode: 'PAIR-S6-2' }); + await store.recordPairingApproval( + 'PAIR-S6-2', + { kiloUserId: 'u-9', kiloToken: 'kilo-s6' }, + NOW + ); + expect( + await store.approveCode('PAIR-S6-2', { kiloUserId: 'u-9', organizationId: 'o-9' }, NOW) + ).toBe(true); + expect(await store.getCode('s6-code-2')).toMatchObject({ + status: 'approved', + organizationId: 'o-9', + kiloToken: 'kilo-s6', + }); + }); + + it('denyCode moves a pending pairing to denied exactly once', async () => { + await store.createCode({ ...pairInput, code: 's6-deny', deviceAuthCode: 'PAIR-DENY' }); + expect(await store.denyCode('PAIR-DENY', NOW)).toBe(true); + expect((await store.getCode('s6-deny'))?.status).toBe('denied'); + expect(await store.denyCode('PAIR-DENY', NOW)).toBe(false); + expect(await store.denyCode('PAIR-GHOST', NOW)).toBe(false); + }); + }); + + describe('getKiloToken (forwarding credential, s6)', () => { + const grant = ( + id: string, + createdAt: string, + overrides: Partial = {} + ): NewRefreshToken => ({ + id, + tokenHash: `${id}${'0'.repeat(60)}`.slice(0, 64), + clientId: 'c-k', + kiloUserId: 'u-k', + organizationId: null, + kiloToken: `kilo-${id}`, + resource: 'https://mcp.test/mcp', + scope: 'mcp', + createdAt, + expiresAt: '2099-01-01T00:00:00.000Z', + ...overrides, + }); + + it('returns the newest live grant for (user, client)', async () => { + await store.saveRefreshToken(grant('g-old', NOW)); + await store.saveRefreshToken(grant('g-new', LATER)); + expect(await store.getKiloToken('u-k', 'c-k', NOW)).toBe('kilo-g-new'); + }); + + it('skips revoked and expired grants and other identities', async () => { + expect(await store.getKiloToken('ghost-user', 'c-k', NOW)).toBeNull(); + expect(await store.getKiloToken('u-k', 'ghost-client', NOW)).toBeNull(); + await store.rotateRefreshToken('g-new', grant('g-rot', '2098-01-01T00:00:00.000Z'), NOW); + // rotation revoked g-new; the rotated row carries the credential forward + expect(await store.getKiloToken('u-k', 'c-k', NOW)).toBe('kilo-g-rot'); + expect(await store.getKiloToken('u-k', 'c-k', '2099-01-02T00:00:00.000Z')).toBeNull(); + }); + + it('a grant without a Kilo token never surfaces a stale one', async () => { + await store.saveRefreshToken( + grant('g-legacy', NOW, { + kiloToken: null, + kiloUserId: 'u-legacy', + clientId: 'c-legacy', + tokenHash: 'f'.repeat(64), + }) + ); + expect(await store.getKiloToken('u-legacy', 'c-legacy', NOW)).toBeNull(); + }); + }); + + describe('refresh tokens: hashed + rotation', () => { + const tokenInput = { + id: 'rt-1', + tokenHash: 'a'.repeat(64), + clientId: 'c-1', + kiloUserId: 'u-1', + organizationId: 'o-1', + kiloToken: 'kilo-tok-rt-1', + resource: 'https://mcp.test/mcp', + scope: 'mcp', + createdAt: NOW, + expiresAt: LATER, + }; + + it('stores and retrieves by hash only', async () => { + await store.saveRefreshToken(tokenInput); + expect(await store.getRefreshTokenByHash('a'.repeat(64))).toMatchObject({ + id: 'rt-1', + revokedAt: null, + }); + expect(await store.getRefreshTokenByHash('b'.repeat(64))).toBeNull(); + }); + + it('rotates: revokes the old row and inserts the new one', async () => { + const rotated = await store.rotateRefreshToken( + 'rt-1', + { ...tokenInput, id: 'rt-2', tokenHash: 'b'.repeat(64) }, + NOW + ); + expect(rotated).toBe(true); + expect((await store.getRefreshTokenByHash('a'.repeat(64)))?.revokedAt).toBe(NOW); + expect((await store.getRefreshTokenByHash('b'.repeat(64)))?.revokedAt).toBeNull(); + }); + + it('refuses to rotate an already-revoked token', async () => { + expect( + await store.rotateRefreshToken( + 'rt-1', + { ...tokenInput, id: 'rt-3', tokenHash: 'c'.repeat(64) }, + NOW + ) + ).toBe(false); + expect(await store.getRefreshTokenByHash('c'.repeat(64))).toBeNull(); + }); + + it('refuses to rotate an expired token', async () => { + await store.saveRefreshToken({ + ...tokenInput, + id: 'rt-exp', + tokenHash: 'd'.repeat(64), + expiresAt: EXPIRED, + }); + expect( + await store.rotateRefreshToken( + 'rt-exp', + { ...tokenInput, id: 'rt-4', tokenHash: 'e'.repeat(64) }, + NOW + ) + ).toBe(false); + }); + + it('enforces the unique token hash', async () => { + await expect(store.saveRefreshToken({ ...tokenInput, id: 'rt-dup' })).rejects.toThrow(); + }); + }); + + describe('revokeGrant (stolen-grant revocation, RFC 9700)', () => { + const grantInput = (overrides: Partial = {}): NewRefreshToken => ({ + id: 'rg-1', + tokenHash: '1'.repeat(64), + clientId: 'c-rg', + kiloUserId: 'u-rg', + organizationId: 'o-rg', + kiloToken: 'kilo-rg', + resource: 'https://mcp.test/mcp', + scope: 'mcp', + createdAt: NOW, + expiresAt: LATER, + ...overrides, + }); + + it('revokes every live row of one grant identity and nothing else', async () => { + await store.saveRefreshToken(grantInput({ id: 'rg-a', tokenHash: '1'.repeat(64) })); + await store.saveRefreshToken(grantInput({ id: 'rg-b', tokenHash: '2'.repeat(64) })); + await store.saveRefreshToken( + grantInput({ id: 'rg-exp', tokenHash: '3'.repeat(64), expiresAt: EXPIRED }) + ); + await store.saveRefreshToken( + grantInput({ id: 'rg-user', tokenHash: '4'.repeat(64), kiloUserId: 'u-other' }) + ); + await store.saveRefreshToken( + grantInput({ id: 'rg-org', tokenHash: '5'.repeat(64), organizationId: null }) + ); + expect( + await store.revokeGrant( + { + clientId: 'c-rg', + kiloUserId: 'u-rg', + organizationId: 'o-rg', + resource: 'https://mcp.test/mcp', + }, + NOW + ) + ).toBe(2); + expect((await store.getRefreshTokenByHash('1'.repeat(64)))?.revokedAt).toBe(NOW); + expect((await store.getRefreshTokenByHash('2'.repeat(64)))?.revokedAt).toBe(NOW); + // Not the expired row, another user, or the org-less sibling grant. + expect((await store.getRefreshTokenByHash('3'.repeat(64)))?.revokedAt).toBeNull(); + expect((await store.getRefreshTokenByHash('4'.repeat(64)))?.revokedAt).toBeNull(); + expect((await store.getRefreshTokenByHash('5'.repeat(64)))?.revokedAt).toBeNull(); + // Idempotent: nothing live is left in the grant. + expect( + await store.revokeGrant( + { + clientId: 'c-rg', + kiloUserId: 'u-rg', + organizationId: 'o-rg', + resource: 'https://mcp.test/mcp', + }, + NOW + ) + ).toBe(0); + }); + }); + + describe('jti revocation registry', () => { + it('flags revoked jtis and tolerates double-revoke', async () => { + expect(await store.isJtiRevoked('jti-1')).toBe(false); + await store.revokeJti('jti-1', LATER, NOW); + expect(await store.isJtiRevoked('jti-1')).toBe(true); + await store.revokeJti('jti-1', LATER, NOW); + expect(await store.isJtiRevoked('jti-1')).toBe(true); + }); + }); + + describe('purgeExpired', () => { + it('drops rows past their own expiry and keeps live ones', async () => { + db.prepare( + 'INSERT INTO oauth_codes (code, client_id, redirect_uri, code_challenge, resource, scope, state, device_auth_code, status, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' + ).run( + 'purge-me', + 'c-1', + 'https://a.test/cb', + 'ch', + 'res', + 'mcp', + null, + 'PAIR-PURGE', + 'pending', + NOW, + EXPIRED + ); + const deleted = await store.purgeExpired(NOW); + expect(deleted).toBeGreaterThanOrEqual(1); + expect(await store.getCode('purge-me')).toBeNull(); + expect((await store.getCode('code-1'))?.code).toBe('code-1'); + }); + }); +}); diff --git a/services/kilo-mcp/src/store/oauth-store.ts b/services/kilo-mcp/src/store/oauth-store.ts new file mode 100644 index 0000000000..89d026e52d --- /dev/null +++ b/services/kilo-mcp/src/store/oauth-store.ts @@ -0,0 +1,525 @@ +import { DurableObject } from 'cloudflare:workers'; +import { and, desc, eq, gt, isNull, lt } from 'drizzle-orm'; +import { drizzle, type DrizzleSqliteDODatabase } from 'drizzle-orm/durable-sqlite'; +import { migrate } from 'drizzle-orm/durable-sqlite/migrator'; +import migrations from '../../drizzle/migrations'; +import { + oauthClients, + oauthCodes, + oauthRefreshTokens, + oauthRevokedJtis, +} from '../db/sqlite-schema'; + +/** + * KiloMcpOAuthStore — the OAuth 2.1 state for THIS MCP (clients, pairing + * codes, refresh tokens, revoked access-token jtis) in DO SQLite via Drizzle's + * query builder. Tracked migration: wrangler.jsonc `migrations` tag v1. + * + * The registry is one logical namespace (any worker instance must see any + * client/code), so a single SQLite DO instance (`getByName(STORE_INSTANCE_NAME)`) + * is the coordination atom. Volume is auth traffic only (DCR + token exchange), + * not MCP tool calls. + * + * Every write carries `nowIso` from the caller so expiry semantics are + * deterministic under test; the DO never reads the clock for authorization + * decisions. Rows are structured-clone-safe plain objects. + * + * Never log tokens, hashes, or identities from these records. + */ + +/** Fixed instance name for the single global registry. */ +const STORE_INSTANCE_NAME = 'kilo-mcp-oauth'; + +/** Interval between expired-row purges (DO alarm). */ +const PURGE_INTERVAL_MS = 6 * 60 * 60 * 1000; + +export type StoredClient = { + clientId: string; + redirectUris: string[]; + clientName: string; + createdAt: string; +}; + +export type NewOAuthClient = { + clientId: string; + redirectUris: string[]; + clientName: string; + createdAt: string; +}; + +export type OAuthCodeStatus = 'pending' | 'approved' | 'used' | 'denied'; + +export type OAuthCodeRecord = { + code: string; + clientId: string; + redirectUri: string; + codeChallenge: string; + resource: string; + scope: string; + state: string | null; + deviceAuthCode: string; + status: OAuthCodeStatus; + kiloUserId: string | null; + organizationId: string | null; + /** + * The Kilo API token from the approved device-auth pairing (s6). Set by + * recordPairingApproval while the code is still 'pending' (the org is not + * chosen yet); carried onto the refresh-token grant at exchange so /mcp can + * forward it. Never log it. + */ + kiloToken: string | null; + createdAt: string; + expiresAt: string; +}; + +export type NewOAuthCode = { + code: string; + clientId: string; + redirectUri: string; + codeChallenge: string; + resource: string; + scope: string; + state: string | null; + deviceAuthCode: string; + createdAt: string; + /** ISO timestamp; the record is exchangeable only until then. */ + expiresAt: string; +}; + +export type RefreshTokenRecord = { + id: string; + tokenHash: string; + clientId: string; + kiloUserId: string; + organizationId: string | null; + /** The Kilo API token this grant forwards to apps/web (s6). Never log it. */ + kiloToken: string | null; + resource: string; + scope: string; + createdAt: string; + expiresAt: string; + revokedAt: string | null; +}; + +export type NewRefreshToken = { + id: string; + tokenHash: string; + clientId: string; + kiloUserId: string; + organizationId: string | null; + kiloToken: string | null; + resource: string; + scope: string; + createdAt: string; + expiresAt: string; +}; + +/** + * The RPC surface the auth endpoints depend on. The DurableObjectStub of + * KiloMcpOAuthStore satisfies it structurally; unit tests pass an in-memory + * fake. Kept as an interface so handlers never touch the namespace binding. + */ +export interface OAuthStoreApi { + registerClient(input: NewOAuthClient): Promise; + getClient(clientId: string): Promise; + createCode(input: NewOAuthCode): Promise; + getCode(code: string): Promise; + /** + * Record the approved Kilo pairing while the code is still pending (s6): + * binds `{ kiloUserId, kiloToken }` without choosing an org. The upstream + * device-auth poll is single-use, so this write is what stops the status + * endpoint from ever polling apps/web twice for one pairing. The first + * writer wins; a second call never overwrites the stored token. + */ + recordPairingApproval( + deviceAuthCode: string, + identity: { kiloUserId: string; kiloToken: string }, + nowIso: string + ): Promise; + /** pending -> denied after the user denied the Kilo pairing upstream (s6). */ + denyCode(deviceAuthCode: string, nowIso: string): Promise; + /** pending -> approved with the Kilo identity; false when not exchangeable-pending. */ + approveCode( + deviceAuthCode: string, + identity: { kiloUserId: string; organizationId: string | null }, + nowIso: string + ): Promise; + /** Atomic single-use exchange: approved -> used. Null when the code is not exchangeable. */ + consumeCode(code: string, nowIso: string): Promise; + saveRefreshToken(input: NewRefreshToken): Promise; + getRefreshTokenByHash(tokenHash: string): Promise; + /** Atomic rotation: revoke the old token (if still valid) and insert the new one. */ + rotateRefreshToken(oldId: string, input: NewRefreshToken, nowIso: string): Promise; + /** + * Revoke every live refresh token of one grant — (client, user, org, + * resource) — in one write. The replay of a rotated-away token is evidence + * the grant was stolen (RFC 9700 §2.2.2), so the thief's newer rotation must + * die with the replay. Returns the number of rows revoked. + */ + revokeGrant( + grant: { + clientId: string; + kiloUserId: string; + organizationId: string | null; + resource: string; + }, + nowIso: string + ): Promise; + /** + * The Kilo API token to forward for a verified MCP identity (s6): the newest + * live grant for (user, client). Null when the user must reconnect. + */ + getKiloToken(kiloUserId: string, clientId: string, nowIso: string): Promise; + revokeJti(jti: string, tokenExpiresAt: string, nowIso: string): Promise; + isJtiRevoked(jti: string): Promise; + /** Housekeeping: drop rows past their own expiry. Returns deleted row count. */ + purgeExpired(nowIso: string): Promise; +} + +function rowToClient(row: typeof oauthClients.$inferSelect): StoredClient { + return { + clientId: row.client_id, + redirectUris: JSON.parse(row.redirect_uris) as string[], + clientName: row.client_name, + createdAt: row.created_at, + }; +} + +function rowToCode(row: typeof oauthCodes.$inferSelect): OAuthCodeRecord { + return { + code: row.code, + clientId: row.client_id, + redirectUri: row.redirect_uri, + codeChallenge: row.code_challenge, + resource: row.resource, + scope: row.scope, + state: row.state, + deviceAuthCode: row.device_auth_code, + status: row.status, + kiloUserId: row.kilo_user_id, + organizationId: row.organization_id, + kiloToken: row.kilo_token, + createdAt: row.created_at, + expiresAt: row.expires_at, + }; +} + +function rowToRefreshToken(row: typeof oauthRefreshTokens.$inferSelect): RefreshTokenRecord { + return { + id: row.id, + tokenHash: row.token_hash, + clientId: row.client_id, + kiloUserId: row.kilo_user_id, + organizationId: row.organization_id, + kiloToken: row.kilo_token, + resource: row.resource, + scope: row.scope, + createdAt: row.created_at, + expiresAt: row.expires_at, + revokedAt: row.revoked_at, + }; +} + +export class KiloMcpOAuthStore extends DurableObject implements OAuthStoreApi { + private readonly db: DrizzleSqliteDODatabase; + + constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env); + this.db = drizzle(ctx.storage); + void ctx.blockConcurrencyWhile(async () => { + await migrate(this.db, migrations); + if ((await ctx.storage.getAlarm()) === null) { + await ctx.storage.setAlarm(Date.now() + PURGE_INTERVAL_MS); + } + }); + } + + async registerClient(input: NewOAuthClient): Promise { + this.db + .insert(oauthClients) + .values({ + client_id: input.clientId, + redirect_uris: JSON.stringify(input.redirectUris), + client_name: input.clientName, + created_at: input.createdAt, + }) + .run(); + } + + async getClient(clientId: string): Promise { + const row = this.db + .select() + .from(oauthClients) + .where(eq(oauthClients.client_id, clientId)) + .get(); + return row ? rowToClient(row) : null; + } + + async createCode(input: NewOAuthCode): Promise { + this.db + .insert(oauthCodes) + .values({ + code: input.code, + client_id: input.clientId, + redirect_uri: input.redirectUri, + code_challenge: input.codeChallenge, + resource: input.resource, + scope: input.scope, + state: input.state, + device_auth_code: input.deviceAuthCode, + status: 'pending', + created_at: input.createdAt, + expires_at: input.expiresAt, + }) + .run(); + } + + async getCode(code: string): Promise { + const row = this.db.select().from(oauthCodes).where(eq(oauthCodes.code, code)).get(); + return row ? rowToCode(row) : null; + } + + async recordPairingApproval( + deviceAuthCode: string, + identity: { kiloUserId: string; kiloToken: string }, + nowIso: string + ): Promise { + // `kilo_user_id IS NULL` keeps this first-writer-wins: the upstream poll + // that returned the token is never re-run, and a racing second poll can + // not overwrite the stored credential. + const row = this.db + .update(oauthCodes) + .set({ kilo_user_id: identity.kiloUserId, kilo_token: identity.kiloToken }) + .where( + and( + eq(oauthCodes.device_auth_code, deviceAuthCode), + eq(oauthCodes.status, 'pending'), + isNull(oauthCodes.kilo_user_id), + gt(oauthCodes.expires_at, nowIso) + ) + ) + .returning({ code: oauthCodes.code }) + .get(); + return row !== undefined; + } + + async denyCode(deviceAuthCode: string, nowIso: string): Promise { + const row = this.db + .update(oauthCodes) + .set({ status: 'denied' }) + .where( + and( + eq(oauthCodes.device_auth_code, deviceAuthCode), + eq(oauthCodes.status, 'pending'), + gt(oauthCodes.expires_at, nowIso) + ) + ) + .returning({ code: oauthCodes.code }) + .get(); + return row !== undefined; + } + + async approveCode( + deviceAuthCode: string, + identity: { kiloUserId: string; organizationId: string | null }, + nowIso: string + ): Promise { + const row = this.db + .update(oauthCodes) + .set({ + status: 'approved', + kilo_user_id: identity.kiloUserId, + organization_id: identity.organizationId, + }) + .where( + and( + eq(oauthCodes.device_auth_code, deviceAuthCode), + eq(oauthCodes.status, 'pending'), + gt(oauthCodes.expires_at, nowIso) + ) + ) + .returning({ code: oauthCodes.code }) + .get(); + return row !== undefined; + } + + async consumeCode(code: string, nowIso: string): Promise { + const row = this.db + .update(oauthCodes) + .set({ status: 'used' }) + .where( + and( + eq(oauthCodes.code, code), + eq(oauthCodes.status, 'approved'), + gt(oauthCodes.expires_at, nowIso) + ) + ) + .returning() + .get(); + return row ? rowToCode(row) : null; + } + + async saveRefreshToken(input: NewRefreshToken): Promise { + this.db + .insert(oauthRefreshTokens) + .values({ + id: input.id, + token_hash: input.tokenHash, + client_id: input.clientId, + kilo_user_id: input.kiloUserId, + organization_id: input.organizationId, + kilo_token: input.kiloToken, + resource: input.resource, + scope: input.scope, + created_at: input.createdAt, + expires_at: input.expiresAt, + }) + .run(); + } + + async getRefreshTokenByHash(tokenHash: string): Promise { + const row = this.db + .select() + .from(oauthRefreshTokens) + .where(eq(oauthRefreshTokens.token_hash, tokenHash)) + .get(); + return row ? rowToRefreshToken(row) : null; + } + + async rotateRefreshToken( + oldId: string, + input: NewRefreshToken, + nowIso: string + ): Promise { + const revoked = this.db + .update(oauthRefreshTokens) + .set({ revoked_at: nowIso }) + .where( + and( + eq(oauthRefreshTokens.id, oldId), + isNull(oauthRefreshTokens.revoked_at), + gt(oauthRefreshTokens.expires_at, nowIso) + ) + ) + .returning({ id: oauthRefreshTokens.id }) + .get(); + if (revoked === undefined) return false; + this.db + .insert(oauthRefreshTokens) + .values({ + id: input.id, + token_hash: input.tokenHash, + client_id: input.clientId, + kilo_user_id: input.kiloUserId, + organization_id: input.organizationId, + kilo_token: input.kiloToken, + resource: input.resource, + scope: input.scope, + created_at: input.createdAt, + expires_at: input.expiresAt, + }) + .run(); + return true; + } + + async revokeGrant( + grant: { + clientId: string; + kiloUserId: string; + organizationId: string | null; + resource: string; + }, + nowIso: string + ): Promise { + const rows = this.db + .update(oauthRefreshTokens) + .set({ revoked_at: nowIso }) + .where( + and( + eq(oauthRefreshTokens.client_id, grant.clientId), + eq(oauthRefreshTokens.kilo_user_id, grant.kiloUserId), + eq(oauthRefreshTokens.resource, grant.resource), + // organization_id is nullable; a null-org grant matches only its own rows. + grant.organizationId === null + ? isNull(oauthRefreshTokens.organization_id) + : eq(oauthRefreshTokens.organization_id, grant.organizationId), + isNull(oauthRefreshTokens.revoked_at), + gt(oauthRefreshTokens.expires_at, nowIso) + ) + ) + .returning({ id: oauthRefreshTokens.id }) + .all(); + return rows.length; + } + + async getKiloToken(kiloUserId: string, clientId: string, nowIso: string): Promise { + const row = this.db + .select({ kiloToken: oauthRefreshTokens.kilo_token }) + .from(oauthRefreshTokens) + .where( + and( + eq(oauthRefreshTokens.kilo_user_id, kiloUserId), + eq(oauthRefreshTokens.client_id, clientId), + isNull(oauthRefreshTokens.revoked_at), + gt(oauthRefreshTokens.expires_at, nowIso) + ) + ) + .orderBy(desc(oauthRefreshTokens.created_at)) + .limit(1) + .get(); + return row?.kiloToken ?? null; + } + + async revokeJti(jti: string, tokenExpiresAt: string, nowIso: string): Promise { + this.db + .insert(oauthRevokedJtis) + .values({ jti, expires_at: tokenExpiresAt, revoked_at: nowIso }) + .onConflictDoNothing() + .run(); + } + + async isJtiRevoked(jti: string): Promise { + const row = this.db + .select({ jti: oauthRevokedJtis.jti }) + .from(oauthRevokedJtis) + .where(eq(oauthRevokedJtis.jti, jti)) + .get(); + return row !== undefined; + } + + async purgeExpired(nowIso: string): Promise { + const expiredCodes = this.db + .delete(oauthCodes) + .where(lt(oauthCodes.expires_at, nowIso)) + .returning({ code: oauthCodes.code }) + .all().length; + const expiredRefreshTokens = this.db + .delete(oauthRefreshTokens) + .where(lt(oauthRefreshTokens.expires_at, nowIso)) + .returning({ id: oauthRefreshTokens.id }) + .all().length; + const expiredJtis = this.db + .delete(oauthRevokedJtis) + .where(lt(oauthRevokedJtis.expires_at, nowIso)) + .returning({ jti: oauthRevokedJtis.jti }) + .all().length; + return expiredCodes + expiredRefreshTokens + expiredJtis; + } + + /** One alarm per DO: purge rows past their own expiry, then reschedule. */ + async alarm(): Promise { + await this.purgeExpired(new Date().toISOString()); + await this.ctx.storage.setAlarm(Date.now() + PURGE_INTERVAL_MS); + } +} + +/** Repo DO convention: a single stub helper so callers never touch the namespace directly. */ +export function getKiloMcpOAuthStoreStub(env: Env): OAuthStoreApi { + const namespace = env.KILO_MCP_OAUTH_STORE; + if (!namespace) { + throw new Error( + 'KILO_MCP_OAUTH_STORE is not bound for this worker environment (wrangler.jsonc durable_objects).' + ); + } + return namespace.getByName(STORE_INSTANCE_NAME); +} diff --git a/services/kilo-mcp/src/types.ts b/services/kilo-mcp/src/types.ts new file mode 100644 index 0000000000..ed00c3ae1d --- /dev/null +++ b/services/kilo-mcp/src/types.ts @@ -0,0 +1,76 @@ +/** + * Shared types for the kilo-mcp worker. The catalog is dumped and committed by + * apps/web/src/scripts/mcp-catalog (see dump.ts); this slice bundles it as a + * static artifact (`import catalog from '../catalog.json'`). + */ + +/** One published tRPC query, as recorded in services/kilo-mcp/catalog.json. */ +export type CatalogRow = { + path: string; + kind: 'query'; + summary: string; + /** Published JSON Schema (draft 2020-12) of the procedure input, `{}` when it takes none. */ + inputSchema: Record; + tags: string[]; + searchBlob: string; +}; + +/** The whole catalog: keyed by procedure path. */ +export type Catalog = Record; + +/** Credentials forwarded to apps/web; apps/web resolves identity and org membership. */ +export type ForwardedAuth = { + /** + * The raw `Authorization` header value to pass through. With s6 + * enforcement this is the Kilo API token behind the verified MCP token + * (apps/web cannot verify the worker's own JWT); only the unconfigured- + * worker passthrough and tests carry a caller-supplied bearer. + */ + authorization: string; + /** + * Value of the organization header. With a verified MCP token this is the + * token's org claim — a caller-supplied header is never consulted. + */ + organizationId?: string; + /** + * Set when the bearer was verified as an MCP access token issued by this + * worker: the identity the token is bound to (s6). + */ + mcpIdentity?: { + kiloUserId: string; + organizationId: string | null; + clientId: string; + expiresAt: number; + }; +}; + +/** A search hit returned by the search tool. */ +export type SearchResult = { + path: string; + kind: CatalogRow['kind']; + summary: string; + tags: string[]; + score: number; +}; + +/** + * Injectable Vectorize kNN hook (filled by s3). Returns extra candidates with + * semantic scores keyed by catalog path; defaults to none. + */ +export type SemanticCandidates = ( + query: string, + limit: number +) => Promise>; + +/** Error whose fields map onto a JSON-RPC error response. */ +export class JsonRpcFailure extends Error { + readonly code: number; + readonly data?: Record; + + constructor(code: number, message: string, data?: Record) { + super(message); + this.name = 'JsonRpcFailure'; + this.code = code; + this.data = data; + } +} diff --git a/services/kilo-mcp/tsconfig.json b/services/kilo-mcp/tsconfig.json new file mode 100644 index 0000000000..a8f8e49f7e --- /dev/null +++ b/services/kilo-mcp/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "lib": ["ES2022"], + "types": ["./worker-configuration.d.ts"], + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "esModuleInterop": true, + "strict": true, + "skipLibCheck": true, + "isolatedModules": true, + "noEmit": true + }, + "include": ["**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/services/kilo-mcp/vitest.config.ts b/services/kilo-mcp/vitest.config.ts new file mode 100644 index 0000000000..5d431d278b --- /dev/null +++ b/services/kilo-mcp/vitest.config.ts @@ -0,0 +1,31 @@ +import { readFileSync } from 'node:fs'; +import { defineConfig, type Plugin } from 'vitest/config'; + +/** Serve `.sql` imports as raw text so tests run the real DO migrations. */ +function rawSql(): Plugin { + return { + name: 'raw-sql', + enforce: 'pre', + load(id) { + if (id.endsWith('.sql')) { + return `export default ${JSON.stringify(readFileSync(id, 'utf8'))};`; + } + return null; + }, + }; +} + +export default defineConfig({ + plugins: [rawSql()], + test: { + name: 'unit', + globals: true, + environment: 'node', + include: ['src/**/*.test.ts'], + coverage: { + provider: 'v8', + reporter: ['text', 'json', 'html'], + exclude: ['node_modules/', 'dist/', '**/*.test.ts'], + }, + }, +}); diff --git a/services/kilo-mcp/worker-configuration.d.ts b/services/kilo-mcp/worker-configuration.d.ts new file mode 100644 index 0000000000..793c6397b1 --- /dev/null +++ b/services/kilo-mcp/worker-configuration.d.ts @@ -0,0 +1,15295 @@ +/* eslint-disable */ +// Generated by Wrangler by running `wrangler types` (hash: 92b3a7808ca3d786fe11eb9e1c9e4893) +// Runtime types generated with workerd@1.20260828.1 2025-09-01 nodejs_compat +interface __BaseEnv_Env { + VECTORIZE: VectorizeIndex; + AI: Ai; + WEB_BASE_URL: "http://localhost:3000" | "https://app.kilo.ai"; + KILO_MCP_OAUTH_STORE: DurableObjectNamespace; + MCP_TOKEN_SECRET?: string; +} +declare namespace Cloudflare { + interface GlobalProps { + mainModule: typeof import("./src/index"); + durableNamespaces: "KiloMcpOAuthStore"; + } + interface DevEnv { + VECTORIZE: VectorizeIndex; + AI: Ai; + WEB_BASE_URL: "http://localhost:3000"; + KILO_MCP_OAUTH_STORE: DurableObjectNamespace; + } + interface Env extends __BaseEnv_Env {} +} +interface Env extends __BaseEnv_Env {} +type StringifyValues> = { + [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; +}; +declare namespace NodeJS { + interface ProcessEnv extends StringifyValues> {} +} + +// Begin runtime types +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare var onmessage: never; +/** + * The **`DOMException`** interface represents an abnormal event (called an exception) that occurs as a result of calling a method or accessing a property of a web API. This is how error conditions are described in web APIs. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) + */ +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /** + * The **`message`** read-only property of the DOMException interface returns a string representing a message or description associated with the given error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) + */ + readonly message: string; + /** + * The **`name`** read-only property of the DOMException interface returns a string that contains one of the strings associated with an error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) + */ + readonly name: string; + /** + * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or 0 if none match. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; + get stack(): any; + set stack(value: any); +} +type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * + * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) + */ +interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /** + * The **`console.clear()`** static method clears the console if possible. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) + */ + clear(): void; + /** + * The **`console.count()`** static method logs the number of times that this particular call to count() has been called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) + */ + count(label?: string): void; + /** + * The **`console.countReset()`** static method resets counter used with console.count(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) + */ + countReset(label?: string): void; + /** + * The **`console.debug()`** static method outputs a message to the console at the "debug" log level. The message is only displayed to the user if the console is configured to display debug output. In most cases, the log level is configured within the console UI. This log level might correspond to the Debug or Verbose log level. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) + */ + debug(...data: any[]): void; + /** + * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. In browser consoles, the output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) + */ + dir(item?: any, options?: any): void; + /** + * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. If it is not possible to display as an element the JavaScript Object view is shown instead. The output is presented as a hierarchical listing of expandable nodes that let you see the contents of child nodes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) + */ + dirxml(...data: any[]): void; + /** + * The **`console.error()`** static method outputs a message to the console at the "error" log level. The message is only displayed to the user if the console is configured to display error output. In most cases, the log level is configured within the console UI. The message may be formatted as an error, with red colors and call stack information. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) + */ + error(...data: any[]): void; + /** + * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console.groupEnd() is called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) + */ + group(...data: any[]): void; + /** + * The **`console.groupCollapsed()`** static method creates a new inline group in the console. Unlike console.group(), however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) + */ + groupCollapsed(...data: any[]): void; + /** + * The **`console.groupEnd()`** static method exits the current inline group in the console. See Using groups in the console in the console documentation for details and examples. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) + */ + groupEnd(): void; + /** + * The **`console.info()`** static method outputs a message to the console at the "info" log level. The message is only displayed to the user if the console is configured to display info output. In most cases, the log level is configured within the console UI. The message may receive special formatting, such as a small "i" icon next to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) + */ + info(...data: any[]): void; + /** + * The **`console.log()`** static method outputs a message to the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) + */ + log(...data: any[]): void; + /** + * The **`console.table()`** static method displays tabular data as a table. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) + */ + table(tabularData?: any, properties?: string[]): void; + /** + * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. You give each timer a unique name, and may have up to 10,000 timers running on a given page. When you call console.timeEnd() with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) + */ + time(label?: string): void; + /** + * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console.time(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) + */ + timeEnd(label?: string): void; + /** + * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console.time(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) + */ + timeLog(label?: string, ...data: any[]): void; + /* The **`console.timeStamp()`** static method adds a single marker to the browser's Performance tool (Firefox bug 1387528, Chrome). This lets you correlate a point in your code with the other events recorded in the timeline, such as layout and paint events. */ + timeStamp(label?: string): void; + /** + * The **`console.trace()`** static method outputs a stack trace to the console. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) + */ + trace(...data: any[]): void; + /** + * The **`console.warn()`** static method outputs a warning message to the console at the "warning" log level. The message is only displayed to the user if the console is configured to display warning output. In most cases, the log level is configured within the console UI. The message may receive special formatting, such as yellow colors and a warning icon. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) + */ + warn(...data: any[]): void; +} +declare const console: Console; +type BufferSource = ArrayBufferView | ArrayBuffer; +type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + Cloudflare: Cloudflare; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + MessageChannel: typeof MessageChannel; + MessagePort: typeof MessagePort; + EventSource: typeof EventSource; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + TransformStreamDefaultController: typeof TransformStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; +declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; +/** + * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ +declare function btoa(data: string): string; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ +declare function atob(data: string): string; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ +declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ +declare function setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ +declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ +declare function setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ +declare function structuredClone(value: T, options?: StructuredSerializeOptions): T; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ +declare function reportError(error: any): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ +declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; +declare const self: ServiceWorkerGlobalScope; +/** +* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. +* The Workers runtime implements the full surface of this API, but with some differences in +* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) +* compared to those implemented in most browsers. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) +*/ +declare const crypto: Crypto; +/** +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ +declare const caches: CacheStorage; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/scheduler) */ +declare const scheduler: Scheduler; +/** +* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, +* as well as timing of subrequests and other operations. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) +*/ +declare const performance: Performance; +declare const Cloudflare: Cloudflare; +declare const origin: string; +declare const navigator: Navigator; +interface TestController { +} +interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; + readonly props: Props; + cache?: CacheContext; + readonly access?: CloudflareAccessContext; + tracing: Tracing; + abort(reason?: any): void; +} +type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; +type ExportedHandlerConnectHandler = (socket: Socket, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; +type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; +interface ExportedHandler { + fetch?: ExportedHandlerFetchHandler; + connect?: ExportedHandlerConnectHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +interface StructuredSerializeOptions { + transfer?: any[]; +} +declare abstract class Navigator { + sendBeacon(url: string, body?: BodyInit): boolean; + readonly userAgent: string; + readonly hardwareConcurrency: number; + readonly platform: string; + readonly language: string; + readonly languages: string[]; +} +interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; + readonly scheduledTime: number; +} +interface Cloudflare { + readonly compatibilityFlags: Record; +} +interface CachePurgeError { + code: number; + message: string; +} +interface CachePurgeResult { + success: boolean; + errors: CachePurgeError[]; +} +interface CachePurgeOptions { + tags?: string[]; + pathPrefixes?: string[]; + purgeEverything?: boolean; +} +interface CacheContext { + purge(options: CachePurgeOptions): Promise; +} +interface CloudflareAccessContext { + readonly aud: string; + getIdentity(): Promise; +} +declare abstract class ColoLocalActorNamespace { + get(actorId: string): Fetcher; +} +interface DurableObject { + fetch(request: Request): Response | Promise; + connect?(socket: Socket): void | Promise; + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; + webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; + webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +type DurableObjectStub = Fetcher & { + readonly id: DurableObjectId; + readonly name?: string; +}; +interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; + readonly jurisdiction?: string; +} +declare abstract class DurableObjectNamespace { + newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; + getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high" | "us"; +interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "apac-ne" | "apac-se" | "oc" | "afr" | "me"; +type DurableObjectRoutingMode = "primary-only"; +interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; + routingMode?: DurableObjectRoutingMode; +} +interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { +} +interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly props: Props; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + container?: Container; + facets: DurableObjectFacets; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; + abort(reason?: string, options?: DurableObjectAbortOptions): void; +} +interface DurableObjectTransaction { + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +interface DurableObjectStorage { + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + sql: SqlStorage; + kv: SyncKvStorage; + transactionSync(closure: () => T): T; + getCurrentBookmark(): Promise; + getBookmarkForTime(timestamp: number | Date): Promise; + onNextSessionRestoreBookmark(bookmark: string): Promise; +} +interface DurableObjectAbortOptions { + retryAlarm?: boolean; +} +interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +interface DurableObjectFacets { + get(name: string, getStartupOptions: () => FacetStartupOptions | Promise>): Fetcher; + abort(name: string, reason: any): void; + delete(name: string): void; + clone(src: string, dst: string): void; +} +interface FacetStartupOptions { + id?: DurableObjectId | string; + class: DurableObjectClass; +} +interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +/** + * The **`Event`** interface represents an event which takes place on an EventTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) + */ +declare class Event { + constructor(type: string, init?: EventInit); + /** + * The **`type`** read-only property of the Event interface returns a string containing the event's type. It is set when the event is constructed and is the name commonly used to refer to the specific event, such as click, load, or error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * The **`eventPhase`** read-only property of the Event interface indicates which phase of the event flow is currently being evaluated. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * The read-only **`composed`** property of the Event interface returns a boolean value which indicates whether or not the event will propagate across the shadow DOM boundary into the standard DOM. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * The read-only **`target`** property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) + */ + get target(): EventTarget | undefined; + /** + * The deprecated **`Event.srcElement`** is an alias for the Event.target property. Use Event.target instead. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * The **`isTrusted`** read-only property of the Event interface is a boolean value that is true when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and false when the event was dispatched via EventTarget.dispatchEvent(). The only exception is the click event, which initializes the isTrusted property to false in user agents. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * The **`cancelBubble`** property of the Event interface is deprecated. Use Event.stopPropagation() instead. Setting its value to true before returning from an event handler prevents propagation of the event. In later implementations, setting this to false does nothing. See Browser compatibility for details. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * The **`cancelBubble`** property of the Event interface is deprecated. Use Event.stopPropagation() instead. Setting its value to true before returning from an event handler prevents propagation of the event. In later implementations, setting this to false does nothing. See Browser compatibility for details. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * The **`stopImmediatePropagation()`** method of the Event interface prevents other listeners of the same event from being called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * The **`preventDefault()`** method of the Event interface tells the user agent that the event is being explicitly handled, so its default action, such as page scrolling, link navigation, or pasting text, should not be taken. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, see the preventDefault() method. It also does not prevent propagation to other event-handlers of the current element. If you want to stop those, see stopImmediatePropagation(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. This does not include nodes in shadow trees if the shadow root was created with its ShadowRoot.mode closed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +type EventListener = (event: EventType) => void; +interface EventListenerObject { + handleEvent(event: EventType): void; +} +type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +/** + * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) + */ +declare class EventTarget = Record> { + constructor(); + /** + * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; + /** + * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; + /** + * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +interface EventTargetEventListenerOptions { + capture?: boolean; +} +interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +/** + * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) + */ +declare class AbortController { + constructor(); + /** + * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get signal(): AbortSignal; + /** + * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. This is able to abort fetch requests, the consumption of any response bodies, or streams. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +/** + * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) + */ +declare abstract class AbortSignal extends EventTarget { + /** + * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an abort event). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) + */ + static abort(reason?: any): AbortSignal; + /** + * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) + */ + static timeout(delay: number): AbortSignal; + /** + * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. The returned abort signal is aborted when any of the input iterable abort signals are aborted. The abort reason will be set to the reason of the first signal that is aborted. If any of the given abort signals are already aborted then so will be the returned AbortSignal. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) + */ + static any(signals: AbortSignal[]): AbortSignal; + /** + * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (true) or not (false). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** + * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) + */ + get reason(): any; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** + * The **`throwIfAborted()`** method throws the signal's abort reason if the signal has been aborted; otherwise it does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) + */ + throwIfAborted(): void; +} +/** + * The **`Scheduler`** interface of the Prioritized Task Scheduling API provides methods for scheduling prioritized tasks. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Scheduler) + */ +interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +interface SchedulerWaitOptions { + signal?: AbortSignal; +} +/** + * The **`ExtendableEvent`** interface extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) + */ +declare abstract class ExtendableEvent extends Event { + /** + * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. It can also be used to detect whether that work was successful. In service workers, waitUntil() tells the browser that work is ongoing until the promise settles, and it shouldn't terminate the service worker if it wants that work to complete. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) + */ + waitUntil(promise: Promise): void; +} +/** + * The **`CustomEvent`** interface can be used to attach custom data to an event generated by an application. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) + */ +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +/** + * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) + */ +declare class Blob { + constructor(bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); + /** + * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) + */ + get size(): number; + /** + * The **`type`** read-only property of the Blob interface returns the MIME type of the file. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) + */ + get type(): string; + /** + * The **`slice()`** method of the Blob interface creates and returns a new Blob object which contains data from a subset of the blob on which it's called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) + */ + arrayBuffer(): Promise; + /** + * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) + */ + bytes(): Promise; + /** + * The **`text()`** method of the Blob interface returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) + */ + text(): Promise; + /** + * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the Blob. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) + */ + stream(): ReadableStream; +} +interface BlobOptions { + type?: string; +} +/** + * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) + */ +declare class File extends Blob { + constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions); + /** + * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) + */ + get name(): string; + /** + * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) + */ + get lastModified(): number; +} +interface FileOptions { + type?: string; + lastModified?: number; +} +/** +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ +declare abstract class CacheStorage { + /** + * The **`open()`** method of the CacheStorage interface returns a Promise that resolves to the Cache object matching the cacheName. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) + */ + open(cacheName: string): Promise; + readonly default: Cache; +} +/** +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ +declare abstract class Cache { + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ + delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ + match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ + put(request: RequestInfo | URL, response: Response): Promise; +} +interface CacheQueryOptions { + ignoreMethod?: boolean; +} +/** +* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. +* The Workers runtime implements the full surface of this API, but with some differences in +* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) +* compared to those implemented in most browsers. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) +*/ +declare abstract class Crypto { + /** + * The **`Crypto.subtle`** read-only property returns a SubtleCrypto which can then be used to perform low-level cryptographic operations. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** + * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) + */ + getRandomValues(buffer: T): T; + /** + * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +/** + * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) + */ +declare abstract class SubtleCrypto { + /** + * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) + */ + encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. It takes as arguments a key to decrypt with, some optional extra parameters, and the data to decrypt (also known as "ciphertext"). It returns a Promise which will be fulfilled with the decrypted data (also known as "plaintext"). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) + */ + decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) + */ + sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) + */ + verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`digest()`** method of the SubtleCrypto interface generates a digest of the given data, using the specified hash function. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) + */ + digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) + */ + generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /** + * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) + */ + deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /** + * The **`deriveBits()`** method of the SubtleCrypto interface can be used to derive an array of bits from a base key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) + */ + deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise; + /** + * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) + */ + importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /** + * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) + */ + exportKey(format: string, key: CryptoKey): Promise; + /** + * The **`wrapKey()`** method of the SubtleCrypto interface "wraps" a key. This means that it exports the key in an external, portable format, then encrypts the exported key. Wrapping a key helps protect it in untrusted environments, such as inside an otherwise unprotected data store or in transmission over an unprotected network. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) + */ + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise; + /** + * The **`unwrapKey()`** method of the SubtleCrypto interface "unwraps" a key. This means that it takes as its input a key that has been exported and then encrypted (also called "wrapped"). It decrypts the key and then imports it, returning a CryptoKey object that can be used in the Web Crypto API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) + */ + unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; +} +/** + * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods generateKey(), deriveKey(), importKey(), or unwrapKey(). + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) + */ +declare abstract class CryptoKey { + /** + * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. It can have the following values: + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) + */ + readonly type: string; + /** + * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) + */ + readonly extractable: boolean; + /** + * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) + */ + readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; + /** + * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) + */ + readonly usages: string[]; +} +interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: (ArrayBuffer | ArrayBufferView); + iterations?: number; + hash?: (string | SubtleCryptoHashAlgorithm); + $public?: CryptoKey; + info?: (ArrayBuffer | ArrayBufferView); +} +interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: (ArrayBuffer | ArrayBufferView); + additionalData?: (ArrayBuffer | ArrayBufferView); + tagLength?: number; + counter?: (ArrayBuffer | ArrayBufferView); + length?: number; + label?: (ArrayBuffer | ArrayBufferView); +} +interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + modulusLength?: number; + publicExponent?: (ArrayBuffer | ArrayBufferView); + length?: number; + namedCurve?: string; +} +interface SubtleCryptoHashAlgorithm { + name: string; +} +interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + length?: number; + namedCurve?: string; + compressed?: boolean; +} +interface SubtleCryptoSignAlgorithm { + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + dataLength?: number; + saltLength?: number; +} +interface CryptoKeyKeyAlgorithm { + name: string; +} +interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | ArrayBufferView; + hash?: CryptoKeyKeyAlgorithm; +} +interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream { + constructor(algorithm: string | SubtleCryptoHashAlgorithm, options?: DigestStreamOptions); + readonly digest: Promise; + get bytesWritten(): number | bigint; +} +interface DigestStreamOptions { + toWellFormed?: boolean; +} +/** + * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as UTF-8, ISO-8859-2, or GBK. A decoder takes an array of bytes as input and returns a JavaScript string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) + */ +declare class TextDecoder { + constructor(label?: string, options?: TextDecoderConstructorOptions); + /** + * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +/** + * The **`TextEncoder`** interface enables you to encode a JavaScript string using UTF-8. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) + */ +declare class TextEncoder { + constructor(); + /** + * The **`TextEncoder.encode()`** method takes a string as input, and returns a Uint8Array containing the string encoded using UTF-8. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns an object indicating the progress of the encoding. This is potentially more performant than the encode() method — especially when the target buffer is a view into a Wasm heap. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult; + get encoding(): string; +} +interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +interface TextDecoderDecodeOptions { + stream: boolean; +} +interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +/** + * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) + */ +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /** + * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) + */ + get filename(): string; + /** + * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) + */ + get message(): string; + /** + * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) + */ + get lineno(): number; + /** + * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) + */ + get colno(): number; + /** + * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) + */ + get error(): any; +} +interface ErrorEventErrorEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +/** + * The **`MessageEvent`** interface represents a message received by a target object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) + */ +declare class MessageEvent extends Event { + constructor(type: string, initializer?: MessageEventInit); + /** + * The **`data`** read-only property of the MessageEvent interface represents the data sent by the message emitter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) + */ + readonly data: any; + /** + * The **`origin`** read-only property of the MessageEvent interface is a string representing the origin of the message emitter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) + */ + readonly origin: string | null; + /** + * The **`lastEventId`** read-only property of the MessageEvent interface is a string representing a unique ID for the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) + */ + readonly lastEventId: string; + /** + * The **`source`** read-only property of the MessageEvent interface is a MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) + */ + readonly source: MessagePort | null; + /** + * The **`ports`** read-only property of the MessageEvent interface is an array of MessagePort objects containing all MessagePort objects sent with the message, in order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) + */ + readonly ports: MessagePort[]; +} +interface MessageEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + data?: any; + origin?: string; + lastEventId?: string; + source?: MessagePort; + ports?: MessagePort[]; +} +/** + * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. These events are particularly useful for telemetry and debugging purposes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) + */ +declare abstract class PromiseRejectionEvent extends Event { + /** + * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript Promise which was rejected. You can examine the event's PromiseRejectionEvent.reason property to learn why the promise was rejected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) + */ + readonly promise: Promise; + /** + * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). This in theory provides information about why the promise was rejected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) + */ + readonly reason: any; +} +/** + * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the fetch(), XMLHttpRequest.send() or navigator.sendBeacon() methods. It uses the same format a form would use if the encoding type were set to "multipart/form-data". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) + */ +declare class FormData { + constructor(); + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string | Blob): void; + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string): void; + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: Blob, filename?: string): void; + /** + * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a FormData object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) + */ + delete(name: string): void; + /** + * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) + */ + get(name: string): (File | string) | null; + /** + * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a FormData object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) + */ + getAll(name: string): (File | string)[]; + /** + * The **`has()`** method of the FormData interface returns whether a FormData object contains a certain key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) + */ + has(name: string): boolean; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string | Blob): void; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string): void; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: Blob, filename?: string): void; + entries(): IterableIterator<[ + key: string, + value: File | string + ]>; + keys(): IterableIterator; + values(): IterableIterator<(File | string)>; + forEach(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: File | string + ]>; +} +interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string | ReadableStream | Response, options?: ContentOptions): Element; + after(content: string | ReadableStream | Response, options?: ContentOptions): Element; + prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; + append(content: string | ReadableStream | Response, options?: ContentOptions): Element; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +interface EndTag { + name: string; + before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + remove(): EndTag; +} +interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string | ReadableStream | Response, options?: ContentOptions): Text; + after(content: string | ReadableStream | Response, options?: ContentOptions): Text; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; + remove(): Text; +} +interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +/** + * This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) + */ +declare abstract class FetchEvent extends ExtendableEvent { + /** + * The **`request`** read-only property of the FetchEvent interface returns the Request that triggered the event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) + */ + readonly request: Request; + /** + * The **`respondWith()`** method of FetchEvent prevents the browser's default fetch handling, and allows you to provide a promise for a Response yourself. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) + */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +type HeadersInit = Headers | Iterable> | Record; +/** + * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request's headers. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) + */ +declare class Headers { + constructor(init?: HeadersInit); + /** + * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn't exist in the Headers object, it returns null. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) + */ + get(name: string): string | null; + getAll(name: string): string[]; + /** + * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. This allows Headers objects to handle having multiple Set-Cookie headers, which wasn't possible prior to its implementation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) + */ + getSetCookie(): string[]; + /** + * The **`has()`** method of the Headers interface returns a boolean stating whether a Headers object contains a certain header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) + */ + has(name: string): boolean; + /** + * The **`set()`** method of the Headers interface sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) + */ + set(name: string, value: string): void; + /** + * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a Headers object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) + */ + append(name: string, value: string): void; + /** + * The **`delete()`** method of the Headers interface deletes a header from the current Headers object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) + */ + delete(name: string): void; + forEach(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void; + entries(): IterableIterator<[ + key: string, + value: string + ]>; + keys(): IterableIterator; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: string + ]>; +} +type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData; +declare abstract class Body { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ + get body(): ReadableStream | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ + get bodyUsed(): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ + arrayBuffer(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ + bytes(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ + text(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ + json(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ + formData(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ + blob(): Promise; +} +/** + * The **`Response`** interface of the Fetch API represents the response to a request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) + */ +declare var Response: { + prototype: Response; + new (body?: BodyInit | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; + json(any: any, maybeInit?: (ResponseInit | Response)): Response; +}; +/** + * The **`Response`** interface of the Fetch API represents the response to a request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) + */ +interface Response extends Body { + /** + * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) + */ + clone(): Response; + /** + * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) + */ + status: number; + /** + * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) + */ + statusText: string; + /** + * The **`headers`** read-only property of the Response interface contains the Headers object associated with the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) + */ + headers: Headers; + /** + * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) + */ + ok: boolean; + /** + * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) + */ + redirected: boolean; + /** + * The **`url`** read-only property of the Response interface contains the URL of the response. The value of the url property will be the final URL obtained after any redirects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) + */ + url: string; + webSocket: WebSocket | null; + cf: any | undefined; + /** + * The **`type`** read-only property of the Response interface contains the type of the response. The type determines whether scripts are able to access the response body and headers. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) + */ + type: "default" | "error"; +} +interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: (WebSocket | null); + encodeBody?: "automatic" | "manual"; +} +type RequestInfo> = Request | string; +/** + * The **`Request`** interface of the Fetch API represents a resource request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) + */ +declare var Request: { + prototype: Request; + new >(input: RequestInfo | URL, init?: RequestInit): Request; +}; +/** + * The **`Request`** interface of the Fetch API represents a resource request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) + */ +interface Request> extends Body { + /** + * The **`clone()`** method of the Request interface creates a copy of the current Request object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) + */ + clone(): Request; + /** + * The **`method`** read-only property of the Request interface contains the request's method (GET, POST, etc.) + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + method: string; + /** + * The **`url`** read-only property of the Request interface contains the URL of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + url: string; + /** + * The **`headers`** read-only property of the Request interface contains the Headers object associated with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + headers: Headers; + /** + * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + redirect: string; + fetcher: Fetcher | null; + /** + * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + signal: AbortSignal; + cf?: Cf; + /** + * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + integrity: string; + /** + * The **`keepalive`** read-only property of the Request interface contains the request's keepalive setting (true or false), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + keepalive: boolean; + /** + * The **`cache`** read-only property of the Request interface contains the cache mode of the request. It controls how the request will interact with the browser's HTTP cache. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) + */ + cache?: "no-store" | "no-cache"; +} +interface RequestInit { + /* A string to set request's method. */ + method?: string; + /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /* A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: (Fetcher | null); + cf?: Cf; + /* A string indicating how the request will interact with the browser's cache to set request's cache. */ + cache?: "no-store" | "no-cache"; + /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /* An AbortSignal to set request's signal. */ + signal?: (AbortSignal | null); + encodeResponseBody?: "automatic" | "manual"; +} +type Service Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; +type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +type KVNamespaceListResult = { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; +} | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; +}; +interface KVNamespace { + get(key: Key, options?: Partial>): Promise; + get(key: Key, type: "text"): Promise; + get(key: Key, type: "json"): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"json">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; + get(key: Array, type: "text"): Promise>; + get(key: Array, type: "json"): Promise>; + get(key: Array, options?: Partial>): Promise>; + get(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>; + get(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>; + list(options?: KVNamespaceListOptions): Promise>; + put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise; + getWithMetadata(key: Key, options?: Partial>): Promise>; + getWithMetadata(key: Key, type: "text"): Promise>; + getWithMetadata(key: Key, type: "json"): Promise>; + getWithMetadata(key: Key, type: "arrayBuffer"): Promise>; + getWithMetadata(key: Key, type: "stream"): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"text">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"json">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"stream">): Promise>; + getWithMetadata(key: Array, type: "text"): Promise>>; + getWithMetadata(key: Array, type: "json"): Promise>>; + getWithMetadata(key: Array, options?: Partial>): Promise>>; + getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>>; + getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>>; + delete(key: Key): Promise; +} +interface KVNamespaceListOptions { + limit?: number; + prefix?: (string | null); + cursor?: (string | null); +} +interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: (any | null); +} +interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +type QueueContentType = "text" | "bytes" | "json" | "v8"; +interface Queue { + metrics(): Promise; + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; +} +interface QueueSendMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface QueueSendMetadata { + metrics: QueueSendMetrics; +} +interface QueueSendResponse { + metadata: QueueSendMetadata; +} +interface QueueSendBatchMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface QueueSendBatchMetadata { + metrics: QueueSendBatchMetrics; +} +interface QueueSendBatchResponse { + metadata: QueueSendBatchMetadata; +} +interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +interface QueueSendBatchOptions { + delaySeconds?: number; +} +interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +interface QueueMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface MessageBatchMetrics { + backlogCount: number; + backlogBytes: number; + oldestMessageTimestamp?: Date; +} +interface MessageBatchMetadata { + metrics: MessageBatchMetrics; +} +interface QueueRetryOptions { + delaySeconds?: number; +} +interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + readonly metadata: MessageBatchMetadata; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + readonly metadata: MessageBatchMetadata; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +interface R2Bucket { + head(key: string): Promise; + get(key: string, options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }): Promise; + get(key: string, options?: R2GetOptions): Promise; + put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }): Promise; + put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise; + createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + readonly ssecKeyMd5?: string; + writeHttpMetadata(headers: Headers): void; +} +interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + bytes(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +type R2Range = { + offset: number; + length?: number; +} | { + offset?: number; + length: number; +} | { + suffix: number; +}; +interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +interface R2GetOptions { + onlyIf?: (R2Conditional | Headers); + range?: (R2Range | Headers); + ssecKey?: (ArrayBuffer | string); +} +interface R2PutOptions { + onlyIf?: (R2Conditional | Headers); + httpMetadata?: (R2HTTPMetadata | Headers); + customMetadata?: Record; + md5?: ((ArrayBuffer | ArrayBufferView) | string); + sha1?: ((ArrayBuffer | ArrayBufferView) | string); + sha256?: ((ArrayBuffer | ArrayBufferView) | string); + sha384?: ((ArrayBuffer | ArrayBufferView) | string); + sha512?: ((ArrayBuffer | ArrayBufferView) | string); + storageClass?: string; + ssecKey?: (ArrayBuffer | string); +} +interface R2MultipartOptions { + httpMetadata?: (R2HTTPMetadata | Headers); + customMetadata?: Record; + storageClass?: string; + ssecKey?: (ArrayBuffer | string); +} +interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ({ + truncated: true; + cursor: string; +} | { + truncated: false; +}); +interface R2UploadPartOptions { + ssecKey?: (ArrayBuffer | string); +} +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +interface QueuingStrategy { + highWaterMark?: (number | bigint); + size?: (chunk: T) => number | bigint; +} +interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +interface UnderlyingSource { + type?: "" | undefined; + start?: (controller: ReadableStreamDefaultController) => void | Promise; + pull?: (controller: ReadableStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: (number | bigint); +} +interface Transformer { + readableType?: string; + writableType?: string; + start?: (controller: TransformStreamDefaultController) => void | Promise; + transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; + flush?: (controller: TransformStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. + * + * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. + * + * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. + * + * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. + * + * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. + */ + preventClose?: boolean; + signal?: AbortSignal; +} +type ReadableStreamReadResult = { + done: false; + value: R; +} | { + done: true; + value?: undefined; +}; +/** + * The **`ReadableStream`** interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +interface ReadableStream { + /** + * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) + */ + get locked(): boolean; + /** + * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) + */ + cancel(reason?: any): Promise; + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ + getReader(): ReadableStreamDefaultReader; + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** + * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) + */ + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + /** + * The **`pipeTo()`** method of the ReadableStream interface pipes the current ReadableStream to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * The **`tee()`** method of the ReadableStream interface tees the current readable stream, returning a two-element array containing the two resulting branches as new ReadableStream instances. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) + */ + tee(): [ + ReadableStream, + ReadableStream + ]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; +} +/** + * The **`ReadableStream`** interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare const ReadableStream: { + prototype: ReadableStream; + new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; +}; +/** + * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) + */ +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) + */ + read(): Promise>; + /** + * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) + */ + releaseLock(): void; +} +/** + * The **`ReadableStreamBYOBReader`** interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. It is used for efficient copying from underlying sources where the data is delivered as an "anonymous" sequence of bytes, such as files. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) + */ +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) + */ + read(view: T): Promise>; + /** + * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) + */ + releaseLock(): void; + readAtLeast(minElements: number, view: T): Promise>; +} +interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/** + * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a "pull request" for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) + */ +declare abstract class ReadableStreamBYOBRequest { + /** + * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) + */ + get view(): Uint8Array | null; + /** + * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) + */ + respond(bytesWritten: number): void; + /** + * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) + */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/** + * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. Default controllers are for streams that are not byte streams. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) + */ +declare abstract class ReadableStreamDefaultController { + /** + * The **`desiredSize`** read-only property of the ReadableStreamDefaultController interface returns the desired size required to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) + */ + close(): void; + /** + * The **`enqueue()`** method of the ReadableStreamDefaultController interface enqueues a given chunk in the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) + */ + enqueue(chunk?: R): void; + /** + * The **`error()`** method of the ReadableStreamDefaultController interface causes any future interactions with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) + */ + error(reason: any): void; +} +/** + * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. It allows control of the state and internal queue of a ReadableStream with an underlying byte source, and enables efficient zero-copy transfer of data from the underlying source to a consumer when the stream's internal queue is empty. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) + */ +declare abstract class ReadableByteStreamController { + /** + * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or null if there are no pending requests. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) + */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** + * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its "desired size". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) + */ + close(): void; + /** + * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is transferred into the stream's internal queues). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) + */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** + * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) + */ + error(reason: any): void; +} +/** + * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +declare abstract class WritableStreamDefaultController { + /** + * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) + */ + get signal(): AbortSignal; + /** + * The **`error()`** method of the WritableStreamDefaultController interface causes any future interactions with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) + */ + error(reason?: any): void; +} +/** + * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) + */ +declare abstract class TransformStreamDefaultController { + /** + * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) + */ + enqueue(chunk?: O): void; + /** + * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) + */ + error(reason: any): void; + /** + * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) + */ + terminate(): void; +} +interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream; +} +/** + * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) + */ +declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); + /** + * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the WritableStream is locked to a writer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) + */ + get locked(): boolean; + /** + * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) + */ + abort(reason?: any): Promise; + /** + * The **`close()`** method of the WritableStream interface closes the associated stream. All chunks written before this method is called are sent before the returned promise is fulfilled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) + */ + close(): Promise; + /** + * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) + */ + getWriter(): WritableStreamDefaultWriter; +} +/** + * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the WritableStream ensuring that no other streams can write to the underlying sink. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) + */ +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** + * The **`closed`** read-only property of the WritableStreamDefaultWriter interface returns a Promise that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) + */ + get closed(): Promise; + /** + * The **`ready`** read-only property of the WritableStreamDefaultWriter interface returns a Promise that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) + */ + get ready(): Promise; + /** + * The **`desiredSize`** read-only property of the WritableStreamDefaultWriter interface returns the desired size required to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`abort()`** method of the WritableStreamDefaultWriter interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) + */ + abort(reason?: any): Promise; + /** + * The **`close()`** method of the WritableStreamDefaultWriter interface closes the associated writable stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) + */ + close(): Promise; + /** + * The **`write()`** method of the WritableStreamDefaultWriter interface writes a passed chunk of data to a WritableStream and its underlying sink, then returns a Promise that resolves to indicate the success or failure of the write operation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) + */ + write(chunk?: W): Promise; + /** + * The **`releaseLock()`** method of the WritableStreamDefaultWriter interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) + */ + releaseLock(): void; +} +/** + * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain transform stream concept. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) + */ +declare class TransformStream { + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /** + * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this TransformStream. This stream emits the transformed output data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) + */ + get readable(): ReadableStream; + /** + * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this TransformStream. This stream accepts input data that will be transformed and emitted to the readable stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) + */ + get writable(): WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare class IdentityTransformStream extends TransformStream { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: (number | bigint); +} +interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +/** + * The **`CompressionStream`** interface of the Compression Streams API compresses a stream of data. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) + */ +declare class CompressionStream extends TransformStream { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +/** + * The **`DecompressionStream`** interface of the Compression Streams API decompresses a stream of data. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) + */ +declare class DecompressionStream extends TransformStream { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +/** + * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. It is the streaming equivalent of TextEncoder. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) + */ +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +/** + * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. It is the streaming equivalent of TextDecoder. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) + */ +declare class TextDecoderStream extends TransformStream { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +/** + * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) + */ +declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** + * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) + */ + get highWaterMark(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +/** + * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy) + */ +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** + * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) + */ + get highWaterMark(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. + */ + highWaterMark: number; +} +interface TracePreviewInfo { + id: string; + slug: string; + name: string; +} +interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +interface TraceItem { + readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemConnectEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly tailAttributes?: Record; + readonly preview?: TracePreviewInfo; + readonly durableObjectId?: string; + readonly outcome: string; + readonly executionModel: string; + readonly truncated: boolean; + readonly cpuTime: number; + readonly wallTime: number; +} +interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +interface TraceItemConnectEventInfo { +} +interface TraceItemCustomEventInfo { +} +interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; +} +interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; + readonly errorInfo?: (TraceLogErrorInfo | null)[]; +} +interface TraceLogErrorInfo { + name: string; + message: string; + stack?: string; +} +interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +/** + * The **`URL`** interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) + */ +declare class URL { + constructor(url: string | URL, base?: string | URL); + /** + * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) + */ + get origin(): string; + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ + get href(): string; + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ + set href(value: string); + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ + get protocol(): string; + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ + set protocol(value: string); + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. If the URL does not have a username, this property contains an empty string, "". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ + get username(): string; + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. If the URL does not have a username, this property contains an empty string, "". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ + set username(value: string); + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. If the URL does not have a password, this property contains an empty string, "". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ + get password(): string; + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. If the URL does not have a password, this property contains an empty string, "". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ + set password(value: string); + /** + * The **`host`** property of the URL interface is a string containing the host, which is the hostname, and then, if the port of the URL is nonempty, a ":", followed by the port of the URL. If the URL does not have a hostname, this property contains an empty string, "". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ + get host(): string; + /** + * The **`host`** property of the URL interface is a string containing the host, which is the hostname, and then, if the port of the URL is nonempty, a ":", followed by the port of the URL. If the URL does not have a hostname, this property contains an empty string, "". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ + set host(value: string); + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. If the URL does not have a hostname, this property contains an empty string, "". IPv4 and IPv6 addresses are normalized, such as stripping leading zeros, and domain names are converted to IDN. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ + get hostname(): string; + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. If the URL does not have a hostname, this property contains an empty string, "". IPv4 and IPv6 addresses are normalized, such as stripping leading zeros, and domain names are converted to IDN. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ + set hostname(value: string); + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. If the port is the default for the protocol (80 for ws: and http:, 443 for wss: and https:, and 21 for ftp:), this property contains an empty string, "". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ + get port(): string; + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. If the port is the default for the protocol (80 for ws: and http:, 443 for wss: and https:, and 21 for ftp:), this property contains an empty string, "". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ + set port(value: string); + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ + get pathname(): string; + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ + set pathname(value: string); + /** + * The **`search`** property of the URL interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the URL. If the URL does not have a search query, this property contains an empty string, "". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ + get search(): string; + /** + * The **`search`** property of the URL interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the URL. If the URL does not have a search query, this property contains an empty string, "". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ + set search(value: string); + /** + * The **`hash`** property of the URL interface is a string containing a "#" followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this property contains an empty string, "". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ + get hash(): string; + /** + * The **`hash`** property of the URL interface is a string containing a "#" followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this property contains an empty string, "". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ + set hash(value: string); + /** + * The **`searchParams`** read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) + */ + get searchParams(): URLSearchParams; + /** + * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as URL.toString(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) + */ + toJSON(): string; + /*function toString() { [native code] }*/ + toString(): string; + /** + * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) + */ + static canParse(url: string, base?: string): boolean; + /** + * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) + */ + static parse(url: string, base?: string): URL | null; + /** + * The **`createObjectURL()`** static method of the URL interface creates a string containing a blob URL pointing to the object given in the parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) + */ + static createObjectURL(object: File | Blob): string; + /** + * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling URL.createObjectURL(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) + */ + static revokeObjectURL(object_url: string): void; +} +/** + * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) + */ +declare class URLSearchParams { + constructor(init?: (Iterable> | Record | string)); + /** + * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) + */ + get size(): number; + /** + * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) + */ + append(name: string, value: string): void; + /** + * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) + */ + delete(name: string, value?: string): void; + /** + * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) + */ + get(name: string): string | null; + /** + * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) + */ + getAll(name: string): string[]; + /** + * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) + */ + has(name: string, value?: string): boolean; + /** + * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) + */ + set(name: string, value: string): void; + /** + * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns undefined. Key/value pairs are sorted by the values of the UTF-16 code units of the keys. This method uses a stable sorting algorithm (i.e., the relative order between key/value pairs with equal keys will be preserved). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) + */ + sort(): void; + entries(): IterableIterator<[ + key: string, + value: string + ]>; + keys(): IterableIterator; + values(): IterableIterator; + forEach(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void; + /*function toString() { [native code] }*/ + toString(): string; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: string + ]>; +} +/** + * The **`URLPattern`** interface of the URL Pattern API matches URLs or parts of URLs against a pattern. The pattern can contain capturing groups that extract parts of the matched URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern) + */ +declare class URLPattern { + constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions); + /** + * The **`protocol`** read-only property of the URLPattern interface is a string containing the pattern used to match the protocol part of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/protocol) + */ + get protocol(): string; + /** + * The **`username`** read-only property of the URLPattern interface is a string containing the pattern used to match the username part of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/username) + */ + get username(): string; + /** + * The **`password`** read-only property of the URLPattern interface is a string containing the pattern used to match the password part of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/password) + */ + get password(): string; + /** + * The **`hostname`** read-only property of the URLPattern interface is a string containing the pattern used to match the hostname part of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hostname) + */ + get hostname(): string; + /** + * The **`port`** read-only property of the URLPattern interface is a string containing the pattern used to match the port part of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/port) + */ + get port(): string; + /** + * The **`pathname`** read-only property of the URLPattern interface is a string containing the pattern used to match the pathname part of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/pathname) + */ + get pathname(): string; + /** + * The **`search`** read-only property of the URLPattern interface is a string containing the pattern used to match the search part of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/search) + */ + get search(): string; + /** + * The **`hash`** read-only property of the URLPattern interface is a string containing the pattern used to match the fragment part of a URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hash) + */ + get hash(): string; + /** + * The **`hasRegExpGroups`** read-only property of the URLPattern interface is a boolean indicating whether or not any of the URLPattern components contain regular expression capturing groups. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hasRegExpGroups) + */ + get hasRegExpGroups(): boolean; + /** + * The **`test()`** method of the URLPattern interface takes a URL string or object of URL parts, and returns a boolean indicating if the given input matches the current pattern. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/test) + */ + test(input?: (string | URLPatternInit), baseURL?: string): boolean; + /** + * The **`exec()`** method of the URLPattern interface takes a URL or object of URL parts, and returns either an object containing the results of matching the URL to the pattern, or null if the URL does not match the pattern. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/exec) + */ + exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null; +} +interface URLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +interface URLPatternComponentResult { + input: string; + groups: Record; +} +interface URLPatternResult { + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; +} +interface URLPatternOptions { + ignoreCase?: boolean; +} +/** + * A **`CloseEvent`** is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) + */ +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * The **`wasClean`** read-only property of the CloseEvent interface returns true if the connection closed cleanly. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +interface CloseEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + code?: number; + reason?: string; + wasClean?: boolean; +} +type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +/** + * The **`WebSocket`** object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) + */ +declare var WebSocket: { + prototype: WebSocket; + new (url: string, protocols?: (string[] | string)): WebSocket; + readonly READY_STATE_CONNECTING: number; + readonly CONNECTING: number; + readonly READY_STATE_OPEN: number; + readonly OPEN: number; + readonly READY_STATE_CLOSING: number; + readonly CLOSING: number; + readonly READY_STATE_CLOSED: number; + readonly CLOSED: number; +}; +/** + * The **`WebSocket`** object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) + */ +interface WebSocket extends EventTarget { + accept(options?: WebSocketAcceptOptions): void; + /** + * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of bufferedAmount by the number of bytes needed to contain the data. If the data can't be sent (for example, because it needs to be buffered but the buffer is full), the socket is closed automatically. The browser will throw an exception if you call send() when the connection is in the CONNECTING state. If you call send() when the connection is in the CLOSING or CLOSED states, the browser will silently discard the data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * The **`WebSocket.close()`** method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + /** + * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readyState: number; + /** + * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + url: string | null; + /** + * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object, or the empty string if no connection is established. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + protocol: string | null; + /** + * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. This is currently only the empty string or a list of extensions as negotiated by the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + extensions: string | null; + /** + * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) + */ + binaryType: "blob" | "arraybuffer"; +} +interface WebSocketAcceptOptions { + /** + * When set to `true`, receiving a server-initiated WebSocket Close frame will not + * automatically send a reciprocal Close frame, leaving the connection in a half-open + * state. This is useful for proxying scenarios where you need to coordinate closing + * both sides independently. Defaults to `false` when the + * `no_web_socket_half_open_by_default` compatibility flag is enabled. + */ + allowHalfOpen?: boolean; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +interface SqlStorage { + exec>(query: string, ...bindings: any[]): SqlStorageCursor; + get databaseSize(): number; + Cursor: typeof SqlStorageCursor; + Statement: typeof SqlStorageStatement; +} +declare abstract class SqlStorageStatement { +} +type SqlStorageValue = ArrayBuffer | string | number | null; +declare abstract class SqlStorageCursor> { + next(): { + done?: false; + value: T; + } | { + done: true; + value?: never; + }; + toArray(): T[]; + one(): T; + raw(): IterableIterator; + columnNames: string[]; + get rowsRead(): number; + get rowsWritten(): number; + [Symbol.iterator](): IterableIterator; +} +interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + get upgraded(): boolean; + get secureTransport(): "on" | "off" | "starttls"; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; + highWaterMark?: (number | bigint); +} +interface SocketAddress { + hostname: string; + port: number; +} +interface TlsOptions { + expectedServerHostname?: string; +} +interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +/** + * The **`EventSource`** interface is web content's interface to server-sent events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) + */ +declare class EventSource extends EventTarget { + constructor(url: string, init?: EventSourceEventSourceInit); + /** + * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void; + /** + * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + get url(): string; + /** + * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials(): boolean; + /** + * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null); + static readonly CONNECTING: number; + static readonly OPEN: number; + static readonly CLOSED: number; + static from(stream: ReadableStream): EventSource; +} +interface EventSourceEventSourceInit { + withCredentials?: boolean; + fetcher?: Fetcher; +} +interface ExecOutput { + readonly stdout: ArrayBuffer; + readonly stderr: ArrayBuffer; + readonly exitCode: number; +} +interface ContainerExecOptions { + cwd?: string; + env?: Record; + user?: string; + signal?: AbortSignal; + pty?: boolean | ContainerExecPtyOptions; + stdin?: ReadableStream | "pipe"; + stdout?: "pipe" | "ignore"; + stderr?: "pipe" | "ignore" | "combined"; +} +interface ContainerExecPtyOptions { + cols?: number; + rows?: number; +} +interface ExecProcess { + readonly stdin: WritableStream | null; + readonly stdout: ReadableStream | null; + readonly stderr: ReadableStream | null; + readonly pid: number; + readonly isPty: boolean; + readonly exitCode: Promise; + output(): Promise; + kill(signal?: number): void; + resize(cols: number, rows: number): void; +} +interface Container { + get running(): boolean; + start(options?: ContainerStartupOptions): void; + monitor(): Promise; + destroy(error?: any): Promise; + signal(signo: number): void; + getTcpPort(port: number): Fetcher; + setInactivityTimeout(durationMs: number | bigint): Promise; + interceptOutboundHttp(addr: string, binding: Fetcher): Promise; + interceptAllOutboundHttp(binding: Fetcher): Promise; + snapshotDirectory(options: ContainerDirectorySnapshotOptions): Promise; + snapshotContainer(options: ContainerSnapshotOptions): Promise; + interceptOutboundHttps(addr: string, binding: Fetcher): Promise; + exec(cmd: string[], options?: ContainerExecOptions): Promise; +} +interface ContainerDirectorySnapshot { + id: string; + size: number; + dir: string; + name?: string; +} +interface ContainerDirectorySnapshotOptions { + dir: string; + name?: string; +} +type ContainerDirectorySnapshotRestoreParams = { + snapshot: ContainerDirectorySnapshot; + mountPoint?: string; +} | { + snapshot?: undefined; + mountPoint: string; +}; +interface ContainerSnapshot { + id: string; + size: number; + name?: string; +} +interface ContainerSnapshotRestoreParams { + id: string; +} +interface ContainerSnapshotOptions { + name?: string; +} +type ContainerStartupOptions = { + entrypoint?: string[]; + enableInternet: boolean; + env?: Record; + instance?: "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4" | ContainerStartResources; + labels?: Record; + directorySnapshots?: ContainerDirectorySnapshotRestoreParams[]; +} & ({ + image: string; + containerSnapshot?: never; +} | { + image?: never; + containerSnapshot?: ContainerSnapshotRestoreParams; +}); +interface ContainerStartResources { + vcpu: number; + memoryMib: number; + diskMb: number; +} +/** + * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) + */ +declare abstract class MessagePort extends EventTarget { + /** + * The **`postMessage()`** method of the MessagePort interface sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) + */ + postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void; + /** + * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. This stops the flow of messages to that port. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) + */ + close(): void; + /** + * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. This method is only needed when using EventTarget.addEventListener; it is implied when using onmessage. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) + */ + start(): void; + get onmessage(): any | null; + set onmessage(value: any | null); +} +/** + * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel) + */ +declare class MessageChannel { + constructor(); + /** + * The **`port1`** read-only property of the MessageChannel interface returns the first port of the message channel — the port attached to the context that originated the channel. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) + */ + readonly port1: MessagePort; + /** + * The **`port2`** read-only property of the MessageChannel interface returns the second port of the message channel — the port attached to the context at the other end of the channel, which the message is initially sent to. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) + */ + readonly port2: MessagePort; +} +interface MessagePortPostMessageOptions { + transfer?: any[]; +} +type LoopbackForExport Rpc.EntrypointBranded) | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass> : T extends ExportedHandler ? LoopbackServiceStub : undefined; +type LoopbackServiceStub = Fetcher & (T extends CloudflareWorkersModule.WorkerEntrypoint ? (opts: { + props?: Props; +}) => Fetcher : (opts: { + props?: any; +}) => Fetcher); +type LoopbackDurableObjectClass = DurableObjectClass & (T extends CloudflareWorkersModule.DurableObject ? (opts: { + props?: Props; +}) => DurableObjectClass : (opts: { + props?: any; +}) => DurableObjectClass); +interface LoopbackDurableObjectNamespace extends DurableObjectNamespace { +} +interface LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace { +} +interface SyncKvStorage { + get(key: string): T | undefined; + list(options?: SyncKvListOptions): Iterable<[ + string, + T + ]>; + put(key: string, value: T): void; + delete(key: string): boolean; +} +interface SyncKvListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; +} +interface WorkerStub { + getEntrypoint(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; + getDurableObjectClass(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass; +} +interface WorkerStubEntrypointOptions { + props?: any; + limits?: workerdResourceLimits; +} +interface WorkerLoader { + get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; + load(code: WorkerLoaderWorkerCode): WorkerStub; +} +interface WorkerLoaderModule { + js?: string; + cjs?: string; + text?: string; + data?: ArrayBuffer; + json?: any; + py?: string; + wasm?: ArrayBuffer | ArrayBufferView | WebAssembly.Module; +} +interface WorkerLoaderWorkerCode { + compatibilityDate: string; + compatibilityFlags?: string[]; + allowExperimental?: boolean; + limits?: workerdResourceLimits; + mainModule: string; + modules: Record; + env?: any; + globalOutbound?: (Fetcher | null); + tails?: Fetcher[]; + streamingTails?: Fetcher[]; +} +interface workerdResourceLimits { + cpuMs?: number; + subRequests?: number; +} +/** +* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, +* as well as timing of subrequests and other operations. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) +*/ +declare abstract class Performance { + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ + get timeOrigin(): number; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ + now(): number; + /** + * The **`toJSON()`** method of the Performance interface is a serializer; it returns a JSON representation of the Performance object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON) + */ + toJSON(): object; +} +interface Tracing { + enterSpan(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T; + startActiveSpan(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T; + startSpan(name: string): Span; + Span: typeof Span; +} +declare abstract class Span { + get isTraced(): boolean; + setAttribute(key: string, value: boolean | number | string): this; + setAttributes(attributes: Record): this; + end(): void; +} +/** + * Represents the identity of a user authenticated via Cloudflare Access. + * This matches the result of calling /cdn-cgi/access/get-identity. + * + * The exact structure of the returned object depends on the identity provider + * configuration for the Access application. The fields below represent commonly + * available properties, but additional provider-specific fields may be present. + */ +interface CloudflareAccessIdentity extends Record { + /** The user's email address, if available from the identity provider. */ + email?: string; + /** The user's display name. */ + name?: string; + /** The user's unique identifier. */ + user_uuid?: string; + /** The Cloudflare account ID. */ + account_id?: string; + /** Login timestamp (Unix epoch seconds). */ + iat?: number; + /** The user's IP address at authentication time. */ + ip?: string; + /** Authentication methods used (e.g., "pwd"). */ + amr?: string[]; + /** Identity provider information. */ + idp?: { + id: string; + type: string; + }; + /** Geographic information about where the user authenticated. */ + geo?: { + country: string; + }; + /** Group memberships from the identity provider. */ + groups?: Array<{ + id: string; + name: string; + email?: string; + }>; + /** Device posture check results, keyed by check ID. */ + devicePosture?: Record; + /** True if the user connected via Cloudflare WARP. */ + is_warp?: boolean; + /** True if the user is authenticated via Cloudflare Gateway. */ + is_gateway?: boolean; +} +// ============================================================================ +// Agent Memory +// +// Public type surface for user Workers binding to an Agent Memory namespace. +// ============================================================================ +/** Memory type — every memory is classified into exactly one. */ +type AgentMemoryMemoryType = "fact" | "event" | "instruction" | "task"; +/** Search intensity for recall. */ +type AgentMemoryThinkingLevel = "low" | "medium" | "high"; +/** Response verbosity for recall. */ +type AgentMemoryResponseLength = "short" | "medium" | "long"; +/** A conversation message passed to ingest(). */ +interface AgentMemoryMessage { + role: "system" | "user" | "assistant"; + content: string; + /** Optional message timestamp. */ + timestamp?: Date; +} +/** Raw memory content passed to remember(). */ +interface AgentMemoryIncomingMemory { + /** Raw memory content. The service classifies and summarizes automatically. */ + content: string; + /** Optional session identifier to associate with this memory. */ + sessionId?: string | null | undefined; +} +/** A stored memory returned from remember(), get(), and delete(). */ +interface AgentMemoryMemory { + /** Memory ID. */ + id: string; + /** Memory type. */ + type: AgentMemoryMemoryType; + /** Text summary. */ + summary: string; + /** Memory text. */ + content: string; + /** Session that created this memory. */ + sessionId: string | null; + /** Memory creation time. */ + createdAt: Date; + /** Memory last-update time. */ + updatedAt: Date; +} +/** Single entry in a list() response. Same shape as Memory minus full content. */ +type AgentMemoryMemoryListEntry = Omit; +/** A scored memory candidate in a recall result. */ +interface AgentMemoryScoredCandidate { + /** Candidate ID. */ + id: string; + /** Text summary. */ + summary: string; + /** Session that created this candidate, when known. */ + sessionId: string | null; + /** Relevance score (higher is better). Comparable only within a single query. */ + score: number; +} +/** Options for the ingest() method. */ +interface AgentMemoryIngestOptions { + /** Session identifier to associate with memories created during ingestion. */ + sessionId?: string | null | undefined; +} +/** Options for the getSummary() method. */ +interface AgentMemoryGetSummaryOptions { + /** Session identifier to retrieve session summary for. */ + sessionId?: string | null | undefined; +} +/** Response from the getSummary() method. */ +interface AgentMemoryGetSummaryResponse { + /** Markdown summary. */ + summary: string; +} +/** + * Options for the recall() method. + * + * `referenceDate` accepts a Date object, an ISO-8601 date string + * (YYYY-MM-DD), or a full ISO-8601 datetime string. When provided, this + * date is used as "today" for resolving relative time references + * ("how many days ago", "last week") instead of the server's wall-clock time. + */ +interface AgentMemoryRecallOptions { + /** Recall intensity: "low" (default), "medium", or "high". */ + thinkingLevel?: AgentMemoryThinkingLevel; + /** Response verbosity: "short", "medium" (default), or "long". */ + responseLength?: AgentMemoryResponseLength; + /** Temporal anchor for date arithmetic. */ + referenceDate?: Date | string; +} +/** Response from the recall() method. */ +interface AgentMemoryRecallResult { + /** Number of memories retrieved. */ + count: number; + /** LLM-generated answer synthesizing the matching memories. */ + answer: string; + /** Matching memories ranked by relevance. */ + candidates: AgentMemoryScoredCandidate[]; +} +/** + * Options for the list() method. + * + * `cursor` is the opaque continuation token returned by the previous page; + * pass it back unchanged to fetch the next page. `sessionId` and `type` + * are exact-match filters; combining them is allowed. + */ +interface AgentMemoryListMemoriesOptions { + /** Maximum number of memories to return. Default 20, max 500. */ + limit?: number; + /** Opaque cursor from a previous page. */ + cursor?: string; + /** Exact-match session filter. */ + sessionId?: string; + /** Exact-match memory-type filter. */ + type?: AgentMemoryMemoryType; +} +/** Response from the list() method. */ +interface AgentMemoryListMemoriesResult { + memories: AgentMemoryMemoryListEntry[]; + /** Continuation cursor; absent when this page exhausted the result set. */ + cursor?: string; +} +/** + * A single Agent Memory profile, scoped to a profile name. + * + * Returned by {@link AgentMemoryNamespace.getProfile}. + */ +declare abstract class AgentMemoryProfile { + /** + * Retrieve a memory by ID. + * + * @param memoryId - ULID of the memory to retrieve. + * @throws if the memory does not exist. + */ + get(memoryId: string): Promise; + /** + * Delete a memory by ID. + * + * Removes the memory and any source messages linked by the memory's + * source message IDs. + * + * @param memoryId - ULID of the memory to delete. + * @throws if the memory does not exist. + */ + delete(memoryId: string): Promise; + /** + * Store a memory in this profile. The content is automatically classified, + * summarized, and indexed. + * + * @param memory - Raw memory content to persist. + */ + remember(memory: AgentMemoryIncomingMemory): Promise; + /** + * Extract memories from a conversation. + * + * @param messages - Conversation messages to extract memories from. + * @param options - Optional ingest options. + */ + ingest(messages: Iterable, options?: AgentMemoryIngestOptions): Promise; + /** + * Get a profile summary. + * + * @param options - Optional getSummary options. + */ + getSummary(options?: AgentMemoryGetSummaryOptions): Promise; + /** + * Recall memories in this profile. + * + * @param query - Recall query matched against memory content and keywords. + * @param options - Optional recall parameters. + * @returns Matching memories with relevance scores and a synthesized answer. + */ + recall(query: string, options?: AgentMemoryRecallOptions): Promise; + /** + * List active memories in this profile. + * + * Returns a paginated, filterable view of stored memories. Superseded + * versions are excluded. Use the returned `cursor` (when present) to + * fetch the next page. + * + * @param options - Optional pagination and filter options. + */ + list(options?: AgentMemoryListMemoriesOptions): Promise; + /** + * Soft-delete every memory and message in this profile that is tagged + * with `sessionId`. + * + * Idempotent: deleting a sessionId that has no rows is a no-op. + * + * @param sessionId - Session to delete. + */ + deleteSession(sessionId: string): Promise; +} +/** + * Namespace-level Agent Memory binding. + * + * Used as the type of an `env.MEMORY`-style binding backed by the Agent + * Memory product. + * + * @example + * ```ts + * export default { + * async fetch(_request: Request, env: Env): Promise { + * const profile = await env.MEMORY.getProfile("wrangler-e2e"); + * const summary = await profile.getSummary(); + * return Response.json(summary); + * }, + * }; + * ``` + */ +declare abstract class AgentMemoryNamespace { + /** + * Get a memory profile by name. Profiles are isolated by namespace and + * addressed by a compound key (namespaceId:profileName). + * + * @param profileName - Profile name (validated against naming rules). + * @returns RPC target for interacting with the profile. + */ + getProfile(profileName: string): Promise; + /** + * Soft-delete a profile and schedule deferred purge. Marks all + * memories and messages as deleted. + * + * @param profileName - Name of the profile to delete. + */ + deleteProfile(profileName: string): Promise; +} +// ============ AI Search Error Interfaces ============ +interface AiSearchInternalError extends Error { +} +interface AiSearchNotFoundError extends Error { +} +// ============ AI Search Common Types ============ +/** A single message in a conversation-style search or chat request. */ +type AiSearchMessage = { + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; +}; +/** + * Common shape for `ai_search_options` used by both single-instance and multi-instance requests. + * Contains retrieval, query rewrite, reranking, and cache sub-options. + */ +type AiSearchOptions = { + retrieval?: { + /** Which retrieval backend to use. Defaults to the instance's configured index_method. */ + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + /** Fusion method for combining vector + keyword results. */ + fusion_method?: 'max' | 'rrf'; + /** How keyword terms are combined: "and" = all terms must match, "or" = any term matches. */ + keyword_match_mode?: 'and' | 'or'; + /** Minimum similarity score (0-1) for a result to be included. Default 0.4. */ + match_threshold?: number; + /** Maximum number of results to return (1-50). Default 10. */ + max_num_results?: number; + /** Vectorize metadata filters applied to the search. */ + filters?: VectorizeVectorMetadataFilter; + /** Number of surrounding chunks to include for context (0-3). Default 0. */ + context_expansion?: number; + /** If true, return only item metadata without chunk text. */ + metadata_only?: boolean; + /** If true (default), return empty results on retrieval failure instead of throwing. */ + return_on_failure?: boolean; + /** Boost results by metadata field values. Max 3 entries. */ + boost_by?: Array<{ + field: string; + direction?: 'asc' | 'desc' | 'exists' | 'not_exists'; + }>; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + enabled?: boolean; + model?: string; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + [key: string]: unknown; + }; + cache?: { + enabled?: boolean; + cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes'; + }; + [key: string]: unknown; +}; +// ============ AI Search Request Types ============ +/** + * Request body for single-instance search. + * Exactly one of `query` or `messages` must be provided. + */ +type AiSearchSearchRequest = { + /** Simple query string. */ + query: string; + messages?: never; + ai_search_options?: AiSearchOptions; +} | { + query?: never; + /** Conversation-style input. At least one user message with non-empty content is required. */ + messages: AiSearchMessage[]; + ai_search_options?: AiSearchOptions; +}; +type AiSearchChatCompletionsRequest = { + messages: AiSearchMessage[]; + model?: string; + stream?: boolean; + ai_search_options?: AiSearchOptions; + [key: string]: unknown; +}; +// ============ AI Search Multi-Instance Types (Namespace-Scoped) ============ +/** `ai_search_options` shape for multi-instance requests — requires `instance_ids`. */ +type AiSearchMultiSearchOptions = AiSearchOptions & { + /** Instance IDs to search across (1-10). */ + instance_ids: string[]; +}; +/** + * Request for searching across multiple instances within a namespace. + * `ai_search_options` is required and must include `instance_ids`. + * Exactly one of `query` or `messages` must be provided. + */ +type AiSearchMultiSearchRequest = { + /** Simple query string. */ + query: string; + messages?: never; + ai_search_options: AiSearchMultiSearchOptions; +} | { + query?: never; + /** Conversation-style input. */ + messages: AiSearchMessage[]; + ai_search_options: AiSearchMultiSearchOptions; +}; +/** A search result chunk tagged with the instance it originated from. */ +type AiSearchMultiSearchChunk = AiSearchSearchResponse['chunks'][number] & { + instance_id: string; +}; +/** Describes a per-instance error during a multi-instance operation. */ +type AiSearchMultiSearchError = { + instance_id: string; + message: string; +}; +/** Response from a multi-instance search, with chunks tagged by instance and optional partial-failure errors. */ +type AiSearchMultiSearchResponse = { + search_query: string; + chunks: AiSearchMultiSearchChunk[]; + errors?: AiSearchMultiSearchError[]; +}; +/** Request for chat completions across multiple instances within a namespace. `ai_search_options` is required and must include `instance_ids`. */ +type AiSearchMultiChatCompletionsRequest = Omit & { + ai_search_options: AiSearchMultiSearchOptions; +}; +/** Response from multi-instance chat completions, with chunks tagged by instance and optional partial-failure errors. */ +type AiSearchMultiChatCompletionsResponse = Omit & { + chunks: AiSearchMultiSearchChunk[]; + errors?: AiSearchMultiSearchError[]; +}; +// ============ AI Search Response Types ============ +type AiSearchSearchResponse = { + search_query: string; + chunks: Array<{ + id: string; + type: string; + /** Match score (0-1) */ + score: number; + text: string; + item: { + timestamp?: number; + key: string; + metadata?: Record; + }; + scoring_details?: { + /** Keyword match score (0-1) */ + keyword_score?: number; + /** Vector similarity score (0-1) */ + vector_score?: number; + /** Keyword rank position */ + keyword_rank?: number; + /** Vector rank position */ + vector_rank?: number; + /** Reranking model score */ + reranking_score?: number; + /** Fusion method used to combine results */ + fusion_method?: 'rrf' | 'max'; + [key: string]: unknown; + }; + }>; +}; +type AiSearchChatCompletionsResponse = { + id?: string; + object?: string; + model?: string; + choices: Array<{ + index?: number; + message: { + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + [key: string]: unknown; + }; + [key: string]: unknown; + }>; + chunks: AiSearchSearchResponse['chunks']; + [key: string]: unknown; +}; +type AiSearchStatsResponse = { + queued?: number; + running?: number; + completed?: number; + error?: number; + skipped?: number; + outdated?: number; + last_activity?: string; + /** Storage engine statistics. */ + engine?: { + vectorize?: { + vectorsCount: number; + dimensions: number; + }; + r2?: { + payloadSizeBytes: number; + metadataSizeBytes: number; + objectCount: number; + }; + }; +}; +// ============ AI Search Instance Info Types ============ +type AiSearchInstanceInfo = { + id: string; + type?: 'r2' | 'web-crawler' | string; + source?: string; + source_params?: unknown; + paused?: boolean; + status?: string; + namespace?: string; + created_at?: string; + modified_at?: string; + token_id?: string; + ai_gateway_id?: string; + rewrite_query?: boolean; + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; + rewrite_model?: string; + reranking_model?: string; + /** @deprecated Use index_method instead. */ + hybrid_search_enabled?: boolean; + /** Controls which storage backends are active. */ + index_method?: { + vector?: boolean; + keyword?: boolean; + }; + /** Fusion method for combining vector and keyword results. */ + fusion_method?: 'max' | 'rrf'; + indexing_options?: { + keyword_tokenizer?: 'porter' | 'trigram'; + } | null; + retrieval_options?: { + keyword_match_mode?: 'and' | 'or'; + boost_by?: Array<{ + field: string; + direction?: 'asc' | 'desc' | 'exists' | 'not_exists'; + }>; + } | null; + chunk?: boolean; + chunk_size?: number; + chunk_overlap?: number; + score_threshold?: number; + max_num_results?: number; + cache?: boolean; + cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes'; + custom_metadata?: Array<{ + field_name: string; + data_type: 'text' | 'number' | 'boolean' | 'datetime'; + }>; + /** Sync interval in seconds. */ + sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400; + metadata?: Record; + [key: string]: unknown; +}; +/** Pagination, search, and ordering parameters for listing instances within a namespace. */ +type AiSearchListInstancesParams = { + page?: number; + per_page?: number; + /** Search instances by ID. */ + search?: string; + /** Field to sort by. */ + order_by?: 'created_at'; + /** Sort direction. */ + order_by_direction?: 'asc' | 'desc'; +}; +type AiSearchListResponse = { + result: AiSearchInstanceInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +// ============ AI Search Config Types ============ +type AiSearchConfig = { + /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ + id: string; + /** Instance type. Omit to create with built-in storage. */ + type?: 'r2' | 'web-crawler' | string; + /** Source URL (required for web-crawler type). */ + source?: string; + source_params?: unknown; + /** Token ID (UUID format) */ + token_id?: string; + ai_gateway_id?: string; + /** Enable query rewriting (default false) */ + rewrite_query?: boolean; + /** Enable reranking (default false) */ + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; + rewrite_model?: string; + reranking_model?: string; + /** @deprecated Use index_method instead. */ + hybrid_search_enabled?: boolean; + /** Controls which storage backends are used during indexing. Defaults to vector-only. */ + index_method?: { + vector?: boolean; + keyword?: boolean; + }; + /** Fusion method for combining vector and keyword results. "rrf" = reciprocal rank fusion (default), "max" = maximum score. */ + fusion_method?: 'max' | 'rrf'; + indexing_options?: { + keyword_tokenizer?: 'porter' | 'trigram'; + } | null; + retrieval_options?: { + keyword_match_mode?: 'and' | 'or'; + boost_by?: Array<{ + field: string; + direction?: 'asc' | 'desc' | 'exists' | 'not_exists'; + }>; + } | null; + chunk?: boolean; + chunk_size?: number; + chunk_overlap?: number; + /** Minimum similarity score (0-1) for a result to be included. */ + score_threshold?: number; + max_num_results?: number; + cache?: boolean; + /** Similarity threshold for cache hits. Stricter = fewer cache hits but higher relevance. */ + cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes'; + custom_metadata?: Array<{ + field_name: string; + data_type: 'text' | 'number' | 'boolean' | 'datetime'; + }>; + namespace?: string; + /** Sync interval in seconds. 3600=1h, 7200=2h, 14400=4h, 21600=6h, 43200=12h, 86400=24h. */ + sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400; + metadata?: Record; + [key: string]: unknown; +}; +// ============ AI Search Item Types ============ +type AiSearchItemInfo = { + id: string; + key: string; + status: 'completed' | 'error' | 'skipped' | 'queued' | 'running' | 'outdated'; + next_action?: 'INDEX' | 'DELETE' | null; + error?: string; + checksum?: string; + namespace?: string; + chunks_count?: number | null; + file_size?: number | null; + source_id?: string | null; + last_seen_at?: string; + created_at?: string; + metadata?: Record; + [key: string]: unknown; +}; +type AiSearchItemContentResult = { + body: ReadableStream; + contentType: string; + filename: string; + size: number; +}; +type AiSearchUploadItemOptions = { + metadata?: Record; +}; +type AiSearchListItemsParams = { + page?: number; + per_page?: number; + /** Search items by key name. */ + search?: string; + /** Sort order for results. */ + sort_by?: 'status' | 'modified_at'; + /** Filter items by processing status. */ + status?: 'queued' | 'running' | 'completed' | 'error' | 'skipped' | 'outdated'; + /** Filter items by source (e.g. "builtin" or "web-crawler:https://example.com"). */ + source?: string; + /** JSON-encoded Vectorize filter for metadata filtering. */ + metadata_filter?: string; + /** Filter items by their unique ID. Returns at most one item. */ + item_id?: string; + /** + * Filter items by their exact key (object key / filename). Keys are unique + * per source, so combine with `source` to disambiguate across data sources. + */ + key?: string; +}; +type AiSearchListItemsResponse = { + result: AiSearchItemInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +// ============ AI Search Item Logs Types ============ +type AiSearchItemLogsParams = { + /** Maximum number of log entries to return (1-100, default 50). */ + limit?: number; + /** Opaque cursor for pagination. Pass the `cursor` value from a previous response. */ + cursor?: string; +}; +type AiSearchItemLog = { + timestamp: string; + action: string; + message: string; + fileKey?: string; + chunkCount?: number; + processingTimeMs?: number; + errorType?: string; +}; +/** Paginated response for item processing logs (cursor-based). */ +type AiSearchItemLogsResponse = { + result: AiSearchItemLog[]; + result_info: { + count: number; + per_page: number; + cursor: string | null; + truncated: boolean; + }; +}; +// ============ AI Search Item Chunks Types ============ +type AiSearchItemChunksParams = { + /** Maximum number of chunks to return (1-100, default 20). */ + limit?: number; + /** Offset into the chunks list (default 0). */ + offset?: number; +}; +/** A single indexed chunk belonging to an item, including its text content and byte range. */ +type AiSearchItemChunk = { + id: string; + text: string; + start_byte: number; + end_byte: number; + item?: { + timestamp?: number; + key: string; + metadata?: Record; + }; +}; +/** Paginated response for item chunks (offset-based). */ +type AiSearchItemChunksResponse = { + result: AiSearchItemChunk[]; + result_info: { + count: number; + total: number; + limit: number; + offset: number; + }; +}; +// ============ AI Search Job Types ============ +type AiSearchJobInfo = { + id: string; + source: 'user' | 'schedule'; + description?: string; + last_seen_at?: string; + started_at?: string; + ended_at?: string; + end_reason?: string; +}; +type AiSearchJobLog = { + id: number; + message: string; + message_type: number; + created_at: number; +}; +type AiSearchCreateJobParams = { + description?: string; +}; +type AiSearchListJobsParams = { + page?: number; + per_page?: number; +}; +type AiSearchListJobsResponse = { + result: AiSearchJobInfo[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +type AiSearchJobLogsParams = { + page?: number; + per_page?: number; +}; +type AiSearchJobLogsResponse = { + result: AiSearchJobLog[]; + result_info?: { + count: number; + page: number; + per_page: number; + total_count: number; + }; +}; +// ============ AI Search Sub-Service Classes ============ +/** + * Single item service for an AI Search instance. + * Provides info, download, sync, logs, and chunks operations on a specific item. + */ +declare abstract class AiSearchItem { + /** Get metadata about this item. */ + info(): Promise; + /** + * Download the item's content. + * @returns Object with body stream, content type, filename, and size. + */ + download(): Promise; + /** + * Trigger re-indexing of this item. + * @returns The updated item info. + */ + sync(): Promise; + /** + * Retrieve processing logs for this item (cursor-based pagination). + * @param params Optional pagination parameters (limit, cursor). + * @returns Paginated log entries for this item. + */ + logs(params?: AiSearchItemLogsParams): Promise; + /** + * List indexed chunks for this item (offset-based pagination). + * @param params Optional pagination parameters (limit, offset). + * @returns Paginated chunk entries for this item. + */ + chunks(params?: AiSearchItemChunksParams): Promise; +} +/** + * Items collection service for an AI Search instance. + * Provides list, upload, and access to individual items. + */ +declare abstract class AiSearchItems { + /** List items in this instance. */ + list(params?: AiSearchListItemsParams): Promise; + /** + * Upload a file as an item. Behaves as an upsert: if an item with the same + * filename already exists, it is overwritten and re-indexed. + * @param name Filename for the uploaded item. + * @param content File content as a ReadableStream, Blob, or string. + * @param options Optional metadata to attach to the item. + * @returns The created item info. + */ + upload(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions): Promise; + /** + * Upload a file and poll until processing completes. + * Behaves as an upsert: if an item with the same filename already exists, + * it is overwritten and re-indexed. + * @param name Filename for the uploaded item. + * @param content File content as a ReadableStream, Blob, or string. + * @param options Optional metadata and polling configuration. + * @returns The item info after processing completes (or timeout). + */ + uploadAndPoll(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions & { + /** Polling interval in milliseconds (default 1000). */ + pollIntervalMs?: number; + /** Maximum time to wait in milliseconds (default 30000). */ + timeoutMs?: number; + }): Promise; + /** + * Get an item by ID. + * @param itemId The item identifier. + * @returns Item service for info, download, sync, logs, and chunks operations. + */ + get(itemId: string): AiSearchItem; + /** + * Delete an item from the instance. + * @param itemId The item identifier. + */ + delete(itemId: string): Promise; +} +/** + * Single job service for an AI Search instance. + * Provides info, logs, and cancel operations for a specific job. + */ +declare abstract class AiSearchJob { + /** Get metadata about this job. */ + info(): Promise; + /** Get logs for this job. */ + logs(params?: AiSearchJobLogsParams): Promise; + /** + * Cancel a running job. + * @returns The updated job info. + * @throws AiSearchNotFoundError if the job does not exist. + */ + cancel(): Promise; +} +/** + * Jobs collection service for an AI Search instance. + * Provides list, create, and access to individual jobs. + */ +declare abstract class AiSearchJobs { + /** List jobs for this instance. */ + list(params?: AiSearchListJobsParams): Promise; + /** + * Create a new indexing job. + * @param params Optional job parameters. + * @returns The created job info. + */ + create(params?: AiSearchCreateJobParams): Promise; + /** + * Get a job by ID. + * @param jobId The job identifier. + * @returns Job service for info, logs, and cancel operations. + */ + get(jobId: string): AiSearchJob; +} +// ============ AI Search Binding Classes ============ +/** + * Instance-level AI Search service. + * + * Used as: + * - The return type of `AiSearchNamespace.get(name)` (namespace binding) + * - The type of `env.BLOG_SEARCH` (single instance binding via `ai_search`) + * + * Provides search, chat, update, stats, items, and jobs operations. + * + * @example + * ```ts + * // Via namespace binding + * const instance = env.AI_SEARCH.get("blog"); + * const results = await instance.search({ + * query: "How does caching work?", + * }); + * + * // Via single instance binding + * const results = await env.BLOG_SEARCH.search({ + * messages: [{ role: "user", content: "How does caching work?" }], + * }); + * ``` + */ +declare abstract class AiSearchInstance { + /** + * Search the AI Search instance for relevant chunks. + * @param params Search request with query or messages and optional AI search options. + * @returns Search response with matching chunks and search query. + */ + search(params: AiSearchSearchRequest): Promise; + /** + * Generate chat completions with AI Search context (streaming). + * @param params Chat completions request with stream: true. + * @returns ReadableStream of server-sent events. + */ + chatCompletions(params: AiSearchChatCompletionsRequest & { + stream: true; + }): Promise; + /** + * Generate chat completions with AI Search context. + * @param params Chat completions request. + * @returns Chat completion response with choices and RAG chunks. + */ + chatCompletions(params: AiSearchChatCompletionsRequest): Promise; + /** + * Update the instance configuration. + * @param config Partial configuration to update. + * @returns Updated instance info. + */ + update(config: Partial): Promise; + /** Get metadata about this instance. */ + info(): Promise; + /** + * Get instance statistics (item count, indexing status, etc.). + * @returns Statistics with counts per status, last activity time, and engine details. + */ + stats(): Promise; + /** Items collection — list, upload, and manage items in this instance. */ + get items(): AiSearchItems; + /** Jobs collection — list, create, and inspect indexing jobs. */ + get jobs(): AiSearchJobs; +} +/** + * Namespace-level AI Search service. + * + * Used as the type of `env.AI_SEARCH` (namespace binding via `ai_search_namespaces`). + * Scoped to a single namespace. Provides dynamic instance access, creation, deletion, + * and multi-instance search/chat operations. + * + * @example + * ```ts + * // Access an instance within the namespace + * const blog = env.AI_SEARCH.get("blog"); + * const results = await blog.search({ query: "How does caching work?" }); + * + * // List all instances in the namespace + * const instances = await env.AI_SEARCH.list(); + * + * // Create a new instance with built-in storage + * const tenant = await env.AI_SEARCH.create({ id: "tenant-123" }); + * + * // Upload items into the instance + * await tenant.items.upload("doc.pdf", fileContent); + * + * // Search across multiple instances + * const multi = await env.AI_SEARCH.search({ + * query: "caching", + * ai_search_options: { instance_ids: ["blog", "docs"] }, + * }); + * + * // Delete an instance + * await env.AI_SEARCH.delete("tenant-123"); + * ``` + */ +declare abstract class AiSearchNamespace { + /** + * Get an instance by name within the bound namespace. + * @param name Instance name. + * @returns Instance service for search, chat, update, stats, items, and jobs. + */ + get(name: string): AiSearchInstance; + /** + * List instances in the bound namespace. + * @param params Optional pagination, search, and ordering parameters. + * @returns Array of instance metadata with pagination info. + */ + list(params?: AiSearchListInstancesParams): Promise; + /** + * Create a new instance within the bound namespace. + * @param config Instance configuration. Only `id` is required — omit `type` and `source` to create with built-in storage. + * @returns Instance service for the newly created instance. + * + * @example + * ```ts + * // Create with built-in storage (upload items manually) + * const instance = await env.AI_SEARCH.create({ id: "my-search" }); + * + * // Create with web crawler source + * const instance = await env.AI_SEARCH.create({ + * id: "docs-search", + * type: "web-crawler", + * source: "https://developers.cloudflare.com", + * }); + * ``` + */ + create(config: AiSearchConfig): Promise; + /** + * Delete an instance from the bound namespace. + * @param name Instance name to delete. + */ + delete(name: string): Promise; + /** + * Search across multiple instances within the bound namespace. + * Fans out to the specified instance_ids and merges results. + * @param params Search request with required `ai_search_options.instance_ids`. + * @returns Search response with chunks tagged by instance_id and optional partial-failure errors. + */ + search(params: AiSearchMultiSearchRequest): Promise; + /** + * Generate chat completions across multiple instances within the bound namespace (streaming). + * Fans out to the specified instance_ids, merges context, and generates a response. + * @param params Chat completions request with stream: true and required `ai_search_options.instance_ids`. + * @returns ReadableStream of server-sent events. + */ + chatCompletions(params: AiSearchMultiChatCompletionsRequest & { + stream: true; + }): Promise; + /** + * Generate chat completions across multiple instances within the bound namespace. + * Fans out to the specified instance_ids, merges context, and generates a response. + * @param params Chat completions request with required `ai_search_options.instance_ids`. + * @returns Chat completion response with choices, chunks tagged by instance_id, and optional partial-failure errors. + */ + chatCompletions(params: AiSearchMultiChatCompletionsRequest): Promise; +} +type AiImageClassificationInput = { + image: number[]; +}; +type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +type AiImageTextToTextInput = { + image: string; + prompt?: string; + max_tokens?: number; + temperature?: number; + ignore_eos?: boolean; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +type AiImageTextToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageTextToText { + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; +} +type AiMultimodalEmbeddingsInput = { + image: string; + text: string[]; +}; +type AiIMultimodalEmbeddingsOutput = { + data: number[][]; + shape: number[]; +}; +declare abstract class BaseAiMultimodalEmbeddings { + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; +} +type AiObjectDetectionInput = { + image: number[]; +}; +type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +type AiAutomaticSpeechRecognitionInput = { + audio: number[]; +}; +type AiAutomaticSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiAutomaticSpeechRecognition { + inputs: AiAutomaticSpeechRecognitionInput; + postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; +} +type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +type AiTextClassificationInput = { + text: string; +}; +type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +type AiTextEmbeddingsInput = { + text: string | string[]; +}; +type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +type RoleScopedChatInput = { + role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); + content: string; + name?: string; +}; +type AiTextGenerationToolLegacyInput = { + name: string; + description: string; + parameters?: { + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; +}; +type AiTextGenerationToolInput = { + type: "function" | (string & NonNullable); + function: { + name: string; + description: string; + parameters?: { + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; + }; +}; +type AiTextGenerationFunctionsInput = { + name: string; + code: string; +}; +type AiTextGenerationResponseFormat = { + type: string; + json_schema?: any; +}; +type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + temperature?: number; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + messages?: RoleScopedChatInput[]; + response_format?: AiTextGenerationResponseFormat; + tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable); + functions?: AiTextGenerationFunctionsInput[]; +}; +type AiTextGenerationToolLegacyOutput = { + name: string; + arguments: unknown; +}; +type AiTextGenerationToolOutput = { + id: string; + type: "function"; + function: { + name: string; + arguments: string; + }; +}; +type UsageTags = { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; +}; +type AiTextGenerationOutput = { + response?: string; + tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; + usage?: UsageTags; +}; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +type AiTextToSpeechInput = { + prompt: string; + lang?: string; +}; +type AiTextToSpeechOutput = Uint8Array | { + audio: string; +}; +declare abstract class BaseAiTextToSpeech { + inputs: AiTextToSpeechInput; + postProcessedOutputs: AiTextToSpeechOutput; +} +type AiTextToImageInput = { + prompt: string; + negative_prompt?: string; + height?: number; + width?: number; + image?: number[]; + image_b64?: string; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; + seed?: number; +}; +type AiTextToImageOutput = ReadableStream; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +/** + * Workers AI support for OpenAI's Chat Completions API + */ +type ChatCompletionContentPartText = { + type: "text"; + text: string; +}; +type ChatCompletionContentPartImage = { + type: "image_url"; + image_url: { + url: string; + detail?: "auto" | "low" | "high"; + }; +}; +type ChatCompletionContentPartInputAudio = { + type: "input_audio"; + input_audio: { + /** Base64 encoded audio data. */ + data: string; + format: "wav" | "mp3"; + }; +}; +type ChatCompletionContentPartFile = { + type: "file"; + file: { + /** Base64 encoded file data. */ + file_data?: string; + /** The ID of an uploaded file. */ + file_id?: string; + filename?: string; + }; +}; +type ChatCompletionContentPartRefusal = { + type: "refusal"; + refusal: string; +}; +type ChatCompletionContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage | ChatCompletionContentPartInputAudio | ChatCompletionContentPartFile; +type FunctionDefinition = { + name: string; + description?: string; + parameters?: Record; + strict?: boolean | null; +}; +type ChatCompletionFunctionTool = { + type: "function"; + function: FunctionDefinition; +}; +type ChatCompletionCustomToolGrammarFormat = { + type: "grammar"; + grammar: { + definition: string; + syntax: "lark" | "regex"; + }; +}; +type ChatCompletionCustomToolTextFormat = { + type: "text"; +}; +type ChatCompletionCustomToolFormat = ChatCompletionCustomToolTextFormat | ChatCompletionCustomToolGrammarFormat; +type ChatCompletionCustomTool = { + type: "custom"; + custom: { + name: string; + description?: string; + format?: ChatCompletionCustomToolFormat; + }; +}; +type ChatCompletionTool = ChatCompletionFunctionTool | ChatCompletionCustomTool; +type ChatCompletionMessageFunctionToolCall = { + id: string; + type: "function"; + function: { + name: string; + /** JSON-encoded arguments string. */ + arguments: string; + }; +}; +type ChatCompletionMessageCustomToolCall = { + id: string; + type: "custom"; + custom: { + name: string; + input: string; + }; +}; +type ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall; +type ChatCompletionToolChoiceFunction = { + type: "function"; + function: { + name: string; + }; +}; +type ChatCompletionToolChoiceCustom = { + type: "custom"; + custom: { + name: string; + }; +}; +type ChatCompletionToolChoiceAllowedTools = { + type: "allowed_tools"; + allowed_tools: { + mode: "auto" | "required"; + tools: Array>; + }; +}; +type ChatCompletionToolChoiceOption = "none" | "auto" | "required" | ChatCompletionToolChoiceFunction | ChatCompletionToolChoiceCustom | ChatCompletionToolChoiceAllowedTools; +type DeveloperMessage = { + role: "developer"; + content: string | Array<{ + type: "text"; + text: string; + }>; + name?: string; +}; +type SystemMessage = { + role: "system"; + content: string | Array<{ + type: "text"; + text: string; + }>; + name?: string; +}; +/** + * Permissive merged content part used inside UserMessage arrays. + * + * Cabidela has a limitation where anyOf/oneOf with enum-based discrimination + * inside nested array items does not correctly match different branches for + * different array elements, so the schema uses a single merged object. + */ +type UserMessageContentPart = { + type: "text" | "image_url" | "input_audio" | "file"; + text?: string; + image_url?: { + url?: string; + detail?: "auto" | "low" | "high"; + }; + input_audio?: { + data?: string; + format?: "wav" | "mp3"; + }; + file?: { + file_data?: string; + file_id?: string; + filename?: string; + }; +}; +type UserMessage = { + role: "user"; + content: string | Array; + name?: string; +}; +type AssistantMessageContentPart = { + type: "text" | "refusal"; + text?: string; + refusal?: string; +}; +type AssistantMessage = { + role: "assistant"; + content?: string | null | Array; + refusal?: string | null; + name?: string; + audio?: { + id: string; + }; + tool_calls?: Array; + function_call?: { + name: string; + arguments: string; + }; +}; +type ToolMessage = { + role: "tool"; + content: string | Array<{ + type: "text"; + text: string; + }>; + tool_call_id: string; +}; +type FunctionMessage = { + role: "function"; + content: string; + name: string; +}; +type ChatCompletionMessageParam = DeveloperMessage | SystemMessage | UserMessage | AssistantMessage | ToolMessage | FunctionMessage; +type ChatCompletionsResponseFormatText = { + type: "text"; +}; +type ChatCompletionsResponseFormatJSONObject = { + type: "json_object"; +}; +type ResponseFormatJSONSchema = { + type: "json_schema"; + json_schema: { + name: string; + description?: string; + schema?: Record; + strict?: boolean | null; + }; +}; +type ResponseFormat = ChatCompletionsResponseFormatText | ChatCompletionsResponseFormatJSONObject | ResponseFormatJSONSchema; +type ChatCompletionsStreamOptions = { + include_usage?: boolean; + include_obfuscation?: boolean; +}; +type PredictionContent = { + type: "content"; + content: string | Array<{ + type: "text"; + text: string; + }>; +}; +type AudioParams = { + voice: string | { + id: string; + }; + format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16"; +}; +type WebSearchUserLocation = { + type: "approximate"; + approximate: { + city?: string; + country?: string; + region?: string; + timezone?: string; + }; +}; +type WebSearchOptions = { + search_context_size?: "low" | "medium" | "high"; + user_location?: WebSearchUserLocation; +}; +type ChatTemplateKwargs = { + /** Whether to enable reasoning, enabled by default. */ + enable_thinking?: boolean; + /** If false, preserves reasoning context between turns. */ + clear_thinking?: boolean; +}; +/** Shared optional properties used by both Prompt and Messages input branches. */ +type ChatCompletionsCommonOptions = { + model?: string; + audio?: AudioParams; + frequency_penalty?: number | null; + logit_bias?: Record | null; + logprobs?: boolean | null; + top_logprobs?: number | null; + max_tokens?: number | null; + max_completion_tokens?: number | null; + metadata?: Record | null; + modalities?: Array<"text" | "audio"> | null; + n?: number | null; + parallel_tool_calls?: boolean; + prediction?: PredictionContent; + presence_penalty?: number | null; + reasoning_effort?: "low" | "medium" | "high" | null; + chat_template_kwargs?: ChatTemplateKwargs; + response_format?: ResponseFormat; + seed?: number | null; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + stop?: string | Array | null; + store?: boolean | null; + stream?: boolean | null; + stream_options?: ChatCompletionsStreamOptions; + temperature?: number | null; + tool_choice?: ChatCompletionToolChoiceOption; + tools?: Array; + top_p?: number | null; + user?: string; + web_search_options?: WebSearchOptions; + function_call?: "none" | "auto" | { + name: string; + }; + functions?: Array; +}; +type PromptTokensDetails = { + cached_tokens?: number; + audio_tokens?: number; +}; +type CompletionTokensDetails = { + reasoning_tokens?: number; + audio_tokens?: number; + accepted_prediction_tokens?: number; + rejected_prediction_tokens?: number; +}; +type CompletionUsage = { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; + prompt_tokens_details?: PromptTokensDetails; + completion_tokens_details?: CompletionTokensDetails; +}; +type ChatCompletionTopLogprob = { + token: string; + logprob: number; + bytes: Array | null; +}; +type ChatCompletionTokenLogprob = { + token: string; + logprob: number; + bytes: Array | null; + top_logprobs: Array; +}; +type ChatCompletionAudio = { + id: string; + /** Base64 encoded audio bytes. */ + data: string; + expires_at: number; + transcript: string; +}; +type ChatCompletionUrlCitation = { + type: "url_citation"; + url_citation: { + url: string; + title: string; + start_index: number; + end_index: number; + }; +}; +type ChatCompletionResponseMessage = { + role: "assistant"; + content: string | null; + refusal: string | null; + annotations?: Array; + audio?: ChatCompletionAudio; + tool_calls?: Array; + function_call?: { + name: string; + arguments: string; + } | null; +}; +type ChatCompletionLogprobs = { + content: Array | null; + refusal?: Array | null; +}; +type ChatCompletionChoice = { + index: number; + message: ChatCompletionResponseMessage; + finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call"; + logprobs: ChatCompletionLogprobs | null; +}; +type ChatCompletionsMessagesInput = { + messages: Array; +} & ChatCompletionsCommonOptions; +type ChatCompletionsOutput = { + id: string; + object: string; + created: number; + model: string; + choices: Array; + usage?: CompletionUsage; + system_fingerprint?: string | null; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; +}; +/** + * Workers AI support for OpenAI's Responses API + * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts + * + * It's a stripped down version from its source. + * It currently supports basic function calling, json mode and accepts images as input. + * + * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. + * We plan to add those incrementally as model + platform capabilities evolve. + */ +type ResponsesInput = { + background?: boolean | null; + conversation?: string | ResponseConversationParam | null; + include?: Array | null; + input?: string | ResponseInput; + instructions?: string | null; + max_output_tokens?: number | null; + parallel_tool_calls?: boolean | null; + previous_response_id?: string | null; + prompt_cache_key?: string; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + stream?: boolean | null; + stream_options?: StreamOptions | null; + temperature?: number | null; + text?: ResponseTextConfig; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + truncation?: "auto" | "disabled" | null; +}; +type ResponsesOutput = { + id?: string; + created_at?: number; + output_text?: string; + error?: ResponseError | null; + incomplete_details?: ResponseIncompleteDetails | null; + instructions?: string | Array | null; + object?: "response"; + output?: Array; + parallel_tool_calls?: boolean; + temperature?: number | null; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + max_output_tokens?: number | null; + previous_response_id?: string | null; + prompt?: ResponsePrompt | null; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + status?: ResponseStatus; + text?: ResponseTextConfig; + truncation?: "auto" | "disabled" | null; + usage?: ResponseUsage; +}; +type EasyInputMessage = { + content: string | ResponseInputMessageContentList; + role: "user" | "assistant" | "system" | "developer"; + type?: "message"; +}; +type ResponsesFunctionTool = { + name: string; + parameters: { + [key: string]: unknown; + } | null; + strict: boolean | null; + type: "function"; + description?: string | null; +}; +type ResponseIncompleteDetails = { + reason?: "max_output_tokens" | "content_filter"; +}; +type ResponsePrompt = { + id: string; + variables?: { + [key: string]: string | ResponseInputText | ResponseInputImage; + } | null; + version?: string | null; +}; +type Reasoning = { + effort?: ReasoningEffort | null; + generate_summary?: "auto" | "concise" | "detailed" | null; + summary?: "auto" | "concise" | "detailed" | null; +}; +type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText; +type ResponseContentReasoningText = { + text: string; + type: "reasoning_text"; +}; +type ResponseConversationParam = { + id: string; +}; +type ResponseCreatedEvent = { + response: Response; + sequence_number: number; + type: "response.created"; +}; +type ResponseCustomToolCallOutput = { + call_id: string; + output: string | Array; + type: "custom_tool_call_output"; + id?: string; +}; +type ResponseError = { + code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found"; + message: string; +}; +type ResponseErrorEvent = { + code: string | null; + message: string; + param: string | null; + sequence_number: number; + type: "error"; +}; +type ResponseFailedEvent = { + response: Response; + sequence_number: number; + type: "response.failed"; +}; +type ResponseFormatText = { + type: "text"; +}; +type ResponseFormatJSONObject = { + type: "json_object"; +}; +type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; +type ResponseFormatTextJSONSchemaConfig = { + name: string; + schema: { + [key: string]: unknown; + }; + type: "json_schema"; + description?: string; + strict?: boolean | null; +}; +type ResponseFunctionCallArgumentsDeltaEvent = { + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.delta"; +}; +type ResponseFunctionCallArgumentsDoneEvent = { + arguments: string; + item_id: string; + name: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.done"; +}; +type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; +type ResponseFunctionCallOutputItemList = Array; +type ResponseFunctionToolCall = { + arguments: string; + call_id: string; + name: string; + type: "function_call"; + id?: string; + status?: "in_progress" | "completed" | "incomplete"; +}; +interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { + id: string; +} +type ResponseFunctionToolCallOutputItem = { + id: string; + call_id: string; + output: string | Array; + type: "function_call_output"; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs"; +type ResponseIncompleteEvent = { + response: Response; + sequence_number: number; + type: "response.incomplete"; +}; +type ResponseInput = Array; +type ResponseInputContent = ResponseInputText | ResponseInputImage; +type ResponseInputImage = { + detail: "low" | "high" | "auto"; + type: "input_image"; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputImageContent = { + type: "input_image"; + detail?: "low" | "high" | "auto" | null; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem; +type ResponseInputItemFunctionCallOutput = { + call_id: string; + output: string | ResponseFunctionCallOutputItemList; + type: "function_call_output"; + id?: string | null; + status?: "in_progress" | "completed" | "incomplete" | null; +}; +type ResponseInputItemMessage = { + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputMessageContentList = Array; +type ResponseInputMessageItem = { + id: string; + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputText = { + text: string; + type: "input_text"; +}; +type ResponseInputTextContent = { + text: string; + type: "input_text"; +}; +type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; +type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; +type ResponseOutputItemAddedEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.added"; +}; +type ResponseOutputItemDoneEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.done"; +}; +type ResponseOutputMessage = { + id: string; + content: Array; + role: "assistant"; + status: "in_progress" | "completed" | "incomplete"; + type: "message"; +}; +type ResponseOutputRefusal = { + refusal: string; + type: "refusal"; +}; +type ResponseOutputText = { + text: string; + type: "output_text"; + logprobs?: Array; +}; +type ResponseReasoningItem = { + id: string; + summary: Array; + type: "reasoning"; + content?: Array; + encrypted_content?: string | null; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseReasoningSummaryItem = { + text: string; + type: "summary_text"; +}; +type ResponseReasoningContentItem = { + text: string; + type: "reasoning_text"; +}; +type ResponseReasoningTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.reasoning_text.delta"; +}; +type ResponseReasoningTextDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + sequence_number: number; + text: string; + type: "response.reasoning_text.done"; +}; +type ResponseRefusalDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.refusal.delta"; +}; +type ResponseRefusalDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + refusal: string; + sequence_number: number; + type: "response.refusal.done"; +}; +type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete"; +type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent; +type ResponseCompletedEvent = { + response: Response; + sequence_number: number; + type: "response.completed"; +}; +type ResponseTextConfig = { + format?: ResponseFormatTextConfig; + verbosity?: "low" | "medium" | "high" | null; +}; +type ResponseTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + type: "response.output_text.delta"; +}; +type ResponseTextDoneEvent = { + content_index: number; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + text: string; + type: "response.output_text.done"; +}; +type Logprob = { + token: string; + logprob: number; + top_logprobs?: Array; +}; +type TopLogprob = { + token?: string; + logprob?: number; +}; +type ResponseUsage = { + input_tokens: number; + output_tokens: number; + total_tokens: number; +}; +type Tool = ResponsesFunctionTool; +type ToolChoiceFunction = { + name: string; + type: "function"; +}; +type ToolChoiceOptions = "none"; +type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; +type StreamOptions = { + include_obfuscation?: boolean; +}; +/** Marks keys from T that aren't in U as optional never */ +type Without = { + [P in Exclude]?: never; +}; +/** Either T or U, but not both (mutually exclusive) */ +type XOR = (T & Without) | (U & Without); +type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; +} +type Ai_Cf_Openai_Whisper_Input = string | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; +}; +interface Ai_Cf_Openai_Whisper_Output { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; + /** + * The second this word begins in the recording + */ + start?: number; + /** + * The ending second when the word completes + */ + end?: number; + }[]; + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper { + inputs: Ai_Cf_Openai_Whisper_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; +} +type Ai_Cf_Meta_M2M100_1_2B_Input = { + /** + * The text to be translated + */ + text: string; + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + /** + * The text to be translated + */ + text: string; + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; + }[]; +}; +type Ai_Cf_Meta_M2M100_1_2B_Output = { + /** + * The translated text in the target language + */ + translated_text?: string; +} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; +interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { + inputs: Ai_Cf_Meta_M2M100_1_2B_Input; + postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; +} +type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; +} +type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; +} +type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | { + /** + * The input text prompt for the model to generate a response. + */ + prompt?: string; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + image: number[] | (string & NonNullable); + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; +}; +interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { + description?: string; +} +declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { + inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; + postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; +} +type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; +}; +interface Ai_Cf_Openai_Whisper_Tiny_En_Output { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; + /** + * The second this word begins in the recording + */ + start?: number; + /** + * The ending second when the word completes + */ + end?: number; + }[]; + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { + inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { + audio: string | { + body?: object; + contentType?: string; + }; + /** + * Supported tasks are 'translate' or 'transcribe'. + */ + task?: string; + /** + * The language of the audio being transcribed or translated. + */ + language?: string; + /** + * Preprocess the audio with a voice activity detection model. + */ + vad_filter?: boolean; + /** + * A text prompt to help provide context to the model on the contents of the audio. + */ + initial_prompt?: string; + /** + * The prefix appended to the beginning of the output of the transcription and can guide the transcription result. + */ + prefix?: string; + /** + * The number of beams to use in beam search decoding. Higher values may improve accuracy at the cost of speed. + */ + beam_size?: number; + /** + * Whether to condition on previous text during transcription. Setting to false may help prevent hallucination loops. + */ + condition_on_previous_text?: boolean; + /** + * Threshold for detecting no-speech segments. Segments with no-speech probability above this value are skipped. + */ + no_speech_threshold?: number; + /** + * Threshold for filtering out segments with high compression ratio, which often indicate repetitive or hallucinated text. + */ + compression_ratio_threshold?: number; + /** + * Threshold for filtering out segments with low average log probability, indicating low confidence. + */ + log_prob_threshold?: number; + /** + * Optional threshold (in seconds) to skip silent periods that may cause hallucinations. + */ + hallucination_silence_threshold?: number; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { + transcription_info?: { + /** + * The language of the audio being transcribed or translated. + */ + language?: string; + /** + * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. + */ + language_probability?: number; + /** + * The total duration of the original audio file, in seconds. + */ + duration?: number; + /** + * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. + */ + duration_after_vad?: number; + }; + /** + * The complete transcription of the audio. + */ + text: string; + /** + * The total number of words in the transcription. + */ + word_count?: number; + segments?: { + /** + * The starting time of the segment within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the segment within the audio, in seconds. + */ + end?: number; + /** + * The transcription of the segment. + */ + text?: string; + /** + * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. + */ + temperature?: number; + /** + * The average log probability of the predictions for the words in this segment, indicating overall confidence. + */ + avg_logprob?: number; + /** + * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. + */ + compression_ratio?: number; + /** + * The probability that the segment contains no speech, represented as a decimal between 0 and 1. + */ + no_speech_prob?: number; + words?: { + /** + * The individual word transcribed from the audio. + */ + word?: string; + /** + * The starting time of the word within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the word within the audio, in seconds. + */ + end?: number; + }[]; + }[]; + /** + * The transcription in WebVTT format, which includes timing and text information for use in subtitles. + */ + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { + inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; +} +type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[]; +}; +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_Embedding { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Output_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Output_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse; +interface Ai_Cf_Baai_Bge_M3_Output_Query { + response?: { + /** + * Index of the context in the request + */ + id?: number; + /** + * Score of the context under the index. + */ + score?: number; + }[]; +} +interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { + response?: number[][]; + shape?: number[]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} +interface Ai_Cf_Baai_Bge_M3_Output_Embedding { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} +interface Ai_Cf_Baai_Bge_M3_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_M3 { + inputs: Ai_Cf_Baai_Bge_M3_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * The number of diffusion steps; higher values can improve quality but take longer. + */ + steps?: number; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { + /** + * The generated image in Base64 format. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { + inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; +} +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + image?: number[] | (string & NonNullable); + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; +} +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + image?: number[] | (string & NonNullable); + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * If true, the response will be streamed back incrementally. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { + /** + * The generated text response from the model + */ + response?: string; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { + inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: string | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { + requests?: { + /** + * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. + */ + external_reference?: string; + /** + * Prompt for the text generation model + */ + prompt?: string; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; + }[]; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { + inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender must alternate between 'user' and 'assistant'. + */ + role: "user" | "assistant"; + /** + * The content of the message as a string. + */ + content: string; + }[]; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Dictate the output format of the generated response. + */ + response_format?: { + /** + * Set to json_object to process and output generated text as JSON. + */ + type?: string; + }; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { + response?: string | { + /** + * Whether the conversation is safe or not. + */ + safe?: boolean; + /** + * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. + */ + categories?: string[]; + }; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { + inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Input { + /** + * A query you wish to perform against the provided contexts. + */ + /** + * Number of returned results starting with the best score. + */ + top_k?: number; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Output { + response?: { + /** + * Index of the context in the request + */ + id?: number; + /** + * Score of the context under the index. + */ + score?: number; + }[]; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { + inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { + inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; +} +type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; +interface Ai_Cf_Qwen_Qwq_32B_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwq_32B_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Qwen_Qwq_32B_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { + inputs: Ai_Cf_Qwen_Qwq_32B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; +} +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { + inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; +} +type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages; +interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Google_Gemma_3_12B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Google_Gemma_3_12B_It_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { + inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; + postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; +} +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { + requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[]; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The tool call id. + */ + id?: string; + /** + * Specifies the type of tool (e.g., 'function'). + */ + type?: string; + /** + * Details of the function tool. + */ + function?: { + /** + * The name of the tool to be called + */ + name?: string; + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + }; + }[]; +}; +declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { + inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: string | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { + requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: string | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { + inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; +} +interface Ai_Cf_Deepgram_Nova_3_Input { + audio: { + body: object; + contentType: string; + }; + /** + * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. + */ + custom_topic_mode?: "extended" | "strict"; + /** + * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 + */ + custom_topic?: string; + /** + * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param + */ + custom_intent_mode?: "extended" | "strict"; + /** + * Custom intents you want the model to detect within your input audio if present + */ + custom_intent?: string; + /** + * Identifies and extracts key entities from content in submitted audio + */ + detect_entities?: boolean; + /** + * Identifies the dominant language spoken in submitted audio + */ + detect_language?: boolean; + /** + * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 + */ + diarize?: boolean; + /** + * Identify and extract key entities from content in submitted audio + */ + dictation?: boolean; + /** + * Specify the expected encoding of your submitted audio + */ + encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729"; + /** + * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing + */ + extra?: string; + /** + * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' + */ + filler_words?: boolean; + /** + * Key term prompting can boost or suppress specialized terminology and brands. + */ + keyterm?: string; + /** + * Keywords can boost or suppress specialized terminology and brands. + */ + keywords?: string; + /** + * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. + */ + language?: string; + /** + * Spoken measurements will be converted to their corresponding abbreviations. + */ + measurements?: boolean; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. + */ + mip_opt_out?: boolean; + /** + * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio + */ + mode?: "general" | "medical" | "finance"; + /** + * Transcribe each audio channel independently. + */ + multichannel?: boolean; + /** + * Numerals converts numbers from written format to numerical format. + */ + numerals?: boolean; + /** + * Splits audio into paragraphs to improve transcript readability. + */ + paragraphs?: boolean; + /** + * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. + */ + profanity_filter?: boolean; + /** + * Add punctuation and capitalization to the transcript. + */ + punctuate?: boolean; + /** + * Redaction removes sensitive information from your transcripts. + */ + redact?: string; + /** + * Search for terms or phrases in submitted audio and replaces them. + */ + replace?: string; + /** + * Search for terms or phrases in submitted audio. + */ + search?: string; + /** + * Recognizes the sentiment throughout a transcript or text. + */ + sentiment?: boolean; + /** + * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. + */ + smart_format?: boolean; + /** + * Detect topics throughout a transcript or text. + */ + topics?: boolean; + /** + * Segments speech into meaningful semantic units. + */ + utterances?: boolean; + /** + * Seconds to wait before detecting a pause between words in submitted audio. + */ + utt_split?: number; + /** + * The number of channels in the submitted audio + */ + channels?: number; + /** + * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. + */ + interim_results?: boolean; + /** + * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing + */ + endpointing?: string; + /** + * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. + */ + vad_events?: boolean; + /** + * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. + */ + utterance_end_ms?: boolean; +} +interface Ai_Cf_Deepgram_Nova_3_Output { + results?: { + channels?: { + alternatives?: { + confidence?: number; + transcript?: string; + words?: { + confidence?: number; + end?: number; + start?: number; + word?: string; + }[]; + }[]; + }[]; + summary?: { + result?: string; + short?: string; + }; + sentiments?: { + segments?: { + text?: string; + start_word?: number; + end_word?: number; + sentiment?: string; + sentiment_score?: number; + }[]; + average?: { + sentiment?: string; + sentiment_score?: number; + }; + }; + }; +} +declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { + inputs: Ai_Cf_Deepgram_Nova_3_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { + queries?: string | string[]; + /** + * Optional instruction for the task + */ + instruction?: string; + documents?: string | string[]; + text?: string | string[]; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { + data?: number[][]; + shape?: number[]; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { + inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; +} +type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = { + /** + * readable stream with audio data and content-type specified for that data + */ + audio: { + body: object; + contentType: string; + }; + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: "uint8" | "float32" | "float64"; +} | { + /** + * base64 encoded audio data + */ + audio: string; + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: "uint8" | "float32" | "float64"; +}; +interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { + /** + * if true, end-of-turn was detected + */ + is_complete?: boolean; + /** + * probability of the end-of-turn detection + */ + probability?: number; +} +declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { + inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; + postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; +} +declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { + inputs: XOR; + postProcessedOutputs: XOR; +} +declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { + inputs: XOR; + postProcessedOutputs: XOR; +} +interface Ai_Cf_Leonardo_Phoenix_1_0_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number; + /** + * Random seed for reproducibility of the image generation + */ + seed?: number; + /** + * The height of the generated image in pixels + */ + height?: number; + /** + * The width of the generated image in pixels + */ + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * Specify what to exclude from the generated images + */ + negative_prompt?: string; +} +/** + * The generated image in JPEG format + */ +type Ai_Cf_Leonardo_Phoenix_1_0_Output = string; +declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { + inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output; +} +interface Ai_Cf_Leonardo_Lucid_Origin_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number; + /** + * Random seed for reproducibility of the image generation + */ + seed?: number; + /** + * The height of the generated image in pixels + */ + height?: number; + /** + * The width of the generated image in pixels + */ + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + steps?: number; +} +interface Ai_Cf_Leonardo_Lucid_Origin_Output { + /** + * The generated image in Base64 format. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { + inputs: Ai_Cf_Leonardo_Lucid_Origin_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output; +} +interface Ai_Cf_Deepgram_Aura_1_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_1_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { + inputs: Ai_Cf_Deepgram_Aura_1_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; +} +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { + /** + * Input text to translate. Can be a single string or a list of strings. + */ + text: string | string[]; + /** + * Target langauge to translate to + */ + target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva"; +} +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { + /** + * Translated texts + */ + translations: string[]; +} +declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { + inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; + postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: string | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { + requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[]; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + content: string | { + /** + * Type of the content (text) + */ + type?: string; + /** + * Text content + */ + text?: string; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { + inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; + postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { + /** + * Input text to embed. Can be a single string or a list of strings. + */ + text: string | string[]; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { + /** + * Embedding vectors, where each vector is a list of floats. + */ + data: number[][]; + /** + * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. + * + * @minItems 2 + * @maxItems 2 + */ + shape: [ + number, + number + ]; +} +declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { + inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; + postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; +} +interface Ai_Cf_Deepgram_Flux_Input { + /** + * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. + */ + encoding: "linear16"; + /** + * Sample rate of the audio stream in Hz. + */ + sample_rate: string; + /** + * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. + */ + eager_eot_threshold?: string; + /** + * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. + */ + eot_threshold?: string; + /** + * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. + */ + eot_timeout_ms?: string; + /** + * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. + */ + keyterm?: string; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip + */ + mip_opt_out?: "true" | "false"; + /** + * Label your requests for the purpose of identification during usage reporting + */ + tag?: string; +} +/** + * Output will be returned as websocket messages. + */ +interface Ai_Cf_Deepgram_Flux_Output { + /** + * The unique identifier of the request (uuid) + */ + request_id?: string; + /** + * Starts at 0 and increments for each message the server sends to the client. + */ + sequence_id?: number; + /** + * The type of event being reported. + */ + event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn"; + /** + * The index of the current turn + */ + turn_index?: number; + /** + * Start time in seconds of the audio range that was transcribed + */ + audio_window_start?: number; + /** + * End time in seconds of the audio range that was transcribed + */ + audio_window_end?: number; + /** + * Text that was said over the course of the current turn + */ + transcript?: string; + /** + * The words in the transcript + */ + words?: { + /** + * The individual punctuated, properly-cased word from the transcript + */ + word: string; + /** + * Confidence that this word was transcribed correctly + */ + confidence: number; + }[]; + /** + * Confidence that no more speech is coming in this turn + */ + end_of_turn_confidence?: number; +} +declare abstract class Base_Ai_Cf_Deepgram_Flux { + inputs: Ai_Cf_Deepgram_Flux_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; +} +interface Ai_Cf_Deepgram_Aura_2_En_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_En_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { + inputs: Ai_Cf_Deepgram_Aura_2_En_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; +} +interface Ai_Cf_Deepgram_Aura_2_Es_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_Es_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { + inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input { + multipart: { + body?: object; + contentType?: string; + }; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output { + /** + * Generated image as Base64 string. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev { + inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input { + multipart: { + body?: object; + contentType?: string; + }; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output { + /** + * Generated image as Base64 string. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B { + inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input { + multipart: { + body?: object; + contentType?: string; + }; +} +interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output { + /** + * Generated image as Base64 string. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B { + inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output; +} +declare abstract class Base_Ai_Cf_Zai_Org_Glm_4_7_Flash { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_6 { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_7_Code { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_2 { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +interface Ai_Cf_Moondream_Moondream3_1_9B_A2B_Input { + /** + * Which Moondream skill to run. + */ + task?: "query" | "caption" | "point" | "detect"; + /** + * Input image as a public HTTPS URL or base64 data URI. Optional for `query`; required for `caption`, `point`, and `detect`. + */ + image?: string; + /** + * Question for the `query` task. + */ + question?: string; + /** + * Caption length for the `caption` task. + */ + caption_length?: "short" | "normal" | "long"; + /** + * Object phrase to locate for `point` and `detect` tasks (e.g. 'person wearing a red shirt'). + */ + target?: string; + /** + * Enable reasoning trace for the `query` task. + */ + reasoning?: boolean; + /** + * Sampling temperature. + */ + temperature?: number; + /** + * Top-p (nucleus) sampling. + */ + top_p?: number; + /** + * Max tokens to generate for `query` and `caption`. + */ + max_tokens?: number; + /** + * Max objects to return for `point` and `detect`. + */ + max_objects?: number; + /** + * Return incremental tokens for `query` and `caption`. `point` and `detect` do not support streaming. + */ + stream?: boolean; +} +interface Ai_Cf_Moondream_Moondream3_1_9B_A2B_Output { + /** + * Reason the generation finished. + */ + finish_reason: string; + metrics: { + /** + * Number of input tokens consumed. + */ + input_tokens: number; + /** + * Number of output tokens generated. + */ + output_tokens: number; + /** + * Prefill time in milliseconds. + */ + prefill_time_ms: number; + /** + * Decode time in milliseconds. + */ + decode_time_ms: number; + /** + * Time to first token in milliseconds. + */ + ttft_ms: number; + }; + /** + * Answer text for the `query` task. Null for other tasks. + */ + answer?: string; + /** + * Caption text for the `caption` task. Null for other tasks. + */ + caption?: string; + /** + * Located points for the `point` task. Null for other tasks. + */ + points?: { + /** + * X coordinate. + */ + x: number; + /** + * Y coordinate. + */ + y: number; + }[]; + /** + * Detected bounding boxes for the `detect` task. Null for other tasks. + */ + objects?: { + /** + * Minimum X coordinate. + */ + x_min: number; + /** + * Minimum Y coordinate. + */ + y_min: number; + /** + * Maximum X coordinate. + */ + x_max: number; + /** + * Maximum Y coordinate. + */ + y_max: number; + }[]; + /** + * Reasoning trace for the `query` task when reasoning=true. Null otherwise. + */ + reasoning?: { + /** + * Reasoning text. + */ + text: string; + /** + * Grounding information. + */ + grounding?: {}[]; + }; +} +declare abstract class Base_Ai_Cf_Moondream_Moondream3_1_9B_A2B { + inputs: Ai_Cf_Moondream_Moondream3_1_9B_A2B_Input; + postProcessedOutputs: Ai_Cf_Moondream_Moondream3_1_9B_A2B_Output; +} +declare abstract class Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Flash_0731 { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Pro_0813 { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_8_27B { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_3_Flash { + inputs: ChatCompletionsInput; + postProcessedOutputs: ChatCompletionsOutput; +} +interface AiModels { + "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; + "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage; + "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage; + "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage; + "@cf/myshell-ai/melotts": BaseAiTextToSpeech; + "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings; + "@cf/microsoft/resnet-50": BaseAiImageClassification; + "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration; + "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration; + "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration; + "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration; + "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration; + "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration; + "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration; + "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration; + "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration; + "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration; + "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration; + "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration; + "@cf/microsoft/phi-2": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration; + "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration; + "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration; + "@hf/google/gemma-7b-it": BaseAiTextGeneration; + "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration; + "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration; + "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration; + "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; + "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; + "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; + "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; + "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration; + "@cf/facebook/bart-large-cnn": BaseAiSummarization; + "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; + "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; + "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; + "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B; + "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5; + "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5; + "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; + "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En; + "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; + "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3; + "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; + "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; + "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; + "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; + "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; + "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; + "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B; + "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; + "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; + "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; + "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; + "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; + "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; + "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; + "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; + "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; + "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; + "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; + "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; + "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; + "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; + "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; + "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux; + "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En; + "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es; + "@cf/black-forest-labs/flux-2-dev": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev; + "@cf/black-forest-labs/flux-2-klein-4b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B; + "@cf/black-forest-labs/flux-2-klein-9b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B; + "@cf/zai-org/glm-4.7-flash": Base_Ai_Cf_Zai_Org_Glm_4_7_Flash; + "@cf/moonshotai/kimi-k2.5": Base_Ai_Cf_Moonshotai_Kimi_K2_5; + "@cf/moonshotai/kimi-k2.6": Base_Ai_Cf_Moonshotai_Kimi_K2_6; + "@cf/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B; + "@cf/google/gemma-4-26b-a4b-it": Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT; + "@cf/moonshotai/kimi-k2.7-code": Base_Ai_Cf_Moonshotai_Kimi_K2_7_Code; + "@cf/zai-org/glm-5.2": Base_Ai_Cf_Zai_Org_Glm_5_2; + "@cf/moondream/moondream3.1-9B-A2B": Base_Ai_Cf_Moondream_Moondream3_1_9B_A2B; + "@cf/deepseek-ai/deepseek-v4-flash-0731": Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Flash_0731; + "@cf/deepseek-ai/deepseek-v4-pro-0813": Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Pro_0813; + "@cf/qwen/qwen3.8-27b": Base_Ai_Cf_Qwen_Qwen3_8_27B; + "@cf/zai-org/glm-5.3-flash": Base_Ai_Cf_Zai_Org_Glm_5_3_Flash; +} +type AiOptions = { + /** + * Send requests as an asynchronous batch job, only works for supported models + * https://developers.cloudflare.com/workers-ai/features/batch-api + */ + queueRequest?: boolean; + /** + * Establish websocket connections, only works for supported models + */ + websocket?: boolean; + /** + * Tag your requests to group and view them in Cloudflare dashboard. + * + * Rules: + * Tags must only contain letters, numbers, and the symbols: : - . / @ + * Each tag can have maximum 50 characters. + * Maximum 5 tags are allowed each request. + * Duplicate tags will removed. + */ + tags?: string[]; + gateway?: GatewayOptions; + returnRawResponse?: boolean; + prefix?: string; + extraHeaders?: object; + signal?: AbortSignal; +}; +type AiModelsSearchParams = { + author?: string; + hide_experimental?: boolean; + page?: number; + per_page?: number; + search?: string; + source?: number; + task?: string; +}; +type AiModelsSearchObject = { + id: string; + source: number; + name: string; + description: string; + task: { + id: string; + name: string; + description: string; + }; + tags: string[]; + properties: { + property_id: string; + value: string; + }[]; +}; +type ChatCompletionsBase = ChatCompletionsMessagesInput; +type ChatCompletionsInput = ChatCompletionsMessagesInput; +interface InferenceUpstreamError extends Error { +} +interface AiInternalError extends Error { +} +type AiModelListType = Record; +type AiAsyncBatchResponse = { + request_id: string; +}; +declare abstract class Ai { + aiGatewayLogId: string | null; + gateway(gatewayId: string): AiGateway; + /** + * @deprecated Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(): AiSearchNamespace; + /** + * @deprecated AutoRAG has been replaced by AI Search. + * Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + * + * @param autoragId Instance ID + */ + autorag(autoragId: string): AutoRAG; + // Batch request + run(model: Name, inputs: { + requests: AiModelList[Name]['inputs'][]; + }, options: AiOptions & { + queueRequest: true; + }): Promise; + // Raw response + run(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & { + returnRawResponse: true; + }): Promise; + // WebSocket + run(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & { + websocket: true; + }): Promise; + // Streaming + run(model: Name, inputs: AiModelList[Name]['inputs'] & { + stream: true; + }, options?: AiOptions): Promise; + // Normal (default) - known model + run(model: Name, inputs: AiModelList[Name]['inputs'], options?: AiOptions): Promise; + // Unknown model (fallback). + // + // The `Exclude<..., keyof AiModelList>` constraint forces TypeScript to + // route any model name that is a literal key of `AiModelList` to one of + // the known-model overloads above (so input/output mismatches surface as + // type errors rather than silently falling back to `Record`). + // Names that aren't in `AiModelList` — e.g. third-party gateway models + // like `"google/nano-banana"` — still hit this overload. + run(model: Model extends keyof AiModelList ? never : Model, inputs: Record, options?: AiOptions): Promise>; + models(params?: AiModelsSearchParams): Promise; + toMarkdown(): ToMarkdownService; + toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; + toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; +} +type GatewayRetries = { + maxAttempts?: 1 | 2 | 3 | 4 | 5; + retryDelayMs?: number; + backoff?: 'constant' | 'linear' | 'exponential'; +}; +type GatewayOptions = { + id: string; + cacheKey?: string; + cacheTtl?: number; + skipCache?: boolean; + metadata?: Record; + collectLog?: boolean; + eventId?: string; + requestTimeoutMs?: number; + retries?: GatewayRetries; +}; +type UniversalGatewayOptions = Exclude & { + /** + ** @deprecated + */ + id?: string; +}; +type AiGatewayPatchLog = { + score?: number | null; + feedback?: -1 | 1 | null; + metadata?: Record | null; +}; +type AiGatewayLog = { + id: string; + provider: string; + model: string; + model_type?: string; + path: string; + duration: number; + request_type?: string; + request_content_type?: string; + status_code: number; + response_content_type?: string; + success: boolean; + cached: boolean; + tokens_in?: number; + tokens_out?: number; + metadata?: Record; + step?: number; + cost?: number; + custom_cost?: boolean; + request_size: number; + request_head?: string; + request_head_complete: boolean; + response_size: number; + response_head?: string; + response_head_complete: boolean; + created_at: Date; +}; +type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly'; +type AIGatewayHeaders = { + 'cf-aig-metadata': Record | string; + 'cf-aig-custom-cost': { + per_token_in?: number; + per_token_out?: number; + } | { + total_cost?: number; + } | string; + 'cf-aig-cache-ttl': number | string; + 'cf-aig-skip-cache': boolean | string; + 'cf-aig-cache-key': string; + 'cf-aig-event-id': string; + 'cf-aig-request-timeout': number | string; + 'cf-aig-max-attempts': number | string; + 'cf-aig-retry-delay': number | string; + 'cf-aig-backoff': string; + 'cf-aig-collect-log': boolean | string; + Authorization: string; + 'Content-Type': string; + [key: string]: string | number | boolean | object; +}; +type AIGatewayUniversalRequest = { + provider: AIGatewayProviders | string; // eslint-disable-line + endpoint: string; + headers: Partial; + query: unknown; +}; +interface AiGatewayInternalError extends Error { +} +interface AiGatewayLogNotFound extends Error { +} +declare abstract class AiGateway { + patchLog(logId: string, data: AiGatewayPatchLog): Promise; + getLog(logId: string): Promise; + run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { + gateway?: UniversalGatewayOptions; + extraHeaders?: object; + signal?: AbortSignal; + }): Promise; + getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line +} +// Copyright (c) 2022-2025 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Artifacts — Git-compatible file storage on Cloudflare Workers. + * + * Provides programmatic access to create, manage, and fork repositories, + * and to issue and revoke scoped access tokens. + */ +/** Information about a repository. */ +interface ArtifactsRepoInfo { + /** Unique repository ID. */ + id: string; + /** Repository name. */ + name: string; + /** Repository description, or null if not set. */ + description: string | null; + /** Default branch name (e.g. "main"). */ + defaultBranch: string; + /** ISO 8601 creation timestamp. */ + createdAt: string; + /** ISO 8601 last-updated timestamp. */ + updatedAt: string; + /** ISO 8601 timestamp of the last push, or null if never pushed. */ + lastPushAt: string | null; + /** Fork source (e.g. "github:owner/repo", "artifacts:namespace/repo"), or null if not a fork. */ + source: string | null; + /** Whether the repository is read-only. */ + readOnly: boolean; + /** HTTPS git remote URL. */ + remote: string; +} +/** Result of creating a repository — includes the initial access token. */ +interface ArtifactsCreateRepoResult { + /** Unique repository ID. */ + id: string; + /** Repository name. */ + name: string; + /** Repository description, or null if not set. */ + description: string | null; + /** Default branch name. */ + defaultBranch: string; + /** HTTPS git remote URL. */ + remote: string; + /** Plaintext access token (only returned at creation time). */ + token: string; + /** ISO 8601 token expiry timestamp. */ + tokenExpiresAt: string; +} +/** Paginated list of repositories. */ +interface ArtifactsRepoListResult { + /** Repositories in this page (without the `remote` field). */ + repos: Omit[]; + /** Total number of repositories in the namespace. */ + total: number; + /** Cursor for the next page, if there are more results. */ + cursor?: string; +} +/** Result of creating an access token. */ +interface ArtifactsCreateTokenResult { + /** Unique token ID. */ + id: string; + /** Plaintext token (only returned at creation time). */ + plaintext: string; + /** Token scope: "read" or "write". */ + scope: 'read' | 'write'; + /** ISO 8601 token expiry timestamp. */ + expiresAt: string; +} +/** Token metadata (no plaintext). */ +interface ArtifactsTokenInfo { + /** Unique token ID. */ + id: string; + /** Token scope: "read" or "write". */ + scope: 'read' | 'write'; + /** Token state: "active", "expired", or "revoked". */ + state: 'active' | 'expired' | 'revoked'; + /** ISO 8601 creation timestamp. */ + createdAt: string; + /** ISO 8601 expiry timestamp. */ + expiresAt: string; +} +/** Paginated list of tokens for a repository. */ +interface ArtifactsTokenListResult { + /** Tokens in this page. */ + tokens: ArtifactsTokenInfo[]; + /** Total number of tokens for the repository. */ + total: number; +} +/** + * Handle for a single repository. Returned by Artifacts.get(). + * + * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs. + */ +interface ArtifactsRepo extends ArtifactsRepoInfo { + /** + * Create an access token for this repo. + * @param scope Token scope: "write" (default) or "read". + * @param ttl Time-to-live in seconds (default 86400, min 60, max 31536000). + * @throws {ArtifactsError} with code `INVALID_TTL` if ttl is out of range. + */ + createToken(scope?: 'write' | 'read', ttl?: number): Promise; + /** List tokens for this repo (metadata only, no plaintext). */ + listTokens(): Promise; + /** + * Revoke a token by plaintext or ID. + * @param tokenOrId Plaintext token or token ID. + * @returns true if revoked, false if not found. + * @throws {ArtifactsError} with code `INVALID_INPUT` if tokenOrId is empty. + */ + revokeToken(tokenOrId: string): Promise; + // ── Fork ── + /** + * Fork this repo to a new repo. + * @param name Target repository name. + * @param opts Optional: description, readOnly flag, defaultBranchOnly (default true). + * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid. + * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists. + * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if a fork is already running. + */ + fork(name: string, opts?: { + description?: string; + readOnly?: boolean; + defaultBranchOnly?: boolean; + }): Promise; +} +// ── Error types ────────────────────────────────────────────────────────────── +/** + * Error codes returned by Artifacts binding operations. + * + * Each code maps to a numeric code available on `ArtifactsError.numericCode`. + */ +type ArtifactsErrorCode = 'ALREADY_EXISTS' | 'NOT_FOUND' | 'IMPORT_IN_PROGRESS' | 'FORK_IN_PROGRESS' | 'INVALID_INPUT' | 'INVALID_REPO_NAME' | 'INVALID_TTL' | 'INVALID_URL' | 'REMOTE_AUTH_REQUIRED' | 'UPSTREAM_UNAVAILABLE' | 'MEMORY_LIMIT' | 'INTERNAL_ERROR'; +/** + * Error thrown by Artifacts binding operations. + * + * Uses a string `.code` discriminator following the Cloudflare platform + * convention (StreamError, ImagesError, etc.). The `.numericCode` matches + * the REST API `errors[].code` values. + */ +interface ArtifactsError extends Error { + readonly name: 'ArtifactsError'; + /** String error code for programmatic matching. */ + readonly code: ArtifactsErrorCode; + /** Numeric error code matching the REST API. */ + readonly numericCode: number; +} +// ── Binding ────────────────────────────────────────────────────────────────── +/** + * Artifacts binding — namespace-level operations. + * + * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs. + */ +interface Artifacts { + /** + * Create a new repository with an initial access token. + * @param name Repository name (alphanumeric, dots, hyphens, underscores). + * @param opts Optional: readOnly flag, description, default branch name. + * @returns Repo metadata with initial token. + * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid. + * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the repo already exists. + */ + create(name: string, opts?: { + readOnly?: boolean; + description?: string; + setDefaultBranch?: string; + }): Promise; + /** + * Get a handle to an existing repository. + * @param name Repository name. + * @returns Repo handle. + * @throws {ArtifactsError} with code `NOT_FOUND` if the repo does not exist. + * @throws {ArtifactsError} with code `IMPORT_IN_PROGRESS` if the repo is still importing. + * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if the repo is still forking. + */ + get(name: string): Promise; + /** + * Import a repository from an external git remote. + * @param params Source URL and optional branch/depth, plus target name and options. + * @returns Repo metadata with initial token. + * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if the target name is invalid. + * @throws {ArtifactsError} with code `INVALID_INPUT` if the source URL is not valid HTTPS. + * @throws {ArtifactsError} with code `INVALID_URL` if the source URL does not point to a git repository. + * @throws {ArtifactsError} with code `REMOTE_AUTH_REQUIRED` if the remote requires authentication. + * @throws {ArtifactsError} with code `NOT_FOUND` if the remote repository does not exist. + * @throws {ArtifactsError} with code `UPSTREAM_UNAVAILABLE` if the remote cannot be reached. + * @throws {ArtifactsError} with code `MEMORY_LIMIT` if the import exceeds service memory limits. + * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists. + */ + import(params: { + source: { + url: string; + branch?: string; + depth?: number; + }; + target: { + name: string; + opts?: { + description?: string; + readOnly?: boolean; + }; + }; + }): Promise; + /** + * List repositories with cursor-based pagination. + * @param opts Optional: limit (1–200, default 50), cursor for next page. + */ + list(opts?: { + limit?: number; + cursor?: string; + }): Promise; + /** + * Delete a repository and all associated tokens. + * @param name Repository name. + * @returns true if deleted, false if not found. + * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid. + */ + delete(name: string): Promise; +} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGInternalError extends Error { +} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGNotFoundError extends Error { +} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGUnauthorizedError extends Error { +} +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +interface AutoRAGNameNotSetError extends Error { +} +type ComparisonFilter = { + key: string; + type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; + value: string | number | boolean; +}; +type CompoundFilter = { + type: 'and' | 'or'; + filters: ComparisonFilter[]; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagSearchRequest = { + query: string; + filters?: CompoundFilter | ComparisonFilter; + max_num_results?: number; + ranking_options?: { + ranker?: string; + score_threshold?: number; + }; + reranking?: { + enabled?: boolean; + model?: string; + }; + rewrite_query?: boolean; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagAiSearchRequest = AutoRagSearchRequest & { + stream?: boolean; + system_prompt?: string; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagAiSearchRequestStreaming = Omit & { + stream: true; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagSearchResponse = { + object: 'vector_store.search_results.page'; + search_query: string; + data: { + file_id: string; + filename: string; + score: number; + attributes: Record; + content: { + type: 'text'; + text: string; + }[]; + }[]; + has_more: boolean; + next_page: string | null; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagListResponse = { + id: string; + enable: boolean; + type: string; + source: string; + vectorize_name: string; + paused: boolean; + status: string; +}[]; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +type AutoRagAiSearchResponse = AutoRagSearchResponse & { + response: string; +}; +/** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ +declare abstract class AutoRAG { + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + list(): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + search(params: AutoRagSearchRequest): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; + /** + * @deprecated Use the standalone AI Search Workers binding instead. + * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; +} +type BrowserRunLifecycleEvent = 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2'; +type BrowserRunResourceType = 'document' | 'stylesheet' | 'image' | 'media' | 'font' | 'script' | 'texttrack' | 'xhr' | 'fetch' | 'prefetch' | 'eventsource' | 'websocket' | 'manifest' | 'signedexchange' | 'ping' | 'cspviolationreport' | 'preflight' | 'other'; +/** Options fields shared by all quick actions. */ +interface BrowserRunBaseOptions { + /** Adds ``; - return htmlResponse(authPage('Sign in to Kilo MCP', body)); + return htmlResponse(authPage('Connect to Kilo MCP', body)); } export type KiloPollOutcome = diff --git a/services/kilo-mcp/src/oauth-pages/org-picker.test.ts b/services/kilo-mcp/src/oauth-pages/org-picker.test.ts index a93473a65d..175db1139a 100644 --- a/services/kilo-mcp/src/oauth-pages/org-picker.test.ts +++ b/services/kilo-mcp/src/oauth-pages/org-picker.test.ts @@ -269,7 +269,7 @@ describe('GET /authorize/org (picker render)', () => { }); expect(response.status).toBe(200); const html = await response.text(); - expect(html).toContain('Sign in to Kilo MCP'); + expect(html).toContain('Connect to Kilo MCP'); expect(html).toContain(`${WEB}/device-auth?code=${record.deviceAuthCode}`); }); diff --git a/services/kilo-mcp/src/oauth-pages/org-picker.ts b/services/kilo-mcp/src/oauth-pages/org-picker.ts index 9d34d2cd5d..c65634b2da 100644 --- a/services/kilo-mcp/src/oauth-pages/org-picker.ts +++ b/services/kilo-mcp/src/oauth-pages/org-picker.ts @@ -49,14 +49,14 @@ export const PERSONAL_ORG_ID = 'personal'; /** The catalog query used to list the caller's orgs (read-only, in the dump). */ export const ORG_LIST_QUERY_PATH = 'organizations.list'; +// The picker needs a radio-list layout the shared shell does not carry. Colors +// and the submit CTA come from the shell's Kilo Cloud palette (auth/http.ts). const PICKER_STYLE = '.org{display:flex;align-items:center;gap:10px;padding:12px 14px;margin:8px 0;' + - 'border:1px solid #262a34;border-radius:10px;cursor:pointer}' + - '.org input{accent-color:#5b5bd6}' + - // the shared shell styles a.cta only; the submit button gets the same CTA look. - 'button.cta{display:inline-block;margin-top:16px;padding:12px 20px;border-radius:8px;' + - 'background:#5b5bd6;color:#fff;font-weight:600;border:0;cursor:pointer}' + - '.err{color:#f87171}'; + 'border:1px solid var(--border);border-radius:10px;cursor:pointer;background:var(--input)}' + + '.org:hover{border-color:var(--border-strong);background:var(--hover)}' + + '.org input{accent-color:var(--primary);margin:0}' + + '.err{color:var(--danger)}'; /** * Fetch the Kilo identity's organizations by calling the catalog tRPC query From c40d9584143ddac9c1d699a4f9385045346080db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Igor=20=C5=A0=C4=87eki=C4=87?= Date: Thu, 10 Sep 2026 14:51:34 +0200 Subject: [PATCH 05/11] ci(kilo-mcp): accept a durable Kilo API key for catalog summaries Pass KILO_API_KEY and KILO_ORG_ID from repo secrets alongside the optional KILO_AUTH_CONTENT auth store, so the catalog jobs can run on an API key instead of a personal CLI login. --- .github/workflows/kilo-mcp-catalog.yml | 8 ++++++++ scripts/kilo-mcp-catalog.test.mjs | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/.github/workflows/kilo-mcp-catalog.yml b/.github/workflows/kilo-mcp-catalog.yml index c615ce0c3f..f96e5d0278 100644 --- a/.github/workflows/kilo-mcp-catalog.yml +++ b/.github/workflows/kilo-mcp-catalog.yml @@ -99,7 +99,11 @@ jobs: # requirement 6; a same-repo dump failure stays fatal. continue-on-error: ${{ github.event.pull_request.head.repo.fork == true }} env: + # Either a signed-in CLI auth store (KILO_AUTH_CONTENT) or a + # durable Kilo API key + org (KILO_API_KEY / KILO_ORG_ID). KILO_AUTH_CONTENT: ${{ secrets.MCP_CATALOG_KILO_AUTH }} + KILO_API_KEY: ${{ secrets.MCP_CATALOG_KILO_API_KEY }} + KILO_ORG_ID: ${{ secrets.MCP_CATALOG_KILO_ORG_ID }} run: pnpm --filter web script src/scripts/mcp-catalog/dump.ts # Requirement 6 when the dump itself cannot run: the drift-gated fork @@ -236,7 +240,11 @@ jobs: # (requirement 8); keep-edit semantics leave author edits alone. - name: Regenerate catalog.json env: + # Either a signed-in CLI auth store (KILO_AUTH_CONTENT) or a + # durable Kilo API key + org (KILO_API_KEY / KILO_ORG_ID). KILO_AUTH_CONTENT: ${{ secrets.MCP_CATALOG_KILO_AUTH }} + KILO_API_KEY: ${{ secrets.MCP_CATALOG_KILO_API_KEY }} + KILO_ORG_ID: ${{ secrets.MCP_CATALOG_KILO_ORG_ID }} run: pnpm --filter web script src/scripts/mcp-catalog/dump.ts # Vectorize upsert (requirement 9). The index name and account id match diff --git a/scripts/kilo-mcp-catalog.test.mjs b/scripts/kilo-mcp-catalog.test.mjs index 035e252fa3..67b829695a 100644 --- a/scripts/kilo-mcp-catalog.test.mjs +++ b/scripts/kilo-mcp-catalog.test.mjs @@ -54,6 +54,16 @@ function validate(workflow) { '${{ secrets.MCP_CATALOG_KILO_AUTH }}', 'PR dump exports the Kilo CLI credential from the repo secret' ); + assert.equal( + prDump.env?.KILO_API_KEY, + '${{ secrets.MCP_CATALOG_KILO_API_KEY }}', + 'PR dump accepts a durable Kilo API key' + ); + assert.equal( + prDump.env?.KILO_ORG_ID, + '${{ secrets.MCP_CATALOG_KILO_ORG_ID }}', + 'PR dump accepts the Kilo org for the API key' + ); findStep( pr, step => step.run === kiloInstallCommand, @@ -154,6 +164,11 @@ function validate(workflow) { '${{ secrets.MCP_CATALOG_KILO_AUTH }}', 'merge dump exports the Kilo CLI credential' ); + assert.equal( + mergeDump.env?.KILO_API_KEY, + '${{ secrets.MCP_CATALOG_KILO_API_KEY }}', + 'merge dump accepts a durable Kilo API key' + ); findStep( merge, step => step.run === kiloInstallCommand, From d6060332d51de7c9b62c2131181d38122ea3f9d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Igor=20=C5=A0=C4=87eki=C4=87?= Date: Thu, 10 Sep 2026 15:04:40 +0200 Subject: [PATCH 06/11] fix(kilo-mcp): match the documented kilo run JSON event contract Review found runKiloCompletion concatenated every part.type === 'text' event, while the in-repo contract (auto-routing-benchmark/src/kilo-events.ts) takes only completed text events (part.time.end set) and also accepts the flattened evt.text shape. - A streaming delta plus the final text produced garbled JSON. - A flattened event produced no text, so the dump failed. parseKiloCompletion now mirrors that contract. Add unit tests for the delta, flattened, and malformed-line cases. --- .../src/scripts/mcp-catalog/catalog.test.ts | 37 +++++++++++- apps/web/src/scripts/mcp-catalog/catalog.ts | 58 ++++++++++++------- 2 files changed, 73 insertions(+), 22 deletions(-) diff --git a/apps/web/src/scripts/mcp-catalog/catalog.test.ts b/apps/web/src/scripts/mcp-catalog/catalog.test.ts index 7a7c9e679e..7713c0abfb 100644 --- a/apps/web/src/scripts/mcp-catalog/catalog.test.ts +++ b/apps/web/src/scripts/mcp-catalog/catalog.test.ts @@ -20,6 +20,7 @@ import { buildCatalogRows, collectCatalogLeaves, generateMissingSummaries, + parseKiloCompletion, readCommittedSummaries, runKiloCompletion, type CatalogLeaf, @@ -248,7 +249,7 @@ describe('mcp-catalog catalog', () => { const bin = join(dir, 'fake-kilo'); writeFileSync( bin, - `#!/bin/sh\ncat > /dev/null\nprintf '%s\\n' '{"type":"step_start","part":{"type":"step-start"}}' '{"type":"text","part":{"type":"text","text":"{\\"usageAnalytics.probe\\":\\"ok\\"}"}}'\n`, + `#!/bin/sh\ncat > /dev/null\nprintf '%s\\n' '{"type":"step_start","part":{"type":"step-start"}}' '{"type":"text","part":{"type":"text","text":"{\\"usageAnalytics.probe\\":\\"ok\\"}","time":{"end":1}}}'\n`, { mode: 0o755 } ); const previous = process.env.KILO_BIN; @@ -264,6 +265,40 @@ describe('mcp-catalog catalog', () => { } }); + it('takes only completed text events, ignoring in-progress streaming deltas', () => { + // Same contract as services/auto-routing-benchmark/src/kilo-events.ts. + // Concatenating the deltas would garble the JSON the dump has to parse. + expect( + parseKiloCompletion([ + JSON.stringify({ + type: 'text', + part: { type: 'text', text: '{"a"', time: { start: 1 } }, + }), + JSON.stringify({ + type: 'text', + part: { type: 'text', text: '{"a":1}', time: { end: 2 } }, + }), + ]) + ).toBe('{"a":1}'); + }); + + it('accepts the flattened top-level event shape', () => { + expect( + parseKiloCompletion([JSON.stringify({ type: 'text', text: '{"a":1}', time: { end: 2 } })]) + ).toBe('{"a":1}'); + }); + + it('skips malformed lines without throwing', () => { + expect( + parseKiloCompletion([ + 'not json', + '', + '{ broken', + JSON.stringify({ type: 'text', part: { type: 'text', text: 'x', time: { end: 1 } } }), + ]) + ).toBe('x'); + }); + it('marks a non-zero Kilo CLI exit as retryable and names the failed batch', () => { const dir = mkdtempSync(join(tmpdir(), 'kilo-summary-')); const bin = join(dir, 'fake-kilo'); diff --git a/apps/web/src/scripts/mcp-catalog/catalog.ts b/apps/web/src/scripts/mcp-catalog/catalog.ts index a51c2f2040..603a054301 100644 --- a/apps/web/src/scripts/mcp-catalog/catalog.ts +++ b/apps/web/src/scripts/mcp-catalog/catalog.ts @@ -503,6 +503,41 @@ function isNonRetryableCliFailure(detail: string): boolean { return /sign in|not logged in|unauthor|api key|401|403/i.test(detail); } +/** + * Reduce the `kilo run --format json` NDJSON stream to the assistant answer. + * + * Mirrors the in-repo contract in + * `services/auto-routing-benchmark/src/kilo-events.ts`: only *completed* text + * events count (`part.time.end` set), so in-progress streaming deltas are not + * concatenated onto the final text. Both the nested `evt.part.*` and the + * flattened `evt.*` shapes are accepted, because the event shape varies + * across CLI versions. Malformed lines are skipped, never thrown on. + */ +export function parseKiloCompletion(lines: string[]): string { + const texts: string[] = []; + for (const line of lines) { + let event: unknown; + try { + event = JSON.parse(line); + } catch { + continue; + } + if (event === null || typeof event !== 'object') continue; + const evt = event as { + type?: unknown; + text?: unknown; + time?: { end?: unknown }; + part?: { type?: unknown; text?: unknown; time?: { end?: unknown } }; + }; + if (evt.type !== 'text') continue; + const end = evt.part?.time?.end ?? evt.time?.end; + if (end === undefined || end === null) continue; + const text = typeof evt.part?.text === 'string' ? evt.part.text : evt.text; + if (typeof text === 'string') texts.push(text); + } + return texts.join('\n'); +} + /** * Run one summary completion through the Kilo CLI: * `kilo run --model --variant --format json`. @@ -510,7 +545,7 @@ function isNonRetryableCliFailure(detail: string): boolean { * The prompt arrives on stdin, so batch size is never bounded by `ARGV_MAX`. * The CLI runs in the OS temp directory so it does not load this repo's * project config or agent instructions. Its JSON event stream is reduced to - * the concatenated assistant text parts. + * the concatenated completed assistant text parts. * * Never logs credentials: stdout is the model reply, stderr is only surfaced * (truncated) inside error messages. @@ -552,26 +587,7 @@ export function runKiloCompletion(prompt: string, batchLabel: string): string { ); } - const texts: string[] = []; - for (const line of (result.stdout ?? '').split('\n')) { - const trimmed = line.trim(); - if (!trimmed.startsWith('{')) continue; - let event: unknown; - try { - event = JSON.parse(trimmed); - } catch { - continue; - } - const part = (event as { part?: { type?: unknown; text?: unknown } }).part; - if ( - (event as { type?: unknown }).type === 'text' && - part?.type === 'text' && - typeof part.text === 'string' - ) { - texts.push(part.text); - } - } - const content = texts.join(''); + const content = parseKiloCompletion((result.stdout ?? '').split('\n')); if (content.trim() === '') { throw new CatalogSummaryError( `Kilo CLI returned no summary completion for ${batchLabel}${detail ? ` — ${detail}` : ''}`, From efedce1b52058c73e098cfe87d8e90b5697c631e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Igor=20=C5=A0=C4=87eki=C4=87?= Date: Thu, 10 Sep 2026 15:15:14 +0200 Subject: [PATCH 07/11] feat(kilo-mcp): serve production on mcp.kiloapps.io Use the shared kiloapps.io zone instead of kilosessions.ai. The issuer is derived from the request URL, so the OAuth metadata advertises https://mcp.kiloapps.io with no extra config. --- services/kilo-mcp/wrangler.jsonc | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/services/kilo-mcp/wrangler.jsonc b/services/kilo-mcp/wrangler.jsonc index a6c7a1c6b4..4bfee02f1c 100644 --- a/services/kilo-mcp/wrangler.jsonc +++ b/services/kilo-mcp/wrangler.jsonc @@ -6,15 +6,15 @@ "compatibility_date": "2025-09-01", "compatibility_flags": ["nodejs_compat"], // Production is reached only through its custom domain, so the OAuth issuer - // in the metadata is always https://kilo-mcp.kilosessions.ai (the issuer is - // derived from the request URL — src/auth/metadata.ts). The workers.dev URL - // stays disabled in prod; the `dev` env below keeps its own workers.dev URL. + // in the metadata is always https://mcp.kiloapps.io (the issuer is derived + // from the request URL — src/auth/metadata.ts). The workers.dev URL stays + // disabled in prod; the `dev` env below keeps its own workers.dev URL. "workers_dev": false, "preview_urls": false, "routes": [ { - "pattern": "kilo-mcp.kilosessions.ai", - "zone_name": "kilosessions.ai", + "pattern": "mcp.kiloapps.io", + "zone_name": "kiloapps.io", "custom_domain": true, }, ], From cd3328854f4f7a35399ce05e749495aff76a8db6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Igor=20=C5=A0=C4=87eki=C4=87?= Date: Thu, 10 Sep 2026 16:16:51 +0200 Subject: [PATCH 08/11] feat(web): mint catalog tokens for the benchmarking service account The MCP catalog dump shells out to `kilo run`, which needs a Kilo API token. Add POST /api/internal/mcp-catalog/token to exchange a dedicated shared secret for a 1-hour token that belongs to the benchmarking service account, instead of a maintainer's personal CLI credential. --- .../internal/mcp-catalog/token/route.test.ts | 105 ++++++++++++++++++ .../api/internal/mcp-catalog/token/route.ts | 83 ++++++++++++++ apps/web/src/lib/config.server.ts | 4 + docs/token-issuance-policy.md | 3 +- 4 files changed, 194 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/app/api/internal/mcp-catalog/token/route.test.ts create mode 100644 apps/web/src/app/api/internal/mcp-catalog/token/route.ts diff --git a/apps/web/src/app/api/internal/mcp-catalog/token/route.test.ts b/apps/web/src/app/api/internal/mcp-catalog/token/route.test.ts new file mode 100644 index 0000000000..6bcef95b0f --- /dev/null +++ b/apps/web/src/app/api/internal/mcp-catalog/token/route.test.ts @@ -0,0 +1,105 @@ +import { NextRequest } from 'next/server'; +import { generateApiToken } from '@/lib/tokens'; +import { + DEFAULT_BENCHMARK_ORG_ID, + DEFAULT_BENCHMARK_USER_ID, +} from '@kilocode/auto-routing-contracts'; + +jest.mock('@/lib/config.server', () => ({ + MCP_CATALOG_TOKEN_SECRET: 'catalog-secret', +})); + +const mockRows: unknown[] = []; +const mockMembershipRows: unknown[] = []; +let mockSelectCallCount = 0; +jest.mock('@/lib/drizzle', () => ({ + db: { + select: () => { + const callIndex = mockSelectCallCount++; + return { + from: () => ({ + where: () => ({ + limit: () => Promise.resolve(callIndex === 0 ? mockRows : mockMembershipRows), + }), + }), + }; + }, + }, +})); + +jest.mock('@/lib/tokens', () => ({ + generateApiToken: jest.fn(() => 'minted-token'), +})); + +import { POST } from './route'; + +const mockGenerateApiToken = jest.mocked(generateApiToken); + +function createRequest(headers: Record = {}) { + return new NextRequest('http://localhost:3000/api/internal/mcp-catalog/token', { + method: 'POST', + headers: { 'content-type': 'application/json', ...headers }, + }); +} + +describe('POST /api/internal/mcp-catalog/token', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockRows.length = 0; + mockMembershipRows.length = 0; + mockSelectCallCount = 0; + }); + + it('returns 401 without the bearer secret', async () => { + mockRows.push({ id: DEFAULT_BENCHMARK_USER_ID, api_token_pepper: 'pepper' }); + const res = await POST(createRequest()); + expect(res.status).toBe(401); + expect(mockGenerateApiToken).not.toHaveBeenCalled(); + }); + + it('returns 401 with the wrong bearer secret', async () => { + const res = await POST(createRequest({ authorization: 'Bearer wrong' })); + expect(res.status).toBe(401); + expect(mockGenerateApiToken).not.toHaveBeenCalled(); + }); + + it('returns 404 when the benchmark service account does not exist', async () => { + const res = await POST(createRequest({ authorization: 'Bearer catalog-secret' })); + expect(res.status).toBe(404); + expect(mockGenerateApiToken).not.toHaveBeenCalled(); + }); + + it('returns 404 when the benchmark organization membership is missing', async () => { + mockRows.push({ id: DEFAULT_BENCHMARK_USER_ID, api_token_pepper: 'pepper' }); + const res = await POST(createRequest({ authorization: 'Bearer catalog-secret' })); + expect(res.status).toBe(404); + expect(mockGenerateApiToken).not.toHaveBeenCalled(); + }); + + it('mints a 1h benchmarking token scoped to the benchmark organization', async () => { + const user = { id: DEFAULT_BENCHMARK_USER_ID, api_token_pepper: 'pepper' }; + mockRows.push(user); + mockMembershipRows.push({ role: 'owner' }); + + const res = await POST(createRequest({ authorization: 'Bearer catalog-secret' })); + + expect(res.status).toBe(200); + const json = (await res.json()) as { + token: string; + organizationId: string; + expiresAt: string; + }; + expect(json.token).toBe('minted-token'); + expect(json.organizationId).toBe(DEFAULT_BENCHMARK_ORG_ID); + expect(typeof json.expiresAt).toBe('string'); + expect(mockGenerateApiToken).toHaveBeenCalledWith( + user, + { + tokenSource: 'mcp-catalog', + organizationId: DEFAULT_BENCHMARK_ORG_ID, + organizationRole: 'owner', + }, + { expiresIn: 60 * 60 } + ); + }); +}); diff --git a/apps/web/src/app/api/internal/mcp-catalog/token/route.ts b/apps/web/src/app/api/internal/mcp-catalog/token/route.ts new file mode 100644 index 0000000000..2a46d669f6 --- /dev/null +++ b/apps/web/src/app/api/internal/mcp-catalog/token/route.ts @@ -0,0 +1,83 @@ +/** + * Internal API: mint a short-lived Kilo API token for the MCP catalog dump. + * + * Called by `.github/workflows/kilo-mcp-catalog.yml`. The catalog dump shells + * out to `kilo run` to generate missing search summaries, and the CLI + * authenticates against the gateway with a user API token. The workflow holds + * `MCP_CATALOG_TOKEN_SECRET`, a shared secret whose only purpose is this mint, + * and exchanges it for a token that belongs to the benchmarking service + * account instead of a maintainer's personal login. + * + * The minted token is a full user API token (includes `apiTokenPepper`) so the + * gateway accepts it as a real user token. It expires in 1 hour — a single + * catalog dump run — and is scoped to the benchmarking organization. + * + * URL: POST /api/internal/mcp-catalog/token + */ + +import type { NextRequest } from 'next/server'; +import { NextResponse } from 'next/server'; +import { timingSafeEqual } from '@kilocode/encryption'; +import { extractBearerToken } from '@kilocode/worker-utils/extract-bearer-token'; +import { and, eq } from 'drizzle-orm'; +import { + DEFAULT_BENCHMARK_ORG_ID, + DEFAULT_BENCHMARK_USER_ID, +} from '@kilocode/auto-routing-contracts'; +import { kilocode_users, organization_memberships } from '@kilocode/db/schema'; +import { db } from '@/lib/drizzle'; +import { generateApiToken } from '@/lib/tokens'; +import { MCP_CATALOG_TOKEN_SECRET } from '@/lib/config.server'; + +const ONE_HOUR_IN_SECONDS = 60 * 60; + +export async function POST(req: NextRequest) { + const secret = extractBearerToken(req.headers.get('authorization')); + if (!MCP_CATALOG_TOKEN_SECRET || !secret || !timingSafeEqual(secret, MCP_CATALOG_TOKEN_SECRET)) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const [user] = await db + .select() + .from(kilocode_users) + .where(eq(kilocode_users.id, DEFAULT_BENCHMARK_USER_ID)) + .limit(1); + + if (!user) { + return NextResponse.json({ error: 'Benchmark service account not found' }, { status: 404 }); + } + + const [membership] = await db + .select({ role: organization_memberships.role }) + .from(organization_memberships) + .where( + and( + eq(organization_memberships.kilo_user_id, DEFAULT_BENCHMARK_USER_ID), + eq(organization_memberships.organization_id, DEFAULT_BENCHMARK_ORG_ID) + ) + ) + .limit(1); + + if (!membership) { + return NextResponse.json( + { error: 'Benchmark organization membership not found' }, + { status: 404 } + ); + } + + const apiToken = generateApiToken( + user, + { + tokenSource: 'mcp-catalog', + organizationId: DEFAULT_BENCHMARK_ORG_ID, + organizationRole: membership.role, + }, + { expiresIn: ONE_HOUR_IN_SECONDS } + ); + + return NextResponse.json({ + token: apiToken, + organizationId: DEFAULT_BENCHMARK_ORG_ID, + expiresAt: new Date(Date.now() + ONE_HOUR_IN_SECONDS * 1000).toISOString(), + }); +} diff --git a/apps/web/src/lib/config.server.ts b/apps/web/src/lib/config.server.ts index d093c75121..1aab929323 100644 --- a/apps/web/src/lib/config.server.ts +++ b/apps/web/src/lib/config.server.ts @@ -60,6 +60,10 @@ export const MISTRAL_API_KEY = getEnvVariable('MISTRAL_API_KEY'); export const INCEPTION_API_KEY = getEnvVariable('INCEPTION_API_KEY'); export const EXA_API_KEY = getEnvVariable('EXA_API_KEY'); export const INTERNAL_API_SECRET = getEnvVariable('INTERNAL_API_SECRET'); +// Shared secret with the MCP catalog CI job +// (.github/workflows/kilo-mcp-catalog.yml). It authenticates only the mint in +// app/api/internal/mcp-catalog/token; it is never accepted as a Kilo credential. +export const MCP_CATALOG_TOKEN_SECRET = getEnvVariable('MCP_CATALOG_TOKEN_SECRET'); export function isBoundedInternalServiceTokenIssuanceEnabled(): boolean { return getEnvVariable('BOUNDED_INTERNAL_SERVICE_TOKENS_ENABLED') === 'true'; } diff --git a/docs/token-issuance-policy.md b/docs/token-issuance-policy.md index 50aac3eab4..e425c07c5c 100644 --- a/docs/token-issuance-policy.md +++ b/docs/token-issuance-policy.md @@ -104,12 +104,13 @@ This is a concrete, selective map from the shared Kilo token entry points. It do | User-data export | `apps/web/src/lib/user-data-export-worker-client.ts` | `services/user-data-export/src/index.ts` | `user-data-export` | Preserve `user-data-export` | Requires its additional internal API key and five-minute assertion limit. | | Organization and attribution | `apps/web/src/app/api/organizations/[id]/user-tokens/route.ts` | `services/ai-attribution/src/util/auth.ts` | None | `ai-attribution` | Organization-bearing tokens have other valid uses; attribution consumer transport was not fully traced. | | Auto-routing benchmark | `apps/web/src/app/api/internal/auto-routing-benchmark/token/route.ts` | `services/auto-routing-benchmark/src/run.ts` decider CLI | None | `kilo-api` / `kilo-gateway` based on actual downstream call | `tokenSource: 'auto-routing-benchmark'` identifies issuance, not an authorization audience; full CLI call graph is unresolved. | +| MCP catalog dump | `apps/web/src/app/api/internal/mcp-catalog/token/route.ts` | `.github/workflows/kilo-mcp-catalog.yml` `kilo run` (benchmarking service account) | None | `kilo-api` / `kilo-gateway` based on actual downstream call | `tokenSource: 'mcp-catalog'` identifies issuance; the `MCP_CATALOG_TOKEN_SECRET` shared secret only authenticates the mint and is never a Kilo credential. | ## Existing markers and excluded families Core optional markers accepted by the shared schema are documented in `packages/worker-utils/src/kilo-token.ts`: `tokenSource`, `botId`, `internalApiUse`, `createdOnPlatform`, `deviceAuthRequestCode`, `deviceSessionId`, admin/Gastown flags, and organization claims. -- Confirmed `tokenSource` values: `cloud-agent`, `kilo-chat`, `auto-routing-benchmark`. +- Confirmed `tokenSource` values: `cloud-agent`, `kilo-chat`, `auto-routing-benchmark`, `mcp-catalog`. - Confirmed `botId` values: `reviewer`, `auto-fix`, `auto-triage`, `discord-bot`, `webhook-bot`. - `internalApiUse` and `createdOnPlatform` are additional automation markers; `services/security-auto-analysis/src/token.ts` emits `internalApiUse: true` and `createdOnPlatform: 'security-agent'`. - No universal signed system marker or reliable system-user-ID convention was confirmed. From 556ff144649127cff84db9721057643e4e1c3208 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Igor=20=C5=A0=C4=87eki=C4=87?= Date: Thu, 10 Sep 2026 16:16:56 +0200 Subject: [PATCH 09/11] ci(kilo-mcp): make the catalog check required and credential-safe Two changes to the catalog workflow: - Run it on every PR and gate the work on a change-detection step, so `catalog (PR)` can be a required check without leaving unrelated PRs blocked on an expected-but-skipped workflow. Removes catalog drift. - Mint a short-lived service-account token instead of reading a maintainer's personal CLI credential. Fork PRs still fail with the hand-written-summary recovery. --- .github/workflows/kilo-mcp-catalog.yml | 172 +++++++++++++++++++------ scripts/kilo-mcp-catalog.test.mjs | 114 +++++++++++----- 2 files changed, 221 insertions(+), 65 deletions(-) diff --git a/.github/workflows/kilo-mcp-catalog.yml b/.github/workflows/kilo-mcp-catalog.yml index f96e5d0278..14abd24f21 100644 --- a/.github/workflows/kilo-mcp-catalog.yml +++ b/.github/workflows/kilo-mcp-catalog.yml @@ -6,31 +6,37 @@ name: Kilo MCP catalog # the refreshed catalog.json committed back to the PR branch (requirement 5); # fork PRs cannot be pushed to, so the diff ships as a `catalog.patch` # artifact, a one-line PR comment points at it, and the job fails -# (requirement 6). A fork PR also gets no Kilo CLI credential (GitHub -# withholds secrets from fork events), so when the dump itself cannot run, a -# dedicated step posts the credential-free recovery — hand-written summaries -# in catalog.json, which the keep-edit rule preserves — and fails the job, so +# (requirement 6). A fork PR also gets no catalog credential (GitHub withholds +# secrets from fork events), so when the dump itself cannot run, a dedicated +# step posts the credential-free recovery — hand-written summaries in +# catalog.json, which the keep-edit rule preserves — and fails the job, so # requirement 6 holds on that path too. The PR job never touches Vectorize or -# the embed script -# (requirement 10) and never generates summaries at runtime — only the dump -# does, and it preserves author-edited summaries (requirement 2, s1 keep-edit -# rule). +# the embed script (requirement 10) and never generates summaries at runtime — +# only the dump does, and it preserves author-edited summaries (requirement 2, +# s1 keep-edit rule). +# `catalog (PR)` is a REQUIRED check on main, so this workflow runs on every +# PR (no pull_request path filter). The job is always reported; the +# change-detection step gates the heavy work on the catalog's source paths so +# an unrelated PR still gets a fast, green check instead of "Expected". # - Merge job: gated to main pushes only, so PRs structurally cannot reach it # (requirement 10). Re-runs the dump to fill any summaries that slipped # through (requirement 8), then upserts the Vectorize index (requirement 9). # Production deploys from main, so the committed bundled catalog and the # upserted index stay in lockstep (requirement 22). # +# The dump's `kilo run` never uses a maintainer's personal credential: both jobs +# mint a short-lived benchmarking-service-account token from apps/web +# (POST /api/internal/mcp-catalog/token) using MCP_CATALOG_TOKEN_SECRET, a +# shared secret whose only purpose is that mint. +# # The CI wiring of this file is asserted by scripts/kilo-mcp-catalog.test.mjs # (same pattern as scripts/stacked-ci.test.mjs in .github/workflows/ci.yml). on: + # No paths filter: `catalog (PR)` is a required status check, and a + # path-filtered workflow leaves that check "Expected" (blocking) on every PR + # it skips. The job gates its own work instead. pull_request: - paths: - - 'apps/web/src/**' - - 'services/kilo-mcp/**' - - '.github/workflows/kilo-mcp-catalog.yml' - - 'scripts/kilo-mcp-catalog.test.mjs' push: branches: [main] paths: @@ -58,12 +64,40 @@ jobs: contents: write pull-requests: write steps: + # Full history so the change-detection step below can diff against the + # PR's base sha. - uses: useblacksmith/checkout@41cdeedae8edb2e684ba22896a5fd2a3cb85db6b # v1 + with: + fetch-depth: 0 + + # The job always reports (required check); only the catalog's own paths + # justify the expensive dump. Keep the patterns in sync with the `push` + # filter and with scripts/kilo-mcp-catalog.test.mjs. + - name: Detect catalog-relevant changes + id: catalog_changes + run: | + set -euo pipefail + # If the base object is unavailable, run the catalog work rather than + # skip it: a false "no changes" would break the required check's + # promise, while a redundant dump is harmless. + base="${{ github.event.pull_request.base.sha }}" + if ! git rev-parse --verify "${base}^{commit}" > /dev/null 2>&1; then + echo "catalog=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + if git diff --name-only "$base" HEAD \ + | grep -Eq '^apps/web/src/|^services/kilo-mcp/|^\.github/workflows/kilo-mcp-catalog\.yml$|^scripts/kilo-mcp-catalog\.test\.mjs$'; then + echo "catalog=true" >> "$GITHUB_OUTPUT" + else + echo "catalog=false" >> "$GITHUB_OUTPUT" + fi - name: Setup pnpm + if: steps.catalog_changes.outputs.catalog == 'true' uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v4.4.0 - name: Setup Node + if: steps.catalog_changes.outputs.catalog == 'true' uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version-file: '.nvmrc' @@ -71,39 +105,67 @@ jobs: # The dump shells out to `kilo run` to generate missing summaries. - name: Install Kilo CLI + if: steps.catalog_changes.outputs.catalog == 'true' run: npm install -g @kilocode/cli - name: Install root dependencies + if: steps.catalog_changes.outputs.catalog == 'true' run: pnpm --filter kilocode-monorepo install --frozen-lockfile --ignore-scripts - name: Check catalog workflow wiring + if: steps.catalog_changes.outputs.catalog == 'true' run: node --test scripts/kilo-mcp-catalog.test.mjs - name: Install web dependencies + if: steps.catalog_changes.outputs.catalog == 'true' run: pnpm install --frozen-lockfile --filter web... # Same dummies the jest suite already tolerates (ci.yml does the same for # the production build). The dump itself layers apps/web/.env.test under - # any real env, and dotenv never overrides exported values, so the LLM - # key below always wins over the .env.test placeholder. + # any real env, and dotenv never overrides exported values, so the minted + # token below always wins over any placeholder. - name: Setup dummy env + if: steps.catalog_changes.outputs.catalog == 'true' working-directory: apps/web run: cp .env.test .env + # Mint a short-lived token for the benchmarking service account so the + # dump's `kilo run` never uses a maintainer's personal credential. The + # mint endpoint ships with the PR that adds this step, so before that + # merge the endpoint 404s; the dump only needs the credential when + # summaries are missing, and it still fails loudly if it does. + - name: Mint catalog token + id: mint + if: steps.catalog_changes.outputs.catalog == 'true' + continue-on-error: true + env: + MCP_CATALOG_TOKEN_SECRET: ${{ secrets.MCP_CATALOG_TOKEN_SECRET }} + WEB_API_BASE_URL: https://app.kilo.ai + run: | + set -euo pipefail + response="$(curl -fsS -X POST "$WEB_API_BASE_URL/api/internal/mcp-catalog/token" \ + -H "Authorization: Bearer $MCP_CATALOG_TOKEN_SECRET" \ + -H 'content-type: application/json' \ + -d '{}')" + token="$(printf '%s' "$response" | jq -r '.token')" + org="$(printf '%s' "$response" | jq -r '.organizationId')" + if [ -z "$token" ] || [ "$token" = "null" ]; then + echo "::error::The catalog token mint returned no token" + exit 1 + fi + echo "::add-mask::$token" + echo "KILO_API_KEY=$token" >> "$GITHUB_ENV" + echo "KILO_ORG_ID=$org" >> "$GITHUB_ENV" + - name: Regenerate catalog.json id: dump - # Fork PRs never receive MCP_CATALOG_KILO_AUTH (GitHub withholds + if: steps.catalog_changes.outputs.catalog == 'true' + # Fork PRs never receive MCP_CATALOG_TOKEN_SECRET (GitHub withholds # secrets from fork pull_request events), so a fork PR that adds a # query without committed summaries always fails the dump here. # Tolerate that on forks so the guidance step below can still honour # requirement 6; a same-repo dump failure stays fatal. continue-on-error: ${{ github.event.pull_request.head.repo.fork == true }} - env: - # Either a signed-in CLI auth store (KILO_AUTH_CONTENT) or a - # durable Kilo API key + org (KILO_API_KEY / KILO_ORG_ID). - KILO_AUTH_CONTENT: ${{ secrets.MCP_CATALOG_KILO_AUTH }} - KILO_API_KEY: ${{ secrets.MCP_CATALOG_KILO_API_KEY }} - KILO_ORG_ID: ${{ secrets.MCP_CATALOG_KILO_ORG_ID }} run: pnpm --filter web script src/scripts/mcp-catalog/dump.ts # Requirement 6 when the dump itself cannot run: the drift-gated fork @@ -112,13 +174,16 @@ jobs: # keep-edit rule preserves hand-written summaries in the committed # catalog — and fails the job. Must run before drift detection. - name: Guide fork PR past an un-runnable catalog dump - if: steps.dump.outcome == 'failure' && github.event.pull_request.head.repo.fork == true + if: >- + steps.catalog_changes.outputs.catalog == 'true' && + steps.dump.outcome == 'failure' && + github.event.pull_request.head.repo.fork == true env: GH_TOKEN: ${{ github.token }} PR_NUMBER: ${{ github.event.pull_request.number }} COMMENT_BODY: >- The MCP catalog dump failed on this fork PR. Fork PRs never get - CI's Kilo CLI credentials (GitHub withholds secrets from fork + CI's catalog credentials (GitHub withholds secrets from fork events), so summaries for new query paths cannot be generated here. To recover, hand-write a summary for each new path in `services/kilo-mcp/catalog.json` (committed summaries are kept by @@ -129,11 +194,12 @@ jobs: fix that and push. run: | gh pr comment "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" --body "$COMMENT_BODY" || true - echo "::error::The MCP catalog dump failed on this fork PR (fork PRs get no Kilo CLI credentials). Hand-write a summary for each new path in services/kilo-mcp/catalog.json — the dump keeps committed summaries — or run the dump locally with a signed-in Kilo CLI and push." + echo "::error::The MCP catalog dump failed on this fork PR (fork PRs get no catalog credentials). Hand-write a summary for each new path in services/kilo-mcp/catalog.json — the dump keeps committed summaries — or run the dump locally with a signed-in Kilo CLI and push." exit 1 - name: Detect catalog drift id: drift + if: steps.catalog_changes.outputs.catalog == 'true' run: | if git diff --exit-code -- services/kilo-mcp/catalog.json > /dev/null; then echo "changed=false" >> "$GITHUB_OUTPUT" @@ -146,7 +212,10 @@ jobs: # an author-edited summary in the committed file survives the regen, so # this push never reverts a human edit. - name: Commit catalog to PR branch - if: steps.drift.outputs.changed == 'true' && github.event.pull_request.head.repo.fork == false + if: >- + steps.catalog_changes.outputs.catalog == 'true' && + steps.drift.outputs.changed == 'true' && + github.event.pull_request.head.repo.fork == false env: GH_TOKEN: ${{ github.token }} HEAD_BRANCH: ${{ github.head_ref }} @@ -169,11 +238,17 @@ jobs: # patch and fail loudly instead of silently leaving the catalog stale # (requirement 6). - name: Export catalog patch (fork PRs) - if: steps.drift.outputs.changed == 'true' && github.event.pull_request.head.repo.fork == true + if: >- + steps.catalog_changes.outputs.catalog == 'true' && + steps.drift.outputs.changed == 'true' && + github.event.pull_request.head.repo.fork == true run: git diff -- services/kilo-mcp/catalog.json > catalog.patch - name: Upload catalog patch artifact - if: steps.drift.outputs.changed == 'true' && github.event.pull_request.head.repo.fork == true + if: >- + steps.catalog_changes.outputs.catalog == 'true' && + steps.drift.outputs.changed == 'true' && + github.event.pull_request.head.repo.fork == true uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 with: name: catalog.patch @@ -184,7 +259,10 @@ jobs: # keeps the job failing with the deliberate ::error annotation below rather # than with a raw comment-permission failure. - name: Comment on fork PR - if: steps.drift.outputs.changed == 'true' && github.event.pull_request.head.repo.fork == true + if: >- + steps.catalog_changes.outputs.catalog == 'true' && + steps.drift.outputs.changed == 'true' && + github.event.pull_request.head.repo.fork == true continue-on-error: true env: GH_TOKEN: ${{ github.token }} @@ -199,7 +277,10 @@ jobs: run: gh pr comment "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" --body "$COMMENT_BODY" - name: Fail fork PR with stale catalog - if: steps.drift.outputs.changed == 'true' && github.event.pull_request.head.repo.fork == true + if: >- + steps.catalog_changes.outputs.catalog == 'true' && + steps.drift.outputs.changed == 'true' && + github.event.pull_request.head.repo.fork == true run: | echo "::error::services/kilo-mcp/catalog.json is stale and cannot be committed from a fork PR. Apply the catalog.patch artifact attached to this run, or run the dump locally and push." exit 1 @@ -236,15 +317,34 @@ jobs: working-directory: apps/web run: cp .env.test .env + # The first main run after this workflow lands may race the apps/web + # deploy that adds the mint endpoint; the dump only needs the credential + # when summaries are missing, so a failed mint is tolerated here too. + - name: Mint catalog token + id: mint + continue-on-error: true + env: + MCP_CATALOG_TOKEN_SECRET: ${{ secrets.MCP_CATALOG_TOKEN_SECRET }} + WEB_API_BASE_URL: https://app.kilo.ai + run: | + set -euo pipefail + response="$(curl -fsS -X POST "$WEB_API_BASE_URL/api/internal/mcp-catalog/token" \ + -H "Authorization: Bearer $MCP_CATALOG_TOKEN_SECRET" \ + -H 'content-type: application/json' \ + -d '{}')" + token="$(printf '%s' "$response" | jq -r '.token')" + org="$(printf '%s' "$response" | jq -r '.organizationId')" + if [ -z "$token" ] || [ "$token" = "null" ]; then + echo "::error::The catalog token mint returned no token" + exit 1 + fi + echo "::add-mask::$token" + echo "KILO_API_KEY=$token" >> "$GITHUB_ENV" + echo "KILO_ORG_ID=$org" >> "$GITHUB_ENV" + # Fill any summaries that slipped through before the index is updated # (requirement 8); keep-edit semantics leave author edits alone. - name: Regenerate catalog.json - env: - # Either a signed-in CLI auth store (KILO_AUTH_CONTENT) or a - # durable Kilo API key + org (KILO_API_KEY / KILO_ORG_ID). - KILO_AUTH_CONTENT: ${{ secrets.MCP_CATALOG_KILO_AUTH }} - KILO_API_KEY: ${{ secrets.MCP_CATALOG_KILO_API_KEY }} - KILO_ORG_ID: ${{ secrets.MCP_CATALOG_KILO_ORG_ID }} run: pnpm --filter web script src/scripts/mcp-catalog/dump.ts # Vectorize upsert (requirement 9). The index name and account id match diff --git a/scripts/kilo-mcp-catalog.test.mjs b/scripts/kilo-mcp-catalog.test.mjs index 67b829695a..88fa650096 100644 --- a/scripts/kilo-mcp-catalog.test.mjs +++ b/scripts/kilo-mcp-catalog.test.mjs @@ -11,10 +11,21 @@ const mergeJobName = 'catalog-merge'; const dumpCommand = 'pnpm --filter web script src/scripts/mcp-catalog/dump.ts'; const embedCommand = 'node services/kilo-mcp/scripts/embed-catalog.ts upsert'; const kiloInstallCommand = 'npm install -g @kilocode/cli'; +const mintCommand = 'api/internal/mcp-catalog/token'; +const mintSecretEnv = '${{ secrets.MCP_CATALOG_TOKEN_SECRET }}'; const mergeGate = "github.event_name == 'push' && github.ref == 'refs/heads/main'"; const forkCondition = 'github.event.pull_request.head.repo.fork == true'; const sameRepoCondition = 'github.event.pull_request.head.repo.fork == false'; -const prPaths = ['apps/web/src/**', 'services/kilo-mcp/**', workflowPath, testPath]; +const changeGate = "steps.catalog_changes.outputs.catalog == 'true'"; +// The paths the change-detection step must recognise. The workflow-path +// entries tolerate the grep escaping (`\.yml`, `\.test\.mjs`) so the required +// check keeps running the dump whenever the catalog can actually change. +const catalogPathFragments = [ + /apps\/web\/src\//, + /services\/kilo-mcp\//, + /kilo-mcp-catalog\\?\.yml/, + /kilo-mcp-catalog\\?\.test\\?\.mjs/, +]; function readWorkflow() { return load(readFileSync(new URL(`../${workflowPath}`, import.meta.url), 'utf8')); @@ -35,34 +46,46 @@ function validate(workflow) { const pr = workflow.jobs[prJobName]; const merge = workflow.jobs[mergeJobName]; - // Triggers: PRs on the catalog's source paths; pushes on main only. + // Triggers: PRs on every branch head (the check is required and must always + // report); pushes on main only. assert.equal(pr.if, "github.event_name == 'pull_request'", `${prJobName}: PR-event only`); assert.equal(merge.if, mergeGate, `${mergeJobName}: gated to main pushes only (requirement 10)`); - assert.deepEqual( - workflow.on.pull_request.paths, - prPaths, - 'pull_request admits the catalog paths' + assert.ok( + !workflow.on.pull_request?.paths, + 'pull_request must not filter by path: a skipped required check blocks unrelated PRs' ); assert.deepEqual(workflow.on.push.branches, ['main'], 'push stays main-only'); - // The PR job runs the real dump script with Kilo CLI credentials so missing - // summaries get filled (requirement 2), and keeps author edits through the - // dump's own keep-edit rule (requirement 5). + // The job always reports, but only catalog-relevant changes pay for the dump. + const gate = findStep(pr, step => step.id === 'catalog_changes', 'change-detection step'); + for (const fragment of catalogPathFragments) { + assert.match(gate.run ?? '', fragment, `change-detection step must recognise ${fragment}`); + } + const gateIndex = pr.steps.indexOf(gate); + for (const step of pr.steps.slice(gateIndex + 1)) { + assert.match( + step.if ?? '', + new RegExp(changeGate.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), + `${step.name ?? step.uses}: every post-detection step must be gated on catalog-relevant changes` + ); + } + + // The PR job runs the real dump script with a short-lived benchmarking + // token mint (requirement 2), never a maintainer's personal credential, and + // keeps author edits through the dump's own keep-edit rule (requirement 5). const prDump = findStep(pr, step => step.run === dumpCommand, 'PR job runs the real dump script'); + const prMint = findStep(pr, step => step.id === 'mint', 'PR job mints a catalog token'); assert.equal( - prDump.env?.KILO_AUTH_CONTENT, - '${{ secrets.MCP_CATALOG_KILO_AUTH }}', - 'PR dump exports the Kilo CLI credential from the repo secret' - ); - assert.equal( - prDump.env?.KILO_API_KEY, - '${{ secrets.MCP_CATALOG_KILO_API_KEY }}', - 'PR dump accepts a durable Kilo API key' + prMint.env?.MCP_CATALOG_TOKEN_SECRET, + mintSecretEnv, + 'PR mint reads the shared mint secret from the repo secret' ); - assert.equal( - prDump.env?.KILO_ORG_ID, - '${{ secrets.MCP_CATALOG_KILO_ORG_ID }}', - 'PR dump accepts the Kilo org for the API key' + assert.match(prMint.run ?? '', new RegExp(mintCommand.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))); + assert.match(prMint.run ?? '', /KILO_API_KEY/, 'PR mint exports the short-lived Kilo API key'); + assert.doesNotMatch( + JSON.stringify(prDump.env ?? {}), + /MCP_CATALOG_KILO_AUTH|KILO_AUTH_CONTENT/, + 'PR dump must not use the personal CLI credential' ); findStep( pr, @@ -70,7 +93,7 @@ function validate(workflow) { 'PR job installs the Kilo CLI the dump shells out to' ); - // Fork PRs never receive the Kilo credential (GitHub withholds secrets from + // Fork PRs never receive the mint secret (GitHub withholds secrets from // fork pull_request events), so a fork that adds a query cannot run the dump // at all. Requirement 6 must still fire: the dump is continue-on-error on // forks only, and a fork-conditioned follow-up step posts the self-service @@ -159,15 +182,16 @@ function validate(workflow) { // Merge job: dump fills stragglers (requirement 8), then the embed script // upserts Vectorize with the Cloudflare credentials (requirement 9). const mergeDump = findStep(merge, step => step.run === dumpCommand, 'merge job runs the dump'); + const mergeMint = findStep(merge, step => step.id === 'mint', 'merge job mints a catalog token'); assert.equal( - mergeDump.env?.KILO_AUTH_CONTENT, - '${{ secrets.MCP_CATALOG_KILO_AUTH }}', - 'merge dump exports the Kilo CLI credential' + mergeMint.env?.MCP_CATALOG_TOKEN_SECRET, + mintSecretEnv, + 'merge mint reads the shared mint secret from the repo secret' ); - assert.equal( - mergeDump.env?.KILO_API_KEY, - '${{ secrets.MCP_CATALOG_KILO_API_KEY }}', - 'merge dump accepts a durable Kilo API key' + assert.doesNotMatch( + JSON.stringify(mergeDump.env ?? {}), + /MCP_CATALOG_KILO_AUTH|KILO_AUTH_CONTENT/, + 'merge dump must not use the personal CLI credential' ); findStep( merge, @@ -317,6 +341,38 @@ for (const [name, defect] of [ 'merge upsert removed', workflow => dropStep(workflow, mergeJobName, step => step.run === embedCommand), ], + [ + 'PR dump reverted to the personal credential', + workflow => { + const step = workflow.jobs[prJobName].steps.find(item => item.run === dumpCommand); + step.env = { KILO_AUTH_CONTENT: '${{ secrets.MCP_CATALOG_KILO_AUTH }}' }; + }, + ], + [ + 'PR mint secret changed', + workflow => { + const step = workflow.jobs[prJobName].steps.find(item => item.id === 'mint'); + step.env.MCP_CATALOG_TOKEN_SECRET = '${{ secrets.SOMETHING_ELSE }}'; + }, + ], + [ + 'change-detection gate removed', + workflow => dropStep(workflow, prJobName, step => step.id === 'catalog_changes'), + ], + [ + 'change-detection drops a catalog path', + workflow => { + const step = workflow.jobs[prJobName].steps.find(item => item.id === 'catalog_changes'); + step.run = step.run.replace('^services/kilo-mcp/', '^services/other/'); + }, + ], + [ + 'a post-detection step escapes the gate', + workflow => { + const step = workflow.jobs[prJobName].steps.find(item => item.run === dumpCommand); + delete step.if; + }, + ], ]) { test(`wiring check rejects: ${name}`, () => { const workflow = readWorkflow(); From c3cf0b81db484bbf1cab39d78b790b0509280dd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Igor=20=C5=A0=C4=87eki=C4=87?= Date: Fri, 11 Sep 2026 13:04:49 +0200 Subject: [PATCH 10/11] fix(kilo-mcp): scope credential lookup to the verified grant - getKiloToken now filters by the token's org and resource indicator, not just user + client, so a token for one grant can never forward another grant's Kilo credential. Null-org identities match only null-org rows. - VerifiedMcpToken carries its bound resource so the lookup can use it. - callCatalogEndpoint rejects any input for a no-input catalog procedure before any upstream request. - the merge catalog job fails when the dump changes catalog.json, so the Vectorize index cannot diverge from the deployed Worker bundle. --- .github/workflows/kilo-mcp-catalog.yml | 11 ++++ scripts/kilo-mcp-catalog.test.mjs | 22 +++++++ services/kilo-mcp/src/auth.test.ts | 24 +++++++- services/kilo-mcp/src/auth/verify.test.ts | 1 + services/kilo-mcp/src/auth/verify.ts | 3 + services/kilo-mcp/src/call.test.ts | 16 +++++ services/kilo-mcp/src/call.ts | 7 +++ services/kilo-mcp/src/index.test.ts | 19 ++++-- services/kilo-mcp/src/index.ts | 8 ++- .../kilo-mcp/src/store/oauth-store.test.ts | 59 ++++++++++++++++--- services/kilo-mcp/src/store/oauth-store.ts | 36 +++++++++-- 11 files changed, 184 insertions(+), 22 deletions(-) diff --git a/.github/workflows/kilo-mcp-catalog.yml b/.github/workflows/kilo-mcp-catalog.yml index 14abd24f21..2d2454845d 100644 --- a/.github/workflows/kilo-mcp-catalog.yml +++ b/.github/workflows/kilo-mcp-catalog.yml @@ -347,6 +347,17 @@ jobs: - name: Regenerate catalog.json run: pnpm --filter web script src/scripts/mcp-catalog/dump.ts + # The bundled catalog a production deploy serves must match the index this + # run upserts. If the dump changes the checked-in file, main was stale + # (the PR job never landed the refresh): fail instead of indexing content + # the Worker bundle does not carry (requirement 22). + - name: Fail if the regenerated catalog is not the committed one + run: | + if ! git diff --exit-code -- services/kilo-mcp/catalog.json > /dev/null; then + echo "::error::The dump changed services/kilo-mcp/catalog.json on main. Commit the regenerated catalog before the Vectorize upsert; otherwise the deployed Worker bundle and the index diverge." + exit 1 + fi + # Vectorize upsert (requirement 9). The index name and account id match # the production bindings in services/kilo-mcp/wrangler.jsonc; the # account id is not a secret (it is committed there). diff --git a/scripts/kilo-mcp-catalog.test.mjs b/scripts/kilo-mcp-catalog.test.mjs index 88fa650096..6a04f75c45 100644 --- a/scripts/kilo-mcp-catalog.test.mjs +++ b/scripts/kilo-mcp-catalog.test.mjs @@ -199,6 +199,21 @@ function validate(workflow) { 'merge job installs the Kilo CLI the dump shells out to' ); const upsert = findStep(merge, step => step.run === embedCommand, 'merge job upserts Vectorize'); + const mergeDrift = findStep( + merge, + step => /git diff --exit-code[\s\S]*services\/kilo-mcp\/catalog\.json/.test(step.run ?? ''), + 'merge job fails when the regenerated catalog is not the committed one' + ); + assert.ok( + merge.steps.indexOf(mergeDump) < merge.steps.indexOf(mergeDrift) && + merge.steps.indexOf(mergeDrift) < merge.steps.indexOf(upsert), + 'the merge drift check must run between the dump and the Vectorize upsert' + ); + assert.match( + mergeDrift.run ?? '', + /exit 1/, + 'a catalog changed on main must fail the merge job, not index the stale bundled catalog' + ); assert.equal( upsert.env?.CLOUDFLARE_API_TOKEN, '${{ secrets.CLOUDFLARE_API_TOKEN }}', @@ -341,6 +356,13 @@ for (const [name, defect] of [ 'merge upsert removed', workflow => dropStep(workflow, mergeJobName, step => step.run === embedCommand), ], + [ + 'merge drift check removed', + workflow => + dropStep(workflow, mergeJobName, step => + /git diff --exit-code[\s\S]*services\/kilo-mcp\/catalog\.json/.test(step.run ?? '') + ), + ], [ 'PR dump reverted to the personal credential', workflow => { diff --git a/services/kilo-mcp/src/auth.test.ts b/services/kilo-mcp/src/auth.test.ts index 3feabd30f0..fb784fcc68 100644 --- a/services/kilo-mcp/src/auth.test.ts +++ b/services/kilo-mcp/src/auth.test.ts @@ -79,7 +79,10 @@ describe('authenticate (s2 passthrough)', () => { describe('authenticate (s5 verify + s6 enforcement: only MCP tokens)', () => { const withKilo = { mcpToken, - resolveKiloToken: async (identity: { kiloUserId: string; clientId: string }) => + resolveKiloToken: async (identity: { + kiloUserId: string; + clientId: string; + }) => identity.kiloUserId === 'kilo-user-1' && identity.clientId === 'client-1' ? 'kilo-app-token' : null, @@ -100,9 +103,28 @@ describe('authenticate (s5 verify + s6 enforcement: only MCP tokens)', () => { kiloUserId: 'kilo-user-1', organizationId: 'org-uuid-1', clientId: 'client-1', + resource: RESOURCE, }); }); + it('a token for one org cannot resolve another org grant’s credential', async () => { + const strict = { + mcpToken, + resolveKiloToken: async (identity: { + kiloUserId: string; + clientId: string; + organizationId: string | null; + resource: string; + }) => + identity.organizationId === 'org-uuid-1' && identity.resource === RESOURCE + ? 'kilo-app-token' + : null, + }; + expect(await authenticate(bearerRequest(await mcpAccessToken()), strict)).not.toBeNull(); + const token = await mcpAccessToken({ org: 'org-other' }); + expect(await authenticate(bearerRequest(token), strict)).toBeNull(); + }); + it('the caller-supplied organization header is ignored; the org claim wins', async () => { const token = await mcpAccessToken({ org: null }); const auth = await authenticate( diff --git a/services/kilo-mcp/src/auth/verify.test.ts b/services/kilo-mcp/src/auth/verify.test.ts index 118235d06b..252f14d543 100644 --- a/services/kilo-mcp/src/auth/verify.test.ts +++ b/services/kilo-mcp/src/auth/verify.test.ts @@ -37,6 +37,7 @@ describe('verifyMcpAccessToken', () => { kiloUserId: 'kilo-user-1', organizationId: 'org-1', clientId: 'client-1', + resource: RESOURCE, expiresAt: expect.any(Number), }, }); diff --git a/services/kilo-mcp/src/auth/verify.ts b/services/kilo-mcp/src/auth/verify.ts index de9d3a260a..676e64c915 100644 --- a/services/kilo-mcp/src/auth/verify.ts +++ b/services/kilo-mcp/src/auth/verify.ts @@ -17,6 +17,8 @@ export type VerifiedMcpToken = { kiloUserId: string; organizationId: string | null; clientId: string; + /** The token's bound resource (`aud`), so credential lookups stay grant-scoped. */ + resource: string; /** Seconds (JWT `exp`), for callers that want to cache the verify result. */ expiresAt: number; }; @@ -77,6 +79,7 @@ export async function verifyMcpAccessToken( kiloUserId: sub, organizationId: typeof org === 'string' ? org : null, clientId, + resource: deps.resource, expiresAt: exp, }, }; diff --git a/services/kilo-mcp/src/call.test.ts b/services/kilo-mcp/src/call.test.ts index e070b8a25b..3c30f41284 100644 --- a/services/kilo-mcp/src/call.test.ts +++ b/services/kilo-mcp/src/call.test.ts @@ -149,6 +149,22 @@ describe('callCatalogEndpoint', () => { expect('x-kilocode-organizationid' in headers).toBe(false); }); + it('rejects any input for a no-input procedure before any request', async () => { + const fetchImpl = vi.fn(); + const error = await callCatalogEndpoint({ + catalog: testCatalog, + path: 'organizations.list', + input: { unexpected: true }, + auth, + webBaseUrl: WEB_BASE_URL, + fetchImpl, + }).catch((e: unknown) => e); + expect(error).toBeInstanceOf(JsonRpcFailure); + expect((error as JsonRpcFailure).code).toBe(-32602); + expect((error as Error).message).toMatch(/takes no input/); + expect(fetchImpl).not.toHaveBeenCalled(); + }); + it('maps a tRPC error body to a JSON-RPC error preserving code and httpStatus (retryable)', async () => { const fetchImpl = vi.fn(async () => upstreamResponse( diff --git a/services/kilo-mcp/src/call.ts b/services/kilo-mcp/src/call.ts index 179249e1c6..11c573b241 100644 --- a/services/kilo-mcp/src/call.ts +++ b/services/kilo-mcp/src/call.ts @@ -128,6 +128,13 @@ export async function callCatalogEndpoint(options: { const schemaIsEmpty = isNoInputSchema(row.inputSchema); const sendInput = input !== undefined && input !== null; + if (schemaIsEmpty && sendInput) { + throw new JsonRpcFailure( + INVALID_PARAMS, + `"${path}" takes no input; omit "input" for this endpoint.`, + { path } + ); + } if (sendInput && !schemaIsEmpty) { const validate = validatorFor(row.inputSchema); if (!validate(input)) { diff --git a/services/kilo-mcp/src/index.test.ts b/services/kilo-mcp/src/index.test.ts index d343245a08..2a2703589a 100644 --- a/services/kilo-mcp/src/index.test.ts +++ b/services/kilo-mcp/src/index.test.ts @@ -538,20 +538,27 @@ describe('auth endpoint routing (s5)', () => { refreshTokens.set(input.id, { ...input, revokedAt: null }); return true; }, - async getKiloToken(kiloUserId, clientId) { + async getKiloToken(identity) { for (const grant of [...refreshTokens.values()].reverse()) { if ( - grant.kiloUserId === kiloUserId && - grant.clientId === clientId && + grant.kiloUserId === identity.kiloUserId && + grant.clientId === identity.clientId && + grant.organizationId === identity.organizationId && + grant.resource === identity.resource && grant.revokedAt === null && grant.kiloToken ) { return grant.kiloToken; } } - // The s5 verification tests mint tokens for user-1/c-1 without going - // through the exchange; that pair keeps a standing credential. - return kiloUserId === 'user-1' && clientId === 'c-1' ? 'kilo-forward-me' : null; + // The s5 verification tests mint tokens for user-1/c-1/org-1 without + // going through the exchange; that grant keeps a standing credential. + return identity.kiloUserId === 'user-1' && + identity.clientId === 'c-1' && + identity.organizationId === 'org-1' && + identity.resource === `${ISSUER}/mcp` + ? 'kilo-forward-me' + : null; }, revokeGrant: unused, revokeJti: unused, diff --git a/services/kilo-mcp/src/index.ts b/services/kilo-mcp/src/index.ts index e3f99127ea..88384797cb 100644 --- a/services/kilo-mcp/src/index.ts +++ b/services/kilo-mcp/src/index.ts @@ -305,8 +305,12 @@ export function createMcpHandler(deps: McpHandlerDeps) { }, resolveKiloToken: identity => mcpAuth.store.getKiloToken( - identity.kiloUserId, - identity.clientId, + { + kiloUserId: identity.kiloUserId, + clientId: identity.clientId, + organizationId: identity.organizationId, + resource: identity.resource, + }, new Date().toISOString() ), } diff --git a/services/kilo-mcp/src/store/oauth-store.test.ts b/services/kilo-mcp/src/store/oauth-store.test.ts index b8904dc5ad..cbdfda0d9f 100644 --- a/services/kilo-mcp/src/store/oauth-store.test.ts +++ b/services/kilo-mcp/src/store/oauth-store.test.ts @@ -282,6 +282,12 @@ describe('KiloMcpOAuthStore (real drizzle durable-sqlite over node:sqlite)', () }); describe('getKiloToken (forwarding credential, s6)', () => { + const identity = { + kiloUserId: 'u-k', + clientId: 'c-k', + organizationId: null, + resource: 'https://mcp.test/mcp', + }; const grant = ( id: string, createdAt: string, @@ -300,19 +306,53 @@ describe('KiloMcpOAuthStore (real drizzle durable-sqlite over node:sqlite)', () ...overrides, }); - it('returns the newest live grant for (user, client)', async () => { + it('returns the newest live grant for the exact identity', async () => { await store.saveRefreshToken(grant('g-old', NOW)); await store.saveRefreshToken(grant('g-new', LATER)); - expect(await store.getKiloToken('u-k', 'c-k', NOW)).toBe('kilo-g-new'); + expect(await store.getKiloToken(identity, NOW)).toBe('kilo-g-new'); }); it('skips revoked and expired grants and other identities', async () => { - expect(await store.getKiloToken('ghost-user', 'c-k', NOW)).toBeNull(); - expect(await store.getKiloToken('u-k', 'ghost-client', NOW)).toBeNull(); + expect(await store.getKiloToken({ ...identity, kiloUserId: 'ghost-user' }, NOW)).toBeNull(); + expect(await store.getKiloToken({ ...identity, clientId: 'ghost-client' }, NOW)).toBeNull(); await store.rotateRefreshToken('g-new', grant('g-rot', '2098-01-01T00:00:00.000Z'), NOW); // rotation revoked g-new; the rotated row carries the credential forward - expect(await store.getKiloToken('u-k', 'c-k', NOW)).toBe('kilo-g-rot'); - expect(await store.getKiloToken('u-k', 'c-k', '2099-01-02T00:00:00.000Z')).toBeNull(); + expect(await store.getKiloToken(identity, NOW)).toBe('kilo-g-rot'); + expect(await store.getKiloToken(identity, '2099-01-02T00:00:00.000Z')).toBeNull(); + }); + + it('never forwards a credential from a different org or resource grant', async () => { + await store.saveRefreshToken( + grant('g-org-a', NOW, { organizationId: 'org-a', kiloToken: 'kilo-org-a' }) + ); + await store.saveRefreshToken( + grant('g-org-b', LATER, { organizationId: 'org-b', kiloToken: 'kilo-org-b' }) + ); + await store.saveRefreshToken( + grant('g-other-resource', LATER, { + organizationId: 'org-a', + resource: 'https://other-mcp.test/mcp', + kiloToken: 'kilo-other-resource', + }) + ); + await store.saveRefreshToken(grant('g-null-org', LATER, { kiloToken: 'kilo-null-org' })); + expect(await store.getKiloToken({ ...identity, organizationId: 'org-a' }, NOW)).toBe( + 'kilo-org-a' + ); + expect(await store.getKiloToken({ ...identity, organizationId: 'org-b' }, NOW)).toBe( + 'kilo-org-b' + ); + // A null-org identity matches only null-org rows, never the org rows — + // g-org-b is the newest grant overall, so a broken org filter would surface it. + const nullOrg = await store.getKiloToken(identity, NOW); + expect(nullOrg).not.toBe('kilo-org-b'); + // The same org but a different resource indicator is a different grant. + expect( + await store.getKiloToken( + { ...identity, organizationId: 'org-a', resource: 'https://third-mcp.test/mcp' }, + NOW + ) + ).toBeNull(); }); it('a grant without a Kilo token never surfaces a stale one', async () => { @@ -324,7 +364,12 @@ describe('KiloMcpOAuthStore (real drizzle durable-sqlite over node:sqlite)', () tokenHash: 'f'.repeat(64), }) ); - expect(await store.getKiloToken('u-legacy', 'c-legacy', NOW)).toBeNull(); + expect( + await store.getKiloToken( + { ...identity, kiloUserId: 'u-legacy', clientId: 'c-legacy' }, + NOW + ) + ).toBeNull(); }); }); diff --git a/services/kilo-mcp/src/store/oauth-store.ts b/services/kilo-mcp/src/store/oauth-store.ts index 89d026e52d..b345c7419f 100644 --- a/services/kilo-mcp/src/store/oauth-store.ts +++ b/services/kilo-mcp/src/store/oauth-store.ts @@ -166,10 +166,21 @@ export interface OAuthStoreApi { nowIso: string ): Promise; /** - * The Kilo API token to forward for a verified MCP identity (s6): the newest - * live grant for (user, client). Null when the user must reconnect. + * The Kilo API token to forward for a verified MCP identity: the newest live + * grant for (user, client, org, resource). Null when the user must + * reconnect. The lookup must be scoped to the token's own grant — a token + * minted for one org or resource must never forward another grant's + * credential. */ - getKiloToken(kiloUserId: string, clientId: string, nowIso: string): Promise; + getKiloToken( + identity: { + kiloUserId: string; + clientId: string; + organizationId: string | null; + resource: string; + }, + nowIso: string + ): Promise; revokeJti(jti: string, tokenExpiresAt: string, nowIso: string): Promise; isJtiRevoked(jti: string): Promise; /** Housekeeping: drop rows past their own expiry. Returns deleted row count. */ @@ -452,14 +463,27 @@ export class KiloMcpOAuthStore extends DurableObject implements OAuthStoreA return rows.length; } - async getKiloToken(kiloUserId: string, clientId: string, nowIso: string): Promise { + async getKiloToken( + identity: { + kiloUserId: string; + clientId: string; + organizationId: string | null; + resource: string; + }, + nowIso: string + ): Promise { const row = this.db .select({ kiloToken: oauthRefreshTokens.kilo_token }) .from(oauthRefreshTokens) .where( and( - eq(oauthRefreshTokens.kilo_user_id, kiloUserId), - eq(oauthRefreshTokens.client_id, clientId), + eq(oauthRefreshTokens.kilo_user_id, identity.kiloUserId), + eq(oauthRefreshTokens.client_id, identity.clientId), + eq(oauthRefreshTokens.resource, identity.resource), + // organization_id is nullable; a null-org identity matches only null rows. + identity.organizationId === null + ? isNull(oauthRefreshTokens.organization_id) + : eq(oauthRefreshTokens.organization_id, identity.organizationId), isNull(oauthRefreshTokens.revoked_at), gt(oauthRefreshTokens.expires_at, nowIso) ) From 12dc2336bee43194fb98694c0fc8c5e155c2a2b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Igor=20=C5=A0=C4=87eki=C4=87?= Date: Fri, 11 Sep 2026 13:15:44 +0200 Subject: [PATCH 11/11] style(kilo-mcp): apply oxfmt to the review-fix tests --- services/kilo-mcp/src/auth.test.ts | 5 +---- services/kilo-mcp/src/store/oauth-store.test.ts | 5 +---- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/services/kilo-mcp/src/auth.test.ts b/services/kilo-mcp/src/auth.test.ts index fb784fcc68..139403b6a7 100644 --- a/services/kilo-mcp/src/auth.test.ts +++ b/services/kilo-mcp/src/auth.test.ts @@ -79,10 +79,7 @@ describe('authenticate (s2 passthrough)', () => { describe('authenticate (s5 verify + s6 enforcement: only MCP tokens)', () => { const withKilo = { mcpToken, - resolveKiloToken: async (identity: { - kiloUserId: string; - clientId: string; - }) => + resolveKiloToken: async (identity: { kiloUserId: string; clientId: string }) => identity.kiloUserId === 'kilo-user-1' && identity.clientId === 'client-1' ? 'kilo-app-token' : null, diff --git a/services/kilo-mcp/src/store/oauth-store.test.ts b/services/kilo-mcp/src/store/oauth-store.test.ts index cbdfda0d9f..6f84ede612 100644 --- a/services/kilo-mcp/src/store/oauth-store.test.ts +++ b/services/kilo-mcp/src/store/oauth-store.test.ts @@ -365,10 +365,7 @@ describe('KiloMcpOAuthStore (real drizzle durable-sqlite over node:sqlite)', () }) ); expect( - await store.getKiloToken( - { ...identity, kiloUserId: 'u-legacy', clientId: 'c-legacy' }, - NOW - ) + await store.getKiloToken({ ...identity, kiloUserId: 'u-legacy', clientId: 'c-legacy' }, NOW) ).toBeNull(); }); });