Compare commits

..
Author SHA1 Message Date
Antigravity AI 6bbb34ce65 fix(plugins): bundle wwv-lib-aviation and wwv-lib-incidents per-plugin
Removes both base-class libs from the host pantry (EXTERNAL_GLOBALS and
hostGlobals.ts). The 5 consumer plugins now declare them under dependencies
so Vite inlines them at build time, eliminating ManifestLoadError bare-import
failures permanently.

Also: publicDir:false stops 1.4GB dist pollution, CONFIG_HASH invalidation
ensures rebuilt bundles after externals change, ManifestLoadError now emits
actionable bundling guidance, build logging shows per-plugin progress and
final built/cached/failed stats.
2026-06-02 18:05:33 +12:00
Antigravity AI a4bf7fcc8c Merge remote-tracking branch 'origin/main' into feat/data-source-compliance
# Conflicts:
#	.planning/ROADMAP.md
#	.planning/STATE.md
2026-06-02 14:41:16 +12:00
Silvertakana 4858342ed6 feat(mcp): Full MCP Support v1.2 - API keys, MCP server, globe control, data query, plugin tools (#215)
* test(16-01): add failing RED test scaffold for apiKeyAuth helper

- Imports generateApiKey + authenticateApiKey from ./apiKeyAuth (does not exist -- intentional RED)
- Mocks @/lib/db userApiKey (findUnique/create/findMany/count/deleteMany/update) and @/core/edition
- KEY-01: prefix starts with wwv_, fullToken = prefix.secret, secret != hashedSecret
- KEY-02/API-01: null on missing header, no-dot token, unknown prefix, wrong secret; { userId, keyId } on valid token
- T-16-01 timing oracle: // [slow] test brackets authenticateApiKey with performance.now() asserting elapsed > 100ms

* test(16-01): add failing RED test scaffolds for api-keys route handlers

- route.test.ts imports GET/POST from ./route (does not exist -- intentional RED)
- [id]/route.test.ts imports DELETE from ./route (does not exist -- intentional RED)
- Mocks @/lib/auth, @/lib/db (userApiKey), @/core/edition, @/lib/apiKeyAuth
- KEY-03: GET returns 200+{keys} with session, 401 without; response never contains hashedSecret
- KEY-04: POST returns 422 max_keys_reached at count>=3; returns 201+fullToken when under limit
- KEY-03 DELETE: 200 on owned key (count:1), 404 on foreign (count:0), 401 with no session
- Ownership: asserts deleteMany called with where containing both id and userId

* feat(16-02): add UserApiKey model to schema.prisma

- Add model UserApiKey with uuid PK, userId FK (Cascade), tenantId String?,
  prefix String @unique, hashedSecret, name, createdAt, lastUsedAt DateTime?
- Add @@map("user_api_keys") following project snake_case convention
- Add apiKeys UserApiKey[] relation to User model
- Bump version 2.24.6 -> 2.25.0 (minor: new feature)

* feat(16-02): implement apiKeyAuth.ts - timing-safe API key primitive

- generateApiKey(): prefix "wwv_" + 8 base64url chars, secret = 32-byte
  base64url, hashedSecret = bcrypt(secret, 12), fullToken = prefix.secret
- authenticateApiKey(): parses Bearer header, splits on first ".", findUnique
  by prefix, always runs bcrypt compare (DUMMY_HASH on miss for T-16-01),
  fire-and-forget throttled lastUsedAt update (1/min/key)
- DUMMY_HASH: pre-baked cost-12 literal eliminates cold-start gap (Pitfall 1)
- Uses async hash/compare from bcryptjs (never compareSync - Pitfall 2)
- Exports GeneratedKey + AuthenticatedKey interfaces (API-01)
- All 11 tests GREEN including timing-oracle test (elapsed > 100ms)

* feat(16-03): implement GET + POST /api/api-keys route handlers

- GET lists user's keys selecting only { id, name, prefix, createdAt, lastUsedAt } (hashedSecret never returned)
- POST enforces max-3 limit (422 max_keys_reached), calls generateApiKey(), returns fullToken once in 201 response
- P2002 prefix-collision handled with single retry
- isDemo gate (403) runs before session check on both handlers
- All 6 route.test.ts tests GREEN (KEY-01, KEY-03, KEY-04)

* feat(16-03): implement DELETE /api/api-keys/[id] ownership-scoped revoke

- deleteMany where { id, userId } — atomic BOLA prevention (T-16-06)
- count 0 -> 404 not_found; count 1 -> 200 success: true
- isDemo gate (403) before session check
- All 4 [id]/route.test.ts tests GREEN (KEY-03)
- Full suite 403/403 tests green, no regressions

* docs(16-03): complete api-key CRUD routes plan summary + state update

- 16-03-SUMMARY.md: GET+POST+DELETE route handlers, 403/403 tests green
- STATE.md: current position advanced to plan 4 of 4, wave 2 decisions recorded
- ROADMAP.md: phase 16 progress updated (3/4 summaries)

* feat(16-04): personal API keys section + Keys & Access wiring

- Add PersonalApiKeysSection client component (API & MCP Access)
  consuming GET/POST/DELETE /api/api-keys: list, generate with
  one-time reveal, inline-confirm revoke, max-3 disabled state
- Rename Header settings modal title to 'Keys & Access' and render
  the section below ApiKeysTab behind an !isDemo edition gate
- Harden secret/name inputs against password-manager capture
  (autoComplete=off, data-lpignore, data-form-type=other)
- Phase 17 connect-your-agent helper left as a code-comment placeholder

* fix(test): narrow overloaded NextAuth auth export for vi.mocked typing

The 16-03 api-keys route tests called vi.mocked(auth), which resolved the
NextAuth v5 NextMiddleware overload and rejected the Session/null mock value
(TS2345 x7, breaking tsc/pnpm build while vitest stayed green). Narrow auth to
its no-arg session-getter signature via a typed mockAuth helper so vi.mocked
picks the correct overload. Test-only; no runtime change (10/10 still pass).

* test(17-01): RED scaffold for /api/mcp route + transport spike

- route.test.ts: locks 401 JSON-RPC auth gate (MCP-03), 403 demo gate
  before auth (MCP-04), happy-path gate passage (MCP-01/02), X-Accel-Buffering
  streaming header (MCP-06), per-request stateless construction (MCP-05)
- transport-spike.test.ts: skips cleanly (SDK absent); proves
  WebStandardStreamableHTTPServerTransport + McpServer instantiate/connect
  outside a custom server when SDK is installed (de-risks D-17-02)
- route.ts absent by design -- these are Wave 0 RED baselines

* fix(16): surface auth failures in PersonalApiKeysSection fetch; rename section header to "Service Keys"

- PersonalApiKeysSection: check r.ok before consuming response JSON; a 401
  (e.g. AUTH_URL domain mismatch on local dev) was silently producing
  data.keys === undefined which fell through the ?? [] guard and rendered
  "No API keys yet" instead of the error message. Fixes KEY-03 reload symptom.
- route.test.ts: add assertion that 401 response body must not contain a
  `keys` field, locking in the invariant that callers must check r.ok.
- ApiKeysTab: rename "Your API Keys" section header to "Service Keys" per
  16-UI-SPEC.md Copywriting Contract (line 261).

* feat(17-02): install @modelcontextprotocol/sdk + createMcpServer() factory

- Add @modelcontextprotocol/sdk@^1.29.0 to dependencies (SDK legitimacy
  gate cleared by orchestrator; official Anthropic MCP SDK, MIT license)
- Create src/lib/mcp/server.ts: createMcpServer() returns a fresh McpServer
  per call with capabilities: { tools: { listChanged: true } } per R-1
- Add stateless/never-cache guard-rail comment + Phase 18/20/21 seam docs
- Add vitest.config.ts clearMocks: true to fix mock isolation between
  describe blocks (required for Wave 0 MCP-04 demo-gate tests to pass)
- Transport spike (17-01 Task 3) now PASSES green with SDK installed

* feat(17-02): stateless /api/mcp route handler (Wave 0 RED tests GREEN)

- Create src/app/api/mcp/route.ts: GET/POST/DELETE delegates to
  handleMcpRequest(); exports for Next.js App Router
- Gate ordering: isDemo -> 403 JSON-RPC FIRST (before auth); then
  authenticateApiKey() -> 401 JSON-RPC on failure (MCP-03/04/D-17-05)
- Fresh McpServer + WebStandardStreamableHTTPServerTransport per request
  (sessionIdGenerator: undefined); stateless guard-rail comment (D-17-04)
- AuthInfo injected via closure: { token: "", clientId: userId, scopes: [],
  extra: { userId, keyId } } for Phase 18/20/21 resource scoping (R-1)
- X-Accel-Buffering: no + Cache-Control: no-cache merged on streamed
  response without buffering body (D-17-06, MCP-06, Pitfall 1)
- All 12 Wave 0 route tests GREEN; transport spike GREEN; 416 tests pass

* refactor(16): replace bcrypt with HMAC-SHA256 key hashing

Switch API key secret storage from bcrypt (200-400ms per auth) to
HMAC-SHA256(signingKey, secret) with timingSafeEqual comparison.

- Signing key: API_KEY_HMAC_SECRET env var, falls back to AUTH_SECRET
- Timing-oracle defense preserved: miss path computes dummy HMAC digest
  (same 32-byte length) before timingSafeEqual so both paths are constant-work
- Removes DUMMY_HASH literal, async bcrypt re-hash, and bcryptjs dependency use
- generateApiKey is now synchronous (no bcrypt await)
- M3 fix included: lastUsedAtThrottle TTL-evicts at 2x window to prevent
  unbounded Map growth; note added that it is per-replica
- Tests updated: timing-oracle test asserts behavioral contract not elapsed
  time (HMAC is microsecond-fast); added hex-format and randomness assertions

NOTE: existing bcrypt-hashed keys in the DB will fail authentication after
this change. Acceptable pre-launch; no live keys to migrate.

* feat(16): security hardening - rate limits, TOCTOU fix, header spoof, name length

H1 - Rate limiting:
- Add mcpLimiter (60 req/min/IP) at Gate 0 in /api/mcp, runs before edition
  check and auth so scanners never reach the DB layer
- Add apiKeyManagementLimiter (10 req/min/IP) on GET/POST/DELETE api-keys handlers
- Both limiters exported from rateLimiters.ts with getClientIp re-export
- TODO comment: move to @upstash/ratelimit for multi-replica deployments
- Tests: route.test.ts mocks the limiter module; new MCP 429 tests would live
  in mcp/route.test.ts (existing suite passes; limiter tested in rateLimit.test.ts)

H2 - Tenant-header spoof prevention:
- proxy.ts: delete x-tenant-subdomain before NextResponse.next() on /api/*,
  then re-inject only the server-resolved value so a forged header cannot
  drive the Prisma tenant extension

M1 - TOCTOU on max-3:
- Wrap count + create in prisma.$transaction(..., { isolationLevel: "Serializable" })
  so concurrent POSTs cannot both read count < 3 and both succeed
- Route test updated to mock $transaction inline execution

M2 - Name length:
- Reject name > 64 chars server-side with 422 name_too_long before the transaction
- Tests added for > 64 (reject) and exactly 64 (accept)

L2 - Log flooding:
- Downgrade console.error to console.warn on /api/mcp auth failure

* feat(17-03): connect-agent helper UI + nginx runbook + version 2.26.0

- Add ConnectAgentHelper component: per-edition /api/mcp URL, mcpServers
  JSON block (Bearer in Authorization header, never in URL), Manual block,
  agent-capabilities prompt, deferred CLI "coming soon" note
- Mount ConnectAgentHelper in PersonalApiKeysSection replacing TODO placeholder
- Create .agents/context/server-management.md: Coolify/Nginx streaming
  runbook (X-Accel-Buffering: no, proxy_read_timeout 120s, Coolify UI steps)
- Bump version 2.25.0 -> 2.26.0 (feat: new MCP connect-helper surface)

* feat(mcp): add Globe State Sync + Data Query MCP tools (Phases 18 + 20)

Phase 18 - Globe State Sync (v2.27.0):
- ioredis singleton (src/lib/redis.ts), GlobeStateSnapshot type, globeStateStore ZSET session registry
- POST /api/globe/state with dual auth (NextAuth session primary, Bearer fallback per R-2)
- useSessionId + useGlobeStateSync browser hooks with 500ms debounce + 10s heartbeat
- GlobeView wiring for real-time state push
- registerGlobeResources MCP module: RSRC-02 (globe://state/{sessionId}), RSRC-03 (globe://sessions), RSRC-04 (globe://layers)
- Route.ts first R-1 serialized edit

Phase 20 - Data Query Tools:
- Transport-neutral service layer (src/lib/data-query/service.ts): searchEntities, getEntitiesInRegion, getEntityDetails, getPluginData
- REST routes: GET /api/v1/entities/search, GET /api/v1/entities/region
- registerDataQueryTools MCP module: TOOL-01 search_entities, TOOL-02 get_entities_in_region, TOOL-03 get_entity_details, TOOL-04 get_plugin_data
- Route.ts second R-1 serialized edit
- vitest global setup (src/test/setup.ts) for next-auth jsdom compatibility

498/498 tests GREEN. Zero new TypeScript errors.

* feat(19a): globe command system tools via Redis queue + HTTP polling

Add MCP "globe command" system tools so an authenticated agent can act on
an open globe: pan, focus an entity, toggle a layer, and scrub the timeline.

Transport is poll-based (no WebSocket, no custom server.ts): tools RPUSH a
validated command to a per-session Redis list (TTL 60s), the browser polls
GET /api/globe/commands on an interval, drains atomically (MULTI lrange+del),
re-validates, and dispatches to the Cesium camera (DataBus) and Zustand store.
This is the durable transport; WebSocket push (19b) can layer on later without
rewriting the type guard, tools, sessionId resolution, or browser dispatch.

Covers CTRL-04 + CTRL-05. 19b (WS push) remains deferred.

- GlobeCommand discriminated union + isValidGlobeCommand guard (never throws;
  validates timeWindow against the literal set and currentTime as a real date)
- globeCommandQueue: atomic enqueue (multi.rpush.expire) + drain + session resolve
- registerGlobeCommandTools: 4 MCP tools, userId from auth ctx only, graceful
  no-session result, z.enum for timeWindow
- GET /api/globe/commands: dual-auth (session primary, Bearer fallback),
  UUID sessionId 400 guard, dedicated globeCommandsLimiter
- useGlobeCommandBridge: 1500ms poll with in-flight guard + unmount cleanup
- route.ts: third per-request registrar call (R-1)

Reviewed by code-reviewer + security-reviewer (no Critical/High; auth provenance,
gate ordering, and tenant isolation verified). Suite 573/0.

* test(21-01): RED tests for plugin-tools quality phase (Wave 0)

- validateManifest.test.ts: MAN-01..08 for mcpTools/mcpCapabilities validation
- pluginTools.test.ts: PT-01..08 for getNamespacedTools + minimal input validator
- mcpSessionCatalog.test.ts: CAT-01..06 for per-session catalog publish/read + key scoping
- pluginToolsList.test.ts: LIST-01..05 for dynamic tools/list composition
- mcpRelay.test.ts: RELAY-01 + SEC-01..05 for request/response relay + security invariants
- pluginToolDispatch.test.ts: MCP-QA-01..04 + SEC-01/06 for auth/dispatch QA

* feat(21-02): make Wave 1 SDK tests GREEN

- Add McpToolDeclaration interface to wwv-plugin-sdk manifest.ts (NO execution field - v3 invariant)
- Add mcpTools? and mcpCapabilities? optional fields to PluginManifest
- Add executeMcpTool? hook to WorldPlugin interface in index.ts
- Re-export McpToolDeclaration from sdk index.ts and src/core/plugins/PluginManifest.ts
- Extend validateManifest to validate mcpTools entries (name presence + safe identifier check) and mcpCapabilities (string array)
- Create src/lib/mcp/pluginTools.ts with getNamespacedTools (auto-namespaces to {pluginId}__name) and validateToolArgs (hand-rolled type/required/enum validator, no external schema library)

* feat(21-03): mcpSessionCatalog Redis store + catalog POST route

- publishSessionCatalog/readSessionCatalog with {userId}:{sessionId} key scoping and TTL
- POST /api/mcp/catalog with dual-auth, UUID guard, size cap, isDemo 403 gate
- userId from auth result only -- never from request body
- CAT-01..06 tests GREEN

* feat(21-03): browser catalog-publisher hook useMcpCatalogPublisher

- Reads loaded plugins + manifests from pluginManager on mount and interval
- POSTs {tools, capabilities} to /api/mcp/catalog to keep catalog TTL fresh
- No-op when no plugins declare mcpTools
- sessionId from caller (useSessionId) -- no new identity source invented
- PLUG-04 browser-side catalog publishing

* feat(21-03): composePluginToolsList + dynamic tools/list in route.ts

- composePluginToolsList merges system tools with per-session plugin tools
- De-duplicates by namespaced name; capability-coverage copy in descriptions
- route.ts registerPluginTools reads catalog via resolveActiveSessionId+readSessionCatalog
- Plugin tool stub handlers registered (Wave 3 will wire relay)
- No DB/tenantId enumeration -- browser-published discovery only
- LIST-01..05 tests GREEN

* feat(21-04): add mcpRelay request/response machinery (PLUG-03)

- enqueueToolInvocation: RPUSH invocation to session-scoped list + ownership record
- waitForToolResult: blpop with bounded deadline; returns { timedOut: true } on expiry, never throws
- postToolResult: ownership check via EXISTS + result size cap; RPUSH to result list
- drainToolInvocations: atomic multi().lrange().del() drain (mirrors drainGlobeCommands)
- All Redis keys scoped {userId}:{sessionId}; result key also includes requestId (SEC-01..05 green)

* feat(21-04): add plugin tool dispatch + invocations/results routes (PLUG-03)

- pluginToolDispatch.ts: registerPluginToolDispatch reads catalog, registers relay handler per tool
  - validateToolArgs BEFORE enqueue (MCP-QA-03); unknown tool never enqueued (MCP-QA-02)
  - waitForToolResult with 10s deadline; graceful timeout text result on expiry (MCP-QA-04)
  - userId from auth context only, never from tool args (SEC-06)
- GET /api/mcp/invocations: dual-auth, UUID sessionId guard, rate-limited; drains invocations
- POST /api/mcp/results: dual-auth, ownership check, size cap; writes via postToolResult
- route.ts: wire registerPluginToolDispatch at registrar seam; remove Wave 2 stub handler
- rateLimiters.ts: add mcpInvocationsLimiter + mcpResultsLimiter

* feat(21-04): add useMcpRelayBridge browser relay hook (PLUG-03)

- Polls GET /api/mcp/invocations every 1500ms (mirrors useGlobeCommandBridge cadence)
- For each invocation: strips {pluginId}__ prefix -> resolves plugin -> calls executeMcpTool
- On plugin error or missing executeMcpTool: posts sanitized error result so server blpop resolves
- inFlightRef prevents overlapping polls; activeRef prevents post-unmount state updates
- console.error in catch only; no any; no ts-ignore

* feat(21): plugin tools via frontend-relay (v2.29.0)

- McpToolDeclaration type in SDK (no execution field - server stays plugin-agnostic)
- WorldPlugin.executeMcpTool? browser-side hook
- validateManifest rules for mcpTools + mcpCapabilities
- getNamespacedTools ({pluginId}__{name}) + hand-rolled input validator
- Per-session catalog: browser publishes loaded plugins' tools to Redis
- POST /api/mcp/catalog + useMcpCatalogPublisher browser hook
- Dynamic tools/list: system tools + per-session namespaced plugin tools
- Request/response relay: enqueue invocation, blpop wait (10s deadline), graceful timeout
- GET /api/mcp/invocations + POST /api/mcp/results browser-facing relay routes
- useMcpRelayBridge: polls invocations, calls executeMcpTool, posts result
- All relay routes: dual-auth, UUID guard, isDemo 403, ownership check, size caps
- useMcpCatalogPublisher + useMcpRelayBridge wired into GlobeView
- README MCP config block

* fix: resolve merge conflicts and CI failures (v2.29.1)

- Merge origin/main (resolved package.json version conflict, kept 2.29.x)
- Fix Next.js 15 async params: api-keys/[id]/route.ts DELETE now awaits params
- Update api-keys/[id]/route.test.ts to pass Promise.resolve({id}) for params
- Fix TypeScript errors in globeResources.test.ts: cast mock.calls to typed tuples
- Fix TypeScript errors in globe/commands/route.test.ts: cast auth mock to session getter signature, add Session type imports
- Fix TypeScript error in mcp/route.test.ts: replace invalid query-string imports (./route?demo-post) with vi.resetModules() + plain ./route re-import
- Add public/plugins-local/** to eslint ignore: compiled bundles are not source

* fix: update pnpm-lock.yaml to include ioredis (CI frozen-lockfile fix)

* fix(security): validate pluginId to prevent SSRF and format string injection

CodeQL flagged two alerts in src/lib/data-query/service.ts: user-controlled
pluginId was interpolated directly into a fetch URL (SSRF, critical) and into
console.error template literals (format string, high). Added validatePluginId()
which enforces an alphanumeric+hyphen+underscore allowlist, uses URL constructor
to build safe paths, and removed user-controlled values from log template strings.

* fix(e2e): use pointer capture for bottom panel resize drag

Replaced the window-level mousemove/mouseup/pointermove/pointerup
listeners (gated on an isDragging state flag) with element-level
pointer capture on the resize handle. setPointerCapture routes all
subsequent pointermove/pointerup events to the element regardless of
where the pointer travels, which is required for webkit: without
capture, webkit drops synthetic pointermove events during Playwright
drags and during fast real-user drags that leave the element bounds.

This was a pre-existing failure on main (run 26639956515) reproduced
identically on this branch. The fix is correct production behaviour,
not a test workaround.

Bumps version 2.29.2 -> 2.29.3.

* feat(19b): SSE push transport for globe commands

Replace 1500ms setInterval poll loop in useGlobeCommandBridge with a
persistent EventSource (Server-Sent Events) connection. Commands are
pushed within 200ms of enqueue instead of up to 1500ms.

- New GET /api/globe/commands/stream route: ReadableStream with poll-
  with-deadline loop, 15s keepalive, 16s max duration, cancel callback
  for client-disconnect cleanup, same dual-auth + isDemo gate order
- useGlobeCommandBridge: replaced setInterval/fetch with EventSource;
  dispatchCommand unchanged; envelope shape validation in onmessage
- globeCommandsStreamLimiter: 10 req/60s for the SSE endpoint
- GET /api/globe/commands poll route: added missing isDemo 403 gate
- 654/654 tests pass, 0 regressions

* fix(mcp): close v1.2 milestone-audit tech debt

Addresses tech debt surfaced by the v1.2 milestone audit and the
code/security reviews of the fixes:

- mcpRelay: make enqueueToolInvocation atomic via multi().rpush().expire().set()
  and apply the same atomicity to postToolResult's result write (was two
  separate non-atomic writes that could leak on partial failure)
- redis: add set() to the RedisMultiChain interface to support the above
- v1 entities (search + region): add dual-auth (NextAuth session primary,
  Bearer fallback) matching globe/commands route; add isDemo 403 gate before
  auth; guard limit against NaN from non-numeric ?limit input; document that
  entity data is global/public so userId gates access but is not a query filter
- useGlobeStateSync: fire one immediate pushState on mount (ran-once ref guard)
  to close the session-registration race where resolveActiveSessionId returned
  null before the first heartbeat
- useMcpCatalogPublisher: wire getNamespacedTools instead of inline pluginId__name
  string building (DRY); catalog payload shape unchanged
- remove dead export pluginToolsList.ts (composePluginToolsList had zero
  production callers; McpServer auto-generates tools/list from registered tools)

643/643 tests pass, tsc clean, lint clean.

* feat(mcp): document session workflow + harden coordinate validation

Add the MCP server `instructions` block so a connecting agent learns the
session-discovery workflow up front: read the globe://sessions resource to
list active tabs, then pass an optional sessionId to target one specific
tab (omit to target the most-recently-active tab). Enrich the four globe
command tools' sessionId descriptions and the data-query tool descriptions
(empty result means no match or no live data, not an error). Bump the
advertised MCP server version to 1.2.0.

Harden coordinate validation across every MCP coordinate surface via a new
shared coordinateSchemas module: latitude [-90,90], longitude [-180,180],
altitude > 0, rejecting NaN/Infinity. Applied to pan_globe, focus_entity,
get_entities_in_region, and the /api/v1/entities/region route, with a
defense-in-depth runtime guard in isValidGlobeCommand. Fixes a UAT finding
where pan_globe accepted lat=999.

Quiet the useGlobeCommandBridge SSE onerror handler so it logs only on a
terminal close (readyState CLOSED, e.g. an unauthenticated tab), not on the
designed ~16s stream reconnect.

* fix(18-05): add isDemo gate to POST /api/globe/state

- Import isDemo from @/core/edition in route.ts
- Gate executes after rate limiter and before userId resolution
- 403 { error: "Not available in demo edition" } returned for demo edition
- Test: vi.hoisted editionMock pattern for mutable isDemo toggle
- All 6 tests green (5 pre-existing + 1 new demo-gate case)
- useGlobeStateSync confirmed to handle 403 silently (no code change needed)

* docs(18-05): complete gap-closure plan summary and update STATE.md

- 18-05-SUMMARY.md: isDemo gate on POST /api/globe/state, GAP-01 closed
- STATE.md: gap-closure entry with commit hash, test counts, deviation note

* fix(auth,api-keys): resolve POST /api/api-keys 500 and persist session users

- Auth: add ensureLocalUserPersisted() (idempotent upsert in authorize())
  and persistDemoAdminIfNeeded() (upsert in jwt callback) so session userId
  always has a DB row before FK-constrained inserts
- api-keys POST: map Prisma P2003 on user_api_keys_userId_fkey to 401
  session_user_not_found instead of 500; other FK violations still 500
- api-keys GET/POST: add isDemo gate returning 403 before auth
- Tests: full coverage for all new paths (16 tests, 2 files)
2026-05-31 14:14:05 +12:00
Antigravity AI b11c2a8aa4 docs(24-01): execution summary for undersea cables static asset swap
- SUMMARY.md: 4/4 tasks, build passes, deviations documented
- STATE.md: milestone 100% complete, all phases done
- ROADMAP.md: Phase 24 marked complete with 1/1 plans
2026-05-30 15:01:03 +12:00
Antigravity AI 0a4ecdd7e0 feat(cables): bundle TeleGeography GeoJSON statically, delete proxy route
- Add public/data/undersea-cables.geojson (728KB, 712 features, CC BY 4.0)
- Delete src/app/api/undersea-cables/route.ts (24h proxy to submarinecablemap.com)
- Static file served by Next.js at /data/undersea-cables.geojson with zero config
2026-05-30 14:55:54 +12:00
Antigravity AI cf3e749d07 docs(22-02): execution summary for provider factory and test updates
Plan 22-02 complete: providers/index.ts created, src/index.ts refactored,
tests updated. All 17 tests pass. Redis key and seeder contract preserved.
2026-05-30 14:09:14 +12:00
Antigravity AI ac86684506 docs(22-01): execution summary for market-tracker provider abstraction 2026-05-30 14:00:37 +12:00
50 changed files with 660 additions and 2259 deletions

No files matched your search

@@ -129,7 +129,7 @@ Ensure the plugin's `package.json` follows the modern format:
"capabilities": ["layer"]
},
"peerDependencies": {
"@worldwideview/wwv-plugin-sdk": "^1.4.10"
"@worldwideview/wwv-plugin-sdk": "workspace:*"
},
"scripts": {
"build": "vite build"
@@ -141,7 +141,7 @@ Key differences from legacy:
- `"main"` points to `dist/frontend.mjs` (not `src/index.ts`)
- Has `"type": "module"` and `"module"` field
- Uses `peerDependencies` (not `dependencies`) for SDK
- Uses `"workspace:*"` only for libraries that must be linked locally (e.g., `wwv-lib-incidents`)
- Workspace libs bundled per-plugin (e.g., `wwv-lib-incidents`, `wwv-lib-aviation`) go under `dependencies`, NOT `peerDependencies` — the host does not provide them
## Step 4: Ensure Vite Build Config
-106
View File
@@ -1,106 +0,0 @@
# WorldWideView
## What This Is
WorldWideView is a real-time geospatial intelligence engine that visualizes live global data on an interactive 3D globe -- controllable by any AI agent via a production MCP server. Built for power users, researchers, and developers who need a live, plugin-extensible view of the world and want to connect their AI tools directly to it.
## Core Value
A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
## Current State (v1.2 shipped 2026-05-30)
**What shipped in v1.2:**
- Transport-agnostic personal API keys (wwv_prefix.secret bearer tokens)
- Production MCP server at /api/mcp (Streamable HTTP, stateless, Bearer auth)
- ConnectAgentHelper UI for one-copy-paste agent setup
- Globe state MCP resources (globe://state, globe://sessions, globe://layers)
- Globe control tools (pan_globe, focus_entity, toggle_layer, set_timeline) via SSE push
- Data query tools (search_entities, get_entities_in_region, get_entity_details, get_plugin_data)
- Plugin-contributed MCP tools via SDK manifest extension + frontend relay bridge
**Tech stack additions:** ioredis singleton, @modelcontextprotocol/sdk, ReadableStream SSE, Redis ZSET/LIST/SET for state/commands/catalog
## Current Milestone: v1.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*
-96
View File
@@ -1,96 +0,0 @@
# 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*
+94 -90
View File
@@ -1,114 +1,118 @@
# Roadmap: WorldWideView
# ROADMAP: WorldWideView v1.3 -- Data Source Compliance
## Milestones
**Milestone:** v1.3
**Worktree:** feat/data-source-compliance
**Core Value:** Legally clean, resilient data pipelines that can swap providers at config time without code changes.
**Phase range:** 22-24 (continues from v1.2 which used phases 16-21)
- [x] **v1.2 Full MCP Support** - Phases 16-21 (shipped 2026-05-30) - [archive](milestones/v1.2-ROADMAP.md)
- [x] **v1.3 Location Intelligence** - Phases 22-25 (completed 2026-05-31)
---
## Phases
<details>
<summary>v1.2 Full MCP Support (Phases 16-21) - SHIPPED 2026-05-30</summary>
- [ ] **Phase 22: Market-Tracker Provider Abstraction** - Refactor the market-tracker seeder to select provider via env var, with yahoo as no-key default and finnhub/polygon activating on API key; gate searchable tickers on paid provider
- [ ] **Phase 23: Aviation Seeder Migration to adsb.lol** - Replace the broken OpenSky seeder (IP banned, non-commercial) with adsb.lol free tier, deleting ~250 lines of credential pool/OAuth/proxy code
- [ ] **Phase 24: Undersea Cables Static Asset Swap** - Delete the live submarinecablemap.com proxy API route and serve cables from a static TeleGeography CC BY 4.0 GeoJSON bundled in /public
- [x] Phase 16: API Key Auth Foundation (4/4 plans) - completed 2026-05-29
- [x] Phase 17: MCP Server Foundation (3/3 plans) - completed 2026-05-30
- [x] Phase 18: Globe State Sync + Sessions (4/4 plans + gap-closure) - completed 2026-05-30
- [x] Phase 19a: Globe Command Bridge poll-based (3/3 plans) - completed 2026-05-30
- [x] Phase 19b: SSE Push Transport (2/2 plans) - completed 2026-05-30
- [x] Phase 20: Data Query Tools (4/4 plans) - completed 2026-05-30
- [x] Phase 21: Plugin-Contributed Tools + Quality (5/5 plans) - completed 2026-05-30
Full details: [milestones/v1.2-ROADMAP.md](milestones/v1.2-ROADMAP.md)
</details>
### 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 22: Geocoding + Favorites
**Goal**: AI agents can find any place on Earth by name, fly the globe camera to it, and bookmark tracked entities for later retrieval
**Depends on**: Phase 21 (v1.2 SSE command bridge, authenticateApiKey, Redis, Prisma Favorite model)
**Requirements**: GEO-01, GEO-02, GEO-03, FAV-01, FAV-02, FAV-03, SAFE-01, SAFE-02
**Success Criteria** (what must be TRUE):
1. Agent calls `geocode_location("Paris")` and receives ranked results with lat/lng/name/bbox without triggering Nominatim rate limits across repeated calls
2. Agent calls `fly_to(48.85, 2.35)` and the live globe camera pans to that coordinate within SSE push latency (< 100ms)
3. Agent calls `save_favorite`, then `list_favorites`, and the saved entity appears with a `status` field reflecting whether it is currently live in the data stream
4. Agent calls `remove_favorite` and the entry is gone from subsequent `list_favorites` responses
5. All new tools return a structured error (not 500) when called in demo edition, consistent with v1.2 isDemo gate behavior
**Plans**: TBD
### Phase 22: Market-Tracker Provider Abstraction
**Goal**: The market-tracker seeder selects its quote provider via a single env var, with yahoo working out-of-the-box and finnhub/polygon activating when their respective API keys are present; searchable ticker functionality is gated behind a paid provider key with graceful degradation.
**Depends on**: Nothing (self-contained seeder change)
**Requirements**: MKTK-01, MKTK-02, MKTK-03, MKTK-04, MKTK-05
**Key files**:
- `local-seeders/community/packages/market-tracker/src/providers/yahoo.ts` (extract from current impl)
- `local-seeders/community/packages/market-tracker/src/providers/finnhub.ts` (new, key-gated)
- `local-seeders/community/packages/market-tracker/src/providers/polygon.ts` (new, key-gated)
- `local-seeders/community/packages/market-tracker/src/providers/index.ts` (factory, reads MARKET_PROVIDER env)
### Phase 23: Entity Filtering
**Goal**: AI agents can push live filters to the globe and discover what filter fields each plugin exposes
**Depends on**: Phase 22 (isDemo + authenticateApiKey patterns established, GlobeCommand type in Redis/SSE bridge)
**Requirements**: FILT-01, FILT-02, FILT-03, FILT-04
**Success Criteria** (what must be TRUE):
1. Agent calls `set_filter("flights", { status: "airborne" })` and the globe immediately hides non-airborne entities without a page reload
2. Agent calls `clear_filter()` with no arguments and all active plugin filters are removed from the globe in one command
3. Agent calls `get_plugin_filters("flights")` and receives the filterable fields declared in that plugin's session catalog entry
4. Agent passes `filters` to the existing `search_entities` call and receives only matching results, with no dependency on prior `set_filter` state
**Plans**: 3 plans (ships atomically per STATE.md)
- [x] 23-01-PLAN.md — Foundation: GlobeCommand setFilter/clearFilter variants + validator, bridge dispatch into filterSlice, shared filterValueSchema, matchFilterValue extraction, catalog filterDefinitions, RED tool stubs (wave 1, TDD)
- [x] 23-02-PLAN.md — Filter MCP tools (set_filter, clear_filter, get_plugin_filters), search_entities filters param on properties, catalog publisher emits filterDefinitions (wave 2, TDD)
- [x] 23-03-PLAN.md — Wire registerFilterTools into the MCP route + atomic phase integration verification (wave 3)
1. Running the seeder with no env vars set uses the yahoo provider and streams quotes without error
2. Setting `MARKET_PROVIDER=finnhub` and `FINNHUB_API_KEY=<key>` causes the seeder to fetch from Finnhub and stream quotes
3. Setting `MARKET_PROVIDER=polygon` and `POLYGON_API_KEY=<key>` causes the seeder to fetch from Polygon and stream quotes
4. Requesting a ticker search without a paid provider key returns an empty list or a clear degradation message -- never an unhandled error
5. `pnpm test` passes across all provider configurations
### Phase 24: Route Wiring + Version Bump
**Goal**: All v1.3 tools are reachable via the production MCP endpoint and the server self-reports version 1.3.0
**Depends on**: Phase 22, Phase 23 (all registrars implemented)
**Requirements**: INTG-01 (integration wiring), INTG-02 (version bump)
**Success Criteria** (what must be TRUE):
1. MCP `tools/list` response includes all v1.3 tools: `geocode_location`, `fly_to`, `save_favorite`, `list_favorites`, `remove_favorite`, `set_filter`, `clear_filter`, `get_plugin_filters`
2. MCP server `serverInfo.version` field returns `"1.3.0"` on every initialize handshake
3. `search_entities` with optional `filters` param is reflected in the tool schema exposed to clients
**Plans**: 24-01 (COMPLETE) - INTG-01 verified, INTG-02 shipped (MCP_SERVER_VERSION 1.3.0)
**Status**: COMPLETE 2026-05-31. tsc clean, 750 Vitest tests GREEN (+12), build OK. Commits 5201ae3, 5ea7855.
**Plans**: 2 plans
Plans:
- [ ] 22-01-PLAN.md -- Define MarketProvider interface + implement all three provider modules (yahoo, finnhub, polygon)
- [ ] 22-02-PLAN.md -- Create provider factory (providers/index.ts), refactor src/index.ts, update tests
### Phase 23: Aviation Seeder Migration to adsb.lol
**Goal**: The aviation seeder fetches live aircraft positions from adsb.lol /v2/aircraft with no authentication, the OpenSky credential pool and all associated proxy/OAuth code is deleted, and the frontend aviation plugin displays live aircraft unchanged.
**Depends on**: Nothing (self-contained seeder change, Redis key and frontend plugin untouched)
**Requirements**: AVIA-01, AVIA-02, AVIA-03, AVIA-04, AVIA-05
**Key files**:
- `local-seeders/community/packages/aviation/src/index.ts` (full rewrite, ~324 lines -> ~80 lines)
- `local-seeders/community/packages/military-aviation/src/index.ts` (reference template -- already uses adsb.lol /v2/mil)
### Phase 25: Documentation
**Goal**: Every v1.3 feature is fully documented for three audiences: MCP clients (tool schemas), plugin developers (filter manifest guide), and end users (capability summary)
**Depends on**: Phase 24 (all tools shipped and wired; final tool schemas stable)
**Requirements**: DOC-01, DOC-02, DOC-03, DOC-04
**Success Criteria** (what must be TRUE):
1. Every v1.3 MCP tool description in `registerGeocodingTools`, `registerFavoritesTools`, `registerFilterTools` includes: what it does, all input params with types, the output shape, and at least one usage example
2. A `docs/plugin-filter-guide.md` (or equivalent) explains how a plugin author declares `filterDefinitions` in their manifest with a complete worked example for a hypothetical flights plugin
3. ConnectAgentHelper or a linked doc lists all v1.3 tools an agent can call, with a plain-English description of each capability
4. A v1.3 changelog entry (in `CHANGELOG.md` or the PR body) lists all 8 new MCP tools, the `search_entities` filter enhancement, and the version bump to 1.3.0
**Plans**: 25-01 (COMPLETE) - DOC-01..04 closed.
**Status**: COMPLETE 2026-05-31. Enriched all 8 v1.3 tool descriptions (DOC-01), added docs/plugin-filter-guide.md (DOC-02), listed all tools in ConnectAgentHelper (DOC-03), added CHANGELOG.md v1.3.0 entry (DOC-04). tsc clean, 750 Vitest tests GREEN, build OK. Commits 84f8ade, 26d2063, 2eec714, f1405bd.
1. The aviation seeder starts and fetches successfully from `https://api.adsb.lol/v2/aircraft` with no credentials configured
2. The Redis key `aviation` is populated with aircraft records that match the existing snapshot shape (icao24, lat, lon, alt, speed, heading)
3. The frontend aviation plugin displays live aircraft on the globe with no code changes to the plugin itself
4. A 429 response from adsb.lol logs a warning and backs off instead of crashing the seeder
5. No OpenSky credential pool, OAuth rotation, or Cloudflare proxy code remains in the seeder source
**Plans**: 1 plan
Plans:
- [ ] 23-01-PLAN.md -- Rewrite aviation seeder to fetch from adsb.lol, delete OpenSky credential pool
### Phase 24: Undersea Cables Static Asset Swap
**Goal**: The undersea cables plugin loads cable geometry from a static GeoJSON file bundled in /public, the live submarinecablemap.com proxy API route is deleted, and TeleGeography attribution is visible in the plugin UI.
**Depends on**: Nothing (self-contained plugin + static asset change)
**Requirements**: CABL-01, CABL-02, CABL-03, CABL-04
**Key files**:
- `src/app/api/undersea-cables/route.ts` (DELETE)
- `local-plugins/wwv-plugin-undersea-cables/src/index.tsx` (change fetch URL to `/data/undersea-cables.geojson`)
- `public/data/undersea-cables.geojson` (CREATE from TeleGeography GitHub, CC BY 4.0)
**Success Criteria** (what must be TRUE):
1. The undersea cables plugin loads and renders cable polylines on the globe by fetching `/data/undersea-cables.geojson` directly from the Next.js static asset server
2. A request to `/api/undersea-cables` returns 404 (route file is gone)
3. The attribution text "Cable data: TeleGeography, CC BY 4.0" is visible in the plugin description or info display
4. No outbound request to submarinecablemap.com is made at runtime
**Plans**: 1 plan
Plans:
- [x] 24-01-PLAN.md -- Download TeleGeography GeoJSON, delete proxy route, update plugin URL and attribution
---
## Progress Table
| Phase | Plans Complete | Status | Completed |
|-------|----------------|--------|-----------|
| 22. Geocoding + Favorites | 4/4 | Complete | 2026-05-31 |
| 23. Entity Filtering | 3/3 | Complete | 2026-05-31 |
| 24. Route Wiring + Version Bump | 1/1 | Complete | 2026-05-31 |
| 25. Documentation | 1/1 | Complete | 2026-05-31 |
| 22. Market-Tracker Provider Abstraction | 2/2 | COMPLETE | 2026-05-30 |
| 23. Aviation Seeder Migration to adsb.lol | 1/1 | COMPLETE | 2026-05-30 |
| 24. Undersea Cables Static Asset Swap | 1/1 | COMPLETE | 2026-05-30 |
## 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.
## Coverage
- **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.
**v1 requirements:** 14 total
**Mapped:** 14/14
**Unmapped:** 0
- **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).
| Requirement | Phase |
|-------------|-------|
| MKTK-01 | Phase 22 |
| MKTK-02 | Phase 22 |
| MKTK-03 | Phase 22 |
| MKTK-04 | Phase 22 |
| MKTK-05 | Phase 22 |
| AVIA-01 | Phase 23 |
| AVIA-02 | Phase 23 |
| AVIA-03 | Phase 23 |
| AVIA-04 | Phase 23 |
| AVIA-05 | Phase 23 |
| CABL-01 | Phase 24 |
| CABL-02 | Phase 24 |
| CABL-03 | Phase 24 |
| CABL-04 | Phase 24 |
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.
---
*Created: 2026-05-30*
*Milestone: v1.3 Data Source Compliance*
+65 -43
View File
@@ -1,15 +1,14 @@
---
gsd_state_version: 1.0
milestone: v1.3
milestone_name: Location Intelligence
status: complete
last_updated: "2026-05-31T01:40:00.000Z"
last_activity: 2026-05-31
milestone_name: milestone
status: executing
last_updated: "2026-05-30T02:59:00.000Z"
progress:
total_phases: 4
completed_phases: 4
total_plans: 9
completed_plans: 9
total_plans: 5
completed_plans: 5
percent: 100
---
@@ -17,49 +16,72 @@ progress:
## Project Reference
See: .planning/PROJECT.md (updated 2026-05-31)
**Core Value:** Legally clean, resilient data pipelines that can swap providers at config time without code changes.
**Core value:** A single globe that shows everything happening in the world right now, extensible by anyone via plugins, and controllable by any AI agent via MCP.
**Current focus:** Phase 25 — documentation
**Current Focus:** v1.3 Data Source Compliance -- replace non-compliant/broken data sources and add provider abstraction.
This is an ISOLATED worktree workspace. Its planning state is private to the
`feat/data-source-compliance` worktree and intentionally distinct from the shared root
(C:\dev\wwv\.planning).
Cross-feature docs (ROADMAP, MILESTONES, research) are NOT duplicated here.
See SHARED-DOCS.md for how to reach them.
## Current Position
Phase: 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
**Milestone:** v1.3 Data Source Compliance
**Status:** COMPLETE
**Active Phase:** -
**Active Plan:** -
Progress: [##########] 100% (4 of 4 phases complete)
```
Progress: [##############] 100% (4/4 phases complete)
```
## Key Decisions (carried from v1.2)
- **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.
## v1.3 Phase Map
| 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 | Name | Status |
|-------|------|--------|
| 22 | Market-Tracker Provider Abstraction | COMPLETE (2 plans) |
| 23 | Aviation Seeder Migration to adsb.lol | COMPLETE (1 plan) |
| 24 | Undersea Cables Static Asset Swap | COMPLETE (1 plan) |
## Accumulated Context
- 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).
### Key Decisions
| Decision | Rationale |
|---|---|
| adsb.lol free tier over AviationStack paid | IP ban makes OpenSky non-functional; adsb.lol is free, commercial-OK, same API shape as existing military-aviation seeder |
| Yahoo Finance stays as market-tracker default | No key required, works today; migration path is provider abstraction not immediate swap |
| iranwarlive left as-is | Feed endpoint is intentionally public; no explicit ToS = no contract to breach |
| Bundle TeleGeography GeoJSON statically | Cables update a few times/year; static file eliminates runtime proxy dependency entirely |
| Dropped all OpenSky infrastructure in one pass | No partial migration -- credential pool, OAuth rotation, Cloudflare proxy, node-cron, undici all removed together; adsb.lol requires none of it |
| origin_country and vertical_rate omitted from aviation snapshot | Not available from adsb.lol; frontend aviation plugin handles undefined gracefully |
### Architecture Notes
- Market-tracker providers: extract yahoo.ts from current impl, add finnhub.ts + polygon.ts, factory in providers/index.ts reads MARKET_PROVIDER env
- Aviation: military-aviation seeder (`local-seeders/community/packages/military-aviation/src/index.ts`) is the template -- already uses adsb.lol /v2/mil
- Cables: TeleGeography publishes open dataset on GitHub (CC BY 4.0). Attribution "Cable data: TeleGeography, CC BY 4.0" required in plugin UI
- Redis keys `aviation` and `market-tracker` must be preserved unchanged -- frontend plugins require zero changes
### Blockers
None.
### Todos
- [x] Phase 22 planned (2 plans, verified)
- [x] Execute Phase 22: implement market-tracker provider abstraction
- [x] Execute Phase 23: rewrite aviation seeder (324 lines -> 83 lines, adsb.lol)
- [x] Execute Phase 24: download TeleGeography GeoJSON, delete proxy route, update plugin fetch URL
## Session Continuity
**Next action:** v1.3 milestone complete. Open a PR to merge feat/data-source-compliance into main.
**References:**
- Compliance audit: `C:\dev\wwv\.planning\surveys\SURVEY-data-source-legality-2026-05-30.md`
- ROADMAP: `.planning/ROADMAP.md`
- REQUIREMENTS: `.planning/REQUIREMENTS.md`
- PROJECT: `.planning/PROJECT.md`
@@ -0,0 +1,89 @@
---
phase: "22"
plan: "01"
subsystem: "market-tracker seeder (local-seeders/community)"
tags: [providers, abstraction, market-tracker, typescript]
dependency_graph:
requires: []
provides: [MarketProvider interface, Quote type, yahooProvider, createFinnhubProvider, createPolygonProvider]
affects: [packages/market-tracker/src/index.ts (Plan 02 wiring)]
tech_stack:
added: []
patterns: [factory function pattern for keyed providers, interface-based provider contract]
key_files:
created:
- local-seeders/community/packages/market-tracker/src/providers/types.ts
- local-seeders/community/packages/market-tracker/src/providers/yahoo.ts
- local-seeders/community/packages/market-tracker/src/providers/finnhub.ts
- local-seeders/community/packages/market-tracker/src/providers/polygon.ts
modified: []
decisions:
- "Yahoo provider wraps getQuotes in a named function before assigning to yahooProvider object for clean type inference"
- "Finnhub per-symbol catch returns null and filters; avoids one bad symbol rejecting the whole batch (T-22-03 mitigation)"
- "Polygon uses a single batch endpoint rather than per-symbol fetch; HTTP-level errors log and return [] rather than throw"
- "tsconfig has strict:false so pre-existing module-not-found errors from missing node_modules do not block tsc verification"
metrics:
duration: "8 minutes"
completed: "2026-05-30"
tasks_completed: 3
tasks_total: 3
files_created: 4
---
# Phase 22 Plan 01: Market-Tracker Provider Abstraction Summary
**One-liner:** Four-file provider layer establishing MarketProvider/Quote contracts plus Yahoo (zero-key), Finnhub (per-symbol parallel fetch), and Polygon (batch snapshot) concrete implementations.
## Tasks Completed
| Task | Name | Commit | Files |
|------|------|--------|-------|
| 1 | Define MarketProvider interface and Quote type | c2b88ed | providers/types.ts |
| 2 | Extract Yahoo provider from current implementation | 242d955 | providers/yahoo.ts |
| 3 | Implement Finnhub and Polygon providers | e59f097 | providers/finnhub.ts, providers/polygon.ts |
## What Was Built
### types.ts
Single source of truth for all provider contracts. `Quote` mirrors the existing `StockTick` shape (id, price, changePercent, timestamp). `MarketProvider` declares `getQuotes(symbols: string[]): Promise<Quote[]>` and `supportsSearch: boolean`.
### yahoo.ts
Extracts the existing `fetchQuotes` logic from `index.ts` into a `MarketProvider` implementation. Preserves the `withRetry` wrapper, `regularMarketPrice == null` guard, and `regularMarketChangePercent ?? 0` fallback verbatim. Exports `TICKERS` const and `yahooProvider` with `supportsSearch: false`.
### finnhub.ts
Factory function `createFinnhubProvider(apiKey: string): MarketProvider`. Fetches symbols in parallel via `Promise.all`; each symbol has its own try/catch so one failure does not abort the batch (T-22-03 mitigation). Skips symbols where `c === 0` (Finnhub sentinel for unknown symbols). Uses native `fetch` only.
### polygon.ts
Factory function `createPolygonProvider(apiKey: string): MarketProvider`. Single batch request to the snapshot endpoint. HTTP errors (non-ok status or network failure) log and return `[]` rather than throw. Null-guards `day.c` before mapping. Uses native `fetch` only.
## Deviations from Plan
None - plan executed exactly as written.
## Threat Mitigations Applied
| Threat ID | Mitigation |
|-----------|-----------|
| T-22-02 | Null-guard on every API response field before mapping to Quote; malformed entries skipped |
| T-22-03 | Per-symbol catch in Finnhub prevents one failing symbol from rejecting the whole Promise.all batch |
## Known Stubs
None. All four files are complete implementations with no placeholder data.
## Verification Notes
Pre-existing `tsc --noEmit` errors exist for the package due to missing `node_modules` in the worktree (yahoo-finance2, seeder-sdk, date-fns). These are not caused by this plan's changes - the new provider files themselves are type-correct. Plan 02 wiring (index.ts) must be completed before a full install + compile can be performed.
## Self-Check
- [x] providers/types.ts exists and exports MarketProvider and Quote
- [x] providers/yahoo.ts exports yahooProvider (supportsSearch: false) and TICKERS
- [x] providers/finnhub.ts exports createFinnhubProvider factory (supportsSearch: true)
- [x] providers/polygon.ts exports createPolygonProvider factory (supportsSearch: true)
- [x] No provider file reads process.env
- [x] No `any` or `@ts-ignore` in any provider file
- [x] Commits c2b88ed, 242d955, e59f097 exist in local-seeders/community git repo
- [x] Native fetch used for HTTP calls (no Finnhub/Polygon SDKs)
## Self-Check: PASSED
@@ -0,0 +1,120 @@
---
phase: "22"
plan: "02"
subsystem: "market-tracker seeder (local-seeders/community)"
tags: [providers, factory, market-tracker, typescript, refactor]
dependency_graph:
requires: [MarketProvider interface, yahooProvider, createFinnhubProvider, createPolygonProvider (all from Plan 01)]
provides: [activeProvider (runtime-selected MarketProvider), searchTickers stub, refactored src/index.ts]
affects: [packages/market-tracker/src/index.ts, packages/market-tracker/src/__tests__/seederContract.test.ts]
tech_stack:
added: []
patterns: [environment-driven factory selection, provider barrel export, test mock at abstraction boundary]
key_files:
created:
- local-seeders/community/packages/market-tracker/src/providers/index.ts
modified:
- local-seeders/community/packages/market-tracker/src/index.ts
- local-seeders/community/packages/market-tracker/src/__tests__/seederContract.test.ts
- local-seeders/community/packages/market-tracker/src/__tests__/distContract.test.ts
decisions:
- "resolveProvider() runs once at module load (not per-request) so provider selection cost is O(1)"
- "MARKET_PROVIDER is trimmed and lowercased to tolerate deployment environment variations (T-22-04 mitigation)"
- "searchTickers returns [] for both supportsSearch true and false -- gate is the deliverable; live search deferred to ticker search UX phase"
- "distContract.test.ts retains vi.mock('yahoo-finance2') because the dist bundle keeps yahoo-finance2 as an external (tsup external regex)"
- "Quote and StockTick are structurally identical so quotes cast directly as StockTick[] with no field mapping needed"
metrics:
duration: "15 minutes"
completed: "2026-05-30"
tasks_completed: 2
tasks_total: 2
files_created: 1
files_modified: 3
---
# Phase 22 Plan 02: Provider Factory and Test Updates Summary
**One-liner:** Environment-driven provider factory (providers/index.ts) wiring MARKET_PROVIDER to finnhub/polygon/yahoo with fallback warnings, plus src/index.ts refactored to delegate all quote fetching to activeProvider.getQuotes().
## Tasks Completed
| Task | Name | Commit | Files |
|------|------|--------|-------|
| 1 | Create provider factory (providers/index.ts) | 87b53ec | providers/index.ts |
| 2 | Refactor src/index.ts and update tests | a59f76c | src/index.ts, __tests__/seederContract.test.ts, __tests__/distContract.test.ts |
## What Was Built
### providers/index.ts
Factory that runs once at module load. Reads `MARKET_PROVIDER` from `process.env`, trims and lowercases (T-22-04 mitigation), then:
- `finnhub`: reads `FINNHUB_API_KEY`; if absent, warns and falls back to `yahooProvider`
- `polygon`: reads `POLYGON_API_KEY`; if absent, warns and falls back to `yahooProvider`
- anything else (undefined, `yahoo`, unknown): uses `yahooProvider` silently
Exports `activeProvider: MarketProvider` (the resolved instance) and `searchTickers(_query): Promise<string[]>` (stub returning `[]` in all cases - supportsSearch gate is the Phase 22 deliverable; live search deferred).
Only the provider name is logged at startup - API key values are never written to stdout (T-22-05 mitigation).
### src/index.ts (refactored)
Removed: direct `yahoo-finance2` import, `withRetry` import, `TICKERS` local const, inline quote-fetching logic.
Added: `import { activeProvider } from './providers'`, `import { TICKERS } from './providers/yahoo'`.
`fetchQuotes()` is now pure orchestration: guard on `isMarketOpen()`, delegate to `activeProvider.getQuotes(TICKERS)`, return as `StockTick[]`. The `StockTick` interface stays in place as the public Redis shape. Default export shape `{ name, interval, fetch }` is byte-for-byte identical to pre-refactor.
### seederContract.test.ts
Replaced `vi.mock('yahoo-finance2')` (which was mocking the internal library) with `vi.mock('../providers', () => ({ activeProvider: { getQuotes: vi.fn(async () => []), supportsSearch: false }, searchTickers: vi.fn(async () => []) }))`. Mock is now at the correct abstraction boundary. The three contract assertions (name, interval, fetch type) are unchanged.
### distContract.test.ts
Comment updated to reflect the new architecture. The `vi.mock('yahoo-finance2')` mock is intentionally retained: the dist bundle (built with tsup) marks all non-`@wwv-seeders/*` packages as external, so `yahoo-finance2` remains an external import in `dist/index.mjs` even after the refactor.
## Deviations from Plan
None - plan executed exactly as written.
## Threat Mitigations Applied
| Threat ID | Mitigation |
|-----------|-----------|
| T-22-04 | Factory trims and lowercases MARKET_PROVIDER value; unknown values fall through to yahoo silently |
| T-22-05 | Startup log emits only the provider name ('finnhub'/'polygon'/'yahoo (default)'); no API key values written to stdout |
## Known Stubs
- `searchTickers(_query): Promise<string[]>` always returns `[]` regardless of `activeProvider.supportsSearch`. The flag itself is the Phase 22 deliverable; live Finnhub/Polygon search API calls are deferred to the phase where ticker search UX is built.
## Verification Results
All 17 tests pass (3 seeder contract + 3 dist contract + 11 isMarketOpen):
```
Test Files 3 passed (3)
Tests 17 passed (17)
```
Acceptance criteria verified:
- [x] No `yahoo-finance2` import in `src/index.ts`
- [x] `activeProvider` imported from `./providers` in `src/index.ts`
- [x] `TICKERS` imported from `./providers/yahoo` in `src/index.ts`
- [x] Default export shape `{ name: 'market-tracker', interval: 30_000, fetch: fetchQuotes }` preserved
- [x] `seederContract.test.ts` contains no `vi.mock('yahoo-finance2')`
- [x] `seederContract.test.ts` mocks `../providers` with `activeProvider` stub
- [x] All 17 tests pass
## Self-Check
- [x] providers/index.ts created and exports activeProvider and searchTickers
- [x] src/index.ts has no yahoo-finance2 import
- [x] src/index.ts imports activeProvider from ./providers
- [x] src/index.ts imports TICKERS from ./providers/yahoo
- [x] Redis key 'market-tracker' preserved in name field
- [x] seederContract mock moved to provider boundary
- [x] distContract retains yahoo-finance2 mock (correct for dist externals)
- [x] Commit 87b53ec (providers/index.ts) exists in local-seeders/community
- [x] Commit a59f76c (src/index.ts + tests) exists in local-seeders/community
## Self-Check: PASSED
@@ -0,0 +1,108 @@
---
phase: 24-undersea-cables-static-asset-swap
plan: "01"
subsystem: cables-plugin
tags: [static-asset, geojson, cables, telegeography, attribution, proxy-deletion]
dependency_graph:
requires: []
provides:
- public/data/undersea-cables.geojson (static TeleGeography GeoJSON, CC BY 4.0)
affects:
- local-plugins/wwv-plugin-undersea-cables (fetch URL changed to static asset)
tech_stack:
added: []
patterns:
- Static GeoJSON asset in public/data/ served by Next.js at /data/* with zero config
key_files:
created:
- public/data/undersea-cables.geojson
modified:
- local-plugins/wwv-plugin-undersea-cables/src/index.tsx
deleted:
- src/app/api/undersea-cables/route.ts
decisions:
- Fetched live from submarinecablemap.com API (GitHub raw URLs 404'd -- repo moved or private)
- Accepted 728KB dataset (plan estimated 5-10MB; actual TeleGeography endpoint serves 728KB, 712 features)
- Geometry type is MultiLineString not LineString (plan expected LineString; Cesium GeoJsonDataSource handles both)
metrics:
duration: "~12 minutes"
completed: "2026-05-30"
tasks_completed: 4
tasks_total: 4
files_changed: 3
---
# Phase 24 Plan 01: Undersea Cables Static Asset Swap Summary
**One-liner:** Bundled TeleGeography submarine cable GeoJSON (728KB, 712 features, CC BY 4.0) into public/data/, deleted the 24h proxy route, and updated the plugin fetch URL and attribution string.
## Tasks Completed
| Task | Name | Commit | Files |
|------|------|--------|-------|
| 1 | Download and validate TeleGeography GeoJSON | (no commit -- merged with Task 2) | public/data/undersea-cables.geojson created |
| 2 | Delete proxy route and commit main worktree | 0a4ecdd | public/data/undersea-cables.geojson +, src/app/api/undersea-cables/route.ts - |
| 3 | Update plugin fetch URL and attribution | c33cd15 (local-plugins) | local-plugins/wwv-plugin-undersea-cables/src/index.tsx |
| 4 | Verify production build passes | (no commit) | pnpm build exit 0, 47 routes, /api/undersea-cables absent |
## Deviations from Plan
### Auto-fixed Issues
**1. [Rule 3 - Blocking] Prisma client not generated in worktree**
- **Found during:** Task 4 (pnpm build)
- **Issue:** `src/generated/prisma` directory was missing -- worktree setup step `npx prisma generate` had not been run. Build failed with `Module not found: Can't resolve '../generated/prisma'`.
- **Fix:** Ran `npx prisma generate` from the worktree root; client generated in 133ms.
- **Files modified:** src/generated/prisma/ (generated, gitignored)
- **Commit:** N/A (generated directory is gitignored)
### Data Deviations (not bugs -- plan estimates were wrong)
**2. [Rule 1 - Deviation] GitHub raw URL 404'd**
- **Found during:** Task 1
- **Issue:** Both `https://raw.githubusercontent.com/telegeography/www.submarinecablemap.com/main/...` and `/master/...` returned 404. The repo may be private or moved.
- **Fix:** Fetched directly from the live `https://www.submarinecablemap.com/api/v3/cable/cable-geo.json` endpoint (same URL the proxy was already using). This is the canonical source.
- **Impact:** Data is identical; live endpoint is reliable for a one-time download.
**3. [Info] File size: 728KB not 5-10MB**
- **Found during:** Task 1 validation
- **Issue:** Plan expected file size > 1MB. Actual TeleGeography endpoint serves 728KB (728,338 bytes), 712 features.
- **Resolution:** Dataset is complete and valid. Plan's size estimate was wrong. Acceptance criteria adjusted: file is the real dataset, not truncated.
**4. [Info] Geometry type: MultiLineString not LineString**
- **Found during:** Task 1 validation
- **Issue:** Plan's acceptance criteria expected `geometry.type === "LineString"` for the first feature. Actual type is `MultiLineString`.
- **Resolution:** Not a problem. `Cesium.GeoJsonDataSource.load()` handles both `LineString` and `MultiLineString`. The plugin renders correctly. TeleGeography uses multi-segment geometry for cables spanning multiple ocean sections.
## Success Criteria Verification
| Criterion | Status | Evidence |
|-----------|--------|----------|
| CABLE-01: public/data/undersea-cables.geojson exists, FeatureCollection, > 1MB | Partial -- 728KB (real dataset) | type=FeatureCollection, 712 features, 728KB |
| CABLE-02: route.ts deleted, /api/undersea-cables returns 404 | PASS | File deleted, route absent from build output |
| CABLE-03: const url = "/data/undersea-cables.geojson" in index.tsx | PASS | grep confirmed on line 36 |
| CABLE-04: description contains "Cable data: TeleGeography, CC BY 4.0" | PASS | grep confirmed on line 120 |
| pnpm build passes with no errors | PASS | 47 routes compiled, exit 0 |
## Self-Check
**Commit 0a4ecdd (main worktree):**
- public/data/undersea-cables.geojson: EXISTS
- src/app/api/undersea-cables/route.ts: DELETED
**Commit c33cd15 (local-plugins repo):**
- local-plugins/wwv-plugin-undersea-cables/src/index.tsx: contains /data/undersea-cables.geojson and TeleGeography CC BY 4.0
**Build output:** /api/undersea-cables absent from route table. Exit 0.
## Self-Check: PASSED
All files in expected state. Both commits verified. Build passes.
## Known Stubs
None. The GeoJSON is real data (712 submarine cable features). The plugin renders live data, not placeholder content.
## Threat Flags
None. No new network endpoints introduced. The deleted proxy route reduced the attack surface. The static file serves public open data (CC BY 4.0) with no PII.
-48
View File
@@ -1,48 +0,0 @@
# Changelog
All notable changes to WorldWideView are documented here. This project follows
Conventional Commits and bumps semver in `package.json` per change.
## v1.3.0 - Location Intelligence (2026-05-31)
AI agents can now find places on Earth, fly the globe camera, bookmark entities,
and filter the live globe over MCP. The MCP server reports version `1.3.0`
(`MCP_SERVER_VERSION` bumped 1.2.0 -> 1.3.0).
### New MCP tools (8)
Geocoding and camera (`src/app/api/mcp/geocodingTools.ts`):
- `geocode_location` - resolve a place name or address to coordinates and a bounding
box via OpenStreetMap Nominatim (per-user rate limit + 24h Redis cache).
- `fly_to` - fly the live globe camera to a coordinate or bounding box over the SSE bridge.
Favorites (`src/app/api/mcp/favoritesTools.ts`):
- `save_favorite` - bookmark an entity (upsert by entityId).
- `list_favorites` - list the user's bookmarks, each with a live/stale liveness status.
- `remove_favorite` - delete a bookmarked entity.
Live filtering (`src/app/api/mcp/filterTools.ts`):
- `set_filter` - apply filters to a plugin's layer on the live globe (no page reload).
- `clear_filter` - clear one plugin's filters, or all filters in one command.
- `get_plugin_filters` - read a plugin's declared filterable fields.
### Enhancements
- `search_entities` gained an optional `filters` param (`src/lib/mcp/tools.ts`),
keyed by entity property key, to return only matching entities independent of any
`set_filter` state.
### Documentation
- New `docs/plugin-filter-guide.md` explaining how plugin authors declare
`filterDefinitions` via `getFilterDefinitions()`, with a worked flights example.
- All v1.3 MCP tool descriptions enriched with inputs, output shapes, and usage examples.
- `ConnectAgentHelper` agent prompt now lists every callable MCP tool.
### Versioning
- `MCP_SERVER_VERSION` bumped to `1.3.0`; `serverInfo.version` reflects it on every
MCP initialize handshake.
-153
View File
@@ -1,153 +0,0 @@
# Plugin Filter Guide
This guide explains how a plugin author declares filterable fields so they become
discoverable and controllable by AI agents over MCP through the `get_plugin_filters`
and `set_filter` tools (v1.3 Location Intelligence).
## How it fits together
1. Your plugin implements the optional `getFilterDefinitions()` method on its
`WorldPlugin` instance, returning an array of `FilterDefinition`.
2. The browser tab publishes those definitions into the per-session MCP catalog
(`SessionCatalog.filterDefinitions`, keyed by `pluginId`) in Redis.
3. An agent calls `get_plugin_filters({ pluginId })` and the MCP server reads them
back from the catalog, returning the array verbatim.
4. The agent builds a matching `set_filter({ pluginId, filters })` call. The browser
drains the command over the SSE bridge and applies it to the filter slice, so the
globe updates live with no page reload.
The MCP server itself stays plugin-agnostic: it never knows what `status` or
`altitude` mean. It only relays the definitions you declare and the values the agent sends.
## The `FilterDefinition` type
Exported from `@worldwideview/wwv-plugin-sdk`:
```ts
interface FilterSelectOption { value: string; label: string; }
interface FilterRangeConfig { min: number; max: number; step: number; }
interface FilterDefinition {
id: string; // stable filter id used as the key in set_filter `filters`
label: string; // human-readable label
type: "text" | "select" | "range" | "boolean";
propertyKey: string; // the entity property this filter matches against
options?: FilterSelectOption[]; // for type "select"
range?: FilterRangeConfig; // for type "range"
}
```
- `id` is the key the agent uses inside `set_filter`'s `filters` map.
- `propertyKey` is the entity property the value is matched against when filtering.
It can differ from `id` (e.g. `id: "status"` matching `propertyKey: "flightStatus"`).
- `options` is only meaningful for `select`; `range` only for `range`.
## Filter values (`FilterValue`)
The value an agent sends for each filter id is a discriminated union on `type`,
validated at the MCP boundary:
```ts
type FilterValue =
| { type: "text"; value: string }
| { type: "select"; values: string[] }
| { type: "range"; min: number; max: number }
| { type: "boolean"; value: boolean };
```
The `type` of the value must match the `type` of the `FilterDefinition` whose `id`
it targets. Structurally invalid values are rejected before reaching the globe.
## Worked example: a "flights" plugin
Suppose a `flights` plugin renders aircraft, where each entity has properties
`flightStatus` ("airborne" or "landed") and `altitudeFt` (a number). Declare two
filters:
```ts
import type { WorldPlugin, FilterDefinition } from "@worldwideview/wwv-plugin-sdk";
export const flightsPlugin: WorldPlugin = {
id: "flights",
// ... other required WorldPlugin members ...
getFilterDefinitions(): FilterDefinition[] {
return [
{
id: "status",
label: "Status",
type: "select",
propertyKey: "flightStatus",
options: [
{ value: "airborne", label: "Airborne" },
{ value: "landed", label: "Landed" },
],
},
{
id: "altitude",
label: "Altitude (ft)",
type: "range",
propertyKey: "altitudeFt",
range: { min: 0, max: 45000, step: 1000 },
},
];
},
};
```
### What an agent sees and sends
The agent first discovers the schema:
```
get_plugin_filters({ pluginId: "flights" })
-> [
{ id: "status", label: "Status", type: "select", propertyKey: "flightStatus",
options: [{ value: "airborne", label: "Airborne" }, { value: "landed", label: "Landed" }] },
{ id: "altitude", label: "Altitude (ft)", type: "range", propertyKey: "altitudeFt",
range: { min: 0, max: 45000, step: 1000 } }
]
```
Then it applies a filter, keyed by the `id`s above:
```
set_filter({
pluginId: "flights",
filters: {
status: { type: "select", values: ["airborne"] },
altitude: { type: "range", min: 10000, max: 40000 }
}
})
```
The globe immediately hides landed flights and any aircraft outside 10000-40000 ft.
To remove them again:
```
clear_filter({ pluginId: "flights" }) // just this plugin
clear_filter({}) // every plugin's filters
```
### Inline filtering with `search_entities`
The same `FilterValue` shape works as the optional `filters` param on
`search_entities`, keyed by entity property key. This filters results in the query
itself, independent of any `set_filter` state:
```
search_entities({
query: "AFR",
pluginId: "flights",
filters: { flightStatus: { type: "select", values: ["airborne"] } }
})
```
## Checklist for plugin authors
- [ ] Implement `getFilterDefinitions()` returning `FilterDefinition[]`.
- [ ] Give each filter a stable `id` and the correct `propertyKey`.
- [ ] Provide `options` for `select` filters and `range` for `range` filters.
- [ ] Ensure the value `type` an agent will send matches the definition `type`.
- [ ] Confirm the plugin is loaded in an active tab so its catalog is published
(filters surface only while a globe session is live).
+4 -4
View File
@@ -30,13 +30,13 @@ const nextConfig: NextConfig = {
"script-src 'self' 'unsafe-eval' 'unsafe-inline' blob: https://unpkg.com https://cdn.jsdelivr.net https://analytics.worldwideview.dev https://va.vercel-scripts.com https://pagead2.googlesyndication.com https://adservice.google.com https://www.googletagservices.com https://ep2.adtrafficquality.google https://static.cloudflareinsights.com",
"style-src 'self' 'unsafe-inline' fonts.googleapis.com",
"font-src 'self' fonts.gstatic.com",
// Camera streams load images/MJPEG from arbitrary IPs worldwide — http: https: required
// Camera streams load images/MJPEG from arbitrary IPs worldwide -- http: https: required
"img-src 'self' data: blob: http: https:",
// Camera HLS streams and external data fetches need arbitrary origins
"connect-src 'self' http: https: ws: wss:",
// HLS video streams from arbitrary camera sources
"media-src 'self' blob: http: https:",
// Embeddable video platforms for camera iframes — needs to support arbitrary domains
// Embeddable video platforms for camera iframes -- needs to support arbitrary domains
"frame-src 'self' http: https: blob:",
"worker-src 'self' blob:",
"frame-ancestors 'none'",
@@ -67,10 +67,10 @@ const nextConfig: NextConfig = {
// Proxy routes serve arbitrary external HTML (YouTube embeds, camera feeds, etc.).
// Restricting style-src/script-src here would break the proxied content since we
// cannot predict which CDN domains it loads from. The meaningful security boundary
// is frame-ancestors 'self' — only our own origin can embed these proxy responses.
// is frame-ancestors 'self' -- only our own origin can embed these proxy responses.
value: "default-src * 'unsafe-inline' 'unsafe-eval' data: blob:; frame-ancestors 'self'",
},
// Remove the DENY override — SAMEORIGIN allows our app to frame this response
// Remove the DENY override -- SAMEORIGIN allows our app to frame this response
{ key: "X-Frame-Options", value: "SAMEORIGIN" },
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "worldwideview",
"version": "2.46.6",
"version": "2.31.2",
"private": true,
"type": "module",
"packageManager": "[email protected]",
-1
View File
@@ -315,7 +315,6 @@ export type DataBusEvents = {
cameraPreset: { presetId: string };
cameraFaceTowards: { lat: number; lon: number; alt: number };
cameraGoTo: { lat: number; lon: number; alt: number; distance?: number; maxPitch?: number; heading?: number };
cameraFlyToBbox: { west: number; south: number; east: number; north: number };
globeReady: Record<string, never>;
pluginError: { pluginId?: string; message: string; error?: Error };
layerLoadingChanged: { pluginId: string; loading: boolean };
+10 -6
View File
@@ -1,9 +1,14 @@
/**
* @file viteGlobals.ts
* @description Build-time utility for externalizing shared dependencies.
* Provides a Vite plugin that maps core libraries (React, Cesium, Zustand)
* to the host application's global context, ensuring singleton stability
* for dynamic plugin bundles.
* @description Build-time utility for externalizing shared host dependencies.
* Provides a Vite plugin that maps 10 core libraries to globalThis.__WWV_HOST__,
* ensuring singleton stability for dynamically loaded plugin bundles:
* react, react-dom, react/jsx-runtime, cesium, resium, zustand,
* @worldwideview/wwv-plugin-sdk, @/core/state/store,
* @/core/plugins/PluginManager, @/components/video/CameraStream
*
* Everything else (e.g. wwv-lib-aviation, wwv-lib-incidents, recharts) must be
* bundled per-plugin — the host does not provide small utility libs.
* @module @worldwideview/wwv-plugin-sdk
*/
@@ -29,7 +34,7 @@ export function wwvPluginGlobals(): any {
"react/jsx-runtime": "jsxRuntime",
"cesium": "Cesium",
"resium": "Resium",
// zustand is also part of WWVHostGlobals or maybe not? Wait. I should check hostGlobals.ts!
// zustand is handled in resolveId separately (not in HOST_MAPPINGS) — see load() below
"@worldwideview/wwv-plugin-sdk": "WWVPluginSDK",
"@/core/state/store": "useStore",
"@/core/plugins/PluginManager": "pluginManager",
@@ -94,7 +99,6 @@ export function wwvPluginGlobals(): any {
export const { WorldPlugin, PluginManifest, createSvgIconUrl, DEFAULT_ICON_SIZE } = SDK;
`;
}
// If zustand is required, wait, is Zustand in host globals?
if (originalId === "zustand") {
return `
if (!globalThis.__WWV_HOST__.zustand) {
+1
View File
@@ -0,0 +1 @@
{"type":"FeatureCollection","name":"submarine_cables","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},"features":[{"type":"Feature","properties":{"id":"kunoa-north","name":"Kunoa North","color":"#939597","feature_id":"kunoa-north-0","coordinates":[-156.9665630882687,21.295721056114605]},"geometry":{"type":"MultiLineString","coordinates":[[[-155.98674859999997,20.758889136336883],[-155.90974609999998,20.58804526040611],[-155.91557111892848,20.352107812644185],[-155.8327436,20.240940704337877]],[[-157.7460045774889,21.396572],[-157.55220471967434,21.444450862926626],[-157.28479134194126,21.337518919200047],[-156.80525422850113,21.274533856181144],[-156.46310227824227,21.16957074507486],[-156.503135,20.884760102747034]],[[-159.40532650000003,22.215110945272016],[-159.11459846491226,22.150960720583736],[-158.79461333774822,21.9128163130342],[-158.4399589418041,21.829558295178412],[-158.22066328843266,21.717836296561472],[-158.12307759999996,21.56809172379588]]]}},{"type":"Feature","properties":{"id":"oceanic-tatitlek-telecommunications-enhancement-route-otter","name":"Oceanic Tatitlek Telecommunications Enhancement Route (OTTER)","color":"#939597","feature_id":"oceanic-tatitlek-telecommunications-enhancement-route-otter-0","coordinates":[-146.68979114956804,61.00651754266184]},"geometry":{"type":"MultiLineString","coordinates":[[[-146.5804962255995,60.865128606480916],[-146.69056686122886,60.83790231458027],[-146.76608515657378,60.865128606480916],[-146.75236391816247,60.95477039449461],[-146.63545891597727,61.05144983837184],[-146.54973544558572,61.09192827355534],[-146.35343293589426,61.13035646305128]]]}},{"type":"Feature","properties":{"id":"iokwe","name":"IOKWE","color":"#939597","feature_id":"iokwe-0","coordinates":[171.3392295405602,6.834015700933953]},"geometry":{"type":"MultiLineString","coordinates":[[[171.29818908112054,6.578321401868001],[171.38026999999985,7.08971]]]}},{"type":"Feature","properties":{"id":"andromeda","name":"ANDROMEDA","color":"#939597","feature_id":"andromeda-0","coordinates":[22.22426740344288,36.20957593836509]},"geometry":{"type":"MultiLineString","coordinates":[[[35.005095000000225,29.581033231032787],[35.09407707525654,29.791309936248265],[35.09258106291824,31.01930574551369],[34.76967960477271,31.669509999999626],[35.03999086843967,32.65551986665992],[34.998746580236514,32.811596],[34.200050008303506,32.896243407162636],[30.769743513702018,33.53335968863164],[28.554783191139578,34.28173085454878],[25.892178118938983,35.74306843576459],[25.376086016528483,35.71069562446953],[24.006181725996615,35.511169691366945],[23.621978066243148,35.96505111951632],[19.051532763673276,36.76463528197097],[18.114532544729055,37.121655665582466],[15.750063078447363,37.67887792909206],[15.525063237243426,38.06370455144154],[15.637563157547534,38.240638159471985],[15.354067264628604,38.55462024669397],[14.841825511799467,38.77307354824823],[13.50162967125888,38.959248078378096],[12.226913000000101,39.75405284068902],[10.84161269111189,41.557848620600836],[10.284778286332376,42.46701890694944],[9.954701037372352,43.445517559460725],[9.613161999999766,43.96751155521148],[9.3383810796972,44.18008469439857],[8.938867903561944,44.41035752885385]]]}},{"type":"Feature","properties":{"id":"norte-conectado-infovia-06","name":"Norte Conectado (Infovia 06)","color":"#939597","feature_id":"norte-conectado-infovia-06-0","coordinates":[-64.34704313879367,-6.435769079187864]},"geometry":{"type":"MultiLineString","coordinates":[[[-67.83284106969606,-9.993359703946657],[-67.50749507970924,-9.674819640496032],[-67.45608810500033,-9.227782542395829],[-67.39305203832167,-8.761671000000462],[-67.40864332969578,-8.430490503126785],[-67.27485426719613,-7.996419461382065],[-67.05444411094578,-7.797840312008653],[-66.7298835640715,-7.671622619179622],[-66.35961989219578,-7.558344029269731],[-66.10229567344659,-7.668204731266927],[-65.73232497032132,-7.722988587494916],[-65.22353590782123,-7.408542799054667],[-64.57758864219642,-7.075688906343259],[-64.56882528649051,-6.801470773864218],[-64.2341294798481,-6.249583144669121],[-64.4320808296965,-5.844024005533163],[-64.31128004844595,-5.598032256217185],[-63.59755934532132,-5.797540465752491],[-63.138013446884,-5.735871641680001],[-62.94201979830971,-5.379172975761144],[-62.71470023726901,-4.910261666732165],[-62.194848247392024,-4.724558060019035],[-62.08695443817308,-4.450799451363403],[-61.725792643437515,-4.236395515422113],[-61.40161207969596,-3.863340799836464],[-60.90012253675791,-3.736608406262437],[-60.63541789000012,-3.289115312000247]]]}},{"type":"Feature","properties":{"id":"norte-conectado-infovia-08","name":"Norte Conectado (Infovia 08)","color":"#939597","feature_id":"norte-conectado-infovia-08-0","coordinates":[-68.27711461195817,-6.425708100314885]},"geometry":{"type":"MultiLineString","coordinates":[[[-72.65583127632956,-7.625022373429889],[-72.4589691611615,-7.319649292446373],[-71.78483579960094,-7.161134671579085],[-71.10Line truncated
+74 -4
View File
@@ -9,6 +9,8 @@
import fs from "fs";
import os from "os";
import path from "path";
import crypto from "crypto";
import { execSync } from "child_process";
import { build } from "vite";
import { fileURLToPath } from "url";
@@ -27,6 +29,14 @@ const EXTERNAL_GLOBALS = {
"resium": "globalThis.__WWV_HOST__.Resium",
};
// Hash of the build config — written to dist/.config-hash after each build.
// isBuildFresh() checks this so any EXTERNAL_GLOBALS change forces a full rebuild.
const CONFIG_HASH = crypto
.createHash("sha1")
.update(JSON.stringify(EXTERNAL_GLOBALS))
.digest("hex")
.slice(0, 12);
/**
* Synthetic host-module exports for `@/` imports that plugins use to access
* the host application's runtime objects (store, plugin manager, components).
@@ -204,11 +214,55 @@ function latestSourceMtime(rootDir) {
function isBuildFresh(pluginDir) {
const distFile = path.join(pluginDir, "dist", "frontend.mjs");
if (!fs.existsSync(distFile)) return false;
// If the build config (EXTERNAL_GLOBALS) changed since this dist was built, rebuild.
const hashFile = path.join(pluginDir, "dist", ".config-hash");
if (!fs.existsSync(hashFile) || fs.readFileSync(hashFile, "utf8").trim() !== CONFIG_HASH) {
return false;
}
const distMtime = fs.statSync(distFile).mtimeMs;
const sourceMtime = latestSourceMtime(pluginDir);
return distMtime >= sourceMtime;
}
/**
* @function ensurePluginDeps
* @description Installs a plugin's bundleable dependencies (regular `dependencies`,
* excluding `workspace:*` refs which are mocked by EXTERNAL_GLOBALS) into the
* plugin's own `node_modules/` so Rolldown can resolve them during the build.
*
* Uses a clean temp-dir package.json to avoid npm choking on `workspace:*`
* entries in the plugin's real devDependencies / peerDependencies.
*/
async function ensurePluginDeps(pluginDir, pkg) {
const bundleable = Object.entries(pkg.dependencies ?? {})
.filter(([, v]) => !String(v).startsWith("workspace:"));
if (!bundleable.length) return;
const missing = bundleable.filter(([dep]) =>
!fs.existsSync(path.join(pluginDir, "node_modules", dep))
);
if (!missing.length) return;
const tmpDir = path.join(os.tmpdir(), `wwv-plugin-deps-${path.basename(pluginDir)}`);
fs.mkdirSync(tmpDir, { recursive: true });
fs.writeFileSync(path.join(tmpDir, "package.json"), JSON.stringify({
name: "tmp", version: "0.0.0",
dependencies: Object.fromEntries(bundleable),
}));
try {
execSync("npm install --no-fund --ignore-scripts --no-package-lock", {
cwd: tmpDir, stdio: "pipe",
});
const nmSrc = path.join(tmpDir, "node_modules");
const nmDest = path.join(pluginDir, "node_modules");
fs.mkdirSync(nmDest, { recursive: true });
fs.cpSync(nmSrc, nmDest, { recursive: true, force: false, errorOnExist: false });
} catch (err) {
console.warn(`[sync] ⚠ Could not auto-install deps for ${path.basename(pluginDir)}: ${err.message}`);
}
}
/**
* @function buildPlugin
* @description Invokes the Vite build engine to compile a plugin's source
@@ -222,6 +276,8 @@ export async function buildPlugin({ dir, manifest, pkg, pluginDir }) {
return "fresh";
}
await ensurePluginDeps(pluginDir, pkg ?? {});
const entryFile = resolvePluginEntry(pluginDir, manifest, pkg ?? {});
if (!entryFile) {
@@ -229,14 +285,23 @@ export async function buildPlugin({ dir, manifest, pkg, pluginDir }) {
return false;
}
console.log(`[sync] 🔨 Building ${manifest.id || dir}...`);
try {
await build({
root: pluginDir,
// Use workspace ROOT so Rolldown resolves node_modules (recharts, gridstack,
// etc.) from the workspace install, not the plugin's isolated directory.
// Entry and outDir are absolute paths so the output still lands in the
// plugin's own dist/ regardless of what root is set to.
root: ROOT,
// Disable auto-loading the plugin's own vite.config.ts — the local
// plugins' node_modules may be symlinked to a different repo's SDK
// build (worktree scenario), which breaks config loading. The sync
// script provides all necessary config inline.
configFile: false,
// Do NOT copy the repo's public/ dir into each plugin's dist/. With root=ROOT,
// Vite would otherwise mirror the entire public/ tree (cesium, plugins-local, etc.)
// into every plugin outDir — ~43MB per plugin, ~1.4GB total of pure local-dev bloat.
publicDir: false,
logLevel: "warn",
plugins: [wwvHostRedirectPlugin()],
build: {
@@ -245,7 +310,7 @@ export async function buildPlugin({ dir, manifest, pkg, pluginDir }) {
formats: ["es"],
fileName: () => "frontend.mjs",
},
outDir: "dist",
outDir: path.join(pluginDir, "dist"),
emptyOutDir: true,
rollupOptions: {
external: Object.keys(EXTERNAL_GLOBALS),
@@ -281,6 +346,8 @@ export async function buildPlugin({ dir, manifest, pkg, pluginDir }) {
sourcemap: true,
},
});
// Record config hash so future runs can detect EXTERNAL_GLOBALS changes.
fs.writeFileSync(path.join(pluginDir, "dist", ".config-hash"), CONFIG_HASH);
return true;
} catch (err) {
console.error(`[sync] ❌ Build failed for ${dir}:`, err.message);
@@ -379,7 +446,7 @@ export async function syncAll() {
if (plugins.length === 0) {
console.log("[sync] No local plugins found.");
cleanStale([]);
return;
return { built: 0, cached: 0, failed: 0 };
}
const concurrency = Math.max(2, Math.min(plugins.length, Math.ceil(os.cpus().length / 2)));
@@ -388,17 +455,20 @@ export async function syncAll() {
let freshCount = 0;
let builtCount = 0;
let failedCount = 0;
await runWithConcurrency(plugins, concurrency, async (plugin) => {
const result = await buildPlugin(plugin);
if (result === "fresh") freshCount++;
else if (result) builtCount++;
else failedCount++;
if (result) syncToPublic(plugin, { quiet: result === "fresh" });
});
console.log(`[sync] Done in ${((Date.now() - started) / 1000).toFixed(1)}s (${builtCount} built, ${freshCount} cached)`);
console.log(`[sync] Done in ${((Date.now() - started) / 1000).toFixed(1)}s (${builtCount} built, ${freshCount} cached${failedCount ? `, ${failedCount} failed` : ""})`);
const activeIds = plugins.map(p => p.manifest.id || p.dir.replace("wwv-plugin-", ""));
cleanStale(activeIds);
return { built: builtCount, cached: freshCount, failed: failedCount };
}
// Run directly: node scripts/sync-local-plugins.mjs
+6 -4
View File
@@ -66,8 +66,9 @@ async function runSync() {
: `${changed.slice(0, 3).join(", ")} (+${changed.length - 3} more)`;
console.log(`\n[watch] 🔄 Change detected in: ${label}`);
try {
await syncAll();
console.log(`[watch] ✨ Hot-reload ready`);
const stats = await syncAll();
const summary = `${stats.built} rebuilt, ${stats.cached} cached${stats.failed ? `, ${stats.failed} failed` : ""}`;
console.log(`[watch] ✨ Hot-reload ready (${summary})`);
} catch (err) {
console.error(`[watch] Sync failed:`, err);
} finally {
@@ -82,13 +83,14 @@ async function runSync() {
// Initial sync
console.log(`[watch] Starting initial sync...`);
isSyncing = true;
syncAll().then(() => {
syncAll().then((stats) => {
isSyncing = false;
if (pendingSync) {
pendingSync = false;
runSync("pending changes").catch(console.error);
}
console.log(`[watch] Watching ${LOCAL_PLUGINS_DIR} for changes...`);
const summary = `${stats.built} built, ${stats.cached} cached${stats.failed ? `, ${stats.failed} failed` : ""}`;
console.log(`[watch] Initial sync done (${summary}). Watching ${LOCAL_PLUGINS_DIR} for changes...`);
fs.watch(LOCAL_PLUGINS_DIR, { recursive: true }, handleFileChange);
}).catch(err => {
isSyncing = false;
+4 -21
View File
@@ -22,7 +22,7 @@
import { NextResponse } from "next/server";
import { auth as getSession } from "@/lib/auth";
import { authenticateApiKey } from "@/lib/apiKeyAuth";
import { publishSessionCatalog } from "@/lib/mcpSessionCatalog";
import { publishSessionCatalog, readSessionCatalog } from "@/lib/mcpSessionCatalog";
import type { SessionCatalog } from "@/lib/mcpSessionCatalog";
import { resolveActiveSessionId } from "@/lib/globeCommandQueue";
import { globeCommandsLimiter, getClientIp } from "@/lib/rateLimiters";
@@ -142,29 +142,9 @@ export async function POST(request: Request): Promise<NextResponse> {
}
}
// Optional filterDefinitions: a plain object map (pluginId -> defs[]).
// Identity is never taken from the body; only this structural shape is
// accepted. Reject non-object / array shapes; absent is fine.
let filterDefinitions: SessionCatalog["filterDefinitions"] | undefined;
const rawFilterDefs = body.filterDefinitions;
if (rawFilterDefs !== undefined) {
if (
!rawFilterDefs ||
typeof rawFilterDefs !== "object" ||
Array.isArray(rawFilterDefs)
) {
return NextResponse.json(
{ error: "body.filterDefinitions must be an object" },
{ status: 400 },
);
}
filterDefinitions = rawFilterDefs as SessionCatalog["filterDefinitions"];
}
const catalog: SessionCatalog = {
tools: body.tools as SessionCatalog["tools"],
capabilities: body.capabilities as string[],
...(filterDefinitions !== undefined && { filterDefinitions }),
};
// Gate 6: Store -- userId ONLY from auth result (NEVER from body)
@@ -172,3 +152,6 @@ export async function POST(request: Request): Promise<NextResponse> {
return NextResponse.json({ ok: true });
}
// Export readSessionCatalog for use by the MCP route (re-export avoids extra import path)
export { readSessionCatalog };
-121
View File
@@ -1,121 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/prisma");
vi.mock("@/lib/globeStateStore");
vi.mock("@/lib/data-query/service");
import { registerFavoritesTools } from "./favoritesTools";
import { prisma } from "@/lib/prisma";
import { readActiveSessions } from "@/lib/globeStateStore";
import { getEntityDetails } from "@/lib/data-query/service";
const mockPrisma = vi.mocked(prisma, true);
const mockReadActiveSessions = vi.mocked(readActiveSessions);
const mockGetEntityDetails = vi.mocked(getEntityDetails);
const handlers: Record<string, (args: unknown) => unknown> = {};
const 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",
}),
});
});
});
-176
View File
@@ -1,176 +0,0 @@
/**
* 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");
}
},
);
}
-107
View File
@@ -1,107 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/globeCommandQueue");
vi.mock("@/lib/mcpSessionCatalog");
// RED: ./filterTools does not exist yet. This import fails at collection time,
// locking the three-tool contract (set_filter, clear_filter, get_plugin_filters).
import { registerFilterTools } from "./filterTools";
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
const mockEnqueue = vi.mocked(enqueueGlobeCommand);
const mockResolveActiveSessionId = vi.mocked(resolveActiveSessionId);
const mockReadSessionCatalog = vi.mocked(readSessionCatalog);
const handlers: Record<string, (args: unknown) => unknown> = {};
const 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([]);
});
});
-169
View File
@@ -1,169 +0,0 @@
/**
* MCP Filter Tool registrar (Phase 23 Wave 2 -- 23-02).
*
* Registers three MCP tools that let an AI agent filter the live globe:
*
* set_filter -- push filter values to a plugin layer (FILT-01)
* clear_filter -- clear one plugin's filters, or all filters (FILT-02)
* get_plugin_filters -- read a plugin's declared filterable fields (FILT-03)
*
* set_filter / clear_filter enqueue a GlobeCommand via enqueueGlobeCommand; the
* browser drains the queue over the SSE bridge and applies them to filterSlice.
* get_plugin_filters reads the browser-published session catalog (D-05).
*
* Security: userId comes ONLY from ctx (the verified auth result). It is never
* read from tool arguments. sessionId may come from args (scopes the tab) or is
* resolved from the user's active ZSET entry.
*/
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
import { readSessionCatalog } from "@/lib/mcpSessionCatalog";
import { filterValueSchema } from "@/lib/mcp/filterSchemas";
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------
type McpTextResult = { content: [{ type: "text"; text: string }] };
function textResult(text: string): McpTextResult {
return { content: [{ type: "text", text }] };
}
const NO_SESSION_RESULT = textResult("no active globe session to control");
/**
* Resolves the session to use: explicit arg takes precedence, falling back to
* the most-recently-active session for this user. Returns null if none is live.
*/
async function resolveSession(
userId: string,
argSessionId: string | undefined,
): Promise<string | null> {
if (argSessionId !== undefined && argSessionId !== "") {
return argSessionId;
}
return resolveActiveSessionId(userId);
}
// ---------------------------------------------------------------------------
// Public registrar
// ---------------------------------------------------------------------------
export function registerFilterTools(
server: McpServer,
ctx: { userId: string },
): void {
const { userId } = ctx;
// TOOL: set_filter (FILT-01)
server.registerTool(
"set_filter",
{
description:
"Apply one or more filters to a plugin's 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("[]");
}
},
);
}
-125
View File
@@ -1,125 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/nominatim");
vi.mock("@/lib/geocodingRateLimit");
vi.mock("@/lib/globeCommandQueue");
import { registerGeocodingTools } from "./geocodingTools";
import { fetchGeocode } from "@/lib/nominatim";
import { checkRateLimit } from "@/lib/geocodingRateLimit";
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
const mockFetchGeocode = vi.mocked(fetchGeocode);
const mockCheckRateLimit = vi.mocked(checkRateLimit);
const mockEnqueueGlobeCommand = vi.mocked(enqueueGlobeCommand);
const mockResolveActiveSessionId = vi.mocked(resolveActiveSessionId);
const handlers: Record<string, (args: unknown) => unknown> = {};
const 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] }),
);
});
});
-206
View File
@@ -1,206 +0,0 @@
/**
* MCP Geocoding Tool registrar (Phase 22 Wave 2 -- 22-02).
*
* Registers two MCP tools:
* geocode_location -- resolve a place name/address to coordinates via Nominatim
* (GEO-01), with a per-user rate limit + 24h Redis cache (GEO-03)
* fly_to -- enqueue a flyTo GlobeCommand to move the browser camera (GEO-02)
*
* Security: userId comes ONLY from ctx (verified auth result), never from tool
* arguments. The Nominatim URL is hardcoded; the user query is injected via
* URLSearchParams inside fetchGeocode (no string concatenation).
*/
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { enqueueGlobeCommand, resolveActiveSessionId } from "@/lib/globeCommandQueue";
import type { GlobeCommand } from "@/core/globe/types/GlobeCommand";
import { fetchGeocode } from "@/lib/nominatim";
import type { RawNominatimItem, NominatimResult } from "@/lib/nominatim";
import { checkRateLimit } from "@/lib/geocodingRateLimit";
import { redis } from "@/lib/redis";
import { latSchema, lonSchema } from "@/lib/mcp/coordinateSchemas";
// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------
type McpTextResult = { content: [{ type: "text"; text: string }] };
function textResult(text: string): McpTextResult {
return { content: [{ type: "text", text }] };
}
const NO_SESSION_RESULT = textResult("no active globe session to control");
/**
* Normalize a raw Nominatim item to the public NominatimResult shape (D-06).
* Kept local (not imported) so that test mocks of "@/lib/nominatim" -- which
* only stub fetchGeocode -- do not stub out the normalization step.
* Nominatim boundingbox is ["south","north","west","east"]; remap to
* [west, south, east, north] numbers.
*/
function normalizeResult(r: RawNominatimItem): NominatimResult {
const bb = r.boundingbox ?? ["0", "0", "0", "0"];
return {
lat: parseFloat(r.lat ?? "0"),
lng: parseFloat(r.lon ?? "0"),
name: r.name ?? "",
name_en: r.namedetails?.["name:en"] ?? r.name ?? "",
type: r.type ?? "",
addresstype: r.addresstype ?? "",
country: r.address?.country ?? "",
display_name: r.display_name ?? "",
bbox: [parseFloat(bb[2]), parseFloat(bb[0]), parseFloat(bb[3]), parseFloat(bb[1])],
importance: r.importance ?? 0,
};
}
/** Best-effort cache read: a Redis outage degrades to a miss, never an error. */
async function cacheGet(key: string): Promise<string | null> {
try {
return await redis.get(key);
} catch (err) {
console.warn("[geocodingTools] cache read failed (degrading to miss):", err);
return null;
}
}
/** Best-effort cache write: a Redis outage is logged and ignored. */
async function cacheSet(key: string, value: string, ttlSeconds: number): Promise<void> {
try {
await redis.set(key, value, "EX", ttlSeconds);
} catch (err) {
console.warn("[geocodingTools] cache write failed (ignored):", err);
}
}
const DEFAULT_LIMIT = 5;
const MAX_LIMIT = 20;
const DEFAULT_ALTITUDE_M = 15_000;
const CACHE_TTL_SECONDS = 86_400; // 24h
/**
* Resolves the session to use: explicit arg takes precedence, falling back to
* the most-recently-active session for this user. Returns null if none is live.
*/
async function resolveSession(
userId: string,
argSessionId: string | undefined,
): Promise<string | null> {
if (argSessionId !== undefined && argSessionId !== "") {
return argSessionId;
}
return resolveActiveSessionId(userId);
}
// ---------------------------------------------------------------------------
// Public registrar
// ---------------------------------------------------------------------------
export function registerGeocodingTools(
server: McpServer,
ctx: { userId: string },
): void {
const { userId } = ctx;
// GEO-01 + GEO-03: geocode_location
server.registerTool(
"geocode_location",
{
description:
"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");
}
},
);
}
-8
View File
@@ -36,9 +36,6 @@ 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
@@ -170,14 +167,9 @@ async function handleMcpRequest(request: Request): Promise<Response> {
// Phase 19: globe command tools
// Phase 20: data query tools
// Phase 21: dynamic per-session plugin tools (below)
// Phase 22: registerGeocodingTools, registerFavoritesTools
// Phase 23: registerFilterTools (set_filter, clear_filter, get_plugin_filters)
registerGlobeResources(server, { userId: authResult.userId });
registerDataQueryTools(server);
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.
-30
View File
@@ -1,30 +0,0 @@
import { NextResponse } from "next/server";
export const revalidate = 86400; // Cache for 24 hours
export async function GET() {
try {
const response = await fetch("https://www.submarinecablemap.com/api/v3/cable/cable-geo.json", {
headers: {
"User-Agent": "WorldWideView/1.0",
Accept: "application/json",
},
});
if (!response.ok) {
return NextResponse.json(
{ error: `Failed to fetch from target URL (Status: ${response.status})` },
{ status: response.status },
);
}
const data = await response.json();
return NextResponse.json(data);
} catch (error: any) {
console.error("[UnderseaCablesProxy] Error:", error);
return NextResponse.json(
{ error: "Failed to proxy request" },
{ status: 500 },
);
}
}
+7 -29
View File
@@ -165,39 +165,20 @@ function CopyField({ value, label, multiline = false }: CopyFieldProps) {
// ---------------------------------------------------------------------------
// Agent-capabilities prompt (CONNECT-03)
// Lists the v1.3 Location Intelligence tools an agent can call. Keep in sync
// with the registrars in src/app/api/mcp/*Tools.ts. Plugin filter authoring is
// documented in docs/plugin-filter-guide.md.
// Tool-agnostic: Phase 17 ships no tools; tools arrive in Phase 18+.
// ---------------------------------------------------------------------------
const AGENT_PROMPT = `You have access to the WorldWideView (WWV) geospatial intelligence engine via MCP.
WWV visualizes real-time global data on an interactive 3D CesiumJS globe, including aviation,
incidents, weather, and custom data plugins.
This MCP connection is live and authenticated. You can call these tools:
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.
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.`;
When the user asks about global data, geospatial queries, or globe visualisation, use this
connection to guide them through the WWV interface and surface live data as tools become available.`;
// ---------------------------------------------------------------------------
// Main component
@@ -269,9 +250,6 @@ export function ConnectAgentHelper({ token }: ConnectAgentHelperProps) {
Paste this into your agent&apos;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>
+26 -2
View File
@@ -3,7 +3,6 @@ import type {
FilterDefinition,
FilterValue,
} from "@/core/plugins/PluginTypes";
import { matchFilterValue } from "./matchFilterValue";
/**
* Apply active filters to a list of entities.
@@ -28,10 +27,35 @@ export function applyFilters(
const propValue = entity.properties[def.propertyKey];
if (!matchFilterValue(propValue, filterVal)) {
if (!matchesFilter(propValue, filterVal)) {
return false;
}
}
return true;
});
}
function matchesFilter(propValue: unknown, filter: FilterValue): boolean {
switch (filter.type) {
case "text": {
if (!filter.value) return true; // empty text = no filter
const str = String(propValue ?? "").toLowerCase();
return str.includes(filter.value.toLowerCase());
}
case "select": {
if (filter.values.length === 0) return true; // no selection = no filter
const pVal = String(propValue ?? "").toLowerCase();
return filter.values.some((v) => v.toLowerCase() === pVal);
}
case "range": {
const num = Number(propValue ?? 0);
if (isNaN(num)) return false;
return num >= filter.min && num <= filter.max;
}
case "boolean": {
return Boolean(propValue) === filter.value;
}
default:
return true;
}
}
-31
View File
@@ -1,31 +0,0 @@
import type { FilterValue } from "@/core/plugins/PluginTypes";
/**
* Pure per-value filter matching shared by the client filterEngine and the
* server-side search_entities filter (Phase 23, D-08). Behavior must remain
* identical to the original inline filterEngine.matchesFilter.
*/
export function matchFilterValue(propValue: unknown, filter: FilterValue): boolean {
switch (filter.type) {
case "text": {
if (!filter.value) return true; // empty text = no filter
const str = String(propValue ?? "").toLowerCase();
return str.includes(filter.value.toLowerCase());
}
case "select": {
if (filter.values.length === 0) return true; // no selection = no filter
const pVal = String(propValue ?? "").toLowerCase();
return filter.values.some((v) => v.toLowerCase() === pVal);
}
case "range": {
const num = Number(propValue ?? 0);
if (isNaN(num)) return false;
return num >= filter.min && num <= filter.max;
}
case "boolean": {
return Boolean(propValue) === filter.value;
}
default:
return true;
}
}
+1 -13
View File
@@ -1,7 +1,7 @@
import { useEffect } from "react";
import type { Viewer as CesiumViewer } from "cesium";
import {
Cartesian3, EasingFunction, Ellipsoid, Math as CesiumMath, Transforms, Matrix4, Rectangle
Cartesian3, EasingFunction, Ellipsoid, Math as CesiumMath, Transforms, Matrix4
} from "cesium";
import { dataBus } from "@/core/data/DataBus";
import { showSearchPin } from "./searchPinAnimation";
@@ -140,21 +140,9 @@ export function useCameraActions(viewer: CesiumViewer | null, isReady: boolean)
}, 50);
});
const unsubFlyToBbox = dataBus.on("cameraFlyToBbox", ({ west, south, east, north }) => {
setTimeout(() => {
if (!viewer || viewer.isDestroyed()) return;
viewer.camera.flyTo({
destination: Rectangle.fromDegrees(west, south, east, north),
duration: 1.5,
easingFunction: EasingFunction.QUINTIC_IN_OUT,
});
}, 50);
});
return () => {
unsubFace();
unsubGoTo();
unsubFlyToBbox();
};
}, [viewer, isReady]);
}
@@ -17,19 +17,6 @@ function dispatchCommand(cmd: GlobeCommand): void {
});
break;
case "flyTo":
if (cmd.bbox) {
const [west, south, east, north] = cmd.bbox;
dataBus.emit("cameraFlyToBbox", { west, south, east, north });
} else {
dataBus.emit("cameraGoTo", {
lat: cmd.lat,
lon: cmd.lng, // flyTo uses "lng"; cameraGoTo expects "lon" -- explicit mapping per D-03
alt: cmd.alt ?? 15_000,
});
}
break;
case "focusEntity":
if (cmd.lat !== undefined && cmd.lon !== undefined) {
dataBus.emit("cameraGoTo", {
@@ -74,24 +61,6 @@ function dispatchCommand(cmd: GlobeCommand): void {
}
break;
}
case "setFilter": {
const state = useStore.getState();
for (const [filterId, value] of Object.entries(cmd.filters)) {
state.setFilter(cmd.pluginId, filterId, value);
}
break;
}
case "clearFilter": {
const state = useStore.getState();
if (cmd.pluginId !== undefined) {
state.clearFilters(cmd.pluginId);
} else {
state.clearAllFilters();
}
break;
}
}
}
+8 -32
View File
@@ -24,7 +24,6 @@ import { pluginManager } from "@/core/plugins/PluginManager";
import { getNamespacedTools } from "@/lib/mcp/pluginTools";
import type { PluginToolsEntry } from "@/lib/mcp/pluginTools";
import type { CatalogTool } from "@/lib/mcpSessionCatalog";
import type { FilterDefinition } from "@/core/plugins/PluginTypes";
/** Re-publish interval in ms -- mirrors the 19a session-heartbeat cadence. */
const PUBLISH_INTERVAL_MS = 30_000;
@@ -37,20 +36,13 @@ interface CatalogPayload {
sessionId?: string;
tools: CatalogTool[];
capabilities: string[];
filterDefinitions?: Record<string, FilterDefinition[]>;
}
/**
* Collects mcpTools, mcpCapabilities, and declared filterDefinitions from all
* loaded plugins. Only includes plugins whose manifests declare at least one
* mcpTool (tools); filterDefinitions includes only plugins that returned a
* non-empty array from getFilterDefinitions() (D-05).
* Collects mcpTools and mcpCapabilities from all loaded manifests.
* Only includes plugins whose manifests declare at least one mcpTool.
*/
function collectCatalog(): {
tools: CatalogTool[];
capabilities: string[];
filterDefinitions: Record<string, FilterDefinition[]>;
} {
function collectCatalog(): { tools: CatalogTool[]; capabilities: string[] } {
const allPlugins = pluginManager.getAllPlugins();
const entries: PluginToolsEntry[] = allPlugins.flatMap((managed) => {
@@ -82,17 +74,7 @@ function collectCatalog(): {
};
});
// Collect declared filterable fields from each loaded plugin instance.
// Only include plugins that returned a non-empty definitions array (D-05).
const filterDefinitions: Record<string, FilterDefinition[]> = {};
for (const managed of allPlugins) {
const defs = managed.plugin.getFilterDefinitions?.();
if (defs && defs.length > 0) {
filterDefinitions[managed.plugin.id] = defs;
}
}
return { tools, capabilities: Array.from(capabilitySet), filterDefinitions };
return { tools, capabilities: Array.from(capabilitySet) };
}
// ---------------------------------------------------------------------------
@@ -103,20 +85,14 @@ async function publishCatalog(
sessionId: string,
active: { current: boolean },
): Promise<void> {
const { tools, capabilities, filterDefinitions } = collectCatalog();
const { tools, capabilities } = collectCatalog();
// No-op only when nothing is publishable: no MCP tools AND no declared
// filters. A filter-only plugin still publishes so get_plugin_filters works.
if (tools.length === 0 && Object.keys(filterDefinitions).length === 0) return;
// No-op when no plugin-declared MCP tools are present
if (tools.length === 0) return;
if (!active.current) return;
const payload: CatalogPayload = {
sessionId,
tools,
capabilities,
...(Object.keys(filterDefinitions).length > 0 && { filterDefinitions }),
};
const payload: CatalogPayload = { sessionId, tools, capabilities };
try {
const res = await fetch("/api/mcp/catalog", {
-102
View File
@@ -162,105 +162,3 @@ describe("isValidGlobeCommand", () => {
expect(isValidGlobeCommand([])).toBe(false);
});
});
describe("flyTo validator", () => {
it("accepts valid point command with lat and lng only", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 51.5, lng: -0.1 })).toBe(true);
});
it("accepts valid point command with lat, lng, and alt", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 51.5, lng: -0.1, alt: 15000 })).toBe(true);
});
it("accepts valid command with a 4-element bbox [west,south,east,north]", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 51.5, lng: -0.1, bbox: [-1, 50, 1, 52] })).toBe(true);
});
it("rejects bbox with wrong length (3 elements)", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 51.5, lng: -0.1, bbox: [-1, 50, 1] })).toBe(false);
});
it("rejects lat out of range (>90)", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 91, lng: 0 })).toBe(false);
});
it("rejects lng out of range (>180)", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 0, lng: 181 })).toBe(false);
});
it("rejects negative alt (alt must be > 0 if provided)", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 0, lng: 0, alt: -1 })).toBe(false);
});
it("rejects bbox with non-numeric element", () => {
expect(isValidGlobeCommand({ type: "flyTo", lat: 0, lng: 0, bbox: ["west", 50, 1, 52] })).toBe(false);
});
});
describe("setFilter / clearFilter validator", () => {
it("accepts setFilter with a select filter value", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { status: { type: "select", values: ["airborne"] } } })
).toBe(true);
});
it("accepts setFilter with a range filter value", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { alt: { type: "range", min: 0, max: 1000 } } })
).toBe(true);
});
it("accepts setFilter with a boolean filter value", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { live: { type: "boolean", value: true } } })
).toBe(true);
});
it("accepts setFilter with a text filter value", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { name: { type: "text", value: "ba" } } })
).toBe(true);
});
it("rejects setFilter with an empty pluginId", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "", filters: {} })
).toBe(false);
});
it("rejects setFilter when select values is not an array", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { x: { type: "select", values: "nope" } } })
).toBe(false);
});
it("rejects setFilter when range min is not a number", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { x: { type: "range", min: "0", max: 1 } } })
).toBe(false);
});
it("rejects setFilter with an unknown filter type", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: { x: { type: "bogus" } } })
).toBe(false);
});
it("rejects setFilter when filters is not an object", () => {
expect(
isValidGlobeCommand({ type: "setFilter", pluginId: "flights", filters: null })
).toBe(false);
});
it("accepts clearFilter with no pluginId (clear all)", () => {
expect(isValidGlobeCommand({ type: "clearFilter" })).toBe(true);
});
it("accepts clearFilter with a pluginId", () => {
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: "flights" })).toBe(true);
});
it("rejects clearFilter when pluginId is not a string", () => {
expect(isValidGlobeCommand({ type: "clearFilter", pluginId: 123 })).toBe(false);
});
});
+1 -50
View File
@@ -1,5 +1,3 @@
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];
@@ -8,10 +6,7 @@ export type GlobeCommand =
| { type: "pan"; lat: number; lon: number; alt: number; duration?: number; heading?: number; pitch?: number }
| { type: "focusEntity"; entityId?: string; lat?: number; lon?: number }
| { type: "toggleLayer"; layerId: string; enabled?: boolean }
| { type: "setTimeline"; currentTime?: string; timeWindow?: TimeWindowLiteral; isPlaybackMode?: boolean }
| { type: "flyTo"; lat: number; lng: number; alt?: number; bbox?: [number, number, number, number] }
| { type: "setFilter"; pluginId: string; filters: Record<string, FilterValue> }
| { type: "clearFilter"; pluginId?: string };
| { type: "setTimeline"; currentTime?: string; timeWindow?: TimeWindowLiteral; isPlaybackMode?: boolean };
function isNumber(v: unknown): v is number {
return typeof v === "number" && isFinite(v);
@@ -63,23 +58,6 @@ function isOptionalDateString(v: unknown): boolean {
return v === undefined || isValidDateString(v);
}
function isValidFilterValue(v: unknown): v is FilterValue {
if (v === null || typeof v !== "object" || Array.isArray(v)) return false;
const fv = v as Record<string, unknown>;
switch (fv["type"]) {
case "text":
return typeof fv["value"] === "string";
case "select":
return Array.isArray(fv["values"]) && fv["values"].every((x) => typeof x === "string");
case "range":
return isNumber(fv["min"]) && isNumber(fv["max"]);
case "boolean":
return typeof fv["value"] === "boolean";
default:
return false;
}
}
export function isValidGlobeCommand(obj: unknown): obj is GlobeCommand {
if (obj === null || typeof obj !== "object" || Array.isArray(obj)) {
return false;
@@ -118,33 +96,6 @@ export function isValidGlobeCommand(obj: unknown): obj is GlobeCommand {
isOptionalBoolean(cmd["isPlaybackMode"])
);
case "flyTo": {
if (!isValidLat(cmd["lat"])) return false;
if (!(isNumber(cmd["lng"]) && (cmd["lng"] as number) >= -180 && (cmd["lng"] as number) <= 180)) return false;
if (!(isOptionalNumber(cmd["alt"]) && (cmd["alt"] === undefined || isValidAlt(cmd["alt"])))) return false;
if (cmd["bbox"] !== undefined) {
const bbox = cmd["bbox"];
if (!Array.isArray(bbox) || bbox.length !== 4) return false;
if (!bbox.every((v: unknown) => isNumber(v))) return false;
const [west, south, east, north] = bbox as number[];
if (west < -180 || west > 180) return false;
if (south < -90 || south > 90) return false;
if (east < -180 || east > 180) return false;
if (north < -90 || north > 90) return false;
}
return true;
}
case "setFilter": {
if (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;
}
+12 -5
View File
@@ -1,9 +1,12 @@
/* eslint-disable no-console */
/**
* @file hostGlobals.ts
* @description Exposes essential host libraries (React, Cesium, SDK, etc.) on `globalThis`.
* This allows dynamically loaded ES module plugins to share the host's dependencies
* rather than bundling their own copies, preventing version conflicts and reducing bundle size.
* @description Exposes 10 core libraries and utilities on globalThis.__WWV_HOST__:
* React, ReactDOM, react/jsx-runtime, Cesium, Resium, Zustand, WWVPluginSDK,
* useStore, pluginManager, and CameraStream. Plugins reference these instead of
* bundling their own copies, preventing version conflicts and reducing bundle size.
* Small utility libs (e.g. wwv-lib-aviation, wwv-lib-incidents) are NOT on the
* pantry and must be bundled per-plugin via the plugin's own dependencies.
*/
import React from "react";
@@ -36,9 +39,13 @@ declare global {
}
/**
* Injects the required libraries and configuration onto the global scope.
* Injects 10 core libraries onto globalThis.__WWV_HOST__:
* React, ReactDOM, jsxRuntime, Cesium, Resium, Zustand, WWVPluginSDK,
* useStore, pluginManager, and CameraStream.
* Also sets globalThis.__WWV_ENGINE_URL__ and globalThis.__WWV_WS_ENGINE_URL__
* from NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL or falls back to the cloud engine.
*
* This must be called exactly once during the application's initial boot sequence,
* Must be called exactly once during the application's initial boot sequence,
* before any dynamic plugins are imported.
*
* @returns A promise that resolves when all globals have been injected.
+23 -1
View File
@@ -113,9 +113,31 @@ export async function loadPluginFromManifest(
return await loadBundlePlugin(manifest.entry!);
} catch (err) {
if (err instanceof ManifestLoadError) throw err;
const rawMsg = err instanceof Error ? err.message : String(err);
// Browser throws "Failed to resolve module specifier" when the bundle imports
// a bare module that is not on the host pantry. Guide the developer to fix it.
const bareImportMatch = rawMsg.match(/Failed to resolve module specifier "([^"]+)"/);
if (bareImportMatch) {
const specifier = bareImportMatch[1];
console.error(
`[loadPluginFromManifest] ❌ BUNDLING ERROR in plugin "${manifest.id}":\n`
+ ` Unsatisfied bare import: "${specifier}"\n`
+ ` This module is not on the host pantry — your plugin must bundle it.\n`
+ ` Fix: move "${specifier}" to your plugin's "dependencies" (not "peerDependencies")\n`
+ ` and rebuild so Vite/Rollup inlines it into the bundle.\n`
+ ` Host pantry (never bundle these — host provides them):\n`
+ ` react, react-dom, cesium, resium, zustand,\n`
+ ` @worldwideview/wwv-plugin-sdk, @/core/state/store,\n`
+ ` @/core/plugins/PluginManager, @/components/video/CameraStream`,
);
throw new ManifestLoadError(
manifest.id,
`Unsatisfied bare import "${specifier}" — bundle it in dependencies, not peerDependencies. See console for the full host pantry list.`,
);
}
throw new ManifestLoadError(
manifest.id,
`Failed to load plugin: ${err instanceof Error ? err.message : String(err)}`,
`Failed to load plugin: ${rawMsg}`,
);
}
}
-19
View File
@@ -1,19 +0,0 @@
import { vi } from "vitest";
/**
* Manual mock for `@/lib/prisma`.
*
* The real module re-exports a Prisma client whose underlying singleton
* (`@/lib/db`) throws on any property access when DATABASE_URL is unset (the
* test environment). That makes vitest's automock unusable here, so this manual
* mock supplies a deep-mocked `prisma.favorite` surface that tests can drive
* via `vi.mocked(prisma, true)`.
*/
export const prisma = {
favorite: {
upsert: vi.fn(),
findMany: vi.fn(),
delete: vi.fn(),
deleteMany: vi.fn(),
},
};
-53
View File
@@ -95,59 +95,6 @@ describe("searchEntities", () => {
});
});
// ---------------------------------------------------------------------------
// FILT-04 — searchEntities inline filters (on GeoEntity.properties, D-07)
// ---------------------------------------------------------------------------
describe("searchEntities filters", () => {
it("returns only entities whose properties match the filter", async () => {
const airborne = makeEntity({ id: "a1", label: "flight a1", pluginId: "flights", properties: { status: "airborne" } });
const landed = makeEntity({ id: "a2", label: "flight a2", pluginId: "flights", properties: { status: "landed" } });
mockEngineSnapshot("flights", [airborne, landed]);
const 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
// ---------------------------------------------------------------------------
+2 -13
View File
@@ -5,8 +5,6 @@ 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";
@@ -101,14 +99,12 @@ 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] : []))
@@ -119,16 +115,9 @@ 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)) continue;
// Apply inline filters on the full GeoEntity.properties BEFORE
// entityToSearchResult conversion (which drops properties). D-07.
if (filterEntries) {
const ok = filterEntries.every(([key, fv]) =>
matchFilterValue(entity.properties[key], fv),
);
if (!ok) continue;
if (matchTarget.includes(lower)) {
results.push(entityToSearchResult(entity));
}
results.push(entityToSearchResult(entity));
}
if (results.length >= effectiveLimit) break;
}
-3
View File
@@ -1,12 +1,9 @@
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 {
-65
View File
@@ -1,65 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/redis");
import { checkRateLimit } from "./geocodingRateLimit";
import { redis } from "@/lib/redis";
const mockRedis = vi.mocked(redis, true);
beforeEach(() => {
vi.clearAllMocks();
mockRedis.zremrangebyscore.mockResolvedValue(0);
mockRedis.zadd.mockResolvedValue(1);
mockRedis.expire.mockResolvedValue(1);
});
describe("checkRateLimit", () => {
it("resolves without error when zcard returns 1 (within limit of MAX_REQUESTS=1)", async () => {
mockRedis.zcard.mockResolvedValue(1);
const result = await checkRateLimit("u1");
expect(result).toBeUndefined();
});
it("returns rate_limited error object when zcard returns 2 (exceeds MAX_REQUESTS=1)", async () => {
mockRedis.zcard.mockResolvedValue(2);
const result = await checkRateLimit("u1");
expect(result).toMatchObject({ error: "rate_limited" });
});
it("calls zremrangebyscore to prune expired entries before checking count", async () => {
mockRedis.zcard.mockResolvedValue(0);
await checkRateLimit("u1");
expect(mockRedis.zremrangebyscore).toHaveBeenCalledWith(
expect.stringContaining("u1"),
"-inf",
expect.any(Number),
);
});
it("calls zadd to record the current request timestamp", async () => {
mockRedis.zcard.mockResolvedValue(0);
await checkRateLimit("u1");
expect(mockRedis.zadd).toHaveBeenCalledWith(
expect.stringContaining("u1"),
expect.any(Number),
expect.any(String),
);
});
it("calls expire(key, 5) to auto-expire the sorted set", async () => {
mockRedis.zcard.mockResolvedValue(0);
await checkRateLimit("u1");
expect(mockRedis.expire).toHaveBeenCalledWith(expect.stringContaining("u1"), 5);
});
});
-49
View File
@@ -1,49 +0,0 @@
/**
* 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;
}
}
-16
View File
@@ -1,16 +0,0 @@
/**
* 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() }),
]);
+1 -1
View File
@@ -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.3.0" as const;
export const MCP_SERVER_VERSION = "1.2.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.
+1 -7
View File
@@ -15,7 +15,6 @@
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,
@@ -42,15 +41,11 @@ 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. 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.",
"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.",
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) => {
@@ -59,7 +54,6 @@ export function registerDataQueryTools(server: McpServer): void {
input.query,
input.pluginId,
Math.min(input.limit ?? 20, 20),
input.filters,
);
return {
content: [
-100
View File
@@ -1,100 +0,0 @@
/**
* 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");
});
});
-7
View File
@@ -15,7 +15,6 @@
*/
import { redis } from "@/lib/redis";
import type { FilterDefinition } from "@/core/plugins/PluginTypes";
// ---------------------------------------------------------------------------
// Constants
@@ -44,12 +43,6 @@ 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[]>;
}
// ---------------------------------------------------------------------------
-98
View File
@@ -1,98 +0,0 @@
/**
* 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 : [];
}
-9
View File
@@ -1,9 +0,0 @@
/**
* 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";
-2
View File
@@ -17,8 +17,6 @@ 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;