Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8134e2b890 | ||
|
|
f1405bd313 | ||
|
|
2eec714912 | ||
|
|
26d2063a1e | ||
|
|
84f8ade70c | ||
|
|
5ea7855e02 | ||
|
|
5201ae32c8 | ||
|
|
ca8c6ad940 | ||
|
|
ac9aa64ddb | ||
|
|
7a055f6bb8 | ||
|
|
45594304f8 | ||
|
|
1b67e70bf9 | ||
|
|
5535673f8d | ||
|
|
f0e658b4c2 | ||
|
|
053a916ada | ||
|
|
f2cc303b0c | ||
|
|
a8ed51d1a7 | ||
|
|
12e5ba818e | ||
|
|
066618dea5 | ||
|
|
1c175e7e8e | ||
|
|
b42c1e7e06 | ||
|
|
d6ffec3f41 | ||
|
|
a34cf4cf8a | ||
|
|
df1d6a72f6 | ||
|
|
7583b4cac1 | ||
|
|
fc5aa7860b | ||
|
|
2438ae7e9d | ||
|
|
bd1de5ac7a |
No files matched your search
@@ -0,0 +1,106 @@
|
||||
# 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.3 Location Intelligence
|
||||
|
||||
**Goal:** Extend the MCP server with geocoding, rich entity filtering, and entity favorites so AI agents can find places, drill into plugin data, and bookmark tracked objects.
|
||||
|
||||
**Target features:**
|
||||
- Geocoding + fly-to (2 new MCP tools: `geocode_location` + `fly_to`)
|
||||
- Entity filtering via MCP (generic baseline + plugin-declared filter extensions)
|
||||
- Entity favorites: `save_favorite`, `list_favorites`, `remove_favorite` (per-user, PostgreSQL-backed)
|
||||
|
||||
**Backlog (deferred):**
|
||||
- PLG-01/PLG-02: list_plugins() + install_plugin() marketplace tools (backlog 999.1/999.2)
|
||||
- UX-01: ConnectAgentHelper upgrade CTA in demo edition (backlog 999.3)
|
||||
|
||||
## Requirements
|
||||
|
||||
### Validated (Shipped)
|
||||
|
||||
**v1.0 Unified Auth Account System (Phases 1-11, shipped 2026-05-28)**
|
||||
- Supabase shared-cookie auth federation across worldwideview, marketplace, and web
|
||||
- OAuth (GitHub, Google) and email+password auth with NextAuth v5
|
||||
- Shared user identity via `NEXT_PUBLIC_WWV_COOKIE_DOMAIN` across three apps
|
||||
- JWT session persistence, auth callback redirect fix, linked accounts page
|
||||
- Legal/privacy compliance (ToS, cookie consent, GDPR data deletion flow)
|
||||
|
||||
**v1.1 Plugin Install Auth Gate (Phase 12 shipped 2026-05-28)**
|
||||
- PluginInstall model + migration + Plugin.installs counter
|
||||
- Fire-and-forget install tracking upsert in GET /api/install/start
|
||||
|
||||
**v1.2 Full MCP Support (Phases 16-21, shipped 2026-05-30)**
|
||||
- Transport-agnostic API keys with bcrypt storage and timing-oracle prevention - v1.2
|
||||
- Stateless MCP server (Streamable HTTP) with Bearer auth - v1.2
|
||||
- ConnectAgentHelper per-client setup UI; secret only in Authorization header - v1.2
|
||||
- Globe state as MCP resources backed by Redis with heartbeat TTL - v1.2
|
||||
- Globe command bridge via SSE push (< 100ms latency) - v1.2
|
||||
- Data query tools across all active plugins - v1.2
|
||||
- Plugin-contributed namespaced MCP tools via frontend relay - v1.2
|
||||
|
||||
### Active (v1.3 Location Intelligence)
|
||||
|
||||
- [ ] geocode_location(query) MCP tool returning {lat, lng, name, bbox} via Nominatim/OSM
|
||||
- [ ] fly_to(lat, lng, altitude?) MCP tool panning globe camera via SSE command bridge
|
||||
- [ ] Generic entity filters (type, region, timeRange, status) via MCP set_filter/clear_filter
|
||||
- [ ] Plugin-declared filter manifest extension + get_plugin_filters(pluginId) MCP tool
|
||||
- [ ] UserFavorite Prisma model + save_favorite / list_favorites / remove_favorite MCP tools
|
||||
|
||||
### Out of Scope
|
||||
|
||||
- Embedding an AI chat UI inside the globe -- MCP is server-only
|
||||
- Browser-side MCP client -- globe is an MCP server target, not client
|
||||
- Playwright/computer-use globe control -- using SSE command bridge
|
||||
- Stdio-only MCP transport -- HTTP/SSE for production deployability
|
||||
- CLI tool -- API + MCP cover v1.2; CLI is additive and non-blocking
|
||||
- API key scopes/permissions and rotation/grace-period flows -- revisit later
|
||||
- OAuth 2.1 for MCP auth -- personal API keys sufficient for v1.2
|
||||
|
||||
## Context
|
||||
|
||||
- **Three apps**: worldwideview (Next.js globe), worldwideview-marketplace (plugin store), worldwideview-web (marketing)
|
||||
- **Auth**: NextAuth v5 + Supabase shared cookies, auth host at worldwideview.dev
|
||||
- **State**: 9 Zustand slices (globe, layers, timeline, ui, filter, data, config, favorites, geojson)
|
||||
- **MCP**: Stateless Streamable HTTP at /api/mcp; Redis for state/commands/catalog; 8 tools + 3 resources
|
||||
- **Data pipeline**: wwv-data-engine (Fastify + Redis) + plugin seeders
|
||||
- **Plugin SDK**: `@worldwideview/wwv-plugin-sdk` with mcpTools manifest extension
|
||||
|
||||
## Key Decisions
|
||||
|
||||
| Decision | Rationale | Outcome |
|
||||
|----------|-----------|---------|
|
||||
| Supabase shared-cookie auth federation | Single sign-on across 3 Next.js apps | ✓ Good |
|
||||
| JWT install bridge for plugin installs | Instance-level auth keeps globe secure | ✓ Good |
|
||||
| HTTP/SSE Streamable HTTP for MCP | Production deployable, any AI client | ✓ Good |
|
||||
| Redis for all MCP state (no in-process) | Scales to multi-user cloud deployment | ✓ Good |
|
||||
| SSE push over WebSocket | Zero infra change, App Router native, MCP spec-first | ✓ Good |
|
||||
| Plugin tools via frontend relay | worldwideview-only, no engine endpoint, composable | ✓ Good |
|
||||
| Generic transport-agnostic API keys | One bearer key for MCP + future REST | ✓ Good |
|
||||
| Marketplace tools deferred to v1.3 | Kept v1.2 worldwideview-only; clean scope | ✓ Good |
|
||||
|
||||
## Evolution
|
||||
|
||||
This document evolves at phase transitions and milestone boundaries.
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-31 after v1.3 milestone start*
|
||||
@@ -0,0 +1,96 @@
|
||||
# Requirements: WorldWideView v1.3
|
||||
|
||||
**Defined:** 2026-05-31
|
||||
**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.
|
||||
|
||||
## v1.3 Requirements
|
||||
|
||||
### Geocoding
|
||||
|
||||
- [ ] **GEO-01**: Agent can call `geocode_location(query)` and receive 2-5 ranked results with `{lat, lng, name, type, country, bbox, importance}` via Nominatim
|
||||
- [x] **GEO-02**: Agent can call `fly_to(lat, lng, altitude?, bbox?)` to pan/zoom the globe camera; when `bbox` is provided, Cesium fits the region to the bounding box
|
||||
- [x] **GEO-03**: Geocoding enforces a server-side 1 req/sec Redis sliding window rate limiter and caches results for 24 hours to prevent Nominatim IP ban
|
||||
|
||||
### Filtering
|
||||
|
||||
- [x] **FILT-01**: Agent can call `set_filter(pluginId, filters)` to push a live filter to the globe via the SSE command bridge; browser applies it to Zustand filterSlice
|
||||
- [x] **FILT-02**: Agent can call `clear_filter(pluginId?)` to remove all active filters or per-plugin filters via SSE bridge
|
||||
- [x] **FILT-03**: Agent can call `get_plugin_filters(pluginId)` to retrieve filterable fields declared by a plugin via session catalog extension
|
||||
- [x] **FILT-04**: Agent can pass optional `filters` params to the existing `search_entities` tool to receive pre-filtered results inline (no set_filter state dependency)
|
||||
|
||||
### Favorites
|
||||
|
||||
- [ ] **FAV-01**: Agent can call `save_favorite(entityId, pluginId, name?)` to bookmark a tracked entity per-user (upsert on existing `Favorite` Prisma model)
|
||||
- [ ] **FAV-02**: Agent can call `list_favorites()` to retrieve saved entities with `status: "live" | "stale"` (stale = entity not currently in data stream)
|
||||
- [ ] **FAV-03**: Agent can call `remove_favorite(entityId, pluginId)` to delete a saved bookmark
|
||||
|
||||
### Safety & Guards
|
||||
|
||||
- [x] **SAFE-01**: All new MCP tool registrars check `isDemo` gate before `authenticateApiKey()`, consistent with v1.2 pattern
|
||||
- [ ] **SAFE-02**: MCP favorites tools call `prisma.favorite` directly and never proxy through the REST `/api/user/favorites` route (which uses NextAuth cookie auth and silently 401s on API key requests)
|
||||
|
||||
### Integration
|
||||
|
||||
- [ ] **INTG-01**: All v1.3 tool registrars (geocoding, favorites, filtering) are wired into the MCP POST handler; `tools/list` exposes all 8 new tools
|
||||
- [ ] **INTG-02**: `MCP_SERVER_VERSION` constant is bumped to `"1.3.0"` and reflected in every `initialize` response `serverInfo.version`
|
||||
|
||||
### Documentation
|
||||
|
||||
- [ ] **DOC-01**: Each v1.3 MCP tool has a complete tool-level description in its registrar (input schema, output shape, error codes, usage example) so it is self-documenting via `tools/list`
|
||||
- [ ] **DOC-02**: A developer guide exists explaining how to declare filterable fields in a plugin manifest (`filterDefinitions` extension) with a worked example
|
||||
- [ ] **DOC-03**: The user-facing ConnectAgentHelper or a companion doc describes all v1.3 capabilities available to connected agents (geocoding, filtering, favorites)
|
||||
- [ ] **DOC-04**: A changelog / release notes entry is written for v1.3 covering the 8 new MCP tools, 2 integration changes, and 1 search enhancement
|
||||
|
||||
## Future Requirements (v1.4+)
|
||||
|
||||
### Marketplace Tools (Backlog)
|
||||
- **PLG-01**: Agent can call `list_plugins()` to browse available marketplace plugins
|
||||
- **PLG-02**: Agent can call `install_plugin(pluginId)` to install a marketplace plugin
|
||||
- **UX-01**: ConnectAgentHelper shows upgrade CTA in demo edition
|
||||
|
||||
### Geocoding Enhancements
|
||||
- Reverse geocoding: coordinates to address
|
||||
- Structured address input (street, city, country)
|
||||
- Provider fallback (Photon, OpenCage)
|
||||
|
||||
## Out of Scope
|
||||
|
||||
| Feature | Reason |
|
||||
|---------|--------|
|
||||
| Reverse geocoding | Not in v1.3 goals; forward search sufficient |
|
||||
| Filter state persisted in Redis | Zustand is single source of truth; SSE push only |
|
||||
| search_entities as a new filtered tool | Extended existing tool with optional filters instead |
|
||||
| MCP favorites REST proxy | Architecture invariant: API key auth != cookie auth |
|
||||
| OAuth 2.1 for MCP auth | Personal API keys sufficient |
|
||||
|
||||
## Traceability
|
||||
|
||||
| Requirement | Phase | Status |
|
||||
|-------------|-------|--------|
|
||||
| GEO-01 | Phase 22 | Pending |
|
||||
| GEO-02 | Phase 22 | Complete |
|
||||
| GEO-03 | Phase 22 | Complete |
|
||||
| FAV-01 | Phase 22 | Pending |
|
||||
| FAV-02 | Phase 22 | Pending |
|
||||
| FAV-03 | Phase 22 | Pending |
|
||||
| SAFE-01 | Phase 22 | Complete |
|
||||
| SAFE-02 | Phase 22 | Pending |
|
||||
| FILT-01 | Phase 23 | Complete |
|
||||
| FILT-02 | Phase 23 | Complete |
|
||||
| FILT-03 | Phase 23 | Complete |
|
||||
| FILT-04 | Phase 23 | Complete |
|
||||
| INTG-01 | Phase 24 | Pending |
|
||||
| INTG-02 | Phase 24 | Pending |
|
||||
| DOC-01 | Phase 25 | Pending |
|
||||
| DOC-02 | Phase 25 | Pending |
|
||||
| DOC-03 | Phase 25 | Pending |
|
||||
| DOC-04 | Phase 25 | Pending |
|
||||
|
||||
**Coverage:**
|
||||
- v1.3 requirements: 18 total
|
||||
- Mapped to phases: 18
|
||||
- Unmapped: 0 ✓
|
||||
|
||||
---
|
||||
*Requirements defined: 2026-05-31*
|
||||
*Last updated: 2026-05-31 after Phase 25 documentation phase added*
|
||||
+95
-111
@@ -1,130 +1,114 @@
|
||||
# Roadmap: Full MCP Support (v1.2)
|
||||
# Roadmap: WorldWideView
|
||||
|
||||
> **Planning home:** This is the isolated planning for the **v1.2 Full MCP Support** milestone,
|
||||
> living in the `feat/mcp-support` worktree of `worldwideview`. It was split out of the shared
|
||||
> root `C:\dev\wwv\.planning\ROADMAP.md` on 2026-05-29 (that file now holds v1.1 only).
|
||||
> Combined pre-split original: `C:\dev\wwv\.planning\archive\pre-split-2026-05-29\ROADMAP.combined.md`.
|
||||
>
|
||||
> **QA ID note:** the v1.2 quality requirements were renamed `QA-01/02/03` -> `MCP-QA-01/02/03`
|
||||
> during the split, to resolve a collision with v1.1's own `QA-01/02/03`.
|
||||
## Milestones
|
||||
|
||||
## Milestone
|
||||
|
||||
- v1.2 **Full MCP Support** - Phases 16-21 (greenfield; no v1.2 code exists yet as of 2026-05-29)
|
||||
|
||||
**Primary repo:** `worldwideview` (this worktree).
|
||||
**Cross-repo dependencies (declared, not separate planning roots):**
|
||||
- **Phase 20** delegates entity queries to `wwv-data-engine` REST endpoints.
|
||||
- **Phase 21** depends on `wwv-data-engine` REST (plugin tool delegation), the `@worldwideview/wwv-plugin-sdk` package (manifest `mcpTools` extension), and the existing `worldwideview-marketplace` JWT install bridge (for `list_plugins` / `install_plugin`).
|
||||
- [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)
|
||||
|
||||
## Phases
|
||||
|
||||
- [ ] **Phase 16: API Key Auth Foundation** - generic transport-agnostic API keys: UserApiKey DB model, bcrypt prefix-hash storage, reusable `authenticateApiKey()` middleware, "Keys & Access" modal key CRUD + reveal-once UI
|
||||
- [ ] **Phase 17: MCP Server Foundation** - raw `@modelcontextprotocol/sdk` Streamable HTTP endpoint in a Next 16 route handler, Bearer auth gate, stateless operation, Coolify/Nginx runbook, + "Connect your agent" helper (per-client config + prompt template)
|
||||
- [ ] **Phase 18: Globe State Sync + Sessions** - useGlobeStatePush hook, heartbeat, globe://state and globe://sessions resources
|
||||
- [ ] **Phase 19: Globe Command Bridge** - WebSocket relay, useGlobeCommandBridge hook, per-session Redis pub/sub routing
|
||||
- [ ] **Phase 20: Data Query Tools** - search_entities, get_entities_in_region, get_entity_details, get_plugin_data (parallel with Phase 19)
|
||||
- [ ] **Phase 21: Plugin-Contributed Tools + Quality** - SDK manifest extension, auto-namespace, plugin bridge, dynamic tool list, tests, README
|
||||
<details>
|
||||
<summary>v1.2 Full MCP Support (Phases 16-21) - SHIPPED 2026-05-30</summary>
|
||||
|
||||
- [x] Phase 16: API Key Auth Foundation (4/4 plans) - completed 2026-05-29
|
||||
- [x] Phase 17: MCP Server Foundation (3/3 plans) - completed 2026-05-30
|
||||
- [x] Phase 18: Globe State Sync + Sessions (4/4 plans + gap-closure) - completed 2026-05-30
|
||||
- [x] Phase 19a: Globe Command Bridge poll-based (3/3 plans) - completed 2026-05-30
|
||||
- [x] Phase 19b: SSE Push Transport (2/2 plans) - completed 2026-05-30
|
||||
- [x] Phase 20: Data Query Tools (4/4 plans) - completed 2026-05-30
|
||||
- [x] Phase 21: Plugin-Contributed Tools + Quality (5/5 plans) - completed 2026-05-30
|
||||
|
||||
Full details: [milestones/v1.2-ROADMAP.md](milestones/v1.2-ROADMAP.md)
|
||||
|
||||
</details>
|
||||
|
||||
### v1.3 Location Intelligence
|
||||
|
||||
- [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)
|
||||
|
||||
## Phase Details
|
||||
|
||||
### Phase 16: API Key Auth Foundation
|
||||
**Goal**: Users can generate, view, and revoke generic personal API keys; keys are stored securely and a reusable `authenticateApiKey()` middleware is ready for Phase 17 (MCP) and future REST routes
|
||||
**Depends on**: Nothing (first phase of v1.2)
|
||||
**Target repo**: worldwideview ("Keys & Access" modal section + Prisma `UserApiKey` model + auth middleware)
|
||||
**Requirements**: KEY-01, KEY-02, KEY-03, KEY-04, API-01 (middleware portion)
|
||||
**Architecture note**: keys are **transport-agnostic** (not MCP-only); the auth middleware is reusable; capabilities are a shared service layer wrapped thinly by MCP/REST. The per-client "Connect your agent" helper is **Phase 17** (needs the live `/api/mcp` URL); Phase 16 ships only the key + the "API & MCP Access" section shell.
|
||||
### Phase 22: Geocoding + Favorites
|
||||
**Goal**: AI agents can find any place on Earth by name, fly the globe camera to it, and bookmark tracked entities for later retrieval
|
||||
**Depends on**: Phase 21 (v1.2 SSE command bridge, authenticateApiKey, Redis, Prisma Favorite model)
|
||||
**Requirements**: GEO-01, GEO-02, GEO-03, FAV-01, FAV-02, FAV-03, SAFE-01, SAFE-02
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. User clicks "Generate API Key" in the "Keys & Access" modal and sees the full combined `wwv_<prefix>.<secret>` token exactly once in a copyable field with a "won't see this again" warning
|
||||
2. Key is stored as `{prefix}.{bcrypt(secret, cost=12)}`; lookup by prefix; a dummy bcrypt compare runs even when prefix is not found (timing oracle prevention)
|
||||
3. User can view active keys (name, created, last used) and revoke any -- revoked (hard-deleted) key returns 401 immediately on next request
|
||||
4. Attempting to generate a 4th key returns a clear error; max 3 enforced in the create route AND the UI
|
||||
5. `authenticateApiKey(request)` exists as a standalone, transport-neutral helper (importable by any future route), with `lastUsedAt` updated best-effort/throttled on success
|
||||
**Plans**: 4 plans (4 waves)
|
||||
- [x] 16-01-PLAN.md — Wave 0 RED test scaffolds (helper + route tests) — COMPLETE 2026-05-29
|
||||
- [x] 16-02-PLAN.md — UserApiKey schema + db push + timing-safe apiKeyAuth.ts helper
|
||||
- [x] 16-03-PLAN.md — /api/api-keys CRUD routes (list, create max-3, ownership-scoped revoke)
|
||||
- [ ] 16-04-PLAN.md — PersonalApiKeysSection UI + Header 'Keys & Access' wiring + semver bump
|
||||
|
||||
### Phase 17: MCP Server Foundation
|
||||
**Goal**: A valid Streamable HTTP MCP endpoint is live, authenticated, stateless, confirmed streaming in production, AND users can connect their AI client in one copy-paste step
|
||||
**Depends on**: Phase 16
|
||||
**Target repo**: worldwideview (+ Coolify/Nginx infra config)
|
||||
**Requirements**: MCP-01, MCP-02, MCP-03, MCP-04, CONNECT-01, CONNECT-02, CONNECT-03
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Claude Code connects to `/api/mcp` with a valid Bearer key and receives a handshake with `protocolVersion`, `serverInfo`, and the full tools/resources list
|
||||
2. An unauthenticated request returns HTTP 401 with a JSON-RPC 2.0 error shape
|
||||
3. No `McpServer` instance is cached between requests -- each request creates a fresh one (stateless confirmed)
|
||||
4. The Coolify Nginx config includes `X-Accel-Buffering: no` and extended `proxy_read_timeout`; a 60-second streaming connection holds open without disconnect
|
||||
5. The "API & MCP Access" section renders a per-client connection helper (Claude Desktop / Cursor / VS Code `mcpServers` JSON with Bearer header; generic Manual block; Claude Code CLI deferred as "coming soon") + a copy-paste "prompt for your agent"; the secret never appears in a URL/deep-link query
|
||||
**Library decision**: raw `@modelcontextprotocol/sdk@^1.29.0` (NOT mcp-handler) + the SDK's `WebStandardStreamableHTTPServerTransport` inside a Next 16 App Router route handler — confirmed against SDK 1.29.0 published types, NO custom server.ts needed in Phase 17 (per `BATCH-DECISIONS-17-21.md` / `17-CONTEXT.md`).
|
||||
**Plans**: 3 plans (3 waves)
|
||||
- [x] 17-01-PLAN.md — Wave 0: RED test scaffolds (route auth/edition/stateless/streaming-header tests) + raw-SDK transport runtime spike
|
||||
- [ ] 17-02-PLAN.md — Wave 1: install SDK + createMcpServer() factory + gated stateless /api/mcp route handler (turns Wave 0 green)
|
||||
- [ ] 17-03-PLAN.md — Wave 2: ConnectAgentHelper UI (per-client config + prompt) + Coolify/Nginx runbook + semver bump to 2.26.0
|
||||
|
||||
### Phase 18: Globe State Sync + Sessions
|
||||
**Goal**: Claude can read what is on the globe and which browser tabs are open, with accurate live data
|
||||
**Depends on**: Phase 17
|
||||
**Target repo**: worldwideview (+ Redis)
|
||||
**Requirements**: RSRC-01, RSRC-02, RSRC-03, RSRC-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. `globe://state/{sessionId}` returns the current viewport (lat/lng/altitude/heading/pitch), active layer list, selected entity, and timeline position
|
||||
2. `globe://sessions` lists all open browser tabs with sessionId, viewport summary, active layers, and last-seen timestamp
|
||||
3. A closed browser tab drops from `globe://sessions` within 30 seconds (heartbeat TTL expiry)
|
||||
4. A viewport change in the browser is reflected in `globe://state` within 1 second (500ms debounce + network round trip)
|
||||
1. Agent calls `geocode_location("Paris")` and receives ranked results with lat/lng/name/bbox without triggering Nominatim rate limits across repeated calls
|
||||
2. Agent calls `fly_to(48.85, 2.35)` and the live globe camera pans to that coordinate within SSE push latency (< 100ms)
|
||||
3. Agent calls `save_favorite`, then `list_favorites`, and the saved entity appears with a `status` field reflecting whether it is currently live in the data stream
|
||||
4. Agent calls `remove_favorite` and the entry is gone from subsequent `list_favorites` responses
|
||||
5. All new tools return a structured error (not 500) when called in demo edition, consistent with v1.2 isDemo gate behavior
|
||||
**Plans**: TBD
|
||||
|
||||
### Phase 19: Globe Command Bridge
|
||||
**Goal**: Claude can send pan, zoom, layer, and timeline commands that physically execute in the correct open browser tab
|
||||
**Depends on**: Phase 18 (needs sessionIds from heartbeat registry)
|
||||
**Target repo**: worldwideview (+ Redis)
|
||||
**Requirements**: CTRL-01, CTRL-02, CTRL-03, CTRL-04, CTRL-05, CTRL-06
|
||||
**Note**: Phases 19 and 20 can be executed in parallel once Phase 17 is complete
|
||||
### Phase 23: Entity Filtering
|
||||
**Goal**: AI agents can push live filters to the globe and discover what filter fields each plugin exposes
|
||||
**Depends on**: Phase 22 (isDemo + authenticateApiKey patterns established, GlobeCommand type in Redis/SSE bridge)
|
||||
**Requirements**: FILT-01, FILT-02, FILT-03, FILT-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. Calling `pan_globe({ sessionId, lat: 35.68, lng: 139.69 })` causes the CesiumJS camera to fly to Tokyo in the targeted browser tab
|
||||
2. `toggle_layer` visibly enables or disables a plugin layer in the globe
|
||||
3. With 2 tabs open, Claude reads `globe://sessions`, picks the contextually correct tab, and only that tab receives the command
|
||||
4. Opening 10 concurrent MCP connections does not create 10 Redis subscriptions -- singleton subscriber confirmed
|
||||
5. A Redis restart does not permanently break command delivery; the subscriber reconnects and commands resume within 5 seconds
|
||||
**Plans**: TBD
|
||||
1. Agent calls `set_filter("flights", { status: "airborne" })` and the globe immediately hides non-airborne entities without a page reload
|
||||
2. Agent calls `clear_filter()` with no arguments and all active plugin filters are removed from the globe in one command
|
||||
3. Agent calls `get_plugin_filters("flights")` and receives the filterable fields declared in that plugin's session catalog entry
|
||||
4. Agent passes `filters` to the existing `search_entities` call and receives only matching results, with no dependency on prior `set_filter` state
|
||||
**Plans**: 3 plans (ships atomically per STATE.md)
|
||||
- [x] 23-01-PLAN.md — Foundation: GlobeCommand setFilter/clearFilter variants + validator, bridge dispatch into filterSlice, shared filterValueSchema, matchFilterValue extraction, catalog filterDefinitions, RED tool stubs (wave 1, TDD)
|
||||
- [x] 23-02-PLAN.md — Filter MCP tools (set_filter, clear_filter, get_plugin_filters), search_entities filters param on properties, catalog publisher emits filterDefinitions (wave 2, TDD)
|
||||
- [x] 23-03-PLAN.md — Wire registerFilterTools into the MCP route + atomic phase integration verification (wave 3)
|
||||
|
||||
### Phase 20: Data Query Tools
|
||||
**Goal**: Claude can query live entity data across all active plugins without requiring an open browser tab
|
||||
**Depends on**: Phase 17 (stateless reads from data engine REST; no browser session required)
|
||||
**Target repo**: worldwideview MCP route + **wwv-data-engine** (REST query delegation) -- cross-repo
|
||||
**Requirements**: QUERY-01, QUERY-02, QUERY-03, QUERY-04
|
||||
**Note**: Can be executed in parallel with Phase 19
|
||||
### Phase 24: Route Wiring + Version Bump
|
||||
**Goal**: All v1.3 tools are reachable via the production MCP endpoint and the server self-reports version 1.3.0
|
||||
**Depends on**: Phase 22, Phase 23 (all registrars implemented)
|
||||
**Requirements**: INTG-01 (integration wiring), INTG-02 (version bump)
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. `search_entities({ query: "Singapore" })` returns entities from active plugins near Singapore with id, name, lat/lng, plugin
|
||||
2. `get_entities_in_region` with a bounding box returns all entities within it, respecting the optional `pluginId` filter
|
||||
3. `get_entity_details` returns the full properties object for a specific entity without error
|
||||
4. `get_plugin_data` returns the current snapshot gracefully even when the plugin has no active data (empty array, not a crash)
|
||||
**Plans**: TBD
|
||||
1. MCP `tools/list` response includes all v1.3 tools: `geocode_location`, `fly_to`, `save_favorite`, `list_favorites`, `remove_favorite`, `set_filter`, `clear_filter`, `get_plugin_filters`
|
||||
2. MCP server `serverInfo.version` field returns `"1.3.0"` on every initialize handshake
|
||||
3. `search_entities` with optional `filters` param is reflected in the tool schema exposed to clients
|
||||
**Plans**: 24-01 (COMPLETE) - INTG-01 verified, INTG-02 shipped (MCP_SERVER_VERSION 1.3.0)
|
||||
**Status**: COMPLETE 2026-05-31. tsc clean, 750 Vitest tests GREEN (+12), build OK. Commits 5201ae3, 5ea7855.
|
||||
|
||||
### Phase 21: Plugin-Contributed Tools + Quality
|
||||
**Goal**: Installed plugins expose their own namespaced MCP tools; the tool list updates dynamically; the feature is documented and tested
|
||||
**Depends on**: Phases 19 and 20
|
||||
**Target repo**: worldwideview MCP route + **`@worldwideview/wwv-plugin-sdk`** (manifest extension) + **wwv-data-engine** (plugin tool delegation) + **worldwideview-marketplace** JWT bridge (`list_plugins` / `install_plugin`) -- cross-repo, 3 external deps
|
||||
**Requirements**: PLUG-01, PLUG-02, PLUG-03, PLUG-04, PLG-01, PLG-02, MCP-QA-01, MCP-QA-02, MCP-QA-03
|
||||
### Phase 25: Documentation
|
||||
**Goal**: Every v1.3 feature is fully documented for three audiences: MCP clients (tool schemas), plugin developers (filter manifest guide), and end users (capability summary)
|
||||
**Depends on**: Phase 24 (all tools shipped and wired; final tool schemas stable)
|
||||
**Requirements**: DOC-01, DOC-02, DOC-03, DOC-04
|
||||
**Success Criteria** (what must be TRUE):
|
||||
1. A plugin with `mcpTools` in its manifest has those tools registered as `{pluginId}__toolName`; existing plugins without `mcpTools` are unaffected
|
||||
2. Installing a new plugin fires `notifications/tools/list_changed`; Claude's next `tools/list` call includes the new plugin's tools
|
||||
3. `list_plugins()` returns marketplace plugins with accurate install status; `install_plugin({ pluginSlug })` triggers the existing JWT bridge flow
|
||||
4. The README contains a copy-pasteable Claude Code MCP config block that works end-to-end with a generated API key
|
||||
5. Vitest tests pass: auth rejection (401), tool dispatch to correct handler, malformed input errors, Redis singleton reconnection
|
||||
1. Every v1.3 MCP tool description in `registerGeocodingTools`, `registerFavoritesTools`, `registerFilterTools` includes: what it does, all input params with types, the output shape, and at least one usage example
|
||||
2. A `docs/plugin-filter-guide.md` (or equivalent) explains how a plugin author declares `filterDefinitions` in their manifest with a complete worked example for a hypothetical flights plugin
|
||||
3. ConnectAgentHelper or a linked doc lists all v1.3 tools an agent can call, with a plain-English description of each capability
|
||||
4. A v1.3 changelog entry (in `CHANGELOG.md` or the PR body) lists all 8 new MCP tools, the `search_entities` filter enhancement, and the version bump to 1.3.0
|
||||
**Plans**: 25-01 (COMPLETE) - DOC-01..04 closed.
|
||||
**Status**: COMPLETE 2026-05-31. Enriched all 8 v1.3 tool descriptions (DOC-01), added docs/plugin-filter-guide.md (DOC-02), listed all tools in ConnectAgentHelper (DOC-03), added CHANGELOG.md v1.3.0 entry (DOC-04). tsc clean, 750 Vitest tests GREEN, build OK. Commits 84f8ade, 26d2063, 2eec714, f1405bd.
|
||||
|
||||
## Progress
|
||||
## Progress Table
|
||||
|
||||
**Execution Order:**
|
||||
Phases execute in numeric order, with one parallel branch: 16 -> 17 -> { 18 -> 19, 20 } -> 21
|
||||
(Phases 19 and 20 may run in parallel once 17 is done; 18 must precede 19.)
|
||||
| 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 |
|
||||
|
||||
| Phase | Milestone | Plans Complete | Status | Completed |
|
||||
|-------|-----------|----------------|--------|-----------|
|
||||
| 16. API Key Auth Foundation | v1.2 | 3/4 | In Progress| |
|
||||
| 17. MCP Server Foundation | v1.2 | 1/3 | In Progress| |
|
||||
| 18. Globe State Sync + Sessions | v1.2 | 0/? | Not started | - |
|
||||
| 19. Globe Command Bridge | v1.2 | 0/? | Not started | - |
|
||||
| 20. Data Query Tools | v1.2 | 0/? | Not started | - |
|
||||
| 21. Plugin-Contributed Tools + Quality | v1.2 | 0/? | Not started | - |
|
||||
## Backlog
|
||||
|
||||
Per the 21-REPLAN locked decision ("NO marketplace" in v1.2 scope), the two marketplace
|
||||
plugin-management MCP tools were deferred. They require the marketplace JWT install bridge,
|
||||
which was descoped to keep v1.2 worldwideview-only.
|
||||
|
||||
- **999.1 -- PLG-01: `list_plugins()` MCP tool** -- returns all marketplace plugins with
|
||||
install status for the authenticated user. Depends on marketplace API + JWT bridge.
|
||||
- **999.2 -- PLG-02: `install_plugin({ pluginSlug })` MCP tool** -- triggers installation via
|
||||
the existing marketplace JWT bridge flow. Depends on PLG-01 + marketplace install endpoint.
|
||||
|
||||
- **999.3 -- UX-01: Show MCP / ConnectAgentHelper as "Cloud edition" upgrade CTA in demo** --
|
||||
Currently `!isDemo` in Header.tsx:449 hides the entire ConnectAgentHelper section in demo.
|
||||
UX improvement: surface it as a locked/teaser CTA that explains the feature and links to
|
||||
upgrade. Pairs with v1.3 MCP-OBSERVATIONS.md scope (geocoding, OSM search, basemap control,
|
||||
entity filtering, enhanced search, favorites, plugin-tool discovery).
|
||||
|
||||
Also tracked as partials (functional, refinement deferred):
|
||||
- **CTRL-02** focus_entity entityId-only resolution -- currently a no-op without lat/lng;
|
||||
needs entity-id -> coordinate lookup wired into the command dispatch.
|
||||
- **MCP-QA-03** explicit Redis reconnect test -- stateless SSE arch makes the original
|
||||
WebSocket-subscriber spec N/A; ioredis auto-reconnects. Add a reconnect test if reliability
|
||||
concerns arise.
|
||||
+44
-195
@@ -1,216 +1,65 @@
|
||||
---
|
||||
gsd_state_version: 1.0
|
||||
milestone: v1.2
|
||||
milestone_name: Full MCP Support
|
||||
status: active
|
||||
last_updated: "2026-05-30T09:54:58.389Z"
|
||||
milestone: v1.3
|
||||
milestone_name: Location Intelligence
|
||||
status: complete
|
||||
last_updated: "2026-05-31T01:40:00.000Z"
|
||||
last_activity: 2026-05-31
|
||||
progress:
|
||||
total_phases: 7
|
||||
completed_phases: 3
|
||||
total_plans: 23
|
||||
completed_plans: 16
|
||||
percent: 43
|
||||
total_phases: 4
|
||||
completed_phases: 4
|
||||
total_plans: 9
|
||||
completed_plans: 9
|
||||
percent: 100
|
||||
---
|
||||
|
||||
# Project State
|
||||
|
||||
## Project Reference
|
||||
|
||||
Isolated planning workspace for the **v1.2 Full MCP Support** milestone (Phases 16-21).
|
||||
Split out of the shared root `C:\dev\wwv\.planning` on 2026-05-29 because v1.1 (marketplace
|
||||
auth gate) and v1.2 (MCP server) were tangled in one ROADMAP/REQUIREMENTS with no shared
|
||||
phases or dependency.
|
||||
See: .planning/PROJECT.md (updated 2026-05-31)
|
||||
|
||||
Primary repo: this worktree (`worldwideview`, branch `feat/mcp-support`).
|
||||
Cross-repo deps declared in ROADMAP.md: Phase 20 -> wwv-data-engine REST; Phase 21 ->
|
||||
wwv-data-engine + `@worldwideview/wwv-plugin-sdk` + marketplace JWT bridge.
|
||||
|
||||
Cross-feature docs (MILESTONES.md, the plugin-pipeline backlogs) stay at the shared root and
|
||||
are NOT duplicated here.
|
||||
**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:** Phase 25 — documentation
|
||||
|
||||
## Current Position
|
||||
|
||||
**Phase 16:** code complete (5f3fe69 UI, 90dfb68 tsc fix). UAT run on :3005 (Playwright) passed steps
|
||||
1-5 EXCEPT: (a) cosmetic - existing section header reads "Your API Keys" not spec's "Service Keys"
|
||||
(fix in progress); (b) ANOMALY - after reload, GET /api/api-keys returned [] (all keys vanished). A
|
||||
debugger agent is investigating whether (b) is a code bug or a shared-dev-DB-across-worktrees artifact,
|
||||
and fixing (a). Phase 16 NOT marked verified until (b) is resolved.
|
||||
Phase: 25 (documentation) - COMPLETE
|
||||
Plan: 1 of 1 (25-01 landed)
|
||||
Status: Phase 25 COMPLETE - DOC-01..04 closed. Enriched all 8 v1.3 MCP tool descriptions, added docs/plugin-filter-guide.md, listed all tools in ConnectAgentHelper, added CHANGELOG.md v1.3.0 entry. tsc clean, 750 Vitest tests GREEN, build OK. Commits 84f8ade, 26d2063, 2eec714, f1405bd. Milestone v1.3 Location Intelligence COMPLETE (4 of 4 phases).
|
||||
Last activity: 2026-05-31
|
||||
Resume file: None
|
||||
|
||||
**Phase 17:** COMPLETE (verified 2026-05-30). Wave 0 (fcb7a5e) + Wave 1 (e0ad832, 0053f1d) + Wave 2
|
||||
(6f77495). Human-verify PASSED 6/6: token only in Authorization header, copy buttons flip, placeholder
|
||||
after dismiss, 401 JSON-RPC body, 200 SSE with x-accel-buffering:no + protocolVersion 2025-06-18.
|
||||
Version 2.26.0.
|
||||
Progress: [##########] 100% (4 of 4 phases complete)
|
||||
|
||||
**Phase 18:** COMPLETE (2026-05-30). Wave 0 + 1 + 2 + 3 all done. 498/498 tests GREEN. Delivered:
|
||||
ioredis singleton, GlobeStateSnapshot, globeStateStore (ZSET sessions), POST /api/globe/state (dual
|
||||
auth per R-2), useSessionId + useGlobeStateSync hooks, GlobeView wiring, registerGlobeResources MCP
|
||||
module (RSRC-02/03/04), route.ts first R-1 edit. Version TBD (bump in final commit).
|
||||
## Key Decisions (carried from v1.2)
|
||||
|
||||
**Phase 20:** COMPLETE (2026-05-30). All waves done. 498/498 tests GREEN. Delivered: types.ts +
|
||||
service.ts transport-neutral service layer, REST routes (search + region), registerDataQueryTools
|
||||
MCP module (TOOL-01/02/03/04), route.ts second R-1 edit. Commit a5b4b62 (combined with Phase 18).
|
||||
Version 2.27.0.
|
||||
- **MCP transport:** Stateless Streamable HTTP at /api/mcp; raw @modelcontextprotocol/sdk; Bearer auth via authenticateApiKey(). No custom server.ts.
|
||||
- **Redis for ephemeral state:** Globe state, command queues, session catalogs all in Redis. PostgreSQL for user-owned persistent data.
|
||||
- **SSE command bridge:** EventSource-based push (GET /api/globe/commands/stream). Reuse for fly_to in v1.3.
|
||||
- **Plugin tools via frontend relay:** No engine endpoint. useMcpCatalogPublisher + useMcpRelayBridge pattern.
|
||||
- **Three editions:** NEXT_PUBLIC_WWV_EDITION (local/cloud/demo). isDemo gate runs before auth on all new endpoints.
|
||||
- **Generic API keys:** wwv_prefix.secret bearer tokens. authenticateApiKey() middleware reused for all new MCP tools.
|
||||
|
||||
**Phase 19:** SPLIT (2026-05-30, user-approved) into 19a + 19b. See phases/19-globe-command-bridge/19-SPLIT.md.
|
||||
## v1.3 Phase Map
|
||||
|
||||
- **19a (Globe Command System Tools, poll-based):** COMPLETE (2026-05-30, commit a3c8f12). Command tools
|
||||
(pan/focus/toggle/timeline) + Redis list queue + GET /api/globe/commands poll route + browser poll hook.
|
||||
NO boot-path change. Covers CTRL-04 + CTRL-05. Version 2.28.0.
|
||||
|
||||
- All 3 waves GREEN. Full suite 573 passed / 0 failed.
|
||||
- code-reviewer + security-reviewer DONE: no Critical/High. Security PASS on hard invariants (userId only
|
||||
from auth, gate ordering rate-limit -> isDemo 403 -> auth, per-user/tenant queue namespacing, no secret in
|
||||
URL, double-validation). Review findings folded in: timeWindow/currentTime validation, atomic enqueue
|
||||
(multi.rpush.expire), UUID sessionId 400 guard, dedicated globeCommandsLimiter (120/60s), in-flight poll
|
||||
guard, focusEntity entityId-only -> console.warn (no 0,0 fly), z.enum timeWindow.
|
||||
|
||||
- Committed: 15 files (excluded pnpm-lock.yaml, .planning, debug PNGs per constraints).
|
||||
- **Phase 21 readiness (IMPORTANT — two conflicting plan generations on disk):**
|
||||
- AUTHORITATIVE: 21-REPLAN.md + 21-DECISIONS.md (May 30 02:16) — PLUG-03 via streamUrl delegation,
|
||||
worldwideview-only, NO engine endpoint, NO marketplace. 4 decisions LOCKED.
|
||||
|
||||
- STALE: 21-RESEARCH.md + 21-01..04-PLAN.md (May 29 22:31-23:28) — route PLUG-03 through a NEW
|
||||
wwv-data-engine REST endpoint + marketplace JWT bridge. DO NOT EXECUTE these wave plans; they predate
|
||||
the re-plan. Archive them and regenerate 21-01..N against 21-REPLAN.md before executing.
|
||||
|
||||
- OPEN DECISION (the one heavy item): InstalledPlugin model is keyed by tenantId (nullable), NOT userId.
|
||||
The MCP auth chain produces userId. Wave 2 ("tools/list from user's active installed plugins") needs a
|
||||
resolved userId -> tenantId -> InstalledPlugin path. Stale research's `findMany({ where: { userId } })`
|
||||
will NOT compile. Decide enumeration strategy (likely tenantId null in local edition = single-tenant)
|
||||
before planning Wave 2.
|
||||
|
||||
- **19b (WebSocket push transport):** DEFERRED out of milestone. server.ts + WS + Docker entrypoint + Nginx
|
||||
+ pub/sub subscriber. Covers CTRL-01/02/03/06. Basis = original 19-01..19-05 plans. Not executed unless
|
||||
user later requests. The risky boot-path change is parked here.
|
||||
|
||||
**Phase 21:** COMPLETE (2026-05-30). All 5 waves done. PR #215 open on feat/mcp-support. Re-planned as v3 frontend-relay (21-REPLAN.md). Delivered: McpToolDeclaration SDK type, mcpTools/mcpCapabilities manifest fields, executeMcpTool hook, per-session Redis catalog, catalog POST route, useMcpCatalogPublisher, composePluginToolsList, mcpRelay (enqueue/wait/post/drain), /api/mcp/invocations GET, /api/mcp/results POST, useMcpRelayBridge, namespaced-tool dispatch in route.ts, README MCP config block. Version 2.29.x committed.
|
||||
|
||||
**Phase 19b:** COMPLETE (2026-05-30, commit 7fd1d7e, version 2.30.0). SSE push transport replacing the 1500ms poll loop. Delivered: GET /api/globe/commands/stream (ReadableStream, 200ms drain, 15s keepalive, 16s max, dual-auth, isDemo 403, globeCommandsStreamLimiter 10/60s, cancel() disconnect cleanup), useGlobeCommandBridge rewritten to EventSource with envelope validation and onerror handler. Poll route kept. 654/654 tests GREEN. tsc + lint clean.
|
||||
|
||||
- **21-03 (Wave 2, catalog + tools/list):** COMPLETE (2026-05-30, commits 6779921 + cbd48e5 + 23b893c). publishSessionCatalog/readSessionCatalog (Redis SET+EX, {userId}:{sessionId} key, 120s TTL), POST /api/mcp/catalog (dual-auth, UUID guard, size cap, isDemo gate), useMcpCatalogPublisher hook (reads pluginManager manifests, POSTs on mount + 30s interval), composePluginToolsList (system tools + de-duplicated namespaced plugin tools + capability copy), registerPluginTools in route.ts (reads per-session catalog, registers stub handlers). CAT-01..06 + LIST-01..05 GREEN. Zod v4 z.record() fix applied.
|
||||
|
||||
- **21-02 (Wave 1, SDK):** COMPLETE (2026-05-30, commit bda235f). McpToolDeclaration (NO execution field), mcpTools? + mcpCapabilities? in PluginManifest, WorldPlugin.executeMcpTool? hook, validateManifest extended with MAN-01..08 rules, getNamespacedTools + validateToolArgs in src/lib/mcp/pluginTools.ts. 32/32 targeted tests GREEN. Pre-existing Wave 0 RED tests for future waves remain red (correct).
|
||||
|
||||
- **21-01 (Wave 0, RED):** COMPLETE (2026-05-30, commit 5930bc7). Six RED test files authored:
|
||||
validateManifest.test.ts (extended + MAN-01..08), pluginTools.test.ts (PT-01..08),
|
||||
mcpSessionCatalog.test.ts (CAT-01..06), pluginToolsList.test.ts (LIST-01..05),
|
||||
mcpRelay.test.ts (RELAY-01 + SEC-01..05), pluginToolDispatch.test.ts (MCP-QA-01..04 + SEC-01/06).
|
||||
tsc: only TS2307 "module not found" (expected). lint: zero errors on new files. vitest: 5 files FAIL
|
||||
"Failed to resolve import" (correct RED), validateManifest.test.ts 7 RED + 9 GREEN.
|
||||
|
||||
**Execution order (per RECONCILIATION R-7):** 17 done -> 18 done -> 20 done -> 19 (PAUSED, awaiting
|
||||
user discussion on WebSocket + custom server.ts) -> 21 (re-plan pause). route.ts serialization:
|
||||
18-04 first, then 20-04 appended. Commit checkpoint: a5b4b62 (Phases 18 + 20 combined).
|
||||
|
||||
## Phase 17 Plan Map (planned 2026-05-29)
|
||||
|
||||
- **17-01 (Wave 0, autonomous):** RED test scaffolds for /api/mcp (401 JSON-RPC, 403 demo gate,
|
||||
stateless per-request construction, X-Accel-Buffering header) + a raw-SDK transport runtime spike
|
||||
that proves WebStandardStreamableHTTPServerTransport + McpServer instantiate/connect outside a
|
||||
custom server (or flags a blocker). Covers MCP-01..04.
|
||||
|
||||
- **17-02 (Wave 1, autonomous + blocking-human SDK-legitimacy checkpoint):** `pnpm add
|
||||
@modelcontextprotocol/sdk@^1.29.0`, `src/lib/mcp/server.ts` createMcpServer() factory (empty
|
||||
capabilities), and the gated stateless `src/app/api/mcp/route.ts` (isDemo-first 403, Bearer 401
|
||||
via Phase 16 authenticateApiKey, fresh server+transport per request, X-Accel-Buffering: no). Turns
|
||||
Wave 0 green. Covers MCP-01..04.
|
||||
|
||||
- **17-03 (Wave 2, autonomous + human-verify checkpoint):** `ConnectAgentHelper.tsx` (per-edition
|
||||
URL + mcpServers JSON with Bearer header for Desktop/Cursor/VS Code + Manual block + agent prompt;
|
||||
Claude Code CLI deferred as "coming soon"), mounted where the Phase 16 TODO placeholder was;
|
||||
`.agents/context/server-management.md` Coolify/Nginx streaming runbook (documented, not automated);
|
||||
semver bump 2.25.0 -> 2.26.0. Covers CONNECT-01/02/03.
|
||||
|
||||
## Key Decisions
|
||||
|
||||
- **17 transport decision (LOCKED, BATCH-DECISIONS-17-21.md + 17-CONTEXT.md):** raw
|
||||
`@modelcontextprotocol/sdk@^1.29.0` (NOT mcp-handler) + the SDK's
|
||||
`WebStandardStreamableHTTPServerTransport` (`@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js`)
|
||||
inside a Next 16 App Router route handler at `src/app/api/mcp/route.ts`. **Confirmed against the
|
||||
published SDK 1.29.0 types**: `handleRequest(req: Request): Promise<Response>` is Web-Standard and
|
||||
documented for Hono/Cloudflare-Workers fetch handlers — identical Request/Response shape to a Next 16
|
||||
route handler. NO custom `server.ts` is needed in Phase 17 (that is a Phase 19 / WebSocket artifact).
|
||||
NO BLOCKER. A Wave 0 spike re-confirms at runtime and escalates only if the transport genuinely
|
||||
cannot run in a route handler.
|
||||
|
||||
- **17 stateless (D-17-04):** fresh McpServer + transport per request (sessionIdGenerator: undefined),
|
||||
never cached at module scope, with a guard-rail comment. No tools/resources registered this phase.
|
||||
|
||||
- **17 auth (D-17-03):** reuse Phase 16 `authenticateApiKey()` unchanged; 401 JSON-RPC body
|
||||
`{ jsonrpc:"2.0", error:{ code:-32600, message:"Unauthorized" }, id:null }`. Demo -> 403, gate FIRST.
|
||||
|
||||
- **17 connect helper (D-17-08/09):** in "API & MCP Access"; mcpServers JSON carries the token in the
|
||||
Authorization HEADER (raw-SDK Streamable HTTP form), never in a URL; Claude Code CLI deferred "coming
|
||||
soon". Nginx/Coolify buffering documented (D-17-07), not automated.
|
||||
|
||||
- **17-03 (Wave 2):** mcpServers JSON shape uses `{ "url": "...", "headers": { "Authorization": "Bearer
|
||||
<token>" } }` -- raw-SDK Streamable HTTP form (D-17-09). Local URL derived from window.location.origin
|
||||
at runtime (not hardcoded :3000). CopyField sub-component pattern established for clipboard interactions.
|
||||
.agents/context/ is gitignored in both worktree and main repo; server-management.md exists on disk as
|
||||
a local operator runbook only (D-17-07 intent: document not automate).
|
||||
|
||||
- **17-02 (Wave 1):** vitest.config.ts clearMocks: true required to fix mock call count isolation
|
||||
between describe blocks (MCP-04 demo-gate tests inherited stale call counts from MCP-03 without this).
|
||||
Optional chaining on server?.connect?.() and transport.handleRequest?.() guards against vi.resetAllMocks()
|
||||
clearing SDK mock implementations in happy-path tests. AuthInfo.token = "" (raw token not re-exposed).
|
||||
createMcpServer() capabilities: { tools: { listChanged: true } } per RECONCILIATION R-1.
|
||||
|
||||
- **17-01 (Wave 0):** @vite-ignore on variable-based import specifier required in transport spike to
|
||||
prevent Vite's import-analysis from crashing at transform time on absent SDK. Runtime try/catch alone
|
||||
is insufficient because Vite resolves import() specifiers statically before test execution.
|
||||
SDK vi.mock factories (no real module) work correctly for route.test.ts stateless-construction tests.
|
||||
|
||||
- **16-01 (Wave 0):** Three RED test files lock api-key contracts (token format, timing oracle T-16-01,
|
||||
max-3, ownership-scoped delete) before any implementation. timing-oracle test tagged `// [slow]`.
|
||||
|
||||
- **16-02 (Wave 1):** UserApiKey Prisma model + apiKeyAuth.ts helper. DUMMY_HASH pre-baked literal
|
||||
eliminates cold-start timing oracle gap; async bcrypt compare always runs on miss (T-16-01). All
|
||||
helper tests GREEN.
|
||||
|
||||
- **16-03 (Wave 2):** isDemo gate runs FIRST (before auth()). deleteMany ownership-scoped delete
|
||||
eliminates TOCTOU (T-16-06). fullToken returned once in POST 201; GET omits hashedSecret (T-16-07).
|
||||
|
||||
- **16-04 (Wave 3):** PersonalApiKeysSection UI shipped in the renamed "Keys & Access" modal; version
|
||||
bumped to 2.25.0; Phase 17 connect-helper placeholder comment left at ~L347.
|
||||
|
||||
- v1.2 QA requirement IDs renamed `QA-01/02/03` -> `MCP-QA-01/02/03` to resolve a v1.1 collision.
|
||||
- One primary worktree for the whole milestone; data-engine / SDK / marketplace are declared cross-repo
|
||||
dependencies, not separate planning roots.
|
||||
|
||||
- **Scope expansion (2026-05-29, user-approved):** keys are generic transport-agnostic API keys (req
|
||||
API-01); one reusable `authenticateApiKey()` middleware; capabilities as a shared service layer
|
||||
wrapped by MCP + future REST (`/api/v1/*`, Phases 20/21). CLI deferred to a future milestone.
|
||||
|
||||
## Milestone Audit (2026-05-30)
|
||||
|
||||
v1.2 audited: status **tech_debt** (no critical blockers). Report: `.planning/v1.2-MILESTONE-AUDIT.md`.
|
||||
Requirements: 31 Complete, 2 Partial (CTRL-02 entityId-only focus, MCP-QA-03 reconnect test),
|
||||
2 Deferred (PLG-01/PLG-02 -- marketplace descoped to v1.3 per 21-REPLAN). Integration: 47/52,
|
||||
all 4 browser hooks mounted, 9/12 E2E flows complete (2 broken = the deferred PLG tools).
|
||||
|
||||
**Tech debt closed (commit dc1e802, version 2.30.1, pushed):** mcpRelay enqueue+postResult made
|
||||
atomic (multi/exec) + redis.ts RedisMultiChain.set(); v1 entity routes got dual-auth + isDemo 403
|
||||
gate + NaN limit guard + global-read intent comment; useGlobeStateSync immediate initial push
|
||||
(ran-once ref) closes the session-registration race; useMcpCatalogPublisher wired to
|
||||
getNamespacedTools (DRY); deleted dead pluginToolsList.ts. Code + security review: no Critical/High;
|
||||
all review warnings folded in. 643/643 tests, tsc clean, lint clean.
|
||||
|
||||
REQUIREMENTS.md traceability table + checkboxes updated to actual status. ROADMAP.md has a
|
||||
"Deferred to v1.3 (Backlog)" section for PLG-01/02 (999.1/999.2).
|
||||
|
||||
**Gap-closure 18-05 (2026-05-30, commit ee16ec0):** POST /api/globe/state isDemo gate added.
|
||||
Returns 403 { error: "Not available in demo edition" } before auth when isDemo is true. Closes
|
||||
GAP-01 from PR #215 pre-merge audit. vi.hoisted() pattern used for mutable editionMock (deviation
|
||||
from plan's simpler const suggestion -- Vitest hoisting requires it). 6/6 tests green, tsc clean.
|
||||
useGlobeStateSync confirmed to handle 403 silently with no code change (fetch catches only thrown
|
||||
exceptions, not HTTP responses). RSRC-01 fully satisfied.
|
||||
|
||||
## Remaining for milestone close
|
||||
|
||||
1. Merge PR #215 (feat/mcp-support -> main) once CI is green.
|
||||
2. After merge: run milestone lifecycle (`/gsd:autonomous` no --only, or
|
||||
`/gsd:complete-milestone v1.2` then `/gsd:cleanup`) to archive + tag + clean up the worktree.
|
||||
| Phase | Goal | Key requirements |
|
||||
|-------|------|-----------------|
|
||||
| 22 | Geocoding + Favorites | GEO-01..03, FAV-01..03, SAFE-01..02 |
|
||||
| 23 | Entity Filtering | FILT-01..04 |
|
||||
| 24 | Route Wiring + Version Bump | INTG-01, INTG-02 |
|
||||
| 25 | Documentation | DOC-01..04 |
|
||||
|
||||
## Blockers
|
||||
|
||||
None. (Phase 17 transport-in-route-handler question resolved: confirmed viable, no custom server.ts.)
|
||||
None.
|
||||
|
||||
## Accumulated Context
|
||||
|
||||
- v1.2 archived at .planning/milestones/v1.2-* and tagged v1.2 in git.
|
||||
- PR #215 (feat/mcp-support) open on GitHub, awaiting merge.
|
||||
- Phase numbering continues from v1.2's last phase (21). v1.3 starts at Phase 22.
|
||||
- Phase 23 (Entity Filtering) must ship atomically: GlobeCommand type extensions + catalog changes + all 4 FILT tools are coupled. Do not split.
|
||||
- Phase 24 is purely mechanical wiring (no new logic); can proceed immediately after 22 and 23 complete.
|
||||
- Nominatim integration: server-side rate limiter (1 req/sec Redis sliding window) + 24h result cache are mandatory before any geocoding tool goes live (GEO-03).
|
||||
- Favorites use prisma.favorite directly -- never proxy through /api/user/favorites (cookie auth incompatible with API key sessions, SAFE-02).
|
||||
@@ -0,0 +1,48 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,153 @@
|
||||
# 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).
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "2.31.1",
|
||||
"version": "2.46.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
|
||||
@@ -315,6 +315,7 @@ 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 };
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth as getSession } from "@/lib/auth";
|
||||
import { authenticateApiKey } from "@/lib/apiKeyAuth";
|
||||
import { publishSessionCatalog, readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { publishSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import type { SessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { globeCommandsLimiter, getClientIp } from "@/lib/rateLimiters";
|
||||
@@ -142,9 +142,29 @@ 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)
|
||||
@@ -152,6 +172,3 @@ 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 };
|
||||
@@ -0,0 +1,121 @@
|
||||
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 mockServer = {
|
||||
registerTool: vi.fn((name: string, _schema: unknown, handler: (args: unknown) => unknown) => {
|
||||
handlers[name] = handler;
|
||||
}),
|
||||
};
|
||||
|
||||
const ctx = { userId: "u1" };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.keys(handlers).forEach((k) => delete handlers[k]);
|
||||
registerFavoritesTools(mockServer as never, ctx);
|
||||
});
|
||||
|
||||
describe("save_favorite tool handler", () => {
|
||||
it("calls prisma.favorite.upsert with userId from context, not from args", async () => {
|
||||
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
|
||||
|
||||
await handlers["save_favorite"]({
|
||||
entityId: "ship:123",
|
||||
pluginId: "maritime",
|
||||
userId: "attacker",
|
||||
});
|
||||
|
||||
expect(mockPrisma.favorite.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({ userId: "u1" }),
|
||||
create: expect.objectContaining({ userId: "u1" }),
|
||||
}),
|
||||
);
|
||||
expect(mockPrisma.favorite.upsert).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ create: expect.objectContaining({ userId: "attacker" }) }),
|
||||
);
|
||||
});
|
||||
|
||||
it("sets pluginName to pluginId as fallback when name is omitted", async () => {
|
||||
mockPrisma.favorite.upsert.mockResolvedValue({} as never);
|
||||
|
||||
await handlers["save_favorite"]({ entityId: "ship:456", pluginId: "maritime" });
|
||||
|
||||
expect(mockPrisma.favorite.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({ pluginName: "maritime" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("list_favorites tool handler", () => {
|
||||
it("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({ 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(null);
|
||||
|
||||
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("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",
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* MCP Favorites Tool registrar (Phase 22 Wave 2 -- 22-03).
|
||||
*
|
||||
* Registers three 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)
|
||||
*
|
||||
* Security (SAFE-02): userId comes ONLY from ctx (the verified auth result). It
|
||||
* is never read from tool arguments, and all Prisma queries are row-scoped by
|
||||
* userId. Favorites are persisted directly via prisma.favorite -- never through
|
||||
* the /api/user/favorites HTTP route, which uses NextAuth cookie auth and would
|
||||
* silently 401 on API-key-authenticated MCP requests.
|
||||
*
|
||||
* Liveness (D-04 / D-05): list_favorites reports status "live" only when the
|
||||
* user has an active globe session AND getEntityDetails resolves the entity.
|
||||
* With no active session, ALL favorites are reported "stale" (no "unknown").
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { readActiveSessions } from "@/lib/globeStateStore";
|
||||
import { getEntityDetails } from "@/lib/data-query/service";
|
||||
import type { Prisma } from "@/generated/prisma";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type McpTextResult = { content: [{ type: "text"; text: string }] };
|
||||
|
||||
function textResult(text: string): McpTextResult {
|
||||
return { content: [{ type: "text", text }] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the unique-where selector for the (userId, entityId) compound key.
|
||||
*
|
||||
* Includes the Prisma-canonical `userId_entityId` nested form (required at
|
||||
* runtime) alongside flat `userId`/`entityId` keys, then casts to the generated
|
||||
* input type. The flat keys are inert for Prisma but let callers and tests
|
||||
* inspect the scope without unwrapping the compound key.
|
||||
*/
|
||||
function favoriteWhere(userId: string, entityId: string): Prisma.FavoriteWhereUniqueInput {
|
||||
return {
|
||||
userId,
|
||||
entityId,
|
||||
userId_entityId: { userId, entityId },
|
||||
} as Prisma.FavoriteWhereUniqueInput;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerFavoritesTools(
|
||||
server: McpServer,
|
||||
ctx: { userId: string },
|
||||
): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
// TOOL: save_favorite (FAV-01)
|
||||
server.registerTool(
|
||||
"save_favorite",
|
||||
{
|
||||
description:
|
||||
"Bookmark an entity so the user can return to it later (upsert by entityId). " +
|
||||
"Inputs: entityId (string, required) -- the unique entity id; pluginId (string, required) -- the plugin that owns the entity; " +
|
||||
"name (string, optional) -- a human-readable label, defaults to entityId. " +
|
||||
"Output: text 'Saved favorite: <label>'. " +
|
||||
"Example: save_favorite({ entityId: 'AFR123', pluginId: 'flights', name: 'Air France 123' }).",
|
||||
inputSchema: {
|
||||
entityId: z.string().min(1).describe("Unique entity identifier"),
|
||||
pluginId: z.string().min(1).describe("Plugin that owns this entity"),
|
||||
name: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Human-readable label for the bookmark (defaults to entityId)"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const label = args.name ?? args.entityId;
|
||||
await prisma.favorite.upsert({
|
||||
where: favoriteWhere(userId, args.entityId),
|
||||
update: {
|
||||
pluginId: args.pluginId,
|
||||
label,
|
||||
lastSeen: new Date(),
|
||||
},
|
||||
create: {
|
||||
userId,
|
||||
entityId: args.entityId,
|
||||
pluginId: args.pluginId,
|
||||
label,
|
||||
pluginName: args.pluginId,
|
||||
lastSeen: new Date(),
|
||||
},
|
||||
});
|
||||
return textResult(`Saved favorite: ${label}`);
|
||||
} catch (err) {
|
||||
console.error("[favoritesTools] save_favorite failed:", err);
|
||||
return textResult("save_favorite failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL: list_favorites (FAV-02)
|
||||
server.registerTool(
|
||||
"list_favorites",
|
||||
{
|
||||
description:
|
||||
"List the authenticated user's bookmarked entities, most recently seen first. " +
|
||||
"Inputs: none. " +
|
||||
"Output: a JSON array of favorites, each with { id, userId, entityId, pluginId, label, pluginName, lastSeen, status }, " +
|
||||
"where status is 'live' if the entity currently resolves on an active globe session, otherwise 'stale'. " +
|
||||
"With no active session ALL entries are reported 'stale'. Returns [] when there are no favorites. " +
|
||||
"Example: list_favorites({}) -> [{ entityId: 'AFR123', pluginId: 'flights', label: 'Air France 123', 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 !== 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: remove_favorite (FAV-03)
|
||||
server.registerTool(
|
||||
"remove_favorite",
|
||||
{
|
||||
description:
|
||||
"Remove a bookmarked entity from the authenticated user's favorites. " +
|
||||
"Inputs: entityId (string, required) -- the entity id to remove. " +
|
||||
"Output: text 'Removed favorite: <entityId>'. " +
|
||||
"Example: remove_favorite({ entityId: 'AFR123' }).",
|
||||
inputSchema: {
|
||||
entityId: z.string().min(1).describe("Entity identifier to remove from favorites"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
await prisma.favorite.delete({
|
||||
where: favoriteWhere(userId, args.entityId),
|
||||
});
|
||||
return textResult(`Removed favorite: ${args.entityId}`);
|
||||
} catch (err) {
|
||||
console.error("[favoritesTools] remove_favorite failed:", err);
|
||||
return textResult("remove_favorite failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
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 mockServer = {
|
||||
registerTool: vi.fn((name: string, _schema: unknown, handler: (args: unknown) => unknown) => {
|
||||
handlers[name] = handler;
|
||||
}),
|
||||
};
|
||||
|
||||
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]);
|
||||
mockResolveActiveSessionId.mockResolvedValue("sess-abc");
|
||||
registerFilterTools(mockServer as never, ctx);
|
||||
});
|
||||
|
||||
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 the plugin's filterDefinitions array as JSON", 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" });
|
||||
|
||||
expect(JSON.parse(textOf(result))).toEqual(defs);
|
||||
});
|
||||
|
||||
it("returns [] when there is no active session", async () => {
|
||||
mockResolveActiveSessionId.mockResolvedValue(null);
|
||||
|
||||
const result = await handlers["get_plugin_filters"]({ pluginId: "flights" });
|
||||
|
||||
expect(JSON.parse(textOf(result))).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns [] when catalog has no entry for the plugin", async () => {
|
||||
mockReadSessionCatalog.mockResolvedValue({
|
||||
tools: [],
|
||||
capabilities: [],
|
||||
filterDefinitions: {},
|
||||
} as never);
|
||||
|
||||
const result = await handlers["get_plugin_filters"]({ pluginId: "flights" });
|
||||
|
||||
expect(JSON.parse(textOf(result))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* MCP Filter Tool registrar (Phase 23 Wave 2 -- 23-02).
|
||||
*
|
||||
* Registers three MCP tools that let an AI agent filter the live globe:
|
||||
*
|
||||
* set_filter -- push filter values to a plugin layer (FILT-01)
|
||||
* clear_filter -- clear one plugin's filters, or all filters (FILT-02)
|
||||
* get_plugin_filters -- read a plugin's declared filterable fields (FILT-03)
|
||||
*
|
||||
* set_filter / clear_filter enqueue a GlobeCommand via enqueueGlobeCommand; the
|
||||
* browser drains the queue over the SSE bridge and applies them to filterSlice.
|
||||
* get_plugin_filters reads the browser-published session catalog (D-05).
|
||||
*
|
||||
* Security: userId comes ONLY from ctx (the verified auth result). It is never
|
||||
* read from tool arguments. sessionId may come from args (scopes the tab) or is
|
||||
* resolved from the user's active ZSET entry.
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
|
||||
import { filterValueSchema } from "@/lib/mcp/filterSchemas";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type McpTextResult = { content: [{ type: "text"; text: string }] };
|
||||
|
||||
function textResult(text: string): McpTextResult {
|
||||
return { content: [{ type: "text", text }] };
|
||||
}
|
||||
|
||||
const NO_SESSION_RESULT = textResult("no active globe session to control");
|
||||
|
||||
/**
|
||||
* Resolves the session to use: explicit arg takes precedence, falling back to
|
||||
* the most-recently-active session for this user. Returns null if none is live.
|
||||
*/
|
||||
async function resolveSession(
|
||||
userId: string,
|
||||
argSessionId: string | undefined,
|
||||
): Promise<string | null> {
|
||||
if (argSessionId !== undefined && argSessionId !== "") {
|
||||
return argSessionId;
|
||||
}
|
||||
return resolveActiveSessionId(userId);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerFilterTools(
|
||||
server: McpServer,
|
||||
ctx: { userId: string },
|
||||
): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
// TOOL: set_filter (FILT-01)
|
||||
server.registerTool(
|
||||
"set_filter",
|
||||
{
|
||||
description:
|
||||
"Apply one or more filters to a plugin's layer on the live globe (no page reload). " +
|
||||
"Inputs: pluginId (string, required) -- the plugin whose layer to filter, e.g. 'flights'; " +
|
||||
"filters (object, required) -- a map of filterId -> filter value, where each value is one of " +
|
||||
"{ type: 'text', value: string } | { type: 'select', values: string[] } | { type: 'range', min: number, max: number } | { type: 'boolean', value: boolean }; " +
|
||||
"sessionId (string, optional) -- target a specific tab; omit for the most-recently-active tab. " +
|
||||
"Discover valid filter ids and value types via get_plugin_filters. " +
|
||||
"Output: text 'set_filter command enqueued for <pluginId> (N filter(s))', or 'no active globe session to control'. " +
|
||||
"Example: set_filter({ pluginId: 'flights', filters: { status: { type: 'select', values: ['airborne'] } } }).",
|
||||
inputSchema: {
|
||||
pluginId: z.string().min(1).describe("Plugin whose layer to filter, e.g. 'flights'"),
|
||||
filters: z
|
||||
.record(z.string(), filterValueSchema)
|
||||
.describe("Map of filterId -> filter value. Discover valid filter ids via get_plugin_filters."),
|
||||
sessionId: z.string().optional().describe("Target globe session id. Omit to target most-recently-active tab."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "setFilter",
|
||||
pluginId: args.pluginId,
|
||||
filters: args.filters,
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
return textResult(
|
||||
`set_filter command enqueued for '${args.pluginId}' (${Object.keys(args.filters).length} filter(s))`,
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[filterTools] set_filter failed:", err);
|
||||
return textResult("set_filter command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL: clear_filter (FILT-02)
|
||||
server.registerTool(
|
||||
"clear_filter",
|
||||
{
|
||||
description:
|
||||
"Clear active filters on the live globe in one command. " +
|
||||
"Inputs: pluginId (string, optional) -- clear just that plugin's filters; omit to clear ALL filters across every plugin; " +
|
||||
"sessionId (string, optional) -- target a specific tab; omit for the most-recently-active tab. " +
|
||||
"Output: text 'clear_filter enqueued for <pluginId>' or 'clear_filter enqueued for ALL plugins', or 'no active globe session to control'. " +
|
||||
"Example: clear_filter({ pluginId: 'flights' }) or clear_filter({}).",
|
||||
inputSchema: {
|
||||
pluginId: z.string().optional().describe("Plugin whose filters to clear. Omit to clear ALL filters on the globe."),
|
||||
sessionId: z.string().optional().describe("Target globe session id. Omit to target most-recently-active tab."),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveSession(userId, args.sessionId);
|
||||
if (sessionId === null) return NO_SESSION_RESULT;
|
||||
|
||||
const cmd: GlobeCommand = {
|
||||
type: "clearFilter",
|
||||
...(args.pluginId !== undefined && { pluginId: args.pluginId }),
|
||||
};
|
||||
await enqueueGlobeCommand(userId, sessionId, cmd);
|
||||
return textResult(
|
||||
args.pluginId
|
||||
? `clear_filter enqueued for '${args.pluginId}'`
|
||||
: "clear_filter enqueued for ALL plugins",
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[filterTools] clear_filter failed:", err);
|
||||
return textResult("clear_filter command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TOOL: get_plugin_filters (FILT-03)
|
||||
server.registerTool(
|
||||
"get_plugin_filters",
|
||||
{
|
||||
description:
|
||||
"List the filterable fields a plugin has declared (via its getFilterDefinitions), so you can build a valid set_filter call. " +
|
||||
"Inputs: pluginId (string, required) -- the plugin to inspect. " +
|
||||
"Output: a JSON array of FilterDefinition, each { id, label, type: 'text'|'select'|'range'|'boolean', propertyKey, options?: {value,label}[], range?: {min,max,step} }. " +
|
||||
"Returns [] when the plugin declares no filters or no globe session is active. " +
|
||||
"Example: get_plugin_filters({ pluginId: 'flights' }) -> [{ id: 'status', label: 'Status', type: 'select', propertyKey: 'flightStatus', options: [...] }].",
|
||||
inputSchema: {
|
||||
pluginId: z.string().min(1).describe("Plugin to inspect for declared filterable fields"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const sessionId = await resolveActiveSessionId(userId);
|
||||
if (!sessionId) return textResult("[]");
|
||||
|
||||
const catalog = await readSessionCatalog(userId, sessionId);
|
||||
const defs = catalog?.filterDefinitions?.[args.pluginId] ?? [];
|
||||
return textResult(JSON.stringify(defs));
|
||||
} catch (err) {
|
||||
console.error("[filterTools] get_plugin_filters failed:", err);
|
||||
return textResult("[]");
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/nominatim");
|
||||
vi.mock("@/lib/geocodingRateLimit");
|
||||
vi.mock("@/lib/globeCommandQueue");
|
||||
|
||||
import { registerGeocodingTools } from "./geocodingTools";
|
||||
import { fetchGeocode } from "@/lib/nominatim";
|
||||
import { checkRateLimit } from "@/lib/geocodingRateLimit";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
|
||||
const mockFetchGeocode = vi.mocked(fetchGeocode);
|
||||
const mockCheckRateLimit = vi.mocked(checkRateLimit);
|
||||
const mockEnqueueGlobeCommand = vi.mocked(enqueueGlobeCommand);
|
||||
const mockResolveActiveSessionId = vi.mocked(resolveActiveSessionId);
|
||||
|
||||
const handlers: Record<string, (args: unknown) => unknown> = {};
|
||||
const mockServer = {
|
||||
registerTool: vi.fn((name: string, _schema: unknown, handler: (args: unknown) => unknown) => {
|
||||
handlers[name] = handler;
|
||||
}),
|
||||
};
|
||||
|
||||
const ctx = { userId: "u1" };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.keys(handlers).forEach((k) => delete handlers[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("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] }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* MCP Geocoding Tool registrar (Phase 22 Wave 2 -- 22-02).
|
||||
*
|
||||
* Registers two MCP tools:
|
||||
* geocode_location -- resolve a place name/address to coordinates via Nominatim
|
||||
* (GEO-01), with a per-user rate limit + 24h Redis cache (GEO-03)
|
||||
* fly_to -- enqueue a flyTo GlobeCommand to move the browser camera (GEO-02)
|
||||
*
|
||||
* Security: userId comes ONLY from ctx (verified auth result), never from tool
|
||||
* arguments. The Nominatim URL is hardcoded; the user query is injected via
|
||||
* URLSearchParams inside fetchGeocode (no string concatenation).
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
|
||||
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
|
||||
import { fetchGeocode } from "@/lib/nominatim";
|
||||
import type { RawNominatimItem, NominatimResult } from "@/lib/nominatim";
|
||||
import { checkRateLimit } from "@/lib/geocodingRateLimit";
|
||||
import { redis } from "@/lib/redis";
|
||||
import { latSchema, lonSchema } from "@/lib/mcp/coordinateSchemas";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type McpTextResult = { content: [{ type: "text"; text: string }] };
|
||||
|
||||
function textResult(text: string): McpTextResult {
|
||||
return { content: [{ type: "text", text }] };
|
||||
}
|
||||
|
||||
const NO_SESSION_RESULT = textResult("no active globe session to control");
|
||||
|
||||
/**
|
||||
* Normalize a raw Nominatim item to the public NominatimResult shape (D-06).
|
||||
* Kept local (not imported) so that test mocks of "@/lib/nominatim" -- which
|
||||
* only stub fetchGeocode -- do not stub out the normalization step.
|
||||
* Nominatim boundingbox is ["south","north","west","east"]; remap to
|
||||
* [west, south, east, north] numbers.
|
||||
*/
|
||||
function normalizeResult(r: RawNominatimItem): NominatimResult {
|
||||
const bb = r.boundingbox ?? ["0", "0", "0", "0"];
|
||||
return {
|
||||
lat: parseFloat(r.lat ?? "0"),
|
||||
lng: parseFloat(r.lon ?? "0"),
|
||||
name: r.name ?? "",
|
||||
name_en: r.namedetails?.["name:en"] ?? r.name ?? "",
|
||||
type: r.type ?? "",
|
||||
addresstype: r.addresstype ?? "",
|
||||
country: r.address?.country ?? "",
|
||||
display_name: r.display_name ?? "",
|
||||
bbox: [parseFloat(bb[2]), parseFloat(bb[0]), parseFloat(bb[3]), parseFloat(bb[1])],
|
||||
importance: r.importance ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** Best-effort cache read: a Redis outage degrades to a miss, never an error. */
|
||||
async function cacheGet(key: string): Promise<string | null> {
|
||||
try {
|
||||
return await redis.get(key);
|
||||
} catch (err) {
|
||||
console.warn("[geocodingTools] cache read failed (degrading to miss):", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Best-effort cache write: a Redis outage is logged and ignored. */
|
||||
async function cacheSet(key: string, value: string, ttlSeconds: number): Promise<void> {
|
||||
try {
|
||||
await redis.set(key, value, "EX", ttlSeconds);
|
||||
} catch (err) {
|
||||
console.warn("[geocodingTools] cache write failed (ignored):", err);
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_LIMIT = 5;
|
||||
const MAX_LIMIT = 20;
|
||||
const DEFAULT_ALTITUDE_M = 15_000;
|
||||
const CACHE_TTL_SECONDS = 86_400; // 24h
|
||||
|
||||
/**
|
||||
* Resolves the session to use: explicit arg takes precedence, falling back to
|
||||
* the most-recently-active session for this user. Returns null if none is live.
|
||||
*/
|
||||
async function resolveSession(
|
||||
userId: string,
|
||||
argSessionId: string | undefined,
|
||||
): Promise<string | null> {
|
||||
if (argSessionId !== undefined && argSessionId !== "") {
|
||||
return argSessionId;
|
||||
}
|
||||
return resolveActiveSessionId(userId);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public registrar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function registerGeocodingTools(
|
||||
server: McpServer,
|
||||
ctx: { userId: string },
|
||||
): void {
|
||||
const { userId } = ctx;
|
||||
|
||||
// GEO-01 + GEO-03: geocode_location
|
||||
server.registerTool(
|
||||
"geocode_location",
|
||||
{
|
||||
description:
|
||||
"Geocode a place name or address to coordinates and a bounding box via OpenStreetMap Nominatim. " +
|
||||
"Inputs: query (string, required) -- the place name or address; limit (integer 1-20, optional, default 5) -- max results. " +
|
||||
"Output: a JSON array of results sorted by importance, each with { lat, lng, name, name_en, type, addresstype, country, display_name, bbox: [west, south, east, north], importance }. " +
|
||||
"Returns the literal text 'no results found' when nothing matches. " +
|
||||
"Example: geocode_location({ query: 'Paris', limit: 3 }) -> [{ lat: 48.85, lng: 2.35, name: 'Paris', bbox: [...], ... }].",
|
||||
inputSchema: {
|
||||
query: z.string().min(1).describe("Location name or address to geocode"),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(MAX_LIMIT)
|
||||
.optional()
|
||||
.describe("Max results to return (default 5, max 20)"),
|
||||
},
|
||||
},
|
||||
async (args) => {
|
||||
try {
|
||||
const limit = Math.min(args.limit ?? DEFAULT_LIMIT, MAX_LIMIT);
|
||||
const cacheKey = `geocode:${args.query.toLowerCase().trim()}:${limit}`;
|
||||
|
||||
const cached = await cacheGet(cacheKey);
|
||||
if (cached) return textResult(cached);
|
||||
|
||||
const rateLimitResult = await checkRateLimit(userId);
|
||||
if (rateLimitResult) return textResult(JSON.stringify(rateLimitResult));
|
||||
|
||||
const raw = await fetchGeocode({ query: args.query, limit });
|
||||
if (raw.length === 0) return textResult("no results found");
|
||||
|
||||
const results = raw.map(normalizeResult);
|
||||
const json = JSON.stringify(results);
|
||||
await cacheSet(cacheKey, json, CACHE_TTL_SECONDS);
|
||||
return textResult(json);
|
||||
} catch (err) {
|
||||
console.error("[geocodingTools] geocode_location failed:", err);
|
||||
return textResult("geocode_location command failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// GEO-02: fly_to
|
||||
server.registerTool(
|
||||
"fly_to",
|
||||
{
|
||||
description:
|
||||
"Fly the live globe camera to a coordinate, optionally fitting a bounding box in view. " +
|
||||
"Inputs: lat (number -90..90, required), lng (number -180..180, required), altitude (positive number metres, optional, default 15000), " +
|
||||
"bbox ([west, south, east, north] tuple, optional -- fit this box in view), sessionId (string, optional -- target a specific browser tab; omit for the most-recently-active tab). " +
|
||||
"Output: text 'fly_to command enqueued (...)' on success, or 'no active globe session to control' when no tab is live. " +
|
||||
"The camera moves over the SSE bridge with no page reload. " +
|
||||
"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");
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -36,6 +36,9 @@ 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";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// JSON-RPC 2.0 error response helpers
|
||||
@@ -167,9 +170,14 @@ 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);
|
||||
registerGlobeCommandTools(server, { userId: authResult.userId });
|
||||
registerGeocodingTools(server, { userId: authResult.userId });
|
||||
registerFavoritesTools(server, { userId: authResult.userId });
|
||||
registerFilterTools(server, { userId: authResult.userId });
|
||||
|
||||
// Phase 21: dynamic plugin tools — read the per-session catalog and
|
||||
// register each plugin tool so tools/list includes them.
|
||||
|
||||
@@ -165,20 +165,39 @@ function CopyField({ value, label, multiline = false }: CopyFieldProps) {
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Agent-capabilities prompt (CONNECT-03)
|
||||
// Tool-agnostic: Phase 17 ships no tools; tools arrive in Phase 18+.
|
||||
// Lists the v1.3 Location Intelligence tools an agent can call. Keep in sync
|
||||
// with the registrars in src/app/api/mcp/*Tools.ts. Plugin filter authoring is
|
||||
// documented in docs/plugin-filter-guide.md.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const AGENT_PROMPT = `You have access to the WorldWideView (WWV) geospatial intelligence engine via MCP.
|
||||
WWV visualizes real-time global data on an interactive 3D CesiumJS globe, including aviation,
|
||||
incidents, weather, and custom data plugins.
|
||||
|
||||
This MCP connection is 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.
|
||||
This MCP connection is live and authenticated. You can call these tools:
|
||||
|
||||
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.`;
|
||||
Data query:
|
||||
- search_entities: search entities by name across active plugins; supports optional inline filters.
|
||||
- get_entities_in_region: find entities inside a lat/lng bounding box.
|
||||
- get_entity_details: get full details for one entity by pluginId + entityId.
|
||||
- get_plugin_data: get the current snapshot of all entities for a plugin.
|
||||
|
||||
Location (geocoding + camera):
|
||||
- geocode_location: resolve a place name or address to coordinates and a bounding box.
|
||||
- fly_to: fly the live globe camera to a coordinate or bounding box.
|
||||
|
||||
Favorites:
|
||||
- save_favorite: bookmark an entity so the user can return to it later.
|
||||
- list_favorites: list the user's bookmarks, each with a live/stale status.
|
||||
- remove_favorite: delete a bookmarked entity.
|
||||
|
||||
Live filtering:
|
||||
- get_plugin_filters: list the filterable fields a plugin declares.
|
||||
- set_filter: apply filters to a plugin's layer on the live globe.
|
||||
- clear_filter: clear one plugin's filters, or all filters.
|
||||
|
||||
When the user asks about global data, geospatial queries, or globe visualisation, use these tools
|
||||
to find places, move the camera, search and filter live entities, and manage their bookmarks.`;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main component
|
||||
@@ -250,6 +269,9 @@ 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>
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
FilterDefinition,
|
||||
FilterValue,
|
||||
} from "@/core/plugins/PluginTypes";
|
||||
import { matchFilterValue } from "./matchFilterValue";
|
||||
|
||||
/**
|
||||
* Apply active filters to a list of entities.
|
||||
@@ -27,35 +28,10 @@ export function applyFilters(
|
||||
|
||||
const propValue = entity.properties[def.propertyKey];
|
||||
|
||||
if (!matchesFilter(propValue, filterVal)) {
|
||||
if (!matchFilterValue(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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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
|
||||
Cartesian3, EasingFunction, Ellipsoid, Math as CesiumMath, Transforms, Matrix4, Rectangle
|
||||
} from "cesium";
|
||||
import { dataBus } from "@/core/data/DataBus";
|
||||
import { showSearchPin } from "./searchPinAnimation";
|
||||
@@ -140,9 +140,21 @@ 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]);
|
||||
}
|
||||
@@ -17,6 +17,19 @@ 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", {
|
||||
@@ -61,6 +74,24 @@ 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,6 +24,7 @@ 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;
|
||||
@@ -36,13 +37,20 @@ interface CatalogPayload {
|
||||
sessionId?: string;
|
||||
tools: CatalogTool[];
|
||||
capabilities: string[];
|
||||
filterDefinitions?: Record<string, FilterDefinition[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects mcpTools and mcpCapabilities from all loaded manifests.
|
||||
* Only includes plugins whose manifests declare at least one mcpTool.
|
||||
* 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).
|
||||
*/
|
||||
function collectCatalog(): { tools: CatalogTool[]; capabilities: string[] } {
|
||||
function collectCatalog(): {
|
||||
tools: CatalogTool[];
|
||||
capabilities: string[];
|
||||
filterDefinitions: Record<string, FilterDefinition[]>;
|
||||
} {
|
||||
const allPlugins = pluginManager.getAllPlugins();
|
||||
|
||||
const entries: PluginToolsEntry[] = allPlugins.flatMap((managed) => {
|
||||
@@ -74,7 +82,17 @@ function collectCatalog(): { tools: CatalogTool[]; capabilities: string[] } {
|
||||
};
|
||||
});
|
||||
|
||||
return { tools, capabilities: Array.from(capabilitySet) };
|
||||
// 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 };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -85,14 +103,20 @@ async function publishCatalog(
|
||||
sessionId: string,
|
||||
active: { current: boolean },
|
||||
): Promise<void> {
|
||||
const { tools, capabilities } = collectCatalog();
|
||||
const { tools, capabilities, filterDefinitions } = collectCatalog();
|
||||
|
||||
// No-op when no plugin-declared MCP tools are present
|
||||
if (tools.length === 0) return;
|
||||
// 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;
|
||||
|
||||
if (!active.current) return;
|
||||
|
||||
const payload: CatalogPayload = { sessionId, tools, capabilities };
|
||||
const payload: CatalogPayload = {
|
||||
sessionId,
|
||||
tools,
|
||||
capabilities,
|
||||
...(Object.keys(filterDefinitions).length > 0 && { filterDefinitions }),
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/mcp/catalog", {
|
||||
|
||||
@@ -162,3 +162,105 @@ 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,3 +1,5 @@
|
||||
import type { FilterValue } from "@/core/plugins/PluginTypes";
|
||||
|
||||
// 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];
|
||||
@@ -6,7 +8,10 @@ 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: "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 };
|
||||
|
||||
function isNumber(v: unknown): v is number {
|
||||
return typeof v === "number" && isFinite(v);
|
||||
@@ -58,6 +63,23 @@ 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;
|
||||
@@ -96,6 +118,33 @@ 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 (typeof cmd["pluginId"] !== "string" || 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 isOptionalString(cmd["pluginId"]);
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
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(),
|
||||
delete: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
};
|
||||
@@ -95,6 +95,59 @@ 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 results = await searchEntities("flight", "flights", 20, {
|
||||
status: { type: "select", values: ["airborne"] },
|
||||
});
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[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 results = await searchEntities("flight", "flights", 20);
|
||||
expect(results).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 results = await searchEntities("flight", "flights", 20, {
|
||||
status: { type: "select", values: ["airborne"] },
|
||||
});
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[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 results = await searchEntities("flight", "flights", 2, {
|
||||
status: { type: "select", values: ["airborne"] },
|
||||
});
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results.every((r) => r.id.startsWith("d"))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// QUERY-02 — getEntitiesInRegion
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -5,6 +5,8 @@ import type {
|
||||
DetailResult,
|
||||
PluginDataSnapshot,
|
||||
} from "./types";
|
||||
import { matchFilterValue } from "@/core/filters/matchFilterValue";
|
||||
import type { FilterValue } from "@/core/plugins/PluginTypes";
|
||||
|
||||
function getEngineUrl(): string {
|
||||
return process.env.NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL ?? "http://localhost:5000";
|
||||
@@ -99,12 +101,14 @@ export async function searchEntities(
|
||||
query: string,
|
||||
pluginId?: string,
|
||||
limit: number = 20,
|
||||
filters?: Record<string, FilterValue>,
|
||||
): Promise<SearchResult[]> {
|
||||
const trimmed = query.trim();
|
||||
if (trimmed === "") return [];
|
||||
|
||||
const effectiveLimit = Math.min(Math.max(limit, 1), 100);
|
||||
const lower = trimmed.toLowerCase();
|
||||
const filterEntries = filters ? Object.entries(filters) : null;
|
||||
|
||||
const snapshots = pluginId
|
||||
? await fetchPluginSnapshot(pluginId).then((s) => (s ? [s] : []))
|
||||
@@ -115,9 +119,16 @@ export async function searchEntities(
|
||||
for (const entity of snapshot.entities) {
|
||||
if (results.length >= effectiveLimit) break;
|
||||
const matchTarget = (entity.label ?? entity.id).toLowerCase();
|
||||
if (matchTarget.includes(lower)) {
|
||||
results.push(entityToSearchResult(entity));
|
||||
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;
|
||||
}
|
||||
results.push(entityToSearchResult(entity));
|
||||
}
|
||||
if (results.length >= effectiveLimit) break;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import type { GeoEntity } from "@worldwideview/wwv-plugin-sdk";
|
||||
import type { FilterValue } from "@/core/plugins/PluginTypes";
|
||||
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Per-user sliding-window rate limiter for geocoding (Phase 22 Wave 2 -- 22-02).
|
||||
*
|
||||
* Implements a Redis ZSET sliding window keyed per user. Each call prunes
|
||||
* entries older than WINDOW_MS, records the current request, bounds the key
|
||||
* lifetime, then counts. If the count exceeds MAX_REQUESTS the call is rejected.
|
||||
*
|
||||
* Best-effort (T-22-02-05): on any Redis error we fail OPEN (return undefined)
|
||||
* so a broken rate-limit check never causes a permanent geocoding outage. The
|
||||
* 1 req/sec limit is advisory, not a hard security boundary.
|
||||
*/
|
||||
|
||||
import { redis } from "@/lib/redis";
|
||||
|
||||
const WINDOW_MS = 1_000;
|
||||
const MAX_REQUESTS = 1;
|
||||
const KEY_TTL_SECONDS = 5;
|
||||
const RETRY_AFTER_MS = 1_000;
|
||||
|
||||
export interface RateLimitExceeded {
|
||||
error: "rate_limited";
|
||||
retryAfterMs: number;
|
||||
}
|
||||
|
||||
function rateKey(userId: string): string {
|
||||
return `nominatim:ratelimit:${userId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `undefined` when the request is allowed, or a `rate_limited` result
|
||||
* object when the per-user window limit is exceeded.
|
||||
*/
|
||||
export async function checkRateLimit(userId: string): Promise<RateLimitExceeded | undefined> {
|
||||
const key = rateKey(userId);
|
||||
try {
|
||||
const now = Date.now();
|
||||
await redis.zremrangebyscore(key, "-inf", now - WINDOW_MS);
|
||||
await redis.zadd(key, now, String(now));
|
||||
await redis.expire(key, KEY_TTL_SECONDS);
|
||||
const count = await redis.zcard(key);
|
||||
if (count > MAX_REQUESTS) {
|
||||
return { error: "rate_limited", retryAfterMs: RETRY_AFTER_MS };
|
||||
}
|
||||
return undefined;
|
||||
} catch (err) {
|
||||
console.warn("[geocodingRateLimit] Redis error, failing open:", err);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Shared Zod filter-value schema for MCP tool input validation.
|
||||
*
|
||||
* A strict discriminated union on `type` so structurally invalid filter values
|
||||
* are rejected at the tool boundary (T-23-01-02 tampering mitigation). Reused by
|
||||
* filterTools.ts (set_filter) and search_entities in tools.ts.
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
export const filterValueSchema = z.discriminatedUnion("type", [
|
||||
z.object({ type: z.literal("text"), value: z.string() }),
|
||||
z.object({ type: z.literal("select"), values: z.array(z.string()) }),
|
||||
z.object({ type: z.literal("range"), min: z.number(), max: z.number() }),
|
||||
z.object({ type: z.literal("boolean"), value: z.boolean() }),
|
||||
]);
|
||||
@@ -27,7 +27,7 @@ const SERVER_NAME = "worldwideview" as const;
|
||||
// The MCP server's own protocol-advertised version. Bump this when the
|
||||
// server's self-description or tool surface changes in a meaningful way.
|
||||
// This is NOT package.json -- do not keep them in sync automatically.
|
||||
export const MCP_SERVER_VERSION = "1.2.0" as const;
|
||||
export const MCP_SERVER_VERSION = "1.3.0" as const;
|
||||
|
||||
export const MCP_SERVER_INSTRUCTIONS = `\
|
||||
WorldWideView MCP server. Read and control a live 3D geospatial globe for the authenticated user. Everything is scoped to your API key: you only ever see and control your own data and your own browser sessions.
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
import { z } from "zod";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { latSchema, lonSchema } from "@/lib/mcp/coordinateSchemas";
|
||||
import { filterValueSchema } from "@/lib/mcp/filterSchemas";
|
||||
import {
|
||||
searchEntities,
|
||||
getEntitiesInRegion,
|
||||
@@ -41,11 +42,15 @@ export function registerDataQueryTools(server: McpServer): void {
|
||||
"search_entities",
|
||||
{
|
||||
description:
|
||||
"Search for geospatial entities by name across active plugins. Returns up to 20 results with id, name, latitude, longitude, and pluginId. An empty result (count 0) means no match or no live data, not an error.",
|
||||
"Search for geospatial entities by name across active plugins. Returns up to 20 results with id, name, latitude, longitude, and pluginId. Optionally pass 'filters' keyed by entity property key to return only matching entities (independent of any set_filter state). An empty result (count 0) means no match or no live data, not an error.",
|
||||
inputSchema: {
|
||||
query: z.string().describe("Search query string"),
|
||||
pluginId: z.string().optional().describe("Restrict search to a specific plugin"),
|
||||
limit: z.number().optional().describe("Maximum results to return (max 20)"),
|
||||
filters: z
|
||||
.record(z.string(), filterValueSchema)
|
||||
.optional()
|
||||
.describe("Optional inline filters keyed by entity property key (e.g. { status: { type: 'select', values: ['airborne'] } }). Independent of set_filter state."),
|
||||
},
|
||||
},
|
||||
async (input) => {
|
||||
@@ -54,6 +59,7 @@ export function registerDataQueryTools(server: McpServer): void {
|
||||
input.query,
|
||||
input.pluginId,
|
||||
Math.min(input.limit ?? 20, 20),
|
||||
input.filters,
|
||||
);
|
||||
return {
|
||||
content: [
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Phase 24 (INTG-01 + INTG-02) verification.
|
||||
*
|
||||
* Locks two contracts for the v1.3 MCP surface:
|
||||
* 1. The MCP protocol server advertises version "1.3.0" (INTG-02). This is
|
||||
* the serverInfo.version returned on every initialize handshake. It is the
|
||||
* protocol server version, NOT package.json semver.
|
||||
* 2. All 8 v1.3 tools register and reach tools/list, and search_entities still
|
||||
* exposes its optional `filters` param (INTG-01).
|
||||
*
|
||||
* The registrars run synchronously and only call server.registerTool(name,
|
||||
* schema, handler) at registration time, so a stub server captures the full
|
||||
* tool surface without a live transport. External deps are mocked so import +
|
||||
* registration never touch Nominatim, Redis, or Prisma.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/nominatim");
|
||||
vi.mock("@/lib/geocodingRateLimit");
|
||||
vi.mock("@/lib/globeCommandQueue");
|
||||
vi.mock("@/lib/mcpSessionCatalog");
|
||||
vi.mock("@/lib/prisma");
|
||||
vi.mock("@/lib/globeStateStore");
|
||||
vi.mock("@/lib/data-query/service");
|
||||
|
||||
import { MCP_SERVER_VERSION, createMcpServer } from "./server";
|
||||
import { registerDataQueryTools } from "./tools";
|
||||
import { registerGeocodingTools } from "@/app/api/mcp/geocodingTools";
|
||||
import { registerFavoritesTools } from "@/app/api/mcp/favoritesTools";
|
||||
import { registerFilterTools } from "@/app/api/mcp/filterTools";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// INTG-02: protocol server version
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("MCP server version (INTG-02)", () => {
|
||||
it("advertises protocol server version 1.3.0", () => {
|
||||
expect(MCP_SERVER_VERSION).toBe("1.3.0");
|
||||
});
|
||||
|
||||
it("createMcpServer() does not throw and is a fresh instance per call", () => {
|
||||
const a = createMcpServer();
|
||||
const b = createMcpServer();
|
||||
expect(a).toBeDefined();
|
||||
expect(b).toBeDefined();
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// INTG-01: v1.3 tool surface
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const schemas: Record<string, { inputSchema?: Record<string, unknown> }> = {};
|
||||
const stubServer = {
|
||||
registerTool: vi.fn(
|
||||
(name: string, schema: { inputSchema?: Record<string, unknown> }) => {
|
||||
schemas[name] = schema;
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
const ctx = { userId: "u1" };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.keys(schemas).forEach((k) => delete schemas[k]);
|
||||
registerDataQueryTools(stubServer as never);
|
||||
registerGeocodingTools(stubServer as never, ctx);
|
||||
registerFavoritesTools(stubServer as never, ctx);
|
||||
registerFilterTools(stubServer as never, ctx);
|
||||
});
|
||||
|
||||
describe("v1.3 tool registration (INTG-01)", () => {
|
||||
const v13Tools = [
|
||||
"geocode_location",
|
||||
"fly_to",
|
||||
"save_favorite",
|
||||
"list_favorites",
|
||||
"remove_favorite",
|
||||
"set_filter",
|
||||
"clear_filter",
|
||||
"get_plugin_filters",
|
||||
];
|
||||
|
||||
it.each(v13Tools)("registers the %s tool", (name) => {
|
||||
expect(Object.keys(schemas)).toContain(name);
|
||||
});
|
||||
|
||||
it("registers all 8 v1.3 tools", () => {
|
||||
for (const name of v13Tools) {
|
||||
expect(schemas[name]).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("search_entities exposes the optional filters param in its input schema", () => {
|
||||
expect(schemas["search_entities"]).toBeDefined();
|
||||
expect(schemas["search_entities"].inputSchema).toHaveProperty("filters");
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
|
||||
import { redis } from "@/lib/redis";
|
||||
import type { FilterDefinition } from "@/core/plugins/PluginTypes";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
@@ -43,6 +44,12 @@ export interface CatalogTool {
|
||||
export interface SessionCatalog {
|
||||
tools: CatalogTool[];
|
||||
capabilities: string[];
|
||||
/**
|
||||
* Optional per-plugin filter definitions, keyed by pluginId. Browser-published
|
||||
* only (Phase 23, D-05); the server stays plugin-agnostic. Optional so old
|
||||
* catalogs without it still parse.
|
||||
*/
|
||||
filterDefinitions?: Record<string, FilterDefinition[]>;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Nominatim geocoding HTTP wrapper (Phase 22 Wave 2 -- 22-02).
|
||||
*
|
||||
* Wraps the public OpenStreetMap Nominatim /search endpoint. The query is the
|
||||
* only user-controlled value and is injected exclusively via URLSearchParams
|
||||
* (no string concatenation into the URL) to prevent SSRF / parameter injection.
|
||||
* The base URL and header values are hardcoded constants.
|
||||
*
|
||||
* `fetchGeocode` returns the RAW Nominatim items; callers normalize them via
|
||||
* `normalizeNominatimResult` to the public `NominatimResult` shape (D-06).
|
||||
* Nominatim returns boundingbox as ["south_lat","north_lat","west_lon","east_lon"]
|
||||
* (strings); the normalizer remaps to [west, south, east, north] numbers.
|
||||
*/
|
||||
|
||||
const NOMINATIM_SEARCH_URL = "https://nominatim.openstreetmap.org/search";
|
||||
const USER_AGENT = "WorldWideView-MCP/1.3 ([email protected])";
|
||||
const REQUEST_TIMEOUT_MS = 8_000;
|
||||
|
||||
/** Raw Nominatim /search response item shape. */
|
||||
export interface RawNominatimItem {
|
||||
lat?: string;
|
||||
lon?: string;
|
||||
name?: string;
|
||||
type?: string;
|
||||
addresstype?: string;
|
||||
display_name?: string;
|
||||
boundingbox?: [string, string, string, string];
|
||||
importance?: number;
|
||||
namedetails?: Record<string, string> | null;
|
||||
address?: { country?: string } | null;
|
||||
}
|
||||
|
||||
/** Public, normalized geocode result (D-06). */
|
||||
export interface NominatimResult {
|
||||
lat: number;
|
||||
lng: number;
|
||||
name: string;
|
||||
name_en: string;
|
||||
type: string;
|
||||
addresstype: string;
|
||||
country: string;
|
||||
display_name: string;
|
||||
/** [west, south, east, north] */
|
||||
bbox: [number, number, number, number];
|
||||
importance: number;
|
||||
}
|
||||
|
||||
export interface FetchGeocodeArgs {
|
||||
query: string;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
/** Normalize a raw Nominatim item to the public NominatimResult shape (D-06). */
|
||||
export function normalizeNominatimResult(r: RawNominatimItem): NominatimResult {
|
||||
const bb = r.boundingbox ?? ["0", "0", "0", "0"];
|
||||
return {
|
||||
lat: parseFloat(r.lat ?? "0"),
|
||||
lng: parseFloat(r.lon ?? "0"),
|
||||
name: r.name ?? "",
|
||||
name_en: r.namedetails?.["name:en"] ?? r.name ?? "",
|
||||
type: r.type ?? "",
|
||||
addresstype: r.addresstype ?? "",
|
||||
country: r.address?.country ?? "",
|
||||
display_name: r.display_name ?? "",
|
||||
// Nominatim order [S, N, W, E] -> [W, S, E, N]
|
||||
bbox: [parseFloat(bb[2]), parseFloat(bb[0]), parseFloat(bb[3]), parseFloat(bb[1])],
|
||||
importance: r.importance ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Geocode a free-text query via Nominatim. Returns the RAW response items.
|
||||
*
|
||||
* @throws on network failure / timeout (AbortSignal.timeout) or non-OK status.
|
||||
*/
|
||||
export async function fetchGeocode({ query, limit }: FetchGeocodeArgs): Promise<RawNominatimItem[]> {
|
||||
const url = new URL(NOMINATIM_SEARCH_URL);
|
||||
url.searchParams.set("q", query);
|
||||
url.searchParams.set("format", "json");
|
||||
url.searchParams.set("limit", String(limit));
|
||||
url.searchParams.set("addressdetails", "1");
|
||||
url.searchParams.set("namedetails", "1");
|
||||
|
||||
const res = await fetch(url, {
|
||||
headers: {
|
||||
"User-Agent": USER_AGENT,
|
||||
"Accept-Language": "en",
|
||||
},
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Nominatim returned HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const raw = (await res.json()) as RawNominatimItem[];
|
||||
return Array.isArray(raw) ? raw : [];
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Prisma client re-export.
|
||||
*
|
||||
* The canonical singleton lives in `@/lib/db` (PostgreSQL adapter + tenant
|
||||
* isolation extension). This module re-exports it under the conventional
|
||||
* `@/lib/prisma` path so feature code and tests can depend on a stable import
|
||||
* specifier without reaching into db.ts internals.
|
||||
*/
|
||||
export { prisma } from "@/lib/db";
|
||||
@@ -17,6 +17,8 @@ export interface RedisClient {
|
||||
zadd(key: string, score: number, member: string): Promise<number>;
|
||||
zrange(key: string, start: number | string, stop: number | string, withScores: "WITHSCORES"): Promise<string[]>;
|
||||
zrem(key: string, ...members: string[]): Promise<number>;
|
||||
zremrangebyscore(key: string, min: number | "-inf", max: number | "+inf"): Promise<number>;
|
||||
zcard(key: string): Promise<number>;
|
||||
rpush(key: string, ...values: string[]): Promise<number>;
|
||||
expire(key: string, seconds: number): Promise<number>;
|
||||
multi(): RedisMultiChain;
|
||||
|
||||
Reference in new issue
Block a user