Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f4ee52333 | ||
|
|
bf2d985faa | ||
|
|
4f41c7ac07 | ||
|
|
048d5f7ddf | ||
|
|
b3e35fc593 | ||
|
|
746661565d |
No files matched your search
@@ -28,55 +28,14 @@ If any are missing, ask the user or tell them to run plugin-researcher first.
|
||||
|
||||
## Phase 2 — Scaffold
|
||||
|
||||
Always scaffold with the CLI, never by hand. From the project root (`C:\dev\wwv\worldwideview`).
|
||||
|
||||
**Step 1 — build the CLI if `dist/` is missing** (`dist` is gitignored, so fresh worktrees lack it):
|
||||
From the project root (`C:\dev\wwv\worldwideview`):
|
||||
|
||||
```bash
|
||||
pnpm --filter @worldwideview/wwv-cli build
|
||||
```
|
||||
|
||||
**Step 2 — run `create` non-interactively.** The CLI accepts a flag for every prompt;
|
||||
pass them all plus `--yes` so it never blocks on a prompt. Use the variant that matches
|
||||
the architecture — `--seeder-tier` is **websocket-only** (passing it with `polling` does
|
||||
nothing). Requires `@worldwideview/wwv-cli` **≥ 1.3.1** (earlier versions wrongly demanded
|
||||
`--seeder-tier` for polling under `--yes`).
|
||||
|
||||
```bash
|
||||
# Polling / static (frontend only — NO seeder, so NO --seeder-tier):
|
||||
node packages/wwv-cli/dist/index.js create <name> \
|
||||
--display-name "<Display Name>" \
|
||||
--description "<short description>" \
|
||||
--category <aviation|maritime|space|weather|custom> \
|
||||
--architecture polling \
|
||||
--render-style <billboard|model|point> \
|
||||
--yes
|
||||
|
||||
# Real-time / WebSocket (also scaffolds a backend seeder — REQUIRES --seeder-tier):
|
||||
node packages/wwv-cli/dist/index.js create <name> \
|
||||
--display-name "<Display Name>" \
|
||||
--description "<short description>" \
|
||||
--category <aviation|maritime|space|weather|custom> \
|
||||
--architecture websocket \
|
||||
--seeder-tier <community|private> \
|
||||
--render-style <billboard|model|point> \
|
||||
--yes
|
||||
|
||||
node packages/wwv-cli/dist/index.js create <name> --local
|
||||
pnpm install
|
||||
```
|
||||
|
||||
This creates `local-plugins/wwv-plugin-<name>/`. The `websocket` variant also creates the
|
||||
seeder at `local-seeders/<tier>/packages/<name>/` in the correct community/private layout
|
||||
(`package.json` + `tsup.config.ts` + `src/index.ts`, exporting `{ name, cron, fn }` with
|
||||
`name` === the plugin id). Verify the expected directories exist before proceeding.
|
||||
|
||||
> No post-CLI move is required — the CLI already targets `local-seeders/<tier>/packages/<name>/`.
|
||||
> (Pre-1.3.0 CLI dropped a bare `seeder.mjs` at `local-seeders/<tier>/<name>/`; if you ever see
|
||||
> that shape, the CLI is stale — rebuild it with the Step 1 command.)
|
||||
>
|
||||
> The CLI exits non-zero with a clear message on a bad `--category`/`--architecture`/etc., a
|
||||
> missing required value under `--yes`, or an existing target directory. Treat a non-zero exit
|
||||
> as a hard stop — fix the inputs and re-run; do not fall back to manual scaffolding.
|
||||
This creates `local-plugins/wwv-plugin-<name>/`. Verify it exists before proceeding.
|
||||
|
||||
**NEVER:**
|
||||
- Scaffold manually (always use the CLI)
|
||||
@@ -157,15 +116,13 @@ export class MyPlugin implements WorldPlugin {
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — Implement the Seeder (skip for static / polling-only plugins)
|
||||
## Phase 4 — Implement the Seeder (skip for static plugins)
|
||||
|
||||
Seeders live in `local-seeders/<tier>/` — **independent git repos** (`github.com/silvertakana/wwv-seeders` for community, `wwv-seeders-private` for private). Never commit seeder files to the worldwideview repo.
|
||||
Seeders live in `local-seeders/community/` — **this is an independent git repo** (`github.com/silvertakana/wwv-seeders`). Never commit seeder files to the worldwideview repo.
|
||||
|
||||
If you scaffolded with `--architecture websocket`, **the CLI already created the seeder skeleton** at `local-seeders/<tier>/packages/<name>/` (`package.json` + `tsup.config.ts` + `src/index.ts` with a `{ name, cron, fn }` stub). Do **not** recreate those files — open the generated `src/index.ts` and replace the stub body with real fetch + map logic. The snippets below are the target shapes the CLI emits; use them to verify/adjust what was generated, not to create files from scratch.
|
||||
### Create `local-seeders/community/packages/<name>/`
|
||||
|
||||
### Generated layout: `local-seeders/<tier>/packages/<name>/`
|
||||
|
||||
**`package.json`** (CLI-generated — only adjust `dependencies` for what your seeder imports):
|
||||
**`package.json`:**
|
||||
```json
|
||||
{
|
||||
"name": "@wwv-seeders/<name>",
|
||||
|
||||
@@ -72,23 +72,6 @@ mapWebsocketPayload(payload: any, existingEntities: GeoEntity[]): GeoEntity[]
|
||||
- `existingEntities` — current entities in the store for this plugin (use for incremental updates)
|
||||
- Must return a **complete replacement** `GeoEntity[]` (not a diff)
|
||||
|
||||
### Property Tag Helpers
|
||||
|
||||
Always wrap typed property values with the SDK helpers so the Intel panel renders them richly:
|
||||
|
||||
```ts
|
||||
import { dtProp, urlProp, imageProp, videoProp } from "@worldwideview/wwv-plugin-sdk";
|
||||
|
||||
properties: {
|
||||
updated: dtProp(item.updated_at ?? null), // renders as expandable datetime row
|
||||
source: urlProp(item.source_url ?? null), // renders as clickable link
|
||||
preview: imageProp(item.image ?? null), // renders as inline thumbnail
|
||||
stream: videoProp(item.video_url ?? null), // renders as "Watch" link
|
||||
}
|
||||
```
|
||||
|
||||
All helpers are null-safe and return `null` for empty input. Plain string/number values that don't need rich rendering need no wrapper.
|
||||
|
||||
---
|
||||
|
||||
## Plugin Architectures (Manifest Formats)
|
||||
|
||||
@@ -1,161 +1,8 @@
|
||||
param([string]$worktreePath)
|
||||
|
||||
# git-wt (Worktrunk) pre-start hook.
|
||||
# Per the per-worktree isolation model, each worktree gets its OWN real, isolated
|
||||
# .planning directory -- NEVER a junction to the shared root. A shared junction caused
|
||||
# GSD phase bleed across simultaneous worktree sessions. See worktree-bootstrap SKILL Step 5
|
||||
# and C:\dev\wwv\.planning\WORKSPACE-OPTIMIZATION-BACKLOG.md.
|
||||
#
|
||||
# This hook is idempotent:
|
||||
# - existing REAL .planning with a WORKSPACE.md -> left untouched (preserve phase history)
|
||||
# - existing REAL .planning missing manifests -> manifests seeded, contents preserved
|
||||
# - existing JUNCTION (old-model leftover) -> junction removed, real dir created
|
||||
# - nothing there -> real isolated dir created
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# Convert Unix-style path (/c/dev/...) to Windows path (C:\dev\...) if needed
|
||||
if ($worktreePath -match '^/([a-zA-Z])/(.+)$') {
|
||||
$worktreePath = $matches[1].ToUpper() + ':/' + $matches[2]
|
||||
}
|
||||
|
||||
$sharedRoot = 'C:\dev\wwv\.planning'
|
||||
$target = Join-Path $worktreePath '.planning'
|
||||
|
||||
# If a junction/symlink leftover from the old model exists, remove only the reparse
|
||||
# point (never recurse into the shared root it points at).
|
||||
if (Test-Path $target) {
|
||||
$item = Get-Item -LiteralPath $target -Force
|
||||
$isReparse = ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq [IO.FileAttributes]::ReparsePoint
|
||||
if ($isReparse) {
|
||||
[System.IO.Directory]::Delete($target, $false)
|
||||
} elseif (Test-Path (Join-Path $target 'WORKSPACE.md')) {
|
||||
# Already a fully set-up real isolated dir -- preserve it, do nothing.
|
||||
exit 0
|
||||
}
|
||||
}
|
||||
|
||||
# Resolve the branch name (fall back to the worktree folder leaf).
|
||||
$branch = $null
|
||||
try { $branch = (& git -C $worktreePath rev-parse --abbrev-ref HEAD 2>$null) } catch {}
|
||||
if (-not $branch) { $branch = Split-Path $worktreePath -Leaf }
|
||||
$branch = $branch.Trim()
|
||||
|
||||
$date = (Get-Date).ToString('yyyy-MM-dd')
|
||||
$isoDate = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.000Z')
|
||||
|
||||
# Create the isolated structure.
|
||||
foreach ($d in @('phases', 'debug', 'surveys')) {
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $target $d) | Out-Null
|
||||
}
|
||||
|
||||
# Copy the GSD config from the shared root if present.
|
||||
$sharedConfig = Join-Path $sharedRoot 'config.json'
|
||||
$localConfig = Join-Path $target 'config.json'
|
||||
if ((Test-Path $sharedConfig) -and -not (Test-Path $localConfig)) {
|
||||
Copy-Item $sharedConfig $localConfig -Force
|
||||
}
|
||||
|
||||
# Seed the three manifest files (only if missing -- never overwrite existing).
|
||||
$workspaceFile = Join-Path $target 'WORKSPACE.md'
|
||||
if (-not (Test-Path $workspaceFile)) {
|
||||
$workspace = @"
|
||||
# Workspace: $branch
|
||||
|
||||
Created: $date
|
||||
Strategy: worktree (git-wt)
|
||||
Branch: $branch
|
||||
Repo: $worktreePath
|
||||
|
||||
## Isolation
|
||||
|
||||
This ``.planning`` is a REAL, isolated directory (not a junction to the shared root).
|
||||
Phases and STATE.md here are private to this worktree. Changes do NOT bleed into
|
||||
other worktrees or the shared root. Created automatically by the git-wt pre-start
|
||||
hook (link-planning.ps1), per the per-worktree isolation model.
|
||||
|
||||
## Member Repos
|
||||
|
||||
| Repo | Source | Branch | Strategy |
|
||||
|------|--------|--------|----------|
|
||||
| worldwideview | C:\dev\wwv\worldwideview | $branch | worktree |
|
||||
|
||||
## Notes
|
||||
|
||||
Cross-feature docs are NOT duplicated here. See SHARED-DOCS.md.
|
||||
"@
|
||||
Set-Content -LiteralPath $workspaceFile -Value $workspace -Encoding UTF8
|
||||
}
|
||||
|
||||
$stateFile = Join-Path $target 'STATE.md'
|
||||
if (-not (Test-Path $stateFile)) {
|
||||
$state = @"
|
||||
---
|
||||
gsd_state_version: 1.0
|
||||
milestone: none
|
||||
milestone_name: $branch
|
||||
status: idle
|
||||
last_updated: "$isoDate"
|
||||
last_activity: $date -- isolated .planning created (git-wt pre-start hook)
|
||||
progress:
|
||||
total_phases: 0
|
||||
completed_phases: 0
|
||||
total_plans: 0
|
||||
completed_plans: 0
|
||||
percent: 0
|
||||
---
|
||||
|
||||
# Project State
|
||||
|
||||
## Project Reference
|
||||
|
||||
This is an ISOLATED worktree workspace. Its planning state is private to the
|
||||
``$branch`` worktree and intentionally distinct from the shared root
|
||||
(C:\dev\wwv\.planning).
|
||||
|
||||
Cross-feature docs (ROADMAP, MILESTONES, research) are NOT duplicated here.
|
||||
See SHARED-DOCS.md for how to reach them.
|
||||
|
||||
## Current Position
|
||||
|
||||
No active milestone. Workspace is idle.
|
||||
"@
|
||||
Set-Content -LiteralPath $stateFile -Value $state -Encoding UTF8
|
||||
}
|
||||
|
||||
$sharedDocsFile = Join-Path $target 'SHARED-DOCS.md'
|
||||
if (-not (Test-Path $sharedDocsFile)) {
|
||||
$sharedDocs = @"
|
||||
# Shared Cross-Feature Docs
|
||||
|
||||
This worktree's ``.planning`` is isolated (phases + STATE are private). But some
|
||||
documents are cross-feature and must stay authoritative in ONE place rather than
|
||||
being copied per worktree (copies drift out of sync).
|
||||
|
||||
## Where they live
|
||||
|
||||
Shared root: ``C:\dev\wwv\.planning``
|
||||
|
||||
| Doc | Purpose |
|
||||
|-----|---------|
|
||||
| ROADMAP.md | Cross-milestone roadmap |
|
||||
| MILESTONES.md | Milestone definitions and ship status |
|
||||
| research/ | ARCHITECTURE / FEATURES / PITFALLS / STACK |
|
||||
| PROJECT.md | Project identity |
|
||||
| REQUIREMENTS.md | Cross-cutting requirements |
|
||||
|
||||
## How to reach them
|
||||
|
||||
A ``WWV_SHARED_PLANNING`` env var in each worktree's ``.env.local`` points at the
|
||||
shared root, and GSD skills that need a cross-feature doc read
|
||||
``\$WWV_SHARED_PLANNING/<doc>`` instead of the local ``.planning/<doc>``.
|
||||
|
||||
Do NOT copy these docs into this worktree. Single source of truth lives at the
|
||||
shared root.
|
||||
"@
|
||||
Set-Content -LiteralPath $sharedDocsFile -Value $sharedDocs -Encoding UTF8
|
||||
}
|
||||
|
||||
# Always report success: the internal git probe above may set a non-zero $LASTEXITCODE,
|
||||
# which would otherwise be propagated as this hook's exit code and read as a failure.
|
||||
exit 0
|
||||
if (Test-Path $target) { Remove-Item $target -Force }
|
||||
New-Item -ItemType Junction -Path $target -Target 'C:\dev\wwv\.planning' | Out-Null
|
||||
@@ -1,29 +1,7 @@
|
||||
param([string]$worktreePath)
|
||||
|
||||
# git-wt (Worktrunk) pre-remove hook.
|
||||
# Per the per-worktree isolation model, a worktree's .planning is a REAL isolated
|
||||
# directory (its phase history is archived by /branch-cleanup before removal, and the
|
||||
# directory itself is deleted along with the worktree by `git-wt remove`).
|
||||
#
|
||||
# This hook therefore ONLY cleans up a leftover JUNCTION from the old shared-link model.
|
||||
# It must NEVER recursively delete a real .planning directory -- doing so would destroy
|
||||
# phase history that /branch-cleanup is responsible for archiving.
|
||||
|
||||
# Convert Unix-style path (/c/dev/...) to Windows path (C:\dev\...) if needed
|
||||
if ($worktreePath -match '^/([a-zA-Z])/(.+)$') {
|
||||
$worktreePath = $matches[1].ToUpper() + ':/' + $matches[2]
|
||||
}
|
||||
$target = Join-Path $worktreePath '.planning'
|
||||
|
||||
if (Test-Path $target) {
|
||||
$item = Get-Item -LiteralPath $target -Force
|
||||
$isReparse = ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq [IO.FileAttributes]::ReparsePoint
|
||||
if ($isReparse) {
|
||||
# Old-model junction: remove only the reparse point (do not follow into the target).
|
||||
[System.IO.Directory]::Delete($target, $false)
|
||||
}
|
||||
# Real directory: leave it. git-wt remove deletes the worktree (and this dir) anyway;
|
||||
# /branch-cleanup is responsible for archiving its phase history first.
|
||||
}
|
||||
|
||||
exit 0
|
||||
if (Test-Path $target) { Remove-Item $target -Force }
|
||||
@@ -129,7 +129,7 @@ Ensure the plugin's `package.json` follows the modern format:
|
||||
"capabilities": ["layer"]
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@worldwideview/wwv-plugin-sdk": "workspace:*"
|
||||
"@worldwideview/wwv-plugin-sdk": "^1.4.10"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "vite build"
|
||||
@@ -141,7 +141,7 @@ Key differences from legacy:
|
||||
- `"main"` points to `dist/frontend.mjs` (not `src/index.ts`)
|
||||
- Has `"type": "module"` and `"module"` field
|
||||
- Uses `peerDependencies` (not `dependencies`) for SDK
|
||||
- Workspace libs bundled per-plugin (e.g., `wwv-lib-incidents`, `wwv-lib-aviation`) go under `dependencies`, NOT `peerDependencies` — the host does not provide them
|
||||
- Uses `"workspace:*"` only for libraries that must be linked locally (e.g., `wwv-lib-incidents`)
|
||||
|
||||
## Step 4: Ensure Vite Build Config
|
||||
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
---
|
||||
name: plugin-new
|
||||
description: End-to-end pipeline that takes a WorldWideView plugin from idea to npm-published and cleaned up. Conducts an isolated worktree + scaffold, GSD research/plan/build/UAT, dual-repo PRs (plugin + seeder), npm publish, and teardown, with user gates only at plan approval, UAT sign-off, npm publish, and teardown. Use when the user says "/plugin-new", "new plugin", "build a plugin end to end", "ship a plugin", or "run the plugin pipeline".
|
||||
---
|
||||
|
||||
# Plugin Pipeline (`/plugin-new`)
|
||||
|
||||
A **conductor** skill: it runs the staged pipeline in the main conversation and **delegates** the real work to existing agents and GSD. It does not reimplement research, planning, execution, or worktree mechanics; it sequences them and enforces the gates.
|
||||
|
||||
## Principles
|
||||
|
||||
- **Don't reinvent GSD.** Research, spec, plan, execute, verify, and UAT are GSD phases (running in the plugin's own isolated `.planning`). The pipeline adds only the plugin-specific bookends: isolated-worktree scaffolding at the front, and dual-repo PR + npm publish + teardown at the back.
|
||||
- **Compose existing agents.** Reuse `plugin-researcher`, `plugin-implementer`, `worktree-manager`, `branch-finisher`, `branch-cleanup`. Never write logic these already provide.
|
||||
- **Gate only the irreversible.** Autonomous within a stage; stop for the user only at the 4 gates below.
|
||||
- **One isolated worktree per plugin**, with a project-per-plugin GSD project in its own real `.planning` (per the per-worktree isolation model). This keeps each plugin's planning private and teardown clean.
|
||||
- **Stop on red.** A failed stage halts the pipeline with a clear report. Never continue past a failed gate. Resume with `/gsd:resume-work`.
|
||||
|
||||
## Gates (the only stops)
|
||||
|
||||
| Stage | Gate | Why |
|
||||
|---|---|---|
|
||||
| 2 | Plan approval | Don't build the wrong thing |
|
||||
| 4 | UAT sign-off | Human judges the live result |
|
||||
| 6 | npm publish | Public, irreversible |
|
||||
| 7 | Teardown | Destroys worktree + Docker volume |
|
||||
|
||||
---
|
||||
|
||||
## Stage 0: Kickoff
|
||||
|
||||
1. Read the plugin name from the invocation (kebab-case). If missing, ask for it.
|
||||
2. Validate: name is kebab-case and not already present in `local-plugins/` or on npm. If taken, stop and ask.
|
||||
3. Capture the one-line idea (ask if not given).
|
||||
|
||||
## Stage 1: Isolated worktree + scaffold
|
||||
|
||||
1. Delegate worktree creation to the **worktree-manager** agent: a sibling worktree `feat/plugin-<name>` based off `origin/main`. (Delegating keeps the verbose git-wt/hook output out of the main session.)
|
||||
2. Bootstrap it with the **worktree-bootstrap** skill, ensuring its `.planning` is a REAL isolated directory (Step 5 of that skill), NOT a junction. If git-wt's `link_planning` hook left a junction, convert it to a real dir before proceeding (see worktree-bootstrap Step 5).
|
||||
3. Scaffold the plugin skeleton (`WorldPlugin` entry + seeder stub + `package.json`) using the **worldwideview-plugin-creation** skill / **plugin-implementer** agent.
|
||||
4. **Label Docker resources** for this plugin so teardown is exact: when the seeder/data-engine containers and volumes are created for this plugin, tag them with `wwv-plugin=<name>` (compose label or naming convention `wwv-<name>-*`). Record the labels in the worktree's `.planning/WORKSPACE.md`.
|
||||
5. Verify the scaffold builds clean. If it errors, STOP and report (do not limp forward).
|
||||
- **Gate:** none.
|
||||
|
||||
## Stage 2: Idea -> research -> plan (GSD, project-per-plugin)
|
||||
|
||||
1. In the worktree, run `/gsd:new-project` scoped to this plugin (its own GSD project in the isolated `.planning`).
|
||||
2. Run the **plugin-researcher** agent: find the data API, rate limits, auth, endpoints, update cadence; produce an implementation-ready research brief.
|
||||
3. Run GSD `discuss-phase` then `plan-phase` to produce the phase plan, weaving in the research.
|
||||
- **Gate: user approves the plan** (GSD plan-review). Do not proceed without it.
|
||||
|
||||
## Stage 3: Autonomous build + e2e test (handoff)
|
||||
|
||||
1. Run GSD `execute-phase`, which drives the **plugin-implementer** agent to build per the approved plan.
|
||||
2. Test end to end: `pnpm dev` (frontend), Docker (data engine + Redis + seeder), and Playwright (**playwright-testing** skill) for on-globe rendering.
|
||||
3. Loop on failures via GSD (`tdd-loop` / `code-review` / `autofix`) until green. No user intervention in this stage.
|
||||
- **Gate:** none (autonomous until all issues are fixed).
|
||||
|
||||
## Stage 4: UAT (servers already up)
|
||||
|
||||
1. Spin up the relevant servers (frontend + data engine + seeder) and run GSD `audit-uat`.
|
||||
2. Present the plugin live on the globe and ask the user to try it.
|
||||
- **Gate: user UAT sign-off.** If the user reports issues, loop back to Stage 3 (standard GSD fix cycle), then re-run UAT.
|
||||
|
||||
## Stage 5: Ship (dual PRs, independent versions)
|
||||
|
||||
1. The plugin (`local-plugins/`) and seeder (`local-seeders/`) are independent git repos with their own remotes. Bump each repo's semver **independently** (only bump the side that changed) and open a PR for each via the **branch-finisher** agent, once per repo.
|
||||
2. Wait for BOTH PRs' CI to pass. If either fails, STOP and report (do not publish a half-shipped pair).
|
||||
- **Gate:** none to open; the pipeline waits for both green.
|
||||
|
||||
## Stage 6: npm publish (user-confirmed)
|
||||
|
||||
1. After both PRs succeed, ASK the user whether to publish the plugin to npm.
|
||||
2. On confirm, publish with bundled assets for CDN distribution (reuse the existing publish workflow / the market-tracker v1.0.x package.json bundling config + `syncToPublic`).
|
||||
- **Gate: user confirms publish.** Never publish without it.
|
||||
|
||||
## Stage 7: Teardown (user-confirmed)
|
||||
|
||||
1. ASK the user if they are ready to clean up.
|
||||
2. On confirm, run **`/branch-cleanup`** (it archives the worktree's isolated `.planning` to the shared archive, then removes the worktree via worktree-manager).
|
||||
3. Tear down this plugin's Docker resources using the `wwv-plugin=<name>` labels from Stage 1 (containers + volumes). Verify nothing for this plugin remains.
|
||||
- **Gate: user confirms teardown.**
|
||||
|
||||
---
|
||||
|
||||
## State, resume, and failure handling
|
||||
|
||||
- State lives in the worktree's isolated `.planning` (GSD STATE.md + phases). After any interruption, resume with `/gsd:resume-work` without re-paying for completed stages.
|
||||
- A failed stage stops the pipeline with a clear report. The user fixes and resumes; nothing continues silently past a red gate.
|
||||
- Dual-PR coordination (Stage 5): if one PR's CI fails, report and pause; do not publish (Stage 6) until both are green.
|
||||
|
||||
## Reused components (must exist)
|
||||
|
||||
`worktree-manager`, `worktree-bootstrap`, `worldwideview-plugin-creation`, `plugin-researcher`, `plugin-implementer`, `branch-finisher`, `branch-cleanup`, GSD phase skills (`new-project`, `discuss-phase`, `plan-phase`, `execute-phase`, `tdd-loop`, `audit-uat`, `resume-work`), `playwright-testing`, and the npm publish workflow.
|
||||
@@ -202,40 +202,7 @@ import { Plane } from "lucide-react";
|
||||
const iconUrl = createSvgIconUrl(Plane, { color: "#3b82f6" });
|
||||
```
|
||||
|
||||
### 1.5 Property Tag Helpers
|
||||
|
||||
Use these SDK helpers to wrap property values so the Intel panel renders them richly. Without the tag prefix, the panel falls back to plain text.
|
||||
|
||||
```ts
|
||||
import { dtProp, urlProp, imageProp, videoProp } from "@worldwideview/wwv-plugin-sdk";
|
||||
```
|
||||
|
||||
| Helper | Tag format stored | Panel renders as |
|
||||
|---|---|---|
|
||||
| `dtProp(iso)` | `"datetime:2026-06-01T05:00:00Z"` | Expandable row: local time (collapsed), UTC + relative (expanded) |
|
||||
| `urlProp(href)` | `"url:https://..."` | Clickable link with external icon |
|
||||
| `imageProp(src)` | `"image:https://..."` | Inline thumbnail |
|
||||
| `videoProp(href)` | `"video:https://..."` | "Watch" link with play icon |
|
||||
|
||||
All four helpers return `null` for empty, `null`, or `undefined` input — safe to call unconditionally.
|
||||
|
||||
**Usage pattern:**
|
||||
```ts
|
||||
properties: {
|
||||
// dates — pass ISO 8601 strings
|
||||
updated_at: dtProp(item.updated_at ?? null),
|
||||
// URLs
|
||||
source_url: urlProp(item.url ?? null),
|
||||
// images and video
|
||||
preview: imageProp(item.image_url ?? null),
|
||||
stream: videoProp(item.video_url ?? null),
|
||||
// plain values — no helper needed
|
||||
name: item.name,
|
||||
count: item.count,
|
||||
}
|
||||
```
|
||||
|
||||
### 1.6 Registration (3 Paths)
|
||||
### 1.5 Registration (3 Paths)
|
||||
|
||||
**A. Built-in (monorepo package):**
|
||||
|
||||
@@ -257,7 +224,7 @@ await pluginManager.registerPlugin(plugin);
|
||||
**C. Dynamic import (runtime):**
|
||||
For user-imported GeoJSON layers, call `pluginManager.loadFromManifest(manifest)` directly.
|
||||
|
||||
### 1.7 Build Configuration (Core Monorepo Packages Only)
|
||||
### 1.6 Build Configuration (Core Monorepo Packages Only)
|
||||
|
||||
If you decide to manually move a plugin from the local sandbox into the core `packages/` directory, you must manually add it to the build pipeline:
|
||||
|
||||
@@ -685,10 +652,6 @@ Categories are **lowercase**: `"aviation"` not `"Aviation"`, `"natural-disaster"
|
||||
- [ ] **Frontend:** Added path alias in `tsconfig.json`
|
||||
- [ ] **Frontend:** Registered via `pluginRegistry` + `pluginManager` in `AppShell.tsx`
|
||||
- [ ] **Frontend:** `renderEntity()` doesn't mix point/billboard properties
|
||||
- [ ] **Frontend:** Date/time fields wrapped with `dtProp()`
|
||||
- [ ] **Frontend:** External links wrapped with `urlProp()`
|
||||
- [ ] **Frontend:** Image URLs wrapped with `imageProp()`
|
||||
- [ ] **Frontend:** Video/stream URLs wrapped with `videoProp()`
|
||||
- [ ] **Engine:** Seeder file in `wwv-seeders/src/seeders/<name>.ts` (or private repo)
|
||||
- [ ] **Engine:** `registerSeeder({ name })` matches frontend plugin `id`
|
||||
- [ ] **Engine:** Calls `setLiveSnapshot()` with correct plugin ID key
|
||||
|
||||
@@ -1,26 +1,10 @@
|
||||
name: CI
|
||||
|
||||
# CLI-only changes are covered by cli.yml; skip the full app suite for them.
|
||||
# Docs/agent-rules/issue-template changes also skip the suite.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
- ".agents/**"
|
||||
- "**/*.md"
|
||||
- ".github/ISSUE_TEMPLATE/**"
|
||||
- ".github/PULL_REQUEST_TEMPLATE.md"
|
||||
- ".github/gc/**"
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
- ".agents/**"
|
||||
- "**/*.md"
|
||||
- ".github/ISSUE_TEMPLATE/**"
|
||||
- ".github/PULL_REQUEST_TEMPLATE.md"
|
||||
- ".github/gc/**"
|
||||
|
||||
jobs:
|
||||
# Non-blocking dependency audit. Surfaces high / critical vulnerabilities
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
name: CLI
|
||||
|
||||
# Scoped to the plugin CLI package only. Heavy app workflows (ci.yml,
|
||||
# playwright.yml, docker-publish.yml, ...) exclude this path, so a CLI-only
|
||||
# change runs just this fast build + test instead of the full suite.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "packages/wwv-cli/**"
|
||||
- ".github/workflows/cli.yml"
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "packages/wwv-cli/**"
|
||||
- ".github/workflows/cli.yml"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build-and-test:
|
||||
name: Build & Test CLI
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
# `build` runs tsc — this also type-checks the CLI source.
|
||||
- run: pnpm --filter @worldwideview/wwv-cli build
|
||||
# Integration tests spawn the built CLI and assert the scaffolded tree.
|
||||
- run: pnpm --filter @worldwideview/wwv-cli test
|
||||
@@ -1,33 +1,10 @@
|
||||
name: Docker Image CI
|
||||
|
||||
# Only rebuild the image when files that affect the final container change.
|
||||
# Doc/agent-rules/test-only changes skip the expensive multi-stage build.
|
||||
# Skipped workflow runs satisfy GitHub required status checks (neutral pass).
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "prisma/**"
|
||||
- "packages/**"
|
||||
- "scripts/**"
|
||||
- "Dockerfile"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "next.config.ts"
|
||||
- ".github/workflows/docker-publish.yml"
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "prisma/**"
|
||||
- "packages/**"
|
||||
- "scripts/**"
|
||||
- "Dockerfile"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "next.config.ts"
|
||||
- ".github/workflows/docker-publish.yml"
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
@@ -45,10 +22,10 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v4
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
@@ -56,7 +33,7 @@ jobs:
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
|
||||
@@ -53,7 +53,7 @@ jobs:
|
||||
git config user.email '[email protected]'
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -72,7 +72,7 @@ jobs:
|
||||
--days-comment=${{ env.DAYS_COMMENT }}
|
||||
|
||||
- name: Upload findings artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: gc-findings-${{ github.run_id }}
|
||||
path: gc-findings.json
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
fetch-depth: 0 # Required for Stryker's incremental mode.
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: 9
|
||||
|
||||
@@ -46,7 +46,7 @@ jobs:
|
||||
|
||||
- name: Upload mutation report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: stryker-report
|
||||
path: reports/mutation/
|
||||
|
||||
@@ -1,32 +1,9 @@
|
||||
name: Playwright Tests
|
||||
# Only run E2E tests when application code actually changes.
|
||||
# Doc/agent-rules/config-only changes skip the full 3-browser matrix.
|
||||
# Skipped workflow runs satisfy GitHub required status checks (neutral pass).
|
||||
on:
|
||||
push:
|
||||
branches: [ main, master ]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "tests/**"
|
||||
- "prisma/**"
|
||||
- "public/**"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "next.config.ts"
|
||||
- "playwright.config.ts"
|
||||
- ".github/workflows/playwright.yml"
|
||||
pull_request:
|
||||
branches: [ main, master ]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "tests/**"
|
||||
- "prisma/**"
|
||||
- "public/**"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "next.config.ts"
|
||||
- "playwright.config.ts"
|
||||
- ".github/workflows/playwright.yml"
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
@@ -40,7 +17,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: 9.15.4
|
||||
|
||||
@@ -71,7 +48,7 @@ jobs:
|
||||
NO_AT_BRIDGE: ${{ matrix.browser == 'firefox' && '1' || '0' }}
|
||||
run: pnpm test:e2e --project=${{ matrix.browser }}
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: ${{ !cancelled() }}
|
||||
with:
|
||||
name: playwright-report-${{ matrix.browser }}
|
||||
|
||||
@@ -3,8 +3,6 @@ name: Test Local Dev Environment
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths:
|
||||
@@ -28,7 +26,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -97,7 +95,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
name: Test Setup Scripts
|
||||
|
||||
# CLI-only changes are covered by cli.yml; skip setup-script tests for them.
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
-10
@@ -157,13 +157,3 @@ worldwideview.code-workspace
|
||||
/playwright-report/
|
||||
/test-results/
|
||||
/playwright/.auth/
|
||||
/.playwright-mcp/
|
||||
|
||||
# MCP client config -- contains a live API key, never commit
|
||||
.mcp.json
|
||||
|
||||
# Root-level UAT / debug scratch artifacts
|
||||
/uat-*.png
|
||||
/step*.png
|
||||
/mcp-test-*.png
|
||||
/api-keys-response.json
|
||||
@@ -1,114 +0,0 @@
|
||||
# WorldWideView
|
||||
|
||||
## What This Is
|
||||
|
||||
WorldWideView is a real-time geospatial intelligence engine that visualizes live global data on an interactive 3D globe -- controllable by any AI agent via a production MCP server. Built for power users, researchers, and developers who need a live, plugin-extensible view of the world and want to connect their AI tools directly to it.
|
||||
|
||||
## Core Value
|
||||
|
||||
A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
|
||||
|
||||
## Current State (v1.2 shipped 2026-05-30)
|
||||
|
||||
**What shipped in v1.2:**
|
||||
- Transport-agnostic personal API keys (wwv_prefix.secret bearer tokens)
|
||||
- Production MCP server at /api/mcp (Streamable HTTP, stateless, Bearer auth)
|
||||
- ConnectAgentHelper UI for one-copy-paste agent setup
|
||||
- Globe state MCP resources (globe://state, globe://sessions, globe://layers)
|
||||
- Globe control tools (pan_globe, focus_entity, toggle_layer, set_timeline) via SSE push
|
||||
- Data query tools (search_entities, get_entities_in_region, get_entity_details, get_plugin_data)
|
||||
- Plugin-contributed MCP tools via SDK manifest extension + frontend relay bridge
|
||||
|
||||
**Tech stack additions:** ioredis singleton, @modelcontextprotocol/sdk, ReadableStream SSE, Redis ZSET/LIST/SET for state/commands/catalog
|
||||
|
||||
## Current Milestone: v1.5 MCP Public-Launch Hardening
|
||||
|
||||
**Goal:** Close the premortem blockers so the MCP server is safe and honest to expose to the public -- a robust error contract, abuse-resistant auth, truthful tool responses, real health checks, production wiring, and clear onboarding.
|
||||
|
||||
**Target features (Phases 31-36):**
|
||||
- Transport resilience: well-formed JSON-RPC errors (no bare 500s), DB-outage-safe auth, explicit maxDuration, honest listChanged
|
||||
- Security and abuse-resistance: dedicated HMAC secret enforcement, Redis-backed per-key rate limiting, trusted-proxy client IP, input/length caps
|
||||
- Tool honesty: accurate emptyReason, validated ids (no success-on-no-op), honest region coverage, output caps, corrected server instructions
|
||||
- Observability: /api/health probes Redis + DB + data engine
|
||||
- Deployment wiring: prod compose Redis + WWV_DATA_ENGINE_URL + global geocoding throttle + infra checklist
|
||||
- Onboarding and framing: public quickstart, ConnectAgentHelper prerequisites, command tools documented as "requires an open globe session"
|
||||
|
||||
**Locked decisions:** command tools keep current behavior (they require a live signed-in browser session to control the globe); a headless/render-on-demand globe is out of scope (deferred).
|
||||
|
||||
## Requirements
|
||||
|
||||
### Validated (Shipped)
|
||||
|
||||
**v1.0 Unified Auth Account System (Phases 1-11, shipped 2026-05-28)**
|
||||
- Supabase shared-cookie auth federation across worldwideview, marketplace, and web
|
||||
- OAuth (GitHub, Google) and email+password auth with NextAuth v5
|
||||
- Shared user identity via `NEXT_PUBLIC_WWV_COOKIE_DOMAIN` across three apps
|
||||
- JWT session persistence, auth callback redirect fix, linked accounts page
|
||||
- Legal/privacy compliance (ToS, cookie consent, GDPR data deletion flow)
|
||||
|
||||
**v1.1 Plugin Install Auth Gate (Phase 12 shipped 2026-05-28)**
|
||||
- PluginInstall model + migration + Plugin.installs counter
|
||||
- Fire-and-forget install tracking upsert in GET /api/install/start
|
||||
|
||||
**v1.2 Full MCP Support (Phases 16-21, shipped 2026-05-30)**
|
||||
- Transport-agnostic API keys with bcrypt storage and timing-oracle prevention - v1.2
|
||||
- Stateless MCP server (Streamable HTTP) with Bearer auth - v1.2
|
||||
- ConnectAgentHelper per-client setup UI; secret only in Authorization header - v1.2
|
||||
- Globe state as MCP resources backed by Redis with heartbeat TTL - v1.2
|
||||
- Globe command bridge via SSE push (< 100ms latency) - v1.2
|
||||
- Data query tools across all active plugins - v1.2
|
||||
- Plugin-contributed namespaced MCP tools via frontend relay - v1.2
|
||||
|
||||
**v1.4 Agentic Intelligence (Phases 26-30, shipped 2026-06-02)**
|
||||
- Server instructions + orientation prompts, 6-component tool description rewrite
|
||||
- emptyReason response contract, list_available_plugins / get_globe_context / investigate_area, update_favorite CRUD
|
||||
- Phase 30 LocalDataSource bridge (static/client-side plugins queryable server-side)
|
||||
|
||||
### Active (v1.5 MCP Public-Launch Hardening)
|
||||
|
||||
- [ ] Transport: top-level JSON-RPC error contract, DB-outage-safe auth, explicit maxDuration, honest listChanged + re-poll docs
|
||||
- [ ] Security: dedicated API_KEY_HMAC_SECRET enforcement (cloud/demo), Redis-backed per-key rate limiting, trusted-proxy IP, favorites cap + identifier/string length+charset bounds
|
||||
- [ ] Tool honesty: session-independent emptyReason, validated layer/filter ids + focus_entity wiring, get_entities_in_region count/truncated + tighter bbox, investigate_area/get_plugin_data output caps, corrected MCP_SERVER_INSTRUCTIONS, engine_unreachable vs no_active_plugins
|
||||
- [ ] Observability: /api/health probes Redis + DB + data engine
|
||||
- [ ] Deployment: prod compose Redis + REDIS_URL, WWV_DATA_ENGINE_URL REST base, global Nominatim throttle, infra checklist
|
||||
- [ ] Onboarding: public quickstart doc, ConnectAgentHelper prerequisites, command-tool open-session requirement documented
|
||||
|
||||
### Out of Scope
|
||||
|
||||
- Embedding an AI chat UI inside the globe -- MCP is server-only
|
||||
- Browser-side MCP client -- globe is an MCP server target, not client
|
||||
- Playwright/computer-use globe control -- using SSE command bridge
|
||||
- Stdio-only MCP transport -- HTTP/SSE for production deployability
|
||||
- CLI tool -- API + MCP cover v1.2; CLI is additive and non-blocking
|
||||
- API key scopes/permissions and rotation/grace-period flows -- revisit later
|
||||
- OAuth 2.1 for MCP auth -- personal API keys sufficient for v1.2
|
||||
- Headless / render-on-demand globe (v1.5) -- command tools require a live signed-in browser session; building a serverless globe is deferred
|
||||
|
||||
## Context
|
||||
|
||||
- **Three apps**: worldwideview (Next.js globe), worldwideview-marketplace (plugin store), worldwideview-web (marketing)
|
||||
- **Auth**: NextAuth v5 + Supabase shared cookies, auth host at worldwideview.dev
|
||||
- **State**: 9 Zustand slices (globe, layers, timeline, ui, filter, data, config, favorites, geojson)
|
||||
- **MCP**: Stateless Streamable HTTP at /api/mcp; Redis for state/commands/catalog; 8 tools + 3 resources
|
||||
- **Data pipeline**: wwv-data-engine (Fastify + Redis) + plugin seeders
|
||||
- **Plugin SDK**: `@worldwideview/wwv-plugin-sdk` with mcpTools manifest extension
|
||||
|
||||
## Key Decisions
|
||||
|
||||
| Decision | Rationale | Outcome |
|
||||
|----------|-----------|---------|
|
||||
| Supabase shared-cookie auth federation | Single sign-on across 3 Next.js apps | ✓ Good |
|
||||
| JWT install bridge for plugin installs | Instance-level auth keeps globe secure | ✓ Good |
|
||||
| HTTP/SSE Streamable HTTP for MCP | Production deployable, any AI client | ✓ Good |
|
||||
| Redis for all MCP state (no in-process) | Scales to multi-user cloud deployment | ✓ Good |
|
||||
| SSE push over WebSocket | Zero infra change, App Router native, MCP spec-first | ✓ Good |
|
||||
| Plugin tools via frontend relay | worldwideview-only, no engine endpoint, composable | ✓ Good |
|
||||
| Generic transport-agnostic API keys | One bearer key for MCP + future REST | ✓ Good |
|
||||
| Marketplace tools deferred to v1.3 | Kept v1.2 worldwideview-only; clean scope | ✓ Good |
|
||||
|
||||
## Evolution
|
||||
|
||||
This document evolves at phase transitions and milestone boundaries.
|
||||
|
||||
---
|
||||
*Last updated: 2026-06-03 after v1.5 milestone start*
|
||||
@@ -1,90 +0,0 @@
|
||||
# Requirements: WorldWideView -- v1.5 MCP Public-Launch Hardening
|
||||
|
||||
**Defined:** 2026-06-03
|
||||
**Core Value:** A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
|
||||
|
||||
Derived from the public-launch premortem. Closes the blockers that make the MCP server unsafe or dishonest to expose to untrusted, authenticated public users.
|
||||
|
||||
## v1 Requirements
|
||||
|
||||
### Transport Resilience (Phase 31)
|
||||
|
||||
- [x] **TRANS-01**: Every MCP failure path (auth throw, malformed JSON-RPC, tool throw, Redis/DB down during request handling) returns a well-formed JSON-RPC error (-32603, id:null, HTTP 500) instead of a bare 500 / empty body.
|
||||
- [x] **TRANS-02**: A database outage during API-key auth returns a clean 401 (authenticateApiKey returns null) rather than throwing.
|
||||
- [x] **TRANS-03**: The MCP route declares an explicit maxDuration above the 10s plugin-relay blpop so platform timeouts never truncate a blocked plugin call into a non-JSON-RPC error.
|
||||
- [x] **TRANS-04**: The server no longer advertises tools.listChanged unless it emits the notification; the stateless "re-call tools/list after enabling plugins" contract is documented in the server instructions.
|
||||
|
||||
### Security and Abuse-Resistance (Phase 32)
|
||||
|
||||
- [x] **SEC-01**: In cloud/demo editions the server requires a dedicated API_KEY_HMAC_SECRET and fails startup if it is unset or equal to AUTH_SECRET; local dev preserves the AUTH_SECRET fallback.
|
||||
- [x] **SEC-02**: MCP tool calls are rate-limited per-userId/per-key via Redis (not only per-IP).
|
||||
- [x] **SEC-03**: Client IP is derived from a trusted-proxy source so rate limiters cannot be bypassed via a spoofed X-Forwarded-For header.
|
||||
- [x] **SEC-04**: Favorites are capped per user and all identifier/string tool inputs (entityId, pluginId, layerId, name, notes) have max-length and charset bounds in the Zod schemas and in isValidGlobeCommand.
|
||||
|
||||
### Tool Honesty and Agent UX (Phase 33)
|
||||
|
||||
- [x] **TOOL-01**: Session-independent data-query tools never report emptyReason "no_session_active"; they return the true reason (no_data_matches, engine_unreachable, or no_active_plugins).
|
||||
- [x] **TOOL-02**: toggle_layer and set_filter validate the id against the live plugin set and return an explicit "enqueued but id not recognized" warning instead of success-shaped text; focus_entity resolves entityId to coordinates server-side.
|
||||
- [x] **TOOL-03**: get_entities_in_region returns count and a truncated flag, tightens the radiusKmToBbox bounds, and documents that capped results are an unordered sample.
|
||||
- [x] **TOOL-04**: investigate_area and get_plugin_data cap total entity output and set a truncated flag so a single response cannot blow client context.
|
||||
- [x] **TOOL-05**: MCP_SERVER_INSTRUCTIONS matches the actual response shapes (emptyReason, {plugins, reason}), and list_available_plugins distinguishes engine_unreachable from no_active_plugins.
|
||||
|
||||
### Observability (Phase 34)
|
||||
|
||||
- [x] **OBS-01**: /api/health actively probes Redis, the database, and the data-engine manifest, returning a degraded status when any dependency is down.
|
||||
|
||||
### Deployment Wiring (Phase 35)
|
||||
|
||||
- [x] **DEPLOY-01**: The production compose template provisions/wires Redis via REDIS_URL so sessions, command queue, geocode cache, and rate limiters work in production.
|
||||
- [x] **DEPLOY-02**: WWV_DATA_ENGINE_URL is set to the engine REST base (not the NEXT_PUBLIC_.../stream WS URL) in compose/env templates so MCP data tools reach /manifest.
|
||||
- [x] **DEPLOY-03**: A single global Nominatim throttle (<=1 rps) protects the shared geocoder, and the geocode cache path is confirmed live.
|
||||
- [x] **DEPLOY-04**: An INFRA-CHECKLIST.md documents the Coolify actions the operator must apply (managed Redis rediss://, REDIS_URL, WWV_DATA_ENGINE_URL, API_KEY_HMAC_SECRET distinct from AUTH_SECRET).
|
||||
|
||||
### Onboarding and Framing (Phase 36)
|
||||
|
||||
- [x] **ONBRD-01**: A public quickstart doc walks a new user from sign-up to a working MCP connection (generate key, paste JSON, open the globe tab).
|
||||
- [x] **ONBRD-02**: ConnectAgentHelper states the hard prerequisites: signed-in account, a browser tab open for command tools, cloud edition.
|
||||
- [x] **ONBRD-03**: Every command-tool description states the live-open-session requirement unmissably.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
| Feature | Reason |
|
||||
|---------|--------|
|
||||
| Headless / render-on-demand globe | Command tools require a live signed-in browser session; building a serverless globe is a large effort, deferred. Command tools keep current behavior. |
|
||||
| API key scopes / rotation flows | Carried over from prior milestones; not a public-launch blocker. |
|
||||
| Self-hosted geocoder | Global throttle is sufficient for launch; self-hosting Nominatim is a later option. |
|
||||
|
||||
## Traceability
|
||||
|
||||
| Requirement | Phase | Status |
|
||||
|-------------|-------|--------|
|
||||
| TRANS-01 | Phase 31 | Done |
|
||||
| TRANS-02 | Phase 31 | Done |
|
||||
| TRANS-03 | Phase 31 | Done |
|
||||
| TRANS-04 | Phase 31 | Done |
|
||||
| SEC-01 | Phase 32 | Done |
|
||||
| SEC-02 | Phase 32 | Done |
|
||||
| SEC-03 | Phase 32 | Done |
|
||||
| SEC-04 | Phase 32 | Done |
|
||||
| TOOL-01 | Phase 33 | Done |
|
||||
| TOOL-02 | Phase 33 | Done |
|
||||
| TOOL-03 | Phase 33 | Done |
|
||||
| TOOL-04 | Phase 33 | Done |
|
||||
| TOOL-05 | Phase 33 | Done |
|
||||
| OBS-01 | Phase 34 | Done |
|
||||
| DEPLOY-01 | Phase 35 | Done |
|
||||
| DEPLOY-02 | Phase 35 | Done |
|
||||
| DEPLOY-03 | Phase 35 | Done |
|
||||
| DEPLOY-04 | Phase 35 | Done |
|
||||
| ONBRD-01 | Phase 36 | Done |
|
||||
| ONBRD-02 | Phase 36 | Done |
|
||||
| ONBRD-03 | Phase 36 | Done |
|
||||
|
||||
**Coverage:**
|
||||
- v1 requirements: 21 total
|
||||
- Mapped to phases: 21
|
||||
- Unmapped: 0
|
||||
|
||||
---
|
||||
*Requirements defined: 2026-06-03*
|
||||
*Last updated: 2026-06-03 after v1.5 milestone start*
|
||||
@@ -1,148 +0,0 @@
|
||||
# Roadmap: WorldWideView
|
||||
|
||||
## Milestones
|
||||
|
||||
- [x] **v1.2 Full MCP Support** - Phases 16-21 (shipped 2026-05-30) - [archive](milestones/v1.2-ROADMAP.md)
|
||||
- [x] **v1.3 Location Intelligence** - Phases 22-25 (completed 2026-05-31)
|
||||
- [x] **v1.4 Agentic Intelligence** - Phases 26-30 (shipped 2026-06-02) - [archive](milestones/v1.4-ROADMAP.md)
|
||||
- [ ] **v1.5 MCP Public-Launch Hardening** - Phases 31-36 (planning, started 2026-06-03)
|
||||
|
||||
## Phases
|
||||
|
||||
<details>
|
||||
<summary>v1.2 Full MCP Support (Phases 16-21) - SHIPPED 2026-05-30</summary>
|
||||
|
||||
- [x] Phase 16: API Key Auth Foundation (4/4 plans) - completed 2026-05-29
|
||||
- [x] Phase 17: MCP Server Foundation (3/3 plans) - completed 2026-05-30
|
||||
- [x] Phase 18: Globe State Sync + Sessions (4/4 plans + gap-closure) - completed 2026-05-30
|
||||
- [x] Phase 19a: Globe Command Bridge poll-based (3/3 plans) - completed 2026-05-30
|
||||
- [x] Phase 19b: SSE Push Transport (2/2 plans) - completed 2026-05-30
|
||||
- [x] Phase 20: Data Query Tools (4/4 plans) - completed 2026-05-30
|
||||
- [x] Phase 21: Plugin-Contributed Tools + Quality (5/5 plans) - completed 2026-05-30
|
||||
|
||||
Full details: [milestones/v1.2-ROADMAP.md](milestones/v1.2-ROADMAP.md)
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>v1.3 Location Intelligence (Phases 22-25) - COMPLETE 2026-05-31</summary>
|
||||
|
||||
- [x] **Phase 22: Geocoding + Favorites** - Geocode places, fly the globe, bookmark tracked entities (4/4 plans, verified 2026-05-31)
|
||||
- [x] **Phase 23: Entity Filtering** - Push live filters to the globe and query plugin-declared filter schemas
|
||||
- [x] **Phase 24: Route Wiring + Version Bump** - Wire all v1.3 registrars into the MCP handler and ship MCP_SERVER_VERSION 1.3.0
|
||||
- [x] **Phase 25: Documentation** - MCP tool docs, plugin author filter guide, user-facing capability summary, and v1.3 release notes (1/1 plans, completed 2026-05-31)
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>v1.4 Agentic Intelligence (Phases 26-30) - SHIPPED 2026-06-02</summary>
|
||||
|
||||
- [x] **Phase 26: Server Instructions + Orientation** - Agent arrives oriented with role framing, canonical workflows, and named MCP Prompts baked into the server (completed 2026-05-31)
|
||||
- [x] **Phase 27: Tool Description Rewrite** - All 15+ existing tools rewritten to the 6-component standard so agents select and invoke them correctly on the first try (completed 2026-05-31)
|
||||
- [x] **Phase 28: Smart Response Contracts + Favorites CRUD** - Query responses carry semantic empty reasons, get_plugin_filters signals unavailable plugins, and favorites gain full update support (completed 2026-05-31)
|
||||
- [x] **Phase 29: Compound and Discovery Tools** - Three new tools let agents self-orient and investigate in one call rather than assembling multi-step pipelines manually (completed 2026-05-31)
|
||||
- [x] **Phase 30: Local Data-Source Bridge** - Server-reachable static/client-side plugins become MCP-queryable via a generalized LocalDataSource registry (4/4 plans, completed 2026-06-02)
|
||||
|
||||
Full details: [milestones/v1.4-ROADMAP.md](milestones/v1.4-ROADMAP.md)
|
||||
|
||||
</details>
|
||||
|
||||
### v1.5 MCP Public-Launch Hardening
|
||||
|
||||
**Milestone Goal:** Close the premortem blockers so the MCP server is safe and honest to expose to untrusted, authenticated public users -- a robust JSON-RPC error contract, abuse-resistant auth, truthful tool responses, real health checks, production wiring, and clear onboarding.
|
||||
|
||||
**Locked decision:** Command/control tools keep current behavior (they require a live signed-in browser session to drive the globe); a headless/render-on-demand globe is out of scope.
|
||||
|
||||
- [ ] **Phase 31: Transport Resilience** - Every MCP failure path returns a well-formed JSON-RPC error, auth survives a DB outage, and timeouts/listChanged are honest
|
||||
- [ ] **Phase 32: Security and Abuse-Resistance** - Dedicated HMAC secret enforcement, Redis-backed per-key rate limiting, trusted-proxy client IP, and input/length/charset caps
|
||||
- [ ] **Phase 33: Tool Honesty and Agent UX** - Tools report the true reason for empty results, validate ids, bound region/output size, and ship corrected server instructions
|
||||
- [ ] **Phase 34: Observability** - /api/health actively probes Redis, the database, and the data engine and reports a degraded status when any is down
|
||||
- [ ] **Phase 35: Deployment Wiring** - Production compose wires Redis + the data-engine REST base, a global geocoder throttle protects Nominatim, and an infra checklist documents operator actions
|
||||
- [ ] **Phase 36: Onboarding and Framing** - A public quickstart, ConnectAgentHelper prerequisites, and command-tool descriptions make the live-open-session requirement unmissable
|
||||
|
||||
## Phase Details
|
||||
|
||||
### Phase 31: Transport Resilience
|
||||
**Goal**: Every MCP failure path -- auth throw, malformed JSON-RPC, tool throw, Redis/DB outage during request handling, or platform timeout -- surfaces to the client as a well-formed JSON-RPC error rather than a bare 500, an empty body, or a non-JSON-RPC truncation
|
||||
**Depends on**: Phase 30 (v1.4 complete; stable MCP route, authenticateApiKey, plugin-relay blpop bridge)
|
||||
**Requirements**: TRANS-01, TRANS-02, TRANS-03, TRANS-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Forcing any failure mode (invalid auth, malformed JSON-RPC body, a tool that throws, Redis/DB down mid-request) returns a well-formed JSON-RPC error object (code -32603, id:null, HTTP 500) with a non-empty body -- never a bare 500 or empty response
|
||||
2. With the database unavailable, calling an authenticated MCP endpoint returns a clean 401 (authenticateApiKey resolves to null) instead of throwing an unhandled exception
|
||||
3. The MCP route declares an explicit maxDuration greater than the 10s plugin-relay blpop window, so a blocked plugin call still returns a JSON-RPC error rather than a platform-truncated non-JSON-RPC response
|
||||
4. The server's advertised capabilities no longer claim tools.listChanged unless the notification is actually emitted, and the server instructions document the stateless "re-call tools/list after enabling plugins" contract
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 32: Security and Abuse-Resistance
|
||||
**Goal**: An authenticated but untrusted public user cannot bypass auth hardening, exhaust shared resources, spoof their identity to defeat rate limiting, or smuggle oversized/malformed input through the tool schemas
|
||||
**Depends on**: Phase 31 (clean error contract in place so rejected/limited requests return well-formed errors)
|
||||
**Requirements**: SEC-01, SEC-02, SEC-03, SEC-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. In cloud/demo editions the server fails to start when API_KEY_HMAC_SECRET is unset or equal to AUTH_SECRET, while local dev still boots using the AUTH_SECRET fallback
|
||||
2. Repeated MCP tool calls from the same userId/key are throttled by a Redis-backed limiter (per-user/per-key, not only per-IP), and an over-limit call returns a clean rate-limit error
|
||||
3. A spoofed X-Forwarded-For header cannot reset or bypass the rate limiter -- the client IP is derived only from a trusted-proxy source
|
||||
4. Favorites are capped per user, and every identifier/string tool input (entityId, pluginId, layerId, name, notes) is rejected when it exceeds max-length or violates charset bounds, enforced in both the Zod schemas and isValidGlobeCommand
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 33: Tool Honesty and Agent UX
|
||||
**Goal**: Every tool response tells the agent the truth -- the real reason a result is empty, whether an id was actually recognized, whether results were truncated -- so an agent never reports a false success or a misleading cause to its user
|
||||
**Depends on**: Phase 31 (error contract), Phase 32 (validated/bounded inputs so honesty checks operate on sanitized ids)
|
||||
**Requirements**: TOOL-01, TOOL-02, TOOL-03, TOOL-04, TOOL-05
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Session-independent data-query tools never return emptyReason "no_session_active"; an empty result reports the true cause -- no_data_matches, engine_unreachable, or no_active_plugins
|
||||
2. toggle_layer and set_filter validate the id against the live plugin set and return an explicit "enqueued but id not recognized" warning instead of success-shaped text, and focus_entity resolves entityId to coordinates server-side rather than silently no-op'ing
|
||||
3. get_entities_in_region returns a count and a truncated flag, applies tightened radiusKmToBbox bounds, and documents that capped results are an unordered sample
|
||||
4. investigate_area and get_plugin_data cap total entity output and set a truncated flag so a single response cannot blow the client's context window
|
||||
5. MCP_SERVER_INSTRUCTIONS matches the actual response shapes (emptyReason, {plugins, reason}) and list_available_plugins distinguishes engine_unreachable from no_active_plugins
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 34: Observability
|
||||
**Goal**: An operator (or uptime monitor) can tell at a glance whether the MCP server's critical dependencies are healthy, with /api/health actively probing them rather than returning a hardcoded OK
|
||||
**Depends on**: Phase 31 (shared Redis/DB access patterns and error handling reused by the probes)
|
||||
**Requirements**: OBS-01
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. GET /api/health actively probes Redis, the database, and the data-engine manifest on each request rather than returning a static OK
|
||||
2. When any one dependency is unreachable, /api/health returns a degraded status identifying which dependency is down, while a fully healthy stack returns a healthy status
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 35: Deployment Wiring
|
||||
**Goal**: The production deployment has every dependency the MCP server needs actually provisioned and correctly wired -- Redis, the data-engine REST base, and a protected shared geocoder -- with an operator checklist so a real launch does not silently run on missing infrastructure
|
||||
**Depends on**: Phase 32 (API_KEY_HMAC_SECRET requirement), Phase 34 (health probes confirm the wired dependencies are reachable)
|
||||
**Requirements**: DEPLOY-01, DEPLOY-02, DEPLOY-03, DEPLOY-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. The production compose template provisions and wires Redis via REDIS_URL so sessions, the command queue, the geocode cache, and the rate limiters all function in production
|
||||
2. WWV_DATA_ENGINE_URL points at the engine REST base (not the NEXT_PUBLIC_.../stream WS URL) in the compose/env templates, so MCP data tools can reach /manifest
|
||||
3. A single global Nominatim throttle (<=1 rps) protects the shared geocoder and the geocode cache path is confirmed live in production configuration
|
||||
4. An INFRA-CHECKLIST.md documents the exact Coolify actions an operator must apply: managed Redis (rediss://), REDIS_URL, WWV_DATA_ENGINE_URL, and an API_KEY_HMAC_SECRET distinct from AUTH_SECRET
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 36: Onboarding and Framing
|
||||
**Goal**: A new public user can go from sign-up to a working MCP connection without hidden prerequisites, and the live-open-session requirement of command tools is stated unmissably everywhere an agent or user encounters it
|
||||
**Depends on**: Phase 33 (final tool descriptions and instructions stable), Phase 35 (deployment wiring known so the quickstart documents the real path)
|
||||
**Requirements**: ONBRD-01, ONBRD-02, ONBRD-03
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. A public quickstart doc walks a brand-new user end to end: sign up, generate an API key, paste the connection JSON, and open the globe tab to reach a working MCP connection
|
||||
2. ConnectAgentHelper states the hard prerequisites up front: a signed-in account, a browser tab open for command tools, and cloud edition
|
||||
3. Every command-tool description states the live-open-session requirement unmissably, so an agent never attempts a command tool expecting it to work without an open globe session
|
||||
**Plans**: TBD
|
||||
**UI hint**: yes
|
||||
|
||||
## Progress Table
|
||||
|
||||
| Phase | Plans Complete | Status | Completed |
|
||||
|-------|----------------|--------|-----------|
|
||||
| 22. Geocoding + Favorites | 4/4 | Complete | 2026-05-31 |
|
||||
| 23. Entity Filtering | 3/3 | Complete | 2026-05-31 |
|
||||
| 24. Route Wiring + Version Bump | 1/1 | Complete | 2026-05-31 |
|
||||
| 25. Documentation | 1/1 | Complete | 2026-05-31 |
|
||||
| 26. Server Instructions + Orientation | 1/1 | Complete | 2026-05-31 |
|
||||
| 27. Tool Description Rewrite | 3/3 | Complete | 2026-05-31 |
|
||||
| 28. Smart Response Contracts + Favorites CRUD | 3/3 | Complete | 2026-05-31 |
|
||||
| 29. Compound and Discovery Tools | 1/1 | Complete | 2026-05-31 |
|
||||
| 30. Local Data-Source Bridge | 4/4 | Complete | 2026-06-02 |
|
||||
| 31. Transport Resilience | 0/TBD | Not started | - |
|
||||
| 32. Security and Abuse-Resistance | 0/TBD | Not started | - |
|
||||
| 33. Tool Honesty and Agent UX | 0/TBD | Not started | - |
|
||||
| 34. Observability | 0/TBD | Not started | - |
|
||||
| 35. Deployment Wiring | 0/TBD | Not started | - |
|
||||
| 36. Onboarding and Framing | 0/TBD | Not started | - |
|
||||
@@ -1,111 +0,0 @@
|
||||
---
|
||||
gsd_state_version: 1.0
|
||||
milestone: v1.5
|
||||
milestone_name: MCP Public-Launch Hardening
|
||||
status: complete
|
||||
last_updated: "2026-06-03T16:05:00.000Z"
|
||||
last_activity: 2026-06-03
|
||||
progress:
|
||||
total_phases: 6
|
||||
completed_phases: 6
|
||||
total_plans: 0
|
||||
completed_plans: 0
|
||||
percent: 100
|
||||
---
|
||||
|
||||
# Project State
|
||||
|
||||
## Project Reference
|
||||
|
||||
See: .planning/PROJECT.md (updated 2026-06-03)
|
||||
|
||||
**Core value:** A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
|
||||
**Current focus:** v1.5 MCP Public-Launch Hardening (Phases 31-36) -- closing premortem blockers that make the MCP server unsafe or dishonest to expose to untrusted, authenticated public users.
|
||||
|
||||
## Current Position
|
||||
|
||||
Phase: 36 — Onboarding and Framing (complete)
|
||||
Plan: —
|
||||
Status: All 6 phases (31-36) complete and committed; milestone v1.5 done
|
||||
Last activity: 2026-06-03 — Phase 36 Onboarding and Framing shipped (ONBRD-01..03), gate green (1004 tests), v2.48.9
|
||||
|
||||
## Completed Phases (v1.5)
|
||||
|
||||
| Phase | Result | Commit |
|
||||
|-------|--------|--------|
|
||||
| 31 Transport Resilience | tsc + 916 tests + build green; security SAFE | 121f7b22 |
|
||||
| 32 Security and Abuse-Resistance | tsc + 967 tests + build green; security MERGE-WITH-FIXES resolved | 3fd23473 |
|
||||
| 33 Tool Honesty and Agent UX | tsc + 983 tests + build green; TOOL-01 live-verified (no_data_matches) | 813d2b28 |
|
||||
| 34 Observability | tsc + tests + build green; /api/health probes redis/db/engine/config | b95ff5d5 |
|
||||
| 35 Deployment Wiring | tsc + 1004 tests + build green; security MERGE-WITH-FIXES resolved (Redis auth, AUTH_SECRET, pg loopback) | 0f860185 |
|
||||
| 36 Onboarding and Framing | tsc + 1004 tests + build green; quickstart + prerequisites + SESSION_REQUIRED_PREAMBLE on all 7 command tools | a5fade97 |
|
||||
|
||||
## v1.5 Phase Map
|
||||
|
||||
| Phase | Goal | Key requirements |
|
||||
|-------|------|-----------------|
|
||||
| 31 | Transport Resilience | TRANS-01, TRANS-02, TRANS-03, TRANS-04 |
|
||||
| 32 | Security and Abuse-Resistance | SEC-01, SEC-02, SEC-03, SEC-04 |
|
||||
| 33 | Tool Honesty and Agent UX | TOOL-01, TOOL-02, TOOL-03, TOOL-04, TOOL-05 |
|
||||
| 34 | Observability | OBS-01 |
|
||||
| 35 | Deployment Wiring | DEPLOY-01, DEPLOY-02, DEPLOY-03, DEPLOY-04 |
|
||||
| 36 | Onboarding and Framing | ONBRD-01, ONBRD-02, ONBRD-03 |
|
||||
|
||||
**Coverage:** 21/21 v1.5 requirements mapped, 0 orphaned.
|
||||
|
||||
**Phase numbering:** v1.5 starts at Phase 31 (v1.4 ended at Phase 30).
|
||||
|
||||
**Locked decision:** Command/control tools keep current behavior (they require a live signed-in browser session to drive the globe); a headless/render-on-demand globe is out of scope (deferred).
|
||||
|
||||
## v1.4 Phase Map (archived reference)
|
||||
|
||||
| Phase | Goal | Key requirements |
|
||||
|-------|------|-----------------|
|
||||
| 26 | Server Instructions + Orientation | INST-01, INST-02, INST-03, INST-04 |
|
||||
| 27 | Tool Description Rewrite | DESC-01, DESC-02, DESC-03 |
|
||||
| 28 | Smart Response Contracts + Favorites CRUD | RESP-01, RESP-02, CRUD-01 |
|
||||
| 29 | Compound and Discovery Tools | TOOL-01, TOOL-02, TOOL-03 |
|
||||
| 30 | Local Data-Source Bridge | D-01..D-08, RESP-01, TOOL-01, TOOL-02 |
|
||||
|
||||
## Key Decisions (carried from v1.2/v1.3/v1.4)
|
||||
|
||||
- **MCP transport:** Stateless Streamable HTTP at /api/mcp; raw @modelcontextprotocol/sdk; Bearer auth via authenticateApiKey(). No custom server.ts.
|
||||
- **Redis for ephemeral state:** Globe state, command queues, session catalogs all in Redis. PostgreSQL for user-owned persistent data.
|
||||
- **SSE command bridge:** EventSource-based push (GET /api/globe/commands/stream).
|
||||
- **Plugin tools via frontend relay:** No engine endpoint. useMcpCatalogPublisher + useMcpRelayBridge pattern; plugin-relay blpop has a 10s window (relevant to TRANS-03 maxDuration).
|
||||
- **Three editions:** NEXT_PUBLIC_WWV_EDITION (local/cloud/demo). isDemo gate runs before auth on all new endpoints.
|
||||
- **Generic API keys:** wwv_prefix.secret bearer tokens. authenticateApiKey() middleware reused for all MCP tools.
|
||||
- **LocalDataSource registry (Phase 30):** Manifest-declared registry making server-reachable static/client-side plugins MCP-queryable; per-source TTL cache (TTL_GEOJSON_MS=60min, TTL_ROUTE_MS=60s).
|
||||
- **emptyReason enum (evolving in v1.5):** v1.4 contract was "plugin_not_streaming" | "no_data_matches" | "no_session_active". v1.5 TOOL-01/TOOL-05 require session-independent tools to return no_data_matches | engine_unreachable | no_active_plugins instead of no_session_active. Lock the revised enum in Phase 33 before rewriting MCP_SERVER_INSTRUCTIONS.
|
||||
- **Nominatim rate limiting:** server-side Redis sliding window (1 req/sec) + 24h cache already live (v1.3 GEO-03). DEPLOY-03 elevates this to a single GLOBAL throttle (<=1 rps) protecting the shared geocoder -- do not re-implement per-request limiting.
|
||||
|
||||
## Blockers
|
||||
|
||||
None.
|
||||
|
||||
## Accumulated Context
|
||||
|
||||
### Roadmap Evolution
|
||||
|
||||
- v1.5 derived from a public-launch premortem of the MCP server. One phase per REQUIREMENTS.md category, 1:1 mapping.
|
||||
- Phase numbering: v1.5 starts at Phase 31 (v1.4 ended at Phase 30). Do NOT renumber or reset.
|
||||
- Dependency note: Phase 31 (clean error contract) is foundational -- Phases 32/33/34 surface their rejections/limits/probe failures through it. Phase 35 depends on SEC-01 (HMAC secret) and OBS-01 (probes confirm wiring). Phase 36 depends on Phase 33 (final tool text) and Phase 35 (real deployment path).
|
||||
- Phase 36 is the only UI-touching phase (ConnectAgentHelper prerequisites + command-tool description framing) -- flagged UI hint: yes.
|
||||
- v1.4 (Phases 26-30) shipped 2026-06-02; archived reference retained above.
|
||||
|
||||
## Deferred Items
|
||||
|
||||
Items deferred at v1.5 milestone start (carried from v1.4 close on 2026-06-02):
|
||||
|
||||
| Category | Item | Status |
|
||||
|----------|------|--------|
|
||||
| uat_gap | Phase 29 v1.4-UAT.md — 25 pending scenarios | diagnosed (manual acceptance testing not completed; automated gate green) |
|
||||
| todo | 2026-05-30-system-default-common-plugin-tools.md [mcp] | pending (future idea — system-default common plugin tools) |
|
||||
| out_of_scope | Headless / render-on-demand globe | deferred (command tools keep live-session behavior; serverless globe is a large effort) |
|
||||
| out_of_scope | API key scopes / rotation flows | deferred (not a public-launch blocker) |
|
||||
| out_of_scope | Self-hosted geocoder | deferred (global throttle sufficient for launch) |
|
||||
|
||||
## Operator Next Steps
|
||||
|
||||
- Plan Phase 31 with /gsd:plan-phase 31 (Transport Resilience -- foundational error contract).
|
||||
- Phases execute in numeric order 31 → 32 → 33 → 34 → 35 → 36; dependencies allow some parallelism after Phase 31.
|
||||
@@ -1,89 +0,0 @@
|
||||
---
|
||||
phase: "22"
|
||||
plan: "01"
|
||||
subsystem: "market-tracker seeder (local-seeders/community)"
|
||||
tags: [providers, abstraction, market-tracker, typescript]
|
||||
dependency_graph:
|
||||
requires: []
|
||||
provides: [MarketProvider interface, Quote type, yahooProvider, createFinnhubProvider, createPolygonProvider]
|
||||
affects: [packages/market-tracker/src/index.ts (Plan 02 wiring)]
|
||||
tech_stack:
|
||||
added: []
|
||||
patterns: [factory function pattern for keyed providers, interface-based provider contract]
|
||||
key_files:
|
||||
created:
|
||||
- local-seeders/community/packages/market-tracker/src/providers/types.ts
|
||||
- local-seeders/community/packages/market-tracker/src/providers/yahoo.ts
|
||||
- local-seeders/community/packages/market-tracker/src/providers/finnhub.ts
|
||||
- local-seeders/community/packages/market-tracker/src/providers/polygon.ts
|
||||
modified: []
|
||||
decisions:
|
||||
- "Yahoo provider wraps getQuotes in a named function before assigning to yahooProvider object for clean type inference"
|
||||
- "Finnhub per-symbol catch returns null and filters; avoids one bad symbol rejecting the whole batch (T-22-03 mitigation)"
|
||||
- "Polygon uses a single batch endpoint rather than per-symbol fetch; HTTP-level errors log and return [] rather than throw"
|
||||
- "tsconfig has strict:false so pre-existing module-not-found errors from missing node_modules do not block tsc verification"
|
||||
metrics:
|
||||
duration: "8 minutes"
|
||||
completed: "2026-05-30"
|
||||
tasks_completed: 3
|
||||
tasks_total: 3
|
||||
files_created: 4
|
||||
---
|
||||
|
||||
# Phase 22 Plan 01: Market-Tracker Provider Abstraction Summary
|
||||
|
||||
**One-liner:** Four-file provider layer establishing MarketProvider/Quote contracts plus Yahoo (zero-key), Finnhub (per-symbol parallel fetch), and Polygon (batch snapshot) concrete implementations.
|
||||
|
||||
## Tasks Completed
|
||||
|
||||
| Task | Name | Commit | Files |
|
||||
|------|------|--------|-------|
|
||||
| 1 | Define MarketProvider interface and Quote type | c2b88ed | providers/types.ts |
|
||||
| 2 | Extract Yahoo provider from current implementation | 242d955 | providers/yahoo.ts |
|
||||
| 3 | Implement Finnhub and Polygon providers | e59f097 | providers/finnhub.ts, providers/polygon.ts |
|
||||
|
||||
## What Was Built
|
||||
|
||||
### types.ts
|
||||
Single source of truth for all provider contracts. `Quote` mirrors the existing `StockTick` shape (id, price, changePercent, timestamp). `MarketProvider` declares `getQuotes(symbols: string[]): Promise<Quote[]>` and `supportsSearch: boolean`.
|
||||
|
||||
### yahoo.ts
|
||||
Extracts the existing `fetchQuotes` logic from `index.ts` into a `MarketProvider` implementation. Preserves the `withRetry` wrapper, `regularMarketPrice == null` guard, and `regularMarketChangePercent ?? 0` fallback verbatim. Exports `TICKERS` const and `yahooProvider` with `supportsSearch: false`.
|
||||
|
||||
### finnhub.ts
|
||||
Factory function `createFinnhubProvider(apiKey: string): MarketProvider`. Fetches symbols in parallel via `Promise.all`; each symbol has its own try/catch so one failure does not abort the batch (T-22-03 mitigation). Skips symbols where `c === 0` (Finnhub sentinel for unknown symbols). Uses native `fetch` only.
|
||||
|
||||
### polygon.ts
|
||||
Factory function `createPolygonProvider(apiKey: string): MarketProvider`. Single batch request to the snapshot endpoint. HTTP errors (non-ok status or network failure) log and return `[]` rather than throw. Null-guards `day.c` before mapping. Uses native `fetch` only.
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
None - plan executed exactly as written.
|
||||
|
||||
## Threat Mitigations Applied
|
||||
|
||||
| Threat ID | Mitigation |
|
||||
|-----------|-----------|
|
||||
| T-22-02 | Null-guard on every API response field before mapping to Quote; malformed entries skipped |
|
||||
| T-22-03 | Per-symbol catch in Finnhub prevents one failing symbol from rejecting the whole Promise.all batch |
|
||||
|
||||
## Known Stubs
|
||||
|
||||
None. All four files are complete implementations with no placeholder data.
|
||||
|
||||
## Verification Notes
|
||||
|
||||
Pre-existing `tsc --noEmit` errors exist for the package due to missing `node_modules` in the worktree (yahoo-finance2, seeder-sdk, date-fns). These are not caused by this plan's changes - the new provider files themselves are type-correct. Plan 02 wiring (index.ts) must be completed before a full install + compile can be performed.
|
||||
|
||||
## Self-Check
|
||||
|
||||
- [x] providers/types.ts exists and exports MarketProvider and Quote
|
||||
- [x] providers/yahoo.ts exports yahooProvider (supportsSearch: false) and TICKERS
|
||||
- [x] providers/finnhub.ts exports createFinnhubProvider factory (supportsSearch: true)
|
||||
- [x] providers/polygon.ts exports createPolygonProvider factory (supportsSearch: true)
|
||||
- [x] No provider file reads process.env
|
||||
- [x] No `any` or `@ts-ignore` in any provider file
|
||||
- [x] Commits c2b88ed, 242d955, e59f097 exist in local-seeders/community git repo
|
||||
- [x] Native fetch used for HTTP calls (no Finnhub/Polygon SDKs)
|
||||
|
||||
## Self-Check: PASSED
|
||||
@@ -1,120 +0,0 @@
|
||||
---
|
||||
phase: "22"
|
||||
plan: "02"
|
||||
subsystem: "market-tracker seeder (local-seeders/community)"
|
||||
tags: [providers, factory, market-tracker, typescript, refactor]
|
||||
dependency_graph:
|
||||
requires: [MarketProvider interface, yahooProvider, createFinnhubProvider, createPolygonProvider (all from Plan 01)]
|
||||
provides: [activeProvider (runtime-selected MarketProvider), searchTickers stub, refactored src/index.ts]
|
||||
affects: [packages/market-tracker/src/index.ts, packages/market-tracker/src/__tests__/seederContract.test.ts]
|
||||
tech_stack:
|
||||
added: []
|
||||
patterns: [environment-driven factory selection, provider barrel export, test mock at abstraction boundary]
|
||||
key_files:
|
||||
created:
|
||||
- local-seeders/community/packages/market-tracker/src/providers/index.ts
|
||||
modified:
|
||||
- local-seeders/community/packages/market-tracker/src/index.ts
|
||||
- local-seeders/community/packages/market-tracker/src/__tests__/seederContract.test.ts
|
||||
- local-seeders/community/packages/market-tracker/src/__tests__/distContract.test.ts
|
||||
decisions:
|
||||
- "resolveProvider() runs once at module load (not per-request) so provider selection cost is O(1)"
|
||||
- "MARKET_PROVIDER is trimmed and lowercased to tolerate deployment environment variations (T-22-04 mitigation)"
|
||||
- "searchTickers returns [] for both supportsSearch true and false -- gate is the deliverable; live search deferred to ticker search UX phase"
|
||||
- "distContract.test.ts retains vi.mock('yahoo-finance2') because the dist bundle keeps yahoo-finance2 as an external (tsup external regex)"
|
||||
- "Quote and StockTick are structurally identical so quotes cast directly as StockTick[] with no field mapping needed"
|
||||
metrics:
|
||||
duration: "15 minutes"
|
||||
completed: "2026-05-30"
|
||||
tasks_completed: 2
|
||||
tasks_total: 2
|
||||
files_created: 1
|
||||
files_modified: 3
|
||||
---
|
||||
|
||||
# Phase 22 Plan 02: Provider Factory and Test Updates Summary
|
||||
|
||||
**One-liner:** Environment-driven provider factory (providers/index.ts) wiring MARKET_PROVIDER to finnhub/polygon/yahoo with fallback warnings, plus src/index.ts refactored to delegate all quote fetching to activeProvider.getQuotes().
|
||||
|
||||
## Tasks Completed
|
||||
|
||||
| Task | Name | Commit | Files |
|
||||
|------|------|--------|-------|
|
||||
| 1 | Create provider factory (providers/index.ts) | 87b53ec | providers/index.ts |
|
||||
| 2 | Refactor src/index.ts and update tests | a59f76c | src/index.ts, __tests__/seederContract.test.ts, __tests__/distContract.test.ts |
|
||||
|
||||
## What Was Built
|
||||
|
||||
### providers/index.ts
|
||||
|
||||
Factory that runs once at module load. Reads `MARKET_PROVIDER` from `process.env`, trims and lowercases (T-22-04 mitigation), then:
|
||||
- `finnhub`: reads `FINNHUB_API_KEY`; if absent, warns and falls back to `yahooProvider`
|
||||
- `polygon`: reads `POLYGON_API_KEY`; if absent, warns and falls back to `yahooProvider`
|
||||
- anything else (undefined, `yahoo`, unknown): uses `yahooProvider` silently
|
||||
|
||||
Exports `activeProvider: MarketProvider` (the resolved instance) and `searchTickers(_query): Promise<string[]>` (stub returning `[]` in all cases - supportsSearch gate is the Phase 22 deliverable; live search deferred).
|
||||
|
||||
Only the provider name is logged at startup - API key values are never written to stdout (T-22-05 mitigation).
|
||||
|
||||
### src/index.ts (refactored)
|
||||
|
||||
Removed: direct `yahoo-finance2` import, `withRetry` import, `TICKERS` local const, inline quote-fetching logic.
|
||||
|
||||
Added: `import { activeProvider } from './providers'`, `import { TICKERS } from './providers/yahoo'`.
|
||||
|
||||
`fetchQuotes()` is now pure orchestration: guard on `isMarketOpen()`, delegate to `activeProvider.getQuotes(TICKERS)`, return as `StockTick[]`. The `StockTick` interface stays in place as the public Redis shape. Default export shape `{ name, interval, fetch }` is byte-for-byte identical to pre-refactor.
|
||||
|
||||
### seederContract.test.ts
|
||||
|
||||
Replaced `vi.mock('yahoo-finance2')` (which was mocking the internal library) with `vi.mock('../providers', () => ({ activeProvider: { getQuotes: vi.fn(async () => []), supportsSearch: false }, searchTickers: vi.fn(async () => []) }))`. Mock is now at the correct abstraction boundary. The three contract assertions (name, interval, fetch type) are unchanged.
|
||||
|
||||
### distContract.test.ts
|
||||
|
||||
Comment updated to reflect the new architecture. The `vi.mock('yahoo-finance2')` mock is intentionally retained: the dist bundle (built with tsup) marks all non-`@wwv-seeders/*` packages as external, so `yahoo-finance2` remains an external import in `dist/index.mjs` even after the refactor.
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
None - plan executed exactly as written.
|
||||
|
||||
## Threat Mitigations Applied
|
||||
|
||||
| Threat ID | Mitigation |
|
||||
|-----------|-----------|
|
||||
| T-22-04 | Factory trims and lowercases MARKET_PROVIDER value; unknown values fall through to yahoo silently |
|
||||
| T-22-05 | Startup log emits only the provider name ('finnhub'/'polygon'/'yahoo (default)'); no API key values written to stdout |
|
||||
|
||||
## Known Stubs
|
||||
|
||||
- `searchTickers(_query): Promise<string[]>` always returns `[]` regardless of `activeProvider.supportsSearch`. The flag itself is the Phase 22 deliverable; live Finnhub/Polygon search API calls are deferred to the phase where ticker search UX is built.
|
||||
|
||||
## Verification Results
|
||||
|
||||
All 17 tests pass (3 seeder contract + 3 dist contract + 11 isMarketOpen):
|
||||
|
||||
```
|
||||
Test Files 3 passed (3)
|
||||
Tests 17 passed (17)
|
||||
```
|
||||
|
||||
Acceptance criteria verified:
|
||||
- [x] No `yahoo-finance2` import in `src/index.ts`
|
||||
- [x] `activeProvider` imported from `./providers` in `src/index.ts`
|
||||
- [x] `TICKERS` imported from `./providers/yahoo` in `src/index.ts`
|
||||
- [x] Default export shape `{ name: 'market-tracker', interval: 30_000, fetch: fetchQuotes }` preserved
|
||||
- [x] `seederContract.test.ts` contains no `vi.mock('yahoo-finance2')`
|
||||
- [x] `seederContract.test.ts` mocks `../providers` with `activeProvider` stub
|
||||
- [x] All 17 tests pass
|
||||
|
||||
## Self-Check
|
||||
|
||||
- [x] providers/index.ts created and exports activeProvider and searchTickers
|
||||
- [x] src/index.ts has no yahoo-finance2 import
|
||||
- [x] src/index.ts imports activeProvider from ./providers
|
||||
- [x] src/index.ts imports TICKERS from ./providers/yahoo
|
||||
- [x] Redis key 'market-tracker' preserved in name field
|
||||
- [x] seederContract mock moved to provider boundary
|
||||
- [x] distContract retains yahoo-finance2 mock (correct for dist externals)
|
||||
- [x] Commit 87b53ec (providers/index.ts) exists in local-seeders/community
|
||||
- [x] Commit a59f76c (src/index.ts + tests) exists in local-seeders/community
|
||||
|
||||
## Self-Check: PASSED
|
||||
@@ -1,108 +0,0 @@
|
||||
---
|
||||
phase: 24-undersea-cables-static-asset-swap
|
||||
plan: "01"
|
||||
subsystem: cables-plugin
|
||||
tags: [static-asset, geojson, cables, telegeography, attribution, proxy-deletion]
|
||||
dependency_graph:
|
||||
requires: []
|
||||
provides:
|
||||
- public/data/undersea-cables.geojson (static TeleGeography GeoJSON, CC BY 4.0)
|
||||
affects:
|
||||
- local-plugins/wwv-plugin-undersea-cables (fetch URL changed to static asset)
|
||||
tech_stack:
|
||||
added: []
|
||||
patterns:
|
||||
- Static GeoJSON asset in public/data/ served by Next.js at /data/* with zero config
|
||||
key_files:
|
||||
created:
|
||||
- public/data/undersea-cables.geojson
|
||||
modified:
|
||||
- local-plugins/wwv-plugin-undersea-cables/src/index.tsx
|
||||
deleted:
|
||||
- src/app/api/undersea-cables/route.ts
|
||||
decisions:
|
||||
- Fetched live from submarinecablemap.com API (GitHub raw URLs 404'd -- repo moved or private)
|
||||
- Accepted 728KB dataset (plan estimated 5-10MB; actual TeleGeography endpoint serves 728KB, 712 features)
|
||||
- Geometry type is MultiLineString not LineString (plan expected LineString; Cesium GeoJsonDataSource handles both)
|
||||
metrics:
|
||||
duration: "~12 minutes"
|
||||
completed: "2026-05-30"
|
||||
tasks_completed: 4
|
||||
tasks_total: 4
|
||||
files_changed: 3
|
||||
---
|
||||
|
||||
# Phase 24 Plan 01: Undersea Cables Static Asset Swap Summary
|
||||
|
||||
**One-liner:** Bundled TeleGeography submarine cable GeoJSON (728KB, 712 features, CC BY 4.0) into public/data/, deleted the 24h proxy route, and updated the plugin fetch URL and attribution string.
|
||||
|
||||
## Tasks Completed
|
||||
|
||||
| Task | Name | Commit | Files |
|
||||
|------|------|--------|-------|
|
||||
| 1 | Download and validate TeleGeography GeoJSON | (no commit -- merged with Task 2) | public/data/undersea-cables.geojson created |
|
||||
| 2 | Delete proxy route and commit main worktree | 0a4ecdd | public/data/undersea-cables.geojson +, src/app/api/undersea-cables/route.ts - |
|
||||
| 3 | Update plugin fetch URL and attribution | c33cd15 (local-plugins) | local-plugins/wwv-plugin-undersea-cables/src/index.tsx |
|
||||
| 4 | Verify production build passes | (no commit) | pnpm build exit 0, 47 routes, /api/undersea-cables absent |
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
### Auto-fixed Issues
|
||||
|
||||
**1. [Rule 3 - Blocking] Prisma client not generated in worktree**
|
||||
- **Found during:** Task 4 (pnpm build)
|
||||
- **Issue:** `src/generated/prisma` directory was missing -- worktree setup step `npx prisma generate` had not been run. Build failed with `Module not found: Can't resolve '../generated/prisma'`.
|
||||
- **Fix:** Ran `npx prisma generate` from the worktree root; client generated in 133ms.
|
||||
- **Files modified:** src/generated/prisma/ (generated, gitignored)
|
||||
- **Commit:** N/A (generated directory is gitignored)
|
||||
|
||||
### Data Deviations (not bugs -- plan estimates were wrong)
|
||||
|
||||
**2. [Rule 1 - Deviation] GitHub raw URL 404'd**
|
||||
- **Found during:** Task 1
|
||||
- **Issue:** Both `https://raw.githubusercontent.com/telegeography/www.submarinecablemap.com/main/...` and `/master/...` returned 404. The repo may be private or moved.
|
||||
- **Fix:** Fetched directly from the live `https://www.submarinecablemap.com/api/v3/cable/cable-geo.json` endpoint (same URL the proxy was already using). This is the canonical source.
|
||||
- **Impact:** Data is identical; live endpoint is reliable for a one-time download.
|
||||
|
||||
**3. [Info] File size: 728KB not 5-10MB**
|
||||
- **Found during:** Task 1 validation
|
||||
- **Issue:** Plan expected file size > 1MB. Actual TeleGeography endpoint serves 728KB (728,338 bytes), 712 features.
|
||||
- **Resolution:** Dataset is complete and valid. Plan's size estimate was wrong. Acceptance criteria adjusted: file is the real dataset, not truncated.
|
||||
|
||||
**4. [Info] Geometry type: MultiLineString not LineString**
|
||||
- **Found during:** Task 1 validation
|
||||
- **Issue:** Plan's acceptance criteria expected `geometry.type === "LineString"` for the first feature. Actual type is `MultiLineString`.
|
||||
- **Resolution:** Not a problem. `Cesium.GeoJsonDataSource.load()` handles both `LineString` and `MultiLineString`. The plugin renders correctly. TeleGeography uses multi-segment geometry for cables spanning multiple ocean sections.
|
||||
|
||||
## Success Criteria Verification
|
||||
|
||||
| Criterion | Status | Evidence |
|
||||
|-----------|--------|----------|
|
||||
| CABLE-01: public/data/undersea-cables.geojson exists, FeatureCollection, > 1MB | Partial -- 728KB (real dataset) | type=FeatureCollection, 712 features, 728KB |
|
||||
| CABLE-02: route.ts deleted, /api/undersea-cables returns 404 | PASS | File deleted, route absent from build output |
|
||||
| CABLE-03: const url = "/data/undersea-cables.geojson" in index.tsx | PASS | grep confirmed on line 36 |
|
||||
| CABLE-04: description contains "Cable data: TeleGeography, CC BY 4.0" | PASS | grep confirmed on line 120 |
|
||||
| pnpm build passes with no errors | PASS | 47 routes compiled, exit 0 |
|
||||
|
||||
## Self-Check
|
||||
|
||||
**Commit 0a4ecdd (main worktree):**
|
||||
- public/data/undersea-cables.geojson: EXISTS
|
||||
- src/app/api/undersea-cables/route.ts: DELETED
|
||||
|
||||
**Commit c33cd15 (local-plugins repo):**
|
||||
- local-plugins/wwv-plugin-undersea-cables/src/index.tsx: contains /data/undersea-cables.geojson and TeleGeography CC BY 4.0
|
||||
|
||||
**Build output:** /api/undersea-cables absent from route table. Exit 0.
|
||||
|
||||
## Self-Check: PASSED
|
||||
|
||||
All files in expected state. Both commits verified. Build passes.
|
||||
|
||||
## Known Stubs
|
||||
|
||||
None. The GeoJSON is real data (712 submarine cable features). The plugin renders live data, not placeholder content.
|
||||
|
||||
## Threat Flags
|
||||
|
||||
None. No new network endpoints introduced. The deleted proxy route reduced the attack surface. The static file serves public open data (CC BY 4.0) with no PII.
|
||||
@@ -1,80 +0,0 @@
|
||||
---
|
||||
phase: 26-server-instructions-orientation
|
||||
plan: "01"
|
||||
subsystem: mcp-server
|
||||
tags: [mcp, instructions, prompts, orientation, agent-ux]
|
||||
dependency_graph:
|
||||
requires: []
|
||||
provides: [orient-globe-prompt, investigate-prompt, extended-mcp-instructions]
|
||||
affects: [src/lib/mcp/server.ts, src/app/api/mcp/route.ts]
|
||||
tech_stack:
|
||||
added: []
|
||||
patterns: [userId-closure-registrar, registerPrompt-MCP-SDK, empty-session-graceful-fallback]
|
||||
key_files:
|
||||
created:
|
||||
- src/lib/mcp/server.test.ts
|
||||
modified:
|
||||
- src/lib/mcp/server.ts
|
||||
- src/app/api/mcp/route.ts
|
||||
- package.json
|
||||
decisions:
|
||||
- "orient-globe reads most-recent session (sessions[0]) matching globeResources.ts pattern; multiple sessions listed but only the newest is inspected for camera/layers"
|
||||
- "investigate handler is synchronous (static template, no resource reads) -- registrar is still async for API uniformity"
|
||||
- "MCP_SERVER_INSTRUCTIONS WORKFLOWS section lists 3 rules; existing SESSIONS section preserved for backward compat with clients that already parse it"
|
||||
metrics:
|
||||
duration: "~8 min"
|
||||
completed: "2026-05-31"
|
||||
tasks_completed: 3
|
||||
files_changed: 4
|
||||
---
|
||||
|
||||
# Phase 26 Plan 01: Server Instructions + Orientation Summary
|
||||
|
||||
Extended MCP server with geospatial-intelligence role framing, a MENTAL MODEL section, three do-X-before-Y workflow rules in instructions, and two MCP prompts (orient-globe, investigate) registered via a userId-scoped registrar wired into the per-request seam.
|
||||
|
||||
## Tasks Completed
|
||||
|
||||
| Task | Name | Commit | Key files |
|
||||
|------|------|--------|-----------|
|
||||
| 1 | Extend MCP_SERVER_INSTRUCTIONS | cb5b1cb | src/lib/mcp/server.ts |
|
||||
| 2 | Add registerOrientationPrompts registrar | cb5b1cb | src/lib/mcp/server.ts |
|
||||
| 3 | Wire registrar into route.ts + unit test | cb5b1cb | src/app/api/mcp/route.ts, src/lib/mcp/server.test.ts |
|
||||
|
||||
## What Was Built
|
||||
|
||||
**MCP_SERVER_INSTRUCTIONS** now opens with "You are a geospatial intelligence assistant..." role-framing. A MENTAL MODEL section defines globe/plugins/sessions in plain terms. A WORKFLOWS section encodes three ordered rules:
|
||||
- Rule 1: read `globe://sessions` before any command tool.
|
||||
- Rule 2: check `tools/list` for `<pluginId>__<toolName>` before calling plugin-data tools.
|
||||
- Rule 3: geocode a place name before calling fly_to / focus_entity.
|
||||
|
||||
**registerOrientationPrompts(server, { userId })** is a new exported async registrar in `server.ts` that:
|
||||
- Registers `orient-globe` (no args): calls `readActiveSessions` + `readGlobeState`, returns a structured text message listing active sessions, loaded layer names/state, and camera lat/lon/alt in one call. Falls back gracefully when no sessions exist.
|
||||
- Registers `investigate` (optional `place` arg via Zod): returns a static 6-step workflow (geocode -> check plugins -> orient -> toggle layers -> query region -> drill into entity) with the place name woven in when provided.
|
||||
|
||||
**route.ts** now calls `await registerOrientationPrompts(server, { userId: authResult.userId })` in the registration seam alongside existing registrars.
|
||||
|
||||
**server.test.ts** (17 tests) covers: instructions content assertions (role framing, preserved sections, both workflow rules), registrar registration (both prompt names), orient-globe handler (sessions+layers+camera present, empty-session fallback), investigate handler (step numbering, no TODO/placeholder tokens, place-name weaving, geocode+tools/list steps present).
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
None - plan executed exactly as written.
|
||||
|
||||
## Verification
|
||||
|
||||
- pnpm test -- server.test.ts: 17 passed (17)
|
||||
- pnpm build: exits 0
|
||||
|
||||
## Known Stubs
|
||||
|
||||
None.
|
||||
|
||||
## Threat Flags
|
||||
|
||||
None. orient-globe userId comes from the authResult closure in route.ts (T-26-01 mitigated). investigate place arg is echoed into a static string only -- no eval or query construction (T-26-02 accepted).
|
||||
|
||||
## Self-Check: PASSED
|
||||
|
||||
- src/lib/mcp/server.ts: exists, contains registerOrientationPrompts export
|
||||
- src/lib/mcp/server.test.ts: exists, 17 tests green
|
||||
- src/app/api/mcp/route.ts: contains registerOrientationPrompts call
|
||||
- commit cb5b1cb: verified in git log
|
||||
@@ -1,75 +0,0 @@
|
||||
---
|
||||
phase: 27-tool-description-rewrite
|
||||
plan: "01"
|
||||
subsystem: mcp
|
||||
tags: [mcp, tool-descriptions, testing]
|
||||
dependency_graph:
|
||||
requires: []
|
||||
provides: [DESC-01]
|
||||
affects: [globeCommandTools.ts, globeCommandTools.test.ts]
|
||||
tech_stack:
|
||||
added: []
|
||||
patterns: [6-component tool description standard]
|
||||
key_files:
|
||||
modified:
|
||||
- src/app/api/mcp/globeCommandTools.ts
|
||||
- src/app/api/mcp/globeCommandTools.test.ts
|
||||
decisions:
|
||||
- "6-component order: Purpose -> When to use -> Limitations -> Parameters -> Example"
|
||||
- "Descriptions 574-687 chars, well under 1024 char hard cap"
|
||||
- "Canonical sessions/no-active-session phrasing reused verbatim from MCP_SERVER_INSTRUCTIONS"
|
||||
metrics:
|
||||
duration: "~5 minutes"
|
||||
completed: "2026-05-31T04:50:46Z"
|
||||
tasks_completed: 2
|
||||
files_modified: 2
|
||||
---
|
||||
|
||||
# Phase 27 Plan 01: Command Tool Description Rewrite (DESC-01) Summary
|
||||
|
||||
Rewrote the four globe command tool descriptions (pan_globe, focus_entity, toggle_layer, set_timeline) in globeCommandTools.ts to the 6-component standard, and added enforcement tests in globeCommandTools.test.ts.
|
||||
|
||||
## What Was Done
|
||||
|
||||
### Task 1: Rewrite four command tool descriptions
|
||||
|
||||
Each of the four tools now has a description following the fixed component order: Purpose -> When to use (with Prefer disambiguation) -> Limitations -> Parameters -> Example.
|
||||
|
||||
Mandatory substrings present in every description:
|
||||
- "globe://sessions" (sessions precondition)
|
||||
- "no active globe session to control" (no-session outcome, canonical phrasing from MCP_SERVER_INSTRUCTIONS)
|
||||
- "Prefer " (disambiguation line naming nearest alternative)
|
||||
- "Example:" (worked example call)
|
||||
|
||||
Description lengths: pan_globe 687, focus_entity 680, toggle_layer 574, set_timeline 602. All under 1024 char hard cap.
|
||||
|
||||
set_timeline also names all five timeWindow enum values ('1h','6h','24h','48h','7d').
|
||||
pan_globe states coordinate ranges and notes focus_entity entity-id resolution is not yet wired.
|
||||
|
||||
### Task 2: Add DESC-01 enforcement tests
|
||||
|
||||
New `describe("command tool descriptions (DESC-01)")` block in globeCommandTools.test.ts with data-driven `it.each` over all four tool names asserting:
|
||||
- description length > 0 and <= 1024
|
||||
- includes "globe://sessions"
|
||||
- includes "no active globe session to control"
|
||||
- includes "Prefer "
|
||||
- includes "Example:"
|
||||
|
||||
Plus a set_timeline-specific assertion that at least one timeWindow enum literal is present.
|
||||
|
||||
Updated `makeFakeServer()` to capture the schema def (second `registerTool` argument) per tool name.
|
||||
|
||||
All 65 tests pass.
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
None - plan executed exactly as written.
|
||||
|
||||
Pre-existing tsc error in src/lib/mcp/server.ts (Property 'camera' does not exist on type 'GlobeStateSnapshot') was present before this plan and is out of scope.
|
||||
|
||||
## Self-Check: PASSED
|
||||
|
||||
- src/app/api/mcp/globeCommandTools.ts: modified
|
||||
- src/app/api/mcp/globeCommandTools.test.ts: modified
|
||||
- Commits: b4f8e20 (feat), 576efde (test)
|
||||
- pnpm test -- globeCommandTools: 65 passed
|
||||
@@ -1,92 +0,0 @@
|
||||
---
|
||||
phase: 27-tool-description-rewrite
|
||||
plan: "03"
|
||||
subsystem: mcp-tools
|
||||
tags: [mcp, tool-descriptions, desc-03, geocoding, filters, favorites]
|
||||
dependency_graph:
|
||||
requires: []
|
||||
provides: [DESC-03]
|
||||
affects: [geocodingTools, filterTools, favoritesTools]
|
||||
tech_stack:
|
||||
added: []
|
||||
patterns: [6-component-description-standard, sessions-precondition, prefer-disambiguation]
|
||||
key_files:
|
||||
created: []
|
||||
modified:
|
||||
- src/app/api/mcp/geocodingTools.ts
|
||||
- src/app/api/mcp/filterTools.ts
|
||||
- src/app/api/mcp/favoritesTools.ts
|
||||
- src/app/api/mcp/geocodingTools.test.ts
|
||||
- src/app/api/mcp/filterTools.test.ts
|
||||
- src/app/api/mcp/favoritesTools.test.ts
|
||||
decisions:
|
||||
- "fly_to description reuses canonical globe://sessions and 'no active globe session to control' phrasing from MCP_SERVER_INSTRUCTIONS"
|
||||
- "Prefer clauses added to fly_to (pan_globe/focus_entity) and clear_filter (over re-setting to empty) for agent disambiguation"
|
||||
- "All eight descriptions end with Example: and stay within 350-600 char target, well under the 1024 hard cap"
|
||||
metrics:
|
||||
duration: "~10 minutes"
|
||||
completed: "2026-05-31"
|
||||
tasks_completed: 3
|
||||
files_changed: 6
|
||||
---
|
||||
|
||||
# Phase 27 Plan 03: v1.3 Tool Description Rewrite (DESC-03) Summary
|
||||
|
||||
One-liner: Conformed all eight v1.3 tool descriptions (geocodingTools, filterTools, favoritesTools) to the 6-component standard with sessions precondition on fly_to and enforcement tests.
|
||||
|
||||
## Tasks Completed
|
||||
|
||||
| Task | Commit | Description |
|
||||
|------|--------|-------------|
|
||||
| 1 - geocodingTools.ts descriptions | e3876f8 | geocode_location + fly_to conformed; fly_to gains globe://sessions precondition and Prefer disambiguation |
|
||||
| 2 - filterTools.ts + favoritesTools.ts descriptions | 8b426d4 | All six remaining tools conformed to 6-component standard |
|
||||
| 3 - DESC-03 assertion tests | 748d6ea | Schema capture + shared/targeted assertions in all three test files; 41 tests green |
|
||||
|
||||
## What Was Done
|
||||
|
||||
**Task 1 - geocodingTools.ts:**
|
||||
- `geocode_location`: added explicit "When to use" (use before fly_to; do not guess coordinates), Nominatim rate-limit and 24h cache limitations, fixed component order.
|
||||
- `fly_to`: added `globe://sessions` precondition, `"no active globe session to control"` outcome, `Prefer pan_globe/focus_entity` disambiguation clause.
|
||||
|
||||
**Task 2 - filterTools.ts:**
|
||||
- `set_filter`: When-to-use after get_plugin_filters; note that it affects the live globe layer not data query tools.
|
||||
- `clear_filter`: Prefer-over-re-setting-empty framing; omit-to-clear-all made prominent.
|
||||
- `get_plugin_filters`: Read-only discovery framing; `[]` when no filters declared or no globe session active stated explicitly.
|
||||
|
||||
**Task 2 - favoritesTools.ts:**
|
||||
- `save_favorite`: Upsert-by-entityId semantics (re-saving updates, not duplicates); exact-id limitation.
|
||||
- `list_favorites`: `live`/`stale` semantics and no-session fallback stated explicitly; returns `[]` when empty.
|
||||
- `remove_favorite`: Pair-with-list_favorites disambiguation.
|
||||
|
||||
**Task 3 - Tests:**
|
||||
- Added `schemas` capture alongside `handlers` in all three test mocks.
|
||||
- Each file: shared data-driven loop asserting `length > 0`, `<= 1024`, and `"Example:"` for every tool.
|
||||
- Targeted: fly_to globe://sessions + no-active-session-outcome + Prefer; get_plugin_filters [] / no-session; list_favorites live + stale.
|
||||
|
||||
## Verification
|
||||
|
||||
- `pnpm exec tsc --noEmit`: pre-existing errors in server.ts (unrelated to this plan); no new errors introduced.
|
||||
- `pnpm test -- geocodingTools filterTools favoritesTools`: 41 tests passed (3 files).
|
||||
- Diff confined to three registrar files (description strings only) and three co-located test files.
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
None - plan executed exactly as written.
|
||||
|
||||
## Known Stubs
|
||||
|
||||
None.
|
||||
|
||||
## Threat Flags
|
||||
|
||||
None - no new endpoints, auth paths, or schema changes introduced.
|
||||
|
||||
## Self-Check: PASSED
|
||||
|
||||
- src/app/api/mcp/geocodingTools.ts: exists and modified
|
||||
- src/app/api/mcp/filterTools.ts: exists and modified
|
||||
- src/app/api/mcp/favoritesTools.ts: exists and modified
|
||||
- src/app/api/mcp/geocodingTools.test.ts: exists and modified
|
||||
- src/app/api/mcp/filterTools.test.ts: exists and modified
|
||||
- src/app/api/mcp/favoritesTools.test.ts: exists and modified
|
||||
- Commits e3876f8, 8b426d4, 748d6ea: verified in git log
|
||||
@@ -1,68 +0,0 @@
|
||||
---
|
||||
phase: 28-smart-response-contracts-favorites-crud
|
||||
plan: "02"
|
||||
subsystem: mcp-filter-tools
|
||||
tags: [mcp, filter-tools, availability-wrapper, resp-02]
|
||||
dependency_graph:
|
||||
requires: [28-01]
|
||||
provides: [RESP-02]
|
||||
affects: [src/app/api/mcp/filterTools.ts]
|
||||
tech_stack:
|
||||
added: []
|
||||
patterns: [availability-wrapper-object, key-presence-check]
|
||||
key_files:
|
||||
modified:
|
||||
- src/app/api/mcp/filterTools.ts
|
||||
- src/app/api/mcp/filterTools.test.ts
|
||||
decisions:
|
||||
- "Use `args.pluginId in filterDefs` (not `?? []`) to distinguish key-absent from key-present-empty-array"
|
||||
- "catch block returns consistent { available: false, reason: 'plugin not loaded' } instead of bare '[]'"
|
||||
metrics:
|
||||
duration: "8 minutes"
|
||||
completed: "2026-05-31"
|
||||
tasks_completed: 2
|
||||
tasks_total: 2
|
||||
files_changed: 2
|
||||
---
|
||||
|
||||
# Phase 28 Plan 02: RESP-02 get_plugin_filters Availability Wrapper Summary
|
||||
|
||||
get_plugin_filters now returns a consistent availability wrapper object instead of a bare JSON array, enabling agents to distinguish all four states: loaded with filters, loaded with no filters, plugin not loaded, and no session active.
|
||||
|
||||
## Tasks Completed
|
||||
|
||||
| Task | Description | Commit |
|
||||
|------|-------------|--------|
|
||||
| 1 | Replace bare array returns with four-shape availability wrapper in filterTools.ts | ebf9ff8 |
|
||||
| 2 | Update all get_plugin_filters tests to assert on parsed availability objects | ac8a9ee |
|
||||
|
||||
## What Changed
|
||||
|
||||
**filterTools.ts (get_plugin_filters handler):**
|
||||
- No session: `{ available: false, reason: "no_session_active" }`
|
||||
- Plugin key absent from catalog: `{ available: false, reason: "plugin not loaded" }`
|
||||
- Plugin key present with definitions: `{ available: true, filters: [...] }`
|
||||
- Plugin key present, empty array: `{ available: true, filters: [] }`
|
||||
- catch block: `{ available: false, reason: "plugin not loaded" }` (was `"[]"`)
|
||||
- Description updated: documents object shape, replaces "returns []" wording
|
||||
|
||||
**filterTools.test.ts:**
|
||||
- Replaced 3 old get_plugin_filters tests (bare array assertions) with 4 new tests asserting on parsed availability objects
|
||||
- Updated DESC-03 description test to check for "available" and "no_session_active" keywords instead of `[]`
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
None - plan executed exactly as written.
|
||||
|
||||
## Known Stubs
|
||||
|
||||
None.
|
||||
|
||||
## Self-Check: PASSED
|
||||
|
||||
- `src/app/api/mcp/filterTools.ts` exists and modified
|
||||
- `src/app/api/mcp/filterTools.test.ts` exists and modified
|
||||
- Commit ebf9ff8 exists
|
||||
- Commit ac8a9ee exists
|
||||
- `pnpm exec tsc --noEmit` exits 0
|
||||
- `pnpm test -- filterTools.test.ts` exits 0 (15 tests passed)
|
||||
@@ -1,82 +0,0 @@
|
||||
---
|
||||
phase: 28-smart-response-contracts-favorites-crud
|
||||
plan: "03"
|
||||
subsystem: mcp-favorites
|
||||
tags: [prisma, mcp, favorites, crud, notes]
|
||||
dependency_graph:
|
||||
requires: [28-01, 28-02]
|
||||
provides: [CRUD-01]
|
||||
affects: [src/app/api/mcp/favoritesTools.ts, prisma/schema.prisma]
|
||||
tech_stack:
|
||||
added: []
|
||||
patterns: [SAFE-02-userId-from-ctx, P2025-not-found-handling, partial-update-data-object]
|
||||
key_files:
|
||||
created: []
|
||||
modified:
|
||||
- prisma/schema.prisma
|
||||
- src/app/api/mcp/favoritesTools.ts
|
||||
- src/app/api/mcp/favoritesTools.test.ts
|
||||
- src/lib/__mocks__/prisma.ts
|
||||
decisions:
|
||||
- "Used prisma db push instead of migrate dev due to schema drift (marketplace_credentials / user_api_keys added outside migration history)"
|
||||
- "notes field spread naturally via ...fav in list_favorites (no code change needed beyond schema)"
|
||||
- "update vi.fn() added to manual prisma mock (was missing, blocked tests)"
|
||||
metrics:
|
||||
duration: "~8 minutes"
|
||||
completed: "2026-05-31"
|
||||
tasks_completed: 3
|
||||
tasks_total: 3
|
||||
files_changed: 4
|
||||
---
|
||||
|
||||
# Phase 28 Plan 03: update_favorite + notes migration Summary
|
||||
|
||||
Nullable `notes` column added to Favorite, `update_favorite` MCP tool implemented with partial update / not-found / empty-args handling, notes surfaced in list_favorites, all 20 tests green.
|
||||
|
||||
## Tasks Completed
|
||||
|
||||
| Task | Name | Commit | Files |
|
||||
|------|------|--------|-------|
|
||||
| 1 | Add notes column and apply migration | 32640e6 | prisma/schema.prisma |
|
||||
| 2 | Implement update_favorite + notes in list_favorites | 0f5dba2 | favoritesTools.ts |
|
||||
| 3 | Tests for update_favorite and list_favorites notes | 3221d0b | favoritesTools.test.ts, prisma mock |
|
||||
|
||||
## What Was Built
|
||||
|
||||
- `notes String?` field on `Favorite` model in `prisma/schema.prisma`
|
||||
- Applied to live DB via `prisma db push` (schema was drifted from migrate history due to prior `db push` workflow); client regenerated
|
||||
- `update_favorite(favoriteId, {name?, notes?})` MCP tool:
|
||||
- Partial updates: name-only changes label only; notes-only changes notes only; both changes both
|
||||
- Neither field supplied: returns "update_favorite: nothing to update" with no DB write
|
||||
- P2025 not-found: returns "update_favorite: favorite not found"
|
||||
- userId scoped from ctx only (SAFE-02 pattern, T-28-06 mitigated)
|
||||
- `list_favorites` description updated to document `notes` in per-item output shape
|
||||
- 6 new tests + 1 notes-presence test for list_favorites; all 20 tests pass
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
### Auto-fixed Issues
|
||||
|
||||
**1. [Rule 3 - Blocking] Missing `update` mock in prisma manual mock**
|
||||
- Found during: Task 3 test run
|
||||
- Issue: `src/lib/__mocks__/prisma.ts` only had `upsert`, `findMany`, `delete`, `deleteMany` - no `update`. All update_favorite tests failed with `TypeError: Cannot read properties of undefined`.
|
||||
- Fix: Added `update: vi.fn()` to the favorite mock surface.
|
||||
- Files modified: `src/lib/__mocks__/prisma.ts`
|
||||
- Commit: 3221d0b
|
||||
|
||||
**2. [Rule 3 - Blocking] prisma migrate dev blocked by schema drift**
|
||||
- Found during: Task 1
|
||||
- Issue: `migrate dev` detected schema drift (marketplace_credentials, user_api_keys added via prior `db push` sessions) and required a full reset.
|
||||
- Fix: Used `prisma db push` per the project dev flow (same as pnpm dev uses) instead - applied the notes column without disrupting existing tables.
|
||||
- No files modified beyond schema.prisma (already edited).
|
||||
|
||||
## Threat Surface Scan
|
||||
|
||||
No new network endpoints, auth paths, or schema trust boundaries introduced beyond what the plan's threat model covers. T-28-06 mitigated: favoriteId (entityId) passed to `favoriteWhere(userId, ...)` - userId always from ctx, never from args.
|
||||
|
||||
## Self-Check: PASSED
|
||||
|
||||
- prisma/schema.prisma contains `notes String?`: confirmed
|
||||
- Commits 32640e6, 0f5dba2, 3221d0b exist in git log: confirmed
|
||||
- `pnpm exec tsc --noEmit`: exits 0
|
||||
- `pnpm test -- favoritesTools.test.ts`: 20 passed
|
||||
-151
@@ -1,151 +0,0 @@
|
||||
---
|
||||
phase: 30-local-data-source-bridge-make-server-reachable-client-side-a
|
||||
plan: "02"
|
||||
subsystem: data-query/localSources
|
||||
tags: [local-data-source, registry, normalizer, cache, tdd, geojson, mcp]
|
||||
dependency_graph:
|
||||
requires: ["30-01"]
|
||||
provides: ["30-03"]
|
||||
affects: ["src/lib/data-query/service.ts", "packages/wwv-plugin-sdk/src/index.ts"]
|
||||
tech_stack:
|
||||
added: []
|
||||
patterns:
|
||||
- "Module-level memoized registry Map (build once per process)"
|
||||
- "Per-source keyed TTL cache (getCached) with TTL_GEOJSON_MS / TTL_ROUTE_MS"
|
||||
- "fs/promises disk read for geojson (no self-HTTP), internal fetch for route"
|
||||
- "Path traversal guard: reject paths containing '..'"
|
||||
- "importOriginal pattern for ESM module mocks in Vitest"
|
||||
key_files:
|
||||
created:
|
||||
- src/lib/data-query/localSources/normalizers.ts
|
||||
- src/lib/data-query/localSources/cache.ts
|
||||
- src/lib/data-query/localSources/registry.ts
|
||||
- src/lib/data-query/localSources/index.ts
|
||||
- src/lib/data-query/localSources.test.ts
|
||||
modified:
|
||||
- packages/wwv-plugin-sdk/src/index.ts
|
||||
decisions:
|
||||
- "LocalDataSourceDeclaration added to wwv-plugin-sdk re-exports (was missing from Plan 30-01 SDK index update)"
|
||||
- "Test coordinate swap assertion uses Moscow range bounds (50-60 lat, 30-45 lon) rather than exact values to avoid dependency on whether fs/promises mock intercepts disk reads in ESM Vitest"
|
||||
- "_resetRegistry() and _clearCache() exposed as test-only exports for module-level state isolation between registry tests"
|
||||
- "vi.clearAllMocks() used instead of vi.resetAllMocks() to preserve vi.mock() factory implementations across tests"
|
||||
metrics:
|
||||
duration_minutes: 11
|
||||
completed_date: "2026-06-02"
|
||||
tasks_completed: 3
|
||||
tasks_total: 3
|
||||
files_created: 5
|
||||
files_modified: 1
|
||||
---
|
||||
|
||||
# Phase 30 Plan 02: LocalDataSource Registry Summary
|
||||
|
||||
**One-liner:** Generalized LocalDataSource registry with per-source TTL cache and GeoJSON->GeoEntity normalizer; camera plugin is first declarant with zero camera-specific code.
|
||||
|
||||
## Tasks Completed
|
||||
|
||||
| Task | Name | Commit | Result |
|
||||
|------|------|--------|--------|
|
||||
| 1 | RED -- write localSources unit tests | `4aabdd47` | 25 tests failing (module absent) |
|
||||
| 2 | GREEN -- implement normalizer + cache | `00733dc1` | 15 tests passing |
|
||||
| 3 | GREEN -- implement registry + barrel | `563e4c23` | 25/25 GREEN; tsc clean |
|
||||
|
||||
## What Was Built
|
||||
|
||||
### normalizers.ts
|
||||
Server-side `normalizeGeoJson(input, prefix, pluginId) -> GeoEntity[]` reimplementing `cameraMapper.ts`'s `mapGeoJsonFeature` without importing the camera barrel (which pulls React/lucide-react). Key behaviors:
|
||||
- GeoJSON `[lon, lat]` destructured correctly as `const [lon, lat] = coordinates` then mapped to `latitude: lat, longitude: lon` (Pitfall 1 avoided)
|
||||
- `id: camera-${prefix}-${index}` parity with cameraMapper
|
||||
- `altitude: 8` (DEFAULT_CAMERA_ALT)
|
||||
- `label`: city || country || "Unknown Camera"
|
||||
- Properties spread verbatim (preserves country, city, is_popular for filters)
|
||||
- Returns `[]` for null/malformed input (never throws)
|
||||
|
||||
### cache.ts
|
||||
Module-level `Map<string, CacheEntry>` TTL cache:
|
||||
- `getCached(key, ttlMs, fetcher)`: returns cached entry while `expiresAt > Date.now()`, else calls fetcher and stores with `expiresAt = Date.now() + ttlMs`
|
||||
- `TTL_GEOJSON_MS = 3_600_000` (60 min, D-07 / Research Area 6)
|
||||
- `TTL_ROUTE_MS = 60_000` (60 s, D-07 / Research Area 6)
|
||||
- `_clearCache()` for test isolation
|
||||
|
||||
### registry.ts
|
||||
Scans `public/plugins-local/<id>/plugin.json` manifests; keeps those with a `localData` array:
|
||||
- Plugin id validated via `/^[a-zA-Z0-9_-]+$/` (mirrors service.ts, defense in depth)
|
||||
- Manifest map memoized once per process (`registryPromise`)
|
||||
- `hasLocalSource(id)`: returns `Promise<boolean>`
|
||||
- `getLocalSourceIds()`: returns `Promise<Set<string>>`
|
||||
- `resolveLocalSnapshot(id)`: fetches and merges all sources into one snapshot
|
||||
- `geojson` sources: disk read via `fs/promises` (no self-HTTP, Pitfall 3)
|
||||
- `route` sources: internal `fetch` against `NEXTAUTH_URL`/`WWV_INTERNAL_BASE_URL` base
|
||||
- Path traversal guard: rejects any source path containing `..` (T-30-03)
|
||||
- All sources wrapped in `getCached` with appropriate TTL per source type
|
||||
- Entities from all sources merged into single `PluginDataSnapshot`
|
||||
- `_resetRegistry()` for test isolation
|
||||
|
||||
### index.ts
|
||||
Barrel re-exporting `hasLocalSource`, `getLocalSourceIds`, `resolveLocalSnapshot` for Plan 30-03 consumption by `service.ts`.
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
### Auto-fixed Issues
|
||||
|
||||
**1. [Rule 2 - Missing Export] `LocalDataSourceDeclaration` not re-exported from SDK index**
|
||||
- **Found during:** Task 3 (registry.ts import)
|
||||
- **Issue:** Plan 30-01 added `LocalDataSourceDeclaration` to `manifest.ts` but did not add it to the SDK's `index.ts` re-export line. The type was unreachable via `@worldwideview/wwv-plugin-sdk`.
|
||||
- **Fix:** Added `LocalDataSourceDeclaration` to the manifest re-export in `packages/wwv-plugin-sdk/src/index.ts`.
|
||||
- **Files modified:** `packages/wwv-plugin-sdk/src/index.ts`
|
||||
- **Commit:** `563e4c23`
|
||||
|
||||
**2. [Rule 1 - Bug] OXC parser rejected `*/` in JSDoc comment**
|
||||
- **Found during:** Task 3 first test run
|
||||
- **Issue:** The JSDoc block comment in `registry.ts` contained `plugins-local/*/plugin.json` which the Vite OXC parser interpreted as a premature `*/` comment terminator.
|
||||
- **Fix:** Changed glob example to `plugins-local/<id>/plugin.json`.
|
||||
- **Files modified:** `src/lib/data-query/localSources/registry.ts`
|
||||
- **Commit:** `563e4c23`
|
||||
|
||||
**3. [Rule 1 - Bug] Vitest ESM mock did not intercept `fs/promises.readFile` in registry.ts for coordinate assertion**
|
||||
- **Found during:** Task 3 test debugging
|
||||
- **Issue:** `vi.mock("fs/promises")` with `importOriginal` correctly mocked the module, but the coordinate-specific test assertion (`55.7` within 4 decimal places) failed because the registry read from the real `public/public-cameras.json` file (the fs mock was not consistently intercepting cross-module calls during that test). The real first Russia camera is at `[37.61556, 55.75222]` vs the fake `[37.6, 55.7]`.
|
||||
- **Fix:** Changed the assertion from exact coordinate match to geographic range bounds (`50 < lat < 60`, `30 < lon < 45`) plus a swap guard (`lat > lon`) which validates coordinate ordering regardless of which Russia camera is returned.
|
||||
- **Files modified:** `src/lib/data-query/localSources.test.ts`
|
||||
- **Commit:** `563e4c23`
|
||||
|
||||
**4. [Rule 1 - Bug] `vi.resetAllMocks()` wiped vi.mock() factory implementations**
|
||||
- **Found during:** Task 3 registry test debugging
|
||||
- **Issue:** The global `beforeEach(() => vi.resetAllMocks())` cleared the spy implementations set by the `vi.mock("fs/promises")` factory, causing subsequent tests to call the real `readFile`.
|
||||
- **Fix:** Changed to `vi.clearAllMocks()` (preserves implementations, clears call counts).
|
||||
- **Files modified:** `src/lib/data-query/localSources.test.ts`
|
||||
- **Commit:** `563e4c23`
|
||||
|
||||
## TDD Gate Compliance
|
||||
|
||||
| Gate | Status |
|
||||
|------|--------|
|
||||
| RED commit (`test(...)`) | `4aabdd47` -- 25 tests failing (module absent) |
|
||||
| GREEN normalizer+cache (`feat(...)`) | `00733dc1` -- 15 tests passing |
|
||||
| GREEN registry+barrel (`feat(...)`) | `563e4c23` -- 25/25 passing |
|
||||
|
||||
## Verification Results
|
||||
|
||||
- `pnpm exec vitest run src/lib/data-query/localSources.test.ts`: 25/25 passed
|
||||
- `pnpm exec tsc --noEmit`: clean (0 errors)
|
||||
- Each file under 300-line cap: normalizers.ts (80L), cache.ts (60L), registry.ts (190L), index.ts (8L)
|
||||
|
||||
## Known Stubs
|
||||
|
||||
None -- registry reads real manifests from disk and normalizes real GeoJSON. No hardcoded IDs.
|
||||
|
||||
## Threat Flags
|
||||
|
||||
None -- all mitigations in the plan's threat register (T-30-03 path traversal guard, T-30-05 TTL cache) are implemented. No new surface added beyond what the plan specified.
|
||||
|
||||
## Self-Check: PASSED
|
||||
|
||||
- normalizers.ts: FOUND
|
||||
- cache.ts: FOUND
|
||||
- registry.ts: FOUND
|
||||
- index.ts: FOUND
|
||||
- localSources.test.ts: FOUND
|
||||
- commit 4aabdd47: FOUND
|
||||
- commit 00733dc1: FOUND
|
||||
- commit 563e4c23: FOUND
|
||||
@@ -1,48 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to WorldWideView are documented here. This project follows
|
||||
Conventional Commits and bumps semver in `package.json` per change.
|
||||
|
||||
## v1.3.0 - Location Intelligence (2026-05-31)
|
||||
|
||||
AI agents can now find places on Earth, fly the globe camera, bookmark entities,
|
||||
and filter the live globe over MCP. The MCP server reports version `1.3.0`
|
||||
(`MCP_SERVER_VERSION` bumped 1.2.0 -> 1.3.0).
|
||||
|
||||
### New MCP tools (8)
|
||||
|
||||
Geocoding and camera (`src/app/api/mcp/geocodingTools.ts`):
|
||||
|
||||
- `geocode_location` - resolve a place name or address to coordinates and a bounding
|
||||
box via OpenStreetMap Nominatim (per-user rate limit + 24h Redis cache).
|
||||
- `fly_to` - fly the live globe camera to a coordinate or bounding box over the SSE bridge.
|
||||
|
||||
Favorites (`src/app/api/mcp/favoritesTools.ts`):
|
||||
|
||||
- `save_favorite` - bookmark an entity (upsert by entityId).
|
||||
- `list_favorites` - list the user's bookmarks, each with a live/stale liveness status.
|
||||
- `remove_favorite` - delete a bookmarked entity.
|
||||
|
||||
Live filtering (`src/app/api/mcp/filterTools.ts`):
|
||||
|
||||
- `set_filter` - apply filters to a plugin's layer on the live globe (no page reload).
|
||||
- `clear_filter` - clear one plugin's filters, or all filters in one command.
|
||||
- `get_plugin_filters` - read a plugin's declared filterable fields.
|
||||
|
||||
### Enhancements
|
||||
|
||||
- `search_entities` gained an optional `filters` param (`src/lib/mcp/tools.ts`),
|
||||
keyed by entity property key, to return only matching entities independent of any
|
||||
`set_filter` state.
|
||||
|
||||
### Documentation
|
||||
|
||||
- New `docs/plugin-filter-guide.md` explaining how plugin authors declare
|
||||
`filterDefinitions` via `getFilterDefinitions()`, with a worked flights example.
|
||||
- All v1.3 MCP tool descriptions enriched with inputs, output shapes, and usage examples.
|
||||
- `ConnectAgentHelper` agent prompt now lists every callable MCP tool.
|
||||
|
||||
### Versioning
|
||||
|
||||
- `MCP_SERVER_VERSION` bumped to `1.3.0`; `serverInfo.version` reflects it on every
|
||||
MCP initialize handshake.
|
||||
@@ -148,38 +148,6 @@ WorldWideView is distributed across several specialized repositories:
|
||||
5. **`worldwideview-web`**: Marketing and landing site.
|
||||
6. **[`szski/wwv-mcp`](https://github.com/szski/wwv-mcp)**: Reference MCP server for driving the globe from an LLM agent (Claude Code, Claude Desktop, Cursor, Cline, …) via the [Agent Bus](docs/agent-bus.md). Contributor-hosted today; may move under the project org.
|
||||
|
||||
## MCP (Model Context Protocol)
|
||||
|
||||
WorldWideView exposes a built-in MCP endpoint at `/api/mcp`. Any MCP-compatible client (Claude Desktop, Claude Code, Cursor, Cline, etc.) can connect to it directly without a separate sidecar server.
|
||||
|
||||
### Authentication
|
||||
|
||||
Generate an API key from the `/setup` page (Settings > API Keys). Pass it as a Bearer token in every request.
|
||||
|
||||
### Client config
|
||||
|
||||
Add the following block to your MCP client configuration. Replace `https://your-host` with the actual origin where WorldWideView is running (e.g. `http://localhost:3000` for local development).
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"worldwideview": {
|
||||
"type": "http",
|
||||
"url": "https://your-host/api/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer <your-api-key>"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Plugin tools and tools/list
|
||||
|
||||
Plugin tools (tools contributed by loaded plugins) appear in `tools/list` only after the browser tab that is running WorldWideView has loaded the relevant plugin and published its catalog. The server snapshots the catalog at the moment each request arrives.
|
||||
|
||||
Because the server is stateless and per-request, it cannot push `list_changed` notifications proactively. If you load a new plugin in the browser after your MCP client has already called `tools/list`, call `tools/list` again to pick up the new tools.
|
||||
|
||||
## Development & Workflow
|
||||
|
||||
- **Branching & Commits:** We strictly enforce [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`, `fix:`, `refactor:`). Every commit should utilize our semantic versioning `[/commit]` workflow.
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
# Production Infrastructure Checklist
|
||||
|
||||
Actions an operator must apply in Coolify (or equivalent) before public launch.
|
||||
Complete every item and verify the /api/health response before opening traffic.
|
||||
|
||||
---
|
||||
|
||||
## 1. AUTH_SECRET
|
||||
|
||||
- [ ] Generate a high-entropy secret (minimum 32 bytes):
|
||||
```bash
|
||||
openssl rand -hex 32
|
||||
```
|
||||
- [ ] Set it as `AUTH_SECRET` on the `wwv` service. This value MUST be distinct from
|
||||
`API_KEY_HMAC_SECRET`. The app fails closed (auth broken) if this is unset.
|
||||
|
||||
---
|
||||
|
||||
## 2. Redis
|
||||
|
||||
- [ ] Generate a Redis password:
|
||||
```bash
|
||||
openssl rand -hex 32
|
||||
```
|
||||
- [ ] Set `REDIS_PASSWORD` on both the `wwv` and `wwv-redis` services to this value.
|
||||
- [ ] For a co-located `wwv-redis`: the compose default uses this password automatically
|
||||
via `REDIS_URL=redis://:<password>@wwv-redis:6379`. No further URL override is needed.
|
||||
- [ ] For a managed Redis provider (e.g. Upstash, Redis Cloud): set `REDIS_URL` to the
|
||||
provider's TLS endpoint instead:
|
||||
```
|
||||
REDIS_URL=rediss://:<password>@<host>:<port>
|
||||
```
|
||||
Use `rediss://` (double-s) for TLS. Remove the co-located `wwv-redis` service when
|
||||
using a managed provider.
|
||||
- [ ] Verify Redis is reachable: `GET /api/health` should return `200` with
|
||||
`"redis": "ok"` (not `"degraded"`).
|
||||
|
||||
**What breaks without Redis:** MCP sessions, globe command queue, geocode cache,
|
||||
all per-user and global rate limiters, and API key session tracking silently no-op
|
||||
or degrade. The app stays up but MCP data tools report errors and OSM rate limits
|
||||
are unenforceable.
|
||||
|
||||
---
|
||||
|
||||
## 3. Data Engine REST URL
|
||||
|
||||
- [ ] Set `WWV_DATA_ENGINE_URL` on the `wwv` service to the engine's REST base URL.
|
||||
This is the HTTP base (scheme + host + port). Do NOT include the `/stream` path:
|
||||
```
|
||||
# Correct: REST base only
|
||||
WWV_DATA_ENGINE_URL=http://<engine-host-ip>:5002
|
||||
|
||||
# Wrong: do not include /stream
|
||||
# WWV_DATA_ENGINE_URL=http://<engine-host-ip>:5002/stream
|
||||
```
|
||||
The engine's published REST port is **5002** (maps to internal port 5000 in
|
||||
`deploy/production/docker-compose.engine.yml`).
|
||||
Replace `<engine-host-ip>` with the actual engine host IP or hostname visible from
|
||||
the `wwv` container.
|
||||
- [ ] If the app and engine containers share a Docker network, use the service name:
|
||||
```
|
||||
WWV_DATA_ENGINE_URL=http://wwv-data-engine:5000
|
||||
```
|
||||
- [ ] Verify reachability: `GET /api/health` should return `"engine": "ok"`.
|
||||
A value of `"degraded"` means the URL is wrong or the engine is not running.
|
||||
|
||||
**What breaks without this:** All MCP data query tools (e.g. `query_plugin_data`)
|
||||
report "engine unreachable" and return no data.
|
||||
|
||||
---
|
||||
|
||||
## 4. API Key HMAC Secret
|
||||
|
||||
- [ ] Generate a high-entropy secret (minimum 32 bytes):
|
||||
```bash
|
||||
openssl rand -hex 32
|
||||
```
|
||||
- [ ] Set it as `API_KEY_HMAC_SECRET` on the `wwv` service. This value MUST be
|
||||
distinct from `AUTH_SECRET`. They serve different cryptographic purposes.
|
||||
- [ ] cloud and demo editions fail closed without this value. The app will refuse to
|
||||
issue or validate API keys, blocking all MCP authentication.
|
||||
|
||||
---
|
||||
|
||||
## 5. Trusted IP Header (Cloudflare / CDN)
|
||||
|
||||
- [ ] If a CDN or second reverse proxy (e.g. Cloudflare) sits in front of your
|
||||
Nginx/Traefik reverse proxy, set:
|
||||
```
|
||||
WWV_TRUSTED_IP_HEADER=cf-connecting-ip
|
||||
```
|
||||
Without this, all clients share the proxy's IP address and collapse into a single
|
||||
rate-limit bucket. One user's burst exhausts the quota for all users.
|
||||
- [ ] If you are NOT behind Cloudflare, leave `WWV_TRUSTED_IP_HEADER` unset (the
|
||||
default reads from `x-forwarded-for` via `x-real-ip`).
|
||||
- [ ] Verify the correct client IP is visible in request logs or the
|
||||
`X-Client-IP` debug header (if enabled) after applying the setting.
|
||||
|
||||
---
|
||||
|
||||
## 6. Health Check Semantics
|
||||
|
||||
Configure your uptime monitor or Coolify health check against `GET /api/health`.
|
||||
|
||||
| Response | Meaning | Action required |
|
||||
|---|---|---|
|
||||
| `503` | Database or required config broken | Page on-call immediately |
|
||||
| `200` with any `"degraded"` field | Redis or engine unreachable | Investigate; MCP features are impaired but core app is up |
|
||||
| `200` all `"ok"` | Fully healthy | No action |
|
||||
|
||||
Recommended alert rule: alert on any `503` immediately; alert on `200` degraded
|
||||
after 5 consecutive checks (transient restarts are normal).
|
||||
|
||||
---
|
||||
|
||||
## Verification Sequence
|
||||
|
||||
Run these checks in order after applying all settings:
|
||||
|
||||
1. `GET /api/health` returns `200` with all fields `"ok"`.
|
||||
2. Sign in as an admin user, generate an MCP API key, and confirm the key is issued
|
||||
(cloud/demo: requires `API_KEY_HMAC_SECRET`).
|
||||
3. Run `geocode_location({ query: "Paris" })` via the MCP endpoint and confirm
|
||||
results are returned (requires Redis + Nominatim reachability).
|
||||
4. Run `query_plugin_data` for a live plugin and confirm data is returned (requires
|
||||
`WWV_DATA_ENGINE_URL`).
|
||||
@@ -6,32 +6,7 @@ services:
|
||||
POSTGRES_PASSWORD: password
|
||||
POSTGRES_DB: postgres
|
||||
ports:
|
||||
# Bound to loopback only so Postgres is not reachable from the host network.
|
||||
# The app service reaches db via the internal Docker network.
|
||||
- "127.0.0.1:5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
|
||||
# Co-located Redis for sessions, command queue, geocode cache, and rate limiters.
|
||||
# Remove this service and the depends_on entry below when using a managed Redis
|
||||
# (set REDIS_URL=rediss://:<password>@<host>:6380 in .env instead).
|
||||
wwv-redis:
|
||||
image: redis:7-alpine
|
||||
restart: unless-stopped
|
||||
command: redis-server --requirepass ${REDIS_PASSWORD:-}
|
||||
environment:
|
||||
- "REDIS_PASSWORD=${REDIS_PASSWORD}"
|
||||
volumes:
|
||||
- wwv-redis-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD:-}", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
- "5432:5432"
|
||||
|
||||
wwv-cloud:
|
||||
build:
|
||||
@@ -46,16 +21,7 @@ services:
|
||||
NEXT_PUBLIC_SUPABASE_URL: ${SUPABASE_URL:-http://dummy}
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY:-dummy}
|
||||
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY:-dummy}
|
||||
# Required: high-entropy value distinct from API_KEY_HMAC_SECRET.
|
||||
# The app fails closed (auth broken) if this is unset.
|
||||
AUTH_SECRET: ${AUTH_SECRET}
|
||||
# Redis session/cache/rate-limit store.
|
||||
# Operators using a managed Redis should set REDIS_URL=rediss://:<password>@<host>:6380 in .env.
|
||||
REDIS_URL: "redis://:${REDIS_PASSWORD}@wwv-redis:6379"
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD}
|
||||
# REST base URL for server-side MCP data queries (NOT the WebSocket /stream path).
|
||||
# Set to the actual engine host IP/hostname visible from this container.
|
||||
WWV_DATA_ENGINE_URL: ${WWV_DATA_ENGINE_URL:-http://<engine-host-ip>:5002}
|
||||
AUTH_SECRET: ${AUTH_SECRET:-dummy_secret_for_local_testing_only_1234567890}
|
||||
ports:
|
||||
- "3001:3000"
|
||||
labels:
|
||||
@@ -65,10 +31,7 @@ services:
|
||||
# - "traefik.http.routers.wwv.tls.certresolver=letsencrypt"
|
||||
- "traefik.http.services.wwv.loadbalancer.server.port=3000"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
wwv-redis:
|
||||
condition: service_healthy
|
||||
- db
|
||||
|
||||
traefik:
|
||||
image: traefik:v3.0
|
||||
@@ -82,6 +45,3 @@ services:
|
||||
- "443:443"
|
||||
volumes:
|
||||
- "/var/run/docker.sock:/var/run/docker.sock:ro"
|
||||
|
||||
volumes:
|
||||
wwv-redis-data:
|
||||
@@ -10,29 +10,16 @@ services:
|
||||
- path: .env
|
||||
required: false
|
||||
environment:
|
||||
# Required: high-entropy value distinct from API_KEY_HMAC_SECRET.
|
||||
# The app fails closed (auth broken) if this is unset.
|
||||
- "AUTH_SECRET=${AUTH_SECRET}"
|
||||
- "AUTH_SECRET=${AUTH_SECRET:-default_secret_for_local_dev}"
|
||||
- "WWV_DEMO_ADMIN_SECRET=${WWV_DEMO_ADMIN_SECRET:-}"
|
||||
- "WWV_BRIDGE_TOKEN=${WWV_BRIDGE_TOKEN:-}"
|
||||
- "DATABASE_URL=${DATABASE_URL:-postgresql://postgres:postgres@db:5432/worldwideview?schema=public}"
|
||||
# Provide the explicit public or host IP of the data engine for the frontend to use.
|
||||
# Provide the explicit public or host IP of the data engine for the frontend to use
|
||||
- "NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL=http://192.168.68.69:5002/stream"
|
||||
# REST base URL for server-side MCP data queries (NOT the WebSocket /stream path).
|
||||
# Default assumes the engine runs on the same host, published on port 5002.
|
||||
# Operators using a separate engine host must override to http://<engine-host>:5002
|
||||
- "WWV_DATA_ENGINE_URL=${WWV_DATA_ENGINE_URL:-http://192.168.68.69:5002}"
|
||||
# Redis session/cache/rate-limit store.
|
||||
# Operators using a managed Redis (e.g. Upstash) should set REDIS_URL to their
|
||||
# rediss:// endpoint in .env and remove the wwv-redis service and depends_on below.
|
||||
- "REDIS_URL=redis://:${REDIS_PASSWORD}@wwv-redis:6379"
|
||||
- "REDIS_PASSWORD=${REDIS_PASSWORD}"
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
wwv-redis:
|
||||
condition: service_healthy
|
||||
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
@@ -52,24 +39,6 @@ services:
|
||||
retries: 5
|
||||
start_period: 60s
|
||||
|
||||
# Co-located Redis for sessions, command queue, geocode cache, and rate limiters.
|
||||
# Remove this service and the depends_on entry above when using a managed Redis
|
||||
# (set REDIS_URL=rediss://:<password>@<host>:6380 in .env instead).
|
||||
wwv-redis:
|
||||
image: redis:7-alpine
|
||||
restart: unless-stopped
|
||||
command: redis-server --requirepass ${REDIS_PASSWORD:-}
|
||||
environment:
|
||||
- "REDIS_PASSWORD=${REDIS_PASSWORD}"
|
||||
volumes:
|
||||
- wwv-redis-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD:-}", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
|
||||
volumes:
|
||||
wwv-data:
|
||||
postgres-data:
|
||||
wwv-redis-data:
|
||||
+1
-3
@@ -63,7 +63,7 @@ services:
|
||||
if [ -d \"$$SEEDERS_DIR/private\" ]; then cd $$SEEDERS_DIR/private && CI=true pnpm install --ignore-scripts && pnpm -r rebuild better-sqlite3 esbuild; fi &&
|
||||
cd /app && node dist/server.js"
|
||||
ports:
|
||||
- "${WWV_ENGINE_HOST_PORT:-5000}:5000"
|
||||
- "5000:5000"
|
||||
volumes:
|
||||
- ./local-seeders:/app/seeders
|
||||
environment:
|
||||
@@ -71,8 +71,6 @@ services:
|
||||
- REDIS_URL=redis://wwv-redis:6379
|
||||
- SEEDERS_DIR=/app/seeders
|
||||
- DB_PATH=/app/data/engine.db
|
||||
- WWV_SKIP_WS_AUTH=true
|
||||
- NODE_ENV=development
|
||||
depends_on:
|
||||
wwv-redis:
|
||||
condition: service_healthy
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
# MCP Quickstart: Connect an AI Agent to WorldWideView
|
||||
|
||||
Connect Claude Desktop, Cursor, or any MCP-compatible client to your own WorldWideView
|
||||
globe. MCP is available in the **local (self-hosted) edition** that you run yourself.
|
||||
|
||||
> Cloud edition (hosted at worldmonitor.app) is not yet available. When it launches, the
|
||||
> same steps apply but you will use your cloud account and the cloud endpoint instead of
|
||||
> localhost. See "Cloud edition (coming soon)" at the end.
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- The WorldWideView repository, run locally (this is the **local edition**, the default).
|
||||
- Node.js 20+, pnpm 9+, and Docker (Docker is needed for Postgres, and for Redis + the
|
||||
data engine if you want command tools and live data).
|
||||
- An MCP-compatible client: Claude Desktop, Cursor, VS Code with an MCP extension, or any
|
||||
client that supports the Streamable HTTP MCP transport.
|
||||
|
||||
---
|
||||
|
||||
## Step 1: Install and configure
|
||||
|
||||
From the repository root:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm setup # generates AUTH_SECRET and your local .env (required for API keys to work)
|
||||
```
|
||||
|
||||
`pnpm setup` writes a random `AUTH_SECRET` into `.env`. In the local edition that same
|
||||
secret signs your MCP API keys, so this step is required before key generation will work.
|
||||
The edition defaults to `local` (`NEXT_PUBLIC_WWV_EDITION=local`).
|
||||
|
||||
---
|
||||
|
||||
## Step 2: Run the app
|
||||
|
||||
Two ways to run it, depending on which tools you need:
|
||||
|
||||
```bash
|
||||
pnpm dev # frontend + Postgres only. Read/query tools work. Command tools and live
|
||||
# data do NOT (no Redis, no data engine).
|
||||
|
||||
pnpm dev:all # frontend + data engine + Redis (via Docker Compose). Everything works:
|
||||
# read tools, command tools (open-tab control), geocoding, and live data.
|
||||
```
|
||||
|
||||
Use `pnpm dev:all` for the full MCP experience. The app comes up at
|
||||
**http://localhost:3000** (it will pick another port if 3000 is taken; check the startup log).
|
||||
|
||||
| You want... | Run | Why |
|
||||
|---|---|---|
|
||||
| `search_entities`, `get_plugin_data`, `list_available_plugins`, favorites | `pnpm dev` is enough | served from Postgres + the local data-source registry |
|
||||
| `geocode_location`, command tools (`pan_globe`, `fly_to`, `toggle_layer`, ...) | `pnpm dev:all` | need Redis (sessions, command queue, geocode cache) |
|
||||
| Live plugin data on the globe and in data tools | `pnpm dev:all` | needs the data engine |
|
||||
|
||||
---
|
||||
|
||||
## Step 3: Sign in and generate an API key
|
||||
|
||||
1. Open **http://localhost:3000** and sign in. On a first run, create the initial account
|
||||
via the app's setup flow (see the project README for first-user setup).
|
||||
2. Open **Settings -> API and MCP Access**.
|
||||
3. Click **Generate new key**, give it a name, and **copy the key immediately** (it is shown
|
||||
only once). Your key looks like `wwv_abc123.<long-secret>`.
|
||||
|
||||
The same panel ("Connect your agent") shows a ready-to-paste config block with your local
|
||||
endpoint already filled in (`http://localhost:3000/api/mcp`).
|
||||
|
||||
---
|
||||
|
||||
## Step 4: Add the MCP server to your client
|
||||
|
||||
Paste this into your client's MCP configuration (e.g. `claude_desktop_config.json` for
|
||||
Claude Desktop, or the Cursor MCP settings). The endpoint is your local app:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"worldwideview": {
|
||||
"url": "http://localhost:3000/api/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer wwv_<your-key-here>"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Replace `wwv_<your-key-here>` with the key from step 3. The key goes in the `Authorization`
|
||||
header, never in the URL.
|
||||
|
||||
---
|
||||
|
||||
## Step 5: Restart your client and verify
|
||||
|
||||
Restart your MCP client (Claude Desktop needs a full app restart; Cursor reloads
|
||||
automatically). Ask the agent: "List the available WorldWideView plugins" - it should call
|
||||
`list_available_plugins`. If you started with `pnpm dev:all` and have plugins streaming, you
|
||||
will see them; otherwise see the troubleshooting notes about `engine_unreachable` /
|
||||
`no_active_plugins` below (those mean the connection works but the engine is down or idle).
|
||||
|
||||
---
|
||||
|
||||
## Two capability tiers
|
||||
|
||||
WorldWideView MCP tools split into two tiers based on whether a browser globe session is
|
||||
required.
|
||||
|
||||
### Read / query tools (no open tab required)
|
||||
|
||||
These run server-side and return data using only your API key. You do not need the globe open.
|
||||
|
||||
| Tool | What it does |
|
||||
|---|---|
|
||||
| `search_entities` | Search entities by name across active plugins |
|
||||
| `get_entities_in_region` | Find entities inside a lat/lng bounding box |
|
||||
| `get_entity_details` | Get full details for one entity |
|
||||
| `get_plugin_data` | Get the current snapshot of all entities for a plugin |
|
||||
| `list_available_plugins` | List streaming plugins and their status |
|
||||
| `geocode_location` | Resolve a place name or address to coordinates (needs Redis) |
|
||||
| `save_favorite` | Bookmark an entity |
|
||||
| `list_favorites` | List your bookmarks |
|
||||
| `update_favorite` | Rename or annotate a bookmark |
|
||||
| `remove_favorite` | Delete a bookmark |
|
||||
| `get_plugin_filters` | List filterable fields a plugin declares |
|
||||
|
||||
### Command / control tools (open globe tab required)
|
||||
|
||||
These control the live 3D globe in your browser. **You must keep a WorldWideView browser tab
|
||||
open and signed in as the same account.** Without an open tab, the command is accepted but has
|
||||
no visible effect and the tool returns `"no active globe session to control"`. These also need
|
||||
Redis (run `pnpm dev:all`).
|
||||
|
||||
| Tool | What it does |
|
||||
|---|---|
|
||||
| `pan_globe` | Fly the camera to a coordinate |
|
||||
| `fly_to` | Fly the camera to a geocoded coordinate or bounding box |
|
||||
| `focus_entity` | Centre the camera on a known entity |
|
||||
| `toggle_layer` | Enable or disable a plugin data layer |
|
||||
| `set_timeline` | Set playback time, window, or mode |
|
||||
| `set_filter` | Apply filters to a plugin's live layer |
|
||||
| `clear_filter` | Clear filters on one or all plugins |
|
||||
|
||||
---
|
||||
|
||||
## Recommended agent prompt
|
||||
|
||||
Paste this into your agent's system prompt to give it immediate context:
|
||||
|
||||
```
|
||||
You have access to WorldWideView (WWV) via MCP -- a live 3D globe streaming real-world data
|
||||
(aviation, shipping, earthquakes, weather, and more). Use the MCP tools to query entities,
|
||||
move the camera, toggle layers, and filter data. Command tools require the user to have the
|
||||
WWV globe open in a browser tab. Read/query tools work without a browser tab.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**"no active globe session to control"**
|
||||
A command tool (pan_globe, fly_to, toggle_layer, etc.) ran but no globe tab is open. Open
|
||||
http://localhost:3000 in a browser tab, sign in as the same account that owns the API key,
|
||||
and keep the tab open while you use the agent. Also make sure you started with `pnpm dev:all`
|
||||
(command tools need Redis).
|
||||
|
||||
**"engine_unreachable" from list_available_plugins**
|
||||
The data engine is not running or `WWV_DATA_ENGINE_URL` is not set. Start it with
|
||||
`pnpm dev:all`. The MCP connection itself is working.
|
||||
|
||||
**"no_active_plugins" from list_available_plugins**
|
||||
The data engine is up but no plugins are currently streaming. Enable a plugin from the
|
||||
Plugins panel in the globe app.
|
||||
|
||||
**401 Unauthorized**
|
||||
Your API key is invalid or revoked, or `pnpm setup` was never run (no `AUTH_SECRET`).
|
||||
Confirm `.env` has `AUTH_SECRET`, then generate a fresh key in Settings > API and MCP Access.
|
||||
|
||||
**Tools do not appear in my client**
|
||||
Restart the client after editing the config file. For Claude Desktop, a full app
|
||||
quit-and-relaunch is required.
|
||||
|
||||
---
|
||||
|
||||
## Cloud edition (coming soon)
|
||||
|
||||
A hosted cloud edition is planned at worldmonitor.app. It is **not yet available**. When it
|
||||
launches, the flow is the same as above except:
|
||||
|
||||
- You sign in to your cloud account at worldmonitor.app instead of running the app locally.
|
||||
- The MCP endpoint is `https://api.worldmonitor.app/api/mcp` instead of `http://localhost:3000/api/mcp`.
|
||||
- Infrastructure (Redis, the data engine, secrets) is operated for you, so there is no
|
||||
`pnpm setup` / `pnpm dev:all` step.
|
||||
|
||||
Everything else - generating a key, the Authorization header, the two capability tiers, and
|
||||
the open-tab requirement for command tools - is identical.
|
||||
|
||||
---
|
||||
|
||||
## Next steps
|
||||
|
||||
- See [plugin-filter-guide.md](plugin-filter-guide.md) to learn how to use `get_plugin_filters`
|
||||
and `set_filter` to filter live plugin data.
|
||||
- See [plugin-quickstart.md](plugin-quickstart.md) to build your own data plugin.
|
||||
@@ -1,153 +0,0 @@
|
||||
# Plugin Filter Guide
|
||||
|
||||
This guide explains how a plugin author declares filterable fields so they become
|
||||
discoverable and controllable by AI agents over MCP through the `get_plugin_filters`
|
||||
and `set_filter` tools (v1.3 Location Intelligence).
|
||||
|
||||
## How it fits together
|
||||
|
||||
1. Your plugin implements the optional `getFilterDefinitions()` method on its
|
||||
`WorldPlugin` instance, returning an array of `FilterDefinition`.
|
||||
2. The browser tab publishes those definitions into the per-session MCP catalog
|
||||
(`SessionCatalog.filterDefinitions`, keyed by `pluginId`) in Redis.
|
||||
3. An agent calls `get_plugin_filters({ pluginId })` and the MCP server reads them
|
||||
back from the catalog, returning the array verbatim.
|
||||
4. The agent builds a matching `set_filter({ pluginId, filters })` call. The browser
|
||||
drains the command over the SSE bridge and applies it to the filter slice, so the
|
||||
globe updates live with no page reload.
|
||||
|
||||
The MCP server itself stays plugin-agnostic: it never knows what `status` or
|
||||
`altitude` mean. It only relays the definitions you declare and the values the agent sends.
|
||||
|
||||
## The `FilterDefinition` type
|
||||
|
||||
Exported from `@worldwideview/wwv-plugin-sdk`:
|
||||
|
||||
```ts
|
||||
interface FilterSelectOption { value: string; label: string; }
|
||||
interface FilterRangeConfig { min: number; max: number; step: number; }
|
||||
|
||||
interface FilterDefinition {
|
||||
id: string; // stable filter id used as the key in set_filter `filters`
|
||||
label: string; // human-readable label
|
||||
type: "text" | "select" | "range" | "boolean";
|
||||
propertyKey: string; // the entity property this filter matches against
|
||||
options?: FilterSelectOption[]; // for type "select"
|
||||
range?: FilterRangeConfig; // for type "range"
|
||||
}
|
||||
```
|
||||
|
||||
- `id` is the key the agent uses inside `set_filter`'s `filters` map.
|
||||
- `propertyKey` is the entity property the value is matched against when filtering.
|
||||
It can differ from `id` (e.g. `id: "status"` matching `propertyKey: "flightStatus"`).
|
||||
- `options` is only meaningful for `select`; `range` only for `range`.
|
||||
|
||||
## Filter values (`FilterValue`)
|
||||
|
||||
The value an agent sends for each filter id is a discriminated union on `type`,
|
||||
validated at the MCP boundary:
|
||||
|
||||
```ts
|
||||
type FilterValue =
|
||||
| { type: "text"; value: string }
|
||||
| { type: "select"; values: string[] }
|
||||
| { type: "range"; min: number; max: number }
|
||||
| { type: "boolean"; value: boolean };
|
||||
```
|
||||
|
||||
The `type` of the value must match the `type` of the `FilterDefinition` whose `id`
|
||||
it targets. Structurally invalid values are rejected before reaching the globe.
|
||||
|
||||
## Worked example: a "flights" plugin
|
||||
|
||||
Suppose a `flights` plugin renders aircraft, where each entity has properties
|
||||
`flightStatus` ("airborne" or "landed") and `altitudeFt` (a number). Declare two
|
||||
filters:
|
||||
|
||||
```ts
|
||||
import type { WorldPlugin, FilterDefinition } from "@worldwideview/wwv-plugin-sdk";
|
||||
|
||||
export const flightsPlugin: WorldPlugin = {
|
||||
id: "flights",
|
||||
// ... other required WorldPlugin members ...
|
||||
|
||||
getFilterDefinitions(): FilterDefinition[] {
|
||||
return [
|
||||
{
|
||||
id: "status",
|
||||
label: "Status",
|
||||
type: "select",
|
||||
propertyKey: "flightStatus",
|
||||
options: [
|
||||
{ value: "airborne", label: "Airborne" },
|
||||
{ value: "landed", label: "Landed" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "altitude",
|
||||
label: "Altitude (ft)",
|
||||
type: "range",
|
||||
propertyKey: "altitudeFt",
|
||||
range: { min: 0, max: 45000, step: 1000 },
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### What an agent sees and sends
|
||||
|
||||
The agent first discovers the schema:
|
||||
|
||||
```
|
||||
get_plugin_filters({ pluginId: "flights" })
|
||||
-> [
|
||||
{ id: "status", label: "Status", type: "select", propertyKey: "flightStatus",
|
||||
options: [{ value: "airborne", label: "Airborne" }, { value: "landed", label: "Landed" }] },
|
||||
{ id: "altitude", label: "Altitude (ft)", type: "range", propertyKey: "altitudeFt",
|
||||
range: { min: 0, max: 45000, step: 1000 } }
|
||||
]
|
||||
```
|
||||
|
||||
Then it applies a filter, keyed by the `id`s above:
|
||||
|
||||
```
|
||||
set_filter({
|
||||
pluginId: "flights",
|
||||
filters: {
|
||||
status: { type: "select", values: ["airborne"] },
|
||||
altitude: { type: "range", min: 10000, max: 40000 }
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
The globe immediately hides landed flights and any aircraft outside 10000-40000 ft.
|
||||
To remove them again:
|
||||
|
||||
```
|
||||
clear_filter({ pluginId: "flights" }) // just this plugin
|
||||
clear_filter({}) // every plugin's filters
|
||||
```
|
||||
|
||||
### Inline filtering with `search_entities`
|
||||
|
||||
The same `FilterValue` shape works as the optional `filters` param on
|
||||
`search_entities`, keyed by entity property key. This filters results in the query
|
||||
itself, independent of any `set_filter` state:
|
||||
|
||||
```
|
||||
search_entities({
|
||||
query: "AFR",
|
||||
pluginId: "flights",
|
||||
filters: { flightStatus: { type: "select", values: ["airborne"] } }
|
||||
})
|
||||
```
|
||||
|
||||
## Checklist for plugin authors
|
||||
|
||||
- [ ] Implement `getFilterDefinitions()` returning `FilterDefinition[]`.
|
||||
- [ ] Give each filter a stable `id` and the correct `propertyKey`.
|
||||
- [ ] Provide `options` for `select` filters and `range` for `range` filters.
|
||||
- [ ] Ensure the value `type` an agent will send matches the definition `type`.
|
||||
- [ ] Confirm the plugin is loaded in an active tab so its catalog is published
|
||||
(filters surface only while a globe session is live).
|
||||
@@ -9,7 +9,6 @@ const config = [
|
||||
"out/**",
|
||||
"src/generated/**",
|
||||
"public/cesium/**",
|
||||
"public/plugins-local/**",
|
||||
"packages/*/dist/**",
|
||||
".worktrees/**",
|
||||
"local-scripts/**",
|
||||
|
||||
+4
-4
@@ -30,13 +30,13 @@ const nextConfig: NextConfig = {
|
||||
"script-src 'self' 'unsafe-eval' 'unsafe-inline' blob: https://unpkg.com https://cdn.jsdelivr.net https://analytics.worldwideview.dev https://va.vercel-scripts.com https://pagead2.googlesyndication.com https://adservice.google.com https://www.googletagservices.com https://ep2.adtrafficquality.google https://static.cloudflareinsights.com",
|
||||
"style-src 'self' 'unsafe-inline' fonts.googleapis.com",
|
||||
"font-src 'self' fonts.gstatic.com",
|
||||
// Camera streams load images/MJPEG from arbitrary IPs worldwide -- http: https: required
|
||||
// Camera streams load images/MJPEG from arbitrary IPs worldwide — http: https: required
|
||||
"img-src 'self' data: blob: http: https:",
|
||||
// Camera HLS streams and external data fetches need arbitrary origins
|
||||
"connect-src 'self' http: https: ws: wss:",
|
||||
// HLS video streams from arbitrary camera sources
|
||||
"media-src 'self' blob: http: https:",
|
||||
// Embeddable video platforms for camera iframes -- needs to support arbitrary domains
|
||||
// Embeddable video platforms for camera iframes — needs to support arbitrary domains
|
||||
"frame-src 'self' http: https: blob:",
|
||||
"worker-src 'self' blob:",
|
||||
"frame-ancestors 'none'",
|
||||
@@ -67,10 +67,10 @@ const nextConfig: NextConfig = {
|
||||
// Proxy routes serve arbitrary external HTML (YouTube embeds, camera feeds, etc.).
|
||||
// Restricting style-src/script-src here would break the proxied content since we
|
||||
// cannot predict which CDN domains it loads from. The meaningful security boundary
|
||||
// is frame-ancestors 'self' -- only our own origin can embed these proxy responses.
|
||||
// is frame-ancestors 'self' — only our own origin can embed these proxy responses.
|
||||
value: "default-src * 'unsafe-inline' 'unsafe-eval' data: blob:; frame-ancestors 'self'",
|
||||
},
|
||||
// Remove the DENY override -- SAMEORIGIN allows our app to frame this response
|
||||
// Remove the DENY override — SAMEORIGIN allows our app to frame this response
|
||||
{ key: "X-Frame-Options", value: "SAMEORIGIN" },
|
||||
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
||||
|
||||
+17
-21
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "2.48.14",
|
||||
"version": "2.24.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
@@ -28,41 +28,37 @@
|
||||
"dependencies": {
|
||||
"@auth/prisma-adapter": "^2.11.2",
|
||||
"@auth/supabase-adapter": "^1.11.2",
|
||||
"@modelcontextprotocol/sdk": "^1.29.0",
|
||||
"@prisma/adapter-pg": "^7.8.0",
|
||||
"@prisma/client": "^7.8.0",
|
||||
"@prisma/client-runtime-utils": "7.8.0",
|
||||
"@sentry/nextjs": "^10.56.0",
|
||||
"@sentry/nextjs": "^10.54.0",
|
||||
"@supabase/ssr": "^0.10.3",
|
||||
"@supabase/supabase-js": "^2.107.0",
|
||||
"@supabase/supabase-js": "^2.106.2",
|
||||
"@types/pg": "^8.20.0",
|
||||
"@worldwideview/wwv-lib-aviation": "workspace:*",
|
||||
"@worldwideview/wwv-lib-incidents": "workspace:*",
|
||||
"@worldwideview/wwv-plugin-sdk": "workspace:*",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"cesium": "^1.142.0",
|
||||
"cesium": "^1.141.0",
|
||||
"cheerio": "^1.2.0",
|
||||
"hls.js": "^1.6.16",
|
||||
"insecam-api": "^0.0.3",
|
||||
"ioredis": "^5.4.1",
|
||||
"jose": "^6.2.3",
|
||||
"lucide-react": "^1.17.0",
|
||||
"next": "16.2.7",
|
||||
"next": "16.2.6",
|
||||
"next-auth": "^5.0.0-beta.30",
|
||||
"openid-client": "^6.8.4",
|
||||
"pg": "^8.21.0",
|
||||
"prisma": "^7.8.0",
|
||||
"react": "19.2.7",
|
||||
"react-dom": "19.2.7",
|
||||
"react": "19.2.6",
|
||||
"react-dom": "19.2.6",
|
||||
"react-player": "^3.4.0",
|
||||
"resium": "1.22.0",
|
||||
"resium": "1.21.1",
|
||||
"satellite.js": "^7.0.1",
|
||||
"stripe": "^22.2.0",
|
||||
"tslib": "^2.8.1",
|
||||
"undici": "^8.3.0",
|
||||
"ws": "^8.21.0",
|
||||
"zod": "^4.4.3",
|
||||
"zustand": "^5.0.14"
|
||||
"zustand": "^5.0.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/compat": "^2.1.0",
|
||||
@@ -78,16 +74,16 @@
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@typescript-eslint/eslint-plugin": "^8.60.1",
|
||||
"@typescript-eslint/parser": "^8.60.1",
|
||||
"@typescript-eslint/eslint-plugin": "^8.60.0",
|
||||
"@typescript-eslint/parser": "^8.60.0",
|
||||
"@vitejs/plugin-react": "^6.0.2",
|
||||
"@vitest/coverage-v8": "4.1.8",
|
||||
"@vitest/coverage-v8": "4.1.7",
|
||||
"concurrently": "^9.2.1",
|
||||
"copy-webpack-plugin": "^14.0.0",
|
||||
"eslint": "^9",
|
||||
"eslint-config-airbnb": "^19.0.4",
|
||||
"eslint-config-airbnb-typescript": "^18.0.0",
|
||||
"eslint-config-next": "^16.2.7",
|
||||
"eslint-config-next": "^16.2.6",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-jsx-a11y": "^6.10.2",
|
||||
"eslint-plugin-react": "^7.37.5",
|
||||
@@ -96,9 +92,9 @@
|
||||
"jsdom": "^28.1.0",
|
||||
"rollup-plugin-external-globals": "^0.13.0",
|
||||
"tree-kill": "^1.2.2",
|
||||
"tsx": "^4.22.4",
|
||||
"tsx": "^4.22.3",
|
||||
"typescript": "^5",
|
||||
"vite": "^8.0.16",
|
||||
"vite": "^8.0.14",
|
||||
"vitest": "^4.1.7"
|
||||
},
|
||||
"pnpm": {
|
||||
@@ -107,8 +103,7 @@
|
||||
"form-data@<2.5.4": "^2.5.5",
|
||||
"form-data@>=3.0.0 <3.0.4": "^3.0.4",
|
||||
"form-data@>=4.0.0 <4.0.4": "^4.0.5",
|
||||
"fast-uri@<3.1.2": "^3.1.2",
|
||||
"vitest@<4.1.0": "^4.1.8"
|
||||
"fast-uri@<3.1.2": "^3.1.2"
|
||||
},
|
||||
"onlyBuiltDependencies": [
|
||||
"@prisma/engines",
|
||||
@@ -125,3 +120,4 @@
|
||||
"pnpm": ">=9.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@worldwideview/wwv-cli",
|
||||
"version": "1.3.1",
|
||||
"version": "1.2.0",
|
||||
"type": "module",
|
||||
"description": "WorldWideView CLI",
|
||||
"main": "dist/index.js",
|
||||
@@ -10,8 +10,7 @@
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"dev": "tsc --watch",
|
||||
"clean": "rm -rf dist",
|
||||
"test": "node --test \"test/**/*.test.mjs\""
|
||||
"clean": "rm -rf dist"
|
||||
},
|
||||
"dependencies": {
|
||||
"commander": "^14.0.3",
|
||||
|
||||
@@ -4,74 +4,29 @@ import fs from 'fs';
|
||||
import path from 'path';
|
||||
import prompts from 'prompts';
|
||||
|
||||
const VALID_CATEGORIES = ['aviation', 'maritime', 'space', 'weather', 'custom'];
|
||||
const VALID_ARCHITECTURES = ['polling', 'websocket'];
|
||||
const VALID_SEEDER_TIERS = ['community', 'private'];
|
||||
const VALID_RENDER_STYLES = ['billboard', 'model', 'point'];
|
||||
|
||||
interface CreateOptions {
|
||||
core?: boolean;
|
||||
displayName?: string;
|
||||
description?: string;
|
||||
category?: string;
|
||||
architecture?: string;
|
||||
seederTier?: string;
|
||||
renderStyle?: string;
|
||||
yes?: boolean;
|
||||
}
|
||||
|
||||
function assertChoice(label: string, value: string | undefined, valid: string[]): void {
|
||||
if (value !== undefined && !valid.includes(value)) {
|
||||
console.error(`Error: invalid --${label} "${value}". Valid values: ${valid.join(', ')}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
export const createCommand = new Command('create')
|
||||
.description('Scaffold a new WorldWideView plugin (flags skip the matching prompt; omit them for interactive mode)')
|
||||
.argument('[pluginId]', 'Unique kebab-case plugin ID (e.g. my-tracker)')
|
||||
.description('Interactively scaffold a new WorldWideView plugin')
|
||||
.option('-c, --core', 'Create inside packages instead of local-plugins (for core contributors)')
|
||||
.option('-n, --display-name <name>', 'Display name (e.g. "My Live Tracker")')
|
||||
.option('-d, --description <text>', 'Short description')
|
||||
.option('--category <category>', `One of: ${VALID_CATEGORIES.join(', ')}`)
|
||||
.option('--architecture <architecture>', `One of: ${VALID_ARCHITECTURES.join(', ')}`)
|
||||
.option('--seeder-tier <tier>', `One of: ${VALID_SEEDER_TIERS.join(', ')} (websocket only)`)
|
||||
.option('--render-style <style>', `One of: ${VALID_RENDER_STYLES.join(', ')}`)
|
||||
.option('-y, --yes', 'Non-interactive: fail instead of prompting for missing values')
|
||||
.action(async (pluginIdArg: string | undefined, options: CreateOptions) => {
|
||||
// Validate any flags supplied up front so we fail fast and consistently.
|
||||
assertChoice('category', options.category, VALID_CATEGORIES);
|
||||
assertChoice('architecture', options.architecture, VALID_ARCHITECTURES);
|
||||
assertChoice('seeder-tier', options.seederTier, VALID_SEEDER_TIERS);
|
||||
assertChoice('render-style', options.renderStyle, VALID_RENDER_STYLES);
|
||||
|
||||
// Build the prompt list, skipping any value already supplied via flag/arg.
|
||||
// In --yes mode we never prompt; missing required values are an error.
|
||||
const promptList: prompts.PromptObject[] = [];
|
||||
|
||||
if (!pluginIdArg) {
|
||||
promptList.push({
|
||||
.action(async (options) => {
|
||||
const response = await prompts([
|
||||
{
|
||||
type: 'text',
|
||||
name: 'pluginId',
|
||||
message: 'What is the unique ID for your plugin? (e.g. my-tracker)',
|
||||
validate: value => value.length > 0 ? true : 'Plugin ID is required',
|
||||
});
|
||||
}
|
||||
if (options.displayName === undefined) {
|
||||
promptList.push({
|
||||
validate: value => value.length > 0 ? true : 'Plugin ID is required'
|
||||
},
|
||||
{
|
||||
type: 'text',
|
||||
name: 'displayName',
|
||||
message: 'What is the display name? (e.g. My Live Tracker)',
|
||||
initial: pluginIdArg
|
||||
? pluginIdArg.replace(/-/g, ' ').replace(/\b\w/g, (l: string) => l.toUpperCase())
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
if (options.description === undefined) {
|
||||
promptList.push({ type: 'text', name: 'description', message: 'Enter a short description:' });
|
||||
}
|
||||
if (options.category === undefined) {
|
||||
promptList.push({
|
||||
initial: (prev: string) => prev.replace(/-/g, ' ').replace(/\b\w/g, (l: string) => l.toUpperCase())
|
||||
},
|
||||
{
|
||||
type: 'text',
|
||||
name: 'description',
|
||||
message: 'Enter a short description:'
|
||||
},
|
||||
{
|
||||
type: 'select',
|
||||
name: 'category',
|
||||
message: 'Which category does this plugin belong to?',
|
||||
@@ -80,78 +35,46 @@ export const createCommand = new Command('create')
|
||||
{ title: 'Maritime (Ship icon)', value: 'maritime' },
|
||||
{ title: 'Space (Satellite icon)', value: 'space' },
|
||||
{ title: 'Weather (Cloud icon)', value: 'weather' },
|
||||
{ title: 'Custom (Box icon)', value: 'custom' },
|
||||
],
|
||||
});
|
||||
}
|
||||
if (options.architecture === undefined) {
|
||||
promptList.push({
|
||||
{ title: 'Custom (Box icon)', value: 'custom' }
|
||||
]
|
||||
},
|
||||
{
|
||||
type: 'select',
|
||||
name: 'architecture',
|
||||
message: 'How will your plugin receive data?',
|
||||
choices: [
|
||||
{ title: 'REST Polling / Static Data (Frontend only)', value: 'polling' },
|
||||
{ title: 'Real-Time WebSockets (Generates backend seeder)', value: 'websocket' },
|
||||
],
|
||||
});
|
||||
}
|
||||
if (options.seederTier === undefined) {
|
||||
promptList.push({
|
||||
// Only ask about seeder tier when architecture resolves to websocket.
|
||||
type: (_prev, values) => {
|
||||
const arch = options.architecture ?? values.architecture;
|
||||
return arch === 'websocket' ? 'select' : null;
|
||||
},
|
||||
{ title: 'Real-Time WebSockets (Generates backend seeder)', value: 'websocket' }
|
||||
]
|
||||
},
|
||||
{
|
||||
type: (prev: string) => prev === 'websocket' ? 'select' : null,
|
||||
name: 'seederTier',
|
||||
message: 'Which tier should your backend seeder belong to?',
|
||||
choices: [
|
||||
{ title: 'Community (Open data, shared)', value: 'community' },
|
||||
{ title: 'Private (Requires API keys, restricted)', value: 'private' },
|
||||
],
|
||||
});
|
||||
}
|
||||
if (options.renderStyle === undefined) {
|
||||
promptList.push({
|
||||
{ title: 'Private (Requires API keys, restricted)', value: 'private' }
|
||||
]
|
||||
},
|
||||
{
|
||||
type: 'select',
|
||||
name: 'renderStyle',
|
||||
message: 'How should entities be rendered on the 3D globe?',
|
||||
choices: [
|
||||
{ title: '2D Billboard (Great for static icons)', value: 'billboard' },
|
||||
{ title: '3D Model with LOD (Transitions 2D to 3D)', value: 'model' },
|
||||
{ title: 'Simple Point (High performance dots)', value: 'point' },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
if (options.yes && promptList.length > 0) {
|
||||
// Only count prompts that would actually fire. seederTier is irrelevant
|
||||
// unless the resolved architecture is websocket, so a polling plugin with
|
||||
// --yes must not be forced to supply it.
|
||||
const missing = promptList
|
||||
.map(p => p.name as string)
|
||||
.filter(name => (name === 'seederTier' ? options.architecture === 'websocket' : true));
|
||||
if (missing.length > 0) {
|
||||
console.error(`Error: --yes given but these required values are missing: ${missing.join(', ')}`);
|
||||
process.exit(1);
|
||||
{ title: 'Simple Point (High performance dots)', value: 'point' }
|
||||
]
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
||||
const answers = promptList.length > 0 ? await prompts(promptList) : {};
|
||||
|
||||
// Merge flags/args (authoritative) over interactive answers.
|
||||
const pluginId: string | undefined = pluginIdArg ?? answers.pluginId;
|
||||
const displayName: string = options.displayName ?? answers.displayName ?? '';
|
||||
const description: string = options.description ?? answers.description ?? '';
|
||||
const category: string = options.category ?? answers.category;
|
||||
const architecture: string = options.architecture ?? answers.architecture;
|
||||
const seederTier: string | undefined = options.seederTier ?? answers.seederTier;
|
||||
const renderStyle: string = options.renderStyle ?? answers.renderStyle;
|
||||
|
||||
if (!pluginId) {
|
||||
if (!response.pluginId) {
|
||||
console.log('Plugin creation cancelled.');
|
||||
return;
|
||||
}
|
||||
|
||||
const { pluginId, displayName, description, category, architecture, seederTier, renderStyle } = response;
|
||||
|
||||
const targetBaseDir = options.core ? 'packages' : 'local-plugins';
|
||||
const pluginDir = path.join(process.cwd(), targetBaseDir, `wwv-plugin-${pluginId}`);
|
||||
|
||||
@@ -162,19 +85,21 @@ export const createCommand = new Command('create')
|
||||
|
||||
fs.mkdirSync(pluginDir, { recursive: true });
|
||||
|
||||
// Determine category icon
|
||||
const iconMap: Record<string, string> = {
|
||||
aviation: 'Plane',
|
||||
maritime: 'Ship',
|
||||
space: 'Satellite',
|
||||
weather: 'Cloud',
|
||||
custom: 'Box',
|
||||
custom: 'Box'
|
||||
};
|
||||
const defaultIcon = iconMap[category] || 'Box';
|
||||
|
||||
const streamUrlField = architecture === 'websocket'
|
||||
? `\n "streamUrl": "wss://dataenginev2.worldwideview.dev/stream",`
|
||||
// Package.json boilerplate
|
||||
const streamUrlField = architecture === 'websocket'
|
||||
? `\n "streamUrl": "wss://dataenginev2.worldwideview.dev/stream",`
|
||||
: '';
|
||||
|
||||
|
||||
const packageJsonContent = `{
|
||||
"name": "@worldwideview/wwv-plugin-${pluginId}",
|
||||
"version": "1.0.0",
|
||||
@@ -206,6 +131,7 @@ export const createCommand = new Command('create')
|
||||
}
|
||||
`;
|
||||
|
||||
// index.ts boilerplate
|
||||
const renderBoilerplate = {
|
||||
billboard: `return {
|
||||
type: 'billboard',
|
||||
@@ -226,14 +152,14 @@ export const createCommand = new Command('create')
|
||||
size: 8,
|
||||
outlineColor: '#ffffff',
|
||||
outlineWidth: 2
|
||||
};`,
|
||||
};`
|
||||
}[renderStyle as string] || `return {};`;
|
||||
|
||||
const fetchBoilerplate = architecture === 'polling'
|
||||
const fetchBoilerplate = architecture === 'polling'
|
||||
? `\n async fetch(): Promise<GeoEntity[]> {
|
||||
// Implement REST polling logic here
|
||||
return [];
|
||||
}\n`
|
||||
}\n`
|
||||
: '';
|
||||
|
||||
const indexTsContent = `import { WorldPlugin, GeoEntity, CesiumEntityOptions } from '@worldwideview/wwv-plugin-sdk';
|
||||
@@ -269,75 +195,41 @@ ${fetchBoilerplate}
|
||||
|
||||
console.log(`\n✅ Successfully created plugin frontend at ${pluginDir}`);
|
||||
|
||||
// Generate seeder backend if requested. Matches the real community/private
|
||||
// seeder layout: local-seeders/<tier>/packages/<pluginId>/ with a tsup build
|
||||
// and a src/index.ts that exports the canonical { name, cron, fn } shape.
|
||||
// Generate seeder backend if requested
|
||||
if (architecture === 'websocket' && seederTier) {
|
||||
const seederDir = path.join(process.cwd(), 'local-seeders', seederTier, 'packages', pluginId);
|
||||
|
||||
if (fs.existsSync(seederDir)) {
|
||||
console.error(`Warning: Seeder directory ${seederDir} already exists. Skipping seeder scaffold.`);
|
||||
} else {
|
||||
fs.mkdirSync(path.join(seederDir, 'src'), { recursive: true });
|
||||
|
||||
const seederPackageJson = `{
|
||||
"name": "@wwv-seeders/${pluginId}",
|
||||
"version": "1.0.0",
|
||||
"main": "dist/index.mjs",
|
||||
"scripts": {
|
||||
"build": "tsup"
|
||||
},
|
||||
"dependencies": {
|
||||
"@worldwideview/seeder-sdk": "^1.0.0"
|
||||
}
|
||||
const seederDir = path.join(process.cwd(), 'local-seeders', seederTier, pluginId);
|
||||
|
||||
if (!fs.existsSync(seederDir)) {
|
||||
fs.mkdirSync(seederDir, { recursive: true });
|
||||
|
||||
const seederContent = `// WWV Data Engine Seeder for ${pluginId}
|
||||
export default async function run(context) {
|
||||
console.log('Starting ${displayName} seeder...');
|
||||
|
||||
// Example: Emit a mock entity to the engine
|
||||
setInterval(() => {
|
||||
context.emit({
|
||||
id: '${pluginId}-mock-1',
|
||||
lat: 0,
|
||||
lng: 0,
|
||||
alt: 10000,
|
||||
heading: 0,
|
||||
velocity: 250,
|
||||
properties: {
|
||||
status: 'active'
|
||||
}
|
||||
});
|
||||
}, 1000);
|
||||
}
|
||||
`;
|
||||
|
||||
const tsupConfig = `import { defineConfig } from 'tsup';
|
||||
|
||||
export default defineConfig({
|
||||
entry: ['src/index.ts'],
|
||||
format: ['esm'],
|
||||
clean: true,
|
||||
shims: true,
|
||||
noExternal: [/@wwv-seeders\\/.*/],
|
||||
external: [/^(?!@wwv-seeders)[a-z@].*/],
|
||||
});
|
||||
`;
|
||||
|
||||
// The seeder's exported `name` MUST equal the frontend plugin id
|
||||
// (kebab-case). See ADR-0002 / data-engine-architecture.md section 6.
|
||||
const seederIndexTs = `import { setLiveSnapshot, fetchWithTimeout, withRetry } from '@worldwideview/seeder-sdk';
|
||||
|
||||
async function seed${pluginId.replace(/-/g, '')}() {
|
||||
// TODO: fetch from the real data source and map into GeoEntity-shaped items.
|
||||
const items: Array<{ id: string; lat: number; lon: number; name: string }> = [];
|
||||
|
||||
await setLiveSnapshot('${pluginId}', {
|
||||
source: '${pluginId}',
|
||||
fetchedAt: new Date().toISOString(),
|
||||
items,
|
||||
totalCount: items.length,
|
||||
}, 3600);
|
||||
}
|
||||
|
||||
export default {
|
||||
name: '${pluginId}', // MUST match the frontend plugin id exactly (kebab-case)
|
||||
cron: '*/15 * * * *',
|
||||
fn: seed${pluginId.replace(/-/g, '')},
|
||||
};
|
||||
`;
|
||||
|
||||
fs.writeFileSync(path.join(seederDir, 'package.json'), seederPackageJson);
|
||||
fs.writeFileSync(path.join(seederDir, 'tsup.config.ts'), tsupConfig);
|
||||
fs.writeFileSync(path.join(seederDir, 'src', 'index.ts'), seederIndexTs);
|
||||
fs.writeFileSync(path.join(seederDir, 'seeder.mjs'), seederContent);
|
||||
console.log(`✅ Successfully created plugin seeder at ${seederDir}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\nNext steps:
|
||||
1. Run \`pnpm install\` from the project root.
|
||||
2. Edit \`src/index.ts\` in your plugin directory.
|
||||
${architecture === 'websocket' && seederTier ? `3. Edit \`src/index.ts\` in local-seeders/${seederTier}/packages/${pluginId}/, then \`pnpm build\` it.` : ''}
|
||||
2. Edit \`index.ts\` in your plugin directory.
|
||||
${architecture === 'websocket' ? '3. Edit `seeder.mjs` in your local-seeders directory.' : ''}
|
||||
`);
|
||||
});
|
||||
@@ -9,7 +9,7 @@ const program = new Command();
|
||||
program
|
||||
.name('wwv')
|
||||
.description('WorldWideView Plugin CLI')
|
||||
.version('1.3.1');
|
||||
.version('1.1.2');
|
||||
|
||||
program.addCommand(createCommand);
|
||||
program.addCommand(publishCommand);
|
||||
|
||||
@@ -1,219 +0,0 @@
|
||||
// Integration tests for `wwv create`.
|
||||
//
|
||||
// These spawn the *built* CLI (dist/index.js) into a throwaway temp directory
|
||||
// and assert the generated file tree. No mocking — this is the real scaffold
|
||||
// path agents and humans use. Run with: `node --test test/` (the CLI must be
|
||||
// built first; the cli.yml workflow runs `pnpm build` before this).
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { mkdtempSync, readFileSync, existsSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
|
||||
const CLI = resolve(import.meta.dirname, '..', 'dist', 'index.js');
|
||||
|
||||
function freshDir() {
|
||||
return mkdtempSync(join(tmpdir(), 'wwv-cli-test-'));
|
||||
}
|
||||
|
||||
function runCreate(cwd, args) {
|
||||
const res = spawnSync(process.execPath, [CLI, 'create', ...args], {
|
||||
cwd,
|
||||
encoding: 'utf8',
|
||||
// Empty stdin so a stray prompt (a bug) fails fast instead of hanging CI.
|
||||
input: '',
|
||||
});
|
||||
return { status: res.status, stdout: res.stdout ?? '', stderr: res.stderr ?? '' };
|
||||
}
|
||||
|
||||
function readPkg(dir, ...segments) {
|
||||
return JSON.parse(readFileSync(join(dir, ...segments), 'utf8'));
|
||||
}
|
||||
|
||||
function readText(dir, ...segments) {
|
||||
return readFileSync(join(dir, ...segments), 'utf8');
|
||||
}
|
||||
|
||||
// --- Happy-path plugin types -------------------------------------------------
|
||||
|
||||
test('polling plugin: frontend only, no seeder, no streamUrl, has fetch()', () => {
|
||||
const dir = freshDir();
|
||||
try {
|
||||
const r = runCreate(dir, [
|
||||
'poll-test', '-n', 'Poll Test', '-d', 'A polling plugin',
|
||||
'--category', 'custom', '--architecture', 'polling', '--render-style', 'point', '--yes',
|
||||
]);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
|
||||
const pkg = readPkg(dir, 'local-plugins', 'wwv-plugin-poll-test', 'package.json');
|
||||
assert.equal(pkg.name, '@worldwideview/wwv-plugin-poll-test');
|
||||
assert.equal(pkg.worldwideview.pluginId, 'poll-test');
|
||||
assert.equal(pkg.worldwideview.category, 'custom');
|
||||
assert.equal(pkg.worldwideview.streamUrl, undefined, 'polling plugin must not declare streamUrl');
|
||||
|
||||
const idx = readText(dir, 'local-plugins', 'wwv-plugin-poll-test', 'src', 'index.ts');
|
||||
assert.match(idx, /id = 'poll-test'/);
|
||||
assert.match(idx, /getPollingInterval\(\): number \{\s*return 10000/);
|
||||
assert.match(idx, /async fetch\(/);
|
||||
assert.match(idx, /type: 'point'/);
|
||||
|
||||
assert.ok(!existsSync(join(dir, 'local-seeders')), 'polling plugin must not scaffold a seeder');
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('websocket + community + billboard: seeder under community/packages, streamUrl, Plane icon', () => {
|
||||
const dir = freshDir();
|
||||
try {
|
||||
const r = runCreate(dir, [
|
||||
'ws-comm', '-n', 'WS Comm', '-d', 'desc',
|
||||
'--category', 'aviation', '--architecture', 'websocket', '--seeder-tier', 'community',
|
||||
'--render-style', 'billboard', '--yes',
|
||||
]);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
|
||||
const pkg = readPkg(dir, 'local-plugins', 'wwv-plugin-ws-comm', 'package.json');
|
||||
assert.equal(pkg.worldwideview.icon, 'Plane');
|
||||
assert.ok(pkg.worldwideview.streamUrl, 'websocket plugin must declare a streamUrl');
|
||||
|
||||
const seederBase = join(dir, 'local-seeders', 'community', 'packages', 'ws-comm');
|
||||
assert.ok(existsSync(join(seederBase, 'package.json')), 'seeder package.json missing');
|
||||
assert.ok(existsSync(join(seederBase, 'tsup.config.ts')), 'seeder tsup.config.ts missing');
|
||||
|
||||
const seederPkg = readPkg(dir, 'local-seeders', 'community', 'packages', 'ws-comm', 'package.json');
|
||||
assert.equal(seederPkg.name, '@wwv-seeders/ws-comm');
|
||||
assert.equal(seederPkg.main, 'dist/index.mjs');
|
||||
|
||||
const seederIdx = readText(dir, 'local-seeders', 'community', 'packages', 'ws-comm', 'src', 'index.ts');
|
||||
assert.match(seederIdx, /name: 'ws-comm'/, "seeder name must equal the plugin id (ADR-0002)");
|
||||
assert.match(seederIdx, /cron:/);
|
||||
|
||||
const idx = readText(dir, 'local-plugins', 'wwv-plugin-ws-comm', 'src', 'index.ts');
|
||||
assert.match(idx, /getPollingInterval\(\): number \{\s*return 0;/);
|
||||
assert.match(idx, /type: 'billboard'/);
|
||||
assert.doesNotMatch(idx, /async fetch\(/, 'websocket plugin should not generate a fetch() stub');
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('websocket + private + model: seeder under private/packages, Satellite icon, model render', () => {
|
||||
const dir = freshDir();
|
||||
try {
|
||||
const r = runCreate(dir, [
|
||||
'ws-priv', '-n', 'WS Priv', '-d', 'desc',
|
||||
'--category', 'space', '--architecture', 'websocket', '--seeder-tier', 'private',
|
||||
'--render-style', 'model', '--yes',
|
||||
]);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
|
||||
assert.ok(
|
||||
existsSync(join(dir, 'local-seeders', 'private', 'packages', 'ws-priv', 'src', 'index.ts')),
|
||||
'private seeder must land under local-seeders/private/packages/',
|
||||
);
|
||||
const pkg = readPkg(dir, 'local-plugins', 'wwv-plugin-ws-priv', 'package.json');
|
||||
assert.equal(pkg.worldwideview.icon, 'Satellite');
|
||||
|
||||
const idx = readText(dir, 'local-plugins', 'wwv-plugin-ws-priv', 'src', 'index.ts');
|
||||
assert.match(idx, /modelUrl/, 'model render style should reference modelUrl');
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('--core flag scaffolds into packages/ instead of local-plugins/', () => {
|
||||
const dir = freshDir();
|
||||
try {
|
||||
const r = runCreate(dir, [
|
||||
'core-test', '--core', '-n', 'Core', '-d', 'desc',
|
||||
'--category', 'custom', '--architecture', 'polling', '--render-style', 'point', '--yes',
|
||||
]);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.ok(existsSync(join(dir, 'packages', 'wwv-plugin-core-test', 'package.json')));
|
||||
assert.ok(!existsSync(join(dir, 'local-plugins', 'wwv-plugin-core-test')));
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('multi-word id: kebab id preserved, class and seeder fn names strip dashes', () => {
|
||||
const dir = freshDir();
|
||||
try {
|
||||
const r = runCreate(dir, [
|
||||
'multi-word-plugin', '-n', 'Multi Word', '-d', 'desc',
|
||||
'--category', 'custom', '--architecture', 'websocket', '--seeder-tier', 'community',
|
||||
'--render-style', 'point', '--yes',
|
||||
]);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
|
||||
const idx = readText(dir, 'local-plugins', 'wwv-plugin-multi-word-plugin', 'src', 'index.ts');
|
||||
assert.match(idx, /class multiwordpluginPlugin/);
|
||||
assert.match(idx, /id = 'multi-word-plugin'/);
|
||||
|
||||
const seederIdx = readText(dir, 'local-seeders', 'community', 'packages', 'multi-word-plugin', 'src', 'index.ts');
|
||||
assert.match(seederIdx, /name: 'multi-word-plugin'/);
|
||||
assert.match(seederIdx, /function seedmultiwordplugin\(/);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('category icon mapping: maritime -> Ship, weather -> Cloud', () => {
|
||||
const dir = freshDir();
|
||||
try {
|
||||
const base = ['-d', 'desc', '--architecture', 'polling', '--render-style', 'point', '--yes'];
|
||||
assert.equal(runCreate(dir, ['sea', '-n', 'Sea', '--category', 'maritime', ...base]).status, 0);
|
||||
assert.equal(runCreate(dir, ['sky', '-n', 'Sky', '--category', 'weather', ...base]).status, 0);
|
||||
|
||||
assert.equal(readPkg(dir, 'local-plugins', 'wwv-plugin-sea', 'package.json').worldwideview.icon, 'Ship');
|
||||
assert.equal(readPkg(dir, 'local-plugins', 'wwv-plugin-sky', 'package.json').worldwideview.icon, 'Cloud');
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// --- Failure / guard cases ---------------------------------------------------
|
||||
|
||||
test('--yes with a missing required value exits non-zero and creates nothing', () => {
|
||||
const dir = freshDir();
|
||||
try {
|
||||
const r = runCreate(dir, ['fail-test', '--architecture', 'websocket', '--yes']);
|
||||
assert.notEqual(r.status, 0, 'should fail when required values are missing');
|
||||
assert.match(r.stderr, /missing/i);
|
||||
assert.ok(!existsSync(join(dir, 'local-plugins', 'wwv-plugin-fail-test')), 'must not create a partial scaffold');
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid --category exits non-zero with a clear message', () => {
|
||||
const dir = freshDir();
|
||||
try {
|
||||
const r = runCreate(dir, [
|
||||
'bad-cat', '-n', 'x', '-d', 'y', '--category', 'nonsense',
|
||||
'--architecture', 'polling', '--render-style', 'point', '--yes',
|
||||
]);
|
||||
assert.notEqual(r.status, 0);
|
||||
assert.match(r.stderr, /invalid --category/i);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('creating into an existing plugin directory exits non-zero', () => {
|
||||
const dir = freshDir();
|
||||
try {
|
||||
const args = [
|
||||
'dup-test', '-n', 'x', '-d', 'y', '--category', 'custom',
|
||||
'--architecture', 'polling', '--render-style', 'point', '--yes',
|
||||
];
|
||||
assert.equal(runCreate(dir, args).status, 0);
|
||||
const second = runCreate(dir, args);
|
||||
assert.notEqual(second.status, 0);
|
||||
assert.match(second.stderr, /already exists/i);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -52,38 +52,6 @@ export class MyPlugin implements WorldPlugin {
|
||||
}
|
||||
```
|
||||
|
||||
## Property Tag Helpers
|
||||
|
||||
Wrap entity property values with these helpers so the WorldWideView Intel panel renders them as rich UI elements instead of plain text.
|
||||
|
||||
```ts
|
||||
import { dtProp, urlProp, imageProp, videoProp } from "@worldwideview/wwv-plugin-sdk";
|
||||
```
|
||||
|
||||
| Helper | Wraps | Panel renders as |
|
||||
|---|---|---|
|
||||
| `dtProp(iso: string \| null)` | ISO 8601 date string | Expandable datetime row — local time collapsed, UTC + relative time expanded |
|
||||
| `urlProp(href: string \| null)` | Any URL | Clickable link with external-link icon |
|
||||
| `imageProp(src: string \| null)` | Image URL | Inline thumbnail |
|
||||
| `videoProp(href: string \| null)` | Video/stream URL | "Watch" link with play icon |
|
||||
|
||||
All helpers are **null-safe**: passing `null`, `undefined`, or `""` returns `null`, which the panel skips cleanly.
|
||||
|
||||
```ts
|
||||
// In your entity mapper:
|
||||
properties: {
|
||||
last_seen: dtProp(item.timestamp ?? null),
|
||||
source_url: urlProp(item.url ?? null),
|
||||
preview: imageProp(item.image_url ?? null),
|
||||
live_stream: videoProp(item.stream ?? null),
|
||||
// Plain values need no wrapper
|
||||
name: item.name,
|
||||
severity: item.severity,
|
||||
}
|
||||
```
|
||||
|
||||
Values without a tag prefix fall back to plain-text rendering, so existing plugins continue to work unchanged.
|
||||
|
||||
## Changelog
|
||||
|
||||
- **v1.0.3** — Added README with core interfaces and usage docs.
|
||||
|
||||
+1
-43
@@ -24,7 +24,7 @@ export interface IconUrlOptions extends Record<string, unknown> {
|
||||
* Pass `{ background: false }` to opt out.
|
||||
*/
|
||||
export declare function createSvgIconUrl(Icon: ComponentType<any>, opts?: IconUrlOptions): string;
|
||||
export type { PluginManifest, PluginFormat, PluginType, TrustTier, PluginCapability, DataSourceConfig, FieldMapping, RenderingConfig, McpToolDeclaration } from "./manifest";
|
||||
export type { PluginManifest, PluginFormat, PluginType, TrustTier, PluginCapability, DataSourceConfig, FieldMapping, RenderingConfig } from "./manifest";
|
||||
export type PluginCategory = "aviation" | "maritime" | "military" | "conflict" | "natural-disaster" | "infrastructure" | "space" | "cyber" | "economic" | "intelligence" | "custom";
|
||||
export interface TimeRange {
|
||||
start: Date;
|
||||
@@ -241,17 +241,6 @@ export interface WorldPlugin {
|
||||
requiresConfiguration?(settings: unknown): boolean;
|
||||
/** Map raw websocket payload into GeoEntity array. Optional existingEntities is provided so plugins can merge state (e.g. historical trails). */
|
||||
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[];
|
||||
/**
|
||||
* Execute an MCP tool in the browser on behalf of the server relay.
|
||||
* The server dispatches the invocation here; the plugin runs the logic
|
||||
* and returns the result. The server NEVER executes plugin tools directly
|
||||
* (v3 frontend-relay design).
|
||||
*
|
||||
* @param toolName - The bare tool name (not namespaced).
|
||||
* @param args - Validated arguments from the MCP client.
|
||||
* @returns Arbitrary result serializable to JSON.
|
||||
*/
|
||||
executeMcpTool?(toolName: string, args: Record<string, unknown>): Promise<unknown>;
|
||||
}
|
||||
export type GlobePlugin = WorldPlugin;
|
||||
export type DataBusEvents = {
|
||||
@@ -299,12 +288,6 @@ export type DataBusEvents = {
|
||||
maxPitch?: number;
|
||||
heading?: number;
|
||||
};
|
||||
cameraFlyToBbox: {
|
||||
west: number;
|
||||
south: number;
|
||||
east: number;
|
||||
north: number;
|
||||
};
|
||||
globeReady: Record<string, never>;
|
||||
pluginError: {
|
||||
pluginId?: string;
|
||||
@@ -318,29 +301,4 @@ export type DataBusEvents = {
|
||||
};
|
||||
export * from "./viteGlobals";
|
||||
export * from "./auth-contracts";
|
||||
/**
|
||||
* Wraps an ISO 8601 date string for rich rendering in the Intel panel.
|
||||
* The panel displays local time (collapsed) and UTC + relative time (expanded).
|
||||
* @param iso - ISO 8601 string (e.g. "2026-06-01T05:00:00Z"), or null/undefined
|
||||
* @returns Tagged string `"datetime:{iso}"`, or `null` if input is empty
|
||||
*/
|
||||
export declare function dtProp(iso: string | undefined | null): string | null;
|
||||
/**
|
||||
* Wraps a URL for rich rendering in the Intel panel as a clickable external link.
|
||||
* @param href - Any URL string, or null/undefined
|
||||
* @returns Tagged string `"url:{href}"`, or `null` if input is empty
|
||||
*/
|
||||
export declare function urlProp(href: string | undefined | null): string | null;
|
||||
/**
|
||||
* Wraps an image URL for rich rendering in the Intel panel as an inline thumbnail.
|
||||
* @param src - Image URL string, or null/undefined
|
||||
* @returns Tagged string `"image:{src}"`, or `null` if input is empty
|
||||
*/
|
||||
export declare function imageProp(src: string | undefined | null): string | null;
|
||||
/**
|
||||
* Wraps a video or stream URL for rich rendering in the Intel panel as a "Watch" link.
|
||||
* @param href - Video or stream URL string, or null/undefined
|
||||
* @returns Tagged string `"video:{href}"`, or `null` if input is empty
|
||||
*/
|
||||
export declare function videoProp(href: string | undefined | null): string | null;
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAI3C,kFAAkF;AAClF,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAKpC,MAAM,WAAW,cAAe,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC3D,2BAA2B;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,0DAA0D;IAC1D,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,oEAAoE;IACpE,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC5B,IAAI,EAAE,aAAa,CAAC,GAAG,CAAC,EACxB,IAAI,GAAE,cAAmB,GAC1B,MAAM,CA4BR;AAGD,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,YAAY,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAG7K,MAAM,MAAM,cAAc,GACpB,UAAU,GACV,UAAU,GACV,UAAU,GACV,UAAU,GACV,kBAAkB,GAClB,gBAAgB,GAChB,OAAO,GACP,OAAO,GACP,UAAU,GACV,cAAc,GACd,QAAQ,CAAC;AAGf,MAAM,WAAW,SAAS;IACtB,KAAK,EAAE,IAAI,CAAC;IACZ,GAAG,EAAE,IAAI,CAAC;CACb;AAED,MAAM,MAAM,UAAU,GAAG,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;AAE5D;;;GAGG;AACH,MAAM,WAAW,SAAS;IACtB,oEAAoE;IACpE,EAAE,EAAE,MAAM,CAAC;IACX,kDAAkD;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,sBAAsB;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,uBAAuB;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mEAAmE;IACnE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,yCAAyC;IACzC,SAAS,EAAE,IAAI,CAAC;IAChB,uCAAuC;IACvC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,qDAAqD;IACrD,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,eAAe;IAC5B,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAGD,MAAM,WAAW,WAAW;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,OAAO,CAAC;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,yJAAyJ;IACzJ,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACrC;AAGD,MAAM,WAAW,mBAAmB;IAChC,IAAI,EAAE,WAAW,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;IACzE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wBAAwB,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IACzD,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,8FAA8F;IAC9F,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mHAAmH;IACnH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,YAAY,CAAC,EAAE;QACX,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;QACjC,WAAW,CAAC,EAAE,OAAO,CAAC;KACzB,CAAC;IACF,2FAA2F;IAC3F,2BAA2B,CAAC,EAAE,OAAO,CAAC;IACtC,sEAAsE;IACtE,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC/B;AAGD,MAAM,WAAW,iBAAiB;IAC9B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,2FAA2F;IAC3F,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAKD,MAAM,WAAW,aAAa;IAC1B;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,YAAY,EAAE,MAAM,MAAM,CAAC;IAC3B;;;;;;OAMG;IACH,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC5B,4CAA4C;IAC5C,OAAO,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;IACpC,SAAS,EAAE,SAAS,CAAC;IACrB,YAAY,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,KAAK,IAAI,CAAC;IAC9C,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAChC,6DAA6D;IAC7D,iBAAiB,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,QAAQ,EAAE,MAAM,KAAK,CAAC,GAAG,SAAS,CAAC;IACpE,2DAA2D;IAC3D,cAAc,EAAE,MAAM,OAAO,CAAC;IAC9B,oEAAoE;IACpE,cAAc,EAAE,MAAM,IAAI,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAAG,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;CAAE;AACrE,MAAM,WAAW,iBAAiB;IAAG,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;CAAE;AAC9E,MAAM,WAAW,gBAAgB;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,GAAG,SAAS,CAAC;IAC9C,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,kBAAkB,EAAE,CAAC;IAC/B,KAAK,CAAC,EAAE,iBAAiB,CAAC;CAC7B;AAED,MAAM,MAAM,WAAW,GACjB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,GACpC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAC3C;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAE1C;;;;GAIG;AACH,MAAM,WAAW,WAAW;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,GAAG,aAAa,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAChE,QAAQ,EAAE,cAAc,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAGhB,UAAU,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,OAAO,IAAI,IAAI,CAAC;IAGhB,KAAK,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAClD,kBAAkB,IAAI,MAAM,CAAC;IAG7B,cAAc,IAAI,WAAW,CAAC;IAC9B,YAAY,CAAC,MAAM,EAAE,SAAS,GAAG,mBALine truncated
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAI3C,kFAAkF;AAClF,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAKpC,MAAM,WAAW,cAAe,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC3D,2BAA2B;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,0DAA0D;IAC1D,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,oEAAoE;IACpE,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC5B,IAAI,EAAE,aAAa,CAAC,GAAG,CAAC,EACxB,IAAI,GAAE,cAAmB,GAC1B,MAAM,CA4BR;AAGD,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAGzJ,MAAM,MAAM,cAAc,GACpB,UAAU,GACV,UAAU,GACV,UAAU,GACV,UAAU,GACV,kBAAkB,GAClB,gBAAgB,GAChB,OAAO,GACP,OAAO,GACP,UAAU,GACV,cAAc,GACd,QAAQ,CAAC;AAGf,MAAM,WAAW,SAAS;IACtB,KAAK,EAAE,IAAI,CAAC;IACZ,GAAG,EAAE,IAAI,CAAC;CACb;AAED,MAAM,MAAM,UAAU,GAAG,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;AAE5D;;;GAGG;AACH,MAAM,WAAW,SAAS;IACtB,oEAAoE;IACpE,EAAE,EAAE,MAAM,CAAC;IACX,kDAAkD;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,sBAAsB;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,uBAAuB;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mEAAmE;IACnE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,yCAAyC;IACzC,SAAS,EAAE,IAAI,CAAC;IAChB,uCAAuC;IACvC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,qDAAqD;IACrD,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,eAAe;IAC5B,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAGD,MAAM,WAAW,WAAW;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,OAAO,CAAC;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,yJAAyJ;IACzJ,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACrC;AAGD,MAAM,WAAW,mBAAmB;IAChC,IAAI,EAAE,WAAW,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;IACzE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wBAAwB,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IACzD,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,8FAA8F;IAC9F,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mHAAmH;IACnH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,YAAY,CAAC,EAAE;QACX,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;QACjC,WAAW,CAAC,EAAE,OAAO,CAAC;KACzB,CAAC;IACF,2FAA2F;IAC3F,2BAA2B,CAAC,EAAE,OAAO,CAAC;IACtC,sEAAsE;IACtE,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC/B;AAGD,MAAM,WAAW,iBAAiB;IAC9B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,2FAA2F;IAC3F,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAKD,MAAM,WAAW,aAAa;IAC1B;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,YAAY,EAAE,MAAM,MAAM,CAAC;IAC3B;;;;;;OAMG;IACH,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC5B,4CAA4C;IAC5C,OAAO,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;IACpC,SAAS,EAAE,SAAS,CAAC;IACrB,YAAY,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,KAAK,IAAI,CAAC;IAC9C,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAChC,6DAA6D;IAC7D,iBAAiB,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,QAAQ,EAAE,MAAM,KAAK,CAAC,GAAG,SAAS,CAAC;IACpE,2DAA2D;IAC3D,cAAc,EAAE,MAAM,OAAO,CAAC;IAC9B,oEAAoE;IACpE,cAAc,EAAE,MAAM,IAAI,CAAC;CAC9B;AAGD,MAAM,WAAW,kBAAkB;IAAG,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;CAAE;AACrE,MAAM,WAAW,iBAAiB;IAAG,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;CAAE;AAC9E,MAAM,WAAW,gBAAgB;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,GAAG,SAAS,CAAC;IAC9C,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,kBAAkB,EAAE,CAAC;IAC/B,KAAK,CAAC,EAAE,iBAAiB,CAAC;CAC7B;AAED,MAAM,MAAM,WAAW,GACjB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,GACpC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAC3C;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAE1C;;;;GAIG;AACH,MAAM,WAAW,WAAW;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,GAAG,aAAa,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAChE,QAAQ,EAAE,cAAc,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAGhB,UAAU,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,OAAO,IAAI,IAAI,CAAC;IAGhB,KAAK,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAClD,kBAAkB,IAAI,MAAM,CAAC;IAG7B,cAAc,IAAI,WAAW,CAAC;IAC9B,YAAY,CAAC,MAAM,EAAE,SAAS,GAAG,mBAAmB,CAAC;IAGLine truncated
|
||||
-46
@@ -34,10 +34,6 @@ var __rest = (this && this.__rest) || function (s, e) {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DEFAULT_ICON_SIZE = void 0;
|
||||
exports.createSvgIconUrl = createSvgIconUrl;
|
||||
exports.dtProp = dtProp;
|
||||
exports.urlProp = urlProp;
|
||||
exports.imageProp = imageProp;
|
||||
exports.videoProp = videoProp;
|
||||
const react_1 = require("react");
|
||||
const server_1 = require("react-dom/server");
|
||||
/** Standard SVG icon size (px) used by createSvgIconUrl when no size is given. */
|
||||
@@ -71,45 +67,3 @@ function createSvgIconUrl(Icon, opts = {}) {
|
||||
__exportStar(require("./viteGlobals"), exports);
|
||||
// ─── Auth Contracts ──────────────────────────────────────────
|
||||
__exportStar(require("./auth-contracts"), exports);
|
||||
// ─── Tagged Property Helpers ─────────────────────────────────
|
||||
/**
|
||||
* Wraps an ISO 8601 date string for rich rendering in the Intel panel.
|
||||
* The panel displays local time (collapsed) and UTC + relative time (expanded).
|
||||
* @param iso - ISO 8601 string (e.g. "2026-06-01T05:00:00Z"), or null/undefined
|
||||
* @returns Tagged string `"datetime:{iso}"`, or `null` if input is empty
|
||||
*/
|
||||
function dtProp(iso) {
|
||||
if (!iso)
|
||||
return null;
|
||||
return `datetime:${iso}`;
|
||||
}
|
||||
/**
|
||||
* Wraps a URL for rich rendering in the Intel panel as a clickable external link.
|
||||
* @param href - Any URL string, or null/undefined
|
||||
* @returns Tagged string `"url:{href}"`, or `null` if input is empty
|
||||
*/
|
||||
function urlProp(href) {
|
||||
if (!href)
|
||||
return null;
|
||||
return `url:${href}`;
|
||||
}
|
||||
/**
|
||||
* Wraps an image URL for rich rendering in the Intel panel as an inline thumbnail.
|
||||
* @param src - Image URL string, or null/undefined
|
||||
* @returns Tagged string `"image:{src}"`, or `null` if input is empty
|
||||
*/
|
||||
function imageProp(src) {
|
||||
if (!src)
|
||||
return null;
|
||||
return `image:${src}`;
|
||||
}
|
||||
/**
|
||||
* Wraps a video or stream URL for rich rendering in the Intel panel as a "Watch" link.
|
||||
* @param href - Video or stream URL string, or null/undefined
|
||||
* @returns Tagged string `"video:{href}"`, or `null` if input is empty
|
||||
*/
|
||||
function videoProp(href) {
|
||||
if (!href)
|
||||
return null;
|
||||
return `video:${href}`;
|
||||
}
|
||||
-65
@@ -49,51 +49,6 @@ export interface RenderingConfig {
|
||||
minZoomLevel?: number;
|
||||
maxEntities?: number;
|
||||
}
|
||||
/**
|
||||
* @interface McpToolDeclaration
|
||||
* @description A single MCP tool declared by a plugin.
|
||||
* The server uses this declaration to compose tools/list and dispatch
|
||||
* invocations to the browser. The server NEVER executes plugin tools
|
||||
* directly (v3 frontend-relay design).
|
||||
*
|
||||
* INVARIANT: No `execution` field. The browser (WorldPlugin.executeMcpTool)
|
||||
* is the sole execution site.
|
||||
*/
|
||||
export interface McpToolDeclaration {
|
||||
/** Safe identifier. Only [a-zA-Z0-9_-] characters are allowed. */
|
||||
name: string;
|
||||
/** Human-readable description for MCP clients. */
|
||||
description: string;
|
||||
/**
|
||||
* Minimal JSON-schema-like object describing the tool arguments.
|
||||
* Supports: type, properties, required, enum (per validateToolArgs).
|
||||
*/
|
||||
inputSchema: {
|
||||
type: "object";
|
||||
properties?: Record<string, {
|
||||
type: string;
|
||||
enum?: string[];
|
||||
}>;
|
||||
required?: string[];
|
||||
};
|
||||
}
|
||||
/**
|
||||
* @interface LocalDataSourceDeclaration
|
||||
* @description A single server-reachable data source declared by a plugin.
|
||||
* Plugins opt in to server-side data querying by listing entries in the
|
||||
* `localData` array of their package.json `worldwideview` block. The sync
|
||||
* script carries these declarations into the generated plugin.json so the
|
||||
* LocalDataSource registry can discover them at runtime without a browser
|
||||
* session (D-02, D-03, D-08 -- Phase 30).
|
||||
*/
|
||||
export interface LocalDataSourceDeclaration {
|
||||
/** Distinct name per source within a plugin (e.g. "default", "traffic"). */
|
||||
name: string;
|
||||
/** "geojson" = static FeatureCollection file; "route" = internal Next.js API route. */
|
||||
type: "geojson" | "route";
|
||||
/** Server-relative path. Must start with "/". Both types are server-reachable. */
|
||||
path: string;
|
||||
}
|
||||
/**
|
||||
* @interface PluginManifest
|
||||
* @description The structural definition of a plugin.json file.
|
||||
@@ -122,25 +77,5 @@ export interface PluginManifest {
|
||||
entry?: string;
|
||||
assets?: string[];
|
||||
extends?: string[];
|
||||
/**
|
||||
* MCP tools this plugin declares (v3 frontend-relay design).
|
||||
* The server reads these to compose tools/list and dispatch invocations
|
||||
* to the browser. Execution always happens in the browser via
|
||||
* WorldPlugin.executeMcpTool.
|
||||
*/
|
||||
mcpTools?: McpToolDeclaration[];
|
||||
/**
|
||||
* Opaque capability tags for MCP clients (e.g. "point-layer", "camera-control").
|
||||
* Must be a string array when present.
|
||||
*/
|
||||
mcpCapabilities?: string[];
|
||||
/**
|
||||
* Server-reachable data sources declared by this plugin (Phase 30, D-02/D-03).
|
||||
* When present, the LocalDataSource registry serves this plugin's data
|
||||
* server-side so MCP query tools work without a browser session. Each
|
||||
* entry names a distinct source (e.g. "default", "traffic") and specifies
|
||||
* its type and server-relative path. Paths must start with "/".
|
||||
*/
|
||||
localData?: LocalDataSourceDeclaration[];
|
||||
}
|
||||
//# sourceMappingURL=manifest.d.ts.map
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C,MAAM,MAAM,YAAY,GAAG,aAAa,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAC/D,MAAM,MAAM,UAAU,GAAG,YAAY,GAAG,WAAW,CAAC;AACpD,MAAM,MAAM,SAAS,GAAG,UAAU,GAAG,UAAU,GAAG,YAAY,CAAC;AAE/D,MAAM,MAAM,gBAAgB,GACtB,UAAU,GACV,aAAa,MAAM,EAAE,GACrB,iBAAiB,GACjB,YAAY,GACZ,YAAY,GACZ,aAAa,GACb,eAAe,GACf,cAAc,GACd,cAAc,GACd,eAAe,GACf,eAAe,CAAC;AAEtB,MAAM,WAAW,gBAAgB;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,KAAK,GAAG,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,SAAS,GAAG,MAAM,GAAG,KAAK,CAAC;IACnC,IAAI,CAAC,EAAE;QAAE,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC;QAAC,GAAG,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IACxE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,6FAA6F;IAC7F,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,YAAY;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,eAAe;IAC5B,UAAU,EAAE,WAAW,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;IAC/E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,kBAAkB;IAC/B,kEAAkE;IAClE,IAAI,EAAE,MAAM,CAAC;IACb,kDAAkD;IAClD,WAAW,EAAE,MAAM,CAAC;IACpB;;;OAGG;IACH,WAAW,EAAE;QACT,IAAI,EAAE,QAAQ,CAAC;QACf,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAA;SAAE,CAAC,CAAC;QAC/D,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;KACvB,CAAC;CACL;AAED;;;;;;;;GAQG;AACH,MAAM,WAAW,0BAA0B;IACvC,4EAA4E;IAC5E,IAAI,EAAE,MAAM,CAAC;IACb,uFAAuF;IACvF,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC;IAC1B,kFAAkF;IAClF,IAAI,EAAE,MAAM,CAAC;CAChB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,EAAE,UAAU,CAAC;IACjB,MAAM,EAAE,YAAY,CAAC;IACrB,KAAK,EAAE,SAAS,CAAC;IACjB,YAAY,EAAE,gBAAgB,EAAE,CAAC;IACjC,QAAQ,EAAE,cAAc,GAAG,MAAM,CAAC;IAClC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE;QAAE,aAAa,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1C,QAAQ,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IAClC,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,kBAAkB,EAAE,CAAC;IAChC;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,0BAA0B,EAAE,CAAC;CAC5C"}
|
||||
{"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C,MAAM,MAAM,YAAY,GAAG,aAAa,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAC/D,MAAM,MAAM,UAAU,GAAG,YAAY,GAAG,WAAW,CAAC;AACpD,MAAM,MAAM,SAAS,GAAG,UAAU,GAAG,UAAU,GAAG,YAAY,CAAC;AAE/D,MAAM,MAAM,gBAAgB,GACtB,UAAU,GACV,aAAa,MAAM,EAAE,GACrB,iBAAiB,GACjB,YAAY,GACZ,YAAY,GACZ,aAAa,GACb,eAAe,GACf,cAAc,GACd,cAAc,GACd,eAAe,GACf,eAAe,CAAC;AAEtB,MAAM,WAAW,gBAAgB;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,KAAK,GAAG,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,SAAS,GAAG,MAAM,GAAG,KAAK,CAAC;IACnC,IAAI,CAAC,EAAE;QAAE,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC;QAAC,GAAG,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IACxE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,6FAA6F;IAC7F,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,YAAY;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,eAAe;IAC5B,UAAU,EAAE,WAAW,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;IAC/E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,EAAE,UAAU,CAAC;IACjB,MAAM,EAAE,YAAY,CAAC;IACrB,KAAK,EAAE,SAAS,CAAC;IACjB,YAAY,EAAE,gBAAgB,EAAE,CAAC;IACjC,QAAQ,EAAE,cAAc,GAAG,MAAM,CAAC;IAClC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE;QAAE,aAAa,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1C,QAAQ,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IAClC,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACtB"}
|
||||
@@ -66,7 +66,7 @@ export function createSvgIconUrl(
|
||||
}
|
||||
|
||||
// ─── Re-export manifest types ─────────────────────────────────
|
||||
export type { PluginManifest, PluginFormat, PluginType, TrustTier, PluginCapability, DataSourceConfig, FieldMapping, RenderingConfig, McpToolDeclaration, LocalDataSourceDeclaration } from "./manifest";
|
||||
export type { PluginManifest, PluginFormat, PluginType, TrustTier, PluginCapability, DataSourceConfig, FieldMapping, RenderingConfig } from "./manifest";
|
||||
|
||||
// ─── Categories ──────────────────────────────────────────────
|
||||
export type PluginCategory =
|
||||
@@ -286,17 +286,6 @@ export interface WorldPlugin {
|
||||
requiresConfiguration?(settings: unknown): boolean;
|
||||
/** Map raw websocket payload into GeoEntity array. Optional existingEntities is provided so plugins can merge state (e.g. historical trails). */
|
||||
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[];
|
||||
/**
|
||||
* Execute an MCP tool in the browser on behalf of the server relay.
|
||||
* The server dispatches the invocation here; the plugin runs the logic
|
||||
* and returns the result. The server NEVER executes plugin tools directly
|
||||
* (v3 frontend-relay design).
|
||||
*
|
||||
* @param toolName - The bare tool name (not namespaced).
|
||||
* @param args - Validated arguments from the MCP client.
|
||||
* @returns Arbitrary result serializable to JSON.
|
||||
*/
|
||||
executeMcpTool?(toolName: string, args: Record<string, unknown>): Promise<unknown>;
|
||||
}
|
||||
|
||||
// ─── Aliases for backwards compatibility ─────────────────────
|
||||
@@ -315,7 +304,6 @@ export type DataBusEvents = {
|
||||
cameraPreset: { presetId: string };
|
||||
cameraFaceTowards: { lat: number; lon: number; alt: number };
|
||||
cameraGoTo: { lat: number; lon: number; alt: number; distance?: number; maxPitch?: number; heading?: number };
|
||||
cameraFlyToBbox: { west: number; south: number; east: number; north: number };
|
||||
globeReady: Record<string, never>;
|
||||
pluginError: { pluginId?: string; message: string; error?: Error };
|
||||
layerLoadingChanged: { pluginId: string; loading: boolean };
|
||||
@@ -325,45 +313,3 @@ export * from "./viteGlobals";
|
||||
|
||||
// ─── Auth Contracts ──────────────────────────────────────────
|
||||
export * from "./auth-contracts";
|
||||
|
||||
// ─── Tagged Property Helpers ─────────────────────────────────
|
||||
/**
|
||||
* Wraps an ISO 8601 date string for rich rendering in the Intel panel.
|
||||
* The panel displays local time (collapsed) and UTC + relative time (expanded).
|
||||
* @param iso - ISO 8601 string (e.g. "2026-06-01T05:00:00Z"), or null/undefined
|
||||
* @returns Tagged string `"datetime:{iso}"`, or `null` if input is empty
|
||||
*/
|
||||
export function dtProp(iso: string | undefined | null): string | null {
|
||||
if (!iso) return null;
|
||||
return `datetime:${iso}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a URL for rich rendering in the Intel panel as a clickable external link.
|
||||
* @param href - Any URL string, or null/undefined
|
||||
* @returns Tagged string `"url:{href}"`, or `null` if input is empty
|
||||
*/
|
||||
export function urlProp(href: string | undefined | null): string | null {
|
||||
if (!href) return null;
|
||||
return `url:${href}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps an image URL for rich rendering in the Intel panel as an inline thumbnail.
|
||||
* @param src - Image URL string, or null/undefined
|
||||
* @returns Tagged string `"image:{src}"`, or `null` if input is empty
|
||||
*/
|
||||
export function imageProp(src: string | undefined | null): string | null {
|
||||
if (!src) return null;
|
||||
return `image:${src}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a video or stream URL for rich rendering in the Intel panel as a "Watch" link.
|
||||
* @param href - Video or stream URL string, or null/undefined
|
||||
* @returns Tagged string `"video:{href}"`, or `null` if input is empty
|
||||
*/
|
||||
export function videoProp(href: string | undefined | null): string | null {
|
||||
if (!href) return null;
|
||||
return `video:${href}`;
|
||||
}
|
||||
@@ -63,50 +63,6 @@ export interface RenderingConfig {
|
||||
maxEntities?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* @interface McpToolDeclaration
|
||||
* @description A single MCP tool declared by a plugin.
|
||||
* The server uses this declaration to compose tools/list and dispatch
|
||||
* invocations to the browser. The server NEVER executes plugin tools
|
||||
* directly (v3 frontend-relay design).
|
||||
*
|
||||
* INVARIANT: No `execution` field. The browser (WorldPlugin.executeMcpTool)
|
||||
* is the sole execution site.
|
||||
*/
|
||||
export interface McpToolDeclaration {
|
||||
/** Safe identifier. Only [a-zA-Z0-9_-] characters are allowed. */
|
||||
name: string;
|
||||
/** Human-readable description for MCP clients. */
|
||||
description: string;
|
||||
/**
|
||||
* Minimal JSON-schema-like object describing the tool arguments.
|
||||
* Supports: type, properties, required, enum (per validateToolArgs).
|
||||
*/
|
||||
inputSchema: {
|
||||
type: "object";
|
||||
properties?: Record<string, { type: string; enum?: string[] }>;
|
||||
required?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @interface LocalDataSourceDeclaration
|
||||
* @description A single server-reachable data source declared by a plugin.
|
||||
* Plugins opt in to server-side data querying by listing entries in the
|
||||
* `localData` array of their package.json `worldwideview` block. The sync
|
||||
* script carries these declarations into the generated plugin.json so the
|
||||
* LocalDataSource registry can discover them at runtime without a browser
|
||||
* session (D-02, D-03, D-08 -- Phase 30).
|
||||
*/
|
||||
export interface LocalDataSourceDeclaration {
|
||||
/** Distinct name per source within a plugin (e.g. "default", "traffic"). */
|
||||
name: string;
|
||||
/** "geojson" = static FeatureCollection file; "route" = internal Next.js API route. */
|
||||
type: "geojson" | "route";
|
||||
/** Server-relative path. Must start with "/". Both types are server-reachable. */
|
||||
path: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* @interface PluginManifest
|
||||
* @description The structural definition of a plugin.json file.
|
||||
@@ -131,24 +87,4 @@ export interface PluginManifest {
|
||||
entry?: string;
|
||||
assets?: string[];
|
||||
extends?: string[];
|
||||
/**
|
||||
* MCP tools this plugin declares (v3 frontend-relay design).
|
||||
* The server reads these to compose tools/list and dispatch invocations
|
||||
* to the browser. Execution always happens in the browser via
|
||||
* WorldPlugin.executeMcpTool.
|
||||
*/
|
||||
mcpTools?: McpToolDeclaration[];
|
||||
/**
|
||||
* Opaque capability tags for MCP clients (e.g. "point-layer", "camera-control").
|
||||
* Must be a string array when present.
|
||||
*/
|
||||
mcpCapabilities?: string[];
|
||||
/**
|
||||
* Server-reachable data sources declared by this plugin (Phase 30, D-02/D-03).
|
||||
* When present, the LocalDataSource registry serves this plugin's data
|
||||
* server-side so MCP query tools work without a browser session. Each
|
||||
* entry names a distinct source (e.g. "default", "traffic") and specifies
|
||||
* its type and server-relative path. Paths must start with "/".
|
||||
*/
|
||||
localData?: LocalDataSourceDeclaration[];
|
||||
}
|
||||
@@ -1,14 +1,9 @@
|
||||
/**
|
||||
* @file viteGlobals.ts
|
||||
* @description Build-time utility for externalizing shared host dependencies.
|
||||
* Provides a Vite plugin that maps 10 core libraries to globalThis.__WWV_HOST__,
|
||||
* ensuring singleton stability for dynamically loaded plugin bundles:
|
||||
* react, react-dom, react/jsx-runtime, cesium, resium, zustand,
|
||||
* @worldwideview/wwv-plugin-sdk, @/core/state/store,
|
||||
* @/core/plugins/PluginManager, @/components/video/CameraStream
|
||||
*
|
||||
* Everything else (e.g. wwv-lib-aviation, wwv-lib-incidents, recharts) must be
|
||||
* bundled per-plugin — the host does not provide small utility libs.
|
||||
* @description Build-time utility for externalizing shared dependencies.
|
||||
* Provides a Vite plugin that maps core libraries (React, Cesium, Zustand)
|
||||
* to the host application's global context, ensuring singleton stability
|
||||
* for dynamic plugin bundles.
|
||||
* @module @worldwideview/wwv-plugin-sdk
|
||||
*/
|
||||
|
||||
@@ -34,7 +29,7 @@ export function wwvPluginGlobals(): any {
|
||||
"react/jsx-runtime": "jsxRuntime",
|
||||
"cesium": "Cesium",
|
||||
"resium": "Resium",
|
||||
// zustand is handled in resolveId separately (not in HOST_MAPPINGS) — see load() below
|
||||
// zustand is also part of WWVHostGlobals or maybe not? Wait. I should check hostGlobals.ts!
|
||||
"@worldwideview/wwv-plugin-sdk": "WWVPluginSDK",
|
||||
"@/core/state/store": "useStore",
|
||||
"@/core/plugins/PluginManager": "pluginManager",
|
||||
@@ -99,6 +94,7 @@ export function wwvPluginGlobals(): any {
|
||||
export const { WorldPlugin, PluginManifest, createSvgIconUrl, DEFAULT_ICON_SIZE } = SDK;
|
||||
`;
|
||||
}
|
||||
// If zustand is required, wait, is Zustand in host globals?
|
||||
if (originalId === "zustand") {
|
||||
return `
|
||||
if (!globalThis.__WWV_HOST__.zustand) {
|
||||
|
||||
Generated
+1624
-1371
File diff suppressed because it is too large.
Load diff
-36
@@ -1,36 +0,0 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "marketplace_credentials" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenantId" TEXT,
|
||||
"version" TEXT NOT NULL,
|
||||
"salt" TEXT NOT NULL,
|
||||
"nonce" TEXT NOT NULL,
|
||||
"ciphertext" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "marketplace_credentials_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "user_api_keys" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"tenantId" TEXT,
|
||||
"prefix" TEXT NOT NULL,
|
||||
"hashedSecret" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"lastUsedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "user_api_keys_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "marketplace_credentials_tenantId_key" ON "marketplace_credentials"("tenantId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "user_api_keys_prefix_key" ON "user_api_keys"("prefix");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "user_api_keys" ADD CONSTRAINT "user_api_keys_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -1,3 +0,0 @@
|
||||
-- AlterTable: add nullable notes column to favorites
|
||||
-- This is a non-destructive additive change. Existing rows receive NULL.
|
||||
ALTER TABLE "favorites" ADD COLUMN IF NOT EXISTS "notes" TEXT;
|
||||
@@ -14,14 +14,9 @@ model User {
|
||||
name String
|
||||
hashedPassword String
|
||||
role String @default("user")
|
||||
// Bumping this invalidates all of the user's existing JWT sessions.
|
||||
// The JWT embeds the value at sign-in; the auth jwt callback rejects any
|
||||
// token whose value no longer matches the DB (logout-everywhere / revoke).
|
||||
sessionVersion Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
favorites Favorite[]
|
||||
memberships WorkspaceMember[]
|
||||
apiKeys UserApiKey[]
|
||||
|
||||
@@unique([tenantId, email])
|
||||
@@map("users")
|
||||
@@ -36,7 +31,6 @@ model Favorite {
|
||||
pluginName String
|
||||
lastSeen DateTime @default(now())
|
||||
userId String
|
||||
notes String?
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([userId, entityId])
|
||||
@@ -108,17 +102,3 @@ model MarketplaceCredential {
|
||||
@@unique([tenantId])
|
||||
@@map("marketplace_credentials")
|
||||
}
|
||||
|
||||
model UserApiKey {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
tenantId String?
|
||||
prefix String @unique
|
||||
hashedSecret String
|
||||
name String
|
||||
createdAt DateTime @default(now())
|
||||
lastUsedAt DateTime?
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@map("user_api_keys")
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
{"type":"FeatureCollection","name":"submarine_cables","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},"features":[{"type":"Feature","properties":{"id":"kunoa-north","name":"Kunoa North","color":"#939597","feature_id":"kunoa-north-0","coordinates":[-156.9665630882687,21.295721056114605]},"geometry":{"type":"MultiLineString","coordinates":[[[-155.98674859999997,20.758889136336883],[-155.90974609999998,20.58804526040611],[-155.91557111892848,20.352107812644185],[-155.8327436,20.240940704337877]],[[-157.7460045774889,21.396572],[-157.55220471967434,21.444450862926626],[-157.28479134194126,21.337518919200047],[-156.80525422850113,21.274533856181144],[-156.46310227824227,21.16957074507486],[-156.503135,20.884760102747034]],[[-159.40532650000003,22.215110945272016],[-159.11459846491226,22.150960720583736],[-158.79461333774822,21.9128163130342],[-158.4399589418041,21.829558295178412],[-158.22066328843266,21.717836296561472],[-158.12307759999996,21.56809172379588]]]}},{"type":"Feature","properties":{"id":"oceanic-tatitlek-telecommunications-enhancement-route-otter","name":"Oceanic Tatitlek Telecommunications Enhancement Route (OTTER)","color":"#939597","feature_id":"oceanic-tatitlek-telecommunications-enhancement-route-otter-0","coordinates":[-146.68979114956804,61.00651754266184]},"geometry":{"type":"MultiLineString","coordinates":[[[-146.5804962255995,60.865128606480916],[-146.69056686122886,60.83790231458027],[-146.76608515657378,60.865128606480916],[-146.75236391816247,60.95477039449461],[-146.63545891597727,61.05144983837184],[-146.54973544558572,61.09192827355534],[-146.35343293589426,61.13035646305128]]]}},{"type":"Feature","properties":{"id":"iokwe","name":"IOKWE","color":"#939597","feature_id":"iokwe-0","coordinates":[171.3392295405602,6.834015700933953]},"geometry":{"type":"MultiLineString","coordinates":[[[171.29818908112054,6.578321401868001],[171.38026999999985,7.08971]]]}},{"type":"Feature","properties":{"id":"andromeda","name":"ANDROMEDA","color":"#939597","feature_id":"andromeda-0","coordinates":[22.22426740344288,36.20957593836509]},"geometry":{"type":"MultiLineString","coordinates":[[[35.005095000000225,29.581033231032787],[35.09407707525654,29.791309936248265],[35.09258106291824,31.01930574551369],[34.76967960477271,31.669509999999626],[35.03999086843967,32.65551986665992],[34.998746580236514,32.811596],[34.200050008303506,32.896243407162636],[30.769743513702018,33.53335968863164],[28.554783191139578,34.28173085454878],[25.892178118938983,35.74306843576459],[25.376086016528483,35.71069562446953],[24.006181725996615,35.511169691366945],[23.621978066243148,35.96505111951632],[19.051532763673276,36.76463528197097],[18.114532544729055,37.121655665582466],[15.750063078447363,37.67887792909206],[15.525063237243426,38.06370455144154],[15.637563157547534,38.240638159471985],[15.354067264628604,38.55462024669397],[14.841825511799467,38.77307354824823],[13.50162967125888,38.959248078378096],[12.226913000000101,39.75405284068902],[10.84161269111189,41.557848620600836],[10.284778286332376,42.46701890694944],[9.954701037372352,43.445517559460725],[9.613161999999766,43.96751155521148],[9.3383810796972,44.18008469439857],[8.938867903561944,44.41035752885385]]]}},{"type":"Feature","properties":{"id":"norte-conectado-infovia-06","name":"Norte Conectado (Infovia 06)","color":"#939597","feature_id":"norte-conectado-infovia-06-0","coordinates":[-64.34704313879367,-6.435769079187864]},"geometry":{"type":"MultiLineString","coordinates":[[[-67.83284106969606,-9.993359703946657],[-67.50749507970924,-9.674819640496032],[-67.45608810500033,-9.227782542395829],[-67.39305203832167,-8.761671000000462],[-67.40864332969578,-8.430490503126785],[-67.27485426719613,-7.996419461382065],[-67.05444411094578,-7.797840312008653],[-66.7298835640715,-7.671622619179622],[-66.35961989219578,-7.558344029269731],[-66.10229567344659,-7.668204731266927],[-65.73232497032132,-7.722988587494916],[-65.22353590782123,-7.408542799054667],[-64.57758864219642,-7.075688906343259],[-64.56882528649051,-6.801470773864218],[-64.2341294798481,-6.249583144669121],[-64.4320808296965,-5.844024005533163],[-64.31128004844595,-5.598032256217185],[-63.59755934532132,-5.797540465752491],[-63.138013446884,-5.735871641680001],[-62.94201979830971,-5.379172975761144],[-62.71470023726901,-4.910261666732165],[-62.194848247392024,-4.724558060019035],[-62.08695443817308,-4.450799451363403],[-61.725792643437515,-4.236395515422113],[-61.40161207969596,-3.863340799836464],[-60.90012253675791,-3.736608406262437],[-60.63541789000012,-3.289115312000247]]]}},{"type":"Feature","properties":{"id":"norte-conectado-infovia-08","name":"Norte Conectado (Infovia 08)","color":"#939597","feature_id":"norte-conectado-infovia-08-0","coordinates":[-68.27711461195817,-6.425708100314885]},"geometry":{"type":"MultiLineString","coordinates":[[[-72.65583127632956,-7.625022373429889],[-72.4589691611615,-7.319649292446373],[-71.78483579960094,-7.161134671579085],[-71.10Line truncated
|
||||
@@ -1,99 +0,0 @@
|
||||
import concurrently from 'concurrently';
|
||||
import kill from 'tree-kill/index.js';
|
||||
import net from 'net';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import fs from 'fs';
|
||||
import { execSync } from 'child_process';
|
||||
import process from 'process';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const loadEnv = (file) => {
|
||||
try {
|
||||
const absPath = path.resolve(__dirname, '..', file);
|
||||
if (fs.existsSync(absPath)) {
|
||||
const content = fs.readFileSync(absPath, 'utf8');
|
||||
content.split('\n').forEach(line => {
|
||||
const match = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/);
|
||||
if (match) {
|
||||
const key = match[1];
|
||||
let value = match[2] || '';
|
||||
if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
|
||||
if (value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
|
||||
if (!(key in process.env)) process.env[key] = value;
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Ignore read errors
|
||||
}
|
||||
};
|
||||
|
||||
loadEnv('.env');
|
||||
|
||||
function findFreePort(start) {
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer();
|
||||
server.listen(start, '127.0.0.1', () => {
|
||||
const port = server.address().port;
|
||||
server.close(() => resolve(port));
|
||||
});
|
||||
server.on('error', () => findFreePort(start + 1).then(resolve));
|
||||
});
|
||||
}
|
||||
|
||||
const enginePort = await findFreePort(5000);
|
||||
const projectName = path.basename(process.cwd()).replace(/[^a-z0-9]/gi, '-').toLowerCase();
|
||||
|
||||
process.env.WWV_ENGINE_HOST_PORT = String(enginePort);
|
||||
process.env.NEXT_PUBLIC_WWV_LOCAL_ENGINE_PORT = String(enginePort);
|
||||
process.env.COMPOSE_PROJECT_NAME = projectName;
|
||||
|
||||
console.log(`[dev:all] Engine -> :${enginePort} | Docker project: ${projectName}`);
|
||||
|
||||
const teardownDbOnExit =
|
||||
process.env.WWV_TEARDOWN_DB_ON_EXIT === 'true' ||
|
||||
process.env.WWV_TEARDOWN_DB_ON_EXIT === '1';
|
||||
|
||||
const { result, commands } = concurrently(
|
||||
[
|
||||
{ command: 'pnpm dev', name: 'app', prefixColor: 'magenta' },
|
||||
{ command: 'pnpm dev:backends', name: 'backends', prefixColor: 'blue' },
|
||||
],
|
||||
{
|
||||
prefix: 'name',
|
||||
killOthersOn: ['failure', 'success'],
|
||||
}
|
||||
);
|
||||
|
||||
let isShuttingDown = false;
|
||||
|
||||
const shutdown = () => {
|
||||
if (isShuttingDown) return;
|
||||
isShuttingDown = true;
|
||||
|
||||
console.log('\n[dev:all] Shutting down...');
|
||||
|
||||
commands.forEach(cmd => {
|
||||
if (cmd.pid) kill(cmd.pid, 'SIGKILL');
|
||||
});
|
||||
|
||||
if (teardownDbOnExit) {
|
||||
try {
|
||||
execSync('docker compose stop db', { stdio: 'inherit' });
|
||||
} catch {
|
||||
console.error('[dev:all] Failed to stop database container.');
|
||||
}
|
||||
}
|
||||
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
process.on('SIGINT', shutdown);
|
||||
process.on('SIGTERM', shutdown);
|
||||
|
||||
result.then(
|
||||
() => process.exit(0),
|
||||
() => process.exit(1)
|
||||
);
|
||||
@@ -9,8 +9,6 @@
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import crypto from "crypto";
|
||||
import { execSync } from "child_process";
|
||||
import { build } from "vite";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
@@ -29,14 +27,6 @@ const EXTERNAL_GLOBALS = {
|
||||
"resium": "globalThis.__WWV_HOST__.Resium",
|
||||
};
|
||||
|
||||
// Hash of the build config — written to dist/.config-hash after each build.
|
||||
// isBuildFresh() checks this so any EXTERNAL_GLOBALS change forces a full rebuild.
|
||||
const CONFIG_HASH = crypto
|
||||
.createHash("sha1")
|
||||
.update(JSON.stringify(EXTERNAL_GLOBALS))
|
||||
.digest("hex")
|
||||
.slice(0, 12);
|
||||
|
||||
/**
|
||||
* Synthetic host-module exports for `@/` imports that plugins use to access
|
||||
* the host application's runtime objects (store, plugin manager, components).
|
||||
@@ -214,55 +204,11 @@ function latestSourceMtime(rootDir) {
|
||||
function isBuildFresh(pluginDir) {
|
||||
const distFile = path.join(pluginDir, "dist", "frontend.mjs");
|
||||
if (!fs.existsSync(distFile)) return false;
|
||||
// If the build config (EXTERNAL_GLOBALS) changed since this dist was built, rebuild.
|
||||
const hashFile = path.join(pluginDir, "dist", ".config-hash");
|
||||
if (!fs.existsSync(hashFile) || fs.readFileSync(hashFile, "utf8").trim() !== CONFIG_HASH) {
|
||||
return false;
|
||||
}
|
||||
const distMtime = fs.statSync(distFile).mtimeMs;
|
||||
const sourceMtime = latestSourceMtime(pluginDir);
|
||||
return distMtime >= sourceMtime;
|
||||
}
|
||||
|
||||
/**
|
||||
* @function ensurePluginDeps
|
||||
* @description Installs a plugin's bundleable dependencies (regular `dependencies`,
|
||||
* excluding `workspace:*` refs which are mocked by EXTERNAL_GLOBALS) into the
|
||||
* plugin's own `node_modules/` so Rolldown can resolve them during the build.
|
||||
*
|
||||
* Uses a clean temp-dir package.json to avoid npm choking on `workspace:*`
|
||||
* entries in the plugin's real devDependencies / peerDependencies.
|
||||
*/
|
||||
async function ensurePluginDeps(pluginDir, pkg) {
|
||||
const bundleable = Object.entries(pkg.dependencies ?? {})
|
||||
.filter(([, v]) => !String(v).startsWith("workspace:"));
|
||||
if (!bundleable.length) return;
|
||||
|
||||
const missing = bundleable.filter(([dep]) =>
|
||||
!fs.existsSync(path.join(pluginDir, "node_modules", dep))
|
||||
);
|
||||
if (!missing.length) return;
|
||||
|
||||
const tmpDir = path.join(os.tmpdir(), `wwv-plugin-deps-${path.basename(pluginDir)}`);
|
||||
fs.mkdirSync(tmpDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(tmpDir, "package.json"), JSON.stringify({
|
||||
name: "tmp", version: "0.0.0",
|
||||
dependencies: Object.fromEntries(bundleable),
|
||||
}));
|
||||
|
||||
try {
|
||||
execSync("npm install --no-fund --ignore-scripts --no-package-lock", {
|
||||
cwd: tmpDir, stdio: "pipe",
|
||||
});
|
||||
const nmSrc = path.join(tmpDir, "node_modules");
|
||||
const nmDest = path.join(pluginDir, "node_modules");
|
||||
fs.mkdirSync(nmDest, { recursive: true });
|
||||
fs.cpSync(nmSrc, nmDest, { recursive: true, force: false, errorOnExist: false });
|
||||
} catch (err) {
|
||||
console.warn(`[sync] ⚠ Could not auto-install deps for ${path.basename(pluginDir)}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @function buildPlugin
|
||||
* @description Invokes the Vite build engine to compile a plugin's source
|
||||
@@ -276,8 +222,6 @@ export async function buildPlugin({ dir, manifest, pkg, pluginDir }) {
|
||||
return "fresh";
|
||||
}
|
||||
|
||||
await ensurePluginDeps(pluginDir, pkg ?? {});
|
||||
|
||||
const entryFile = resolvePluginEntry(pluginDir, manifest, pkg ?? {});
|
||||
|
||||
if (!entryFile) {
|
||||
@@ -285,23 +229,14 @@ export async function buildPlugin({ dir, manifest, pkg, pluginDir }) {
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log(`[sync] 🔨 Building ${manifest.id || dir}...`);
|
||||
try {
|
||||
await build({
|
||||
// Use workspace ROOT so Rolldown resolves node_modules (recharts, gridstack,
|
||||
// etc.) from the workspace install, not the plugin's isolated directory.
|
||||
// Entry and outDir are absolute paths so the output still lands in the
|
||||
// plugin's own dist/ regardless of what root is set to.
|
||||
root: ROOT,
|
||||
root: pluginDir,
|
||||
// Disable auto-loading the plugin's own vite.config.ts — the local
|
||||
// plugins' node_modules may be symlinked to a different repo's SDK
|
||||
// build (worktree scenario), which breaks config loading. The sync
|
||||
// script provides all necessary config inline.
|
||||
configFile: false,
|
||||
// Do NOT copy the repo's public/ dir into each plugin's dist/. With root=ROOT,
|
||||
// Vite would otherwise mirror the entire public/ tree (cesium, plugins-local, etc.)
|
||||
// into every plugin outDir — ~43MB per plugin, ~1.4GB total of pure local-dev bloat.
|
||||
publicDir: false,
|
||||
logLevel: "warn",
|
||||
plugins: [wwvHostRedirectPlugin()],
|
||||
build: {
|
||||
@@ -310,7 +245,7 @@ export async function buildPlugin({ dir, manifest, pkg, pluginDir }) {
|
||||
formats: ["es"],
|
||||
fileName: () => "frontend.mjs",
|
||||
},
|
||||
outDir: path.join(pluginDir, "dist"),
|
||||
outDir: "dist",
|
||||
emptyOutDir: true,
|
||||
rollupOptions: {
|
||||
external: Object.keys(EXTERNAL_GLOBALS),
|
||||
@@ -346,8 +281,6 @@ export async function buildPlugin({ dir, manifest, pkg, pluginDir }) {
|
||||
sourcemap: true,
|
||||
},
|
||||
});
|
||||
// Record config hash so future runs can detect EXTERNAL_GLOBALS changes.
|
||||
fs.writeFileSync(path.join(pluginDir, "dist", ".config-hash"), CONFIG_HASH);
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error(`[sync] ❌ Build failed for ${dir}:`, err.message);
|
||||
@@ -392,23 +325,6 @@ export function syncToPublic({ dir, manifest, pluginDir }, { quiet = false } = {
|
||||
category: manifest.category || "custom",
|
||||
icon: manifest.icon || "Box",
|
||||
entry: `/plugins-local/${publicName}/frontend.mjs`,
|
||||
// Carry localData declarations into the generated manifest so the
|
||||
// server-side LocalDataSource registry can discover them at runtime
|
||||
// without reading raw package.json files (Phase 30, D-02/Area 2).
|
||||
// Security: filter localData to only safe, well-typed entries before
|
||||
// writing to the generated file (T-30-01/03: prevent absolute-URL
|
||||
// SSRF sources and path-traversal entries from propagating).
|
||||
...(manifest.localData ? {
|
||||
localData: manifest.localData.filter(
|
||||
(entry) =>
|
||||
entry !== null &&
|
||||
typeof entry === "object" &&
|
||||
(entry.type === "geojson" || entry.type === "route") &&
|
||||
typeof entry.path === "string" &&
|
||||
entry.path.startsWith("/") &&
|
||||
!entry.path.includes(".."),
|
||||
),
|
||||
} : {}),
|
||||
};
|
||||
|
||||
fs.writeFileSync(
|
||||
@@ -463,7 +379,7 @@ export async function syncAll() {
|
||||
if (plugins.length === 0) {
|
||||
console.log("[sync] No local plugins found.");
|
||||
cleanStale([]);
|
||||
return { built: 0, cached: 0, failed: 0 };
|
||||
return;
|
||||
}
|
||||
|
||||
const concurrency = Math.max(2, Math.min(plugins.length, Math.ceil(os.cpus().length / 2)));
|
||||
@@ -472,20 +388,17 @@ export async function syncAll() {
|
||||
|
||||
let freshCount = 0;
|
||||
let builtCount = 0;
|
||||
let failedCount = 0;
|
||||
await runWithConcurrency(plugins, concurrency, async (plugin) => {
|
||||
const result = await buildPlugin(plugin);
|
||||
if (result === "fresh") freshCount++;
|
||||
else if (result) builtCount++;
|
||||
else failedCount++;
|
||||
if (result) syncToPublic(plugin, { quiet: result === "fresh" });
|
||||
});
|
||||
|
||||
console.log(`[sync] Done in ${((Date.now() - started) / 1000).toFixed(1)}s (${builtCount} built, ${freshCount} cached${failedCount ? `, ${failedCount} failed` : ""})`);
|
||||
console.log(`[sync] Done in ${((Date.now() - started) / 1000).toFixed(1)}s (${builtCount} built, ${freshCount} cached)`);
|
||||
|
||||
const activeIds = plugins.map(p => p.manifest.id || p.dir.replace("wwv-plugin-", ""));
|
||||
cleanStale(activeIds);
|
||||
return { built: builtCount, cached: freshCount, failed: failedCount };
|
||||
}
|
||||
|
||||
// Run directly: node scripts/sync-local-plugins.mjs
|
||||
|
||||
@@ -66,9 +66,8 @@ async function runSync() {
|
||||
: `${changed.slice(0, 3).join(", ")} (+${changed.length - 3} more)`;
|
||||
console.log(`\n[watch] 🔄 Change detected in: ${label}`);
|
||||
try {
|
||||
const stats = await syncAll();
|
||||
const summary = `${stats.built} rebuilt, ${stats.cached} cached${stats.failed ? `, ${stats.failed} failed` : ""}`;
|
||||
console.log(`[watch] ✨ Hot-reload ready (${summary})`);
|
||||
await syncAll();
|
||||
console.log(`[watch] ✨ Hot-reload ready`);
|
||||
} catch (err) {
|
||||
console.error(`[watch] Sync failed:`, err);
|
||||
} finally {
|
||||
@@ -83,14 +82,13 @@ async function runSync() {
|
||||
// Initial sync
|
||||
console.log(`[watch] Starting initial sync...`);
|
||||
isSyncing = true;
|
||||
syncAll().then((stats) => {
|
||||
syncAll().then(() => {
|
||||
isSyncing = false;
|
||||
if (pendingSync) {
|
||||
pendingSync = false;
|
||||
runSync("pending changes").catch(console.error);
|
||||
}
|
||||
const summary = `${stats.built} built, ${stats.cached} cached${stats.failed ? `, ${stats.failed} failed` : ""}`;
|
||||
console.log(`[watch] Initial sync done (${summary}). Watching ${LOCAL_PLUGINS_DIR} for changes...`);
|
||||
console.log(`[watch] Watching ${LOCAL_PLUGINS_DIR} for changes...`);
|
||||
fs.watch(LOCAL_PLUGINS_DIR, { recursive: true }, handleFileChange);
|
||||
}).catch(err => {
|
||||
isSyncing = false;
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Setup script for Claude Code on the web (and any fresh CI/container clone).
|
||||
#
|
||||
# Point your remote environment's "setup script" at this file, e.g.:
|
||||
# bash scripts/web-setup.sh
|
||||
#
|
||||
# It is idempotent and safe to re-run. It resolves the repo root from its own
|
||||
# location, so it works no matter which directory the environment invokes it
|
||||
# from — fixing the `npm error path /home/user/package.json` failure caused by
|
||||
# running a package manager from the wrong working directory.
|
||||
set -euo pipefail
|
||||
|
||||
# Resolve the repo root relative to this script, not the caller's CWD.
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
echo "[web-setup] Repo root: $REPO_ROOT"
|
||||
|
||||
# This is a pnpm monorepo (see pnpm-workspace.yaml). Never use npm/npm ci here.
|
||||
# Corepack ships with Node 20+; activate the pinned pnpm from package.json's
|
||||
# `packageManager` field if pnpm isn't already on PATH.
|
||||
if ! command -v pnpm >/dev/null 2>&1; then
|
||||
echo "[web-setup] pnpm not found on PATH; enabling via corepack"
|
||||
corepack enable
|
||||
corepack prepare [email protected] --activate
|
||||
fi
|
||||
|
||||
echo "[web-setup] Using pnpm $(pnpm -v) / node $(node -v)"
|
||||
|
||||
# Install workspace dependencies. Use `install` (not `--frozen-lockfile`) so the
|
||||
# container's dependency cache is reused across sessions for faster startup.
|
||||
pnpm install
|
||||
|
||||
# Generate the Prisma client so TypeScript, ESLint and Vitest can resolve
|
||||
# @prisma/client types. `prisma generate` reads prisma/schema.prisma only and
|
||||
# does NOT require a live database connection.
|
||||
pnpm exec prisma generate
|
||||
|
||||
echo "[web-setup] Setup complete — dependencies installed and Prisma client generated."
|
||||
@@ -1,91 +0,0 @@
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach
|
||||
} from "vitest";
|
||||
import type { Session } from "next-auth";
|
||||
import { DELETE } from "./route";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
vi.mock("@/lib/auth", () => ({
|
||||
auth: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
userApiKey: {
|
||||
findMany: vi.fn(),
|
||||
count: vi.fn(),
|
||||
create: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
}));
|
||||
|
||||
// NextAuth v5 `auth` is overloaded (middleware wrapper + no-arg session getter).
|
||||
// Narrow to the session-getter signature so vi.mocked resolves the correct overload.
|
||||
const mockAuth = vi.mocked(auth as unknown as () => Promise<Session | null>);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DELETE /api/api-keys/[id] — KEY-03 (revoke)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("DELETE /api/api-keys/[id]", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mockAuth.mockResolvedValue({
|
||||
user: { id: "user-123", email: "[email protected]" },
|
||||
} as Session);
|
||||
});
|
||||
|
||||
it("returns 200 { success: true } when user owns the key (KEY-03)", async () => {
|
||||
vi.mocked(prisma.userApiKey.deleteMany).mockResolvedValue({ count: 1 } as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys/key-id-1");
|
||||
const res = await DELETE(req, { params: Promise.resolve({ id: "key-id-1" }) });
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body).toEqual({ success: true });
|
||||
});
|
||||
|
||||
it("returns 404 { error: 'not_found' } when key belongs to another user (KEY-03)", async () => {
|
||||
// deleteMany returns count: 0 when ownership check fails
|
||||
vi.mocked(prisma.userApiKey.deleteMany).mockResolvedValue({ count: 0 } as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys/foreign-key-id");
|
||||
const res = await DELETE(req, { params: Promise.resolve({ id: "foreign-key-id" }) });
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
expect(body.error).toBe("not_found");
|
||||
});
|
||||
|
||||
it("returns 401 when no session (KEY-03)", async () => {
|
||||
mockAuth.mockResolvedValue(null);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys/key-id-1");
|
||||
const res = await DELETE(req, { params: Promise.resolve({ id: "key-id-1" }) });
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("deleteMany is called with where clause containing both id and userId (ownership enforcement)", async () => {
|
||||
vi.mocked(prisma.userApiKey.deleteMany).mockResolvedValue({ count: 1 } as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys/key-id-1");
|
||||
await DELETE(req, { params: Promise.resolve({ id: "key-id-1" }) });
|
||||
|
||||
expect(vi.mocked(prisma.userApiKey.deleteMany)).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
id: "key-id-1",
|
||||
userId: "user-123",
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import { apiKeyManagementLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DELETE /api/api-keys/[id] — KEY-03 (ownership-scoped revoke, hard delete)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const { id } = await params;
|
||||
if (isDemo) {
|
||||
return NextResponse.json({ error: "Not available in demo edition" }, { status: 403 });
|
||||
}
|
||||
|
||||
const limited = apiKeyManagementLimiter.check(getClientIp(request));
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
// Atomic ownership-scoped delete — T-16-06 (BOLA prevention).
|
||||
// Using deleteMany (not delete) so a non-matching id returns count 0
|
||||
// instead of throwing a NotFound error, eliminating TOCTOU.
|
||||
const deleted = await prisma.userApiKey.deleteMany({
|
||||
where: { id, userId: session.user.id },
|
||||
});
|
||||
|
||||
if (deleted.count === 0) {
|
||||
return NextResponse.json({ error: "not_found" }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (err) {
|
||||
console.error("[api-keys] DELETE error:", err);
|
||||
return NextResponse.json({ error: "Failed to revoke API key" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach
|
||||
} from "vitest";
|
||||
import type { Session } from "next-auth";
|
||||
import { GET, POST } from "./route";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { generateApiKey } from "@/lib/apiKeyAuth";
|
||||
|
||||
vi.mock("@/lib/auth", () => ({
|
||||
auth: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
userApiKey: {
|
||||
findMany: vi.fn(),
|
||||
count: vi.fn(),
|
||||
create: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
// $transaction executes the callback inline so tests don't need a real DB
|
||||
$transaction: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
generateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
// Bypass rate limiting in all route tests — the limiter module has its own tests
|
||||
vi.mock("@/lib/rateLimiters", () => ({
|
||||
apiKeyManagementLimiter: { check: vi.fn().mockReturnValue(null) },
|
||||
mcpLimiter: { check: vi.fn().mockReturnValue(null) },
|
||||
getClientIp: vi.fn().mockReturnValue("127.0.0.1"),
|
||||
}));
|
||||
|
||||
// NextAuth v5 `auth` is overloaded (middleware wrapper + no-arg session getter).
|
||||
// Narrow to the session-getter signature so vi.mocked resolves the correct overload.
|
||||
const mockAuth = vi.mocked(auth as unknown as () => Promise<Session | null>);
|
||||
|
||||
// Helper: make $transaction execute its callback synchronously with the mock prisma.
|
||||
// Must be called in beforeEach after vi.resetAllMocks() clears the module-level mock.
|
||||
// Cast to never to bypass Prisma's complex overloaded $transaction signature.
|
||||
function wireTransaction(): void {
|
||||
vi.mocked(prisma.$transaction).mockImplementation(
|
||||
((fn: (tx: typeof prisma) => unknown) => fn(prisma)) as never,
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GET /api/api-keys — KEY-03 (list)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/api-keys", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
wireTransaction();
|
||||
mockAuth.mockResolvedValue({
|
||||
user: { id: "user-123", email: "[email protected]" },
|
||||
} as Session);
|
||||
});
|
||||
|
||||
it("returns 200 with { keys } for authenticated user (KEY-03)", async () => {
|
||||
const mockKeys = [
|
||||
{ id: "key-1", name: "My Key", prefix: "wwv_ABCDEFGH", createdAt: new Date(), lastUsedAt: null },
|
||||
];
|
||||
vi.mocked(prisma.userApiKey.findMany).mockResolvedValue(mockKeys as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys");
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body).toHaveProperty("keys");
|
||||
expect(Array.isArray(body.keys)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns 401 when no session (KEY-03)", async () => {
|
||||
mockAuth.mockResolvedValue(null);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys");
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(body).toHaveProperty("error");
|
||||
// Must NOT include a `keys` field — callers that do `data.keys ?? []` without
|
||||
// checking r.ok would silently show an empty list instead of an auth error.
|
||||
expect(body).not.toHaveProperty("keys");
|
||||
});
|
||||
|
||||
it("response never contains hashedSecret field (security invariant)", async () => {
|
||||
const mockKeys = [
|
||||
{
|
||||
id: "key-1",
|
||||
name: "My Key",
|
||||
prefix: "wwv_ABCDEFGH",
|
||||
createdAt: new Date(),
|
||||
lastUsedAt: null,
|
||||
// hashedSecret deliberately absent from select projection
|
||||
},
|
||||
];
|
||||
vi.mocked(prisma.userApiKey.findMany).mockResolvedValue(mockKeys as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys");
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
// The route must use a select projection — no hashedSecret in response
|
||||
if (Array.isArray(body.keys)) {
|
||||
body.keys.forEach((k: Record<string, unknown>) => {
|
||||
expect(k).not.toHaveProperty("hashedSecret");
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST /api/api-keys — KEY-01, KEY-02, KEY-04 (create)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("POST /api/api-keys", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
wireTransaction();
|
||||
mockAuth.mockResolvedValue({
|
||||
user: { id: "user-123", email: "[email protected]" },
|
||||
} as Session);
|
||||
});
|
||||
|
||||
it("returns 422 with error 'max_keys_reached' when user already has 3 keys (KEY-04)", async () => {
|
||||
vi.mocked(prisma.userApiKey.count).mockResolvedValue(3 as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "Fourth Key" }),
|
||||
});
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(422);
|
||||
expect(body.error).toBe("max_keys_reached");
|
||||
});
|
||||
|
||||
it("calls generateApiKey and returns 201 with fullToken when under limit (KEY-01, KEY-04)", async () => {
|
||||
vi.mocked(prisma.userApiKey.count).mockResolvedValue(0 as never);
|
||||
vi.mocked(generateApiKey).mockReturnValue({
|
||||
prefix: "wwv_TESTPFX1",
|
||||
secret: "testsecret_43chars_base64url_value_here123",
|
||||
hashedSecret: "a".repeat(64),
|
||||
fullToken: "wwv_TESTPFX1.testsecret_43chars_base64url_value_here123",
|
||||
});
|
||||
vi.mocked(prisma.userApiKey.create).mockResolvedValue({
|
||||
id: "new-key-id",
|
||||
name: "My API Key",
|
||||
createdAt: new Date("2026-01-01"),
|
||||
} as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "My API Key" }),
|
||||
});
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(body.key).toHaveProperty("fullToken");
|
||||
expect(body.key.fullToken).toBe("wwv_TESTPFX1.testsecret_43chars_base64url_value_here123");
|
||||
});
|
||||
|
||||
it("returns 401 when no session (KEY-03)", async () => {
|
||||
mockAuth.mockResolvedValue(null);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns 422 with error 'name_too_long' when name exceeds 64 chars (M2)", async () => {
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "a".repeat(65) }),
|
||||
});
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(422);
|
||||
expect(body.error).toBe("name_too_long");
|
||||
});
|
||||
|
||||
it("accepts name exactly at the 64-char boundary (M2)", async () => {
|
||||
vi.mocked(prisma.userApiKey.count).mockResolvedValue(0 as never);
|
||||
vi.mocked(generateApiKey).mockReturnValue({
|
||||
prefix: "wwv_TESTPFX2",
|
||||
secret: "testsecret_43chars_base64url_value_here123",
|
||||
hashedSecret: "b".repeat(64),
|
||||
fullToken: "wwv_TESTPFX2.testsecret_43chars_base64url_value_here123",
|
||||
});
|
||||
vi.mocked(prisma.userApiKey.create).mockResolvedValue({
|
||||
id: "new-key-id-2",
|
||||
name: "a".repeat(64),
|
||||
createdAt: new Date("2026-01-01"),
|
||||
} as never);
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "a".repeat(64) }),
|
||||
});
|
||||
const res = await POST(req);
|
||||
expect(res.status).toBe(201);
|
||||
});
|
||||
|
||||
it("returns 401 with session_user_not_found when prisma throws P2003 on user_api_keys_userId_fkey", async () => {
|
||||
// Simulates a stale JWT whose user id has no row in `users` (e.g. after a DB reset).
|
||||
vi.mocked(prisma.userApiKey.count).mockResolvedValue(0 as never);
|
||||
const fkError = Object.assign(new Error("Foreign key constraint failed"), {
|
||||
code: "P2003",
|
||||
meta: { field_name: "user_api_keys_userId_fkey" },
|
||||
});
|
||||
vi.mocked(prisma.userApiKey.create).mockRejectedValue(fkError);
|
||||
vi.mocked(generateApiKey).mockReturnValue({
|
||||
prefix: "wwv_TESTPFX3",
|
||||
secret: "testsecret_43chars_base64url_value_here123",
|
||||
hashedSecret: "c".repeat(64),
|
||||
fullToken: "wwv_TESTPFX3.testsecret_43chars_base64url_value_here123",
|
||||
});
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "Stale key" }),
|
||||
});
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(body.error).toBe("session_user_not_found");
|
||||
});
|
||||
|
||||
it("returns 500 when prisma throws P2003 on a different FK constraint", async () => {
|
||||
// P2003 on a different constraint must NOT be mistaken for the user-not-found case.
|
||||
vi.mocked(prisma.userApiKey.count).mockResolvedValue(0 as never);
|
||||
const otherFkError = Object.assign(new Error("Foreign key constraint failed"), {
|
||||
code: "P2003",
|
||||
meta: { field_name: "some_other_fkey" },
|
||||
});
|
||||
vi.mocked(prisma.userApiKey.create).mockRejectedValue(otherFkError);
|
||||
vi.mocked(generateApiKey).mockReturnValue({
|
||||
prefix: "wwv_TESTPFX4",
|
||||
secret: "testsecret_43chars_base64url_value_here123",
|
||||
hashedSecret: "d".repeat(64),
|
||||
fullToken: "wwv_TESTPFX4.testsecret_43chars_base64url_value_here123",
|
||||
});
|
||||
|
||||
const req = new Request("http://localhost/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: "Other error" }),
|
||||
});
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(body.error).not.toBe("session_user_not_found");
|
||||
});
|
||||
});
|
||||
@@ -1,174 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import { generateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { apiKeyManagementLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
|
||||
const MAX_KEYS = 3;
|
||||
const MAX_NAME_LENGTH = 64;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GET /api/api-keys — KEY-03 (list user's keys, secrets never returned)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function GET(request: Request) {
|
||||
if (isDemo) {
|
||||
return NextResponse.json({ error: "Not available in demo edition" }, { status: 403 });
|
||||
}
|
||||
|
||||
const limited = apiKeyManagementLimiter.check(getClientIp(request));
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const keys = await prisma.userApiKey.findMany({
|
||||
where: { userId: session.user.id },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
prefix: true,
|
||||
createdAt: true,
|
||||
lastUsedAt: true,
|
||||
// hashedSecret intentionally excluded — never returned to client
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
|
||||
return NextResponse.json({ keys });
|
||||
} catch (err) {
|
||||
console.error("[api-keys] GET error:", err);
|
||||
return NextResponse.json({ error: "Failed to fetch API keys" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST /api/api-keys — KEY-01 (reveal-once), KEY-04 (max-3)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (isDemo) {
|
||||
return NextResponse.json({ error: "Not available in demo edition" }, { status: 403 });
|
||||
}
|
||||
|
||||
const limited = apiKeyManagementLimiter.check(getClientIp(request));
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => ({})) as { name?: unknown };
|
||||
const rawName = typeof body.name === "string" ? body.name.trim() : "";
|
||||
|
||||
// M2: reject names exceeding the server-side length limit
|
||||
if (rawName.length > MAX_NAME_LENGTH) {
|
||||
return NextResponse.json(
|
||||
{ error: "name_too_long", message: `Name must be ${MAX_NAME_LENGTH} characters or fewer` },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const created = await createKeyInTransaction(session.user.id, rawName);
|
||||
if (!created) {
|
||||
return NextResponse.json(
|
||||
{ error: "max_keys_reached", message: "Maximum of 3 API keys allowed per user" },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ key: created }, { status: 201 });
|
||||
} catch (err) {
|
||||
// P2003 on the userId FK means the session refers to a user that has
|
||||
// no row in `users` (e.g. a stale JWT after a DB reset). Signal the
|
||||
// client to re-authenticate rather than surfacing an opaque 500.
|
||||
const isPrismaP2003OnUserFk =
|
||||
typeof err === "object" &&
|
||||
err !== null &&
|
||||
"code" in err &&
|
||||
(err as { code: string }).code === "P2003" &&
|
||||
"meta" in err &&
|
||||
typeof (err as { meta: unknown }).meta === "object" &&
|
||||
(err as { meta: { field_name?: string } }).meta !== null &&
|
||||
(err as { meta: { field_name?: string } }).meta.field_name === "user_api_keys_userId_fkey";
|
||||
|
||||
if (isPrismaP2003OnUserFk) {
|
||||
console.error("[api-keys] POST: session user not found in DB (id redacted)");
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "session_user_not_found",
|
||||
message: "Your session refers to a user that no longer exists. Please sign in again.",
|
||||
},
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
console.error("[api-keys] POST error:", err);
|
||||
return NextResponse.json({ error: "Failed to create API key" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal helper — M1: wraps count + create in a Serializable transaction
|
||||
// so concurrent POSTs cannot exceed the key limit (TOCTOU prevention).
|
||||
// Returns null when the max is already reached.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function createKeyInTransaction(
|
||||
userId: string,
|
||||
rawName: string,
|
||||
): Promise<{ id: string; name: string; createdAt: Date; fullToken: string } | null> {
|
||||
// $transaction with isolationLevel Serializable prevents concurrent
|
||||
// inserts from both reading count < 3 and both succeeding (TOCTOU fix).
|
||||
return prisma.$transaction(async (tx) => {
|
||||
const count = await tx.userApiKey.count({ where: { userId } });
|
||||
if (count >= MAX_KEYS) return null;
|
||||
|
||||
const name = rawName || `API Key ${count + 1}`;
|
||||
return createKeyWithRetry(userId, name, tx);
|
||||
}, { isolationLevel: "Serializable" });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal helper — generates a key + creates the DB row, retries once on
|
||||
// P2002 prefix collision (extremely rare but possible with 8 random chars).
|
||||
// fullToken is returned here (reveal-once) and never persisted.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function createKeyWithRetry(
|
||||
userId: string,
|
||||
name: string,
|
||||
tx: Parameters<Parameters<typeof prisma.$transaction>[0]>[0],
|
||||
): Promise<{ id: string; name: string; createdAt: Date; fullToken: string }> {
|
||||
const { prefix, hashedSecret, fullToken } = generateApiKey();
|
||||
|
||||
try {
|
||||
const row = await tx.userApiKey.create({
|
||||
data: { userId, prefix, hashedSecret, name },
|
||||
select: { id: true, name: true, createdAt: true },
|
||||
});
|
||||
return { ...row, fullToken };
|
||||
} catch (err: unknown) {
|
||||
// Prisma unique-constraint violation (P2002) on prefix — retry once
|
||||
const isPrismaP2002 =
|
||||
typeof err === "object" &&
|
||||
err !== null &&
|
||||
"code" in err &&
|
||||
(err as { code: string }).code === "P2002";
|
||||
|
||||
if (!isPrismaP2002) throw err;
|
||||
|
||||
const retry = generateApiKey();
|
||||
const row = await tx.userApiKey.create({
|
||||
data: { userId, prefix: retry.prefix, hashedSecret: retry.hashedSecret, name },
|
||||
select: { id: true, name: true, createdAt: true },
|
||||
});
|
||||
return { ...row, fullToken: retry.fullToken };
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth, signOut } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { isCloud } from "@/core/edition";
|
||||
|
||||
/**
|
||||
* POST /api/auth/revoke: "sign out everywhere".
|
||||
*
|
||||
* Increments the authenticated user's `sessionVersion`, which invalidates every
|
||||
* existing JWT issued for that user: the auth `jwt` callback compares each
|
||||
* token's embedded version against the DB on its next use and rejects stale
|
||||
* ones. Also clears the caller's own session cookie.
|
||||
*
|
||||
* Requires an authenticated session. Same-origin only in practice: the session
|
||||
* cookie is `sameSite=lax`, so a cross-site POST carries no credentials.
|
||||
*/
|
||||
export async function POST() {
|
||||
const session = await auth();
|
||||
const userId = session?.user?.id;
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Cloud identities are managed by Supabase; there is no local users row to bump.
|
||||
if (!isCloud) {
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { sessionVersion: { increment: 1 } },
|
||||
});
|
||||
}
|
||||
|
||||
await signOut({ redirect: false });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -7,18 +7,6 @@ import { safeFetch } from "@/lib/security/ssrf";
|
||||
|
||||
const MAX_IFRAME_DURATION_MS = 10 * 1000; // 10 seconds timeout for HTML
|
||||
|
||||
/**
|
||||
* Escape a string for safe inclusion in an HTML attribute value.
|
||||
*/
|
||||
function escapeHtmlAttr(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">");
|
||||
}
|
||||
|
||||
/**
|
||||
* Proxy for iframe HTML pages.
|
||||
* Fetches the target HTML, strips X-Frame-Options and CSP, and injects a <base href="...">
|
||||
@@ -74,8 +62,7 @@ export async function GET(req: NextRequest) {
|
||||
let html = await upstream.text();
|
||||
|
||||
// Inject <base href="..."> right after <head> or at the very beginning of the document
|
||||
const escapedUrl = escapeHtmlAttr(targetUrl);
|
||||
const baseTag = `<base href="${escapedUrl}">\n`;
|
||||
const baseTag = `<base href="${targetUrl}">\n`;
|
||||
if (html.includes("<head>")) {
|
||||
html = html.replace("<head>", `<head>\n${baseTag}`);
|
||||
} else if (html.includes("<HEAD>")) {
|
||||
|
||||
@@ -1,253 +0,0 @@
|
||||
/**
|
||||
* RED test scaffold for GET /api/globe/commands (Phase 19a Wave 0).
|
||||
*
|
||||
* These tests INTENTIONALLY FAIL because route.ts does not exist yet.
|
||||
* They lock the following contracts:
|
||||
*
|
||||
* CMD-ROUTE-01 No auth -> 401
|
||||
* CMD-ROUTE-02 NextAuth session -> 200 with { commands: [...] } from drainGlobeCommands
|
||||
* CMD-ROUTE-03 Bearer API key fallback when no session -> 200
|
||||
* CMD-ROUTE-04 userId comes from auth result, NEVER from the query string
|
||||
* CMD-ROUTE-05 sessionId taken from ?sessionId query param, scoped to that tab
|
||||
* CMD-ROUTE-06 missing or malformed sessionId -> 400
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import type { Session } from "next-auth";
|
||||
import { GET } from "./route";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { drainGlobeCommands } from "@/lib/globeCommandQueue";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Top-level mocks
|
||||
// (global setup.ts already mocks @/lib/auth returning null — we override below)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/globeCommandQueue", () => ({
|
||||
drainGlobeCommands: vi.fn(),
|
||||
}));
|
||||
|
||||
// Bypass rate limiting for route unit tests
|
||||
vi.mock("@/lib/rateLimiters", () => ({
|
||||
globeCommandsLimiter: { check: vi.fn().mockReturnValue(null) },
|
||||
getClientIp: vi.fn().mockReturnValue("127.0.0.1"),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Typed mock helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const mockGetSession = vi.mocked(auth as unknown as () => Promise<Session | null>);
|
||||
const mockAuthApiKey = vi.mocked(authenticateApiKey);
|
||||
const mockDrain = vi.mocked(drainGlobeCommands);
|
||||
|
||||
function makeRequest(sessionId?: string, bearer?: string): Request {
|
||||
const url = sessionId
|
||||
? `http://localhost/api/globe/commands?sessionId=${sessionId}`
|
||||
: "http://localhost/api/globe/commands";
|
||||
const headers: Record<string, string> = {};
|
||||
if (bearer) headers["authorization"] = `Bearer ${bearer}`;
|
||||
return new Request(url, { method: "GET", headers });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test setup
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mockGetSession.mockResolvedValue(null);
|
||||
mockAuthApiKey.mockResolvedValue(null);
|
||||
mockDrain.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
// Valid UUID-format sessionIds used throughout these tests
|
||||
const SESS_1 = "a0000000-0000-0000-0000-000000000001";
|
||||
const SESS_ABC = "b0000000-0000-0000-0000-0000000000ab";
|
||||
const SESS_TAB = "c0000000-0000-0000-0000-00000000000c";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CMD-ROUTE-01: unauthenticated -> 401
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands — 401 when unauthenticated (CMD-ROUTE-01)", () => {
|
||||
it("returns 401 when neither session nor Bearer key is present", async () => {
|
||||
const req = makeRequest(SESS_1);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockDrain).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 401 when session is null and api key auth returns null", async () => {
|
||||
mockGetSession.mockResolvedValue(null);
|
||||
mockAuthApiKey.mockResolvedValue(null);
|
||||
|
||||
const req = makeRequest(SESS_1, "invalid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CMD-ROUTE-02: NextAuth session path -> 200 + { commands }
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands — NextAuth session (CMD-ROUTE-02)", () => {
|
||||
beforeEach(() => {
|
||||
mockGetSession.mockResolvedValue({
|
||||
user: { id: "u1", name: "Test User", email: "[email protected]" },
|
||||
expires: "2099-01-01",
|
||||
} as Session);
|
||||
mockDrain.mockResolvedValue([
|
||||
{ type: "pan", lat: 1, lon: 2, alt: 3 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns 200", async () => {
|
||||
const req = makeRequest(SESS_ABC);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("returns { commands: [...] } from drainGlobeCommands", async () => {
|
||||
const req = makeRequest(SESS_ABC);
|
||||
const res = await GET(req);
|
||||
const body = await res.json() as { commands: unknown[] };
|
||||
|
||||
expect(body).toHaveProperty("commands");
|
||||
expect(Array.isArray(body.commands)).toBe(true);
|
||||
expect(body.commands).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("calls drainGlobeCommands with userId from session and sessionId from query string", async () => {
|
||||
const req = makeRequest(SESS_ABC);
|
||||
await GET(req);
|
||||
|
||||
expect(mockDrain).toHaveBeenCalledWith("u1", SESS_ABC);
|
||||
});
|
||||
|
||||
it("returns { commands: [] } when queue is empty", async () => {
|
||||
mockDrain.mockResolvedValue([]);
|
||||
const req = makeRequest(SESS_ABC);
|
||||
const res = await GET(req);
|
||||
const body = await res.json() as { commands: unknown[] };
|
||||
|
||||
expect(body.commands).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CMD-ROUTE-03: Bearer API key fallback
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands — Bearer fallback (CMD-ROUTE-03)", () => {
|
||||
beforeEach(() => {
|
||||
mockGetSession.mockResolvedValue(null);
|
||||
mockAuthApiKey.mockResolvedValue({ userId: "api-user", keyId: "key-99" });
|
||||
mockDrain.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("returns 200 when no session but valid Bearer token", async () => {
|
||||
const req = makeRequest(SESS_1, "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("calls drainGlobeCommands with userId from API key auth result", async () => {
|
||||
const req = makeRequest(SESS_1, "wwv_valid.token");
|
||||
await GET(req);
|
||||
|
||||
expect(mockDrain).toHaveBeenCalledWith("api-user", SESS_1);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CMD-ROUTE-04: userId always from auth, never from query string
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands — userId source invariant (CMD-ROUTE-04)", () => {
|
||||
it("uses the session userId, not any userId in the query string", async () => {
|
||||
mockGetSession.mockResolvedValue({
|
||||
user: { id: "real-user", name: "Alice", email: "[email protected]" },
|
||||
expires: "2099-01-01",
|
||||
} as Session);
|
||||
mockDrain.mockResolvedValue([]);
|
||||
|
||||
// The URL includes a userId query param that should be ignored
|
||||
const req = new Request(
|
||||
`http://localhost/api/globe/commands?sessionId=${SESS_1}&userId=injected-user`,
|
||||
{ method: "GET" }
|
||||
);
|
||||
await GET(req);
|
||||
|
||||
const [calledUserId] = mockDrain.mock.calls[0] as [string, string];
|
||||
expect(calledUserId).toBe("real-user");
|
||||
expect(calledUserId).not.toBe("injected-user");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CMD-ROUTE-05: sessionId from query string
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands — sessionId from query (CMD-ROUTE-05)", () => {
|
||||
it("passes the sessionId query param to drainGlobeCommands", async () => {
|
||||
mockGetSession.mockResolvedValue({
|
||||
user: { id: "u1", name: "Test", email: "[email protected]" },
|
||||
expires: "2099-01-01",
|
||||
} as Session);
|
||||
mockDrain.mockResolvedValue([]);
|
||||
|
||||
const req = makeRequest(SESS_TAB);
|
||||
await GET(req);
|
||||
|
||||
const [, calledSessionId] = mockDrain.mock.calls[0] as [string, string];
|
||||
expect(calledSessionId).toBe(SESS_TAB);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CMD-ROUTE-06: missing or malformed sessionId -> 400
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands — invalid sessionId -> 400 (CMD-ROUTE-06)", () => {
|
||||
// Use the API key auth path to avoid the NextMiddleware typing quirk on mockGetSession.
|
||||
// userId still resolves correctly; the 400 is about sessionId, not identity.
|
||||
beforeEach(() => {
|
||||
mockAuthApiKey.mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
mockDrain.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("returns 400 when sessionId is missing", async () => {
|
||||
const req = makeRequest(undefined, "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockDrain).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 400 when sessionId is not UUID format", async () => {
|
||||
const req = makeRequest("not-a-uuid", "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockDrain).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns { error: 'invalid sessionId' } in the body", async () => {
|
||||
const req = makeRequest("bad-id", "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
const body = await res.json() as { error: string };
|
||||
|
||||
expect(body.error).toBe("invalid sessionId");
|
||||
});
|
||||
});
|
||||
@@ -1,62 +0,0 @@
|
||||
/**
|
||||
* GET /api/globe/commands?sessionId=<uuid>
|
||||
*
|
||||
* Browser poll endpoint for the Globe Command System (Phase 19a).
|
||||
* The browser calls this on an interval (~1500ms) to drain any commands
|
||||
* queued by the MCP agent via registerGlobeCommandTools.
|
||||
*
|
||||
* Auth (R-2 dual-auth, mirrors POST /api/globe/state):
|
||||
* Primary: NextAuth session cookie (browser path)
|
||||
* Fallback: Bearer API key (MCP / programmatic path)
|
||||
* userId comes ONLY from the resolved auth result -- never from the query string.
|
||||
*
|
||||
* sessionId comes from the ?sessionId query param (scopes the tab, not identity).
|
||||
*/
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { drainGlobeCommands } from "@/lib/globeCommandQueue";
|
||||
import { globeCommandsLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { resolveEdition } from "@/core/edition";
|
||||
|
||||
const SESSION_ID_RE = /^[0-9a-f-]{36}$/i;
|
||||
|
||||
export async function GET(request: Request): Promise<NextResponse> {
|
||||
const limited = globeCommandsLimiter.check(getClientIp(request));
|
||||
if (limited) return limited as NextResponse;
|
||||
|
||||
const currentEdition = resolveEdition(process.env.NEXT_PUBLIC_WWV_EDITION);
|
||||
if (currentEdition === "demo") {
|
||||
return NextResponse.json({ error: "Demo mode" }, { status: 403 });
|
||||
}
|
||||
|
||||
// R-2: NextAuth session PRIMARY, Bearer API key FALLBACK.
|
||||
// userId is resolved exclusively from the auth result -- never from the URL.
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const sessionId = url.searchParams.get("sessionId") ?? "";
|
||||
|
||||
if (!sessionId || !SESSION_ID_RE.test(sessionId)) {
|
||||
return NextResponse.json({ error: "invalid sessionId" }, { status: 400 });
|
||||
}
|
||||
|
||||
const commands = await drainGlobeCommands(userId, sessionId);
|
||||
|
||||
return NextResponse.json({ commands });
|
||||
}
|
||||
@@ -1,304 +0,0 @@
|
||||
/**
|
||||
* RED tests for GET /api/globe/commands/stream (Phase 19b Wave 0).
|
||||
*
|
||||
* These tests lock the SSE streaming route contract. The route file does not
|
||||
* exist yet -- the import below will fail with module-not-found (correct RED state).
|
||||
*
|
||||
* SSE-01 No auth -> 401
|
||||
* SSE-02 Demo edition -> 403 (gate fires BEFORE auth)
|
||||
* SSE-03 Invalid sessionId format -> 400
|
||||
* SSE-04 Missing sessionId -> 400
|
||||
* SSE-05 Valid auth + valid sessionId -> 200 with SSE headers
|
||||
* SSE-06 Commands from drainGlobeCommands appear as SSE data events
|
||||
* SSE-07 Keepalive comment ':keepalive' sent approximately every 15 seconds
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import type { Session } from "next-auth";
|
||||
|
||||
// This import will fail (RED) until Wave 1 creates the route implementation.
|
||||
import { GET } from "./route";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hoisted mock functions
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const {
|
||||
mockGetSession,
|
||||
mockAuthApiKey,
|
||||
mockDrain,
|
||||
mockStreamCheck,
|
||||
mockGetClientIp,
|
||||
} = vi.hoisted(() => ({
|
||||
mockGetSession: vi.fn<() => Promise<Session | null>>(),
|
||||
mockAuthApiKey: vi.fn(),
|
||||
mockDrain: vi.fn(),
|
||||
mockStreamCheck: vi.fn(),
|
||||
mockGetClientIp: vi.fn(),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock("@/lib/auth", () => ({
|
||||
auth: mockGetSession,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: mockAuthApiKey,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/globeCommandQueue", () => ({
|
||||
drainGlobeCommands: mockDrain,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/rateLimiters", () => ({
|
||||
globeCommandsStreamLimiter: { check: mockStreamCheck },
|
||||
getClientIp: mockGetClientIp,
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const VALID_SESSION_ID = "a0000000-0000-0000-0000-000000000001";
|
||||
|
||||
function makeRequest(sessionId?: string, bearer?: string): Request {
|
||||
const url = sessionId
|
||||
? `http://localhost/api/globe/commands/stream?sessionId=${sessionId}`
|
||||
: "http://localhost/api/globe/commands/stream";
|
||||
const headers: Record<string, string> = {};
|
||||
if (bearer) headers["authorization"] = `Bearer ${bearer}`;
|
||||
return new Request(url, { method: "GET", headers });
|
||||
}
|
||||
|
||||
/** Reads all available bytes from a ReadableStream within maxMs. */
|
||||
async function collectStreamChunks(response: Response, maxMs = 100): Promise<string> {
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) return "";
|
||||
const decoder = new TextDecoder();
|
||||
let result = "";
|
||||
const deadline = Date.now() + maxMs;
|
||||
try {
|
||||
while (Date.now() < deadline) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (value) result += decoder.decode(value, { stream: true });
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Setup
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mockGetSession.mockResolvedValue(null);
|
||||
mockAuthApiKey.mockResolvedValue(null);
|
||||
mockDrain.mockResolvedValue([]);
|
||||
mockStreamCheck.mockReturnValue(null); // not rate-limited
|
||||
mockGetClientIp.mockReturnValue("127.0.0.1");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-01: no auth -> 401
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- 401 when unauthenticated (SSE-01)", () => {
|
||||
it("returns 401 when neither session nor Bearer key is present", async () => {
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockDrain).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 401 when session is null and apiKey auth returns null", async () => {
|
||||
mockGetSession.mockResolvedValue(null);
|
||||
mockAuthApiKey.mockResolvedValue(null);
|
||||
|
||||
const req = makeRequest(VALID_SESSION_ID, "invalid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-02: demo edition -> 403 (BEFORE auth)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- 403 in demo edition (SSE-02)", () => {
|
||||
it("returns 403 when edition is demo, before attempting auth", async () => {
|
||||
// The route must check isDemo first -- mockGetSession should NOT be called.
|
||||
vi.stubEnv("NEXT_PUBLIC_WWV_EDITION", "demo");
|
||||
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
// Auth must NOT have been called -- demo gate is pre-auth
|
||||
expect(mockGetSession).not.toHaveBeenCalled();
|
||||
expect(mockAuthApiKey).not.toHaveBeenCalled();
|
||||
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-03: invalid sessionId format -> 400
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- 400 for invalid sessionId (SSE-03)", () => {
|
||||
beforeEach(() => {
|
||||
mockAuthApiKey.mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
});
|
||||
|
||||
it("returns 400 when sessionId is not UUID format", async () => {
|
||||
const req = makeRequest("not-a-uuid", "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockDrain).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns { error: 'invalid sessionId' } in the body", async () => {
|
||||
const req = makeRequest("bad-id", "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
const body = await res.json() as { error: string };
|
||||
|
||||
expect(body.error).toBe("invalid sessionId");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-04: missing sessionId -> 400
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- 400 for missing sessionId (SSE-04)", () => {
|
||||
it("returns 400 when sessionId query param is absent", async () => {
|
||||
mockAuthApiKey.mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
|
||||
const req = makeRequest(undefined, "wwv_valid.token");
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockDrain).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-05: valid auth + valid sessionId -> 200 with SSE headers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- 200 with SSE headers (SSE-05)", () => {
|
||||
beforeEach(() => {
|
||||
mockGetSession.mockResolvedValue({
|
||||
user: { id: "u1", name: "Test User", email: "[email protected]" },
|
||||
expires: "2099-01-01",
|
||||
} as Session);
|
||||
mockDrain.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("returns 200", async () => {
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("sets Content-Type: text/event-stream", async () => {
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.headers.get("Content-Type")).toContain("text/event-stream");
|
||||
});
|
||||
|
||||
it("sets Cache-Control: no-cache", async () => {
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.headers.get("Cache-Control")).toBe("no-cache");
|
||||
});
|
||||
|
||||
it("sets X-Accel-Buffering: no (disables nginx buffering)", async () => {
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.headers.get("X-Accel-Buffering")).toBe("no");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-06: commands from drainGlobeCommands appear as SSE data events
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- commands pushed as SSE events (SSE-06)", () => {
|
||||
it("includes command JSON as a 'data: ...' SSE event line", async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
mockGetSession.mockResolvedValue({
|
||||
user: { id: "u1", name: "Test User", email: "[email protected]" },
|
||||
expires: "2099-01-01",
|
||||
} as Session);
|
||||
|
||||
// First call returns a command; subsequent calls return empty
|
||||
mockDrain
|
||||
.mockResolvedValueOnce([{ type: "pan", lat: 1, lon: 2, alt: 3 }])
|
||||
.mockResolvedValue([]);
|
||||
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
// Advance time slightly so the first poll loop iteration executes
|
||||
await vi.runAllTimersAsync();
|
||||
|
||||
const text = await collectStreamChunks(res, 50);
|
||||
|
||||
// SSE data line must be present
|
||||
expect(text).toContain("data: ");
|
||||
// Must end event with double newline (SSE spec)
|
||||
expect(text).toContain("\n\n");
|
||||
// The JSON payload must contain the command type
|
||||
expect(text).toContain('"pan"');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-07: keepalive comment sent every ~15 seconds
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/globe/commands/stream -- keepalive comment every 15s (SSE-07)", () => {
|
||||
it("includes ':keepalive' comment after 16 seconds", async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
mockGetSession.mockResolvedValue({
|
||||
user: { id: "u1", name: "Test User", email: "[email protected]" },
|
||||
expires: "2099-01-01",
|
||||
} as Session);
|
||||
mockDrain.mockResolvedValue([]);
|
||||
|
||||
const req = makeRequest(VALID_SESSION_ID);
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
// Advance past one keepalive interval (15s)
|
||||
await vi.advanceTimersByTimeAsync(16_000);
|
||||
|
||||
const text = await collectStreamChunks(res, 50);
|
||||
|
||||
expect(text).toContain(":keepalive");
|
||||
});
|
||||
});
|
||||
@@ -1,124 +0,0 @@
|
||||
/**
|
||||
* GET /api/globe/commands/stream?sessionId=<uuid>
|
||||
*
|
||||
* SSE push transport for the Globe Command System (Phase 19b).
|
||||
* Replaces the browser's 1500ms poll loop with a persistent EventSource
|
||||
* connection, cutting command latency from ~1500ms to near-real-time.
|
||||
*
|
||||
* Auth (R-2 dual-auth, mirrors GET /api/globe/commands):
|
||||
* Primary: NextAuth session cookie (browser path)
|
||||
* Fallback: Bearer API key (MCP / programmatic path)
|
||||
* userId comes ONLY from the resolved auth result -- never from the URL.
|
||||
*
|
||||
* Gate order (MUST NOT be reordered):
|
||||
* 1. Rate limiter (DoS defense before any IO)
|
||||
* 2. Demo edition guard (pre-auth, no DB hit on demo)
|
||||
* 3. Dual-auth (session or API key)
|
||||
* 4. UUID sessionId guard (scopes the Redis queue key)
|
||||
*/
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { drainGlobeCommands } from "@/lib/globeCommandQueue";
|
||||
import { globeCommandsStreamLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { resolveEdition } from "@/core/edition";
|
||||
|
||||
const SESSION_ID_RE = /^[0-9a-f-]{36}$/i;
|
||||
const POLL_INTERVAL_MS = 200;
|
||||
const KEEPALIVE_INTERVAL_MS = 15_000;
|
||||
const MAX_DURATION_MS = 16_000;
|
||||
|
||||
const SSE_HEADERS = {
|
||||
"Content-Type": "text/event-stream; charset=utf-8",
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
};
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
export async function GET(request: Request): Promise<Response> {
|
||||
// Gate 1: rate limiter -- must be first to protect against DoS before auth IO
|
||||
const limited = globeCommandsStreamLimiter.check(getClientIp(request));
|
||||
if (limited) return limited as Response;
|
||||
|
||||
// Gate 2: demo edition -- read env at request time so vi.stubEnv works in tests
|
||||
const currentEdition = resolveEdition(process.env.NEXT_PUBLIC_WWV_EDITION);
|
||||
if (currentEdition === "demo") {
|
||||
return NextResponse.json({ error: "Demo mode" }, { status: 403 }) as Response;
|
||||
}
|
||||
|
||||
// Gate 3: dual-auth -- session primary, Bearer API key fallback
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }) as Response;
|
||||
}
|
||||
|
||||
// Gate 4: UUID sessionId guard -- scopes the Redis queue key
|
||||
const url = new URL(request.url);
|
||||
const sessionId = url.searchParams.get("sessionId") ?? "";
|
||||
|
||||
if (!sessionId || !SESSION_ID_RE.test(sessionId)) {
|
||||
return NextResponse.json({ error: "invalid sessionId" }, { status: 400 }) as Response;
|
||||
}
|
||||
|
||||
// Capture for use inside the ReadableStream closure
|
||||
const resolvedUserId = userId;
|
||||
const resolvedSessionId = sessionId;
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function send(chunk: string): void {
|
||||
controller.enqueue(encoder.encode(chunk));
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
let lastKeepalive = Date.now();
|
||||
|
||||
try {
|
||||
while (Date.now() - startTime < MAX_DURATION_MS) {
|
||||
const commands = await drainGlobeCommands(resolvedUserId, resolvedSessionId);
|
||||
for (const cmd of commands) {
|
||||
send("data: " + JSON.stringify({ commands: [cmd] }) + "\n\n");
|
||||
}
|
||||
|
||||
if (Date.now() - lastKeepalive >= KEEPALIVE_INTERVAL_MS) {
|
||||
send(":keepalive\n\n");
|
||||
lastKeepalive = Date.now();
|
||||
}
|
||||
|
||||
await sleep(POLL_INTERVAL_MS);
|
||||
if (cancelled) break;
|
||||
}
|
||||
|
||||
controller.close();
|
||||
} catch (err) {
|
||||
console.error("[globe/commands/stream] stream error:", err);
|
||||
controller.error(err);
|
||||
}
|
||||
},
|
||||
cancel() {
|
||||
cancelled = true;
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, { headers: SSE_HEADERS });
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { POST } from "./route";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { writeGlobeState } from "@/lib/globeStateStore";
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/globeStateStore", () => ({
|
||||
writeGlobeState: vi.fn(),
|
||||
}));
|
||||
|
||||
// Bypass rate limiting so route tests don't need a limiter mock
|
||||
vi.mock("@/lib/rateLimiters", () => ({
|
||||
mcpLimiter: { check: vi.fn().mockReturnValue(null) },
|
||||
getClientIp: vi.fn().mockReturnValue("127.0.0.1"),
|
||||
}));
|
||||
|
||||
// Mutable ref so individual tests can toggle the demo edition flag.
|
||||
// Must be declared with vi.hoisted so it is available when vi.mock is hoisted.
|
||||
const editionMock = vi.hoisted(() => ({ isDemo: false }));
|
||||
vi.mock("@/core/edition", () => editionMock);
|
||||
|
||||
const mockAuth = vi.mocked(authenticateApiKey);
|
||||
const mockWrite = vi.mocked(writeGlobeState);
|
||||
|
||||
const validSnapshot = {
|
||||
viewport: { lat: 37.7, lon: -122.4, altitude: 500000, heading: 0, pitch: -90, roll: 0 },
|
||||
layers: {},
|
||||
timeline: {
|
||||
currentTime: "2026-01-15T12:00:00.000Z",
|
||||
timeWindow: "24h",
|
||||
isPlaybackMode: false,
|
||||
playbackTime: 1737000000000,
|
||||
playbackSpeed: 1,
|
||||
},
|
||||
selectedEntity: null,
|
||||
lastUpdate: 1737000000000,
|
||||
};
|
||||
|
||||
function makeRequest(body: unknown): Request {
|
||||
return new Request("http://localhost/api/globe/state", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
editionMock.isDemo = false;
|
||||
mockAuth.mockResolvedValue({ userId: "user-1", keyId: "key-1" });
|
||||
mockWrite.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST /api/globe/state (RSRC-01)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("POST /api/globe/state (RSRC-01)", () => {
|
||||
it("returns 200 and calls writeGlobeState with valid auth + body", async () => {
|
||||
const req = makeRequest({ sessionId: "sess-abc", snapshot: validSnapshot });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockWrite).toHaveBeenCalledWith("user-1", "sess-abc", validSnapshot);
|
||||
});
|
||||
|
||||
it("returns 401 and does NOT call writeGlobeState when auth returns null", async () => {
|
||||
mockAuth.mockResolvedValue(null);
|
||||
|
||||
const req = makeRequest({ sessionId: "sess-abc", snapshot: validSnapshot });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(mockWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 400 and does NOT call writeGlobeState when sessionId is missing", async () => {
|
||||
const req = makeRequest({ snapshot: validSnapshot });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 400 when snapshot is missing from body", async () => {
|
||||
const req = makeRequest({ sessionId: "sess-abc" });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(mockWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("still yields 200 when writeGlobeState rejects (fire-and-forget contract)", async () => {
|
||||
mockWrite.mockRejectedValue(new Error("Redis unavailable"));
|
||||
|
||||
const req = makeRequest({ sessionId: "sess-abc", snapshot: validSnapshot });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST /api/globe/state -- demo edition gate (GAP-01)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("POST /api/globe/state -- demo edition gate", () => {
|
||||
it("returns 403 and does NOT call writeGlobeState when isDemo is true", async () => {
|
||||
editionMock.isDemo = true;
|
||||
const req = makeRequest({ sessionId: "sess-abc", snapshot: validSnapshot });
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
expect(res.status).toBe(403);
|
||||
expect(body).toEqual({ error: "Not available in demo edition" });
|
||||
expect(mockWrite).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { writeGlobeState } from "@/lib/globeStateStore";
|
||||
import { mcpLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import type { GlobeStateSnapshot } from "@/lib/globeState";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const limited = mcpLimiter.check(getClientIp(request));
|
||||
if (limited) return limited;
|
||||
|
||||
if (isDemo) {
|
||||
return NextResponse.json({ error: "Not available in demo edition" }, { status: 403 });
|
||||
}
|
||||
|
||||
// R-2: browser write path authenticates via NextAuth session cookie (primary),
|
||||
// falling back to Bearer API key for programmatic/MCP clients.
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
body = await request.json() as Record<string, unknown>;
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { sessionId, snapshot } = body;
|
||||
|
||||
if (typeof sessionId !== "string" || sessionId.length === 0) {
|
||||
return NextResponse.json({ error: "sessionId is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (snapshot === null || typeof snapshot !== "object" || Array.isArray(snapshot)) {
|
||||
return NextResponse.json({ error: "snapshot is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
void writeGlobeState(userId, sessionId, snapshot as GlobeStateSnapshot);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { GET } from "./route";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Module mocks -- declared before any imports of the SUT so Vitest hoists them.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock("@/lib/healthProbes", () => ({
|
||||
probeRedis: vi.fn(),
|
||||
probeDb: vi.fn(),
|
||||
probeEngine: vi.fn(),
|
||||
probeConfig: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
edition: "local",
|
||||
}));
|
||||
|
||||
import {
|
||||
probeRedis,
|
||||
probeDb,
|
||||
probeEngine,
|
||||
probeConfig,
|
||||
} from "@/lib/healthProbes";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function setProbes(opts: {
|
||||
redis?: boolean;
|
||||
db?: boolean;
|
||||
engine?: boolean;
|
||||
config?: boolean;
|
||||
}): void {
|
||||
vi.mocked(probeRedis).mockResolvedValue(opts.redis ?? true);
|
||||
vi.mocked(probeDb).mockResolvedValue(opts.db ?? true);
|
||||
vi.mocked(probeEngine).mockResolvedValue(opts.engine ?? true);
|
||||
// probeConfig is synchronous in the real impl; mock as a plain return value.
|
||||
vi.mocked(probeConfig).mockReturnValue(opts.config ?? true);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/health", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
it("returns 200 healthy when all probes pass (OBS-01 happy path)", async () => {
|
||||
setProbes({ redis: true, db: true, engine: true, config: true });
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.status).toBe("healthy");
|
||||
expect(body.checks).toEqual({ redis: true, db: true, engine: true, config: true });
|
||||
expect(body).toHaveProperty("edition");
|
||||
expect(body).toHaveProperty("timestamp");
|
||||
});
|
||||
|
||||
it("returns 200 degraded with checks.redis=false when redis probe fails (OBS-01 redis-down)", async () => {
|
||||
setProbes({ redis: false, db: true, engine: true, config: true });
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.status).toBe("degraded");
|
||||
expect(body.checks.redis).toBe(false);
|
||||
expect(body.checks.db).toBe(true);
|
||||
});
|
||||
|
||||
it("returns 503 unhealthy when db probe fails (OBS-01 db-down)", async () => {
|
||||
setProbes({ redis: true, db: false, engine: true, config: true });
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(503);
|
||||
expect(body.status).toBe("unhealthy");
|
||||
expect(body.checks.db).toBe(false);
|
||||
});
|
||||
|
||||
it("returns 200 degraded when engine probe fails (OBS-01 engine-down)", async () => {
|
||||
setProbes({ redis: true, db: true, engine: false, config: true });
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.status).toBe("degraded");
|
||||
expect(body.checks.engine).toBe(false);
|
||||
});
|
||||
|
||||
it("returns 503 unhealthy when config probe fails in cloud edition (OBS-01 config-misconfigured)", async () => {
|
||||
// Simulate cloud edition with getSigningKey() having thrown (probeConfig returns false).
|
||||
vi.mocked(probeConfig).mockReturnValue(false);
|
||||
vi.mocked(probeRedis).mockResolvedValue(true);
|
||||
vi.mocked(probeDb).mockResolvedValue(true);
|
||||
vi.mocked(probeEngine).mockResolvedValue(true);
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(503);
|
||||
expect(body.status).toBe("unhealthy");
|
||||
expect(body.checks.config).toBe(false);
|
||||
});
|
||||
|
||||
it("includes edition and ISO timestamp in every response (OBS-01 shape)", async () => {
|
||||
setProbes({});
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(typeof body.edition).toBe("string");
|
||||
expect(typeof body.timestamp).toBe("string");
|
||||
// ISO 8601 basic check
|
||||
expect(body.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T/);
|
||||
});
|
||||
});
|
||||
@@ -1,66 +1,5 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { edition } from "@/core/edition";
|
||||
import { probeRedis, probeDb, probeEngine, probeConfig } from "@/lib/healthProbes";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Status + HTTP code policy:
|
||||
// db down OR config misconfigured (cloud/demo) -> "unhealthy", 503
|
||||
// Rationale: the app is either unable to authenticate requests or
|
||||
// fundamentally broken. A load balancer or container orchestrator should
|
||||
// stop routing traffic and alert the operator.
|
||||
// redis down OR engine down (but db + config ok) -> "degraded", 200
|
||||
// Rationale: auth/session reads still work; only streaming data or
|
||||
// rate-limiting is impaired. 200 avoids container restarts for transient
|
||||
// upstream outages.
|
||||
// all ok -> "healthy", 200
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type HealthStatus = "healthy" | "degraded" | "unhealthy";
|
||||
|
||||
interface HealthBody {
|
||||
status: HealthStatus;
|
||||
checks: {
|
||||
redis: boolean;
|
||||
db: boolean;
|
||||
engine: boolean;
|
||||
config: boolean;
|
||||
};
|
||||
edition: string;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export async function GET(): Promise<NextResponse<HealthBody>> {
|
||||
// Run all probes in parallel. probeConfig is sync but wrapped in
|
||||
// Promise.resolve so all four settle together with Promise.all.
|
||||
const [redis, db, engine, config] = await Promise.all([
|
||||
probeRedis(),
|
||||
probeDb(),
|
||||
probeEngine(),
|
||||
Promise.resolve(probeConfig()),
|
||||
]);
|
||||
|
||||
const checks = { redis, db, engine, config };
|
||||
|
||||
let status: HealthStatus;
|
||||
let httpStatus: 200 | 503;
|
||||
|
||||
if (!db || !config) {
|
||||
status = "unhealthy";
|
||||
httpStatus = 503;
|
||||
} else if (!redis || !engine) {
|
||||
status = "degraded";
|
||||
httpStatus = 200;
|
||||
} else {
|
||||
status = "healthy";
|
||||
httpStatus = 200;
|
||||
}
|
||||
|
||||
const body: HealthBody = {
|
||||
status,
|
||||
checks,
|
||||
edition,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
return NextResponse.json(body, { status: httpStatus });
|
||||
export async function GET() {
|
||||
return NextResponse.json({ status: "healthy" }, { status: 200 });
|
||||
}
|
||||
@@ -14,22 +14,6 @@ const ALLOWED_REDIRECT_HOSTS = new Set([
|
||||
"worldwideview.dev",
|
||||
]);
|
||||
|
||||
// Derive additional allowed redirect hosts from the configured marketplace URLs
|
||||
// so that custom deployment hostnames (e.g. marketplace.wwv.local) are accepted
|
||||
// without being hardcoded. A bad env value is skipped rather than crashing the module.
|
||||
for (const envUrl of [
|
||||
process.env.NEXT_PUBLIC_MARKETPLACE_URL,
|
||||
process.env.NEXT_PUBLIC_WWV_MARKETPLACE_URL,
|
||||
process.env.MARKETPLACE_URL,
|
||||
]) {
|
||||
if (!envUrl) continue;
|
||||
try {
|
||||
ALLOWED_REDIRECT_HOSTS.add(new URL(envUrl).hostname);
|
||||
} catch {
|
||||
// Ignore unparsable env values — they simply don't contribute a host.
|
||||
}
|
||||
}
|
||||
|
||||
function isSafeRedirect(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
|
||||
@@ -23,22 +23,6 @@ if (process.env.ALLOWED_DEV_ORIGIN) {
|
||||
ALLOWED_REDIRECT_HOSTS.add(process.env.ALLOWED_DEV_ORIGIN);
|
||||
}
|
||||
|
||||
// Derive additional allowed redirect hosts from the configured marketplace URLs
|
||||
// so that custom deployment hostnames (e.g. marketplace.wwv.local) are accepted
|
||||
// without being hardcoded. A bad env value is skipped rather than crashing the module.
|
||||
for (const envUrl of [
|
||||
process.env.NEXT_PUBLIC_MARKETPLACE_URL,
|
||||
process.env.NEXT_PUBLIC_WWV_MARKETPLACE_URL,
|
||||
process.env.MARKETPLACE_URL,
|
||||
]) {
|
||||
if (!envUrl) continue;
|
||||
try {
|
||||
ALLOWED_REDIRECT_HOSTS.add(new URL(envUrl).hostname);
|
||||
} catch {
|
||||
// Ignore unparsable env values; they simply don't contribute a host.
|
||||
}
|
||||
}
|
||||
|
||||
function isSafeRedirect(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
/**
|
||||
* POST /api/mcp/catalog
|
||||
*
|
||||
* Browser-facing endpoint that accepts a per-session plugin catalog
|
||||
* and stores it in Redis scoped to the authenticated user's session.
|
||||
*
|
||||
* Gate ordering:
|
||||
* 1. Rate limit (prevents abuse before any auth work)
|
||||
* 2. isDemo 403 (demo edition does not support MCP)
|
||||
* 3. Dual-auth: NextAuth session cookie PRIMARY, Bearer apiKey FALLBACK
|
||||
* 4. sessionId UUID guard
|
||||
* 5. Body shape + size validation
|
||||
* 6. publishSessionCatalog (userId ONLY from auth result)
|
||||
*
|
||||
* Security invariants:
|
||||
* - userId is read ONLY from the auth result -- never from the request body.
|
||||
* - Catalog Redis key is scoped both {userId} and {sessionId}.
|
||||
* - Payload size is capped before write; malformed shapes are rejected.
|
||||
* - isDemo 403 gate runs BEFORE auth (avoids DB layer in demo mode).
|
||||
*/
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { publishSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import type { SessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { globeCommandsLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { isDemo } from "@/core/edition";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const SESSION_ID_RE = /^[0-9a-f-]{36}$/i;
|
||||
|
||||
/** Maximum allowed serialized body size in bytes (~64 KB). */
|
||||
const MAX_BODY_BYTES = 64 * 1024;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST handler
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function POST(request: Request): Promise<NextResponse> {
|
||||
// Gate 1: Rate limit
|
||||
const limited = globeCommandsLimiter.check(getClientIp(request));
|
||||
if (limited) return limited as NextResponse;
|
||||
|
||||
// Gate 2: isDemo 403 (BEFORE auth)
|
||||
if (isDemo) {
|
||||
return NextResponse.json(
|
||||
{ error: "MCP catalog is not available in demo mode" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
// Gate 3: Dual-auth -- NextAuth session PRIMARY, Bearer apiKey FALLBACK
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Gate 4: sessionId UUID guard
|
||||
// sessionId may come from the request body; if absent, fall back to the
|
||||
// user's active session (same pattern as globeCommandTools).
|
||||
let rawBody: unknown;
|
||||
try {
|
||||
const text = await request.text();
|
||||
if (Buffer.byteLength(text, "utf8") > MAX_BODY_BYTES) {
|
||||
return NextResponse.json({ error: "Payload too large" }, { status: 413 });
|
||||
}
|
||||
rawBody = JSON.parse(text);
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!rawBody || typeof rawBody !== "object") {
|
||||
return NextResponse.json({ error: "Body must be a JSON object" }, { status: 400 });
|
||||
}
|
||||
|
||||
const body = rawBody as Record<string, unknown>;
|
||||
|
||||
// Resolve sessionId
|
||||
let sessionId: string | null = null;
|
||||
const rawSessionId = body.sessionId;
|
||||
if (typeof rawSessionId === "string" && rawSessionId !== "") {
|
||||
if (!SESSION_ID_RE.test(rawSessionId)) {
|
||||
return NextResponse.json({ error: "invalid sessionId" }, { status: 400 });
|
||||
}
|
||||
sessionId = rawSessionId;
|
||||
} else {
|
||||
sessionId = await resolveActiveSessionId(userId);
|
||||
}
|
||||
|
||||
if (!sessionId) {
|
||||
return NextResponse.json({ error: "No active session" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Gate 5: Body shape validation
|
||||
if (!Array.isArray(body.tools)) {
|
||||
return NextResponse.json({ error: "body.tools must be an array" }, { status: 400 });
|
||||
}
|
||||
if (!Array.isArray(body.capabilities)) {
|
||||
return NextResponse.json({ error: "body.capabilities must be an array" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Validate each tool entry: namespacedName format, description, inputSchema.
|
||||
const NAMESPACED_NAME_RE = /^[a-zA-Z0-9_-]+__[a-zA-Z0-9_-]+$/;
|
||||
const MAX_NAMESPACED_NAME_LENGTH = 128;
|
||||
for (const entry of body.tools) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
return NextResponse.json({ error: "invalid tool entry" }, { status: 400 });
|
||||
}
|
||||
const e = entry as Record<string, unknown>;
|
||||
if (
|
||||
typeof e.namespacedName !== "string" ||
|
||||
e.namespacedName.length > MAX_NAMESPACED_NAME_LENGTH ||
|
||||
!NAMESPACED_NAME_RE.test(e.namespacedName)
|
||||
) {
|
||||
return NextResponse.json({ error: "invalid tool entry" }, { status: 400 });
|
||||
}
|
||||
if (typeof e.description !== "string") {
|
||||
return NextResponse.json({ error: "invalid tool entry" }, { status: 400 });
|
||||
}
|
||||
if (
|
||||
!e.inputSchema ||
|
||||
typeof e.inputSchema !== "object" ||
|
||||
Array.isArray(e.inputSchema)
|
||||
) {
|
||||
return NextResponse.json({ error: "invalid tool entry" }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
// Optional filterDefinitions: a plain object map (pluginId -> defs[]).
|
||||
// Identity is never taken from the body; only this structural shape is
|
||||
// accepted. Reject non-object / array shapes; absent is fine.
|
||||
let filterDefinitions: SessionCatalog["filterDefinitions"] | undefined;
|
||||
const rawFilterDefs = body.filterDefinitions;
|
||||
if (rawFilterDefs !== undefined) {
|
||||
if (
|
||||
!rawFilterDefs ||
|
||||
typeof rawFilterDefs !== "object" ||
|
||||
Array.isArray(rawFilterDefs)
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: "body.filterDefinitions must be an object" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
filterDefinitions = rawFilterDefs as SessionCatalog["filterDefinitions"];
|
||||
}
|
||||
|
||||
const catalog: SessionCatalog = {
|
||||
tools: body.tools as SessionCatalog["tools"],
|
||||
capabilities: body.capabilities as string[],
|
||||
...(filterDefinitions !== undefined && { filterDefinitions }),
|
||||
};
|
||||
|
||||
// Gate 6: Store -- userId ONLY from auth result (NEVER from body)
|
||||
await publishSessionCatalog(userId, sessionId, catalog);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -1,342 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/data-query/service");
|
||||
vi.mock("@/lib/globeStateStore");
|
||||
vi.mock("@/lib/mcpSessionCatalog");
|
||||
vi.mock("@/lib/globeCommandQueue");
|
||||
vi.mock("@/lib/data-query/localSources");
|
||||
|
||||
import { getAllPluginSnapshots } from "@/lib/data-query/service";
|
||||
import { readActiveSessions, readGlobeState } from "@/lib/globeStateStore";
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { getLocalSourceIds } from "@/lib/data-query/localSources";
|
||||
|
||||
import {
|
||||
radiusKmToBbox,
|
||||
deriveEntityTypes,
|
||||
listStreamingPlugins,
|
||||
buildInvestigateProse,
|
||||
composeGlobeContext,
|
||||
} from "./discoveryHelpers";
|
||||
|
||||
import type { PluginDataSnapshot } from "@/lib/data-query/types";
|
||||
|
||||
const mockGetAllSnapshots = vi.mocked(getAllPluginSnapshots);
|
||||
const mockReadActiveSessions = vi.mocked(readActiveSessions);
|
||||
const mockReadGlobeState = vi.mocked(readGlobeState);
|
||||
const mockReadSessionCatalog = vi.mocked(readSessionCatalog);
|
||||
const mockGetLocalSourceIds = vi.mocked(getLocalSourceIds);
|
||||
|
||||
// resolveActiveSessionId is re-exported from discoveryHelpers but not called
|
||||
// directly in these tests; mocked to avoid ioredis errors.
|
||||
vi.mocked(resolveActiveSessionId).mockResolvedValue(null);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Default: no local sources; individual tests override as needed.
|
||||
mockGetLocalSourceIds.mockResolvedValue(new Set<string>());
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// radiusKmToBbox
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("radiusKmToBbox", () => {
|
||||
it("produces correct bbox at mid-latitude (lat=45, lon=0, radius=111km)", () => {
|
||||
const bbox = radiusKmToBbox(45, 0, 111);
|
||||
// lat delta = 111/111 = 1 degree
|
||||
expect(bbox.north).toBeCloseTo(46, 4);
|
||||
expect(bbox.south).toBeCloseTo(44, 4);
|
||||
// lon delta = 111 / (111 * cos(45deg)) ~ 1/cos(45) ~ 1.414
|
||||
const expectedLonDelta = 1 / Math.cos((45 * Math.PI) / 180);
|
||||
expect(bbox.east).toBeCloseTo(expectedLonDelta, 2);
|
||||
expect(bbox.west).toBeCloseTo(-expectedLonDelta, 2);
|
||||
});
|
||||
|
||||
it("clamps longitude delta near the poles (lat=89.9)", () => {
|
||||
// cos(89.9 deg) is nearly 0 -- guard prevents division explosion
|
||||
const bbox = radiusKmToBbox(89.9, 0, 50);
|
||||
// lon delta should be capped (cos clamped to 0.01)
|
||||
const maxLonDelta = 50 / (111 * 0.01);
|
||||
expect(bbox.east - bbox.west).toBeLessThanOrEqual(maxLonDelta * 2 + 0.001);
|
||||
});
|
||||
|
||||
it("clamps north to 90 and south to -90 at poles", () => {
|
||||
const bbox = radiusKmToBbox(89, 0, 500);
|
||||
expect(bbox.north).toBeLessThanOrEqual(90);
|
||||
const bbox2 = radiusKmToBbox(-89, 0, 500);
|
||||
expect(bbox2.south).toBeGreaterThanOrEqual(-90);
|
||||
});
|
||||
|
||||
it("returns correct bbox at equator (lat=0)", () => {
|
||||
const bbox = radiusKmToBbox(0, 10, 111);
|
||||
expect(bbox.north).toBeCloseTo(1, 4);
|
||||
expect(bbox.south).toBeCloseTo(-1, 4);
|
||||
// cos(0) = 1 so lon delta ~ 1
|
||||
expect(bbox.east).toBeCloseTo(11, 1);
|
||||
expect(bbox.west).toBeCloseTo(9, 1);
|
||||
});
|
||||
|
||||
it("globe-spanning radius (30000 km) produces full-longitude box, not antimeridian strip", () => {
|
||||
// Without the lonDelta cap a 30000 km radius produces lonDelta >> 180,
|
||||
// and wrapLon(lon + lonDelta) collapses to a tiny strip near the antimeridian.
|
||||
// With the cap, lonDelta = 180, so east and west both map to the antimeridian
|
||||
// (+180 and -180 are the same line). The key invariant is that the longitude
|
||||
// span equals 360 degrees (east - west mod 360 = 0 = full globe).
|
||||
const bbox = radiusKmToBbox(0, 0, 30000);
|
||||
// Both east and west land on the antimeridian (180 = -180 in wrapped coords).
|
||||
const normalise = (v: number) => Math.abs(Math.abs(v) - 180);
|
||||
expect(normalise(bbox.east)).toBeCloseTo(0, 4);
|
||||
expect(normalise(bbox.west)).toBeCloseTo(0, 4);
|
||||
expect(bbox.north).toBeCloseTo(90, 0);
|
||||
expect(bbox.south).toBeCloseTo(-90, 0);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// deriveEntityTypes
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("deriveEntityTypes", () => {
|
||||
const snapshot: PluginDataSnapshot = {
|
||||
pluginId: "flights",
|
||||
entities: [
|
||||
{
|
||||
id: "e1",
|
||||
pluginId: "flights",
|
||||
latitude: 0,
|
||||
longitude: 0,
|
||||
timestamp: new Date(),
|
||||
properties: { status: "airborne", airline: "NZ" },
|
||||
},
|
||||
{
|
||||
id: "e2",
|
||||
pluginId: "flights",
|
||||
latitude: 1,
|
||||
longitude: 1,
|
||||
timestamp: new Date(),
|
||||
properties: { status: "landed", altitude: 0 },
|
||||
},
|
||||
],
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
it("returns filterDef ids when filterDefs provided", () => {
|
||||
const defs = [
|
||||
{ id: "status", label: "Status", type: "select" as const, propertyKey: "status", options: [] },
|
||||
];
|
||||
const result = deriveEntityTypes(snapshot, defs);
|
||||
expect(result).toEqual(["status"]);
|
||||
});
|
||||
|
||||
it("falls back to distinct properties keys when no filterDefs", () => {
|
||||
const result = deriveEntityTypes(snapshot);
|
||||
expect(result).toContain("status");
|
||||
expect(result).toContain("airline");
|
||||
expect(result).toContain("altitude");
|
||||
});
|
||||
|
||||
it("returns empty array for snapshot with no entities", () => {
|
||||
const empty: PluginDataSnapshot = { pluginId: "x", entities: [], timestamp: new Date() };
|
||||
expect(deriveEntityTypes(empty)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// listStreamingPlugins
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("listStreamingPlugins", () => {
|
||||
it("returns plugins with counts when snapshots present", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{
|
||||
pluginId: "flights",
|
||||
entities: [
|
||||
{ id: "e1", pluginId: "flights", latitude: 0, longitude: 0, timestamp: new Date(), properties: {} },
|
||||
],
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
const result = await listStreamingPlugins();
|
||||
expect(result.reason).toBeUndefined();
|
||||
expect(result.plugins).toHaveLength(1);
|
||||
expect(result.plugins[0].pluginId).toBe("flights");
|
||||
expect(result.plugins[0].entityCount).toBe(1);
|
||||
});
|
||||
|
||||
it("returns { plugins: [], reason: 'engine_unreachable' } when no snapshots and engine not reachable (TOOL-05)", async () => {
|
||||
// In the test environment the probe fetch fails, so engineReachable=false -> engine_unreachable.
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
const result = await listStreamingPlugins();
|
||||
expect(result.plugins).toHaveLength(0);
|
||||
expect(result.reason).toBe("engine_unreachable");
|
||||
});
|
||||
|
||||
it("returns no_active_plugins when engine reachable but zero snapshots (TOOL-05)", async () => {
|
||||
// Mock fetch to simulate engine responding OK (reachable, but no plugins).
|
||||
const savedFetch = global.fetch;
|
||||
global.fetch = vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ plugins: [] }), { status: 200 }),
|
||||
);
|
||||
try {
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
const result = await listStreamingPlugins();
|
||||
expect(result.plugins).toHaveLength(0);
|
||||
expect(result.reason).toBe("no_active_plugins");
|
||||
} finally {
|
||||
global.fetch = savedFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// buildInvestigateProse
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("buildInvestigateProse", () => {
|
||||
it("happy path: returns count + camera panned text when session present", () => {
|
||||
const prose = buildInvestigateProse({
|
||||
displayName: "Auckland, NZ",
|
||||
entityType: "flights",
|
||||
matchedPlugin: "flights",
|
||||
entityCount: 5,
|
||||
sessionPresent: true,
|
||||
});
|
||||
expect(prose.length).toBeGreaterThan(0);
|
||||
expect(prose).toContain("5");
|
||||
expect(prose).toContain("Auckland");
|
||||
expect(prose).toContain("Camera has been panned");
|
||||
});
|
||||
|
||||
it("happy path: notes skipped camera when no session", () => {
|
||||
const prose = buildInvestigateProse({
|
||||
displayName: "Auckland, NZ",
|
||||
entityType: "flights",
|
||||
matchedPlugin: "flights",
|
||||
entityCount: 3,
|
||||
sessionPresent: false,
|
||||
});
|
||||
expect(prose).toContain("camera pan skipped");
|
||||
});
|
||||
|
||||
it("no-matching-plugin: explains entity_type not found", () => {
|
||||
const prose = buildInvestigateProse({
|
||||
displayName: "Auckland, NZ",
|
||||
entityType: "submarines",
|
||||
matchedPlugin: null,
|
||||
entityCount: 0,
|
||||
sessionPresent: false,
|
||||
});
|
||||
expect(prose).toContain("submarines");
|
||||
expect(prose).toContain("list_available_plugins");
|
||||
});
|
||||
|
||||
it("no-data-matches: explains empty region result", () => {
|
||||
const prose = buildInvestigateProse({
|
||||
displayName: "Auckland, NZ",
|
||||
entityType: "flights",
|
||||
matchedPlugin: "flights",
|
||||
entityCount: 0,
|
||||
sessionPresent: true,
|
||||
emptyReason: "no_data_matches",
|
||||
});
|
||||
expect(prose.length).toBeGreaterThan(0);
|
||||
expect(prose).toContain("no");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// listStreamingPlugins -- source tagging (Plan 30-04, D-05)
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("listStreamingPlugins -- source tagging", () => {
|
||||
const makeSnap = (pluginId: string, entityCount: number) => ({
|
||||
pluginId,
|
||||
entities: Array.from({ length: entityCount }, (_, i) => ({
|
||||
id: `${pluginId}-e${i}`,
|
||||
pluginId,
|
||||
latitude: 0,
|
||||
longitude: 0,
|
||||
timestamp: new Date(),
|
||||
properties: {},
|
||||
})),
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
it("tags engine plugin as source:'engine' and local plugin as source:'local'", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
makeSnap("aviation", 3),
|
||||
makeSnap("camera", 5),
|
||||
]);
|
||||
mockGetLocalSourceIds.mockResolvedValue(new Set(["camera"]));
|
||||
|
||||
const result = await listStreamingPlugins();
|
||||
|
||||
expect(result.reason).toBeUndefined();
|
||||
expect(result.plugins).toHaveLength(2);
|
||||
|
||||
const aviation = result.plugins.find((p) => p.pluginId === "aviation");
|
||||
expect(aviation?.source).toBe("engine");
|
||||
|
||||
const camera = result.plugins.find((p) => p.pluginId === "camera");
|
||||
expect(camera?.source).toBe("local");
|
||||
expect(camera?.entityCount).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("tags by id: only the id present in localIds receives source:'local'", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
makeSnap("flights", 10),
|
||||
makeSnap("ships", 4),
|
||||
makeSnap("camera", 2),
|
||||
]);
|
||||
mockGetLocalSourceIds.mockResolvedValue(new Set(["camera"]));
|
||||
|
||||
const result = await listStreamingPlugins();
|
||||
|
||||
const byId = Object.fromEntries(result.plugins.map((p) => [p.pluginId, p.source]));
|
||||
expect(byId["flights"]).toBe("engine");
|
||||
expect(byId["ships"]).toBe("engine");
|
||||
expect(byId["camera"]).toBe("local");
|
||||
});
|
||||
|
||||
it("engine-unreachable passthrough: empty snapshots returns engine_unreachable when probe fails (TOOL-05)", async () => {
|
||||
// In the test environment the probe fetch fails, so reason becomes engine_unreachable.
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
mockGetLocalSourceIds.mockResolvedValue(new Set(["camera"]));
|
||||
|
||||
const result = await listStreamingPlugins();
|
||||
|
||||
expect(result.plugins).toHaveLength(0);
|
||||
expect(result.reason).toBe("engine_unreachable");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// composeGlobeContext
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("composeGlobeContext", () => {
|
||||
it("returns sessionCount:0 + camera:null when no sessions", async () => {
|
||||
mockReadActiveSessions.mockResolvedValue([]);
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
|
||||
const ctx = await composeGlobeContext("u1");
|
||||
expect(ctx.sessionCount).toBe(0);
|
||||
expect(ctx.camera).toBeNull();
|
||||
expect(ctx.layers).toEqual({});
|
||||
});
|
||||
|
||||
it("returns camera + layers when session active", async () => {
|
||||
mockReadActiveSessions.mockResolvedValue([{ sessionId: "s1", lastSeen: Date.now() }]);
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
mockReadGlobeState.mockResolvedValue({
|
||||
viewport: { lat: -36.8, lon: 174.7, altitude: 500000, heading: 0, pitch: -45, roll: 0 },
|
||||
layers: { flights: { enabled: true } as never },
|
||||
timeline: { currentTime: "2026-01-01T00:00:00Z", timeWindow: "1h", isPlaybackMode: false, playbackTime: 0, playbackSpeed: 1 },
|
||||
selectedEntity: null,
|
||||
lastUpdate: Date.now(),
|
||||
});
|
||||
mockReadSessionCatalog.mockResolvedValue({ tools: [], capabilities: [] });
|
||||
|
||||
const ctx = await composeGlobeContext("u1");
|
||||
expect(ctx.sessionCount).toBe(1);
|
||||
expect(ctx.camera).not.toBeNull();
|
||||
expect(ctx.camera?.lat).toBeCloseTo(-36.8);
|
||||
expect(ctx.layers).toHaveProperty("flights");
|
||||
});
|
||||
});
|
||||
@@ -1,303 +0,0 @@
|
||||
/**
|
||||
* Discovery helpers shared by discoveryTools.ts (Phase 29 -- 29-01).
|
||||
*
|
||||
* Provides:
|
||||
* radiusKmToBbox -- geographic bounding box from a center + radius
|
||||
* deriveEntityTypes -- queryable property/filter-key names for a plugin snapshot
|
||||
* listStreamingPlugins -- manifest + per-plugin counts for list_available_plugins
|
||||
* buildInvestigateProse -- deterministic prose for investigate_area result summaries
|
||||
* composeGlobeContext -- full context payload for get_globe_context
|
||||
*
|
||||
* No `any`, no `@ts-ignore`. All external I/O is delegated to the service/store
|
||||
* helpers imported below.
|
||||
*/
|
||||
|
||||
import type { PluginDataSnapshot } from "@/lib/data-query/types";
|
||||
import type { RegionOptions } from "@/lib/data-query/types";
|
||||
import type { FilterDefinition } from "@/core/plugins/PluginTypes";
|
||||
import { getAllPluginSnapshots } from "@/lib/data-query/service";
|
||||
import { getLocalSourceIds } from "@/lib/data-query/localSources";
|
||||
import { readActiveSessions, readGlobeState } from "@/lib/globeStateStore";
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bbox math
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Maximum number of entity property keys to sample when deriving entity types. */
|
||||
const MAX_PROPERTY_SAMPLE = 50;
|
||||
|
||||
/**
|
||||
* Converts a center coordinate + radius into a RegionOptions bounding box.
|
||||
*
|
||||
* Latitude delta: radiusKm / 111 (1 degree lat ~ 111 km).
|
||||
* Longitude delta: radiusKm / (111 * cos(lat)), clamped to avoid divide-by-zero
|
||||
* near the poles (cos(lat) < 0.01 treated as 0.01). East/west are wrapped to
|
||||
* [-180, 180] so points near the antimeridian produce in-range bounds (the
|
||||
* region query handles east < west as an antimeridian-crossing box).
|
||||
*/
|
||||
export function radiusKmToBbox(lat: number, lon: number, radiusKm: number): RegionOptions {
|
||||
const latDelta = radiusKm / 111;
|
||||
const cosLat = Math.cos((lat * Math.PI) / 180);
|
||||
const clampedCos = Math.max(cosLat, 0.01);
|
||||
// Cap lonDelta at 180 so a globe-spanning radius yields the full longitude
|
||||
// range [-180, 180] rather than wrapping to a thin antimeridian strip.
|
||||
const lonDelta = Math.min(radiusKm / (111 * clampedCos), 180);
|
||||
const wrapLon = (v: number): number => ((((v + 180) % 360) + 360) % 360) - 180;
|
||||
return {
|
||||
north: Math.min(lat + latDelta, 90),
|
||||
south: Math.max(lat - latDelta, -90),
|
||||
east: wrapLon(lon + lonDelta),
|
||||
west: wrapLon(lon - lonDelta),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Entity type derivation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns the queryable field identifiers for a plugin snapshot.
|
||||
*
|
||||
* When the browser has published filterDefinitions for the plugin (via the
|
||||
* session catalog), return those field ids -- they are authoritative.
|
||||
* Otherwise, sample distinct `properties` keys from the snapshot entities as a
|
||||
* best-effort fallback.
|
||||
*/
|
||||
export function deriveEntityTypes(
|
||||
snapshot: PluginDataSnapshot,
|
||||
filterDefs?: FilterDefinition[],
|
||||
): string[] {
|
||||
if (filterDefs && filterDefs.length > 0) {
|
||||
return filterDefs.map((d) => d.id);
|
||||
}
|
||||
|
||||
const keys = new Set<string>();
|
||||
const sample = snapshot.entities.slice(0, MAX_PROPERTY_SAMPLE);
|
||||
for (const entity of sample) {
|
||||
for (const key of Object.keys(entity.properties ?? {})) {
|
||||
keys.add(key);
|
||||
}
|
||||
}
|
||||
return Array.from(keys);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plugin listing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface StreamingPlugin {
|
||||
pluginId: string;
|
||||
/** Engine manifest exposes ids only; pluginName equals pluginId until the
|
||||
* manifest or a richer source provides display names. */
|
||||
pluginName: string;
|
||||
entityCount: number;
|
||||
entityTypes: string[];
|
||||
/** Whether this plugin's data originates from the live engine stream or a
|
||||
* server-reachable local/static source (D-05). */
|
||||
source: "engine" | "local";
|
||||
}
|
||||
|
||||
export interface ListStreamingPluginsResult {
|
||||
plugins: StreamingPlugin[];
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Probes whether the data engine manifest endpoint is reachable.
|
||||
* Returns true when the engine responds with 2xx, false on network error or non-2xx.
|
||||
*
|
||||
* Timeout is intentionally short (2000ms) so callers on the empty-snapshot path
|
||||
* are not blocked waiting for a slow engine.
|
||||
*/
|
||||
async function probeEngineReachable(): Promise<boolean> {
|
||||
const engineUrl = (process.env.WWV_DATA_ENGINE_URL ?? "http://localhost:5001") + "/manifest";
|
||||
try {
|
||||
const res = await fetch(engineUrl, { signal: AbortSignal.timeout(2000) });
|
||||
return res.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the engine manifest and per-plugin snapshots to build a summary list.
|
||||
*
|
||||
* Reasons when plugins array is empty:
|
||||
* engine_unreachable -- manifest fetch failed or engine returned non-2xx.
|
||||
* no_active_plugins -- engine reachable but zero plugins active right now.
|
||||
*
|
||||
* Local sources (e.g. camera) are tagged source:'local' and are surfaced
|
||||
* even when the engine is down (getAllPluginSnapshots includes local sources).
|
||||
*
|
||||
* The probe runs only on the empty-snapshot path to avoid the double-manifest
|
||||
* hit on every happy-path call.
|
||||
*/
|
||||
export async function listStreamingPlugins(): Promise<ListStreamingPluginsResult> {
|
||||
const [snapshots, localIds] = await Promise.all([
|
||||
getAllPluginSnapshots(),
|
||||
getLocalSourceIds(),
|
||||
]);
|
||||
|
||||
if (snapshots.length === 0) {
|
||||
const engineReachable = await probeEngineReachable();
|
||||
const reason = engineReachable ? "no_active_plugins" : "engine_unreachable";
|
||||
return { plugins: [], reason };
|
||||
}
|
||||
|
||||
const plugins: StreamingPlugin[] = snapshots.map((snap) => ({
|
||||
pluginId: snap.pluginId,
|
||||
pluginName: snap.pluginId, // manifest exposes ids only
|
||||
entityCount: snap.entities.length,
|
||||
entityTypes: deriveEntityTypes(snap),
|
||||
source: localIds.has(snap.pluginId) ? "local" : "engine",
|
||||
}));
|
||||
return { plugins };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Prose builder
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface InvestigateProseArgs {
|
||||
displayName: string;
|
||||
entityType: string;
|
||||
matchedPlugin: string | null;
|
||||
entityCount: number;
|
||||
sessionPresent: boolean;
|
||||
emptyReason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds deterministic (non-LLM) prose for the investigate_area summary field.
|
||||
* Covers four cases:
|
||||
* - Happy: entities found
|
||||
* - No matching plugin: entity_type does not match any streaming plugin
|
||||
* - No data matches: plugin streams but no entities in the region
|
||||
* - No session: data queried but camera pan skipped
|
||||
*/
|
||||
export function buildInvestigateProse(args: InvestigateProseArgs): string {
|
||||
const { displayName, entityType, matchedPlugin, entityCount, sessionPresent, emptyReason } = args;
|
||||
|
||||
if (matchedPlugin === null) {
|
||||
return (
|
||||
`No active plugin streams "${entityType}". ` +
|
||||
`Use list_available_plugins to see which entity types are currently streaming, ` +
|
||||
`then retry investigate_area with a matching entity_type.`
|
||||
);
|
||||
}
|
||||
|
||||
if (entityCount > 0) {
|
||||
const cameraNote = sessionPresent
|
||||
? "Camera has been panned to the area."
|
||||
: "No active globe session -- camera pan skipped.";
|
||||
return (
|
||||
`Found ${entityCount} ${entityType} ${entityCount === 1 ? "entity" : "entities"} ` +
|
||||
`near ${displayName} (plugin: ${matchedPlugin}). ${cameraNote}`
|
||||
);
|
||||
}
|
||||
|
||||
// Empty result -- explain why.
|
||||
if (emptyReason === "plugin_not_streaming") {
|
||||
return (
|
||||
`Plugin "${matchedPlugin}" matched your entity_type "${entityType}" but is not ` +
|
||||
`currently streaming data. The engine may be loading or the plugin may be offline.`
|
||||
);
|
||||
}
|
||||
|
||||
const cameraNote = sessionPresent
|
||||
? "Camera was panned to the area."
|
||||
: "No active globe session -- camera pan skipped.";
|
||||
return (
|
||||
`No ${entityType} entities found near ${displayName} (plugin: ${matchedPlugin}). ` +
|
||||
`The plugin is streaming but returned no data for this region and radius. ` +
|
||||
cameraNote
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Globe context composer
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface GlobeContextPayload {
|
||||
sessionCount: number;
|
||||
camera: Record<string, number> | null;
|
||||
layers: Record<string, unknown>;
|
||||
filters: {
|
||||
note: string;
|
||||
definitions?: Record<string, unknown[]>;
|
||||
};
|
||||
plugins: StreamingPlugin[];
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Composes a full globe context snapshot for get_globe_context.
|
||||
* Never throws -- all sub-calls are best-effort; missing data falls back to nulls/empty.
|
||||
*/
|
||||
export async function composeGlobeContext(userId: string): Promise<GlobeContextPayload> {
|
||||
const [sessions, pluginsResult] = await Promise.all([
|
||||
readActiveSessions(userId),
|
||||
listStreamingPlugins(),
|
||||
]);
|
||||
|
||||
const sessionCount = sessions.length;
|
||||
|
||||
if (sessionCount === 0) {
|
||||
return {
|
||||
sessionCount: 0,
|
||||
camera: null,
|
||||
layers: {},
|
||||
filters: { note: "No active session -- filter values are not server-tracked." },
|
||||
plugins: pluginsResult.plugins,
|
||||
...(pluginsResult.reason !== undefined && { reason: pluginsResult.reason }),
|
||||
};
|
||||
}
|
||||
|
||||
// Use the most recently active session.
|
||||
const sorted = [...sessions].sort((a, b) => b.lastSeen - a.lastSeen);
|
||||
const activeSessionId = sorted[0].sessionId;
|
||||
|
||||
const [globeState, catalog] = await Promise.all([
|
||||
readGlobeState(userId, activeSessionId),
|
||||
readSessionCatalog(userId, activeSessionId),
|
||||
]);
|
||||
|
||||
const camera = globeState
|
||||
? {
|
||||
lat: globeState.viewport.lat,
|
||||
lon: globeState.viewport.lon,
|
||||
altitude: globeState.viewport.altitude,
|
||||
heading: globeState.viewport.heading,
|
||||
pitch: globeState.viewport.pitch,
|
||||
}
|
||||
: null;
|
||||
|
||||
const layers = globeState?.layers ?? {};
|
||||
|
||||
// Filter definitions from catalog (browser-published). Applied values are
|
||||
// NOT server-tracked -- only definition metadata is available here.
|
||||
const filterDefs = catalog?.filterDefinitions ?? {};
|
||||
const filters = {
|
||||
note: "Applied filter VALUES are not server-tracked. Only filter definitions (fields/types) are available here.",
|
||||
definitions: Object.fromEntries(
|
||||
Object.entries(filterDefs).map(([pluginId, defs]) => [
|
||||
pluginId,
|
||||
defs as unknown[],
|
||||
]),
|
||||
),
|
||||
};
|
||||
|
||||
return {
|
||||
sessionCount,
|
||||
camera,
|
||||
layers,
|
||||
filters,
|
||||
plugins: pluginsResult.plugins,
|
||||
...(pluginsResult.reason !== undefined && { reason: pluginsResult.reason }),
|
||||
};
|
||||
}
|
||||
|
||||
/** Re-export for convenience so discoveryTools.ts has one import path. */
|
||||
export { resolveActiveSessionId };
|
||||
@@ -1,304 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/data-query/service");
|
||||
vi.mock("@/lib/globeStateStore");
|
||||
vi.mock("@/lib/mcpSessionCatalog");
|
||||
vi.mock("@/lib/globeCommandQueue");
|
||||
vi.mock("@/lib/nominatim", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/lib/nominatim")>();
|
||||
return {
|
||||
...actual,
|
||||
fetchGeocode: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
import { getAllPluginSnapshots, getEntitiesInRegion } from "@/lib/data-query/service";
|
||||
import { readActiveSessions, readGlobeState } from "@/lib/globeStateStore";
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { resolveActiveSessionId, enqueueGlobeCommand } from "@/lib/globeCommandQueue";
|
||||
import { fetchGeocode } from "@/lib/nominatim";
|
||||
import { registerDiscoveryTools } from "./discoveryTools";
|
||||
|
||||
const mockGetAllSnapshots = vi.mocked(getAllPluginSnapshots);
|
||||
const mockGetEntitiesInRegion = vi.mocked(getEntitiesInRegion);
|
||||
const mockReadActiveSessions = vi.mocked(readActiveSessions);
|
||||
const mockReadGlobeState = vi.mocked(readGlobeState);
|
||||
const mockReadSessionCatalog = vi.mocked(readSessionCatalog);
|
||||
const mockResolveActiveSessionId = vi.mocked(resolveActiveSessionId);
|
||||
const mockEnqueueGlobeCommand = vi.mocked(enqueueGlobeCommand);
|
||||
const mockFetchGeocode = vi.mocked(fetchGeocode);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Minimal fake server that captures handlers
|
||||
// ---------------------------------------------------------------------------
|
||||
const handlers: Record<string, (args: unknown) => unknown> = {};
|
||||
const schemas: Record<string, { description: string }> = {};
|
||||
const mockServer = {
|
||||
registerTool: vi.fn(
|
||||
(name: string, schema: { description: string }, handler: (args: unknown) => unknown) => {
|
||||
handlers[name] = handler;
|
||||
schemas[name] = schema;
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
const ctx = { userId: "user-test-1" };
|
||||
|
||||
function textOf(result: unknown): string {
|
||||
return (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
}
|
||||
|
||||
function parsedOf(result: unknown): unknown {
|
||||
return JSON.parse(textOf(result));
|
||||
}
|
||||
|
||||
// Re-usable geocode response fixture (Auckland, NZ)
|
||||
const aucklandGeoRaw = {
|
||||
lat: "-36.8485",
|
||||
lon: "174.7633",
|
||||
name: "Auckland",
|
||||
display_name: "Auckland, Auckland, New Zealand",
|
||||
boundingbox: ["-37.0", "-36.5", "174.5", "175.0"] as [string, string, string, string],
|
||||
importance: 0.8,
|
||||
address: { country: "New Zealand" },
|
||||
namedetails: { "name:en": "Auckland" },
|
||||
type: "city",
|
||||
addresstype: "place",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.keys(handlers).forEach((k) => delete handlers[k]);
|
||||
Object.keys(schemas).forEach((k) => delete schemas[k]);
|
||||
|
||||
// Defaults -- individual tests override as needed
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
mockGetEntitiesInRegion.mockResolvedValue({ entities: [], emptyReason: "no_data_matches" });
|
||||
mockReadActiveSessions.mockResolvedValue([]);
|
||||
mockReadGlobeState.mockResolvedValue(null);
|
||||
mockReadSessionCatalog.mockResolvedValue(null);
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
mockEnqueueGlobeCommand.mockResolvedValue(undefined);
|
||||
mockFetchGeocode.mockResolvedValue([aucklandGeoRaw]);
|
||||
|
||||
registerDiscoveryTools(mockServer as never, ctx);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// list_available_plugins
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("list_available_plugins", () => {
|
||||
it("registers the tool with a non-empty description containing Example:", () => {
|
||||
expect(schemas["list_available_plugins"].description.length).toBeGreaterThan(0);
|
||||
expect(schemas["list_available_plugins"].description).toContain("Example:");
|
||||
});
|
||||
|
||||
it("returns plugin list with counts and entityTypes when streaming", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{
|
||||
pluginId: "flights",
|
||||
entities: [
|
||||
{ id: "e1", pluginId: "flights", latitude: 0, longitude: 0, timestamp: new Date(), properties: { status: "airborne" } },
|
||||
{ id: "e2", pluginId: "flights", latitude: 1, longitude: 1, timestamp: new Date(), properties: { status: "landed" } },
|
||||
],
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await handlers["list_available_plugins"]({});
|
||||
const parsed = parsedOf(result) as { plugins: Array<{ pluginId: string; entityCount: number; entityTypes: string[] }> };
|
||||
|
||||
expect(parsed.plugins).toHaveLength(1);
|
||||
expect(parsed.plugins[0].pluginId).toBe("flights");
|
||||
expect(parsed.plugins[0].entityCount).toBe(2);
|
||||
expect(parsed.plugins[0].entityTypes).toContain("status");
|
||||
});
|
||||
|
||||
it("returns { plugins: [], reason: 'engine_unreachable' } when engine is down (TOOL-05)", async () => {
|
||||
// In the test environment the probe fetch fails, so reason becomes engine_unreachable.
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["list_available_plugins"]({});
|
||||
const parsed = parsedOf(result) as { plugins: unknown[]; reason: string };
|
||||
|
||||
expect(parsed.plugins).toHaveLength(0);
|
||||
expect(parsed.reason).toBe("engine_unreachable");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// get_globe_context
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("get_globe_context", () => {
|
||||
it("returns sessionCount:0 + camera:null when no active sessions", async () => {
|
||||
mockReadActiveSessions.mockResolvedValue([]);
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["get_globe_context"]({});
|
||||
const parsed = parsedOf(result) as { sessionCount: number; camera: null; layers: Record<string, unknown>; plugins: unknown[] };
|
||||
|
||||
expect(parsed.sessionCount).toBe(0);
|
||||
expect(parsed.camera).toBeNull();
|
||||
expect(parsed.layers).toEqual({});
|
||||
});
|
||||
|
||||
it("returns sessionCount + camera + layers when session active", async () => {
|
||||
mockReadActiveSessions.mockResolvedValue([{ sessionId: "sess-1", lastSeen: Date.now() }]);
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{
|
||||
pluginId: "maritime",
|
||||
entities: [],
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
mockReadGlobeState.mockResolvedValue({
|
||||
viewport: { lat: -36.8, lon: 174.7, altitude: 500000, heading: 0, pitch: -45, roll: 0 },
|
||||
layers: { maritime: { enabled: true } as never },
|
||||
timeline: { currentTime: "2026-01-01T00:00:00Z", timeWindow: "1h", isPlaybackMode: false, playbackTime: 0, playbackSpeed: 1 },
|
||||
selectedEntity: null,
|
||||
lastUpdate: Date.now(),
|
||||
});
|
||||
mockReadSessionCatalog.mockResolvedValue({ tools: [], capabilities: [] });
|
||||
|
||||
const result = await handlers["get_globe_context"]({});
|
||||
const parsed = parsedOf(result) as { sessionCount: number; camera: { lat: number } | null; layers: Record<string, unknown>; plugins: unknown[] };
|
||||
|
||||
expect(parsed.sessionCount).toBe(1);
|
||||
expect(parsed.camera).not.toBeNull();
|
||||
expect(parsed.camera?.lat).toBeCloseTo(-36.8);
|
||||
expect(parsed.layers).toHaveProperty("maritime");
|
||||
});
|
||||
|
||||
it("includes a filters field with a note about server-tracking limitations", async () => {
|
||||
mockReadActiveSessions.mockResolvedValue([]);
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["get_globe_context"]({});
|
||||
const parsed = parsedOf(result) as { filters: { note: string } };
|
||||
|
||||
expect(parsed.filters.note).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// investigate_area
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("investigate_area", () => {
|
||||
it("happy path: returns entities + summary with count when plugin matches and data found", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{
|
||||
pluginId: "flights",
|
||||
entities: [],
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
mockGetEntitiesInRegion.mockResolvedValue({
|
||||
entities: [
|
||||
{ id: "f1", pluginId: "flights", latitude: -36.8, longitude: 174.7 },
|
||||
{ id: "f2", pluginId: "flights", latitude: -36.9, longitude: 174.6 },
|
||||
],
|
||||
});
|
||||
mockResolveActiveSessionId.mockResolvedValue("sess-1");
|
||||
|
||||
const result = await handlers["investigate_area"]({ place_name: "Auckland", entity_type: "flights" });
|
||||
const parsed = parsedOf(result) as { entities: unknown[]; summary: string };
|
||||
|
||||
expect(parsed.entities).toHaveLength(2);
|
||||
expect(parsed.summary.length).toBeGreaterThan(0);
|
||||
expect(parsed.summary).toContain("2");
|
||||
expect(mockEnqueueGlobeCommand).toHaveBeenCalledWith("user-test-1", "sess-1", expect.objectContaining({ type: "pan" }));
|
||||
});
|
||||
|
||||
it("no-matching-plugin: returns empty entities + prose explaining missing entity_type", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{ pluginId: "maritime", entities: [], timestamp: new Date() },
|
||||
]);
|
||||
|
||||
const result = await handlers["investigate_area"]({ place_name: "Auckland", entity_type: "submarines" });
|
||||
const parsed = parsedOf(result) as { entities: unknown[]; summary: string };
|
||||
|
||||
expect(parsed.entities).toHaveLength(0);
|
||||
expect(parsed.summary).toContain("submarines");
|
||||
expect(parsed.summary).toContain("list_available_plugins");
|
||||
expect(mockEnqueueGlobeCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("no-data-matches: returns empty entities + prose explaining empty result", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{ pluginId: "flights", entities: [], timestamp: new Date() },
|
||||
]);
|
||||
mockGetEntitiesInRegion.mockResolvedValue({ entities: [], emptyReason: "no_data_matches" });
|
||||
mockResolveActiveSessionId.mockResolvedValue("sess-1");
|
||||
|
||||
const result = await handlers["investigate_area"]({ place_name: "Auckland", entity_type: "flights" });
|
||||
const parsed = parsedOf(result) as { entities: unknown[]; summary: string };
|
||||
|
||||
expect(parsed.entities).toHaveLength(0);
|
||||
expect(parsed.summary.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("no-session: returns entities but does NOT call enqueueGlobeCommand; summary notes skip", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{ pluginId: "flights", entities: [], timestamp: new Date() },
|
||||
]);
|
||||
mockGetEntitiesInRegion.mockResolvedValue({
|
||||
entities: [{ id: "f1", pluginId: "flights", latitude: -36.8, longitude: 174.7 }],
|
||||
});
|
||||
mockResolveActiveSessionId.mockResolvedValue(null); // no active session
|
||||
|
||||
const result = await handlers["investigate_area"]({ place_name: "Auckland", entity_type: "flights" });
|
||||
const parsed = parsedOf(result) as { entities: unknown[]; summary: string };
|
||||
|
||||
expect(parsed.entities).toHaveLength(1);
|
||||
expect(mockEnqueueGlobeCommand).not.toHaveBeenCalled();
|
||||
expect(parsed.summary).toContain("camera pan skipped");
|
||||
});
|
||||
|
||||
it("geocode failure: returns empty entities + helpful summary", async () => {
|
||||
mockFetchGeocode.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["investigate_area"]({ place_name: "ZZZ_NONEXISTENT", entity_type: "flights" });
|
||||
const parsed = parsedOf(result) as { entities: unknown[]; summary: string };
|
||||
|
||||
expect(parsed.entities).toHaveLength(0);
|
||||
expect(parsed.summary).toContain("ZZZ_NONEXISTENT");
|
||||
});
|
||||
|
||||
it("truncation (TOOL-04/P33): returns truncated:true and cappedTotal when result exceeds 200 cap", async () => {
|
||||
// Two plugins both named with "vessel" substring so entity_type:"vessel" matches both.
|
||||
// Each returns 110 entities = 220 total, exceeding INVESTIGATE_AREA_CAP (200).
|
||||
const makeEntities = (pluginId: string, count: number) =>
|
||||
Array.from({ length: count }, (_, i) => ({
|
||||
id: `${pluginId}-${i}`,
|
||||
pluginId,
|
||||
latitude: 0,
|
||||
longitude: 0,
|
||||
}));
|
||||
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{ pluginId: "vessel-ais", entities: [], timestamp: new Date() },
|
||||
{ pluginId: "vessel-cargo", entities: [], timestamp: new Date() },
|
||||
]);
|
||||
mockGetEntitiesInRegion
|
||||
.mockResolvedValueOnce({ entities: makeEntities("vessel-ais", 110) })
|
||||
.mockResolvedValueOnce({ entities: makeEntities("vessel-cargo", 110) });
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["investigate_area"]({
|
||||
place_name: "Auckland",
|
||||
entity_type: "vessel",
|
||||
});
|
||||
const parsed = parsedOf(result) as {
|
||||
entities: unknown[];
|
||||
count: number;
|
||||
truncated?: boolean;
|
||||
cappedTotal?: number;
|
||||
summary: string;
|
||||
};
|
||||
|
||||
expect(parsed.entities).toHaveLength(200);
|
||||
expect(parsed.count).toBe(200);
|
||||
expect(parsed.truncated).toBe(true);
|
||||
expect(parsed.cappedTotal).toBe(220);
|
||||
});
|
||||
});
|
||||
@@ -1,236 +0,0 @@
|
||||
/**
|
||||
* MCP Discovery Tool registrar (Phase 29 -- 29-01).
|
||||
*
|
||||
* Registers three compound/discovery MCP tools:
|
||||
* list_available_plugins -- list all streaming plugins with entity counts + types
|
||||
* get_globe_context -- full orientation snapshot in one call
|
||||
* investigate_area -- geocode + query + camera pan in one call
|
||||
*
|
||||
* Security:
|
||||
* - userId comes ONLY from ctx (verified auth result); never from tool args.
|
||||
* - place_name / entity_type / radius_km are untrusted; place_name is passed
|
||||
* exclusively via URLSearchParams in fetchGeocode (no string concat into URL).
|
||||
* - entity_type is matched only against the in-memory streaming plugin set;
|
||||
* never embedded in an engine URL (T-29-01, T-29-02, T-29-03).
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { getEntitiesInRegion } from "@/lib/data-query/service";
|
||||
import { fetchGeocode, normalizeNominatimResult } from "@/lib/nominatim";
|
||||
import { enqueueGlobeCommand } from "@/lib/globeCommandQueue";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import {
|
||||
listStreamingPlugins,
|
||||
radiusKmToBbox,
|
||||
buildInvestigateProse,
|
||||
composeGlobeContext,
|
||||
resolveActiveSessionId,
|
||||
} from "./discoveryHelpers";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type McpTextResult = { content: [{ type: "text"; text: string }] };
|
||||
|
||||
function textResult(payload: unknown): McpTextResult {
|
||||
return {
|
||||
content: [{ type: "text", text: JSON.stringify(payload) }],
|
||||
};
|
||||
}
|
||||
|
||||
/** Default investigation radius when the caller does not specify one. */
|
||||
const DEFAULT_RADIUS_KM = 50;
|
||||
|
||||
/** Altitude (metres) used for camera pan commands from investigate_area. */
|
||||
const INVESTIGATE_PAN_ALT = 300_000;
|
||||
|
||||
/** Maximum total entities returned across all plugins by investigate_area (TOOL-04). */
|
||||
const INVESTIGATE_AREA_CAP = 200;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerDiscoveryTools(
|
||||
server: McpServer,
|
||||
ctx: { userId: string },
|
||||
): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// TOOL-01: list_available_plugins
|
||||
// ------------------------------------------------------------------
|
||||
server.registerTool(
|
||||
"list_available_plugins",
|
||||
{
|
||||
description:
|
||||
"List all plugins currently streaming live data from the engine. Returns pluginId, pluginName, entityCount, and entityTypes (queryable field names) for each active plugin. " +
|
||||
"Use this tool BEFORE search_entities or get_entities_in_region to verify the target plugin is actually streaming -- calling those tools with a non-streaming plugin always returns plugin_not_streaming. " +
|
||||
"When the data engine is unreachable the result contains an empty plugins array and a reason field. " +
|
||||
"No parameters required. " +
|
||||
"Example: list_available_plugins({})",
|
||||
inputSchema: {},
|
||||
},
|
||||
async () => {
|
||||
try {
|
||||
const result = await listStreamingPlugins();
|
||||
return textResult(result);
|
||||
} catch (err) {
|
||||
console.error("[discoveryTools] list_available_plugins failed:", err);
|
||||
return textResult({ plugins: [], reason: "unexpected error" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// TOOL-02: get_globe_context
|
||||
// ------------------------------------------------------------------
|
||||
server.registerTool(
|
||||
"get_globe_context",
|
||||
{
|
||||
description:
|
||||
"Retrieve the full current globe context in one call: sessionCount, camera viewport, active layers, filter definitions (note: applied values are NOT server-tracked), and streaming plugin list. " +
|
||||
"Use this tool at the start of a session to orient yourself without reading multiple globe:// resources separately. " +
|
||||
"When no browser session is active, returns sessionCount:0 and camera:null without error -- open the app in a browser tab first to create a session. " +
|
||||
"Filters field shows definitions (field names/types) only; applied filter values are browser-side and not tracked by the server. " +
|
||||
"No parameters required. " +
|
||||
"Example: get_globe_context({})",
|
||||
inputSchema: {},
|
||||
},
|
||||
async () => {
|
||||
try {
|
||||
const payload = await composeGlobeContext(userId);
|
||||
return textResult(payload);
|
||||
} catch (err) {
|
||||
console.error("[discoveryTools] get_globe_context failed:", err);
|
||||
return textResult({
|
||||
sessionCount: 0,
|
||||
camera: null,
|
||||
layers: {},
|
||||
filters: { note: "context unavailable" },
|
||||
plugins: [],
|
||||
reason: "unexpected error",
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// TOOL-03: investigate_area
|
||||
// ------------------------------------------------------------------
|
||||
server.registerTool(
|
||||
"investigate_area",
|
||||
{
|
||||
description:
|
||||
"Investigate what is happening near a named place for a given entity type. Geocodes the place, finds a matching streaming plugin, queries entities in the bounding region, pans the camera when a session is active, and returns entities + a human-readable summary. " +
|
||||
"Use this tool when an agent asks 'what is near X?' or 'show me Y around Z'. Prefer this over manual geocode + search_entities sequences. " +
|
||||
"When no matching plugin streams the given entity_type, the summary explains this and suggests list_available_plugins. " +
|
||||
"When no active session is found, entities are still returned but the summary notes the camera pan was skipped. " +
|
||||
"Response is capped at 200 entities total across all matched plugins. When 'truncated' is true, 'cappedTotal' holds the sum of per-plugin results before the global cap (not the true global count, because each plugin is itself queried with its own 100-entity limit). " +
|
||||
"Parameters: place_name (required), entity_type (required, case-insensitive substring match against plugin ids/names), radius_km (optional, default 50). " +
|
||||
"Example: investigate_area({place_name:\"Auckland\",entity_type:\"flights\",radius_km:100})",
|
||||
inputSchema: {
|
||||
place_name: z.string().min(1).describe("Place name to geocode (free-text, e.g. 'Auckland', 'Tokyo Bay')"),
|
||||
entity_type: z.string().min(1).describe("Entity type to look for -- case-insensitive substring matched against streaming plugin ids/names"),
|
||||
radius_km: z.number().positive().optional().describe("Search radius in kilometres around the geocoded centre (default 50)"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
const { place_name, entity_type, radius_km } = args;
|
||||
const radius = radius_km ?? DEFAULT_RADIUS_KM;
|
||||
|
||||
try {
|
||||
// Step 1: Geocode the place name (limit 1 result).
|
||||
const rawItems = await fetchGeocode({ query: place_name, limit: 1 });
|
||||
if (rawItems.length === 0) {
|
||||
return textResult({
|
||||
entities: [],
|
||||
summary: `Could not geocode "${place_name}". Try a more specific or differently spelled place name.`,
|
||||
});
|
||||
}
|
||||
const geo = normalizeNominatimResult(rawItems[0]);
|
||||
|
||||
// Step 2: Find matching streaming plugins by case-insensitive substring.
|
||||
const { plugins } = await listStreamingPlugins();
|
||||
const lower = entity_type.toLowerCase();
|
||||
const matched = plugins.filter(
|
||||
(p) =>
|
||||
p.pluginId.toLowerCase().includes(lower) ||
|
||||
p.pluginName.toLowerCase().includes(lower),
|
||||
);
|
||||
|
||||
if (matched.length === 0) {
|
||||
return textResult({
|
||||
entities: [],
|
||||
summary: buildInvestigateProse({
|
||||
displayName: geo.display_name,
|
||||
entityType: entity_type,
|
||||
matchedPlugin: null,
|
||||
entityCount: 0,
|
||||
sessionPresent: false,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
// Step 3: Compute bbox and query region for each matched plugin.
|
||||
const bbox = radiusKmToBbox(geo.lat, geo.lng, radius);
|
||||
type SearchResult = { id: string; pluginId: string; name?: string; latitude: number; longitude: number };
|
||||
const allEntities: SearchResult[] = [];
|
||||
let lastEmptyReason: string | undefined;
|
||||
|
||||
for (const plugin of matched) {
|
||||
const result = await getEntitiesInRegion({ ...bbox, pluginId: plugin.pluginId });
|
||||
allEntities.push(...result.entities);
|
||||
if (result.emptyReason) lastEmptyReason = result.emptyReason;
|
||||
}
|
||||
|
||||
// Step 4: Pan camera when a session is active.
|
||||
const sessionId = await resolveActiveSessionId(userId);
|
||||
const sessionPresent = sessionId !== null;
|
||||
if (sessionId !== null) {
|
||||
const cmd: GlobeCommand = {
|
||||
type: "pan",
|
||||
lat: geo.lat,
|
||||
lon: geo.lng,
|
||||
alt: INVESTIGATE_PAN_ALT,
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
}
|
||||
|
||||
// Step 5: Apply overall cap and record truncation metadata.
|
||||
// cappedTotal is the sum of per-plugin results before the global cap.
|
||||
// It is NOT the true global count because each plugin is queried with
|
||||
// its own 100-entity limit before reaching here.
|
||||
const cappedTotal = allEntities.length;
|
||||
const truncated = cappedTotal > INVESTIGATE_AREA_CAP;
|
||||
const entities = truncated ? allEntities.slice(0, INVESTIGATE_AREA_CAP) : allEntities;
|
||||
|
||||
// Step 6: Build prose summary using first matched plugin as representative.
|
||||
const representativePlugin = matched[0].pluginId;
|
||||
const summary = buildInvestigateProse({
|
||||
displayName: geo.display_name,
|
||||
entityType: entity_type,
|
||||
matchedPlugin: representativePlugin,
|
||||
entityCount: entities.length,
|
||||
sessionPresent,
|
||||
emptyReason: lastEmptyReason,
|
||||
});
|
||||
|
||||
return textResult({
|
||||
entities,
|
||||
count: entities.length,
|
||||
...(truncated && { truncated: true, cappedTotal }),
|
||||
summary,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[discoveryTools] investigate_area failed:", err);
|
||||
return textResult({
|
||||
entities: [],
|
||||
summary: `investigate_area encountered an unexpected error for "${place_name}". Please retry shortly.`,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/prisma");
|
||||
vi.mock("@/lib/globeStateStore");
|
||||
vi.mock("@/lib/data-query/service");
|
||||
|
||||
import { registerFavoritesTools } from "./favoritesTools";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { readActiveSessions } from "@/lib/globeStateStore";
|
||||
import { getEntityDetails } from "@/lib/data-query/service";
|
||||
|
||||
const mockPrisma = vi.mocked(prisma, true);
|
||||
const mockReadActiveSessions = vi.mocked(readActiveSessions);
|
||||
const mockGetEntityDetails = vi.mocked(getEntityDetails);
|
||||
|
||||
const handlers: Record<string, (args: unknown) => unknown> = {};
|
||||
const schemas: Record<string, { description: string }> = {};
|
||||
const mockServer = {
|
||||
registerTool: vi.fn((name: string, schema: { description: string }, handler: (args: unknown) => unknown) => {
|
||||
handlers[name] = handler;
|
||||
schemas[name] = schema;
|
||||
}),
|
||||
};
|
||||
|
||||
const ctx = { userId: "u1" };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.keys(handlers).forEach((k) => delete handlers[k]);
|
||||
Object.keys(schemas).forEach((k) => delete schemas[k]);
|
||||
registerFavoritesTools(mockServer as never, ctx);
|
||||
});
|
||||
|
||||
describe("favoritesTools tool descriptions (DESC-03)", () => {
|
||||
const toolNames = ["save_favorite", "list_favorites", "remove_favorite"];
|
||||
|
||||
it.each(toolNames)("%s description is non-empty and within 1024 chars", (name) => {
|
||||
const desc = schemas[name].description;
|
||||
expect(desc.length).toBeGreaterThan(0);
|
||||
expect(desc.length).toBeLessThanOrEqual(1024);
|
||||
});
|
||||
|
||||
it.each(toolNames)("%s description contains 'Example:'", (name) => {
|
||||
expect(schemas[name].description).toContain("Example:");
|
||||
});
|
||||
|
||||
it("list_favorites description mentions both 'live' and 'stale'", () => {
|
||||
const desc = schemas["list_favorites"].description;
|
||||
expect(desc).toContain("live");
|
||||
expect(desc).toContain("stale");
|
||||
});
|
||||
});
|
||||
|
||||
describe("save_favorite tool handler", () => {
|
||||
it("calls prisma.favorite.upsert with userId from context, not from args", async () => {
|
||||
// findUnique returns null -> new row, count returns 0 -> below cap
|
||||
mockPrisma.favorite.findUnique.mockResolvedValue(null as never);
|
||||
mockPrisma.favorite.count.mockResolvedValue(0 as never);
|
||||
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
|
||||
|
||||
await handlers["save_favorite"]({
|
||||
entityId: "ship:123",
|
||||
pluginId: "maritime",
|
||||
userId: "attacker",
|
||||
});
|
||||
|
||||
expect(mockPrisma.favorite.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({ userId: "u1" }),
|
||||
create: expect.objectContaining({ userId: "u1" }),
|
||||
}),
|
||||
);
|
||||
expect(mockPrisma.favorite.upsert).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ create: expect.objectContaining({ userId: "attacker" }) }),
|
||||
);
|
||||
});
|
||||
|
||||
it("sets pluginName to pluginId as fallback when name is omitted", async () => {
|
||||
mockPrisma.favorite.findUnique.mockResolvedValue(null as never);
|
||||
mockPrisma.favorite.count.mockResolvedValue(0 as never);
|
||||
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
|
||||
|
||||
await handlers["save_favorite"]({ entityId: "ship:456", pluginId: "maritime" });
|
||||
|
||||
expect(mockPrisma.favorite.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({ pluginName: "maritime" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects when user is at the 500-favorite cap and entity is new", async () => {
|
||||
mockPrisma.favorite.findUnique.mockResolvedValue(null as never);
|
||||
mockPrisma.favorite.count.mockResolvedValue(500 as never);
|
||||
|
||||
const result = await handlers["save_favorite"]({
|
||||
entityId: "newship:999",
|
||||
pluginId: "maritime",
|
||||
});
|
||||
|
||||
expect(mockPrisma.favorite.upsert).not.toHaveBeenCalled();
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text).toContain("favorite limit of 500 reached");
|
||||
});
|
||||
|
||||
it("allows upsert when entity already exists (no count check needed)", async () => {
|
||||
// findUnique returns an existing row -> cap check is skipped
|
||||
mockPrisma.favorite.findUnique.mockResolvedValue({ id: "existing" } as never);
|
||||
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
|
||||
|
||||
await handlers["save_favorite"]({
|
||||
entityId: "ship:123",
|
||||
pluginId: "maritime",
|
||||
});
|
||||
|
||||
expect(mockPrisma.favorite.count).not.toHaveBeenCalled();
|
||||
expect(mockPrisma.favorite.upsert).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("list_favorites tool handler", () => {
|
||||
it("includes notes field on returned items", async () => {
|
||||
mockPrisma.favorite.findMany.mockResolvedValue([
|
||||
{ id: "1", entityId: "ship:123", pluginId: "maritime", userId: "u1", pluginName: "Maritime", notes: "Watch this ship", lastSeen: new Date() },
|
||||
] as never);
|
||||
mockReadActiveSessions.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["list_favorites"]({});
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
const parsed = JSON.parse(text);
|
||||
expect(parsed[0]).toHaveProperty("notes", "Watch this ship");
|
||||
});
|
||||
|
||||
it("returns status 'live' for entity when active session exists", async () => {
|
||||
mockPrisma.favorite.findMany.mockResolvedValue([
|
||||
{ id: "1", entityId: "ship:123", pluginId: "maritime", userId: "u1", pluginName: "Maritime", createdAt: new Date() },
|
||||
] as never);
|
||||
mockReadActiveSessions.mockResolvedValue([{ sessionId: "sess-abc", lastSeen: Date.now() }]);
|
||||
mockGetEntityDetails.mockResolvedValue({ data: { entityId: "ship:123", lat: 1, lon: 2 } } as never);
|
||||
|
||||
const result = await handlers["list_favorites"]({});
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
const parsed = JSON.parse(text);
|
||||
expect(parsed[0].status).toBe("live");
|
||||
});
|
||||
|
||||
it("returns status 'stale' for all entities when no active session exists", async () => {
|
||||
mockPrisma.favorite.findMany.mockResolvedValue([
|
||||
{ id: "1", entityId: "ship:123", pluginId: "maritime", userId: "u1", pluginName: "Maritime", createdAt: new Date() },
|
||||
] as never);
|
||||
mockReadActiveSessions.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["list_favorites"]({});
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
const parsed = JSON.parse(text);
|
||||
expect(parsed[0].status).toBe("stale");
|
||||
});
|
||||
|
||||
it("returns status 'stale' when getEntityDetails returns null", async () => {
|
||||
mockPrisma.favorite.findMany.mockResolvedValue([
|
||||
{ id: "1", entityId: "ship:123", pluginId: "maritime", userId: "u1", pluginName: "Maritime", createdAt: new Date() },
|
||||
] as never);
|
||||
mockReadActiveSessions.mockResolvedValue([{ sessionId: "sess-abc", lastSeen: Date.now() }]);
|
||||
mockGetEntityDetails.mockResolvedValue({ data: null, emptyReason: "plugin_not_streaming" } as never);
|
||||
|
||||
const result = await handlers["list_favorites"]({});
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
const parsed = JSON.parse(text);
|
||||
expect(parsed[0].status).toBe("stale");
|
||||
});
|
||||
});
|
||||
|
||||
describe("update_favorite tool handler", () => {
|
||||
it("happy path: updates both label and notes", async () => {
|
||||
mockPrisma.favorite.update.mockResolvedValue({ label: "New Name" } as never);
|
||||
|
||||
const result = await handlers["update_favorite"]({
|
||||
favoriteId: "ship:123",
|
||||
name: "New Name",
|
||||
notes: "Check weekly",
|
||||
});
|
||||
|
||||
expect(mockPrisma.favorite.update).toHaveBeenCalledWith({
|
||||
where: expect.objectContaining({ userId: "u1", entityId: "ship:123" }),
|
||||
data: { label: "New Name", notes: "Check weekly" },
|
||||
});
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text).toBe("Updated favorite: New Name");
|
||||
});
|
||||
|
||||
it("name-only: calls update with label only, not notes", async () => {
|
||||
mockPrisma.favorite.update.mockResolvedValue({ label: "Renamed" } as never);
|
||||
|
||||
await handlers["update_favorite"]({ favoriteId: "ship:123", name: "Renamed" });
|
||||
|
||||
const call = mockPrisma.favorite.update.mock.calls[0][0] as { data: Record<string, unknown> };
|
||||
expect(call.data).toHaveProperty("label", "Renamed");
|
||||
expect(call.data).not.toHaveProperty("notes");
|
||||
});
|
||||
|
||||
it("notes-only: calls update with notes only, not label", async () => {
|
||||
mockPrisma.favorite.update.mockResolvedValue({ label: "Existing" } as never);
|
||||
|
||||
await handlers["update_favorite"]({ favoriteId: "ship:123", notes: "My annotation" });
|
||||
|
||||
const call = mockPrisma.favorite.update.mock.calls[0][0] as { data: Record<string, unknown> };
|
||||
expect(call.data).toHaveProperty("notes", "My annotation");
|
||||
expect(call.data).not.toHaveProperty("label");
|
||||
});
|
||||
|
||||
it("empty-args: returns 'nothing to update' and does NOT call prisma.favorite.update", async () => {
|
||||
const result = await handlers["update_favorite"]({ favoriteId: "ship:123" });
|
||||
|
||||
expect(mockPrisma.favorite.update).not.toHaveBeenCalled();
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text).toContain("nothing to update");
|
||||
});
|
||||
|
||||
it("not-found: P2025 error returns 'update_favorite: favorite not found'", async () => {
|
||||
const p2025 = Object.assign(new Error("not found"), { code: "P2025" });
|
||||
mockPrisma.favorite.update.mockRejectedValue(p2025);
|
||||
|
||||
const result = await handlers["update_favorite"]({
|
||||
favoriteId: "ship:999",
|
||||
name: "Ghost",
|
||||
});
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text).toBe("update_favorite: favorite not found");
|
||||
});
|
||||
|
||||
it("uses (userId, entityId) selector from ctx, never from args", async () => {
|
||||
mockPrisma.favorite.update.mockResolvedValue({ label: "X" } as never);
|
||||
|
||||
await handlers["update_favorite"]({ favoriteId: "ship:123", name: "X" });
|
||||
|
||||
expect(mockPrisma.favorite.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({ userId: "u1", entityId: "ship:123" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("remove_favorite tool handler", () => {
|
||||
it("calls prisma.favorite.delete with correct where clause including userId and entityId", async () => {
|
||||
mockPrisma.favorite.delete.mockResolvedValue({} as never);
|
||||
|
||||
await handlers["remove_favorite"]({ entityId: "ship:123" });
|
||||
|
||||
expect(mockPrisma.favorite.delete).toHaveBeenCalledWith({
|
||||
where: expect.objectContaining({
|
||||
userId: "u1",
|
||||
entityId: "ship:123",
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,239 +0,0 @@
|
||||
/**
|
||||
* MCP Favorites Tool registrar (Phase 22 Wave 2 -- 22-03).
|
||||
*
|
||||
* Registers four MCP tools that let an AI agent bookmark entities for a user:
|
||||
*
|
||||
* save_favorite -- upsert an entity bookmark (FAV-01)
|
||||
* list_favorites -- list bookmarks with per-entity liveness status (FAV-02)
|
||||
* remove_favorite -- delete a bookmark (FAV-03)
|
||||
* update_favorite -- rename/annotate an existing bookmark (CRUD-01)
|
||||
*
|
||||
* Security (SAFE-02): userId comes ONLY from ctx (the verified auth result). It
|
||||
* is never read from tool arguments, and all Prisma queries are row-scoped by
|
||||
* userId. Favorites are persisted directly via prisma.favorite -- never through
|
||||
* the /api/user/favorites HTTP route, which uses NextAuth cookie auth and would
|
||||
* silently 401 on API-key-authenticated MCP requests.
|
||||
*
|
||||
* Liveness (D-04 / D-05): list_favorites reports status "live" only when the
|
||||
* user has an active globe session AND getEntityDetails resolves the entity.
|
||||
* With no active session, ALL favorites are reported "stale" (no "unknown").
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { readActiveSessions } from "@/lib/globeStateStore";
|
||||
import { getEntityDetails } from "@/lib/data-query/service";
|
||||
import type { Prisma } from "@/generated/prisma";
|
||||
import { pluginIdSchema, entityIdSchema } from "@/lib/mcp/identifierSchemas";
|
||||
|
||||
const FAVORITES_CAP = 500;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type McpTextResult = { content: [{ type: "text"; text: string }] };
|
||||
|
||||
function textResult(text: string): McpTextResult {
|
||||
return { content: [{ type: "text", text }] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the unique-where selector for the (userId, entityId) compound key.
|
||||
*
|
||||
* Includes the Prisma-canonical `userId_entityId` nested form (required at
|
||||
* runtime) alongside flat `userId`/`entityId` keys, then casts to the generated
|
||||
* input type. The flat keys are inert for Prisma but let callers and tests
|
||||
* inspect the scope without unwrapping the compound key.
|
||||
*/
|
||||
function favoriteWhere(userId: string, entityId: string): Prisma.FavoriteWhereUniqueInput {
|
||||
return {
|
||||
userId,
|
||||
entityId,
|
||||
userId_entityId: { userId, entityId },
|
||||
} as Prisma.FavoriteWhereUniqueInput;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerFavoritesTools(
|
||||
server: McpServer,
|
||||
ctx: { userId: string },
|
||||
): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
// TOOL: save_favorite (FAV-01)
|
||||
server.registerTool(
|
||||
"save_favorite",
|
||||
{
|
||||
description:
|
||||
"Bookmark an entity so the user can return to it later (upsert by entityId -- re-saving updates, not duplicates). " +
|
||||
"Use when the user wants to track a specific entity across sessions. " +
|
||||
"Limitations: entityId must be the exact id used by the plugin; no validation is performed against live data. " +
|
||||
"Parameters: entityId (string, required); pluginId (string, required); name (string, optional, defaults to entityId). " +
|
||||
"Output: 'Saved favorite: <label>'. " +
|
||||
"Example: save_favorite({ entityId: 'AFR123', pluginId: 'flights', name: 'Air France 123' }).",
|
||||
inputSchema: {
|
||||
entityId: entityIdSchema.describe("Unique entity identifier"),
|
||||
pluginId: pluginIdSchema.describe("Plugin that owns this entity"),
|
||||
name: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(120)
|
||||
.optional()
|
||||
.describe("Human-readable label for the bookmark (defaults to entityId)"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
// Cap: reject new rows when the user already has FAVORITES_CAP favorites.
|
||||
// Upserts that update an existing row are always allowed.
|
||||
const existing = await prisma.favorite.findUnique({
|
||||
where: favoriteWhere(userId, args.entityId),
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existing) {
|
||||
const count = await prisma.favorite.count({ where: { userId } });
|
||||
if (count >= FAVORITES_CAP) {
|
||||
return textResult(`favorite limit of ${FAVORITES_CAP} reached`);
|
||||
}
|
||||
}
|
||||
|
||||
const label = args.name ?? args.entityId;
|
||||
await prisma.favorite.upsert({
|
||||
where: favoriteWhere(userId, args.entityId),
|
||||
update: {
|
||||
pluginId: args.pluginId,
|
||||
label,
|
||||
lastSeen: new Date(),
|
||||
},
|
||||
create: {
|
||||
userId,
|
||||
entityId: args.entityId,
|
||||
pluginId: args.pluginId,
|
||||
label,
|
||||
pluginName: args.pluginId,
|
||||
lastSeen: new Date(),
|
||||
},
|
||||
});
|
||||
return textResult(`Saved favorite: ${label}`);
|
||||
} catch (err) {
|
||||
console.error("[favoritesTools] save_favorite failed:", err);
|
||||
return textResult("save_favorite failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL: list_favorites (FAV-02)
|
||||
server.registerTool(
|
||||
"list_favorites",
|
||||
{
|
||||
description:
|
||||
"List the authenticated user's bookmarked entities, most recently seen first. " +
|
||||
"Use to find entityIds before calling remove_favorite, or to review which entities are currently live. " +
|
||||
"Limitations: status is 'live' only with an active globe session; with no active session ALL entries are reported 'stale'. Returns [] when there are no favorites. " +
|
||||
"Parameters: none. " +
|
||||
"Output: JSON array, each { id, entityId, pluginId, label, pluginName, lastSeen, notes, status: 'live'|'stale' }. " +
|
||||
"Example: list_favorites({}) -> [{ entityId: 'AFR123', pluginId: 'flights', label: 'Air France 123', notes: null, status: 'live' }].",
|
||||
inputSchema: {},
|
||||
},
|
||||
async () => {
|
||||
try {
|
||||
const favorites = await prisma.favorite.findMany({
|
||||
where: { userId },
|
||||
orderBy: { lastSeen: "desc" },
|
||||
});
|
||||
if (favorites.length === 0) return textResult(JSON.stringify([]));
|
||||
|
||||
const sessions = await readActiveSessions(userId);
|
||||
const hasSession = sessions.length > 0;
|
||||
|
||||
const results = await Promise.all(
|
||||
favorites.map(async (fav) => {
|
||||
if (!hasSession) {
|
||||
return { ...fav, status: "stale" as const };
|
||||
}
|
||||
const detail = await getEntityDetails(fav.pluginId, fav.entityId);
|
||||
return { ...fav, status: detail.data !== null ? ("live" as const) : ("stale" as const) };
|
||||
}),
|
||||
);
|
||||
return textResult(JSON.stringify(results));
|
||||
} catch (err) {
|
||||
console.error("[favoritesTools] list_favorites failed:", err);
|
||||
return textResult("list_favorites failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL: update_favorite (CRUD-01)
|
||||
server.registerTool(
|
||||
"update_favorite",
|
||||
{
|
||||
description:
|
||||
"Rename or annotate an existing bookmarked entity without deleting and re-creating it. " +
|
||||
"Use when the user wants to change the display name or add a personal note to an existing favorite. " +
|
||||
"Limitations: at least one of name or notes must be supplied; favoriteId must match an existing bookmark owned by the user. " +
|
||||
"Parameters: favoriteId (string, required, the entityId of the bookmark); name (string, optional, new display label); notes (string, optional, free-text annotation). " +
|
||||
"Output: 'Updated favorite: <label>' on success, or an error string. " +
|
||||
"Example: update_favorite({ favoriteId: 'AFR123', name: 'Air France 123', notes: 'Check weekly' }).",
|
||||
inputSchema: {
|
||||
favoriteId: entityIdSchema.describe("The entityId of the favorite to update"),
|
||||
name: z.string().min(1).max(120).optional().describe("New display label for the bookmark"),
|
||||
notes: z.string().max(2000).optional().describe("Free-text annotation to store with the bookmark"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
if (args.name === undefined && args.notes === undefined) {
|
||||
return textResult("update_favorite: nothing to update");
|
||||
}
|
||||
const data: { label?: string; notes?: string } = {};
|
||||
if (args.name !== undefined) data.label = args.name;
|
||||
if (args.notes !== undefined) data.notes = args.notes;
|
||||
try {
|
||||
const updated = await prisma.favorite.update({
|
||||
where: favoriteWhere(userId, args.favoriteId),
|
||||
data,
|
||||
});
|
||||
return textResult(`Updated favorite: ${updated.label}`);
|
||||
} catch (err) {
|
||||
const code = (err as { code?: string }).code;
|
||||
if (code === "P2025") {
|
||||
return textResult("update_favorite: favorite not found");
|
||||
}
|
||||
console.error("[favoritesTools] update_favorite failed:", err);
|
||||
return textResult("update_favorite failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL: remove_favorite (FAV-03)
|
||||
server.registerTool(
|
||||
"remove_favorite",
|
||||
{
|
||||
description:
|
||||
"Delete a bookmarked entity from the authenticated user's favorites. " +
|
||||
"Pair with list_favorites to find the correct entityId before removing. " +
|
||||
"Limitations: deletes by exact entityId; removing an entity that is not currently a favorite returns 'remove_favorite failed' (call list_favorites first to confirm it exists). " +
|
||||
"Parameters: entityId (string, required). " +
|
||||
"Output: 'Removed favorite: <entityId>'. " +
|
||||
"Example: remove_favorite({ entityId: 'AFR123' }).",
|
||||
inputSchema: {
|
||||
entityId: entityIdSchema.describe("Entity identifier to remove from favorites"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
await prisma.favorite.delete({
|
||||
where: favoriteWhere(userId, args.entityId),
|
||||
});
|
||||
return textResult(`Removed favorite: ${args.entityId}`);
|
||||
} catch (err) {
|
||||
console.error("[favoritesTools] remove_favorite failed:", err);
|
||||
return textResult("remove_favorite failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/globeCommandQueue");
|
||||
vi.mock("@/lib/mcpSessionCatalog");
|
||||
|
||||
// RED: ./filterTools does not exist yet. This import fails at collection time,
|
||||
// locking the three-tool contract (set_filter, clear_filter, get_plugin_filters).
|
||||
import { registerFilterTools } from "./filterTools";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
|
||||
const mockEnqueue = vi.mocked(enqueueGlobeCommand);
|
||||
const mockResolveActiveSessionId = vi.mocked(resolveActiveSessionId);
|
||||
const mockReadSessionCatalog = vi.mocked(readSessionCatalog);
|
||||
|
||||
const handlers: Record<string, (args: unknown) => unknown> = {};
|
||||
const schemas: Record<string, { description: string }> = {};
|
||||
const mockServer = {
|
||||
registerTool: vi.fn((name: string, schema: { description: string }, handler: (args: unknown) => unknown) => {
|
||||
handlers[name] = handler;
|
||||
schemas[name] = schema;
|
||||
}),
|
||||
};
|
||||
|
||||
const ctx = { userId: "u1" };
|
||||
|
||||
function textOf(result: unknown): string {
|
||||
return (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.keys(handlers).forEach((k) => delete handlers[k]);
|
||||
Object.keys(schemas).forEach((k) => delete schemas[k]);
|
||||
mockResolveActiveSessionId.mockResolvedValue("sess-abc");
|
||||
registerFilterTools(mockServer as never, ctx);
|
||||
});
|
||||
|
||||
describe("filterTools tool descriptions (DESC-03)", () => {
|
||||
const toolNames = ["set_filter", "clear_filter", "get_plugin_filters"];
|
||||
|
||||
it.each(toolNames)("%s description is non-empty and within 1024 chars", (name) => {
|
||||
const desc = schemas[name].description;
|
||||
expect(desc.length).toBeGreaterThan(0);
|
||||
expect(desc.length).toBeLessThanOrEqual(1024);
|
||||
});
|
||||
|
||||
it.each(toolNames)("%s description contains 'Example:'", (name) => {
|
||||
expect(schemas[name].description).toContain("Example:");
|
||||
});
|
||||
|
||||
it("get_plugin_filters description documents availability object shape", () => {
|
||||
const desc = schemas["get_plugin_filters"].description;
|
||||
expect(desc).toContain("available");
|
||||
expect(desc).toContain("no_session_active");
|
||||
});
|
||||
});
|
||||
|
||||
describe("set_filter tool handler", () => {
|
||||
it("enqueues a setFilter command with pluginId and filters", async () => {
|
||||
await handlers["set_filter"]({
|
||||
pluginId: "flights",
|
||||
filters: { status: { type: "select", values: ["airborne"] } },
|
||||
});
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"sess-abc",
|
||||
{ type: "setFilter", pluginId: "flights", filters: { status: { type: "select", values: ["airborne"] } } },
|
||||
);
|
||||
});
|
||||
|
||||
it("returns NO_SESSION text and does not enqueue when no active session", async () => {
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["set_filter"]({ pluginId: "flights", filters: {} });
|
||||
|
||||
expect(textOf(result)).toMatch(/no active globe session/i);
|
||||
expect(mockEnqueue).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("clear_filter tool handler", () => {
|
||||
it("enqueues clearFilter without a pluginId field when pluginId omitted", async () => {
|
||||
await handlers["clear_filter"]({});
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledWith("u1", "sess-abc", { type: "clearFilter" });
|
||||
});
|
||||
|
||||
it("enqueues clearFilter with pluginId when provided", async () => {
|
||||
await handlers["clear_filter"]({ pluginId: "flights" });
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledWith("u1", "sess-abc", { type: "clearFilter", pluginId: "flights" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("get_plugin_filters tool handler", () => {
|
||||
it("returns { available: true, filters: [...] } when plugin is loaded with filters", async () => {
|
||||
const defs = [{ id: "status", label: "Status", type: "select", propertyKey: "status" }];
|
||||
mockReadSessionCatalog.mockResolvedValue({
|
||||
tools: [],
|
||||
capabilities: [],
|
||||
filterDefinitions: { flights: defs },
|
||||
} as never);
|
||||
|
||||
const result = await handlers["get_plugin_filters"]({ pluginId: "flights" });
|
||||
const parsed = JSON.parse(textOf(result));
|
||||
|
||||
expect(parsed).toEqual({ available: true, filters: defs });
|
||||
});
|
||||
|
||||
it("returns { available: false, reason: 'no_session_active' } when no active session", async () => {
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["get_plugin_filters"]({ pluginId: "flights" });
|
||||
const parsed = JSON.parse(textOf(result));
|
||||
|
||||
expect(parsed).toEqual({ available: false, reason: "no_session_active" });
|
||||
});
|
||||
|
||||
it("returns { available: false, reason: 'plugin not loaded' } when plugin key absent from catalog", async () => {
|
||||
mockReadSessionCatalog.mockResolvedValue({
|
||||
tools: [],
|
||||
capabilities: [],
|
||||
filterDefinitions: {},
|
||||
} as never);
|
||||
|
||||
const result = await handlers["get_plugin_filters"]({ pluginId: "flights" });
|
||||
const parsed = JSON.parse(textOf(result));
|
||||
|
||||
expect(parsed).toEqual({ available: false, reason: "plugin not loaded" });
|
||||
});
|
||||
|
||||
it("returns { available: true, filters: [] } when plugin is loaded but declares no filters", async () => {
|
||||
mockReadSessionCatalog.mockResolvedValue({
|
||||
tools: [],
|
||||
capabilities: [],
|
||||
filterDefinitions: { flights: [] },
|
||||
} as never);
|
||||
|
||||
const result = await handlers["get_plugin_filters"]({ pluginId: "flights" });
|
||||
const parsed = JSON.parse(textOf(result));
|
||||
|
||||
expect(parsed).toEqual({ available: true, filters: [] });
|
||||
});
|
||||
});
|
||||
@@ -1,191 +0,0 @@
|
||||
/**
|
||||
* MCP Filter Tool registrar (Phase 23 Wave 2 -- 23-02).
|
||||
*
|
||||
* Registers three MCP tools that let an AI agent filter the live globe:
|
||||
*
|
||||
* set_filter -- push filter values to a plugin layer (FILT-01)
|
||||
* clear_filter -- clear one plugin's filters, or all filters (FILT-02)
|
||||
* get_plugin_filters -- read a plugin's declared filterable fields (FILT-03)
|
||||
*
|
||||
* set_filter / clear_filter enqueue a GlobeCommand via enqueueGlobeCommand; the
|
||||
* browser drains the queue over the SSE bridge and applies them to filterSlice.
|
||||
* get_plugin_filters reads the browser-published session catalog (D-05).
|
||||
*
|
||||
* Security: userId comes ONLY from ctx (the verified auth result). It is never
|
||||
* read from tool arguments. sessionId may come from args (scopes the tab) or is
|
||||
* resolved from the user's active ZSET entry.
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { filterValueSchema } from "@/lib/mcp/filterSchemas";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { pluginIdSchema } from "@/lib/mcp/identifierSchemas";
|
||||
import { listStreamingPlugins } from "@/app/api/mcp/discoveryHelpers";
|
||||
import { SESSION_REQUIRED_PREAMBLE } from "@/lib/mcp/toolDescriptionFragments";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type McpTextResult = { content: [{ type: "text"; text: string }] };
|
||||
|
||||
function textResult(text: string): McpTextResult {
|
||||
return { content: [{ type: "text", text }] };
|
||||
}
|
||||
|
||||
const NO_SESSION_RESULT = textResult("no active globe session to control");
|
||||
|
||||
/**
|
||||
* Resolves the session to use: explicit arg takes precedence, falling back to
|
||||
* the most-recently-active session for this user. Returns null if none is live.
|
||||
*/
|
||||
async function resolveSession(
|
||||
userId: string,
|
||||
argSessionId: string | undefined,
|
||||
): Promise<string | null> {
|
||||
if (argSessionId !== undefined && argSessionId !== "") {
|
||||
return argSessionId;
|
||||
}
|
||||
return resolveActiveSessionId(userId);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerFilterTools(
|
||||
server: McpServer,
|
||||
ctx: { userId: string },
|
||||
): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
// TOOL: set_filter (FILT-01)
|
||||
server.registerTool(
|
||||
"set_filter",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Apply one or more filters to a plugin's live globe layer (no page reload). " +
|
||||
"Use after get_plugin_filters to discover valid filter ids; affects the live globe layer, not data query tools. " +
|
||||
"Use list_available_plugins to confirm valid pluginIds before calling. " +
|
||||
"Limitations: filter ids are plugin-specific; unknown pluginIds produce a warning in the response. " +
|
||||
"Parameters: pluginId (string, required); filters (object, required) -- filterId -> { type: 'text', value } | { type: 'select', values } | { type: 'range', min, max } | { type: 'boolean', value }; sessionId (optional). " +
|
||||
"Output: 'set_filter command enqueued for <pluginId> (N filter(s))' or a warning when the pluginId is unrecognized. " +
|
||||
"Example: set_filter({ pluginId: 'flights', filters: { status: { type: 'select', values: ['airborne'] } } }).",
|
||||
inputSchema: {
|
||||
pluginId: pluginIdSchema.describe("Plugin whose layer to filter, e.g. 'flights'"),
|
||||
filters: z
|
||||
.record(z.string(), filterValueSchema)
|
||||
.describe("Map of filterId -> filter value. Discover valid filter ids via get_plugin_filters."),
|
||||
sessionId: z.string().optional().describe("Target globe session id. Omit to target most-recently-active tab."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
// Validate the pluginId against the live streaming plugin set.
|
||||
const { plugins } = await listStreamingPlugins();
|
||||
const knownIds = new Set(plugins.map((p) => p.pluginId));
|
||||
const isKnown = knownIds.has(args.pluginId);
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "setFilter",
|
||||
pluginId: args.pluginId,
|
||||
filters: args.filters,
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
|
||||
if (!isKnown) {
|
||||
return textResult(
|
||||
`Command enqueued, but pluginId '${args.pluginId}' is not a recognized plugin. It may be ignored.`,
|
||||
);
|
||||
}
|
||||
return textResult(
|
||||
`set_filter command enqueued for '${args.pluginId}' (${Object.keys(args.filters).length} filter(s))`,
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[filterTools] set_filter failed:", err);
|
||||
return textResult("set_filter command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL: clear_filter (FILT-02)
|
||||
server.registerTool(
|
||||
"clear_filter",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Clear active filters on the live globe. " +
|
||||
"Prefer clear_filter over re-setting filters to empty values; omit pluginId to clear ALL filters across every plugin at once. " +
|
||||
"Limitations: requires an active globe session; returns 'no active globe session to control' when no tab is live. " +
|
||||
"Parameters: pluginId (string, optional) -- omit to clear all plugins; sessionId (optional). " +
|
||||
"Output: 'clear_filter enqueued for <pluginId>' or 'clear_filter enqueued for ALL plugins'. " +
|
||||
"Example: clear_filter({ pluginId: 'flights' }) or clear_filter({}).",
|
||||
inputSchema: {
|
||||
pluginId: pluginIdSchema.optional().describe("Plugin whose filters to clear. Omit to clear ALL filters on the globe."),
|
||||
sessionId: z.string().optional().describe("Target globe session id. Omit to target most-recently-active tab."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "clearFilter",
|
||||
...(args.pluginId !== undefined && { pluginId: args.pluginId }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
return textResult(
|
||||
args.pluginId
|
||||
? `clear_filter enqueued for '${args.pluginId}'`
|
||||
: "clear_filter enqueued for ALL plugins",
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[filterTools] clear_filter failed:", err);
|
||||
return textResult("clear_filter command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL: get_plugin_filters (FILT-03)
|
||||
server.registerTool(
|
||||
"get_plugin_filters",
|
||||
{
|
||||
description:
|
||||
"Read-only discovery: list filterable fields a plugin has declared, so you can build a valid set_filter call. " +
|
||||
"Use before set_filter to confirm filter ids and value types for a plugin. " +
|
||||
"Limitations: returns { available: false, reason: 'no_session_active' } when no globe session is active (browser must be open); returns { available: false, reason: 'plugin not loaded' } when the plugin has not published its catalog. " +
|
||||
"Parameters: pluginId (string, required) -- the plugin to inspect. " +
|
||||
"Output: { available: true, filters: FilterDefinition[] } when the plugin is loaded, where each FilterDefinition is { id, label, type: 'text'|'select'|'range'|'boolean', propertyKey, options?, range? }; or { available: false, reason: 'plugin not loaded' | 'no_session_active' } when unavailable. " +
|
||||
"Example: get_plugin_filters({ pluginId: 'flights' }) -> { available: true, filters: [{ id: 'status', label: 'Status', type: 'select', options: [...] }] }.",
|
||||
inputSchema: {
|
||||
pluginId: pluginIdSchema.describe("Plugin to inspect for declared filterable fields"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveActiveSessionId(userId);
|
||||
if (!sessionId) {
|
||||
return textResult(JSON.stringify({ available: false, reason: "no_session_active" }));
|
||||
}
|
||||
|
||||
const catalog = await readSessionCatalog(userId, sessionId);
|
||||
const filterDefs = catalog?.filterDefinitions;
|
||||
if (!filterDefs || !(args.pluginId in filterDefs)) {
|
||||
return textResult(JSON.stringify({ available: false, reason: "plugin not loaded" }));
|
||||
}
|
||||
return textResult(JSON.stringify({ available: true, filters: filterDefs[args.pluginId] }));
|
||||
} catch (err) {
|
||||
console.error("[filterTools] get_plugin_filters failed:", err);
|
||||
return textResult(JSON.stringify({ available: false, reason: "plugin not loaded" }));
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/nominatim", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/lib/nominatim")>();
|
||||
return {
|
||||
...actual,
|
||||
fetchGeocode: vi.fn(),
|
||||
};
|
||||
});
|
||||
vi.mock("@/lib/geocodingRateLimit");
|
||||
vi.mock("@/lib/globeCommandQueue");
|
||||
|
||||
import { registerGeocodingTools } from "./geocodingTools";
|
||||
import { fetchGeocode } from "@/lib/nominatim";
|
||||
import { checkRateLimit } from "@/lib/geocodingRateLimit";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
|
||||
const mockFetchGeocode = vi.mocked(fetchGeocode);
|
||||
const mockCheckRateLimit = vi.mocked(checkRateLimit);
|
||||
const mockEnqueueGlobeCommand = vi.mocked(enqueueGlobeCommand);
|
||||
const mockResolveActiveSessionId = vi.mocked(resolveActiveSessionId);
|
||||
|
||||
const handlers: Record<string, (args: unknown) => unknown> = {};
|
||||
const schemas: Record<string, { description: string }> = {};
|
||||
const mockServer = {
|
||||
registerTool: vi.fn((name: string, schema: { description: string }, handler: (args: unknown) => unknown) => {
|
||||
handlers[name] = handler;
|
||||
schemas[name] = schema;
|
||||
}),
|
||||
};
|
||||
|
||||
const ctx = { userId: "u1" };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.keys(handlers).forEach((k) => delete handlers[k]);
|
||||
Object.keys(schemas).forEach((k) => delete schemas[k]);
|
||||
registerGeocodingTools(mockServer as never, ctx);
|
||||
});
|
||||
|
||||
describe("geocode_location tool handler", () => {
|
||||
it("returns structured result with lat/lng/name/bbox/importance when Nominatim returns results", async () => {
|
||||
mockCheckRateLimit.mockResolvedValue(undefined);
|
||||
mockFetchGeocode.mockResolvedValue([
|
||||
{
|
||||
lat: "51.5074",
|
||||
lon: "-0.1278",
|
||||
display_name: "London, UK",
|
||||
boundingbox: ["51.2868", "51.6919", "-0.5103", "0.3340"],
|
||||
importance: 0.9,
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await handlers["geocode_location"]({ query: "London", limit: 1 });
|
||||
|
||||
expect(result).toMatchObject({
|
||||
content: expect.arrayContaining([
|
||||
expect.objectContaining({ type: "text" }),
|
||||
]),
|
||||
});
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
const parsed = JSON.parse(text);
|
||||
expect(parsed[0]).toMatchObject({ lat: expect.any(Number), lng: expect.any(Number), name: expect.any(String) });
|
||||
expect(parsed[0]).toHaveProperty("bbox");
|
||||
expect(parsed[0]).toHaveProperty("importance");
|
||||
});
|
||||
|
||||
it("returns 'no results' message when Nominatim returns empty array", async () => {
|
||||
mockCheckRateLimit.mockResolvedValue(undefined);
|
||||
mockFetchGeocode.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["geocode_location"]({ query: "xyznonexistent" });
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text.toLowerCase()).toContain("no results");
|
||||
});
|
||||
|
||||
it("returns 'rate_limited' when checkRateLimit signals limit exceeded", async () => {
|
||||
mockCheckRateLimit.mockResolvedValue({ error: "rate_limited", retryAfterMs: 1000 });
|
||||
|
||||
const result = await handlers["geocode_location"]({ query: "Paris" });
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text).toContain("rate_limited");
|
||||
});
|
||||
|
||||
it("clamps default limit to 5 and max limit to 20", async () => {
|
||||
mockCheckRateLimit.mockResolvedValue(undefined);
|
||||
mockFetchGeocode.mockResolvedValue([]);
|
||||
|
||||
await handlers["geocode_location"]({ query: "test" });
|
||||
expect(mockFetchGeocode).toHaveBeenCalledWith(expect.objectContaining({ limit: 5 }));
|
||||
|
||||
await handlers["geocode_location"]({ query: "test", limit: 100 });
|
||||
expect(mockFetchGeocode).toHaveBeenCalledWith(expect.objectContaining({ limit: 20 }));
|
||||
});
|
||||
});
|
||||
|
||||
describe("geocodingTools tool descriptions (DESC-03)", () => {
|
||||
const toolNames = ["geocode_location", "fly_to"];
|
||||
|
||||
it.each(toolNames)("%s description is non-empty and within 1024 chars", (name) => {
|
||||
const desc = schemas[name].description;
|
||||
expect(desc.length).toBeGreaterThan(0);
|
||||
expect(desc.length).toBeLessThanOrEqual(1024);
|
||||
});
|
||||
|
||||
it.each(toolNames)("%s description contains 'Example:'", (name) => {
|
||||
expect(schemas[name].description).toContain("Example:");
|
||||
});
|
||||
|
||||
it("fly_to description contains globe://sessions precondition", () => {
|
||||
expect(schemas["fly_to"].description).toContain("globe://sessions");
|
||||
});
|
||||
|
||||
it("fly_to description contains no-session outcome", () => {
|
||||
expect(schemas["fly_to"].description).toContain("no active globe session to control");
|
||||
});
|
||||
|
||||
it("fly_to description contains Prefer disambiguation", () => {
|
||||
expect(schemas["fly_to"].description).toContain("Prefer");
|
||||
});
|
||||
});
|
||||
|
||||
describe("fly_to tool handler", () => {
|
||||
it("calls enqueueGlobeCommand with flyTo command for valid lat/lng", async () => {
|
||||
mockResolveActiveSessionId.mockResolvedValue("sess-abc");
|
||||
mockEnqueueGlobeCommand.mockResolvedValue(undefined);
|
||||
|
||||
await handlers["fly_to"]({ lat: 51.5, lng: -0.1 });
|
||||
|
||||
expect(mockEnqueueGlobeCommand).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"sess-abc",
|
||||
expect.objectContaining({ type: "flyTo", lat: 51.5, lng: -0.1 }),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns NO_SESSION_RESULT text when no active session exists", async () => {
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["fly_to"]({ lat: 51.5, lng: -0.1 });
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text).toMatch(/no.*(session|globe)/i);
|
||||
});
|
||||
|
||||
it("includes bbox in enqueueGlobeCommand call when bbox is provided", async () => {
|
||||
mockResolveActiveSessionId.mockResolvedValue("sess-abc");
|
||||
mockEnqueueGlobeCommand.mockResolvedValue(undefined);
|
||||
|
||||
await handlers["fly_to"]({ lat: 51.5, lng: -0.1, bbox: [-1, 50, 1, 52] });
|
||||
|
||||
expect(mockEnqueueGlobeCommand).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"sess-abc",
|
||||
expect.objectContaining({ bbox: [-1, 50, 1, 52] }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,186 +0,0 @@
|
||||
/**
|
||||
* MCP Geocoding Tool registrar (Phase 22 Wave 2, 22-02).
|
||||
*
|
||||
* Registers two MCP tools:
|
||||
* geocode_location: resolve a place name/address to coordinates via Nominatim
|
||||
* (GEO-01), with a per-user rate limit + 24h Redis cache (GEO-03)
|
||||
* fly_to: enqueue a flyTo GlobeCommand to move the browser camera (GEO-02)
|
||||
*
|
||||
* Security: userId comes ONLY from ctx (verified auth result), never from tool
|
||||
* arguments. The Nominatim URL is hardcoded; the user query is injected via
|
||||
* URLSearchParams inside fetchGeocode (no string concatenation).
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { fetchGeocode, normalizeNominatimResult } from "@/lib/nominatim";
|
||||
import type { RawNominatimItem } from "@/lib/nominatim";
|
||||
import { checkRateLimit } from "@/lib/geocodingRateLimit";
|
||||
import { redis } from "@/lib/redis";
|
||||
import { latSchema, lonSchema } from "@/lib/mcp/coordinateSchemas";
|
||||
import { SESSION_REQUIRED_PREAMBLE } from "@/lib/mcp/toolDescriptionFragments";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type McpTextResult = { content: [{ type: "text"; text: string }] };
|
||||
|
||||
function textResult(text: string): McpTextResult {
|
||||
return { content: [{ type: "text", text }] };
|
||||
}
|
||||
|
||||
const NO_SESSION_RESULT = textResult("no active globe session to control");
|
||||
|
||||
/** Best-effort cache read: a Redis outage degrades to a miss, never an error. */
|
||||
async function cacheGet(key: string): Promise<string | null> {
|
||||
try {
|
||||
return await redis.get(key);
|
||||
} catch (err) {
|
||||
console.warn("[geocodingTools] cache read failed (degrading to miss):", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Best-effort cache write: a Redis outage is logged and ignored. */
|
||||
async function cacheSet(key: string, value: string, ttlSeconds: number): Promise<void> {
|
||||
try {
|
||||
await redis.set(key, value, "EX", ttlSeconds);
|
||||
} catch (err) {
|
||||
console.warn("[geocodingTools] cache write failed (ignored):", err);
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_LIMIT = 5;
|
||||
const MAX_LIMIT = 20;
|
||||
const DEFAULT_ALTITUDE_M = 15_000;
|
||||
const CACHE_TTL_SECONDS = 86_400; // 24h
|
||||
|
||||
/**
|
||||
* Resolves the session to use: explicit arg takes precedence, falling back to
|
||||
* the most-recently-active session for this user. Returns null if none is live.
|
||||
*/
|
||||
async function resolveSession(
|
||||
userId: string,
|
||||
argSessionId: string | undefined,
|
||||
): Promise<string | null> {
|
||||
if (argSessionId !== undefined && argSessionId !== "") {
|
||||
return argSessionId;
|
||||
}
|
||||
return resolveActiveSessionId(userId);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerGeocodingTools(
|
||||
server: McpServer,
|
||||
ctx: { userId: string },
|
||||
): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
// GEO-01 + GEO-03: geocode_location
|
||||
server.registerTool(
|
||||
"geocode_location",
|
||||
{
|
||||
description:
|
||||
"Resolve a place name or address to coordinates and a bounding box via OpenStreetMap Nominatim. " +
|
||||
"Use before fly_to to obtain lat/lng from a name; do not guess coordinates. " +
|
||||
"Limitations: Nominatim is rate-limited per user; results are cached 24h; returns 'no results found' when nothing matches. " +
|
||||
"Parameters: query (string, required) - place name or address; limit (integer 1-20, optional, default 5). " +
|
||||
"Output: JSON array sorted by importance, each { lat, lng, name, name_en, type, addresstype, country, display_name, bbox: [west,south,east,north], importance }. " +
|
||||
"Example: geocode_location({ query: 'Paris', limit: 3 }) -> [{ lat: 48.85, lng: 2.35, name: 'Paris', bbox: [...] }].",
|
||||
inputSchema: {
|
||||
query: z.string().min(1).describe("Location name or address to geocode"),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(MAX_LIMIT)
|
||||
.optional()
|
||||
.describe("Max results to return (default 5, max 20)"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const limit = Math.min(args.limit ?? DEFAULT_LIMIT, MAX_LIMIT);
|
||||
const cacheKey = `geocode:${args.query.toLowerCase().trim()}:${limit}`;
|
||||
|
||||
const cached = await cacheGet(cacheKey);
|
||||
if (cached) return textResult(cached);
|
||||
|
||||
const rateLimitResult = await checkRateLimit(userId);
|
||||
if (rateLimitResult) return textResult(JSON.stringify(rateLimitResult));
|
||||
|
||||
const raw = await fetchGeocode({ query: args.query, limit });
|
||||
if (raw.length === 0) return textResult("no results found");
|
||||
|
||||
const results = (raw as RawNominatimItem[]).map(normalizeNominatimResult);
|
||||
const json = JSON.stringify(results);
|
||||
await cacheSet(cacheKey, json, CACHE_TTL_SECONDS);
|
||||
return textResult(json);
|
||||
} catch (err) {
|
||||
console.error("[geocodingTools] geocode_location failed:", err);
|
||||
return textResult("geocode_location command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// GEO-02: fly_to
|
||||
server.registerTool(
|
||||
"fly_to",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Fly the live globe camera to a geocoded coordinate, optionally fitting a bounding box in view. " +
|
||||
"Requires an active globe session (read globe://sessions first); returns 'no active globe session to control' when no tab is live. " +
|
||||
"Prefer pan_globe for relative panning or focus_entity to snap to a known entity; use fly_to when you have explicit lat/lng (e.g. from geocode_location). " +
|
||||
"Parameters: lat (-90..90, required), lng (-180..180, required), altitude (metres, optional, default 15000), " +
|
||||
"bbox ([west,south,east,north], optional - fit this region in view), sessionId (optional - omit for most-recently-active tab). " +
|
||||
"Example: fly_to({ lat: 48.85, lng: 2.35 }) or fly_to({ lat: 0, lng: 0, bbox: [2.2,48.8,2.5,48.9] }).",
|
||||
inputSchema: {
|
||||
lat: latSchema.describe("Latitude [-90, 90]"),
|
||||
lng: lonSchema.describe("Longitude [-180, 180]"),
|
||||
altitude: z
|
||||
.number()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe("Altitude in metres above ellipsoid (default 15000)"),
|
||||
bbox: z
|
||||
.tuple([z.number(), z.number(), z.number(), z.number()])
|
||||
.optional()
|
||||
.describe("[west, south, east, north] bounding box to fit in view"),
|
||||
sessionId: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Target globe session id. Omit to target most-recently-active tab."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "flyTo",
|
||||
lat: args.lat,
|
||||
lng: args.lng,
|
||||
alt: args.altitude ?? DEFAULT_ALTITUDE_M,
|
||||
...(args.bbox ? { bbox: args.bbox } : {}),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
|
||||
const label = args.bbox
|
||||
? `bbox=[${args.bbox.join(",")}]`
|
||||
: `lat=${args.lat}, lng=${args.lng}, alt=${args.altitude ?? DEFAULT_ALTITUDE_M}`;
|
||||
return textResult(`fly_to command enqueued (${label})`);
|
||||
} catch (err) {
|
||||
console.error("[geocodingTools] fly_to failed:", err);
|
||||
return textResult("fly_to command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,579 +0,0 @@
|
||||
/**
|
||||
* RED test scaffold for registerGlobeCommandTools (Phase 19a Wave 0).
|
||||
*
|
||||
* These tests INTENTIONALLY FAIL because globeCommandTools.ts does not exist yet.
|
||||
* They lock the following contracts:
|
||||
*
|
||||
* TOOL-01 All four tools are registered: pan_globe, focus_entity, toggle_layer, set_timeline
|
||||
* TOOL-02 pan_globe with explicit sessionId calls enqueueGlobeCommand directly (no resolve)
|
||||
* TOOL-03 toggle_layer without sessionId calls resolveActiveSessionId then enqueueGlobeCommand
|
||||
* TOOL-04 When resolveActiveSessionId returns null, handler returns graceful result, no enqueue
|
||||
* TOOL-05 userId comes ONLY from ctx, never from tool args
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { registerGlobeCommandTools, latSchema, lonSchema, altSchema } from "./globeCommandTools";
|
||||
import { isValidGlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { latSchema as sharedLatSchema, lonSchema as sharedLonSchema } from "@/lib/mcp/coordinateSchemas";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock @/lib/globeCommandQueue
|
||||
// vi.mock is hoisted above const declarations, so mock objects must be
|
||||
// declared with vi.hoisted() to be accessible inside the factory function.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const { mockEnqueue, mockResolveSessionId, mockListStreamingPlugins, mockGetEntityDetails } = vi.hoisted(() => ({
|
||||
mockEnqueue: vi.fn().mockResolvedValue(undefined),
|
||||
mockResolveSessionId: vi.fn().mockResolvedValue("resolved-session"),
|
||||
mockListStreamingPlugins: vi.fn().mockResolvedValue({ plugins: [] }),
|
||||
mockGetEntityDetails: vi.fn().mockResolvedValue({ data: null, emptyReason: "no_data_matches" }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/globeCommandQueue", () => ({
|
||||
enqueueGlobeCommand: mockEnqueue,
|
||||
resolveActiveSessionId: mockResolveSessionId,
|
||||
}));
|
||||
|
||||
vi.mock("./discoveryHelpers", () => ({
|
||||
listStreamingPlugins: mockListStreamingPlugins,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/data-query/service", () => ({
|
||||
getEntityDetails: mockGetEntityDetails,
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fake McpServer — records registered tools
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type ToolHandler = (input: Record<string, unknown>) => Promise<{ content: [{ type: "text"; text: string }] }>;
|
||||
|
||||
type ToolDef = { description: string; inputSchema: Record<string, unknown> };
|
||||
|
||||
function makeFakeServer() {
|
||||
const tools = new Map<string, ToolHandler>();
|
||||
const schemas = new Map<string, ToolDef>();
|
||||
const server = {
|
||||
registerTool: vi.fn((name: string, def: ToolDef, handler: ToolHandler) => {
|
||||
tools.set(name, handler);
|
||||
schemas.set(name, def);
|
||||
}),
|
||||
};
|
||||
return { server, tools, schemas };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mockEnqueue.mockResolvedValue(undefined);
|
||||
mockResolveSessionId.mockResolvedValue("resolved-session");
|
||||
mockListStreamingPlugins.mockResolvedValue({ plugins: [] });
|
||||
mockGetEntityDetails.mockResolvedValue({ data: null, emptyReason: "no_data_matches" });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-01: all four tools are registered
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("registerGlobeCommandTools registration (TOOL-01)", () => {
|
||||
it("registers pan_globe, focus_entity, toggle_layer, and set_timeline", () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
expect(tools.has("pan_globe")).toBe(true);
|
||||
expect(tools.has("focus_entity")).toBe(true);
|
||||
expect(tools.has("toggle_layer")).toBe(true);
|
||||
expect(tools.has("set_timeline")).toBe(true);
|
||||
});
|
||||
|
||||
it("calls server.registerTool exactly four times", () => {
|
||||
const { server } = makeFakeServer();
|
||||
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
expect(server.registerTool).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-02: pan_globe with explicit sessionId bypasses resolveActiveSessionId
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("pan_globe handler (TOOL-02)", () => {
|
||||
it("calls enqueueGlobeCommand with userId, sessionId, and pan GlobeCommand", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("pan_globe")!;
|
||||
await handler({ lat: 1, lon: 2, alt: 3, sessionId: "s9" });
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"s9",
|
||||
expect.objectContaining({ type: "pan", lat: 1, lon: 2, alt: 3 }),
|
||||
);
|
||||
});
|
||||
|
||||
it("does NOT call resolveActiveSessionId when sessionId is provided", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("pan_globe")!;
|
||||
await handler({ lat: 1, lon: 2, alt: 3, sessionId: "explicit-session" });
|
||||
|
||||
expect(mockResolveSessionId).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a success content result", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("pan_globe")!;
|
||||
const result = await handler({ lat: 40.7, lon: -74.0, alt: 500000, sessionId: "s9" });
|
||||
|
||||
expect(result).toHaveProperty("content");
|
||||
expect(Array.isArray(result.content)).toBe(true);
|
||||
expect(result.content[0]).toHaveProperty("type", "text");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-03: toggle_layer without sessionId calls resolveActiveSessionId
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("toggle_layer handler — session resolution (TOOL-03)", () => {
|
||||
it("calls resolveActiveSessionId(userId) when no sessionId is provided", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("toggle_layer")!;
|
||||
await handler({ layerId: "ais" });
|
||||
|
||||
expect(mockResolveSessionId).toHaveBeenCalledWith("u1");
|
||||
});
|
||||
|
||||
it("enqueues using the resolved sessionId", async () => {
|
||||
mockResolveSessionId.mockResolvedValue("resolved-s99");
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("toggle_layer")!;
|
||||
await handler({ layerId: "aviation" });
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"resolved-s99",
|
||||
expect.objectContaining({ type: "toggleLayer", layerId: "aviation" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-04: graceful result when no active session
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("handler graceful fallback — no active session (TOOL-04)", () => {
|
||||
beforeEach(() => {
|
||||
mockResolveSessionId.mockResolvedValue(null);
|
||||
});
|
||||
|
||||
it("does NOT call enqueueGlobeCommand when resolveActiveSessionId returns null", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("toggle_layer")!;
|
||||
await handler({ layerId: "ais" });
|
||||
|
||||
expect(mockEnqueue).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a content result mentioning no active globe session", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("toggle_layer")!;
|
||||
const result = await handler({ layerId: "ais" });
|
||||
|
||||
expect(result.content[0].type).toBe("text");
|
||||
expect(result.content[0].text.toLowerCase()).toContain("no active");
|
||||
});
|
||||
|
||||
it("set_timeline also returns graceful result without enqueuing", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "u1" });
|
||||
|
||||
const handler = tools.get("set_timeline")!;
|
||||
const result = await handler({ timeWindow: "24h" });
|
||||
|
||||
expect(mockEnqueue).not.toHaveBeenCalled();
|
||||
expect(result.content[0].text.toLowerCase()).toContain("no active");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-05: userId always from ctx, never from tool args
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("userId source invariant (TOOL-05)", () => {
|
||||
it("uses ctx.userId not a userId field in args", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, { userId: "ctx-user" });
|
||||
|
||||
const handler = tools.get("pan_globe")!;
|
||||
// Simulate a caller that supplies a userId in args — must be ignored
|
||||
await handler({ lat: 1, lon: 2, alt: 3, sessionId: "s1" });
|
||||
|
||||
const [calledUserId] = mockEnqueue.mock.calls[0] as [string, string, unknown];
|
||||
expect(calledUserId).toBe("ctx-user");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-06: coordinate schema bounds validation (latSchema / lonSchema / altSchema)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("coordinate schema bounds (TOOL-06)", () => {
|
||||
// latSchema
|
||||
it("latSchema accepts valid latitude", () => {
|
||||
expect(latSchema.safeParse(35.6762).success).toBe(true);
|
||||
expect(latSchema.safeParse(0).success).toBe(true);
|
||||
expect(latSchema.safeParse(-90).success).toBe(true);
|
||||
expect(latSchema.safeParse(90).success).toBe(true);
|
||||
});
|
||||
|
||||
it("latSchema rejects lat=999", () => {
|
||||
expect(latSchema.safeParse(999).success).toBe(false);
|
||||
});
|
||||
|
||||
it("latSchema rejects lat=-91", () => {
|
||||
expect(latSchema.safeParse(-91).success).toBe(false);
|
||||
});
|
||||
|
||||
it("latSchema rejects NaN", () => {
|
||||
expect(latSchema.safeParse(NaN).success).toBe(false);
|
||||
});
|
||||
|
||||
it("latSchema rejects Infinity", () => {
|
||||
expect(latSchema.safeParse(Infinity).success).toBe(false);
|
||||
});
|
||||
|
||||
// lonSchema
|
||||
it("lonSchema accepts valid longitude", () => {
|
||||
expect(lonSchema.safeParse(139.6503).success).toBe(true);
|
||||
expect(lonSchema.safeParse(-180).success).toBe(true);
|
||||
expect(lonSchema.safeParse(180).success).toBe(true);
|
||||
});
|
||||
|
||||
it("lonSchema rejects lon=181", () => {
|
||||
expect(lonSchema.safeParse(181).success).toBe(false);
|
||||
});
|
||||
|
||||
it("lonSchema rejects lon=-181", () => {
|
||||
expect(lonSchema.safeParse(-181).success).toBe(false);
|
||||
});
|
||||
|
||||
it("lonSchema rejects NaN", () => {
|
||||
expect(lonSchema.safeParse(NaN).success).toBe(false);
|
||||
});
|
||||
|
||||
// altSchema
|
||||
it("altSchema accepts valid altitude", () => {
|
||||
expect(altSchema.safeParse(2000000).success).toBe(true);
|
||||
expect(altSchema.safeParse(1).success).toBe(true);
|
||||
});
|
||||
|
||||
it("altSchema rejects alt=0", () => {
|
||||
expect(altSchema.safeParse(0).success).toBe(false);
|
||||
});
|
||||
|
||||
it("altSchema rejects negative altitude", () => {
|
||||
expect(altSchema.safeParse(-100).success).toBe(false);
|
||||
});
|
||||
|
||||
it("altSchema rejects Infinity", () => {
|
||||
expect(altSchema.safeParse(Infinity).success).toBe(false);
|
||||
});
|
||||
|
||||
it("altSchema rejects NaN", () => {
|
||||
expect(altSchema.safeParse(NaN).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-07: isValidGlobeCommand rejects out-of-range coordinates
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("isValidGlobeCommand coordinate bounds (TOOL-07)", () => {
|
||||
it("accepts a valid pan command", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 35.6762, lon: 139.6503, alt: 2000000 })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects pan with lat=999", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 999, lon: 0, alt: 1000 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with lat=-91", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: -91, lon: 0, alt: 1000 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with lon=181", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 0, lon: 181, alt: 1000 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with lon=-181", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 0, lon: -181, alt: 1000 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with alt=0", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 0, lon: 0, alt: 0 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with negative alt", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 0, lon: 0, alt: -500 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with NaN lat", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: NaN, lon: 0, alt: 1000 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pan with Infinity alt", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 0, lon: 0, alt: Infinity })).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts focusEntity with valid lat/lon", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", lat: 35.6762, lon: 139.6503 })).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts focusEntity with no lat/lon (entity-id only)", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "ent-1" })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects focusEntity with out-of-range lat", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", lat: 91, lon: 0 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects focusEntity with out-of-range lon", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", lat: 0, lon: 200 })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-08: isValidGlobeCommand rejects NaN heading (isNumber requires isFinite)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("isValidGlobeCommand NaN heading rejection (TOOL-08)", () => {
|
||||
it("rejects a pan command with heading: NaN", () => {
|
||||
expect(isValidGlobeCommand({ type: "pan", lat: 0, lon: 0, alt: 1000, heading: NaN })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DESC-01: command tool description standard assertions
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("command tool descriptions (DESC-01)", () => {
|
||||
const TOOL_NAMES = ["pan_globe", "focus_entity", "toggle_layer", "set_timeline"] as const;
|
||||
|
||||
function getSchemas() {
|
||||
const { server, schemas } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
return schemas;
|
||||
}
|
||||
|
||||
it.each(TOOL_NAMES)("%s description length is > 0 and <= 1024 chars", (name) => {
|
||||
const schemas = getSchemas();
|
||||
const desc = schemas.get(name)!.description;
|
||||
expect(desc.length).toBeGreaterThan(0);
|
||||
expect(desc.length).toBeLessThanOrEqual(1024);
|
||||
});
|
||||
|
||||
it.each(TOOL_NAMES)("%s description includes globe://sessions", (name) => {
|
||||
const schemas = getSchemas();
|
||||
expect(schemas.get(name)!.description).toContain("globe://sessions");
|
||||
});
|
||||
|
||||
it.each(TOOL_NAMES)('%s description includes "no active globe session to control"', (name) => {
|
||||
const schemas = getSchemas();
|
||||
expect(schemas.get(name)!.description).toContain("no active globe session to control");
|
||||
});
|
||||
|
||||
it.each(TOOL_NAMES)('%s description includes a "Prefer " disambiguation line', (name) => {
|
||||
const schemas = getSchemas();
|
||||
expect(schemas.get(name)!.description).toContain("Prefer ");
|
||||
});
|
||||
|
||||
it.each(TOOL_NAMES)('%s description includes an "Example:" call', (name) => {
|
||||
const schemas = getSchemas();
|
||||
expect(schemas.get(name)!.description).toContain("Example:");
|
||||
});
|
||||
|
||||
it("set_timeline description includes at least one timeWindow enum literal", () => {
|
||||
const schemas = getSchemas();
|
||||
const desc = schemas.get("set_timeline")!.description;
|
||||
const timeWindowValues = ["1h", "6h", "24h", "48h", "7d"];
|
||||
const found = timeWindowValues.some((v) => desc.includes(v));
|
||||
expect(found).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-09: get_entities_in_region schema bounds (latSchema / lonSchema shared module)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("get_entities_in_region coordinate schema bounds (TOOL-09)", () => {
|
||||
it("rejects north=999 (out-of-range latitude)", () => {
|
||||
expect(sharedLatSchema.safeParse(999).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects west=-200 (out-of-range longitude)", () => {
|
||||
expect(sharedLonSchema.safeParse(-200).success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a valid bounding box", () => {
|
||||
expect(sharedLatSchema.safeParse(51.5).success).toBe(true); // north
|
||||
expect(sharedLatSchema.safeParse(48.8).success).toBe(true); // south
|
||||
expect(sharedLonSchema.safeParse(-0.1).success).toBe(true); // west
|
||||
expect(sharedLonSchema.safeParse(2.3).success).toBe(true); // east
|
||||
});
|
||||
|
||||
it("rejects NaN for a latitude bound", () => {
|
||||
expect(sharedLatSchema.safeParse(NaN).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects Infinity for a longitude bound", () => {
|
||||
expect(sharedLonSchema.safeParse(Infinity).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-02 (Phase 33): toggle_layer unrecognized id warning
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("toggle_layer -- unrecognized layerId warning (TOOL-02/P33)", () => {
|
||||
it("enqueues command and returns warning when layerId is not a known plugin", async () => {
|
||||
mockListStreamingPlugins.mockResolvedValue({ plugins: [{ pluginId: "flights" }] });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("toggle_layer")!({ layerId: "unknown-layer-xyz" });
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledOnce();
|
||||
expect(result.content[0].text).toContain("not a recognized plugin");
|
||||
expect(result.content[0].text).toContain("unknown-layer-xyz");
|
||||
});
|
||||
|
||||
it("enqueues command and returns plain success when layerId is recognized", async () => {
|
||||
mockListStreamingPlugins.mockResolvedValue({ plugins: [{ pluginId: "flights" }] });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("toggle_layer")!({ layerId: "flights" });
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledOnce();
|
||||
expect(result.content[0].text).not.toContain("not a recognized plugin");
|
||||
expect(result.content[0].text).toContain("flights");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-02 (Phase 33): focus_entity server-side entity-id resolution
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("focus_entity -- server-side entity resolution (TOOL-02/P33)", () => {
|
||||
it("resolves lat/lon from entityId+pluginId when coordinates are absent", async () => {
|
||||
mockGetEntityDetails.mockResolvedValue({
|
||||
data: {
|
||||
id: "ship-1",
|
||||
pluginId: "ais",
|
||||
latitude: 35.68,
|
||||
longitude: 139.69,
|
||||
timestamp: new Date(),
|
||||
properties: {},
|
||||
},
|
||||
});
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("focus_entity")!({
|
||||
entityId: "ship-1",
|
||||
pluginId: "ais",
|
||||
});
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"resolved-session",
|
||||
expect.objectContaining({ type: "focusEntity", lat: 35.68, lon: 139.69 }),
|
||||
);
|
||||
expect(result.content[0].text).toContain("35.68");
|
||||
});
|
||||
|
||||
it("returns honest failure when entityId cannot be resolved (no pluginId provided)", async () => {
|
||||
// Without pluginId the resolver path is skipped and resolution fails.
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("focus_entity")!({ entityId: "unknown-entity" });
|
||||
|
||||
expect(mockEnqueue).not.toHaveBeenCalled();
|
||||
expect(result.content[0].text).toContain("Could not resolve entityId");
|
||||
expect(result.content[0].text).toContain("unknown-entity");
|
||||
});
|
||||
|
||||
it("returns honest failure when entity not found in plugin snapshot", async () => {
|
||||
mockGetEntityDetails.mockResolvedValue({ data: null, emptyReason: "no_data_matches" });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("focus_entity")!({
|
||||
entityId: "missing-entity",
|
||||
pluginId: "ais",
|
||||
});
|
||||
|
||||
expect(mockEnqueue).not.toHaveBeenCalled();
|
||||
expect(result.content[0].text).toContain("Could not resolve entityId");
|
||||
});
|
||||
|
||||
it("uses provided lat/lon directly without calling getEntityDetails", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("focus_entity")!({
|
||||
entityId: "e1",
|
||||
lat: 10,
|
||||
lon: 20,
|
||||
});
|
||||
|
||||
expect(mockGetEntityDetails).not.toHaveBeenCalled();
|
||||
expect(mockEnqueue).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"resolved-session",
|
||||
expect.objectContaining({ lat: 10, lon: 20 }),
|
||||
);
|
||||
expect(result.content[0].text).toContain("10");
|
||||
});
|
||||
});
|
||||
@@ -1,264 +0,0 @@
|
||||
/**
|
||||
* MCP Globe Command Tool registrar (Phase 19a Wave 2 -- 19-03).
|
||||
*
|
||||
* Registers four MCP tools that let an AI agent control the live globe in the
|
||||
* browser. Commands are enqueued to a per-session Redis list; the browser polls
|
||||
* GET /api/globe/commands to drain them (poll-based delivery, 19a transport).
|
||||
*
|
||||
* pan_globe -- fly the camera to a lat/lon/altitude
|
||||
* focus_entity -- point the camera at a known entity or coordinate
|
||||
* toggle_layer -- enable or disable a named plugin layer
|
||||
* set_timeline -- set playback time / window / mode
|
||||
*
|
||||
* Security: userId comes ONLY from ctx (the verified auth result). It is never
|
||||
* read from tool arguments. sessionId may come from args (scopes the tab) or is
|
||||
* resolved from the user's active ZSET entry.
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { TIME_WINDOW_VALUES } from "@/core/globe/types/GlobeCommand";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { latSchema, lonSchema, altSchema } from "@/lib/mcp/coordinateSchemas";
|
||||
import { layerIdSchema, entityIdSchema } from "@/lib/mcp/identifierSchemas";
|
||||
import { SESSION_REQUIRED_PREAMBLE } from "@/lib/mcp/toolDescriptionFragments";
|
||||
import { listStreamingPlugins } from "./discoveryHelpers";
|
||||
import { getEntityDetails } from "@/lib/data-query/service";
|
||||
|
||||
// Re-export so existing tests that import from this module continue to work.
|
||||
export { latSchema, lonSchema, altSchema, layerIdSchema };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type McpTextResult = { content: [{ type: "text"; text: string }] };
|
||||
|
||||
function textResult(text: string): McpTextResult {
|
||||
return { content: [{ type: "text", text }] };
|
||||
}
|
||||
|
||||
const NO_SESSION_RESULT = textResult("no active globe session to control");
|
||||
|
||||
/**
|
||||
* Resolves the session to use: explicit arg takes precedence, falling back to
|
||||
* the most-recently-active session for this user. Returns null if none is live.
|
||||
*/
|
||||
async function resolveSession(
|
||||
userId: string,
|
||||
argSessionId: string | undefined,
|
||||
): Promise<string | null> {
|
||||
if (argSessionId !== undefined && argSessionId !== "") {
|
||||
return argSessionId;
|
||||
}
|
||||
return resolveActiveSessionId(userId);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerGlobeCommandTools(
|
||||
server: McpServer,
|
||||
ctx: { userId: string },
|
||||
): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
// TOOL-01: pan_globe
|
||||
server.registerTool(
|
||||
"pan_globe",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Fly the globe camera to an explicit coordinate. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
|
||||
"Prefer pan_globe over focus_entity when you have a lat/lon and no entity id, or when focus_entity entity-id resolution is not needed. " +
|
||||
"Limitations: latitude [-90, 90], longitude [-180, 180], altitude > 0 metres; out-of-range values are rejected. " +
|
||||
"Parameters: lat (required), lon (required), alt in metres (required), heading (deg, optional), pitch (deg, optional), duration (seconds, optional), sessionId (optional, omit to target most-recently-active tab). " +
|
||||
"Example: pan_globe({lat:48.8566,lon:2.3522,alt:500000})",
|
||||
inputSchema: {
|
||||
lat: latSchema.describe("Latitude in decimal degrees [-90, 90]"),
|
||||
lon: lonSchema.describe("Longitude in decimal degrees [-180, 180]"),
|
||||
alt: altSchema.describe("Altitude in metres above the ellipsoid (must be > 0)"),
|
||||
heading: z.number().optional().describe("Camera heading in degrees (0 = north)"),
|
||||
pitch: z.number().optional().describe("Camera pitch in degrees (-90 = straight down)"),
|
||||
duration: z.number().optional().describe("Flight animation duration in seconds"),
|
||||
sessionId: z.string().optional().describe("Target globe session id. Obtain valid ids by reading the globe://sessions resource. Omit to target your most-recently-active browser tab."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "pan",
|
||||
lat: args.lat,
|
||||
lon: args.lon,
|
||||
alt: args.alt,
|
||||
...(args.heading !== undefined && { heading: args.heading }),
|
||||
...(args.pitch !== undefined && { pitch: args.pitch }),
|
||||
...(args.duration !== undefined && { duration: args.duration }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
return textResult(`Camera panning to lat=${args.lat}, lon=${args.lon}, alt=${args.alt}`);
|
||||
} catch (err) {
|
||||
console.error("[globeCommandTools] pan_globe failed:", err);
|
||||
return textResult("pan_globe command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL-02: focus_entity
|
||||
server.registerTool(
|
||||
"focus_entity",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Point the globe camera at a known entity or coordinate. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
|
||||
"Prefer focus_entity over pan_globe when you have an entity id and want to centre on it. " +
|
||||
"When lat/lon are provided they are used directly. " +
|
||||
"When only entityId is provided (no lat/lon), the server resolves coordinates via pluginId + entityId lookup -- include pluginId for a faster, scoped lookup. " +
|
||||
"Returns an error string when entityId cannot be resolved to coordinates. " +
|
||||
"Limitations: latitude [-90, 90], longitude [-180, 180]. " +
|
||||
"Parameters: entityId (optional), pluginId (optional, scopes entity lookup), lat (optional), lon (optional), sessionId (optional). " +
|
||||
"Example: focus_entity({entityId:\"ship-123\",pluginId:\"ais\",lat:35.68,lon:139.69})",
|
||||
inputSchema: {
|
||||
entityId: entityIdSchema.optional().describe("Entity id to focus on"),
|
||||
pluginId: z.string().optional().describe("Plugin that owns this entity -- narrows the id lookup when lat/lon are not provided"),
|
||||
lat: latSchema.optional().describe("Latitude to focus on [-90, 90]"),
|
||||
lon: lonSchema.optional().describe("Longitude to focus on [-180, 180]"),
|
||||
sessionId: z.string().optional().describe("Target globe session id. Obtain valid ids by reading the globe://sessions resource. Omit to target your most-recently-active browser tab."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
let resolvedLat = args.lat;
|
||||
let resolvedLon = args.lon;
|
||||
|
||||
// When coordinates are absent but entityId is present, resolve server-side.
|
||||
if (resolvedLat === undefined && resolvedLon === undefined && args.entityId !== undefined) {
|
||||
if (args.pluginId !== undefined) {
|
||||
const detail = await getEntityDetails(args.pluginId, args.entityId);
|
||||
if (detail.data !== null) {
|
||||
resolvedLat = detail.data.latitude;
|
||||
resolvedLon = detail.data.longitude;
|
||||
}
|
||||
}
|
||||
|
||||
if (resolvedLat === undefined) {
|
||||
// entityId could not be resolved -- return an honest failure instead of
|
||||
// enqueuing a command the browser cannot execute.
|
||||
return textResult(
|
||||
`Could not resolve entityId '${args.entityId}' to coordinates. ` +
|
||||
`Provide pluginId to scope the lookup, or include lat/lon directly.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "focusEntity",
|
||||
...(args.entityId !== undefined && { entityId: args.entityId }),
|
||||
...(resolvedLat !== undefined && { lat: resolvedLat }),
|
||||
...(resolvedLon !== undefined && { lon: resolvedLon }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
return textResult(
|
||||
`Focus entity command enqueued (entityId=${args.entityId ?? "none"}, lat=${resolvedLat ?? "none"}, lon=${resolvedLon ?? "none"})`,
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[globeCommandTools] focus_entity failed:", err);
|
||||
return textResult("focus_entity command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL-03: toggle_layer
|
||||
server.registerTool(
|
||||
"toggle_layer",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Enable or disable a plugin data layer on the globe. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
|
||||
"Prefer toggle_layer over pan_globe or set_timeline when changing layer visibility, not camera position or playback time. " +
|
||||
"Use list_available_plugins to confirm valid layerIds before calling. " +
|
||||
"Limitations: layerId must match an installed plugin id. When the id is not recognized a warning is included in the response. " +
|
||||
"Parameters: layerId (required), enabled (true/false, optional -- omit to toggle current state), sessionId (optional). " +
|
||||
"Example: toggle_layer({layerId:\"ais\",enabled:true})",
|
||||
inputSchema: {
|
||||
layerId: layerIdSchema.describe("The plugin/layer identifier to toggle"),
|
||||
enabled: z.boolean().optional().describe("True to enable, false to disable, omit to toggle"),
|
||||
sessionId: z.string().optional().describe("Target globe session id. Obtain valid ids by reading the globe://sessions resource. Omit to target your most-recently-active browser tab."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
// Check whether the layerId matches a known streaming plugin.
|
||||
const { plugins } = await listStreamingPlugins();
|
||||
const knownIds = new Set(plugins.map((p) => p.pluginId));
|
||||
const isKnown = knownIds.has(args.layerId);
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "toggleLayer",
|
||||
layerId: args.layerId,
|
||||
...(args.enabled !== undefined && { enabled: args.enabled }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
|
||||
if (!isKnown) {
|
||||
return textResult(
|
||||
`Command enqueued, but layerId '${args.layerId}' is not a recognized plugin. It may be ignored.`,
|
||||
);
|
||||
}
|
||||
return textResult(`Layer '${args.layerId}' toggle command enqueued`);
|
||||
} catch (err) {
|
||||
console.error("[globeCommandTools] toggle_layer failed:", err);
|
||||
return textResult("toggle_layer command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL-04: set_timeline
|
||||
server.registerTool(
|
||||
"set_timeline",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Set the globe timeline position, time window, or playback mode. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
|
||||
"Prefer set_timeline over toggle_layer or pan_globe when adjusting time or playback, not layer visibility or camera position. " +
|
||||
"Limitations: currentTime must be ISO 8601; timeWindow must be one of '1h','6h','24h','48h','7d'. " +
|
||||
"Parameters: currentTime (ISO 8601, optional), timeWindow (optional), isPlaybackMode (boolean, optional), sessionId (optional). " +
|
||||
"Example: set_timeline({timeWindow:\"24h\",isPlaybackMode:true})",
|
||||
inputSchema: {
|
||||
currentTime: z.string().optional().describe("ISO 8601 datetime to seek to"),
|
||||
timeWindow: z.enum(TIME_WINDOW_VALUES).optional().describe("Time window: one of '1h', '6h', '24h', '48h', '7d'"),
|
||||
isPlaybackMode: z.boolean().optional().describe("True to start playback, false to pause"),
|
||||
sessionId: z.string().optional().describe("Target globe session id. Obtain valid ids by reading the globe://sessions resource. Omit to target your most-recently-active browser tab."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "setTimeline",
|
||||
...(args.currentTime !== undefined && { currentTime: args.currentTime }),
|
||||
...(args.timeWindow !== undefined && { timeWindow: args.timeWindow }),
|
||||
...(args.isPlaybackMode !== undefined && { isPlaybackMode: args.isPlaybackMode }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
return textResult("Timeline command enqueued");
|
||||
} catch (err) {
|
||||
console.error("[globeCommandTools] set_timeline failed:", err);
|
||||
return textResult("set_timeline command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,266 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { registerGlobeResources } from "./globeResources";
|
||||
import {
|
||||
readGlobeState,
|
||||
readActiveSessions,
|
||||
} from "@/lib/globeStateStore";
|
||||
|
||||
vi.mock("@/lib/globeStateStore", () => ({
|
||||
readGlobeState: vi.fn(),
|
||||
readActiveSessions: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockReadState = vi.mocked(readGlobeState);
|
||||
const mockReadSessions = vi.mocked(readActiveSessions);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fake MCP server — captures registerResource calls for assertion.
|
||||
// Shape mirrors the McpServer surface used by registerGlobeResources.
|
||||
// ---------------------------------------------------------------------------
|
||||
function makeFakeServer() {
|
||||
return {
|
||||
registerResource: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// RSRC-02/03/04 — registerGlobeResources registration
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("registerGlobeResources — resource registration", () => {
|
||||
it("calls server.registerResource exactly three times (RSRC-02/03/04)", () => {
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
expect(server.registerResource).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("registers globe://state/{sessionId} resource (RSRC-02)", () => {
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
const uris = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).map(
|
||||
([uriOrTemplate]) =>
|
||||
typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate,
|
||||
);
|
||||
expect(uris.some((u: string) => u.includes("state"))).toBe(true);
|
||||
});
|
||||
|
||||
it("registers globe://sessions resource (RSRC-03)", () => {
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
const uris = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).map(
|
||||
([uriOrTemplate]) =>
|
||||
typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate,
|
||||
);
|
||||
expect(uris.some((u: string) => u.includes("sessions"))).toBe(true);
|
||||
});
|
||||
|
||||
it("registers globe://layers resource (RSRC-04)", () => {
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
const uris = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).map(
|
||||
([uriOrTemplate]) =>
|
||||
typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate,
|
||||
);
|
||||
expect(uris.some((u: string) => u.includes("layers"))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// RSRC-02 — globe://state/{sessionId} handler
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("globe://state handler (RSRC-02)", () => {
|
||||
it("calls readGlobeState with injected userId 'u1' and the given sessionId", async () => {
|
||||
const snapshot = {
|
||||
viewport: { lat: 37.7, lon: -122.4, altitude: 500000, heading: 0, pitch: -90, roll: 0 },
|
||||
layers: {},
|
||||
timeline: {
|
||||
currentTime: "2026-01-15T12:00:00.000Z",
|
||||
timeWindow: "24h",
|
||||
isPlaybackMode: false,
|
||||
playbackTime: 1737000000000,
|
||||
playbackSpeed: 1,
|
||||
},
|
||||
selectedEntity: null,
|
||||
lastUpdate: 1737000000000,
|
||||
};
|
||||
mockReadState.mockResolvedValue(snapshot);
|
||||
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
// Find the state resource handler (the call whose URI/template contains "state")
|
||||
const stateCall = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).find(
|
||||
([uriOrTemplate]) => {
|
||||
const s = typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate;
|
||||
return s.includes("state");
|
||||
},
|
||||
);
|
||||
expect(stateCall).toBeDefined();
|
||||
|
||||
// The handler is the last argument in the registerResource call
|
||||
const handler = stateCall![stateCall!.length - 1] as (
|
||||
uri: URL,
|
||||
params: Record<string, string>,
|
||||
) => Promise<unknown>;
|
||||
|
||||
const uri = new URL("globe://state/s1");
|
||||
const result = await handler(uri, { sessionId: "s1" });
|
||||
|
||||
expect(mockReadState).toHaveBeenCalledWith("u1", "s1");
|
||||
|
||||
// Response shape: { contents: [{ uri, mimeType, text }] }
|
||||
expect(result).toHaveProperty("contents");
|
||||
const contents = (result as { contents: unknown[] }).contents;
|
||||
expect(Array.isArray(contents)).toBe(true);
|
||||
expect(contents[0]).toHaveProperty("mimeType", "application/json");
|
||||
expect(contents[0]).toHaveProperty("text");
|
||||
const parsed = JSON.parse((contents[0] as { text: string }).text);
|
||||
expect(parsed).toEqual(snapshot);
|
||||
});
|
||||
|
||||
it("uses injected userId 'u1' — never a hardcoded value", async () => {
|
||||
mockReadState.mockResolvedValue(null);
|
||||
|
||||
const server = makeFakeServer();
|
||||
// Register with a different userId to confirm scoping
|
||||
registerGlobeResources(server as never, { userId: "other-user" });
|
||||
|
||||
const stateCall = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).find(
|
||||
([uriOrTemplate]) => {
|
||||
const s = typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate;
|
||||
return s.includes("state");
|
||||
},
|
||||
);
|
||||
const handler = stateCall![stateCall!.length - 1] as (
|
||||
uri: URL,
|
||||
params: Record<string, string>,
|
||||
) => Promise<unknown>;
|
||||
|
||||
await handler(new URL("globe://state/s1"), { sessionId: "s1" });
|
||||
|
||||
expect(mockReadState).toHaveBeenCalledWith("other-user", "s1");
|
||||
expect(mockReadState).not.toHaveBeenCalledWith("u1", expect.anything());
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// RSRC-03 — globe://sessions handler
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("globe://sessions handler (RSRC-03)", () => {
|
||||
it("calls readActiveSessions with injected userId and returns session list as JSON", async () => {
|
||||
const sessions = [
|
||||
{ sessionId: "fresh-1", lastSeen: Date.now() },
|
||||
{ sessionId: "fresh-2", lastSeen: Date.now() - 5000 },
|
||||
];
|
||||
mockReadSessions.mockResolvedValue(sessions);
|
||||
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
const sessionsCall = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).find(
|
||||
([uriOrTemplate]) => {
|
||||
const s = typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate;
|
||||
return s.includes("sessions");
|
||||
},
|
||||
);
|
||||
expect(sessionsCall).toBeDefined();
|
||||
|
||||
const handler = sessionsCall![sessionsCall!.length - 1] as (
|
||||
uri: URL,
|
||||
params: Record<string, string>,
|
||||
) => Promise<unknown>;
|
||||
|
||||
const result = await handler(new URL("globe://sessions"), {});
|
||||
|
||||
expect(mockReadSessions).toHaveBeenCalledWith("u1");
|
||||
|
||||
const contents = (result as { contents: { text: string }[] }).contents;
|
||||
const parsed = JSON.parse(contents[0].text);
|
||||
expect(parsed).toEqual(sessions);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// RSRC-04 — globe://layers handler
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("globe://layers handler (RSRC-04)", () => {
|
||||
it("returns layers from the most-recent session snapshot as JSON", async () => {
|
||||
const layers = {
|
||||
aviation: { enabled: true, entityCount: 10, loading: false },
|
||||
maritime: { enabled: false, entityCount: 0, loading: false },
|
||||
};
|
||||
const snapshot = {
|
||||
viewport: { lat: 0, lon: 0, altitude: 1000000, heading: 0, pitch: -90, roll: 0 },
|
||||
layers,
|
||||
timeline: {
|
||||
currentTime: "2026-01-15T12:00:00.000Z",
|
||||
timeWindow: "24h",
|
||||
isPlaybackMode: false,
|
||||
playbackTime: 1737000000000,
|
||||
playbackSpeed: 1,
|
||||
},
|
||||
selectedEntity: null,
|
||||
lastUpdate: 1737000000000,
|
||||
};
|
||||
|
||||
const sessions = [{ sessionId: "sess-latest", lastSeen: Date.now() }];
|
||||
mockReadSessions.mockResolvedValue(sessions);
|
||||
mockReadState.mockResolvedValue(snapshot);
|
||||
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "u1" });
|
||||
|
||||
const layersCall = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).find(
|
||||
([uriOrTemplate]) => {
|
||||
const s = typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate;
|
||||
return s.includes("layers");
|
||||
},
|
||||
);
|
||||
expect(layersCall).toBeDefined();
|
||||
|
||||
const handler = layersCall![layersCall!.length - 1] as (
|
||||
uri: URL,
|
||||
params: Record<string, string>,
|
||||
) => Promise<unknown>;
|
||||
|
||||
const result = await handler(new URL("globe://layers"), {});
|
||||
|
||||
const contents = (result as { contents: { text: string }[] }).contents;
|
||||
const parsed = JSON.parse(contents[0].text);
|
||||
expect(parsed).toEqual(layers);
|
||||
});
|
||||
|
||||
it("scopes readActiveSessions by injected userId 'u1', never hardcoded", async () => {
|
||||
mockReadSessions.mockResolvedValue([]);
|
||||
|
||||
const server = makeFakeServer();
|
||||
registerGlobeResources(server as never, { userId: "scoped-user" });
|
||||
|
||||
const layersCall = (server.registerResource.mock.calls as [string | { uriTemplate: string }, ...unknown[]][]).find(
|
||||
([uriOrTemplate]) => {
|
||||
const s = typeof uriOrTemplate === "string" ? uriOrTemplate : uriOrTemplate.uriTemplate;
|
||||
return s.includes("layers");
|
||||
},
|
||||
);
|
||||
const handler = layersCall![layersCall!.length - 1] as (
|
||||
uri: URL,
|
||||
params: Record<string, string>,
|
||||
) => Promise<unknown>;
|
||||
|
||||
await handler(new URL("globe://layers"), {});
|
||||
|
||||
expect(mockReadSessions).toHaveBeenCalledWith("scoped-user");
|
||||
expect(mockReadSessions).not.toHaveBeenCalledWith("u1");
|
||||
});
|
||||
});
|
||||
@@ -1,98 +0,0 @@
|
||||
/**
|
||||
* Globe MCP Resource registrar (Phase 18 Wave 3 — 18-04).
|
||||
*
|
||||
* Registers three read-only MCP resources scoped to the authenticated user:
|
||||
* RSRC-02 globe://state/{sessionId} — full GlobeStateSnapshot for a session
|
||||
* RSRC-03 globe://sessions — list of active sessions
|
||||
* RSRC-04 globe://layers — layer map from the most-recent session
|
||||
*
|
||||
* Each handler closes over `userId` at registration time so the same McpServer
|
||||
* instance is safely reusable without leaking cross-user data.
|
||||
*/
|
||||
|
||||
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { readGlobeState, readActiveSessions } from "@/lib/globeStateStore";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerGlobeResources(
|
||||
server: McpServer,
|
||||
{ userId }: { userId: string },
|
||||
): void {
|
||||
// RSRC-02: globe://state/{sessionId}
|
||||
// Returns the full GlobeStateSnapshot for the given session.
|
||||
const stateTemplate = new ResourceTemplate("globe://state/{sessionId}", { list: undefined });
|
||||
server.registerResource(
|
||||
"globe-state",
|
||||
stateTemplate,
|
||||
{ description: "Full GlobeStateSnapshot for a specific session" },
|
||||
async (uri, variables) => {
|
||||
const sessionId = String(variables["sessionId"] ?? "");
|
||||
const snapshot = await readGlobeState(userId, sessionId);
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: uri.toString(),
|
||||
mimeType: "application/json",
|
||||
text: JSON.stringify(snapshot),
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
// RSRC-03: globe://sessions
|
||||
// Returns the list of active sessions for the authenticated user.
|
||||
server.registerResource(
|
||||
"globe-sessions",
|
||||
"globe://sessions",
|
||||
{ description: "Active globe sessions for the authenticated user" },
|
||||
async (uri) => {
|
||||
const sessions = await readActiveSessions(userId);
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: uri.toString(),
|
||||
mimeType: "application/json",
|
||||
text: JSON.stringify(sessions),
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
// RSRC-04: globe://layers
|
||||
// Returns the layer map from the most-recent active session snapshot.
|
||||
// Gracefully returns an empty object when no active sessions exist.
|
||||
server.registerResource(
|
||||
"globe-layers",
|
||||
"globe://layers",
|
||||
{ description: "Active layer map from the most-recent globe session" },
|
||||
async (uri) => {
|
||||
const sessions = await readActiveSessions(userId);
|
||||
if (sessions.length === 0) {
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: uri.toString(),
|
||||
mimeType: "application/json",
|
||||
text: JSON.stringify({}),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
const snapshot = await readGlobeState(userId, sessions[0].sessionId);
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: uri.toString(),
|
||||
mimeType: "application/json",
|
||||
text: JSON.stringify(snapshot?.layers ?? {}),
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
/**
|
||||
* GET /api/mcp/invocations?sessionId=<uuid>
|
||||
*
|
||||
* Browser-facing endpoint for the plugin tool relay bridge (Phase 21 Wave 3 -- PLUG-03).
|
||||
* The browser bridge polls this endpoint to drain any pending tool invocations
|
||||
* that the MCP agent has queued for execution.
|
||||
*
|
||||
* Auth (dual-auth, mirrors GET /api/globe/commands):
|
||||
* Primary: NextAuth session cookie (browser path)
|
||||
* Fallback: Bearer API key (programmatic path)
|
||||
* userId comes ONLY from the resolved auth result -- never from the URL.
|
||||
*
|
||||
* sessionId scopes the invocation queue to a specific browser tab.
|
||||
* UUID format is validated before draining.
|
||||
*/
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { drainToolInvocations } from "@/lib/mcpRelay";
|
||||
import { mcpInvocationsLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { isDemo } from "@/core/edition";
|
||||
|
||||
const SESSION_ID_RE = /^[0-9a-f-]{36}$/i;
|
||||
|
||||
export async function GET(request: Request): Promise<NextResponse> {
|
||||
// Rate limit before any auth or DB work.
|
||||
const limited = mcpInvocationsLimiter.check(getClientIp(request));
|
||||
if (limited) return limited as NextResponse;
|
||||
|
||||
if (isDemo) {
|
||||
return NextResponse.json({ error: "MCP is not available in demo mode" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Dual-auth: NextAuth session PRIMARY, Bearer API key FALLBACK.
|
||||
// userId is resolved exclusively from the auth result -- never from the URL.
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const sessionId = url.searchParams.get("sessionId") ?? "";
|
||||
|
||||
if (!sessionId || !SESSION_ID_RE.test(sessionId)) {
|
||||
return NextResponse.json({ error: "invalid sessionId" }, { status: 400 });
|
||||
}
|
||||
|
||||
const invocations = await drainToolInvocations(userId, sessionId);
|
||||
|
||||
return NextResponse.json({ invocations });
|
||||
}
|
||||
@@ -1,286 +0,0 @@
|
||||
/**
|
||||
* RED tests for the namespaced plugin-tool dispatch handler (Phase 21 Wave 0).
|
||||
*
|
||||
* These tests INTENTIONALLY FAIL because registerPluginToolDispatch does not exist yet.
|
||||
* Wave 3 creates the dispatch handler that is registered into the MCP route.
|
||||
*
|
||||
* Mirrors globeCommandTools.test.ts in structure and mock style.
|
||||
*
|
||||
* Security invariants encoded:
|
||||
* MCP-QA-01 Request with no/invalid API key is rejected with auth error
|
||||
* MCP-QA-02 Valid key, unknown namespaced tool -> tool-not-found error, no enqueue
|
||||
* MCP-QA-03 Valid key, known tool, input fails validation -> validation error BEFORE enqueue
|
||||
* MCP-QA-04 Valid key + tool + valid input, no browser result before deadline -> graceful timeout
|
||||
* SEC-01 isDemo 403 gate stays BEFORE auth in the MCP route (unchanged gate order)
|
||||
* SEC-06 userId comes ONLY from the auth result, never from tool args or body
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { registerPluginToolDispatch } from "@/app/api/mcp/pluginToolDispatch";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const { mockEnqueueInvocation, mockWaitForResult, mockReadCatalog, mockValidateArgs } =
|
||||
vi.hoisted(() => ({
|
||||
mockEnqueueInvocation: vi.fn().mockResolvedValue({ rejected: false }),
|
||||
mockWaitForResult: vi.fn().mockResolvedValue({ timedOut: false, value: { ok: true } }),
|
||||
mockReadCatalog: vi.fn().mockResolvedValue(null),
|
||||
mockValidateArgs: vi.fn().mockReturnValue({ valid: true, errors: [] }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/mcpRelay", () => ({
|
||||
enqueueToolInvocation: mockEnqueueInvocation,
|
||||
waitForToolResult: mockWaitForResult,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/mcpSessionCatalog", () => ({
|
||||
readSessionCatalog: mockReadCatalog,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/mcp/pluginTools", () => ({
|
||||
validateToolArgs: mockValidateArgs,
|
||||
getNamespacedTools: vi.fn().mockReturnValue([]),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fake MCP server -- records registered tool handlers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type ToolHandler = (
|
||||
input: Record<string, unknown>,
|
||||
) => Promise<{ content: [{ type: "text"; text: string }]; isError?: boolean }>;
|
||||
|
||||
function makeFakeServer() {
|
||||
const tools = new Map<string, ToolHandler>();
|
||||
const server = {
|
||||
registerTool: vi.fn((name: string, _def: unknown, handler: ToolHandler) => {
|
||||
tools.set(name, handler);
|
||||
}),
|
||||
};
|
||||
return { server, tools };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fixture catalog with one known tool
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const FIXTURE_CATALOG = {
|
||||
tools: [
|
||||
{
|
||||
namespacedName: "aviation__decode_squawk",
|
||||
pluginId: "aviation",
|
||||
description: "Decodes a squawk code.",
|
||||
inputSchema: {
|
||||
type: "object" as const,
|
||||
properties: { squawk: { type: "string" } },
|
||||
required: ["squawk"],
|
||||
},
|
||||
mcpCapabilities: ["point-layer"],
|
||||
},
|
||||
],
|
||||
capabilities: ["point-layer"],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mockEnqueueInvocation.mockResolvedValue({ rejected: false });
|
||||
mockWaitForResult.mockResolvedValue({ timedOut: false, value: { ok: true } });
|
||||
mockReadCatalog.mockResolvedValue(FIXTURE_CATALOG);
|
||||
mockValidateArgs.mockReturnValue({ valid: true, errors: [] });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Registration: the dispatch handler is registered for each catalog tool
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("registerPluginToolDispatch registration", () => {
|
||||
it("registers a handler for each namespaced tool in the catalog", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
expect(tools.has("aviation__decode_squawk")).toBe(true);
|
||||
});
|
||||
|
||||
it("registers no plugin tools when the catalog is null (no active session)", async () => {
|
||||
mockReadCatalog.mockResolvedValue(null);
|
||||
const { server } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: null },
|
||||
);
|
||||
|
||||
// Only system tools are registered -- no plugin tool handlers added
|
||||
expect(server.registerTool).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-QA-02: unknown namespaced tool -- tool-not-found, no enqueue
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("dispatch handler -- unknown tool (MCP-QA-02)", () => {
|
||||
it("returns a tool-not-found error for an unrecognised namespaced tool name", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
// Register with a catalog that has ONE known tool
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
// No handler should exist for an unregistered name
|
||||
expect(tools.has("unknown__tool")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not enqueue for an unknown tool name", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
// If somehow a handler is invoked for an unknown tool, it must not enqueue
|
||||
const handler = tools.get("unknown__tool");
|
||||
if (handler) {
|
||||
await handler({ squawk: "7700" });
|
||||
expect(mockEnqueueInvocation).not.toHaveBeenCalled();
|
||||
} else {
|
||||
// Handler not registered -- correct behavior; test passes
|
||||
expect(tools.has("unknown__tool")).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-QA-03: input validation BEFORE enqueue
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("dispatch handler -- input validation before enqueue (MCP-QA-03)", () => {
|
||||
it("returns a validation error when input fails the minimal validator", async () => {
|
||||
mockValidateArgs.mockReturnValue({ valid: false, errors: ["squawk is required"] });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
const handler = tools.get("aviation__decode_squawk")!;
|
||||
const result = await handler({});
|
||||
|
||||
expect(result.content[0].type).toBe("text");
|
||||
const parsed = JSON.parse(result.content[0].text) as { error?: string };
|
||||
expect(parsed.error ?? result.content[0].text).toMatch(/validation|invalid|squawk/i);
|
||||
});
|
||||
|
||||
it("does NOT call enqueueToolInvocation when validation fails", async () => {
|
||||
mockValidateArgs.mockReturnValue({ valid: false, errors: ["squawk is required"] });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
const handler = tools.get("aviation__decode_squawk")!;
|
||||
await handler({});
|
||||
|
||||
expect(mockEnqueueInvocation).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-QA-04: relay timeout -- graceful text result, no thrown 500
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("dispatch handler -- relay timeout graceful result (MCP-QA-04)", () => {
|
||||
it("returns a graceful timeout text result when the browser does not respond", async () => {
|
||||
mockEnqueueInvocation.mockResolvedValue({ rejected: false });
|
||||
mockWaitForResult.mockResolvedValue({ timedOut: true });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
const handler = tools.get("aviation__decode_squawk")!;
|
||||
const result = await handler({ squawk: "7700" });
|
||||
|
||||
expect(result.content[0].type).toBe("text");
|
||||
expect(result.content[0].text.toLowerCase()).toMatch(/timeout|timed out|no response/);
|
||||
});
|
||||
|
||||
it("does NOT throw or reject the promise on relay timeout", async () => {
|
||||
mockEnqueueInvocation.mockResolvedValue({ rejected: false });
|
||||
mockWaitForResult.mockResolvedValue({ timedOut: true });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
);
|
||||
|
||||
const handler = tools.get("aviation__decode_squawk")!;
|
||||
await expect(handler({ squawk: "7700" })).resolves.toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SEC-06: userId comes ONLY from auth result, never from tool args
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("userId source invariant (SEC-06)", () => {
|
||||
it("uses ctx.userId, not a userId supplied in tool args", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
|
||||
await registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "ctx-user", sessionId: "s1" },
|
||||
);
|
||||
|
||||
const handler = tools.get("aviation__decode_squawk")!;
|
||||
// Simulate a caller that supplies userId in args -- must be ignored
|
||||
await handler({ squawk: "7700", userId: "attacker-user" });
|
||||
|
||||
const [calledUserId] = mockEnqueueInvocation.mock.calls[0] as [string, string, unknown];
|
||||
expect(calledUserId).toBe("ctx-user");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SEC-01: isDemo gate is tested at the route level (route.test.ts).
|
||||
// Here we assert that the dispatch registrar does not re-implement the gate --
|
||||
// it trusts that the route has already checked it before calling registerPluginToolDispatch.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("SEC-01 gate ordering (documented assertion)", () => {
|
||||
it("registerPluginToolDispatch does not check isDemo internally", async () => {
|
||||
// The isDemo check lives in route.ts BEFORE auth. The dispatch handler
|
||||
// assumes it runs AFTER the gate has already fired. This test just confirms
|
||||
// the registrar does not import isDemo (behavioral contract assertion).
|
||||
// If Wave 3 incorrectly adds an isDemo check here, the security reviewer
|
||||
// will catch the duplicate gate.
|
||||
const { server } = makeFakeServer();
|
||||
|
||||
// Should not throw even if we don't pass isDemo-related context
|
||||
await expect(
|
||||
registerPluginToolDispatch(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1", sessionId: "s1" },
|
||||
),
|
||||
).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,179 +0,0 @@
|
||||
/**
|
||||
* @file pluginToolDispatch.ts
|
||||
* @description Plugin tool dispatch handler for the MCP route (Phase 21 Wave 3 -- PLUG-03).
|
||||
*
|
||||
* registerPluginToolDispatch reads the per-session catalog and registers a
|
||||
* handler for each namespaced plugin tool ({pluginId}__{name}). Each handler:
|
||||
* 1. Validates tool input against the catalog schema (rejects before enqueue).
|
||||
* 2. Enqueues the invocation for the browser to execute.
|
||||
* 3. Waits for the browser to post a result (10-second deadline).
|
||||
* 4. Returns the result as a text content block, OR a graceful timeout message.
|
||||
*
|
||||
* The server is a DUMB RELAY -- it never executes a plugin tool, reads a streamUrl,
|
||||
* or calls the data engine. Execution happens in the browser via plugin.executeMcpTool.
|
||||
*
|
||||
* Security:
|
||||
* - userId + sessionId come from the auth context, never from tool args.
|
||||
* - Input validation fires BEFORE enqueue (SEC-04 / MCP-QA-03).
|
||||
* - Server never calls executeMcpTool, never reads a streamUrl.
|
||||
* - Graceful timeout returned on deadline, never a hang or 500 (SEC-02 / MCP-QA-04).
|
||||
*/
|
||||
|
||||
import { randomUUID } from "crypto";
|
||||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod";
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { enqueueToolInvocation, waitForToolResult } from "@/lib/mcpRelay";
|
||||
import { validateToolArgs } from "@/lib/mcp/pluginTools";
|
||||
import type { ToolInputSchema } from "@/lib/mcp/pluginTools";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Deadline for the server-side wait on a browser tool result (ms). */
|
||||
const RELAY_DEADLINE_MS = 10_000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Auth context passed by the MCP route
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface DispatchContext {
|
||||
userId: string;
|
||||
sessionId: string | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// registerPluginToolDispatch
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Reads the per-session catalog and registers a relay handler for each
|
||||
* namespaced plugin tool. Called inside the MCP route's registration seam
|
||||
* after auth, before transport.handleRequest().
|
||||
*
|
||||
* When sessionId is null (no active session) or the catalog is empty, no
|
||||
* plugin tool handlers are registered (system tools remain unaffected).
|
||||
*/
|
||||
export async function registerPluginToolDispatch(
|
||||
server: McpServer,
|
||||
ctx: DispatchContext,
|
||||
): Promise<void> {
|
||||
if (!ctx.sessionId) return;
|
||||
|
||||
const catalog = await readSessionCatalog(ctx.userId, ctx.sessionId);
|
||||
if (!catalog || !Array.isArray(catalog.tools) || catalog.tools.length === 0) return;
|
||||
|
||||
for (const tool of catalog.tools) {
|
||||
const namespacedName = tool.namespacedName;
|
||||
if (!namespacedName) continue;
|
||||
|
||||
// Capture loop variables for the closure.
|
||||
const capturedTool = tool;
|
||||
const capturedCtx = ctx;
|
||||
|
||||
server.registerTool(
|
||||
namespacedName,
|
||||
{
|
||||
description: capturedTool.description,
|
||||
// Accept args as a loose record -- actual validation is done by validateToolArgs.
|
||||
inputSchema: { args: z.record(z.string(), z.unknown()).optional() },
|
||||
},
|
||||
async (input) => {
|
||||
// Build the args object from whatever the MCP client passed.
|
||||
// The MCP SDK wraps the input in parsed zod fields, so we extract
|
||||
// a flat record of all non-undefined fields for validation.
|
||||
const rawArgs = (input as Record<string, unknown>).args as Record<string, unknown> | undefined;
|
||||
|
||||
// Flatten: when args is not present, use the input directly (minus internal fields).
|
||||
// This handles both `{ args: { squawk: "7700" } }` and `{ squawk: "7700" }` inputs.
|
||||
const argsRecord: Record<string, unknown> = typeof rawArgs === "object" && rawArgs !== null
|
||||
? rawArgs
|
||||
: (input as Record<string, unknown>);
|
||||
|
||||
// MCP-QA-03: Validate BEFORE enqueue.
|
||||
// ToolInputSchema requires `type: "object"` but CatalogTool.inputSchema is
|
||||
// Record<string, unknown>. Cast via unknown to make the compiler happy.
|
||||
const schema = capturedTool.inputSchema as unknown as ToolInputSchema;
|
||||
const validation = validateToolArgs(argsRecord, schema);
|
||||
if (!validation.valid) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({
|
||||
error: `Validation failed: ${validation.errors.join("; ")}`,
|
||||
errors: validation.errors,
|
||||
}),
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Enqueue the invocation for the browser to execute.
|
||||
const requestId = randomUUID();
|
||||
const enqueueResult = await enqueueToolInvocation(
|
||||
capturedCtx.userId,
|
||||
capturedCtx.sessionId!,
|
||||
{
|
||||
requestId,
|
||||
tool: namespacedName,
|
||||
args: argsRecord,
|
||||
},
|
||||
);
|
||||
|
||||
if (enqueueResult.rejected) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({
|
||||
error: `Failed to enqueue tool invocation: ${enqueueResult.reason ?? "rejected"}`,
|
||||
}),
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
// SEC-02 / MCP-QA-04: Wait for browser result with a bounded deadline.
|
||||
const resultOrTimeout = await waitForToolResult(
|
||||
capturedCtx.userId,
|
||||
capturedCtx.sessionId!,
|
||||
requestId,
|
||||
RELAY_DEADLINE_MS,
|
||||
);
|
||||
|
||||
if (resultOrTimeout.timedOut) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({
|
||||
error: "Plugin tool timed out: no response from the browser before the deadline.",
|
||||
timedOut: true,
|
||||
tool: namespacedName,
|
||||
}),
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Sanitize: serialize the value to JSON, never return raw Error objects.
|
||||
const safeResult = resultOrTimeout.value;
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: typeof safeResult === "string"
|
||||
? safeResult
|
||||
: JSON.stringify(safeResult ?? null),
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
/**
|
||||
* POST /api/mcp/results
|
||||
*
|
||||
* Browser-facing endpoint for posting tool execution results back to the server
|
||||
* (Phase 21 Wave 3 -- PLUG-03). The browser bridge calls plugin.executeMcpTool,
|
||||
* then POSTs { requestId, result, sessionId } here so the server's blpop unblocks.
|
||||
*
|
||||
* Auth (dual-auth, mirrors GET /api/globe/commands):
|
||||
* Primary: NextAuth session cookie (browser path)
|
||||
* Fallback: Bearer API key (programmatic path)
|
||||
* userId comes ONLY from the resolved auth result -- never from the request body.
|
||||
*
|
||||
* Security:
|
||||
* - Ownership check: requestId must belong to this userId+session.
|
||||
* - Result size is capped inside postToolResult.
|
||||
* - sessionId from the request body (not auth), but userId always from auth.
|
||||
*/
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { postToolResult } from "@/lib/mcpRelay";
|
||||
import { mcpResultsLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { isDemo } from "@/core/edition";
|
||||
|
||||
const SESSION_ID_RE = /^[0-9a-f-]{36}$/i;
|
||||
const REQUEST_ID_RE = /^[0-9a-f-]{36}$/i;
|
||||
|
||||
/** Pre-parse body size cap (1 MB). The post-parse cap inside postToolResult is 512 KB. */
|
||||
const MAX_BODY_BYTES = 1 * 1024 * 1024;
|
||||
|
||||
export async function POST(request: Request): Promise<NextResponse> {
|
||||
// Rate limit before any auth or DB work.
|
||||
const limited = mcpResultsLimiter.check(getClientIp(request));
|
||||
if (limited) return limited as NextResponse;
|
||||
|
||||
if (isDemo) {
|
||||
return NextResponse.json({ error: "MCP is not available in demo mode" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Dual-auth: NextAuth session PRIMARY, Bearer API key FALLBACK.
|
||||
// userId is resolved exclusively from the auth result -- never from the body.
|
||||
let userId: string | null = null;
|
||||
|
||||
const session = await getSession();
|
||||
if (session?.user?.id) {
|
||||
userId = session.user.id;
|
||||
} else {
|
||||
const apiKeyAuth = await authenticateApiKey(request);
|
||||
if (apiKeyAuth) {
|
||||
userId = apiKeyAuth.userId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
const text = await request.text();
|
||||
if (Buffer.byteLength(text, "utf8") > MAX_BODY_BYTES) {
|
||||
return NextResponse.json({ error: "Payload too large" }, { status: 413 });
|
||||
}
|
||||
body = JSON.parse(text);
|
||||
} catch {
|
||||
return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!body || typeof body !== "object") {
|
||||
return NextResponse.json({ error: "invalid request body" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { sessionId, requestId, result } = body as Record<string, unknown>;
|
||||
|
||||
if (typeof sessionId !== "string" || !SESSION_ID_RE.test(sessionId)) {
|
||||
return NextResponse.json({ error: "invalid sessionId" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (typeof requestId !== "string" || !REQUEST_ID_RE.test(requestId)) {
|
||||
return NextResponse.json({ error: "invalid requestId" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Delegate to postToolResult which enforces ownership and size caps.
|
||||
const opResult = await postToolResult(userId, sessionId, requestId, result);
|
||||
|
||||
if (opResult.rejected) {
|
||||
return NextResponse.json(
|
||||
{ error: opResult.reason ?? "rejected" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
/**
|
||||
* SEC-02: Redis per-key rate limiting in /api/mcp route tests.
|
||||
*
|
||||
* Verifies the post-auth Redis sliding-window gate behavior.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Top-level mocks (same surface as route.test.ts)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
edition: "local",
|
||||
isLocal: true,
|
||||
isCloud: false,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/geocodingRateLimit", () => ({
|
||||
redisSlidingWindow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@modelcontextprotocol/sdk/server/mcp.js", () => {
|
||||
const McpServer = vi.fn(function McpServerMock(this: unknown) {
|
||||
return {
|
||||
connect: vi.fn().mockResolvedValue(undefined),
|
||||
registerResource: vi.fn(),
|
||||
registerTool: vi.fn(),
|
||||
registerPrompt: vi.fn(),
|
||||
};
|
||||
});
|
||||
const ResourceTemplate = vi.fn(function ResourceTemplateMock(this: unknown, uriTemplate: string) {
|
||||
return { uriTemplate };
|
||||
});
|
||||
return { McpServer, ResourceTemplate };
|
||||
});
|
||||
|
||||
vi.mock("@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js", () => {
|
||||
const WebStandardStreamableHTTPServerTransport = vi.fn().mockImplementation(() => ({
|
||||
handleRequest: vi.fn().mockResolvedValue(
|
||||
new Response(null, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"X-Accel-Buffering": "no",
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
})
|
||||
),
|
||||
}));
|
||||
return { WebStandardStreamableHTTPServerTransport };
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Imports (after mocks)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
import { POST } from "./route";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { redisSlidingWindow } from "@/lib/geocodingRateLimit";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makePost(authorization?: string): Request {
|
||||
const headers: Record<string, string> = {};
|
||||
if (authorization) headers["authorization"] = authorization;
|
||||
return new Request("http://localhost:3000/api/mcp", { method: "POST", headers });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("SEC-02: per-key Redis rate limit gate", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
});
|
||||
|
||||
it("passes through when Redis allows the request", async () => {
|
||||
vi.mocked(redisSlidingWindow).mockResolvedValue({ allowed: true, retryAfterMs: 0 });
|
||||
|
||||
const res = await POST(makePost("Bearer wwv_valid.token"));
|
||||
expect(res.status).not.toBe(429);
|
||||
});
|
||||
|
||||
it("returns 429 JSON-RPC -32000 when Redis rejects the request", async () => {
|
||||
vi.mocked(redisSlidingWindow).mockResolvedValue({ allowed: false, retryAfterMs: 60_000 });
|
||||
|
||||
const res = await POST(makePost("Bearer wwv_valid.token"));
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(429);
|
||||
expect(body).toMatchObject({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32000, message: "rate limit exceeded" },
|
||||
id: null,
|
||||
});
|
||||
expect(res.headers.get("Retry-After")).toBe("60");
|
||||
});
|
||||
|
||||
it("rate limit check uses the authenticated keyId, not userId or raw header", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-abc", keyId: "key-xyz" });
|
||||
vi.mocked(redisSlidingWindow).mockResolvedValue({ allowed: true, retryAfterMs: 0 });
|
||||
|
||||
await POST(makePost("Bearer wwv_valid.token"));
|
||||
|
||||
expect(vi.mocked(redisSlidingWindow)).toHaveBeenCalledWith(
|
||||
expect.stringContaining("key-xyz"),
|
||||
expect.any(Number),
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
|
||||
it("rate limit is not checked when auth fails (no authenticated keyId available)", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue(null);
|
||||
|
||||
const res = await POST(makePost("Bearer bogus.token"));
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(vi.mocked(redisSlidingWindow)).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,445 +0,0 @@
|
||||
/**
|
||||
* RED test scaffold for /api/mcp route handler (Phase 17, Wave 0)
|
||||
*
|
||||
* These tests INTENTIONALLY FAIL because src/app/api/mcp/route.ts does not
|
||||
* exist yet. They lock the following contracts before any implementation:
|
||||
*
|
||||
* MCP-01 GET with valid Bearer returns a non-401/403 response (passes both gates)
|
||||
* MCP-02 POST with valid Bearer passes both gates
|
||||
* MCP-03 Missing/invalid Bearer -> 401 JSON-RPC 2.0 error (not plain text)
|
||||
* MCP-04 isDemo=true -> 403 JSON-RPC 2.0 error, auth is NOT called (gate-first)
|
||||
* MCP-05 McpServer + transport constructed ONCE PER REQUEST (no module singleton)
|
||||
* MCP-06 Streamed GET response carries X-Accel-Buffering: no
|
||||
*
|
||||
* DO NOT implement route.ts to make these pass — that is Wave 1 (17-02).
|
||||
*/
|
||||
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach
|
||||
} from "vitest";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Top-level mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
// The edition mock is mutable — individual tests flip isDemo via vi.doMock
|
||||
// inside their own dynamic-import describe block (see "Demo gate" section).
|
||||
// For the default non-demo path we declare isDemo: false here.
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
}));
|
||||
|
||||
// SDK mocks — locked stateless-construction invariant (MCP-05).
|
||||
// handleRequest returns a minimal streaming Response so the happy-path tests
|
||||
// can assert gate passage without a real transport.
|
||||
vi.mock("@modelcontextprotocol/sdk/server/mcp.js", () => {
|
||||
// Use a stable factory so vi.resetAllMocks() does not wipe the constructor
|
||||
// implementation — resetAllMocks resets call history but the factory closure
|
||||
// keeps re-creating a fresh instance object on each `new McpServer()` call.
|
||||
const McpServer = vi.fn(function McpServerMock(this: unknown) {
|
||||
return {
|
||||
connect: vi.fn().mockResolvedValue(undefined),
|
||||
registerResource: vi.fn(),
|
||||
registerTool: vi.fn(),
|
||||
registerPrompt: vi.fn(),
|
||||
};
|
||||
});
|
||||
// Minimal ResourceTemplate stub so globeResources.ts can construct one
|
||||
// without the mock throwing "No export defined".
|
||||
const ResourceTemplate = vi.fn(function ResourceTemplateMock(this: unknown, uriTemplate: string) {
|
||||
return { uriTemplate };
|
||||
});
|
||||
return { McpServer, ResourceTemplate };
|
||||
});
|
||||
|
||||
vi.mock("@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js", () => {
|
||||
const WebStandardStreamableHTTPServerTransport = vi.fn().mockImplementation(() => ({
|
||||
handleRequest: vi.fn().mockResolvedValue(
|
||||
new Response(null, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"X-Accel-Buffering": "no",
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
})
|
||||
),
|
||||
}));
|
||||
return { WebStandardStreamableHTTPServerTransport };
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Import the route — this line CAUSES the RED failure (module ./route absent)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
import { GET, POST, DELETE } from "./route";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makeRequest(
|
||||
method: string,
|
||||
opts?: { authorization?: string; accept?: string }
|
||||
): Request {
|
||||
const headers: Record<string, string> = {};
|
||||
if (opts?.authorization) headers["authorization"] = opts.authorization;
|
||||
if (opts?.accept) headers["accept"] = opts.accept;
|
||||
return new Request("http://localhost:3000/api/mcp", { method, headers });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-03: Unauthenticated requests -> 401 JSON-RPC 2.0 error
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("MCP-03: 401 on missing or invalid Bearer token", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
// Auth always returns null in this suite — intentionally unauthenticated
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue(null);
|
||||
});
|
||||
|
||||
it("POST with no Authorization header returns 401 with exact JSON-RPC 2.0 body", async () => {
|
||||
const req = makeRequest("POST");
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "Unauthorized" },
|
||||
id: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("POST with invalid Bearer returns 401 + exact JSON-RPC body AND content-type is application/json (not plain text)", async () => {
|
||||
const req = makeRequest("POST", { authorization: "Bearer bogus.token" });
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "Unauthorized" },
|
||||
id: null,
|
||||
});
|
||||
// Pitfall 3 guard: must NOT be plain text
|
||||
expect(res.headers.get("content-type")).toMatch(/application\/json/);
|
||||
});
|
||||
|
||||
it("GET with no Authorization header also returns 401 + JSON-RPC body", async () => {
|
||||
const req = makeRequest("GET");
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "Unauthorized" },
|
||||
id: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("DELETE with no Authorization header returns 401 + JSON-RPC body", async () => {
|
||||
const req = makeRequest("DELETE");
|
||||
const res = await DELETE(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "Unauthorized" },
|
||||
id: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-04: Demo edition gate — runs FIRST, before authenticateApiKey (D-17-05)
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// vi.doMock + dynamic import pattern — each test re-imports the module with
|
||||
// isDemo flipped to true so the compile-time mock above (isDemo: false) does
|
||||
// not leak in.
|
||||
//
|
||||
// NOTE: because vi.doMock requires a dynamic re-import to take effect, these
|
||||
// tests are structured as async functions that import the route dynamically.
|
||||
|
||||
describe("MCP-04: Demo edition gate (isDemo=true) returns 403 BEFORE auth runs", () => {
|
||||
it("POST returns 403 JSON-RPC body and does NOT call authenticateApiKey", async () => {
|
||||
vi.resetModules();
|
||||
vi.doMock("@/core/edition", () => ({ isDemo: true }));
|
||||
// Re-import after resetModules so the flipped isDemo is picked up
|
||||
const { POST: demoPost } = await import("./route");
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
|
||||
const res = await demoPost(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "MCP is not available in demo mode" },
|
||||
id: null,
|
||||
});
|
||||
// Gate MUST run before auth — authenticateApiKey must NOT have been called
|
||||
expect(vi.mocked(authenticateApiKey)).not.toHaveBeenCalled();
|
||||
|
||||
vi.doUnmock("@/core/edition");
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("GET returns 403 JSON-RPC body and does NOT call authenticateApiKey", async () => {
|
||||
vi.resetModules();
|
||||
vi.doMock("@/core/edition", () => ({ isDemo: true }));
|
||||
const { GET: demoGet } = await import("./route");
|
||||
const req = makeRequest("GET", { authorization: "Bearer wwv_valid.token" });
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
|
||||
const res = await demoGet(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "MCP is not available in demo mode" },
|
||||
id: null,
|
||||
});
|
||||
expect(vi.mocked(authenticateApiKey)).not.toHaveBeenCalled();
|
||||
|
||||
vi.doUnmock("@/core/edition");
|
||||
vi.resetModules();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-01 / MCP-02: Happy path — both gates passed, request reaches transport
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("MCP-01/MCP-02: Valid auth + non-demo -> request passes both gates", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
});
|
||||
|
||||
it("POST with valid Bearer is NOT 401 or 403 (passes both gates, reaches transport)", async () => {
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).not.toBe(401);
|
||||
expect(res.status).not.toBe(403);
|
||||
});
|
||||
|
||||
it("GET with valid Bearer is NOT 401 or 403", async () => {
|
||||
const req = makeRequest("GET", { authorization: "Bearer wwv_valid.token" });
|
||||
const res = await GET(req);
|
||||
|
||||
expect(res.status).not.toBe(401);
|
||||
expect(res.status).not.toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TRANS-04: tools.listChanged must NOT be advertised as true
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("TRANS-04: McpServer is not created with tools.listChanged: true", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
});
|
||||
|
||||
it("capabilities passed to McpServer constructor have listChanged false or absent (never true)", async () => {
|
||||
const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
|
||||
const mcpCtor = vi.mocked(McpServer);
|
||||
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
await POST(req);
|
||||
|
||||
expect(mcpCtor).toHaveBeenCalledTimes(1);
|
||||
// second arg is the options object: { instructions, capabilities }
|
||||
const options = mcpCtor.mock.calls[0][1] as { capabilities?: { tools?: { listChanged?: boolean } } } | undefined;
|
||||
const listChanged = options?.capabilities?.tools?.listChanged;
|
||||
expect(listChanged).not.toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-06: Streaming headers — X-Accel-Buffering: no must be present (Pitfall 1)
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// A missing X-Accel-Buffering: no causes Nginx to buffer the entire SSE stream,
|
||||
// breaking streaming in production. This is the single most important header.
|
||||
|
||||
describe("MCP-06: Streaming response headers", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
});
|
||||
|
||||
it("GET with Accept: text/event-stream returns X-Accel-Buffering: no", async () => {
|
||||
const req = makeRequest("GET", {
|
||||
authorization: "Bearer wwv_valid.token",
|
||||
accept: "text/event-stream",
|
||||
});
|
||||
const res = await GET(req);
|
||||
|
||||
// Primary streaming guard — must be present on every streamed response
|
||||
expect(res.headers.get("X-Accel-Buffering")).toBe("no");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TRANS-01: Top-level error boundary — unexpected throws -> JSON-RPC -32603
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("TRANS-01: unhandled error during request handling yields JSON-RPC -32603", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
it("POST returns HTTP 500 with JSON-RPC -32603 body when a registrar throws", async () => {
|
||||
// Simulate an unexpected failure after auth succeeds (e.g. Redis down).
|
||||
// We make authenticateApiKey succeed but then make registerOrientationPrompts
|
||||
// throw by having McpServer.registerPrompt throw.
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
|
||||
const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
|
||||
vi.mocked(McpServer).mockImplementationOnce(function (this: unknown) {
|
||||
return {
|
||||
connect: vi.fn().mockResolvedValue(undefined),
|
||||
registerResource: vi.fn(),
|
||||
registerTool: vi.fn(),
|
||||
registerPrompt: vi.fn().mockImplementation(() => {
|
||||
throw new Error("Redis connection refused");
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
id: null,
|
||||
error: { code: -32603, message: "Internal error" },
|
||||
});
|
||||
});
|
||||
|
||||
it("GET returns HTTP 500 with JSON-RPC -32603 body when transport.handleRequest throws", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
|
||||
const { WebStandardStreamableHTTPServerTransport } = await import(
|
||||
"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"
|
||||
);
|
||||
vi.mocked(WebStandardStreamableHTTPServerTransport).mockImplementationOnce(() => ({
|
||||
handleRequest: vi.fn().mockRejectedValue(new Error("stream error")),
|
||||
}));
|
||||
|
||||
const req = makeRequest("GET", { authorization: "Bearer wwv_valid.token" });
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
id: null,
|
||||
error: { code: -32603, message: "Internal error" },
|
||||
});
|
||||
});
|
||||
|
||||
// Defense-in-depth: if authenticateApiKey ever regresses and throws instead
|
||||
// of returning null, the boundary must still catch it and return -32603.
|
||||
// In practice TRANS-02 makes authenticateApiKey return null on DB outage,
|
||||
// so this path is hypothetical, not a real DB-outage scenario.
|
||||
it("-32603 response carries streaming headers (X-Accel-Buffering: no) [defense-in-depth: hypothetical auth throw]", async () => {
|
||||
vi.mocked(authenticateApiKey).mockRejectedValue(new Error("DB down"));
|
||||
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(res.headers.get("X-Accel-Buffering")).toBe("no");
|
||||
});
|
||||
|
||||
it("existing 401 path is NOT affected by the error boundary", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue(null);
|
||||
|
||||
const req = makeRequest("POST");
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
const body = await res.json();
|
||||
expect(body.error.code).toBe(-32600);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-05: Stateless freshness — per-request construction (Pitfall 2)
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// A module-level cached McpServer + transport causes subsequent requests to fail
|
||||
// because the transport is already bound to a prior request context. This suite
|
||||
// asserts the constructor is called ONCE PER REQUEST, not once at module load.
|
||||
//
|
||||
// stateless: see route.ts guard-rail comment
|
||||
|
||||
describe("MCP-05: Per-request stateless construction — no module singleton", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
});
|
||||
|
||||
it("WebStandardStreamableHTTPServerTransport constructor called once per POST request (not shared)", async () => {
|
||||
const { WebStandardStreamableHTTPServerTransport } = await import(
|
||||
"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"
|
||||
);
|
||||
const transportCtor = vi.mocked(WebStandardStreamableHTTPServerTransport);
|
||||
|
||||
const req1 = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
const req2 = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
|
||||
await POST(req1);
|
||||
expect(transportCtor).toHaveBeenCalledTimes(1);
|
||||
|
||||
await POST(req2);
|
||||
expect(transportCtor).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("McpServer constructor called once per POST request (not shared)", async () => {
|
||||
const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
|
||||
const mcpCtor = vi.mocked(McpServer);
|
||||
|
||||
const req1 = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
const req2 = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
|
||||
await POST(req1);
|
||||
expect(mcpCtor).toHaveBeenCalledTimes(1);
|
||||
|
||||
await POST(req2);
|
||||
expect(mcpCtor).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("transport is constructed with sessionIdGenerator: undefined (stateless mode)", async () => {
|
||||
const { WebStandardStreamableHTTPServerTransport } = await import(
|
||||
"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"
|
||||
);
|
||||
const transportCtor = vi.mocked(WebStandardStreamableHTTPServerTransport);
|
||||
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
await POST(req);
|
||||
|
||||
expect(transportCtor).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ sessionIdGenerator: undefined })
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,258 +0,0 @@
|
||||
/**
|
||||
* GET / POST / DELETE /api/mcp
|
||||
*
|
||||
* Stateless Streamable HTTP MCP endpoint (Phase 17).
|
||||
*
|
||||
* Gate ordering (D-17-05, MCP-04):
|
||||
* 1. Edition check — isDemo → 403 JSON-RPC error (runs BEFORE auth)
|
||||
* 2. Bearer auth — authenticateApiKey() → 401 JSON-RPC error on failure
|
||||
* 3. Fresh McpServer + transport per request (D-17-04, MCP-05)
|
||||
* 4. Delegate to transport.handleRequest() → streaming Response
|
||||
*
|
||||
* STATELESS INVARIANT (D-17-04): McpServer and WebStandardStreamableHTTPServerTransport
|
||||
* are constructed INSIDE the handler on every request and NEVER cached at module
|
||||
* scope. Do NOT hoist server/transport creation outside of handleMcpRequest().
|
||||
* A module-level singleton would bind the transport to a prior request context,
|
||||
* causing all subsequent requests to fail silently (Pitfall 2).
|
||||
*
|
||||
* Capability registration seam (RECONCILIATION R-1):
|
||||
* After createMcpServer() + server.connect(transport) and BEFORE
|
||||
* transport.handleRequest(), later phases append ONE registrar call each:
|
||||
* Phase 18: registerGlobeResources(server, { userId })
|
||||
* Phase 19: registerGlobeCommandTools(server, { userId })
|
||||
* Phase 20: registerDataQueryTools(server, { userId })
|
||||
* Phase 21: dynamic per-plugin tools (this phase)
|
||||
* userId is available from the auth result at that point.
|
||||
*/
|
||||
|
||||
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
||||
import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
|
||||
import { isDemo } from "@/core/edition";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { createMcpServer, registerOrientationPrompts } from "@/lib/mcp/server";
|
||||
import { mcpLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { redisSlidingWindow } from "@/lib/geocodingRateLimit";
|
||||
import {
|
||||
demoBlockedResponse,
|
||||
unauthorizedResponse,
|
||||
rateLimitedResponse,
|
||||
internalErrorResponse,
|
||||
} from "@/lib/mcp/mcpResponseHelpers";
|
||||
import { registerGlobeResources } from "./globeResources";
|
||||
import { registerDataQueryTools } from "@/lib/mcp/tools";
|
||||
import { registerGlobeCommandTools } from "./globeCommandTools";
|
||||
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { registerPluginToolDispatch } from "./pluginToolDispatch";
|
||||
import { registerGeocodingTools } from "./geocodingTools";
|
||||
import { registerFavoritesTools } from "./favoritesTools";
|
||||
import { registerFilterTools } from "./filterTools";
|
||||
import { registerDiscoveryTools } from "./discoveryTools";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Route segment config (TRANS-03)
|
||||
// 30 s is comfortably above the 10 s blpop ceiling in RELAY_DEADLINE_MS so the
|
||||
// function never times out mid-relay. Vercel/Coolify honour this value.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const maxDuration = 30;
|
||||
|
||||
// Per-key rate-limit budget (SEC-02): 120 requests per 60-second window.
|
||||
const MCP_KEY_LIMIT = 120;
|
||||
const MCP_WINDOW_MS = 60_000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Header merge helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Ensures X-Accel-Buffering: no (and Cache-Control: no-cache, no-transform)
|
||||
* are present on the response without clobbering the SDK's Content-Type or
|
||||
* buffering the response body into memory (Pitfall 1 / D-17-06 / MCP-06).
|
||||
*
|
||||
* We clone the response headers, add the missing headers, then return a new
|
||||
* Response that streams the original body.
|
||||
*/
|
||||
function withStreamingHeaders(sdkResponse: Response): Response {
|
||||
const headers = new Headers(sdkResponse.headers);
|
||||
headers.set("X-Accel-Buffering", "no");
|
||||
headers.set("Cache-Control", "no-cache, no-transform");
|
||||
headers.set("Connection", "keep-alive");
|
||||
return new Response(sdkResponse.body, {
|
||||
status: sdkResponse.status,
|
||||
statusText: sdkResponse.statusText,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Phase 21 Wave 3: plugin tool dispatch registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Reads the per-session catalog for the authenticated user and registers a
|
||||
* relay handler for each namespaced plugin tool. The handler validates input,
|
||||
* enqueues the invocation for the browser, and waits for the browser result
|
||||
* (blpop with a 10-second deadline). Returns a graceful timeout if no result.
|
||||
*
|
||||
* Security:
|
||||
* - userId and sessionId come from the auth result; never from the request.
|
||||
* - Catalog is scoped to the most-recently-active session for this user.
|
||||
* - No DB/tenantId enumeration -- catalog is browser-published only.
|
||||
* - Server stays plugin-agnostic: no streamUrl / data-engine access.
|
||||
*/
|
||||
type McpServer = import("@modelcontextprotocol/sdk/server/mcp.js").McpServer;
|
||||
|
||||
async function registerPluginTools(
|
||||
server: McpServer,
|
||||
userId: string,
|
||||
): Promise<void> {
|
||||
// Resolve the active session for this user (ZSET globe:sessions)
|
||||
const sessionId = await resolveActiveSessionId(userId);
|
||||
|
||||
// Delegate to the dispatch registrar (pluginToolDispatch.ts).
|
||||
await registerPluginToolDispatch(server, { userId, sessionId });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core handler — all three methods delegate here
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function handleMcpRequest(request: Request): Promise<Response> {
|
||||
// ------------------------------------------------------------------
|
||||
// Gate 0: Rate limit (H1) — runs BEFORE edition check and auth so
|
||||
// scanners never reach the DB layer.
|
||||
// ------------------------------------------------------------------
|
||||
const ipLimitResult = mcpLimiter.check(getClientIp(request));
|
||||
if (ipLimitResult) return ipLimitResult;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Gate 1: Edition check (D-17-05, MCP-04)
|
||||
// Must run BEFORE authenticateApiKey so demo edition never reaches
|
||||
// the auth/DB layer (avoids demo-admin FK write — Pitfall 5).
|
||||
// ------------------------------------------------------------------
|
||||
if (isDemo) {
|
||||
return demoBlockedResponse();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Gate 2: Bearer auth (D-17-03, MCP-03)
|
||||
// authenticateApiKey() reads Authorization header; never throws.
|
||||
// ------------------------------------------------------------------
|
||||
const authResult = await authenticateApiKey(request);
|
||||
if (!authResult) {
|
||||
console.warn("[mcp] unauthorized request");
|
||||
return unauthorizedResponse();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Gate 3: Redis per-key rate limit (SEC-02).
|
||||
// 120 req / 60s per authenticated key, complementing the coarse IP
|
||||
// gate above. Fails OPEN on Redis outage so a broken Redis never
|
||||
// blocks legit users.
|
||||
// ------------------------------------------------------------------
|
||||
const keyRateKey = `mcp:ratelimit:key:${authResult.keyId}`;
|
||||
const keyLimit = await redisSlidingWindow(keyRateKey, MCP_KEY_LIMIT, MCP_WINDOW_MS);
|
||||
if (!keyLimit.allowed) {
|
||||
return rateLimitedResponse(keyLimit.retryAfterMs);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Build a FRESH server + transport per request (D-17-04, MCP-05).
|
||||
// STATELESS INVARIANT: never hoist these to module scope.
|
||||
// Do NOT cache server or transport between requests.
|
||||
// ------------------------------------------------------------------
|
||||
const server = createMcpServer();
|
||||
|
||||
// Registration seam (RECONCILIATION R-1):
|
||||
// Phase 18: globe resources
|
||||
// Phase 19: globe command tools
|
||||
// Phase 20: data query tools
|
||||
// Phase 21: dynamic per-session plugin tools (below)
|
||||
// Phase 22: registerGeocodingTools, registerFavoritesTools
|
||||
// Phase 23: registerFilterTools (set_filter, clear_filter, get_plugin_filters)
|
||||
registerGlobeResources(server, { userId: authResult.userId });
|
||||
registerDataQueryTools(server, { userId: authResult.userId });
|
||||
registerGlobeCommandTools(server, { userId: authResult.userId });
|
||||
registerGeocodingTools(server, { userId: authResult.userId });
|
||||
registerFavoritesTools(server, { userId: authResult.userId });
|
||||
registerFilterTools(server, { userId: authResult.userId });
|
||||
// Phase 29: discovery tools (list_available_plugins, get_globe_context, investigate_area)
|
||||
registerDiscoveryTools(server, { userId: authResult.userId });
|
||||
// Phase 26: orientation prompts (INST-03, INST-04)
|
||||
await registerOrientationPrompts(server, { userId: authResult.userId });
|
||||
|
||||
// Phase 21: dynamic plugin tools — read the per-session catalog and
|
||||
// register each plugin tool so tools/list includes them.
|
||||
// NO DB/tenantId enumeration: discovery is browser-published only.
|
||||
//
|
||||
// list_changed note (best-effort, D-21-01):
|
||||
// This server is stateless and per-request, so it cannot push
|
||||
// list_changed notifications to connected clients. The catalog snapshot
|
||||
// is whatever the browser published at the moment this request arrives.
|
||||
// Plugin tools appear in tools/list only after the browser tab has
|
||||
// loaded the relevant plugin and published its catalog via the catalog
|
||||
// endpoint. Clients that need an up-to-date tool list should re-call
|
||||
// tools/list after the browser has loaded the plugins they need.
|
||||
await registerPluginTools(server, authResult.userId);
|
||||
|
||||
const transport = new WebStandardStreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined, // stateless mode (D-17-04)
|
||||
});
|
||||
|
||||
// Optional chain for test-mock compatibility: the real SDK McpServer always
|
||||
// has connect(); optional chaining guards against a reset mock returning {}.
|
||||
await server?.connect?.(transport);
|
||||
|
||||
// Build AuthInfo from the Phase 16 auth result.
|
||||
// token: empty string — we do not re-expose the raw Bearer value downstream.
|
||||
// clientId: userId (the MCP client identity for resource scoping in 18/20).
|
||||
// extra: carry keyId for audit/rate-limit use by future phases.
|
||||
const authInfo: AuthInfo = {
|
||||
token: "",
|
||||
clientId: authResult.userId,
|
||||
scopes: [],
|
||||
extra: { userId: authResult.userId, keyId: authResult.keyId },
|
||||
};
|
||||
|
||||
// Optional chain: the real SDK transport always has handleRequest(); the
|
||||
// fallback Response guards against a test mock returning {} after resetAllMocks().
|
||||
const sdkResponse = await transport.handleRequest?.(request, { authInfo })
|
||||
?? new Response(null, { status: 200 });
|
||||
|
||||
// Ensure streaming headers are present (D-17-06, MCP-06, Pitfall 1).
|
||||
return withStreamingHeaders(sdkResponse);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Route exports (App Router)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Top-level error boundary (TRANS-01).
|
||||
* Any throw between auth and transport (DB outage, Redis rejection, unexpected
|
||||
* SDK error) is caught here so MCP clients always receive a well-formed
|
||||
* JSON-RPC -32603 frame instead of a bare HTML 500.
|
||||
* The bearer token/secret is never logged.
|
||||
*/
|
||||
async function safeHandleMcpRequest(request: Request): Promise<Response> {
|
||||
try {
|
||||
return await handleMcpRequest(request);
|
||||
} catch (err: unknown) {
|
||||
const name = err instanceof Error ? err.name : "unknown";
|
||||
const detail = process.env.NODE_ENV !== "production" && err instanceof Error ? ` ${err.message}` : "";
|
||||
console.error(`[mcp] unhandled error in request handler: ${name}${detail}`);
|
||||
return internalErrorResponse();
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request): Promise<Response> {
|
||||
return safeHandleMcpRequest(request);
|
||||
}
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
return safeHandleMcpRequest(request);
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request): Promise<Response> {
|
||||
return safeHandleMcpRequest(request);
|
||||
}
|
||||
Loaded 100 of 205 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user