Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6bbb34ce65 | ||
|
|
a4bf7fcc8c | ||
|
|
b11c2a8aa4 | ||
|
|
0a4ecdd7e0 | ||
|
|
cf3e749d07 | ||
|
|
ac86684506 |
No files matched your search
@@ -45,10 +45,10 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v4
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
@@ -56,7 +56,7 @@ jobs:
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
|
||||
@@ -53,7 +53,7 @@ jobs:
|
||||
git config user.email '[email protected]'
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -72,7 +72,7 @@ jobs:
|
||||
--days-comment=${{ env.DAYS_COMMENT }}
|
||||
|
||||
- name: Upload findings artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: gc-findings-${{ github.run_id }}
|
||||
path: gc-findings.json
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
fetch-depth: 0 # Required for Stryker's incremental mode.
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: 9
|
||||
|
||||
@@ -46,7 +46,7 @@ jobs:
|
||||
|
||||
- name: Upload mutation report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: stryker-report
|
||||
path: reports/mutation/
|
||||
|
||||
@@ -40,7 +40,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: 9.15.4
|
||||
|
||||
@@ -71,7 +71,7 @@ jobs:
|
||||
NO_AT_BRIDGE: ${{ matrix.browser == 'firefox' && '1' || '0' }}
|
||||
run: pnpm test:e2e --project=${{ matrix.browser }}
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: ${{ !cancelled() }}
|
||||
with:
|
||||
name: playwright-report-${{ matrix.browser }}
|
||||
|
||||
@@ -28,7 +28,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -97,7 +97,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
# WorldWideView
|
||||
|
||||
## What This Is
|
||||
|
||||
WorldWideView is a real-time geospatial intelligence engine that visualizes live global data on an interactive 3D globe -- controllable by any AI agent via a production MCP server. Built for power users, researchers, and developers who need a live, plugin-extensible view of the world and want to connect their AI tools directly to it.
|
||||
|
||||
## Core Value
|
||||
|
||||
A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
|
||||
|
||||
## Current State (v1.2 shipped 2026-05-30)
|
||||
|
||||
**What shipped in v1.2:**
|
||||
- Transport-agnostic personal API keys (wwv_prefix.secret bearer tokens)
|
||||
- Production MCP server at /api/mcp (Streamable HTTP, stateless, Bearer auth)
|
||||
- ConnectAgentHelper UI for one-copy-paste agent setup
|
||||
- Globe state MCP resources (globe://state, globe://sessions, globe://layers)
|
||||
- Globe control tools (pan_globe, focus_entity, toggle_layer, set_timeline) via SSE push
|
||||
- Data query tools (search_entities, get_entities_in_region, get_entity_details, get_plugin_data)
|
||||
- Plugin-contributed MCP tools via SDK manifest extension + frontend relay bridge
|
||||
|
||||
**Tech stack additions:** ioredis singleton, @modelcontextprotocol/sdk, ReadableStream SSE, Redis ZSET/LIST/SET for state/commands/catalog
|
||||
|
||||
## Current Milestone: v1.5 MCP Public-Launch Hardening
|
||||
|
||||
**Goal:** Close the premortem blockers so the MCP server is safe and honest to expose to the public -- a robust error contract, abuse-resistant auth, truthful tool responses, real health checks, production wiring, and clear onboarding.
|
||||
|
||||
**Target features (Phases 31-36):**
|
||||
- Transport resilience: well-formed JSON-RPC errors (no bare 500s), DB-outage-safe auth, explicit maxDuration, honest listChanged
|
||||
- Security and abuse-resistance: dedicated HMAC secret enforcement, Redis-backed per-key rate limiting, trusted-proxy client IP, input/length caps
|
||||
- Tool honesty: accurate emptyReason, validated ids (no success-on-no-op), honest region coverage, output caps, corrected server instructions
|
||||
- Observability: /api/health probes Redis + DB + data engine
|
||||
- Deployment wiring: prod compose Redis + WWV_DATA_ENGINE_URL + global geocoding throttle + infra checklist
|
||||
- Onboarding and framing: public quickstart, ConnectAgentHelper prerequisites, command tools documented as "requires an open globe session"
|
||||
|
||||
**Locked decisions:** command tools keep current behavior (they require a live signed-in browser session to control the globe); a headless/render-on-demand globe is out of scope (deferred).
|
||||
|
||||
## Requirements
|
||||
|
||||
### Validated (Shipped)
|
||||
|
||||
**v1.0 Unified Auth Account System (Phases 1-11, shipped 2026-05-28)**
|
||||
- Supabase shared-cookie auth federation across worldwideview, marketplace, and web
|
||||
- OAuth (GitHub, Google) and email+password auth with NextAuth v5
|
||||
- Shared user identity via `NEXT_PUBLIC_WWV_COOKIE_DOMAIN` across three apps
|
||||
- JWT session persistence, auth callback redirect fix, linked accounts page
|
||||
- Legal/privacy compliance (ToS, cookie consent, GDPR data deletion flow)
|
||||
|
||||
**v1.1 Plugin Install Auth Gate (Phase 12 shipped 2026-05-28)**
|
||||
- PluginInstall model + migration + Plugin.installs counter
|
||||
- Fire-and-forget install tracking upsert in GET /api/install/start
|
||||
|
||||
**v1.2 Full MCP Support (Phases 16-21, shipped 2026-05-30)**
|
||||
- Transport-agnostic API keys with bcrypt storage and timing-oracle prevention - v1.2
|
||||
- Stateless MCP server (Streamable HTTP) with Bearer auth - v1.2
|
||||
- ConnectAgentHelper per-client setup UI; secret only in Authorization header - v1.2
|
||||
- Globe state as MCP resources backed by Redis with heartbeat TTL - v1.2
|
||||
- Globe command bridge via SSE push (< 100ms latency) - v1.2
|
||||
- Data query tools across all active plugins - v1.2
|
||||
- Plugin-contributed namespaced MCP tools via frontend relay - v1.2
|
||||
|
||||
**v1.4 Agentic Intelligence (Phases 26-30, shipped 2026-06-02)**
|
||||
- Server instructions + orientation prompts, 6-component tool description rewrite
|
||||
- emptyReason response contract, list_available_plugins / get_globe_context / investigate_area, update_favorite CRUD
|
||||
- Phase 30 LocalDataSource bridge (static/client-side plugins queryable server-side)
|
||||
|
||||
### Active (v1.5 MCP Public-Launch Hardening)
|
||||
|
||||
- [ ] Transport: top-level JSON-RPC error contract, DB-outage-safe auth, explicit maxDuration, honest listChanged + re-poll docs
|
||||
- [ ] Security: dedicated API_KEY_HMAC_SECRET enforcement (cloud/demo), Redis-backed per-key rate limiting, trusted-proxy IP, favorites cap + identifier/string length+charset bounds
|
||||
- [ ] Tool honesty: session-independent emptyReason, validated layer/filter ids + focus_entity wiring, get_entities_in_region count/truncated + tighter bbox, investigate_area/get_plugin_data output caps, corrected MCP_SERVER_INSTRUCTIONS, engine_unreachable vs no_active_plugins
|
||||
- [ ] Observability: /api/health probes Redis + DB + data engine
|
||||
- [ ] Deployment: prod compose Redis + REDIS_URL, WWV_DATA_ENGINE_URL REST base, global Nominatim throttle, infra checklist
|
||||
- [ ] Onboarding: public quickstart doc, ConnectAgentHelper prerequisites, command-tool open-session requirement documented
|
||||
|
||||
### Out of Scope
|
||||
|
||||
- Embedding an AI chat UI inside the globe -- MCP is server-only
|
||||
- Browser-side MCP client -- globe is an MCP server target, not client
|
||||
- Playwright/computer-use globe control -- using SSE command bridge
|
||||
- Stdio-only MCP transport -- HTTP/SSE for production deployability
|
||||
- CLI tool -- API + MCP cover v1.2; CLI is additive and non-blocking
|
||||
- API key scopes/permissions and rotation/grace-period flows -- revisit later
|
||||
- OAuth 2.1 for MCP auth -- personal API keys sufficient for v1.2
|
||||
- Headless / render-on-demand globe (v1.5) -- command tools require a live signed-in browser session; building a serverless globe is deferred
|
||||
|
||||
## Context
|
||||
|
||||
- **Three apps**: worldwideview (Next.js globe), worldwideview-marketplace (plugin store), worldwideview-web (marketing)
|
||||
- **Auth**: NextAuth v5 + Supabase shared cookies, auth host at worldwideview.dev
|
||||
- **State**: 9 Zustand slices (globe, layers, timeline, ui, filter, data, config, favorites, geojson)
|
||||
- **MCP**: Stateless Streamable HTTP at /api/mcp; Redis for state/commands/catalog; 8 tools + 3 resources
|
||||
- **Data pipeline**: wwv-data-engine (Fastify + Redis) + plugin seeders
|
||||
- **Plugin SDK**: `@worldwideview/wwv-plugin-sdk` with mcpTools manifest extension
|
||||
|
||||
## Key Decisions
|
||||
|
||||
| Decision | Rationale | Outcome |
|
||||
|----------|-----------|---------|
|
||||
| Supabase shared-cookie auth federation | Single sign-on across 3 Next.js apps | ✓ Good |
|
||||
| JWT install bridge for plugin installs | Instance-level auth keeps globe secure | ✓ Good |
|
||||
| HTTP/SSE Streamable HTTP for MCP | Production deployable, any AI client | ✓ Good |
|
||||
| Redis for all MCP state (no in-process) | Scales to multi-user cloud deployment | ✓ Good |
|
||||
| SSE push over WebSocket | Zero infra change, App Router native, MCP spec-first | ✓ Good |
|
||||
| Plugin tools via frontend relay | worldwideview-only, no engine endpoint, composable | ✓ Good |
|
||||
| Generic transport-agnostic API keys | One bearer key for MCP + future REST | ✓ Good |
|
||||
| Marketplace tools deferred to v1.3 | Kept v1.2 worldwideview-only; clean scope | ✓ Good |
|
||||
|
||||
## Evolution
|
||||
|
||||
This document evolves at phase transitions and milestone boundaries.
|
||||
|
||||
---
|
||||
*Last updated: 2026-06-03 after v1.5 milestone start*
|
||||
@@ -1,90 +0,0 @@
|
||||
# Requirements: WorldWideView -- v1.5 MCP Public-Launch Hardening
|
||||
|
||||
**Defined:** 2026-06-03
|
||||
**Core Value:** A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
|
||||
|
||||
Derived from the public-launch premortem. Closes the blockers that make the MCP server unsafe or dishonest to expose to untrusted, authenticated public users.
|
||||
|
||||
## v1 Requirements
|
||||
|
||||
### Transport Resilience (Phase 31)
|
||||
|
||||
- [x] **TRANS-01**: Every MCP failure path (auth throw, malformed JSON-RPC, tool throw, Redis/DB down during request handling) returns a well-formed JSON-RPC error (-32603, id:null, HTTP 500) instead of a bare 500 / empty body.
|
||||
- [x] **TRANS-02**: A database outage during API-key auth returns a clean 401 (authenticateApiKey returns null) rather than throwing.
|
||||
- [x] **TRANS-03**: The MCP route declares an explicit maxDuration above the 10s plugin-relay blpop so platform timeouts never truncate a blocked plugin call into a non-JSON-RPC error.
|
||||
- [x] **TRANS-04**: The server no longer advertises tools.listChanged unless it emits the notification; the stateless "re-call tools/list after enabling plugins" contract is documented in the server instructions.
|
||||
|
||||
### Security and Abuse-Resistance (Phase 32)
|
||||
|
||||
- [x] **SEC-01**: In cloud/demo editions the server requires a dedicated API_KEY_HMAC_SECRET and fails startup if it is unset or equal to AUTH_SECRET; local dev preserves the AUTH_SECRET fallback.
|
||||
- [x] **SEC-02**: MCP tool calls are rate-limited per-userId/per-key via Redis (not only per-IP).
|
||||
- [x] **SEC-03**: Client IP is derived from a trusted-proxy source so rate limiters cannot be bypassed via a spoofed X-Forwarded-For header.
|
||||
- [x] **SEC-04**: Favorites are capped per user and all identifier/string tool inputs (entityId, pluginId, layerId, name, notes) have max-length and charset bounds in the Zod schemas and in isValidGlobeCommand.
|
||||
|
||||
### Tool Honesty and Agent UX (Phase 33)
|
||||
|
||||
- [x] **TOOL-01**: Session-independent data-query tools never report emptyReason "no_session_active"; they return the true reason (no_data_matches, engine_unreachable, or no_active_plugins).
|
||||
- [x] **TOOL-02**: toggle_layer and set_filter validate the id against the live plugin set and return an explicit "enqueued but id not recognized" warning instead of success-shaped text; focus_entity resolves entityId to coordinates server-side.
|
||||
- [x] **TOOL-03**: get_entities_in_region returns count and a truncated flag, tightens the radiusKmToBbox bounds, and documents that capped results are an unordered sample.
|
||||
- [x] **TOOL-04**: investigate_area and get_plugin_data cap total entity output and set a truncated flag so a single response cannot blow client context.
|
||||
- [x] **TOOL-05**: MCP_SERVER_INSTRUCTIONS matches the actual response shapes (emptyReason, {plugins, reason}), and list_available_plugins distinguishes engine_unreachable from no_active_plugins.
|
||||
|
||||
### Observability (Phase 34)
|
||||
|
||||
- [x] **OBS-01**: /api/health actively probes Redis, the database, and the data-engine manifest, returning a degraded status when any dependency is down.
|
||||
|
||||
### Deployment Wiring (Phase 35)
|
||||
|
||||
- [x] **DEPLOY-01**: The production compose template provisions/wires Redis via REDIS_URL so sessions, command queue, geocode cache, and rate limiters work in production.
|
||||
- [x] **DEPLOY-02**: WWV_DATA_ENGINE_URL is set to the engine REST base (not the NEXT_PUBLIC_.../stream WS URL) in compose/env templates so MCP data tools reach /manifest.
|
||||
- [x] **DEPLOY-03**: A single global Nominatim throttle (<=1 rps) protects the shared geocoder, and the geocode cache path is confirmed live.
|
||||
- [x] **DEPLOY-04**: An INFRA-CHECKLIST.md documents the Coolify actions the operator must apply (managed Redis rediss://, REDIS_URL, WWV_DATA_ENGINE_URL, API_KEY_HMAC_SECRET distinct from AUTH_SECRET).
|
||||
|
||||
### Onboarding and Framing (Phase 36)
|
||||
|
||||
- [x] **ONBRD-01**: A public quickstart doc walks a new user from sign-up to a working MCP connection (generate key, paste JSON, open the globe tab).
|
||||
- [x] **ONBRD-02**: ConnectAgentHelper states the hard prerequisites: signed-in account, a browser tab open for command tools, cloud edition.
|
||||
- [x] **ONBRD-03**: Every command-tool description states the live-open-session requirement unmissably.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
| Feature | Reason |
|
||||
|---------|--------|
|
||||
| Headless / render-on-demand globe | Command tools require a live signed-in browser session; building a serverless globe is a large effort, deferred. Command tools keep current behavior. |
|
||||
| API key scopes / rotation flows | Carried over from prior milestones; not a public-launch blocker. |
|
||||
| Self-hosted geocoder | Global throttle is sufficient for launch; self-hosting Nominatim is a later option. |
|
||||
|
||||
## Traceability
|
||||
|
||||
| Requirement | Phase | Status |
|
||||
|-------------|-------|--------|
|
||||
| TRANS-01 | Phase 31 | Done |
|
||||
| TRANS-02 | Phase 31 | Done |
|
||||
| TRANS-03 | Phase 31 | Done |
|
||||
| TRANS-04 | Phase 31 | Done |
|
||||
| SEC-01 | Phase 32 | Done |
|
||||
| SEC-02 | Phase 32 | Done |
|
||||
| SEC-03 | Phase 32 | Done |
|
||||
| SEC-04 | Phase 32 | Done |
|
||||
| TOOL-01 | Phase 33 | Done |
|
||||
| TOOL-02 | Phase 33 | Done |
|
||||
| TOOL-03 | Phase 33 | Done |
|
||||
| TOOL-04 | Phase 33 | Done |
|
||||
| TOOL-05 | Phase 33 | Done |
|
||||
| OBS-01 | Phase 34 | Done |
|
||||
| DEPLOY-01 | Phase 35 | Done |
|
||||
| DEPLOY-02 | Phase 35 | Done |
|
||||
| DEPLOY-03 | Phase 35 | Done |
|
||||
| DEPLOY-04 | Phase 35 | Done |
|
||||
| ONBRD-01 | Phase 36 | Done |
|
||||
| ONBRD-02 | Phase 36 | Done |
|
||||
| ONBRD-03 | Phase 36 | Done |
|
||||
|
||||
**Coverage:**
|
||||
- v1 requirements: 21 total
|
||||
- Mapped to phases: 21
|
||||
- Unmapped: 0
|
||||
|
||||
---
|
||||
*Requirements defined: 2026-06-03*
|
||||
*Last updated: 2026-06-03 after v1.5 milestone start*
|
||||
+96
-126
@@ -1,148 +1,118 @@
|
||||
# Roadmap: WorldWideView
|
||||
# ROADMAP: WorldWideView v1.3 -- Data Source Compliance
|
||||
|
||||
## Milestones
|
||||
**Milestone:** v1.3
|
||||
**Worktree:** feat/data-source-compliance
|
||||
**Core Value:** Legally clean, resilient data pipelines that can swap providers at config time without code changes.
|
||||
**Phase range:** 22-24 (continues from v1.2 which used phases 16-21)
|
||||
|
||||
- [x] **v1.2 Full MCP Support** - Phases 16-21 (shipped 2026-05-30) - [archive](milestones/v1.2-ROADMAP.md)
|
||||
- [x] **v1.3 Location Intelligence** - Phases 22-25 (completed 2026-05-31)
|
||||
- [x] **v1.4 Agentic Intelligence** - Phases 26-30 (shipped 2026-06-02) - [archive](milestones/v1.4-ROADMAP.md)
|
||||
- [ ] **v1.5 MCP Public-Launch Hardening** - Phases 31-36 (planning, started 2026-06-03)
|
||||
---
|
||||
|
||||
## Phases
|
||||
|
||||
<details>
|
||||
<summary>v1.2 Full MCP Support (Phases 16-21) - SHIPPED 2026-05-30</summary>
|
||||
- [ ] **Phase 22: Market-Tracker Provider Abstraction** - Refactor the market-tracker seeder to select provider via env var, with yahoo as no-key default and finnhub/polygon activating on API key; gate searchable tickers on paid provider
|
||||
- [ ] **Phase 23: Aviation Seeder Migration to adsb.lol** - Replace the broken OpenSky seeder (IP banned, non-commercial) with adsb.lol free tier, deleting ~250 lines of credential pool/OAuth/proxy code
|
||||
- [ ] **Phase 24: Undersea Cables Static Asset Swap** - Delete the live submarinecablemap.com proxy API route and serve cables from a static TeleGeography CC BY 4.0 GeoJSON bundled in /public
|
||||
|
||||
- [x] Phase 16: API Key Auth Foundation (4/4 plans) - completed 2026-05-29
|
||||
- [x] Phase 17: MCP Server Foundation (3/3 plans) - completed 2026-05-30
|
||||
- [x] Phase 18: Globe State Sync + Sessions (4/4 plans + gap-closure) - completed 2026-05-30
|
||||
- [x] Phase 19a: Globe Command Bridge poll-based (3/3 plans) - completed 2026-05-30
|
||||
- [x] Phase 19b: SSE Push Transport (2/2 plans) - completed 2026-05-30
|
||||
- [x] Phase 20: Data Query Tools (4/4 plans) - completed 2026-05-30
|
||||
- [x] Phase 21: Plugin-Contributed Tools + Quality (5/5 plans) - completed 2026-05-30
|
||||
|
||||
Full details: [milestones/v1.2-ROADMAP.md](milestones/v1.2-ROADMAP.md)
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>v1.3 Location Intelligence (Phases 22-25) - COMPLETE 2026-05-31</summary>
|
||||
|
||||
- [x] **Phase 22: Geocoding + Favorites** - Geocode places, fly the globe, bookmark tracked entities (4/4 plans, verified 2026-05-31)
|
||||
- [x] **Phase 23: Entity Filtering** - Push live filters to the globe and query plugin-declared filter schemas
|
||||
- [x] **Phase 24: Route Wiring + Version Bump** - Wire all v1.3 registrars into the MCP handler and ship MCP_SERVER_VERSION 1.3.0
|
||||
- [x] **Phase 25: Documentation** - MCP tool docs, plugin author filter guide, user-facing capability summary, and v1.3 release notes (1/1 plans, completed 2026-05-31)
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>v1.4 Agentic Intelligence (Phases 26-30) - SHIPPED 2026-06-02</summary>
|
||||
|
||||
- [x] **Phase 26: Server Instructions + Orientation** - Agent arrives oriented with role framing, canonical workflows, and named MCP Prompts baked into the server (completed 2026-05-31)
|
||||
- [x] **Phase 27: Tool Description Rewrite** - All 15+ existing tools rewritten to the 6-component standard so agents select and invoke them correctly on the first try (completed 2026-05-31)
|
||||
- [x] **Phase 28: Smart Response Contracts + Favorites CRUD** - Query responses carry semantic empty reasons, get_plugin_filters signals unavailable plugins, and favorites gain full update support (completed 2026-05-31)
|
||||
- [x] **Phase 29: Compound and Discovery Tools** - Three new tools let agents self-orient and investigate in one call rather than assembling multi-step pipelines manually (completed 2026-05-31)
|
||||
- [x] **Phase 30: Local Data-Source Bridge** - Server-reachable static/client-side plugins become MCP-queryable via a generalized LocalDataSource registry (4/4 plans, completed 2026-06-02)
|
||||
|
||||
Full details: [milestones/v1.4-ROADMAP.md](milestones/v1.4-ROADMAP.md)
|
||||
|
||||
</details>
|
||||
|
||||
### v1.5 MCP Public-Launch Hardening
|
||||
|
||||
**Milestone Goal:** Close the premortem blockers so the MCP server is safe and honest to expose to untrusted, authenticated public users -- a robust JSON-RPC error contract, abuse-resistant auth, truthful tool responses, real health checks, production wiring, and clear onboarding.
|
||||
|
||||
**Locked decision:** Command/control tools keep current behavior (they require a live signed-in browser session to drive the globe); a headless/render-on-demand globe is out of scope.
|
||||
|
||||
- [ ] **Phase 31: Transport Resilience** - Every MCP failure path returns a well-formed JSON-RPC error, auth survives a DB outage, and timeouts/listChanged are honest
|
||||
- [ ] **Phase 32: Security and Abuse-Resistance** - Dedicated HMAC secret enforcement, Redis-backed per-key rate limiting, trusted-proxy client IP, and input/length/charset caps
|
||||
- [ ] **Phase 33: Tool Honesty and Agent UX** - Tools report the true reason for empty results, validate ids, bound region/output size, and ship corrected server instructions
|
||||
- [ ] **Phase 34: Observability** - /api/health actively probes Redis, the database, and the data engine and reports a degraded status when any is down
|
||||
- [ ] **Phase 35: Deployment Wiring** - Production compose wires Redis + the data-engine REST base, a global geocoder throttle protects Nominatim, and an infra checklist documents operator actions
|
||||
- [ ] **Phase 36: Onboarding and Framing** - A public quickstart, ConnectAgentHelper prerequisites, and command-tool descriptions make the live-open-session requirement unmissable
|
||||
---
|
||||
|
||||
## Phase Details
|
||||
|
||||
### Phase 31: Transport Resilience
|
||||
**Goal**: Every MCP failure path -- auth throw, malformed JSON-RPC, tool throw, Redis/DB outage during request handling, or platform timeout -- surfaces to the client as a well-formed JSON-RPC error rather than a bare 500, an empty body, or a non-JSON-RPC truncation
|
||||
**Depends on**: Phase 30 (v1.4 complete; stable MCP route, authenticateApiKey, plugin-relay blpop bridge)
|
||||
**Requirements**: TRANS-01, TRANS-02, TRANS-03, TRANS-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Forcing any failure mode (invalid auth, malformed JSON-RPC body, a tool that throws, Redis/DB down mid-request) returns a well-formed JSON-RPC error object (code -32603, id:null, HTTP 500) with a non-empty body -- never a bare 500 or empty response
|
||||
2. With the database unavailable, calling an authenticated MCP endpoint returns a clean 401 (authenticateApiKey resolves to null) instead of throwing an unhandled exception
|
||||
3. The MCP route declares an explicit maxDuration greater than the 10s plugin-relay blpop window, so a blocked plugin call still returns a JSON-RPC error rather than a platform-truncated non-JSON-RPC response
|
||||
4. The server's advertised capabilities no longer claim tools.listChanged unless the notification is actually emitted, and the server instructions document the stateless "re-call tools/list after enabling plugins" contract
|
||||
**Plans**: TBD
|
||||
### Phase 22: Market-Tracker Provider Abstraction
|
||||
**Goal**: The market-tracker seeder selects its quote provider via a single env var, with yahoo working out-of-the-box and finnhub/polygon activating when their respective API keys are present; searchable ticker functionality is gated behind a paid provider key with graceful degradation.
|
||||
**Depends on**: Nothing (self-contained seeder change)
|
||||
**Requirements**: MKTK-01, MKTK-02, MKTK-03, MKTK-04, MKTK-05
|
||||
**Key files**:
|
||||
- `local-seeders/community/packages/market-tracker/src/providers/yahoo.ts` (extract from current impl)
|
||||
- `local-seeders/community/packages/market-tracker/src/providers/finnhub.ts` (new, key-gated)
|
||||
- `local-seeders/community/packages/market-tracker/src/providers/polygon.ts` (new, key-gated)
|
||||
- `local-seeders/community/packages/market-tracker/src/providers/index.ts` (factory, reads MARKET_PROVIDER env)
|
||||
|
||||
### Phase 32: Security and Abuse-Resistance
|
||||
**Goal**: An authenticated but untrusted public user cannot bypass auth hardening, exhaust shared resources, spoof their identity to defeat rate limiting, or smuggle oversized/malformed input through the tool schemas
|
||||
**Depends on**: Phase 31 (clean error contract in place so rejected/limited requests return well-formed errors)
|
||||
**Requirements**: SEC-01, SEC-02, SEC-03, SEC-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. In cloud/demo editions the server fails to start when API_KEY_HMAC_SECRET is unset or equal to AUTH_SECRET, while local dev still boots using the AUTH_SECRET fallback
|
||||
2. Repeated MCP tool calls from the same userId/key are throttled by a Redis-backed limiter (per-user/per-key, not only per-IP), and an over-limit call returns a clean rate-limit error
|
||||
3. A spoofed X-Forwarded-For header cannot reset or bypass the rate limiter -- the client IP is derived only from a trusted-proxy source
|
||||
4. Favorites are capped per user, and every identifier/string tool input (entityId, pluginId, layerId, name, notes) is rejected when it exceeds max-length or violates charset bounds, enforced in both the Zod schemas and isValidGlobeCommand
|
||||
**Plans**: TBD
|
||||
1. Running the seeder with no env vars set uses the yahoo provider and streams quotes without error
|
||||
2. Setting `MARKET_PROVIDER=finnhub` and `FINNHUB_API_KEY=<key>` causes the seeder to fetch from Finnhub and stream quotes
|
||||
3. Setting `MARKET_PROVIDER=polygon` and `POLYGON_API_KEY=<key>` causes the seeder to fetch from Polygon and stream quotes
|
||||
4. Requesting a ticker search without a paid provider key returns an empty list or a clear degradation message -- never an unhandled error
|
||||
5. `pnpm test` passes across all provider configurations
|
||||
|
||||
### Phase 33: Tool Honesty and Agent UX
|
||||
**Goal**: Every tool response tells the agent the truth -- the real reason a result is empty, whether an id was actually recognized, whether results were truncated -- so an agent never reports a false success or a misleading cause to its user
|
||||
**Depends on**: Phase 31 (error contract), Phase 32 (validated/bounded inputs so honesty checks operate on sanitized ids)
|
||||
**Requirements**: TOOL-01, TOOL-02, TOOL-03, TOOL-04, TOOL-05
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Session-independent data-query tools never return emptyReason "no_session_active"; an empty result reports the true cause -- no_data_matches, engine_unreachable, or no_active_plugins
|
||||
2. toggle_layer and set_filter validate the id against the live plugin set and return an explicit "enqueued but id not recognized" warning instead of success-shaped text, and focus_entity resolves entityId to coordinates server-side rather than silently no-op'ing
|
||||
3. get_entities_in_region returns a count and a truncated flag, applies tightened radiusKmToBbox bounds, and documents that capped results are an unordered sample
|
||||
4. investigate_area and get_plugin_data cap total entity output and set a truncated flag so a single response cannot blow the client's context window
|
||||
5. MCP_SERVER_INSTRUCTIONS matches the actual response shapes (emptyReason, {plugins, reason}) and list_available_plugins distinguishes engine_unreachable from no_active_plugins
|
||||
**Plans**: TBD
|
||||
**Plans**: 2 plans
|
||||
Plans:
|
||||
- [ ] 22-01-PLAN.md -- Define MarketProvider interface + implement all three provider modules (yahoo, finnhub, polygon)
|
||||
- [ ] 22-02-PLAN.md -- Create provider factory (providers/index.ts), refactor src/index.ts, update tests
|
||||
|
||||
### Phase 34: Observability
|
||||
**Goal**: An operator (or uptime monitor) can tell at a glance whether the MCP server's critical dependencies are healthy, with /api/health actively probing them rather than returning a hardcoded OK
|
||||
**Depends on**: Phase 31 (shared Redis/DB access patterns and error handling reused by the probes)
|
||||
**Requirements**: OBS-01
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. GET /api/health actively probes Redis, the database, and the data-engine manifest on each request rather than returning a static OK
|
||||
2. When any one dependency is unreachable, /api/health returns a degraded status identifying which dependency is down, while a fully healthy stack returns a healthy status
|
||||
**Plans**: TBD
|
||||
### Phase 23: Aviation Seeder Migration to adsb.lol
|
||||
**Goal**: The aviation seeder fetches live aircraft positions from adsb.lol /v2/aircraft with no authentication, the OpenSky credential pool and all associated proxy/OAuth code is deleted, and the frontend aviation plugin displays live aircraft unchanged.
|
||||
**Depends on**: Nothing (self-contained seeder change, Redis key and frontend plugin untouched)
|
||||
**Requirements**: AVIA-01, AVIA-02, AVIA-03, AVIA-04, AVIA-05
|
||||
**Key files**:
|
||||
- `local-seeders/community/packages/aviation/src/index.ts` (full rewrite, ~324 lines -> ~80 lines)
|
||||
- `local-seeders/community/packages/military-aviation/src/index.ts` (reference template -- already uses adsb.lol /v2/mil)
|
||||
|
||||
### Phase 35: Deployment Wiring
|
||||
**Goal**: The production deployment has every dependency the MCP server needs actually provisioned and correctly wired -- Redis, the data-engine REST base, and a protected shared geocoder -- with an operator checklist so a real launch does not silently run on missing infrastructure
|
||||
**Depends on**: Phase 32 (API_KEY_HMAC_SECRET requirement), Phase 34 (health probes confirm the wired dependencies are reachable)
|
||||
**Requirements**: DEPLOY-01, DEPLOY-02, DEPLOY-03, DEPLOY-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. The production compose template provisions and wires Redis via REDIS_URL so sessions, the command queue, the geocode cache, and the rate limiters all function in production
|
||||
2. WWV_DATA_ENGINE_URL points at the engine REST base (not the NEXT_PUBLIC_.../stream WS URL) in the compose/env templates, so MCP data tools can reach /manifest
|
||||
3. A single global Nominatim throttle (<=1 rps) protects the shared geocoder and the geocode cache path is confirmed live in production configuration
|
||||
4. An INFRA-CHECKLIST.md documents the exact Coolify actions an operator must apply: managed Redis (rediss://), REDIS_URL, WWV_DATA_ENGINE_URL, and an API_KEY_HMAC_SECRET distinct from AUTH_SECRET
|
||||
**Plans**: TBD
|
||||
1. The aviation seeder starts and fetches successfully from `https://api.adsb.lol/v2/aircraft` with no credentials configured
|
||||
2. The Redis key `aviation` is populated with aircraft records that match the existing snapshot shape (icao24, lat, lon, alt, speed, heading)
|
||||
3. The frontend aviation plugin displays live aircraft on the globe with no code changes to the plugin itself
|
||||
4. A 429 response from adsb.lol logs a warning and backs off instead of crashing the seeder
|
||||
5. No OpenSky credential pool, OAuth rotation, or Cloudflare proxy code remains in the seeder source
|
||||
|
||||
**Plans**: 1 plan
|
||||
Plans:
|
||||
- [ ] 23-01-PLAN.md -- Rewrite aviation seeder to fetch from adsb.lol, delete OpenSky credential pool
|
||||
|
||||
### Phase 24: Undersea Cables Static Asset Swap
|
||||
**Goal**: The undersea cables plugin loads cable geometry from a static GeoJSON file bundled in /public, the live submarinecablemap.com proxy API route is deleted, and TeleGeography attribution is visible in the plugin UI.
|
||||
**Depends on**: Nothing (self-contained plugin + static asset change)
|
||||
**Requirements**: CABL-01, CABL-02, CABL-03, CABL-04
|
||||
**Key files**:
|
||||
- `src/app/api/undersea-cables/route.ts` (DELETE)
|
||||
- `local-plugins/wwv-plugin-undersea-cables/src/index.tsx` (change fetch URL to `/data/undersea-cables.geojson`)
|
||||
- `public/data/undersea-cables.geojson` (CREATE from TeleGeography GitHub, CC BY 4.0)
|
||||
|
||||
### Phase 36: Onboarding and Framing
|
||||
**Goal**: A new public user can go from sign-up to a working MCP connection without hidden prerequisites, and the live-open-session requirement of command tools is stated unmissably everywhere an agent or user encounters it
|
||||
**Depends on**: Phase 33 (final tool descriptions and instructions stable), Phase 35 (deployment wiring known so the quickstart documents the real path)
|
||||
**Requirements**: ONBRD-01, ONBRD-02, ONBRD-03
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. A public quickstart doc walks a brand-new user end to end: sign up, generate an API key, paste the connection JSON, and open the globe tab to reach a working MCP connection
|
||||
2. ConnectAgentHelper states the hard prerequisites up front: a signed-in account, a browser tab open for command tools, and cloud edition
|
||||
3. Every command-tool description states the live-open-session requirement unmissably, so an agent never attempts a command tool expecting it to work without an open globe session
|
||||
**Plans**: TBD
|
||||
**UI hint**: yes
|
||||
1. The undersea cables plugin loads and renders cable polylines on the globe by fetching `/data/undersea-cables.geojson` directly from the Next.js static asset server
|
||||
2. A request to `/api/undersea-cables` returns 404 (route file is gone)
|
||||
3. The attribution text "Cable data: TeleGeography, CC BY 4.0" is visible in the plugin description or info display
|
||||
4. No outbound request to submarinecablemap.com is made at runtime
|
||||
|
||||
**Plans**: 1 plan
|
||||
Plans:
|
||||
- [x] 24-01-PLAN.md -- Download TeleGeography GeoJSON, delete proxy route, update plugin URL and attribution
|
||||
|
||||
---
|
||||
|
||||
## Progress Table
|
||||
|
||||
| Phase | Plans Complete | Status | Completed |
|
||||
|-------|----------------|--------|-----------|
|
||||
| 22. Geocoding + Favorites | 4/4 | Complete | 2026-05-31 |
|
||||
| 23. Entity Filtering | 3/3 | Complete | 2026-05-31 |
|
||||
| 24. Route Wiring + Version Bump | 1/1 | Complete | 2026-05-31 |
|
||||
| 25. Documentation | 1/1 | Complete | 2026-05-31 |
|
||||
| 26. Server Instructions + Orientation | 1/1 | Complete | 2026-05-31 |
|
||||
| 27. Tool Description Rewrite | 3/3 | Complete | 2026-05-31 |
|
||||
| 28. Smart Response Contracts + Favorites CRUD | 3/3 | Complete | 2026-05-31 |
|
||||
| 29. Compound and Discovery Tools | 1/1 | Complete | 2026-05-31 |
|
||||
| 30. Local Data-Source Bridge | 4/4 | Complete | 2026-06-02 |
|
||||
| 31. Transport Resilience | 0/TBD | Not started | - |
|
||||
| 32. Security and Abuse-Resistance | 0/TBD | Not started | - |
|
||||
| 33. Tool Honesty and Agent UX | 0/TBD | Not started | - |
|
||||
| 34. Observability | 0/TBD | Not started | - |
|
||||
| 35. Deployment Wiring | 0/TBD | Not started | - |
|
||||
| 36. Onboarding and Framing | 0/TBD | Not started | - |
|
||||
| 22. Market-Tracker Provider Abstraction | 2/2 | COMPLETE | 2026-05-30 |
|
||||
| 23. Aviation Seeder Migration to adsb.lol | 1/1 | COMPLETE | 2026-05-30 |
|
||||
| 24. Undersea Cables Static Asset Swap | 1/1 | COMPLETE | 2026-05-30 |
|
||||
|
||||
---
|
||||
|
||||
## Coverage
|
||||
|
||||
**v1 requirements:** 14 total
|
||||
**Mapped:** 14/14
|
||||
**Unmapped:** 0
|
||||
|
||||
| Requirement | Phase |
|
||||
|-------------|-------|
|
||||
| MKTK-01 | Phase 22 |
|
||||
| MKTK-02 | Phase 22 |
|
||||
| MKTK-03 | Phase 22 |
|
||||
| MKTK-04 | Phase 22 |
|
||||
| MKTK-05 | Phase 22 |
|
||||
| AVIA-01 | Phase 23 |
|
||||
| AVIA-02 | Phase 23 |
|
||||
| AVIA-03 | Phase 23 |
|
||||
| AVIA-04 | Phase 23 |
|
||||
| AVIA-05 | Phase 23 |
|
||||
| CABL-01 | Phase 24 |
|
||||
| CABL-02 | Phase 24 |
|
||||
| CABL-03 | Phase 24 |
|
||||
| CABL-04 | Phase 24 |
|
||||
|
||||
---
|
||||
|
||||
*Created: 2026-05-30*
|
||||
*Milestone: v1.3 Data Source Compliance*
|
||||
+62
-86
@@ -1,15 +1,14 @@
|
||||
---
|
||||
gsd_state_version: 1.0
|
||||
milestone: v1.5
|
||||
milestone_name: MCP Public-Launch Hardening
|
||||
status: complete
|
||||
last_updated: "2026-06-03T16:05:00.000Z"
|
||||
last_activity: 2026-06-03
|
||||
milestone: v1.3
|
||||
milestone_name: milestone
|
||||
status: executing
|
||||
last_updated: "2026-05-30T02:59:00.000Z"
|
||||
progress:
|
||||
total_phases: 6
|
||||
completed_phases: 6
|
||||
total_plans: 0
|
||||
completed_plans: 0
|
||||
total_phases: 4
|
||||
completed_phases: 4
|
||||
total_plans: 5
|
||||
completed_plans: 5
|
||||
percent: 100
|
||||
---
|
||||
|
||||
@@ -17,95 +16,72 @@ progress:
|
||||
|
||||
## Project Reference
|
||||
|
||||
See: .planning/PROJECT.md (updated 2026-06-03)
|
||||
**Core Value:** Legally clean, resilient data pipelines that can swap providers at config time without code changes.
|
||||
|
||||
**Core value:** A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
|
||||
**Current focus:** v1.5 MCP Public-Launch Hardening (Phases 31-36) -- closing premortem blockers that make the MCP server unsafe or dishonest to expose to untrusted, authenticated public users.
|
||||
**Current Focus:** v1.3 Data Source Compliance -- replace non-compliant/broken data sources and add provider abstraction.
|
||||
|
||||
This is an ISOLATED worktree workspace. Its planning state is private to the
|
||||
`feat/data-source-compliance` worktree and intentionally distinct from the shared root
|
||||
(C:\dev\wwv\.planning).
|
||||
|
||||
Cross-feature docs (ROADMAP, MILESTONES, research) are NOT duplicated here.
|
||||
See SHARED-DOCS.md for how to reach them.
|
||||
|
||||
## Current Position
|
||||
|
||||
Phase: 36 — Onboarding and Framing (complete)
|
||||
Plan: —
|
||||
Status: All 6 phases (31-36) complete and committed; milestone v1.5 done
|
||||
Last activity: 2026-06-03 — Phase 36 Onboarding and Framing shipped (ONBRD-01..03), gate green (1004 tests), v2.48.9
|
||||
**Milestone:** v1.3 Data Source Compliance
|
||||
**Status:** COMPLETE
|
||||
**Active Phase:** -
|
||||
**Active Plan:** -
|
||||
|
||||
## Completed Phases (v1.5)
|
||||
```
|
||||
Progress: [##############] 100% (4/4 phases complete)
|
||||
```
|
||||
|
||||
| Phase | Result | Commit |
|
||||
|-------|--------|--------|
|
||||
| 31 Transport Resilience | tsc + 916 tests + build green; security SAFE | 121f7b22 |
|
||||
| 32 Security and Abuse-Resistance | tsc + 967 tests + build green; security MERGE-WITH-FIXES resolved | 3fd23473 |
|
||||
| 33 Tool Honesty and Agent UX | tsc + 983 tests + build green; TOOL-01 live-verified (no_data_matches) | 813d2b28 |
|
||||
| 34 Observability | tsc + tests + build green; /api/health probes redis/db/engine/config | b95ff5d5 |
|
||||
| 35 Deployment Wiring | tsc + 1004 tests + build green; security MERGE-WITH-FIXES resolved (Redis auth, AUTH_SECRET, pg loopback) | 0f860185 |
|
||||
| 36 Onboarding and Framing | tsc + 1004 tests + build green; quickstart + prerequisites + SESSION_REQUIRED_PREAMBLE on all 7 command tools | a5fade97 |
|
||||
|
||||
## v1.5 Phase Map
|
||||
|
||||
| Phase | Goal | Key requirements |
|
||||
|-------|------|-----------------|
|
||||
| 31 | Transport Resilience | TRANS-01, TRANS-02, TRANS-03, TRANS-04 |
|
||||
| 32 | Security and Abuse-Resistance | SEC-01, SEC-02, SEC-03, SEC-04 |
|
||||
| 33 | Tool Honesty and Agent UX | TOOL-01, TOOL-02, TOOL-03, TOOL-04, TOOL-05 |
|
||||
| 34 | Observability | OBS-01 |
|
||||
| 35 | Deployment Wiring | DEPLOY-01, DEPLOY-02, DEPLOY-03, DEPLOY-04 |
|
||||
| 36 | Onboarding and Framing | ONBRD-01, ONBRD-02, ONBRD-03 |
|
||||
|
||||
**Coverage:** 21/21 v1.5 requirements mapped, 0 orphaned.
|
||||
|
||||
**Phase numbering:** v1.5 starts at Phase 31 (v1.4 ended at Phase 30).
|
||||
|
||||
**Locked decision:** Command/control tools keep current behavior (they require a live signed-in browser session to drive the globe); a headless/render-on-demand globe is out of scope (deferred).
|
||||
|
||||
## v1.4 Phase Map (archived reference)
|
||||
|
||||
| Phase | Goal | Key requirements |
|
||||
|-------|------|-----------------|
|
||||
| 26 | Server Instructions + Orientation | INST-01, INST-02, INST-03, INST-04 |
|
||||
| 27 | Tool Description Rewrite | DESC-01, DESC-02, DESC-03 |
|
||||
| 28 | Smart Response Contracts + Favorites CRUD | RESP-01, RESP-02, CRUD-01 |
|
||||
| 29 | Compound and Discovery Tools | TOOL-01, TOOL-02, TOOL-03 |
|
||||
| 30 | Local Data-Source Bridge | D-01..D-08, RESP-01, TOOL-01, TOOL-02 |
|
||||
|
||||
## Key Decisions (carried from v1.2/v1.3/v1.4)
|
||||
|
||||
- **MCP transport:** Stateless Streamable HTTP at /api/mcp; raw @modelcontextprotocol/sdk; Bearer auth via authenticateApiKey(). No custom server.ts.
|
||||
- **Redis for ephemeral state:** Globe state, command queues, session catalogs all in Redis. PostgreSQL for user-owned persistent data.
|
||||
- **SSE command bridge:** EventSource-based push (GET /api/globe/commands/stream).
|
||||
- **Plugin tools via frontend relay:** No engine endpoint. useMcpCatalogPublisher + useMcpRelayBridge pattern; plugin-relay blpop has a 10s window (relevant to TRANS-03 maxDuration).
|
||||
- **Three editions:** NEXT_PUBLIC_WWV_EDITION (local/cloud/demo). isDemo gate runs before auth on all new endpoints.
|
||||
- **Generic API keys:** wwv_prefix.secret bearer tokens. authenticateApiKey() middleware reused for all MCP tools.
|
||||
- **LocalDataSource registry (Phase 30):** Manifest-declared registry making server-reachable static/client-side plugins MCP-queryable; per-source TTL cache (TTL_GEOJSON_MS=60min, TTL_ROUTE_MS=60s).
|
||||
- **emptyReason enum (evolving in v1.5):** v1.4 contract was "plugin_not_streaming" | "no_data_matches" | "no_session_active". v1.5 TOOL-01/TOOL-05 require session-independent tools to return no_data_matches | engine_unreachable | no_active_plugins instead of no_session_active. Lock the revised enum in Phase 33 before rewriting MCP_SERVER_INSTRUCTIONS.
|
||||
- **Nominatim rate limiting:** server-side Redis sliding window (1 req/sec) + 24h cache already live (v1.3 GEO-03). DEPLOY-03 elevates this to a single GLOBAL throttle (<=1 rps) protecting the shared geocoder -- do not re-implement per-request limiting.
|
||||
|
||||
## Blockers
|
||||
|
||||
None.
|
||||
| Phase | Name | Status |
|
||||
|-------|------|--------|
|
||||
| 22 | Market-Tracker Provider Abstraction | COMPLETE (2 plans) |
|
||||
| 23 | Aviation Seeder Migration to adsb.lol | COMPLETE (1 plan) |
|
||||
| 24 | Undersea Cables Static Asset Swap | COMPLETE (1 plan) |
|
||||
|
||||
## Accumulated Context
|
||||
|
||||
### Roadmap Evolution
|
||||
### Key Decisions
|
||||
|
||||
- v1.5 derived from a public-launch premortem of the MCP server. One phase per REQUIREMENTS.md category, 1:1 mapping.
|
||||
- Phase numbering: v1.5 starts at Phase 31 (v1.4 ended at Phase 30). Do NOT renumber or reset.
|
||||
- Dependency note: Phase 31 (clean error contract) is foundational -- Phases 32/33/34 surface their rejections/limits/probe failures through it. Phase 35 depends on SEC-01 (HMAC secret) and OBS-01 (probes confirm wiring). Phase 36 depends on Phase 33 (final tool text) and Phase 35 (real deployment path).
|
||||
- Phase 36 is the only UI-touching phase (ConnectAgentHelper prerequisites + command-tool description framing) -- flagged UI hint: yes.
|
||||
- v1.4 (Phases 26-30) shipped 2026-06-02; archived reference retained above.
|
||||
| Decision | Rationale |
|
||||
|---|---|
|
||||
| adsb.lol free tier over AviationStack paid | IP ban makes OpenSky non-functional; adsb.lol is free, commercial-OK, same API shape as existing military-aviation seeder |
|
||||
| Yahoo Finance stays as market-tracker default | No key required, works today; migration path is provider abstraction not immediate swap |
|
||||
| iranwarlive left as-is | Feed endpoint is intentionally public; no explicit ToS = no contract to breach |
|
||||
| Bundle TeleGeography GeoJSON statically | Cables update a few times/year; static file eliminates runtime proxy dependency entirely |
|
||||
| Dropped all OpenSky infrastructure in one pass | No partial migration -- credential pool, OAuth rotation, Cloudflare proxy, node-cron, undici all removed together; adsb.lol requires none of it |
|
||||
| origin_country and vertical_rate omitted from aviation snapshot | Not available from adsb.lol; frontend aviation plugin handles undefined gracefully |
|
||||
|
||||
## Deferred Items
|
||||
### Architecture Notes
|
||||
|
||||
Items deferred at v1.5 milestone start (carried from v1.4 close on 2026-06-02):
|
||||
- Market-tracker providers: extract yahoo.ts from current impl, add finnhub.ts + polygon.ts, factory in providers/index.ts reads MARKET_PROVIDER env
|
||||
- Aviation: military-aviation seeder (`local-seeders/community/packages/military-aviation/src/index.ts`) is the template -- already uses adsb.lol /v2/mil
|
||||
- Cables: TeleGeography publishes open dataset on GitHub (CC BY 4.0). Attribution "Cable data: TeleGeography, CC BY 4.0" required in plugin UI
|
||||
- Redis keys `aviation` and `market-tracker` must be preserved unchanged -- frontend plugins require zero changes
|
||||
|
||||
| Category | Item | Status |
|
||||
|----------|------|--------|
|
||||
| uat_gap | Phase 29 v1.4-UAT.md — 25 pending scenarios | diagnosed (manual acceptance testing not completed; automated gate green) |
|
||||
| todo | 2026-05-30-system-default-common-plugin-tools.md [mcp] | pending (future idea — system-default common plugin tools) |
|
||||
| out_of_scope | Headless / render-on-demand globe | deferred (command tools keep live-session behavior; serverless globe is a large effort) |
|
||||
| out_of_scope | API key scopes / rotation flows | deferred (not a public-launch blocker) |
|
||||
| out_of_scope | Self-hosted geocoder | deferred (global throttle sufficient for launch) |
|
||||
### Blockers
|
||||
|
||||
## Operator Next Steps
|
||||
None.
|
||||
|
||||
- Plan Phase 31 with /gsd:plan-phase 31 (Transport Resilience -- foundational error contract).
|
||||
- Phases execute in numeric order 31 → 32 → 33 → 34 → 35 → 36; dependencies allow some parallelism after Phase 31.
|
||||
### Todos
|
||||
|
||||
- [x] Phase 22 planned (2 plans, verified)
|
||||
- [x] Execute Phase 22: implement market-tracker provider abstraction
|
||||
- [x] Execute Phase 23: rewrite aviation seeder (324 lines -> 83 lines, adsb.lol)
|
||||
- [x] Execute Phase 24: download TeleGeography GeoJSON, delete proxy route, update plugin fetch URL
|
||||
|
||||
## Session Continuity
|
||||
|
||||
**Next action:** v1.3 milestone complete. Open a PR to merge feat/data-source-compliance into main.
|
||||
|
||||
**References:**
|
||||
|
||||
- Compliance audit: `C:\dev\wwv\.planning\surveys\SURVEY-data-source-legality-2026-05-30.md`
|
||||
- ROADMAP: `.planning/ROADMAP.md`
|
||||
- REQUIREMENTS: `.planning/REQUIREMENTS.md`
|
||||
- PROJECT: `.planning/PROJECT.md`
|
||||
@@ -0,0 +1,94 @@
|
||||
---
|
||||
phase: 16-api-key-auth-foundation
|
||||
plan: "03"
|
||||
subsystem: api-key-auth
|
||||
tags: [api-keys, crud-routes, auth, ownership-scoping, reveal-once]
|
||||
dependency_graph:
|
||||
requires: ["16-01", "16-02"]
|
||||
provides: ["16-04"]
|
||||
affects: []
|
||||
tech_stack:
|
||||
added: []
|
||||
patterns:
|
||||
- "isDemo gate before session check on all handlers"
|
||||
- "deleteMany for atomic ownership-scoped hard delete (BOLA prevention)"
|
||||
- "P2002 prefix-collision retry on create"
|
||||
- "reveal-once fullToken in 201 body only"
|
||||
key_files:
|
||||
created:
|
||||
- src/app/api/api-keys/route.ts
|
||||
- src/app/api/api-keys/[id]/route.ts
|
||||
modified: []
|
||||
decisions:
|
||||
- "userId always taken from session.user.id, never from request body (T-16-09)"
|
||||
- "isDemo gate runs FIRST before auth() in all three handlers (Pitfall 6 - demo has no DB row)"
|
||||
- "createKeyWithRetry helper isolates P2002 catch so outer handler catch-all remains clean"
|
||||
- "deleteMany (not delete) used to avoid Prisma NotFound throw on foreign key - returns count 0 instead (TOCTOU elimination)"
|
||||
metrics:
|
||||
duration: "~12 minutes"
|
||||
completed_date: "2026-05-29"
|
||||
tasks_completed: 2
|
||||
tasks_total: 2
|
||||
files_created: 2
|
||||
files_modified: 0
|
||||
---
|
||||
|
||||
# Phase 16 Plan 03: API Key CRUD Route Handlers Summary
|
||||
|
||||
## One-liner
|
||||
|
||||
GET/POST/DELETE route handlers for `/api/api-keys` with ownership-scoped revoke, max-3 enforcement, and reveal-once fullToken in the 201 response.
|
||||
|
||||
## What Was Built
|
||||
|
||||
Three HTTP handlers completing the Wave 2 server surface:
|
||||
|
||||
**`src/app/api/api-keys/route.ts`** (GET + POST)
|
||||
- GET: lists the session user's keys selecting only `{ id, name, prefix, createdAt, lastUsedAt }` - `hashedSecret` never included in response
|
||||
- POST: enforces max-3 (422 `max_keys_reached`), calls `generateApiKey()`, creates the row via Prisma, handles P2002 prefix collision with a single retry, returns 201 `{ key: { id, name, createdAt, fullToken } }` - fullToken returned exactly once here, never again
|
||||
|
||||
**`src/app/api/api-keys/[id]/route.ts`** (DELETE)
|
||||
- `deleteMany({ where: { id, userId } })` - atomic ownership scoping; a foreign or missing key yields `count 0` -> 404, never a 500 or accidental deletion of another user's key
|
||||
|
||||
Both files apply the isDemo gate (403) before `auth()` on every handler, per Pitfall 6 (the demo virtual admin has no DB row).
|
||||
|
||||
## Tasks Completed
|
||||
|
||||
| Task | Name | Commit | Files |
|
||||
|------|------|--------|-------|
|
||||
| 1 | Implement GET + POST route.ts | 476befe | src/app/api/api-keys/route.ts |
|
||||
| 2 | Implement DELETE [id]/route.ts | 4e6ff07 | src/app/api/api-keys/[id]/route.ts |
|
||||
|
||||
## Test Results
|
||||
|
||||
- `pnpm test -- --run src/app/api/api-keys/route.test.ts`: 6/6 GREEN
|
||||
- `pnpm test -- --run "src/app/api/api-keys/[id]/route.test.ts"`: 4/4 GREEN
|
||||
- Full suite `pnpm test -- --run`: 403/403 GREEN (56 test files, no regressions)
|
||||
|
||||
## Security Invariants Verified
|
||||
|
||||
| Threat ID | Disposition | Verification |
|
||||
|-----------|-------------|--------------|
|
||||
| T-16-06 (BOLA - foreign key delete) | mitigated | deleteMany where clause tested in [id]/route.test.ts "ownership enforcement" test |
|
||||
| T-16-07 (hashedSecret/fullToken in list) | mitigated | "response never contains hashedSecret field" test asserts this; GET select projection omits it |
|
||||
| T-16-08 (demo gate) | mitigated | isDemo check is first line of all three handlers |
|
||||
| T-16-09 (userId from body) | mitigated | userId always `session.user.id`, never read from request body |
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
None - plan executed exactly as written.
|
||||
|
||||
## Known Stubs
|
||||
|
||||
None.
|
||||
|
||||
## Threat Flags
|
||||
|
||||
None - no new network surface beyond the planned routes.
|
||||
|
||||
## Self-Check: PASSED
|
||||
|
||||
- `src/app/api/api-keys/route.ts` exists: FOUND
|
||||
- `src/app/api/api-keys/[id]/route.ts` exists: FOUND
|
||||
- Commit 476befe exists: FOUND
|
||||
- Commit 4e6ff07 exists: FOUND
|
||||
@@ -0,0 +1,99 @@
|
||||
---
|
||||
phase: 18-globe-state-sync
|
||||
plan: "05"
|
||||
subsystem: api-route-security
|
||||
tags: [security, demo-gate, gap-closure, rsrc-01]
|
||||
dependency_graph:
|
||||
requires: []
|
||||
provides: [isDemo-gate-on-globe-state-post]
|
||||
affects: [src/app/api/globe/state/route.ts, src/app/api/globe/state/route.test.ts]
|
||||
tech_stack:
|
||||
added: []
|
||||
patterns: [vi.hoisted-mutable-mock, isDemo-gate-before-auth]
|
||||
key_files:
|
||||
created: []
|
||||
modified:
|
||||
- src/app/api/globe/state/route.ts
|
||||
- src/app/api/globe/state/route.test.ts
|
||||
decisions:
|
||||
- "vi.hoisted() required for editionMock because vi.mock factories are hoisted above const declarations"
|
||||
- "isDemo gate placed after rate limiter and before userId resolution (matching canonical api-keys pattern)"
|
||||
- "useGlobeStateSync requires no code change: fetch only catches thrown exceptions, not HTTP 4xx responses"
|
||||
metrics:
|
||||
duration: "8 minutes"
|
||||
completed: "2026-05-30"
|
||||
tasks_completed: 2
|
||||
tasks_total: 2
|
||||
---
|
||||
|
||||
# Phase 18 Plan 05: isDemo Gate for POST /api/globe/state Summary
|
||||
|
||||
**One-liner:** Added isDemo edition gate (403 before auth) to POST /api/globe/state, closing GAP-01 identified in the PR #215 pre-merge audit.
|
||||
|
||||
## Tasks Completed
|
||||
|
||||
| Task | Name | Commit | Files |
|
||||
|------|------|--------|-------|
|
||||
| 1 | Add isDemo gate + test | ee16ec0 | route.ts, route.test.ts |
|
||||
| 2 | Verify useGlobeStateSync handles 403 gracefully | (no commit - read-only verification) | useGlobeStateSync.ts |
|
||||
|
||||
## What Was Built
|
||||
|
||||
**GAP-01 closed:** `POST /api/globe/state` previously had no demo-edition gate, allowing demo users to write globe state to Redis. The fix:
|
||||
|
||||
1. `route.ts`: Added `import { isDemo } from "@/core/edition"` and an early-return guard immediately after the rate limiter check and before the `userId` resolution block. Returns `{ error: "Not available in demo edition" }` with HTTP 403.
|
||||
|
||||
2. `route.test.ts`: Added `editionMock` via `vi.hoisted()` (required because `vi.mock` factories are hoisted above normal `const` declarations), a `vi.mock("@/core/edition", () => editionMock)` call, reset `editionMock.isDemo = false` in the existing `beforeEach`, and a new describe block "POST /api/globe/state -- demo edition gate" with one test asserting 403 + correct body + `writeGlobeState` not called.
|
||||
|
||||
**Task 2 - verification only:** `useGlobeStateSync.pushState` wraps `fetch` in a `try/catch` that only catches thrown exceptions (network errors). HTTP 403 responses are awaited and silently discarded because the hook never inspects `response.ok` or `response.status`. No code change was required.
|
||||
|
||||
## Deviations from Plan
|
||||
|
||||
### Auto-fixed Issues
|
||||
|
||||
**1. [Rule 1 - Bug] vi.hoisted() required for editionMock**
|
||||
- **Found during:** Task 1 (test run)
|
||||
- **Issue:** The plan suggested `const editionMock = { isDemo: false }` declared at module scope, but Vitest hoists `vi.mock` calls above all `const` declarations. The mock factory referenced `editionMock` before it was initialized, causing `ReferenceError: Cannot access 'editionMock' before initialization`.
|
||||
- **Fix:** Wrapped the declaration in `vi.hoisted()`: `const editionMock = vi.hoisted(() => ({ isDemo: false }))`. This runs the factory function before hoisting resolves, making the variable available to the `vi.mock` factory.
|
||||
- **Files modified:** `src/app/api/globe/state/route.test.ts`
|
||||
- **Commit:** ee16ec0
|
||||
|
||||
## Test Results
|
||||
|
||||
All 6 tests passed (5 pre-existing + 1 new):
|
||||
|
||||
```
|
||||
POST /api/globe/state (RSRC-01)
|
||||
- returns 200 and calls writeGlobeState with valid auth + body
|
||||
- returns 401 and does NOT call writeGlobeState when auth returns null
|
||||
- returns 400 and does NOT call writeGlobeState when sessionId is missing
|
||||
- returns 400 when snapshot is missing from body
|
||||
- still yields 200 when writeGlobeState rejects (fire-and-forget contract)
|
||||
POST /api/globe/state -- demo edition gate
|
||||
- returns 403 and does NOT call writeGlobeState when isDemo is true
|
||||
```
|
||||
|
||||
TypeScript strict mode: zero errors (`pnpm tsc --noEmit`).
|
||||
|
||||
## Threat Model Coverage
|
||||
|
||||
| Threat ID | Mitigation | Status |
|
||||
|-----------|-----------|--------|
|
||||
| T-18-05-01 | isDemo gate before auth prevents demo users writing state even with a valid session | MITIGATED |
|
||||
| T-18-05-02 | 403 returned before writeGlobeState is called; no Redis write occurs on demo edition | MITIGATED |
|
||||
|
||||
## Known Stubs
|
||||
|
||||
None.
|
||||
|
||||
## Threat Flags
|
||||
|
||||
None - this plan closes a security gap rather than introducing new surface.
|
||||
|
||||
## Self-Check: PASSED
|
||||
|
||||
- [x] `src/app/api/globe/state/route.ts` modified - `isDemo` import and guard present
|
||||
- [x] `src/app/api/globe/state/route.test.ts` modified - new describe block present
|
||||
- [x] Commit ee16ec0 exists in git log
|
||||
- [x] 6/6 tests green
|
||||
- [x] tsc --noEmit: zero errors
|
||||
@@ -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.
|
||||
@@ -1,126 +0,0 @@
|
||||
# Production Infrastructure Checklist
|
||||
|
||||
Actions an operator must apply in Coolify (or equivalent) before public launch.
|
||||
Complete every item and verify the /api/health response before opening traffic.
|
||||
|
||||
---
|
||||
|
||||
## 1. AUTH_SECRET
|
||||
|
||||
- [ ] Generate a high-entropy secret (minimum 32 bytes):
|
||||
```bash
|
||||
openssl rand -hex 32
|
||||
```
|
||||
- [ ] Set it as `AUTH_SECRET` on the `wwv` service. This value MUST be distinct from
|
||||
`API_KEY_HMAC_SECRET`. The app fails closed (auth broken) if this is unset.
|
||||
|
||||
---
|
||||
|
||||
## 2. Redis
|
||||
|
||||
- [ ] Generate a Redis password:
|
||||
```bash
|
||||
openssl rand -hex 32
|
||||
```
|
||||
- [ ] Set `REDIS_PASSWORD` on both the `wwv` and `wwv-redis` services to this value.
|
||||
- [ ] For a co-located `wwv-redis`: the compose default uses this password automatically
|
||||
via `REDIS_URL=redis://:<password>@wwv-redis:6379`. No further URL override is needed.
|
||||
- [ ] For a managed Redis provider (e.g. Upstash, Redis Cloud): set `REDIS_URL` to the
|
||||
provider's TLS endpoint instead:
|
||||
```
|
||||
REDIS_URL=rediss://:<password>@<host>:<port>
|
||||
```
|
||||
Use `rediss://` (double-s) for TLS. Remove the co-located `wwv-redis` service when
|
||||
using a managed provider.
|
||||
- [ ] Verify Redis is reachable: `GET /api/health` should return `200` with
|
||||
`"redis": "ok"` (not `"degraded"`).
|
||||
|
||||
**What breaks without Redis:** MCP sessions, globe command queue, geocode cache,
|
||||
all per-user and global rate limiters, and API key session tracking silently no-op
|
||||
or degrade. The app stays up but MCP data tools report errors and OSM rate limits
|
||||
are unenforceable.
|
||||
|
||||
---
|
||||
|
||||
## 3. Data Engine REST URL
|
||||
|
||||
- [ ] Set `WWV_DATA_ENGINE_URL` on the `wwv` service to the engine's REST base URL.
|
||||
This is the HTTP base (scheme + host + port). Do NOT include the `/stream` path:
|
||||
```
|
||||
# Correct: REST base only
|
||||
WWV_DATA_ENGINE_URL=http://<engine-host-ip>:5002
|
||||
|
||||
# Wrong: do not include /stream
|
||||
# WWV_DATA_ENGINE_URL=http://<engine-host-ip>:5002/stream
|
||||
```
|
||||
The engine's published REST port is **5002** (maps to internal port 5000 in
|
||||
`deploy/production/docker-compose.engine.yml`).
|
||||
Replace `<engine-host-ip>` with the actual engine host IP or hostname visible from
|
||||
the `wwv` container.
|
||||
- [ ] If the app and engine containers share a Docker network, use the service name:
|
||||
```
|
||||
WWV_DATA_ENGINE_URL=http://wwv-data-engine:5000
|
||||
```
|
||||
- [ ] Verify reachability: `GET /api/health` should return `"engine": "ok"`.
|
||||
A value of `"degraded"` means the URL is wrong or the engine is not running.
|
||||
|
||||
**What breaks without this:** All MCP data query tools (e.g. `query_plugin_data`)
|
||||
report "engine unreachable" and return no data.
|
||||
|
||||
---
|
||||
|
||||
## 4. API Key HMAC Secret
|
||||
|
||||
- [ ] Generate a high-entropy secret (minimum 32 bytes):
|
||||
```bash
|
||||
openssl rand -hex 32
|
||||
```
|
||||
- [ ] Set it as `API_KEY_HMAC_SECRET` on the `wwv` service. This value MUST be
|
||||
distinct from `AUTH_SECRET`. They serve different cryptographic purposes.
|
||||
- [ ] cloud and demo editions fail closed without this value. The app will refuse to
|
||||
issue or validate API keys, blocking all MCP authentication.
|
||||
|
||||
---
|
||||
|
||||
## 5. Trusted IP Header (Cloudflare / CDN)
|
||||
|
||||
- [ ] If a CDN or second reverse proxy (e.g. Cloudflare) sits in front of your
|
||||
Nginx/Traefik reverse proxy, set:
|
||||
```
|
||||
WWV_TRUSTED_IP_HEADER=cf-connecting-ip
|
||||
```
|
||||
Without this, all clients share the proxy's IP address and collapse into a single
|
||||
rate-limit bucket. One user's burst exhausts the quota for all users.
|
||||
- [ ] If you are NOT behind Cloudflare, leave `WWV_TRUSTED_IP_HEADER` unset (the
|
||||
default reads from `x-forwarded-for` via `x-real-ip`).
|
||||
- [ ] Verify the correct client IP is visible in request logs or the
|
||||
`X-Client-IP` debug header (if enabled) after applying the setting.
|
||||
|
||||
---
|
||||
|
||||
## 6. Health Check Semantics
|
||||
|
||||
Configure your uptime monitor or Coolify health check against `GET /api/health`.
|
||||
|
||||
| Response | Meaning | Action required |
|
||||
|---|---|---|
|
||||
| `503` | Database or required config broken | Page on-call immediately |
|
||||
| `200` with any `"degraded"` field | Redis or engine unreachable | Investigate; MCP features are impaired but core app is up |
|
||||
| `200` all `"ok"` | Fully healthy | No action |
|
||||
|
||||
Recommended alert rule: alert on any `503` immediately; alert on `200` degraded
|
||||
after 5 consecutive checks (transient restarts are normal).
|
||||
|
||||
---
|
||||
|
||||
## Verification Sequence
|
||||
|
||||
Run these checks in order after applying all settings:
|
||||
|
||||
1. `GET /api/health` returns `200` with all fields `"ok"`.
|
||||
2. Sign in as an admin user, generate an MCP API key, and confirm the key is issued
|
||||
(cloud/demo: requires `API_KEY_HMAC_SECRET`).
|
||||
3. Run `geocode_location({ query: "Paris" })` via the MCP endpoint and confirm
|
||||
results are returned (requires Redis + Nominatim reachability).
|
||||
4. Run `query_plugin_data` for a live plugin and confirm data is returned (requires
|
||||
`WWV_DATA_ENGINE_URL`).
|
||||
@@ -6,32 +6,7 @@ services:
|
||||
POSTGRES_PASSWORD: password
|
||||
POSTGRES_DB: postgres
|
||||
ports:
|
||||
# Bound to loopback only so Postgres is not reachable from the host network.
|
||||
# The app service reaches db via the internal Docker network.
|
||||
- "127.0.0.1:5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
|
||||
# Co-located Redis for sessions, command queue, geocode cache, and rate limiters.
|
||||
# Remove this service and the depends_on entry below when using a managed Redis
|
||||
# (set REDIS_URL=rediss://:<password>@<host>:6380 in .env instead).
|
||||
wwv-redis:
|
||||
image: redis:7-alpine
|
||||
restart: unless-stopped
|
||||
command: redis-server --requirepass ${REDIS_PASSWORD:-}
|
||||
environment:
|
||||
- "REDIS_PASSWORD=${REDIS_PASSWORD}"
|
||||
volumes:
|
||||
- wwv-redis-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD:-}", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
- "5432:5432"
|
||||
|
||||
wwv-cloud:
|
||||
build:
|
||||
@@ -46,16 +21,7 @@ services:
|
||||
NEXT_PUBLIC_SUPABASE_URL: ${SUPABASE_URL:-http://dummy}
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY:-dummy}
|
||||
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY:-dummy}
|
||||
# Required: high-entropy value distinct from API_KEY_HMAC_SECRET.
|
||||
# The app fails closed (auth broken) if this is unset.
|
||||
AUTH_SECRET: ${AUTH_SECRET}
|
||||
# Redis session/cache/rate-limit store.
|
||||
# Operators using a managed Redis should set REDIS_URL=rediss://:<password>@<host>:6380 in .env.
|
||||
REDIS_URL: "redis://:${REDIS_PASSWORD}@wwv-redis:6379"
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD}
|
||||
# REST base URL for server-side MCP data queries (NOT the WebSocket /stream path).
|
||||
# Set to the actual engine host IP/hostname visible from this container.
|
||||
WWV_DATA_ENGINE_URL: ${WWV_DATA_ENGINE_URL:-http://<engine-host-ip>:5002}
|
||||
AUTH_SECRET: ${AUTH_SECRET:-dummy_secret_for_local_testing_only_1234567890}
|
||||
ports:
|
||||
- "3001:3000"
|
||||
labels:
|
||||
@@ -65,10 +31,7 @@ services:
|
||||
# - "traefik.http.routers.wwv.tls.certresolver=letsencrypt"
|
||||
- "traefik.http.services.wwv.loadbalancer.server.port=3000"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
wwv-redis:
|
||||
condition: service_healthy
|
||||
- db
|
||||
|
||||
traefik:
|
||||
image: traefik:v3.0
|
||||
@@ -82,6 +45,3 @@ services:
|
||||
- "443:443"
|
||||
volumes:
|
||||
- "/var/run/docker.sock:/var/run/docker.sock:ro"
|
||||
|
||||
volumes:
|
||||
wwv-redis-data:
|
||||
@@ -10,29 +10,16 @@ services:
|
||||
- path: .env
|
||||
required: false
|
||||
environment:
|
||||
# Required: high-entropy value distinct from API_KEY_HMAC_SECRET.
|
||||
# The app fails closed (auth broken) if this is unset.
|
||||
- "AUTH_SECRET=${AUTH_SECRET}"
|
||||
- "AUTH_SECRET=${AUTH_SECRET:-default_secret_for_local_dev}"
|
||||
- "WWV_DEMO_ADMIN_SECRET=${WWV_DEMO_ADMIN_SECRET:-}"
|
||||
- "WWV_BRIDGE_TOKEN=${WWV_BRIDGE_TOKEN:-}"
|
||||
- "DATABASE_URL=${DATABASE_URL:-postgresql://postgres:postgres@db:5432/worldwideview?schema=public}"
|
||||
# Provide the explicit public or host IP of the data engine for the frontend to use.
|
||||
# Provide the explicit public or host IP of the data engine for the frontend to use
|
||||
- "NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL=http://192.168.68.69:5002/stream"
|
||||
# REST base URL for server-side MCP data queries (NOT the WebSocket /stream path).
|
||||
# Default assumes the engine runs on the same host, published on port 5002.
|
||||
# Operators using a separate engine host must override to http://<engine-host>:5002
|
||||
- "WWV_DATA_ENGINE_URL=${WWV_DATA_ENGINE_URL:-http://192.168.68.69:5002}"
|
||||
# Redis session/cache/rate-limit store.
|
||||
# Operators using a managed Redis (e.g. Upstash) should set REDIS_URL to their
|
||||
# rediss:// endpoint in .env and remove the wwv-redis service and depends_on below.
|
||||
- "REDIS_URL=redis://:${REDIS_PASSWORD}@wwv-redis:6379"
|
||||
- "REDIS_PASSWORD=${REDIS_PASSWORD}"
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
wwv-redis:
|
||||
condition: service_healthy
|
||||
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
@@ -52,24 +39,6 @@ services:
|
||||
retries: 5
|
||||
start_period: 60s
|
||||
|
||||
# Co-located Redis for sessions, command queue, geocode cache, and rate limiters.
|
||||
# Remove this service and the depends_on entry above when using a managed Redis
|
||||
# (set REDIS_URL=rediss://:<password>@<host>:6380 in .env instead).
|
||||
wwv-redis:
|
||||
image: redis:7-alpine
|
||||
restart: unless-stopped
|
||||
command: redis-server --requirepass ${REDIS_PASSWORD:-}
|
||||
environment:
|
||||
- "REDIS_PASSWORD=${REDIS_PASSWORD}"
|
||||
volumes:
|
||||
- wwv-redis-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD:-}", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
|
||||
volumes:
|
||||
wwv-data:
|
||||
postgres-data:
|
||||
wwv-redis-data:
|
||||
+1
-3
@@ -63,7 +63,7 @@ services:
|
||||
if [ -d \"$$SEEDERS_DIR/private\" ]; then cd $$SEEDERS_DIR/private && CI=true pnpm install --ignore-scripts && pnpm -r rebuild better-sqlite3 esbuild; fi &&
|
||||
cd /app && node dist/server.js"
|
||||
ports:
|
||||
- "${WWV_ENGINE_HOST_PORT:-5000}:5000"
|
||||
- "5000:5000"
|
||||
volumes:
|
||||
- ./local-seeders:/app/seeders
|
||||
environment:
|
||||
@@ -71,8 +71,6 @@ services:
|
||||
- REDIS_URL=redis://wwv-redis:6379
|
||||
- SEEDERS_DIR=/app/seeders
|
||||
- DB_PATH=/app/data/engine.db
|
||||
- WWV_SKIP_WS_AUTH=true
|
||||
- NODE_ENV=development
|
||||
depends_on:
|
||||
wwv-redis:
|
||||
condition: service_healthy
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
# MCP Quickstart: Connect an AI Agent to WorldWideView
|
||||
|
||||
Connect Claude Desktop, Cursor, or any MCP-compatible client to your own WorldWideView
|
||||
globe. MCP is available in the **local (self-hosted) edition** that you run yourself.
|
||||
|
||||
> Cloud edition (hosted at worldmonitor.app) is not yet available. When it launches, the
|
||||
> same steps apply but you will use your cloud account and the cloud endpoint instead of
|
||||
> localhost. See "Cloud edition (coming soon)" at the end.
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- The WorldWideView repository, run locally (this is the **local edition**, the default).
|
||||
- Node.js 20+, pnpm 9+, and Docker (Docker is needed for Postgres, and for Redis + the
|
||||
data engine if you want command tools and live data).
|
||||
- An MCP-compatible client: Claude Desktop, Cursor, VS Code with an MCP extension, or any
|
||||
client that supports the Streamable HTTP MCP transport.
|
||||
|
||||
---
|
||||
|
||||
## Step 1: Install and configure
|
||||
|
||||
From the repository root:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm setup # generates AUTH_SECRET and your local .env (required for API keys to work)
|
||||
```
|
||||
|
||||
`pnpm setup` writes a random `AUTH_SECRET` into `.env`. In the local edition that same
|
||||
secret signs your MCP API keys, so this step is required before key generation will work.
|
||||
The edition defaults to `local` (`NEXT_PUBLIC_WWV_EDITION=local`).
|
||||
|
||||
---
|
||||
|
||||
## Step 2: Run the app
|
||||
|
||||
Two ways to run it, depending on which tools you need:
|
||||
|
||||
```bash
|
||||
pnpm dev # frontend + Postgres only. Read/query tools work. Command tools and live
|
||||
# data do NOT (no Redis, no data engine).
|
||||
|
||||
pnpm dev:all # frontend + data engine + Redis (via Docker Compose). Everything works:
|
||||
# read tools, command tools (open-tab control), geocoding, and live data.
|
||||
```
|
||||
|
||||
Use `pnpm dev:all` for the full MCP experience. The app comes up at
|
||||
**http://localhost:3000** (it will pick another port if 3000 is taken; check the startup log).
|
||||
|
||||
| You want... | Run | Why |
|
||||
|---|---|---|
|
||||
| `search_entities`, `get_plugin_data`, `list_available_plugins`, favorites | `pnpm dev` is enough | served from Postgres + the local data-source registry |
|
||||
| `geocode_location`, command tools (`pan_globe`, `fly_to`, `toggle_layer`, ...) | `pnpm dev:all` | need Redis (sessions, command queue, geocode cache) |
|
||||
| Live plugin data on the globe and in data tools | `pnpm dev:all` | needs the data engine |
|
||||
|
||||
---
|
||||
|
||||
## Step 3: Sign in and generate an API key
|
||||
|
||||
1. Open **http://localhost:3000** and sign in. On a first run, create the initial account
|
||||
via the app's setup flow (see the project README for first-user setup).
|
||||
2. Open **Settings -> API and MCP Access**.
|
||||
3. Click **Generate new key**, give it a name, and **copy the key immediately** (it is shown
|
||||
only once). Your key looks like `wwv_abc123.<long-secret>`.
|
||||
|
||||
The same panel ("Connect your agent") shows a ready-to-paste config block with your local
|
||||
endpoint already filled in (`http://localhost:3000/api/mcp`).
|
||||
|
||||
---
|
||||
|
||||
## Step 4: Add the MCP server to your client
|
||||
|
||||
Paste this into your client's MCP configuration (e.g. `claude_desktop_config.json` for
|
||||
Claude Desktop, or the Cursor MCP settings). The endpoint is your local app:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"worldwideview": {
|
||||
"url": "http://localhost:3000/api/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer wwv_<your-key-here>"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Replace `wwv_<your-key-here>` with the key from step 3. The key goes in the `Authorization`
|
||||
header, never in the URL.
|
||||
|
||||
---
|
||||
|
||||
## Step 5: Restart your client and verify
|
||||
|
||||
Restart your MCP client (Claude Desktop needs a full app restart; Cursor reloads
|
||||
automatically). Ask the agent: "List the available WorldWideView plugins" - it should call
|
||||
`list_available_plugins`. If you started with `pnpm dev:all` and have plugins streaming, you
|
||||
will see them; otherwise see the troubleshooting notes about `engine_unreachable` /
|
||||
`no_active_plugins` below (those mean the connection works but the engine is down or idle).
|
||||
|
||||
---
|
||||
|
||||
## Two capability tiers
|
||||
|
||||
WorldWideView MCP tools split into two tiers based on whether a browser globe session is
|
||||
required.
|
||||
|
||||
### Read / query tools (no open tab required)
|
||||
|
||||
These run server-side and return data using only your API key. You do not need the globe open.
|
||||
|
||||
| Tool | What it does |
|
||||
|---|---|
|
||||
| `search_entities` | Search entities by name across active plugins |
|
||||
| `get_entities_in_region` | Find entities inside a lat/lng bounding box |
|
||||
| `get_entity_details` | Get full details for one entity |
|
||||
| `get_plugin_data` | Get the current snapshot of all entities for a plugin |
|
||||
| `list_available_plugins` | List streaming plugins and their status |
|
||||
| `geocode_location` | Resolve a place name or address to coordinates (needs Redis) |
|
||||
| `save_favorite` | Bookmark an entity |
|
||||
| `list_favorites` | List your bookmarks |
|
||||
| `update_favorite` | Rename or annotate a bookmark |
|
||||
| `remove_favorite` | Delete a bookmark |
|
||||
| `get_plugin_filters` | List filterable fields a plugin declares |
|
||||
|
||||
### Command / control tools (open globe tab required)
|
||||
|
||||
These control the live 3D globe in your browser. **You must keep a WorldWideView browser tab
|
||||
open and signed in as the same account.** Without an open tab, the command is accepted but has
|
||||
no visible effect and the tool returns `"no active globe session to control"`. These also need
|
||||
Redis (run `pnpm dev:all`).
|
||||
|
||||
| Tool | What it does |
|
||||
|---|---|
|
||||
| `pan_globe` | Fly the camera to a coordinate |
|
||||
| `fly_to` | Fly the camera to a geocoded coordinate or bounding box |
|
||||
| `focus_entity` | Centre the camera on a known entity |
|
||||
| `toggle_layer` | Enable or disable a plugin data layer |
|
||||
| `set_timeline` | Set playback time, window, or mode |
|
||||
| `set_filter` | Apply filters to a plugin's live layer |
|
||||
| `clear_filter` | Clear filters on one or all plugins |
|
||||
|
||||
---
|
||||
|
||||
## Recommended agent prompt
|
||||
|
||||
Paste this into your agent's system prompt to give it immediate context:
|
||||
|
||||
```
|
||||
You have access to WorldWideView (WWV) via MCP -- a live 3D globe streaming real-world data
|
||||
(aviation, shipping, earthquakes, weather, and more). Use the MCP tools to query entities,
|
||||
move the camera, toggle layers, and filter data. Command tools require the user to have the
|
||||
WWV globe open in a browser tab. Read/query tools work without a browser tab.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**"no active globe session to control"**
|
||||
A command tool (pan_globe, fly_to, toggle_layer, etc.) ran but no globe tab is open. Open
|
||||
http://localhost:3000 in a browser tab, sign in as the same account that owns the API key,
|
||||
and keep the tab open while you use the agent. Also make sure you started with `pnpm dev:all`
|
||||
(command tools need Redis).
|
||||
|
||||
**"engine_unreachable" from list_available_plugins**
|
||||
The data engine is not running or `WWV_DATA_ENGINE_URL` is not set. Start it with
|
||||
`pnpm dev:all`. The MCP connection itself is working.
|
||||
|
||||
**"no_active_plugins" from list_available_plugins**
|
||||
The data engine is up but no plugins are currently streaming. Enable a plugin from the
|
||||
Plugins panel in the globe app.
|
||||
|
||||
**401 Unauthorized**
|
||||
Your API key is invalid or revoked, or `pnpm setup` was never run (no `AUTH_SECRET`).
|
||||
Confirm `.env` has `AUTH_SECRET`, then generate a fresh key in Settings > API and MCP Access.
|
||||
|
||||
**Tools do not appear in my client**
|
||||
Restart the client after editing the config file. For Claude Desktop, a full app
|
||||
quit-and-relaunch is required.
|
||||
|
||||
---
|
||||
|
||||
## Cloud edition (coming soon)
|
||||
|
||||
A hosted cloud edition is planned at worldmonitor.app. It is **not yet available**. When it
|
||||
launches, the flow is the same as above except:
|
||||
|
||||
- You sign in to your cloud account at worldmonitor.app instead of running the app locally.
|
||||
- The MCP endpoint is `https://api.worldmonitor.app/api/mcp` instead of `http://localhost:3000/api/mcp`.
|
||||
- Infrastructure (Redis, the data engine, secrets) is operated for you, so there is no
|
||||
`pnpm setup` / `pnpm dev:all` step.
|
||||
|
||||
Everything else - generating a key, the Authorization header, the two capability tiers, and
|
||||
the open-tab requirement for command tools - is identical.
|
||||
|
||||
---
|
||||
|
||||
## Next steps
|
||||
|
||||
- See [plugin-filter-guide.md](plugin-filter-guide.md) to learn how to use `get_plugin_filters`
|
||||
and `set_filter` to filter live plugin data.
|
||||
- See [plugin-quickstart.md](plugin-quickstart.md) to build your own data plugin.
|
||||
@@ -1,153 +0,0 @@
|
||||
# Plugin Filter Guide
|
||||
|
||||
This guide explains how a plugin author declares filterable fields so they become
|
||||
discoverable and controllable by AI agents over MCP through the `get_plugin_filters`
|
||||
and `set_filter` tools (v1.3 Location Intelligence).
|
||||
|
||||
## How it fits together
|
||||
|
||||
1. Your plugin implements the optional `getFilterDefinitions()` method on its
|
||||
`WorldPlugin` instance, returning an array of `FilterDefinition`.
|
||||
2. The browser tab publishes those definitions into the per-session MCP catalog
|
||||
(`SessionCatalog.filterDefinitions`, keyed by `pluginId`) in Redis.
|
||||
3. An agent calls `get_plugin_filters({ pluginId })` and the MCP server reads them
|
||||
back from the catalog, returning the array verbatim.
|
||||
4. The agent builds a matching `set_filter({ pluginId, filters })` call. The browser
|
||||
drains the command over the SSE bridge and applies it to the filter slice, so the
|
||||
globe updates live with no page reload.
|
||||
|
||||
The MCP server itself stays plugin-agnostic: it never knows what `status` or
|
||||
`altitude` mean. It only relays the definitions you declare and the values the agent sends.
|
||||
|
||||
## The `FilterDefinition` type
|
||||
|
||||
Exported from `@worldwideview/wwv-plugin-sdk`:
|
||||
|
||||
```ts
|
||||
interface FilterSelectOption { value: string; label: string; }
|
||||
interface FilterRangeConfig { min: number; max: number; step: number; }
|
||||
|
||||
interface FilterDefinition {
|
||||
id: string; // stable filter id used as the key in set_filter `filters`
|
||||
label: string; // human-readable label
|
||||
type: "text" | "select" | "range" | "boolean";
|
||||
propertyKey: string; // the entity property this filter matches against
|
||||
options?: FilterSelectOption[]; // for type "select"
|
||||
range?: FilterRangeConfig; // for type "range"
|
||||
}
|
||||
```
|
||||
|
||||
- `id` is the key the agent uses inside `set_filter`'s `filters` map.
|
||||
- `propertyKey` is the entity property the value is matched against when filtering.
|
||||
It can differ from `id` (e.g. `id: "status"` matching `propertyKey: "flightStatus"`).
|
||||
- `options` is only meaningful for `select`; `range` only for `range`.
|
||||
|
||||
## Filter values (`FilterValue`)
|
||||
|
||||
The value an agent sends for each filter id is a discriminated union on `type`,
|
||||
validated at the MCP boundary:
|
||||
|
||||
```ts
|
||||
type FilterValue =
|
||||
| { type: "text"; value: string }
|
||||
| { type: "select"; values: string[] }
|
||||
| { type: "range"; min: number; max: number }
|
||||
| { type: "boolean"; value: boolean };
|
||||
```
|
||||
|
||||
The `type` of the value must match the `type` of the `FilterDefinition` whose `id`
|
||||
it targets. Structurally invalid values are rejected before reaching the globe.
|
||||
|
||||
## Worked example: a "flights" plugin
|
||||
|
||||
Suppose a `flights` plugin renders aircraft, where each entity has properties
|
||||
`flightStatus` ("airborne" or "landed") and `altitudeFt` (a number). Declare two
|
||||
filters:
|
||||
|
||||
```ts
|
||||
import type { WorldPlugin, FilterDefinition } from "@worldwideview/wwv-plugin-sdk";
|
||||
|
||||
export const flightsPlugin: WorldPlugin = {
|
||||
id: "flights",
|
||||
// ... other required WorldPlugin members ...
|
||||
|
||||
getFilterDefinitions(): FilterDefinition[] {
|
||||
return [
|
||||
{
|
||||
id: "status",
|
||||
label: "Status",
|
||||
type: "select",
|
||||
propertyKey: "flightStatus",
|
||||
options: [
|
||||
{ value: "airborne", label: "Airborne" },
|
||||
{ value: "landed", label: "Landed" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "altitude",
|
||||
label: "Altitude (ft)",
|
||||
type: "range",
|
||||
propertyKey: "altitudeFt",
|
||||
range: { min: 0, max: 45000, step: 1000 },
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### What an agent sees and sends
|
||||
|
||||
The agent first discovers the schema:
|
||||
|
||||
```
|
||||
get_plugin_filters({ pluginId: "flights" })
|
||||
-> [
|
||||
{ id: "status", label: "Status", type: "select", propertyKey: "flightStatus",
|
||||
options: [{ value: "airborne", label: "Airborne" }, { value: "landed", label: "Landed" }] },
|
||||
{ id: "altitude", label: "Altitude (ft)", type: "range", propertyKey: "altitudeFt",
|
||||
range: { min: 0, max: 45000, step: 1000 } }
|
||||
]
|
||||
```
|
||||
|
||||
Then it applies a filter, keyed by the `id`s above:
|
||||
|
||||
```
|
||||
set_filter({
|
||||
pluginId: "flights",
|
||||
filters: {
|
||||
status: { type: "select", values: ["airborne"] },
|
||||
altitude: { type: "range", min: 10000, max: 40000 }
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
The globe immediately hides landed flights and any aircraft outside 10000-40000 ft.
|
||||
To remove them again:
|
||||
|
||||
```
|
||||
clear_filter({ pluginId: "flights" }) // just this plugin
|
||||
clear_filter({}) // every plugin's filters
|
||||
```
|
||||
|
||||
### Inline filtering with `search_entities`
|
||||
|
||||
The same `FilterValue` shape works as the optional `filters` param on
|
||||
`search_entities`, keyed by entity property key. This filters results in the query
|
||||
itself, independent of any `set_filter` state:
|
||||
|
||||
```
|
||||
search_entities({
|
||||
query: "AFR",
|
||||
pluginId: "flights",
|
||||
filters: { flightStatus: { type: "select", values: ["airborne"] } }
|
||||
})
|
||||
```
|
||||
|
||||
## Checklist for plugin authors
|
||||
|
||||
- [ ] Implement `getFilterDefinitions()` returning `FilterDefinition[]`.
|
||||
- [ ] Give each filter a stable `id` and the correct `propertyKey`.
|
||||
- [ ] Provide `options` for `select` filters and `range` for `range` filters.
|
||||
- [ ] Ensure the value `type` an agent will send matches the definition `type`.
|
||||
- [ ] Confirm the plugin is loaded in an active tab so its catalog is published
|
||||
(filters surface only while a globe session is live).
|
||||
+16
-19
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "2.48.14",
|
||||
"version": "2.31.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
@@ -32,37 +32,35 @@
|
||||
"@prisma/adapter-pg": "^7.8.0",
|
||||
"@prisma/client": "^7.8.0",
|
||||
"@prisma/client-runtime-utils": "7.8.0",
|
||||
"@sentry/nextjs": "^10.56.0",
|
||||
"@sentry/nextjs": "^10.54.0",
|
||||
"@supabase/ssr": "^0.10.3",
|
||||
"@supabase/supabase-js": "^2.107.0",
|
||||
"@supabase/supabase-js": "^2.106.2",
|
||||
"@types/pg": "^8.20.0",
|
||||
"@worldwideview/wwv-lib-aviation": "workspace:*",
|
||||
"@worldwideview/wwv-lib-incidents": "workspace:*",
|
||||
"@worldwideview/wwv-plugin-sdk": "workspace:*",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"cesium": "^1.142.0",
|
||||
"cesium": "^1.141.0",
|
||||
"cheerio": "^1.2.0",
|
||||
"hls.js": "^1.6.16",
|
||||
"insecam-api": "^0.0.3",
|
||||
"ioredis": "^5.4.1",
|
||||
"jose": "^6.2.3",
|
||||
"lucide-react": "^1.17.0",
|
||||
"next": "16.2.7",
|
||||
"next": "16.2.6",
|
||||
"next-auth": "^5.0.0-beta.30",
|
||||
"openid-client": "^6.8.4",
|
||||
"pg": "^8.21.0",
|
||||
"prisma": "^7.8.0",
|
||||
"react": "19.2.7",
|
||||
"react-dom": "19.2.7",
|
||||
"react": "19.2.6",
|
||||
"react-dom": "19.2.6",
|
||||
"react-player": "^3.4.0",
|
||||
"resium": "1.22.0",
|
||||
"resium": "1.21.1",
|
||||
"satellite.js": "^7.0.1",
|
||||
"stripe": "^22.2.0",
|
||||
"tslib": "^2.8.1",
|
||||
"undici": "^8.3.0",
|
||||
"ws": "^8.21.0",
|
||||
"zod": "^4.4.3",
|
||||
"zustand": "^5.0.14"
|
||||
"zustand": "^5.0.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/compat": "^2.1.0",
|
||||
@@ -78,16 +76,16 @@
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@typescript-eslint/eslint-plugin": "^8.60.1",
|
||||
"@typescript-eslint/parser": "^8.60.1",
|
||||
"@typescript-eslint/eslint-plugin": "^8.60.0",
|
||||
"@typescript-eslint/parser": "^8.60.0",
|
||||
"@vitejs/plugin-react": "^6.0.2",
|
||||
"@vitest/coverage-v8": "4.1.8",
|
||||
"@vitest/coverage-v8": "4.1.7",
|
||||
"concurrently": "^9.2.1",
|
||||
"copy-webpack-plugin": "^14.0.0",
|
||||
"eslint": "^9",
|
||||
"eslint-config-airbnb": "^19.0.4",
|
||||
"eslint-config-airbnb-typescript": "^18.0.0",
|
||||
"eslint-config-next": "^16.2.7",
|
||||
"eslint-config-next": "^16.2.6",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-jsx-a11y": "^6.10.2",
|
||||
"eslint-plugin-react": "^7.37.5",
|
||||
@@ -96,9 +94,9 @@
|
||||
"jsdom": "^28.1.0",
|
||||
"rollup-plugin-external-globals": "^0.13.0",
|
||||
"tree-kill": "^1.2.2",
|
||||
"tsx": "^4.22.4",
|
||||
"tsx": "^4.22.3",
|
||||
"typescript": "^5",
|
||||
"vite": "^8.0.16",
|
||||
"vite": "^8.0.14",
|
||||
"vitest": "^4.1.7"
|
||||
},
|
||||
"pnpm": {
|
||||
@@ -107,8 +105,7 @@
|
||||
"form-data@<2.5.4": "^2.5.5",
|
||||
"form-data@>=3.0.0 <3.0.4": "^3.0.4",
|
||||
"form-data@>=4.0.0 <4.0.4": "^4.0.5",
|
||||
"fast-uri@<3.1.2": "^3.1.2",
|
||||
"vitest@<4.1.0": "^4.1.8"
|
||||
"fast-uri@<3.1.2": "^3.1.2"
|
||||
},
|
||||
"onlyBuiltDependencies": [
|
||||
"@prisma/engines",
|
||||
|
||||
+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, McpToolDeclaration } from "./manifest";
|
||||
|
||||
// ─── Categories ──────────────────────────────────────────────
|
||||
export type PluginCategory =
|
||||
@@ -315,7 +315,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 };
|
||||
|
||||
@@ -89,24 +89,6 @@ export interface McpToolDeclaration {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @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.
|
||||
@@ -143,12 +125,4 @@ export interface PluginManifest {
|
||||
* 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[];
|
||||
}
|
||||
Generated
+2718
-884
File diff suppressed because it is too large.
Load diff
-36
@@ -1,36 +0,0 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "marketplace_credentials" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenantId" TEXT,
|
||||
"version" TEXT NOT NULL,
|
||||
"salt" TEXT NOT NULL,
|
||||
"nonce" TEXT NOT NULL,
|
||||
"ciphertext" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "marketplace_credentials_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "user_api_keys" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"tenantId" TEXT,
|
||||
"prefix" TEXT NOT NULL,
|
||||
"hashedSecret" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"lastUsedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "user_api_keys_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "marketplace_credentials_tenantId_key" ON "marketplace_credentials"("tenantId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "user_api_keys_prefix_key" ON "user_api_keys"("prefix");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "user_api_keys" ADD CONSTRAINT "user_api_keys_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -1,3 +0,0 @@
|
||||
-- AlterTable: add nullable notes column to favorites
|
||||
-- This is a non-destructive additive change. Existing rows receive NULL.
|
||||
ALTER TABLE "favorites" ADD COLUMN IF NOT EXISTS "notes" TEXT;
|
||||
@@ -14,10 +14,6 @@ model User {
|
||||
name String
|
||||
hashedPassword String
|
||||
role String @default("user")
|
||||
// Bumping this invalidates all of the user's existing JWT sessions.
|
||||
// The JWT embeds the value at sign-in; the auth jwt callback rejects any
|
||||
// token whose value no longer matches the DB (logout-everywhere / revoke).
|
||||
sessionVersion Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
favorites Favorite[]
|
||||
memberships WorkspaceMember[]
|
||||
@@ -36,7 +32,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])
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
@@ -392,23 +392,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(
|
||||
|
||||
@@ -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,34 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth, signOut } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { isCloud } from "@/core/edition";
|
||||
|
||||
/**
|
||||
* POST /api/auth/revoke: "sign out everywhere".
|
||||
*
|
||||
* Increments the authenticated user's `sessionVersion`, which invalidates every
|
||||
* existing JWT issued for that user: the auth `jwt` callback compares each
|
||||
* token's embedded version against the DB on its next use and rejects stale
|
||||
* ones. Also clears the caller's own session cookie.
|
||||
*
|
||||
* Requires an authenticated session. Same-origin only in practice: the session
|
||||
* cookie is `sameSite=lax`, so a cross-site POST carries no credentials.
|
||||
*/
|
||||
export async function POST() {
|
||||
const session = await auth();
|
||||
const userId = session?.user?.id;
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
// Cloud identities are managed by Supabase; there is no local users row to bump.
|
||||
if (!isCloud) {
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { sessionVersion: { increment: 1 } },
|
||||
});
|
||||
}
|
||||
|
||||
await signOut({ redirect: false });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -7,18 +7,6 @@ import { safeFetch } from "@/lib/security/ssrf";
|
||||
|
||||
const MAX_IFRAME_DURATION_MS = 10 * 1000; // 10 seconds timeout for HTML
|
||||
|
||||
/**
|
||||
* Escape a string for safe inclusion in an HTML attribute value.
|
||||
*/
|
||||
function escapeHtmlAttr(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">");
|
||||
}
|
||||
|
||||
/**
|
||||
* Proxy for iframe HTML pages.
|
||||
* Fetches the target HTML, strips X-Frame-Options and CSP, and injects a <base href="...">
|
||||
@@ -74,8 +62,7 @@ export async function GET(req: NextRequest) {
|
||||
let html = await upstream.text();
|
||||
|
||||
// Inject <base href="..."> right after <head> or at the very beginning of the document
|
||||
const escapedUrl = escapeHtmlAttr(targetUrl);
|
||||
const baseTag = `<base href="${escapedUrl}">\n`;
|
||||
const baseTag = `<base href="${targetUrl}">\n`;
|
||||
if (html.includes("<head>")) {
|
||||
html = html.replace("<head>", `<head>\n${baseTag}`);
|
||||
} else if (html.includes("<HEAD>")) {
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { GET } from "./route";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Module mocks -- declared before any imports of the SUT so Vitest hoists them.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock("@/lib/healthProbes", () => ({
|
||||
probeRedis: vi.fn(),
|
||||
probeDb: vi.fn(),
|
||||
probeEngine: vi.fn(),
|
||||
probeConfig: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
edition: "local",
|
||||
}));
|
||||
|
||||
import {
|
||||
probeRedis,
|
||||
probeDb,
|
||||
probeEngine,
|
||||
probeConfig,
|
||||
} from "@/lib/healthProbes";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function setProbes(opts: {
|
||||
redis?: boolean;
|
||||
db?: boolean;
|
||||
engine?: boolean;
|
||||
config?: boolean;
|
||||
}): void {
|
||||
vi.mocked(probeRedis).mockResolvedValue(opts.redis ?? true);
|
||||
vi.mocked(probeDb).mockResolvedValue(opts.db ?? true);
|
||||
vi.mocked(probeEngine).mockResolvedValue(opts.engine ?? true);
|
||||
// probeConfig is synchronous in the real impl; mock as a plain return value.
|
||||
vi.mocked(probeConfig).mockReturnValue(opts.config ?? true);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("GET /api/health", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
it("returns 200 healthy when all probes pass (OBS-01 happy path)", async () => {
|
||||
setProbes({ redis: true, db: true, engine: true, config: true });
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.status).toBe("healthy");
|
||||
expect(body.checks).toEqual({ redis: true, db: true, engine: true, config: true });
|
||||
expect(body).toHaveProperty("edition");
|
||||
expect(body).toHaveProperty("timestamp");
|
||||
});
|
||||
|
||||
it("returns 200 degraded with checks.redis=false when redis probe fails (OBS-01 redis-down)", async () => {
|
||||
setProbes({ redis: false, db: true, engine: true, config: true });
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.status).toBe("degraded");
|
||||
expect(body.checks.redis).toBe(false);
|
||||
expect(body.checks.db).toBe(true);
|
||||
});
|
||||
|
||||
it("returns 503 unhealthy when db probe fails (OBS-01 db-down)", async () => {
|
||||
setProbes({ redis: true, db: false, engine: true, config: true });
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(503);
|
||||
expect(body.status).toBe("unhealthy");
|
||||
expect(body.checks.db).toBe(false);
|
||||
});
|
||||
|
||||
it("returns 200 degraded when engine probe fails (OBS-01 engine-down)", async () => {
|
||||
setProbes({ redis: true, db: true, engine: false, config: true });
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(body.status).toBe("degraded");
|
||||
expect(body.checks.engine).toBe(false);
|
||||
});
|
||||
|
||||
it("returns 503 unhealthy when config probe fails in cloud edition (OBS-01 config-misconfigured)", async () => {
|
||||
// Simulate cloud edition with getSigningKey() having thrown (probeConfig returns false).
|
||||
vi.mocked(probeConfig).mockReturnValue(false);
|
||||
vi.mocked(probeRedis).mockResolvedValue(true);
|
||||
vi.mocked(probeDb).mockResolvedValue(true);
|
||||
vi.mocked(probeEngine).mockResolvedValue(true);
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(503);
|
||||
expect(body.status).toBe("unhealthy");
|
||||
expect(body.checks.config).toBe(false);
|
||||
});
|
||||
|
||||
it("includes edition and ISO timestamp in every response (OBS-01 shape)", async () => {
|
||||
setProbes({});
|
||||
|
||||
const res = await GET();
|
||||
const body = await res.json();
|
||||
|
||||
expect(typeof body.edition).toBe("string");
|
||||
expect(typeof body.timestamp).toBe("string");
|
||||
// ISO 8601 basic check
|
||||
expect(body.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T/);
|
||||
});
|
||||
});
|
||||
@@ -1,66 +1,5 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { edition } from "@/core/edition";
|
||||
import { probeRedis, probeDb, probeEngine, probeConfig } from "@/lib/healthProbes";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Status + HTTP code policy:
|
||||
// db down OR config misconfigured (cloud/demo) -> "unhealthy", 503
|
||||
// Rationale: the app is either unable to authenticate requests or
|
||||
// fundamentally broken. A load balancer or container orchestrator should
|
||||
// stop routing traffic and alert the operator.
|
||||
// redis down OR engine down (but db + config ok) -> "degraded", 200
|
||||
// Rationale: auth/session reads still work; only streaming data or
|
||||
// rate-limiting is impaired. 200 avoids container restarts for transient
|
||||
// upstream outages.
|
||||
// all ok -> "healthy", 200
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type HealthStatus = "healthy" | "degraded" | "unhealthy";
|
||||
|
||||
interface HealthBody {
|
||||
status: HealthStatus;
|
||||
checks: {
|
||||
redis: boolean;
|
||||
db: boolean;
|
||||
engine: boolean;
|
||||
config: boolean;
|
||||
};
|
||||
edition: string;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export async function GET(): Promise<NextResponse<HealthBody>> {
|
||||
// Run all probes in parallel. probeConfig is sync but wrapped in
|
||||
// Promise.resolve so all four settle together with Promise.all.
|
||||
const [redis, db, engine, config] = await Promise.all([
|
||||
probeRedis(),
|
||||
probeDb(),
|
||||
probeEngine(),
|
||||
Promise.resolve(probeConfig()),
|
||||
]);
|
||||
|
||||
const checks = { redis, db, engine, config };
|
||||
|
||||
let status: HealthStatus;
|
||||
let httpStatus: 200 | 503;
|
||||
|
||||
if (!db || !config) {
|
||||
status = "unhealthy";
|
||||
httpStatus = 503;
|
||||
} else if (!redis || !engine) {
|
||||
status = "degraded";
|
||||
httpStatus = 200;
|
||||
} else {
|
||||
status = "healthy";
|
||||
httpStatus = 200;
|
||||
}
|
||||
|
||||
const body: HealthBody = {
|
||||
status,
|
||||
checks,
|
||||
edition,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
return NextResponse.json(body, { status: httpStatus });
|
||||
export async function GET() {
|
||||
return NextResponse.json({ status: "healthy" }, { status: 200 });
|
||||
}
|
||||
@@ -14,22 +14,6 @@ const ALLOWED_REDIRECT_HOSTS = new Set([
|
||||
"worldwideview.dev",
|
||||
]);
|
||||
|
||||
// Derive additional allowed redirect hosts from the configured marketplace URLs
|
||||
// so that custom deployment hostnames (e.g. marketplace.wwv.local) are accepted
|
||||
// without being hardcoded. A bad env value is skipped rather than crashing the module.
|
||||
for (const envUrl of [
|
||||
process.env.NEXT_PUBLIC_MARKETPLACE_URL,
|
||||
process.env.NEXT_PUBLIC_WWV_MARKETPLACE_URL,
|
||||
process.env.MARKETPLACE_URL,
|
||||
]) {
|
||||
if (!envUrl) continue;
|
||||
try {
|
||||
ALLOWED_REDIRECT_HOSTS.add(new URL(envUrl).hostname);
|
||||
} catch {
|
||||
// Ignore unparsable env values — they simply don't contribute a host.
|
||||
}
|
||||
}
|
||||
|
||||
function isSafeRedirect(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
|
||||
@@ -23,22 +23,6 @@ if (process.env.ALLOWED_DEV_ORIGIN) {
|
||||
ALLOWED_REDIRECT_HOSTS.add(process.env.ALLOWED_DEV_ORIGIN);
|
||||
}
|
||||
|
||||
// Derive additional allowed redirect hosts from the configured marketplace URLs
|
||||
// so that custom deployment hostnames (e.g. marketplace.wwv.local) are accepted
|
||||
// without being hardcoded. A bad env value is skipped rather than crashing the module.
|
||||
for (const envUrl of [
|
||||
process.env.NEXT_PUBLIC_MARKETPLACE_URL,
|
||||
process.env.NEXT_PUBLIC_WWV_MARKETPLACE_URL,
|
||||
process.env.MARKETPLACE_URL,
|
||||
]) {
|
||||
if (!envUrl) continue;
|
||||
try {
|
||||
ALLOWED_REDIRECT_HOSTS.add(new URL(envUrl).hostname);
|
||||
} catch {
|
||||
// Ignore unparsable env values; they simply don't contribute a host.
|
||||
}
|
||||
}
|
||||
|
||||
function isSafeRedirect(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { publishSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { publishSessionCatalog, readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import type { SessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { globeCommandsLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
@@ -142,29 +142,9 @@ export async function POST(request: Request): Promise<NextResponse> {
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
@@ -172,3 +152,6 @@ export async function POST(request: Request): Promise<NextResponse> {
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
// Export readSessionCatalog for use by the MCP route (re-export avoids extra import path)
|
||||
export { readSessionCatalog };
|
||||
@@ -1,342 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/data-query/service");
|
||||
vi.mock("@/lib/globeStateStore");
|
||||
vi.mock("@/lib/mcpSessionCatalog");
|
||||
vi.mock("@/lib/globeCommandQueue");
|
||||
vi.mock("@/lib/data-query/localSources");
|
||||
|
||||
import { getAllPluginSnapshots } from "@/lib/data-query/service";
|
||||
import { readActiveSessions, readGlobeState } from "@/lib/globeStateStore";
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { getLocalSourceIds } from "@/lib/data-query/localSources";
|
||||
|
||||
import {
|
||||
radiusKmToBbox,
|
||||
deriveEntityTypes,
|
||||
listStreamingPlugins,
|
||||
buildInvestigateProse,
|
||||
composeGlobeContext,
|
||||
} from "./discoveryHelpers";
|
||||
|
||||
import type { PluginDataSnapshot } from "@/lib/data-query/types";
|
||||
|
||||
const mockGetAllSnapshots = vi.mocked(getAllPluginSnapshots);
|
||||
const mockReadActiveSessions = vi.mocked(readActiveSessions);
|
||||
const mockReadGlobeState = vi.mocked(readGlobeState);
|
||||
const mockReadSessionCatalog = vi.mocked(readSessionCatalog);
|
||||
const mockGetLocalSourceIds = vi.mocked(getLocalSourceIds);
|
||||
|
||||
// resolveActiveSessionId is re-exported from discoveryHelpers but not called
|
||||
// directly in these tests; mocked to avoid ioredis errors.
|
||||
vi.mocked(resolveActiveSessionId).mockResolvedValue(null);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Default: no local sources; individual tests override as needed.
|
||||
mockGetLocalSourceIds.mockResolvedValue(new Set<string>());
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// radiusKmToBbox
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("radiusKmToBbox", () => {
|
||||
it("produces correct bbox at mid-latitude (lat=45, lon=0, radius=111km)", () => {
|
||||
const bbox = radiusKmToBbox(45, 0, 111);
|
||||
// lat delta = 111/111 = 1 degree
|
||||
expect(bbox.north).toBeCloseTo(46, 4);
|
||||
expect(bbox.south).toBeCloseTo(44, 4);
|
||||
// lon delta = 111 / (111 * cos(45deg)) ~ 1/cos(45) ~ 1.414
|
||||
const expectedLonDelta = 1 / Math.cos((45 * Math.PI) / 180);
|
||||
expect(bbox.east).toBeCloseTo(expectedLonDelta, 2);
|
||||
expect(bbox.west).toBeCloseTo(-expectedLonDelta, 2);
|
||||
});
|
||||
|
||||
it("clamps longitude delta near the poles (lat=89.9)", () => {
|
||||
// cos(89.9 deg) is nearly 0 -- guard prevents division explosion
|
||||
const bbox = radiusKmToBbox(89.9, 0, 50);
|
||||
// lon delta should be capped (cos clamped to 0.01)
|
||||
const maxLonDelta = 50 / (111 * 0.01);
|
||||
expect(bbox.east - bbox.west).toBeLessThanOrEqual(maxLonDelta * 2 + 0.001);
|
||||
});
|
||||
|
||||
it("clamps north to 90 and south to -90 at poles", () => {
|
||||
const bbox = radiusKmToBbox(89, 0, 500);
|
||||
expect(bbox.north).toBeLessThanOrEqual(90);
|
||||
const bbox2 = radiusKmToBbox(-89, 0, 500);
|
||||
expect(bbox2.south).toBeGreaterThanOrEqual(-90);
|
||||
});
|
||||
|
||||
it("returns correct bbox at equator (lat=0)", () => {
|
||||
const bbox = radiusKmToBbox(0, 10, 111);
|
||||
expect(bbox.north).toBeCloseTo(1, 4);
|
||||
expect(bbox.south).toBeCloseTo(-1, 4);
|
||||
// cos(0) = 1 so lon delta ~ 1
|
||||
expect(bbox.east).toBeCloseTo(11, 1);
|
||||
expect(bbox.west).toBeCloseTo(9, 1);
|
||||
});
|
||||
|
||||
it("globe-spanning radius (30000 km) produces full-longitude box, not antimeridian strip", () => {
|
||||
// Without the lonDelta cap a 30000 km radius produces lonDelta >> 180,
|
||||
// and wrapLon(lon + lonDelta) collapses to a tiny strip near the antimeridian.
|
||||
// With the cap, lonDelta = 180, so east and west both map to the antimeridian
|
||||
// (+180 and -180 are the same line). The key invariant is that the longitude
|
||||
// span equals 360 degrees (east - west mod 360 = 0 = full globe).
|
||||
const bbox = radiusKmToBbox(0, 0, 30000);
|
||||
// Both east and west land on the antimeridian (180 = -180 in wrapped coords).
|
||||
const normalise = (v: number) => Math.abs(Math.abs(v) - 180);
|
||||
expect(normalise(bbox.east)).toBeCloseTo(0, 4);
|
||||
expect(normalise(bbox.west)).toBeCloseTo(0, 4);
|
||||
expect(bbox.north).toBeCloseTo(90, 0);
|
||||
expect(bbox.south).toBeCloseTo(-90, 0);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// deriveEntityTypes
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("deriveEntityTypes", () => {
|
||||
const snapshot: PluginDataSnapshot = {
|
||||
pluginId: "flights",
|
||||
entities: [
|
||||
{
|
||||
id: "e1",
|
||||
pluginId: "flights",
|
||||
latitude: 0,
|
||||
longitude: 0,
|
||||
timestamp: new Date(),
|
||||
properties: { status: "airborne", airline: "NZ" },
|
||||
},
|
||||
{
|
||||
id: "e2",
|
||||
pluginId: "flights",
|
||||
latitude: 1,
|
||||
longitude: 1,
|
||||
timestamp: new Date(),
|
||||
properties: { status: "landed", altitude: 0 },
|
||||
},
|
||||
],
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
it("returns filterDef ids when filterDefs provided", () => {
|
||||
const defs = [
|
||||
{ id: "status", label: "Status", type: "select" as const, propertyKey: "status", options: [] },
|
||||
];
|
||||
const result = deriveEntityTypes(snapshot, defs);
|
||||
expect(result).toEqual(["status"]);
|
||||
});
|
||||
|
||||
it("falls back to distinct properties keys when no filterDefs", () => {
|
||||
const result = deriveEntityTypes(snapshot);
|
||||
expect(result).toContain("status");
|
||||
expect(result).toContain("airline");
|
||||
expect(result).toContain("altitude");
|
||||
});
|
||||
|
||||
it("returns empty array for snapshot with no entities", () => {
|
||||
const empty: PluginDataSnapshot = { pluginId: "x", entities: [], timestamp: new Date() };
|
||||
expect(deriveEntityTypes(empty)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// listStreamingPlugins
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("listStreamingPlugins", () => {
|
||||
it("returns plugins with counts when snapshots present", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{
|
||||
pluginId: "flights",
|
||||
entities: [
|
||||
{ id: "e1", pluginId: "flights", latitude: 0, longitude: 0, timestamp: new Date(), properties: {} },
|
||||
],
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
const result = await listStreamingPlugins();
|
||||
expect(result.reason).toBeUndefined();
|
||||
expect(result.plugins).toHaveLength(1);
|
||||
expect(result.plugins[0].pluginId).toBe("flights");
|
||||
expect(result.plugins[0].entityCount).toBe(1);
|
||||
});
|
||||
|
||||
it("returns { plugins: [], reason: 'engine_unreachable' } when no snapshots and engine not reachable (TOOL-05)", async () => {
|
||||
// In the test environment the probe fetch fails, so engineReachable=false -> engine_unreachable.
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
const result = await listStreamingPlugins();
|
||||
expect(result.plugins).toHaveLength(0);
|
||||
expect(result.reason).toBe("engine_unreachable");
|
||||
});
|
||||
|
||||
it("returns no_active_plugins when engine reachable but zero snapshots (TOOL-05)", async () => {
|
||||
// Mock fetch to simulate engine responding OK (reachable, but no plugins).
|
||||
const savedFetch = global.fetch;
|
||||
global.fetch = vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ plugins: [] }), { status: 200 }),
|
||||
);
|
||||
try {
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
const result = await listStreamingPlugins();
|
||||
expect(result.plugins).toHaveLength(0);
|
||||
expect(result.reason).toBe("no_active_plugins");
|
||||
} finally {
|
||||
global.fetch = savedFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// buildInvestigateProse
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("buildInvestigateProse", () => {
|
||||
it("happy path: returns count + camera panned text when session present", () => {
|
||||
const prose = buildInvestigateProse({
|
||||
displayName: "Auckland, NZ",
|
||||
entityType: "flights",
|
||||
matchedPlugin: "flights",
|
||||
entityCount: 5,
|
||||
sessionPresent: true,
|
||||
});
|
||||
expect(prose.length).toBeGreaterThan(0);
|
||||
expect(prose).toContain("5");
|
||||
expect(prose).toContain("Auckland");
|
||||
expect(prose).toContain("Camera has been panned");
|
||||
});
|
||||
|
||||
it("happy path: notes skipped camera when no session", () => {
|
||||
const prose = buildInvestigateProse({
|
||||
displayName: "Auckland, NZ",
|
||||
entityType: "flights",
|
||||
matchedPlugin: "flights",
|
||||
entityCount: 3,
|
||||
sessionPresent: false,
|
||||
});
|
||||
expect(prose).toContain("camera pan skipped");
|
||||
});
|
||||
|
||||
it("no-matching-plugin: explains entity_type not found", () => {
|
||||
const prose = buildInvestigateProse({
|
||||
displayName: "Auckland, NZ",
|
||||
entityType: "submarines",
|
||||
matchedPlugin: null,
|
||||
entityCount: 0,
|
||||
sessionPresent: false,
|
||||
});
|
||||
expect(prose).toContain("submarines");
|
||||
expect(prose).toContain("list_available_plugins");
|
||||
});
|
||||
|
||||
it("no-data-matches: explains empty region result", () => {
|
||||
const prose = buildInvestigateProse({
|
||||
displayName: "Auckland, NZ",
|
||||
entityType: "flights",
|
||||
matchedPlugin: "flights",
|
||||
entityCount: 0,
|
||||
sessionPresent: true,
|
||||
emptyReason: "no_data_matches",
|
||||
});
|
||||
expect(prose.length).toBeGreaterThan(0);
|
||||
expect(prose).toContain("no");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// listStreamingPlugins -- source tagging (Plan 30-04, D-05)
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("listStreamingPlugins -- source tagging", () => {
|
||||
const makeSnap = (pluginId: string, entityCount: number) => ({
|
||||
pluginId,
|
||||
entities: Array.from({ length: entityCount }, (_, i) => ({
|
||||
id: `${pluginId}-e${i}`,
|
||||
pluginId,
|
||||
latitude: 0,
|
||||
longitude: 0,
|
||||
timestamp: new Date(),
|
||||
properties: {},
|
||||
})),
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
it("tags engine plugin as source:'engine' and local plugin as source:'local'", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
makeSnap("aviation", 3),
|
||||
makeSnap("camera", 5),
|
||||
]);
|
||||
mockGetLocalSourceIds.mockResolvedValue(new Set(["camera"]));
|
||||
|
||||
const result = await listStreamingPlugins();
|
||||
|
||||
expect(result.reason).toBeUndefined();
|
||||
expect(result.plugins).toHaveLength(2);
|
||||
|
||||
const aviation = result.plugins.find((p) => p.pluginId === "aviation");
|
||||
expect(aviation?.source).toBe("engine");
|
||||
|
||||
const camera = result.plugins.find((p) => p.pluginId === "camera");
|
||||
expect(camera?.source).toBe("local");
|
||||
expect(camera?.entityCount).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("tags by id: only the id present in localIds receives source:'local'", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
makeSnap("flights", 10),
|
||||
makeSnap("ships", 4),
|
||||
makeSnap("camera", 2),
|
||||
]);
|
||||
mockGetLocalSourceIds.mockResolvedValue(new Set(["camera"]));
|
||||
|
||||
const result = await listStreamingPlugins();
|
||||
|
||||
const byId = Object.fromEntries(result.plugins.map((p) => [p.pluginId, p.source]));
|
||||
expect(byId["flights"]).toBe("engine");
|
||||
expect(byId["ships"]).toBe("engine");
|
||||
expect(byId["camera"]).toBe("local");
|
||||
});
|
||||
|
||||
it("engine-unreachable passthrough: empty snapshots returns engine_unreachable when probe fails (TOOL-05)", async () => {
|
||||
// In the test environment the probe fetch fails, so reason becomes engine_unreachable.
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
mockGetLocalSourceIds.mockResolvedValue(new Set(["camera"]));
|
||||
|
||||
const result = await listStreamingPlugins();
|
||||
|
||||
expect(result.plugins).toHaveLength(0);
|
||||
expect(result.reason).toBe("engine_unreachable");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// composeGlobeContext
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("composeGlobeContext", () => {
|
||||
it("returns sessionCount:0 + camera:null when no sessions", async () => {
|
||||
mockReadActiveSessions.mockResolvedValue([]);
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
|
||||
const ctx = await composeGlobeContext("u1");
|
||||
expect(ctx.sessionCount).toBe(0);
|
||||
expect(ctx.camera).toBeNull();
|
||||
expect(ctx.layers).toEqual({});
|
||||
});
|
||||
|
||||
it("returns camera + layers when session active", async () => {
|
||||
mockReadActiveSessions.mockResolvedValue([{ sessionId: "s1", lastSeen: Date.now() }]);
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
mockReadGlobeState.mockResolvedValue({
|
||||
viewport: { lat: -36.8, lon: 174.7, altitude: 500000, heading: 0, pitch: -45, roll: 0 },
|
||||
layers: { flights: { enabled: true } as never },
|
||||
timeline: { currentTime: "2026-01-01T00:00:00Z", timeWindow: "1h", isPlaybackMode: false, playbackTime: 0, playbackSpeed: 1 },
|
||||
selectedEntity: null,
|
||||
lastUpdate: Date.now(),
|
||||
});
|
||||
mockReadSessionCatalog.mockResolvedValue({ tools: [], capabilities: [] });
|
||||
|
||||
const ctx = await composeGlobeContext("u1");
|
||||
expect(ctx.sessionCount).toBe(1);
|
||||
expect(ctx.camera).not.toBeNull();
|
||||
expect(ctx.camera?.lat).toBeCloseTo(-36.8);
|
||||
expect(ctx.layers).toHaveProperty("flights");
|
||||
});
|
||||
});
|
||||
@@ -1,303 +0,0 @@
|
||||
/**
|
||||
* Discovery helpers shared by discoveryTools.ts (Phase 29 -- 29-01).
|
||||
*
|
||||
* Provides:
|
||||
* radiusKmToBbox -- geographic bounding box from a center + radius
|
||||
* deriveEntityTypes -- queryable property/filter-key names for a plugin snapshot
|
||||
* listStreamingPlugins -- manifest + per-plugin counts for list_available_plugins
|
||||
* buildInvestigateProse -- deterministic prose for investigate_area result summaries
|
||||
* composeGlobeContext -- full context payload for get_globe_context
|
||||
*
|
||||
* No `any`, no `@ts-ignore`. All external I/O is delegated to the service/store
|
||||
* helpers imported below.
|
||||
*/
|
||||
|
||||
import type { PluginDataSnapshot } from "@/lib/data-query/types";
|
||||
import type { RegionOptions } from "@/lib/data-query/types";
|
||||
import type { FilterDefinition } from "@/core/plugins/PluginTypes";
|
||||
import { getAllPluginSnapshots } from "@/lib/data-query/service";
|
||||
import { getLocalSourceIds } from "@/lib/data-query/localSources";
|
||||
import { readActiveSessions, readGlobeState } from "@/lib/globeStateStore";
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bbox math
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Maximum number of entity property keys to sample when deriving entity types. */
|
||||
const MAX_PROPERTY_SAMPLE = 50;
|
||||
|
||||
/**
|
||||
* Converts a center coordinate + radius into a RegionOptions bounding box.
|
||||
*
|
||||
* Latitude delta: radiusKm / 111 (1 degree lat ~ 111 km).
|
||||
* Longitude delta: radiusKm / (111 * cos(lat)), clamped to avoid divide-by-zero
|
||||
* near the poles (cos(lat) < 0.01 treated as 0.01). East/west are wrapped to
|
||||
* [-180, 180] so points near the antimeridian produce in-range bounds (the
|
||||
* region query handles east < west as an antimeridian-crossing box).
|
||||
*/
|
||||
export function radiusKmToBbox(lat: number, lon: number, radiusKm: number): RegionOptions {
|
||||
const latDelta = radiusKm / 111;
|
||||
const cosLat = Math.cos((lat * Math.PI) / 180);
|
||||
const clampedCos = Math.max(cosLat, 0.01);
|
||||
// Cap lonDelta at 180 so a globe-spanning radius yields the full longitude
|
||||
// range [-180, 180] rather than wrapping to a thin antimeridian strip.
|
||||
const lonDelta = Math.min(radiusKm / (111 * clampedCos), 180);
|
||||
const wrapLon = (v: number): number => ((((v + 180) % 360) + 360) % 360) - 180;
|
||||
return {
|
||||
north: Math.min(lat + latDelta, 90),
|
||||
south: Math.max(lat - latDelta, -90),
|
||||
east: wrapLon(lon + lonDelta),
|
||||
west: wrapLon(lon - lonDelta),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Entity type derivation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns the queryable field identifiers for a plugin snapshot.
|
||||
*
|
||||
* When the browser has published filterDefinitions for the plugin (via the
|
||||
* session catalog), return those field ids -- they are authoritative.
|
||||
* Otherwise, sample distinct `properties` keys from the snapshot entities as a
|
||||
* best-effort fallback.
|
||||
*/
|
||||
export function deriveEntityTypes(
|
||||
snapshot: PluginDataSnapshot,
|
||||
filterDefs?: FilterDefinition[],
|
||||
): string[] {
|
||||
if (filterDefs && filterDefs.length > 0) {
|
||||
return filterDefs.map((d) => d.id);
|
||||
}
|
||||
|
||||
const keys = new Set<string>();
|
||||
const sample = snapshot.entities.slice(0, MAX_PROPERTY_SAMPLE);
|
||||
for (const entity of sample) {
|
||||
for (const key of Object.keys(entity.properties ?? {})) {
|
||||
keys.add(key);
|
||||
}
|
||||
}
|
||||
return Array.from(keys);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plugin listing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface StreamingPlugin {
|
||||
pluginId: string;
|
||||
/** Engine manifest exposes ids only; pluginName equals pluginId until the
|
||||
* manifest or a richer source provides display names. */
|
||||
pluginName: string;
|
||||
entityCount: number;
|
||||
entityTypes: string[];
|
||||
/** Whether this plugin's data originates from the live engine stream or a
|
||||
* server-reachable local/static source (D-05). */
|
||||
source: "engine" | "local";
|
||||
}
|
||||
|
||||
export interface ListStreamingPluginsResult {
|
||||
plugins: StreamingPlugin[];
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Probes whether the data engine manifest endpoint is reachable.
|
||||
* Returns true when the engine responds with 2xx, false on network error or non-2xx.
|
||||
*
|
||||
* Timeout is intentionally short (2000ms) so callers on the empty-snapshot path
|
||||
* are not blocked waiting for a slow engine.
|
||||
*/
|
||||
async function probeEngineReachable(): Promise<boolean> {
|
||||
const engineUrl = (process.env.WWV_DATA_ENGINE_URL ?? "http://localhost:5001") + "/manifest";
|
||||
try {
|
||||
const res = await fetch(engineUrl, { signal: AbortSignal.timeout(2000) });
|
||||
return res.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the engine manifest and per-plugin snapshots to build a summary list.
|
||||
*
|
||||
* Reasons when plugins array is empty:
|
||||
* engine_unreachable -- manifest fetch failed or engine returned non-2xx.
|
||||
* no_active_plugins -- engine reachable but zero plugins active right now.
|
||||
*
|
||||
* Local sources (e.g. camera) are tagged source:'local' and are surfaced
|
||||
* even when the engine is down (getAllPluginSnapshots includes local sources).
|
||||
*
|
||||
* The probe runs only on the empty-snapshot path to avoid the double-manifest
|
||||
* hit on every happy-path call.
|
||||
*/
|
||||
export async function listStreamingPlugins(): Promise<ListStreamingPluginsResult> {
|
||||
const [snapshots, localIds] = await Promise.all([
|
||||
getAllPluginSnapshots(),
|
||||
getLocalSourceIds(),
|
||||
]);
|
||||
|
||||
if (snapshots.length === 0) {
|
||||
const engineReachable = await probeEngineReachable();
|
||||
const reason = engineReachable ? "no_active_plugins" : "engine_unreachable";
|
||||
return { plugins: [], reason };
|
||||
}
|
||||
|
||||
const plugins: StreamingPlugin[] = snapshots.map((snap) => ({
|
||||
pluginId: snap.pluginId,
|
||||
pluginName: snap.pluginId, // manifest exposes ids only
|
||||
entityCount: snap.entities.length,
|
||||
entityTypes: deriveEntityTypes(snap),
|
||||
source: localIds.has(snap.pluginId) ? "local" : "engine",
|
||||
}));
|
||||
return { plugins };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Prose builder
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface InvestigateProseArgs {
|
||||
displayName: string;
|
||||
entityType: string;
|
||||
matchedPlugin: string | null;
|
||||
entityCount: number;
|
||||
sessionPresent: boolean;
|
||||
emptyReason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds deterministic (non-LLM) prose for the investigate_area summary field.
|
||||
* Covers four cases:
|
||||
* - Happy: entities found
|
||||
* - No matching plugin: entity_type does not match any streaming plugin
|
||||
* - No data matches: plugin streams but no entities in the region
|
||||
* - No session: data queried but camera pan skipped
|
||||
*/
|
||||
export function buildInvestigateProse(args: InvestigateProseArgs): string {
|
||||
const { displayName, entityType, matchedPlugin, entityCount, sessionPresent, emptyReason } = args;
|
||||
|
||||
if (matchedPlugin === null) {
|
||||
return (
|
||||
`No active plugin streams "${entityType}". ` +
|
||||
`Use list_available_plugins to see which entity types are currently streaming, ` +
|
||||
`then retry investigate_area with a matching entity_type.`
|
||||
);
|
||||
}
|
||||
|
||||
if (entityCount > 0) {
|
||||
const cameraNote = sessionPresent
|
||||
? "Camera has been panned to the area."
|
||||
: "No active globe session -- camera pan skipped.";
|
||||
return (
|
||||
`Found ${entityCount} ${entityType} ${entityCount === 1 ? "entity" : "entities"} ` +
|
||||
`near ${displayName} (plugin: ${matchedPlugin}). ${cameraNote}`
|
||||
);
|
||||
}
|
||||
|
||||
// Empty result -- explain why.
|
||||
if (emptyReason === "plugin_not_streaming") {
|
||||
return (
|
||||
`Plugin "${matchedPlugin}" matched your entity_type "${entityType}" but is not ` +
|
||||
`currently streaming data. The engine may be loading or the plugin may be offline.`
|
||||
);
|
||||
}
|
||||
|
||||
const cameraNote = sessionPresent
|
||||
? "Camera was panned to the area."
|
||||
: "No active globe session -- camera pan skipped.";
|
||||
return (
|
||||
`No ${entityType} entities found near ${displayName} (plugin: ${matchedPlugin}). ` +
|
||||
`The plugin is streaming but returned no data for this region and radius. ` +
|
||||
cameraNote
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Globe context composer
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface GlobeContextPayload {
|
||||
sessionCount: number;
|
||||
camera: Record<string, number> | null;
|
||||
layers: Record<string, unknown>;
|
||||
filters: {
|
||||
note: string;
|
||||
definitions?: Record<string, unknown[]>;
|
||||
};
|
||||
plugins: StreamingPlugin[];
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Composes a full globe context snapshot for get_globe_context.
|
||||
* Never throws -- all sub-calls are best-effort; missing data falls back to nulls/empty.
|
||||
*/
|
||||
export async function composeGlobeContext(userId: string): Promise<GlobeContextPayload> {
|
||||
const [sessions, pluginsResult] = await Promise.all([
|
||||
readActiveSessions(userId),
|
||||
listStreamingPlugins(),
|
||||
]);
|
||||
|
||||
const sessionCount = sessions.length;
|
||||
|
||||
if (sessionCount === 0) {
|
||||
return {
|
||||
sessionCount: 0,
|
||||
camera: null,
|
||||
layers: {},
|
||||
filters: { note: "No active session -- filter values are not server-tracked." },
|
||||
plugins: pluginsResult.plugins,
|
||||
...(pluginsResult.reason !== undefined && { reason: pluginsResult.reason }),
|
||||
};
|
||||
}
|
||||
|
||||
// Use the most recently active session.
|
||||
const sorted = [...sessions].sort((a, b) => b.lastSeen - a.lastSeen);
|
||||
const activeSessionId = sorted[0].sessionId;
|
||||
|
||||
const [globeState, catalog] = await Promise.all([
|
||||
readGlobeState(userId, activeSessionId),
|
||||
readSessionCatalog(userId, activeSessionId),
|
||||
]);
|
||||
|
||||
const camera = globeState
|
||||
? {
|
||||
lat: globeState.viewport.lat,
|
||||
lon: globeState.viewport.lon,
|
||||
altitude: globeState.viewport.altitude,
|
||||
heading: globeState.viewport.heading,
|
||||
pitch: globeState.viewport.pitch,
|
||||
}
|
||||
: null;
|
||||
|
||||
const layers = globeState?.layers ?? {};
|
||||
|
||||
// Filter definitions from catalog (browser-published). Applied values are
|
||||
// NOT server-tracked -- only definition metadata is available here.
|
||||
const filterDefs = catalog?.filterDefinitions ?? {};
|
||||
const filters = {
|
||||
note: "Applied filter VALUES are not server-tracked. Only filter definitions (fields/types) are available here.",
|
||||
definitions: Object.fromEntries(
|
||||
Object.entries(filterDefs).map(([pluginId, defs]) => [
|
||||
pluginId,
|
||||
defs as unknown[],
|
||||
]),
|
||||
),
|
||||
};
|
||||
|
||||
return {
|
||||
sessionCount,
|
||||
camera,
|
||||
layers,
|
||||
filters,
|
||||
plugins: pluginsResult.plugins,
|
||||
...(pluginsResult.reason !== undefined && { reason: pluginsResult.reason }),
|
||||
};
|
||||
}
|
||||
|
||||
/** Re-export for convenience so discoveryTools.ts has one import path. */
|
||||
export { resolveActiveSessionId };
|
||||
@@ -1,304 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/data-query/service");
|
||||
vi.mock("@/lib/globeStateStore");
|
||||
vi.mock("@/lib/mcpSessionCatalog");
|
||||
vi.mock("@/lib/globeCommandQueue");
|
||||
vi.mock("@/lib/nominatim", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/lib/nominatim")>();
|
||||
return {
|
||||
...actual,
|
||||
fetchGeocode: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
import { getAllPluginSnapshots, getEntitiesInRegion } from "@/lib/data-query/service";
|
||||
import { readActiveSessions, readGlobeState } from "@/lib/globeStateStore";
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { resolveActiveSessionId, enqueueGlobeCommand } from "@/lib/globeCommandQueue";
|
||||
import { fetchGeocode } from "@/lib/nominatim";
|
||||
import { registerDiscoveryTools } from "./discoveryTools";
|
||||
|
||||
const mockGetAllSnapshots = vi.mocked(getAllPluginSnapshots);
|
||||
const mockGetEntitiesInRegion = vi.mocked(getEntitiesInRegion);
|
||||
const mockReadActiveSessions = vi.mocked(readActiveSessions);
|
||||
const mockReadGlobeState = vi.mocked(readGlobeState);
|
||||
const mockReadSessionCatalog = vi.mocked(readSessionCatalog);
|
||||
const mockResolveActiveSessionId = vi.mocked(resolveActiveSessionId);
|
||||
const mockEnqueueGlobeCommand = vi.mocked(enqueueGlobeCommand);
|
||||
const mockFetchGeocode = vi.mocked(fetchGeocode);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Minimal fake server that captures handlers
|
||||
// ---------------------------------------------------------------------------
|
||||
const handlers: Record<string, (args: unknown) => unknown> = {};
|
||||
const schemas: Record<string, { description: string }> = {};
|
||||
const mockServer = {
|
||||
registerTool: vi.fn(
|
||||
(name: string, schema: { description: string }, handler: (args: unknown) => unknown) => {
|
||||
handlers[name] = handler;
|
||||
schemas[name] = schema;
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
const ctx = { userId: "user-test-1" };
|
||||
|
||||
function textOf(result: unknown): string {
|
||||
return (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
}
|
||||
|
||||
function parsedOf(result: unknown): unknown {
|
||||
return JSON.parse(textOf(result));
|
||||
}
|
||||
|
||||
// Re-usable geocode response fixture (Auckland, NZ)
|
||||
const aucklandGeoRaw = {
|
||||
lat: "-36.8485",
|
||||
lon: "174.7633",
|
||||
name: "Auckland",
|
||||
display_name: "Auckland, Auckland, New Zealand",
|
||||
boundingbox: ["-37.0", "-36.5", "174.5", "175.0"] as [string, string, string, string],
|
||||
importance: 0.8,
|
||||
address: { country: "New Zealand" },
|
||||
namedetails: { "name:en": "Auckland" },
|
||||
type: "city",
|
||||
addresstype: "place",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.keys(handlers).forEach((k) => delete handlers[k]);
|
||||
Object.keys(schemas).forEach((k) => delete schemas[k]);
|
||||
|
||||
// Defaults -- individual tests override as needed
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
mockGetEntitiesInRegion.mockResolvedValue({ entities: [], emptyReason: "no_data_matches" });
|
||||
mockReadActiveSessions.mockResolvedValue([]);
|
||||
mockReadGlobeState.mockResolvedValue(null);
|
||||
mockReadSessionCatalog.mockResolvedValue(null);
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
mockEnqueueGlobeCommand.mockResolvedValue(undefined);
|
||||
mockFetchGeocode.mockResolvedValue([aucklandGeoRaw]);
|
||||
|
||||
registerDiscoveryTools(mockServer as never, ctx);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// list_available_plugins
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("list_available_plugins", () => {
|
||||
it("registers the tool with a non-empty description containing Example:", () => {
|
||||
expect(schemas["list_available_plugins"].description.length).toBeGreaterThan(0);
|
||||
expect(schemas["list_available_plugins"].description).toContain("Example:");
|
||||
});
|
||||
|
||||
it("returns plugin list with counts and entityTypes when streaming", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{
|
||||
pluginId: "flights",
|
||||
entities: [
|
||||
{ id: "e1", pluginId: "flights", latitude: 0, longitude: 0, timestamp: new Date(), properties: { status: "airborne" } },
|
||||
{ id: "e2", pluginId: "flights", latitude: 1, longitude: 1, timestamp: new Date(), properties: { status: "landed" } },
|
||||
],
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await handlers["list_available_plugins"]({});
|
||||
const parsed = parsedOf(result) as { plugins: Array<{ pluginId: string; entityCount: number; entityTypes: string[] }> };
|
||||
|
||||
expect(parsed.plugins).toHaveLength(1);
|
||||
expect(parsed.plugins[0].pluginId).toBe("flights");
|
||||
expect(parsed.plugins[0].entityCount).toBe(2);
|
||||
expect(parsed.plugins[0].entityTypes).toContain("status");
|
||||
});
|
||||
|
||||
it("returns { plugins: [], reason: 'engine_unreachable' } when engine is down (TOOL-05)", async () => {
|
||||
// In the test environment the probe fetch fails, so reason becomes engine_unreachable.
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["list_available_plugins"]({});
|
||||
const parsed = parsedOf(result) as { plugins: unknown[]; reason: string };
|
||||
|
||||
expect(parsed.plugins).toHaveLength(0);
|
||||
expect(parsed.reason).toBe("engine_unreachable");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// get_globe_context
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("get_globe_context", () => {
|
||||
it("returns sessionCount:0 + camera:null when no active sessions", async () => {
|
||||
mockReadActiveSessions.mockResolvedValue([]);
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["get_globe_context"]({});
|
||||
const parsed = parsedOf(result) as { sessionCount: number; camera: null; layers: Record<string, unknown>; plugins: unknown[] };
|
||||
|
||||
expect(parsed.sessionCount).toBe(0);
|
||||
expect(parsed.camera).toBeNull();
|
||||
expect(parsed.layers).toEqual({});
|
||||
});
|
||||
|
||||
it("returns sessionCount + camera + layers when session active", async () => {
|
||||
mockReadActiveSessions.mockResolvedValue([{ sessionId: "sess-1", lastSeen: Date.now() }]);
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{
|
||||
pluginId: "maritime",
|
||||
entities: [],
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
mockReadGlobeState.mockResolvedValue({
|
||||
viewport: { lat: -36.8, lon: 174.7, altitude: 500000, heading: 0, pitch: -45, roll: 0 },
|
||||
layers: { maritime: { enabled: true } as never },
|
||||
timeline: { currentTime: "2026-01-01T00:00:00Z", timeWindow: "1h", isPlaybackMode: false, playbackTime: 0, playbackSpeed: 1 },
|
||||
selectedEntity: null,
|
||||
lastUpdate: Date.now(),
|
||||
});
|
||||
mockReadSessionCatalog.mockResolvedValue({ tools: [], capabilities: [] });
|
||||
|
||||
const result = await handlers["get_globe_context"]({});
|
||||
const parsed = parsedOf(result) as { sessionCount: number; camera: { lat: number } | null; layers: Record<string, unknown>; plugins: unknown[] };
|
||||
|
||||
expect(parsed.sessionCount).toBe(1);
|
||||
expect(parsed.camera).not.toBeNull();
|
||||
expect(parsed.camera?.lat).toBeCloseTo(-36.8);
|
||||
expect(parsed.layers).toHaveProperty("maritime");
|
||||
});
|
||||
|
||||
it("includes a filters field with a note about server-tracking limitations", async () => {
|
||||
mockReadActiveSessions.mockResolvedValue([]);
|
||||
mockGetAllSnapshots.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["get_globe_context"]({});
|
||||
const parsed = parsedOf(result) as { filters: { note: string } };
|
||||
|
||||
expect(parsed.filters.note).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// investigate_area
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("investigate_area", () => {
|
||||
it("happy path: returns entities + summary with count when plugin matches and data found", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{
|
||||
pluginId: "flights",
|
||||
entities: [],
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
mockGetEntitiesInRegion.mockResolvedValue({
|
||||
entities: [
|
||||
{ id: "f1", pluginId: "flights", latitude: -36.8, longitude: 174.7 },
|
||||
{ id: "f2", pluginId: "flights", latitude: -36.9, longitude: 174.6 },
|
||||
],
|
||||
});
|
||||
mockResolveActiveSessionId.mockResolvedValue("sess-1");
|
||||
|
||||
const result = await handlers["investigate_area"]({ place_name: "Auckland", entity_type: "flights" });
|
||||
const parsed = parsedOf(result) as { entities: unknown[]; summary: string };
|
||||
|
||||
expect(parsed.entities).toHaveLength(2);
|
||||
expect(parsed.summary.length).toBeGreaterThan(0);
|
||||
expect(parsed.summary).toContain("2");
|
||||
expect(mockEnqueueGlobeCommand).toHaveBeenCalledWith("user-test-1", "sess-1", expect.objectContaining({ type: "pan" }));
|
||||
});
|
||||
|
||||
it("no-matching-plugin: returns empty entities + prose explaining missing entity_type", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{ pluginId: "maritime", entities: [], timestamp: new Date() },
|
||||
]);
|
||||
|
||||
const result = await handlers["investigate_area"]({ place_name: "Auckland", entity_type: "submarines" });
|
||||
const parsed = parsedOf(result) as { entities: unknown[]; summary: string };
|
||||
|
||||
expect(parsed.entities).toHaveLength(0);
|
||||
expect(parsed.summary).toContain("submarines");
|
||||
expect(parsed.summary).toContain("list_available_plugins");
|
||||
expect(mockEnqueueGlobeCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("no-data-matches: returns empty entities + prose explaining empty result", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{ pluginId: "flights", entities: [], timestamp: new Date() },
|
||||
]);
|
||||
mockGetEntitiesInRegion.mockResolvedValue({ entities: [], emptyReason: "no_data_matches" });
|
||||
mockResolveActiveSessionId.mockResolvedValue("sess-1");
|
||||
|
||||
const result = await handlers["investigate_area"]({ place_name: "Auckland", entity_type: "flights" });
|
||||
const parsed = parsedOf(result) as { entities: unknown[]; summary: string };
|
||||
|
||||
expect(parsed.entities).toHaveLength(0);
|
||||
expect(parsed.summary.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("no-session: returns entities but does NOT call enqueueGlobeCommand; summary notes skip", async () => {
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{ pluginId: "flights", entities: [], timestamp: new Date() },
|
||||
]);
|
||||
mockGetEntitiesInRegion.mockResolvedValue({
|
||||
entities: [{ id: "f1", pluginId: "flights", latitude: -36.8, longitude: 174.7 }],
|
||||
});
|
||||
mockResolveActiveSessionId.mockResolvedValue(null); // no active session
|
||||
|
||||
const result = await handlers["investigate_area"]({ place_name: "Auckland", entity_type: "flights" });
|
||||
const parsed = parsedOf(result) as { entities: unknown[]; summary: string };
|
||||
|
||||
expect(parsed.entities).toHaveLength(1);
|
||||
expect(mockEnqueueGlobeCommand).not.toHaveBeenCalled();
|
||||
expect(parsed.summary).toContain("camera pan skipped");
|
||||
});
|
||||
|
||||
it("geocode failure: returns empty entities + helpful summary", async () => {
|
||||
mockFetchGeocode.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["investigate_area"]({ place_name: "ZZZ_NONEXISTENT", entity_type: "flights" });
|
||||
const parsed = parsedOf(result) as { entities: unknown[]; summary: string };
|
||||
|
||||
expect(parsed.entities).toHaveLength(0);
|
||||
expect(parsed.summary).toContain("ZZZ_NONEXISTENT");
|
||||
});
|
||||
|
||||
it("truncation (TOOL-04/P33): returns truncated:true and cappedTotal when result exceeds 200 cap", async () => {
|
||||
// Two plugins both named with "vessel" substring so entity_type:"vessel" matches both.
|
||||
// Each returns 110 entities = 220 total, exceeding INVESTIGATE_AREA_CAP (200).
|
||||
const makeEntities = (pluginId: string, count: number) =>
|
||||
Array.from({ length: count }, (_, i) => ({
|
||||
id: `${pluginId}-${i}`,
|
||||
pluginId,
|
||||
latitude: 0,
|
||||
longitude: 0,
|
||||
}));
|
||||
|
||||
mockGetAllSnapshots.mockResolvedValue([
|
||||
{ pluginId: "vessel-ais", entities: [], timestamp: new Date() },
|
||||
{ pluginId: "vessel-cargo", entities: [], timestamp: new Date() },
|
||||
]);
|
||||
mockGetEntitiesInRegion
|
||||
.mockResolvedValueOnce({ entities: makeEntities("vessel-ais", 110) })
|
||||
.mockResolvedValueOnce({ entities: makeEntities("vessel-cargo", 110) });
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["investigate_area"]({
|
||||
place_name: "Auckland",
|
||||
entity_type: "vessel",
|
||||
});
|
||||
const parsed = parsedOf(result) as {
|
||||
entities: unknown[];
|
||||
count: number;
|
||||
truncated?: boolean;
|
||||
cappedTotal?: number;
|
||||
summary: string;
|
||||
};
|
||||
|
||||
expect(parsed.entities).toHaveLength(200);
|
||||
expect(parsed.count).toBe(200);
|
||||
expect(parsed.truncated).toBe(true);
|
||||
expect(parsed.cappedTotal).toBe(220);
|
||||
});
|
||||
});
|
||||
@@ -1,236 +0,0 @@
|
||||
/**
|
||||
* MCP Discovery Tool registrar (Phase 29 -- 29-01).
|
||||
*
|
||||
* Registers three compound/discovery MCP tools:
|
||||
* list_available_plugins -- list all streaming plugins with entity counts + types
|
||||
* get_globe_context -- full orientation snapshot in one call
|
||||
* investigate_area -- geocode + query + camera pan in one call
|
||||
*
|
||||
* Security:
|
||||
* - userId comes ONLY from ctx (verified auth result); never from tool args.
|
||||
* - place_name / entity_type / radius_km are untrusted; place_name is passed
|
||||
* exclusively via URLSearchParams in fetchGeocode (no string concat into URL).
|
||||
* - entity_type is matched only against the in-memory streaming plugin set;
|
||||
* never embedded in an engine URL (T-29-01, T-29-02, T-29-03).
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { getEntitiesInRegion } from "@/lib/data-query/service";
|
||||
import { fetchGeocode, normalizeNominatimResult } from "@/lib/nominatim";
|
||||
import { enqueueGlobeCommand } from "@/lib/globeCommandQueue";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import {
|
||||
listStreamingPlugins,
|
||||
radiusKmToBbox,
|
||||
buildInvestigateProse,
|
||||
composeGlobeContext,
|
||||
resolveActiveSessionId,
|
||||
} from "./discoveryHelpers";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type McpTextResult = { content: [{ type: "text"; text: string }] };
|
||||
|
||||
function textResult(payload: unknown): McpTextResult {
|
||||
return {
|
||||
content: [{ type: "text", text: JSON.stringify(payload) }],
|
||||
};
|
||||
}
|
||||
|
||||
/** Default investigation radius when the caller does not specify one. */
|
||||
const DEFAULT_RADIUS_KM = 50;
|
||||
|
||||
/** Altitude (metres) used for camera pan commands from investigate_area. */
|
||||
const INVESTIGATE_PAN_ALT = 300_000;
|
||||
|
||||
/** Maximum total entities returned across all plugins by investigate_area (TOOL-04). */
|
||||
const INVESTIGATE_AREA_CAP = 200;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerDiscoveryTools(
|
||||
server: McpServer,
|
||||
ctx: { userId: string },
|
||||
): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// TOOL-01: list_available_plugins
|
||||
// ------------------------------------------------------------------
|
||||
server.registerTool(
|
||||
"list_available_plugins",
|
||||
{
|
||||
description:
|
||||
"List all plugins currently streaming live data from the engine. Returns pluginId, pluginName, entityCount, and entityTypes (queryable field names) for each active plugin. " +
|
||||
"Use this tool BEFORE search_entities or get_entities_in_region to verify the target plugin is actually streaming -- calling those tools with a non-streaming plugin always returns plugin_not_streaming. " +
|
||||
"When the data engine is unreachable the result contains an empty plugins array and a reason field. " +
|
||||
"No parameters required. " +
|
||||
"Example: list_available_plugins({})",
|
||||
inputSchema: {},
|
||||
},
|
||||
async () => {
|
||||
try {
|
||||
const result = await listStreamingPlugins();
|
||||
return textResult(result);
|
||||
} catch (err) {
|
||||
console.error("[discoveryTools] list_available_plugins failed:", err);
|
||||
return textResult({ plugins: [], reason: "unexpected error" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// TOOL-02: get_globe_context
|
||||
// ------------------------------------------------------------------
|
||||
server.registerTool(
|
||||
"get_globe_context",
|
||||
{
|
||||
description:
|
||||
"Retrieve the full current globe context in one call: sessionCount, camera viewport, active layers, filter definitions (note: applied values are NOT server-tracked), and streaming plugin list. " +
|
||||
"Use this tool at the start of a session to orient yourself without reading multiple globe:// resources separately. " +
|
||||
"When no browser session is active, returns sessionCount:0 and camera:null without error -- open the app in a browser tab first to create a session. " +
|
||||
"Filters field shows definitions (field names/types) only; applied filter values are browser-side and not tracked by the server. " +
|
||||
"No parameters required. " +
|
||||
"Example: get_globe_context({})",
|
||||
inputSchema: {},
|
||||
},
|
||||
async () => {
|
||||
try {
|
||||
const payload = await composeGlobeContext(userId);
|
||||
return textResult(payload);
|
||||
} catch (err) {
|
||||
console.error("[discoveryTools] get_globe_context failed:", err);
|
||||
return textResult({
|
||||
sessionCount: 0,
|
||||
camera: null,
|
||||
layers: {},
|
||||
filters: { note: "context unavailable" },
|
||||
plugins: [],
|
||||
reason: "unexpected error",
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// TOOL-03: investigate_area
|
||||
// ------------------------------------------------------------------
|
||||
server.registerTool(
|
||||
"investigate_area",
|
||||
{
|
||||
description:
|
||||
"Investigate what is happening near a named place for a given entity type. Geocodes the place, finds a matching streaming plugin, queries entities in the bounding region, pans the camera when a session is active, and returns entities + a human-readable summary. " +
|
||||
"Use this tool when an agent asks 'what is near X?' or 'show me Y around Z'. Prefer this over manual geocode + search_entities sequences. " +
|
||||
"When no matching plugin streams the given entity_type, the summary explains this and suggests list_available_plugins. " +
|
||||
"When no active session is found, entities are still returned but the summary notes the camera pan was skipped. " +
|
||||
"Response is capped at 200 entities total across all matched plugins. When 'truncated' is true, 'cappedTotal' holds the sum of per-plugin results before the global cap (not the true global count, because each plugin is itself queried with its own 100-entity limit). " +
|
||||
"Parameters: place_name (required), entity_type (required, case-insensitive substring match against plugin ids/names), radius_km (optional, default 50). " +
|
||||
"Example: investigate_area({place_name:\"Auckland\",entity_type:\"flights\",radius_km:100})",
|
||||
inputSchema: {
|
||||
place_name: z.string().min(1).describe("Place name to geocode (free-text, e.g. 'Auckland', 'Tokyo Bay')"),
|
||||
entity_type: z.string().min(1).describe("Entity type to look for -- case-insensitive substring matched against streaming plugin ids/names"),
|
||||
radius_km: z.number().positive().optional().describe("Search radius in kilometres around the geocoded centre (default 50)"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
const { place_name, entity_type, radius_km } = args;
|
||||
const radius = radius_km ?? DEFAULT_RADIUS_KM;
|
||||
|
||||
try {
|
||||
// Step 1: Geocode the place name (limit 1 result).
|
||||
const rawItems = await fetchGeocode({ query: place_name, limit: 1 });
|
||||
if (rawItems.length === 0) {
|
||||
return textResult({
|
||||
entities: [],
|
||||
summary: `Could not geocode "${place_name}". Try a more specific or differently spelled place name.`,
|
||||
});
|
||||
}
|
||||
const geo = normalizeNominatimResult(rawItems[0]);
|
||||
|
||||
// Step 2: Find matching streaming plugins by case-insensitive substring.
|
||||
const { plugins } = await listStreamingPlugins();
|
||||
const lower = entity_type.toLowerCase();
|
||||
const matched = plugins.filter(
|
||||
(p) =>
|
||||
p.pluginId.toLowerCase().includes(lower) ||
|
||||
p.pluginName.toLowerCase().includes(lower),
|
||||
);
|
||||
|
||||
if (matched.length === 0) {
|
||||
return textResult({
|
||||
entities: [],
|
||||
summary: buildInvestigateProse({
|
||||
displayName: geo.display_name,
|
||||
entityType: entity_type,
|
||||
matchedPlugin: null,
|
||||
entityCount: 0,
|
||||
sessionPresent: false,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
// Step 3: Compute bbox and query region for each matched plugin.
|
||||
const bbox = radiusKmToBbox(geo.lat, geo.lng, radius);
|
||||
type SearchResult = { id: string; pluginId: string; name?: string; latitude: number; longitude: number };
|
||||
const allEntities: SearchResult[] = [];
|
||||
let lastEmptyReason: string | undefined;
|
||||
|
||||
for (const plugin of matched) {
|
||||
const result = await getEntitiesInRegion({ ...bbox, pluginId: plugin.pluginId });
|
||||
allEntities.push(...result.entities);
|
||||
if (result.emptyReason) lastEmptyReason = result.emptyReason;
|
||||
}
|
||||
|
||||
// Step 4: Pan camera when a session is active.
|
||||
const sessionId = await resolveActiveSessionId(userId);
|
||||
const sessionPresent = sessionId !== null;
|
||||
if (sessionId !== null) {
|
||||
const cmd: GlobeCommand = {
|
||||
type: "pan",
|
||||
lat: geo.lat,
|
||||
lon: geo.lng,
|
||||
alt: INVESTIGATE_PAN_ALT,
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
}
|
||||
|
||||
// Step 5: Apply overall cap and record truncation metadata.
|
||||
// cappedTotal is the sum of per-plugin results before the global cap.
|
||||
// It is NOT the true global count because each plugin is queried with
|
||||
// its own 100-entity limit before reaching here.
|
||||
const cappedTotal = allEntities.length;
|
||||
const truncated = cappedTotal > INVESTIGATE_AREA_CAP;
|
||||
const entities = truncated ? allEntities.slice(0, INVESTIGATE_AREA_CAP) : allEntities;
|
||||
|
||||
// Step 6: Build prose summary using first matched plugin as representative.
|
||||
const representativePlugin = matched[0].pluginId;
|
||||
const summary = buildInvestigateProse({
|
||||
displayName: geo.display_name,
|
||||
entityType: entity_type,
|
||||
matchedPlugin: representativePlugin,
|
||||
entityCount: entities.length,
|
||||
sessionPresent,
|
||||
emptyReason: lastEmptyReason,
|
||||
});
|
||||
|
||||
return textResult({
|
||||
entities,
|
||||
count: entities.length,
|
||||
...(truncated && { truncated: true, cappedTotal }),
|
||||
summary,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[discoveryTools] investigate_area failed:", err);
|
||||
return textResult({
|
||||
entities: [],
|
||||
summary: `investigate_area encountered an unexpected error for "${place_name}". Please retry shortly.`,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/prisma");
|
||||
vi.mock("@/lib/globeStateStore");
|
||||
vi.mock("@/lib/data-query/service");
|
||||
|
||||
import { registerFavoritesTools } from "./favoritesTools";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { readActiveSessions } from "@/lib/globeStateStore";
|
||||
import { getEntityDetails } from "@/lib/data-query/service";
|
||||
|
||||
const mockPrisma = vi.mocked(prisma, true);
|
||||
const mockReadActiveSessions = vi.mocked(readActiveSessions);
|
||||
const mockGetEntityDetails = vi.mocked(getEntityDetails);
|
||||
|
||||
const handlers: Record<string, (args: unknown) => unknown> = {};
|
||||
const schemas: Record<string, { description: string }> = {};
|
||||
const mockServer = {
|
||||
registerTool: vi.fn((name: string, schema: { description: string }, handler: (args: unknown) => unknown) => {
|
||||
handlers[name] = handler;
|
||||
schemas[name] = schema;
|
||||
}),
|
||||
};
|
||||
|
||||
const ctx = { userId: "u1" };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.keys(handlers).forEach((k) => delete handlers[k]);
|
||||
Object.keys(schemas).forEach((k) => delete schemas[k]);
|
||||
registerFavoritesTools(mockServer as never, ctx);
|
||||
});
|
||||
|
||||
describe("favoritesTools tool descriptions (DESC-03)", () => {
|
||||
const toolNames = ["save_favorite", "list_favorites", "remove_favorite"];
|
||||
|
||||
it.each(toolNames)("%s description is non-empty and within 1024 chars", (name) => {
|
||||
const desc = schemas[name].description;
|
||||
expect(desc.length).toBeGreaterThan(0);
|
||||
expect(desc.length).toBeLessThanOrEqual(1024);
|
||||
});
|
||||
|
||||
it.each(toolNames)("%s description contains 'Example:'", (name) => {
|
||||
expect(schemas[name].description).toContain("Example:");
|
||||
});
|
||||
|
||||
it("list_favorites description mentions both 'live' and 'stale'", () => {
|
||||
const desc = schemas["list_favorites"].description;
|
||||
expect(desc).toContain("live");
|
||||
expect(desc).toContain("stale");
|
||||
});
|
||||
});
|
||||
|
||||
describe("save_favorite tool handler", () => {
|
||||
it("calls prisma.favorite.upsert with userId from context, not from args", async () => {
|
||||
// findUnique returns null -> new row, count returns 0 -> below cap
|
||||
mockPrisma.favorite.findUnique.mockResolvedValue(null as never);
|
||||
mockPrisma.favorite.count.mockResolvedValue(0 as never);
|
||||
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
|
||||
|
||||
await handlers["save_favorite"]({
|
||||
entityId: "ship:123",
|
||||
pluginId: "maritime",
|
||||
userId: "attacker",
|
||||
});
|
||||
|
||||
expect(mockPrisma.favorite.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({ userId: "u1" }),
|
||||
create: expect.objectContaining({ userId: "u1" }),
|
||||
}),
|
||||
);
|
||||
expect(mockPrisma.favorite.upsert).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ create: expect.objectContaining({ userId: "attacker" }) }),
|
||||
);
|
||||
});
|
||||
|
||||
it("sets pluginName to pluginId as fallback when name is omitted", async () => {
|
||||
mockPrisma.favorite.findUnique.mockResolvedValue(null as never);
|
||||
mockPrisma.favorite.count.mockResolvedValue(0 as never);
|
||||
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
|
||||
|
||||
await handlers["save_favorite"]({ entityId: "ship:456", pluginId: "maritime" });
|
||||
|
||||
expect(mockPrisma.favorite.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({ pluginName: "maritime" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects when user is at the 500-favorite cap and entity is new", async () => {
|
||||
mockPrisma.favorite.findUnique.mockResolvedValue(null as never);
|
||||
mockPrisma.favorite.count.mockResolvedValue(500 as never);
|
||||
|
||||
const result = await handlers["save_favorite"]({
|
||||
entityId: "newship:999",
|
||||
pluginId: "maritime",
|
||||
});
|
||||
|
||||
expect(mockPrisma.favorite.upsert).not.toHaveBeenCalled();
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text).toContain("favorite limit of 500 reached");
|
||||
});
|
||||
|
||||
it("allows upsert when entity already exists (no count check needed)", async () => {
|
||||
// findUnique returns an existing row -> cap check is skipped
|
||||
mockPrisma.favorite.findUnique.mockResolvedValue({ id: "existing" } as never);
|
||||
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
|
||||
|
||||
await handlers["save_favorite"]({
|
||||
entityId: "ship:123",
|
||||
pluginId: "maritime",
|
||||
});
|
||||
|
||||
expect(mockPrisma.favorite.count).not.toHaveBeenCalled();
|
||||
expect(mockPrisma.favorite.upsert).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("list_favorites tool handler", () => {
|
||||
it("includes notes field on returned items", async () => {
|
||||
mockPrisma.favorite.findMany.mockResolvedValue([
|
||||
{ id: "1", entityId: "ship:123", pluginId: "maritime", userId: "u1", pluginName: "Maritime", notes: "Watch this ship", lastSeen: new Date() },
|
||||
] as never);
|
||||
mockReadActiveSessions.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["list_favorites"]({});
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
const parsed = JSON.parse(text);
|
||||
expect(parsed[0]).toHaveProperty("notes", "Watch this ship");
|
||||
});
|
||||
|
||||
it("returns status 'live' for entity when active session exists", async () => {
|
||||
mockPrisma.favorite.findMany.mockResolvedValue([
|
||||
{ id: "1", entityId: "ship:123", pluginId: "maritime", userId: "u1", pluginName: "Maritime", createdAt: new Date() },
|
||||
] as never);
|
||||
mockReadActiveSessions.mockResolvedValue([{ sessionId: "sess-abc", lastSeen: Date.now() }]);
|
||||
mockGetEntityDetails.mockResolvedValue({ data: { entityId: "ship:123", lat: 1, lon: 2 } } as never);
|
||||
|
||||
const result = await handlers["list_favorites"]({});
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
const parsed = JSON.parse(text);
|
||||
expect(parsed[0].status).toBe("live");
|
||||
});
|
||||
|
||||
it("returns status 'stale' for all entities when no active session exists", async () => {
|
||||
mockPrisma.favorite.findMany.mockResolvedValue([
|
||||
{ id: "1", entityId: "ship:123", pluginId: "maritime", userId: "u1", pluginName: "Maritime", createdAt: new Date() },
|
||||
] as never);
|
||||
mockReadActiveSessions.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["list_favorites"]({});
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
const parsed = JSON.parse(text);
|
||||
expect(parsed[0].status).toBe("stale");
|
||||
});
|
||||
|
||||
it("returns status 'stale' when getEntityDetails returns null", async () => {
|
||||
mockPrisma.favorite.findMany.mockResolvedValue([
|
||||
{ id: "1", entityId: "ship:123", pluginId: "maritime", userId: "u1", pluginName: "Maritime", createdAt: new Date() },
|
||||
] as never);
|
||||
mockReadActiveSessions.mockResolvedValue([{ sessionId: "sess-abc", lastSeen: Date.now() }]);
|
||||
mockGetEntityDetails.mockResolvedValue({ data: null, emptyReason: "plugin_not_streaming" } as never);
|
||||
|
||||
const result = await handlers["list_favorites"]({});
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
const parsed = JSON.parse(text);
|
||||
expect(parsed[0].status).toBe("stale");
|
||||
});
|
||||
});
|
||||
|
||||
describe("update_favorite tool handler", () => {
|
||||
it("happy path: updates both label and notes", async () => {
|
||||
mockPrisma.favorite.update.mockResolvedValue({ label: "New Name" } as never);
|
||||
|
||||
const result = await handlers["update_favorite"]({
|
||||
favoriteId: "ship:123",
|
||||
name: "New Name",
|
||||
notes: "Check weekly",
|
||||
});
|
||||
|
||||
expect(mockPrisma.favorite.update).toHaveBeenCalledWith({
|
||||
where: expect.objectContaining({ userId: "u1", entityId: "ship:123" }),
|
||||
data: { label: "New Name", notes: "Check weekly" },
|
||||
});
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text).toBe("Updated favorite: New Name");
|
||||
});
|
||||
|
||||
it("name-only: calls update with label only, not notes", async () => {
|
||||
mockPrisma.favorite.update.mockResolvedValue({ label: "Renamed" } as never);
|
||||
|
||||
await handlers["update_favorite"]({ favoriteId: "ship:123", name: "Renamed" });
|
||||
|
||||
const call = mockPrisma.favorite.update.mock.calls[0][0] as { data: Record<string, unknown> };
|
||||
expect(call.data).toHaveProperty("label", "Renamed");
|
||||
expect(call.data).not.toHaveProperty("notes");
|
||||
});
|
||||
|
||||
it("notes-only: calls update with notes only, not label", async () => {
|
||||
mockPrisma.favorite.update.mockResolvedValue({ label: "Existing" } as never);
|
||||
|
||||
await handlers["update_favorite"]({ favoriteId: "ship:123", notes: "My annotation" });
|
||||
|
||||
const call = mockPrisma.favorite.update.mock.calls[0][0] as { data: Record<string, unknown> };
|
||||
expect(call.data).toHaveProperty("notes", "My annotation");
|
||||
expect(call.data).not.toHaveProperty("label");
|
||||
});
|
||||
|
||||
it("empty-args: returns 'nothing to update' and does NOT call prisma.favorite.update", async () => {
|
||||
const result = await handlers["update_favorite"]({ favoriteId: "ship:123" });
|
||||
|
||||
expect(mockPrisma.favorite.update).not.toHaveBeenCalled();
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text).toContain("nothing to update");
|
||||
});
|
||||
|
||||
it("not-found: P2025 error returns 'update_favorite: favorite not found'", async () => {
|
||||
const p2025 = Object.assign(new Error("not found"), { code: "P2025" });
|
||||
mockPrisma.favorite.update.mockRejectedValue(p2025);
|
||||
|
||||
const result = await handlers["update_favorite"]({
|
||||
favoriteId: "ship:999",
|
||||
name: "Ghost",
|
||||
});
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text).toBe("update_favorite: favorite not found");
|
||||
});
|
||||
|
||||
it("uses (userId, entityId) selector from ctx, never from args", async () => {
|
||||
mockPrisma.favorite.update.mockResolvedValue({ label: "X" } as never);
|
||||
|
||||
await handlers["update_favorite"]({ favoriteId: "ship:123", name: "X" });
|
||||
|
||||
expect(mockPrisma.favorite.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({ userId: "u1", entityId: "ship:123" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("remove_favorite tool handler", () => {
|
||||
it("calls prisma.favorite.delete with correct where clause including userId and entityId", async () => {
|
||||
mockPrisma.favorite.delete.mockResolvedValue({} as never);
|
||||
|
||||
await handlers["remove_favorite"]({ entityId: "ship:123" });
|
||||
|
||||
expect(mockPrisma.favorite.delete).toHaveBeenCalledWith({
|
||||
where: expect.objectContaining({
|
||||
userId: "u1",
|
||||
entityId: "ship:123",
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,239 +0,0 @@
|
||||
/**
|
||||
* MCP Favorites Tool registrar (Phase 22 Wave 2 -- 22-03).
|
||||
*
|
||||
* Registers four MCP tools that let an AI agent bookmark entities for a user:
|
||||
*
|
||||
* save_favorite -- upsert an entity bookmark (FAV-01)
|
||||
* list_favorites -- list bookmarks with per-entity liveness status (FAV-02)
|
||||
* remove_favorite -- delete a bookmark (FAV-03)
|
||||
* update_favorite -- rename/annotate an existing bookmark (CRUD-01)
|
||||
*
|
||||
* Security (SAFE-02): userId comes ONLY from ctx (the verified auth result). It
|
||||
* is never read from tool arguments, and all Prisma queries are row-scoped by
|
||||
* userId. Favorites are persisted directly via prisma.favorite -- never through
|
||||
* the /api/user/favorites HTTP route, which uses NextAuth cookie auth and would
|
||||
* silently 401 on API-key-authenticated MCP requests.
|
||||
*
|
||||
* Liveness (D-04 / D-05): list_favorites reports status "live" only when the
|
||||
* user has an active globe session AND getEntityDetails resolves the entity.
|
||||
* With no active session, ALL favorites are reported "stale" (no "unknown").
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { readActiveSessions } from "@/lib/globeStateStore";
|
||||
import { getEntityDetails } from "@/lib/data-query/service";
|
||||
import type { Prisma } from "@/generated/prisma";
|
||||
import { pluginIdSchema, entityIdSchema } from "@/lib/mcp/identifierSchemas";
|
||||
|
||||
const FAVORITES_CAP = 500;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type McpTextResult = { content: [{ type: "text"; text: string }] };
|
||||
|
||||
function textResult(text: string): McpTextResult {
|
||||
return { content: [{ type: "text", text }] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the unique-where selector for the (userId, entityId) compound key.
|
||||
*
|
||||
* Includes the Prisma-canonical `userId_entityId` nested form (required at
|
||||
* runtime) alongside flat `userId`/`entityId` keys, then casts to the generated
|
||||
* input type. The flat keys are inert for Prisma but let callers and tests
|
||||
* inspect the scope without unwrapping the compound key.
|
||||
*/
|
||||
function favoriteWhere(userId: string, entityId: string): Prisma.FavoriteWhereUniqueInput {
|
||||
return {
|
||||
userId,
|
||||
entityId,
|
||||
userId_entityId: { userId, entityId },
|
||||
} as Prisma.FavoriteWhereUniqueInput;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerFavoritesTools(
|
||||
server: McpServer,
|
||||
ctx: { userId: string },
|
||||
): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
// TOOL: save_favorite (FAV-01)
|
||||
server.registerTool(
|
||||
"save_favorite",
|
||||
{
|
||||
description:
|
||||
"Bookmark an entity so the user can return to it later (upsert by entityId -- re-saving updates, not duplicates). " +
|
||||
"Use when the user wants to track a specific entity across sessions. " +
|
||||
"Limitations: entityId must be the exact id used by the plugin; no validation is performed against live data. " +
|
||||
"Parameters: entityId (string, required); pluginId (string, required); name (string, optional, defaults to entityId). " +
|
||||
"Output: 'Saved favorite: <label>'. " +
|
||||
"Example: save_favorite({ entityId: 'AFR123', pluginId: 'flights', name: 'Air France 123' }).",
|
||||
inputSchema: {
|
||||
entityId: entityIdSchema.describe("Unique entity identifier"),
|
||||
pluginId: pluginIdSchema.describe("Plugin that owns this entity"),
|
||||
name: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(120)
|
||||
.optional()
|
||||
.describe("Human-readable label for the bookmark (defaults to entityId)"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
// Cap: reject new rows when the user already has FAVORITES_CAP favorites.
|
||||
// Upserts that update an existing row are always allowed.
|
||||
const existing = await prisma.favorite.findUnique({
|
||||
where: favoriteWhere(userId, args.entityId),
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existing) {
|
||||
const count = await prisma.favorite.count({ where: { userId } });
|
||||
if (count >= FAVORITES_CAP) {
|
||||
return textResult(`favorite limit of ${FAVORITES_CAP} reached`);
|
||||
}
|
||||
}
|
||||
|
||||
const label = args.name ?? args.entityId;
|
||||
await prisma.favorite.upsert({
|
||||
where: favoriteWhere(userId, args.entityId),
|
||||
update: {
|
||||
pluginId: args.pluginId,
|
||||
label,
|
||||
lastSeen: new Date(),
|
||||
},
|
||||
create: {
|
||||
userId,
|
||||
entityId: args.entityId,
|
||||
pluginId: args.pluginId,
|
||||
label,
|
||||
pluginName: args.pluginId,
|
||||
lastSeen: new Date(),
|
||||
},
|
||||
});
|
||||
return textResult(`Saved favorite: ${label}`);
|
||||
} catch (err) {
|
||||
console.error("[favoritesTools] save_favorite failed:", err);
|
||||
return textResult("save_favorite failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL: list_favorites (FAV-02)
|
||||
server.registerTool(
|
||||
"list_favorites",
|
||||
{
|
||||
description:
|
||||
"List the authenticated user's bookmarked entities, most recently seen first. " +
|
||||
"Use to find entityIds before calling remove_favorite, or to review which entities are currently live. " +
|
||||
"Limitations: status is 'live' only with an active globe session; with no active session ALL entries are reported 'stale'. Returns [] when there are no favorites. " +
|
||||
"Parameters: none. " +
|
||||
"Output: JSON array, each { id, entityId, pluginId, label, pluginName, lastSeen, notes, status: 'live'|'stale' }. " +
|
||||
"Example: list_favorites({}) -> [{ entityId: 'AFR123', pluginId: 'flights', label: 'Air France 123', notes: null, status: 'live' }].",
|
||||
inputSchema: {},
|
||||
},
|
||||
async () => {
|
||||
try {
|
||||
const favorites = await prisma.favorite.findMany({
|
||||
where: { userId },
|
||||
orderBy: { lastSeen: "desc" },
|
||||
});
|
||||
if (favorites.length === 0) return textResult(JSON.stringify([]));
|
||||
|
||||
const sessions = await readActiveSessions(userId);
|
||||
const hasSession = sessions.length > 0;
|
||||
|
||||
const results = await Promise.all(
|
||||
favorites.map(async (fav) => {
|
||||
if (!hasSession) {
|
||||
return { ...fav, status: "stale" as const };
|
||||
}
|
||||
const detail = await getEntityDetails(fav.pluginId, fav.entityId);
|
||||
return { ...fav, status: detail.data !== null ? ("live" as const) : ("stale" as const) };
|
||||
}),
|
||||
);
|
||||
return textResult(JSON.stringify(results));
|
||||
} catch (err) {
|
||||
console.error("[favoritesTools] list_favorites failed:", err);
|
||||
return textResult("list_favorites failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL: update_favorite (CRUD-01)
|
||||
server.registerTool(
|
||||
"update_favorite",
|
||||
{
|
||||
description:
|
||||
"Rename or annotate an existing bookmarked entity without deleting and re-creating it. " +
|
||||
"Use when the user wants to change the display name or add a personal note to an existing favorite. " +
|
||||
"Limitations: at least one of name or notes must be supplied; favoriteId must match an existing bookmark owned by the user. " +
|
||||
"Parameters: favoriteId (string, required, the entityId of the bookmark); name (string, optional, new display label); notes (string, optional, free-text annotation). " +
|
||||
"Output: 'Updated favorite: <label>' on success, or an error string. " +
|
||||
"Example: update_favorite({ favoriteId: 'AFR123', name: 'Air France 123', notes: 'Check weekly' }).",
|
||||
inputSchema: {
|
||||
favoriteId: entityIdSchema.describe("The entityId of the favorite to update"),
|
||||
name: z.string().min(1).max(120).optional().describe("New display label for the bookmark"),
|
||||
notes: z.string().max(2000).optional().describe("Free-text annotation to store with the bookmark"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
if (args.name === undefined && args.notes === undefined) {
|
||||
return textResult("update_favorite: nothing to update");
|
||||
}
|
||||
const data: { label?: string; notes?: string } = {};
|
||||
if (args.name !== undefined) data.label = args.name;
|
||||
if (args.notes !== undefined) data.notes = args.notes;
|
||||
try {
|
||||
const updated = await prisma.favorite.update({
|
||||
where: favoriteWhere(userId, args.favoriteId),
|
||||
data,
|
||||
});
|
||||
return textResult(`Updated favorite: ${updated.label}`);
|
||||
} catch (err) {
|
||||
const code = (err as { code?: string }).code;
|
||||
if (code === "P2025") {
|
||||
return textResult("update_favorite: favorite not found");
|
||||
}
|
||||
console.error("[favoritesTools] update_favorite failed:", err);
|
||||
return textResult("update_favorite failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL: remove_favorite (FAV-03)
|
||||
server.registerTool(
|
||||
"remove_favorite",
|
||||
{
|
||||
description:
|
||||
"Delete a bookmarked entity from the authenticated user's favorites. " +
|
||||
"Pair with list_favorites to find the correct entityId before removing. " +
|
||||
"Limitations: deletes by exact entityId; removing an entity that is not currently a favorite returns 'remove_favorite failed' (call list_favorites first to confirm it exists). " +
|
||||
"Parameters: entityId (string, required). " +
|
||||
"Output: 'Removed favorite: <entityId>'. " +
|
||||
"Example: remove_favorite({ entityId: 'AFR123' }).",
|
||||
inputSchema: {
|
||||
entityId: entityIdSchema.describe("Entity identifier to remove from favorites"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
await prisma.favorite.delete({
|
||||
where: favoriteWhere(userId, args.entityId),
|
||||
});
|
||||
return textResult(`Removed favorite: ${args.entityId}`);
|
||||
} catch (err) {
|
||||
console.error("[favoritesTools] remove_favorite failed:", err);
|
||||
return textResult("remove_favorite failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/globeCommandQueue");
|
||||
vi.mock("@/lib/mcpSessionCatalog");
|
||||
|
||||
// RED: ./filterTools does not exist yet. This import fails at collection time,
|
||||
// locking the three-tool contract (set_filter, clear_filter, get_plugin_filters).
|
||||
import { registerFilterTools } from "./filterTools";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
|
||||
const mockEnqueue = vi.mocked(enqueueGlobeCommand);
|
||||
const mockResolveActiveSessionId = vi.mocked(resolveActiveSessionId);
|
||||
const mockReadSessionCatalog = vi.mocked(readSessionCatalog);
|
||||
|
||||
const handlers: Record<string, (args: unknown) => unknown> = {};
|
||||
const schemas: Record<string, { description: string }> = {};
|
||||
const mockServer = {
|
||||
registerTool: vi.fn((name: string, schema: { description: string }, handler: (args: unknown) => unknown) => {
|
||||
handlers[name] = handler;
|
||||
schemas[name] = schema;
|
||||
}),
|
||||
};
|
||||
|
||||
const ctx = { userId: "u1" };
|
||||
|
||||
function textOf(result: unknown): string {
|
||||
return (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.keys(handlers).forEach((k) => delete handlers[k]);
|
||||
Object.keys(schemas).forEach((k) => delete schemas[k]);
|
||||
mockResolveActiveSessionId.mockResolvedValue("sess-abc");
|
||||
registerFilterTools(mockServer as never, ctx);
|
||||
});
|
||||
|
||||
describe("filterTools tool descriptions (DESC-03)", () => {
|
||||
const toolNames = ["set_filter", "clear_filter", "get_plugin_filters"];
|
||||
|
||||
it.each(toolNames)("%s description is non-empty and within 1024 chars", (name) => {
|
||||
const desc = schemas[name].description;
|
||||
expect(desc.length).toBeGreaterThan(0);
|
||||
expect(desc.length).toBeLessThanOrEqual(1024);
|
||||
});
|
||||
|
||||
it.each(toolNames)("%s description contains 'Example:'", (name) => {
|
||||
expect(schemas[name].description).toContain("Example:");
|
||||
});
|
||||
|
||||
it("get_plugin_filters description documents availability object shape", () => {
|
||||
const desc = schemas["get_plugin_filters"].description;
|
||||
expect(desc).toContain("available");
|
||||
expect(desc).toContain("no_session_active");
|
||||
});
|
||||
});
|
||||
|
||||
describe("set_filter tool handler", () => {
|
||||
it("enqueues a setFilter command with pluginId and filters", async () => {
|
||||
await handlers["set_filter"]({
|
||||
pluginId: "flights",
|
||||
filters: { status: { type: "select", values: ["airborne"] } },
|
||||
});
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"sess-abc",
|
||||
{ type: "setFilter", pluginId: "flights", filters: { status: { type: "select", values: ["airborne"] } } },
|
||||
);
|
||||
});
|
||||
|
||||
it("returns NO_SESSION text and does not enqueue when no active session", async () => {
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["set_filter"]({ pluginId: "flights", filters: {} });
|
||||
|
||||
expect(textOf(result)).toMatch(/no active globe session/i);
|
||||
expect(mockEnqueue).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("clear_filter tool handler", () => {
|
||||
it("enqueues clearFilter without a pluginId field when pluginId omitted", async () => {
|
||||
await handlers["clear_filter"]({});
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledWith("u1", "sess-abc", { type: "clearFilter" });
|
||||
});
|
||||
|
||||
it("enqueues clearFilter with pluginId when provided", async () => {
|
||||
await handlers["clear_filter"]({ pluginId: "flights" });
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledWith("u1", "sess-abc", { type: "clearFilter", pluginId: "flights" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("get_plugin_filters tool handler", () => {
|
||||
it("returns { available: true, filters: [...] } when plugin is loaded with filters", async () => {
|
||||
const defs = [{ id: "status", label: "Status", type: "select", propertyKey: "status" }];
|
||||
mockReadSessionCatalog.mockResolvedValue({
|
||||
tools: [],
|
||||
capabilities: [],
|
||||
filterDefinitions: { flights: defs },
|
||||
} as never);
|
||||
|
||||
const result = await handlers["get_plugin_filters"]({ pluginId: "flights" });
|
||||
const parsed = JSON.parse(textOf(result));
|
||||
|
||||
expect(parsed).toEqual({ available: true, filters: defs });
|
||||
});
|
||||
|
||||
it("returns { available: false, reason: 'no_session_active' } when no active session", async () => {
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["get_plugin_filters"]({ pluginId: "flights" });
|
||||
const parsed = JSON.parse(textOf(result));
|
||||
|
||||
expect(parsed).toEqual({ available: false, reason: "no_session_active" });
|
||||
});
|
||||
|
||||
it("returns { available: false, reason: 'plugin not loaded' } when plugin key absent from catalog", async () => {
|
||||
mockReadSessionCatalog.mockResolvedValue({
|
||||
tools: [],
|
||||
capabilities: [],
|
||||
filterDefinitions: {},
|
||||
} as never);
|
||||
|
||||
const result = await handlers["get_plugin_filters"]({ pluginId: "flights" });
|
||||
const parsed = JSON.parse(textOf(result));
|
||||
|
||||
expect(parsed).toEqual({ available: false, reason: "plugin not loaded" });
|
||||
});
|
||||
|
||||
it("returns { available: true, filters: [] } when plugin is loaded but declares no filters", async () => {
|
||||
mockReadSessionCatalog.mockResolvedValue({
|
||||
tools: [],
|
||||
capabilities: [],
|
||||
filterDefinitions: { flights: [] },
|
||||
} as never);
|
||||
|
||||
const result = await handlers["get_plugin_filters"]({ pluginId: "flights" });
|
||||
const parsed = JSON.parse(textOf(result));
|
||||
|
||||
expect(parsed).toEqual({ available: true, filters: [] });
|
||||
});
|
||||
});
|
||||
@@ -1,191 +0,0 @@
|
||||
/**
|
||||
* MCP Filter Tool registrar (Phase 23 Wave 2 -- 23-02).
|
||||
*
|
||||
* Registers three MCP tools that let an AI agent filter the live globe:
|
||||
*
|
||||
* set_filter -- push filter values to a plugin layer (FILT-01)
|
||||
* clear_filter -- clear one plugin's filters, or all filters (FILT-02)
|
||||
* get_plugin_filters -- read a plugin's declared filterable fields (FILT-03)
|
||||
*
|
||||
* set_filter / clear_filter enqueue a GlobeCommand via enqueueGlobeCommand; the
|
||||
* browser drains the queue over the SSE bridge and applies them to filterSlice.
|
||||
* get_plugin_filters reads the browser-published session catalog (D-05).
|
||||
*
|
||||
* Security: userId comes ONLY from ctx (the verified auth result). It is never
|
||||
* read from tool arguments. sessionId may come from args (scopes the tab) or is
|
||||
* resolved from the user's active ZSET entry.
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { filterValueSchema } from "@/lib/mcp/filterSchemas";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { pluginIdSchema } from "@/lib/mcp/identifierSchemas";
|
||||
import { listStreamingPlugins } from "@/app/api/mcp/discoveryHelpers";
|
||||
import { SESSION_REQUIRED_PREAMBLE } from "@/lib/mcp/toolDescriptionFragments";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type McpTextResult = { content: [{ type: "text"; text: string }] };
|
||||
|
||||
function textResult(text: string): McpTextResult {
|
||||
return { content: [{ type: "text", text }] };
|
||||
}
|
||||
|
||||
const NO_SESSION_RESULT = textResult("no active globe session to control");
|
||||
|
||||
/**
|
||||
* Resolves the session to use: explicit arg takes precedence, falling back to
|
||||
* the most-recently-active session for this user. Returns null if none is live.
|
||||
*/
|
||||
async function resolveSession(
|
||||
userId: string,
|
||||
argSessionId: string | undefined,
|
||||
): Promise<string | null> {
|
||||
if (argSessionId !== undefined && argSessionId !== "") {
|
||||
return argSessionId;
|
||||
}
|
||||
return resolveActiveSessionId(userId);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerFilterTools(
|
||||
server: McpServer,
|
||||
ctx: { userId: string },
|
||||
): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
// TOOL: set_filter (FILT-01)
|
||||
server.registerTool(
|
||||
"set_filter",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Apply one or more filters to a plugin's live globe layer (no page reload). " +
|
||||
"Use after get_plugin_filters to discover valid filter ids; affects the live globe layer, not data query tools. " +
|
||||
"Use list_available_plugins to confirm valid pluginIds before calling. " +
|
||||
"Limitations: filter ids are plugin-specific; unknown pluginIds produce a warning in the response. " +
|
||||
"Parameters: pluginId (string, required); filters (object, required) -- filterId -> { type: 'text', value } | { type: 'select', values } | { type: 'range', min, max } | { type: 'boolean', value }; sessionId (optional). " +
|
||||
"Output: 'set_filter command enqueued for <pluginId> (N filter(s))' or a warning when the pluginId is unrecognized. " +
|
||||
"Example: set_filter({ pluginId: 'flights', filters: { status: { type: 'select', values: ['airborne'] } } }).",
|
||||
inputSchema: {
|
||||
pluginId: pluginIdSchema.describe("Plugin whose layer to filter, e.g. 'flights'"),
|
||||
filters: z
|
||||
.record(z.string(), filterValueSchema)
|
||||
.describe("Map of filterId -> filter value. Discover valid filter ids via get_plugin_filters."),
|
||||
sessionId: z.string().optional().describe("Target globe session id. Omit to target most-recently-active tab."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
// Validate the pluginId against the live streaming plugin set.
|
||||
const { plugins } = await listStreamingPlugins();
|
||||
const knownIds = new Set(plugins.map((p) => p.pluginId));
|
||||
const isKnown = knownIds.has(args.pluginId);
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "setFilter",
|
||||
pluginId: args.pluginId,
|
||||
filters: args.filters,
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
|
||||
if (!isKnown) {
|
||||
return textResult(
|
||||
`Command enqueued, but pluginId '${args.pluginId}' is not a recognized plugin. It may be ignored.`,
|
||||
);
|
||||
}
|
||||
return textResult(
|
||||
`set_filter command enqueued for '${args.pluginId}' (${Object.keys(args.filters).length} filter(s))`,
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[filterTools] set_filter failed:", err);
|
||||
return textResult("set_filter command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL: clear_filter (FILT-02)
|
||||
server.registerTool(
|
||||
"clear_filter",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Clear active filters on the live globe. " +
|
||||
"Prefer clear_filter over re-setting filters to empty values; omit pluginId to clear ALL filters across every plugin at once. " +
|
||||
"Limitations: requires an active globe session; returns 'no active globe session to control' when no tab is live. " +
|
||||
"Parameters: pluginId (string, optional) -- omit to clear all plugins; sessionId (optional). " +
|
||||
"Output: 'clear_filter enqueued for <pluginId>' or 'clear_filter enqueued for ALL plugins'. " +
|
||||
"Example: clear_filter({ pluginId: 'flights' }) or clear_filter({}).",
|
||||
inputSchema: {
|
||||
pluginId: pluginIdSchema.optional().describe("Plugin whose filters to clear. Omit to clear ALL filters on the globe."),
|
||||
sessionId: z.string().optional().describe("Target globe session id. Omit to target most-recently-active tab."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "clearFilter",
|
||||
...(args.pluginId !== undefined && { pluginId: args.pluginId }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
return textResult(
|
||||
args.pluginId
|
||||
? `clear_filter enqueued for '${args.pluginId}'`
|
||||
: "clear_filter enqueued for ALL plugins",
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[filterTools] clear_filter failed:", err);
|
||||
return textResult("clear_filter command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL: get_plugin_filters (FILT-03)
|
||||
server.registerTool(
|
||||
"get_plugin_filters",
|
||||
{
|
||||
description:
|
||||
"Read-only discovery: list filterable fields a plugin has declared, so you can build a valid set_filter call. " +
|
||||
"Use before set_filter to confirm filter ids and value types for a plugin. " +
|
||||
"Limitations: returns { available: false, reason: 'no_session_active' } when no globe session is active (browser must be open); returns { available: false, reason: 'plugin not loaded' } when the plugin has not published its catalog. " +
|
||||
"Parameters: pluginId (string, required) -- the plugin to inspect. " +
|
||||
"Output: { available: true, filters: FilterDefinition[] } when the plugin is loaded, where each FilterDefinition is { id, label, type: 'text'|'select'|'range'|'boolean', propertyKey, options?, range? }; or { available: false, reason: 'plugin not loaded' | 'no_session_active' } when unavailable. " +
|
||||
"Example: get_plugin_filters({ pluginId: 'flights' }) -> { available: true, filters: [{ id: 'status', label: 'Status', type: 'select', options: [...] }] }.",
|
||||
inputSchema: {
|
||||
pluginId: pluginIdSchema.describe("Plugin to inspect for declared filterable fields"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveActiveSessionId(userId);
|
||||
if (!sessionId) {
|
||||
return textResult(JSON.stringify({ available: false, reason: "no_session_active" }));
|
||||
}
|
||||
|
||||
const catalog = await readSessionCatalog(userId, sessionId);
|
||||
const filterDefs = catalog?.filterDefinitions;
|
||||
if (!filterDefs || !(args.pluginId in filterDefs)) {
|
||||
return textResult(JSON.stringify({ available: false, reason: "plugin not loaded" }));
|
||||
}
|
||||
return textResult(JSON.stringify({ available: true, filters: filterDefs[args.pluginId] }));
|
||||
} catch (err) {
|
||||
console.error("[filterTools] get_plugin_filters failed:", err);
|
||||
return textResult(JSON.stringify({ available: false, reason: "plugin not loaded" }));
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/nominatim", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/lib/nominatim")>();
|
||||
return {
|
||||
...actual,
|
||||
fetchGeocode: vi.fn(),
|
||||
};
|
||||
});
|
||||
vi.mock("@/lib/geocodingRateLimit");
|
||||
vi.mock("@/lib/globeCommandQueue");
|
||||
|
||||
import { registerGeocodingTools } from "./geocodingTools";
|
||||
import { fetchGeocode } from "@/lib/nominatim";
|
||||
import { checkRateLimit } from "@/lib/geocodingRateLimit";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
|
||||
const mockFetchGeocode = vi.mocked(fetchGeocode);
|
||||
const mockCheckRateLimit = vi.mocked(checkRateLimit);
|
||||
const mockEnqueueGlobeCommand = vi.mocked(enqueueGlobeCommand);
|
||||
const mockResolveActiveSessionId = vi.mocked(resolveActiveSessionId);
|
||||
|
||||
const handlers: Record<string, (args: unknown) => unknown> = {};
|
||||
const schemas: Record<string, { description: string }> = {};
|
||||
const mockServer = {
|
||||
registerTool: vi.fn((name: string, schema: { description: string }, handler: (args: unknown) => unknown) => {
|
||||
handlers[name] = handler;
|
||||
schemas[name] = schema;
|
||||
}),
|
||||
};
|
||||
|
||||
const ctx = { userId: "u1" };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.keys(handlers).forEach((k) => delete handlers[k]);
|
||||
Object.keys(schemas).forEach((k) => delete schemas[k]);
|
||||
registerGeocodingTools(mockServer as never, ctx);
|
||||
});
|
||||
|
||||
describe("geocode_location tool handler", () => {
|
||||
it("returns structured result with lat/lng/name/bbox/importance when Nominatim returns results", async () => {
|
||||
mockCheckRateLimit.mockResolvedValue(undefined);
|
||||
mockFetchGeocode.mockResolvedValue([
|
||||
{
|
||||
lat: "51.5074",
|
||||
lon: "-0.1278",
|
||||
display_name: "London, UK",
|
||||
boundingbox: ["51.2868", "51.6919", "-0.5103", "0.3340"],
|
||||
importance: 0.9,
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await handlers["geocode_location"]({ query: "London", limit: 1 });
|
||||
|
||||
expect(result).toMatchObject({
|
||||
content: expect.arrayContaining([
|
||||
expect.objectContaining({ type: "text" }),
|
||||
]),
|
||||
});
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
const parsed = JSON.parse(text);
|
||||
expect(parsed[0]).toMatchObject({ lat: expect.any(Number), lng: expect.any(Number), name: expect.any(String) });
|
||||
expect(parsed[0]).toHaveProperty("bbox");
|
||||
expect(parsed[0]).toHaveProperty("importance");
|
||||
});
|
||||
|
||||
it("returns 'no results' message when Nominatim returns empty array", async () => {
|
||||
mockCheckRateLimit.mockResolvedValue(undefined);
|
||||
mockFetchGeocode.mockResolvedValue([]);
|
||||
|
||||
const result = await handlers["geocode_location"]({ query: "xyznonexistent" });
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text.toLowerCase()).toContain("no results");
|
||||
});
|
||||
|
||||
it("returns 'rate_limited' when checkRateLimit signals limit exceeded", async () => {
|
||||
mockCheckRateLimit.mockResolvedValue({ error: "rate_limited", retryAfterMs: 1000 });
|
||||
|
||||
const result = await handlers["geocode_location"]({ query: "Paris" });
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text).toContain("rate_limited");
|
||||
});
|
||||
|
||||
it("clamps default limit to 5 and max limit to 20", async () => {
|
||||
mockCheckRateLimit.mockResolvedValue(undefined);
|
||||
mockFetchGeocode.mockResolvedValue([]);
|
||||
|
||||
await handlers["geocode_location"]({ query: "test" });
|
||||
expect(mockFetchGeocode).toHaveBeenCalledWith(expect.objectContaining({ limit: 5 }));
|
||||
|
||||
await handlers["geocode_location"]({ query: "test", limit: 100 });
|
||||
expect(mockFetchGeocode).toHaveBeenCalledWith(expect.objectContaining({ limit: 20 }));
|
||||
});
|
||||
});
|
||||
|
||||
describe("geocodingTools tool descriptions (DESC-03)", () => {
|
||||
const toolNames = ["geocode_location", "fly_to"];
|
||||
|
||||
it.each(toolNames)("%s description is non-empty and within 1024 chars", (name) => {
|
||||
const desc = schemas[name].description;
|
||||
expect(desc.length).toBeGreaterThan(0);
|
||||
expect(desc.length).toBeLessThanOrEqual(1024);
|
||||
});
|
||||
|
||||
it.each(toolNames)("%s description contains 'Example:'", (name) => {
|
||||
expect(schemas[name].description).toContain("Example:");
|
||||
});
|
||||
|
||||
it("fly_to description contains globe://sessions precondition", () => {
|
||||
expect(schemas["fly_to"].description).toContain("globe://sessions");
|
||||
});
|
||||
|
||||
it("fly_to description contains no-session outcome", () => {
|
||||
expect(schemas["fly_to"].description).toContain("no active globe session to control");
|
||||
});
|
||||
|
||||
it("fly_to description contains Prefer disambiguation", () => {
|
||||
expect(schemas["fly_to"].description).toContain("Prefer");
|
||||
});
|
||||
});
|
||||
|
||||
describe("fly_to tool handler", () => {
|
||||
it("calls enqueueGlobeCommand with flyTo command for valid lat/lng", async () => {
|
||||
mockResolveActiveSessionId.mockResolvedValue("sess-abc");
|
||||
mockEnqueueGlobeCommand.mockResolvedValue(undefined);
|
||||
|
||||
await handlers["fly_to"]({ lat: 51.5, lng: -0.1 });
|
||||
|
||||
expect(mockEnqueueGlobeCommand).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"sess-abc",
|
||||
expect.objectContaining({ type: "flyTo", lat: 51.5, lng: -0.1 }),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns NO_SESSION_RESULT text when no active session exists", async () => {
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["fly_to"]({ lat: 51.5, lng: -0.1 });
|
||||
|
||||
const text = (result as { content: Array<{ text: string }> }).content[0].text;
|
||||
expect(text).toMatch(/no.*(session|globe)/i);
|
||||
});
|
||||
|
||||
it("includes bbox in enqueueGlobeCommand call when bbox is provided", async () => {
|
||||
mockResolveActiveSessionId.mockResolvedValue("sess-abc");
|
||||
mockEnqueueGlobeCommand.mockResolvedValue(undefined);
|
||||
|
||||
await handlers["fly_to"]({ lat: 51.5, lng: -0.1, bbox: [-1, 50, 1, 52] });
|
||||
|
||||
expect(mockEnqueueGlobeCommand).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"sess-abc",
|
||||
expect.objectContaining({ bbox: [-1, 50, 1, 52] }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,186 +0,0 @@
|
||||
/**
|
||||
* MCP Geocoding Tool registrar (Phase 22 Wave 2, 22-02).
|
||||
*
|
||||
* Registers two MCP tools:
|
||||
* geocode_location: resolve a place name/address to coordinates via Nominatim
|
||||
* (GEO-01), with a per-user rate limit + 24h Redis cache (GEO-03)
|
||||
* fly_to: enqueue a flyTo GlobeCommand to move the browser camera (GEO-02)
|
||||
*
|
||||
* Security: userId comes ONLY from ctx (verified auth result), never from tool
|
||||
* arguments. The Nominatim URL is hardcoded; the user query is injected via
|
||||
* URLSearchParams inside fetchGeocode (no string concatenation).
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { fetchGeocode, normalizeNominatimResult } from "@/lib/nominatim";
|
||||
import type { RawNominatimItem } from "@/lib/nominatim";
|
||||
import { checkRateLimit } from "@/lib/geocodingRateLimit";
|
||||
import { redis } from "@/lib/redis";
|
||||
import { latSchema, lonSchema } from "@/lib/mcp/coordinateSchemas";
|
||||
import { SESSION_REQUIRED_PREAMBLE } from "@/lib/mcp/toolDescriptionFragments";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type McpTextResult = { content: [{ type: "text"; text: string }] };
|
||||
|
||||
function textResult(text: string): McpTextResult {
|
||||
return { content: [{ type: "text", text }] };
|
||||
}
|
||||
|
||||
const NO_SESSION_RESULT = textResult("no active globe session to control");
|
||||
|
||||
/** Best-effort cache read: a Redis outage degrades to a miss, never an error. */
|
||||
async function cacheGet(key: string): Promise<string | null> {
|
||||
try {
|
||||
return await redis.get(key);
|
||||
} catch (err) {
|
||||
console.warn("[geocodingTools] cache read failed (degrading to miss):", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Best-effort cache write: a Redis outage is logged and ignored. */
|
||||
async function cacheSet(key: string, value: string, ttlSeconds: number): Promise<void> {
|
||||
try {
|
||||
await redis.set(key, value, "EX", ttlSeconds);
|
||||
} catch (err) {
|
||||
console.warn("[geocodingTools] cache write failed (ignored):", err);
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_LIMIT = 5;
|
||||
const MAX_LIMIT = 20;
|
||||
const DEFAULT_ALTITUDE_M = 15_000;
|
||||
const CACHE_TTL_SECONDS = 86_400; // 24h
|
||||
|
||||
/**
|
||||
* Resolves the session to use: explicit arg takes precedence, falling back to
|
||||
* the most-recently-active session for this user. Returns null if none is live.
|
||||
*/
|
||||
async function resolveSession(
|
||||
userId: string,
|
||||
argSessionId: string | undefined,
|
||||
): Promise<string | null> {
|
||||
if (argSessionId !== undefined && argSessionId !== "") {
|
||||
return argSessionId;
|
||||
}
|
||||
return resolveActiveSessionId(userId);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerGeocodingTools(
|
||||
server: McpServer,
|
||||
ctx: { userId: string },
|
||||
): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
// GEO-01 + GEO-03: geocode_location
|
||||
server.registerTool(
|
||||
"geocode_location",
|
||||
{
|
||||
description:
|
||||
"Resolve a place name or address to coordinates and a bounding box via OpenStreetMap Nominatim. " +
|
||||
"Use before fly_to to obtain lat/lng from a name; do not guess coordinates. " +
|
||||
"Limitations: Nominatim is rate-limited per user; results are cached 24h; returns 'no results found' when nothing matches. " +
|
||||
"Parameters: query (string, required) - place name or address; limit (integer 1-20, optional, default 5). " +
|
||||
"Output: JSON array sorted by importance, each { lat, lng, name, name_en, type, addresstype, country, display_name, bbox: [west,south,east,north], importance }. " +
|
||||
"Example: geocode_location({ query: 'Paris', limit: 3 }) -> [{ lat: 48.85, lng: 2.35, name: 'Paris', bbox: [...] }].",
|
||||
inputSchema: {
|
||||
query: z.string().min(1).describe("Location name or address to geocode"),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(MAX_LIMIT)
|
||||
.optional()
|
||||
.describe("Max results to return (default 5, max 20)"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const limit = Math.min(args.limit ?? DEFAULT_LIMIT, MAX_LIMIT);
|
||||
const cacheKey = `geocode:${args.query.toLowerCase().trim()}:${limit}`;
|
||||
|
||||
const cached = await cacheGet(cacheKey);
|
||||
if (cached) return textResult(cached);
|
||||
|
||||
const rateLimitResult = await checkRateLimit(userId);
|
||||
if (rateLimitResult) return textResult(JSON.stringify(rateLimitResult));
|
||||
|
||||
const raw = await fetchGeocode({ query: args.query, limit });
|
||||
if (raw.length === 0) return textResult("no results found");
|
||||
|
||||
const results = (raw as RawNominatimItem[]).map(normalizeNominatimResult);
|
||||
const json = JSON.stringify(results);
|
||||
await cacheSet(cacheKey, json, CACHE_TTL_SECONDS);
|
||||
return textResult(json);
|
||||
} catch (err) {
|
||||
console.error("[geocodingTools] geocode_location failed:", err);
|
||||
return textResult("geocode_location command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// GEO-02: fly_to
|
||||
server.registerTool(
|
||||
"fly_to",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Fly the live globe camera to a geocoded coordinate, optionally fitting a bounding box in view. " +
|
||||
"Requires an active globe session (read globe://sessions first); returns 'no active globe session to control' when no tab is live. " +
|
||||
"Prefer pan_globe for relative panning or focus_entity to snap to a known entity; use fly_to when you have explicit lat/lng (e.g. from geocode_location). " +
|
||||
"Parameters: lat (-90..90, required), lng (-180..180, required), altitude (metres, optional, default 15000), " +
|
||||
"bbox ([west,south,east,north], optional - fit this region in view), sessionId (optional - omit for most-recently-active tab). " +
|
||||
"Example: fly_to({ lat: 48.85, lng: 2.35 }) or fly_to({ lat: 0, lng: 0, bbox: [2.2,48.8,2.5,48.9] }).",
|
||||
inputSchema: {
|
||||
lat: latSchema.describe("Latitude [-90, 90]"),
|
||||
lng: lonSchema.describe("Longitude [-180, 180]"),
|
||||
altitude: z
|
||||
.number()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe("Altitude in metres above ellipsoid (default 15000)"),
|
||||
bbox: z
|
||||
.tuple([z.number(), z.number(), z.number(), z.number()])
|
||||
.optional()
|
||||
.describe("[west, south, east, north] bounding box to fit in view"),
|
||||
sessionId: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Target globe session id. Omit to target most-recently-active tab."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "flyTo",
|
||||
lat: args.lat,
|
||||
lng: args.lng,
|
||||
alt: args.altitude ?? DEFAULT_ALTITUDE_M,
|
||||
...(args.bbox ? { bbox: args.bbox } : {}),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
|
||||
const label = args.bbox
|
||||
? `bbox=[${args.bbox.join(",")}]`
|
||||
: `lat=${args.lat}, lng=${args.lng}, alt=${args.altitude ?? DEFAULT_ALTITUDE_M}`;
|
||||
return textResult(`fly_to command enqueued (${label})`);
|
||||
} catch (err) {
|
||||
console.error("[geocodingTools] fly_to failed:", err);
|
||||
return textResult("fly_to command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -22,11 +22,9 @@ import { latSchema as sharedLatSchema, lonSchema as sharedLonSchema } from "@/li
|
||||
// declared with vi.hoisted() to be accessible inside the factory function.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const { mockEnqueue, mockResolveSessionId, mockListStreamingPlugins, mockGetEntityDetails } = vi.hoisted(() => ({
|
||||
const { mockEnqueue, mockResolveSessionId } = vi.hoisted(() => ({
|
||||
mockEnqueue: vi.fn().mockResolvedValue(undefined),
|
||||
mockResolveSessionId: vi.fn().mockResolvedValue("resolved-session"),
|
||||
mockListStreamingPlugins: vi.fn().mockResolvedValue({ plugins: [] }),
|
||||
mockGetEntityDetails: vi.fn().mockResolvedValue({ data: null, emptyReason: "no_data_matches" }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/globeCommandQueue", () => ({
|
||||
@@ -34,40 +32,26 @@ vi.mock("@/lib/globeCommandQueue", () => ({
|
||||
resolveActiveSessionId: mockResolveSessionId,
|
||||
}));
|
||||
|
||||
vi.mock("./discoveryHelpers", () => ({
|
||||
listStreamingPlugins: mockListStreamingPlugins,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/data-query/service", () => ({
|
||||
getEntityDetails: mockGetEntityDetails,
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fake McpServer — records registered tools
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type ToolHandler = (input: Record<string, unknown>) => Promise<{ content: [{ type: "text"; text: string }] }>;
|
||||
|
||||
type ToolDef = { description: string; inputSchema: Record<string, unknown> };
|
||||
|
||||
function makeFakeServer() {
|
||||
const tools = new Map<string, ToolHandler>();
|
||||
const schemas = new Map<string, ToolDef>();
|
||||
const server = {
|
||||
registerTool: vi.fn((name: string, def: ToolDef, handler: ToolHandler) => {
|
||||
registerTool: vi.fn((name: string, _def: unknown, handler: ToolHandler) => {
|
||||
tools.set(name, handler);
|
||||
schemas.set(name, def);
|
||||
}),
|
||||
};
|
||||
return { server, tools, schemas };
|
||||
return { server, tools };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
mockEnqueue.mockResolvedValue(undefined);
|
||||
mockResolveSessionId.mockResolvedValue("resolved-session");
|
||||
mockListStreamingPlugins.mockResolvedValue({ plugins: [] });
|
||||
mockGetEntityDetails.mockResolvedValue({ data: null, emptyReason: "no_data_matches" });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -367,58 +351,6 @@ describe("isValidGlobeCommand NaN heading rejection (TOOL-08)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -447,133 +379,3 @@ describe("get_entities_in_region coordinate schema bounds (TOOL-09)", () => {
|
||||
expect(sharedLonSchema.safeParse(Infinity).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-02 (Phase 33): toggle_layer unrecognized id warning
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("toggle_layer -- unrecognized layerId warning (TOOL-02/P33)", () => {
|
||||
it("enqueues command and returns warning when layerId is not a known plugin", async () => {
|
||||
mockListStreamingPlugins.mockResolvedValue({ plugins: [{ pluginId: "flights" }] });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("toggle_layer")!({ layerId: "unknown-layer-xyz" });
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledOnce();
|
||||
expect(result.content[0].text).toContain("not a recognized plugin");
|
||||
expect(result.content[0].text).toContain("unknown-layer-xyz");
|
||||
});
|
||||
|
||||
it("enqueues command and returns plain success when layerId is recognized", async () => {
|
||||
mockListStreamingPlugins.mockResolvedValue({ plugins: [{ pluginId: "flights" }] });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("toggle_layer")!({ layerId: "flights" });
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledOnce();
|
||||
expect(result.content[0].text).not.toContain("not a recognized plugin");
|
||||
expect(result.content[0].text).toContain("flights");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TOOL-02 (Phase 33): focus_entity server-side entity-id resolution
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("focus_entity -- server-side entity resolution (TOOL-02/P33)", () => {
|
||||
it("resolves lat/lon from entityId+pluginId when coordinates are absent", async () => {
|
||||
mockGetEntityDetails.mockResolvedValue({
|
||||
data: {
|
||||
id: "ship-1",
|
||||
pluginId: "ais",
|
||||
latitude: 35.68,
|
||||
longitude: 139.69,
|
||||
timestamp: new Date(),
|
||||
properties: {},
|
||||
},
|
||||
});
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("focus_entity")!({
|
||||
entityId: "ship-1",
|
||||
pluginId: "ais",
|
||||
});
|
||||
|
||||
expect(mockEnqueue).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"resolved-session",
|
||||
expect.objectContaining({ type: "focusEntity", lat: 35.68, lon: 139.69 }),
|
||||
);
|
||||
expect(result.content[0].text).toContain("35.68");
|
||||
});
|
||||
|
||||
it("returns honest failure when entityId cannot be resolved (no pluginId provided)", async () => {
|
||||
// Without pluginId the resolver path is skipped and resolution fails.
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("focus_entity")!({ entityId: "unknown-entity" });
|
||||
|
||||
expect(mockEnqueue).not.toHaveBeenCalled();
|
||||
expect(result.content[0].text).toContain("Could not resolve entityId");
|
||||
expect(result.content[0].text).toContain("unknown-entity");
|
||||
});
|
||||
|
||||
it("returns honest failure when entity not found in plugin snapshot", async () => {
|
||||
mockGetEntityDetails.mockResolvedValue({ data: null, emptyReason: "no_data_matches" });
|
||||
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("focus_entity")!({
|
||||
entityId: "missing-entity",
|
||||
pluginId: "ais",
|
||||
});
|
||||
|
||||
expect(mockEnqueue).not.toHaveBeenCalled();
|
||||
expect(result.content[0].text).toContain("Could not resolve entityId");
|
||||
});
|
||||
|
||||
it("uses provided lat/lon directly without calling getEntityDetails", async () => {
|
||||
const { server, tools } = makeFakeServer();
|
||||
registerGlobeCommandTools(
|
||||
server as unknown as import("@modelcontextprotocol/sdk/server/mcp.js").McpServer,
|
||||
{ userId: "u1" },
|
||||
);
|
||||
|
||||
const result = await tools.get("focus_entity")!({
|
||||
entityId: "e1",
|
||||
lat: 10,
|
||||
lon: 20,
|
||||
});
|
||||
|
||||
expect(mockGetEntityDetails).not.toHaveBeenCalled();
|
||||
expect(mockEnqueue).toHaveBeenCalledWith(
|
||||
"u1",
|
||||
"resolved-session",
|
||||
expect.objectContaining({ lat: 10, lon: 20 }),
|
||||
);
|
||||
expect(result.content[0].text).toContain("10");
|
||||
});
|
||||
});
|
||||
@@ -21,13 +21,9 @@ import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQ
|
||||
import { TIME_WINDOW_VALUES } from "@/core/globe/types/GlobeCommand";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { latSchema, lonSchema, altSchema } from "@/lib/mcp/coordinateSchemas";
|
||||
import { layerIdSchema, entityIdSchema } from "@/lib/mcp/identifierSchemas";
|
||||
import { SESSION_REQUIRED_PREAMBLE } from "@/lib/mcp/toolDescriptionFragments";
|
||||
import { listStreamingPlugins } from "./discoveryHelpers";
|
||||
import { getEntityDetails } from "@/lib/data-query/service";
|
||||
|
||||
// Re-export so existing tests that import from this module continue to work.
|
||||
export { latSchema, lonSchema, altSchema, layerIdSchema };
|
||||
export { latSchema, lonSchema, altSchema };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
@@ -70,12 +66,7 @@ export function registerGlobeCommandTools(
|
||||
"pan_globe",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Fly the globe camera to an explicit coordinate. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
|
||||
"Prefer pan_globe over focus_entity when you have a lat/lon and no entity id, or when focus_entity entity-id resolution is not needed. " +
|
||||
"Limitations: latitude [-90, 90], longitude [-180, 180], altitude > 0 metres; out-of-range values are rejected. " +
|
||||
"Parameters: lat (required), lon (required), alt in metres (required), heading (deg, optional), pitch (deg, optional), duration (seconds, optional), sessionId (optional, omit to target most-recently-active tab). " +
|
||||
"Example: pan_globe({lat:48.8566,lon:2.3522,alt:500000})",
|
||||
"Fly the globe camera to a geographic position. Provide lat/lon/alt (metres). Optional heading, pitch, and animation duration.",
|
||||
inputSchema: {
|
||||
lat: latSchema.describe("Latitude in decimal degrees [-90, 90]"),
|
||||
lon: lonSchema.describe("Longitude in decimal degrees [-180, 180]"),
|
||||
@@ -114,18 +105,10 @@ export function registerGlobeCommandTools(
|
||||
"focus_entity",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Point the globe camera at a known entity or coordinate. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
|
||||
"Prefer focus_entity over pan_globe when you have an entity id and want to centre on it. " +
|
||||
"When lat/lon are provided they are used directly. " +
|
||||
"When only entityId is provided (no lat/lon), the server resolves coordinates via pluginId + entityId lookup -- include pluginId for a faster, scoped lookup. " +
|
||||
"Returns an error string when entityId cannot be resolved to coordinates. " +
|
||||
"Limitations: latitude [-90, 90], longitude [-180, 180]. " +
|
||||
"Parameters: entityId (optional), pluginId (optional, scopes entity lookup), lat (optional), lon (optional), sessionId (optional). " +
|
||||
"Example: focus_entity({entityId:\"ship-123\",pluginId:\"ais\",lat:35.68,lon:139.69})",
|
||||
"Point the globe camera at a geographic coordinate. Provide lat and lon to fly the camera there. " +
|
||||
"entityId is accepted but entity-id-to-coordinate resolution is not yet wired; always include lat/lon for a reliable camera move.",
|
||||
inputSchema: {
|
||||
entityId: entityIdSchema.optional().describe("Entity id to focus on"),
|
||||
pluginId: z.string().optional().describe("Plugin that owns this entity -- narrows the id lookup when lat/lon are not provided"),
|
||||
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."),
|
||||
@@ -136,39 +119,14 @@ export function registerGlobeCommandTools(
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
let resolvedLat = args.lat;
|
||||
let resolvedLon = args.lon;
|
||||
|
||||
// When coordinates are absent but entityId is present, resolve server-side.
|
||||
if (resolvedLat === undefined && resolvedLon === undefined && args.entityId !== undefined) {
|
||||
if (args.pluginId !== undefined) {
|
||||
const detail = await getEntityDetails(args.pluginId, args.entityId);
|
||||
if (detail.data !== null) {
|
||||
resolvedLat = detail.data.latitude;
|
||||
resolvedLon = detail.data.longitude;
|
||||
}
|
||||
}
|
||||
|
||||
if (resolvedLat === undefined) {
|
||||
// entityId could not be resolved -- return an honest failure instead of
|
||||
// enqueuing a command the browser cannot execute.
|
||||
return textResult(
|
||||
`Could not resolve entityId '${args.entityId}' to coordinates. ` +
|
||||
`Provide pluginId to scope the lookup, or include lat/lon directly.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "focusEntity",
|
||||
...(args.entityId !== undefined && { entityId: args.entityId }),
|
||||
...(resolvedLat !== undefined && { lat: resolvedLat }),
|
||||
...(resolvedLon !== undefined && { lon: resolvedLon }),
|
||||
...(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=${resolvedLat ?? "none"}, lon=${resolvedLon ?? "none"})`,
|
||||
);
|
||||
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");
|
||||
@@ -181,15 +139,9 @@ export function registerGlobeCommandTools(
|
||||
"toggle_layer",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Enable or disable a plugin data layer on the globe. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
|
||||
"Prefer toggle_layer over pan_globe or set_timeline when changing layer visibility, not camera position or playback time. " +
|
||||
"Use list_available_plugins to confirm valid layerIds before calling. " +
|
||||
"Limitations: layerId must match an installed plugin id. When the id is not recognized a warning is included in the response. " +
|
||||
"Parameters: layerId (required), enabled (true/false, optional -- omit to toggle current state), sessionId (optional). " +
|
||||
"Example: toggle_layer({layerId:\"ais\",enabled:true})",
|
||||
"Enable or disable a plugin data layer on the globe. Omit 'enabled' to toggle the current state.",
|
||||
inputSchema: {
|
||||
layerId: layerIdSchema.describe("The plugin/layer identifier to toggle"),
|
||||
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."),
|
||||
},
|
||||
@@ -199,23 +151,12 @@ export function registerGlobeCommandTools(
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
// Check whether the layerId matches a known streaming plugin.
|
||||
const { plugins } = await listStreamingPlugins();
|
||||
const knownIds = new Set(plugins.map((p) => p.pluginId));
|
||||
const isKnown = knownIds.has(args.layerId);
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "toggleLayer",
|
||||
layerId: args.layerId,
|
||||
...(args.enabled !== undefined && { enabled: args.enabled }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
|
||||
if (!isKnown) {
|
||||
return textResult(
|
||||
`Command enqueued, but layerId '${args.layerId}' is not a recognized plugin. It may be ignored.`,
|
||||
);
|
||||
}
|
||||
return textResult(`Layer '${args.layerId}' toggle command enqueued`);
|
||||
} catch (err) {
|
||||
console.error("[globeCommandTools] toggle_layer failed:", err);
|
||||
@@ -229,12 +170,7 @@ export function registerGlobeCommandTools(
|
||||
"set_timeline",
|
||||
{
|
||||
description:
|
||||
SESSION_REQUIRED_PREAMBLE +
|
||||
"Set the globe timeline position, time window, or playback mode. Requires an active globe session: READ globe://sessions first. If no tab is open, returns \"no active globe session to control\". " +
|
||||
"Prefer set_timeline over toggle_layer or pan_globe when adjusting time or playback, not layer visibility or camera position. " +
|
||||
"Limitations: currentTime must be ISO 8601; timeWindow must be one of '1h','6h','24h','48h','7d'. " +
|
||||
"Parameters: currentTime (ISO 8601, optional), timeWindow (optional), isPlaybackMode (boolean, optional), sessionId (optional). " +
|
||||
"Example: set_timeline({timeWindow:\"24h\",isPlaybackMode:true})",
|
||||
"Set the globe timeline position, time window, or playback mode.",
|
||||
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'"),
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
/**
|
||||
* SEC-02: Redis per-key rate limiting in /api/mcp route tests.
|
||||
*
|
||||
* Verifies the post-auth Redis sliding-window gate behavior.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Top-level mocks (same surface as route.test.ts)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock("@/lib/apiKeyAuth", () => ({
|
||||
authenticateApiKey: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
edition: "local",
|
||||
isLocal: true,
|
||||
isCloud: false,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/geocodingRateLimit", () => ({
|
||||
redisSlidingWindow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@modelcontextprotocol/sdk/server/mcp.js", () => {
|
||||
const McpServer = vi.fn(function McpServerMock(this: unknown) {
|
||||
return {
|
||||
connect: vi.fn().mockResolvedValue(undefined),
|
||||
registerResource: vi.fn(),
|
||||
registerTool: vi.fn(),
|
||||
registerPrompt: vi.fn(),
|
||||
};
|
||||
});
|
||||
const ResourceTemplate = vi.fn(function ResourceTemplateMock(this: unknown, uriTemplate: string) {
|
||||
return { uriTemplate };
|
||||
});
|
||||
return { McpServer, ResourceTemplate };
|
||||
});
|
||||
|
||||
vi.mock("@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js", () => {
|
||||
const WebStandardStreamableHTTPServerTransport = vi.fn().mockImplementation(() => ({
|
||||
handleRequest: vi.fn().mockResolvedValue(
|
||||
new Response(null, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"X-Accel-Buffering": "no",
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
})
|
||||
),
|
||||
}));
|
||||
return { WebStandardStreamableHTTPServerTransport };
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Imports (after mocks)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
import { POST } from "./route";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { redisSlidingWindow } from "@/lib/geocodingRateLimit";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makePost(authorization?: string): Request {
|
||||
const headers: Record<string, string> = {};
|
||||
if (authorization) headers["authorization"] = authorization;
|
||||
return new Request("http://localhost:3000/api/mcp", { method: "POST", headers });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("SEC-02: per-key Redis rate limit gate", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
});
|
||||
|
||||
it("passes through when Redis allows the request", async () => {
|
||||
vi.mocked(redisSlidingWindow).mockResolvedValue({ allowed: true, retryAfterMs: 0 });
|
||||
|
||||
const res = await POST(makePost("Bearer wwv_valid.token"));
|
||||
expect(res.status).not.toBe(429);
|
||||
});
|
||||
|
||||
it("returns 429 JSON-RPC -32000 when Redis rejects the request", async () => {
|
||||
vi.mocked(redisSlidingWindow).mockResolvedValue({ allowed: false, retryAfterMs: 60_000 });
|
||||
|
||||
const res = await POST(makePost("Bearer wwv_valid.token"));
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(429);
|
||||
expect(body).toMatchObject({
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32000, message: "rate limit exceeded" },
|
||||
id: null,
|
||||
});
|
||||
expect(res.headers.get("Retry-After")).toBe("60");
|
||||
});
|
||||
|
||||
it("rate limit check uses the authenticated keyId, not userId or raw header", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-abc", keyId: "key-xyz" });
|
||||
vi.mocked(redisSlidingWindow).mockResolvedValue({ allowed: true, retryAfterMs: 0 });
|
||||
|
||||
await POST(makePost("Bearer wwv_valid.token"));
|
||||
|
||||
expect(vi.mocked(redisSlidingWindow)).toHaveBeenCalledWith(
|
||||
expect.stringContaining("key-xyz"),
|
||||
expect.any(Number),
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
|
||||
it("rate limit is not checked when auth fails (no authenticated keyId available)", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue(null);
|
||||
|
||||
const res = await POST(makePost("Bearer bogus.token"));
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(vi.mocked(redisSlidingWindow)).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -46,7 +46,6 @@ vi.mock("@modelcontextprotocol/sdk/server/mcp.js", () => {
|
||||
connect: vi.fn().mockResolvedValue(undefined),
|
||||
registerResource: vi.fn(),
|
||||
registerTool: vi.fn(),
|
||||
registerPrompt: vi.fn(),
|
||||
};
|
||||
});
|
||||
// Minimal ResourceTemplate stub so globeResources.ts can construct one
|
||||
@@ -246,31 +245,6 @@ describe("MCP-01/MCP-02: Valid auth + non-demo -> request passes both gates", ()
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TRANS-04: tools.listChanged must NOT be advertised as true
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("TRANS-04: McpServer is not created with tools.listChanged: true", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
});
|
||||
|
||||
it("capabilities passed to McpServer constructor have listChanged false or absent (never true)", async () => {
|
||||
const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
|
||||
const mcpCtor = vi.mocked(McpServer);
|
||||
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
await POST(req);
|
||||
|
||||
expect(mcpCtor).toHaveBeenCalledTimes(1);
|
||||
// second arg is the options object: { instructions, capabilities }
|
||||
const options = mcpCtor.mock.calls[0][1] as { capabilities?: { tools?: { listChanged?: boolean } } } | undefined;
|
||||
const listChanged = options?.capabilities?.tools?.listChanged;
|
||||
expect(listChanged).not.toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-06: Streaming headers — X-Accel-Buffering: no must be present (Pitfall 1)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -296,93 +270,6 @@ describe("MCP-06: Streaming response headers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TRANS-01: Top-level error boundary — unexpected throws -> JSON-RPC -32603
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("TRANS-01: unhandled error during request handling yields JSON-RPC -32603", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
it("POST returns HTTP 500 with JSON-RPC -32603 body when a registrar throws", async () => {
|
||||
// Simulate an unexpected failure after auth succeeds (e.g. Redis down).
|
||||
// We make authenticateApiKey succeed but then make registerOrientationPrompts
|
||||
// throw by having McpServer.registerPrompt throw.
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
|
||||
const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
|
||||
vi.mocked(McpServer).mockImplementationOnce(function (this: unknown) {
|
||||
return {
|
||||
connect: vi.fn().mockResolvedValue(undefined),
|
||||
registerResource: vi.fn(),
|
||||
registerTool: vi.fn(),
|
||||
registerPrompt: vi.fn().mockImplementation(() => {
|
||||
throw new Error("Redis connection refused");
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
const res = await POST(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
id: null,
|
||||
error: { code: -32603, message: "Internal error" },
|
||||
});
|
||||
});
|
||||
|
||||
it("GET returns HTTP 500 with JSON-RPC -32603 body when transport.handleRequest throws", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "user-123", keyId: "key-1" });
|
||||
|
||||
const { WebStandardStreamableHTTPServerTransport } = await import(
|
||||
"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"
|
||||
);
|
||||
vi.mocked(WebStandardStreamableHTTPServerTransport).mockImplementationOnce(() => ({
|
||||
handleRequest: vi.fn().mockRejectedValue(new Error("stream error")),
|
||||
}));
|
||||
|
||||
const req = makeRequest("GET", { authorization: "Bearer wwv_valid.token" });
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(body).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
id: null,
|
||||
error: { code: -32603, message: "Internal error" },
|
||||
});
|
||||
});
|
||||
|
||||
// Defense-in-depth: if authenticateApiKey ever regresses and throws instead
|
||||
// of returning null, the boundary must still catch it and return -32603.
|
||||
// In practice TRANS-02 makes authenticateApiKey return null on DB outage,
|
||||
// so this path is hypothetical, not a real DB-outage scenario.
|
||||
it("-32603 response carries streaming headers (X-Accel-Buffering: no) [defense-in-depth: hypothetical auth throw]", async () => {
|
||||
vi.mocked(authenticateApiKey).mockRejectedValue(new Error("DB down"));
|
||||
|
||||
const req = makeRequest("POST", { authorization: "Bearer wwv_valid.token" });
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(res.headers.get("X-Accel-Buffering")).toBe("no");
|
||||
});
|
||||
|
||||
it("existing 401 path is NOT affected by the error boundary", async () => {
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue(null);
|
||||
|
||||
const req = makeRequest("POST");
|
||||
const res = await POST(req);
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
const body = await res.json();
|
||||
expect(body.error.code).toBe(-32600);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP-05: Stateless freshness — per-request construction (Pitfall 2)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
+34
-62
@@ -29,36 +29,47 @@ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/
|
||||
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 { createMcpServer } from "@/lib/mcp/server";
|
||||
import { mcpLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
import { redisSlidingWindow } from "@/lib/geocodingRateLimit";
|
||||
import {
|
||||
demoBlockedResponse,
|
||||
unauthorizedResponse,
|
||||
rateLimitedResponse,
|
||||
internalErrorResponse,
|
||||
} from "@/lib/mcp/mcpResponseHelpers";
|
||||
import { registerGlobeResources } from "./globeResources";
|
||||
import { registerDataQueryTools } from "@/lib/mcp/tools";
|
||||
import { registerGlobeCommandTools } from "./globeCommandTools";
|
||||
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { registerPluginToolDispatch } from "./pluginToolDispatch";
|
||||
import { registerGeocodingTools } from "./geocodingTools";
|
||||
import { registerFavoritesTools } from "./favoritesTools";
|
||||
import { registerFilterTools } from "./filterTools";
|
||||
import { registerDiscoveryTools } from "./discoveryTools";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Route segment config (TRANS-03)
|
||||
// 30 s is comfortably above the 10 s blpop ceiling in RELAY_DEADLINE_MS so the
|
||||
// function never times out mid-relay. Vercel/Coolify honour this value.
|
||||
// JSON-RPC 2.0 error response helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const maxDuration = 30;
|
||||
/**
|
||||
* 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 },
|
||||
);
|
||||
}
|
||||
|
||||
// Per-key rate-limit budget (SEC-02): 120 requests per 60-second window.
|
||||
const MCP_KEY_LIMIT = 120;
|
||||
const MCP_WINDOW_MS = 60_000;
|
||||
/**
|
||||
* 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
|
||||
@@ -144,18 +155,6 @@ async function handleMcpRequest(request: Request): Promise<Response> {
|
||||
return unauthorizedResponse();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Gate 3: Redis per-key rate limit (SEC-02).
|
||||
// 120 req / 60s per authenticated key, complementing the coarse IP
|
||||
// gate above. Fails OPEN on Redis outage so a broken Redis never
|
||||
// blocks legit users.
|
||||
// ------------------------------------------------------------------
|
||||
const keyRateKey = `mcp:ratelimit:key:${authResult.keyId}`;
|
||||
const keyLimit = await redisSlidingWindow(keyRateKey, MCP_KEY_LIMIT, MCP_WINDOW_MS);
|
||||
if (!keyLimit.allowed) {
|
||||
return rateLimitedResponse(keyLimit.retryAfterMs);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Build a FRESH server + transport per request (D-17-04, MCP-05).
|
||||
// STATELESS INVARIANT: never hoist these to module scope.
|
||||
@@ -168,18 +167,9 @@ async function handleMcpRequest(request: Request): Promise<Response> {
|
||||
// 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 });
|
||||
registerDataQueryTools(server);
|
||||
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.
|
||||
@@ -227,32 +217,14 @@ async function handleMcpRequest(request: Request): Promise<Response> {
|
||||
// Route exports (App Router)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Top-level error boundary (TRANS-01).
|
||||
* Any throw between auth and transport (DB outage, Redis rejection, unexpected
|
||||
* SDK error) is caught here so MCP clients always receive a well-formed
|
||||
* JSON-RPC -32603 frame instead of a bare HTML 500.
|
||||
* The bearer token/secret is never logged.
|
||||
*/
|
||||
async function safeHandleMcpRequest(request: Request): Promise<Response> {
|
||||
try {
|
||||
return await handleMcpRequest(request);
|
||||
} catch (err: unknown) {
|
||||
const name = err instanceof Error ? err.name : "unknown";
|
||||
const detail = process.env.NODE_ENV !== "production" && err instanceof Error ? ` ${err.message}` : "";
|
||||
console.error(`[mcp] unhandled error in request handler: ${name}${detail}`);
|
||||
return internalErrorResponse();
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request): Promise<Response> {
|
||||
return safeHandleMcpRequest(request);
|
||||
return handleMcpRequest(request);
|
||||
}
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
return safeHandleMcpRequest(request);
|
||||
return handleMcpRequest(request);
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request): Promise<Response> {
|
||||
return safeHandleMcpRequest(request);
|
||||
return handleMcpRequest(request);
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -35,7 +35,7 @@ describe("GET /api/v1/entities/region", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
vi.mocked(getEntitiesInRegion).mockResolvedValue({ entities: [] });
|
||||
vi.mocked(getEntitiesInRegion).mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("returns 401 when no API key", async () => {
|
||||
@@ -65,7 +65,7 @@ describe("GET /api/v1/entities/region", () => {
|
||||
longitude: -0.1,
|
||||
name: "London",
|
||||
};
|
||||
vi.mocked(getEntitiesInRegion).mockResolvedValue({ entities: [entity] });
|
||||
vi.mocked(getEntitiesInRegion).mockResolvedValue([entity]);
|
||||
const req = makeRequest({ north: "52", south: "50", east: "1", west: "-1" });
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
|
||||
@@ -65,12 +65,11 @@ export async function GET(request: NextRequest) {
|
||||
const limit = Math.min(Number.isNaN(parsedLimit) ? 100 : parsedLimit, 1000);
|
||||
|
||||
try {
|
||||
const result = await getEntitiesInRegion({ north, south, east, west, pluginId, limit });
|
||||
const entities = await getEntitiesInRegion({ north, south, east, west, pluginId, limit });
|
||||
return NextResponse.json({
|
||||
entities: result.entities,
|
||||
count: result.entities.length,
|
||||
entities,
|
||||
count: 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";
|
||||
|
||||
@@ -35,7 +35,7 @@ describe("GET /api/v1/entities/search", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(authenticateApiKey).mockResolvedValue({ userId: "u1", keyId: "k1" });
|
||||
vi.mocked(searchEntities).mockResolvedValue({ entities: [] });
|
||||
vi.mocked(searchEntities).mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("returns 401 when no API key", async () => {
|
||||
@@ -59,7 +59,7 @@ describe("GET /api/v1/entities/search", () => {
|
||||
longitude: -0.1,
|
||||
name: "London",
|
||||
};
|
||||
vi.mocked(searchEntities).mockResolvedValue({ entities: [entity] });
|
||||
vi.mocked(searchEntities).mockResolvedValue([entity]);
|
||||
const req = makeRequest({ q: "test" });
|
||||
const res = await GET(req);
|
||||
const body = await res.json();
|
||||
|
||||
@@ -44,13 +44,12 @@ export async function GET(request: NextRequest) {
|
||||
const limit = Math.min(Number.isNaN(parsed) ? 20 : parsed, 100);
|
||||
|
||||
try {
|
||||
const result = await searchEntities(q, pluginId, limit);
|
||||
const entities = await searchEntities(q, pluginId, limit);
|
||||
return NextResponse.json({
|
||||
entities: result.entities,
|
||||
count: result.entities.length,
|
||||
entities,
|
||||
count: entities.length,
|
||||
query: q,
|
||||
...(pluginId !== undefined && { pluginId }),
|
||||
...(result.emptyReason !== undefined && { emptyReason: result.emptyReason }),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[entities/search] GET error:", err);
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Copy, Check } from "lucide-react";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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)",
|
||||
};
|
||||
|
||||
export const mutedMicro: React.CSSProperties = { fontSize: 11, color: "var(--text-muted)" };
|
||||
|
||||
export 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
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
|
||||
interface CopyFieldProps {
|
||||
value: string;
|
||||
label: string;
|
||||
multiline?: boolean;
|
||||
}
|
||||
|
||||
export 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>
|
||||
);
|
||||
}
|
||||
@@ -14,15 +14,15 @@
|
||||
* @module src/components/layout
|
||||
*/
|
||||
|
||||
import { Terminal, Info } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { Copy, Check, Terminal } from "lucide-react";
|
||||
import { isCloud } from "@/core/edition";
|
||||
import { CopyField, mutedMicro, subHeaderStyle } from "./ConnectAgentCopyField";
|
||||
import { AGENT_PROMPT } from "./connectAgentPrompt";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
const PLACEHOLDER_TOKEN = "wwv_<prefix>.<secret>";
|
||||
|
||||
/**
|
||||
@@ -49,6 +49,137 @@ function resolveMcpUrl(): string {
|
||||
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)
|
||||
// Tool-agnostic: Phase 17 ships no tools; tools arrive in Phase 18+.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
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 currently live and authenticated. WWV is preparing to expose tools and
|
||||
resources for querying globe entities, plugins, and live data feeds in upcoming releases. Once
|
||||
tools are available you will be able to list entities, search by geospatial bounds, inspect plugin
|
||||
configurations, and interact with live data streams.
|
||||
|
||||
When the user asks about global data, geospatial queries, or globe visualisation, use this
|
||||
connection to guide them through the WWV interface and surface live data as tools become available.`;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main component
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -96,47 +227,6 @@ export function ConnectAgentHelper({ token }: ConnectAgentHelperProps) {
|
||||
Use the URL and token below to connect Claude Desktop, Cursor, or VS Code to this globe.
|
||||
</div>
|
||||
|
||||
{/* Prerequisites callout (ONBRD-02) */}
|
||||
<div style={{
|
||||
display: "flex",
|
||||
gap: "var(--space-sm)",
|
||||
background: "var(--bg-tertiary)",
|
||||
border: "1px solid var(--border-subtle)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
padding: "var(--space-sm) var(--space-md)",
|
||||
marginTop: "var(--space-sm)",
|
||||
}}
|
||||
>
|
||||
<Info size={13} style={{ color: "var(--text-muted)", flexShrink: 0, marginTop: 1 }} />
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "var(--space-xs)" }}>
|
||||
<div style={{ ...mutedMicro, fontWeight: 600, color: "var(--text-secondary)" }}>
|
||||
Before connecting
|
||||
</div>
|
||||
<ul style={{ ...mutedMicro, margin: 0, paddingLeft: "var(--space-md)", lineHeight: 1.6 }}>
|
||||
<li>
|
||||
You must be <strong>signed in</strong> to WorldWideView. Your API key is tied to your account.
|
||||
</li>
|
||||
{isCloud && (
|
||||
<li>
|
||||
MCP access is a <strong>cloud edition</strong> feature. It is not available on the demo edition.
|
||||
</li>
|
||||
)}
|
||||
<li>
|
||||
<strong>Read/query tools</strong> (search, geocode, favorites, plugin data) work with just
|
||||
your API key and do not require an open browser tab.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Command/control tools</strong> (pan_globe, fly_to, toggle_layer, set_filter, etc.)
|
||||
require this WorldWideView tab to stay open and signed in. Without an open globe tab the
|
||||
command is accepted but has no visible effect.
|
||||
</li>
|
||||
</ul>
|
||||
<div style={mutedMicro}>
|
||||
New here? Follow the MCP quickstart guide in the project docs (docs/mcp-quickstart.md) for step-by-step setup.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Section: mcpServers JSON (CONNECT-02) */}
|
||||
<div style={subHeaderStyle}>Claude Desktop / Cursor / VS Code</div>
|
||||
<div style={{ ...mutedMicro, marginBottom: "var(--space-sm)" }}>
|
||||
@@ -160,9 +250,6 @@ export function ConnectAgentHelper({ token }: ConnectAgentHelperProps) {
|
||||
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>
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export 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.
|
||||
|
||||
Note: fly_to, set_filter, and clear_filter control the live globe and only take visible effect while you have a signed-in WorldWideView browser tab open. The read and query tools work with just your API key.`;
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -20,9 +20,8 @@ function toWsStreamUrl(url: string): string {
|
||||
const DEFAULT_ENGINE_URL = toWsStreamUrl(RAW_ENGINE_URL);
|
||||
|
||||
function getLocalWsUrl() {
|
||||
const port = process.env.NEXT_PUBLIC_WWV_LOCAL_ENGINE_PORT || '5000';
|
||||
if (typeof window === "undefined") return `ws://localhost:${port}/stream`;
|
||||
return `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.hostname}:${port}/stream`;
|
||||
if (typeof window === "undefined") return "ws://localhost:5000/stream";
|
||||
return `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.hostname}:5000/stream`;
|
||||
}
|
||||
/**
|
||||
* Resolves the WebSocket engine URL for a given plugin.
|
||||
|
||||
@@ -48,24 +48,6 @@ export const isCloud: boolean = edition === "cloud";
|
||||
/** True when running as the public demo instance. */
|
||||
export const isDemo: boolean = edition === "demo";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Secure-context detection (https)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* True when the deployment serves over https, derived from the configured auth
|
||||
* URL or a production NODE_ENV. This is the request-independent half of the
|
||||
* secure-context check: the NextAuth cookie WRITER (auth.ts) uses it to decide
|
||||
* the secure flag / __Secure- cookie prefix, and the edge proxy READER (proxy.ts)
|
||||
* ORs it with per-request X-Forwarded-Proto / protocol when reading the token.
|
||||
* Centralised here so the writer and reader can never disagree on which cookie
|
||||
* name is in play behind a TLS-terminating reverse proxy.
|
||||
*/
|
||||
export function isHttpsDeployment(): boolean {
|
||||
const authUrl = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL ?? "";
|
||||
return authUrl.startsWith("https://") || process.env.NODE_ENV === "production";
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Demo admin secret (must be before feature flags so they can reference it)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -3,7 +3,6 @@ import type {
|
||||
FilterDefinition,
|
||||
FilterValue,
|
||||
} from "@/core/plugins/PluginTypes";
|
||||
import { matchFilterValue } from "./matchFilterValue";
|
||||
|
||||
/**
|
||||
* Apply active filters to a list of entities.
|
||||
@@ -28,10 +27,35 @@ export function applyFilters(
|
||||
|
||||
const propValue = entity.properties[def.propertyKey];
|
||||
|
||||
if (!matchFilterValue(propValue, filterVal)) {
|
||||
if (!matchesFilter(propValue, filterVal)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function matchesFilter(propValue: unknown, filter: FilterValue): boolean {
|
||||
switch (filter.type) {
|
||||
case "text": {
|
||||
if (!filter.value) return true; // empty text = no filter
|
||||
const str = String(propValue ?? "").toLowerCase();
|
||||
return str.includes(filter.value.toLowerCase());
|
||||
}
|
||||
case "select": {
|
||||
if (filter.values.length === 0) return true; // no selection = no filter
|
||||
const pVal = String(propValue ?? "").toLowerCase();
|
||||
return filter.values.some((v) => v.toLowerCase() === pVal);
|
||||
}
|
||||
case "range": {
|
||||
const num = Number(propValue ?? 0);
|
||||
if (isNaN(num)) return false;
|
||||
return num >= filter.min && num <= filter.max;
|
||||
}
|
||||
case "boolean": {
|
||||
return Boolean(propValue) === filter.value;
|
||||
}
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import type { FilterValue } from "@/core/plugins/PluginTypes";
|
||||
|
||||
/**
|
||||
* Pure per-value filter matching shared by the client filterEngine and the
|
||||
* server-side search_entities filter (Phase 23, D-08). Behavior must remain
|
||||
* identical to the original inline filterEngine.matchesFilter.
|
||||
*/
|
||||
export function matchFilterValue(propValue: unknown, filter: FilterValue): boolean {
|
||||
switch (filter.type) {
|
||||
case "text": {
|
||||
if (!filter.value) return true; // empty text = no filter
|
||||
const str = String(propValue ?? "").toLowerCase();
|
||||
return str.includes(filter.value.toLowerCase());
|
||||
}
|
||||
case "select": {
|
||||
if (filter.values.length === 0) return true; // no selection = no filter
|
||||
const pVal = String(propValue ?? "").toLowerCase();
|
||||
return filter.values.some((v) => v.toLowerCase() === pVal);
|
||||
}
|
||||
case "range": {
|
||||
const num = Number(propValue ?? 0);
|
||||
if (isNaN(num)) return false;
|
||||
return num >= filter.min && num <= filter.max;
|
||||
}
|
||||
case "boolean": {
|
||||
return Boolean(propValue) === filter.value;
|
||||
}
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect } from "react";
|
||||
import type { Viewer as CesiumViewer } from "cesium";
|
||||
import {
|
||||
Cartesian3, EasingFunction, Ellipsoid, Math as CesiumMath, Transforms, Matrix4, Rectangle
|
||||
Cartesian3, EasingFunction, Ellipsoid, Math as CesiumMath, Transforms, Matrix4
|
||||
} from "cesium";
|
||||
import { dataBus } from "@/core/data/DataBus";
|
||||
import { showSearchPin } from "./searchPinAnimation";
|
||||
@@ -140,21 +140,9 @@ export function useCameraActions(viewer: CesiumViewer | null, isReady: boolean)
|
||||
}, 50);
|
||||
});
|
||||
|
||||
const unsubFlyToBbox = dataBus.on("cameraFlyToBbox", ({ west, south, east, north }) => {
|
||||
setTimeout(() => {
|
||||
if (!viewer || viewer.isDestroyed()) return;
|
||||
viewer.camera.flyTo({
|
||||
destination: Rectangle.fromDegrees(west, south, east, north),
|
||||
duration: 1.5,
|
||||
easingFunction: EasingFunction.QUINTIC_IN_OUT,
|
||||
});
|
||||
}, 50);
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubFace();
|
||||
unsubGoTo();
|
||||
unsubFlyToBbox();
|
||||
};
|
||||
}, [viewer, isReady]);
|
||||
}
|
||||
@@ -7,8 +7,6 @@
|
||||
* BRIDGE-01 Hook opens EventSource to /api/globe/commands/stream?sessionId=... on mount
|
||||
* BRIDGE-02 pan command dispatched via onmessage -> dataBus.emit("cameraGoTo", ...)
|
||||
* BRIDGE-03 toggleLayer command dispatched via onmessage -> Zustand setLayerEnabled
|
||||
* BRIDGE-03a toggleLayer {enabled:true} -> pluginManager.enablePlugin called
|
||||
* BRIDGE-03b toggleLayer {enabled:false} -> pluginManager.disablePlugin called
|
||||
* BRIDGE-04 Unknown command type via onmessage -> nothing dispatched
|
||||
* BRIDGE-05 Empty sessionId -> EventSource never created
|
||||
* BRIDGE-06 Unmount -> EventSource.close() called
|
||||
@@ -33,22 +31,6 @@ vi.mock("@/core/data/DataBus", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock PluginManager
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const { mockEnablePlugin, mockDisablePlugin } = vi.hoisted(() => ({
|
||||
mockEnablePlugin: vi.fn(() => Promise.resolve()),
|
||||
mockDisablePlugin: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/plugins/PluginManager", () => ({
|
||||
pluginManager: {
|
||||
enablePlugin: mockEnablePlugin,
|
||||
disablePlugin: mockDisablePlugin,
|
||||
},
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock Zustand store
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -59,20 +41,12 @@ const {
|
||||
mockSetTimeWindow,
|
||||
mockSetPlaybackMode,
|
||||
mockSetCurrentTime,
|
||||
mockClearEntities,
|
||||
mockSetEntityCount,
|
||||
mockSetHoveredEntity,
|
||||
mockSetSelectedEntity,
|
||||
} = vi.hoisted(() => ({
|
||||
mockSetLayerEnabled: vi.fn(),
|
||||
mockToggleLayer: vi.fn(),
|
||||
mockSetTimeWindow: vi.fn(),
|
||||
mockSetPlaybackMode: vi.fn(),
|
||||
mockSetCurrentTime: vi.fn(),
|
||||
mockClearEntities: vi.fn(),
|
||||
mockSetEntityCount: vi.fn(),
|
||||
mockSetHoveredEntity: vi.fn(),
|
||||
mockSetSelectedEntity: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/core/state/store", () => ({
|
||||
@@ -83,13 +57,7 @@ vi.mock("@/core/state/store", () => ({
|
||||
setTimeWindow: mockSetTimeWindow,
|
||||
setPlaybackMode: mockSetPlaybackMode,
|
||||
setCurrentTime: mockSetCurrentTime,
|
||||
clearEntities: mockClearEntities,
|
||||
setEntityCount: mockSetEntityCount,
|
||||
setHoveredEntity: mockSetHoveredEntity,
|
||||
setSelectedEntity: mockSetSelectedEntity,
|
||||
layers: {},
|
||||
hoveredEntity: null,
|
||||
selectedEntity: null,
|
||||
})),
|
||||
subscribe: vi.fn(() => () => undefined),
|
||||
},
|
||||
@@ -138,13 +106,7 @@ beforeEach(() => {
|
||||
setTimeWindow: mockSetTimeWindow,
|
||||
setPlaybackMode: mockSetPlaybackMode,
|
||||
setCurrentTime: mockSetCurrentTime,
|
||||
clearEntities: mockClearEntities,
|
||||
setEntityCount: mockSetEntityCount,
|
||||
setHoveredEntity: mockSetHoveredEntity,
|
||||
setSelectedEntity: mockSetSelectedEntity,
|
||||
layers: {},
|
||||
hoveredEntity: null,
|
||||
selectedEntity: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -215,54 +177,6 @@ describe("useGlobeCommandBridge toggleLayer dispatch (BRIDGE-03)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BRIDGE-03a: toggleLayer {enabled:true} -> pluginManager.enablePlugin
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("useGlobeCommandBridge toggleLayer enable (BRIDGE-03a)", () => {
|
||||
it("calls pluginManager.enablePlugin when toggleLayer {enabled:true} arrives", () => {
|
||||
renderHook(() => useGlobeCommandBridge("sess-1"));
|
||||
|
||||
act(() => {
|
||||
mockEs.onmessage?.(
|
||||
new MessageEvent("message", {
|
||||
data: JSON.stringify({
|
||||
commands: [{ type: "toggleLayer", layerId: "camera", enabled: true }],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
expect(mockEnablePlugin).toHaveBeenCalledWith("camera");
|
||||
expect(mockSetLayerEnabled).toHaveBeenCalledWith("camera", true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BRIDGE-03b: toggleLayer {enabled:false} -> pluginManager.disablePlugin
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("useGlobeCommandBridge toggleLayer disable (BRIDGE-03b)", () => {
|
||||
it("calls pluginManager.disablePlugin when toggleLayer {enabled:false} arrives", () => {
|
||||
renderHook(() => useGlobeCommandBridge("sess-1"));
|
||||
|
||||
act(() => {
|
||||
mockEs.onmessage?.(
|
||||
new MessageEvent("message", {
|
||||
data: JSON.stringify({
|
||||
commands: [{ type: "toggleLayer", layerId: "camera", enabled: false }],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
expect(mockDisablePlugin).toHaveBeenCalledWith("camera");
|
||||
expect(mockSetLayerEnabled).toHaveBeenCalledWith("camera", false);
|
||||
expect(mockClearEntities).toHaveBeenCalledWith("camera");
|
||||
expect(mockSetEntityCount).toHaveBeenCalledWith("camera", 0);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BRIDGE-04: unknown command type -> nothing dispatched
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -3,7 +3,6 @@ import { dataBus } from "@/core/data/DataBus";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { isValidGlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { setLayerActive } from "@/core/plugins/layerActivation";
|
||||
|
||||
function dispatchCommand(cmd: GlobeCommand): void {
|
||||
switch (cmd.type) {
|
||||
@@ -18,20 +17,6 @@ function dispatchCommand(cmd: GlobeCommand): void {
|
||||
});
|
||||
break;
|
||||
|
||||
case "flyTo":
|
||||
if (cmd.bbox) {
|
||||
const [west, south, east, north] = cmd.bbox;
|
||||
dataBus.emit("cameraFlyToBbox", { west, south, east, north });
|
||||
} else {
|
||||
dataBus.emit("cameraGoTo", {
|
||||
lat: cmd.lat,
|
||||
lon: cmd.lng, // flyTo uses "lng"; cameraGoTo expects "lon" -- explicit mapping per D-03
|
||||
alt: cmd.alt ?? 15_000,
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
|
||||
case "focusEntity":
|
||||
if (cmd.lat !== undefined && cmd.lon !== undefined) {
|
||||
dataBus.emit("cameraGoTo", {
|
||||
@@ -50,11 +35,11 @@ function dispatchCommand(cmd: GlobeCommand): void {
|
||||
break;
|
||||
|
||||
case "toggleLayer": {
|
||||
const state = useStore.getState();
|
||||
if (cmd.enabled !== undefined) {
|
||||
setLayerActive(cmd.layerId, cmd.enabled);
|
||||
state.setLayerEnabled(cmd.layerId, cmd.enabled);
|
||||
} else {
|
||||
const current = useStore.getState().layers[cmd.layerId]?.enabled ?? false;
|
||||
setLayerActive(cmd.layerId, !current);
|
||||
state.toggleLayer(cmd.layerId);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -76,24 +61,6 @@ function dispatchCommand(cmd: GlobeCommand): void {
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "setFilter": {
|
||||
const state = useStore.getState();
|
||||
for (const [filterId, value] of Object.entries(cmd.filters)) {
|
||||
state.setFilter(cmd.pluginId, filterId, value);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "clearFilter": {
|
||||
const state = useStore.getState();
|
||||
if (cmd.pluginId !== undefined) {
|
||||
state.clearFilters(cmd.pluginId);
|
||||
} else {
|
||||
state.clearAllFilters();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,6 @@ import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { getNamespacedTools } from "@/lib/mcp/pluginTools";
|
||||
import type { PluginToolsEntry } from "@/lib/mcp/pluginTools";
|
||||
import type { CatalogTool } from "@/lib/mcpSessionCatalog";
|
||||
import type { FilterDefinition } from "@/core/plugins/PluginTypes";
|
||||
|
||||
/** Re-publish interval in ms -- mirrors the 19a session-heartbeat cadence. */
|
||||
const PUBLISH_INTERVAL_MS = 30_000;
|
||||
@@ -37,20 +36,13 @@ interface CatalogPayload {
|
||||
sessionId?: string;
|
||||
tools: CatalogTool[];
|
||||
capabilities: string[];
|
||||
filterDefinitions?: Record<string, FilterDefinition[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects mcpTools, mcpCapabilities, and declared filterDefinitions from all
|
||||
* loaded plugins. Only includes plugins whose manifests declare at least one
|
||||
* mcpTool (tools); filterDefinitions includes only plugins that returned a
|
||||
* non-empty array from getFilterDefinitions() (D-05).
|
||||
* Collects mcpTools and mcpCapabilities from all loaded manifests.
|
||||
* Only includes plugins whose manifests declare at least one mcpTool.
|
||||
*/
|
||||
function collectCatalog(): {
|
||||
tools: CatalogTool[];
|
||||
capabilities: string[];
|
||||
filterDefinitions: Record<string, FilterDefinition[]>;
|
||||
} {
|
||||
function collectCatalog(): { tools: CatalogTool[]; capabilities: string[] } {
|
||||
const allPlugins = pluginManager.getAllPlugins();
|
||||
|
||||
const entries: PluginToolsEntry[] = allPlugins.flatMap((managed) => {
|
||||
@@ -82,17 +74,7 @@ function collectCatalog(): {
|
||||
};
|
||||
});
|
||||
|
||||
// Collect declared filterable fields from each loaded plugin instance.
|
||||
// Only include plugins that returned a non-empty definitions array (D-05).
|
||||
const filterDefinitions: Record<string, FilterDefinition[]> = {};
|
||||
for (const managed of allPlugins) {
|
||||
const defs = managed.plugin.getFilterDefinitions?.();
|
||||
if (defs && defs.length > 0) {
|
||||
filterDefinitions[managed.plugin.id] = defs;
|
||||
}
|
||||
}
|
||||
|
||||
return { tools, capabilities: Array.from(capabilitySet), filterDefinitions };
|
||||
return { tools, capabilities: Array.from(capabilitySet) };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -103,20 +85,14 @@ async function publishCatalog(
|
||||
sessionId: string,
|
||||
active: { current: boolean },
|
||||
): Promise<void> {
|
||||
const { tools, capabilities, filterDefinitions } = collectCatalog();
|
||||
const { tools, capabilities } = collectCatalog();
|
||||
|
||||
// No-op only when nothing is publishable: no MCP tools AND no declared
|
||||
// filters. A filter-only plugin still publishes so get_plugin_filters works.
|
||||
if (tools.length === 0 && Object.keys(filterDefinitions).length === 0) return;
|
||||
// No-op when no plugin-declared MCP tools are present
|
||||
if (tools.length === 0) return;
|
||||
|
||||
if (!active.current) return;
|
||||
|
||||
const payload: CatalogPayload = {
|
||||
sessionId,
|
||||
tools,
|
||||
capabilities,
|
||||
...(Object.keys(filterDefinitions).length > 0 && { filterDefinitions }),
|
||||
};
|
||||
const payload: CatalogPayload = { sessionId, tools, capabilities };
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/mcp/catalog", {
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
/**
|
||||
* SEC-04: isValidGlobeCommand input cap tests.
|
||||
*
|
||||
* Verifies that toggleLayer, setFilter, and clearFilter enforce the
|
||||
* layerId/pluginId charset and length bounds introduced in SEC-04.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { isValidGlobeCommand } from "./GlobeCommand";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// toggleLayer -- layerId caps
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("isValidGlobeCommand -- toggleLayer layerId caps (SEC-04)", () => {
|
||||
it("accepts a normal plugin id", () => {
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "ais" })).toBe(true);
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "wwv-flights-2" })).toBe(true);
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "plugin.v2" })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects layerId longer than 64 chars", () => {
|
||||
const long = "a".repeat(65);
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: long })).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts layerId of exactly 64 chars", () => {
|
||||
const exact = "a".repeat(64);
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: exact })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects layerId with spaces", () => {
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "bad id" })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects layerId with colons (reserved for entityId)", () => {
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "ship:123" })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects empty layerId", () => {
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: "" })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects null layerId", () => {
|
||||
expect(isValidGlobeCommand({ type: "toggleLayer", layerId: null })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// setFilter -- pluginId caps
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("isValidGlobeCommand -- setFilter pluginId caps (SEC-04)", () => {
|
||||
const validFilters = { status: { type: "text", value: "live" } };
|
||||
|
||||
it("accepts a normal plugin id", () => {
|
||||
expect(isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: validFilters })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects pluginId longer than 64 chars", () => {
|
||||
const long = "a".repeat(65);
|
||||
expect(isValidGlobeCommand({ type: "setFilter", pluginId: long, filters: validFilters })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pluginId with special chars outside the allowed set", () => {
|
||||
expect(isValidGlobeCommand({ type: "setFilter", pluginId: "bad id!", filters: validFilters })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects empty pluginId", () => {
|
||||
expect(isValidGlobeCommand({ type: "setFilter", pluginId: "", filters: validFilters })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// clearFilter -- pluginId caps (optional)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("isValidGlobeCommand -- clearFilter pluginId caps (SEC-04)", () => {
|
||||
it("accepts a normal plugin id", () => {
|
||||
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: "flights" })).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts absent pluginId (clear all)", () => {
|
||||
expect(isValidGlobeCommand({ type: "clearFilter" })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects oversized pluginId", () => {
|
||||
const long = "x".repeat(65);
|
||||
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: long })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pluginId with disallowed chars", () => {
|
||||
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: "a b" })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// focusEntity -- entityId caps (MUST-FIX #1)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("isValidGlobeCommand -- focusEntity entityId caps (SEC-04)", () => {
|
||||
it("accepts a normal entity id", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "ship:123" })).toBe(true);
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "flight/AFR123" })).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts absent entityId (coordinate-only focus)", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", lat: 35.68, lon: 139.69 })).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts entityId of exactly 256 chars", () => {
|
||||
const exact = "a".repeat(256);
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: exact })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects entityId longer than 256 chars", () => {
|
||||
const long = "a".repeat(257);
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: long })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects entityId with control characters", () => {
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "ship\x00123" })).toBe(false);
|
||||
expect(isValidGlobeCommand({ type: "focusEntity", entityId: "flight\n456" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -131,7 +131,7 @@ describe("isValidGlobeCommand", () => {
|
||||
// CMD-07
|
||||
it("returns false for an unknown type", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "unknownCommand", lat: 1, lon: 2 })
|
||||
isValidGlobeCommand({ type: "flyTo", lat: 1, lon: 2 })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
@@ -162,105 +162,3 @@ describe("isValidGlobeCommand", () => {
|
||||
expect(isValidGlobeCommand([])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("flyTo validator", () => {
|
||||
it("accepts valid point command with lat and lng only", () => {
|
||||
expect(isValidGlobeCommand({ type: "flyTo", lat: 51.5, lng: -0.1 })).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts valid point command with lat, lng, and alt", () => {
|
||||
expect(isValidGlobeCommand({ type: "flyTo", lat: 51.5, lng: -0.1, alt: 15000 })).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts valid command with a 4-element bbox [west,south,east,north]", () => {
|
||||
expect(isValidGlobeCommand({ type: "flyTo", lat: 51.5, lng: -0.1, bbox: [-1, 50, 1, 52] })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects bbox with wrong length (3 elements)", () => {
|
||||
expect(isValidGlobeCommand({ type: "flyTo", lat: 51.5, lng: -0.1, bbox: [-1, 50, 1] })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects lat out of range (>90)", () => {
|
||||
expect(isValidGlobeCommand({ type: "flyTo", lat: 91, lng: 0 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects lng out of range (>180)", () => {
|
||||
expect(isValidGlobeCommand({ type: "flyTo", lat: 0, lng: 181 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects negative alt (alt must be > 0 if provided)", () => {
|
||||
expect(isValidGlobeCommand({ type: "flyTo", lat: 0, lng: 0, alt: -1 })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects bbox with non-numeric element", () => {
|
||||
expect(isValidGlobeCommand({ type: "flyTo", lat: 0, lng: 0, bbox: ["west", 50, 1, 52] })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setFilter / clearFilter validator", () => {
|
||||
it("accepts setFilter with a select filter value", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { status: { type: "select", values: ["airborne"] } } })
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts setFilter with a range filter value", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { alt: { type: "range", min: 0, max: 1000 } } })
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts setFilter with a boolean filter value", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { live: { type: "boolean", value: true } } })
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts setFilter with a text filter value", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { name: { type: "text", value: "ba" } } })
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects setFilter with an empty pluginId", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "setFilter", pluginId: "", filters: {} })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects setFilter when select values is not an array", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { x: { type: "select", values: "nope" } } })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects setFilter when range min is not a number", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { x: { type: "range", min: "0", max: 1 } } })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects setFilter with an unknown filter type", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { x: { type: "bogus" } } })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects setFilter when filters is not an object", () => {
|
||||
expect(
|
||||
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: null })
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts clearFilter with no pluginId (clear all)", () => {
|
||||
expect(isValidGlobeCommand({ type: "clearFilter" })).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts clearFilter with a pluginId", () => {
|
||||
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: "flights" })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects clearFilter when pluginId is not a string", () => {
|
||||
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: 123 })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,3 @@
|
||||
import type { FilterValue } from "@/core/plugins/PluginTypes";
|
||||
import { PLUGIN_ID_MAX, PLUGIN_ID_RE, ENTITY_ID_MAX } from "@/lib/mcp/identifierSchemas";
|
||||
|
||||
// Must stay in sync with the TimeWindow union in @worldwideview/wwv-plugin-sdk.
|
||||
export const TIME_WINDOW_VALUES = ["1h", "6h", "24h", "48h", "7d"] as const;
|
||||
export type TimeWindowLiteral = (typeof TIME_WINDOW_VALUES)[number];
|
||||
@@ -9,10 +6,7 @@ export type GlobeCommand =
|
||||
| { type: "pan"; lat: number; lon: number; alt: number; duration?: number; heading?: number; pitch?: number }
|
||||
| { type: "focusEntity"; entityId?: string; lat?: number; lon?: number }
|
||||
| { type: "toggleLayer"; layerId: string; enabled?: boolean }
|
||||
| { type: "setTimeline"; currentTime?: string; timeWindow?: TimeWindowLiteral; isPlaybackMode?: boolean }
|
||||
| { type: "flyTo"; lat: number; lng: number; alt?: number; bbox?: [number, number, number, number] }
|
||||
| { type: "setFilter"; pluginId: string; filters: Record<string, FilterValue> }
|
||||
| { type: "clearFilter"; pluginId?: string };
|
||||
| { type: "setTimeline"; currentTime?: string; timeWindow?: TimeWindowLiteral; isPlaybackMode?: boolean };
|
||||
|
||||
function isNumber(v: unknown): v is number {
|
||||
return typeof v === "number" && isFinite(v);
|
||||
@@ -30,27 +24,18 @@ function isValidAlt(v: unknown): v is number {
|
||||
return isNumber(v) && v > 0;
|
||||
}
|
||||
|
||||
// SEC-04: bounds come from identifierSchemas.ts (single source of truth)
|
||||
function isValidPluginOrLayerId(v: unknown): v is string {
|
||||
return typeof v === "string" && v.length > 0 && v.length <= PLUGIN_ID_MAX && PLUGIN_ID_RE.test(v);
|
||||
}
|
||||
|
||||
function isValidEntityId(v: unknown): v is string {
|
||||
return typeof v === "string" && v.length > 0 && v.length <= ENTITY_ID_MAX && !/[\x00-\x1F\x7F]/.test(v);
|
||||
}
|
||||
|
||||
function isOptionalEntityId(v: unknown): boolean {
|
||||
return v === undefined || isValidEntityId(v);
|
||||
}
|
||||
|
||||
function isOptionalPluginOrLayerId(v: unknown): boolean {
|
||||
return v === undefined || isValidPluginOrLayerId(v);
|
||||
function isString(v: unknown): v is string {
|
||||
return typeof v === "string";
|
||||
}
|
||||
|
||||
function isOptionalNumber(v: unknown): boolean {
|
||||
return v === undefined || isNumber(v);
|
||||
}
|
||||
|
||||
function isOptionalString(v: unknown): boolean {
|
||||
return v === undefined || isString(v);
|
||||
}
|
||||
|
||||
function isOptionalBoolean(v: unknown): boolean {
|
||||
return v === undefined || typeof v === "boolean";
|
||||
}
|
||||
@@ -73,23 +58,6 @@ function isOptionalDateString(v: unknown): boolean {
|
||||
return v === undefined || isValidDateString(v);
|
||||
}
|
||||
|
||||
function isValidFilterValue(v: unknown): v is FilterValue {
|
||||
if (v === null || typeof v !== "object" || Array.isArray(v)) return false;
|
||||
const fv = v as Record<string, unknown>;
|
||||
switch (fv["type"]) {
|
||||
case "text":
|
||||
return typeof fv["value"] === "string";
|
||||
case "select":
|
||||
return Array.isArray(fv["values"]) && fv["values"].every((x) => typeof x === "string");
|
||||
case "range":
|
||||
return isNumber(fv["min"]) && isNumber(fv["max"]);
|
||||
case "boolean":
|
||||
return typeof fv["value"] === "boolean";
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isValidGlobeCommand(obj: unknown): obj is GlobeCommand {
|
||||
if (obj === null || typeof obj !== "object" || Array.isArray(obj)) {
|
||||
return false;
|
||||
@@ -110,14 +78,14 @@ export function isValidGlobeCommand(obj: unknown): obj is GlobeCommand {
|
||||
|
||||
case "focusEntity":
|
||||
return (
|
||||
isOptionalEntityId(cmd["entityId"]) &&
|
||||
isOptionalString(cmd["entityId"]) &&
|
||||
(cmd["lat"] === undefined || isValidLat(cmd["lat"])) &&
|
||||
(cmd["lon"] === undefined || isValidLon(cmd["lon"]))
|
||||
);
|
||||
|
||||
case "toggleLayer":
|
||||
return (
|
||||
isValidPluginOrLayerId(cmd["layerId"]) &&
|
||||
isString(cmd["layerId"]) &&
|
||||
isOptionalBoolean(cmd["enabled"])
|
||||
);
|
||||
|
||||
@@ -128,33 +96,6 @@ export function isValidGlobeCommand(obj: unknown): obj is GlobeCommand {
|
||||
isOptionalBoolean(cmd["isPlaybackMode"])
|
||||
);
|
||||
|
||||
case "flyTo": {
|
||||
if (!isValidLat(cmd["lat"])) return false;
|
||||
if (!(isNumber(cmd["lng"]) && (cmd["lng"] as number) >= -180 && (cmd["lng"] as number) <= 180)) return false;
|
||||
if (!(isOptionalNumber(cmd["alt"]) && (cmd["alt"] === undefined || isValidAlt(cmd["alt"])))) return false;
|
||||
if (cmd["bbox"] !== undefined) {
|
||||
const bbox = cmd["bbox"];
|
||||
if (!Array.isArray(bbox) || bbox.length !== 4) return false;
|
||||
if (!bbox.every((v: unknown) => isNumber(v))) return false;
|
||||
const [west, south, east, north] = bbox as number[];
|
||||
if (west < -180 || west > 180) return false;
|
||||
if (south < -90 || south > 90) return false;
|
||||
if (east < -180 || east > 180) return false;
|
||||
if (north < -90 || north > 90) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
case "setFilter": {
|
||||
if (!isValidPluginOrLayerId(cmd["pluginId"])) return false;
|
||||
const filters = cmd["filters"];
|
||||
if (filters === null || typeof filters !== "object" || Array.isArray(filters)) return false;
|
||||
return Object.values(filters as Record<string, unknown>).every(isValidFilterValue);
|
||||
}
|
||||
|
||||
case "clearFilter":
|
||||
return isOptionalPluginOrLayerId(cmd["pluginId"]);
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { useStore } from "@/core/state/store";
|
||||
|
||||
/**
|
||||
* Single source of truth for activating or deactivating a plugin layer's data lifecycle.
|
||||
* Shared by the UI (LayerPanel) and the agent command bridge (useGlobeCommandBridge)
|
||||
* so both paths trigger identical data loading and entity cleanup behaviour.
|
||||
*
|
||||
* UI-panel-only concerns (highlight layer, open config panel, active config tab,
|
||||
* analytics) are NOT handled here -- they stay in LayerPanel.
|
||||
*/
|
||||
export function setLayerActive(pluginId: string, enabled: boolean): void {
|
||||
const store = useStore.getState();
|
||||
if (enabled) {
|
||||
void pluginManager.enablePlugin(pluginId);
|
||||
store.setLayerEnabled(pluginId, true);
|
||||
} else {
|
||||
pluginManager.disablePlugin(pluginId);
|
||||
store.setLayerEnabled(pluginId, false);
|
||||
store.clearEntities(pluginId);
|
||||
store.setEntityCount(pluginId, 0);
|
||||
if (store.hoveredEntity?.pluginId === pluginId) {
|
||||
store.setHoveredEntity(null, null);
|
||||
}
|
||||
if (store.selectedEntity?.pluginId === pluginId) {
|
||||
store.setSelectedEntity(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -264,91 +264,6 @@ describe("validateManifest mcpCapabilities field (MAN-03)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MAN-LD: localData array validation (Phase 30, D-02)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("validateManifest localData field (MAN-LD)", () => {
|
||||
it("accepts a manifest with no localData field (unchanged pass-through)", () => {
|
||||
const result = validateManifest(baseManifest());
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("accepts a well-formed localData array with geojson and route entries", () => {
|
||||
const manifest = baseManifest({
|
||||
localData: [
|
||||
{ name: "default", type: "geojson", path: "/public-cameras.json" },
|
||||
{ name: "traffic", type: "route", path: "/api/camera/traffic" },
|
||||
],
|
||||
});
|
||||
const result = validateManifest(manifest);
|
||||
const hasLocalDataError = result.errors.some((e) => /localData/i.test(e));
|
||||
expect(hasLocalDataError).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects localData that is not an array (string instead of array)", () => {
|
||||
const manifest = baseManifest({ localData: "not-an-array" });
|
||||
const result = validateManifest(manifest);
|
||||
const hasLocalDataError = result.errors.some((e) =>
|
||||
/localData must be an array/i.test(e),
|
||||
);
|
||||
expect(hasLocalDataError).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a localData entry missing name (empty string)", () => {
|
||||
const manifest = baseManifest({
|
||||
localData: [
|
||||
{ name: "", type: "geojson", path: "/data.json" },
|
||||
],
|
||||
});
|
||||
const result = validateManifest(manifest);
|
||||
const hasNameError = result.errors.some(
|
||||
(e) => /localData\[0\].*name/i.test(e) || /localData\[0\].*name/i.test(e),
|
||||
);
|
||||
expect(hasNameError).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a localData entry with an invalid type (not geojson or route)", () => {
|
||||
const manifest = baseManifest({
|
||||
localData: [
|
||||
{ name: "default", type: "external", path: "/data.json" },
|
||||
],
|
||||
});
|
||||
const result = validateManifest(manifest);
|
||||
const hasTypeError = result.errors.some(
|
||||
(e) => /localData\[0\].*type/i.test(e),
|
||||
);
|
||||
expect(hasTypeError).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a localData entry with a path that does not start with /", () => {
|
||||
const manifest = baseManifest({
|
||||
localData: [
|
||||
{ name: "default", type: "geojson", path: "relative/path.json" },
|
||||
],
|
||||
});
|
||||
const result = validateManifest(manifest);
|
||||
const hasPathError = result.errors.some(
|
||||
(e) => /localData\[0\].*path/i.test(e),
|
||||
);
|
||||
expect(hasPathError).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a localData entry with a path containing .. (traversal)", () => {
|
||||
const manifest = baseManifest({
|
||||
localData: [
|
||||
{ name: "default", type: "geojson", path: "/../etc/passwd" },
|
||||
],
|
||||
});
|
||||
const result = validateManifest(manifest);
|
||||
const hasPathError = result.errors.some(
|
||||
(e) => /localData\[0\].*path/i.test(e),
|
||||
);
|
||||
expect(hasPathError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MAN-04: no "execution" field required (v3 -- server never executes plugin tools)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -22,30 +22,6 @@ const VALID_TRUSTS = ["built-in", "verified", "unverified"] as const;
|
||||
/** Regex for a safe MCP tool name identifier: only [a-zA-Z0-9_-]. */
|
||||
const SAFE_TOOL_NAME = /^[a-zA-Z0-9_-]+$/;
|
||||
|
||||
/**
|
||||
* Hostnames derived from the configured marketplace/instance URLs. A plugin
|
||||
* bundle served from a custom deployment host (e.g. marketplace.wwv.local) must
|
||||
* be accepted by the entry-URL allowlist below without that host being
|
||||
* hardcoded. Computed once at module load; bad env values are skipped rather
|
||||
* than crashing the module.
|
||||
*/
|
||||
const ENV_ALLOWED_ENTRY_HOSTS: ReadonlySet<string> = (() => {
|
||||
const hosts = new Set<string>();
|
||||
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 {
|
||||
hosts.add(new URL(envUrl).hostname);
|
||||
} catch {
|
||||
// Ignore unparsable env values — they simply don't contribute a host.
|
||||
}
|
||||
}
|
||||
return hosts;
|
||||
})();
|
||||
|
||||
/**
|
||||
* Validates a plugin manifest for structural integrity and security compliance.
|
||||
* This is the primary security gate for the WorldWideView plugin ecosystem.
|
||||
@@ -91,20 +67,7 @@ export function validateManifest(
|
||||
const isWWV = entry.includes(".worldwideview.dev");
|
||||
const isCDN = entry.startsWith("https://cdn.jsdelivr.net") || entry.startsWith("https://unpkg.com");
|
||||
|
||||
// Accept bundles served from a configured marketplace/instance host
|
||||
// (e.g. marketplace.wwv.local) derived from env, so custom deployment
|
||||
// hostnames work without being hardcoded.
|
||||
let isConfiguredHost = false;
|
||||
if (ENV_ALLOWED_ENTRY_HOSTS.size > 0) {
|
||||
try {
|
||||
isConfiguredHost = ENV_ALLOWED_ENTRY_HOSTS.has(new URL(entry).hostname);
|
||||
} catch {
|
||||
// Relative paths and other non-absolute entries aren't parseable
|
||||
// as full URLs — they're already covered by `isRelative`.
|
||||
}
|
||||
}
|
||||
|
||||
if (!isRelative && !isLocal && !isWWV && !isCDN && !isConfiguredHost) {
|
||||
if (!isRelative && !isLocal && !isWWV && !isCDN) {
|
||||
errors.push("entry URL must be a relative path, CDN, localhost, or worldwideview.dev domain");
|
||||
}
|
||||
}
|
||||
@@ -163,36 +126,5 @@ export function validateManifest(
|
||||
}
|
||||
}
|
||||
|
||||
// MAN-LD: validate localData entries when present (Phase 30, D-02, T-30-01/T-30-02)
|
||||
if ("localData" in manifest && manifest.localData !== undefined) {
|
||||
if (!Array.isArray(manifest.localData)) {
|
||||
errors.push("localData must be an array when present");
|
||||
} else {
|
||||
const VALID_LOCAL_DATA_TYPES = ["geojson", "route"] as const;
|
||||
(manifest.localData as unknown as Record<string, unknown>[]).forEach((entry, idx) => {
|
||||
const prefix = `localData[${idx}]`;
|
||||
|
||||
// name must be a non-empty string
|
||||
if (typeof entry.name !== "string" || !(entry.name as string).trim()) {
|
||||
errors.push(`${prefix}: name must be a non-empty string`);
|
||||
}
|
||||
|
||||
// type must be one of the allowed literals
|
||||
if (!VALID_LOCAL_DATA_TYPES.includes(entry.type as typeof VALID_LOCAL_DATA_TYPES[number])) {
|
||||
errors.push(
|
||||
`${prefix}: type "${String(entry.type)}" is invalid; must be one of: ${VALID_LOCAL_DATA_TYPES.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
// path must be a string starting with "/" and must not contain ".." (T-30-01)
|
||||
if (typeof entry.path !== "string" || !(entry.path as string).startsWith("/")) {
|
||||
errors.push(`${prefix}: path must be a string starting with "/"`);
|
||||
} else if ((entry.path as string).includes("..")) {
|
||||
errors.push(`${prefix}: path must not contain ".." (traversal rejected)`);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: errors.length === 0, errors };
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import { vi } from "vitest";
|
||||
|
||||
/**
|
||||
* Manual mock for `@/lib/prisma`.
|
||||
*
|
||||
* The real module re-exports a Prisma client whose underlying singleton
|
||||
* (`@/lib/db`) throws on any property access when DATABASE_URL is unset (the
|
||||
* test environment). That makes vitest's automock unusable here, so this manual
|
||||
* mock supplies a deep-mocked `prisma.favorite` surface that tests can drive
|
||||
* via `vi.mocked(prisma, true)`.
|
||||
*/
|
||||
export const prisma = {
|
||||
favorite: {
|
||||
upsert: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
count: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
};
|
||||
@@ -1,169 +0,0 @@
|
||||
/**
|
||||
* SEC-01: getSigningKey() enforcement tests.
|
||||
*
|
||||
* Each describe block uses vi.resetModules() + vi.doMock() to control
|
||||
* the edition and environment independently -- the module-level mocks in
|
||||
* apiKeyAuth.test.ts cannot be re-used here because they are static.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
userApiKey: {
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const ORIGINAL_ENV = { ...process.env };
|
||||
|
||||
beforeEach(() => {
|
||||
// Restore env before each test so mutations do not bleed
|
||||
process.env = { ...ORIGINAL_ENV };
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...ORIGINAL_ENV };
|
||||
vi.resetModules();
|
||||
vi.doUnmock("@/core/edition");
|
||||
});
|
||||
|
||||
async function importGenerateApiKey() {
|
||||
// Dynamic import after resetModules + doMock so the edition mock is picked up
|
||||
const mod = await import("./apiKeyAuth");
|
||||
return mod.generateApiKey;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Local edition: AUTH_SECRET fallback must still work (dev DX)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("SEC-01: local edition -- AUTH_SECRET fallback is allowed", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.doMock("@/core/edition", () => ({
|
||||
edition: "local",
|
||||
isLocal: true,
|
||||
isCloud: false,
|
||||
isDemo: false,
|
||||
}));
|
||||
});
|
||||
|
||||
it("succeeds when only AUTH_SECRET is set (no API_KEY_HMAC_SECRET)", async () => {
|
||||
delete process.env.API_KEY_HMAC_SECRET;
|
||||
process.env.AUTH_SECRET = "some-auth-secret";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).not.toThrow();
|
||||
});
|
||||
|
||||
it("succeeds when API_KEY_HMAC_SECRET equals AUTH_SECRET in local edition", async () => {
|
||||
process.env.API_KEY_HMAC_SECRET = "shared-secret";
|
||||
process.env.AUTH_SECRET = "shared-secret";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).not.toThrow();
|
||||
});
|
||||
|
||||
it("throws only when neither key is set", async () => {
|
||||
delete process.env.API_KEY_HMAC_SECRET;
|
||||
delete process.env.AUTH_SECRET;
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).toThrow("API_KEY_HMAC_SECRET (or AUTH_SECRET) must be set");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cloud edition: dedicated key required, must differ from AUTH_SECRET
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("SEC-01: cloud edition -- API_KEY_HMAC_SECRET required and distinct", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.doMock("@/core/edition", () => ({
|
||||
edition: "cloud",
|
||||
isLocal: false,
|
||||
isCloud: true,
|
||||
isDemo: false,
|
||||
}));
|
||||
});
|
||||
|
||||
it("throws when API_KEY_HMAC_SECRET is unset", async () => {
|
||||
delete process.env.API_KEY_HMAC_SECRET;
|
||||
process.env.AUTH_SECRET = "some-auth-secret";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).toThrow(
|
||||
"API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in cloud edition",
|
||||
);
|
||||
});
|
||||
|
||||
it("throws when API_KEY_HMAC_SECRET equals AUTH_SECRET", async () => {
|
||||
process.env.API_KEY_HMAC_SECRET = "shared-secret";
|
||||
process.env.AUTH_SECRET = "shared-secret";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).toThrow(
|
||||
"API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in cloud edition",
|
||||
);
|
||||
});
|
||||
|
||||
it("succeeds when API_KEY_HMAC_SECRET is set and differs from AUTH_SECRET", async () => {
|
||||
process.env.API_KEY_HMAC_SECRET = "dedicated-hmac-key-cloud";
|
||||
process.env.AUTH_SECRET = "different-auth-secret";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Demo edition: same enforcement as cloud
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("SEC-01: demo edition -- API_KEY_HMAC_SECRET required and distinct", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.doMock("@/core/edition", () => ({
|
||||
edition: "demo",
|
||||
isLocal: false,
|
||||
isCloud: false,
|
||||
isDemo: true,
|
||||
}));
|
||||
});
|
||||
|
||||
it("throws when API_KEY_HMAC_SECRET is unset", async () => {
|
||||
delete process.env.API_KEY_HMAC_SECRET;
|
||||
process.env.AUTH_SECRET = "some-auth-secret";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).toThrow(
|
||||
"API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in demo edition",
|
||||
);
|
||||
});
|
||||
|
||||
it("throws when API_KEY_HMAC_SECRET equals AUTH_SECRET", async () => {
|
||||
process.env.API_KEY_HMAC_SECRET = "same";
|
||||
process.env.AUTH_SECRET = "same";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).toThrow(
|
||||
"API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in demo edition",
|
||||
);
|
||||
});
|
||||
|
||||
it("succeeds when API_KEY_HMAC_SECRET is set and differs from AUTH_SECRET", async () => {
|
||||
process.env.API_KEY_HMAC_SECRET = "dedicated-hmac-key-demo";
|
||||
process.env.AUTH_SECRET = "different-auth-secret-demo";
|
||||
|
||||
const generateApiKey = await importGenerateApiKey();
|
||||
expect(() => generateApiKey()).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -20,9 +20,6 @@ vi.mock("@/lib/db", () => ({
|
||||
|
||||
vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
edition: "local",
|
||||
isLocal: true,
|
||||
isCloud: false,
|
||||
}));
|
||||
|
||||
// AUTH_SECRET must be set so getSigningKey() does not throw in the test env
|
||||
@@ -159,17 +156,6 @@ describe("authenticateApiKey", () => {
|
||||
// compare is well-defined and does not throw.
|
||||
});
|
||||
|
||||
it("returns null (does not throw) when Prisma findUnique rejects (DB outage — TRANS-02)", async () => {
|
||||
vi.mocked(prisma.userApiKey.findUnique).mockRejectedValue(
|
||||
new Error("Connection refused")
|
||||
);
|
||||
const req = new Request("http://localhost/api/test", {
|
||||
headers: { authorization: "Bearer wwv_XXXXXXXX.fakesecret" },
|
||||
});
|
||||
// Must resolve to null, not reject
|
||||
await expect(authenticateApiKey(req)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("hashedSecret is never returned to callers — result only contains userId and keyId", async () => {
|
||||
const { prefix, secret, hashedSecret } = generateApiKey();
|
||||
vi.mocked(prisma.userApiKey.findUnique).mockResolvedValue({
|
||||
|
||||
+6
-38
@@ -1,38 +1,14 @@
|
||||
import { randomBytes, createHmac, timingSafeEqual } from "crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { edition } from "@/core/edition";
|
||||
import { isSigningKeyValid } from "@/lib/signingKeyConfig";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Signing key for HMAC-SHA256 hashing of API key secrets.
|
||||
// API_KEY_HMAC_SECRET is the preferred dedicated variable.
|
||||
// Falls back to AUTH_SECRET in local edition only, so dev works without a
|
||||
// separate .env entry.
|
||||
//
|
||||
// Lazy enforcement (not a bare module-level throw): Next.js evaluates module
|
||||
// code at build time and during edge prerender. A top-level throw would break
|
||||
// `next build` in environments where these env vars are not yet populated.
|
||||
// Throwing inside the function means the check fires only on the first real
|
||||
// auth call, where a missing/shared key is an actual runtime problem.
|
||||
// Falls back to AUTH_SECRET so local dev works without adding a new .env entry.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function getSigningKey(): string {
|
||||
const dedicated = process.env.API_KEY_HMAC_SECRET;
|
||||
const fallback = process.env.AUTH_SECRET;
|
||||
|
||||
if (edition === "cloud" || edition === "demo") {
|
||||
if (!isSigningKeyValid()) {
|
||||
throw new Error(
|
||||
`API_KEY_HMAC_SECRET must be set and distinct from AUTH_SECRET in ${edition} edition`,
|
||||
);
|
||||
}
|
||||
// isSigningKeyValid() returning true guarantees dedicated is set and
|
||||
// distinct from AUTH_SECRET for cloud/demo editions.
|
||||
return dedicated as string;
|
||||
}
|
||||
|
||||
// local edition: allow AUTH_SECRET fallback for convenience
|
||||
const key = dedicated ?? fallback;
|
||||
const key = process.env.API_KEY_HMAC_SECRET ?? process.env.AUTH_SECRET;
|
||||
if (!key) throw new Error("API_KEY_HMAC_SECRET (or AUTH_SECRET) must be set");
|
||||
return key;
|
||||
}
|
||||
@@ -140,18 +116,10 @@ export async function authenticateApiKey(
|
||||
const prefix = token.substring(0, dotIdx);
|
||||
const secret = token.substring(dotIdx + 1);
|
||||
|
||||
// DB outage guard (TRANS-02): a rejected Prisma call is treated as a miss
|
||||
// so the caller receives null (-> 401) rather than an unhandled rejection.
|
||||
let row: { id: string; userId: string; hashedSecret: string } | null;
|
||||
try {
|
||||
row = await prisma.userApiKey.findUnique({
|
||||
where: { prefix },
|
||||
select: { id: true, userId: true, hashedSecret: true },
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn("[apiKeyAuth] DB error during key lookup:", err instanceof Error ? err.name : "unknown");
|
||||
return null;
|
||||
}
|
||||
const row = await prisma.userApiKey.findUnique({
|
||||
where: { prefix },
|
||||
select: { id: true, userId: true, hashedSecret: true },
|
||||
});
|
||||
|
||||
// Compute HMAC of the supplied secret, then compare with timingSafeEqual.
|
||||
// On a prefix miss we compare against a dummy digest — constant-work on
|
||||
|
||||
+1
-45
@@ -18,9 +18,8 @@ vi.unmock("@/lib/auth");
|
||||
// vi.hoisted() runs before all vi.mock() factories, so the variable is
|
||||
// defined before the hoisted factory closure captures it.
|
||||
// ---------------------------------------------------------------------------
|
||||
const { mockUpsert, mockFindUnique } = vi.hoisted(() => ({
|
||||
const { mockUpsert } = vi.hoisted(() => ({
|
||||
mockUpsert: vi.fn().mockResolvedValue(undefined),
|
||||
mockFindUnique: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
@@ -28,7 +27,6 @@ vi.mock("@/lib/db", () => ({
|
||||
user: {
|
||||
upsert: mockUpsert,
|
||||
findFirst: vi.fn(),
|
||||
findUnique: mockFindUnique,
|
||||
},
|
||||
},
|
||||
}));
|
||||
@@ -56,7 +54,6 @@ vi.mock("@/core/edition", () => ({
|
||||
isDemo: false,
|
||||
getDemoAdminSecret: vi.fn(() => undefined),
|
||||
DEMO_ADMIN_ROLE: "demo-admin",
|
||||
isHttpsDeployment: vi.fn(() => false),
|
||||
}));
|
||||
vi.mock("bcryptjs", () => ({ compareSync: vi.fn(() => false) }));
|
||||
|
||||
@@ -64,7 +61,6 @@ vi.mock("bcryptjs", () => ({ compareSync: vi.fn(() => false) }));
|
||||
import {
|
||||
persistDemoAdminIfNeeded,
|
||||
ensureLocalUserPersisted,
|
||||
revalidateSession,
|
||||
DEMO_ADMIN_ID,
|
||||
DEMO_ADMIN_EMAIL,
|
||||
DEMO_ADMIN_NAME,
|
||||
@@ -152,43 +148,3 @@ describe("persistDemoAdminIfNeeded -- jwt callback guard", () => {
|
||||
expect(mockUpsert).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// revalidateSession -- authoritative JWT revocation check
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("revalidateSession -- jwt revocation check", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("returns null when the token carries no user id", async () => {
|
||||
const result = await revalidateSession({});
|
||||
expect(result).toBeNull();
|
||||
expect(mockFindUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns null when the user no longer exists in the DB (deleted / cross-database token)", async () => {
|
||||
mockFindUnique.mockResolvedValue(null);
|
||||
const result = await revalidateSession({ id: "missing-user", sessionVersion: 0 });
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the token sessionVersion is stale (revoked / logout-everywhere)", async () => {
|
||||
mockFindUnique.mockResolvedValue({ sessionVersion: 3, role: "user" });
|
||||
const result = await revalidateSession({ id: "u1", sessionVersion: 2 });
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns the token with role refreshed when the version matches", async () => {
|
||||
mockFindUnique.mockResolvedValue({ sessionVersion: 5, role: "admin" });
|
||||
const result = await revalidateSession({ id: "u1", sessionVersion: 5, role: "user" });
|
||||
expect(result).not.toBeNull();
|
||||
expect((result as { role?: string }).role).toBe("admin");
|
||||
});
|
||||
|
||||
it("treats a missing token sessionVersion as 0", async () => {
|
||||
mockFindUnique.mockResolvedValue({ sessionVersion: 0, role: "user" });
|
||||
const result = await revalidateSession({ id: "u1" });
|
||||
expect(result).not.toBeNull();
|
||||
});
|
||||
});
|
||||
+5
-75
@@ -3,9 +3,8 @@ import Credentials from "next-auth/providers/credentials";
|
||||
import { compareSync } from "bcryptjs";
|
||||
import { timingSafeEqual } from "crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import type { JWT } from "next-auth/jwt";
|
||||
import {
|
||||
isDemo, isCloud, getDemoAdminSecret, DEMO_ADMIN_ROLE, isHttpsDeployment
|
||||
isDemo, isCloud, getDemoAdminSecret, DEMO_ADMIN_ROLE
|
||||
} from "@/core/edition";
|
||||
import { authConfig } from "@/lib/auth.config";
|
||||
import { SupabaseAdapter } from "@auth/supabase-adapter";
|
||||
@@ -92,7 +91,6 @@ const localCredentialsProvider = Credentials({
|
||||
name: "Demo Admin",
|
||||
email: "admin",
|
||||
role: DEMO_ADMIN_ROLE,
|
||||
sessionVersion: 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -122,72 +120,15 @@ const localCredentialsProvider = Credentials({
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
sessionVersion: user.sessionVersion,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
// True when the deployment serves over https (session cookie gets the secure
|
||||
// flag / __Secure- prefix). Shared with the edge proxy reader via
|
||||
// isHttpsDeployment() so the cookie writer and reader never disagree on the
|
||||
// __Secure- prefix behind a TLS-terminating reverse proxy.
|
||||
const isSecureDeploy = isHttpsDeployment();
|
||||
|
||||
/**
|
||||
* Authoritative session revocation check, run from the jwt callback on every
|
||||
* non-sign-in request (local/demo editions). Returns the token unchanged when
|
||||
* still valid, or `null` to invalidate the session when:
|
||||
* - the user row no longer exists (deleted, or the token was minted against a
|
||||
* different database, e.g. another worktree/instance even with a shared
|
||||
* AUTH_SECRET), or
|
||||
* - the user's sessionVersion was bumped (logout-everywhere / credential
|
||||
* rotation), making the token's embedded version stale.
|
||||
*/
|
||||
export async function revalidateSession(token: JWT): Promise<JWT | null> {
|
||||
const userId = token.id;
|
||||
if (typeof userId !== "string" || !userId) return null;
|
||||
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { sessionVersion: true, role: true },
|
||||
});
|
||||
if (!dbUser) return null;
|
||||
|
||||
const tokenVersion = typeof token.sessionVersion === "number" ? token.sessionVersion : 0;
|
||||
if (dbUser.sessionVersion !== tokenVersion) return null;
|
||||
|
||||
// Keep role fresh in case it changed server-side since the token was issued.
|
||||
token.role = dbUser.role;
|
||||
return token;
|
||||
}
|
||||
|
||||
export const {
|
||||
handlers, auth, signIn, signOut
|
||||
} = NextAuth({
|
||||
...authConfig,
|
||||
session: {
|
||||
strategy: "jwt",
|
||||
// Bound the lifetime of the signature-only token. The edge proxy gate
|
||||
// verifies the JWT signature but cannot reach the DB (no Prisma on the
|
||||
// edge runtime), so a shorter maxAge limits how long a leaked-but-
|
||||
// unexpired token can reach pages before the authoritative revocation
|
||||
// check (revalidateSession) rejects it on any auth() call.
|
||||
maxAge: 7 * 24 * 60 * 60, // 7 days
|
||||
updateAge: 24 * 60 * 60, // sliding refresh, at most once per day
|
||||
},
|
||||
// Explicit, hardened cookie options. These pin NextAuth's secure defaults so
|
||||
// they cannot silently regress: httpOnly blocks JS access (XSS token theft),
|
||||
// sameSite=lax blocks cross-site sends (CSRF), secure requires https in prod.
|
||||
cookies: {
|
||||
sessionToken: {
|
||||
options: {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
secure: isSecureDeploy,
|
||||
},
|
||||
},
|
||||
},
|
||||
session: { strategy: "jwt" },
|
||||
adapter: isCloud ? SupabaseAdapter({
|
||||
url: process.env.NEXT_PUBLIC_SUPABASE_URL || "http://dummy.supabase.co",
|
||||
secret: process.env.SUPABASE_SERVICE_ROLE_KEY || "dummy",
|
||||
@@ -196,32 +137,21 @@ export const {
|
||||
callbacks: {
|
||||
...authConfig.callbacks,
|
||||
async jwt({ token, user }) {
|
||||
// Initial sign-in: copy identity claims from the authorized user.
|
||||
if (user) {
|
||||
token.role = user.role ?? "user";
|
||||
token.role = (user as { role?: string }).role ?? "user";
|
||||
token.id = user.id;
|
||||
// Embed the user's current sessionVersion so the token can be
|
||||
// compared against the DB on later requests and revoked.
|
||||
token.sessionVersion = user.sessionVersion ?? 0;
|
||||
// Persist the demo-admin synthetic identity on first sign-in so
|
||||
// that the `users` FK target exists for API key creation. Runs
|
||||
// only when `user` is present (initial sign-in, not token refresh).
|
||||
// All values inside come from server-controlled constants.
|
||||
await persistDemoAdminIfNeeded(user.id!, isCloud);
|
||||
return token;
|
||||
}
|
||||
|
||||
// Every subsequent request re-validates the token against the DB so
|
||||
// that deleted users, cross-database tokens, and bumped
|
||||
// sessionVersions are rejected. Cloud identities live in Supabase
|
||||
// (no local `users` row), so they skip the Prisma comparison.
|
||||
if (isCloud) return token;
|
||||
return revalidateSession(token);
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }) {
|
||||
if (session.user) {
|
||||
session.user.id = token.id as string;
|
||||
session.user.role = token.role as string | undefined;
|
||||
(session.user as { role?: string }).role = token.role as string;
|
||||
}
|
||||
return session;
|
||||
},
|
||||
|
||||
@@ -1,397 +0,0 @@
|
||||
/**
|
||||
* localSources.test.ts
|
||||
*
|
||||
* Unit tests for the LocalDataSource registry module (Plan 30-02, Wave 2).
|
||||
* Covers: normalizer (GeoJSON -> GeoEntity), TTL cache, registry public API,
|
||||
* and barrel re-exports.
|
||||
*
|
||||
* Written RED first (Task 1): all tests fail until localSources/ is implemented.
|
||||
* Turns GREEN in Tasks 2 and 3.
|
||||
*/
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach, afterEach,
|
||||
} from "vitest";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// fs/promises mock — supplies fake plugin.json manifests + cameras GeoJSON
|
||||
// Must be at module level (Vitest hoists vi.mock to top of file).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const FAKE_CAMERA_MANIFEST = JSON.stringify({
|
||||
id: "camera",
|
||||
name: "@worldwideview/wwv-plugin-camera",
|
||||
version: "1.0.12",
|
||||
type: "data-layer",
|
||||
format: "bundle",
|
||||
trust: "unverified",
|
||||
capabilities: ["layer"],
|
||||
category: "Infrastructure",
|
||||
icon: "Camera",
|
||||
entry: "/plugins-local/camera/frontend.mjs",
|
||||
localData: [
|
||||
{ name: "default", type: "geojson", path: "/public-cameras.json" },
|
||||
{ name: "traffic", type: "route", path: "/api/camera/traffic" },
|
||||
],
|
||||
});
|
||||
|
||||
// Moscow feature: GeoJSON is [lon, lat] — must become latitude=55.7, longitude=37.6
|
||||
const MOSCOW_FEATURE = {
|
||||
type: "Feature",
|
||||
geometry: { type: "Point", coordinates: [37.6, 55.7] },
|
||||
properties: { country: "Russia", city: "Moscow", is_popular: true },
|
||||
};
|
||||
|
||||
const FAKE_CAMERAS_GEOJSON = JSON.stringify({
|
||||
type: "FeatureCollection",
|
||||
features: [MOSCOW_FEATURE],
|
||||
});
|
||||
|
||||
const FAKE_TRAFFIC_RESPONSE = JSON.stringify({
|
||||
type: "FeatureCollection",
|
||||
features: [
|
||||
{
|
||||
type: "Feature",
|
||||
geometry: { type: "Point", coordinates: [2.35, 48.85] },
|
||||
properties: { country: "France", city: "Paris", is_popular: false },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
global.fetch = vi.fn();
|
||||
|
||||
// Use clearAllMocks (clears call counts/results) not resetAllMocks (wipes implementations).
|
||||
// resetAllMocks would strip the vi.fn() implementations, causing mocks to return undefined.
|
||||
// Note: registry tests use _setReaderForTest injection instead of vi.mock("node:fs/promises")
|
||||
// to avoid Vitest Node built-in mock interop limitations in the jsdom environment.
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 1. Normalizer — normalizeGeoJson
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("normalizer", () => {
|
||||
it("maps GeoJSON [lon, lat] coordinates to GeoEntity latitude=lat / longitude=lon (NOT swapped)", async () => {
|
||||
const { normalizeGeoJson } = await import("./localSources/normalizers");
|
||||
const fc = { type: "FeatureCollection", features: [MOSCOW_FEATURE] };
|
||||
const entities = normalizeGeoJson(fc, "default", "camera");
|
||||
expect(entities).toHaveLength(1);
|
||||
// coordinates [37.6, 55.7] = [lon, lat]; latitude must be 55.7
|
||||
expect(entities[0].latitude).toBeCloseTo(55.7, 4);
|
||||
expect(entities[0].longitude).toBeCloseTo(37.6, 4);
|
||||
});
|
||||
|
||||
it("assigns id using camera-${prefix}-${index} pattern", async () => {
|
||||
const { normalizeGeoJson } = await import("./localSources/normalizers");
|
||||
const fc = { type: "FeatureCollection", features: [MOSCOW_FEATURE] };
|
||||
const entities = normalizeGeoJson(fc, "default", "camera");
|
||||
expect(entities[0].id).toBe("camera-default-0");
|
||||
});
|
||||
|
||||
it("sets pluginId from the pluginId argument", async () => {
|
||||
const { normalizeGeoJson } = await import("./localSources/normalizers");
|
||||
const fc = { type: "FeatureCollection", features: [MOSCOW_FEATURE] };
|
||||
const entities = normalizeGeoJson(fc, "default", "camera");
|
||||
expect(entities[0].pluginId).toBe("camera");
|
||||
});
|
||||
|
||||
it("sets altitude to 8 (cameraMapper parity)", async () => {
|
||||
const { normalizeGeoJson } = await import("./localSources/normalizers");
|
||||
const fc = { type: "FeatureCollection", features: [MOSCOW_FEATURE] };
|
||||
const entities = normalizeGeoJson(fc, "default", "camera");
|
||||
expect(entities[0].altitude).toBe(8);
|
||||
});
|
||||
|
||||
it("preserves feature properties including country, city, is_popular", async () => {
|
||||
const { normalizeGeoJson } = await import("./localSources/normalizers");
|
||||
const fc = { type: "FeatureCollection", features: [MOSCOW_FEATURE] };
|
||||
const entities = normalizeGeoJson(fc, "default", "camera");
|
||||
expect(entities[0].properties.country).toBe("Russia");
|
||||
expect(entities[0].properties.city).toBe("Moscow");
|
||||
expect(entities[0].properties.is_popular).toBe(true);
|
||||
});
|
||||
|
||||
it("sets label = city when city present", async () => {
|
||||
const { normalizeGeoJson } = await import("./localSources/normalizers");
|
||||
const fc = { type: "FeatureCollection", features: [MOSCOW_FEATURE] };
|
||||
const entities = normalizeGeoJson(fc, "default", "camera");
|
||||
expect(entities[0].label).toBe("Moscow");
|
||||
});
|
||||
|
||||
it("falls back label to country when city is absent", async () => {
|
||||
const { normalizeGeoJson } = await import("./localSources/normalizers");
|
||||
const feature = {
|
||||
type: "Feature",
|
||||
geometry: { type: "Point", coordinates: [30.0, 50.0] },
|
||||
properties: { country: "Ukraine" },
|
||||
};
|
||||
const fc = { type: "FeatureCollection", features: [feature] };
|
||||
const entities = normalizeGeoJson(fc, "default", "camera");
|
||||
expect(entities[0].label).toBe("Ukraine");
|
||||
});
|
||||
|
||||
it("falls back label to 'Unknown Camera' when both city and country absent", async () => {
|
||||
const { normalizeGeoJson } = await import("./localSources/normalizers");
|
||||
const feature = {
|
||||
type: "Feature",
|
||||
geometry: { type: "Point", coordinates: [0, 0] },
|
||||
properties: {},
|
||||
};
|
||||
const fc = { type: "FeatureCollection", features: [feature] };
|
||||
const entities = normalizeGeoJson(fc, "default", "camera");
|
||||
expect(entities[0].label).toBe("Unknown Camera");
|
||||
});
|
||||
|
||||
it("handles empty FeatureCollection gracefully (returns [])", async () => {
|
||||
const { normalizeGeoJson } = await import("./localSources/normalizers");
|
||||
const fc = { type: "FeatureCollection", features: [] };
|
||||
const entities = normalizeGeoJson(fc, "default", "camera");
|
||||
expect(entities).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("handles unknown input shape gracefully (returns [])", async () => {
|
||||
const { normalizeGeoJson } = await import("./localSources/normalizers");
|
||||
const entities = normalizeGeoJson(null, "default", "camera");
|
||||
expect(entities).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 2. TTL cache — getCached
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("cache", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("invokes the fetcher on first call and returns its value", async () => {
|
||||
const { getCached } = await import("./localSources/cache");
|
||||
const fakeSnapshot = { pluginId: "camera", entities: [], timestamp: new Date() };
|
||||
const fetcher = vi.fn().mockResolvedValue(fakeSnapshot);
|
||||
const result = await getCached("cache-test-first", 60_000, fetcher);
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
expect(result).toEqual(fakeSnapshot);
|
||||
});
|
||||
|
||||
it("returns cached value on second call within TTL (fetcher called only once)", async () => {
|
||||
const { getCached } = await import("./localSources/cache");
|
||||
const fakeSnapshot = { pluginId: "camera", entities: [], timestamp: new Date() };
|
||||
const fetcher = vi.fn().mockResolvedValue(fakeSnapshot);
|
||||
await getCached("cache-test-ttl", 60_000, fetcher);
|
||||
// Advance time but stay within TTL
|
||||
vi.advanceTimersByTime(30_000);
|
||||
await getCached("cache-test-ttl", 60_000, fetcher);
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("refetches after TTL expires", async () => {
|
||||
const { getCached } = await import("./localSources/cache");
|
||||
const fakeSnapshot = { pluginId: "camera", entities: [], timestamp: new Date() };
|
||||
const fetcher = vi.fn().mockResolvedValue(fakeSnapshot);
|
||||
await getCached("cache-test-expire", 60_000, fetcher);
|
||||
// Advance past TTL
|
||||
vi.advanceTimersByTime(61_000);
|
||||
await getCached("cache-test-expire", 60_000, fetcher);
|
||||
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("exports TTL_GEOJSON_MS = 3600000 (60 min)", async () => {
|
||||
const { TTL_GEOJSON_MS } = await import("./localSources/cache");
|
||||
expect(TTL_GEOJSON_MS).toBe(60 * 60 * 1000);
|
||||
});
|
||||
|
||||
it("exports TTL_ROUTE_MS = 60000 (60 s)", async () => {
|
||||
const { TTL_ROUTE_MS } = await import("./localSources/cache");
|
||||
expect(TTL_ROUTE_MS).toBe(60 * 1000);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 3. Registry — hasLocalSource, getLocalSourceIds, resolveLocalSnapshot
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("registry", () => {
|
||||
// Fake fs reader using the module-level constants — injected via _setReaderForTest
|
||||
// to bypass Vitest's Node built-in mock interop limitations (jsdom environment).
|
||||
const fakeReaddir = async (dir: string): Promise<string[]> => {
|
||||
if (String(dir).includes("plugins-local")) return ["camera"];
|
||||
return [];
|
||||
};
|
||||
const fakeReadfile = async (filePath: string, _encoding: string): Promise<string> => {
|
||||
const p = String(filePath);
|
||||
if (p.includes("plugins-local") && p.includes("camera") && p.includes("plugin.json")) {
|
||||
return FAKE_CAMERA_MANIFEST;
|
||||
}
|
||||
if (p.includes("public-cameras.json")) {
|
||||
return FAKE_CAMERAS_GEOJSON;
|
||||
}
|
||||
throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" });
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const { _resetRegistry, _setReaderForTest } = await import("./localSources/registry");
|
||||
// Inject fake fs reader so registry reads mock manifests, not real disk.
|
||||
_setReaderForTest(fakeReaddir, fakeReadfile);
|
||||
// Reset the memoized registry so each test gets a fresh scan with the injected reader.
|
||||
_resetRegistry();
|
||||
// Clear the per-source data cache so each test reads through the fake reader.
|
||||
const { _clearCache } = await import("./localSources/cache");
|
||||
_clearCache();
|
||||
// Re-supply fetch mock for route source
|
||||
vi.mocked(global.fetch).mockResolvedValue(
|
||||
new Response(FAKE_TRAFFIC_RESPONSE, { status: 200 }),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
const { _restoreReader } = await import("./localSources/registry");
|
||||
_restoreReader();
|
||||
});
|
||||
|
||||
it("hasLocalSource('camera') returns true after building from manifests", async () => {
|
||||
const { hasLocalSource } = await import("./localSources/registry");
|
||||
expect(await hasLocalSource("camera")).toBe(true);
|
||||
});
|
||||
|
||||
it("hasLocalSource('nope') returns false for unknown plugin", async () => {
|
||||
const { hasLocalSource } = await import("./localSources/registry");
|
||||
expect(await hasLocalSource("nope")).toBe(false);
|
||||
});
|
||||
|
||||
it("getLocalSourceIds() returns a Set that includes 'camera'", async () => {
|
||||
const { getLocalSourceIds } = await import("./localSources/registry");
|
||||
const ids = await getLocalSourceIds();
|
||||
expect(ids).toBeInstanceOf(Set);
|
||||
expect(ids.has("camera")).toBe(true);
|
||||
});
|
||||
|
||||
it("resolveLocalSnapshot('camera') returns a PluginDataSnapshot", async () => {
|
||||
const { resolveLocalSnapshot } = await import("./localSources/registry");
|
||||
const snapshot = await resolveLocalSnapshot("camera");
|
||||
expect(snapshot.pluginId).toBe("camera");
|
||||
expect(Array.isArray(snapshot.entities)).toBe(true);
|
||||
expect(snapshot.timestamp).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it("resolveLocalSnapshot('camera') entities have non-zero length (geojson source loaded)", async () => {
|
||||
const { resolveLocalSnapshot } = await import("./localSources/registry");
|
||||
const snapshot = await resolveLocalSnapshot("camera");
|
||||
// At minimum the geojson source (Moscow) should produce 1 entity
|
||||
expect(snapshot.entities.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("resolveLocalSnapshot geojson entities preserve correct lat/lon order (Russia: lat~55, lon~37)", async () => {
|
||||
const { resolveLocalSnapshot } = await import("./localSources/registry");
|
||||
const snapshot = await resolveLocalSnapshot("camera");
|
||||
const russiaEntity = snapshot.entities.find(
|
||||
(e) => e.properties.country === "Russia",
|
||||
);
|
||||
expect(russiaEntity).toBeDefined();
|
||||
// Moscow coords in GeoJSON: [37.6x, 55.7x] = [lon, lat].
|
||||
// latitude (55) > longitude (37) confirms coordinates are NOT swapped.
|
||||
expect(russiaEntity!.latitude).toBeGreaterThan(50);
|
||||
expect(russiaEntity!.latitude).toBeLessThan(60);
|
||||
expect(russiaEntity!.longitude).toBeGreaterThan(30);
|
||||
expect(russiaEntity!.longitude).toBeLessThan(45);
|
||||
// Swap guard: latitude must be the larger value for Moscow
|
||||
expect(russiaEntity!.latitude).toBeGreaterThan(russiaEntity!.longitude);
|
||||
});
|
||||
|
||||
it("resolveLocalSnapshot throws for unknown plugin id", async () => {
|
||||
const { resolveLocalSnapshot } = await import("./localSources/registry");
|
||||
await expect(resolveLocalSnapshot("unknown-plugin")).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("fetchRouteSource rejects an absolute-URL path (SSRF guard)", async () => {
|
||||
// Inject a reader that returns a manifest with an absolute-URL route source.
|
||||
const maliciousManifest = JSON.stringify({
|
||||
id: "camera",
|
||||
name: "@worldwideview/wwv-plugin-camera",
|
||||
version: "1.0.0",
|
||||
type: "data-layer",
|
||||
format: "bundle",
|
||||
trust: "unverified",
|
||||
capabilities: ["layer"],
|
||||
category: "Infrastructure",
|
||||
icon: "Camera",
|
||||
entry: "/plugins-local/camera/frontend.mjs",
|
||||
localData: [
|
||||
{ name: "evil", type: "route", path: "http://attacker.example/steal" },
|
||||
],
|
||||
});
|
||||
|
||||
const { _resetRegistry, _setReaderForTest } = await import("./localSources/registry");
|
||||
_setReaderForTest(
|
||||
async (dir) => (String(dir).includes("plugins-local") ? ["camera"] : []),
|
||||
async (filePath) => {
|
||||
if (String(filePath).includes("plugin.json")) return maliciousManifest;
|
||||
throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
_resetRegistry();
|
||||
|
||||
const { resolveLocalSnapshot } = await import("./localSources/registry");
|
||||
await expect(resolveLocalSnapshot("camera")).rejects.toThrow(/non-relative/);
|
||||
});
|
||||
|
||||
it("type allowlist drops non-geojson/route sources (only allowed types enter registry)", async () => {
|
||||
// Manifest declares an unsupported type "csv" — registry should drop it,
|
||||
// leaving the plugin with 0 valid sources and therefore not registering it.
|
||||
const badTypeManifest = JSON.stringify({
|
||||
id: "camera",
|
||||
name: "@worldwideview/wwv-plugin-camera",
|
||||
version: "1.0.0",
|
||||
type: "data-layer",
|
||||
format: "bundle",
|
||||
trust: "unverified",
|
||||
capabilities: ["layer"],
|
||||
category: "Infrastructure",
|
||||
icon: "Camera",
|
||||
entry: "/plugins-local/camera/frontend.mjs",
|
||||
localData: [
|
||||
{ name: "feed", type: "csv", path: "/cameras.csv" },
|
||||
],
|
||||
});
|
||||
|
||||
const { _resetRegistry, _setReaderForTest } = await import("./localSources/registry");
|
||||
_setReaderForTest(
|
||||
async (dir) => (String(dir).includes("plugins-local") ? ["camera"] : []),
|
||||
async (filePath) => {
|
||||
if (String(filePath).includes("plugin.json")) return badTypeManifest;
|
||||
throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
_resetRegistry();
|
||||
|
||||
const { hasLocalSource } = await import("./localSources/registry");
|
||||
// "camera" should NOT be registered because its only source has a forbidden type.
|
||||
expect(await hasLocalSource("camera")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 4. Barrel re-export — index.ts
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("localSources barrel (index.ts)", () => {
|
||||
it("exports hasLocalSource", async () => {
|
||||
const mod = await import("./localSources/index");
|
||||
expect(typeof mod.hasLocalSource).toBe("function");
|
||||
});
|
||||
|
||||
it("exports getLocalSourceIds", async () => {
|
||||
const mod = await import("./localSources/index");
|
||||
expect(typeof mod.getLocalSourceIds).toBe("function");
|
||||
});
|
||||
|
||||
it("exports resolveLocalSnapshot", async () => {
|
||||
const mod = await import("./localSources/index");
|
||||
expect(typeof mod.resolveLocalSnapshot).toBe("function");
|
||||
});
|
||||
});
|
||||
@@ -1,58 +0,0 @@
|
||||
/**
|
||||
* @file cache.ts
|
||||
* @description Module-level in-memory TTL cache for PluginDataSnapshot results.
|
||||
*
|
||||
* Keyed per source string (e.g. "camera:default", "camera:traffic").
|
||||
* Returns the cached snapshot while Date.now() < expiresAt, otherwise invokes
|
||||
* the fetcher and stores the new result with a fresh expiry.
|
||||
*
|
||||
* TTL constants (D-07, Research Area 6):
|
||||
* - TTL_GEOJSON_MS: 60 min (static file; changes only on deploy)
|
||||
* - TTL_ROUTE_MS: 60 s (internal Next.js route; data updates frequently)
|
||||
*/
|
||||
|
||||
import type { PluginDataSnapshot } from "../types";
|
||||
|
||||
/** 60-minute TTL for static GeoJSON file sources. */
|
||||
export const TTL_GEOJSON_MS = 60 * 60 * 1000;
|
||||
|
||||
/** 60-second TTL for internal route sources (/api/...). */
|
||||
export const TTL_ROUTE_MS = 60 * 1000;
|
||||
|
||||
interface CacheEntry {
|
||||
snapshot: PluginDataSnapshot;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
/** Module-level cache — persists for the lifetime of the Node.js process. */
|
||||
const cache = new Map<string, CacheEntry>();
|
||||
|
||||
/**
|
||||
* getCached
|
||||
*
|
||||
* Returns a cached snapshot if one exists and has not expired.
|
||||
* Otherwise calls `fetcher`, stores the result, and returns it.
|
||||
*
|
||||
* @param key - Unique string key for this source (e.g. "camera:default").
|
||||
* @param ttlMs - Time-to-live in milliseconds before the entry is invalidated.
|
||||
* @param fetcher - Async function that fetches and returns a fresh snapshot.
|
||||
*/
|
||||
export async function getCached(
|
||||
key: string,
|
||||
ttlMs: number,
|
||||
fetcher: () => Promise<PluginDataSnapshot>,
|
||||
): Promise<PluginDataSnapshot> {
|
||||
const entry = cache.get(key);
|
||||
if (entry !== undefined && entry.expiresAt > Date.now()) {
|
||||
return entry.snapshot;
|
||||
}
|
||||
|
||||
const snapshot = await fetcher();
|
||||
cache.set(key, { snapshot, expiresAt: Date.now() + ttlMs });
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/** Exposed for testing: clear all cache entries. */
|
||||
export function _clearCache(): void {
|
||||
cache.clear();
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
/**
|
||||
* @file index.ts
|
||||
* @description Barrel re-exporting the public LocalDataSource registry API.
|
||||
* Consumed by Plan 30-03's service.ts integration seam.
|
||||
*/
|
||||
|
||||
export { hasLocalSource, getLocalSourceIds, resolveLocalSnapshot } from "./registry";
|
||||
@@ -1,82 +0,0 @@
|
||||
/**
|
||||
* @file normalizers.ts
|
||||
* @description Server-side GeoJSON FeatureCollection -> GeoEntity[] transform.
|
||||
*
|
||||
* Reimplements the ~15-line mapGeoJsonFeature logic from
|
||||
* local-plugins/wwv-plugin-camera/src/cameraMapper.ts WITHOUT importing that
|
||||
* barrel (it pulls React/lucide-react and camera is not in transpilePackages).
|
||||
*
|
||||
* Coordinate order: GeoJSON spec is [longitude, latitude] — we destructure
|
||||
* `const [lon, lat] = coordinates` and assign `latitude: lat, longitude: lon`.
|
||||
* Getting this backwards is the primary footgun (see plan Pitfall 1).
|
||||
*/
|
||||
|
||||
import type { GeoEntity } from "@worldwideview/wwv-plugin-sdk";
|
||||
|
||||
const DEFAULT_CAMERA_ALT = 8;
|
||||
|
||||
/**
|
||||
* Narrows an unknown GeoJSON feature to a typed shape for safe destructuring.
|
||||
*/
|
||||
interface GeoJsonFeature {
|
||||
geometry?: { coordinates?: number[] };
|
||||
properties?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrows an unknown GeoJSON FeatureCollection to a typed shape.
|
||||
*/
|
||||
interface GeoJsonFeatureCollection {
|
||||
features?: unknown[];
|
||||
}
|
||||
|
||||
/**
|
||||
* normalizeGeoJson
|
||||
*
|
||||
* Converts a GeoJSON FeatureCollection (parsed from disk or fetched as JSON)
|
||||
* into a GeoEntity[]. Returns [] for malformed or empty input — never throws.
|
||||
*
|
||||
* @param input - Unknown value expected to be a FeatureCollection object.
|
||||
* @param prefix - Source name used in entity id (e.g. "default", "traffic").
|
||||
* @param pluginId - Plugin identifier assigned to every entity.
|
||||
*/
|
||||
export function normalizeGeoJson(
|
||||
input: unknown,
|
||||
prefix: string,
|
||||
pluginId: string,
|
||||
): GeoEntity[] {
|
||||
if (typeof input !== "object" || input === null) return [];
|
||||
|
||||
const collection = input as GeoJsonFeatureCollection;
|
||||
if (!Array.isArray(collection.features)) return [];
|
||||
|
||||
const entities: GeoEntity[] = [];
|
||||
|
||||
for (let index = 0; index < collection.features.length; index++) {
|
||||
const feature = collection.features[index] as GeoJsonFeature;
|
||||
if (typeof feature !== "object" || feature === null) continue;
|
||||
|
||||
// GeoJSON coordinate order is [longitude, latitude] — destructure accordingly.
|
||||
// Swapping these is Pitfall 1 (plan constraint).
|
||||
const [lon = 0, lat = 0] = feature.geometry?.coordinates ?? [];
|
||||
const props: Record<string, unknown> = feature.properties ?? {};
|
||||
|
||||
const label =
|
||||
(props.city as string | undefined) ||
|
||||
(props.country as string | undefined) ||
|
||||
"Unknown Camera";
|
||||
|
||||
entities.push({
|
||||
id: `${pluginId}-${prefix}-${index}`,
|
||||
pluginId,
|
||||
latitude: lat,
|
||||
longitude: lon,
|
||||
altitude: DEFAULT_CAMERA_ALT,
|
||||
timestamp: new Date(),
|
||||
label,
|
||||
properties: { ...props },
|
||||
});
|
||||
}
|
||||
|
||||
return entities;
|
||||
}
|
||||
@@ -1,274 +0,0 @@
|
||||
/**
|
||||
* @file registry.ts
|
||||
* @description LocalDataSource registry — discovers plugins with localData
|
||||
* declarations and resolves them to PluginDataSnapshot.
|
||||
*
|
||||
* Scans public/plugins-local/<id>/plugin.json at runtime, keeps those with a
|
||||
* `localData` array, and memoizes the assembled map once per process (separate
|
||||
* from the per-source data TTL cache).
|
||||
*
|
||||
* Security (T-30-03): paths from manifests are constrained to
|
||||
* path.join(process.cwd(), "public", <relative>)
|
||||
* and any path containing ".." is rejected before the read.
|
||||
*/
|
||||
|
||||
import { readdir as nodeReaddir, readFile as nodeReadFile } from "node:fs/promises";
|
||||
import path from "path";
|
||||
import type { LocalDataSourceDeclaration } from "@worldwideview/wwv-plugin-sdk";
|
||||
import type { PluginDataSnapshot } from "../types";
|
||||
import { normalizeGeoJson } from "./normalizers";
|
||||
import { getCached, TTL_GEOJSON_MS, TTL_ROUTE_MS } from "./cache";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fs reader — injectable for testing (avoids Node built-in mock interop issues)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type Readdir = (dir: string) => Promise<string[]>;
|
||||
type Readfile = (p: string, enc: string) => Promise<string>;
|
||||
|
||||
let _readdir: Readdir = (dir) => nodeReaddir(dir) as Promise<string[]>;
|
||||
let _readfile: Readfile = (p, enc) => nodeReadFile(p, enc as "utf-8") as Promise<string>;
|
||||
|
||||
/** Exposed for testing ONLY: inject custom fs reader implementations. */
|
||||
export function _setReaderForTest(rd: Readdir, rf: Readfile): void {
|
||||
_readdir = rd;
|
||||
_readfile = rf;
|
||||
}
|
||||
|
||||
/** Restore the default fs readers (call in afterEach when using _setReaderForTest). */
|
||||
export function _restoreReader(): void {
|
||||
_readdir = (dir) => nodeReaddir(dir) as Promise<string[]>;
|
||||
_readfile = (p, enc) => nodeReadFile(p, enc as "utf-8") as Promise<string>;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plugin ID validator (mirrors service.ts — defense in depth)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const PLUGIN_ID_RE = /^[a-zA-Z0-9_-]+$/;
|
||||
|
||||
function validatePluginId(id: string): boolean {
|
||||
return PLUGIN_ID_RE.test(id);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Registry entry
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface RegistryEntry {
|
||||
pluginId: string;
|
||||
sources: LocalDataSourceDeclaration[];
|
||||
}
|
||||
|
||||
// T-30-01: only allow known source types — drop anything else at registry scan time.
|
||||
const ALLOWED_SOURCE_TYPES = new Set(["geojson", "route"]);
|
||||
|
||||
// Memoized map: built once per process from disk, keyed by plugin id.
|
||||
let registryPromise: Promise<Map<string, RegistryEntry>> | null = null;
|
||||
|
||||
/**
|
||||
* Reads all generated plugin.json manifests from public/plugins-local/<id>/
|
||||
* and returns a Map of { id -> RegistryEntry } for those that declare localData.
|
||||
* Result is memoized — only one scan per process lifetime.
|
||||
*/
|
||||
function getRegistry(): Promise<Map<string, RegistryEntry>> {
|
||||
if (registryPromise !== null) return registryPromise;
|
||||
|
||||
registryPromise = (async () => {
|
||||
const map = new Map<string, RegistryEntry>();
|
||||
const pluginsDir = path.join(process.cwd(), "public", "plugins-local");
|
||||
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = await _readdir(pluginsDir);
|
||||
} catch {
|
||||
return map;
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
const manifestPath = path.join(pluginsDir, entry, "plugin.json");
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await _readfile(manifestPath, "utf-8");
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
let manifest: Record<string, unknown>;
|
||||
try {
|
||||
manifest = JSON.parse(raw) as Record<string, unknown>;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
const id = manifest.id as string | undefined;
|
||||
if (typeof id !== "string" || !validatePluginId(id)) continue;
|
||||
|
||||
const localData = manifest.localData;
|
||||
if (!Array.isArray(localData) || localData.length === 0) continue;
|
||||
|
||||
const sources = (localData as unknown[]).filter(
|
||||
(s): s is LocalDataSourceDeclaration => {
|
||||
if (typeof s !== "object" || s === null) return false;
|
||||
const src = s as Record<string, unknown>;
|
||||
// T-30-01: only allow known types (geojson, route) — drop any other.
|
||||
return (
|
||||
typeof src.name === "string" &&
|
||||
typeof src.type === "string" &&
|
||||
ALLOWED_SOURCE_TYPES.has(src.type) &&
|
||||
typeof src.path === "string"
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
if (sources.length === 0) continue;
|
||||
|
||||
map.set(id, { pluginId: id, sources });
|
||||
}
|
||||
|
||||
return map;
|
||||
})();
|
||||
|
||||
return registryPromise;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Path guard (T-30-03 — path traversal)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function isSafeRelativePath(p: string): boolean {
|
||||
return !p.includes("..");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source resolver helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Read a geojson source from disk (no self-HTTP — Pitfall 3).
|
||||
* Path is constrained to process.cwd()/public/<relative>.
|
||||
*/
|
||||
async function fetchGeojsonSource(
|
||||
sourcePath: string,
|
||||
pluginId: string,
|
||||
prefix: string,
|
||||
): Promise<PluginDataSnapshot> {
|
||||
if (!isSafeRelativePath(sourcePath)) {
|
||||
throw new Error(`[localSources] Rejected unsafe path: ${sourcePath}`);
|
||||
}
|
||||
|
||||
// Strip leading "/" if present — path.join handles this correctly
|
||||
const relativePart = sourcePath.startsWith("/") ? sourcePath.slice(1) : sourcePath;
|
||||
const absolutePath = path.join(process.cwd(), "public", relativePart);
|
||||
|
||||
// T-30-03 defense-in-depth: ensure resolved path stays inside public/
|
||||
const publicRoot = path.join(process.cwd(), "public") + path.sep;
|
||||
if (!absolutePath.startsWith(publicRoot)) {
|
||||
throw new Error(`[localSources] Path escapes public/: ${sourcePath}`);
|
||||
}
|
||||
|
||||
const raw = await _readfile(absolutePath, "utf-8");
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
const entities = normalizeGeoJson(parsed, prefix, pluginId);
|
||||
|
||||
return { pluginId, entities, timestamp: new Date() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a route source via the internal Next.js API (server-side fetch).
|
||||
* Base URL is derived from env variable or defaults to localhost:3000.
|
||||
*/
|
||||
async function fetchRouteSource(
|
||||
sourcePath: string,
|
||||
pluginId: string,
|
||||
prefix: string,
|
||||
): Promise<PluginDataSnapshot> {
|
||||
if (!isSafeRelativePath(sourcePath)) {
|
||||
throw new Error(`[localSources] Rejected unsafe path: ${sourcePath}`);
|
||||
}
|
||||
|
||||
// T-30-01 SSRF guard: only relative paths (starting with "/") are allowed.
|
||||
// An absolute URL (containing "://") or a non-slash-prefixed path would
|
||||
// resolve against the base and could reach external hosts.
|
||||
if (!sourcePath.startsWith("/") || sourcePath.includes("://")) {
|
||||
throw new Error(`[localSources] Rejected non-relative route path: ${sourcePath}`);
|
||||
}
|
||||
|
||||
// Drop NEXTAUTH_URL — it is an auth callback URL (may carry a path).
|
||||
const base = process.env.WWV_INTERNAL_BASE_URL ?? "http://localhost:3000";
|
||||
const url = new URL(sourcePath, base).toString();
|
||||
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) {
|
||||
return { pluginId, entities: [], timestamp: new Date() };
|
||||
}
|
||||
|
||||
const parsed: unknown = await res.json();
|
||||
const entities = normalizeGeoJson(parsed, prefix, pluginId);
|
||||
|
||||
return { pluginId, entities, timestamp: new Date() };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns true if the given plugin id has a localData declaration.
|
||||
*/
|
||||
export async function hasLocalSource(id: string): Promise<boolean> {
|
||||
const registry = await getRegistry();
|
||||
return registry.has(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Set of all plugin ids that have localData declarations.
|
||||
*/
|
||||
export async function getLocalSourceIds(): Promise<Set<string>> {
|
||||
const registry = await getRegistry();
|
||||
return new Set(registry.keys());
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves ALL declared local sources for a plugin, merges entities from each,
|
||||
* and returns a single aggregated PluginDataSnapshot.
|
||||
*
|
||||
* Cache keys are scoped per source ("camera:default", "camera:traffic") so
|
||||
* each source has its own TTL, then combined at read time.
|
||||
*/
|
||||
export async function resolveLocalSnapshot(id: string): Promise<PluginDataSnapshot> {
|
||||
const registry = await getRegistry();
|
||||
const entry = registry.get(id);
|
||||
|
||||
if (entry === undefined) {
|
||||
throw new Error(`[localSources] No local source registered for plugin: ${id}`);
|
||||
}
|
||||
|
||||
const allEntities = await Promise.all(
|
||||
entry.sources.map((source) => {
|
||||
const cacheKey = `${id}:${source.name}`;
|
||||
const ttl = source.type === "geojson" ? TTL_GEOJSON_MS : TTL_ROUTE_MS;
|
||||
|
||||
return getCached(cacheKey, ttl, () => {
|
||||
if (source.type === "geojson") {
|
||||
return fetchGeojsonSource(source.path, id, source.name);
|
||||
}
|
||||
return fetchRouteSource(source.path, id, source.name);
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
// Merge all source entities into a single snapshot
|
||||
const mergedEntities = allEntities.flatMap((snap) => snap.entities);
|
||||
|
||||
return {
|
||||
pluginId: id,
|
||||
entities: mergedEntities,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Exposed for testing: reset the memoized registry (allows re-scan in tests). */
|
||||
export function _resetRegistry(): void {
|
||||
registryPromise = null;
|
||||
}
|
||||
@@ -2,44 +2,19 @@ import {
|
||||
describe, it, expect, vi, beforeEach,
|
||||
} from "vitest";
|
||||
import type { GeoEntity } from "@worldwideview/wwv-plugin-sdk";
|
||||
import type { PluginDataSnapshot } from "@/lib/data-query/types";
|
||||
import {
|
||||
searchEntities,
|
||||
getEntitiesInRegion,
|
||||
getEntityDetails,
|
||||
getPluginData,
|
||||
fetchPluginSnapshot,
|
||||
getAllPluginSnapshots,
|
||||
} from "@/lib/data-query/service";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock the local registry module (Plan 30-02 exports).
|
||||
// Default: hasLocalSource → false so existing tests are unaffected.
|
||||
// Per-test overrides use mockResolvedValue / mockReturnValue as needed.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock("@/lib/data-query/localSources", () => ({
|
||||
hasLocalSource: vi.fn().mockResolvedValue(false),
|
||||
getLocalSourceIds: vi.fn().mockResolvedValue(new Set<string>()),
|
||||
// resolveLocalSnapshot never returns null per registry contract; default to empty snapshot.
|
||||
resolveLocalSnapshot: vi.fn().mockResolvedValue({ pluginId: "", entities: [], timestamp: new Date() }),
|
||||
}));
|
||||
|
||||
// Import mocked fns so we can override per-test.
|
||||
import {
|
||||
hasLocalSource,
|
||||
getLocalSourceIds,
|
||||
resolveLocalSnapshot,
|
||||
} from "@/lib/data-query/localSources";
|
||||
// Module does not exist yet — this file is intentionally RED (Wave 0 TDD scaffold)
|
||||
|
||||
global.fetch = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
// Re-apply safe defaults after resetAllMocks clears all mock state.
|
||||
vi.mocked(hasLocalSource).mockResolvedValue(false);
|
||||
vi.mocked(getLocalSourceIds).mockResolvedValue(new Set<string>());
|
||||
vi.mocked(resolveLocalSnapshot).mockResolvedValue({ pluginId: "", entities: [], timestamp: new Date() });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -76,31 +51,30 @@ function mockEngine404(): void {
|
||||
|
||||
describe("searchEntities", () => {
|
||||
it("returns [] for empty query string (no fetch called)", async () => {
|
||||
const result = await searchEntities("");
|
||||
expect(result.entities).toEqual([]);
|
||||
const results = await searchEntities("");
|
||||
expect(results).toEqual([]);
|
||||
expect(vi.mocked(global.fetch)).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns [] when engine returns 404 for plugin", async () => {
|
||||
mockEngine404();
|
||||
const result = await searchEntities("london", "test-plugin");
|
||||
expect(result.entities).toEqual([]);
|
||||
expect(result.emptyReason).toBe("plugin_not_streaming");
|
||||
const results = await searchEntities("london", "test-plugin");
|
||||
expect(results).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns matching entities for substring match on label", async () => {
|
||||
const entity = makeEntity({ id: "e1", label: "London Heathrow", pluginId: "test-plugin" });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const result = await searchEntities("heathrow", "test-plugin");
|
||||
expect(result.entities).toHaveLength(1);
|
||||
expect(result.entities[0].id).toBe("e1");
|
||||
const results = await searchEntities("heathrow", "test-plugin");
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0].id).toBe("e1");
|
||||
});
|
||||
|
||||
it("match is case-insensitive", async () => {
|
||||
const entity = makeEntity({ id: "e2", label: "PARIS CDG", pluginId: "test-plugin" });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const result = await searchEntities("paris", "test-plugin");
|
||||
expect(result.entities).toHaveLength(1);
|
||||
const results = await searchEntities("paris", "test-plugin");
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("respects limit parameter (returns at most N results)", async () => {
|
||||
@@ -108,8 +82,8 @@ describe("searchEntities", () => {
|
||||
makeEntity({ id: `e${i}`, label: `entity ${i}`, pluginId: "test-plugin" }),
|
||||
);
|
||||
mockEngineSnapshot("test-plugin", entities);
|
||||
const result = await searchEntities("entity", "test-plugin", 3);
|
||||
expect(result.entities.length).toBeLessThanOrEqual(3);
|
||||
const results = await searchEntities("entity", "test-plugin", 3);
|
||||
expect(results.length).toBeLessThanOrEqual(3);
|
||||
});
|
||||
|
||||
it("restricts to pluginId when provided (fetch URL contains pluginId)", async () => {
|
||||
@@ -121,59 +95,6 @@ describe("searchEntities", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FILT-04 — searchEntities inline filters (on GeoEntity.properties, D-07)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("searchEntities filters", () => {
|
||||
it("returns only entities whose properties match the filter", async () => {
|
||||
const airborne = makeEntity({ id: "a1", label: "flight a1", pluginId: "flights", properties: { status: "airborne" } });
|
||||
const landed = makeEntity({ id: "a2", label: "flight a2", pluginId: "flights", properties: { status: "landed" } });
|
||||
mockEngineSnapshot("flights", [airborne, landed]);
|
||||
const result = await searchEntities("flight", "flights", 20, {
|
||||
status: { type: "select", values: ["airborne"] },
|
||||
});
|
||||
expect(result.entities).toHaveLength(1);
|
||||
expect(result.entities[0].id).toBe("a1");
|
||||
});
|
||||
|
||||
it("behaves identically when filters are omitted (no regression)", async () => {
|
||||
const e1 = makeEntity({ id: "b1", label: "flight b1", pluginId: "flights", properties: { status: "airborne" } });
|
||||
const e2 = makeEntity({ id: "b2", label: "flight b2", pluginId: "flights", properties: { status: "landed" } });
|
||||
mockEngineSnapshot("flights", [e1, e2]);
|
||||
const result = await searchEntities("flight", "flights", 20);
|
||||
expect(result.entities).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("excludes an entity missing the filtered property key", async () => {
|
||||
const withProp = makeEntity({ id: "c1", label: "flight c1", pluginId: "flights", properties: { status: "airborne" } });
|
||||
const missingProp = makeEntity({ id: "c2", label: "flight c2", pluginId: "flights", properties: {} });
|
||||
mockEngineSnapshot("flights", [withProp, missingProp]);
|
||||
const result = await searchEntities("flight", "flights", 20, {
|
||||
status: { type: "select", values: ["airborne"] },
|
||||
});
|
||||
expect(result.entities).toHaveLength(1);
|
||||
expect(result.entities[0].id).toBe("c1");
|
||||
});
|
||||
|
||||
it("limit counts only matching entities", async () => {
|
||||
const entities = Array.from({ length: 6 }, (_, i) =>
|
||||
makeEntity({
|
||||
id: `d${i}`,
|
||||
label: `flight d${i}`,
|
||||
pluginId: "flights",
|
||||
properties: { status: i % 2 === 0 ? "airborne" : "landed" },
|
||||
}),
|
||||
);
|
||||
mockEngineSnapshot("flights", entities);
|
||||
const result = await searchEntities("flight", "flights", 2, {
|
||||
status: { type: "select", values: ["airborne"] },
|
||||
});
|
||||
expect(result.entities).toHaveLength(2);
|
||||
expect(result.entities.every((r) => r.id.startsWith("d"))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// QUERY-02 — getEntitiesInRegion
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -182,43 +103,42 @@ describe("getEntitiesInRegion", () => {
|
||||
it("returns entities within bounding box", async () => {
|
||||
const entity = makeEntity({ id: "e1", latitude: 51.5, longitude: -0.1, pluginId: "test-plugin" });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const result = await getEntitiesInRegion({
|
||||
const results = await getEntitiesInRegion({
|
||||
north: 52,
|
||||
south: 50,
|
||||
east: 1,
|
||||
west: -1,
|
||||
pluginId: "test-plugin",
|
||||
});
|
||||
expect(result.entities).toHaveLength(1);
|
||||
expect(result.entities[0].id).toBe("e1");
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0].id).toBe("e1");
|
||||
});
|
||||
|
||||
it("returns [] when no entities in region", async () => {
|
||||
const entity = makeEntity({ id: "e1", latitude: 10, longitude: 10, pluginId: "test-plugin" });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const result = await getEntitiesInRegion({
|
||||
const results = await getEntitiesInRegion({
|
||||
north: 52,
|
||||
south: 50,
|
||||
east: 1,
|
||||
west: -1,
|
||||
pluginId: "test-plugin",
|
||||
});
|
||||
expect(result.entities).toEqual([]);
|
||||
expect(result.emptyReason).toBe("no_data_matches");
|
||||
expect(results).toEqual([]);
|
||||
});
|
||||
|
||||
it("handles antimeridian wraparound (east < west): entity at lon 175 inside bounds west:170 east:-170", async () => {
|
||||
const entity = makeEntity({ id: "e1", latitude: 0, longitude: 175, pluginId: "test-plugin" });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const result = await getEntitiesInRegion({
|
||||
const results = await getEntitiesInRegion({
|
||||
north: 10,
|
||||
south: -10,
|
||||
east: -170,
|
||||
west: 170,
|
||||
pluginId: "test-plugin",
|
||||
});
|
||||
expect(result.entities).toHaveLength(1);
|
||||
expect(result.entities[0].id).toBe("e1");
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0].id).toBe("e1");
|
||||
});
|
||||
|
||||
it("respects pluginId filter", async () => {
|
||||
@@ -253,28 +173,26 @@ describe("getEntityDetails", () => {
|
||||
});
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const result = await getEntityDetails("test-plugin", "e1");
|
||||
expect(result.data).not.toBeNull();
|
||||
expect(result.data?.id).toBe("e1");
|
||||
expect(result.data?.pluginId).toBe("test-plugin");
|
||||
expect(result.data?.latitude).toBe(51.5);
|
||||
expect(result.data?.longitude).toBe(-0.1);
|
||||
expect(result.data?.label).toBe("BA123");
|
||||
expect(result.data?.properties).toEqual(props);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.id).toBe("e1");
|
||||
expect(result?.pluginId).toBe("test-plugin");
|
||||
expect(result?.latitude).toBe(51.5);
|
||||
expect(result?.longitude).toBe(-0.1);
|
||||
expect(result?.label).toBe("BA123");
|
||||
expect(result?.properties).toEqual(props);
|
||||
});
|
||||
|
||||
it("returns plugin_not_streaming when plugin returns 404", async () => {
|
||||
it("returns null when plugin returns 404", async () => {
|
||||
mockEngine404();
|
||||
const result = await getEntityDetails("test-plugin", "e1");
|
||||
expect(result.data).toBeNull();
|
||||
expect(result.emptyReason).toBe("plugin_not_streaming");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns no_data_matches when entityId not in snapshot", async () => {
|
||||
it("returns null when entityId not in snapshot", async () => {
|
||||
const entity = makeEntity({ id: "other-entity", pluginId: "test-plugin" });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const result = await getEntityDetails("test-plugin", "e1");
|
||||
expect(result.data).toBeNull();
|
||||
expect(result.emptyReason).toBe("no_data_matches");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returned properties includes original entity.properties object", async () => {
|
||||
@@ -282,7 +200,7 @@ describe("getEntityDetails", () => {
|
||||
const entity = makeEntity({ id: "e1", pluginId: "test-plugin", properties: props });
|
||||
mockEngineSnapshot("test-plugin", [entity]);
|
||||
const result = await getEntityDetails("test-plugin", "e1");
|
||||
expect(result.data?.properties).toEqual(props);
|
||||
expect(result?.properties).toEqual(props);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -296,10 +214,10 @@ describe("getPluginData", () => {
|
||||
vi.mocked(global.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ items: [entity] }), { status: 200 }),
|
||||
);
|
||||
const result = await getPluginData("test-plugin");
|
||||
expect(result.data).not.toBeNull();
|
||||
expect(result.data?.pluginId).toBe("test-plugin");
|
||||
expect(result.data?.entities).toHaveLength(1);
|
||||
const snapshot = await getPluginData("test-plugin");
|
||||
expect(snapshot).not.toBeNull();
|
||||
expect(snapshot?.pluginId).toBe("test-plugin");
|
||||
expect(snapshot?.entities).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("returns PluginDataSnapshot when engine returns flat array []", async () => {
|
||||
@@ -307,25 +225,23 @@ describe("getPluginData", () => {
|
||||
vi.mocked(global.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify([entity]), { status: 200 }),
|
||||
);
|
||||
const result = await getPluginData("test-plugin");
|
||||
expect(result.data).not.toBeNull();
|
||||
expect(result.data?.entities).toHaveLength(1);
|
||||
const snapshot = await getPluginData("test-plugin");
|
||||
expect(snapshot).not.toBeNull();
|
||||
expect(snapshot?.entities).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("returns plugin_not_streaming on engine 404", async () => {
|
||||
it("returns null on engine 404", async () => {
|
||||
mockEngine404();
|
||||
const result = await getPluginData("missing-plugin");
|
||||
expect(result.data).toBeNull();
|
||||
expect(result.emptyReason).toBe("plugin_not_streaming");
|
||||
const snapshot = await getPluginData("missing-plugin");
|
||||
expect(snapshot).toBeNull();
|
||||
});
|
||||
|
||||
it("returns plugin_not_streaming on engine non-2xx (500)", async () => {
|
||||
it("returns null on engine non-2xx (500)", async () => {
|
||||
vi.mocked(global.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: "internal" }), { status: 500 }),
|
||||
);
|
||||
const result = await getPluginData("test-plugin");
|
||||
expect(result.data).toBeNull();
|
||||
expect(result.emptyReason).toBe("plugin_not_streaming");
|
||||
const snapshot = await getPluginData("test-plugin");
|
||||
expect(snapshot).toBeNull();
|
||||
});
|
||||
|
||||
it("normalizes timestamp string to Date object", async () => {
|
||||
@@ -336,206 +252,7 @@ describe("getPluginData", () => {
|
||||
vi.mocked(global.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ items: [entityWithStringTimestamp] }), { status: 200 }),
|
||||
);
|
||||
const result = await getPluginData("test-plugin");
|
||||
expect(result.data?.entities[0].timestamp).toBeInstanceOf(Date);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 30-03 Wave 3 — registry fallback (D-08)
|
||||
// These tests are RED until Task 2 wires the fallback into service.ts.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Helper: build a minimal camera snapshot for local registry tests.
|
||||
function makeCameraSnapshot(entities: GeoEntity[]): PluginDataSnapshot {
|
||||
return { pluginId: "camera", entities, timestamp: new Date() };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Registry fallback — engine-404 + registry hit → non-null snapshot
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("registry fallback (D-08)", () => {
|
||||
it("fetchPluginSnapshot returns non-null when engine 404s and local registry has plugin", async () => {
|
||||
// Engine 404 for camera.
|
||||
mockEngine404();
|
||||
// Local registry knows about camera and returns a snapshot.
|
||||
vi.mocked(hasLocalSource).mockResolvedValue(true);
|
||||
vi.mocked(resolveLocalSnapshot).mockResolvedValue(
|
||||
makeCameraSnapshot([makeEntity({ id: "cam-1", pluginId: "camera", latitude: 55.7, longitude: 37.6 })]),
|
||||
);
|
||||
|
||||
const result = await fetchPluginSnapshot("camera");
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.pluginId).toBe("camera");
|
||||
expect(result?.entities).toHaveLength(1);
|
||||
expect(result?.entities[0].id).toBe("cam-1");
|
||||
});
|
||||
|
||||
it("fetchPluginSnapshot returns null when engine 404s and registry has no entry", async () => {
|
||||
mockEngine404();
|
||||
vi.mocked(hasLocalSource).mockResolvedValue(false);
|
||||
|
||||
const result = await fetchPluginSnapshot("unknown-plugin");
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Russia-bbox acceptance demo — camera via local registry only, no browser
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("Russia bbox acceptance demo", () => {
|
||||
it("getEntitiesInRegion with camera pluginId returns in-box cameras, emptyReason undefined", async () => {
|
||||
// Engine 404 — no streaming engine needed.
|
||||
mockEngine404();
|
||||
// Local registry provides camera snapshot with one in-box and one out-of-box entity.
|
||||
const inBoxCamera = makeEntity({ id: "moscow-cam", pluginId: "camera", latitude: 55.7, longitude: 37.6 });
|
||||
const outOfBoxCamera = makeEntity({ id: "berlin-cam", pluginId: "camera", latitude: 52.5, longitude: 13.4 });
|
||||
vi.mocked(hasLocalSource).mockResolvedValue(true);
|
||||
vi.mocked(resolveLocalSnapshot).mockResolvedValue(
|
||||
makeCameraSnapshot([inBoxCamera, outOfBoxCamera]),
|
||||
);
|
||||
|
||||
// Russia-ish bbox: Europe-to-Pacific, roughly 41-82 N, 19-180 E.
|
||||
const result = await getEntitiesInRegion({
|
||||
north: 82,
|
||||
south: 41,
|
||||
west: 19,
|
||||
east: 180,
|
||||
pluginId: "camera",
|
||||
});
|
||||
|
||||
expect(result.entities.length).toBeGreaterThanOrEqual(1);
|
||||
// Moscow cam is inside the box (lat 55.7, lon 37.6).
|
||||
expect(result.entities.some((e) => e.id === "moscow-cam")).toBe(true);
|
||||
// Berlin cam is outside the box (lon 13.4 < west 19).
|
||||
expect(result.entities.some((e) => e.id === "berlin-cam")).toBe(false);
|
||||
// No emptyReason when entities are found.
|
||||
expect(result.emptyReason).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// D-06 emptyReason contract — RESP-01 must not regress
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("D-06 emptyReason contract (RESP-01)", () => {
|
||||
it("unknown pluginId (engine 404 + not in registry) → plugin_not_streaming", async () => {
|
||||
mockEngine404();
|
||||
vi.mocked(hasLocalSource).mockResolvedValue(false);
|
||||
|
||||
const result = await getEntitiesInRegion({
|
||||
north: 82, south: 41, west: 19, east: 180,
|
||||
pluginId: "nope",
|
||||
});
|
||||
|
||||
expect(result.entities).toEqual([]);
|
||||
expect(result.emptyReason).toBe("plugin_not_streaming");
|
||||
});
|
||||
|
||||
it("registered camera plugin with bbox containing none of its entities → no_data_matches", async () => {
|
||||
// Engine 404, registry has camera but its entities are all outside the query box.
|
||||
mockEngine404();
|
||||
const farAwayCamera = makeEntity({ id: "sydney-cam", pluginId: "camera", latitude: -33.8, longitude: 151.2 });
|
||||
vi.mocked(hasLocalSource).mockResolvedValue(true);
|
||||
vi.mocked(resolveLocalSnapshot).mockResolvedValue(makeCameraSnapshot([farAwayCamera]));
|
||||
|
||||
// Query a box in Scandinavia — no camera entities are inside it.
|
||||
const result = await getEntitiesInRegion({
|
||||
north: 71, south: 55, west: 5, east: 30,
|
||||
pluginId: "camera",
|
||||
});
|
||||
|
||||
expect(result.entities).toEqual([]);
|
||||
expect(result.emptyReason).toBe("no_data_matches");
|
||||
});
|
||||
|
||||
it("unknown pluginId via searchEntities → plugin_not_streaming", async () => {
|
||||
mockEngine404();
|
||||
vi.mocked(hasLocalSource).mockResolvedValue(false);
|
||||
|
||||
const result = await searchEntities("anything", "nope");
|
||||
|
||||
expect(result.entities).toEqual([]);
|
||||
expect(result.emptyReason).toBe("plugin_not_streaming");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// getAllPluginSnapshots union — local ids are merged with engine ids (D-08)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("getAllPluginSnapshots union", () => {
|
||||
it("includes camera snapshot from local registry when engine manifest omits it", async () => {
|
||||
// Engine manifest returns ["flights"]; local registry adds "camera".
|
||||
const flightEntity = makeEntity({ id: "f1", pluginId: "flights", latitude: 51, longitude: 0 });
|
||||
const cameraEntity = makeEntity({ id: "cam-1", pluginId: "camera", latitude: 55.7, longitude: 37.6 });
|
||||
|
||||
vi.mocked(global.fetch).mockImplementation((url: RequestInfo | URL) => {
|
||||
const urlStr = String(url);
|
||||
if (urlStr.includes("/manifest")) {
|
||||
return Promise.resolve(
|
||||
new Response(JSON.stringify({ plugins: ["flights"] }), { status: 200 }),
|
||||
);
|
||||
}
|
||||
if (urlStr.includes("/api/flights")) {
|
||||
return Promise.resolve(
|
||||
new Response(JSON.stringify({ items: [flightEntity] }), { status: 200 }),
|
||||
);
|
||||
}
|
||||
// camera hits engine → 404, falls through to registry.
|
||||
return Promise.resolve(new Response(null, { status: 404 }));
|
||||
});
|
||||
|
||||
vi.mocked(getLocalSourceIds).mockResolvedValue(new Set(["camera"]));
|
||||
vi.mocked(hasLocalSource).mockResolvedValue(true);
|
||||
vi.mocked(resolveLocalSnapshot).mockResolvedValue(makeCameraSnapshot([cameraEntity]));
|
||||
|
||||
const snapshots = await getAllPluginSnapshots();
|
||||
|
||||
const pluginIds = snapshots.map((s) => s.pluginId);
|
||||
expect(pluginIds).toContain("flights");
|
||||
expect(pluginIds).toContain("camera");
|
||||
// No duplicate camera entry.
|
||||
expect(pluginIds.filter((id) => id === "camera")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("engine-first dedup: camera in both engine and registry resolves to engine snapshot", async () => {
|
||||
// Engine manifest includes "camera" AND registry also lists it.
|
||||
// Engine wins — only one camera snapshot, from the engine.
|
||||
const engineCameraEntity = makeEntity({ id: "engine-cam", pluginId: "camera", latitude: 10, longitude: 20 });
|
||||
const localCameraEntity = makeEntity({ id: "local-cam", pluginId: "camera", latitude: 55.7, longitude: 37.6 });
|
||||
|
||||
vi.mocked(global.fetch).mockImplementation((url: RequestInfo | URL) => {
|
||||
const urlStr = String(url);
|
||||
if (urlStr.includes("/manifest")) {
|
||||
return Promise.resolve(
|
||||
new Response(JSON.stringify({ plugins: ["camera"] }), { status: 200 }),
|
||||
);
|
||||
}
|
||||
if (urlStr.includes("/api/camera")) {
|
||||
return Promise.resolve(
|
||||
new Response(JSON.stringify({ items: [engineCameraEntity] }), { status: 200 }),
|
||||
);
|
||||
}
|
||||
return Promise.resolve(new Response(null, { status: 404 }));
|
||||
});
|
||||
|
||||
// Registry also claims camera is local.
|
||||
vi.mocked(getLocalSourceIds).mockResolvedValue(new Set(["camera"]));
|
||||
// hasLocalSource won't be called because engine returns a snapshot first.
|
||||
vi.mocked(hasLocalSource).mockResolvedValue(true);
|
||||
vi.mocked(resolveLocalSnapshot).mockResolvedValue(makeCameraSnapshot([localCameraEntity]));
|
||||
|
||||
const snapshots = await getAllPluginSnapshots();
|
||||
|
||||
const cameraSnapshots = snapshots.filter((s) => s.pluginId === "camera");
|
||||
// Only one camera snapshot.
|
||||
expect(cameraSnapshots).toHaveLength(1);
|
||||
// It came from the engine (engine-cam), not the local registry (local-cam).
|
||||
expect(cameraSnapshots[0].entities[0].id).toBe("engine-cam");
|
||||
const snapshot = await getPluginData("test-plugin");
|
||||
expect(snapshot?.entities[0].timestamp).toBeInstanceOf(Date);
|
||||
});
|
||||
});
|
||||
+47
-138
@@ -4,15 +4,10 @@ import type {
|
||||
RegionOptions,
|
||||
DetailResult,
|
||||
PluginDataSnapshot,
|
||||
QueryResult,
|
||||
SingleResult,
|
||||
} from "./types";
|
||||
import { matchFilterValue } from "@/core/filters/matchFilterValue";
|
||||
import type { FilterValue } from "@/core/plugins/PluginTypes";
|
||||
import { hasLocalSource, resolveLocalSnapshot, getLocalSourceIds } from "./localSources";
|
||||
|
||||
export function getEngineUrl(): string {
|
||||
return process.env.WWV_DATA_ENGINE_URL ?? "http://localhost:5001";
|
||||
function getEngineUrl(): string {
|
||||
return process.env.NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL ?? "http://localhost:5000";
|
||||
}
|
||||
|
||||
function normalizeEntity(raw: unknown): GeoEntity | null {
|
||||
@@ -40,12 +35,8 @@ function validatePluginId(pluginId: string): string {
|
||||
return pluginId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Private helper: attempt to fetch a plugin snapshot from the data engine.
|
||||
* Returns null on 404, non-2xx, or network failure.
|
||||
* Validation of pluginId is the caller's responsibility.
|
||||
*/
|
||||
async function fetchEngineSnapshot(safeId: string): Promise<PluginDataSnapshot | null> {
|
||||
async function fetchPluginSnapshot(pluginId: string): Promise<PluginDataSnapshot | null> {
|
||||
const safeId = validatePluginId(pluginId);
|
||||
const engineBase = getEngineUrl();
|
||||
const url = new URL(`/api/${safeId}`, engineBase).toString();
|
||||
try {
|
||||
@@ -69,48 +60,23 @@ async function fetchEngineSnapshot(safeId: string): Promise<PluginDataSnapshot |
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a snapshot for the given pluginId.
|
||||
* Resolution order (D-08):
|
||||
* 1. Data engine (engine-first, real-time data).
|
||||
* 2. Local registry (server-side static/client-side sources that have no engine endpoint).
|
||||
* 3. null — the pluginId is genuinely unknown; callers map this to "plugin_not_streaming".
|
||||
*/
|
||||
export async function fetchPluginSnapshot(pluginId: string): Promise<PluginDataSnapshot | null> {
|
||||
const safeId = validatePluginId(pluginId);
|
||||
|
||||
const engineSnapshot = await fetchEngineSnapshot(safeId);
|
||||
if (engineSnapshot !== null) return engineSnapshot;
|
||||
|
||||
if (await hasLocalSource(safeId)) {
|
||||
return resolveLocalSnapshot(safeId);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function getAllPluginSnapshots(): Promise<PluginDataSnapshot[]> {
|
||||
const manifestUrl = `${getEngineUrl()}/manifest`;
|
||||
let enginePluginIds: string[] = [];
|
||||
async function getAllPluginSnapshots(): Promise<PluginDataSnapshot[]> {
|
||||
const url = `${getEngineUrl()}/manifest`;
|
||||
let pluginIds: string[] = [];
|
||||
try {
|
||||
const res = await fetch(manifestUrl, { signal: AbortSignal.timeout(5000) });
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) {
|
||||
console.error(`[data-query] Manifest fetch returned ${res.status}`);
|
||||
} else {
|
||||
const data: unknown = await res.json();
|
||||
enginePluginIds = ((data as Record<string, unknown>)?.plugins as string[]) ?? [];
|
||||
return [];
|
||||
}
|
||||
const data: unknown = await res.json();
|
||||
pluginIds = ((data as Record<string, unknown>)?.plugins as string[]) ?? [];
|
||||
} catch (err) {
|
||||
console.error("[data-query] Failed to fetch manifest:", err);
|
||||
return [];
|
||||
}
|
||||
|
||||
// Union engine ids with local-registry ids; dedupe using a Set so a pluginId
|
||||
// present in both resolves only once (engine-first ordering is preserved
|
||||
// because engine ids come first in the Set iteration).
|
||||
const localIds = Array.from(await getLocalSourceIds());
|
||||
const allIds = Array.from(new Set([...enginePluginIds, ...localIds]));
|
||||
|
||||
const results = await Promise.allSettled(allIds.map(fetchPluginSnapshot));
|
||||
const results = await Promise.allSettled(pluginIds.map(fetchPluginSnapshot));
|
||||
return results.reduce<PluginDataSnapshot[]>((acc, result) => {
|
||||
if (result.status === "fulfilled" && result.value !== null) {
|
||||
acc.push(result.value);
|
||||
@@ -133,61 +99,32 @@ export async function searchEntities(
|
||||
query: string,
|
||||
pluginId?: string,
|
||||
limit: number = 20,
|
||||
filters?: Record<string, FilterValue>,
|
||||
): Promise<QueryResult<SearchResult>> {
|
||||
): Promise<SearchResult[]> {
|
||||
const trimmed = query.trim();
|
||||
if (trimmed === "") return { entities: [], emptyReason: "no_data_matches" };
|
||||
if (trimmed === "") return [];
|
||||
|
||||
const effectiveLimit = Math.min(Math.max(limit, 1), 100);
|
||||
const lower = trimmed.toLowerCase();
|
||||
const filterEntries = filters ? Object.entries(filters) : null;
|
||||
|
||||
// Determine if the plugin is known to the engine (streaming check).
|
||||
let snapshotNotStreaming = false;
|
||||
let snapshots: PluginDataSnapshot[];
|
||||
if (pluginId) {
|
||||
const s = await fetchPluginSnapshot(pluginId);
|
||||
if (s === null) {
|
||||
return { entities: [], emptyReason: "plugin_not_streaming" };
|
||||
}
|
||||
snapshots = [s];
|
||||
} else {
|
||||
snapshots = await getAllPluginSnapshots();
|
||||
// When no pluginId filter: 0 snapshots means engine has no active plugins.
|
||||
if (snapshots.length === 0) {
|
||||
snapshotNotStreaming = true;
|
||||
}
|
||||
}
|
||||
const snapshots = pluginId
|
||||
? await fetchPluginSnapshot(pluginId).then((s) => (s ? [s] : []))
|
||||
: await getAllPluginSnapshots();
|
||||
|
||||
const results: SearchResult[] = [];
|
||||
for (const snapshot of snapshots) {
|
||||
for (const entity of snapshot.entities) {
|
||||
if (results.length >= effectiveLimit) break;
|
||||
const matchTarget = (entity.label ?? entity.id).toLowerCase();
|
||||
if (!matchTarget.includes(lower)) continue;
|
||||
// Apply inline filters on the full GeoEntity.properties BEFORE
|
||||
// entityToSearchResult conversion (which drops properties). D-07.
|
||||
if (filterEntries) {
|
||||
const ok = filterEntries.every(([key, fv]) =>
|
||||
matchFilterValue(entity.properties[key], fv),
|
||||
);
|
||||
if (!ok) continue;
|
||||
if (matchTarget.includes(lower)) {
|
||||
results.push(entityToSearchResult(entity));
|
||||
}
|
||||
results.push(entityToSearchResult(entity));
|
||||
}
|
||||
if (results.length >= effectiveLimit) break;
|
||||
}
|
||||
|
||||
if (results.length === 0) {
|
||||
return {
|
||||
entities: [],
|
||||
emptyReason: snapshotNotStreaming ? "plugin_not_streaming" : "no_data_matches",
|
||||
};
|
||||
}
|
||||
return { entities: results };
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function getEntitiesInRegion(bounds: RegionOptions): Promise<QueryResult<SearchResult>> {
|
||||
export async function getEntitiesInRegion(bounds: RegionOptions): Promise<SearchResult[]> {
|
||||
const { north, south, east, west } = bounds;
|
||||
if (isNaN(north) || isNaN(south) || isNaN(east) || isNaN(west)) {
|
||||
throw new Error("Invalid bounding box: north/south/east/west must all be numbers");
|
||||
@@ -196,83 +133,55 @@ export async function getEntitiesInRegion(bounds: RegionOptions): Promise<QueryR
|
||||
const effectiveLimit = Math.min(bounds.limit ?? 100, 1000);
|
||||
const isAntimeridian = east < west;
|
||||
|
||||
let snapshotNotStreaming = false;
|
||||
let snapshots: PluginDataSnapshot[];
|
||||
if (bounds.pluginId) {
|
||||
const s = await fetchPluginSnapshot(bounds.pluginId);
|
||||
if (s === null) {
|
||||
return { entities: [], emptyReason: "plugin_not_streaming" };
|
||||
}
|
||||
snapshots = [s];
|
||||
} else {
|
||||
snapshots = await getAllPluginSnapshots();
|
||||
if (snapshots.length === 0) {
|
||||
snapshotNotStreaming = true;
|
||||
}
|
||||
}
|
||||
const snapshots = bounds.pluginId
|
||||
? await fetchPluginSnapshot(bounds.pluginId).then((s) => (s ? [s] : []))
|
||||
: await getAllPluginSnapshots();
|
||||
|
||||
// Collect all matches first to get a totalMatched count, then cap.
|
||||
const allMatched: SearchResult[] = [];
|
||||
const results: SearchResult[] = [];
|
||||
for (const snapshot of snapshots) {
|
||||
for (const entity of snapshot.entities) {
|
||||
if (results.length >= effectiveLimit) break;
|
||||
const { latitude: lat, longitude: lon } = entity;
|
||||
if (lat < south || lat > north) continue;
|
||||
const inLon = isAntimeridian
|
||||
? lon >= west || lon <= east
|
||||
: lon >= west && lon <= east;
|
||||
if (inLon) allMatched.push(entityToSearchResult(entity));
|
||||
if (inLon) results.push(entityToSearchResult(entity));
|
||||
}
|
||||
if (results.length >= effectiveLimit) break;
|
||||
}
|
||||
|
||||
if (allMatched.length === 0) {
|
||||
return {
|
||||
entities: [],
|
||||
emptyReason: snapshotNotStreaming ? "plugin_not_streaming" : "no_data_matches",
|
||||
};
|
||||
}
|
||||
|
||||
const truncated = allMatched.length > effectiveLimit;
|
||||
const results = truncated ? allMatched.slice(0, effectiveLimit) : allMatched;
|
||||
return {
|
||||
entities: results,
|
||||
...(truncated && { totalMatched: allMatched.length }),
|
||||
};
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function getEntityDetails(
|
||||
pluginId: string,
|
||||
entityId: string,
|
||||
): Promise<SingleResult<DetailResult>> {
|
||||
): Promise<DetailResult | null> {
|
||||
const snapshot = await fetchPluginSnapshot(pluginId);
|
||||
if (!snapshot) return { data: null, emptyReason: "plugin_not_streaming" };
|
||||
if (!snapshot) return null;
|
||||
|
||||
const entity = snapshot.entities.find((e) => e.id === entityId);
|
||||
if (!entity) return { data: null, emptyReason: "no_data_matches" };
|
||||
if (!entity) return null;
|
||||
|
||||
return {
|
||||
data: {
|
||||
id: entity.id,
|
||||
pluginId: entity.pluginId,
|
||||
latitude: entity.latitude,
|
||||
longitude: entity.longitude,
|
||||
altitude: entity.altitude,
|
||||
heading: entity.heading,
|
||||
speed: entity.speed,
|
||||
timestamp: entity.timestamp,
|
||||
label: entity.label,
|
||||
properties: entity.properties,
|
||||
},
|
||||
id: entity.id,
|
||||
pluginId: entity.pluginId,
|
||||
latitude: entity.latitude,
|
||||
longitude: entity.longitude,
|
||||
altitude: entity.altitude,
|
||||
heading: entity.heading,
|
||||
speed: entity.speed,
|
||||
timestamp: entity.timestamp,
|
||||
label: entity.label,
|
||||
properties: entity.properties,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getPluginData(pluginId: string): Promise<SingleResult<PluginDataSnapshot>> {
|
||||
if (!pluginId.trim()) return { data: null, emptyReason: "plugin_not_streaming" };
|
||||
export async function getPluginData(pluginId: string): Promise<PluginDataSnapshot | null> {
|
||||
if (!pluginId.trim()) return null;
|
||||
try {
|
||||
const snapshot = await fetchPluginSnapshot(pluginId);
|
||||
if (snapshot === null) return { data: null, emptyReason: "plugin_not_streaming" };
|
||||
if (snapshot.entities.length === 0) return { data: snapshot, emptyReason: "no_data_matches" };
|
||||
return { data: snapshot };
|
||||
return fetchPluginSnapshot(pluginId);
|
||||
} catch {
|
||||
return { data: null, emptyReason: "plugin_not_streaming" };
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,50 +1,9 @@
|
||||
import type { GeoEntity } from "@worldwideview/wwv-plugin-sdk";
|
||||
import type { FilterValue } from "@/core/plugins/PluginTypes";
|
||||
|
||||
/**
|
||||
* Reason explaining why a data-query result is empty.
|
||||
*
|
||||
* - plugin_not_streaming: the requested pluginId is absent from the engine
|
||||
* /manifest, or its snapshot fetch returned null (plugin not loaded / offline).
|
||||
* - no_data_matches: the plugin is streaming but 0 entities matched the
|
||||
* query / region / filters.
|
||||
* - no_session_active: the authenticated user has no active globe session.
|
||||
* This value is emitted by the tool layer (which has access to userId),
|
||||
* NEVER by the service layer.
|
||||
*
|
||||
* NOTE: data-query tools (search_entities, get_entities_in_region, get_entity_details,
|
||||
* get_plugin_data) must NEVER emit no_session_active -- they are session-independent.
|
||||
* Only session-required command/filter tools may produce this reason.
|
||||
*/
|
||||
export type EmptyReason = "plugin_not_streaming" | "no_data_matches" | "no_session_active";
|
||||
|
||||
/**
|
||||
* Discriminated result carrying a list of entities and an optional emptyReason.
|
||||
* emptyReason is ONLY present when entities.length === 0.
|
||||
* totalMatched is set when results were capped (entities.length < totalMatched).
|
||||
*/
|
||||
export interface QueryResult<T> {
|
||||
entities: T[];
|
||||
emptyReason?: EmptyReason;
|
||||
/** Total entities that matched before the cap was applied. Present only when the result set was truncated. */
|
||||
totalMatched?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discriminated result for single-entity or plugin-data lookups.
|
||||
* data is null when nothing was found; emptyReason explains why.
|
||||
*/
|
||||
export interface SingleResult<T> {
|
||||
data: T | null;
|
||||
emptyReason?: EmptyReason;
|
||||
}
|
||||
|
||||
export interface SearchOptions {
|
||||
query: string;
|
||||
pluginId?: string;
|
||||
limit?: number;
|
||||
/** Optional inline filters keyed by entity property key (FILT-04, D-07). */
|
||||
filters?: Record<string, FilterValue>;
|
||||
}
|
||||
|
||||
export interface SearchResult {
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/redis");
|
||||
|
||||
import { checkRateLimit } from "./geocodingRateLimit";
|
||||
import { redis } from "@/lib/redis";
|
||||
|
||||
const mockRedis = vi.mocked(redis, true);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockRedis.zremrangebyscore.mockResolvedValue(0);
|
||||
mockRedis.zadd.mockResolvedValue(1);
|
||||
mockRedis.expire.mockResolvedValue(1);
|
||||
});
|
||||
|
||||
describe("checkRateLimit", () => {
|
||||
it("resolves without error when zcard returns 1 (within limit of MAX_REQUESTS=1)", async () => {
|
||||
mockRedis.zcard.mockResolvedValue(1);
|
||||
|
||||
const result = await checkRateLimit("u1");
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns rate_limited error object when zcard returns 2 (exceeds MAX_REQUESTS=1)", async () => {
|
||||
mockRedis.zcard.mockResolvedValue(2);
|
||||
|
||||
const result = await checkRateLimit("u1");
|
||||
|
||||
expect(result).toMatchObject({ error: "rate_limited" });
|
||||
});
|
||||
|
||||
it("calls zremrangebyscore to prune expired entries before checking count", async () => {
|
||||
mockRedis.zcard.mockResolvedValue(0);
|
||||
|
||||
await checkRateLimit("u1");
|
||||
|
||||
expect(mockRedis.zremrangebyscore).toHaveBeenCalledWith(
|
||||
expect.stringContaining("u1"),
|
||||
"-inf",
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
|
||||
it("calls zadd to record the current request timestamp", async () => {
|
||||
mockRedis.zcard.mockResolvedValue(0);
|
||||
|
||||
await checkRateLimit("u1");
|
||||
|
||||
expect(mockRedis.zadd).toHaveBeenCalledWith(
|
||||
expect.stringContaining("u1"),
|
||||
expect.any(Number),
|
||||
expect.any(String),
|
||||
);
|
||||
});
|
||||
|
||||
it("calls expire(key, 5) to auto-expire the sorted set", async () => {
|
||||
mockRedis.zcard.mockResolvedValue(0);
|
||||
|
||||
await checkRateLimit("u1");
|
||||
|
||||
expect(mockRedis.expire).toHaveBeenCalledWith(expect.stringContaining("u1"), 5);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user