Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a503f7a517 |
No files matched your search
@@ -28,55 +28,32 @@ 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):
|
||||
# Build the CLI first if dist/ is missing (dist is gitignored; fresh worktrees lack it):
|
||||
# pnpm --filter @worldwideview/wwv-cli build
|
||||
#
|
||||
# The CLI accepts flags for every prompt. Pass them all + --yes for a fully
|
||||
# non-interactive scaffold (omit any flag to be prompted for just that value):
|
||||
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 \
|
||||
--architecture <polling|websocket> \
|
||||
--seeder-tier <community|private> \
|
||||
--render-style <billboard|model|point> \
|
||||
--yes
|
||||
|
||||
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.
|
||||
This creates `local-plugins/wwv-plugin-<name>/`. With `--architecture websocket` it also
|
||||
creates the seeder at `local-seeders/<tier>/packages/<name>/` (correct community/private
|
||||
layout: `package.json` + `tsup.config.ts` + `src/index.ts`). Verify both 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.
|
||||
> The CLI scaffolds the seeder into `local-seeders/<tier>/packages/<name>/` already —
|
||||
> no post-CLI move is required. (Older CLI versions dropped a bare `seeder.mjs` at
|
||||
> `local-seeders/<tier>/<name>/`; if you ever see that, the CLI is out of date — rebuild it.)
|
||||
|
||||
**NEVER:**
|
||||
- Scaffold manually (always use the CLI)
|
||||
@@ -157,15 +134,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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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,15 @@
|
||||
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,33 +1,15 @@
|
||||
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).
|
||||
# CLI-only changes are covered by cli.yml; skip the image build for them.
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "prisma/**"
|
||||
- "packages/**"
|
||||
- "scripts/**"
|
||||
- "Dockerfile"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "next.config.ts"
|
||||
- ".github/workflows/docker-publish.yml"
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "prisma/**"
|
||||
- "packages/**"
|
||||
- "scripts/**"
|
||||
- "Dockerfile"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "next.config.ts"
|
||||
- ".github/workflows/docker-publish.yml"
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
|
||||
@@ -1,32 +1,14 @@
|
||||
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).
|
||||
# CLI-only changes are covered by cli.yml; skip browser E2E for them.
|
||||
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"
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
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"
|
||||
paths-ignore:
|
||||
- "packages/wwv-cli/**"
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
|
||||
-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,115 +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.4 Agentic Intelligence
|
||||
|
||||
**Goal:** Transform the WWV MCP server from a collection of atomic tools into a well-instructed, investigation-capable AI assistant -- one that knows what it has, reasons over the globe, and delivers both globe actions and prose reports.
|
||||
|
||||
**Target features:**
|
||||
- Server `instructions` field + workflow sequences (agent oriented from first connection)
|
||||
- MCP Prompts for named workflows (`orient-globe`, `investigate`)
|
||||
- Full 6-component tool description rewrite across all 15+ existing tools
|
||||
- `emptyReason` field in all query responses (distinguishes "no data" from "plugin not loaded")
|
||||
- `list_available_plugins` tool (agent checks before querying)
|
||||
- `get_globe_context` tool (full orientation snapshot in one call)
|
||||
- `investigate_area` compound tool (geocode + check + query + act + report)
|
||||
- `update_favorite` tool (completes full CRUD lifecycle for favorites)
|
||||
|
||||
**Backlog (deferred):**
|
||||
- PLG-01/PLG-02: list_plugins() + install_plugin() marketplace tools (backlog 999.1/999.2)
|
||||
- UX-01: ConnectAgentHelper upgrade CTA in demo edition (backlog 999.3)
|
||||
|
||||
## 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
|
||||
|
||||
### Active (v1.4 Agentic Intelligence)
|
||||
|
||||
- [ ] Server `instructions` field with role-framing and canonical workflow sequences
|
||||
- [ ] MCP Prompts: `orient-globe` and `investigate` named workflow templates
|
||||
- [ ] 6-component tool description rewrite for all command, query, and v1.3 tools
|
||||
- [ ] `emptyReason` field on all query tool responses
|
||||
- [ ] `get_plugin_filters` returns explicit `{available: false}` when plugin not active
|
||||
- [ ] `list_available_plugins` MCP tool (streaming plugins + entity counts)
|
||||
- [ ] `get_globe_context` MCP tool (full orientation snapshot)
|
||||
- [ ] `investigate_area` compound MCP tool (geocode + check + query + act + prose report)
|
||||
- [ ] `update_favorite` MCP tool (complete CRUD lifecycle for favorites)
|
||||
|
||||
### 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
|
||||
|
||||
## 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-05-31 after v1.4 milestone start*
|
||||
@@ -1,94 +0,0 @@
|
||||
# Requirements: WorldWideView v1.4 Agentic Intelligence
|
||||
|
||||
**Defined:** 2026-05-31
|
||||
**Core Value:** A single globe controllable by any AI agent via MCP -- where the agent arrives oriented, investigates intelligently, and acts with confidence.
|
||||
|
||||
## v1.3 Requirements (shipped)
|
||||
|
||||
All v1.3 requirements are complete. See archive for details.
|
||||
|
||||
## v1.4 Requirements
|
||||
|
||||
### INST -- Server Instructions & Orientation
|
||||
|
||||
- [x] **INST-01**: MCP server returns a populated `instructions` field in InitializeResult containing a role-framing markdown document that tells agents who WWV is, what tools are available, and the mental model for using them
|
||||
- [x] **INST-02**: The `instructions` document embeds canonical workflow sequences: geocode-first before fly_to, check plugin availability before querying entities, read globe://sessions before sending any command tool
|
||||
- [x] **INST-03**: MCP server registers an `orient-globe` Prompt that agents can invoke to get a structured snapshot of current sessions, active layers, and loaded plugins in one response
|
||||
- [x] **INST-04**: MCP server registers an `investigate` Prompt that accepts a place name and guides the agent step-by-step through geocode -> plugin availability check -> region query -> globe action
|
||||
|
||||
### DESC -- Tool Description Rewrite (6-component standard)
|
||||
|
||||
Tool descriptions must include: (1) purpose verb+object front-loaded, (2) when-to-use vs. alternatives, (3) limitations and empty-result meaning, (4) parameter format + ranges, (5) concrete examples, (6) appropriate length (not truncated at the key sentence).
|
||||
|
||||
- [x] **DESC-01**: All globe command tools rewritten to 6-component standard: `pan_globe`, `fly_to`, `focus_entity`, `toggle_layer`, `set_timeline` -- each includes sessions precondition inline and distinguishes from its nearest alternative
|
||||
- [x] **DESC-02**: All data query tools rewritten to 6-component standard: `search_entities`, `get_entities_in_region`, `get_entity_details`, `get_plugin_data` -- each includes plugin-availability note and explanation of what empty results mean
|
||||
- [x] **DESC-03**: All v1.3 tools rewritten to 6-component standard: `geocode_location`, `set_filter`, `clear_filter`, `get_plugin_filters`, `save_favorite`, `list_favorites`, `remove_favorite`
|
||||
|
||||
### RESP -- Smart Response Contracts
|
||||
|
||||
- [x] **RESP-01**: All query tools (`search_entities`, `get_entities_in_region`, `get_entity_details`, `get_plugin_data`) include an `emptyReason` field when results are empty: `"plugin_not_streaming"` | `"no_data_matches"` | `"no_session_active"`
|
||||
- [x] **RESP-02**: `get_plugin_filters` returns `{ available: false, reason: "plugin not loaded" }` (not an empty array) when the requested plugin is not active in the engine
|
||||
|
||||
### TOOL -- New Compound & Discovery Tools
|
||||
|
||||
- [x] **TOOL-01**: `list_available_plugins` MCP tool returns which plugins are currently streaming data to the engine, including entity counts and queryable entity types per plugin -- agents call this before attempting any data query
|
||||
- [x] **TOOL-02**: `get_globe_context` MCP tool returns a full orientation snapshot in one call: active session count, camera position, active layers, applied filters, loaded plugin list -- replaces reading multiple resources separately
|
||||
- [x] **TOOL-03**: `investigate_area(place_name, entity_type, radius_km?)` compound MCP tool that internally geocodes the place, checks which plugins are streaming the entity type, queries the bounding region, positions the globe camera, and returns both the entity list and a prose situation summary
|
||||
|
||||
### CRUD -- Full Favorites Lifecycle
|
||||
|
||||
- [x] **CRUD-01**: `update_favorite(favoriteId, { name?, notes? })` MCP tool allows agents to rename or annotate a saved bookmark without deleting and re-creating it -- completes Create/Read/Update/Delete lifecycle for favorites
|
||||
|
||||
## Future Requirements (deferred)
|
||||
|
||||
### Plugin Marketplace Integration
|
||||
|
||||
- PLG-01: `list_plugins` MCP tool showing available marketplace plugins
|
||||
- PLG-02: `install_plugin` MCP tool to install a plugin from the marketplace
|
||||
- UX-01: ConnectAgentHelper upgrade CTA in demo edition
|
||||
|
||||
### Advanced Investigation
|
||||
|
||||
- Multi-turn investigation memory (agent remembers prior findings across sessions)
|
||||
- Proactive monitoring (agent watches for changes and alerts)
|
||||
- Saved investigation reports (persistent CRUD for investigation outputs)
|
||||
- Filter presets (save/apply named filter configurations)
|
||||
|
||||
## Out of Scope
|
||||
|
||||
| Feature | Reason |
|
||||
|---------|--------|
|
||||
| Embedding AI chat UI in the globe | MCP is server-only; chat is the client's job |
|
||||
| Browser-side MCP client | Globe is an MCP server target, not client |
|
||||
| Playwright / computer-use control | SSE command bridge is the pattern |
|
||||
| Stdio MCP transport | HTTP/SSE for production deployability |
|
||||
| OAuth 2.1 for MCP auth | Personal API keys sufficient |
|
||||
| API key scopes/permissions/rotation | Revisit post-v1.4 |
|
||||
| Proactive monitoring / push alerts | Agent-pulls model only in v1.4 |
|
||||
|
||||
## Traceability
|
||||
|
||||
| Requirement | Phase | Status |
|
||||
|-------------|-------|--------|
|
||||
| INST-01 | Phase 26 | Complete |
|
||||
| INST-02 | Phase 26 | Complete |
|
||||
| INST-03 | Phase 26 | Complete |
|
||||
| INST-04 | Phase 26 | Complete |
|
||||
| DESC-01 | Phase 27 | Complete |
|
||||
| DESC-02 | Phase 27 | Complete |
|
||||
| DESC-03 | Phase 27 | Complete |
|
||||
| RESP-01 | Phase 28 | Complete |
|
||||
| RESP-02 | Phase 28 | Complete |
|
||||
| CRUD-01 | Phase 28 | Complete |
|
||||
| TOOL-01 | Phase 29 | Complete |
|
||||
| TOOL-02 | Phase 29 | Complete |
|
||||
| TOOL-03 | Phase 29 | Complete |
|
||||
|
||||
**Coverage:**
|
||||
- v1.4 requirements: 13 total
|
||||
- Mapped to phases: 13
|
||||
- Unmapped: 0 ✓
|
||||
|
||||
---
|
||||
*Requirements defined: 2026-05-31*
|
||||
*Last updated: 2026-05-31 after initial v1.4 definition*
|
||||
@@ -1,195 +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)
|
||||
- [ ] **v1.4 Agentic Intelligence** - Phases 26-29 (active)
|
||||
|
||||
## 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>
|
||||
|
||||
### v1.4 Agentic Intelligence
|
||||
|
||||
- [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)
|
||||
|
||||
## Phase Details
|
||||
|
||||
### Phase 22: Geocoding + Favorites
|
||||
**Goal**: AI agents can find any place on Earth by name, fly the globe camera to it, and bookmark tracked entities for later retrieval
|
||||
**Depends on**: Phase 21 (v1.2 SSE command bridge, authenticateApiKey, Redis, Prisma Favorite model)
|
||||
**Requirements**: GEO-01, GEO-02, GEO-03, FAV-01, FAV-02, FAV-03, SAFE-01, SAFE-02
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Agent calls `geocode_location("Paris")` and receives ranked results with lat/lng/name/bbox without triggering Nominatim rate limits across repeated calls
|
||||
2. Agent calls `fly_to(48.85, 2.35)` and the live globe camera pans to that coordinate within SSE push latency (< 100ms)
|
||||
3. Agent calls `save_favorite`, then `list_favorites`, and the saved entity appears with a `status` field reflecting whether it is currently live in the data stream
|
||||
4. Agent calls `remove_favorite` and the entry is gone from subsequent `list_favorites` responses
|
||||
5. All new tools return a structured error (not 500) when called in demo edition, consistent with v1.2 isDemo gate behavior
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 23: Entity Filtering
|
||||
**Goal**: AI agents can push live filters to the globe and discover what filter fields each plugin exposes
|
||||
**Depends on**: Phase 22 (isDemo + authenticateApiKey patterns established, GlobeCommand type in Redis/SSE bridge)
|
||||
**Requirements**: FILT-01, FILT-02, FILT-03, FILT-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Agent calls `set_filter("flights", { status: "airborne" })` and the globe immediately hides non-airborne entities without a page reload
|
||||
2. Agent calls `clear_filter()` with no arguments and all active plugin filters are removed from the globe in one command
|
||||
3. Agent calls `get_plugin_filters("flights")` and receives the filterable fields declared in that plugin's session catalog entry
|
||||
4. Agent passes `filters` to the existing `search_entities` call and receives only matching results, with no dependency on prior `set_filter` state
|
||||
**Plans**: 3 plans (ships atomically per STATE.md)
|
||||
- [x] 23-01-PLAN.md — Foundation: GlobeCommand setFilter/clearFilter variants + validator, bridge dispatch into filterSlice, shared filterValueSchema, matchFilterValue extraction, catalog filterDefinitions, RED tool stubs (wave 1, TDD)
|
||||
- [x] 23-02-PLAN.md — Filter MCP tools (set_filter, clear_filter, get_plugin_filters), search_entities filters param on properties, catalog publisher emits filterDefinitions (wave 2, TDD)
|
||||
- [x] 23-03-PLAN.md — Wire registerFilterTools into the MCP route + atomic phase integration verification (wave 3)
|
||||
|
||||
### Phase 24: Route Wiring + Version Bump
|
||||
**Goal**: All v1.3 tools are reachable via the production MCP endpoint and the server self-reports version 1.3.0
|
||||
**Depends on**: Phase 22, Phase 23 (all registrars implemented)
|
||||
**Requirements**: INTG-01 (integration wiring), INTG-02 (version bump)
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. MCP `tools/list` response includes all v1.3 tools: `geocode_location`, `fly_to`, `save_favorite`, `list_favorites`, `remove_favorite`, `set_filter`, `clear_filter`, `get_plugin_filters`
|
||||
2. MCP server `serverInfo.version` field returns `"1.3.0"` on every initialize handshake
|
||||
3. `search_entities` with optional `filters` param is reflected in the tool schema exposed to clients
|
||||
**Plans**: 24-01 (COMPLETE) - INTG-01 verified, INTG-02 shipped (MCP_SERVER_VERSION 1.3.0)
|
||||
**Status**: COMPLETE 2026-05-31. tsc clean, 750 Vitest tests GREEN, build OK. Commits 5201ae3, 5ea7855.
|
||||
|
||||
### Phase 25: Documentation
|
||||
**Goal**: Every v1.3 feature is fully documented for three audiences: MCP clients (tool schemas), plugin developers (filter manifest guide), and end users (capability summary)
|
||||
**Depends on**: Phase 24 (all tools shipped and wired; final tool schemas stable)
|
||||
**Requirements**: DOC-01, DOC-02, DOC-03, DOC-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Every v1.3 MCP tool description in `registerGeocodingTools`, `registerFavoritesTools`, `registerFilterTools` includes: what it does, all input params with types, the output shape, and at least one usage example
|
||||
2. A `docs/plugin-filter-guide.md` (or equivalent) explains how a plugin author declares `filterDefinitions` in their manifest with a complete worked example for a hypothetical flights plugin
|
||||
3. ConnectAgentHelper or a linked doc lists all v1.3 tools an agent can call, with a plain-English description of each capability
|
||||
4. A v1.3 changelog entry (in `CHANGELOG.md` or the PR body) lists all 8 new MCP tools, the `search_entities` filter enhancement, and the version bump to 1.3.0
|
||||
**Plans**: 25-01 (COMPLETE) - DOC-01..04 closed.
|
||||
**Status**: COMPLETE 2026-05-31. Enriched all 8 v1.3 tool descriptions (DOC-01), added docs/plugin-filter-guide.md (DOC-02), listed all tools in ConnectAgentHelper (DOC-03), added CHANGELOG.md v1.3.0 entry (DOC-04). tsc clean, 750 Vitest tests GREEN, build OK. Commits 84f8ade, 26d2063, 2eec714, f1405bd.
|
||||
|
||||
### Phase 26: Server Instructions + Orientation
|
||||
**Goal**: A fresh AI agent connecting to the WWV MCP server for the first time receives a complete orientation -- who WWV is, what tools exist, and the canonical workflows to follow -- without the user having to explain anything
|
||||
**Depends on**: Phase 25 (v1.3 complete; stable tool set as orientation baseline)
|
||||
**Requirements**: INST-01, INST-02, INST-03, INST-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. The MCP `initialize` response contains a non-empty `instructions` field with a role-framing header, a mental model for the globe/plugins/sessions, and at least two explicit "do X before Y" rules (read sessions before commanding; check plugin availability before querying)
|
||||
2. A fresh agent that has only read `instructions` correctly answers: "What do I need to do before calling pan_globe?" without having read any individual tool description
|
||||
3. Calling `prompts/list` returns both `orient-globe` and `investigate` prompt names; calling `prompts/get` on each returns a structured, step-numbered template with no placeholder text
|
||||
4. An agent invoking the `orient-globe` prompt receives a single response containing active sessions, loaded plugin layers, and current camera state -- no follow-up resource reads needed to get oriented
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 27: Tool Description Rewrite
|
||||
**Goal**: Every existing MCP tool description satisfies the 6-component standard so an agent selects the right tool, passes correct arguments, and correctly interprets empty results on the first attempt
|
||||
**Depends on**: Phase 26 (instructions written first; tool descriptions must align with the canonical workflows stated there)
|
||||
**Requirements**: DESC-01, DESC-02, DESC-03
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Every command tool description (`pan_globe`, `fly_to`, `focus_entity`, `toggle_layer`, `set_timeline`) contains inline: the sessions precondition, what "no active session" means, and when to prefer this tool over its nearest alternative
|
||||
2. Every data query tool description (`search_entities`, `get_entities_in_region`, `get_entity_details`, `get_plugin_data`) states explicitly what an empty result means -- distinguishing "plugin not loaded" from "no matching data"
|
||||
3. Every v1.3 tool description (`geocode_location`, `set_filter`, `clear_filter`, `get_plugin_filters`, `save_favorite`, `list_favorites`, `remove_favorite`) passes the 6-component checklist: purpose, when-to-use, limitations, parameter format, example, complete length
|
||||
4. No tool description is truncated at a critical constraint; each fits within MCP client display limits while retaining all mandatory guidance
|
||||
**Plans**: 3 plans (all wave 1, parallel -- no file overlap)
|
||||
- [x] 27-01-PLAN.md — DESC-01: rewrite 4 globe command tool descriptions (pan_globe, focus_entity, toggle_layer, set_timeline) + assertion tests
|
||||
- [x] 27-02-PLAN.md — DESC-02: rewrite 4 data query tool descriptions with empty-result semantics + new tools.test.ts
|
||||
- [x] 27-03-PLAN.md — DESC-03: conform 8 v1.3 tool descriptions across geocoding/filter/favorites (fly_to gets the sessions precondition) + assertion tests
|
||||
|
||||
### Phase 28: Smart Response Contracts + Favorites CRUD
|
||||
**Goal**: Query tools communicate WHY results are empty rather than returning identical empty arrays for unrelated failure modes, and agents can update a saved favorite without deleting and recreating it
|
||||
**Depends on**: Phase 27 (tool descriptions must reference emptyReason semantics described there)
|
||||
**Requirements**: RESP-01, RESP-02, CRUD-01
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Calling `search_entities` with a plugin that has no active streaming session returns `{ success: true, entities: [], count: 0, emptyReason: "plugin_not_streaming" }` -- distinct from a query that returns `"no_data_matches"` when the plugin is streaming but nothing matches the filter
|
||||
2. Calling `search_entities` when no globe session is active returns `emptyReason: "no_session_active"` -- the agent can distinguish this from a data absence without guessing
|
||||
3. Calling `get_plugin_filters("flights")` when the flights plugin is not loaded returns `{ available: false, reason: "plugin not loaded" }` rather than an empty array, allowing the agent to report the real cause to the user
|
||||
4. Calling `update_favorite(id, { name: "New Name", notes: "Updated note" })` persists the change and is reflected in the next `list_favorites` response without requiring `remove_favorite` + `save_favorite`
|
||||
**Plans**: 3 plans
|
||||
- [x] 28-01-PLAN.md — RESP-01: emptyReason discriminated service results + userId threading into registerDataQueryTools + 4-tool passthrough with session-first precedence + tests (wave 1)
|
||||
- [x] 28-02-PLAN.md — RESP-02: get_plugin_filters availability wrapper (4 shapes) + Phase 27 description/test updates (wave 2, depends on 28-01 for route.ts seam)
|
||||
- [x] 28-03-PLAN.md — CRUD-01: [BLOCKING] notes String? migration + update_favorite tool + list_favorites notes surfacing + tests (wave 1, independent files)
|
||||
|
||||
### Phase 29: Compound and Discovery Tools
|
||||
**Goal**: Agents can answer "what is happening near X?" in a single tool call, check which plugins are active before querying, and orient themselves completely without reading multiple resources
|
||||
**Depends on**: Phase 28 (emptyReason contracts and CRUD-01 must be complete; investigate_area depends on emptyReason to characterize its sub-query results)
|
||||
**Requirements**: TOOL-01, TOOL-02, TOOL-03
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Calling `list_available_plugins` returns a list of currently streaming plugins with entity counts and queryable entity types; an agent that calls this before `search_entities` never receives a `plugin_not_streaming` emptyReason it did not anticipate
|
||||
2. Calling `get_globe_context` returns in one response: active session count, camera position, active layers, applied filters, and loaded plugin list -- an agent that reads this resource needs no additional `globe://sessions`, `globe://state`, or `globe://layers` reads to be fully oriented
|
||||
3. Calling `investigate_area("Auckland", "flights")` internally geocodes the place, checks which plugins stream flights, queries the bounding region, positions the globe camera over Auckland, and returns both the entity list and a prose situation summary describing what is happening in that area
|
||||
4. `investigate_area` returns a meaningful prose report even when no entities match -- the summary explains why (e.g., no active flight plugin) rather than returning an empty structure
|
||||
**UI hint**: no
|
||||
**Plans**: 1 plan
|
||||
- [x] 29-01-PLAN.md — All three discovery tools (list_available_plugins, get_globe_context, investigate_area) in discoveryTools.ts + shared discoveryHelpers.ts + route wiring + tests
|
||||
|
||||
## 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 |
|
||||
|
||||
## Backlog
|
||||
|
||||
Per the 21-REPLAN locked decision ("NO marketplace" in v1.2 scope), the two marketplace
|
||||
plugin-management MCP tools were deferred. They require the marketplace JWT install bridge,
|
||||
which was descoped to keep v1.2 worldwideview-only.
|
||||
|
||||
- **999.1 -- PLG-01: `list_plugins()` MCP tool** -- returns all marketplace plugins with
|
||||
install status for the authenticated user. Depends on marketplace API + JWT bridge.
|
||||
- **999.2 -- PLG-02: `install_plugin({ pluginSlug })` MCP tool** -- triggers installation via
|
||||
the existing marketplace JWT install bridge flow. Depends on PLG-01 + marketplace install endpoint.
|
||||
|
||||
- **999.3 -- UX-01: Show MCP / ConnectAgentHelper as "Cloud edition" upgrade CTA in demo** --
|
||||
Currently `!isDemo` in Header.tsx:449 hides the entire ConnectAgentHelper section in demo.
|
||||
UX improvement: surface it as a locked/teaser CTA that explains the feature and links to
|
||||
upgrade. Pairs with v1.3 MCP-OBSERVATIONS.md scope (geocoding, OSM search, basemap control,
|
||||
entity filtering, enhanced search, favorites, plugin-tool discovery).
|
||||
|
||||
Also tracked as partials (functional, refinement deferred):
|
||||
- **CTRL-02** focus_entity entityId-only resolution -- currently a no-op without lat/lng;
|
||||
needs entity-id -> coordinate lookup wired into the command dispatch.
|
||||
- **MCP-QA-03** explicit Redis reconnect test -- stateless SSE arch makes the original
|
||||
WebSocket-subscriber spec N/A; ioredis auto-reconnects. Add a reconnect test if reliability
|
||||
concerns arise.
|
||||
|
||||
### Phase 30: Local Data-Source Bridge: make server-reachable client-side and static plugins (camera GeoJSON, OSM-static plugins) queryable via MCP through a generalized LocalDataSource registry. Closes the MCP coverage gap where browser-loaded plugins return plugin_not_streaming. Camera is the first consumer.
|
||||
|
||||
**Goal:** Server-reachable client-side/static plugins (camera GeoJSON + traffic route) are MCP-queryable through a generalized manifest-declared LocalDataSource registry, with NO browser session -- closing the plugin_not_streaming coverage gap. Acceptance: a Russia-bbox `get_entities_in_region(pluginId:"camera")` returns the in-box cameras and `list_available_plugins` lists camera as `source:"local"` with a non-zero count.
|
||||
**Requirements**: D-01..D-08 (CONTEXT decisions), RESP-01 (emptyReason contract preserved), TOOL-01/TOOL-02 (discovery surface)
|
||||
**Depends on:** Phase 29
|
||||
**Plans:** 4/4 plans complete
|
||||
|
||||
Plans:
|
||||
- [x] 30-01-PLAN.md — Foundation: SDK LocalDataSourceDeclaration type + camera package.json localData declaration + sync-local-plugins passthrough + validateManifest localData validator (wave 1, TDD)
|
||||
- [x] 30-02-PLAN.md — localSources module: manifest-driven registry + server-side GeoJSON normalizer + per-source TTL cache (wave 2, TDD)
|
||||
- [x] 30-03-PLAN.md — Integration seam: fetchPluginSnapshot engine->local->null fallback + getAllPluginSnapshots local-id union; Russia-bbox demo + D-06 emptyReason cases (wave 3, TDD)
|
||||
- [x] 30-04-PLAN.md — Discovery surface: StreamingPlugin source:"engine"|"local" tag in listStreamingPlugins; camera surfaced in list_available_plugins/get_globe_context (wave 4, TDD)
|
||||
@@ -1,83 +0,0 @@
|
||||
---
|
||||
gsd_state_version: 1.0
|
||||
milestone: v1.4
|
||||
milestone_name: Agentic Intelligence
|
||||
status: verifying
|
||||
last_updated: "2026-06-02T04:43:48.134Z"
|
||||
last_activity: 2026-06-02
|
||||
progress:
|
||||
total_phases: 9
|
||||
completed_phases: 8
|
||||
total_plans: 22
|
||||
completed_plans: 21
|
||||
percent: 89
|
||||
---
|
||||
|
||||
# Project State
|
||||
|
||||
## Project Reference
|
||||
|
||||
See: .planning/PROJECT.md (updated 2026-05-31)
|
||||
|
||||
**Core value:** A single globe controllable by any AI agent via MCP -- where the agent arrives oriented, investigates intelligently, and acts with confidence.
|
||||
**Current focus:** Phase 30 — local-data-source-bridge-make-server-reachable-client-side-a
|
||||
|
||||
## Current Position
|
||||
|
||||
Phase: 30 (local-data-source-bridge-make-server-reachable-client-side-a) — EXECUTING
|
||||
Plan: 4 of 4
|
||||
Status: Phase complete — ready for verification
|
||||
Last activity: 2026-06-02
|
||||
Resume file: None
|
||||
|
||||
Progress: [██████████] 95%
|
||||
|
||||
## v1.4 Phase Map
|
||||
|
||||
| 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 |
|
||||
|
||||
## Key Decisions (carried from v1.2/v1.3)
|
||||
|
||||
- **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). Reuse for fly_to in v1.3.
|
||||
- **Plugin tools via frontend relay:** No engine endpoint. useMcpCatalogPublisher + useMcpRelayBridge pattern.
|
||||
- **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 new MCP tools.
|
||||
- **LocalDataSource registry (Phase 30-02):** Scans public/plugins-local/<id>/plugin.json at startup; memoized once per process. Per-source TTL cache: TTL_GEOJSON_MS=60min, TTL_ROUTE_MS=60s. geojson sources read from disk (no self-HTTP); route sources fetched via internal base URL.
|
||||
- **LocalDataSourceDeclaration SDK export:** Added to wwv-plugin-sdk/src/index.ts re-exports (was absent from Plan 30-01 manifest.ts addition).
|
||||
|
||||
## v1.3 Phase Map (archived reference)
|
||||
|
||||
| Phase | Goal | Key requirements |
|
||||
|-------|------|-----------------|
|
||||
| 22 | Geocoding + Favorites | GEO-01..03, FAV-01..03, SAFE-01..02 |
|
||||
| 23 | Entity Filtering | FILT-01..04 |
|
||||
| 24 | Route Wiring + Version Bump | INTG-01, INTG-02 |
|
||||
| 25 | Documentation | DOC-01..04 |
|
||||
|
||||
## Blockers
|
||||
|
||||
None.
|
||||
|
||||
## Accumulated Context
|
||||
|
||||
### Roadmap Evolution
|
||||
|
||||
- Phase 30 added: Local Data-Source Bridge (Option A): generalized LocalDataSource registry to make server-reachable static/client-side plugins MCP-queryable; camera first consumer
|
||||
- v1.2 archived at .planning/milestones/v1.2-* and tagged v1.2 in git.
|
||||
- PR #215 (feat/mcp-support) open on GitHub, awaiting merge.
|
||||
- v1.3 complete 2026-05-31. All 4 phases shipped, tsc clean, 750 tests GREEN.
|
||||
- Phase numbering: v1.4 starts at Phase 26 (v1.3 ended at Phase 25).
|
||||
- Phase 26 is pure configuration/server-init work -- no new tool implementations. McpServer `instructions` string + two MCP Prompt registrations.
|
||||
- Phase 27 is pure description text rewriting across 15+ existing tools -- no schema changes, no new tools. Lowest risk phase.
|
||||
- Phase 28 requires code changes to query handler return shapes (emptyReason field) and one new Prisma mutation (update_favorite). Coordinate with prisma.favorite model in Phase 28 plan.
|
||||
- Phase 29 is the most complex: investigate_area is a compound tool that chains geocode -> plugin check -> region query -> SSE command -> prose generation internally. Design the internal chain carefully; it must not expose intermediate tool results to the caller.
|
||||
- Nominatim integration: server-side rate limiter (1 req/sec Redis sliding window) + 24h result cache are already live (GEO-03, Phase 22). investigate_area (TOOL-03) reuses this path -- do not re-implement.
|
||||
- Favorites use prisma.favorite directly -- never proxy through /api/user/favorites (cookie auth incompatible with API key sessions, SAFE-02). update_favorite (CRUD-01) must follow same pattern.
|
||||
- emptyReason values are an enum contract: "plugin_not_streaming" | "no_data_matches" | "no_session_active". Agree on this enum in Phase 28 and reference it in Phase 27 tool description rewrites -- do Phase 27 after Phase 26 but the enum must be locked before DESC-02 is written.
|
||||
@@ -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
-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,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" },
|
||||
|
||||
+2
-5
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "2.48.4",
|
||||
"version": "2.24.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
@@ -28,7 +28,6 @@
|
||||
"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",
|
||||
@@ -36,15 +35,12 @@
|
||||
"@supabase/ssr": "^0.10.3",
|
||||
"@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.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.6",
|
||||
@@ -124,3 +120,4 @@
|
||||
"pnpm": ">=9.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
+696
-576
File diff suppressed because it is too large.
Load diff
@@ -17,7 +17,6 @@ model User {
|
||||
createdAt DateTime @default(now())
|
||||
favorites Favorite[]
|
||||
memberships WorkspaceMember[]
|
||||
apiKeys UserApiKey[]
|
||||
|
||||
@@unique([tenantId, email])
|
||||
@@map("users")
|
||||
@@ -32,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])
|
||||
@@ -104,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,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 });
|
||||
}
|
||||
@@ -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,310 +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);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
const result = await listStreamingPlugins();
|
||||
expect(result.plugins).toHaveLength(0);
|
||||
expect(result.reason).toBe("engine unreachable");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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 still returns { plugins: [], reason: 'engine unreachable' }", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
// localIds irrelevant when snapshots list is empty
|
||||
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,270 +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);
|
||||
const lonDelta = radiusKm / (111 * clampedCos);
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the engine manifest and per-plugin snapshots to build a summary list.
|
||||
* Returns `{ plugins: [], reason: "engine unreachable" }` when no snapshots are
|
||||
* available (engine down or no active plugins).
|
||||
*/
|
||||
export async function listStreamingPlugins(): Promise<ListStreamingPluginsResult> {
|
||||
const snapshots = await getAllPluginSnapshots();
|
||||
if (snapshots.length === 0) {
|
||||
return { plugins: [], reason: "engine unreachable" };
|
||||
}
|
||||
const localIds = await getLocalSourceIds();
|
||||
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,265 +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", async () => {
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -1,219 +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;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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. " +
|
||||
"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: 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: allEntities.length,
|
||||
sessionPresent,
|
||||
emptyReason: lastEmptyReason,
|
||||
});
|
||||
|
||||
return textResult({ entities: allEntities, 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,228 +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 () => {
|
||||
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.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" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
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,221 +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";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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: z.string().min(1).describe("Unique entity identifier"),
|
||||
pluginId: z.string().min(1).describe("Plugin that owns this entity"),
|
||||
name: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Human-readable label for the bookmark (defaults to entityId)"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
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: z.string().min(1).describe("The entityId of the favorite to update"),
|
||||
name: z.string().optional().describe("New display label for the bookmark"),
|
||||
notes: z.string().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: z.string().min(1).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,174 +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";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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:
|
||||
"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. " +
|
||||
"Limitations: filter ids are plugin-specific; invalid ids are silently ignored by the browser. " +
|
||||
"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 'no active globe session to control'. " +
|
||||
"Example: set_filter({ pluginId: 'flights', filters: { status: { type: 'select', values: ['airborne'] } } }).",
|
||||
inputSchema: {
|
||||
pluginId: z.string().min(1).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;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "setFilter",
|
||||
pluginId: args.pluginId,
|
||||
filters: args.filters,
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
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:
|
||||
"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: z.string().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: z.string().min(1).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,154 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/nominatim");
|
||||
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,207 +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 } from "@/lib/nominatim";
|
||||
import type { RawNominatimItem, NominatimResult } from "@/lib/nominatim";
|
||||
import { checkRateLimit } from "@/lib/geocodingRateLimit";
|
||||
import { redis } from "@/lib/redis";
|
||||
import { latSchema, lonSchema } from "@/lib/mcp/coordinateSchemas";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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");
|
||||
|
||||
/**
|
||||
* Normalize a raw Nominatim item to the public NominatimResult shape (D-06).
|
||||
* Kept local (not imported) so that test mocks of "@/lib/nominatim" -- which
|
||||
* only stub fetchGeocode -- do not stub out the normalization step.
|
||||
* Nominatim boundingbox is ["south","north","west","east"]; remap to
|
||||
* [west, south, east, north] numbers.
|
||||
*/
|
||||
function normalizeResult(r: RawNominatimItem): NominatimResult {
|
||||
const bb = r.boundingbox ?? ["0", "0", "0", "0"];
|
||||
return {
|
||||
lat: parseFloat(r.lat ?? "0"),
|
||||
lng: parseFloat(r.lon ?? "0"),
|
||||
name: r.name ?? "",
|
||||
name_en: r.namedetails?.["name:en"] ?? r.name ?? "",
|
||||
type: r.type ?? "",
|
||||
addresstype: r.addresstype ?? "",
|
||||
country: r.address?.country ?? "",
|
||||
display_name: r.display_name ?? "",
|
||||
bbox: [parseFloat(bb[2]), parseFloat(bb[0]), parseFloat(bb[3]), parseFloat(bb[1])],
|
||||
importance: r.importance ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** 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.map(normalizeResult);
|
||||
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:
|
||||
"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,437 +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 } = vi.hoisted(() => ({
|
||||
mockEnqueue: vi.fn().mockResolvedValue(undefined),
|
||||
mockResolveSessionId: vi.fn().mockResolvedValue("resolved-session"),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/globeCommandQueue", () => ({
|
||||
enqueueGlobeCommand: mockEnqueue,
|
||||
resolveActiveSessionId: mockResolveSessionId,
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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);
|
||||
});
|
||||
});
|
||||
@@ -1,215 +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";
|
||||
|
||||
// Re-export so existing tests that import from this module continue to work.
|
||||
export { latSchema, lonSchema, altSchema };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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:
|
||||
"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:
|
||||
"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; note entity-id-to-coordinate resolution is not yet wired, so always include lat/lon for a reliable camera move. " +
|
||||
"Limitations: latitude [-90, 90], longitude [-180, 180]; entityId alone will not move the camera until resolution is wired. " +
|
||||
"Parameters: entityId (optional, informational), lat (recommended), lon (recommended), sessionId (optional). " +
|
||||
"Example: focus_entity({entityId:\"ship-123\",lat:35.68,lon:139.69})",
|
||||
inputSchema: {
|
||||
entityId: z.string().optional().describe("Entity id (informational; coordinate resolution not yet supported -- also provide lat/lon)"),
|
||||
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;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "focusEntity",
|
||||
...(args.entityId !== undefined && { entityId: args.entityId }),
|
||||
...(args.lat !== undefined && { lat: args.lat }),
|
||||
...(args.lon !== undefined && { lon: args.lon }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
return textResult(`Focus entity command enqueued (entityId=${args.entityId ?? "none"}, lat=${args.lat ?? "none"}, lon=${args.lon ?? "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:
|
||||
"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. " +
|
||||
"Limitations: layerId must match an installed plugin id; unknown ids are silently ignored by the browser. " +
|
||||
"Parameters: layerId (required), enabled (true/false, optional — omit to toggle current state), sessionId (optional). " +
|
||||
"Example: toggle_layer({layerId:\"ais\",enabled:true})",
|
||||
inputSchema: {
|
||||
layerId: z.string().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;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "toggleLayer",
|
||||
layerId: args.layerId,
|
||||
...(args.enabled !== undefined && { enabled: args.enabled }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
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:
|
||||
"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,333 +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);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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,243 +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 { 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";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// JSON-RPC 2.0 error response helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns 403 + JSON-RPC 2.0 body for the demo edition gate (MCP-04).
|
||||
* Runs BEFORE auth so the demo-admin FK write path is never reached.
|
||||
*/
|
||||
function demoBlockedResponse(): Response {
|
||||
return Response.json(
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "MCP is not available in demo mode" },
|
||||
id: null,
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns 401 + JSON-RPC 2.0 body for missing / invalid Bearer token (MCP-03).
|
||||
* Content-Type is application/json (not plain text — Pitfall 3).
|
||||
*/
|
||||
function unauthorizedResponse(): Response {
|
||||
return Response.json(
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32600, message: "Unauthorized" },
|
||||
id: null,
|
||||
},
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 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)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function GET(request: Request): Promise<Response> {
|
||||
return handleMcpRequest(request);
|
||||
}
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
return handleMcpRequest(request);
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request): Promise<Response> {
|
||||
return handleMcpRequest(request);
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
/**
|
||||
* Transport runtime spike — Phase 17, Wave 0 (17-01, Task 3)
|
||||
*
|
||||
* PURPOSE: De-risk D-17-02 BEFORE Wave 1 implementation. Proves that the raw
|
||||
* @modelcontextprotocol/sdk web-standard Streamable HTTP transport can be
|
||||
* imported, instantiated statelessly, and connected to a McpServer within the
|
||||
* Vitest runtime (which runs under the same Web Standard environment a
|
||||
* Next.js 16 App Router route handler uses: global Request, Response, Headers,
|
||||
* ReadableStream are all available).
|
||||
*
|
||||
* PASS/SKIP semantics (intentionally different from route.test.ts RED baseline):
|
||||
* - SDK NOT installed (Wave 0): test SKIPS cleanly. Suite does not hard-fail.
|
||||
* - SDK IS installed (Wave 1+): test MUST PASS green.
|
||||
*
|
||||
* BLOCKER ESCALATION RULE:
|
||||
* If the SDK IS installed and ANY assertion in this file throws at runtime
|
||||
* (import fails, constructor throws, handleRequest is missing, connect
|
||||
* rejects), the executor MUST STOP and flag a BLOCKER in the 17-02 SUMMARY
|
||||
* rather than pulling the Phase 19 custom server.ts work forward. Do NOT
|
||||
* silently swallow errors and mark the test pending.
|
||||
*
|
||||
* DO NOT install @modelcontextprotocol/sdk in this wave. That happens in 17-02.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Runtime guard: detect whether the SDK is installed before importing.
|
||||
//
|
||||
// The /* @vite-ignore */ comment suppresses Vite's static import-analysis
|
||||
// transform error for an unresolved specifier — the import is evaluated at
|
||||
// runtime only, so it throws naturally when the package is absent rather than
|
||||
// crashing the transform step.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const SDK_HTTP_SPECIFIER = "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
||||
const SDK_MCP_SPECIFIER = "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
|
||||
async function sdkAvailable(): Promise<boolean> {
|
||||
try {
|
||||
// @vite-ignore
|
||||
await import(/* @vite-ignore */ SDK_HTTP_SPECIFIER);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Spike suite
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("Transport spike: @modelcontextprotocol/sdk web-standard transport", () => {
|
||||
it(
|
||||
"WebStandardStreamableHTTPServerTransport and McpServer import, instantiate, and connect (or skip if SDK not installed)",
|
||||
async () => {
|
||||
const available = await sdkAvailable();
|
||||
|
||||
if (!available) {
|
||||
// SDK not yet installed (Wave 0 state) — skip cleanly.
|
||||
// Wave 1 (17-02) installs the package; this test will go green then.
|
||||
console.error(
|
||||
"[17-01 spike] @modelcontextprotocol/sdk not installed yet — install in 17-02"
|
||||
);
|
||||
// Return early — test body is a no-op at this wave; no assertions fire.
|
||||
return;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// From here onward: SDK IS installed. All assertions are mandatory.
|
||||
// Any failure -> BLOCKER in 17-02 SUMMARY.
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
const { WebStandardStreamableHTTPServerTransport } =
|
||||
// @vite-ignore
|
||||
await import(/* @vite-ignore */ SDK_HTTP_SPECIFIER) as {
|
||||
WebStandardStreamableHTTPServerTransport: new (opts: {
|
||||
sessionIdGenerator: undefined;
|
||||
}) => {
|
||||
handleRequest: (req: Request) => Promise<Response>;
|
||||
start: () => Promise<void>;
|
||||
};
|
||||
};
|
||||
|
||||
const { McpServer } =
|
||||
// @vite-ignore
|
||||
await import(/* @vite-ignore */ SDK_MCP_SPECIFIER) as {
|
||||
McpServer: new (info: { name: string; version: string }) => {
|
||||
connect: (transport: unknown) => Promise<void>;
|
||||
};
|
||||
};
|
||||
|
||||
// 1. Both exports must be constructor functions
|
||||
expect(typeof WebStandardStreamableHTTPServerTransport).toBe("function");
|
||||
expect(typeof McpServer).toBe("function");
|
||||
|
||||
// 2. Construct McpServer — empty capabilities (Phase 17 registers no tools/resources)
|
||||
const mcpServer = new McpServer({
|
||||
name: "worldwideview",
|
||||
version: "test",
|
||||
});
|
||||
expect(mcpServer).toBeTruthy();
|
||||
|
||||
// 3. Construct transport in STATELESS mode (D-17-04: sessionIdGenerator: undefined)
|
||||
const transport = new WebStandardStreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined,
|
||||
});
|
||||
expect(transport).toBeTruthy();
|
||||
|
||||
// 4. Transport must expose handleRequest (Web Standard Request -> Promise<Response>)
|
||||
expect(typeof transport.handleRequest).toBe("function");
|
||||
|
||||
// 5. Transport must expose start (Transport interface contract)
|
||||
expect(typeof transport.start).toBe("function");
|
||||
|
||||
// 6. mcpServer.connect(transport) must resolve without throwing.
|
||||
// This is the critical proof: the SDK does not require a custom server.ts
|
||||
// to wire McpServer + WebStandardStreamableHTTPServerTransport.
|
||||
await expect(mcpServer.connect(transport)).resolves.not.toThrow();
|
||||
}
|
||||
);
|
||||
});
|
||||
@@ -23,15 +23,9 @@ async function tryMirror(urlStr: string, query: string, timeoutMs: number) {
|
||||
},
|
||||
timeout: timeoutMs,
|
||||
}, (res) => {
|
||||
// Collect raw Buffer chunks and decode the full body as UTF-8 once.
|
||||
// Concatenating Buffers into a string per-chunk (`data += chunk`) decodes
|
||||
// each chunk independently, which corrupts any multi-byte UTF-8 character
|
||||
// (e.g. Cyrillic names) that straddles a chunk boundary — common on large
|
||||
// Overpass responses. Buffering first keeps multi-byte sequences intact.
|
||||
const chunks: Buffer[] = [];
|
||||
res.on("data", (chunk: Buffer) => chunks.push(chunk));
|
||||
let data = "";
|
||||
res.on("data", (chunk) => data += chunk);
|
||||
res.on("end", () => {
|
||||
const data = Buffer.concat(chunks).toString("utf8");
|
||||
resolve({
|
||||
ok: res.statusCode && res.statusCode >= 200 && res.statusCode < 300,
|
||||
status: res.statusCode || 500,
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const revalidate = 86400; // Cache for 24 hours
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const response = await fetch("https://www.submarinecablemap.com/api/v3/cable/cable-geo.json", {
|
||||
headers: {
|
||||
"User-Agent": "WorldWideView/1.0",
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: `Failed to fetch from target URL (Status: ${response.status})` },
|
||||
{ status: response.status },
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return NextResponse.json(data);
|
||||
} catch (error: any) {
|
||||
console.error("[UnderseaCablesProxy] Error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to proxy request" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach,
|
||||
} from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { GET } from "./route";
|
||||
|
||||
vi.mock("@/lib/auth", () => ({
|
||||
auth: vi.fn().mockResolvedValue(null),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/data-query/service", () => ({
|
||||
getEntitiesInRegion: vi.fn(),
|
||||
}));
|
||||
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { getEntitiesInRegion } from "@/lib/data-query/service";
|
||||
|
||||
function makeRequest(params: Record<string, string> = {}): NextRequest {
|
||||
const url = new URL("http://localhost/api/v1/entities/region");
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
url.searchParams.set(key, value);
|
||||
}
|
||||
return new NextRequest(url.toString());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API-01 — GET /api/v1/entities/region
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/v1/entities/region", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
vi.mocked(getEntitiesInRegion).mockResolvedValue({ entities: [] });
|
||||
});
|
||||
|
||||
it("returns 401 when no API key", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue(null);
|
||||
const req = makeRequest({ north: "52", south: "50", east: "1", west: "-1" });
|
||||
const res = await GET(req);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns 400 when bounding box params are missing/NaN (?north=abc)", async () => {
|
||||
const req = makeRequest({ north: "abc", south: "0", east: "0", west: "0" });
|
||||
const res = await GET(req);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 400 when only partial bounds provided (missing west)", async () => {
|
||||
const req = makeRequest({ north: "52", south: "50", east: "1" });
|
||||
const res = await GET(req);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 200 with entities, count, and bounds when valid", async () => {
|
||||
const entity = {
|
||||
id: "e1",
|
||||
pluginId: "test-plugin",
|
||||
latitude: 51.5,
|
||||
longitude: -0.1,
|
||||
name: "London",
|
||||
};
|
||||
vi.mocked(getEntitiesInRegion).mockResolvedValue({ entities: [entity] });
|
||||
const req = makeRequest({ north: "52", south: "50", east: "1", west: "-1" });
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
expect(res.status).toBe(200);
|
||||
expect(body).toHaveProperty("entities");
|
||||
expect(body).toHaveProperty("count");
|
||||
expect(body).toHaveProperty("bounds");
|
||||
expect(body.bounds).toEqual({ north: 52, south: 50, east: 1, west: -1 });
|
||||
});
|
||||
|
||||
it("passes pluginId to getEntitiesInRegion when provided", async () => {
|
||||
const req = makeRequest({ north: "52", south: "50", east: "1", west: "-1", pluginId: "my-plugin" });
|
||||
await GET(req);
|
||||
expect(vi.mocked(getEntitiesInRegion)).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ pluginId: "my-plugin" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,83 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { getEntitiesInRegion } from "@/lib/data-query/service";
|
||||
import { resolveEdition } from "@/core/edition";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const currentEdition = resolveEdition(process.env.NEXT_PUBLIC_WWV_EDITION);
|
||||
if (currentEdition === "demo") {
|
||||
return NextResponse.json({ error: "Demo mode" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Dual-auth: NextAuth session cookie 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 });
|
||||
}
|
||||
|
||||
// Entity data is global/public (plugin-sourced, shared across all users), so userId
|
||||
// gates access (authn) but is intentionally not a query filter -- there is no per-user
|
||||
// entity ownership to scope by.
|
||||
|
||||
const { searchParams } = request.nextUrl;
|
||||
const north = parseFloat(searchParams.get("north") ?? "");
|
||||
const south = parseFloat(searchParams.get("south") ?? "");
|
||||
const east = parseFloat(searchParams.get("east") ?? "");
|
||||
const west = parseFloat(searchParams.get("west") ?? "");
|
||||
|
||||
if (isNaN(north) || isNaN(south) || isNaN(east) || isNaN(west)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Missing or invalid bounding box parameters (north, south, east, west)" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
if (north < -90 || north > 90 || south < -90 || south > 90) {
|
||||
return NextResponse.json(
|
||||
{ error: "north and south must be within [-90, 90]" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
if (east < -180 || east > 180 || west < -180 || west > 180) {
|
||||
return NextResponse.json(
|
||||
{ error: "east and west must be within [-180, 180]" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const pluginId = searchParams.get("pluginId") ?? undefined;
|
||||
const rawLimit = searchParams.get("limit");
|
||||
const parsedLimit = rawLimit !== null ? parseInt(rawLimit, 10) : NaN;
|
||||
const limit = Math.min(Number.isNaN(parsedLimit) ? 100 : parsedLimit, 1000);
|
||||
|
||||
try {
|
||||
const result = await getEntitiesInRegion({ north, south, east, west, pluginId, limit });
|
||||
return NextResponse.json({
|
||||
entities: result.entities,
|
||||
count: result.entities.length,
|
||||
bounds: { north, south, east, west },
|
||||
...(result.emptyReason !== undefined && { emptyReason: result.emptyReason }),
|
||||
});
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Internal server error";
|
||||
if (message.includes("Invalid bounding box")) {
|
||||
return NextResponse.json({ error: message }, { status: 400 });
|
||||
}
|
||||
console.error("[entities/region] GET error:", err);
|
||||
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach,
|
||||
} from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { GET } from "./route";
|
||||
|
||||
vi.mock("@/lib/auth", () => ({
|
||||
auth: vi.fn().mockResolvedValue(null),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/data-query/service", () => ({
|
||||
searchEntities: vi.fn(),
|
||||
}));
|
||||
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { searchEntities } from "@/lib/data-query/service";
|
||||
|
||||
function makeRequest(params: Record<string, string> = {}): NextRequest {
|
||||
const url = new URL("http://localhost/api/v1/entities/search");
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
url.searchParams.set(key, value);
|
||||
}
|
||||
return new NextRequest(url.toString());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API-01 — GET /api/v1/entities/search
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/v1/entities/search", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
vi.mocked(searchEntities).mockResolvedValue({ entities: [] });
|
||||
});
|
||||
|
||||
it("returns 401 when no API key", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue(null);
|
||||
const req = makeRequest({ q: "test" });
|
||||
const res = await GET(req);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns 400 when q param is missing", async () => {
|
||||
const req = makeRequest();
|
||||
const res = await GET(req);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 200 with entities and count when valid", async () => {
|
||||
const entity = {
|
||||
id: "e1",
|
||||
pluginId: "test-plugin",
|
||||
latitude: 51.5,
|
||||
longitude: -0.1,
|
||||
name: "London",
|
||||
};
|
||||
vi.mocked(searchEntities).mockResolvedValue({ entities: [entity] });
|
||||
const req = makeRequest({ q: "test" });
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
expect(res.status).toBe(200);
|
||||
expect(body).toHaveProperty("entities");
|
||||
expect(body).toHaveProperty("count", 1);
|
||||
expect(body).toHaveProperty("query", "test");
|
||||
});
|
||||
|
||||
it("passes pluginId to searchEntities when provided", async () => {
|
||||
const req = makeRequest({ q: "thing", pluginId: "my-plugin" });
|
||||
await GET(req);
|
||||
expect(vi.mocked(searchEntities)).toHaveBeenCalledWith(
|
||||
"thing",
|
||||
"my-plugin",
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
|
||||
it("passes limit capped at 100 when ?limit=999 is given", async () => {
|
||||
const req = makeRequest({ q: "thing", limit: "999" });
|
||||
await GET(req);
|
||||
const callArgs = vi.mocked(searchEntities).mock.calls[0];
|
||||
expect(callArgs[2]).toBeLessThanOrEqual(100);
|
||||
});
|
||||
});
|
||||
@@ -1,59 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { searchEntities } from "@/lib/data-query/service";
|
||||
import { resolveEdition } from "@/core/edition";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const currentEdition = resolveEdition(process.env.NEXT_PUBLIC_WWV_EDITION);
|
||||
if (currentEdition === "demo") {
|
||||
return NextResponse.json({ error: "Demo mode" }, { status: 403 });
|
||||
}
|
||||
|
||||
// Dual-auth: NextAuth session cookie 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 });
|
||||
}
|
||||
|
||||
// Entity data is global/public (plugin-sourced, shared across all users), so userId
|
||||
// gates access (authn) but is intentionally not a query filter -- there is no per-user
|
||||
// entity ownership to scope by.
|
||||
|
||||
const { searchParams } = request.nextUrl;
|
||||
const q = searchParams.get("q");
|
||||
if (!q || q.trim() === "") {
|
||||
return NextResponse.json({ error: "Missing query parameter: q" }, { status: 400 });
|
||||
}
|
||||
|
||||
const pluginId = searchParams.get("pluginId") ?? undefined;
|
||||
const rawLimit = searchParams.get("limit");
|
||||
const parsed = rawLimit !== null ? parseInt(rawLimit, 10) : NaN;
|
||||
const limit = Math.min(Number.isNaN(parsed) ? 20 : parsed, 100);
|
||||
|
||||
try {
|
||||
const result = await searchEntities(q, pluginId, limit);
|
||||
return NextResponse.json({
|
||||
entities: result.entities,
|
||||
count: result.entities.length,
|
||||
query: q,
|
||||
...(pluginId !== undefined && { pluginId }),
|
||||
...(result.emptyReason !== undefined && { emptyReason: result.emptyReason }),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[entities/search] GET error:", err);
|
||||
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -38,9 +38,8 @@ export function PluginIcon({ icon, size = 18, color }: PluginIconProps) {
|
||||
if (typeof icon === "string") {
|
||||
const Resolved = icons[icon as keyof typeof icons] as LucideIcon | undefined;
|
||||
if (Resolved) return <Resolved size={size} color={color} />;
|
||||
// Emoji: render as text. Unresolved ASCII icon name: render fallback so stale names don't leak as text.
|
||||
if (/[^\x00-\x7F]/.test(icon)) return <span>{icon}</span>;
|
||||
return <FallbackIcon size={size} />;
|
||||
// Treat as emoji or text fallback
|
||||
return <span>{icon}</span>;
|
||||
}
|
||||
|
||||
const IconComponent = icon;
|
||||
|
||||
@@ -249,7 +249,7 @@ export function ApiKeysTab() {
|
||||
<div style={{ marginBottom: "var(--space-lg)" }}>
|
||||
<div style={sectionHeaderStyle}>
|
||||
<Key size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
|
||||
Service Keys
|
||||
Your API Keys
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: "var(--text-muted)", marginBottom: "var(--space-md)" }}>
|
||||
Optional — if set, your key is used instead of the shared default.
|
||||
|
||||
@@ -36,7 +36,6 @@ import { FeedbackDialog } from "@/components/common/FeedbackDialog";
|
||||
import { isDemo } from "@/core/edition";
|
||||
|
||||
import { injectHostGlobals } from "@/core/plugins/hostGlobals";
|
||||
import { getDisabledPluginIds } from "@/core/plugins/pluginPreferences";
|
||||
import { initLogCatcher } from "@/lib/logCatcher";
|
||||
import { MobileCameraStats } from "./MobileCameraStats";
|
||||
import { MobileHudBar } from "./MobileHudBar";
|
||||
@@ -89,7 +88,17 @@ export function AppShell() {
|
||||
await injectHostGlobals();
|
||||
setHostReady(true);
|
||||
|
||||
const disabledIds = getDisabledPluginIds();
|
||||
// Fetch disabled built-in plugins before registration
|
||||
let disabledIds = new Set<string>();
|
||||
try {
|
||||
const res = await fetch("/api/marketplace/disabled-builtins");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
disabledIds = new Set<string>(data.disabledIds ?? []);
|
||||
}
|
||||
} catch {
|
||||
// Non-critical — load all built-ins if endpoint fails
|
||||
}
|
||||
|
||||
// Setup demo defaults
|
||||
const demoDefaultPlugins = new Set<string>();
|
||||
|
||||
@@ -15,6 +15,7 @@ export function BottomPanelManager() {
|
||||
|
||||
const [mountedPanel, setMountedPanel] = useState<string | null>(activeBottomPanel);
|
||||
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const resizeRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Get all registered plugins that provide a bottom panel component
|
||||
@@ -38,27 +39,41 @@ export function BottomPanelManager() {
|
||||
}
|
||||
}, [activeBottomPanel]);
|
||||
|
||||
// Pointer-capture drag handlers — attached directly to the resize handle element.
|
||||
// Using setPointerCapture ensures pointermove/pointerup are delivered to the
|
||||
// element even when the pointer leaves it, which is required for webkit
|
||||
// (without capture, webkit drops synthetic pointermove events from Playwright
|
||||
// and from fast real-user drags that leave the element bounds).
|
||||
const handleResizePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
// Handle mouse drag for resizing the panel
|
||||
useEffect(() => {
|
||||
if (!isDragging) {
|
||||
document.body.classList.remove("is-dragging-bottom-panel");
|
||||
return;
|
||||
}
|
||||
|
||||
document.body.classList.add("is-dragging-bottom-panel");
|
||||
};
|
||||
|
||||
const handleResizePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!e.currentTarget.hasPointerCapture(e.pointerId)) return;
|
||||
const newHeight = window.innerHeight - e.clientY;
|
||||
const clampedHeight = Math.max(120, Math.min(newHeight, window.innerHeight - 100));
|
||||
setBottomPanelHeight(clampedHeight);
|
||||
};
|
||||
const handleMove = (clientY: number) => {
|
||||
// Calculate new height based on distance from bottom of window
|
||||
const newHeight = window.innerHeight - clientY;
|
||||
// Clamp between min 120px and max window height - 100px
|
||||
const clampedHeight = Math.max(120, Math.min(newHeight, window.innerHeight - 100));
|
||||
setBottomPanelHeight(clampedHeight);
|
||||
};
|
||||
|
||||
const handleResizePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
e.currentTarget.releasePointerCapture(e.pointerId);
|
||||
document.body.classList.remove("is-dragging-bottom-panel");
|
||||
};
|
||||
const handleMouseMove = (e: MouseEvent) => handleMove(e.clientY);
|
||||
const handlePointerMove = (e: PointerEvent) => handleMove(e.clientY);
|
||||
|
||||
const handleEnd = () => setIsDragging(false);
|
||||
|
||||
window.addEventListener("mousemove", handleMouseMove);
|
||||
window.addEventListener("mouseup", handleEnd);
|
||||
window.addEventListener("pointermove", handlePointerMove);
|
||||
window.addEventListener("pointerup", handleEnd);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("mousemove", handleMouseMove);
|
||||
window.removeEventListener("mouseup", handleEnd);
|
||||
window.removeEventListener("pointermove", handlePointerMove);
|
||||
window.removeEventListener("pointerup", handleEnd);
|
||||
document.body.classList.remove("is-dragging-bottom-panel");
|
||||
};
|
||||
}, [isDragging, setBottomPanelHeight]);
|
||||
|
||||
// Dynamically push sidebars up based on bottom panel height
|
||||
useEffect(() => {
|
||||
@@ -167,14 +182,12 @@ export function BottomPanelManager() {
|
||||
>
|
||||
{mountedPanel && (
|
||||
<>
|
||||
<div
|
||||
className="bottom-panel-resize-handle"
|
||||
<div
|
||||
className="bottom-panel-resize-handle"
|
||||
data-testid="bottom-panel-resize-handle"
|
||||
ref={resizeRef}
|
||||
onPointerDown={handleResizePointerDown}
|
||||
onPointerMove={handleResizePointerMove}
|
||||
onPointerUp={handleResizePointerUp}
|
||||
onPointerCancel={handleResizePointerUp}
|
||||
onMouseDown={() => setIsDragging(true)}
|
||||
onPointerDown={() => setIsDragging(true)}
|
||||
>
|
||||
<div className="resize-grip" />
|
||||
</div>
|
||||
|
||||
@@ -1,310 +0,0 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file ConnectAgentHelper.tsx
|
||||
* @description "Connect your agent" helper rendered inside the "API & MCP Access"
|
||||
* section. Shows the per-edition /api/mcp URL, a copy-paste mcpServers JSON block
|
||||
* (Bearer token in Authorization HEADER -- never in the URL), a generic Manual
|
||||
* block, and a copy-paste agent-capabilities prompt. The Claude Code CLI snippet
|
||||
* is deferred ("coming soon").
|
||||
*
|
||||
* Security invariant (CONNECT-01 / T-17-04): the token appears ONLY in the
|
||||
* Authorization header value inside the JSON/Manual blocks. It is NEVER placed
|
||||
* in the mcpUrl string or any query parameter.
|
||||
* @module src/components/layout
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { Copy, Check, Terminal } from "lucide-react";
|
||||
import { isCloud } from "@/core/edition";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
const PLACEHOLDER_TOKEN = "wwv_<prefix>.<secret>";
|
||||
|
||||
/**
|
||||
* Resolve the /api/mcp base URL per edition (D-17-10).
|
||||
* - local -> http://localhost:3000/api/mcp (no port-hardcode: Next.js default)
|
||||
* - cloud -> NEXT_PUBLIC_MCP_API_URL ?? https://api.worldmonitor.app/api/mcp
|
||||
* - demo -> component is never rendered (gated by the !isDemo wrapper in Header)
|
||||
*
|
||||
* We derive the local URL from the browser origin at runtime so the component
|
||||
* works even if the dev server is on a non-3000 port.
|
||||
*/
|
||||
function resolveMcpUrl(): string {
|
||||
if (isCloud) {
|
||||
return (
|
||||
process.env.NEXT_PUBLIC_MCP_API_URL ??
|
||||
"https://api.worldmonitor.app/api/mcp"
|
||||
);
|
||||
}
|
||||
// local: use the current page origin so the port is derived, not hardcoded.
|
||||
if (typeof window !== "undefined") {
|
||||
return `${window.location.origin}/api/mcp`;
|
||||
}
|
||||
// SSR fallback (should not be reached for a "use client" component).
|
||||
return "http://localhost:3000/api/mcp";
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared style tokens (mirror PersonalApiKeysSection to keep visual parity)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
background: "var(--bg-tertiary)",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
color: "var(--text-primary)",
|
||||
padding: "var(--space-xs) var(--space-sm)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
fontSize: 12,
|
||||
width: "100%",
|
||||
outline: "none",
|
||||
fontFamily: "var(--font-mono)",
|
||||
};
|
||||
|
||||
const buttonStyle: React.CSSProperties = {
|
||||
background: "none",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
color: "var(--text-primary)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
padding: "var(--space-xs) var(--space-sm)",
|
||||
fontSize: 12,
|
||||
cursor: "pointer",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "var(--space-xs)",
|
||||
};
|
||||
|
||||
const mutedMicro: React.CSSProperties = { fontSize: 11, color: "var(--text-muted)" };
|
||||
|
||||
const subHeaderStyle: React.CSSProperties = {
|
||||
fontSize: 11,
|
||||
fontWeight: 600,
|
||||
color: "var(--text-secondary)",
|
||||
textTransform: "uppercase",
|
||||
letterSpacing: "0.08em",
|
||||
marginBottom: "var(--space-xs)",
|
||||
marginTop: "var(--space-md)",
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CopyField sub-component
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface CopyFieldProps {
|
||||
value: string;
|
||||
label: string;
|
||||
multiline?: boolean;
|
||||
}
|
||||
|
||||
function CopyField({ value, label, multiline = false }: CopyFieldProps) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
async function handleCopy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), COPIED_RESET_MS);
|
||||
} catch {
|
||||
// Clipboard access denied -- user must copy manually.
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ marginBottom: "var(--space-sm)" }}>
|
||||
<div style={mutedMicro}>{label}</div>
|
||||
<div style={{ display: "flex", gap: "var(--space-xs)", marginTop: "var(--space-xs)" }}>
|
||||
{multiline ? (
|
||||
<textarea
|
||||
readOnly
|
||||
value={value}
|
||||
rows={value.split("\n").length + 1}
|
||||
style={{
|
||||
...inputStyle,
|
||||
resize: "vertical",
|
||||
minHeight: 80,
|
||||
}}
|
||||
autoComplete="off"
|
||||
data-lpignore="true"
|
||||
data-form-type="other"
|
||||
spellCheck={false}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
type="text"
|
||||
readOnly
|
||||
value={value}
|
||||
style={inputStyle}
|
||||
autoComplete="off"
|
||||
data-lpignore="true"
|
||||
data-form-type="other"
|
||||
spellCheck={false}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCopy}
|
||||
style={{
|
||||
...buttonStyle,
|
||||
color: copied ? "#22c55e" : "var(--text-primary)",
|
||||
flexShrink: 0,
|
||||
alignSelf: "flex-start",
|
||||
}}
|
||||
title={copied ? "Copied!" : `Copy ${label}`}
|
||||
>
|
||||
{copied ? <Check size={12} /> : <Copy size={12} />}
|
||||
{copied ? "Copied!" : "Copy"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Agent-capabilities prompt (CONNECT-03)
|
||||
// Lists the v1.3 Location Intelligence tools an agent can call. Keep in sync
|
||||
// with the registrars in src/app/api/mcp/*Tools.ts. Plugin filter authoring is
|
||||
// documented in docs/plugin-filter-guide.md.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const AGENT_PROMPT = `You have access to the WorldWideView (WWV) geospatial intelligence engine via MCP.
|
||||
WWV visualizes real-time global data on an interactive 3D CesiumJS globe, including aviation,
|
||||
incidents, weather, and custom data plugins.
|
||||
|
||||
This MCP connection is live and authenticated. You can call these tools:
|
||||
|
||||
Data query:
|
||||
- search_entities: search entities by name across active plugins; supports optional inline filters.
|
||||
- get_entities_in_region: find entities inside a lat/lng bounding box.
|
||||
- get_entity_details: get full details for one entity by pluginId + entityId.
|
||||
- get_plugin_data: get the current snapshot of all entities for a plugin.
|
||||
|
||||
Location (geocoding + camera):
|
||||
- geocode_location: resolve a place name or address to coordinates and a bounding box.
|
||||
- fly_to: fly the live globe camera to a coordinate or bounding box.
|
||||
|
||||
Favorites:
|
||||
- save_favorite: bookmark an entity so the user can return to it later.
|
||||
- list_favorites: list the user's bookmarks, each with a live/stale status.
|
||||
- remove_favorite: delete a bookmarked entity.
|
||||
|
||||
Live filtering:
|
||||
- get_plugin_filters: list the filterable fields a plugin declares.
|
||||
- set_filter: apply filters to a plugin's layer on the live globe.
|
||||
- clear_filter: clear one plugin's filters, or all filters.
|
||||
|
||||
When the user asks about global data, geospatial queries, or globe visualisation, use these tools
|
||||
to find places, move the camera, search and filter live entities, and manage their bookmarks.`;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main component
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ConnectAgentHelperProps {
|
||||
token?: string | null;
|
||||
}
|
||||
|
||||
export function ConnectAgentHelper({ token }: ConnectAgentHelperProps) {
|
||||
const mcpUrl = resolveMcpUrl();
|
||||
// SECURITY: displayToken is ONLY placed in the Authorization header value.
|
||||
// It is never concatenated into mcpUrl or any query string.
|
||||
const displayToken = token ?? PLACEHOLDER_TOKEN;
|
||||
|
||||
// mcpServers JSON for Claude Desktop / Cursor / VS Code (D-17-09, raw-SDK Streamable HTTP form).
|
||||
// Uses `headers.Authorization` -- NOT `type: "sse"` + `env.AUTHORIZATION` (superseded research form).
|
||||
const mcpServersJson = JSON.stringify(
|
||||
{
|
||||
mcpServers: {
|
||||
worldwideview: {
|
||||
url: mcpUrl,
|
||||
headers: {
|
||||
Authorization: `Bearer ${displayToken}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
|
||||
const authHeaderValue = `Bearer ${displayToken}`;
|
||||
|
||||
return (
|
||||
<div style={{ marginTop: "var(--space-lg)" }}>
|
||||
<div style={{
|
||||
borderTop: "1px solid var(--border-subtle)",
|
||||
paddingTop: "var(--space-md)",
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 13, fontWeight: 500, color: "var(--text-primary)", marginBottom: "var(--space-xs)" }}>
|
||||
Connect your agent
|
||||
</div>
|
||||
<div style={mutedMicro}>
|
||||
Use the URL and token below to connect Claude Desktop, Cursor, or VS Code to this globe.
|
||||
</div>
|
||||
|
||||
{/* Section: mcpServers JSON (CONNECT-02) */}
|
||||
<div style={subHeaderStyle}>Claude Desktop / Cursor / VS Code</div>
|
||||
<div style={{ ...mutedMicro, marginBottom: "var(--space-sm)" }}>
|
||||
Paste into your client's MCP config file. The token sits in the Authorization header,
|
||||
never in the URL.
|
||||
</div>
|
||||
<CopyField
|
||||
label="mcpServers config block"
|
||||
value={mcpServersJson}
|
||||
multiline
|
||||
/>
|
||||
|
||||
{/* Section: Manual block */}
|
||||
<div style={subHeaderStyle}>Manual / Custom Client</div>
|
||||
<CopyField label="Endpoint URL" value={mcpUrl} />
|
||||
<CopyField label="Authorization header value" value={authHeaderValue} />
|
||||
|
||||
{/* Section: Prompt for your agent (CONNECT-03) */}
|
||||
<div style={subHeaderStyle}>Prompt for your agent</div>
|
||||
<div style={{ ...mutedMicro, marginBottom: "var(--space-sm)" }}>
|
||||
Paste this into your agent's system prompt or first message to describe WWV.
|
||||
</div>
|
||||
<CopyField label="Capabilities prompt" value={AGENT_PROMPT} multiline />
|
||||
<div style={{ ...mutedMicro, marginTop: "var(--space-xs)" }}>
|
||||
Plugin authors: see docs/plugin-filter-guide.md to declare filterable fields for set_filter / get_plugin_filters.
|
||||
</div>
|
||||
|
||||
{/* Section: Claude Code CLI -- deferred (D-17-08) */}
|
||||
<div style={subHeaderStyle}>Claude Code CLI</div>
|
||||
<div style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "var(--space-xs)",
|
||||
background: "var(--bg-tertiary)",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
padding: "var(--space-sm) var(--space-md)",
|
||||
}}
|
||||
>
|
||||
<Terminal size={12} style={{ color: "var(--text-muted)", flexShrink: 0 }} />
|
||||
<span style={mutedMicro}>
|
||||
Claude Code CLI support is coming soon. Use the mcpServers JSON block above in the
|
||||
meantime.
|
||||
</span>
|
||||
<span style={{
|
||||
marginLeft: "auto",
|
||||
fontSize: 10,
|
||||
color: "var(--text-muted)",
|
||||
background: "var(--bg-secondary)",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
padding: "1px 6px",
|
||||
flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
Coming soon
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import Image from "next/image";
|
||||
import { useIsMobile } from "@/core/hooks/useIsMobile";
|
||||
import { SearchBar } from "./SearchBar";
|
||||
import { ApiKeysTab } from "./ApiKeysTab";
|
||||
import { PersonalApiKeysSection } from "./PersonalApiKeysSection";
|
||||
import "./timeSelect.css";
|
||||
|
||||
const REGIONS = [
|
||||
@@ -434,7 +433,7 @@ export function Header() {
|
||||
marginBottom: "16px",
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: 0 }}>Keys & Access</h2>
|
||||
<h2 style={{ margin: 0 }}>API Keys</h2>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
@@ -446,12 +445,6 @@ export function Header() {
|
||||
</div>
|
||||
|
||||
<ApiKeysTab />
|
||||
{!isDemo && (
|
||||
<>
|
||||
<hr style={{ border: "none", borderTop: "1px solid var(--border-subtle)", margin: "var(--space-lg) 0" }} />
|
||||
<PersonalApiKeysSection />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,354 +0,0 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* @file PersonalApiKeysSection.tsx
|
||||
* @description The "API & MCP Access" section of the "Keys & Access" modal.
|
||||
* Lists the signed-in user's personal bearer keys and supports generate
|
||||
* (one-time reveal), inline-confirm revoke, and a max-3 disabled state.
|
||||
* Consumes the session-authenticated /api/api-keys routes. Vanilla CSS-in-JS.
|
||||
* @module src/components/layout
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
KeyRound, Plus, Trash2, AlertTriangle, Loader,
|
||||
} from "lucide-react";
|
||||
import { sectionHeaderStyle } from "../panels/DataConfig/sharedStyles";
|
||||
import { ConnectAgentHelper } from "./ConnectAgentHelper";
|
||||
|
||||
type KeyRecord = {
|
||||
id: string;
|
||||
name: string;
|
||||
prefix: string;
|
||||
createdAt: string;
|
||||
lastUsedAt: string | null;
|
||||
};
|
||||
|
||||
const MAX_KEYS = 3;
|
||||
const COPIED_RESET_MS = 1500;
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
background: "var(--bg-tertiary)",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
color: "var(--text-primary)",
|
||||
padding: "var(--space-xs) var(--space-sm)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
fontSize: 12,
|
||||
width: "100%",
|
||||
outline: "none",
|
||||
};
|
||||
|
||||
const buttonStyle: React.CSSProperties = {
|
||||
background: "none",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
color: "var(--text-primary)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
padding: "var(--space-xs) var(--space-sm)",
|
||||
fontSize: 12,
|
||||
cursor: "pointer",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "var(--space-xs)",
|
||||
};
|
||||
|
||||
const mutedMicro: React.CSSProperties = { fontSize: 11, color: "var(--text-muted)" };
|
||||
const errorText: React.CSSProperties = { fontSize: 11, color: "#ef4444" };
|
||||
const iconBtn: React.CSSProperties = {
|
||||
background: "none", border: "none", cursor: "pointer",
|
||||
padding: "var(--space-xs)", display: "flex", alignItems: "center",
|
||||
};
|
||||
|
||||
function formatDate(iso: string): string {
|
||||
const d = new Date(iso);
|
||||
return Number.isNaN(d.getTime()) ? "unknown" : d.toLocaleDateString();
|
||||
}
|
||||
|
||||
function formatRelative(iso: string | null): string {
|
||||
if (!iso) return "Never used";
|
||||
const then = new Date(iso).getTime();
|
||||
if (Number.isNaN(then)) return "Never used";
|
||||
const days = Math.floor((Date.now() - then) / 86400000);
|
||||
if (days <= 0) return "Last used today";
|
||||
if (days === 1) return "Last used 1 day ago";
|
||||
return `Last used ${days} days ago`;
|
||||
}
|
||||
|
||||
function KeyRow({
|
||||
record, confirming, onAskRevoke, onCancelRevoke, onConfirmRevoke, isLast,
|
||||
}: {
|
||||
record: KeyRecord;
|
||||
confirming: boolean;
|
||||
onAskRevoke: () => void;
|
||||
onCancelRevoke: () => void;
|
||||
onConfirmRevoke: () => void;
|
||||
isLast: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: "var(--space-sm)",
|
||||
padding: "var(--space-sm) 0",
|
||||
borderBottom: isLast ? "none" : "1px solid var(--border-subtle)",
|
||||
}}
|
||||
>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<div style={{ fontSize: 14, color: "var(--text-primary)", fontWeight: 400 }}>{record.name}</div>
|
||||
<div style={mutedMicro}>
|
||||
{`Created ${formatDate(record.createdAt)}`}
|
||||
{" · "}
|
||||
{formatRelative(record.lastUsedAt)}
|
||||
</div>
|
||||
</div>
|
||||
{confirming ? (
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "var(--space-xs)" }}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onConfirmRevoke}
|
||||
style={{ ...iconBtn, color: "#ef4444", fontSize: 11, gap: "var(--space-xs)" }}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
Revoke?
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancelRevoke}
|
||||
style={{ ...iconBtn, color: "var(--text-muted)", fontSize: 11 }}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAskRevoke}
|
||||
aria-label="Revoke key"
|
||||
title="Revoke key"
|
||||
style={{ ...iconBtn, color: "var(--text-muted)" }}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PersonalApiKeysSection() {
|
||||
const [keys, setKeys] = useState<KeyRecord[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [generating, setGenerating] = useState(false);
|
||||
const [generateError, setGenerateError] = useState("");
|
||||
const [revealToken, setRevealToken] = useState<string | null>(null);
|
||||
const [revokeConfirm, setRevokeConfirm] = useState<string | null>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/api/api-keys")
|
||||
.then((r) => {
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return r.json();
|
||||
})
|
||||
.then((data) => setKeys(data.keys ?? []))
|
||||
.catch(() => setError("Could not load keys. Try closing and reopening this panel."))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const atLimit = keys.length >= MAX_KEYS;
|
||||
|
||||
async function handleGenerate() {
|
||||
if (generating || atLimit) return;
|
||||
setGenerating(true);
|
||||
setGenerateError("");
|
||||
try {
|
||||
const res = await fetch("/api/api-keys", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: name.trim() }),
|
||||
});
|
||||
if (res.status === 422) {
|
||||
setGenerateError("Maximum of 3 keys reached");
|
||||
return;
|
||||
}
|
||||
if (!res.ok) {
|
||||
setGenerateError("Failed to generate key. Please try again.");
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
const created: KeyRecord = {
|
||||
id: data.key.id,
|
||||
name: data.key.name,
|
||||
prefix: data.key.prefix ?? "",
|
||||
createdAt: data.key.createdAt,
|
||||
lastUsedAt: null,
|
||||
};
|
||||
setKeys((prev) => [created, ...prev]);
|
||||
setRevealToken(data.key.fullToken);
|
||||
setName("");
|
||||
setCopied(false);
|
||||
} catch {
|
||||
setGenerateError("Failed to generate key. Please try again.");
|
||||
} finally {
|
||||
setGenerating(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRevoke(id: string) {
|
||||
const previous = keys;
|
||||
setKeys((prev) => prev.filter((k) => k.id !== id));
|
||||
setRevokeConfirm(null);
|
||||
try {
|
||||
const res = await fetch(`/api/api-keys/${id}`, { method: "DELETE" });
|
||||
if (!res.ok) setKeys(previous);
|
||||
} catch {
|
||||
setKeys(previous);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCopy() {
|
||||
if (!revealToken) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(revealToken);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), COPIED_RESET_MS);
|
||||
} catch {
|
||||
setGenerateError("Could not copy to clipboard. Select and copy manually.");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ marginBottom: "var(--space-lg)" }}>
|
||||
<style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style>
|
||||
|
||||
<div style={sectionHeaderStyle}>
|
||||
<KeyRound size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
|
||||
API & MCP Access
|
||||
</div>
|
||||
<div style={{ ...mutedMicro, marginBottom: "var(--space-md)" }}>
|
||||
Personal bearer keys for authenticating API and MCP requests. Stored server-side.
|
||||
</div>
|
||||
|
||||
{loading && (
|
||||
<div style={{ display: "flex", justifyContent: "center", color: "var(--text-muted)", padding: "var(--space-md) 0" }}>
|
||||
<Loader size={14} style={{ animation: "spin 1s linear infinite" }} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && error && <div style={errorText}>{error}</div>}
|
||||
|
||||
{!loading && !error && keys.length === 0 && (
|
||||
<div style={{
|
||||
display: "flex", flexDirection: "column", alignItems: "center",
|
||||
gap: "var(--space-md)", padding: "var(--space-xl) 0",
|
||||
}}
|
||||
>
|
||||
<KeyRound size={24} style={{ color: "var(--text-muted)" }} />
|
||||
<div style={{ fontSize: 14, color: "var(--text-muted)", fontWeight: 400 }}>No API keys yet</div>
|
||||
<div style={mutedMicro}>Generate a key to authenticate API and MCP requests.</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && keys.length > 0 && (
|
||||
<div style={{ marginBottom: "var(--space-md)" }}>
|
||||
{keys.map((k, i) => (
|
||||
<KeyRow
|
||||
key={k.id}
|
||||
record={k}
|
||||
isLast={i === keys.length - 1}
|
||||
confirming={revokeConfirm === k.id}
|
||||
onAskRevoke={() => setRevokeConfirm(k.id)}
|
||||
onCancelRevoke={() => setRevokeConfirm(null)}
|
||||
onConfirmRevoke={() => handleRevoke(k.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && (
|
||||
<>
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
placeholder="Name this key (optional)"
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
style={{ ...inputStyle, fontFamily: "inherit", marginBottom: "var(--space-sm)" }}
|
||||
autoComplete="off"
|
||||
data-lpignore="true"
|
||||
data-form-type="other"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleGenerate}
|
||||
disabled={atLimit || generating}
|
||||
style={{
|
||||
...buttonStyle,
|
||||
opacity: atLimit || generating ? 0.4 : 1,
|
||||
cursor: atLimit || generating ? "not-allowed" : "pointer",
|
||||
}}
|
||||
>
|
||||
<Plus size={12} />
|
||||
Generate API Key
|
||||
</button>
|
||||
{atLimit && (
|
||||
<div style={{ fontSize: 10, color: "var(--text-muted)", marginTop: "var(--space-xs)" }}>
|
||||
Maximum of 3 keys reached
|
||||
</div>
|
||||
)}
|
||||
{generateError && (
|
||||
<div style={{ ...errorText, marginTop: "var(--space-xs)" }}>{generateError}</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{revealToken && (
|
||||
<div style={{ marginTop: "var(--space-md)" }}>
|
||||
<div style={{
|
||||
display: "flex", alignItems: "flex-start", gap: "var(--space-xs)",
|
||||
background: "rgba(245,158,11,0.1)", border: "1px solid rgba(245,158,11,0.3)",
|
||||
borderRadius: "var(--radius-sm)", padding: "var(--space-sm) var(--space-md)",
|
||||
marginBottom: "var(--space-sm)",
|
||||
}}
|
||||
>
|
||||
<AlertTriangle size={14} style={{ color: "var(--accent-amber)", flexShrink: 0, marginTop: 1 }} />
|
||||
<span style={{ fontSize: 11, color: "var(--accent-amber)", lineHeight: 1.5 }}>
|
||||
Copy this key now. You won't be able to see it again. Never commit it to source
|
||||
control or share it publicly.
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: "var(--space-xs)" }}>
|
||||
<input
|
||||
type="text"
|
||||
readOnly
|
||||
value={revealToken}
|
||||
style={{ ...inputStyle, fontFamily: "var(--font-mono)" }}
|
||||
autoComplete="off"
|
||||
data-lpignore="true"
|
||||
data-form-type="other"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCopy}
|
||||
style={{ ...buttonStyle, color: copied ? "#22c55e" : "var(--text-primary)" }}
|
||||
>
|
||||
{copied ? "Copied!" : "Copy"}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setRevealToken(null)}
|
||||
style={{ ...buttonStyle, width: "100%", justifyContent: "center", marginTop: "var(--space-sm)" }}
|
||||
>
|
||||
Done, I've saved it
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ConnectAgentHelper token={revealToken} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -74,19 +74,6 @@
|
||||
margin-top: 3px;
|
||||
}
|
||||
|
||||
/* ─── Local Icon ─────────────────────────────────── */
|
||||
.layer-item__local-icon-wrapper {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.layer-item__local-icon {
|
||||
color: var(--accent-cyan);
|
||||
flex-shrink: 0;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
/* ─── Unverified Icon ────────────────────────────── */
|
||||
.layer-item__unverified-icon-wrapper {
|
||||
position: relative;
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* @module src/components/panels
|
||||
*/
|
||||
|
||||
import { ShieldAlert, Wrench } from "lucide-react";
|
||||
import { ShieldAlert } from "lucide-react";
|
||||
import { PluginIcon } from "@/components/common/PluginIcon";
|
||||
import { Tooltip } from "@/components/ui/Tooltip";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
@@ -27,46 +27,29 @@ const CATEGORY_LABELS: Record<string, string> = {
|
||||
custom: "Custom",
|
||||
};
|
||||
|
||||
// ─── Source / Trust Helpers ─────────────────────────────────
|
||||
// ─── Trust Helpers ──────────────────────────────────────────
|
||||
|
||||
function isLocalPlugin(pluginId: string): boolean {
|
||||
type TrustTier = "built-in" | "verified" | "unverified";
|
||||
|
||||
function getTrust(pluginId: string): TrustTier {
|
||||
const manifest = pluginManager.getManifest(pluginId);
|
||||
if (!manifest) return true;
|
||||
const entry = manifest.entry ?? "";
|
||||
return entry.startsWith("/plugins-local/") || entry.startsWith("http://localhost") || entry.startsWith("http://127.0.0.1");
|
||||
return manifest?.trust ?? "unverified";
|
||||
}
|
||||
|
||||
function TrustIcon({ pluginId, pluginName }: { pluginId: string; pluginName: string }) {
|
||||
if (isLocalPlugin(pluginId)) {
|
||||
return (
|
||||
<Tooltip content={`Local plugin: ${pluginName}`}>
|
||||
<span className="layer-item__local-icon-wrapper">
|
||||
<Wrench
|
||||
size={11}
|
||||
className="layer-item__local-icon"
|
||||
aria-label="Local plugin"
|
||||
/>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
function TrustIcon({ trust }: { trust: TrustTier }) {
|
||||
if (trust !== "unverified") return null;
|
||||
|
||||
const manifest = pluginManager.getManifest(pluginId);
|
||||
if (manifest?.trust === "unverified") {
|
||||
return (
|
||||
<Tooltip content="Unverified plugin, use at your own risk">
|
||||
<span className="layer-item__unverified-icon-wrapper">
|
||||
<ShieldAlert
|
||||
size={12}
|
||||
className="layer-item__unverified-icon"
|
||||
aria-label="Unverified plugin"
|
||||
/>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
return (
|
||||
<Tooltip content="Unverified plugin, use at your own risk">
|
||||
<span className="layer-item__unverified-icon-wrapper">
|
||||
<ShieldAlert
|
||||
size={12}
|
||||
className="layer-item__unverified-icon"
|
||||
aria-label="Unverified plugin"
|
||||
/>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── LayerItem Component ────────────────────────────────────
|
||||
@@ -105,6 +88,8 @@ export function LayerItem({
|
||||
onToggle,
|
||||
onSelect,
|
||||
}: LayerItemProps) {
|
||||
const trust = getTrust(plugin.id);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`layer-item ${isSelected ? "layer-item--selected" : ""}`}
|
||||
@@ -117,7 +102,7 @@ export function LayerItem({
|
||||
<div className="layer-item__info">
|
||||
<div className="layer-item__header">
|
||||
<span className="layer-item__name">{plugin.name}</span>
|
||||
<TrustIcon pluginId={plugin.id} pluginName={plugin.name} />
|
||||
<TrustIcon trust={trust} />
|
||||
</div>
|
||||
<div className="layer-item__desc">{plugin.description}</div>
|
||||
<div className="layer-item__footer">
|
||||
|
||||
@@ -16,7 +16,6 @@ import { useStore } from "@/core/state/store";
|
||||
import { useIsMobile } from "@/core/hooks/useIsMobile";
|
||||
import { useResizablePanel } from "@/core/hooks/useResizablePanel";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { setLayerActive } from "@/core/plugins/layerActivation";
|
||||
import { ImportPanel } from "@/plugins/geojson/ImportPanel";
|
||||
import { DiscordIcon } from "@/components/common/DiscordIcon";
|
||||
import { trackEvent } from "@/lib/analytics";
|
||||
@@ -82,12 +81,27 @@ export function LayerPanel() {
|
||||
|
||||
const handleToggle = (pluginId: string) => {
|
||||
const isEnabled = layers[pluginId]?.enabled;
|
||||
setLayerActive(pluginId, !isEnabled);
|
||||
if (!isEnabled) {
|
||||
// UI-panel-specific concerns: open config panel and focus the new layer
|
||||
if (isEnabled) {
|
||||
pluginManager.disablePlugin(pluginId);
|
||||
useStore.getState().setLayerEnabled(pluginId, false);
|
||||
useStore.getState().clearEntities(pluginId);
|
||||
useStore.getState().setEntityCount(pluginId, 0);
|
||||
// Clear hovered/selected if they belong to this layer
|
||||
const state = useStore.getState();
|
||||
if (state.hoveredEntity?.pluginId === pluginId) {
|
||||
state.setHoveredEntity(null, null);
|
||||
}
|
||||
if (state.selectedEntity?.pluginId === pluginId) {
|
||||
state.setSelectedEntity(null);
|
||||
}
|
||||
} else {
|
||||
pluginManager.enablePlugin(pluginId);
|
||||
useStore.getState().setLayerEnabled(pluginId, true);
|
||||
useStore.getState().setHighlightLayerId(pluginId);
|
||||
useStore.getState().setSelectedEntity(null);
|
||||
useStore.getState().setConfigPanelOpen(true);
|
||||
|
||||
// Check if plugin requires configuration
|
||||
const managed = pluginManager.getPlugin(pluginId);
|
||||
const settings = useStore.getState().dataConfig.pluginSettings[pluginId];
|
||||
if (managed?.plugin.requiresConfiguration?.(settings)) {
|
||||
|
||||
@@ -69,7 +69,6 @@
|
||||
.plugin-item__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-bottom: 1px;
|
||||
}
|
||||
@@ -78,7 +77,9 @@
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
word-break: break-word;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.plugin-item__version {
|
||||
@@ -183,7 +184,6 @@
|
||||
text-decoration: none;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
transition: all var(--duration-normal) var(--ease-spring);
|
||||
flex-shrink: 0%;
|
||||
|
||||
@@ -11,16 +11,12 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import {
|
||||
Trash2, ExternalLink, RefreshCw, Download, PowerOff, Power,
|
||||
ShieldCheck, ShieldAlert, HardDrive
|
||||
ShieldCheck, ShieldAlert, Shield
|
||||
} from "lucide-react";
|
||||
import { PluginIcon } from "@/components/common/PluginIcon";
|
||||
import type { ComponentType } from "react";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { getDisabledPluginIds, setPluginDisabled } from "@/core/plugins/pluginPreferences";
|
||||
import { trackEvent } from "@/lib/analytics";
|
||||
import { isPluginInstallEnabled } from "@/core/edition";
|
||||
import type { PluginManifest } from "@/core/plugins/PluginManifest";
|
||||
import "./PluginsTab.css";
|
||||
|
||||
// ─── Types ──────────────────────────────────────────────────
|
||||
@@ -39,9 +35,9 @@ function TrustBadge({ trust }: { trust: string }) {
|
||||
if (trust === "built-in") {
|
||||
return (
|
||||
<span className="trust-badge trust-badge--builtin">
|
||||
<HardDrive size={9} />
|
||||
<Shield size={9} />
|
||||
{' '}
|
||||
Local
|
||||
Built-in
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -100,9 +96,13 @@ function getTrust(record: PluginRecord): string {
|
||||
}
|
||||
}
|
||||
|
||||
function getIcon(record: PluginRecord): string | ComponentType<{ size?: number; color?: string }> {
|
||||
function getIcon(record: PluginRecord): string {
|
||||
const managed = pluginManager.getPlugin(record.pluginId);
|
||||
if (managed) return managed.plugin.icon ?? "📦";
|
||||
if (managed) {
|
||||
return typeof managed.plugin.icon === "string"
|
||||
? managed.plugin.icon
|
||||
: "📦";
|
||||
}
|
||||
try {
|
||||
return JSON.parse(record.config).icon ?? "📦";
|
||||
} catch {
|
||||
@@ -120,11 +120,6 @@ function getName(record: PluginRecord): string {
|
||||
}
|
||||
}
|
||||
|
||||
function getVersion(record: PluginRecord): string {
|
||||
if (record.version !== "built-in") return record.version;
|
||||
return pluginManager.getManifest(record.pluginId)?.version ?? "";
|
||||
}
|
||||
|
||||
// ─── PluginsTab ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -150,8 +145,7 @@ export function PluginsTab() {
|
||||
const dbPlugins: PluginRecord[] = data.plugins ?? [];
|
||||
const dbPluginMap = new Map(dbPlugins.map((p) => [p.pluginId, p]));
|
||||
|
||||
// Add built-in and local plugins that don't have a DB record yet
|
||||
const disabledIds = getDisabledPluginIds();
|
||||
// Add built-in and local plugins that don't have a DB record yet (enabled by default)
|
||||
const allManaged = pluginManager.getAllPlugins();
|
||||
for (const managed of allManaged) {
|
||||
if (!dbPluginMap.has(managed.plugin.id)) {
|
||||
@@ -160,16 +154,11 @@ export function PluginsTab() {
|
||||
version: "built-in",
|
||||
config: "{}",
|
||||
installedAt: new Date().toISOString(),
|
||||
enabled: !disabledIds.has(managed.plugin.id)
|
||||
enabled: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Apply localStorage disabled state to all records
|
||||
dbPlugins.forEach((p) => {
|
||||
if (disabledIds.has(p.pluginId)) p.enabled = false;
|
||||
});
|
||||
|
||||
setPlugins(dbPlugins);
|
||||
if (typeof data.canManagePlugins === "boolean") {
|
||||
setCanInstall(data.canManagePlugins);
|
||||
@@ -203,48 +192,32 @@ export function PluginsTab() {
|
||||
|
||||
const handleDisable = async (pluginId: string) => {
|
||||
setRemoving(pluginId);
|
||||
setPluginDisabled(pluginId, true);
|
||||
pluginManager.disablePlugin(pluginId);
|
||||
const state = useStore.getState();
|
||||
state.setLayerEnabled(pluginId, false);
|
||||
state.clearEntities(pluginId);
|
||||
state.setEntityCount(pluginId, 0);
|
||||
if (state.hoveredEntity?.pluginId === pluginId) state.setHoveredEntity(null, null);
|
||||
if (state.selectedEntity?.pluginId === pluginId) state.setSelectedEntity(null);
|
||||
setNeedsReload(true);
|
||||
trackEvent("plugin-disable", { plugin: pluginId });
|
||||
await loadPlugins();
|
||||
setRemoving(null);
|
||||
try {
|
||||
await fetch("/api/marketplace/disable", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pluginId }),
|
||||
});
|
||||
trackEvent("plugin-disable", { plugin: pluginId });
|
||||
setNeedsReload(true);
|
||||
} catch {
|
||||
setRemoving(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEnable = async (pluginId: string) => {
|
||||
setRemoving(pluginId);
|
||||
setPluginDisabled(pluginId, false);
|
||||
setNeedsReload(false);
|
||||
|
||||
const alreadyRegistered = pluginManager.getPlugin(pluginId);
|
||||
if (!alreadyRegistered) {
|
||||
// Plugin was disabled at startup — its script was never loaded.
|
||||
// Hot-load the script so it's available; leave the layer toggle off.
|
||||
try {
|
||||
const res = await fetch("/api/marketplace/load");
|
||||
if (res.ok) {
|
||||
const { manifests } = await res.json() as { manifests: PluginManifest[] };
|
||||
const manifest = manifests.find((m) => m.id === pluginId);
|
||||
if (manifest) {
|
||||
await pluginManager.loadFromManifest(manifest);
|
||||
useStore.getState().initLayer(pluginId, false);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[PluginsTab] Failed to hot-load plugin:", pluginId, err);
|
||||
}
|
||||
try {
|
||||
await fetch("/api/marketplace/enable", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pluginId }),
|
||||
});
|
||||
trackEvent("plugin-enable", { plugin: pluginId });
|
||||
setNeedsReload(true);
|
||||
} catch {
|
||||
setRemoving(null);
|
||||
}
|
||||
// Layer stays off — user controls it via the Data Layers toggle.
|
||||
|
||||
trackEvent("plugin-enable", { plugin: pluginId });
|
||||
await loadPlugins();
|
||||
setRemoving(null);
|
||||
};
|
||||
|
||||
const handleCheckUpdates = async () => {
|
||||
@@ -379,12 +352,10 @@ export function PluginsTab() {
|
||||
<span className="plugin-item__name">
|
||||
{getName(record)}
|
||||
</span>
|
||||
{getVersion(record) && (
|
||||
<span className="plugin-item__version">
|
||||
v
|
||||
{getVersion(record)}
|
||||
{record.version}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="plugin-item__meta">
|
||||
<TrustBadge trust={getTrust(record)} />
|
||||
@@ -444,12 +415,10 @@ export function PluginsTab() {
|
||||
<span className="plugin-item__name">
|
||||
{getName(record)}
|
||||
</span>
|
||||
{getVersion(record) && (
|
||||
<span className="plugin-item__version">
|
||||
v
|
||||
{getVersion(record)}
|
||||
{record.version}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="plugin-item__meta">
|
||||
<TrustBadge trust={getTrust(record)} />
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { IntelPropertyRow } from "./IntelPropertyRow";
|
||||
|
||||
function formatLocal(iso: string): string {
|
||||
return new Date(iso).toLocaleString(undefined, {
|
||||
day: "numeric", month: "2-digit", year: "numeric",
|
||||
hour: "numeric", minute: "2-digit", hour12: true, timeZoneName: "short",
|
||||
});
|
||||
}
|
||||
|
||||
function formatUtc(iso: string): string {
|
||||
return new Date(iso).toISOString().slice(0, 16).replace("T", " ") + " UTC";
|
||||
}
|
||||
|
||||
function formatRelative(iso: string): string {
|
||||
const diff = new Date(iso).getTime() - Date.now();
|
||||
const abs = Math.abs(diff);
|
||||
const future = diff > 0;
|
||||
if (abs < 60_000) return "just now";
|
||||
if (abs < 3_600_000) {
|
||||
const n = Math.round(abs / 60_000);
|
||||
return future ? `in ${n}m` : `${n}m ago`;
|
||||
}
|
||||
if (abs < 86_400_000) {
|
||||
const n = Math.round(abs / 3_600_000);
|
||||
return future ? `in ${n}h` : `${n}h ago`;
|
||||
}
|
||||
const n = Math.round(abs / 86_400_000);
|
||||
return future ? `in ${n}d` : `${n}d ago`;
|
||||
}
|
||||
|
||||
interface DatetimePropertyRowProps {
|
||||
label: string;
|
||||
iso: string;
|
||||
classNamePrefix?: string;
|
||||
}
|
||||
|
||||
export function DatetimePropertyRow({ label, iso, classNamePrefix = "intel-panel" }: DatetimePropertyRowProps) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
if (expanded) {
|
||||
return (
|
||||
<IntelPropertyRow label={label} isColumn classNamePrefix={classNamePrefix}>
|
||||
<span
|
||||
style={{ cursor: "pointer", fontWeight: 600 }}
|
||||
onClick={() => setExpanded(false)}
|
||||
>
|
||||
{formatLocal(iso)}
|
||||
</span>
|
||||
<span style={{ opacity: 0.6, fontSize: "0.85em" }}>{formatUtc(iso)}</span>
|
||||
<span style={{ opacity: 0.6, fontSize: "0.85em" }}>{formatRelative(iso)}</span>
|
||||
</IntelPropertyRow>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<IntelPropertyRow label={label} classNamePrefix={classNamePrefix}>
|
||||
<span
|
||||
style={{ cursor: "pointer", textDecoration: "underline dotted" }}
|
||||
onClick={() => setExpanded(true)}
|
||||
>
|
||||
{formatLocal(iso)}
|
||||
</span>
|
||||
</IntelPropertyRow>
|
||||
);
|
||||
}
|
||||
@@ -11,8 +11,6 @@ import { ImageProperty } from './ImageProperty';
|
||||
import { UrlProperty } from './UrlProperty';
|
||||
import { LongTextProperty } from './LongTextProperty';
|
||||
import { IntelPropertyRow } from './IntelPropertyRow';
|
||||
import { DatetimePropertyRow } from "./DatetimePropertyRow";
|
||||
import { VideoProperty } from "./VideoProperty";
|
||||
|
||||
/**
|
||||
* @interface DynamicPropertiesRenderProps
|
||||
@@ -39,52 +37,6 @@ export function DynamicPropertiesRender({ entity, classNamePrefix = "intel-panel
|
||||
const label = key.replace(/_/g, " ");
|
||||
const stringValue = String(value);
|
||||
|
||||
// Tagged dispatch - explicit type prefix, checked before heuristics
|
||||
if (typeof value === "string") {
|
||||
if (value.startsWith("datetime:")) {
|
||||
return (
|
||||
<DatetimePropertyRow
|
||||
key={key}
|
||||
label={label}
|
||||
iso={value.slice(9)}
|
||||
classNamePrefix={classNamePrefix}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (value.startsWith("url:")) {
|
||||
return (
|
||||
<UrlProperty
|
||||
key={key}
|
||||
label={label}
|
||||
url={value.slice(4)}
|
||||
classNamePrefix={classNamePrefix}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (value.startsWith("image:")) {
|
||||
return (
|
||||
<ImageProperty
|
||||
key={key}
|
||||
label={label}
|
||||
imageUrl={value.slice(6)}
|
||||
entityId={entity.id}
|
||||
entityLabel={entity.label ?? ""}
|
||||
classNamePrefix={classNamePrefix}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (value.startsWith("video:")) {
|
||||
return (
|
||||
<VideoProperty
|
||||
key={key}
|
||||
label={label}
|
||||
href={value.slice(6)}
|
||||
classNamePrefix={classNamePrefix}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Identify property type
|
||||
const isImage = typeof value === "string" && key.toLowerCase().includes("image") && /^https?:\/\//i.test(value);
|
||||
const isUrl = !isImage && typeof value === "string" && /^https?:\/\//i.test(value);
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import { PlayCircle } from "lucide-react";
|
||||
import { IntelPropertyRow } from "./IntelPropertyRow";
|
||||
|
||||
interface VideoPropertyProps {
|
||||
label: string;
|
||||
href: string;
|
||||
classNamePrefix?: string;
|
||||
}
|
||||
|
||||
export function VideoProperty({ label, href, classNamePrefix = "intel-panel" }: VideoPropertyProps) {
|
||||
return (
|
||||
<IntelPropertyRow label={label} classNamePrefix={classNamePrefix}>
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
style={{ display: "flex", alignItems: "center", gap: 4, color: "var(--accent-cyan)" }}
|
||||
>
|
||||
<PlayCircle size={14} />
|
||||
Watch
|
||||
</a>
|
||||
</IntelPropertyRow>
|
||||
);
|
||||
}
|
||||
@@ -15,9 +15,8 @@ let manifestFetched = false;
|
||||
* Mixing the two caused the production engine to be reported as "local".
|
||||
*/
|
||||
function getLocalEngineBase() {
|
||||
const port = process.env.NEXT_PUBLIC_WWV_LOCAL_ENGINE_PORT || '5000';
|
||||
if (typeof window === "undefined") return `http://localhost:${port}`;
|
||||
return `${window.location.protocol}//${window.location.hostname}:${port}`;
|
||||
if (typeof window === "undefined") return "http://localhost:5000";
|
||||
return `${window.location.protocol}//${window.location.hostname}:5000`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user