Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat: add experimental @kepler.gl/mcp package and demo-app WebMCP and MCP harness bridge (#3678)
Xun Libf065c4e5647
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.jsonnew file mode 100644index 000000000..550d35490--- /dev/null+++ b/.agents/plugins/marketplace.json@@ -0,0 +1,21 @@+{+ "name": "kepler-gl",+ "interface": {+ "displayName": "kepler.gl"+ },+ "plugins": [+ {+ "name": "kepler-gl",+ "source": {+ "source": "local",+ "path": "./plugins/kepler.gl"+ },+ "policy": {+ "installation": "AVAILABLE",+ "authentication": "ON_INSTALL"+ },+ "category": "Data Visualization",+ "description": "kepler.gl skills for AI assistants: create standalone HTML maps from Python data with keplergl, and drive a live kepler.gl map with map.* commands (layers, time animation, basemaps)."+ }+ ]+}diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonnew file mode 100644index 000000000..414c31c05--- /dev/null+++ b/.claude-plugin/marketplace.json@@ -0,0 +1,16 @@+{+ "name": "kepler-gl",+ "owner": {+ "name": "kepler.gl",+ "url": "https://github.com/keplergl"+ },+ "description": "kepler.gl plugins for AI assistants.",+ "plugins": [+ {+ "name": "kepler-gl",+ "source": "./plugins/kepler.gl",+ "description": "kepler.gl skills for AI assistants: create standalone HTML maps from Python data with keplergl, and drive a live kepler.gl map with map.* commands (layers, time animation, basemaps).",+ "category": "Data Visualization"+ }+ ]+}diff --git a/.github/workflows/publish-plugin.yml b/.github/workflows/publish-plugin.ymlnew file mode 100644index 000000000..36bb90802--- /dev/null+++ b/.github/workflows/publish-plugin.yml@@ -0,0 +1,80 @@+name: Publish kepler.gl Plugin++on:+ push:+ paths:+ - 'plugins/kepler.gl/**'+ - '.claude-plugin/marketplace.json'+ - '.agents/plugins/marketplace.json'+ - 'src/mcp/skill/kepler/**'+ - 'scripts/validate-plugin-manifests.js'+ tags:+ - 'plugin-v*'+ workflow_dispatch:++jobs:+ validate-and-package:+ runs-on: ubuntu-latest+ permissions:+ contents: write++ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-node@v4+ with:+ node-version-file: '.nvmrc'++ - name: Validate manifests and shared skill content+ run: node scripts/validate-plugin-manifests.js++ - name: Read plugin version+ id: version+ run: |+ VERSION=$(node -p "require('./plugins/kepler.gl/plugin.json').version")+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"++ # One package per client, each carrying only the manifest that client+ # reads. Skills and assets are identical in all of them.+ - name: Build client packages+ run: |+ set -euo pipefail+ build() {+ name="$1"+ keep="$2"+ staging=$(mktemp -d)+ cp -R plugins/kepler.gl "$staging/kepler-gl"+ for manifest in .claude-plugin plugin.json .cursor-plugin; do+ case " $keep " in+ *" $manifest "*) ;;+ *) rm -rf "$staging/kepler-gl/$manifest" ;;+ esac+ done+ find "$staging/kepler-gl" -name '.DS_Store' -delete+ (cd "$staging" && zip -qr "$GITHUB_WORKSPACE/$name.zip" kepler-gl)+ rm -rf "$staging"+ }+ build kepler-gl-claude '.claude-plugin'+ build kepler-gl-codex 'plugin.json'+ build kepler-gl-cursor '.cursor-plugin'++ staging=$(mktemp -d)+ cp -R plugins/kepler.gl "$staging/kepler-gl"+ (cd "$staging" && zip -qr "$GITHUB_WORKSPACE/kepler-gl-plugin-source.zip" kepler-gl)+ rm -rf "$staging"++ - name: Upload packages+ uses: actions/upload-artifact@v4+ with:+ name: kepler-gl-v${{ steps.version.outputs.version }}+ path: kepler-gl-*.zip++ - name: Attach packages to release+ if: startsWith(github.ref, 'refs/tags/plugin-v')+ uses: softprops/action-gh-release@v2+ with:+ files: |+ kepler-gl-claude.zip+ kepler-gl-codex.zip+ kepler-gl-cursor.zip+ kepler-gl-plugin-source.zipdiff --git a/.github/workflows/publish-skill.yml b/.github/workflows/publish-skill.ymldeleted file mode 100644index bd10b1bcf..000000000--- a/.github/workflows/publish-skill.yml+++ /dev/null@@ -1,77 +0,0 @@-name: Publish kepler.gl Skill--on:- push:- paths:- - 'skill/SKILL.md'- - 'skill/skill-references/**'- - 'skill/agents/**'- - 'skill/plugin.json'- tags:- - 'skill-v*'- workflow_dispatch:--jobs:- build-skills:- runs-on: ubuntu-latest- permissions:- contents: write-- steps:- - uses: actions/checkout@v4-- - name: Read skill version- id: version- run: |- VERSION=$(python3 -c "import json; print(json.load(open('skill/plugin.json'))['version'])")- echo "version=$VERSION" >> "$GITHUB_OUTPUT"-- - name: Build Claude skill package- run: |- STAGING=$(mktemp -d)- SKILL_DIR="$STAGING/kepler.gl"- mkdir -p "$SKILL_DIR"-- cp skill/SKILL.md "$SKILL_DIR/SKILL.md"- cp -r skill/skill-references "$SKILL_DIR/skill-references"-- (cd "$STAGING" && zip -r "$OLDPWD/kepler.gl-claude.zip" kepler.gl)- rm -rf "$STAGING"-- - name: Build Codex skill package- run: |- STAGING=$(mktemp -d)- SKILL_DIR="$STAGING/kepler.gl"- mkdir -p "$SKILL_DIR"-- cp skill/SKILL.md "$SKILL_DIR/SKILL.md"- cp -r skill/skill-references "$SKILL_DIR/skill-references"- cp -r skill/agents "$SKILL_DIR/agents"-- (cd "$STAGING" && zip -r "$OLDPWD/kepler.gl-codex.zip" kepler.gl)- rm -rf "$STAGING"-- - name: Upload Claude skill artifact- uses: actions/upload-artifact@v4- with:- name: kepler.gl-claude-v${{ steps.version.outputs.version }}- path: kepler.gl-claude.zip-- - name: Upload Codex skill artifact- uses: actions/upload-artifact@v4- with:- name: kepler.gl-codex-v${{ steps.version.outputs.version }}- path: kepler.gl-codex.zip-- - name: Build source package- run: |- zip -r kepler.gl-skill-source.zip skill/-- - name: Attach packages to release- if: startsWith(github.ref, 'refs/tags/skill-v')- uses: softprops/action-gh-release@v2- with:- files: |- kepler.gl-claude.zip- kepler.gl-codex.zip- kepler.gl-skill-source.zipdiff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex b8e059b8b..3125eada6 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -22,6 +22,9 @@ jobs:# use Volta to manage yarn/node versions- uses: volta-cli/action@v4+ - name: Validate plugin manifests+ run: node scripts/validate-plugin-manifests.js+- name: Get Yarn cache directoryid: yarn-cache-dirrun: echo "dir=$(yarn config get cacheFolder)" >> "$GITHUB_OUTPUT"diff --git a/examples/demo-app/README.md b/examples/demo-app/README.mdindex b8e4caf5e..f8457d973 100644--- a/examples/demo-app/README.md+++ b/examples/demo-app/README.md@@ -4,14 +4,39 @@ This is the src code of kepler.gl demo app. You can copy this folder out and run> The AI assistant (panel, control, reducer) comes from the published> **`@openassistant/kepler-assistant`** package (`^0.0.12`), which temporarily-> vendors the `@kepler.gl/mcp` map surface (this repo's `src/mcp/` module is-> removed for now). kepler.gl is a **static website**: it only provides the map-> surface *interface* (`@kepler.gl/mcp`) plus a WebSocket listener — it never-> runs an MCP server. Any MCP server (kepler-assistant's own, or any harness-> like Claude Code / Codex driving the map) is **user-provided** and follows the-> `@kepler.gl/mcp` interface, while the command registry executes on the-> in-browser map. See [`docs/NEXT_PLAN.md`](docs/NEXT_PLAN.md) for the permanent-> separation back into a kepler.gl `src/mcp/` module.+> vendors the `@kepler.gl/mcp` map surface. kepler.gl is a **static website**:+> it exposes the map surface *interface* (`@kepler.gl/mcp`) and registers those+> commands with the browser's WebMCP API — it never runs an MCP server.++#### Agent surfaces++The demo exposes the DuckDB-free `map.*` command catalog to agents two ways.+Both are silent — there is no status chip — and share+`kepler-mcp-shared.ts`, which builds the catalog and the redux-backed command+context.++- **WebMCP** (`kepler-webmcp.tsx`) — registers the tools with the browser's+ native [WebMCP](https://webmachinelearning.github.io/webmcp/) API+ (`document.modelContext`, with a `navigator.modelContext` fallback) for+ harnesses that have a built-in browser with WebMCP enabled: Chrome 149+ with+ the origin trial, or `chrome://flags/#enable-webmcp-testing`. Without it the+ surface is inert. Tool names fold `map.load-data` → `map_load_data` (dots are+ common MCP-tool-name poison); the original command id is kept in the+ description and every result string.+- **MCP bridge** (`kepler-mcp-bridge.tsx`) — for harnesses without WebMCP+ (Codex Desktop, the Codex CLI, Claude Code). Build and run the server that+ ships with `@kepler.gl/mcp`:++ ```bash+ yarn workspace @kepler.gl/mcp build+ node src/mcp/dist/cjs/server/stdio.js --map-url http://localhost:8080+ ```++ It listens on a loopback WebSocket and prints a URL carrying a one-time+ token; open that URL and the page connects back. Register the same command as+ a stdio MCP server in your harness, for example+ `codex mcp add kepler -- node src/mcp/dist/cjs/server/stdio.js`.+ Nothing connects unless the page was opened with `?mcp=<token>`.#### Pre requirement- [Node.js ^20.x](http://nodejs.org): We use Node to generate the documentation, run adiff --git a/examples/demo-app/docs/NEXT_PLAN.md b/examples/demo-app/docs/NEXT_PLAN.mddeleted file mode 100644index 9a7c63c95..000000000--- a/examples/demo-app/docs/NEXT_PLAN.md+++ /dev/null@@ -1,80 +0,0 @@-# NEXT_PLAN — The AI assistant's map surface is temporarily vendored--**Status:** Temporary integration (prototyping). See-[`kepler-assistant/NEXT_PLAN.md`](https://github.com/keplergl/kepler-assistant) for the full separation plan.--## What the demo-app consumes--The demo-app's AI assistant is provided by the published-**`@openassistant/kepler-assistant`** package (`^0.0.12` on npm, the-`kepler-assistant` repo). It imports only from `@openassistant/kepler-assistant`:--- `AiAssistantPanel` + `setMapBoundary` (`src/app.tsx`)-- `AiAssistantControlFactory` (`src/factories/map-control.js`)-- `aiAssistantReducer` (`src/reducers/index.js`)--## The temporary integration--`kepler-assistant` normally consumes the reusable kepler.gl map surface:-(`map.*` commands + contract + types + `skill/kepler`). To prototype without-publishing that package, the map surface is **temporarily vendored inside-`kepler-assistant` at `src/mcp/`** (relative imports, no `@kepler.gl/mcp`-dependency). This makes kepler-assistant a single self-contained repo.--## Why `@kepler.gl/mcp` is needed: making kepler.gl work with any AI harness--The next plan is to turn kepler.gl from an app with an in-app chat panel into a-**map surface that any AI harness can operate** — Claude Code, Codex, and other-harness tools (like sqlrooms/ai). `@kepler.gl/mcp` is the enabler for that, which is why it has a-permanent home in the kepler.gl repo rather than staying vendored inside-kepler-assistant.--What `@kepler.gl/mcp` provides:--```-Harness (Claude Code / Codex)- │ MCP (stdio / HTTP) ← MCP is a process/transport protocol- ▼-Local MCP server ── user-provided ── follows the @kepler.gl/mcp interface:- │ kepler-assistant's MCP server, or any MCP- │ server that needs map rendering via kepler.gl- │ WebSocket (page connects out; the local server runs the WS endpoint)- ▼-kepler.gl page (browser, static)- │ hosts @kepler.gl/mcp — the map-surface interface- ▼- ├─ command registry ── executes map.* commands on the in-browser map- ├─ command contract + JSON Schemas + types + skill/kepler- └─ WebSocket transport to the local MCP server-```--Note: importing `@kepler.gl/mcp` does not put a working command registry in the-local MCP server. The two sides consume different parts of the same package —-the MCP server imports the command contract + JSON Schemas + types +-`skill/kepler` to register and validate its tools, while the command registry-only executes in the browser page, where the live map instance exists.--Until `@kepler.gl/mcp` is published, the map surface lives only inside-kepler-assistant's vendored `src/mcp/` (see above), which keeps it out of reach-of external harnesses. Moving it back into the kepler.gl repo and publishing it-(see below) is what unlocks the harness-agnostic plan.--## Next: separate back into the kepler.gl module--The permanent home of the map surface should be the **kepler.gl repo `src/mcp/`**-(package `@kepler.gl/mcp`); When prototyping is done:--1. Copy the final vendored map surface (kepler-assistant `src/mcp/`, minus- `chat-surface.ts`) back into kepler.gl's `src/mcp/`, re-add it to the root- `package.json` workspaces, then publish `@kepler.gl/mcp` from there (see- `kepler-assistant/NEXT_PLAN.md` for the exact steps).-2. kepler-assistant removes the vendored `src/mcp/` and restores- `@kepler.gl/mcp` imports.-3. In this app: add the `@kepler.gl/mcp` esbuild alias and a tsconfig mapping- so the published package resolves through kepler-assistant's externalized- import.-4. Verify: rebuild kepler-assistant, then `yarn start:local` in this folder,- open the AI assistant panel, and drive the registry with- `window.__keplerRoomStore.commands.invokeCommand('map.get-boundary', {})`.-5. Delete this file once separated.diff --git a/examples/demo-app/esbuild.config.mjs b/examples/demo-app/esbuild.config.mjsindex 5408f8c98..1cf041b7f 100644--- a/examples/demo-app/esbuild.config.mjs+++ b/examples/demo-app/esbuild.config.mjs@@ -51,6 +51,7 @@ const KEPLER_SRC_ALIASES = Object.fromEntries('duckdb','layers','localization',+ 'mcp','processors','reducers','schemas',@@ -68,7 +69,10 @@ const getKeplerAliases = () => ({// Chart factories live on a package subpath so the main components barrel// does not load `@kepler.gl/charts`. The `@kepler.gl/components` alias is a// file (index.ts), so this longer key is required.- '@kepler.gl/components/charts': join(SRC_DIR, 'components', 'src', 'charts.ts')+ '@kepler.gl/components/charts': join(SRC_DIR, 'components', 'src', 'charts.ts'),+ // mcp ships the map-management skill markdown as a subpath export; the+ // longer key wins over the `@kepler.gl/mcp` src alias above.+ '@kepler.gl/mcp/skill/kepler/SKILL.md': join(SRC_DIR, 'mcp', 'skill', 'kepler', 'SKILL.md')});/**@@ -177,6 +181,7 @@ const config = {loader: {'.js': 'jsx','.css': 'css',+ '.md': 'text','.ttf': 'file','.woff': 'file','.woff2': 'file'diff --git a/examples/demo-app/src/app.tsx b/examples/demo-app/src/app.tsxindex 0ec976886..02c39b235 100644--- a/examples/demo-app/src/app.tsx+++ b/examples/demo-app/src/app.tsx@@ -12,6 +12,8 @@ import {useParams, useSearchParams, useLocation} from 'react-router-dom';import {WebMercatorViewport} from '@deck.gl/core';import {setMapBoundary} from '@openassistant/kepler-assistant';import {AiAssistantPanel} from '@openassistant/kepler-assistant';+import {KeplerWebMcp} from './kepler-webmcp';+import {KeplerMcpBridge} from './kepler-mcp-bridge';import {panelBorderColor, theme} from '@kepler.gl/styles';import {ParsedConfig} from '@kepler.gl/types';import {getApplicationConfig} from '@kepler.gl/utils';@@ -956,6 +958,11 @@ const App = props => {</>)}</PanelGroup>+ {/* Agent surfaces. Both render nothing: WebMCP registers the tools+ with the browser; the bridge connects out to a local kepler-mcp+ server when the page was opened with ?mcp=<token>. */}+ <KeplerWebMcp reduxStore={reduxStore} />+ <KeplerMcpBridge reduxStore={reduxStore} /></div></GlobalStyle></ThemeProvider>diff --git a/examples/demo-app/src/kepler-mcp-bridge.tsx b/examples/demo-app/src/kepler-mcp-bridge.tsxnew file mode 100644index 000000000..58e8d3764--- /dev/null+++ b/examples/demo-app/src/kepler-mcp-bridge.tsx@@ -0,0 +1,185 @@+/**+ * kepler-mcp-bridge — lets a local `kepler-mcp` process drive this page.+ *+ * Harnesses that do not implement WebMCP (Codex Desktop today, the Codex CLI,+ * Claude Code) reach the map through MCP instead. Browsers cannot LISTEN on a+ * port, so this page is a WebSocket CLIENT: the `kepler-mcp` stdio server+ * prints a URL carrying a one-time token, and opening that URL connects out to+ * `ws://127.0.0.1:<port>/ws?token=...`. Once connected the page advertises the+ * DuckDB-free subset of `getKeplerCommands(ctx)` and answers `call` messages by+ * executing them against the demo's own redux store.+ *+ * Opt-in only: nothing connects unless a token is present. The component+ * renders nothing — the page carries no map-surface status UI — and logs to the+ * console.+ */+import {useEffect, useMemo, useRef} from 'react';+import type {RoomCommandResult} from '@kepler.gl/mcp';+import {buildCatalog, buildKeplerContext, toDescriptor} from './kepler-mcp-shared';++const DEFAULT_PORT = 8765;+const RETRY_MS = 2000;+const MAX_ATTEMPTS = 30;+const TOKEN_KEY = 'kepler-mcp-token';++// The bridge only ever talks to a loopback server. A crafted link must not be+// able to point it at a remote WebSocket (data-exfil / remote-control risk), so+// any host other than loopback is ignored. `0.0.0.0` is deliberately excluded:+// it is the "any address" wildcard, not a loopback address.+const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);+const isLoopbackHost = (host: string) => LOOPBACK_HOSTS.has(host.toLowerCase());++type UrlConfig = {token: string; tokenFromUrl: boolean; host: string; port: number};++function getUrlConfig(): UrlConfig {+ const params = new URLSearchParams(typeof window !== 'undefined' ? window.location.search : '');+ const urlToken = params.get('mcp');+ // sessionStorage (not localStorage): the token is a credential and must not+ // outlive the tab session. A persisted token reconnects on reload, but only+ // to the default loopback host — host/port are honored from the URL alone.+ let stored: string | null = null;+ if (typeof window !== 'undefined') {+ try {+ stored = sessionStorage.getItem(TOKEN_KEY);+ } catch {+ // private mode / blocked storage — treat as absent+ }+ }+ const token = urlToken ?? stored ?? '';+ const requestedHost = params.get('mcpHost');+ const rawHost =+ urlToken != null && requestedHost && isLoopbackHost(requestedHost)+ ? requestedHost+ : 'localhost';+ // IPv6 hosts must be bracketed in a URL (`ws://[::1]:port/...`).+ const host = rawHost.includes(':') && !rawHost.startsWith('[') ? `[${rawHost}]` : rawHost;+ // Clamp to a valid TCP port (1-65535): a crafted ?mcpPort=99999 is truthy+ // after Number() and would produce an invalid WebSocket URL.+ const requestedPort = Number(params.get('mcpPort'));+ const port =+ urlToken != null &&+ Number.isInteger(requestedPort) &&+ requestedPort >= 1 &&+ requestedPort <= 65535+ ? requestedPort+ : DEFAULT_PORT;+ return {token, tokenFromUrl: urlToken != null, host, port};+}++type Props = {+ reduxStore: any;+};++export function KeplerMcpBridge({reduxStore}: Props) {+ const ctx = useMemo(() => buildKeplerContext(reduxStore), [reduxStore]);+ const catalog = useMemo(() => buildCatalog(ctx), [ctx]);+ const commandsById = useMemo(+ () => Object.fromEntries(catalog.map(command => [command.id, command])),+ [catalog]+ );+ const catalogRef = useRef(catalog);+ catalogRef.current = catalog;++ useEffect(() => {+ const config = getUrlConfig();+ if (!config.token) return;++ try {+ sessionStorage.setItem(TOKEN_KEY, config.token);+ } catch {+ // private mode — the bridge still works for this page load+ }++ // Strip the token from the URL so it does not leak through history,+ // screenshots, logs or Referer headers.+ if (config.tokenFromUrl && typeof window !== 'undefined' && window.history?.replaceState) {+ const url = new URL(window.location.href);+ url.searchParams.delete('mcp');+ url.searchParams.delete('mcpHost');+ url.searchParams.delete('mcpPort');+ window.history.replaceState({}, '', url.toString());+ }++ let stopped = false;+ let socket: WebSocket | null = null;+ let attempts = 0;+ let retryTimer: number | null = null;++ const scheduleRetry = () => {+ if (stopped || attempts >= MAX_ATTEMPTS) return;+ retryTimer = window.setTimeout(connect, RETRY_MS);+ };++ const connect = () => {+ if (stopped) return;+ attempts += 1;+ const wsUrl = `ws://${config.host}:${config.port}/ws?token=${encodeURIComponent(+ config.token+ )}`;+ // Never log the token: screenshots and shared console output would leak it.+ const redacted = `ws://${config.host}:${config.port}/ws?token=***`;+ const ws = new WebSocket(wsUrl);+ socket = ws;++ ws.onopen = () => {+ attempts = 0;+ ws.send(JSON.stringify({type: 'hello', commands: catalogRef.current.map(toDescriptor)}));+ console.info(+ `[kepler.gl mcp bridge] connected to ${redacted} · ${catalogRef.current.length} map commands`+ );+ };++ ws.onmessage = async event => {+ let message: any;+ try {+ message = JSON.parse(String(event.data));+ } catch {+ return;+ }+ if (message?.type !== 'call') return;+ const {callId, tool, input} = message as {callId: string; tool: string; input?: unknown};+ let result: RoomCommandResult;+ try {+ const command = commandsById[tool];+ if (!command) throw new Error(`Unknown command: ${tool}`);+ result = (await command.execute(+ {store: undefined, getState: () => undefined, invocation: {surface: 'mcp'}} as any,+ input ?? {}+ )) as RoomCommandResult;+ } catch (error) {+ result = {+ success: false,+ commandId: tool,+ error: error instanceof Error ? error.message : String(error)+ };+ }+ if (ws.readyState === WebSocket.OPEN) {+ ws.send(JSON.stringify({type: 'result', callId, result}));+ }+ };++ ws.onclose = event => {+ if (socket === ws) socket = null;+ if (stopped) return;+ if (event.code === 1008) {+ console.warn(+ '[kepler.gl mcp bridge] the server rejected this token — open the URL printed by kepler-mcp'+ );+ return;+ }+ scheduleRetry();+ };+ };++ connect();++ return () => {+ stopped = true;+ if (retryTimer !== null) window.clearTimeout(retryTimer);+ socket?.close();+ socket = null;+ };+ }, [catalog, commandsById]);++ return null;+}diff --git a/examples/demo-app/src/kepler-mcp-shared.ts b/examples/demo-app/src/kepler-mcp-shared.tsnew file mode 100644index 000000000..b4f333bc0--- /dev/null+++ b/examples/demo-app/src/kepler-mcp-shared.ts@@ -0,0 +1,249 @@+/**+ * Shared plumbing for the demo-app's agent surfaces over the `@kepler.gl/mcp`+ * map.* commands:+ *+ * - `kepler-webmcp.tsx` — native WebMCP registration (`document.modelContext`)+ * for harnesses with a built-in browser (Chrome's agent, Claude Desktop's+ * browser, ...)+ * - `kepler-mcp-bridge.tsx` — WebSocket reverse-connect for harnesses without+ * WebMCP (Codex, Claude Code), opted in with the ?mcp=<token> URL printed by+ * the local `kepler-mcp` server+ *+ * Both surfaces execute commands against the demo's own redux store through+ * `buildKeplerContext` and serve the same DuckDB-free catalog.+ */+import {getKeplerCommands, getValuesFromDataset} from '@kepler.gl/mcp';+import type {+ KeplerContext,+ RoomCommandExecuteOutput,+ RoomCommandResult,+ ToolDescriptor+} from '@kepler.gl/mcp';+import {WebMercatorViewport} from '@deck.gl/core';+import {z} from 'zod';+// The skill markdown ships with the @kepler.gl/mcp package (subpath export), so+// the demo-app folder stays self-contained — no relative path reaching outside+// it into the monorepo layout.+import mapSkillMarkdown from '@kepler.gl/mcp/skill/kepler/SKILL.md';++// map.* commands that need a DuckDB connector / the kepler-app glue+// (`loadTableToKepler`, `loadTableIntoDuckDB`, `getConnector`). The demo+// surfaces (mapping-only bridge / webMCP) do not serve them.+export const DUCKDB_REQUIRED = new Set(['map.create-table', 'map.add-column', 'map.save-data']);++// Mutating map.* commands every agent will reach for without reading the+// skill. Each gets a pointer to kepler.get-map-skill appended to its+// description so the reader tool is impossible to miss.+const SKILL_REQUIRED = new Set([+ 'map.add-layer',+ 'map.update-layer-color',+ 'map.add-time-filter',+ 'map.toggle-time-filter',+ 'map.split-view',+ 'map.load-data',+ 'map.set-basemap'+]);++const SKILL_HINT = `\nREAD THE MAP SKILL FIRST: call kepler.get-map-skill before using this command — it explains layer-type selection, color rules, and the workflow.`;++// The skill markdown is served verbatim, but this demo catalog filters out the+// DuckDB-backed commands. Prepend a note so agents don't get stuck trying+// tools that aren't actually served on the bridge/WebMCP surfaces.+const DUCKDB_UNAVAILABLE_NOTE = `> NOTE: this demo surface does NOT serve the DuckDB-backed commands ${[+ ...DUCKDB_REQUIRED+].join(', ')} — they are filtered out of the catalog. Use the available map.* commands only.`;++/** Live accessors into the demo's own redux store — no kepler-assistant needed. */+export function buildKeplerContext(reduxStore: any): KeplerContext {+ const readMap = () => reduxStore?.getState()?.demo?.keplerGl?.map;+ return {+ getVisState: () => {+ const visState = readMap()?.visState;+ if (!visState) {+ throw new Error('kepler.gl map is not initialized yet.');+ }+ return visState;+ },+ getMapBoundary: () => {+ // Recompute the current viewport corners from the live mapState (same+ // WebMercatorViewport math the app's onViewStateChange uses). Fall back+ // to the assistant slice's stored boundary if mapState lacks a size.+ const mapState = readMap()?.mapState;+ if (mapState?.width && mapState?.height) {+ try {+ const viewport = new WebMercatorViewport(mapState);+ const nw = viewport.unproject([0, 0]);+ const se = viewport.unproject([viewport.width, viewport.height]);+ return {nw: [nw[0], nw[1]], se: [se[0], se[1]]};+ } catch {+ /* fall through to stored boundary */+ }+ }+ // Coerce null → undefined: the assistant slice may hold null, but+ // KeplerContext.getMapBoundary is typed to return the boundary object or+ // undefined only — returning null would break the contract for strict+ // consumers.+ return reduxStore?.getState()?.demo?.aiAssistant?.keplerGl?.mapBoundary ?? undefined;+ },+ getMapboxToken: () => {+ if (typeof window === 'undefined') return undefined;+ try {+ return localStorage.getItem('mapbox-token') ?? undefined;+ } catch {+ // private mode / blocked storage — no token+ return undefined;+ }+ },+ dispatch: (action: any) => reduxStore?.dispatch(action),+ getValuesFromDataset: (datasetName, variableName) => {+ const visState = readMap()?.visState;+ if (!visState) return [];+ return getValuesFromDataset(visState.datasets, visState.layers, datasetName, variableName);+ },+ getDatasetContext: () => {+ // Shape required by map.get-dataset-context: a human line, then a JSON+ // array of {datasetName, datasetId, fields, layers} descriptors.+ const visState = readMap()?.visState;+ const datasets = visState?.datasets;+ const layers = visState?.layers ?? [];+ if (!datasets) return '';+ const context =+ 'Please remember the following datasets and layers for answering the user question:';+ const dataMeta = Object.values(datasets).map((ds: any) => ({+ datasetName: ds?.label ?? ds?.id,+ datasetId: ds?.id,+ // Field name→type mappings as a single object ({colA: typeA, ...}),+ // matching the "field name→type mappings" shape map.get-dataset-context+ // describes — not an array of single-key objects.+ fields: Object.fromEntries((ds?.fields ?? []).map((f: any) => [f.name, f.type])),+ layers: layers+ .filter((layer: any) => layer?.config?.dataId === ds?.id)+ .map((layer: any) => ({+ id: layer.id,+ label: layer.config.label,+ type: layer.type,+ geometryMode: layer.config.columnMode,+ geometryColumns: Object.fromEntries(+ Object.entries(layer.config.columns)+ .filter(([, value]) => value !== null)+ .map(([key, value]) => [+ key,+ typeof value === 'object' && value !== null+ ? Object.fromEntries(Object.entries(value).filter(([, v]) => v !== null))+ : value+ ])+ )+ }))+ }));+ return `${context}\n${JSON.stringify(dataMeta)}`;+ },+ loadTableToKepler: async () => ({+ success: false,+ error: 'map.save-data / loadTableToKepler is not available in the mapping-only bridge.'+ }),+ loadTableIntoDuckDB: async () => {+ throw new Error('DuckDB operations are not available in the mapping-only bridge.');+ },+ getConnector: async () => {+ throw new Error('DuckDB operations are not available in the mapping-only bridge.');+ }+ };+}++/** The DuckDB-free map.* commands this page serves to agents, plus the map skill reader. */+export function buildCatalog(ctx: KeplerContext) {+ const commands = Object.values(getKeplerCommands(ctx)).filter(c => !DUCKDB_REQUIRED.has(c.id));+ return [getMapSkillCommand(), ...commands.map(c => withSkillHint(c))];+}++/**+ * Read-only tool that serves the kepler.gl map-management skill verbatim. First+ * in the catalog so it is the first tool any surface advertises; every mutating+ * command's description also points at it (see `withSkillHint`).+ */+function getMapSkillCommand() {+ return {+ id: 'kepler.get-map-skill',+ name: 'Read map skill',+ group: 'Map',+ description: `READ THE MAP SKILL FIRST — the kepler.gl map-management skill, served verbatim from src/mcp/skill/kepler/SKILL.md.++Call this command BEFORE any other map command. It explains how to choose a layer type (point, arc, line, grid, hexagon, cluster, heatmap, geojson, h3, trip, s2, flow), how to color layers (case-sensitive colorBy, breaks vs unique colorMaps), time animation, split view, and the complete add-layer workflow with JSON examples.++When the user asks for a flow map, "OD flows", "a map of movements" → this skill maps that to layerType "flow" (use "arc" only for straight great-circle lines between un-clustered points).`,+ keywords: ['skill', 'map', 'workflow', 'guide', 'read-me-first'],+ metadata: {readOnly: true, idempotent: true, riskLevel: 'low'},+ execute: async () => ({+ success: true,+ commandId: 'kepler.get-map-skill',+ data: {details: `${DUCKDB_UNAVAILABLE_NOTE}\n\n${mapSkillMarkdown}`}+ })+ };+}++function withSkillHint(cmd: ReturnType<typeof getKeplerCommands>[string]) {+ if (SKILL_REQUIRED.has(cmd.id) && cmd.description) {+ return {...cmd, description: `${cmd.description}${SKILL_HINT}`};+ }+ return cmd;+}++export function toDescriptor(cmd: {+ id: string;+ name: string;+ description?: string;+ group?: string;+ keywords?: string[];+ metadata?: {+ readOnly?: boolean;+ idempotent?: boolean;+ riskLevel?: string;+ requiresConfirmation?: boolean;+ };+ inputSchema?: any;+}): ToolDescriptor {+ let inputSchema: Record<string, unknown> = {type: 'object'};+ if (cmd.inputSchema) {+ try {+ // zod v4 -> JSON Schema. Static import (not require): the demo-app+ // bundles for platform 'browser' / format 'iife', where `require` is+ // undefined — a runtime require would throw and silently fall back to+ // {type: 'object'}, losing tool discoverability and validation.+ inputSchema = (z.toJSONSchema(cmd.inputSchema) ?? {type: 'object'}) as Record<+ string,+ unknown+ >;+ } catch {+ inputSchema = {type: 'object'};+ }+ }+ return {+ id: cmd.id,+ name: cmd.name,+ description: cmd.description,+ group: cmd.group,+ keywords: cmd.keywords,+ inputSchema,+ metadata: cmd.metadata as ToolDescriptor['metadata']+ };+}++export function formatResult(result: RoomCommandExecuteOutput): string {+ // A command may return a bare payload (TData) or void, not just a+ // RoomCommandResult — handle those instead of assuming the result shape.+ if (result && typeof result === 'object' && 'success' in result) {+ const r = result as RoomCommandResult;+ // A structured failure may carry `error` or a `message` field, or neither+ // — treat success:false as a failure regardless so it can't be formatted+ // as a ✓ success and mask the failure in bridge/WebMCP logs.+ if (r.success === false || r.error) {+ const reason = r.error ?? (r as {message?: string}).message ?? 'failed';+ return `✗ ${r.commandId}: ${reason}`;+ }+ const data = r.data as {details?: string} | undefined;+ return data?.details ? `✓ ${data.details}` : `✓ ${r.commandId} ok`;+ }+ return result == null+ ? '✓ ok'+ : `✓ ${typeof result === 'string' ? result : JSON.stringify(result)}`;+}diff --git a/examples/demo-app/src/kepler-webmcp.tsx b/examples/demo-app/src/kepler-webmcp.tsxnew file mode 100644index 000000000..dd47afc2a--- /dev/null+++ b/examples/demo-app/src/kepler-webmcp.tsx@@ -0,0 +1,165 @@+/**+ * kepler-webmcp — exposes the `@kepler.gl/mcp` map.* surface through the+ * browser's native WebMCP API so harnesses with a built-in browser (Chrome's+ * agent, Claude Desktop's browser, Codex, ...) can discover and call the tools+ * directly — no helper process and no WebSocket.+ *+ * WebMCP is a W3C Web Machine Learning CG draft: the page registers tools+ * (`registerTool`) on an in-page model context and the embedded agent invokes+ * them over the JS heap (webmachinelearning/webmcp).+ *+ * Feature detection: the interface has shifted between drafts — current spec+ * puts `modelContext` on `document`, earlier Chromium builds on `navigator`+ * (deprecated in Chromium 150). Native support: Chrome 149+ origin trial, or+ * `chrome://flags/#enable-webmcp-testing`. When neither exists this component+ * is inert.+ *+ * The component renders nothing — the page carries no map-surface status UI.+ * Registration failures are reported to the console only.+ */+import {useEffect, useMemo, useRef} from 'react';+import {buildCatalog, buildKeplerContext, formatResult, toDescriptor} from './kepler-mcp-shared';++/**+ * Minimal structural type for the WebMCP ModelContext (spec: ModelContext on+ * Document, `registerTool(tool, options?) -> Promise<undefined>`). Kept+ * structural because TypeScript DOM libs don't ship WebMCP yet — see the+ * `webmcp-types` npm package for the full surface.+ */+type WebMcpTool = {+ name: string;+ title?: string;+ description: string;+ inputSchema: Record<string, unknown>;+ execute: (input: any, options?: {signal?: AbortSignal}) => Promise<any>;+ annotations?: {readOnlyHint?: boolean; untrustedContentHint?: boolean};+};++type ModelContextLike = {+ registerTool: (tool: WebMcpTool, options?: {signal?: AbortSignal}) => Promise<void> | void;+};++/** `document.modelContext` (current spec) with the pre-150 `navigator.modelContext` fallback. */+function getModelContext(): ModelContextLike | null {+ const win = typeof window === 'undefined' ? null : window;+ if (!win) return null;+ const doc = win.document as any;+ return (doc?.modelContext ?? (win.navigator as any)?.modelContext ?? null) as ModelContextLike;+}++/**+ * WebMCP tool names allow `A-Za-z0-9._-`, but MCP-tool naming in agent+ * harnesses is commonly restricted to `[A-Za-z0-9_-]`, so dots (as in+ * `map.load-data`) are folded to underscores for the registered name. The+ * original command id is kept in the description so callers can still map+ * results back to `RoomCommandResult.commandId`.+ */+function webMcpName(commandId: string): string {+ return commandId.replace(/\./g, '_');+}++type McpWebMcpProps = {+ reduxStore: any;+};++export function KeplerWebMcp({reduxStore}: McpWebMcpProps) {+ const modelContext = useMemo(getModelContext, []);+ const controllerRef = useRef<AbortController | null>(null);++ const ctx = useMemo(() => buildKeplerContext(reduxStore), [reduxStore]);+ const catalog = useMemo(() => buildCatalog(ctx), [ctx]);++ useEffect(() => {+ // Abort the previous registration before re-registering; aborting the+ // controller also unregisters its tools (Chrome 153+).+ controllerRef.current?.abort();+ controllerRef.current = null;++ if (!modelContext || !catalog.length) return;++ const controller = new AbortController();+ controllerRef.current = controller;++ let cancelled = false; // effect re-run / unmount while registrations are in flight++ (async () => {+ const results = await Promise.allSettled(+ catalog.map(async cmd => {+ const desc = toDescriptor(cmd);+ const tool: WebMcpTool = {+ // fold dots to underscores — see webMcpName above+ name: webMcpName(cmd.id),+ title: cmd.name,+ description:+ cmd.id === webMcpName(cmd.id)+ ? cmd.description+ : `${cmd.description ?? cmd.name} (command id: ${cmd.id})`,+ inputSchema: desc.inputSchema,+ annotations: {readOnlyHint: cmd.metadata?.readOnly === true},+ // The agent's transport JSON-serializes the return value, and a+ // rejected execute only surfaces as an opaque UnknownError — so+ // errors are returned as text, never thrown.+ execute: async (input, options) => {+ try {+ const result = await cmd.execute(+ {+ store: undefined,+ getState: () => undefined,+ invocation: {surface: 'webmcp'},+ // Thread the caller's AbortSignal through so agents can+ // cancel long-running commands (e.g. map.load-data).+ signal: options?.signal+ } as any,+ input ?? {}+ );+ return formatResult(result as any);+ } catch (err) {+ return `✗ ${cmd.id}: ${err instanceof Error ? err.message : String(err)}`;+ }+ }+ };+ // Chrome 153+ accepts `{signal}` for unregistration; older drafts+ // take only the tool. Fall back to the single-argument form.+ try {+ await modelContext.registerTool(tool, {signal: controller.signal});+ } catch (err) {+ if (controller.signal.aborted || cancelled) return;+ await modelContext.registerTool(tool);+ }+ })+ );++ if (cancelled || controller.signal.aborted) return;+ const rejected = results.filter(r => r.status === 'rejected');+ if (!rejected.length) return;++ // Nothing else reports WebMCP state — surface a failed registration to+ // whoever is debugging the page rather than failing silently.+ const reasons = rejected+ .map(+ r =>+ (r as PromiseRejectedResult).reason?.message ??+ String((r as PromiseRejectedResult).reason)+ )+ .join('; ');+ console.warn(+ `[kepler.gl webMCP] ${rejected.length} of ${results.length} map tools failed to register: ${reasons}`+ );+ })();++ return () => {+ cancelled = true;+ };+ }, [catalog, modelContext]);++ // Close the controller on unmount so the tools do not outlive the component.+ useEffect(+ () => () => {+ controllerRef.current?.abort();+ controllerRef.current = null;+ },+ []+ );++ return null;+}diff --git a/examples/demo-app/src/md.d.ts b/examples/demo-app/src/md.d.tsnew file mode 100644index 000000000..f3f1daeb0--- /dev/null+++ b/examples/demo-app/src/md.d.ts@@ -0,0 +1,9 @@+/**+ * Ambient declarations for non-code assets the demo-app esbuild bundles.+ * `kepler-mcp-shared.ts` imports the map-management skill markdown as text+ * (esbuild `loader: {'.md': 'text'}`); this keeps editors / tsc quiet.+ */+declare module '*.md' {+ const content: string;+ export default content;+}diff --git a/package.json b/package.jsonindex 209b1260d..3a8e2fd4a 100644--- a/package.json+++ b/package.json@@ -26,6 +26,7 @@"./src/deckgl-arrow-layers","./src/table","./src/layers",+ "./src/mcp","./src/schemas","./src/cloud-providers","./src/processors",@@ -95,6 +96,7 @@"example-version": "babel-node ./scripts/edit-version.js","prettier-all": "prettier --write '{examples,src}/**/src/**/*.{js,tsx,ts}' 'test/**/*.{js,ts,tsx}'","check-circular-deps": "node ./scripts/check-circular-deps.js",+ "validate:plugin": "node ./scripts/validate-plugin-manifests.js","knip": "knip","lint": "yarn typescript && eslint src test webpack examples website --fix --ignore-path .gitignore","lint:check": "yarn typescript && eslint src test webpack examples website --ignore-path .gitignore",diff --git a/plugins/kepler.gl/.claude-plugin/plugin.json b/plugins/kepler.gl/.claude-plugin/plugin.jsonnew file mode 100644index 000000000..31b79f27c--- /dev/null+++ b/plugins/kepler.gl/.claude-plugin/plugin.json@@ -0,0 +1,24 @@+{+ "name": "kepler-gl",+ "version": "0.1.0",+ "description": "kepler.gl skills for AI assistants: create standalone HTML maps from Python data with keplergl, and drive a live kepler.gl map with map.* commands (layers, time animation, basemaps).",+ "author": {+ "name": "kepler.gl",+ "url": "https://github.com/keplergl"+ },+ "homepage": "https://kepler.gl",+ "repository": "https://github.com/keplergl/kepler.gl",+ "license": "MIT",+ "keywords": [+ "maps",+ "geospatial",+ "visualization",+ "kepler.gl",+ "keplergl",+ "GeoJSON",+ "DataFrame",+ "HTML",+ "mcp"+ ],+ "skills": ["./skills/keplergl-python", "./skills/kepler-gl-app"]+}diff --git a/plugins/kepler.gl/.cursor-plugin/plugin.json b/plugins/kepler.gl/.cursor-plugin/plugin.jsonnew file mode 100644index 000000000..c2597bc7c--- /dev/null+++ b/plugins/kepler.gl/.cursor-plugin/plugin.json@@ -0,0 +1,28 @@+{+ "name": "kepler-gl",+ "displayName": "kepler.gl",+ "description": "kepler.gl skills for AI assistants: create standalone HTML maps from Python data with keplergl, and drive a live kepler.gl map with map.* commands (layers, time animation, basemaps).",+ "version": "0.1.0",+ "author": {+ "name": "kepler.gl"+ },+ "publisher": "keplergl",+ "homepage": "https://kepler.gl",+ "repository": "https://github.com/keplergl/kepler.gl",+ "license": "MIT",+ "logo": "assets/icon-large.svg",+ "keywords": [+ "maps",+ "geospatial",+ "visualization",+ "kepler.gl",+ "keplergl",+ "GeoJSON",+ "DataFrame",+ "HTML",+ "mcp"+ ],+ "category": "data-visualization",+ "tags": ["maps", "geospatial", "agent-skills"],+ "skills": "./skills/"+}diff --git a/plugins/kepler.gl/README.md b/plugins/kepler.gl/README.mdnew file mode 100644index 000000000..cb27acd1f--- /dev/null+++ b/plugins/kepler.gl/README.md@@ -0,0 +1,162 @@+# kepler.gl plugin for AI assistants++One plugin, two skills, three client manifests. It replaces the former `skill/`+directory (the Python-only skill, version 0.0.1) and carries the `map.*` app+skill that ships with `src/mcp/`.++| Skill | Surface | Use it when |+|-------|---------|-------------|+| [`keplergl-python`](skills/keplergl-python/SKILL.md) | The `keplergl` Python package (>= 0.4.0) | The deliverable is a Python script or a standalone HTML map |+| [`kepler-gl-app`](skills/kepler-gl-app/SKILL.md) | A running kepler.gl app that exposes the `map.*` commands | The user is looking at an open map and asks to change it |++The two surfaces name the same layer differently — H3 is `hexagonId` in a Python+config but `h3` over MCP, and hexbin is `hexagon` on both. Each skill carries the+same cross-surface reference tables; see [Shared content](#shared-content).++## Layout++```text+plugins/kepler.gl/+├── .claude-plugin/plugin.json Claude Code manifest (skills/ is auto-discovered)+├── plugin.json portable Agent Plugins manifest (Codex; UI under extensions.com.openai)+├── .cursor-plugin/plugin.json Cursor manifest+├── skills/+│ ├── keplergl-python/ SKILL.md + references/+│ └── kepler-gl-app/ SKILL.md+├── assets/ icon-small.svg, icon-large.svg+└── README.md+```++`src/mcp/skill/kepler/` and the plugin's own contents are checked together by+`scripts/validate-plugin-manifests.js`; see [Validation](#validation).++## Install++The marketplace files live at the repository root: `.claude-plugin/marketplace.json`+for Claude Code and `.agents/plugins/marketplace.json` for Codex.++### Claude Code++```bash+claude plugin marketplace add keplergl/kepler.gl+claude plugin install kepler-gl@kepler-gl+```++### Codex++```bash+codex plugin marketplace add keplergl/kepler.gl+codex plugin add kepler-gl@kepler-gl+```++Or run `codex`, then `/plugins` to enable it interactively.++### Cursor++Cursor reads `.cursor-plugin/plugin.json`; skills under `skills/` are+auto-detected. Point Cursor at this plugin directory (or install it from a+marketplace that serves it).++### Plain skill folder++Clients without a plugin loader can take a single skill directly:++```bash+cp -R plugins/kepler.gl/skills/keplergl-python ~/.claude/skills/+cp -R plugins/kepler.gl/skills/kepler-gl-app ~/.agents/skills/+```++## MCP server++`@kepler.gl/mcp` ships a stdio server, `kepler-mcp`. It holds the map tools,+listens on a loopback WebSocket, and prints a URL carrying a one-time token;+open that URL and the kepler.gl page connects back, after which tool calls+execute against the live map. That is how harnesses without WebMCP (Codex+Desktop, the Codex CLI, Claude Code) reach the map. Agents with a built-in+browser can instead use the page's WebMCP registration.++The plugin still ships no `.mcp.json` (Claude) and no `mcp.json` (portable),+because `@kepler.gl/mcp` is not published to npm yet — an `npx` entry would+404. From a checkout the server runs today:++```bash+yarn workspace @kepler.gl/mcp build+node src/mcp/dist/cjs/server/stdio.js --map-url http://localhost:8080+```++Register that command as the `kepler` server in the client, e.g.+`codex mcp add kepler -- node src/mcp/dist/cjs/server/stdio.js`.++Once the package is published, add both files with the same server, bump the+plugin version, and update this section:++```json+{+ "mcpServers": {+ "kepler": {"command": "npx", "args": ["-y", "@kepler.gl/mcp"]}+ }+}+```++## Shared content++The two skills carry four identical blocks, marked in each `SKILL.md`:++```markdown+<!-- shared:layer-types -->+...+<!-- /shared:layer-types -->+```++`layer-types`, `basemaps`, `trip`, and `palettes` describe kepler.gl facts that+hold for both surfaces. They are copied, not extracted into a `shared/`+directory: each skill stays a self-contained folder that can be installed alone.+The validator fails when the copies drift, so edit both `SKILL.md` files in the+same commit. If these blocks grow, moving them into a generated include is the+next step.++## App skill source of truth++`src/mcp/skill/kepler/SKILL.md` is served verbatim by `@kepler.gl/mcp` and the+demo app, so it stays the source of truth. The plugin's+`skills/kepler-gl-app/SKILL.md` is that body verbatim, wrapped in frontmatter+and followed by a cross-surface appendix. Edit the source, then re-copy the body+— the validator checks that the plugin copy still starts with it.++Skill metadata lives in the `SKILL.md` frontmatter only. `skill.yaml` stays in+`src/mcp/skill/kepler/` because the npm package exports it, but it is not copied+here: no plugin client reads it, and a second metadata file in the same folder+would silently disagree with the frontmatter. The validator instead requires the+frontmatter description to equal `skill.yaml`'s.++## Validation++```bash+node scripts/validate-plugin-manifests.js+```++It checks that the three manifests parse, agree on `name`/`version`/`description`,+and follow their own rules (Agent Plugins `$schema` and name grammar, OpenAI+interface metadata and asset paths, Cursor's closed field set and+`author`/`logo`, Claude's kebab-case plugin id); that every skill directory has+a `SKILL.md` whose frontmatter name matches the directory; that both+marketplaces point at `./plugins/kepler.gl`; that the shared blocks match; that+the app skill tracks `src/mcp`; and that every reference link resolves. It needs+only Node — no dependencies.++Where the Claude CLI is available, `claude plugin validate plugins/kepler.gl+--strict` and `claude plugin validate .claude-plugin/marketplace.json --strict`+are the authoritative checks for the Claude side.++## Release++Versions are tracked in all three manifests and must match. To publish:++```bash+git tag plugin-v0.1.0+git push origin plugin-v0.1.0+```++`.github/workflows/publish-plugin.yml` validates the manifests, builds one zip+per client and a source zip, and attaches them to the GitHub release. This+supersedes the old `skill-v*` tag and `publish-skill.yml` workflow.diff --git a/skill/agents/assets/icon-large.svg b/plugins/kepler.gl/assets/icon-large.svgsimilarity index 100%rename from skill/agents/assets/icon-large.svgrename to plugins/kepler.gl/assets/icon-large.svgdiff --git a/skill/agents/assets/icon-small.svg b/plugins/kepler.gl/assets/icon-small.svgsimilarity index 100%rename from skill/agents/assets/icon-small.svgrename to plugins/kepler.gl/assets/icon-small.svgdiff --git a/plugins/kepler.gl/plugin.json b/plugins/kepler.gl/plugin.jsonnew file mode 100644index 000000000..7873234ee--- /dev/null+++ b/plugins/kepler.gl/plugin.json@@ -0,0 +1,44 @@+{+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",+ "name": "kepler-gl",+ "version": "0.1.0",+ "description": "kepler.gl skills for AI assistants: create standalone HTML maps from Python data with keplergl, and drive a live kepler.gl map with map.* commands (layers, time animation, basemaps).",+ "author": {+ "name": "kepler.gl",+ "url": "https://github.com/keplergl"+ },+ "homepage": "https://kepler.gl",+ "repository": "https://github.com/keplergl/kepler.gl",+ "license": "MIT",+ "keywords": [+ "maps",+ "geospatial",+ "visualization",+ "kepler.gl",+ "keplergl",+ "GeoJSON",+ "DataFrame",+ "HTML",+ "mcp"+ ],+ "extensions": {+ "com.openai": {+ "interface": {+ "displayName": "kepler.gl",+ "shortDescription": "Create maps with keplergl or a live kepler.gl app",+ "longDescription": "Two skills in one plugin: build standalone HTML maps from DataFrames, GeoDataFrames, GeoJSON or CSV with the keplergl Python package, and create or restyle layers, animate time, compare split views and change the basemap on a running kepler.gl app through its map.* commands.",+ "developerName": "kepler.gl",+ "category": "Data Visualization",+ "capabilities": ["Read", "Write"],+ "websiteURL": "https://kepler.gl",+ "defaultPrompt": [+ "Create an interactive map visualization from this data",+ "Show these points on the open kepler.gl map, colored by visits"+ ],+ "brandColor": "#1FBAD6",+ "composerIcon": "./assets/icon-small.svg",+ "logo": "./assets/icon-large.svg"+ }+ }+ }+}diff --git a/plugins/kepler.gl/skills/kepler-gl-app/SKILL.md b/plugins/kepler.gl/skills/kepler-gl-app/SKILL.mdnew file mode 100644index 000000000..917f0c3f7--- /dev/null+++ b/plugins/kepler.gl/skills/kepler-gl-app/SKILL.md@@ -0,0 +1,549 @@+---+name: kepler-gl-app+description: Create and configure kepler.gl map layers (point, flow, flowField, arc, line, grid, hexagon, geojson, cluster, heatmap, h3, trip, s2) from datasets, animate them over time, compare them side by side, change the basemap, switch between the 2D, 3D and globe views, update layer colors, load data from a URL, add columns to existing datasets, and read the current map boundary.+---++# Kepler map management++Create and configure kepler.gl map layers from datasets, animate them over+time, compare them side by side, change the basemap, update layer colors,+load data from a URL, add columns to existing datasets, and read the current+map boundary. These are direct map-mutation operations on the kepler.gl map+surface.++## When to use++Use this skill when the user wants to create or reconfigure map layers, change+the appearance or configuration of the map itself, animate data over time, or+compare layers side by side. Examples:+- "Show the shops as points colored by visits"+- "Create a heatmap of the pickup locations"+- "Animate the trips over time"+- "Compare the 2019 and 2024 layers side by side"+- "Change the basemap to dark/satellite/positron"+- "Update the color of the layer to blue"+- "Load data from this URL"+- "Add a new variable / column to an existing dataset"+- "Change a column's type (e.g. make NOSOUTH a string)"+- "Rename a column on the existing dataset"+- "What's the current map boundary/extent?"++Do NOT use this skill for analysis beyond map mutation — spatial statistics,+spatial filtering, colocation, boundary fetching, or charts. Those belong to+your host's analysis skills (e.g. a spatial-analysis skill, a filter skill),+not this one.++## Commands at a glance++| command | purpose |+| ------------------------ | -------------------------------------------------------------- |+| `map.add-layer` | Add a layer (point, flow, flowField, h3, arc, trip, hexagon, grid, cluster, heatmap, geojson, line, s2) to the map. |+| `map.add-time-filter` | Animate a NON-trip layer over a TIMESTAMP/DATE column. |+| `map.toggle-time-filter` | Show/hide the enlarged time controller at the bottom of the map. |+| `map.split-view` | Enable/disable dual-map comparison. |+| `map.update-layer-color` | Update an existing layer's color palette. |+| `map.set-basemap` | Change the basemap style. |+| `map.set-view-mode` | Switch between the flat 2D map, the tilted 3D map and the 3D globe. |+| `map.load-data` | Load data from a URL (no layer — call `map.add-layer`). |+| `map.save-data` | Save a DuckDB table as a map dataset (no layer — call `map.add-layer`). |+| `map.add-column` | Add a column to an EXISTING dataset in place (copy or expression). |+| `map.create-table` | Create a NEW dataset via SQL (original untouched — call `map.add-layer`). |+| `map.get-dataset-context` | List all loaded datasets with their fields and layer configurations. |+| `map.get-boundary` | Read the current map view's bounding box. |++Every command takes a `commandId` (one of the table above) and an `input`+object. Issue commands through your host's map-command dispatcher — the exact+envelope is described in your host's tool listing. In the kepler.gl demo+assistant the dispatcher is the `executeApi` tool with+`apiName: "executeCommand"` and `args: { commandId, input }`.++## Picking a layer type++- Individual locations → `point` (`cluster` for zoom-out density, `heatmap`+ for continuous intensity).+- Density without precomputed cells → `grid` or `hexagon` (auto-binned).+- Pre-aggregated H3 cells → `h3`.+- Origin→destination flows → `flow` (a dedicated flow layer with locations, clustering and weighted edges; requires two point lat/lng pairs — source + destination). Fall back to `arc` only when you want straight great-circle lines between points. For weighted flows optionally pass the magnitude column as `countColumn`.+- Vector fields — wind, currents, downhill terrain flow → `flowField`, animated streamlines over one vector per sample point. This is **not** `flow`: `flow` joins an origin pair to a destination pair, `flowField` draws many short lines through a field of vectors.++- Polylines / polygons → `line` / `geojson`. A decoded GEOMETRY `geom`+ column can be rendered directly with `geojson` — do NOT convert it to+ lat/lon columns or build an intermediate table. For geojson datasets use+ geometryColumn `"_geojson"`.+- Time-animated movement → `trip`.++## Color configuration++- `colorBy` is case-sensitive and must match the column name exactly.+- `simpleColor` is the string `"[r, g, b]"` (e.g. `"[255, 64, 0]"`), not an array.+ It is a single static color for ALL features — NEVER use it for data-driven+ coloring; use `colorBy` + `colorType` + `colorMap` for that.+- For continuous data use `colorType: "breaks"` with a `colorMap` whose last+ entry has `value: null` (the color for the highest bucket):+ `[{value: 0, color: "#fee5d9"}, {value: 50, color: "#fcae91"}, {value: 100, color: "#fb6a4a"}, {value: null, color: "#de2d26"}]`+- For categorical data use `colorType: "unique"`:+ `[{value: "retail", color: "#1f77b4"}, {value: "restaurant", color: "#ff7f0e"}]`+ HARD RULE: the `value`s MUST be the actual unique values in the column.+ Classify the variable with your host's classification tool first and use the+ returned unique values verbatim. NEVER guess category labels from the column+ name — `map.add-layer` rejects values that do not exist in the data.+- For `heatmap`, only `colorRange` (from `colorMap`) takes effect.+- To compute the break values, classify the variable with your host's+ classification tool first and pass the returned breaks as the `colorMap`+ values.+- Generate ColorBrewer-style palettes automatically when the user does not+ specify colors.++### Suggested palettes++- Sequential green: `#ffffcc #c2e699 #78c679 #31a354 #006837 #004529`+- Sequential red: `#fee5d9 #fcae91 #fb6a4a #de2d26 #a50f15`+- Categorical (Tableau 10): `#1f77b4 #ff7f0e #2ca02c #d62728 #9467bd #8c564b`++## Workflow++### 1. Create a layer (`map.add-layer`)++Point layer colored by a continuous variable:++```json+{+ "datasetName": "shops",+ "layerType": "point",+ "layerName": "Shops by visits",+ "colorBy": "visits",+ "colorType": "breaks",+ "colorMap": [+ {"value": 3, "color": "#ffffcc"},+ {"value": 10, "color": "#c2e699"},+ {"value": 25, "color": "#78c679"},+ {"value": 50, "color": "#31a354"},+ {"value": 100, "color": "#006837"},+ {"value": null, "color": "#004529"}+ ]+}+```++Point layer with a uniform color:++```json+{+ "datasetName": "pizza_stores",+ "layerType": "point",+ "layerName": "Pizza stores",+ "simpleColor": "[255, 64, 0]"+}+```++H3 layer:++```json+{+ "datasetName": "visits_h3_r9",+ "layerType": "h3",+ "layerName": "Visits density (h3 r9)",+ "colorBy": "visit_count",+ "colorType": "breaks",+ "colorMap": [+ {"value": 100, "color": "#fee5d9"},+ {"value": 500, "color": "#fcae91"},+ {"value": 2000, "color": "#fb6a4a"},+ {"value": 10000, "color": "#de2d26"},+ {"value": null, "color": "#a50f15"}+ ]+}+```++`map.add-layer` returns `dateTimeColumns` when the dataset has TIMESTAMP/DATE+fields — see "Time animation" below for the follow-up.++### 2. Time animation (NON-trip layers)++When the user asks how something changed/evolved/trended over time and the+source dataset has a TIMESTAMP/DATE column, build a SINGLE layer and animate+it with `map.add-time-filter` — do NOT create a separate static layer per+time step. A stack of snapshot layers does not convey motion and clutters the+map; the animated layer is the deliverable.++- BEFORE creating any layer for a temporal request, DECLARE the expected+ layer count: a change-over-time request ⇒ exactly **1** layer. If you find+ yourself about to issue a 2nd `map.add-layer`, STOP — you have erred.+- `map.add-layer` returns `dateTimeColumns` when timestamp/date fields are+ detected. Pass the first one to `map.add-time-filter`.+- If the column is an integer/string epoch, build a real TIMESTAMP column+ first (Kepler.gl cannot handle negative epochs) — NEVER pass an+ integer/string column directly.+- `map.add-time-filter` input: `{ datasetName, dateTimeColumn, interval? }`.+ `interval` is auto-detected from the data when omitted.+- **Do not retry `map.add-time-filter` more than once.** If it fails, report+ the error and continue — do not loop.+- LAYER ORDERING: create the time-filtered layer LAST so its animation is+ not hidden behind later layers.++```json+{+ "datasetName": "earthquakes",+ "dateTimeColumn": "time"+}+```++### Trip layers (`layerType: "trip"`)++- Trip layers have **built-in** time animation. Do NOT add a+ `map.add-time-filter` for a trip layer — it is unnecessary and can break the+ animation. After creating a trip layer, STOP.+- Strict columns: `id` (shared across a trip's waypoints), `latitude` /+ `longitude` (DOUBLE), `timestamp` (epoch milliseconds). If your epoch is in+ seconds, multiply by 1000.+- Densify sparse O-D data (interpolate lon/lat AND timestamp) or trips+ teleport.++### Flow field layer (`layerType: "flowField"`)++Animated streamlines over a vector field — wind, ocean currents, or downhill+terrain flow. Each row of the dataset is one sample point: a position plus a+direction. It is not the origin→destination `flow` layer — `flow` joins two+point pairs, `flowField` draws many short, continuously moving lines through a+field of vectors.++Pick the mode from the columns the dataset has; `map.add-layer` auto-detects+them in this order and names them in `flowField.*Column` when they differ:++| `flowField.mode` | Columns | Direction comes from |+|------------------|---------|----------------------|+| `UV` (default) | `u`, `v` (+ optional `altitude`) | east/north vector components |+| `SPEED_DIR` | `speed`, `direction` | speed plus compass direction (from) |+| `ELEVATION` | `altitude` | the downhill gradient of a height surface |++Position comes from lat/lng columns — auto-detected, or `latitudeColumn` /+`longitudeColumn` — or from a GeoJSON geometry column when the dataset has one.++Wind encoded as `u`/`v` (no extra parameters needed):++```json+{+ "datasetName": "wind_grid",+ "layerType": "flowField",+ "layerName": "Wind field",+ "flowField": {"colorBySpeed": true}+}+```++Wind encoded as speed + direction under different column names:++```json+{+ "datasetName": "wind_grid",+ "layerType": "flowField",+ "layerName": "Wind field",+ "flowField": {+ "mode": "SPEED_DIR",+ "speedColumn": "wind_speed",+ "directionColumn": "wind_dir"+ }+}+```++- `colorBySpeed: true` colors each streamline by its local speed (using the+ layer's color range); without it the streamlines use `color`. `colorBy` /+ `colorMap` do not apply to this layer.+- Do **not** add `map.add-time-filter` — the flow field animates continuously on+ its own, like a trip layer.+- Streamline density (`linesPerScreen`), `strokeWidth`, `trailLength`,+ `cycleSeconds`, `lineLifetime` and `smoothing` use tuned defaults; they are+ adjusted in the layer panel, not through `map.add-layer`.+- A field layer over a very large grid is expensive: one row per sample point is+ fine, but downsample rasters to roughly 10k–100k points before loading.++### 3. Split map comparison (`map.split-view`)++- `action: "enable"` with `layerIdsForMap0` / `layerIdsForMap1`. Without the+ layer-id arrays all layers show on both panels (no comparison). Use the SAME+ `colorBy` / `colorType` for a fair comparison. `action: "disable"` returns+ to one map.++```json+{+ "action": "enable",+ "layerIdsForMap0": ["layer_2019"],+ "layerIdsForMap1": ["layer_2024"]+}+```++### 4. Toggle the time controller++`map.toggle-time-filter` with `action: "show"` enlarges the time controller+at the bottom of the map; `action: "hide"` collapses it back to the side+panel. A time filter must already exist (created via `map.add-time-filter`).++### 5. Basemap style++```json+{ "styleType": "dark" }+```++Valid `styleType` values: `"no_map"`, `"dark-matter"`, `"positron"`,+`"voyager"`, `"satellite"`, `"dark"`, `"light"`, `"muted"`, `"muted_night"`.+If the user uses a descriptive name, map it to the closest valid `styleType`.+If the request is ambiguous, ask the user to clarify.++### 6. Layer color++```json+{+ "layerId": "layer_xxx",+ "numberOfColors": 5,+ "customColors": ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd"]+}+```++`customColors` is an array of hex color strings; `numberOfColors` must equal+its length. If the user describes colors qualitatively (e.g. "van gogh+starry night", "watercolor"), generate an appropriate palette from the+description. If the user refers to a layer by name rather than id, find the+matching `layerId` from the dataset context.++### 7. Load data from URL++```json+{ "url": "https://..." }+```++This fetches the data, parses it, and adds it to the map as a dataset. It+does NOT create a layer — call `map.add-layer` afterward to visualize the+data (with the layer type, color, and styling you want).++The dataset is named after the URL filename (e.g. `nyc.geojson`). If the+user wants a specific dataset name, pass it as `datasetName`:++```json+{ "url": "https://.../nyc.geojson", "datasetName": "NYC Neighborhoods" }+```++Local files: a local file must be served over http(s) — the browser cannot+fetch `file://` paths. Copy the file into the demo app's served directory+(e.g. `examples/demo-app/dist/`) and pass `/filename.csv`, or serve it with+a CORS-enabled local server (`npx serve --cors -l 8000`) and pass+`http://localhost:8000/filename.csv`. If you have the file content but+cannot serve it (e.g. a remote browser context), pass it as a data URL —+`data:text/csv;base64,<base64 content>` (encode with `base64 -i file.csv`).+This works for small files (up to ~2MB).++For large files (over a few MB), prefer Parquet (`.parquet`) over+GeoJSON/CSV — it loads much faster and is less likely to time out. Convert+GeoJSON to GeoParquet with geopandas (`gdf.to_parquet("data.parquet")`);+kepler reads GeoParquet geometry (WKB) natively, so the map renders the+same lines.++Do NOT create a duplicate dataset just to rename it — never run+`map.create-table` with a plain `SELECT *` (or any copy) to give the loaded+data a friendlier name. `map.create-table` creates a SEPARATE new dataset and+is only for real column transformations; the rename belongs in+`map.load-data`'s `datasetName` (or in the user's hands). Use the loaded+dataset as-is and add the layer to it.++### 8. Map boundary++```json+{}+```++Returns the northwest and southeast coordinates of the current map view:+`{ boundary: { nw: [lon, lat], se: [lon, lat] } }`. When the user says+"current map view", call this to scope spatial queries to the visible area.++### 9. Add / rename / retype a column in an EXISTING dataset (`map.add-column`)++`map.add-column` adds a NEW column to an existing dataset **in place** — the+dataset keeps its name, id, color and layers, and existing columns are+untouched. The new column's values come from exactly ONE of two sources:++- `copyFromColumn` — copy an existing column's values. This is how you rename a+ column in place: to rename `fare` to `fare_amount`, add `fare_amount` copying+ `fare` (the original column stays — the command never removes columns).+- `expression` — an SQL expression computed per row, for a derived variable+ (z-score, ratio, concatenation) OR a type change:+ - z-score: `{ datasetName, newColumnName: "HR60_Z", expression: "(HR60 - AVG(HR60) OVER()) / STDDEV(HR60) OVER()" }`+ - type change: `{ datasetName, newColumnName: "NOSOUTH_str", expression: "NOSOUTH::VARCHAR" }`+ (or `CAST(NOSOUTH AS VARCHAR)`). The new column holds the cast values; the+ original column stays.++```json+{+ "datasetName": "natregimes.geojson",+ "newColumnName": "NOSOUTH_str",+ "expression": "NOSOUTH::VARCHAR"+}+```++`map.create-table` is NOT for this — it builds a separate NEW dataset and leaves+the original untouched. Prefer `map.add-column` whenever the user wants the+change to land in the existing dataset.++### View mode: 2D map, 3D map, or globe (`map.set-view-mode`)++```json+{ "mode": "globe" }+```++- `2d` — flat map, no tilt. The default for city- and region-scale data.+- `3d` — the flat map tilted (pitch 50). For extruded buildings, 3D layers and a+ more dramatic camera; it is **not** a globe.+- `globe` — the 3D globe with atmosphere. Use it when the data spans the world+ (global trips, arcs, lines, points, clusters, hexagons, grids, GeoJSON), so+ the user sees the whole planet instead of a distorted flat world.++Switching to `globe` clamps zoom into the globe's range; switching back to+`2d`/`3d` restores the normal range. The camera mode is independent of the+basemap, so set both when the user asks for a "dark globe" and the like.++- **Keep `flow` and `flowField` layers off the globe.** Neither is supported+ there yet — flow arrows collapse when seen edge-on, and the flow field's+ clipping is mercator-only. Create a global flow field on the 2d map; if the+ user wants a globe view of global movement, use `arc`, `line` or `trip`+ instead, or tell them the field layer needs the flat map.+- Do not switch modes unless the user asks for it or the data's global extent+ makes it clearly better; a map that suddenly becomes a globe is surprising.++## Rules++- Commands that add datasets to the map — `map.load-data`, `map.save-data`,+ `map.create-table` — do NOT auto-create layers. Always call `map.add-layer`+ afterward to visualize the result.+- To add a variable to, rename a column in, or change a column type in an+ EXISTING dataset, use `map.add-column` (copy or expression) — do NOT create a+ new dataset. `map.create-table` only when the user wants a SEPARATE new+ dataset.+- A dataset loaded from a URL keeps the URL filename (or the `datasetName` you+ pass to `map.load-data`). NEVER create a duplicate dataset via+ `map.create-table` just to rename it — use the loaded dataset as-is.+- For change-over-time requests, create exactly ONE animated layer — never+ a separate static layer per time step.+- Do not add a `map.add-time-filter` to a trip layer — trips animate+ themselves.+- If a basemap style name is ambiguous, ask the user to clarify rather than+ guessing.+- For layer color updates, the `layerId` must match an existing layer on the+ map. If the user refers to a layer by name rather than id, use the layer+ name to find the matching layer id from the dataset context.++## Before your final message++- If you created a layer, confirm the layer type, name, and (if any) the+ color field/colorType applied.+- If you added a time filter, confirm the animated column and interval.+- If you enabled split view, confirm which layers are on each panel.+- If you changed the basemap, confirm the new `styleType`.+- If you updated layer colors, confirm the layer id and colors applied.+- If you loaded data, confirm the dataset was loaded and a layer was created.+- If you read the map boundary, report the northwest and southeast+ coordinates.+- If `map.add-layer` returned `dateTimeColumns` and the user asked about+ change over time, you MUST follow up with `map.add-time-filter` on the first+ returned column — do not leave the temporal hint unactioned.++## Cross-surface reference++This plugin also ships the `keplergl-python` skill, which builds standalone HTML+maps from Python. When a request crosses over — the Python script and the open+app must agree on a layer type, a basemap, or a palette — use the shared tables+below, not the Python-side names.++### Layer types++<!-- shared:layer-types -->+**Layer types differ between the two surfaces.** A `keplergl` Python `config`+names the layer in `type`; an MCP `map.add-layer` call names it in `layerType`.+The same spatial concept often uses a different string, and the H3/hexbin pair+is the classic trap:++| Concept | Python config `type` | MCP `layerType` |+|---------|----------------------|-----------------|+| Point | `point` | `point` |+| Cluster | `cluster` | `cluster` |+| Heatmap | `heatmap` | `heatmap` |+| Hexbin (binned from points) | `hexagon` | `hexagon` |+| H3 hexagon (precomputed H3 ids) | `hexagonId` | `h3` |+| Grid (binned from points) | — | `grid` |+| S2 | `s2` | `s2` |+| Arc (great-circle origin→destination) | `arc` | `arc` |+| Flow (weighted origin→destination) | — | `flow` |+| Flow field (streamlines over a vector field) | — | `flowField` |+| Line (polylines) | `line` | `line` |+| GeoJSON / polygon | `geojson` | `geojson` |+| Trip (path + timestamp animation) | `trip` | `trip` |+| Icon | `icon` | — |++- **`hexagonId` is not `hexagon`.** In a Python config, `hexagonId` is H3 and+ `hexagon` is hexbin. Over MCP, H3 is `h3` and `hexagon` is still hexbin.+ Writing `hexagon` for H3 ids gives an empty or wrong layer on both surfaces.+- `—` means the surface has no layer type for that concept; do not substitute+ another one silently.+- MCP layer types are validated against an enum, so an unknown string is+ rejected rather than silently guessed.+- **`flow` is not `flowField`.** `flow` joins an origin point pair to a+ destination point pair; `flowField` draws animated streamlines through one+ vector per sample point (wind, currents, downhill terrain).+<!-- /shared:layer-types -->++### Basemaps++<!-- shared:basemaps -->+Basemap ids are the same on both surfaces, but each surface takes them+differently. Python sets `config.config.mapStyle.styleType`; MCP calls+`map.set-basemap` with `{"styleType": ...}`.++| `styleType` | Needs a Mapbox token |+|-------------|:--------------------:|+| `dark-matter` | no |+| `positron` | no |+| `voyager` | no |+| `no_map` | no |+| `satellite` | yes |+| `dark` | yes |+| `light` | yes |+| `muted` | yes |+| `muted_night` | yes |++- Without a Mapbox token only `dark-matter`, `positron`, `voyager`, and+ `no_map` render.+- `map.set-basemap` rejects any id outside this table (its schema is an enum).+ A Python `mapStyle.styleType` is passed straight to kepler.gl, so it also+ accepts custom styles declared in `mapStyle.mapStyles`.+- The `dark-matter-nolabels`, `positron-nolabels`, and `voyager-nolabels` ids no+ longer exist in kepler.gl; hide basemap labels with+ `mapStyle.visibleLayerGroups.label` instead.+- If a requested style name is ambiguous, ask the user rather than guessing.+<!-- /shared:basemaps -->++### Trips++<!-- shared:trip -->+Trip layers animate themselves. A trip needs an `id` shared across its+waypoints, `latitude` / `longitude`, and a `timestamp`.++- **Never attach a separate time filter to a trip layer** — `map.add-time-filter`+ over MCP, or a `timeRange` filter in a Python config. The trip animation and+ the filter fight over the same clock.+- MCP `map.add-layer` expects epoch **milliseconds** in `timestamp`. A Python+ trip GeoJSON carries the timestamp as the fourth coordinate value,+ `[lng, lat, altitude, timestamp]` (epoch seconds or milliseconds); convert the+ same data to milliseconds before handing it to MCP `map.add-layer`.+- Densify sparse origin→destination data — interpolate longitude, latitude, and+ timestamp together — or the trips teleport between waypoints.+<!-- /shared:trip -->++### Palettes++<!-- shared:palettes -->+Use these palettes when the user does not specify colors. The hex values work+unchanged on both surfaces.++- Sequential green: `#ffffcc #c2e699 #78c679 #31a354 #006837 #004529`+- Sequential red: `#fee5d9 #fcae91 #fb6a4a #de2d26 #a50f15`+- Categorical (Tableau 10): `#1f77b4 #ff7f0e #2ca02c #d62728 #9467bd #8c564b`+- Vibrant (the built-in `Global Warming` range): `#5A1846 #900C3F #C70039 #E3611C #F1920E #FFC300`++For continuous data use a sequential or diverging palette; for categorical data+use distinct hues. Do not reuse one palette for two encodings on the same map.+<!-- /shared:palettes -->diff --git a/skill/SKILL.md b/plugins/kepler.gl/skills/keplergl-python/SKILL.mdsimilarity index 54%rename from skill/SKILL.mdrename to plugins/kepler.gl/skills/keplergl-python/SKILL.mdindex d1a4bd307..344dda2cd 100644--- a/skill/SKILL.md+++ b/plugins/kepler.gl/skills/keplergl-python/SKILL.md@@ -1,5 +1,5 @@----name: kepler.gl+name: keplergl-pythondescription: Create interactive map visualizations and export to standalone HTML using the keplergl Python package. Use when the user wants to create maps, visualize geospatial data, plot locations on a map, or generate HTML map files from DataFrames, GeoDataFrames, GeoJSON, or CSV data with coordinates.---@@ -7,6 +7,21 @@ description: Create interactive map visualizations and export to standalone HTMLUse the `keplergl` Python package to create standalone, interactive HTML map files from geospatial data. The exported HTML loads kepler.gl from CDN — no JavaScript build or server is needed. The resulting `.html` file can be opened directly in any browser.+## Two surfaces++kepler.gl reaches an AI assistant two ways, and this plugin ships a skill for+each:++| Surface | What it does | Skill |+|---------|--------------|-------|+| `keplergl` Python package | Builds a map from data and exports standalone HTML | this skill (`keplergl-python`) |+| Live kepler.gl app over `map.*` commands | Mutates a map that is already open in the app | `kepler-gl-app` |++Use this skill when the deliverable is an HTML file or a Python script. Use+`kepler-gl-app` when the user is looking at a running map and asks you to change+it. The two are not interchangeable — the same layer can need a different type+string on each surface (see [Layer Types](#layer-types)).+## Installation```bash@@ -74,7 +89,29 @@ Read or set the map configuration dict. Use `map.config` after customizing in Ju- For numeric color encoding, if the user does not specify a color scale, use `visualChannels.colorScale: 'quantile'`.- For numeric color encoding, if the user does not specify a palette, use a vibrant sequential/diverging palette (for example, `colorRange.name: 'Global Warming'`).- If the user asks for custom class breaks, compute breakpoints in Python first (for example with `pygeoda`), add a derived classified/bin column to the dataset, and map colors using that derived field.-- **No `SampleMapPanel` in standalone exports.** The `SampleMapPanel` React component lives in the kepler.gl demo app, not in the UMD bundle used by `save_to_html()`. To show a summary/legend overlay, inject an HTML+CSS `<div>` into the exported file (position it at `right: 56px` or `left: 66px` so it doesn't block map controls). See [Summary Panel Overlay](skill-references/summary-panel.md).+- **No `SampleMapPanel` in standalone exports.** The `SampleMapPanel` React component lives in the kepler.gl demo app, not in the UMD bundle used by `save_to_html()`. To show a summary/legend overlay, inject an HTML+CSS `<div>` into the exported file (position it at `right: 56px` or `left: 66px` so it doesn't block map controls). See [Summary Panel Overlay](references/summary-panel.md).++## Color Encoding++Numeric fields are colored with `visualChannels.colorScale` (`quantile` when+the user does not ask for a scale) and a `visConfig.colorRange`. Categorical+fields use `colorScale: 'ordinal'`.++<!-- shared:palettes -->+Use these palettes when the user does not specify colors. The hex values work+unchanged on both surfaces.++- Sequential green: `#ffffcc #c2e699 #78c679 #31a354 #006837 #004529`+- Sequential red: `#fee5d9 #fcae91 #fb6a4a #de2d26 #a50f15`+- Categorical (Tableau 10): `#1f77b4 #ff7f0e #2ca02c #d62728 #9467bd #8c564b`+- Vibrant (the built-in `Global Warming` range): `#5A1846 #900C3F #C70039 #E3611C #F1920E #FFC300`++For continuous data use a sequential or diverging palette; for categorical data+use distinct hues. Do not reuse one palette for two encodings on the same map.+<!-- /shared:palettes -->++`colorRange` is an object (`name`, `type`, `category`, `colors`), not a list of+hex strings — see [Point Map](references/point-map.md) for a complete example.## Supported Data Formats@@ -89,19 +126,64 @@ Read or set the map configuration dict. Use `map.config` after customizing in Ju## Layer Types-| Layer Type | Config `type` | Typical Data |-|------------|---------------|--------------|-| Point | `"point"` | DataFrame with lat/lng columns |-| Arc | `"arc"` | DataFrame with origin/destination lat/lng |-| Line | `"line"` | DataFrame with origin/destination lat/lng |-| Hexbin | `"hexagon"` | DataFrame with lat/lng (aggregated spatially) |-| Heatmap | `"heatmap"` | DataFrame with lat/lng |-| H3 Hexagon | `"hexagonId"` | DataFrame with H3 hex ID column |-| GeoJSON / Polygon | `"geojson"` | GeoJSON or GeoDataFrame with polygon/line geometries |-| Cluster | `"cluster"` | DataFrame with lat/lng |-| Icon | `"icon"` | DataFrame with lat/lng |-| Trip | `"trip"` | GeoJSON with LineString + timestamps |-| S2 | `"s2"` | DataFrame with S2 token column |+<!-- shared:layer-types -->+**Layer types differ between the two surfaces.** A `keplergl` Python `config`+names the layer in `type`; an MCP `map.add-layer` call names it in `layerType`.+The same spatial concept often uses a different string, and the H3/hexbin pair+is the classic trap:++| Concept | Python config `type` | MCP `layerType` |+|---------|----------------------|-----------------|+| Point | `point` | `point` |+| Cluster | `cluster` | `cluster` |+| Heatmap | `heatmap` | `heatmap` |+| Hexbin (binned from points) | `hexagon` | `hexagon` |+| H3 hexagon (precomputed H3 ids) | `hexagonId` | `h3` |+| Grid (binned from points) | — | `grid` |+| S2 | `s2` | `s2` |+| Arc (great-circle origin→destination) | `arc` | `arc` |+| Flow (weighted origin→destination) | — | `flow` |+| Flow field (streamlines over a vector field) | — | `flowField` |+| Line (polylines) | `line` | `line` |+| GeoJSON / polygon | `geojson` | `geojson` |+| Trip (path + timestamp animation) | `trip` | `trip` |+| Icon | `icon` | — |++- **`hexagonId` is not `hexagon`.** In a Python config, `hexagonId` is H3 and+ `hexagon` is hexbin. Over MCP, H3 is `h3` and `hexagon` is still hexbin.+ Writing `hexagon` for H3 ids gives an empty or wrong layer on both surfaces.+- `—` means the surface has no layer type for that concept; do not substitute+ another one silently.+- MCP layer types are validated against an enum, so an unknown string is+ rejected rather than silently guessed.+- **`flow` is not `flowField`.** `flow` joins an origin point pair to a+ destination point pair; `flowField` draws animated streamlines through one+ vector per sample point (wind, currents, downhill terrain).+<!-- /shared:layer-types -->++In a Python config, `columns` carries the field names each layer type needs+(`hex_id` for `hexagonId`, `geojson: '_geojson'` for `geojson`, …) and+`visualChannels` carries the field-to-channel mappings (`colorField`,+`sizeField`, `heightField`, …). The per-layer references below show both.++## Time animation and trips++<!-- shared:trip -->+Trip layers animate themselves. A trip needs an `id` shared across its+waypoints, `latitude` / `longitude`, and a `timestamp`.++- **Never attach a separate time filter to a trip layer** — `map.add-time-filter`+ over MCP, or a `timeRange` filter in a Python config. The trip animation and+ the filter fight over the same clock.+- MCP `map.add-layer` expects epoch **milliseconds** in `timestamp`. A Python+ trip GeoJSON carries the timestamp as the fourth coordinate value,+ `[lng, lat, altitude, timestamp]` (epoch seconds or milliseconds); convert the+ same data to milliseconds before handing it to MCP `map.add-layer`.+- Densify sparse origin→destination data — interpolate longitude, latitude, and+ timestamp together — or the trips teleport between waypoints.+<!-- /shared:trip -->++See [Trip Animation Map](references/trip-animation-map.md) for a full config.## Config Structure@@ -134,28 +216,55 @@ config = {## Basemap Styles-Free (no token needed): `dark-matter`, `positron`, `voyager`, `dark-matter-nolabels`, `positron-nolabels`, `voyager-nolabels`--Mapbox (require `mapbox_token`): `dark`, `light`, `muted`, `muted_night`+<!-- shared:basemaps -->+Basemap ids are the same on both surfaces, but each surface takes them+differently. Python sets `config.config.mapStyle.styleType`; MCP calls+`map.set-basemap` with `{"styleType": ...}`.++| `styleType` | Needs a Mapbox token |+|-------------|:--------------------:|+| `dark-matter` | no |+| `positron` | no |+| `voyager` | no |+| `no_map` | no |+| `satellite` | yes |+| `dark` | yes |+| `light` | yes |+| `muted` | yes |+| `muted_night` | yes |++- Without a Mapbox token only `dark-matter`, `positron`, `voyager`, and+ `no_map` render.+- `map.set-basemap` rejects any id outside this table (its schema is an enum).+ A Python `mapStyle.styleType` is passed straight to kepler.gl, so it also+ accepts custom styles declared in `mapStyle.mapStyles`.+- The `dark-matter-nolabels`, `positron-nolabels`, and `voyager-nolabels` ids no+ longer exist in kepler.gl; hide basemap labels with+ `mapStyle.visibleLayerGroups.label` instead.+- If a requested style name is ambiguous, ask the user rather than guessing.+<!-- /shared:basemaps -->++For the Mapbox styles, pass `mapbox_token=` to `KeplerGl(...)` or to+`save_to_html(...)`; the token is embedded in the exported HTML.## Additional ResourcesFor detailed per-layer-type examples with full config, see supporting files:-- [Point Map](skill-references/point-map.md) — Scatter plot from lat/lng-- [GeoJSON / Polygon Map](skill-references/geojson-polygon-map.md) — Polygons, lines from GeoJSON or GeoDataFrame-- [H3 Hexagon Map](skill-references/h3-hexagon-map.md) — H3 spatial index hexagons-- [Arc / Line Map](skill-references/arc-line-map.md) — Origin-destination connections-- [Heatmap](skill-references/heatmap.md) — Density heatmap from points-- [Hexbin Aggregation Map](skill-references/hexbin-aggregation-map.md) — Spatial binning into hexagons-- [Trip Animation Map](skill-references/trip-animation-map.md) — Animated trips along paths-- [Summary Panel Overlay](skill-references/summary-panel.md) — Inject a SampleMapPanel-style info overlay into the exported HTML (for LISA/cluster counts, model summaries, custom legends)+- [Point Map](references/point-map.md) — Scatter plot from lat/lng+- [GeoJSON / Polygon Map](references/geojson-polygon-map.md) — Polygons, lines from GeoJSON or GeoDataFrame+- [H3 Hexagon Map](references/h3-hexagon-map.md) — H3 spatial index hexagons+- [Arc / Line Map](references/arc-line-map.md) — Origin-destination connections+- [Heatmap](references/heatmap.md) — Density heatmap from points+- [Hexbin Aggregation Map](references/hexbin-aggregation-map.md) — Spatial binning into hexagons+- [Trip Animation Map](references/trip-animation-map.md) — Animated trips along paths+- [Summary Panel Overlay](references/summary-panel.md) — Inject a SampleMapPanel-style info overlay into the exported HTML (for LISA/cluster counts, model summaries, custom legends)## ExamplesFor full config examples per layer type, see:-- [Point Map](skill-references/point-map.md) — includes quantile color + vibrant palette config-- [GeoJSON / Polygon Map](skill-references/geojson-polygon-map.md) — includes choropleth config with `visualChannels`+- [Point Map](references/point-map.md) — includes quantile color + vibrant palette config+- [GeoJSON / Polygon Map](references/geojson-polygon-map.md) — includes choropleth config with `visualChannels`### Quick start (auto-detected layers, no config needed)diff --git a/skill/skill-references/arc-line-map.md b/plugins/kepler.gl/skills/keplergl-python/references/arc-line-map.mdsimilarity index 100%rename from skill/skill-references/arc-line-map.mdrename to plugins/kepler.gl/skills/keplergl-python/references/arc-line-map.mddiff --git a/skill/skill-references/geojson-polygon-map.md b/plugins/kepler.gl/skills/keplergl-python/references/geojson-polygon-map.mdsimilarity index 100%rename from skill/skill-references/geojson-polygon-map.mdrename to plugins/kepler.gl/skills/keplergl-python/references/geojson-polygon-map.mddiff --git a/skill/skill-references/h3-hexagon-map.md b/plugins/kepler.gl/skills/keplergl-python/references/h3-hexagon-map.mdsimilarity index 100%rename from skill/skill-references/h3-hexagon-map.mdrename to plugins/kepler.gl/skills/keplergl-python/references/h3-hexagon-map.mddiff --git a/skill/skill-references/heatmap.md b/plugins/kepler.gl/skills/keplergl-python/references/heatmap.mdsimilarity index 100%rename from skill/skill-references/heatmap.mdrename to plugins/kepler.gl/skills/keplergl-python/references/heatmap.mddiff --git a/skill/skill-references/hexbin-aggregation-map.md b/plugins/kepler.gl/skills/keplergl-python/references/hexbin-aggregation-map.mdsimilarity index 100%rename from skill/skill-references/hexbin-aggregation-map.mdrename to plugins/kepler.gl/skills/keplergl-python/references/hexbin-aggregation-map.mddiff --git a/skill/skill-references/point-map.md b/plugins/kepler.gl/skills/keplergl-python/references/point-map.mdsimilarity index 100%rename from skill/skill-references/point-map.mdrename to plugins/kepler.gl/skills/keplergl-python/references/point-map.mddiff --git a/skill/skill-references/summary-panel.md b/plugins/kepler.gl/skills/keplergl-python/references/summary-panel.mdsimilarity index 100%rename from skill/skill-references/summary-panel.mdrename to plugins/kepler.gl/skills/keplergl-python/references/summary-panel.mddiff --git a/skill/skill-references/trip-animation-map.md b/plugins/kepler.gl/skills/keplergl-python/references/trip-animation-map.mdsimilarity index 100%rename from skill/skill-references/trip-animation-map.mdrename to plugins/kepler.gl/skills/keplergl-python/references/trip-animation-map.mddiff --git a/scripts/validate-plugin-manifests.js b/scripts/validate-plugin-manifests.jsnew file mode 100644index 000000000..8376fcc9c--- /dev/null+++ b/scripts/validate-plugin-manifests.js@@ -0,0 +1,448 @@+#!/usr/bin/env node++// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++// Validates the kepler.gl plugin manifests across the three client formats+// (Claude Code, portable Agent Plugins / Codex, Cursor) plus the two+// marketplace files, and guards the hand-copied content between the two skills.+//+// Run from the repo root: node scripts/validate-plugin-manifests.js+// Exits non-zero on any error. No dependencies, so it runs in CI as-is.++const fs = require('fs');+const path = require('path');++const ROOT = path.resolve(__dirname, '..');+const PLUGIN_DIR = path.join(ROOT, 'plugins', 'kepler.gl');+const MANIFESTS = {+ claude: path.join(PLUGIN_DIR, '.claude-plugin', 'plugin.json'),+ portable: path.join(PLUGIN_DIR, 'plugin.json'),+ cursor: path.join(PLUGIN_DIR, '.cursor-plugin', 'plugin.json')+};+const MARKETPLACES = {+ claude: path.join(ROOT, '.claude-plugin', 'marketplace.json'),+ codex: path.join(ROOT, '.agents', 'plugins', 'marketplace.json')+};+const AGENT_PLUGINS_SCHEMA = 'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json';+const SHARED_BLOCKS = ['layer-types', 'basemaps', 'trip', 'palettes'];++const errors = [];+const checks = [];++const rel = p => path.relative(ROOT, p).split(path.sep).join('/');+const fail = message => errors.push(message);+const pass = message => checks.push(message);+const isDir = p => fs.existsSync(p) && fs.statSync(p).isDirectory();+const isFile = p => fs.existsSync(p) && fs.statSync(p).isFile();+const normalize = value => String(value).replace(/\s+/g, ' ').trim();+const readText = p => fs.readFileSync(p, 'utf8');++function readJson(file, label) {+ if (!isFile(file)) {+ fail(`${label}: missing ${rel(file)}`);+ return null;+ }+ try {+ return JSON.parse(readText(file));+ } catch (error) {+ fail(`${label}: ${rel(file)} is not valid JSON (${error.message})`);+ return null;+ }+}++function readFrontmatter(file) {+ const text = readText(file);+ const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);+ if (!match) return null;+ const data = {};+ for (const line of match[1].split(/\r?\n/)) {+ const field = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);+ if (!field) continue;+ let value = field[2].trim();+ if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1);+ data[field[1]] = value;+ }+ return {data, body: text.slice(match[0].length)};+}++function skillDirs() {+ const dir = path.join(PLUGIN_DIR, 'skills');+ if (!isDir(dir)) return [];+ return fs+ .readdirSync(dir)+ .filter(entry => isDir(path.join(dir, entry)))+ .sort();+}++function extractSharedBlocks(file, label) {+ const text = readText(file);+ const blocks = {};+ for (const name of SHARED_BLOCKS) {+ const pattern = new RegExp(`<!-- shared:${name} -->\\n([\\s\\S]*?)<!-- /shared:${name} -->`);+ const match = text.match(pattern);+ if (!match) {+ fail(`${label}: missing shared block "shared:${name}" in ${rel(file)}`);+ continue;+ }+ blocks[name] = match[1].replace(/\r\n/g, '\n').trim();+ }+ return blocks;+}++function checkLocalSource(source, label, expectedDir) {+ // Agent Plugins: a plain path or {source: "local", path}. Paths are relative+ // to the marketplace root, must start with ./, and must stay inside it.+ const sourcePath = typeof source === 'string' ? source : source && source.path;+ if (typeof source !== 'string' && (!source || source.source !== 'local')) {+ fail(`${label}: expected a local source, got ${JSON.stringify(source)}`);+ return;+ }+ if (!sourcePath || !sourcePath.startsWith('./')) {+ fail(`${label}: source path must start with "./" (got ${JSON.stringify(sourcePath)})`);+ return;+ }+ const resolved = path.resolve(ROOT, sourcePath);+ if (!resolved.startsWith(ROOT + path.sep)) {+ fail(`${label}: source path must stay inside the marketplace root`);+ return;+ }+ if (resolved !== path.resolve(expectedDir)) {+ fail(`${label}: source resolves to ${rel(resolved)}, expected ${rel(expectedDir)}`);+ return;+ }+ pass(`${label}: local source -> ${sourcePath}`);+}++// --- 1. Manifests parse and agree on identity ------------------------------++const manifests = {};+for (const [label, file] of Object.entries(MANIFESTS)) {+ const json = readJson(file, `${label} manifest`);+ if (json) manifests[label] = json;+}++if (Object.keys(manifests).length === Object.keys(MANIFESTS).length) {+ const identity = {};+ for (const [label, json] of Object.entries(manifests)) {+ identity[label] = {+ name: json.name,+ version: json.version,+ description: normalize(json.description)+ };+ if (!json.description) fail(`${label} manifest: missing description`);+ if (!json.version) fail(`${label} manifest: missing version`);+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(json.version || '')) {+ fail(`${label} manifest: version "${json.version}" is not semver`);+ }+ }+ const reference = identity.claude;+ for (const [label, value] of Object.entries(identity)) {+ if (value.name !== reference.name) {+ fail(`${label} manifest: name "${value.name}" != "${reference.name}"`);+ }+ if (value.version !== reference.version) {+ fail(`${label} manifest: version "${value.version}" != "${reference.version}"`);+ }+ if (value.description !== reference.description) {+ fail(`${label} manifest: description differs from the Claude manifest`);+ }+ }+ // Claude.ai marketplace sync and Codex both require a kebab-case id; the+ // display name ("kepler.gl") lives in the Cursor and OpenAI metadata.+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(reference.name || '')) {+ fail(`plugin name "${reference.name}" is not kebab-case`);+ } else {+ pass(`manifests agree on name/version/description (${reference.name}@${reference.version})`);+ }+}++// --- 2. Portable (Codex / Agent Plugins) manifest --------------------------++if (manifests.portable) {+ const portable = manifests.portable;+ if (portable.$schema !== AGENT_PLUGINS_SCHEMA) {+ fail(`portable manifest: $schema must be exactly ${AGENT_PLUGINS_SCHEMA}`);+ } else {+ pass('portable manifest: $schema is the Agent Plugins 1.0.0 schema');+ }+ if (+ !portable.name ||+ !/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(portable.name) ||+ portable.name.includes('--') ||+ portable.name.includes('..')+ ) {+ fail(`portable manifest: name "${portable.name}" violates the Agent Plugins name rules`);+ }+ if (portable.author && typeof portable.author !== 'object') {+ fail('portable manifest: author must be an object ({name, email, url})');+ }+ const openai = portable.extensions && portable.extensions['com.openai'];+ if (!openai || typeof openai !== 'object') {+ fail('portable manifest: missing extensions["com.openai"]');+ } else if (!openai.interface || typeof openai.interface !== 'object') {+ fail('portable manifest: extensions["com.openai"].interface must be an object');+ } else {+ const ui = openai.interface;+ for (const key of ['displayName', 'shortDescription', 'category']) {+ if (!ui[key]) fail(`portable manifest: extensions["com.openai"].interface.${key} is missing`);+ }+ if (ui.brandColor && !/^#[0-9A-Fa-f]{6}$/.test(ui.brandColor)) {+ fail(`portable manifest: brandColor "${ui.brandColor}" is not #RRGGBB`);+ }+ if (ui.defaultPrompt && !Array.isArray(ui.defaultPrompt)) {+ fail('portable manifest: interface.defaultPrompt must be an array');+ }+ for (const key of ['composerIcon', 'logo']) {+ const asset = ui[key];+ if (!asset) continue;+ if (!asset.startsWith('./')) {+ fail(`portable manifest: interface.${key} must start with "./"`);+ } else if (!isFile(path.join(PLUGIN_DIR, asset))) {+ fail(`portable manifest: interface.${key} -> ${asset} does not exist`);+ }+ }+ pass('portable manifest: com.openai interface metadata is complete');+ }+}++// --- 3. Cursor manifest ----------------------------------------------------++// Cursor reads <plugin>/.cursor-plugin/plugin.json — a root cursor-plugin.json+// is a legacy path that current Cursor does not load. The manifest is closed+// (additionalProperties: false) and its author object allows only name/email,+// so the checks below mirror the published schema instead of inventing fields.+const CURSOR_KEYS = [+ 'name',+ 'displayName',+ 'description',+ 'version',+ 'minClientVersions',+ 'author',+ 'publisher',+ 'homepage',+ 'repository',+ 'license',+ 'logo',+ 'keywords',+ 'category',+ 'tags',+ 'commands',+ 'agents',+ 'skills',+ 'rules',+ 'hooks',+ 'variables',+ 'mcpServers'+];+if (manifests.cursor) {+ const cursor = manifests.cursor;+ for (const key of Object.keys(cursor)) {+ if (!CURSOR_KEYS.includes(key)) fail(`cursor manifest: unsupported field "${key}"`);+ }+ if (!cursor.author || typeof cursor.author !== 'object' || !cursor.author.name) {+ fail('cursor manifest: author must be an object with a name');+ } else {+ for (const key of Object.keys(cursor.author)) {+ if (!['name', 'email'].includes(key)) {+ fail(`cursor manifest: author.${key} is not in the Cursor schema`);+ }+ }+ }+ if (cursor.repository && typeof cursor.repository !== 'string') {+ fail('cursor manifest: repository must be a URL string');+ }+ if (cursor.logo && !isFile(path.join(PLUGIN_DIR, cursor.logo))) {+ fail(`cursor manifest: logo -> ${cursor.logo} does not exist`);+ }+ if (cursor.skills) {+ const dir = typeof cursor.skills === 'string' ? cursor.skills : cursor.skills[0];+ if (!isDir(path.join(PLUGIN_DIR, dir))) {+ fail(`cursor manifest: skills -> ${dir} does not exist`);+ } else {+ pass(`cursor manifest: skills -> ${dir}`);+ }+ }+}+if (isFile(path.join(PLUGIN_DIR, 'cursor-plugin.json'))) {+ fail('plugins/kepler.gl/cursor-plugin.json is a legacy path — use .cursor-plugin/plugin.json');+}++// --- 4. Skill discovery and frontmatter -----------------------------------++const dirs = skillDirs();+const foundSkills = {};+if (dirs.length !== 2) {+ fail(`skills/: expected 2 skill directories, found ${dirs.length} (${dirs.join(', ')})`);+}+for (const dir of dirs) {+ const skillFile = path.join(PLUGIN_DIR, 'skills', dir, 'SKILL.md');+ if (!isFile(skillFile)) {+ fail(`skills/${dir}: missing SKILL.md`);+ continue;+ }+ const frontmatter = readFrontmatter(skillFile);+ if (!frontmatter) {+ fail(`skills/${dir}: SKILL.md has no YAML frontmatter`);+ continue;+ }+ const {name, description} = frontmatter.data;+ if (!name) fail(`skills/${dir}: frontmatter is missing "name"`);+ else if (name !== dir) {+ fail(`skills/${dir}: frontmatter name "${name}" must match the directory name`);+ }+ if (!description) fail(`skills/${dir}: frontmatter is missing "description"`);+ if (name && description) foundSkills[name] = frontmatter;+}++const appSkillYaml = path.join(PLUGIN_DIR, 'skills', 'kepler-gl-app', 'skill.yaml');+if (foundSkills['kepler-gl-app'] && isFile(appSkillYaml)) {+ fail(+ 'skills/kepler-gl-app: skill.yaml must not exist — skill metadata lives in the SKILL.md frontmatter'+ );+}++if (manifests.claude && Array.isArray(manifests.claude.skills)) {+ for (const entry of manifests.claude.skills) {+ if (!isDir(path.join(PLUGIN_DIR, entry))) {+ fail(`claude manifest: skills entry ${entry} does not exist`);+ }+ }+ if (manifests.claude.skills.length === 2) {+ pass('claude manifest: both skill directories are declared');+ }+}++// --- 5. Shared blocks stay identical --------------------------------------++const pythonSkill = path.join(PLUGIN_DIR, 'skills', 'keplergl-python', 'SKILL.md');+const appSkill = path.join(PLUGIN_DIR, 'skills', 'kepler-gl-app', 'SKILL.md');+if (isFile(pythonSkill) && isFile(appSkill)) {+ const pythonBlocks = extractSharedBlocks(pythonSkill, 'keplergl-python');+ const appBlocks = extractSharedBlocks(appSkill, 'kepler-gl-app');+ let drift = false;+ for (const name of SHARED_BLOCKS) {+ if (pythonBlocks[name] && appBlocks[name] && pythonBlocks[name] !== appBlocks[name]) {+ fail(`shared block "shared:${name}" differs between keplergl-python and kepler-gl-app`);+ drift = true;+ }+ }+ if (!drift && Object.keys(pythonBlocks).length === SHARED_BLOCKS.length) {+ pass(`shared blocks are identical across both skills (${SHARED_BLOCKS.join(', ')})`);+ }+}++// --- 6. App skill tracks its source in src/mcp -----------------------------+// src/mcp/skill/kepler/SKILL.md is served verbatim by @kepler.gl/mcp and the+// demo app, so it stays the source of truth; the plugin copy adds frontmatter+// and a cross-surface appendix and must otherwise match.++const sourceSkill = path.join(ROOT, 'src', 'mcp', 'skill', 'kepler', 'SKILL.md');+if (isFile(appSkill) && isFile(sourceSkill)) {+ const app = readFrontmatter(appSkill);+ const sourceBody = readText(sourceSkill).replace(/\r\n/g, '\n').trim();+ const appBody = app ? app.body.replace(/\r\n/g, '\n').trim() : '';+ if (!appBody.startsWith(sourceBody)) {+ fail(+ 'skills/kepler-gl-app/SKILL.md no longer starts with src/mcp/skill/kepler/SKILL.md — ' ++ 're-copy the source body (frontmatter + cross-surface appendix go around it)'+ );+ } else {+ pass('kepler-gl-app body matches src/mcp/skill/kepler/SKILL.md');+ }++ const skillYaml = path.join(ROOT, 'src', 'mcp', 'skill', 'kepler', 'skill.yaml');+ if (isFile(skillYaml)) {+ const description = (readText(skillYaml).match(/^description:\s*(.+)$/m) || [])[1];+ if (!description) {+ fail('src/mcp/skill/kepler/skill.yaml: could not read description');+ } else if (normalize(app.data.description) !== normalize(description)) {+ fail(+ 'skills/kepler-gl-app/SKILL.md frontmatter description differs from ' ++ 'src/mcp/skill/kepler/skill.yaml (keep the two in sync)'+ );+ } else {+ pass('kepler-gl-app description matches src/mcp/skill/kepler/skill.yaml');+ }+ }+}++// --- 7. Python skill references resolve -----------------------------------++if (isFile(pythonSkill)) {+ const text = readText(pythonSkill);+ const links = [...text.matchAll(/\]\((references\/[^)\s]+)\)/g)].map(m => m[1]);+ const missing = links.filter(link => !isFile(path.join(path.dirname(pythonSkill), link)));+ if (missing.length) {+ fail(`keplergl-python: broken reference links -> ${missing.join(', ')}`);+ } else {+ pass(`keplergl-python: ${links.length} reference links resolve`);+ }+ const referenced = new Set(links.map(link => path.basename(link)));+ const onDisk = fs.readdirSync(path.join(path.dirname(pythonSkill), 'references'));+ const orphans = onDisk.filter(file => !referenced.has(file));+ if (orphans.length) {+ fail(`keplergl-python: references not linked from SKILL.md -> ${orphans.join(', ')}`);+ }+}++// --- 8. Marketplaces point at the plugin ----------------------------------++const claudeMarketplace = readJson(MARKETPLACES.claude, 'claude marketplace');+if (claudeMarketplace) {+ const errorsBefore = errors.length;+ if (!claudeMarketplace.name) fail('claude marketplace: missing name');+ if (!claudeMarketplace.owner || !claudeMarketplace.owner.name) {+ fail('claude marketplace: missing owner.name');+ }+ const entries = claudeMarketplace.plugins || [];+ if (entries.length !== 1) fail(`claude marketplace: expected 1 plugin, found ${entries.length}`);+ for (const entry of entries) {+ if (!entry.name) fail('claude marketplace: plugin entry is missing name');+ if (manifests.portable && entry.name !== manifests.portable.name) {+ fail(+ `claude marketplace: plugin "${entry.name}" != manifest name "${manifests.portable.name}"`+ );+ }+ checkLocalSource(entry.source, 'claude marketplace', PLUGIN_DIR);+ }+ if (errors.length === errorsBefore) pass('claude marketplace points at plugins/kepler.gl');+}++const codexMarketplace = readJson(MARKETPLACES.codex, 'codex marketplace');+if (codexMarketplace) {+ const errorsBefore = errors.length;+ if (!codexMarketplace.name) fail('codex marketplace: missing name');+ const entries = codexMarketplace.plugins || [];+ if (entries.length !== 1) fail(`codex marketplace: expected 1 plugin, found ${entries.length}`);+ for (const entry of entries) {+ if (!entry.name) fail('codex marketplace: plugin entry is missing name');+ if (!entry.category) fail('codex marketplace: plugin entry is missing category');+ if (manifests.portable && entry.name !== manifests.portable.name) {+ fail(+ `codex marketplace: plugin "${entry.name}" != manifest name "${manifests.portable.name}"`+ );+ }+ if (entry.policy) {+ const {installation, authentication} = entry.policy;+ if (!['NOT_AVAILABLE', 'AVAILABLE', 'INSTALLED_BY_DEFAULT'].includes(installation)) {+ fail(`codex marketplace: invalid policy.installation "${installation}"`);+ }+ if (!['ON_INSTALL', 'ON_USE'].includes(authentication)) {+ fail(`codex marketplace: invalid policy.authentication "${authentication}"`);+ }+ }+ checkLocalSource(entry.source, 'codex marketplace', PLUGIN_DIR);+ }+ if (errors.length === errorsBefore) pass('codex marketplace points at plugins/kepler.gl');+}++// --- Report ---------------------------------------------------------------++for (const check of checks) console.log(` ✔ ${check}`);+if (errors.length) {+ console.error(`\n✘ ${errors.length} problem(s):`);+ for (const error of errors) console.error(` ✘ ${error}`);+ process.exit(1);+}+console.log('\n✔ Plugin manifests are consistent.');diff --git a/skill/README.md b/skill/README.mddeleted file mode 100644index 2c2008196..000000000--- a/skill/README.md+++ /dev/null@@ -1,43 +0,0 @@-# kepler.gl Skill for AI Coding Assistants--This directory contains the **kepler.gl** agent skill — a set of instructions and references that help AI coding assistants (Claude Code, Codex, Cursor, etc.) generate `keplergl` map scripts and exports consistently.--## Skill References--| Reference | Description |-|-----------|-------------|-| [point-map.md](skill-references/point-map.md) | Scatter plot from lat/lng |-| [geojson-polygon-map.md](skill-references/geojson-polygon-map.md) | Polygons & lines from GeoJSON / GeoDataFrame |-| [h3-hexagon-map.md](skill-references/h3-hexagon-map.md) | H3 spatial index hexagons |-| [arc-line-map.md](skill-references/arc-line-map.md) | Origin–destination arcs & lines |-| [heatmap.md](skill-references/heatmap.md) | Density heatmap from points |-| [hexbin-aggregation-map.md](skill-references/hexbin-aggregation-map.md) | Spatial binning into hexagons |-| [trip-animation-map.md](skill-references/trip-animation-map.md) | Animated trips along paths |-| [summary-panel.md](skill-references/summary-panel.md) | SampleMapPanel-style info overlay in exported HTML |--## Quick Setup via AI Agent--The easiest way to get started is to prompt your AI agent:--> Help me install the kepler.gl skill from--- claude: https://github.com/keplergl/kepler.gl/releases/download/skill-v0.0.1/kepler.gl-claude.zip-- codex: https://github.com/keplergl/kepler.gl/releases/download/skill-v0.0.1/kepler.gl-codex.zip-- source: https://github.com/keplergl/kepler.gl/releases/download/skill-v0.0.1/kepler.gl-skill-source.zip--or just "kepler.gl github repo"--The agent will locate the skill file and set it up for you automatically.--## Example Prompt--> Create a map showing distribution of HR60 from natregimes.geojson.-> Color the polygons by population, use a light theme.--The agent will generate a Python script and run it, producing a standalone HTML map file you can open in any browser.--## Versioning--The skill version is tracked in [`plugin.json`](plugin.json). Releases use the tag pattern `skill-v*` (e.g. `skill-v1.0.0`).--> **Note:** The download links above will return 404 until the first skill release is published. To publish, push a `skill-v*` tag (e.g. `git tag skill-v0.0.1 && git push origin skill-v0.0.1`) which triggers the `.github/workflows/publish-skill.yml` workflow to build and attach the zip packages to the GitHub release.diff --git a/skill/agents/openai.yaml b/skill/agents/openai.yamldeleted file mode 100644index 14de76a33..000000000--- a/skill/agents/openai.yaml+++ /dev/null@@ -1,13 +0,0 @@-interface:- display_name: "kepler.gl Map"- short_description: "Create interactive map visualizations with kepler.gl"- icon_small: "./assets/icon-small.svg"- icon_large: "./assets/icon-large.svg"- brand_color: "#1FBAD6"- default_prompt: "Create an interactive map visualization"--policy:- allow_implicit_invocation: true--dependencies:- tools: []diff --git a/skill/cursor-plugin.json b/skill/cursor-plugin.jsondeleted file mode 100644index f899f68f6..000000000--- a/skill/cursor-plugin.json+++ /dev/null@@ -1,38 +0,0 @@-{- "name": "kepler.gl",- "displayName": "kepler.gl Map",- "version": "0.0.1",- "description": "Create interactive map visualizations and export to standalone HTML using the keplergl Python package.",- "publisher": "keplergl",- "icon": "agents/assets/icon-large.svg",- "categories": ["Data Science", "Visualization", "Maps"],- "keywords": [- "maps",- "geospatial",- "visualization",- "kepler.gl",- "GeoJSON",- "DataFrame",- "HTML",- "interactive",- "choropleth",- "heatmap"- ],- "homepage": "https://kepler.gl",- "repository": {- "type": "git",- "url": "https://github.com/keplergl/kepler.gl",- "directory": "bindings/python"- },- "license": "MIT",- "skills": [- {- "path": "SKILL.md",- "name": "kepler.gl",- "description": "Create interactive map visualizations and export to standalone HTML using the keplergl Python package."- }- ],- "engines": {- "cursor": ">=1.0.0"- }-}diff --git a/skill/plugin.json b/skill/plugin.jsondeleted file mode 100644index 9153f8ab5..000000000--- a/skill/plugin.json+++ /dev/null@@ -1,28 +0,0 @@-{- "name": "kepler.gl",- "version": "0.0.1",- "description": "Create interactive map visualizations and export to standalone HTML using the keplergl Python package. Use when the user wants to create maps, visualize geospatial data, plot locations on a map, or generate HTML map files.",- "author": "kepler.gl",- "license": "MIT",- "homepage": "https://kepler.gl",- "repository": {- "type": "git",- "url": "https://github.com/keplergl/kepler.gl",- "directory": "bindings/python"- },- "skills": [- {- "path": "./SKILL.md"- }- ],- "keywords": [- "maps",- "geospatial",- "visualization",- "kepler.gl",- "GeoJSON",- "DataFrame",- "HTML",- "interactive"- ]-}diff --git a/src/mcp/babel.config.js b/src/mcp/babel.config.jsnew file mode 100644index 000000000..3b4d402a3--- /dev/null+++ b/src/mcp/babel.config.js@@ -0,0 +1,57 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++const KeplerPackage = require('./package');++// Plugins shared by both CJS and ESM builds.+const SHARED_PLUGINS = [+ ['@babel/plugin-transform-typescript', {isTSX: true, allowDeclareFields: true}],+ '@babel/plugin-transform-class-properties',+ '@babel/plugin-transform-optional-chaining',+ '@babel/plugin-transform-logical-assignment-operators',+ '@babel/plugin-transform-nullish-coalescing-operator',+ '@babel/plugin-transform-export-namespace-from',+ [+ 'search-and-replace',+ {+ rules: [+ {+ search: '__PACKAGE_VERSION__',+ replace: KeplerPackage.version+ }+ ]+ }+ ]+];++module.exports = function babel(api) {+ // Cache per BABEL_ENV so that CJS and ESM builds get separate cached results.+ api.cache.using(() => process.env.BABEL_ENV || process.env.NODE_ENV || 'development');++ const isEsm = api.env('esm');+ const isTest = api.env('test');+ const isDebug = api.env('debug');++ // ESM build: modules:false preserves import/export so Vite/esbuild can tree-shake.+ // CJS build (default / test): transforms import/export to require/module.exports.+ const presets = [+ ['@babel/preset-env', isEsm ? {modules: false} : {}],+ '@babel/preset-react',+ '@babel/preset-typescript'+ ];++ const plugins = [+ ...SHARED_PLUGINS,+ // CJS and test builds need the CommonJS transform; ESM must omit it.+ ...(isEsm ? [] : ['@babel/plugin-transform-modules-commonjs']),+ // Runtime helpers: ESM variant uses ESM imports, no require() calls.+ ['@babel/transform-runtime', {regenerator: true, ...(isEsm ? {useESModules: true} : {})}],+ ...(isTest ? ['istanbul'] : [])+ ];++ return {+ presets,+ plugins,+ ...(isDebug ? {sourceMaps: 'inline', retainLines: true} : {})+ };+};diff --git a/src/mcp/package.json b/src/mcp/package.jsonnew file mode 100644index 000000000..0c4ab5f29--- /dev/null+++ b/src/mcp/package.json@@ -0,0 +1,86 @@+{+ "name": "@kepler.gl/mcp",+ "author": "Shan He <[email protected]>",+ "version": "3.3.0-alpha.18",+ "description": "The kepler.gl map surface for AI agents: map.* commands, command contract + JSON Schemas + types, a stdio MCP server that bridges to an open kepler.gl page, and the kepler map-management skill",+ "license": "MIT",+ "main": "dist/cjs/index.js",+ "types": "dist/index.d.ts",+ "bin": {+ "kepler-mcp": "dist/cjs/server/stdio.js"+ },+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "import": "./dist/esm/index.js",+ "require": "./dist/cjs/index.js",+ "default": "./dist/cjs/index.js"+ },+ "./server": {+ "types": "./dist/server/index.d.ts",+ "import": "./dist/esm/server/index.js",+ "require": "./dist/cjs/server/index.js",+ "default": "./dist/cjs/server/index.js"+ },+ "./skill/kepler/SKILL.md": "./skill/kepler/SKILL.md",+ "./skill/kepler/skill.yaml": "./skill/kepler/skill.yaml"+ },+ "keywords": [+ "kepler",+ "kepler.gl",+ "map",+ "mcp",+ "ai"+ ],+ "repository": {+ "type": "git",+ "url": "https://github.com/keplergl/kepler.gl.git"+ },+ "scripts": {+ "build": "rm -fr dist && babel src --out-dir dist/cjs --source-maps inline --extensions '.ts,.tsx,.js,.jsx' --ignore '**/*.d.ts,**/*.spec.ts,**/*.test.ts' && BABEL_ENV=esm babel src --out-dir dist/esm --source-maps inline --extensions '.ts,.tsx,.js,.jsx' --ignore '**/*.d.ts,**/*.spec.ts,**/*.test.ts'",+ "build:types": "tsc --project ./tsconfig.production.json",+ "prepublishOnly": "babel-node ../../scripts/license-header/bin --license ../../FILE-HEADER && yarn build && yarn build:types",+ "stab": "mkdir -p dist/cjs dist/esm && echo \"'use strict'; Object.assign(module.exports, require('../../src'));\" > dist/cjs/index.js && echo \"export * from '../../src';\" > dist/esm/index.js"+ },+ "files": [+ "dist",+ "skill"+ ],+ "dependencies": {+ "@kepler.gl/actions": "3.3.0-alpha.18",+ "@kepler.gl/constants": "3.3.0-alpha.18",+ "@kepler.gl/layers": "3.3.0-alpha.18",+ "@kepler.gl/processors": "3.3.0-alpha.18",+ "@kepler.gl/reducers": "3.3.0-alpha.18",+ "@kepler.gl/table": "3.3.0-alpha.18",+ "@kepler.gl/types": "3.3.0-alpha.18",+ "@modelcontextprotocol/sdk": "^1.32.2",+ "apache-arrow": "^17.0.0",+ "ws": "^8.22.0",+ "zod": "^4.4.0"+ },+ "devDependencies": {+ "@babel/cli": "^7.12.1",+ "@babel/node": "^7.12.1",+ "@types/ws": "^8.18.2"+ },+ "nyc": {+ "sourceMap": false,+ "instrument": false+ },+ "maintainers": [+ "Shan He <[email protected]>",+ "Igor Dykhta <[email protected]>",+ "Ilya Boyandin <[email protected]>",+ "Xun Li <[email protected]>"+ ],+ "engines": {+ "node": ">=20"+ },+ "volta": {+ "node": "20.19.3",+ "yarn": "4.4.0"+ },+ "packageManager": "[email protected]",+ "module": "dist/esm/index.js"+}diff --git a/src/mcp/skill/kepler/SKILL.md b/src/mcp/skill/kepler/SKILL.mdnew file mode 100644index 000000000..aaba2a97b--- /dev/null+++ b/src/mcp/skill/kepler/SKILL.md@@ -0,0 +1,438 @@+# Kepler map management++Create and configure kepler.gl map layers from datasets, animate them over+time, compare them side by side, change the basemap, update layer colors,+load data from a URL, add columns to existing datasets, and read the current+map boundary. These are direct map-mutation operations on the kepler.gl map+surface.++## When to use++Use this skill when the user wants to create or reconfigure map layers, change+the appearance or configuration of the map itself, animate data over time, or+compare layers side by side. Examples:+- "Show the shops as points colored by visits"+- "Create a heatmap of the pickup locations"+- "Animate the trips over time"+- "Compare the 2019 and 2024 layers side by side"+- "Change the basemap to dark/satellite/positron"+- "Update the color of the layer to blue"+- "Load data from this URL"+- "Add a new variable / column to an existing dataset"+- "Change a column's type (e.g. make NOSOUTH a string)"+- "Rename a column on the existing dataset"+- "What's the current map boundary/extent?"++Do NOT use this skill for analysis beyond map mutation — spatial statistics,+spatial filtering, colocation, boundary fetching, or charts. Those belong to+your host's analysis skills (e.g. a spatial-analysis skill, a filter skill),+not this one.++## Commands at a glance++| command | purpose |+| ------------------------ | -------------------------------------------------------------- |+| `map.add-layer` | Add a layer (point, flow, flowField, h3, arc, trip, hexagon, grid, cluster, heatmap, geojson, line, s2) to the map. |+| `map.add-time-filter` | Animate a NON-trip layer over a TIMESTAMP/DATE column. |+| `map.toggle-time-filter` | Show/hide the enlarged time controller at the bottom of the map. |+| `map.split-view` | Enable/disable dual-map comparison. |+| `map.update-layer-color` | Update an existing layer's color palette. |+| `map.set-basemap` | Change the basemap style. |+| `map.set-view-mode` | Switch between the flat 2D map, the tilted 3D map and the 3D globe. |+| `map.load-data` | Load data from a URL (no layer — call `map.add-layer`). |+| `map.save-data` | Save a DuckDB table as a map dataset (no layer — call `map.add-layer`). |+| `map.add-column` | Add a column to an EXISTING dataset in place (copy or expression). |+| `map.create-table` | Create a NEW dataset via SQL (original untouched — call `map.add-layer`). |+| `map.get-dataset-context` | List all loaded datasets with their fields and layer configurations. |+| `map.get-boundary` | Read the current map view's bounding box. |++Every command takes a `commandId` (one of the table above) and an `input`+object. Issue commands through your host's map-command dispatcher — the exact+envelope is described in your host's tool listing. In the kepler.gl demo+assistant the dispatcher is the `executeApi` tool with+`apiName: "executeCommand"` and `args: { commandId, input }`.++## Picking a layer type++- Individual locations → `point` (`cluster` for zoom-out density, `heatmap`+ for continuous intensity).+- Density without precomputed cells → `grid` or `hexagon` (auto-binned).+- Pre-aggregated H3 cells → `h3`.+- Origin→destination flows → `flow` (a dedicated flow layer with locations, clustering and weighted edges; requires two point lat/lng pairs — source + destination). Fall back to `arc` only when you want straight great-circle lines between points. For weighted flows optionally pass the magnitude column as `countColumn`.+- Vector fields — wind, currents, downhill terrain flow → `flowField`, animated streamlines over one vector per sample point. This is **not** `flow`: `flow` joins an origin pair to a destination pair, `flowField` draws many short lines through a field of vectors.++- Polylines / polygons → `line` / `geojson`. A decoded GEOMETRY `geom`+ column can be rendered directly with `geojson` — do NOT convert it to+ lat/lon columns or build an intermediate table. For geojson datasets use+ geometryColumn `"_geojson"`.+- Time-animated movement → `trip`.++## Color configuration++- `colorBy` is case-sensitive and must match the column name exactly.+- `simpleColor` is the string `"[r, g, b]"` (e.g. `"[255, 64, 0]"`), not an array.+ It is a single static color for ALL features — NEVER use it for data-driven+ coloring; use `colorBy` + `colorType` + `colorMap` for that.+- For continuous data use `colorType: "breaks"` with a `colorMap` whose last+ entry has `value: null` (the color for the highest bucket):+ `[{value: 0, color: "#fee5d9"}, {value: 50, color: "#fcae91"}, {value: 100, color: "#fb6a4a"}, {value: null, color: "#de2d26"}]`+- For categorical data use `colorType: "unique"`:+ `[{value: "retail", color: "#1f77b4"}, {value: "restaurant", color: "#ff7f0e"}]`+ HARD RULE: the `value`s MUST be the actual unique values in the column.+ Classify the variable with your host's classification tool first and use the+ returned unique values verbatim. NEVER guess category labels from the column+ name — `map.add-layer` rejects values that do not exist in the data.+- For `heatmap`, only `colorRange` (from `colorMap`) takes effect.+- To compute the break values, classify the variable with your host's+ classification tool first and pass the returned breaks as the `colorMap`+ values.+- Generate ColorBrewer-style palettes automatically when the user does not+ specify colors.++### Suggested palettes++- Sequential green: `#ffffcc #c2e699 #78c679 #31a354 #006837 #004529`+- Sequential red: `#fee5d9 #fcae91 #fb6a4a #de2d26 #a50f15`+- Categorical (Tableau 10): `#1f77b4 #ff7f0e #2ca02c #d62728 #9467bd #8c564b`++## Workflow++### 1. Create a layer (`map.add-layer`)++Point layer colored by a continuous variable:++```json+{+ "datasetName": "shops",+ "layerType": "point",+ "layerName": "Shops by visits",+ "colorBy": "visits",+ "colorType": "breaks",+ "colorMap": [+ {"value": 3, "color": "#ffffcc"},+ {"value": 10, "color": "#c2e699"},+ {"value": 25, "color": "#78c679"},+ {"value": 50, "color": "#31a354"},+ {"value": 100, "color": "#006837"},+ {"value": null, "color": "#004529"}+ ]+}+```++Point layer with a uniform color:++```json+{+ "datasetName": "pizza_stores",+ "layerType": "point",+ "layerName": "Pizza stores",+ "simpleColor": "[255, 64, 0]"+}+```++H3 layer:++```json+{+ "datasetName": "visits_h3_r9",+ "layerType": "h3",+ "layerName": "Visits density (h3 r9)",+ "colorBy": "visit_count",+ "colorType": "breaks",+ "colorMap": [+ {"value": 100, "color": "#fee5d9"},+ {"value": 500, "color": "#fcae91"},+ {"value": 2000, "color": "#fb6a4a"},+ {"value": 10000, "color": "#de2d26"},+ {"value": null, "color": "#a50f15"}+ ]+}+```++`map.add-layer` returns `dateTimeColumns` when the dataset has TIMESTAMP/DATE+fields — see "Time animation" below for the follow-up.++### 2. Time animation (NON-trip layers)++When the user asks how something changed/evolved/trended over time and the+source dataset has a TIMESTAMP/DATE column, build a SINGLE layer and animate+it with `map.add-time-filter` — do NOT create a separate static layer per+time step. A stack of snapshot layers does not convey motion and clutters the+map; the animated layer is the deliverable.++- BEFORE creating any layer for a temporal request, DECLARE the expected+ layer count: a change-over-time request ⇒ exactly **1** layer. If you find+ yourself about to issue a 2nd `map.add-layer`, STOP — you have erred.+- `map.add-layer` returns `dateTimeColumns` when timestamp/date fields are+ detected. Pass the first one to `map.add-time-filter`.+- If the column is an integer/string epoch, build a real TIMESTAMP column+ first (Kepler.gl cannot handle negative epochs) — NEVER pass an+ integer/string column directly.+- `map.add-time-filter` input: `{ datasetName, dateTimeColumn, interval? }`.+ `interval` is auto-detected from the data when omitted.+- **Do not retry `map.add-time-filter` more than once.** If it fails, report+ the error and continue — do not loop.+- LAYER ORDERING: create the time-filtered layer LAST so its animation is+ not hidden behind later layers.++```json+{+ "datasetName": "earthquakes",+ "dateTimeColumn": "time"+}+```++### Trip layers (`layerType: "trip"`)++- Trip layers have **built-in** time animation. Do NOT add a+ `map.add-time-filter` for a trip layer — it is unnecessary and can break the+ animation. After creating a trip layer, STOP.+- Strict columns: `id` (shared across a trip's waypoints), `latitude` /+ `longitude` (DOUBLE), `timestamp` (epoch milliseconds). If your epoch is in+ seconds, multiply by 1000.+- Densify sparse O-D data (interpolate lon/lat AND timestamp) or trips+ teleport.++### Flow field layer (`layerType: "flowField"`)++Animated streamlines over a vector field — wind, ocean currents, or downhill+terrain flow. Each row of the dataset is one sample point: a position plus a+direction. It is not the origin→destination `flow` layer — `flow` joins two+point pairs, `flowField` draws many short, continuously moving lines through a+field of vectors.++Pick the mode from the columns the dataset has; `map.add-layer` auto-detects+them in this order and names them in `flowField.*Column` when they differ:++| `flowField.mode` | Columns | Direction comes from |+|------------------|---------|----------------------|+| `UV` (default) | `u`, `v` (+ optional `altitude`) | east/north vector components |+| `SPEED_DIR` | `speed`, `direction` | speed plus compass direction (from) |+| `ELEVATION` | `altitude` | the downhill gradient of a height surface |++Position comes from lat/lng columns — auto-detected, or `latitudeColumn` /+`longitudeColumn` — or from a GeoJSON geometry column when the dataset has one.++Wind encoded as `u`/`v` (no extra parameters needed):++```json+{+ "datasetName": "wind_grid",+ "layerType": "flowField",+ "layerName": "Wind field",+ "flowField": {"colorBySpeed": true}+}+```++Wind encoded as speed + direction under different column names:++```json+{+ "datasetName": "wind_grid",+ "layerType": "flowField",+ "layerName": "Wind field",+ "flowField": {+ "mode": "SPEED_DIR",+ "speedColumn": "wind_speed",+ "directionColumn": "wind_dir"+ }+}+```++- `colorBySpeed: true` colors each streamline by its local speed (using the+ layer's color range); without it the streamlines use `color`. `colorBy` /+ `colorMap` do not apply to this layer.+- Do **not** add `map.add-time-filter` — the flow field animates continuously on+ its own, like a trip layer.+- Streamline density (`linesPerScreen`), `strokeWidth`, `trailLength`,+ `cycleSeconds`, `lineLifetime` and `smoothing` use tuned defaults; they are+ adjusted in the layer panel, not through `map.add-layer`.+- A field layer over a very large grid is expensive: one row per sample point is+ fine, but downsample rasters to roughly 10k–100k points before loading.++### 3. Split map comparison (`map.split-view`)++- `action: "enable"` with `layerIdsForMap0` / `layerIdsForMap1`. Without the+ layer-id arrays all layers show on both panels (no comparison). Use the SAME+ `colorBy` / `colorType` for a fair comparison. `action: "disable"` returns+ to one map.++```json+{+ "action": "enable",+ "layerIdsForMap0": ["layer_2019"],+ "layerIdsForMap1": ["layer_2024"]+}+```++### 4. Toggle the time controller++`map.toggle-time-filter` with `action: "show"` enlarges the time controller+at the bottom of the map; `action: "hide"` collapses it back to the side+panel. A time filter must already exist (created via `map.add-time-filter`).++### 5. Basemap style++```json+{ "styleType": "dark" }+```++Valid `styleType` values: `"no_map"`, `"dark-matter"`, `"positron"`,+`"voyager"`, `"satellite"`, `"dark"`, `"light"`, `"muted"`, `"muted_night"`.+If the user uses a descriptive name, map it to the closest valid `styleType`.+If the request is ambiguous, ask the user to clarify.++### 6. Layer color++```json+{+ "layerId": "layer_xxx",+ "numberOfColors": 5,+ "customColors": ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd"]+}+```++`customColors` is an array of hex color strings; `numberOfColors` must equal+its length. If the user describes colors qualitatively (e.g. "van gogh+starry night", "watercolor"), generate an appropriate palette from the+description. If the user refers to a layer by name rather than id, find the+matching `layerId` from the dataset context.++### 7. Load data from URL++```json+{ "url": "https://..." }+```++This fetches the data, parses it, and adds it to the map as a dataset. It+does NOT create a layer — call `map.add-layer` afterward to visualize the+data (with the layer type, color, and styling you want).++The dataset is named after the URL filename (e.g. `nyc.geojson`). If the+user wants a specific dataset name, pass it as `datasetName`:++```json+{ "url": "https://.../nyc.geojson", "datasetName": "NYC Neighborhoods" }+```++Local files: a local file must be served over http(s) — the browser cannot+fetch `file://` paths. Copy the file into the demo app's served directory+(e.g. `examples/demo-app/dist/`) and pass `/filename.csv`, or serve it with+a CORS-enabled local server (`npx serve --cors -l 8000`) and pass+`http://localhost:8000/filename.csv`. If you have the file content but+cannot serve it (e.g. a remote browser context), pass it as a data URL —+`data:text/csv;base64,<base64 content>` (encode with `base64 -i file.csv`).+This works for small files (up to ~2MB).++For large files (over a few MB), prefer Parquet (`.parquet`) over+GeoJSON/CSV — it loads much faster and is less likely to time out. Convert+GeoJSON to GeoParquet with geopandas (`gdf.to_parquet("data.parquet")`);+kepler reads GeoParquet geometry (WKB) natively, so the map renders the+same lines.++Do NOT create a duplicate dataset just to rename it — never run+`map.create-table` with a plain `SELECT *` (or any copy) to give the loaded+data a friendlier name. `map.create-table` creates a SEPARATE new dataset and+is only for real column transformations; the rename belongs in+`map.load-data`'s `datasetName` (or in the user's hands). Use the loaded+dataset as-is and add the layer to it.++### 8. Map boundary++```json+{}+```++Returns the northwest and southeast coordinates of the current map view:+`{ boundary: { nw: [lon, lat], se: [lon, lat] } }`. When the user says+"current map view", call this to scope spatial queries to the visible area.++### 9. Add / rename / retype a column in an EXISTING dataset (`map.add-column`)++`map.add-column` adds a NEW column to an existing dataset **in place** — the+dataset keeps its name, id, color and layers, and existing columns are+untouched. The new column's values come from exactly ONE of two sources:++- `copyFromColumn` — copy an existing column's values. This is how you rename a+ column in place: to rename `fare` to `fare_amount`, add `fare_amount` copying+ `fare` (the original column stays — the command never removes columns).+- `expression` — an SQL expression computed per row, for a derived variable+ (z-score, ratio, concatenation) OR a type change:+ - z-score: `{ datasetName, newColumnName: "HR60_Z", expression: "(HR60 - AVG(HR60) OVER()) / STDDEV(HR60) OVER()" }`+ - type change: `{ datasetName, newColumnName: "NOSOUTH_str", expression: "NOSOUTH::VARCHAR" }`+ (or `CAST(NOSOUTH AS VARCHAR)`). The new column holds the cast values; the+ original column stays.++```json+{+ "datasetName": "natregimes.geojson",+ "newColumnName": "NOSOUTH_str",+ "expression": "NOSOUTH::VARCHAR"+}+```++`map.create-table` is NOT for this — it builds a separate NEW dataset and leaves+the original untouched. Prefer `map.add-column` whenever the user wants the+change to land in the existing dataset.++### View mode: 2D map, 3D map, or globe (`map.set-view-mode`)++```json+{ "mode": "globe" }+```++- `2d` — flat map, no tilt. The default for city- and region-scale data.+- `3d` — the flat map tilted (pitch 50). For extruded buildings, 3D layers and a+ more dramatic camera; it is **not** a globe.+- `globe` — the 3D globe with atmosphere. Use it when the data spans the world+ (global trips, arcs, lines, points, clusters, hexagons, grids, GeoJSON), so+ the user sees the whole planet instead of a distorted flat world.++Switching to `globe` clamps zoom into the globe's range; switching back to+`2d`/`3d` restores the normal range. The camera mode is independent of the+basemap, so set both when the user asks for a "dark globe" and the like.++- **Keep `flow` and `flowField` layers off the globe.** Neither is supported+ there yet — flow arrows collapse when seen edge-on, and the flow field's+ clipping is mercator-only. Create a global flow field on the 2d map; if the+ user wants a globe view of global movement, use `arc`, `line` or `trip`+ instead, or tell them the field layer needs the flat map.+- Do not switch modes unless the user asks for it or the data's global extent+ makes it clearly better; a map that suddenly becomes a globe is surprising.++## Rules++- Commands that add datasets to the map — `map.load-data`, `map.save-data`,+ `map.create-table` — do NOT auto-create layers. Always call `map.add-layer`+ afterward to visualize the result.+- To add a variable to, rename a column in, or change a column type in an+ EXISTING dataset, use `map.add-column` (copy or expression) — do NOT create a+ new dataset. `map.create-table` only when the user wants a SEPARATE new+ dataset.+- A dataset loaded from a URL keeps the URL filename (or the `datasetName` you+ pass to `map.load-data`). NEVER create a duplicate dataset via+ `map.create-table` just to rename it — use the loaded dataset as-is.+- For change-over-time requests, create exactly ONE animated layer — never+ a separate static layer per time step.+- Do not add a `map.add-time-filter` to a trip layer — trips animate+ themselves.+- If a basemap style name is ambiguous, ask the user to clarify rather than+ guessing.+- For layer color updates, the `layerId` must match an existing layer on the+ map. If the user refers to a layer by name rather than id, use the layer+ name to find the matching layer id from the dataset context.++## Before your final message++- If you created a layer, confirm the layer type, name, and (if any) the+ color field/colorType applied.+- If you added a time filter, confirm the animated column and interval.+- If you enabled split view, confirm which layers are on each panel.+- If you changed the basemap, confirm the new `styleType`.+- If you updated layer colors, confirm the layer id and colors applied.+- If you loaded data, confirm the dataset was loaded and a layer was created.+- If you read the map boundary, report the northwest and southeast+ coordinates.+- If `map.add-layer` returned `dateTimeColumns` and the user asked about+ change over time, you MUST follow up with `map.add-time-filter` on the first+ returned column — do not leave the temporal hint unactioned.diff --git a/src/mcp/skill/kepler/skill.yaml b/src/mcp/skill/kepler/skill.yamlnew file mode 100644index 000000000..47c341a07--- /dev/null+++ b/src/mcp/skill/kepler/skill.yaml@@ -0,0 +1,4 @@+id: kepler+version: 0.2.0+name: Kepler map management+description: Create and configure kepler.gl map layers (point, flow, flowField, arc, line, grid, hexagon, geojson, cluster, heatmap, h3, trip, s2) from datasets, animate them over time, compare them side by side, change the basemap, switch between the 2D, 3D and globe views, update layer colors, load data from a URL, add columns to existing datasets, and read the current map boundary.diff --git a/src/mcp/src/commands/add-column-command.spec.ts b/src/mcp/src/commands/add-column-command.spec.tsnew file mode 100644index 000000000..77a5a2f2a--- /dev/null+++ b/src/mcp/src/commands/add-column-command.spec.ts@@ -0,0 +1,199 @@+import {getAddColumnCommand} from './add-column-command';+import {tableFromArrays} from 'apache-arrow';++// Mock the actions module so the test never touches real kepler state — the+// command's runtime guards + DuckDB query construction + updateDataset payload+// are what we're asserting. (processors is NOT mocked: buildAddColumnPayload+// uses the real arrowSchemaToFields to derive the new column's field.)+jest.mock('@kepler.gl/actions', () => ({+ updateDataset: jest.fn((id: string, data: any) => ({type: 'UPDATE_DATASET', id, data}))+}));++/**+ * Mock KeplerContext. The command resolves the dataset from visState.datasets,+ * loads it into DuckDB via loadTableIntoDuckDB (returning a connector whose+ * query result feeds buildAddColumnPayload), and dispatches updateDataset.+ */+function makeCtx() {+ const dispatched: any[] = [];+ const db = {+ query: jest.fn().mockResolvedValue(tableFromArrays({c: [100, 200]}))+ };+ const dataset = {+ id: 'd1',+ label: 'My Dataset',+ length: 2,+ fields: [+ {name: 'a', type: 'integer'},+ {name: 'b', type: 'integer'}+ ],+ getValue: (name: string, i: number) => (name === 'a' ? [10, 20][i] : [30, 40][i])+ };+ const visState = {datasets: {d1: dataset}, layers: []};+ const ctx = {+ getVisState: () => visState,+ loadTableIntoDuckDB: jest.fn().mockResolvedValue(db),+ dispatch: (action: any) => {+ dispatched.push(action);+ },+ getValuesFromDataset: () => [],+ getMapBoundary: () => null,+ getMapboxToken: () => undefined,+ getDatasetContext: () => ''+ };+ return {ctx, db, getDispatched: () => dispatched};+}++type CommandResult = {success: boolean; error?: string; data?: Record<string, unknown>};++describe('map.add-column', () => {+ it('rejects when neither copyFromColumn nor expression is provided', async () => {+ const {ctx, db} = makeCtx();+ const cmd = getAddColumnCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'My Dataset',+ newColumnName: 'c'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/exactly one/);+ expect(db.query).not.toHaveBeenCalled();+ });++ it('rejects when both copyFromColumn and expression are provided', async () => {+ const {ctx, db} = makeCtx();+ const cmd = getAddColumnCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'My Dataset',+ newColumnName: 'c',+ copyFromColumn: 'a',+ expression: 'a + 1'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/exactly one/);+ expect(db.query).not.toHaveBeenCalled();+ });++ it('rejects an empty expression (bridge path skips zod)', async () => {+ const {ctx, db} = makeCtx();+ const cmd = getAddColumnCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'My Dataset',+ newColumnName: 'c',+ expression: ''+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/expression must be a non-empty string/);+ expect(db.query).not.toHaveBeenCalled();+ });++ it('rejects an empty copyFromColumn (bridge path skips zod)', async () => {+ const {ctx, db} = makeCtx();+ const cmd = getAddColumnCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'My Dataset',+ newColumnName: 'c',+ copyFromColumn: ''+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/copyFromColumn must be a non-empty string/);+ expect(db.query).not.toHaveBeenCalled();+ });++ it('escapes double quotes in identifiers when building the SQL', async () => {+ const {ctx, db} = makeCtx();+ const cmd = getAddColumnCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'My Dataset',+ newColumnName: 'we"ird',+ copyFromColumn: 'a'+ })) as CommandResult;++ expect(result.success).toBe(true);+ const sql = db.query.mock.calls[0][0];+ // the embedded quote is doubled so it can't break out of the identifier+ expect(sql).toContain('"a" AS "we""ird"');+ });++ it('builds the expression path with the raw expression and escaped new column name', async () => {+ const {ctx, db} = makeCtx();+ const cmd = getAddColumnCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'My Dataset',+ newColumnName: 'c',+ expression: '(a - AVG(a) OVER()) / STDDEV(a) OVER()'+ })) as CommandResult;++ expect(result.success).toBe(true);+ const sql = db.query.mock.calls[0][0];+ // the expression is wrapped in parens and the new column name is escaped+ expect(sql).toContain('((a - AVG(a) OVER()) / STDDEV(a) OVER()) AS "c"');+ });++ it('rejects a copyFromColumn that does not exist in the dataset', async () => {+ const {ctx, db} = makeCtx();+ const cmd = getAddColumnCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'My Dataset',+ newColumnName: 'c',+ copyFromColumn: 'nope'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/does not exist/);+ expect(db.query).not.toHaveBeenCalled();+ });++ it('rejects a newColumnName that already exists', async () => {+ const {ctx, db} = makeCtx();+ const cmd = getAddColumnCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'My Dataset',+ newColumnName: 'a',+ copyFromColumn: 'b'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/already exists/);+ expect(db.query).not.toHaveBeenCalled();+ });++ it('errors on a row-count mismatch between the computed column and the dataset', async () => {+ const {ctx, db} = makeCtx();+ // the expression returns only 1 row for a 2-row dataset+ db.query.mockResolvedValue(tableFromArrays({c: [100]}));+ const cmd = getAddColumnCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'My Dataset',+ newColumnName: 'c',+ copyFromColumn: 'a'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/produced 1 rows/);+ });++ it('dispatches updateDataset with the original columns plus the appended one', async () => {+ const {ctx, getDispatched} = makeCtx();+ const cmd = getAddColumnCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'My Dataset',+ newColumnName: 'c',+ copyFromColumn: 'a'+ })) as CommandResult;++ expect(result.success).toBe(true);+ const action = getDispatched().find((a: any) => a.type === 'UPDATE_DATASET');+ expect(action).toBeTruthy();+ expect(action.id).toBe('d1');+ // rows: original a, b + appended c+ expect(action.data.rows).toEqual([+ [10, 30, 100],+ [20, 40, 200]+ ]);+ expect(action.data.fields.map((f: any) => f.name)).toEqual(['a', 'b', 'c']);+ });+});diff --git a/src/mcp/src/commands/add-column-command.ts b/src/mcp/src/commands/add-column-command.tsnew file mode 100644index 000000000..49a4d58aa--- /dev/null+++ b/src/mcp/src/commands/add-column-command.ts@@ -0,0 +1,173 @@+import type {RoomCommand} from './types';+import {z} from 'zod';+import {updateDataset} from '@kepler.gl/actions';+import type {KeplerContext} from './types';+import {buildAddColumnPayload} from './utils';+import {datasetNameToTableName, tableToLLMResult} from './utils';++export const addColumnCommandId = 'map.add-column' as const;++export function getAddColumnCommand(ctx: KeplerContext): RoomCommand {+ return {+ id: addColumnCommandId,+ name: 'Add a column to an existing map dataset',+ group: 'Map',+ description: `Add a NEW column to an existing kepler.gl dataset (table), in place. The dataset keeps its name, id, color and layers; existing columns are untouched, so layers, filters and tooltips keep working unchanged.+The new column's values come from exactly ONE of two sources:+- copyFromColumn — copy the values of an existing column. This is how you "rename" a column in place: to rename "fare" to "fare_amount", add a new column "fare_amount" that copies "fare" (the original "fare" column stays — this command never removes columns).+- expression — an SQL expression computed in DuckDB against the dataset's rows, e.g. a z-score: "(HR60 - AVG(HR60) OVER()) / STDDEV(HR60) OVER()" adds HR60_Z holding the standardized value of HR60. The expression may reference existing columns and window functions; it must produce exactly one value per row.+CHANGING A COLUMN'S TYPE: use expression to add a NEW column that casts the original, e.g. to turn "NOSOUTH" (numeric) into a string, add a new column with expression "NOSOUTH::VARCHAR" (or "CAST(NOSOUTH AS VARCHAR)"). The values become strings; the original column stays. Name the new column clearly (e.g. "NOSOUTH_str") or as the user requests.+IMPORTANT: this command only ADDS columns. It cannot delete or rename-in-place an existing column, and it never changes the type OF an existing column in place — a type change is achieved by adding a NEW column holding the cast values. If you need to remove columns or rebuild the whole table, use map.create-table (which creates a NEW dataset; the original is untouched).`,+ metadata: {readOnly: false, riskLevel: 'medium', idempotent: false},+ inputSchema: z+ .object({+ datasetName: z+ .string()+ .min(1)+ .describe('The name (label) or id of the dataset to add the column to'),+ newColumnName: z+ .string()+ .min(1)+ .describe('The name of the new column to add. Must not already exist in the dataset.'),+ copyFromColumn: z+ .string()+ .min(1)+ .optional()+ .describe(+ 'The name of an EXISTING column whose values the new column will copy. Mutually exclusive with `expression` — provide exactly one.'+ ),+ expression: z+ .string()+ .min(1)+ .optional()+ .describe(+ 'An SQL expression computed in DuckDB against the dataset rows; the result becomes the new column. e.g. z-score: "(HR60 - AVG(HR60) OVER()) / STDDEV(HR60) OVER()". Mutually exclusive with `copyFromColumn` — provide exactly one.'+ )+ })+ .superRefine((data, ctx) => {+ const provided = [data.copyFromColumn, data.expression].filter(v => v != null).length;+ if (provided !== 1) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Provide exactly one of copyFromColumn or expression.'+ });+ }+ }) as any,+ execute: async (_execCtx, input) => {+ const {datasetName, newColumnName, copyFromColumn, expression} = (input ?? {}) as {+ datasetName: string;+ newColumnName: string;+ copyFromColumn?: string;+ expression?: string;+ };+ try {+ // Runtime guard: the bridge/webMCP call execute without zod parsing, so+ // the superRefine "exactly one of copyFromColumn/expression" constraint+ // is not enforced. Without it, both-missing would build+ // `(undefined) AS ...` and produce a confusing DuckDB error.+ const provided = [copyFromColumn, expression].filter(v => v != null).length;+ if (provided !== 1) {+ throw new Error('Provide exactly one of copyFromColumn or expression.');+ }+ if (typeof datasetName !== 'string' || datasetName.length === 0) {+ throw new Error('datasetName must be a non-empty string.');+ }+ if (typeof newColumnName !== 'string' || newColumnName.length === 0) {+ throw new Error('newColumnName must be a non-empty string.');+ }+ // The bridge/webMCP path skips zod, so an empty copyFromColumn/expression+ // would slip through and build `() AS ...` / `"" AS ...` — a confusing+ // DuckDB error instead of an actionable one. Enforce non-empty strings+ // for whichever source is selected.+ if (copyFromColumn != null && (typeof copyFromColumn !== 'string' || copyFromColumn.length === 0)) {+ throw new Error('copyFromColumn must be a non-empty string.');+ }+ if (expression != null && (typeof expression !== 'string' || expression.length === 0)) {+ throw new Error('expression must be a non-empty string.');+ }++ const visState = ctx.getVisState();+ const datasets = visState.datasets;+ const dataId = Object.keys(datasets).find(+ id => id === datasetName || datasets[id].label === datasetName+ );+ if (!dataId) {+ throw new Error(`Dataset "${datasetName}" not found.`);+ }+ const fieldNames = datasets[dataId].fields.map((f: any) => f.name);+ if (copyFromColumn != null && !fieldNames.includes(copyFromColumn)) {+ throw new Error(+ `Column "${copyFromColumn}" does not exist in dataset "${datasetName}". ` ++ `Existing columns: ${fieldNames.join(', ')}.`+ );+ }+ if (fieldNames.includes(newColumnName)) {+ throw new Error(+ `Column "${newColumnName}" already exists in dataset "${datasetName}". Choose a different name.`+ );+ }++ // Derive the DuckDB table name from the resolved dataset id, not the+ // user-provided label: different labels can sanitize to the same table+ // name (e.g. "A-B" vs "A B"), which would clobber another dataset's+ // temp table inside DuckDB and run the SQL against unintended data.+ const dbTableName = datasetNameToTableName(dataId);+ // Pass the user-provided datasetName (label or id) to+ // loadTableIntoDuckDB — the documented KeplerContext contract — not+ // the resolved id.+ const db = await ctx.loadTableIntoDuckDB(datasetName, fieldNames, dbTableName);++ // Add-only: compute ONLY the new column in DuckDB. Existing columns are+ // never round-tripped through DuckDB/Arrow — `tableFromArrays` infers a+ // single Arrow type for `_geojson`, and a dataset mixing Polygon and+ // MultiPolygon features gets the shallower type, so the MultiPolygon+ // coordinates come back as nulls and the geometry disappears.+ // `buildAddColumnPayload` rebuilds the payload from the original kepler+ // values instead, appending the new column from this single-column result.+ // Escape double quotes in identifier names before embedding them in+ // quoted SQL identifiers — a `"` in copyFromColumn/newColumnName would+ // otherwise break the query or enable SQL injection into DuckDB. (The+ // `expression` is user-provided SQL by design, so it is not escaped.)+ const escapeIdent = (name: string) => name.replace(/"/g, '""');+ const appendedSql =+ copyFromColumn != null+ ? `"${escapeIdent(copyFromColumn)}" AS "${escapeIdent(newColumnName)}"`+ : `(${expression}) AS "${escapeIdent(newColumnName)}"`;+ const arrowResult = await db.query(`SELECT ${appendedSql} FROM "${dbTableName}"`);++ const {rows, fields} = buildAddColumnPayload(+ datasets,+ visState.layers,+ datasetName,+ newColumnName,+ arrowResult+ );+ ctx.dispatch(updateDataset(dataId, {rows, fields} as any));++ // LLM-facing preview: first 5 rows of the full (original + new) payload.+ const previewRows = rows+ .slice(0, 5)+ .map(r => Object.fromEntries(fields.map((f, i) => [f.name, r[i]])));+ const valueSource = copyFromColumn != null ? `copied from "${copyFromColumn}"` : `computed`;+ return {+ success: true,+ commandId: addColumnCommandId,+ data: {+ details: `Added column "${newColumnName}" to dataset "${datasetName}" (${valueSource}, ${rows.length} rows).`,+ addedColumns: [newColumnName],+ firstFiveRows: tableToLLMResult(previewRows)+ }+ };+ } catch (error) {+ return {+ success: false,+ commandId: addColumnCommandId,+ error: error instanceof Error ? error.message : String(error),+ data: {+ instruction: 'Please explain the error and give a plan to fix it. Then try again.'+ }+ };+ }+ }+ };+}diff --git a/src/mcp/src/commands/basemap-command.ts b/src/mcp/src/commands/basemap-command.tsnew file mode 100644index 000000000..b353efbc3--- /dev/null+++ b/src/mcp/src/commands/basemap-command.ts@@ -0,0 +1,54 @@+import type {RoomCommand} from './types';+import {z} from 'zod';+import {DEFAULT_MAP_STYLES} from '@kepler.gl/constants';+import {mapStyleChange} from '@kepler.gl/actions';+import type {KeplerContext} from './types';++export const basemapCommandId = 'map.set-basemap' as const;++export function getBasemapCommand(ctx: KeplerContext): RoomCommand {+ return {+ id: basemapCommandId,+ name: 'Set basemap',+ group: 'Map',+ description: 'Change the basemap style of the kepler.gl map.',+ metadata: {readOnly: false, riskLevel: 'low', idempotent: true},+ inputSchema: z.object({+ styleType: z.enum([+ 'no_map',+ 'dark-matter',+ 'positron',+ 'voyager',+ 'satellite',+ 'dark',+ 'light',+ 'muted',+ 'muted_night'+ ])+ }) as any,+ execute: async (_execCtx, input) => {+ const {styleType} = (input ?? {}) as {styleType: string};+ try {+ if (!DEFAULT_MAP_STYLES.find(style => style.id === styleType)) {+ throw new Error(`Invalid basemap style: ${styleType}.`);+ }+ ctx.dispatch(mapStyleChange(styleType));+ return {+ success: true,+ commandId: basemapCommandId,+ data: {details: `Basemap style changed to ${styleType}.`}+ };+ } catch (error) {+ return {+ success: false,+ commandId: basemapCommandId,+ error: error instanceof Error ? error.message : 'Unknown error',+ data: {+ instruction:+ 'Try to fix the error. If the error persists, ask the user to try with a different basemap style.'+ }+ };+ }+ }+ };+}diff --git a/src/mcp/src/commands/boundary-command.ts b/src/mcp/src/commands/boundary-command.tsnew file mode 100644index 000000000..070236878--- /dev/null+++ b/src/mcp/src/commands/boundary-command.ts@@ -0,0 +1,49 @@+import type {RoomCommand} from './types';+import {z} from 'zod';+import type {KeplerContext} from './types';++export const mapBoundaryCommandId = 'map.get-boundary' as const;++export function getMapBoundaryCommand(ctx: KeplerContext): RoomCommand {+ return {+ id: mapBoundaryCommandId,+ name: 'Get map boundary',+ group: 'Map',+ description:+ 'Get the boundary of the map. Northwest and Southeast coordinates in [longitude, latitude] format.',+ metadata: {readOnly: true, riskLevel: 'low', idempotent: true},+ inputSchema: z.object({}) as any,+ execute: async () => {+ try {+ const boundary = ctx.getMapBoundary();+ if (!boundary) {+ return {+ success: false,+ commandId: mapBoundaryCommandId,+ error: 'Map boundary not available.',+ data: {+ instruction: 'Please ensure the kepler.gl map is properly loaded and try again.'+ }+ };+ }+ return {+ success: true,+ commandId: mapBoundaryCommandId,+ data: {+ details: `Map boundary retrieved. NW: [${boundary.nw[0]}, ${boundary.nw[1]}], SE: [${boundary.se[0]}, ${boundary.se[1]}]`,+ boundary+ }+ };+ } catch (error) {+ return {+ success: false,+ commandId: mapBoundaryCommandId,+ error: error instanceof Error ? error.message : 'Unknown error',+ data: {+ instruction: 'Please ensure the kepler.gl map is properly loaded and try again.'+ }+ };+ }+ }+ };+}diff --git a/src/mcp/src/commands/command-wrappers.spec.ts b/src/mcp/src/commands/command-wrappers.spec.tsnew file mode 100644index 000000000..36e11382b--- /dev/null+++ b/src/mcp/src/commands/command-wrappers.spec.ts@@ -0,0 +1,62 @@+import {toolToCommand} from './command-wrappers';++type CommandResult = {success: boolean; error?: string; data?: Record<string, unknown>};++describe('toolToCommand', () => {+ it('propagates a failure carried in the message field (not just error)', async () => {+ const tool = {+ execute: async () => ({success: false, message: 'boom: bad input'})+ };+ const cmd = toolToCommand(tool as any, {id: 'test.tool', name: 'Test'});+ const result = (await cmd.execute({} as any, {})) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toBe('boom: bad input');+ });++ it('propagates a failure carried in the error field', async () => {+ const tool = {+ execute: async () => ({success: false, error: 'boom: bad input'})+ };+ const cmd = toolToCommand(tool as any, {id: 'test.tool', name: 'Test'});+ const result = (await cmd.execute({} as any, {})) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toBe('boom: bad input');+ });++ it('falls back to a generic message when a failure carries neither field', async () => {+ const tool = {+ execute: async () => ({success: false})+ };+ const cmd = toolToCommand(tool as any, {id: 'test.tool', name: 'Test'});+ const result = (await cmd.execute({} as any, {})) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toBe('Tool execution failed.');+ });++ it('returns no error on success', async () => {+ const tool = {+ execute: async () => ({success: true, details: 'ok'})+ };+ const cmd = toolToCommand(tool as any, {id: 'test.tool', name: 'Test'});+ const result = (await cmd.execute({} as any, {})) as CommandResult;++ expect(result.success).toBe(true);+ expect(result.error).toBeUndefined();+ });++ it('surfaces a thrown error', async () => {+ const tool = {+ execute: async () => {+ throw new Error('kaboom');+ }+ };+ const cmd = toolToCommand(tool as any, {id: 'test.tool', name: 'Test'});+ const result = (await cmd.execute({} as any, {})) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toBe('kaboom');+ });+});diff --git a/src/mcp/src/commands/command-wrappers.ts b/src/mcp/src/commands/command-wrappers.tsnew file mode 100644index 000000000..49611742f--- /dev/null+++ b/src/mcp/src/commands/command-wrappers.ts@@ -0,0 +1,110 @@+/**+ * Generic utility for converting an existing AI SDK tool into a sqlrooms+ * `RoomCommand`. Kept dependency-light (only `zod` + `RoomCommand` type) so it+ * can be reused by any in-browser skill system that wants to expose its+ * existing AI SDK tools as commands without rewriting them.+ *+ * The demo-app's own command factories return `RoomCommand` directly (preferred+ * when you own the command — see `basemap-command.ts` for the reference shape). This+ * wrapper is the fallback path for hosts that cannot rewrite their tools:+ * it folds the tool's `execute`, `inputSchema`, and `toModelOutput` (the+ * token-trim logic the AI SDK applies between tool call and model) into a+ * single `RoomCommand.execute` so the registry-stored result already carries+ * the model-facing subset.+ */++import type {RoomCommand} from './types';+import type {ZodType} from 'zod';++/** A built AI SDK tool, treated loosely for dynamic dispatch. */+export type AnyTool = {+ execute?: (args: any, options: any) => Promise<any>;+ toModelOutput?: (params: {output: any; toolCallId?: string}) => any;+ description?: string;+ inputSchema?: ZodType;+};++/** Metadata that the AI SDK tool does not carry but a `RoomCommand` requires. */+export type CommandMeta = {+ /** Stable, namespaced command id, e.g. `map.set-basemap`. */+ id: string;+ /** Human-readable name shown in the command palette / listings. */+ name: string;+ /** Optional grouping label, e.g. `Map`, `Data`, `GeoDa`. */+ group?: string;+ /** Optional search keywords. */+ keywords?: string[];+};++/**+ * Cast a concrete zod schema (e.g. `z.object({...})`, which is `ZodObject<...>`)+ * to the `ZodType<unknown>` that `RoomCommand.inputSchema` expects. The+ * installed zod `ZodObject` is not structurally assignable to sqlrooms'+ * `ZodType<unknown>` (covariance on the output type), so a cast is required at+ * the assignment site. This helper centralizes that cast.+ */+export function asInputSchema(schema: ZodType): ZodType<unknown> {+ return schema as unknown as ZodType<unknown>;+}++/**+ * Wrap an existing AI SDK tool as a sqlrooms `RoomCommand`. The command's+ * `execute` calls the tool's `execute` and then applies the tool's+ * `toModelOutput` (if any) so the trimmed, model-facing shape is what the+ * registry stores and downstream surfaces (AI skill, palette, CLI, MCP) see.+ */+export function toolToCommand(tool: AnyTool, meta: CommandMeta): RoomCommand {+ return {+ id: meta.id,+ name: meta.name,+ description: tool.description,+ group: meta.group,+ keywords: meta.keywords,+ inputSchema: tool.inputSchema as any,+ execute: async (ctx, input) => {+ if (!tool.execute || typeof tool.execute !== 'function') {+ return {+ success: false,+ commandId: meta.id,+ error: 'Tool has no execute function.'+ };+ }+ try {+ // Thread the caller's AbortSignal through so hosts (WebMCP / bridge)+ // can cancel long-running wrapped tools when the agent aborts. Tools+ // that don't use a signal ignore it.+ const rawOutput = await tool.execute(input ?? {}, {+ toolCallId: meta.id,+ signal: ctx.signal+ });+ const trimmed =+ typeof tool.toModelOutput === 'function'+ ? tool.toModelOutput({output: rawOutput, toolCallId: meta.id})+ : rawOutput;+ return {+ success: rawOutput?.success ?? true,+ commandId: meta.id,+ // A structured failure (success:false) that didn't throw must still+ // carry an error message — otherwise callers see {success:false,+ // error:undefined} and downstream formatters misreport it as a+ // success. Many tool/result shapes (including RoomCommandResult)+ // carry the failure in a `message` field rather than `error`, so+ // fall back to that before the generic message.+ error:+ rawOutput?.success === false+ ? (rawOutput?.error as string | undefined) ??+ (rawOutput?.message as string | undefined) ??+ 'Tool execution failed.'+ : undefined,+ data: typeof trimmed === 'object' && trimmed !== null ? trimmed : {details: trimmed}+ };+ } catch (error) {+ return {+ success: false,+ commandId: meta.id,+ error: error instanceof Error ? error.message : String(error)+ };+ }+ }+ };+}diff --git a/src/mcp/src/commands/dataset-context-command.ts b/src/mcp/src/commands/dataset-context-command.tsnew file mode 100644index 000000000..a08778a93--- /dev/null+++ b/src/mcp/src/commands/dataset-context-command.ts@@ -0,0 +1,61 @@+import type {RoomCommand} from './types';+import {z} from 'zod';+import type {KeplerContext} from './types';++export const datasetContextCommandId = 'map.get-dataset-context' as const;++export function getDatasetContextCommand(ctx: KeplerContext): RoomCommand {+ return {+ id: datasetContextCommandId,+ name: 'Get dataset context',+ group: 'Map',+ description:+ 'Get all loaded kepler.gl datasets with their fields and layer configurations. ' ++ 'Returns each dataset name, id, field name→type mappings, and the layers ' ++ '(id, label, type, geometryMode, geometryColumns) bound to it.',+ metadata: {readOnly: true, riskLevel: 'low', idempotent: true},+ inputSchema: z.object({}) as any,+ execute: async () => {+ try {+ const context = ctx.getDatasetContext();+ if (!context) {+ return {+ success: false,+ commandId: datasetContextCommandId,+ error: 'No datasets or layers available.',+ data: {+ instruction: 'Please ensure the kepler.gl map has loaded datasets and try again.'+ }+ };+ }+ // Accept either a pure-JSON context or the two-part "human line + JSON"+ // format: hosts may return either, so don't assume the first line is a+ // preface.+ const trimmed = context.trim();+ const datasets = JSON.parse(+ trimmed.startsWith('[') || trimmed.startsWith('{')+ ? trimmed+ : context.split('\n').slice(1).join('\n')+ );+ const count = Array.isArray(datasets) ? datasets.length : Object.keys(datasets).length;+ return {+ success: true,+ commandId: datasetContextCommandId,+ data: {+ details: `${count} dataset(s) loaded.`,+ datasets+ }+ };+ } catch (error) {+ return {+ success: false,+ commandId: datasetContextCommandId,+ error: error instanceof Error ? error.message : 'Unknown error',+ data: {+ instruction: 'Please ensure the kepler.gl map is properly loaded and try again.'+ }+ };+ }+ }+ };+}diff --git a/src/mcp/src/commands/index.ts b/src/mcp/src/commands/index.tsnew file mode 100644index 000000000..abf13a02a--- /dev/null+++ b/src/mcp/src/commands/index.ts@@ -0,0 +1,87 @@+import type {RoomCommand} from './types';+import type {KeplerContext} from './types';+import {getBasemapCommand} from './basemap-command';+import {getViewModeCommand} from './view-mode-command';+import {getMapBoundaryCommand} from './boundary-command';+import {getAddLayerCommand} from './layer-creation-command';+import {getUpdateLayerColorCommand} from './layer-style-command';+import {getLoadDataCommand} from './load-data-command';+import {getSaveDataCommand} from './save-data-command';+import {getTableCommand} from './table-command';+import {getAddColumnCommand} from './add-column-command';+import {getAddTimeFilterCommand} from './time-filter-command';+import {getToggleTimeFilterCommand} from './toggle-time-filter-command';+import {getSplitViewCommand} from './split-view-command';+import {getDatasetContextCommand} from './dataset-context-command';++/**+ * Owner string under which all kepler-ai commands are registered in the+ * room-store command registry. Used by `registerCommandsForOwner` /+ * `unregisterCommandsForOwner` in the host's store wiring.+ */+export const KEPLER_COMMAND_OWNER = 'kepler-ai';++/**+ * Build the kepler-gl map-mutation commands for a given `KeplerContext`.+ * Returns a map keyed by command id (e.g. `map.set-basemap`) so the registry+ * registration is a flat merge.+ */+export function getKeplerCommands(ctx: KeplerContext): Record<string, RoomCommand> {+ const commands = [+ getBasemapCommand(ctx),+ getViewModeCommand(ctx),+ getMapBoundaryCommand(ctx),+ getAddLayerCommand(ctx),+ getUpdateLayerColorCommand(ctx),+ getLoadDataCommand(ctx),+ getSaveDataCommand(ctx),+ getTableCommand(ctx),+ getAddColumnCommand(ctx),+ getAddTimeFilterCommand(ctx),+ getToggleTimeFilterCommand(ctx),+ getSplitViewCommand(ctx),+ getDatasetContextCommand(ctx)+ ];+ return Object.fromEntries(commands.map(c => [c.id, c]));+}++export {getBasemapCommand} from './basemap-command';+export {getViewModeCommand} from './view-mode-command';+export {getMapBoundaryCommand} from './boundary-command';+export {getAddLayerCommand, guessDefaultLayer} from './layer-creation-command';+export {getUpdateLayerColorCommand} from './layer-style-command';+export {getLoadDataCommand} from './load-data-command';+export {getSaveDataCommand} from './save-data-command';+export {getTableCommand} from './table-command';+export {getAddColumnCommand} from './add-column-command';+export {getAddTimeFilterCommand} from './time-filter-command';+export {getToggleTimeFilterCommand} from './toggle-time-filter-command';+export {getSplitViewCommand} from './split-view-command';+export {getDatasetContextCommand} from './dataset-context-command';+export {toolToCommand, asInputSchema} from './command-wrappers';+export type {AnyTool, CommandMeta} from './command-wrappers';+export type {+ KeplerContext,+ KeplerStateAccessors,+ VisState,+ RoomCommandResult,+ RoomCommandExecuteOutput,+ ToolDescriptor+} from './types';+export {+ datasetNameToTableName,+ convertArrowRowToObject,+ arrowTableToObjects,+ tableToLLMResult,+ formatResultsForLLM,+ NUMBER_OF_ROWS_RETURN_TO_LLM,+ LLM_PREVIEW_MAX_TOTAL_LENGTH,+ LLM_PREVIEW_MAX_VALUE_LENGTH,+ getValuesFromDataset,+ getValuesFromVectorTileLayer,+ isObjectColumn,+ isVectorTileLayer,+ stringifyObjectColumn,+ restoreObjectColumns,+ buildAddColumnPayload+} from './utils';diff --git a/src/mcp/src/commands/layer-creation-command.spec.ts b/src/mcp/src/commands/layer-creation-command.spec.tsnew file mode 100644index 000000000..39d600d0a--- /dev/null+++ b/src/mcp/src/commands/layer-creation-command.spec.ts@@ -0,0 +1,278 @@+import {getAddLayerCommand} from './layer-creation-command';+import KeplerTable from '@kepler.gl/table';+import {ALL_FIELD_TYPES} from '@kepler.gl/constants';++/**+ * Build a plain JS dataset with two point lat/lng pairs (origin + destination)+ * plus a numeric flow-magnitude column — the shape the flow layer branch of+ * guessDefaultLayer consumes. `findPointFieldPairs` keys off `_lat`/`_lng`+ * suffixes, so origin_lat/origin_lng and dest_lat/dest_lng pair up.+ */+async function makeTwoPairTable() {+ const table = new KeplerTable({color: [255, 0, 0]} as any);+ await table.importData({+ data: {+ rows: [+ // origin_lat, origin_lng, dest_lat, dest_lng, count+ [37.77, -122.42, 37.79, -122.41, 5],+ [37.78, -122.45, 37.76, -122.4, 12],+ [37.74, -122.44, 37.8, -122.39, 3]+ ],+ fields: [+ {name: 'origin_lat', type: ALL_FIELD_TYPES.real},+ {name: 'origin_lng', type: ALL_FIELD_TYPES.real},+ {name: 'dest_lat', type: ALL_FIELD_TYPES.real},+ {name: 'dest_lng', type: ALL_FIELD_TYPES.real},+ {name: 'count', type: ALL_FIELD_TYPES.integer}+ ]+ } as any+ });+ return table;+}++function makeCtx(table: KeplerTable) {+ let dispatched: any = null;+ const ctx = {+ getVisState: () => ({datasets: {[table.id as string]: table}, layers: []}),+ dispatch: (action: any) => {+ dispatched = action;+ },+ getValuesFromDataset: () => [],+ getMapBoundary: () => null,+ getMapboxToken: () => undefined,+ getDatasetContext: () => ''+ };+ return {ctx, getDispatched: () => dispatched};+}++type CommandResult = {success: boolean; error?: string; data?: Record<string, unknown>};++describe('map.add-layer (flow)', () => {+ it('builds a flow layer from the first two point field pairs, with weighted count', async () => {+ const table = await makeTwoPairTable();+ const {ctx, getDispatched} = makeCtx(table);++ const cmd = getAddLayerCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: table.label,+ layerType: 'flow',+ layerName: 'Trips flow',+ countColumn: 'count'+ })) as CommandResult;++ expect(result.success).toBe(true);+ const action = getDispatched();+ expect(action).toBeTruthy();+ expect(action.type).toMatch(/ADD_LAYER/);+ expect(action.config.type).toBe('flow');+ expect(action.config.config.label).toBe('Trips flow');+ // buildLayerConfig flattens the column refs to column names. Optional+ // columns the flow layer initializes empty (sourceName/targetName/targetH3)+ // arrive as `null` — the reducer's validateLayersByDatasets runs with+ // allowEmptyColumn, so subset-match on the meaningful ones.+ expect(action.config.config.columns).toMatchObject({+ lat0: 'origin_lat',+ lng0: 'origin_lng',+ lat1: 'dest_lat',+ lng1: 'dest_lng',+ count: 'count'+ });+ // count column must remain attached to the flow layer as the magnitude+ expect(action.config.config.columns.count).toBe('count');+ });++ it('still builds a flow layer without a count column (all weights 1)', async () => {+ const table = await makeTwoPairTable();+ const {ctx, getDispatched} = makeCtx(table);++ const cmd = getAddLayerCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: table.label,+ layerType: 'flow'+ })) as CommandResult;++ expect(result.success).toBe(true);+ const action = getDispatched();+ expect(action.config.type).toBe('flow');+ expect(action.config.config.columns).toMatchObject({+ lat0: 'origin_lat',+ lng0: 'origin_lng',+ lat1: 'dest_lat',+ lng1: 'dest_lng'+ });+ // no count column → magnitude stays unset (null), so all flows weigh 1+ expect(action.config.config.columns.count).toBeNull();+ });++ it('rejects an invalid layerType instead of falling back to a default layer', async () => {+ const table = await makeTwoPairTable();+ const {ctx, getDispatched} = makeCtx(table);++ const cmd = getAddLayerCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: table.label,+ layerType: 'bogus'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/Invalid layerType/);+ // no layer added+ expect(getDispatched()).toBeNull();+ });+});++/**+ * Build a vector-field dataset: lat/lng sample points plus direction columns.+ * `vector` picks the encoding — u/v components or speed/direction.+ */+async function makeVectorTable(vector: 'uv' | 'speedDir') {+ const table = new KeplerTable({color: [255, 0, 0]} as any);+ const vectorFields =+ vector === 'uv'+ ? [+ {name: 'u', type: ALL_FIELD_TYPES.real},+ {name: 'v', type: ALL_FIELD_TYPES.real}+ ]+ : [+ {name: 'wind_speed', type: ALL_FIELD_TYPES.real},+ {name: 'wind_dir', type: ALL_FIELD_TYPES.real}+ ];+ await table.importData({+ data: {+ rows: [+ [37.77, -122.42, 1.5, 0.4],+ [37.78, -122.45, 2.1, -0.2],+ [37.74, -122.44, 0.9, 1.1]+ ],+ fields: [+ {name: 'lat', type: ALL_FIELD_TYPES.real},+ {name: 'lng', type: ALL_FIELD_TYPES.real},+ ...vectorFields+ ]+ } as any+ });+ return table;+}++describe('map.add-layer (flowField)', () => {+ it('builds a UV flow field from lat/lng + u/v, with auto-detected columns', async () => {+ const table = await makeVectorTable('uv');+ const {ctx, getDispatched} = makeCtx(table);++ const cmd = getAddLayerCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: table.label,+ layerType: 'flowField',+ layerName: 'Wind field'+ })) as CommandResult;++ expect(result.success).toBe(true);+ const action = getDispatched();+ expect(action.config.type).toBe('flowField');+ expect(action.config.config.columnMode).toBe('UV');+ expect(action.config.config.columns).toMatchObject({+ lat: 'lat',+ lng: 'lng',+ u: 'u',+ v: 'v'+ });+ });++ it('builds a SPEED_DIR flow field from explicitly named speed/direction columns', async () => {+ const table = await makeVectorTable('speedDir');+ const {ctx, getDispatched} = makeCtx(table);++ const cmd = getAddLayerCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: table.label,+ layerType: 'flowField',+ flowField: {+ mode: 'SPEED_DIR',+ speedColumn: 'wind_speed',+ directionColumn: 'wind_dir',+ colorBySpeed: true+ }+ })) as CommandResult;++ expect(result.success).toBe(true);+ const action = getDispatched();+ expect(action.config.type).toBe('flowField');+ expect(action.config.config.columnMode).toBe('SPEED_DIR');+ expect(action.config.config.columns).toMatchObject({+ lat: 'lat',+ lng: 'lng',+ speed: 'wind_speed',+ direction: 'wind_dir'+ });+ expect(action.config.config.visConfig.colorBySpeed).toBe(true);+ });++ it('errors clearly when the dataset has no vector columns', async () => {+ const table = await makeTwoPairTable();+ const {ctx, getDispatched} = makeCtx(table);++ const cmd = getAddLayerCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: table.label,+ layerType: 'flowField'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/needs a vector/);+ expect(getDispatched()).toBeNull();+ });+});++describe('map.add-layer (colorMap validation)', () => {+ it('finds a unique category that appears only later in a large dataset (full scan)', async () => {+ // 20k rows; the wanted category 'z' exists ONLY at index 10000 — beyond the+ // old prefix scan (first 10k rows), so a bounded sample would falsely flag+ // it as missing. The full scan (with early-exit) finds it.+ const rows: any[] = [];+ for (let i = 0; i < 20000; i++) {+ rows.push([37.77, -122.42, i === 10000 ? 'z' : 'a']);+ }+ const table = new KeplerTable({color: [255, 0, 0]} as any);+ await table.importData({+ data: {+ rows,+ fields: [+ {name: 'lat', type: ALL_FIELD_TYPES.real},+ {name: 'lng', type: ALL_FIELD_TYPES.real},+ {name: 'category', type: ALL_FIELD_TYPES.string}+ ]+ } as any+ });+ const {ctx, getDispatched} = makeCtx(table);++ const cmd = getAddLayerCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: table.label,+ layerType: 'point',+ colorBy: 'category',+ colorType: 'unique',+ colorMap: [{value: 'z', color: '#1f77b4'}]+ })) as CommandResult;++ expect(result.success).toBe(true);+ expect(getDispatched()).toBeTruthy();+ });++ it('still rejects a category that does not exist anywhere in the data', async () => {+ const table = await makeTwoPairTable();+ const {ctx, getDispatched} = makeCtx(table);++ const cmd = getAddLayerCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: table.label,+ layerType: 'flow',+ colorBy: 'count',+ colorType: 'unique',+ colorMap: [{value: 'nope', color: '#1f77b4'}]+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/not found in field/);+ expect(getDispatched()).toBeNull();+ });+});diff --git a/src/mcp/src/commands/layer-creation-command.ts b/src/mcp/src/commands/layer-creation-command.tsnew file mode 100644index 000000000..0fce4853b--- /dev/null+++ b/src/mcp/src/commands/layer-creation-command.ts@@ -0,0 +1,665 @@+import type {RoomCommand} from './types';+import {z} from 'zod';+import {GEOJSON_FIELDS} from '@kepler.gl/constants';+import {LayerClasses} from '@kepler.gl/layers';+import type KeplerTable from '@kepler.gl/table';+import type {Datasets} from '@kepler.gl/table';+import {findDefaultLayer, findMapBounds} from '@kepler.gl/reducers';+import {addLayer as addLayerAction, fitBounds} from '@kepler.gl/actions';+import type {KeplerContext} from './types';++/**+ * Unique layer id. Date.now()-based ids can collide when multiple layers are+ * created within the same millisecond (rapid successive tool calls), producing+ * duplicate layer ids and unpredictable reducer behavior. Append a random+ * suffix — the same Math.random().toString(36) trick kepler's generateHashId+ * uses — so ids stay unique.+ */+function uniqueLayerId(prefix = 'layer'): string {+ return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;+}++export function guessDefaultLayer(+ dataset: KeplerTable,+ layerType: string,+ options?: {countColumn?: string}+) {+ if (layerType === 'heatmap') {+ if (dataset.fieldPairs && dataset.fieldPairs.length > 0) {+ const props = dataset.fieldPairs.map(fieldPair => ({+ isVisible: true,+ label: 'Heatmap',+ columns: fieldPair.pair+ }));+ const layer = new LayerClasses.heatmap(props[0]);+ return layer;+ }+ } else if (layerType === 'hexagon') {+ if (dataset.fieldPairs && dataset.fieldPairs.length > 0) {+ const props = dataset.fieldPairs.map(fieldPair => ({+ isVisible: true,+ label: 'Hexbin',+ columns: fieldPair.pair+ }));+ const layer = new LayerClasses.hexagon(props[0]);+ return layer;+ }+ } else if (layerType === 'cluster') {+ if (dataset.fieldPairs && dataset.fieldPairs.length > 0) {+ const props = dataset.fieldPairs.map(fieldPair => ({+ isVisible: true,+ label: 'Cluster',+ columns: fieldPair.pair+ }));+ const layer = new LayerClasses.cluster(props[0]);+ return layer;+ }+ } else if (layerType === 'trip') {+ const layers = findDefaultLayer(dataset, [LayerClasses.trip] as any);+ const layer = layers.find(l => l.type === layerType);+ if (layer) return layer;+ throw new Error(+ `Failed to create a trip layer. Trip layer requires id, lat, lng, and timestamp columns.`+ );+ } else if (layerType === 'flow') {+ // Flow layers are never auto-detected (findDefaultLayerProps returns+ // {props: []}), so build one explicitly from the first two point lat/lng+ // field pairs — the same source/target pair logic the default arc layer+ // uses: pair[0] = origin (lat0/lng0), pair[1] = destination (lat1/lng1).+ // The count column (flow magnitude) is optional; without it every flow+ // renders at weight 1.+ const pairs = dataset.fieldPairs || [];+ if (pairs.length < 2) {+ throw new Error(+ `Failed to create a flow layer. Flow layer requires two point lat/lng pairs ` ++ `(origin + destination), e.g. origin_lat/origin_lng and dest_lat/dest_lng.`+ );+ }+ const columns: any = {+ lat0: pairs[0].pair.lat,+ lng0: pairs[0].pair.lng,+ lat1: pairs[1].pair.lat,+ lng1: pairs[1].pair.lng+ };+ if (options?.countColumn && dataset.getColumnFieldIdx(options.countColumn) >= 0) {+ columns.count = {+ value: options.countColumn,+ fieldIdx: dataset.getColumnFieldIdx(options.countColumn)+ };+ }+ // LayerClasses' computed keys (keyMirror) aren't statically named, so+ // access flow like the trip branch accesses trip: through an `as any` cast.+ const layer = new (LayerClasses as any).flow({+ isVisible: true,+ label: `${pairs[0].defaultName} -> ${pairs[1].defaultName} flow`,+ columns+ });+ return layer;+ }+ const defaultLayers = findDefaultLayer(dataset, LayerClasses as any);+ const layer = defaultLayers.find(l => l.type === layerType);+ // Return null (not a fallback to the first default layer) when the requested+ // type can't be created — silently substituting a different layer type (e.g.+ // requesting "h3" and getting a point layer) violates the command contract+ // and makes failures hard to diagnose. The caller errors clearly on null.+ return layer || null;+}++/** Column names the flow field layer resolves when the caller doesn't name them. */+const FLOW_FIELD_ALTITUDE_COLUMNS = ['altitude', 'alt', 'elevation', 'elev', 'elv', 'height', 'z'];+const FLOW_FIELD_MODES = ['UV', 'SPEED_DIR', 'ELEVATION'] as const;+type FlowFieldMode = (typeof FLOW_FIELD_MODES)[number];++type FlowFieldOptions = {+ mode?: FlowFieldMode;+ uColumn?: string;+ vColumn?: string;+ speedColumn?: string;+ directionColumn?: string;+ altitudeColumn?: string;+ colorBySpeed?: boolean;+};++/**+ * Flow Field is a vector/streamline layer: each row is a sample point carrying+ * a position plus a direction — u/v components, speed/direction, or an altitude+ * whose downhill gradient supplies the direction. Unlike the origin→destination+ * `flow` layer it needs no second point pair, and unlike `trip` it animates+ * itself, so no time filter belongs on it.+ */+function buildFlowFieldLayer(+ dataset: KeplerTable,+ position: {latitudeColumn?: string; longitudeColumn?: string},+ options: FlowFieldOptions = {}+) {+ const hasColumn = (name?: string) => !!name && dataset.getColumnFieldIdx(name) >= 0;+ const columnRef = (name: string) => {+ const fieldIdx = dataset.getColumnFieldIdx(name);+ if (fieldIdx < 0) {+ const available = dataset.fields?.map((f: any) => f.name).join(', ') ?? '';+ throw new Error(+ `Column "${name}" not found in dataset "${dataset.label}". Available columns: ${available}`+ );+ }+ return {value: name, fieldIdx};+ };++ // Position: explicit lat/lng, else the dataset's first detected point pair,+ // else a GeoJSON geometry column (one position per feature).+ let positionColumns: Record<string, any> | null = null;+ if (position.latitudeColumn && position.longitudeColumn) {+ positionColumns = {+ lat: columnRef(position.latitudeColumn),+ lng: columnRef(position.longitudeColumn)+ };+ } else {+ const pair = dataset.fieldPairs?.[0]?.pair;+ if (pair?.lat && pair?.lng) {+ positionColumns = {lat: pair.lat, lng: pair.lng};+ } else {+ const geoField = dataset.fields?.find(+ (f: any) => f.type === 'geojson' || GEOJSON_FIELDS.geojson.includes(f.name)+ );+ if (geoField) {+ positionColumns = {geojson: {value: geoField.name, fieldIdx: geoField.fieldIdx}};+ }+ }+ }+ if (!positionColumns) {+ throw new Error(+ 'A flow field layer needs a position: lat/lng columns (auto-detected, or pass ' ++ 'latitudeColumn/longitudeColumn) or a GeoJSON geometry column.'+ );+ }++ const altitudeName =+ options.altitudeColumn || FLOW_FIELD_ALTITUDE_COLUMNS.find(name => hasColumn(name)) || null;++ const mode: FlowFieldMode | null =+ options.mode ||+ (options.uColumn || options.vColumn || (hasColumn('u') && hasColumn('v'))+ ? 'UV'+ : options.speedColumn ||+ options.directionColumn ||+ (hasColumn('speed') && hasColumn('direction'))+ ? 'SPEED_DIR'+ : altitudeName+ ? 'ELEVATION'+ : null);+ if (!mode) {+ throw new Error(+ 'A flow field layer needs a vector: u/v columns, speed/direction columns, or an ' ++ 'altitude column (pass flowField.uColumn/vColumn/speedColumn/directionColumn/' ++ 'altitudeColumn when the names differ).'+ );+ }++ let flowColumns: Record<string, any>;+ if (mode === 'UV') {+ flowColumns = {+ u: columnRef(options.uColumn || 'u'),+ v: columnRef(options.vColumn || 'v')+ };+ } else if (mode === 'SPEED_DIR') {+ flowColumns = {+ speed: columnRef(options.speedColumn || 'speed'),+ direction: columnRef(options.directionColumn || 'direction')+ };+ } else {+ if (!altitudeName) {+ throw new Error(+ 'A flow field layer in ELEVATION mode needs an altitude column (pass flowField.altitudeColumn).'+ );+ }+ flowColumns = {altitude: columnRef(altitudeName)};+ }++ // UV and SPEED_DIR may also carry an altitude, which lifts the streamlines.+ const altitudeColumn =+ mode === 'ELEVATION' || !altitudeName ? {} : {altitude: columnRef(altitudeName)};++ const layer = new (LayerClasses as any).flowField({+ isVisible: true,+ label: 'Flow Field',+ color: [255, 255, 255],+ columnMode: mode,+ columns: {...positionColumns, ...flowColumns, ...altitudeColumn}+ });+ if (options.colorBySpeed) {+ layer.config.visConfig = {...layer.config.visConfig, colorBySpeed: true};+ }+ return layer;+}++function buildLayerConfig(+ layer: any,+ datasetId: string,+ layerName: string | undefined,+ sourceName: string,+ layerType: string+) {+ const layerId = layer.id || uniqueLayerId();+ const columns = layer.config?.columns || {};++ return {+ id: layerId,+ type: layer.type,+ config: {+ ...layer.config,+ dataId: datasetId,+ isVisible: true,+ label: layerName || `${sourceName}-${layerType}`,+ columns: Object.keys(columns).reduce<Record<string, any>>((acc, key) => {+ const column = columns[key];+ if (column) {+ acc[key] = column.value;+ }+ return acc;+ }, {}),+ visConfig: {+ ...layer.config?.visConfig+ }+ }+ };+}++function applyColorConfig(+ newLayer: any,+ dataset: KeplerTable,+ args: {+ simpleColor?: string;+ colorBy?: string;+ colorType?: 'breaks' | 'unique';+ colorMap?: Array<{value: string | number | null; color: string}>;+ }+) {+ if (args.simpleColor) {+ const color = args.simpleColor+ .replace(/[^\d,]/g, '')+ .split(',')+ .map(Number);+ if (color.length === 3) {+ newLayer.config.color = color;+ }+ }++ const {colorBy, colorType, colorMap: providedColorMap} = args;++ if (colorBy) {+ const colorField = dataset.fields.find(f => f.name === colorBy);+ if (!colorField) {+ throw new Error(`Field ${colorBy} not found.`);+ }++ // For categorical (customOrdinal) color maps, every value becomes the scale+ // domain, so it must be a real value present in the data. The agent must not+ // invent category labels — get them via geoda.analysis (analysis: 'classify',+ // method: 'unique values'). Rejecting here turns a silent wrong render into a+ // recoverable error. Only run this when colorType is explicitly 'unique':+ // an omitted colorType defaults to a continuous (breaks) scale, whose+ // colorMap values are break boundaries, not data values.+ if (colorType === 'unique' && providedColorMap) {+ // Validate without materializing the whole column: scan rows, deleting+ // matches from a small `wanted` set (early-exit when all are found),+ // while collecting a small sample of actual values for the error message.+ // Scan ALL rows — a bounded sample (prefix OR fixed-stride) can+ // systematically miss a category that exists later in the data and+ // falsely report it as "not found". The early-exit keeps the common case+ // (all categories found early) fast; only a genuinely missing category+ // costs a full scan, which is the price of an accurate error.+ const wanted = new Set(providedColorMap.map(c => c.value));+ const sample: unknown[] = [];+ const seen = new Set<unknown>();+ for (let i = 0; i < dataset.length && wanted.size > 0; i++) {+ const v = dataset.getValue(colorBy, i);+ if (wanted.has(v)) {+ wanted.delete(v);+ } else if (!seen.has(v) && sample.length < 20) {+ seen.add(v);+ sample.push(v);+ }+ }+ if (wanted.size > 0) {+ const missing = [...wanted];+ throw new Error(+ `colorMap value(s) ${missing+ .map(v => JSON.stringify(v))+ .join(', ')} not found in field "${colorBy}". ` ++ `Actual unique values: ${sample.map(v => JSON.stringify(v)).join(', ')}${+ sample.length >= 20 ? ', …' : ''+ }. ` ++ `Call geoda.analysis (analysis: 'classify', method: 'unique values') to get the real values.`+ );+ }+ }++ // colorType is optional; when omitted, default to a continuous (breaks)+ // scale so numeric fields colored via colorBy aren't mis-colored as+ // categorical. Only an explicit 'unique' selects the categorical scale.+ const colorScale = colorType === 'unique' ? 'customOrdinal' : 'custom';++ // Only force a custom palette when the caller provided an explicit+ // colorMap. A synthetic single-entry colorMap ({value: null, color:+ // '#333333'}) would route through kepler's custom colorMap scale path and+ // render everything as the no-value/unknown color; without an explicit+ // colorMap, bind the color field and let kepler.gl's default color range+ // apply.+ const colorRange = providedColorMap+ ? ({+ name: 'color.customPalette',+ type: 'custom',+ category: 'Custom',+ colors: providedColorMap.map(c => c.color),+ colorMap: providedColorMap.map(c => [c.value, c.color])+ } as const)+ : null;++ if (newLayer.type === 'heatmap') {+ if (colorRange && providedColorMap && providedColorMap.length > 1) {+ newLayer.config.visConfig['colorRange'] = {...colorRange};+ }+ } else {+ newLayer.config['colorScale'] = colorScale;+ newLayer.config['colorField'] = colorField;+ newLayer.config['strokeColorScale'] = colorScale;+ newLayer.config['strokeColorField'] = colorField;+ newLayer.config.visConfig['filled'] = true;+ if (colorRange) {+ newLayer.config.visConfig['colorRange'] = colorRange;+ newLayer.config.visConfig['strokeColorRange'] = colorRange;+ }+ }+ }+}++export const addLayerCommandId = 'map.add-layer' as const;++export function getAddLayerCommand(ctx: KeplerContext): RoomCommand {+ return {+ id: addLayerCommandId,+ name: 'Add map layer',+ group: 'Map',+ description: `Add a kepler.gl map layer from a dataset.+IMPORTANT: generated layer names must be unique.++LAYER TYPES:+- point: Point markers (requires lat/lng columns)+- flow: Origin->destination flow map (requires two point lat/lng pairs, auto-detected)+- flowField: Animated streamlines over a vector field (u/v, speed/direction, or altitude)+- h3: H3 hexagon cells (requires hexId column)+- geojson: Polygon/geometry features (uses geometry column, usually auto-detected)+- hexagon: Hexagonal binning of points+- heatmap: Heat map visualization+- cluster: Clustered point visualization+- arc/line: Arc or line connections between points+- grid: Grid binning+- trip: Animated trip (flights, deliveries, vessels)+- s2: S2 geometry cells++FLOW MAPS (layerType 'flow'):+For origin->destination flows use layerType 'flow' — a dedicated flow layer that draws+locations and weighted flows between them. It needs TWO point lat/lng pairs in the+dataset (source pair + destination pair), which are auto-detected. Prefer 'flow' over+'arc' for O-D flows; 'arc' draws straight great-circle lines without location clustering+or flow aggregation. To weight the flows by a value column (flow magnitude), pass+countColumn with the column name — omit it to render all flows at weight 1.++FLOW FIELD (layerType 'flowField'):+Animated streamlines over a vector field — wind, currents, or downhill flow. It is NOT+the origin->destination 'flow' layer: 'flow' joins two point pairs, 'flowField' draws+many short lines through a field of vectors, one row per sample point.+The direction comes from one of three column sets, auto-detected in this order:+- u/v components (default mode 'UV'), optionally with an altitude column+- speed + direction (mode 'SPEED_DIR')+- altitude only (mode 'ELEVATION'): the downhill gradient gives the direction+Position is lat/lng (auto-detected, or latitudeColumn/longitudeColumn) or a GeoJSON+geometry column. When the dataset names the columns differently, pass flowField.mode+plus flowField.uColumn/vColumn/speedColumn/directionColumn/altitudeColumn.+Set flowField.colorBySpeed true to color lines by local speed; otherwise simpleColor+applies. colorBy/colorMap do not apply to this layer. Do NOT add a time filter — the+flow field animates itself.++BASIC MAP:+- Use datasetName, latitudeColumn/longitudeColumn (for point maps), and layerType+- Omit color-related parameters for simple visualization, use simpleColor instead.++COLOR MAPPING:+- If user requests color visualization, use available columns in the dataset+- Use geoda.analysis (analysis: 'classify') to classify data into bins or unique values when needed+- For continuous data (colorType 'breaks'):+ [{value: 0, color: '#fee5d9'}, {value: 50, color: '#fcae91'}, {value: 100, color: '#fb6a4a'}, {value: null, color: '#de2d26'}]+ The last entry with value: null represents the color for the highest values+- For categorical data (colorType 'unique'):+ [{value: 'category1', color: '#1f77b4'}, {value: 'category2', color: '#ff7f0e'}]+ HARD RULE: the colorMap values MUST be the actual unique values present in the data.+ Call geoda.analysis (analysis: 'classify', method: 'unique values') first and use the+ returned uniqueValues verbatim. NEVER invent category labels from the field name —+ the command rejects values that do not exist in the data.+- If the user doesn't specify colors, omit colorBy/colorMap — kepler.gl applies its default color range automatically++For geojson datasets:+- Use geometryColumn: '_geojson' and layerType: 'geojson' even for point collections+`,+ metadata: {readOnly: false, riskLevel: 'medium', idempotent: false},+ inputSchema: z.object({+ datasetName: z+ .string()+ .describe('The name (label) or id of the dataset. Prefer the label when known.'),+ latitudeColumn: z.string().optional(),+ longitudeColumn: z.string().optional(),+ layerName: z+ .string()+ .optional()+ .describe('Generate a unique name for the layer based on the context.'),+ layerType: z.enum([+ 'point',+ 'flow',+ 'flowField',+ 'arc',+ 'line',+ 'grid',+ 'hexagon',+ 'geojson',+ 'cluster',+ 'heatmap',+ 'h3',+ 'trip',+ 's2'+ ]),+ flowField: z+ .object({+ mode: z.enum(FLOW_FIELD_MODES).optional(),+ uColumn: z.string().optional(),+ vColumn: z.string().optional(),+ speedColumn: z.string().optional(),+ directionColumn: z.string().optional(),+ altitudeColumn: z.string().optional(),+ colorBySpeed: z.boolean().optional()+ })+ .optional()+ .describe(+ 'For layerType "flowField" only: how the vector field is encoded. The mode is ' ++ 'inferred from the columns (u/v, speed/direction, otherwise altitude); the ' ++ '*Column fields name the columns when they differ from those defaults.'+ ),+ simpleColor: z+ .string()+ .optional()+ .describe(+ 'The color of the layer e.g. [255, 0, 0]. Only used for simple map visualization (no colorBy, colorType, colorMap).'+ ),+ colorBy: z.string().optional(),+ colorType: z.enum(['breaks', 'unique']).optional(),+ countColumn: z+ .string()+ .optional()+ .describe(+ 'For layerType "flow" (and only flow): a numeric column whose value weights each flow (flow magnitude). Omit to render all flows at weight 1.'+ ),+ colorMap: z+ .array(+ z.object({+ value: z.union([z.string(), z.number(), z.null()]),+ color: z.string()+ })+ )+ .optional()+ }) as any,+ execute: async (_execCtx, input) => {+ const args = (input ?? {}) as {+ datasetName: string;+ layerName?: string;+ latitudeColumn?: string;+ longitudeColumn?: string;+ layerType: string;+ simpleColor?: string;+ colorBy?: string;+ colorType?: 'breaks' | 'unique';+ colorMap?: Array<{value: string | number | null; color: string}>;+ countColumn?: string;+ flowField?: FlowFieldOptions;+ };+ const {+ datasetName,+ layerName,+ latitudeColumn,+ longitudeColumn,+ layerType,+ simpleColor,+ colorBy,+ colorType,+ colorMap,+ countColumn,+ flowField+ } = args;+ try {+ // Runtime guard: the bridge/webMCP call execute without zod parsing, so+ // a missing/invalid layerType must not fall through to+ // guessDefaultLayer's first-default-layer fallback (layerType is+ // required by the command contract).+ const VALID_LAYER_TYPES = [+ 'point',+ 'flow',+ 'flowField',+ 'arc',+ 'line',+ 'grid',+ 'hexagon',+ 'geojson',+ 'cluster',+ 'heatmap',+ 'h3',+ 'trip',+ 's2'+ ];+ if (!layerType || !VALID_LAYER_TYPES.includes(layerType)) {+ throw new Error(+ `Invalid layerType "${String(layerType)}". Must be one of: ${VALID_LAYER_TYPES.join(+ ', '+ )}.`+ );+ }++ const visState = ctx.getVisState();+ const datasets: Datasets = visState.datasets;++ const datasetId = Object.keys(datasets).find(+ dataId => datasets[dataId].label === datasetName || dataId === datasetName+ );+ if (!datasetId) {+ throw new Error(`Dataset ${datasetName} not found.`);+ }++ const dataset = datasets[datasetId];+ // The flow field layer resolves its own columns (position + vector, in+ // one of three modes), so it does not go through guessDefaultLayer —+ // that path only auto-detects the u/v case and would ignore explicit+ // column names.+ let layer =+ layerType === 'flowField'+ ? buildFlowFieldLayer(dataset, {latitudeColumn, longitudeColumn}, flowField)+ : guessDefaultLayer(dataset, layerType, {countColumn});++ if (!layer) {+ if (layerType === 'point' && latitudeColumn && longitudeColumn) {+ // Validate both columns exist before building the config —+ // getColumnFieldIdx returns -1 for a missing column, and an+ // invalid fieldIdx would dispatch a broken layer config (empty+ // render / confusing runtime errors).+ const latIdx = dataset.getColumnFieldIdx(latitudeColumn);+ const lngIdx = dataset.getColumnFieldIdx(longitudeColumn);+ if (latIdx < 0 || lngIdx < 0) {+ const missing = latIdx < 0 ? latitudeColumn : longitudeColumn;+ const available = dataset.fields?.map((f: any) => f.name).join(', ') ?? '';+ throw new Error(+ `Column "${missing}" not found in dataset "${datasetName}". Available columns: ${available}`+ );+ }+ layer = {+ id: uniqueLayerId(),+ type: 'point',+ config: {+ dataId: datasetId,+ label: layerName || `${datasetName}-${layerType}`,+ columns: {+ lat: {value: latitudeColumn, fieldIdx: latIdx},+ lng: {value: longitudeColumn, fieldIdx: lngIdx}+ },+ visConfig: {}+ }+ } as any;+ }+ }+ if (!layer) {+ throw new Error(+ `Could not create ${layerType} layer. Check that the dataset has the required columns.`+ );+ }++ const newLayer = buildLayerConfig(layer, datasetId, layerName, datasetName, layerType);+ applyColorConfig(newLayer, dataset, {simpleColor, colorBy, colorType, colorMap});++ ctx.dispatch(addLayerAction(newLayer, datasetId));++ // Center the map on the new layer's data bounds. `addDataToMap` with+ // `autoCreateLayers: false` (used by `map.load-data`) never fits bounds+ // because no layer exists at load time, and `addLayerUpdater` does not+ // center either — so fit here explicitly.+ const addedLayer = ctx.getVisState().layers.find(l => l.id === newLayer.id);+ const bounds = addedLayer ? findMapBounds([addedLayer]) : null;+ if (bounds) {+ ctx.dispatch(fitBounds(bounds));+ }++ const temporalFields = dataset.fields+ ?.filter((f: any) => f.type === 'timestamp' || f.type === 'date')+ .map((f: any) => f.name);+ const hasTemporalFields = temporalFields && temporalFields.length > 0;++ return {+ success: true,+ commandId: addLayerCommandId,+ data: {+ details: `Map layer ${newLayer.id} has been added to the map.`,+ dateTimeColumns: hasTemporalFields ? temporalFields : undefined,+ dateTimeHint: hasTemporalFields+ ? `DateTime columns detected: ${temporalFields.join(+ ', '+ )}. You can call addTimeFilter with one of these columns to enable time-range animation on the map.`+ : undefined+ }+ };+ } catch (error) {+ return {+ success: false,+ commandId: addLayerCommandId,+ error: error instanceof Error ? error.message : 'Unknown error',+ data: {+ instruction:+ 'Try to fix the error. If the error persists, ask the user to try with different parameters.'+ }+ };+ }+ }+ };+}diff --git a/src/mcp/src/commands/layer-style-command.spec.ts b/src/mcp/src/commands/layer-style-command.spec.tsnew file mode 100644index 000000000..8e0e04fdd--- /dev/null+++ b/src/mcp/src/commands/layer-style-command.spec.ts@@ -0,0 +1,128 @@+import {getUpdateLayerColorCommand} from './layer-style-command';++// A box-map layer's colorRange, exactly as applyColorConfig builds it: 6+// classes (breaks -6.5, 1, 2, 6, 13.5), last colorMap entry [null, color] for+// the highest bucket.+const boxMapColorRange = {+ name: 'color.customPalette',+ type: 'custom',+ category: 'Custom',+ colors: ['#005a9c', '#6ea3d6', '#d9e8f5', '#fbd3a4', '#e07a3f', '#b30000'],+ colorMap: [+ [-6.5, '#005a9c'],+ [1, '#6ea3d6'],+ [2, '#d9e8f5'],+ [6, '#fbd3a4'],+ [13.5, '#e07a3f'],+ [null, '#b30000']+ ]+};++const boxMapLayer = {+ id: 'oa48cne',+ config: {dataId: 'rxv7za', visConfig: {colorRange: boxMapColorRange}}+};++// A plain layer with no colorMap (default quantile scale).+const plainLayer = {+ id: 'plain',+ config: {dataId: 'rxv7za', visConfig: {colorRange: {colors: ['#1f77b4', '#ff7f0e']}}}+};++type CommandResult = {+ success: boolean;+ error?: string;+ data?: Record<string, unknown>;+};++function makeCtx(layer: {id: string; config: {dataId: string; visConfig: {colorRange: any}}}) {+ let dispatched: any = null;+ const ctx = {+ getVisState: () => ({layers: [layer]}),+ dispatch: (action: any) => {+ dispatched = action;+ }+ };+ return {ctx, getDispatched: () => dispatched};+}++async function runUpdateColor(+ layer: {id: string; config: {dataId: string; visConfig: {colorRange: any}}},+ input: {layerId: string; numberOfColors: number; customColors: string[]}+) {+ const {ctx, getDispatched} = makeCtx(layer);+ const cmd = getUpdateLayerColorCommand(ctx as any);+ const result = (await cmd.execute({} as any, input)) as CommandResult;+ return {result, getDispatched};+}++describe('map.update-layer-color', () => {+ it('rejects a palette whose color count does not match the layer class count', async () => {+ const {result} = await runUpdateColor(boxMapLayer, {+ layerId: 'oa48cne',+ numberOfColors: 5,+ customColors: ['#2166ac', '#67a9cf', '#f7f7f7', '#ef8a62', '#b2182b']+ });++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/has 6 classes/);+ expect(result.error).toMatch(/provide exactly 6 colors, got 5/);+ });++ it('applies a palette whose color count matches the layer class count', async () => {+ const {result, getDispatched} = await runUpdateColor(boxMapLayer, {+ layerId: 'oa48cne',+ numberOfColors: 6,+ customColors: ['#2166ac', '#67a9cf', '#d9e8f5', '#f7f7f7', '#ef8a62', '#b2182b']+ });++ expect(result.success).toBe(true);+ const action = getDispatched();+ expect(action).toBeTruthy();+ const colorMap = action.newVisConfig.colorRange.colorMap as [unknown, string][];+ expect(colorMap).toHaveLength(6);+ // every entry keeps its break value and gets a real color — no undefined+ colorMap.forEach(([k, v]) => {+ expect(typeof v).toBe('string');+ expect(v).toMatch(/^#/);+ expect(k).not.toBeUndefined();+ });+ expect(colorMap[5]).toEqual([null, '#b2182b']);+ });++ it('still allows changing the color count on a layer without a colorMap', async () => {+ const {result, getDispatched} = await runUpdateColor(plainLayer, {+ layerId: 'plain',+ numberOfColors: 3,+ customColors: ['#2166ac', '#f7f7f7', '#b2182b']+ });++ expect(result.success).toBe(true);+ const action = getDispatched();+ expect(action.newVisConfig.colorRange.colors).toEqual(['#2166ac', '#f7f7f7', '#b2182b']);+ });++ it('rejects a non-hex color string (bridge path skips zod)', async () => {+ const {result, getDispatched} = await runUpdateColor(plainLayer, {+ layerId: 'plain',+ numberOfColors: 2,+ customColors: ['#2166ac', 'not-a-color']+ });++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/hex color strings/);+ expect(getDispatched()).toBeNull();+ });++ it('rejects a non-positive-integer numberOfColors (bridge path skips zod)', async () => {+ const {result, getDispatched} = await runUpdateColor(plainLayer, {+ layerId: 'plain',+ numberOfColors: 0,+ customColors: ['#2166ac']+ });++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/positive integer/);+ expect(getDispatched()).toBeNull();+ });+});diff --git a/src/mcp/src/commands/layer-style-command.ts b/src/mcp/src/commands/layer-style-command.tsnew file mode 100644index 000000000..48d507496--- /dev/null+++ b/src/mcp/src/commands/layer-style-command.ts@@ -0,0 +1,114 @@+import type {RoomCommand} from './types';+import {z} from 'zod';+import {layerVisualChannelConfigChange} from '@kepler.gl/actions';+import type {KeplerContext} from './types';++export const updateLayerColorCommandId = 'map.update-layer-color' as const;++export function getUpdateLayerColorCommand(ctx: KeplerContext): RoomCommand {+ return {+ id: updateLayerColorCommandId,+ name: 'Update layer color',+ group: 'Map',+ description: 'Update the color palette of an existing layer.',+ metadata: {readOnly: false, riskLevel: 'low', idempotent: true},+ inputSchema: z.object({+ layerId: z.string(),+ numberOfColors: z.number(),+ customColors: z+ .array(z.string())+ .describe(+ 'An array of hex color values. Try to generate colors from user description like: van gogh starry night, water color etc.'+ )+ }) as any,+ execute: async (_execCtx, input) => {+ const {layerId, numberOfColors, customColors} = (input ?? {}) as {+ layerId: string;+ numberOfColors: number;+ customColors: string[];+ };+ try {+ // Runtime guards: the bridge/webMCP call execute without zod parsing,+ // so missing/wrong-typed inputs must fail with actionable errors+ // instead of a TypeError (e.g. reading `.length` of undefined).+ if (typeof layerId !== 'string' || layerId.length === 0) {+ throw new Error('layerId is required and must be a string.');+ }+ if (+ typeof numberOfColors !== 'number' ||+ !Number.isInteger(numberOfColors) ||+ numberOfColors <= 0+ ) {+ throw new Error('numberOfColors is required and must be a positive integer.');+ }+ // The schema/description promise hex colors — a non-hex string would+ // produce an invalid palette downstream, so reject it up front with an+ // actionable error instead of a confusing render.+ const HEX_COLOR_RE = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;+ if (+ !Array.isArray(customColors) ||+ customColors.some(c => typeof c !== 'string' || !HEX_COLOR_RE.test(c))+ ) {+ throw new Error(+ 'customColors is required and must be an array of hex color strings (e.g. #RRGGBB or #RRGGBBAA).'+ );+ }++ const visState = ctx.getVisState();+ const layers = visState.layers;+ const layer = layers.find(l => l.id === layerId);+ if (!layer) {+ throw new Error(`Layer with id ${layerId} not found`);+ }++ if (numberOfColors !== customColors.length) {+ throw new Error(`customColors array must contain exactly ${numberOfColors} colors`);+ }++ const channel = 'color';+ const newConfig = {};++ const oldColorRange = layer.config.visConfig.colorRange;+ if (oldColorRange.colorMap && customColors.length !== oldColorRange.colorMap.length) {+ throw new Error(+ `Layer ${layerId} has ${oldColorRange.colorMap.length} classes (custom colorMap); provide exactly ${oldColorRange.colorMap.length} colors, got ${customColors.length}.`+ );+ }+ const newColorRange = {+ ...oldColorRange,+ colors: customColors,+ ...(oldColorRange.colorMap+ ? {+ colorMap: [+ ...oldColorRange.colorMap.map((c: any, i: number) => [c[0], customColors[i]])+ ]+ }+ : {})+ };++ const newVisConfig = {+ colorRange: newColorRange,+ strokeColorRange: newColorRange+ };++ ctx.dispatch(layerVisualChannelConfigChange(layer, newConfig, channel, newVisConfig));++ return {+ success: true,+ commandId: updateLayerColorCommandId,+ data: {details: `Color updated to ${customColors.join(', ')} for layer ${layerId}`}+ };+ } catch (error) {+ return {+ success: false,+ commandId: updateLayerColorCommandId,+ error: error instanceof Error ? error.message : 'Unknown error',+ data: {+ instruction:+ 'Try to fix the error. If the error persists, ask the user to try with different parameters.'+ }+ };+ }+ }+ };+}diff --git a/src/mcp/src/commands/load-data-command.spec.ts b/src/mcp/src/commands/load-data-command.spec.tsnew file mode 100644index 000000000..e01b38d67--- /dev/null+++ b/src/mcp/src/commands/load-data-command.spec.ts@@ -0,0 +1,305 @@+import {getLoadDataCommand} from './load-data-command';++// Mock the processors so the test never touches real file parsing — the+// command's fetch + batch-parse + dispatch flow is what we're asserting.+jest.mock('@kepler.gl/processors', () => ({+ readFileInBatches: jest.fn(),+ processFileData: jest.fn()+}));++import {readFileInBatches, processFileData} from '@kepler.gl/processors';++// The tests stub global.fetch; capture the original so it can be restored in+// afterEach — otherwise the mock leaks into other suites in the same run and+// causes order-dependent failures.+const originalFetch = global.fetch;++function makeCtx() {+ let dispatched: any = null;+ const ctx = {+ getVisState: () => ({datasets: {}, layers: [], loaders: [], loadOptions: {}}),+ dispatch: (action: any) => {+ dispatched = action;+ },+ getValuesFromDataset: () => [],+ getMapBoundary: () => null,+ getMapboxToken: () => undefined,+ getDatasetContext: () => ''+ };+ return {ctx, getDispatched: () => dispatched};+}++type CommandResult = {success: boolean; error?: string; data?: Record<string, unknown>};++describe('map.load-data', () => {+ beforeEach(() => {+ (readFileInBatches as jest.Mock).mockReset();+ (processFileData as jest.Mock).mockReset();+ });++ afterEach(() => {+ global.fetch = originalFetch;+ });++ it('fetches the URL, parses it, and dispatches addDataToMap with the datasetName override', async () => {+ const {ctx, getDispatched} = makeCtx();++ // fetch resolves to a Response-like blob; readFileInBatches yields one+ // content batch then completes; processFileData returns the parsed dataset.+ global.fetch = jest.fn().mockResolvedValue({+ ok: true,+ statusText: 'OK',+ blob: async () => new Blob(['a,b\n1,2'], {type: 'text/csv'})+ } as any);++ const content = {data: [{a: 1, b: 2}], fileName: 'data.csv'};+ (readFileInBatches as jest.Mock).mockResolvedValue({+ next: jest+ .fn()+ .mockResolvedValueOnce({value: content, done: false})+ .mockResolvedValueOnce({value: undefined, done: true})+ });+ (processFileData as jest.Mock).mockResolvedValue([+ {info: {label: 'data.csv'}, rows: [{a: 1, b: 2}]}+ ]);++ const cmd = getLoadDataCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ url: 'https://example.com/data.csv',+ datasetName: 'My Dataset'+ })) as CommandResult;++ expect(result.success).toBe(true);+ expect(global.fetch).toHaveBeenCalledWith('https://example.com/data.csv', {signal: undefined});++ const action = getDispatched();+ expect(action).toBeTruthy();+ expect(action.type).toMatch(/ADD_DATA_TO_MAP/);+ // datasetName override wins over the URL filename+ expect(action.payload.datasets[0].info.label).toBe('My Dataset');+ // no auto-created layer — the assistant adds layers explicitly+ expect(action.payload.options).toEqual({autoCreateLayers: false, centerMap: true});+ });++ it('falls back to the URL filename when datasetName is omitted', async () => {+ const {ctx, getDispatched} = makeCtx();++ global.fetch = jest.fn().mockResolvedValue({+ ok: true,+ statusText: 'OK',+ blob: async () => new Blob(['a,b\n1,2'], {type: 'text/csv'})+ } as any);++ const content = {data: [{a: 1, b: 2}], fileName: 'data.csv'};+ (readFileInBatches as jest.Mock).mockResolvedValue({+ next: jest+ .fn()+ .mockResolvedValueOnce({value: content, done: false})+ .mockResolvedValueOnce({value: undefined, done: true})+ });+ (processFileData as jest.Mock).mockResolvedValue([+ {info: {label: 'data.csv'}, rows: [{a: 1, b: 2}]}+ ]);++ const cmd = getLoadDataCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ url: 'https://example.com/data.csv?x=1'+ })) as CommandResult;++ expect(result.success).toBe(true);+ const action = getDispatched();+ // query strings are stripped from the derived filename+ expect(action.payload.datasets[0].info.label).toBe('data.csv');+ });++ it('returns an error for an invalid URL without dispatching', async () => {+ const {ctx, getDispatched} = makeCtx();++ const cmd = getLoadDataCommand(ctx as any);+ // `http://` has a scheme but no host — unparseable even with a base, so it+ // stays a genuine "Invalid URL" (a scheme-less string like `not a url` is a+ // valid relative reference in jsdom and resolves against the page origin).+ const result = (await cmd.execute({} as any, {+ url: 'http://'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/Invalid URL/);+ expect(getDispatched()).toBeNull();+ });++ it('returns an error for an empty url without dispatching', async () => {+ const {ctx, getDispatched} = makeCtx();++ const cmd = getLoadDataCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ url: ' '+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/Invalid URL/);+ expect(getDispatched()).toBeNull();+ });++ it('resolves a relative URL against the page origin (local-file support)', async () => {+ const {ctx, getDispatched} = makeCtx();++ global.fetch = jest.fn().mockResolvedValue({+ ok: true,+ statusText: 'OK',+ blob: async () => new Blob(['a,b\n1,2'], {type: 'text/csv'})+ } as any);++ const content = {data: [{a: 1, b: 2}], fileName: 'data.csv'};+ let capturedFile: any;+ (readFileInBatches as jest.Mock).mockImplementation(async ({file}: any) => {+ capturedFile = file;+ return {+ next: jest+ .fn()+ .mockResolvedValueOnce({value: content, done: false})+ .mockResolvedValueOnce({value: undefined, done: true})+ };+ });+ (processFileData as jest.Mock).mockResolvedValue([+ {info: {label: 'data.csv'}, rows: [{a: 1, b: 2}]}+ ]);++ const cmd = getLoadDataCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ url: '/data.csv'+ })) as CommandResult;++ expect(result.success).toBe(true);+ // jsdom's default origin is http://localhost — the relative path resolves+ // against it, so the fetch targets the demo app's own server (same-origin).+ expect(global.fetch).toHaveBeenCalledWith('http://localhost/data.csv', {signal: undefined});+ // the resolved href (not the bare relative path) is preserved for hashing+ expect(capturedFile.keplerSourceUrl).toBe('http://localhost/data.csv');+ const action = getDispatched();+ expect(action).toBeTruthy();+ expect(action.payload.datasets[0].info.label).toBe('data.csv');+ });++ it('includes the numeric status code in a non-ok fetch error', async () => {+ const {ctx, getDispatched} = makeCtx();++ global.fetch = jest.fn().mockResolvedValue({+ ok: false,+ status: 404,+ statusText: 'Not Found'+ } as any);++ const cmd = getLoadDataCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ url: 'https://example.com/missing.csv'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/HTTP 404 Not Found/);+ expect(getDispatched()).toBeNull();+ });++ it('falls back to the bare status code when statusText is empty', async () => {+ const {ctx, getDispatched} = makeCtx();++ global.fetch = jest.fn().mockResolvedValue({+ ok: false,+ status: 500,+ statusText: ''+ } as any);++ const cmd = getLoadDataCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ url: 'https://example.com/broken.csv'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/HTTP 500/);+ expect(getDispatched()).toBeNull();+ });++ it('loads a small file embedded as a data URL (remote-context local file)', async () => {+ const {ctx, getDispatched} = makeCtx();++ global.fetch = jest.fn().mockResolvedValue({+ ok: true,+ statusText: 'OK',+ blob: async () => new Blob(['a,b\n1,2'], {type: 'text/csv'})+ } as any);++ const content = {data: [{a: 1, b: 2}], fileName: 'data.csv'};+ (readFileInBatches as jest.Mock).mockResolvedValue({+ next: jest+ .fn()+ .mockResolvedValueOnce({value: content, done: false})+ .mockResolvedValueOnce({value: undefined, done: true})+ });+ (processFileData as jest.Mock).mockResolvedValue([+ {info: {label: 'data.csv'}, rows: [{a: 1, b: 2}]}+ ]);++ const cmd = getLoadDataCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ url: 'data:text/csv;base64,YSxiCjEsMg=='+ })) as CommandResult;++ expect(result.success).toBe(true);+ expect(global.fetch).toHaveBeenCalledWith('data:text/csv;base64,YSxiCjEsMg==', {+ signal: undefined+ });+ const action = getDispatched();+ expect(action).toBeTruthy();+ // the default dataset name is derived from the data URL's MIME type+ expect(action.payload.datasets[0].info.label).toBe('data.csv');+ });++ it('hashes a data URL down for the dataset source (no huge metadata)', async () => {+ const {ctx} = makeCtx();++ global.fetch = jest.fn().mockResolvedValue({+ ok: true,+ statusText: 'OK',+ blob: async () => new Blob(['a,b\n1,2'], {type: 'text/csv'})+ } as any);++ const content = {data: [{a: 1, b: 2}], fileName: 'data.csv'};+ let capturedFile: any;+ (readFileInBatches as jest.Mock).mockImplementation(async ({file}: any) => {+ capturedFile = file;+ return {+ next: jest+ .fn()+ .mockResolvedValueOnce({value: content, done: false})+ .mockResolvedValueOnce({value: undefined, done: true})+ };+ });+ (processFileData as jest.Mock).mockResolvedValue([+ {info: {label: 'data.csv'}, rows: [{a: 1, b: 2}]}+ ]);++ const cmd = getLoadDataCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ url: 'data:text/csv;base64,YSxiCjEsMg=='+ })) as CommandResult;++ expect(result.success).toBe(true);+ // the source is a short content hash, not the full (potentially large) data URL+ expect(capturedFile.keplerSourceUrl).toMatch(/^data:[a-z0-9]+$/);+ expect(capturedFile.keplerSourceUrl).not.toContain('base64');+ });++ it('rejects an oversized data URL', async () => {+ const {ctx, getDispatched} = makeCtx();++ const cmd = getLoadDataCommand(ctx as any);+ const bigDataUrl = `data:text/csv;base64,${'A'.repeat(2 * 1024 * 1024 + 1)}`;+ const result = (await cmd.execute({} as any, {+ url: bigDataUrl+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/Data URL is too large/);+ expect(getDispatched()).toBeNull();+ });+});diff --git a/src/mcp/src/commands/load-data-command.ts b/src/mcp/src/commands/load-data-command.tsnew file mode 100644index 000000000..fad67f840--- /dev/null+++ b/src/mcp/src/commands/load-data-command.ts@@ -0,0 +1,221 @@+import type {RoomCommand} from './types';+import {z} from 'zod';+import {addDataToMap} from '@kepler.gl/actions';+import {readFileInBatches, processFileData} from '@kepler.gl/processors';+import type {ProcessFileDataContent} from '@kepler.gl/processors';+import type {KeplerContext} from './types';++// MIME type → file extension for data URLs, so a `data:text/csv;base64,...`+// payload gets a sensible default dataset name (`data.csv`) instead of `data`.+const DATA_URL_EXTENSIONS: Record<string, string> = {+ 'text/csv': '.csv',+ 'application/csv': '.csv',+ 'application/json': '.json',+ 'application/geo+json': '.geojson',+ 'application/vnd.apache.arrow.file': '.arrow',+ 'application/vnd.apache.parquet': '.parquet',+ 'text/plain': '.txt'+};++function fileNameFromDataUrl(parsedUrl: URL): string {+ // data:text/csv;base64,... → pathname is "text/csv;base64,"+ const mime = parsedUrl.pathname.split(';')[0].toLowerCase();+ return `data${DATA_URL_EXTENSIONS[mime] ?? ''}`;+}++// Same 32-bit string hash the processors use for dataset ids — applied to a+// data URL's content so the dataset id is content-derived (unique per payload)+// without storing the whole (potentially large) data URL in the metadata.+function hashString(str: string): string {+ let hash = 0;+ for (let i = 0; i < str.length; i++) {+ // eslint-disable-next-line no-bitwise+ hash = (hash << 5) - hash + str.charCodeAt(i);+ // eslint-disable-next-line no-bitwise+ hash |= 0;+ }+ return hash.toString(36);+}++export const loadDataCommandId = 'map.load-data' as const;++export function getLoadDataCommand(ctx: KeplerContext): RoomCommand {+ return {+ id: loadDataCommandId,+ name: 'Load data from URL',+ group: 'Map',+ description:+ 'Load a dataset from a URL into kepler.gl. The dataset is named after the URL filename, ' ++ 'or after `datasetName` when provided. Does NOT create a layer — call map.add-layer to visualize. ' ++ 'Do NOT create a duplicate dataset (e.g. via map.create-table) just to rename it; ' ++ 'name it here with `datasetName` instead, or use the URL-filename dataset as-is. ' ++ 'LOCAL FILES: a local file must be served over http(s) — the browser cannot fetch ' ++ '`file://` paths. To load a file you have on disk: (1) copy it into the demo app\'s ' ++ 'served directory (e.g. `examples/demo-app/dist/`) and pass `/filename.csv`, or ' ++ '(2) serve it with a CORS-enabled local server (`npx serve --cors -l 8000` in the ' ++ 'file\'s folder) and pass `http://localhost:8000/filename.csv`. ' ++ 'EMBEDDED CONTENT: if you have the file content but cannot serve it (e.g. a remote ' ++ 'browser context), pass it as a data URL — `data:text/csv;base64,<base64 content>` ' ++ '(encode with `base64 -i file.csv`). Works for small files (up to ~2MB). ' ++ 'LARGE DATASETS: for files over a few MB, prefer Parquet (.parquet) over GeoJSON/CSV — ' ++ 'it loads much faster and is less likely to time out. Convert GeoJSON to GeoParquet ' ++ 'with geopandas (`gdf.to_parquet("data.parquet")`); kepler reads GeoParquet geometry (WKB) natively.',+ metadata: {readOnly: false, riskLevel: 'medium', requiresConfirmation: true},+ inputSchema: z.object({+ url: z+ .string()+ .describe(+ 'The URL to load data from. May be a full http(s) URL, a path served by the demo app ' ++ '(e.g. /data.geojson), or a data URL embedding small file content (data:text/csv;base64,...).'+ ),+ datasetName: z+ .string()+ .optional()+ .describe(+ 'Optional name for the loaded dataset. If omitted, the URL filename is used. ' ++ 'Use this instead of creating a duplicate dataset to rename it.'+ )+ }) as any,+ execute: async (execCtx, input) => {+ const {url, datasetName} = (input ?? {}) as {url: string; datasetName?: string};+ try {+ if (typeof url !== 'string' || url.trim() === '') {+ throw new Error(`Invalid URL: ${url}`);+ }++ // Resolve the URL before validating the scheme. A scheme-less string is+ // a relative reference — resolve it against the page origin so files+ // served by the demo app itself (same-origin) can be loaded with a bare+ // path (e.g. `/sf_streets.geojson`). Browsers cannot fetch `file://`+ // URLs, so a local file must be served over http(s) by the page's own+ // server (or a CORS-enabled local server). `data:` URLs are allowed for+ // small files — they embed the content directly, which is the one way+ // an agent in a remote browser context can load a local file it cannot+ // serve. `javascript:` and other schemes are rejected.+ const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url);+ const pageOrigin = typeof window !== 'undefined' ? window.location.origin : undefined;+ let parsedUrl: URL;+ try {+ parsedUrl = hasScheme ? new URL(url) : new URL(url, pageOrigin);+ } catch {+ throw new Error(`Invalid URL: ${url}`);+ }+ if (parsedUrl.protocol === 'data:') {+ // Cap the size so a huge embedded payload can't stall the load or+ // bloat the tool input. For larger files the agent should serve the+ // file over http(s) or convert to Parquet instead.+ const MAX_DATA_URL_LENGTH = 2 * 1024 * 1024; // ~2MB of base64+ if (parsedUrl.href.length > MAX_DATA_URL_LENGTH) {+ throw new Error(+ `Data URL is too large (${parsedUrl.href.length} chars). ` ++ 'For files over a few MB, serve the file over http(s) or convert to Parquet.'+ );+ }+ } else if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {+ throw new Error(+ `Unsupported URL scheme "${parsedUrl.protocol}". Only http(s) URLs are supported.`+ );+ }++ const visState = ctx.getVisState();+ // Thread the caller's AbortSignal into the fetch so WebMCP/bridge+ // cancellations stop long-running loads instead of letting them hang.+ const response = await fetch(parsedUrl.href, {signal: execCtx?.signal});+ if (!response.ok) {+ // Include the numeric status — statusText is often empty (e.g. some+ // CDNs / error pages), and the code alone makes failures diagnosable.+ const reason = response.statusText+ ? `HTTP ${response.status} ${response.statusText}`+ : `HTTP ${response.status}`;+ throw new Error(`Failed to fetch data from ${parsedUrl.href}: ${reason}`);+ }++ const blob = await response.blob();+ // Derive the filename from the URL pathname so query strings (e.g.+ // `data.csv?x=1`) don't end up in the dataset name. A data URL has no+ // pathname — fall back to a name derived from its MIME type so the+ // dataset gets a sensible default label (e.g. `data.csv`).+ const fileName =+ parsedUrl.protocol === 'data:'+ ? fileNameFromDataUrl(parsedUrl)+ : parsedUrl.pathname.split('/').pop() || 'data';+ // Carry the Blob's MIME type into the File so loader selection in+ // readFileInBatches can use it — a URL with no extension (or a+ // misleading one) would otherwise leave file.type empty and fail to+ // pick the right loader.+ const file = new File([blob], fileName, {type: blob.type || undefined});+ // Preserve the source URL so processors hash by URL (avoiding dataset-id+ // collisions between same-named files) and can attach externally-hosted+ // metadata — mirrors loadExternallyHostedDataset. Use the RESOLVED href+ // so a relative path and its absolute form hash to the same dataset id.+ // For a data URL the href IS the content (potentially large) — hash it+ // down so the id stays content-derived (unique per payload) without+ // storing the whole payload in the dataset metadata.+ const sourceUrl =+ parsedUrl.protocol === 'data:'+ ? `data:${hashString(parsedUrl.href)}`+ : parsedUrl.href;+ (file as File & {keplerSourceUrl?: string}).keplerSourceUrl = sourceUrl;++ const batches = await readFileInBatches({+ file,+ fileCache: [],+ loaders: visState.loaders ?? [],+ loadOptions: visState.loadOptions ?? {}+ });++ let result = await batches.next();+ let content: ProcessFileDataContent = {data: [], fileName: ''};+ let parsedData: any[] = [];++ while (!result.done) {+ content = result.value as ProcessFileDataContent;+ result = await batches.next();+ if (result.done) {+ parsedData = await processFileData({content, fileCache: []});+ break;+ }+ }++ if (parsedData.length === 0) {+ throw new Error(`No data could be parsed from ${url}.`);+ }++ // Apply a caller-chosen dataset name (default: the URL filename) so the+ // agent never has to create a duplicate dataset just to rename it.+ for (const d of parsedData) {+ if (d?.info) {+ d.info.label = datasetName ?? d.info.label ?? fileName;+ }+ }++ ctx.dispatch(+ addDataToMap({+ datasets: parsedData,+ // Do NOT auto-create a layer — the assistant creates the layer+ // explicitly via `map.add-layer` (with full styling control), so+ // loading data never produces a duplicate default layer.+ options: {autoCreateLayers: false, centerMap: true}+ })+ );++ const dataInfo = parsedData[0]?.info;+ return {+ success: true,+ commandId: loadDataCommandId,+ data: {details: `Successfully loaded data from ${url}`, dataInfo}+ };+ } catch (error) {+ return {+ success: false,+ commandId: loadDataCommandId,+ error: error instanceof Error ? error.message : 'Unknown error',+ data: {+ instruction:+ 'Try to fix the error. If the error persists, ask the user to try with a different URL or format.'+ }+ };+ }+ }+ };+}diff --git a/src/mcp/src/commands/save-data-command.ts b/src/mcp/src/commands/save-data-command.tsnew file mode 100644index 000000000..c3a9b3fc4--- /dev/null+++ b/src/mcp/src/commands/save-data-command.ts@@ -0,0 +1,70 @@+import type {RoomCommand} from './types';+import {z} from 'zod';+import type {KeplerContext} from './types';++export const saveDataCommandId = 'map.save-data' as const;++export function getSaveDataCommand(ctx: KeplerContext): RoomCommand {+ return {+ id: saveDataCommandId,+ name: 'Save DuckDB table to map',+ group: 'Map',+ description:+ 'Save a DuckDB table to kepler.gl as a map dataset. Works with any table including those from buffer, zipcode, county, state, isochrone, routing, query results, etc.',+ metadata: {readOnly: false, riskLevel: 'medium', requiresConfirmation: true},+ inputSchema: z.object({+ datasetNames: z+ .array(z.string())+ .min(1)+ .describe('The names of the DuckDB tables to load into kepler.gl.')+ }) as any,+ execute: async (_execCtx, input) => {+ const {datasetNames} = (input ?? {}) as {datasetNames: string[]};+ try {+ // Runtime guard: the bridge/webMCP call execute without zod parsing,+ // so a missing/empty/wrong-typed datasetNames must not fall through to+ // a confusing TypeError or an unhelpful "No datasets found…" message.+ if (+ !Array.isArray(datasetNames) ||+ datasetNames.length === 0 ||+ datasetNames.some(name => typeof name !== 'string' || name.length === 0)+ ) {+ throw new Error(+ 'datasetNames must be a non-empty array of DuckDB table names, e.g. ["my_table"].'+ );+ }++ const loadedDatasetNames: string[] = [];++ for (const datasetName of datasetNames) {+ const result = await ctx.loadTableToKepler(datasetName);+ if (!result.success) {+ throw new Error(`Cannot save table "${datasetName}" to kepler.gl: ${result.error}`);+ }+ loadedDatasetNames.push(datasetName);+ }++ if (loadedDatasetNames.length === 0) {+ throw new Error(`No datasets found from ${datasetNames.join(', ')}`);+ }++ return {+ success: true,+ commandId: saveDataCommandId,+ data: {+ savedDatasetNames: loadedDatasetNames,+ details: `Successfully saved dataset(s): ${loadedDatasetNames.join(', ')} in kepler.gl`+ }+ };+ } catch (error) {+ return {+ success: false,+ commandId: saveDataCommandId,+ error: `Cannot save data to kepler.gl: ${+ error instanceof Error ? error.message : String(error)+ }`+ };+ }+ }+ };+}diff --git a/src/mcp/src/commands/split-view-command.spec.ts b/src/mcp/src/commands/split-view-command.spec.tsnew file mode 100644index 000000000..0c6dbb083--- /dev/null+++ b/src/mcp/src/commands/split-view-command.spec.ts@@ -0,0 +1,110 @@+import {getSplitViewCommand} from './split-view-command';+import {ActionTypes} from '@kepler.gl/actions';++/**+ * Mock KeplerContext whose dispatch simulates the split-map reducer: toggling+ * index 0 adds the right panel, toggling index 1 removes it. Layer visibility+ * toggles are recorded but not applied (the command re-reads splitMaps between+ * the two panels, so the assertions only need the dispatch sequence).+ */+function makeCtx(opts: {split?: boolean; layers?: any[]} = {}) {+ const dispatched: any[] = [];+ const visState = {+ datasets: {},+ layers: opts.layers ?? [],+ splitMaps: opts.split ? [{layers: {}}, {layers: {}}] : [{layers: {}}]+ };+ const ctx = {+ getVisState: () => visState,+ dispatch: (action: any) => {+ dispatched.push(action);+ if (action.type === ActionTypes.TOGGLE_SPLIT_MAP) {+ if (action.payload === 0) {+ visState.splitMaps = [{layers: {}}, {layers: {}}];+ } else if (action.payload === 1) {+ visState.splitMaps = [{layers: {}}];+ }+ }+ },+ getValuesFromDataset: () => [],+ getMapBoundary: () => null,+ getMapboxToken: () => undefined,+ getDatasetContext: () => ''+ };+ return {ctx, getDispatched: () => dispatched};+}++type CommandResult = {success: boolean; error?: string; data?: Record<string, unknown>};++describe('map.split-view', () => {+ it('enables split view by toggling the right panel on', async () => {+ const {ctx, getDispatched} = makeCtx();+ const cmd = getSplitViewCommand(ctx as any);+ const result = (await cmd.execute({} as any, {action: 'enable'})) as CommandResult;++ expect(result.success).toBe(true);+ const splitToggles = getDispatched().filter(+ (a: any) => a.type === ActionTypes.TOGGLE_SPLIT_MAP+ );+ expect(splitToggles).toHaveLength(1);+ expect(splitToggles[0].payload).toBe(0);+ });++ it('disables split view by closing the right panel (keeps map0)', async () => {+ const {ctx, getDispatched} = makeCtx({split: true});+ const cmd = getSplitViewCommand(ctx as any);+ const result = (await cmd.execute({} as any, {action: 'disable'})) as CommandResult;++ expect(result.success).toBe(true);+ const splitToggles = getDispatched().filter(+ (a: any) => a.type === ActionTypes.TOGGLE_SPLIT_MAP+ );+ expect(splitToggles).toHaveLength(1);+ expect(splitToggles[0].payload).toBe(1);+ });++ it('assigns layers to each panel and toggles visibility to match', async () => {+ const layers = [{id: 'layer_a'}, {id: 'layer_b'}, {id: 'layer_c'}];+ const {ctx, getDispatched} = makeCtx({layers});+ const cmd = getSplitViewCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ action: 'enable',+ layerIdsForMap0: ['layer_a'],+ layerIdsForMap1: ['layer_b', 'layer_c']+ })) as CommandResult;++ expect(result.success).toBe(true);+ const toggles = getDispatched().filter(+ (a: any) => a.type === ActionTypes.TOGGLE_LAYER_FOR_MAP+ );+ // layer_a shown only on map0; layer_b + layer_c shown only on map1+ expect(toggles).toHaveLength(3);+ });++ it('rejects an invalid action instead of falling through to enable', async () => {+ const {ctx, getDispatched} = makeCtx();+ const cmd = getSplitViewCommand(ctx as any);+ const result = (await cmd.execute({} as any, {action: 'toggle'})) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/Invalid action/);+ // no split-map toggle dispatched+ expect(+ getDispatched().filter((a: any) => a.type === ActionTypes.TOGGLE_SPLIT_MAP)+ ).toHaveLength(0);+ });++ it('rejects unknown layer ids instead of silently hiding real layers', async () => {+ const layers = [{id: 'layer_a'}];+ const {ctx} = makeCtx({layers});+ const cmd = getSplitViewCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ action: 'enable',+ layerIdsForMap0: ['layer_a'],+ layerIdsForMap1: ['ghost']+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/Unknown layer id/);+ });+});diff --git a/src/mcp/src/commands/split-view-command.ts b/src/mcp/src/commands/split-view-command.tsnew file mode 100644index 000000000..ef3434db3--- /dev/null+++ b/src/mcp/src/commands/split-view-command.ts@@ -0,0 +1,199 @@+import type {RoomCommand} from './types';+import {z} from 'zod';+import {toggleSplitMap, toggleLayerForMap} from '@kepler.gl/actions';+import type {KeplerContext} from './types';++const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));++export const splitViewCommandId = 'map.split-view' as const;++export function getSplitViewCommand(ctx: KeplerContext): RoomCommand {+ return {+ id: splitViewCommandId,+ name: 'Toggle split map view',+ group: 'Map',+ description: `Enable or disable the dual-map (split view) comparison mode.++When enabled, the map splits into two panels for side-by-side comparison. Pass layerIdsForMap0 / layerIdsForMap1 to assign which layers show ONLY in the left / right panel; without these, all layers show on both panels (no comparison).++When disabled, the map returns to a single panel.++Use the SAME colorBy / colorType for the layers being compared, so the comparison is fair.`,+ metadata: {readOnly: false, riskLevel: 'low', idempotent: true},+ inputSchema: z.object({+ action: z+ .enum(['enable', 'disable'])+ .describe('"enable" activates dual map mode; "disable" returns to a single map.'),+ layerIdsForMap0: z+ .array(z.string())+ .optional()+ .describe(+ 'Layer IDs to show ONLY in the LEFT panel. Layers not listed are hidden from the left panel.'+ ),+ layerIdsForMap1: z+ .array(z.string())+ .optional()+ .describe(+ 'Layer IDs to show ONLY in the RIGHT panel. Layers not listed are hidden from the right panel.'+ )+ }) as any,+ execute: async (_execCtx, input) => {+ const {action, layerIdsForMap0, layerIdsForMap1} = (input ?? {}) as {+ action: 'enable' | 'disable';+ layerIdsForMap0?: string[];+ layerIdsForMap1?: string[];+ };+ try {+ // Runtime guard: the bridge/webMCP call execute without zod parsing, so+ // a missing/invalid action must not fall through to the enable path and+ // toggle split view unexpectedly.+ if (action !== 'enable' && action !== 'disable') {+ return {+ success: false,+ commandId: splitViewCommandId,+ error: `Invalid action "${String(action)}". Must be "enable" or "disable".`,+ data: {+ instruction:+ 'Pass action: "enable" to activate dual map mode, or "disable" to return to a single map.'+ }+ };+ }++ // Runtime guard: the bridge/webMCP call execute without zod parsing, so+ // a string/object passed as layerIdsForMap0/1 must not be treated as+ // iterable (`.length`, `.filter`) and produce surprising layer toggles.+ // Reject non-array or non-string entries when these fields are provided.+ for (const [name, ids] of [+ ['layerIdsForMap0', layerIdsForMap0],+ ['layerIdsForMap1', layerIdsForMap1]+ ] as const) {+ if (+ ids !== undefined &&+ (!Array.isArray(ids) || ids.some(id => typeof id !== 'string' || id.length === 0))+ ) {+ return {+ success: false,+ commandId: splitViewCommandId,+ error: `Invalid ${name}. Must be an array of non-empty layer id strings.`,+ data: {+ instruction: `Pass ${name} as an array of layer id strings, or omit it to show all layers on that panel.`+ }+ };+ }+ }++ const visState = ctx.getVisState();+ const isSplit = visState.splitMaps && visState.splitMaps.length > 1;++ if (action === 'disable') {+ if (isSplit) {+ // Close the RIGHT panel (index 1) so the LEFT panel (map0) survives:+ // `closeSpecificMapAtIndex` keeps `1 - payload`, so closing 0 would+ // keep the right panel and flip layer visibility to map1's config.+ ctx.dispatch(toggleSplitMap(1));+ }+ return {+ success: true,+ commandId: splitViewCommandId,+ data: {details: 'Split map view disabled. Returned to single map view.'}+ };+ }++ // enable+ if (!isSplit) {+ ctx.dispatch(toggleSplitMap(0));+ }++ const hasLayerAssignment =+ (layerIdsForMap0 && layerIdsForMap0.length > 0) ||+ (layerIdsForMap1 && layerIdsForMap1.length > 0);++ if (hasLayerAssignment) {+ await sleep(200);+ const updatedVis = ctx.getVisState();+ const splitMaps = updatedVis.splitMaps;++ if (splitMaps && splitMaps.length > 1) {+ const allLayers = updatedVis.layers || [];+ const allLayerIds = allLayers.map((l: any) => l.id);++ // Fail fast on unknown layer ids — silently ignoring them would+ // hide every real layer not listed and produce an unexpected blank+ // panel.+ const allLayerIdSet = new Set(allLayerIds);+ for (const [panel, ids] of [+ ['left (map0)', layerIdsForMap0],+ ['right (map1)', layerIdsForMap1]+ ] as const) {+ if (ids && ids.length > 0) {+ const unknown = ids.filter(id => !allLayerIdSet.has(id));+ if (unknown.length > 0) {+ throw new Error(+ `Unknown layer id(s) for the ${panel} panel: ${unknown.join(', ')}. ` ++ `Available layer ids: ${allLayerIds.join(', ')}`+ );+ }+ }+ }++ if (layerIdsForMap0 && layerIdsForMap0.length > 0) {+ const map0Layers = splitMaps[0]?.layers || {};+ const desiredSet0 = new Set(layerIdsForMap0);+ for (const layerId of allLayerIds) {+ // Coerce to boolean: a missing entry means "hidden", and+ // `toggleLayerForMapUpdater` toggles missing entries to visible.+ const isVisible = Boolean(map0Layers[layerId]);+ const shouldBeVisible = desiredSet0.has(layerId);+ if (isVisible !== shouldBeVisible) {+ ctx.dispatch(toggleLayerForMap(0, layerId));+ }+ }+ }++ if (layerIdsForMap1 && layerIdsForMap1.length > 0) {+ const freshSplitMaps = ctx.getVisState().splitMaps;+ const map1Layers = freshSplitMaps?.[1]?.layers || {};+ const desiredSet1 = new Set(layerIdsForMap1);+ for (const layerId of allLayerIds) {+ // Coerce to boolean: a missing entry means "hidden", and+ // `toggleLayerForMapUpdater` toggles missing entries to visible.+ const isVisible = Boolean(map1Layers[layerId]);+ const shouldBeVisible = desiredSet1.has(layerId);+ if (isVisible !== shouldBeVisible) {+ ctx.dispatch(toggleLayerForMap(1, layerId));+ }+ }+ }+ }+ }++ const finalVis = ctx.getVisState();+ const layers = finalVis.layers || [];++ return {+ success: true,+ commandId: splitViewCommandId,+ data: {+ details: `Split map view enabled. ${layers.length} layer(s) available.${+ hasLayerAssignment+ ? ` Left panel: ${(layerIdsForMap0 || []).length} layer(s), Right panel: ${+ (layerIdsForMap1 || []).length+ } layer(s).`+ : ' All layers visible on both panels. Provide layerIdsForMap0/layerIdsForMap1 to assign layers to each panel.'+ }`+ }+ };+ } catch (error) {+ return {+ success: false,+ commandId: splitViewCommandId,+ error: error instanceof Error ? error.message : 'Unknown error',+ data: {+ instruction:+ 'Check that a map is loaded and layers exist. If the error persists, ask the user to try with different parameters.'+ }+ };+ }+ }+ };+}diff --git a/src/mcp/src/commands/table-command.spec.ts b/src/mcp/src/commands/table-command.spec.tsnew file mode 100644index 000000000..6a06d230a--- /dev/null+++ b/src/mcp/src/commands/table-command.spec.ts@@ -0,0 +1,151 @@+import {getTableCommand} from './table-command';+import {tableFromArrays} from 'apache-arrow';++// Mock the actions/processors so the test never touches real kepler state —+// the command's DuckDB round-trip + dispatch flow is what we're asserting.+jest.mock('@kepler.gl/actions', () => ({+ addDataToMap: jest.fn((payload: any) => ({type: 'ADD_DATA_TO_MAP', payload}))+}));+jest.mock('@kepler.gl/processors', () => ({+ processFileData: jest.fn()+}));++import {processFileData} from '@kepler.gl/processors';++/**+ * Mock KeplerContext. The command reads visState.datasets, pulls column values+ * via getValuesFromDataset, and runs the SQL through a DuckDB connector+ * (getConnector) whose query result is what arrowTableToObjects consumes.+ */+function makeCtx(opts: {datasets?: any; values?: Record<string, unknown[]>} = {}) {+ const dispatched: any[] = [];+ const db = {+ execute: jest.fn().mockResolvedValue(undefined),+ loadArrow: jest.fn().mockResolvedValue(undefined),+ query: jest.fn()+ };+ const ctx = {+ getVisState: () => ({datasets: opts.datasets ?? {}, layers: []}),+ getValuesFromDataset: (_dsName: string, varName: string) =>+ (opts.values ?? {})[varName] ?? [],+ getConnector: () => db,+ dispatch: (action: any) => {+ dispatched.push(action);+ },+ getMapBoundary: () => null,+ getMapboxToken: () => undefined,+ getDatasetContext: () => ''+ };+ return {ctx, db, getDispatched: () => dispatched};+}++type CommandResult = {success: boolean; error?: string; data?: Record<string, unknown>};++const dataset = {+ id: 'd1',+ label: 'My Dataset',+ length: 2,+ fields: [{name: 'a', type: 'integer'}, {name: 'b', type: 'integer'}]+};++describe('map.create-table', () => {+ beforeEach(() => {+ (processFileData as jest.Mock).mockReset();+ // Default: pass the query result through as the parsed dataset so the+ // dispatch payload mirrors what the command computed.+ (processFileData as jest.Mock).mockImplementation(async ({content}: any) => [+ {info: {label: content.fileName}, rows: content.data}+ ]);+ });++ it('requires the __TABLE__ placeholder in the SQL', async () => {+ const {ctx, db} = makeCtx({datasets: {d1: dataset}});+ const cmd = getTableCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'My Dataset',+ variableNames: ['a'],+ sql: 'SELECT a FROM my_table',+ resultDatasetName: 'New Dataset'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/__TABLE__/);+ // fail fast — no DuckDB round-trip happens+ expect(db.query).not.toHaveBeenCalled();+ expect(db.loadArrow).not.toHaveBeenCalled();+ });++ it('dedupes variableNames before building the Arrow table', async () => {+ const {ctx, db} = makeCtx({+ datasets: {d1: dataset},+ values: {a: [1, 2], b: [3, 4]}+ });+ db.query.mockResolvedValue(tableFromArrays({a: [1, 2], b: [3, 4]}));++ const cmd = getTableCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'My Dataset',+ variableNames: ['a', 'a', 'b'],+ sql: 'SELECT * FROM __TABLE__',+ resultDatasetName: 'New Dataset'+ })) as CommandResult;++ expect(result.success).toBe(true);+ // the loaded Arrow table has the deduped column set (a, b) — not 3 columns+ const loaded = db.loadArrow.mock.calls[0][0];+ expect(loaded.schema.fields.map((f: any) => f.name)).toEqual(['a', 'b']);+ });++ it('errors when the dataset does not exist', async () => {+ const {ctx, db} = makeCtx({datasets: {}});+ const cmd = getTableCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'Nope',+ variableNames: ['a'],+ sql: 'SELECT * FROM __TABLE__',+ resultDatasetName: 'New Dataset'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/not found/);+ expect(db.query).not.toHaveBeenCalled();+ });++ it('preserves object-valued columns through the stringify/restore round-trip', async () => {+ const geojson = {type: 'Feature', properties: {name: 'x'}};+ const {ctx, db, getDispatched} = makeCtx({+ datasets: {+ d1: {+ ...dataset,+ fields: [{name: 'a', type: 'integer'}, {name: '_geojson', type: 'object'}]+ }+ },+ values: {a: [1, 2], _geojson: [geojson, geojson]}+ });+ // DuckDB returns the object column as a JSON string (VARCHAR)+ db.query.mockResolvedValue(+ tableFromArrays({+ a: [1, 2],+ _geojson: [JSON.stringify(geojson), JSON.stringify(geojson)]+ })+ );++ const cmd = getTableCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'My Dataset',+ variableNames: ['a', '_geojson'],+ sql: 'SELECT * FROM __TABLE__',+ resultDatasetName: 'New Dataset'+ })) as CommandResult;++ expect(result.success).toBe(true);+ // the object is restored, not left as a JSON string+ const first = (result.data as any).firstFiveRows[0];+ expect(first._geojson).toEqual(geojson);++ // dispatched with the new dataset, no auto-created layers+ const action = getDispatched().find((a: any) => a.type === 'ADD_DATA_TO_MAP');+ expect(action).toBeTruthy();+ expect(action.payload.options).toEqual({autoCreateLayers: false, centerMap: true});+ });+});diff --git a/src/mcp/src/commands/table-command.ts b/src/mcp/src/commands/table-command.tsnew file mode 100644index 000000000..3ca5b1f93--- /dev/null+++ b/src/mcp/src/commands/table-command.ts@@ -0,0 +1,157 @@+import type {RoomCommand} from './types';+import {z} from 'zod';+import {tableFromArrays, Table as ArrowTable} from 'apache-arrow';+import {addDataToMap} from '@kepler.gl/actions';+import {processFileData} from '@kepler.gl/processors';+import type {KeplerContext} from './types';+import {datasetNameToTableName, arrowTableToObjects} from './utils';+import {isObjectColumn, stringifyObjectColumn, restoreObjectColumns} from './utils';++export const tableCommandId = 'map.create-table' as const;++export function getTableCommand(ctx: KeplerContext): RoomCommand {+ return {+ id: tableCommandId,+ name: 'Create map dataset via SQL',+ group: 'Map',+ description: `Create a NEW dataset in kepler.gl from a SQL query. The result becomes a SEPARATE new dataset (resultDatasetName); the ORIGINAL dataset and its layers/filters are left untouched. Use it to build a new table with different columns — e.g. add, delete, or rename columns, or change a column's type (CAST(col AS <type>)) — inside the new dataset.+NOTE: To modify an EXISTING dataset in place, do NOT use this command — use map.add-column instead (add a column that copies an existing one to "rename", or casts it via expression to change its type). Only reach for map.create-table when the user wants a NEW, separate dataset.+Please note:+1. Do not use * to select all columns, instead use all the column names in dataset.+2. List all column names the new table or dataset will have.+IMPORTANT: Use __TABLE__ as the table name placeholder in SQL. It will be replaced with the actual DuckDB table name at runtime.`,+ metadata: {readOnly: false, riskLevel: 'high', idempotent: false, requiresConfirmation: true},+ inputSchema: z.object({+ datasetName: z.string().describe('The name of the source dataset'),+ variableNames: z+ .array(z.string())+ .describe('Only use variable names that already exist in the dataset.'),+ sql: z+ .string()+ .describe('The SQL query to execute. Use __TABLE__ as the table name placeholder.'),+ resultDatasetName: z.string().describe('The name for the new dataset')+ }) as any,+ execute: async (_execCtx, input) => {+ const {datasetName, variableNames, sql, resultDatasetName} = (input ?? {}) as {+ datasetName: string;+ variableNames: string[];+ sql: string;+ resultDatasetName: string;+ };+ try {+ // Runtime guard: the bridge/webMCP call execute without zod parsing, so+ // missing/wrong-typed inputs must not fall through to TypeErrors (e.g.+ // `sql.includes` on a non-string) that surface as confusing errors.+ if (typeof datasetName !== 'string' || datasetName.length === 0) {+ throw new Error('datasetName must be a non-empty string.');+ }+ if (+ !Array.isArray(variableNames) ||+ variableNames.length === 0 ||+ variableNames.some(v => typeof v !== 'string' || v.length === 0)+ ) {+ throw new Error('variableNames must be a non-empty array of non-empty strings.');+ }+ if (typeof sql !== 'string' || sql.length === 0) {+ throw new Error('sql must be a non-empty string.');+ }+ if (typeof resultDatasetName !== 'string' || resultDatasetName.length === 0) {+ throw new Error('resultDatasetName must be a non-empty string.');+ }++ const visState = ctx.getVisState();+ const datasets = visState.datasets;+ const dataId = Object.keys(datasets).find(+ id => id === datasetName || datasets[id].label === datasetName+ );+ if (!dataId) {+ throw new Error(`Dataset "${datasetName}" not found.`);+ }+ // Derive the DuckDB table name from the resolved dataset id, not the+ // user-provided label: different labels can sanitize to the same table+ // name (e.g. "A-B" vs "A B"), which would clobber another dataset's+ // temp table inside DuckDB and run the SQL against unintended data.+ const dbTableName = datasetNameToTableName(dataId);+ // The contract requires the __TABLE__ placeholder — without it the+ // query would run against whatever table names appear in the SQL (or+ // return unrelated results), which is especially risky for a+ // high-risk, confirmation-gated command. Fail fast with an actionable+ // error instead.+ if (!sql.includes('__TABLE__')) {+ throw new Error(+ 'The SQL query must use the __TABLE__ placeholder as the table name, ' ++ 'e.g. `SELECT * FROM __TABLE__`.'+ );+ }+ const resolvedSql = sql.replace(/__TABLE__/g, `"${dbTableName}"`);+ // Dedupe variableNames: duplicate names would silently overwrite+ // earlier entries in columnData, producing an Arrow table that doesn't+ // match the requested column list.+ const uniqueVariableNames = [...new Set(variableNames)];+ const columnData: Record<string, unknown[]> = {};+ // Object-valued columns (the `_geojson` Feature objects) must not be+ // round-tripped through Arrow raw: `tableFromArrays` infers ONE Arrow+ // type per column from the first value, so a dataset mixing Polygon and+ // MultiPolygon features gets the shallower (Polygon) coordinate nesting+ // and the MultiPolygon coordinates come back as nulls. Stringify them+ // for the DuckDB round-trip and restore the objects afterwards.+ const objectColumns: string[] = [];+ for (const varName of uniqueVariableNames) {+ // Pass the user-provided datasetName (label or id) — the documented+ // KeplerContext contract — not the resolved id; getValuesFromDataset+ // matches by label or id either way.+ const values = ctx.getValuesFromDataset(datasetName, varName);+ if (isObjectColumn(values)) objectColumns.push(varName);+ columnData[varName] = stringifyObjectColumn(values);+ }++ const arrowTable: ArrowTable = tableFromArrays(columnData);+ const db = await ctx.getConnector();++ await db.execute(`DROP TABLE IF EXISTS "${dbTableName}"`);+ await db.loadArrow(arrowTable, dbTableName);++ const arrowResult = await db.query(resolvedSql);++ const jsonResult: Record<string, unknown>[] = arrowTableToObjects(arrowResult);+ restoreObjectColumns(jsonResult, objectColumns);++ const parsedData = await processFileData({+ content: {data: jsonResult, fileName: resultDatasetName},+ fileCache: []+ });++ ctx.dispatch(+ addDataToMap({+ datasets: parsedData,+ // No auto-create — the assistant creates the layer explicitly via+ // `map.add-layer` to avoid duplicate default layers.+ options: {autoCreateLayers: false, centerMap: true}+ })+ );++ // Trimmed, model-facing subset (ported from the old `toModelOutput`).+ const firstFiveRows = jsonResult.slice(0, 5);+ return {+ success: true,+ commandId: tableCommandId,+ data: {+ details: `Table created as ${resultDatasetName} (${jsonResult.length} rows) and added to kepler.gl.`,+ resultDatasetName,+ firstFiveRows+ }+ };+ } catch (error) {+ return {+ success: false,+ commandId: tableCommandId,+ error: error instanceof Error ? error.message : String(error),+ data: {+ instruction:+ 'Please explain the error and give a plan to fix it. Then try again with a different query.'+ }+ };+ }+ }+ };+}diff --git a/src/mcp/src/commands/time-filter-command.spec.ts b/src/mcp/src/commands/time-filter-command.spec.tsnew file mode 100644index 000000000..b9e77bda3--- /dev/null+++ b/src/mcp/src/commands/time-filter-command.spec.ts@@ -0,0 +1,177 @@+import {getAddTimeFilterCommand} from './time-filter-command';+import {ActionTypes} from '@kepler.gl/actions';+import KeplerTable from '@kepler.gl/table';+import {ALL_FIELD_TYPES} from '@kepler.gl/constants';++async function makeTimestampTable() {+ const table = new KeplerTable({color: [255, 0, 0]} as any);+ await table.importData({+ data: {+ rows: [+ [37.77, -122.42, '2024-01-01T00:00:00'],+ [37.78, -122.45, '2024-01-02T00:00:00'],+ [37.74, -122.44, '2024-01-03T00:00:00']+ ],+ fields: [+ {name: 'lat', type: ALL_FIELD_TYPES.real},+ {name: 'lng', type: ALL_FIELD_TYPES.real},+ {name: 'ts', type: ALL_FIELD_TYPES.timestamp}+ ]+ } as any+ });+ return table;+}++// 2024-01-01 .. 2024-01-03 (three daily timestamps → auto-detected '1-day')+const DOMAIN = [1704067200000, 1704326400000];+const DAY = 86_400_000;++/**+ * Mock KeplerContext whose dispatch simulates just enough of the kepler filter+ * reducer for the command's poll loops to succeed: ADD_FILTER creates a filter+ * entry (with id + domain + timeBins), SET_FILTER mutates it in place.+ */+function makeCtx(table: KeplerTable, opts: {existingFilter?: boolean} = {}) {+ const filters: any[] = [];+ const dispatched: any[] = [];+ const visState = {datasets: {[table.id as string]: table}, filters};+ // kepler stores timeBins keyed by dataId, then by interval: {[dataId]: {[interval]: bins[]}}+ const timeBins = {[table.id as string]: {'1-day': [{x0: DOMAIN[0], x1: DOMAIN[0] + DAY}]}};++ if (opts.existingFilter) {+ filters.push({+ id: 'existing_filter',+ dataId: [table.id],+ name: ['ts'],+ domain: DOMAIN,+ plotType: {interval: '1-day'},+ timeBins+ });+ }++ const ctx = {+ getVisState: () => visState,+ dispatch: (action: any) => {+ dispatched.push(action);+ if (action.type === ActionTypes.ADD_FILTER) {+ filters.push({+ id: `filter_${filters.length + 1}`,+ dataId: [action.dataId],+ name: [],+ domain: DOMAIN,+ plotType: {interval: '1-day'},+ timeBins+ });+ } else if (action.type === ActionTypes.SET_FILTER) {+ const f = filters[action.idx];+ if (f) f[action.prop] = action.value;+ }+ },+ getValuesFromDataset: () => [],+ getMapBoundary: () => null,+ getMapboxToken: () => undefined,+ getDatasetContext: () => ''+ };+ return {ctx, getDispatched: () => dispatched};+}++type CommandResult = {success: boolean; error?: string; data?: Record<string, unknown>};++describe('map.add-time-filter', () => {+ it('creates a new filter on a timestamp column and animates it', async () => {+ const table = await makeTimestampTable();+ const {ctx, getDispatched} = makeCtx(table);++ const cmd = getAddTimeFilterCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: table.label,+ dateTimeColumn: 'ts'+ })) as CommandResult;++ expect(result.success).toBe(true);+ const types = getDispatched().map((a: any) => a.type);+ expect(types).toContain(ActionTypes.ADD_FILTER);+ expect(types).toContain(ActionTypes.SET_FILTER);+ expect(types).toContain(ActionTypes.SET_FILTER_ANIMATION_WINDOW);+ expect(types).toContain(ActionTypes.SET_FILTER_ANIMATION_TIME);+ // interval auto-detected from the 1-day gap between the three timestamps+ expect((result.data as any).interval).toBe('1-day');+ });++ it('reuses an existing filter on the same column instead of adding a new one', async () => {+ const table = await makeTimestampTable();+ const {ctx, getDispatched} = makeCtx(table, {existingFilter: true});++ const cmd = getAddTimeFilterCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: table.label,+ dateTimeColumn: 'ts'+ })) as CommandResult;++ expect(result.success).toBe(true);+ const types = getDispatched().map((a: any) => a.type);+ expect(types).not.toContain(ActionTypes.ADD_FILTER);+ expect(types).toContain(ActionTypes.SET_FILTER_ANIMATION_WINDOW);+ expect(types).toContain(ActionTypes.SET_FILTER_ANIMATION_TIME);+ });++ it('rejects an invalid interval at runtime (bridge path skips zod)', async () => {+ const table = await makeTimestampTable();+ const {ctx} = makeCtx(table);++ const cmd = getAddTimeFilterCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: table.label,+ dateTimeColumn: 'ts',+ interval: '2-day'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/Invalid interval/);+ });++ it('rejects an inherited-property interval like "toString" (own-property check)', async () => {+ const table = await makeTimestampTable();+ const {ctx} = makeCtx(table);++ const cmd = getAddTimeFilterCommand(ctx as any);+ // `"toString" in INTERVAL_MILLIS` is true (inherited from Object.prototype),+ // so the guard must use an own-property check to reject it.+ const result = (await cmd.execute({} as any, {+ datasetName: table.label,+ dateTimeColumn: 'ts',+ interval: 'toString'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/Invalid interval/);+ });++ it('rejects a non-timestamp column', async () => {+ const table = await makeTimestampTable();+ const {ctx} = makeCtx(table);++ const cmd = getAddTimeFilterCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: table.label,+ dateTimeColumn: 'lat'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/not timestamp\/date/);+ });++ it('fails fast when the dataset is unknown', async () => {+ const table = await makeTimestampTable();+ const {ctx} = makeCtx(table);++ const cmd = getAddTimeFilterCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ datasetName: 'nope',+ dateTimeColumn: 'ts'+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/not found/);+ });+});diff --git a/src/mcp/src/commands/time-filter-command.ts b/src/mcp/src/commands/time-filter-command.tsnew file mode 100644index 000000000..0ce8dc86b--- /dev/null+++ b/src/mcp/src/commands/time-filter-command.ts@@ -0,0 +1,292 @@+import type {RoomCommand} from './types';+import {z} from 'zod';+import type KeplerTable from '@kepler.gl/table';+import type {Datasets} from '@kepler.gl/table';+import {+ addFilter,+ setFilter,+ setFilterAnimationTime,+ setFilterAnimationWindow+} from '@kepler.gl/actions';+import type {KeplerContext} from './types';++export type IntervalKey =+ | '1-second'+ | '1-minute'+ | '1-hour'+ | '1-day'+ | '1-week'+ | '1-month'+ | '3-month'+ | '1-year';++const MILLIS_SECOND = 1_000;+const MILLIS_MINUTE = 60 * MILLIS_SECOND;+const MILLIS_HOUR = 60 * MILLIS_MINUTE;+const MILLIS_DAY = 24 * MILLIS_HOUR;+const MILLIS_WEEK = 7 * MILLIS_DAY;+const MILLIS_MONTH = 30 * MILLIS_DAY;+const MILLIS_3_MONTH = 91 * MILLIS_DAY;+const MILLIS_YEAR = 365 * MILLIS_DAY;++export const INTERVAL_MILLIS: Record<IntervalKey, number> = {+ '1-second': MILLIS_SECOND,+ '1-minute': MILLIS_MINUTE,+ '1-hour': MILLIS_HOUR,+ '1-day': MILLIS_DAY,+ '1-week': MILLIS_WEEK,+ '1-month': MILLIS_MONTH,+ '3-month': MILLIS_3_MONTH,+ '1-year': MILLIS_YEAR+};++/**+ * Infer a sensible animation interval from a time filter's domain and (when+ * available) the actual distinct timestamps in the dataset. Mirrors the logic+ * used by spatial-agent's `detectIntervalFromDomain` so the skill-path behaves+ * identically.+ */+export function detectIntervalFromDomain(+ domain: [number, number],+ mappedValues?: number[]+): IntervalKey {+ const span = domain[1] - domain[0];+ if (span <= 0) return '1-year';++ let numUniqueSteps: number;+ if (mappedValues && mappedValues.length > 0) {+ const unique = new Set(mappedValues.filter(v => v != null));+ numUniqueSteps = unique.size;+ } else {+ numUniqueSteps = 2;+ }++ if (numUniqueSteps <= 1) return '1-year';++ const avgGap = span / Math.max(numUniqueSteps - 1, 1);++ if (avgGap >= MILLIS_YEAR * 0.8) return '1-year';+ if (avgGap >= MILLIS_MONTH * 2.5) return '3-month';+ if (avgGap >= MILLIS_MONTH * 0.8) return '1-month';+ if (avgGap >= MILLIS_DAY * 5) return '1-week';+ if (avgGap >= MILLIS_DAY * 0.8) return '1-day';+ if (avgGap >= MILLIS_HOUR * 0.8) return '1-hour';+ if (avgGap >= MILLIS_MINUTE * 0.8) return '1-minute';+ return '1-second';+}++const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));++export const addTimeFilterCommandId = 'map.add-time-filter' as const;++export function getAddTimeFilterCommand(ctx: KeplerContext): RoomCommand {+ return {+ id: addTimeFilterCommandId,+ name: 'Add time filter',+ group: 'Map',+ description: `Add a time-range filter to animate a NON-trip layer over a TIMESTAMP/DATE column. The time controller appears at the bottom of the map.++DO NOT call this for a trip layer — trips have built-in time animation.++The dataset and a layer for it must already exist on the map (e.g. from map.add-layer or map.load-data).++Pass the datasetName and the dateTimeColumn to animate over. The interval is auto-detected from the data when omitted; pass it explicitly to override.`,+ metadata: {readOnly: false, riskLevel: 'medium', idempotent: false},+ inputSchema: z.object({+ datasetName: z.string().describe('The name (label) or id of the dataset to animate.'),+ dateTimeColumn: z+ .string()+ .describe(+ 'A TIMESTAMP or DATE column in the dataset. Do NOT pass an integer/string epoch column — build a real TIMESTAMP column first.'+ ),+ interval: z+ .enum(['1-second', '1-minute', '1-hour', '1-day', '1-week', '1-month', '3-month', '1-year'])+ .optional()+ .describe(+ 'Animation step. Auto-detected from the data span and distinct timestamps when omitted.'+ )+ }) as any,+ execute: async (_execCtx, input) => {+ const {datasetName, dateTimeColumn, interval} = (input ?? {}) as {+ datasetName: string;+ dateTimeColumn: string;+ interval?: IntervalKey;+ };+ try {+ // Runtime guard: the bridge/webMCP call execute without zod parsing,+ // so an invalid interval must not be written into kepler filter state+ // (plotType.interval). Use an own-property check — `in` matches+ // inherited properties (e.g. "toString"), so a crafted interval could+ // otherwise bypass the guard — and require a string value.+ if (+ interval !== undefined &&+ (typeof interval !== 'string' ||+ !Object.prototype.hasOwnProperty.call(INTERVAL_MILLIS, interval))+ ) {+ throw new Error(+ `Invalid interval "${String(interval)}". Must be one of: ${Object.keys(+ INTERVAL_MILLIS+ ).join(', ')}.`+ );+ }+ const visState = ctx.getVisState();+ const datasets: Datasets = visState.datasets;++ const datasetId = Object.keys(datasets).find(+ dataId => datasets[dataId].label === datasetName || dataId === datasetName+ );+ if (!datasetId) {+ throw new Error(`Dataset ${datasetName} not found.`);+ }+ const dataset = datasets[datasetId] as KeplerTable;++ const filterField = dataset.fields?.find(f => f.name === dateTimeColumn);+ if (!filterField) {+ throw new Error(+ `Column ${dateTimeColumn} not found in dataset ${datasetName}. Available: ${dataset.fields+ ?.map(f => f.name)+ .join(', ')}`+ );+ }+ if (filterField.type !== 'timestamp' && filterField.type !== 'date') {+ throw new Error(+ `Column ${dateTimeColumn} is of type "${filterField.type}", not timestamp/date. Build a real TIMESTAMP column first (Kepler.gl cannot animate on integer/string epochs).`+ );+ }++ // Explicitly typed: `VisState.filters` is untyped (index signature) and+ // strict consumers (e.g. kepler-assistant, which vendors this module)+ // would otherwise flag the `.findIndex(f => …)` callback as implicit any.+ const filters: any[] = visState.filters ?? [];+ const existingFilterIdx = filters.findIndex(+ f =>+ (Array.isArray(f.dataId) ? f.dataId.includes(datasetId) : f.dataId === datasetId) &&+ (Array.isArray(f.name) ? f.name.includes(dateTimeColumn) : f.name === dateTimeColumn)+ );++ let filterIdx: number;+ let filterId: string;++ if (existingFilterIdx >= 0) {+ filterIdx = existingFilterIdx;+ filterId = filters[existingFilterIdx].id;+ } else {+ filterIdx = filters.length;+ ctx.dispatch(addFilter(datasetId));+ ctx.dispatch(setFilter(filterIdx, 'name', dateTimeColumn));+ // Poll for the filter entry to appear instead of a fixed sleep: on+ // slower devices the filter (and its id) may not be available yet,+ // and a fixed delay would leave filterId as an empty string, making+ // the later setFilterAnimationWindow({id: filterId, ...}) behave+ // unpredictably.+ filterId = '';+ for (let attempt = 0; attempt < 10 && !filterId; attempt++) {+ await sleep(100);+ filterId = ctx.getVisState().filters?.[filterIdx]?.id ?? '';+ }+ if (!filterId) {+ // Fail fast instead of proceeding with an empty id — the later+ // setFilterAnimationWindow({id: filterId, ...}) would no-op or+ // update the wrong filter.+ throw new Error(+ `Timed out waiting for the time filter on column "${dateTimeColumn}" to be created. Please try again.`+ );+ }+ }++ const currentFilters = ctx.getVisState().filters ?? [];+ const targetFilter = currentFilters[filterIdx];++ let resolvedInterval: IntervalKey | string | undefined = interval;++ if (targetFilter?.domain && targetFilter.domain.length === 2) {+ if (!resolvedInterval) {+ let mappedValues: number[] | undefined;+ const fieldIdx = dataset.fields?.indexOf(filterField) ?? -1;+ if (fieldIdx >= 0 && dataset.dataContainer) {+ const rows = dataset.dataContainer.numRows();+ mappedValues = [];+ // Sample a bounded number of rows — iterating every row can freeze+ // the UI thread on large datasets, and a sample is enough for a+ // reasonable interval estimate.+ const MAX_SAMPLES = 1000;+ const step = Math.max(1, Math.floor(rows / MAX_SAMPLES));+ for (let i = 0; i < rows; i += step) {+ const val = dataset.dataContainer.valueAt(i, fieldIdx);+ if (val != null) {+ const ts = typeof val === 'number' ? val : new Date(val as any).getTime();+ if (!isNaN(ts)) mappedValues.push(ts);+ }+ }+ }+ resolvedInterval = detectIntervalFromDomain(+ targetFilter.domain as [number, number],+ mappedValues+ );+ }++ ctx.dispatch(setFilter(filterIdx, 'plotType', {interval: resolvedInterval}));+ ctx.dispatch(setFilterAnimationWindow({id: filterId, animationWindow: 'free'}));++ // Poll for timeBins to become available (kepler computes them async).+ let datasetBins: {x0: number; x1: number}[] | undefined;+ for (let attempt = 0; attempt < 10; attempt++) {+ await sleep(200);+ const updatedFilter = ctx.getVisState().filters?.[filterIdx];+ if (updatedFilter?.domain && updatedFilter.domain.length === 2) {+ // timeBins is keyed by dataset id, then by interval:+ // {[dataId]: {[interval]: bins[]}}. Look up the bins for THIS+ // filter's dataset — grabbing the first entry via+ // Object.values(timeBins)[0] would pick the wrong dataset's bins+ // when multiple datasets/filters exist, animating against the+ // wrong time window.+ const timeBins = (updatedFilter as any).timeBins;+ const bins = timeBins?.[datasetId]?.[resolvedInterval as string];+ if (bins && bins.length > 0) {+ datasetBins = bins;+ break;+ }+ }+ }++ const finalFilter = ctx.getVisState().filters?.[filterIdx];+ if (finalFilter?.domain && finalFilter.domain.length === 2) {+ if (datasetBins && datasetBins.length > 0) {+ ctx.dispatch(+ setFilterAnimationTime(filterIdx, 'value', [datasetBins[0].x0, datasetBins[0].x1])+ );+ } else {+ const domainStart = (finalFilter.domain as number[])[0];+ const windowSize = INTERVAL_MILLIS[resolvedInterval as IntervalKey] ?? MILLIS_YEAR;+ ctx.dispatch(+ setFilterAnimationTime(filterIdx, 'value', [domainStart, domainStart + windowSize])+ );+ }+ }+ }++ return {+ success: true,+ commandId: addTimeFilterCommandId,+ data: {+ details: `Time filter added on column "${dateTimeColumn}" for dataset "${datasetName}" (interval: ${+ resolvedInterval ?? 'auto'+ }, filter index: ${filterIdx}). The time controller is now visible at the bottom of the map.`,+ filterIndex: filterIdx,+ interval: resolvedInterval+ }+ };+ } catch (error) {+ return {+ success: false,+ commandId: addTimeFilterCommandId,+ error: error instanceof Error ? error.message : 'Unknown error',+ data: {+ instruction:+ 'Check that the dataset exists, the column is a TIMESTAMP/DATE, and a layer for the dataset is already on the map. Do not retry more than once.'+ }+ };+ }+ }+ };+}diff --git a/src/mcp/src/commands/toggle-time-filter-command.spec.ts b/src/mcp/src/commands/toggle-time-filter-command.spec.tsnew file mode 100644index 000000000..b90725ce0--- /dev/null+++ b/src/mcp/src/commands/toggle-time-filter-command.spec.ts@@ -0,0 +1,130 @@+import {getToggleTimeFilterCommand} from './toggle-time-filter-command';+import {ActionTypes} from '@kepler.gl/actions';++/**+ * Mock KeplerContext whose dispatch records actions. The command reads+ * visState.filters and dispatches setFilterView(idx, view) — the assertions+ * only need the dispatch sequence, not a real filter reducer.+ */+function makeCtx(opts: {filters?: any[]} = {}) {+ const dispatched: any[] = [];+ const visState = {+ datasets: {},+ layers: [],+ filters: opts.filters ?? []+ };+ const ctx = {+ getVisState: () => visState,+ dispatch: (action: any) => {+ dispatched.push(action);+ },+ getValuesFromDataset: () => [],+ getMapBoundary: () => null,+ getMapboxToken: () => undefined,+ getDatasetContext: () => ''+ };+ return {ctx, getDispatched: () => dispatched};+}++type CommandResult = {success: boolean; error?: string; data?: Record<string, unknown>};++describe('map.toggle-time-filter', () => {+ it('enlarges the first time filter when filterIndex is omitted', async () => {+ const filters = [{id: 'f0', type: 'timeRange'}, {id: 'f1', type: 'timeRange'}];+ const {ctx, getDispatched} = makeCtx({filters});+ const cmd = getToggleTimeFilterCommand(ctx as any);+ const result = (await cmd.execute({} as any, {action: 'show'})) as CommandResult;++ expect(result.success).toBe(true);+ const views = getDispatched().filter((a: any) => a.type === ActionTypes.SET_FILTER_VIEW);+ expect(views).toHaveLength(1);+ expect(views[0].idx).toBe(0);+ expect(views[0].view).toBe('enlarged');+ });++ it('collapses the requested filter back to the side panel', async () => {+ const filters = [{id: 'f0', type: 'timeRange'}, {id: 'f1', type: 'timeRange'}];+ const {ctx, getDispatched} = makeCtx({filters});+ const cmd = getToggleTimeFilterCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ action: 'hide',+ filterIndex: 1+ })) as CommandResult;++ expect(result.success).toBe(true);+ const views = getDispatched().filter((a: any) => a.type === ActionTypes.SET_FILTER_VIEW);+ expect(views).toHaveLength(1);+ expect(views[0].idx).toBe(1);+ expect(views[0].view).toBe('side');+ });++ it('rejects an invalid action instead of silently hiding the controller', async () => {+ const filters = [{id: 'f0', type: 'timeRange'}];+ const {ctx, getDispatched} = makeCtx({filters});+ const cmd = getToggleTimeFilterCommand(ctx as any);+ const result = (await cmd.execute({} as any, {action: 'toggle'})) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/Invalid action/);+ // no setFilterView dispatched+ expect(+ getDispatched().filter((a: any) => a.type === ActionTypes.SET_FILTER_VIEW)+ ).toHaveLength(0);+ });++ it('fails fast when no filters exist on the map', async () => {+ const {ctx, getDispatched} = makeCtx();+ const cmd = getToggleTimeFilterCommand(ctx as any);+ const result = (await cmd.execute({} as any, {action: 'show'})) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/No filters found/);+ expect(getDispatched()).toHaveLength(0);+ });++ it('does not fall back to a non-time filter when filterIndex is omitted', async () => {+ // Filters exist but none are time filters — the auto-pick must error+ // instead of toggling the first (unrelated) filter.+ const filters = [{id: 'f0', type: 'range'}];+ const {ctx, getDispatched} = makeCtx({filters});+ const cmd = getToggleTimeFilterCommand(ctx as any);+ const result = (await cmd.execute({} as any, {action: 'show'})) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/No time filter found/);+ expect(getDispatched()).toHaveLength(0);+ });++ it('rejects an out-of-range filterIndex', async () => {+ const filters = [{id: 'f0', type: 'timeRange'}];+ const {ctx, getDispatched} = makeCtx({filters});+ const cmd = getToggleTimeFilterCommand(ctx as any);+ const result = (await cmd.execute({} as any, {+ action: 'show',+ filterIndex: 5+ })) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/out of range/);+ expect(getDispatched()).toHaveLength(0);+ });++ it('rejects a non-integer or negative filterIndex', async () => {+ const filters = [{id: 'f0', type: 'timeRange'}];+ const {ctx, getDispatched} = makeCtx({filters});+ const cmd = getToggleTimeFilterCommand(ctx as any);++ for (const bad of ['1', 1.5, -1]) {+ const result = (await cmd.execute({} as any, {+ action: 'show',+ filterIndex: bad+ })) as CommandResult;+ expect(result.success).toBe(false);+ expect(result.error).toMatch(/Invalid filterIndex/);+ }+ // no setFilterView dispatched for any of them+ expect(+ getDispatched().filter((a: any) => a.type === ActionTypes.SET_FILTER_VIEW)+ ).toHaveLength(0);+ });+});diff --git a/src/mcp/src/commands/toggle-time-filter-command.ts b/src/mcp/src/commands/toggle-time-filter-command.tsnew file mode 100644index 000000000..105663343--- /dev/null+++ b/src/mcp/src/commands/toggle-time-filter-command.ts@@ -0,0 +1,136 @@+import type {RoomCommand} from './types';+import {z} from 'zod';+import {setFilterView} from '@kepler.gl/actions';+import type {KeplerContext} from './types';++export const toggleTimeFilterCommandId = 'map.toggle-time-filter' as const;++export function getToggleTimeFilterCommand(ctx: KeplerContext): RoomCommand {+ return {+ id: toggleTimeFilterCommandId,+ name: 'Toggle time controller',+ group: 'Map',+ description: `Show or hide the enlarged time controller at the bottom of the map.++A time filter must already exist on the map (created via map.add-time-filter).++- action: "show" — enlarge the time controller so it is visible at the bottom of the map.+- action: "hide" — collapse the time controller back to the side panel.`,+ metadata: {readOnly: false, riskLevel: 'low', idempotent: true},+ inputSchema: z.object({+ action: z+ .enum(['show', 'hide'])+ .describe(+ '"show" enlarges the time controller at the bottom of the map; "hide" collapses it to the side panel.'+ ),+ filterIndex: z+ .number()+ .optional()+ .describe(+ 'Index of the time filter to toggle. If omitted, the first time-range filter found is used.'+ )+ }) as any,+ execute: async (_execCtx, input) => {+ const {action, filterIndex} = (input ?? {}) as {+ action: 'show' | 'hide';+ filterIndex?: number;+ };+ try {+ // Runtime guard: the bridge/webMCP call execute directly without zod+ // parsing, so a missing/invalid action must not silently fall back to+ // 'side' (which would hide the controller — a surprising mutation).+ if (action !== 'show' && action !== 'hide') {+ return {+ success: false,+ commandId: toggleTimeFilterCommandId,+ error: `Invalid action "${String(action)}". Must be "show" or "hide".`,+ data: {+ instruction:+ 'Pass action: "show" to enlarge the time controller, or "hide" to collapse it.'+ }+ };+ }+ // Runtime guard: the bridge/webMCP call execute without zod parsing, so+ // a string/float filterIndex must not slip through and be dispatched+ // into setFilterView (breaking reducer logic / toggling the wrong+ // filter). Reject anything that isn't a non-negative integer.+ if (filterIndex !== undefined && (!Number.isInteger(filterIndex) || filterIndex < 0)) {+ return {+ success: false,+ commandId: toggleTimeFilterCommandId,+ error: `Invalid filterIndex "${String(filterIndex)}". Must be a non-negative integer.`,+ data: {+ instruction:+ 'Pass filterIndex as a non-negative integer, or omit it to auto-detect the first time filter.'+ }+ };+ }++ const visState = ctx.getVisState();+ const filters = visState.filters ?? [];++ if (filters.length === 0) {+ return {+ success: false,+ commandId: toggleTimeFilterCommandId,+ error: 'No filters found on the map. Add a time filter first via map.add-time-filter.',+ data: {instruction: 'Call map.add-time-filter before map.toggle-time-filter.'}+ };+ }++ let targetIdx: number;+ if (filterIndex === undefined) {+ const found = filters.findIndex((f: any) => f.type === 'timeRange' || f.type === 'time');+ // Don't fall back to index 0 when no time filter exists — toggling+ // the first (non-time) filter would mutate an unrelated filter,+ // contradicting the "a time filter must already exist" contract.+ if (found < 0) {+ return {+ success: false,+ commandId: toggleTimeFilterCommandId,+ error:+ 'No time filter found on the map. Add a time filter first via map.add-time-filter.',+ data: {instruction: 'Call map.add-time-filter before map.toggle-time-filter.'}+ };+ }+ targetIdx = found;+ } else {+ targetIdx = filterIndex;+ }++ if (targetIdx < 0 || targetIdx >= filters.length) {+ return {+ success: false,+ commandId: toggleTimeFilterCommandId,+ error: `Filter index ${targetIdx} is out of range. There are ${filters.length} filter(s).`,+ data: {instruction: `Use a filterIndex between 0 and ${filters.length - 1}.`}+ };+ }++ const view = action === 'show' ? 'enlarged' : 'side';+ ctx.dispatch(setFilterView(targetIdx, view as any));++ return {+ success: true,+ commandId: toggleTimeFilterCommandId,+ data: {+ details:+ action === 'show'+ ? `Time filter at index ${targetIdx} is now enlarged. The time controller is visible at the bottom of the map.`+ : `Time filter at index ${targetIdx} has been collapsed back to the side panel.`+ }+ };+ } catch (error) {+ return {+ success: false,+ commandId: toggleTimeFilterCommandId,+ error: error instanceof Error ? error.message : 'Unknown error',+ data: {+ instruction:+ 'Check that a time filter exists. If the error persists, ask the user to try with different parameters.'+ }+ };+ }+ }+ };+}diff --git a/src/mcp/src/commands/types.ts b/src/mcp/src/commands/types.tsnew file mode 100644index 000000000..a61c297ec--- /dev/null+++ b/src/mcp/src/commands/types.ts@@ -0,0 +1,148 @@+import type {Table as ArrowTable} from 'apache-arrow';+import type {ZodType} from 'zod';+import type {Datasets} from '@kepler.gl/table';+import type {KeplerDispatch} from './utils';++/**+ * Structural subset of `@sqlrooms/room-store`'s `RoomCommand` — enough for the+ * map.* command factories and for a host to register the built objects. Defined+ * locally (with `zod`, already a dependency) so this package stays free of+ * `@sqlrooms/room-store`; the objects the factories build are structurally+ * compatible with sqlrooms' own `RoomCommand`.+ */+export type RoomCommandResult<TData = unknown> = {+ success: boolean;+ commandId: string;+ message?: string;+ code?: string;+ data?: TData;+ error?: string;+};++export type RoomCommandExecuteOutput<TData = unknown> = RoomCommandResult<TData> | TData | void;++export type RoomCommandExecutionContext = {+ store: unknown;+ getState: () => unknown;+ invocation: unknown;+ signal?: AbortSignal;+};++export type RoomCommandPolicyMetadata = {+ readOnly?: boolean;+ idempotent?: boolean;+ riskLevel?: 'low' | 'medium' | 'high';+ requiresConfirmation?: boolean;+};++export type RoomCommand = {+ id: string;+ name: string;+ description?: string;+ group?: string;+ keywords?: string[];+ inputSchema?: ZodType<unknown>;+ metadata?: RoomCommandPolicyMetadata;+ execute: (+ context: RoomCommandExecutionContext,+ input?: unknown+ ) => RoomCommandExecuteOutput | Promise<RoomCommandExecuteOutput>;+};++/**+ * A command's model-facing descriptor: the id/name/description/group/keywords+ * plus a JSON-Schema-converted `inputSchema` and the policy metadata. This is+ * the shape hosts advertise over the wire (e.g. the demo-app bridge's+ * `toDescriptor`), so it lives in the map surface package to keep the contract+ * self-contained.+ */+export type ToolDescriptor = {+ id: string;+ name: string;+ description?: string;+ group?: string;+ keywords?: string[];+ inputSchema: Record<string, unknown>;+ metadata?: RoomCommandPolicyMetadata;+};++/**+ * Structural slice of `@sqlrooms/duckdb`'s `DuckDbConnector` — only the methods+ * the map.* commands call, typed against apache-arrow so the query result flows+ * into `arrowTableToObjects` / `arrowSchemaToFields` unchanged. Kept local so+ * this package needs no `@sqlrooms/duckdb` dependency; a host's real sqlrooms+ * connector satisfies this shape.+ */+export type DuckDbConnector = {+ execute(sql: string, options?: {signal?: AbortSignal}): PromiseLike<unknown>;+ query(sql: string, options?: {signal?: AbortSignal}): PromiseLike<ArrowTable>;+ loadArrow(+ table: ArrowTable | Uint8Array,+ tableName: string,+ opts?: {schema?: string}+ ): Promise<void>;+};++export type VisState = {+ datasets: Datasets;+ layers: any[];+ layerData: any[];+ loaders: any[];+ loadOptions: Record<string, any>;+ [key: string]: any;+};++/**+ * Accessors to the kepler.gl application state the assistant needs. The host+ * app supplies these (via `setKeplerStateAccessors`) so this module never+ * hard-codes a redux state shape (e.g. `demo.keplerGl.map.visState`). Any+ * app can provide accessors matching its own store.+ */+export type KeplerStateAccessors = {+ getVisState: () => VisState;+ getMapBoundary: () =>+ | {+ nw: [number, number];+ se: [number, number];+ }+ | undefined;+};++/**+ * KeplerContext provides access to kepler.gl state and dispatch.+ * This is passed into tool factories instead of using Redux directly.+ *+ * The four glue methods (`getValuesFromDataset`, `getDatasetContext`,+ * `loadTableToKepler`, `loadTableIntoDuckDB`, `getConnector`) are the+ * kepler-app-bound seam the map.* commands call. They are implemented by the+ * host's glue (kepler-assistant) so this package stays free of the DuckDB /+ * kepler-app wiring.+ */+export type KeplerContext = {+ getVisState: () => VisState;+ getMapBoundary: () =>+ | {+ nw: [number, number];+ se: [number, number];+ }+ | undefined;+ getMapboxToken: () => string | undefined;+ dispatch: KeplerDispatch;+ /** Read a column's values from a kepler dataset (by label or id). */+ getValuesFromDataset: (datasetName: string, variableName: string) => unknown[];+ /** Build the dataset+layer context string for the LLM. */+ getDatasetContext: () => string;+ /** Load a DuckDB table into kepler.gl as a dataset. */+ loadTableToKepler: (+ tableName: string,+ options?: {autoCreateLayers?: boolean; centerMap?: boolean}+ ) => Promise<{success: boolean; error?: string}>;+ /** Materialize a kepler dataset's columns into a DuckDB table and return the connector. */+ loadTableIntoDuckDB: (+ datasetName: string,+ variableNames: string[],+ dbTableName: string+ ) => Promise<DuckDbConnector>;+ /** The shared DuckDB connector (the store's, when wired). */+ getConnector: () => Promise<DuckDbConnector>;+};diff --git a/src/mcp/src/commands/utils.spec.ts b/src/mcp/src/commands/utils.spec.tsnew file mode 100644index 000000000..d2c016161--- /dev/null+++ b/src/mcp/src/commands/utils.spec.ts@@ -0,0 +1,86 @@+import {Type} from 'apache-arrow';+import {+ arrowTableToObjects,+ isObjectColumn,+ restoreObjectColumns,+ stringifyObjectColumn+} from './utils';++describe('arrowTableToObjects', () => {+ it('resolves Decimal columns to numbers using the declared scale', () => {+ const table = {+ toArray: () => [+ {toJSON: () => ({amount: {0: 123, 1: 0, 2: 0, 3: 0}, name: 'a'})},+ {toJSON: () => ({amount: {0: 456, 1: 0, 2: 0, 3: 0}, name: 'b'})}+ ],+ schema: {+ fields: [+ {name: 'amount', type: {typeId: Type.Decimal, scale: 2}},+ {name: 'name', type: {typeId: Type.Utf8}}+ ]+ }+ };+ expect(arrowTableToObjects(table as any)).toEqual([+ {amount: 1.23, name: 'a'},+ {amount: 4.56, name: 'b'}+ ]);+ });++ it('handles negative Decimal values (two\'s-complement 128-bit words)', () => {+ const table = {+ toArray: () => [+ {+ toJSON: () => ({+ amount: {0: 0xffffff85, 1: 0xffffffff, 2: 0xffffffff, 3: 0xffffffff}+ })+ }+ ],+ schema: {fields: [{name: 'amount', type: {typeId: Type.Decimal, scale: 2}}]}+ };+ expect(arrowTableToObjects(table as any)).toEqual([{amount: -1.23}]);+ });++ it('normalizes Decimal BigNums that arrive as Uint32Array views', () => {+ const table = {+ toArray: () => [{toJSON: () => ({amount: new Uint32Array([123, 0, 0, 0])})}],+ schema: {fields: [{name: 'amount', type: {typeId: Type.Decimal, scale: 2}}]}+ };+ expect(arrowTableToObjects(table as any)).toEqual([{amount: 1.23}]);+ });+});++describe('object-column stringify/restore', () => {+ it('isObjectColumn detects object values but ignores null/undefined', () => {+ expect(isObjectColumn([1, 2, 3])).toBe(false);+ expect(isObjectColumn([{a: 1}])).toBe(true);+ expect(isObjectColumn([null, undefined])).toBe(false);+ });++ it('stringifyObjectColumn serializes objects and passes primitives through', () => {+ expect(stringifyObjectColumn([{a: 1}, null, 'x', 5])).toEqual(['{"a":1}', null, 'x', 5]);+ // no object values → returned unchanged (same reference)+ const primitives = [1, 2, 3];+ expect(stringifyObjectColumn(primitives)).toBe(primitives);+ });++ it('restoreObjectColumns parses JSON strings back to objects/arrays', () => {+ const rows = [+ {_geojson: '{"type":"Point","coordinates":[1,2]}', name: 'a'},+ {_geojson: '[1,2,3]', name: 'b'}+ ];+ restoreObjectColumns(rows, ['_geojson']);+ expect(rows[0]._geojson).toEqual({type: 'Point', coordinates: [1, 2]});+ expect(rows[1]._geojson).toEqual([1, 2, 3]);+ });++ it('restoreObjectColumns leaves non-JSON and primitive-parsing strings as-is', () => {+ const rows = [+ {_geojson: 'not json', name: 'a'},+ // JSON.parse('42') → number 42, but only object/array values are restored+ {_geojson: '42', name: 'b'}+ ];+ restoreObjectColumns(rows, ['_geojson']);+ expect(rows[0]._geojson).toBe('not json');+ expect(rows[1]._geojson).toBe('42');+ });+});diff --git a/src/mcp/src/commands/utils.ts b/src/mcp/src/commands/utils.tsnew file mode 100644index 000000000..d01cad23d--- /dev/null+++ b/src/mcp/src/commands/utils.ts@@ -0,0 +1,455 @@+/**+ * Pure helpers shared by the map.* commands and the analysis shims. These are+ * dependency-light (apache-arrow only) and free of kepler-app state, so they+ * live in the map surface package and are re-exported for the analysis layer+ * (kepler-assistant) to import.+ */++import {Type} from 'apache-arrow';+import {LAYER_TYPES} from '@kepler.gl/constants';+import {arrowSchemaToFields} from '@kepler.gl/processors';+import type {Layer, VectorTileLayer} from '@kepler.gl/layers';+import type {Datasets} from '@kepler.gl/table';+import type {Field} from '@kepler.gl/types';++/** Type for a Redux dispatch function, used by tools that need to dispatch kepler actions */+export type KeplerDispatch = (action: any) => void;++/**+ * Deterministically convert a dataset name into a valid DuckDB table name.+ * Replaces non-alphanumeric characters (except underscores) with underscores,+ * collapses consecutive underscores, trims leading/trailing underscores,+ * lowercases the result, and prepends 'tbl_' to avoid reserved-word collisions.+ */+export function datasetNameToTableName(datasetName: string): string {+ const sanitized = datasetName+ .replace(/[^a-zA-Z0-9_]/g, '_')+ .replace(/_+/g, '_')+ .replace(/^_+|_+$/g, '')+ .toLowerCase();+ return `tbl_${sanitized || 'unnamed'}`;+}++/**+ * Recursively convert an Arrow row (which uses proxy objects) into a plain JS+ * object. Handles nested toJSON(), arrays, and bigint values. Extracted from+ * query-tool.ts so the stock @sqlrooms/ai query tool wrapper can share it.+ */+export function convertArrowRowToObject(row: any): unknown {+ if (row === null || typeof row !== 'object') return row;++ if (typeof row.toJSON === 'function') {+ const json = row.toJSON();+ for (const key in json) {+ const val = json[key];+ if (val && typeof val === 'object' && typeof val.toJSON === 'function') {+ json[key] = convertArrowRowToObject(val);+ } else if (Array.isArray(val)) {+ json[key] = val.map(v => convertArrowRowToObject(v));+ } else if (typeof val === 'bigint') {+ json[key] = val.toString();+ }+ }+ return json;+ }++ if (Array.isArray(row)) {+ return row.map(convertArrowRowToObject) as any;+ }++ return row;+}++/**+ * Normalize a Decimal BigNum into an indexable word array. Arrow's+ * DecimalBigNum is a Uint32Array (has `.length`); `row.toJSON()` can emit it as+ * a plain numeric-key object ({0: low, 1: high, ...}) with no `.length`, which+ * decimalBigNumToNumber would miscompute (the loop never runs, returning 0).+ */+function toWordArray(v: any): number[] {+ if (Array.isArray(v)) {+ return v;+ }+ if (ArrayBuffer.isView(v)) {+ return Array.from(v as unknown as ArrayLike<number>);+ }+ const words: number[] = [];+ for (let i = 0; i < 4; i++) {+ if (v[i] === undefined) break;+ words.push(v[i]);+ }+ return words;+}++/**+ * Convert an Arrow DecimalBigNum (128-bit signed, stored as a Uint32Array of+ * words) to a JS number, applying the column's declared scale.+ *+ * Arrow's own `valueOf(scale)` divides the raw bigint by 10^scale and converts+ * the intermediate denominator with bigIntToNumber, which throws for scale >= 16+ * (10^16 > Number.MAX_SAFE_INTEGER). We instead reconstruct the bigint and+ * insert the decimal point via string manipulation, which avoids that throw and+ * is exact up to the final JS Number coercion — very large Decimal128 values can+ * still lose precision or overflow when converted to a Number.+ */+function decimalBigNumToNumber(v: any, scale: number): number {+ const words = toWordArray(v);+ // Only convert when at least one word exists — an empty word array is a+ // zero value (or a non-BigNum object that shouldn't be here).+ if (words.length === 0) return 0;+ let big = 0n;+ for (let i = words.length - 1; i >= 0; i--) {+ big = (big << 32n) | BigInt(words[i] >>> 0);+ }+ // Two's complement sign (128-bit).+ if (words[words.length - 1] & 0x80000000) {+ big -= 1n << BigInt(32 * words.length);+ }+ const negative = big < 0n;+ if (negative) big = -big;+ let s = big.toString();+ if (scale > 0) {+ if (s.length <= scale) s = s.padStart(scale + 1, '0');+ s = `${s.slice(0, s.length - scale)}.${s.slice(s.length - scale)}`;+ }+ return Number(`${negative ? '-' : ''}${s}`);+}++/**+ * Convert an Arrow Table to an array of plain JS objects.+ *+ * Decimal columns are resolved to numbers using each column's declared scale.+ * `row.toJSON()` passes Decimal values through as opaque BigNum objects+ * ({0: low, 1: high, ...}), which kepler.gl then stores as `object`-typed+ * fields and downstream commands (e.g. `data.merge-tables`) choke on when they+ * try to re-materialize the dataset into DuckDB. The schema carries the scale,+ * so we resolve the value here.+ */+export function arrowTableToObjects(table: {+ toArray: () => any[];+ schema?: {fields: {name: string; type?: {typeId?: number; scale?: number}}[]};+}): Record<string, unknown>[] {+ const scaleByColumn = new Map<string, number>();+ for (const field of table.schema?.fields ?? []) {+ if (field.type?.typeId === Type.Decimal && typeof field.type.scale === 'number') {+ scaleByColumn.set(field.name, field.type.scale);+ }+ }+ return table.toArray().map((row: any) => {+ const json = row.toJSON();+ for (const [name, scale] of scaleByColumn) {+ const v = json[name];+ // The column is Decimal-typed, so object values are BigNums. (The old+ // `typeof v.valueOf === 'function'` guard was always true for objects —+ // every object inherits valueOf — and did not distinguish BigNums.)+ if (v && typeof v === 'object') {+ json[name] = decimalBigNumToNumber(v, scale);+ }+ }+ for (const key in json) {+ const val = json[key];+ if (val && typeof val === 'object' && typeof val.toJSON === 'function') {+ json[key] = convertArrowRowToObject(val);+ } else if (typeof val === 'bigint') {+ json[key] = val.toString();+ }+ }+ return json;+ });+}++/**+ * Read a column's values from a kepler dataset (by dataset label + field name).+ * Vectors through the vector-tile layer when the dataset is a vector-tile+ * dataset (whose values live in the layer's tile set, not the kepler table).+ *+ * Moved in from kepler-assistant's `src/glue/utils.ts` so this package is+ * self-contained — the map.* commands that call this seam (via `KeplerContext`)+ * cannot import from kepler-assistant (that would be circular).+ */+export function getValuesFromDataset(+ datasets: Datasets,+ layers: Layer[],+ datasetName: string,+ variableName: string+): unknown[] {+ // Commands advertise accepting a dataset "name (label) or id", so match by+ // either — a caller using the dataset id must not fail here.+ const datasetId = Object.keys(datasets).find(+ dataId => dataId === datasetName || datasets[dataId].label === datasetName+ );+ if (!datasetId) {+ throw new Error(`Dataset ${datasetName} not found`);+ }+ const dataset = datasets[datasetId];+ if (dataset) {+ const field = dataset.fields.find(f => f.name === variableName);+ if (!field) {+ throw new Error(`Field ${variableName} not found in dataset ${datasetName}`);+ }+ if (dataset.type === 'vector-tile') {+ // Reuse the field resolved above — no need to re-find it by name.+ return getValuesFromVectorTileLayer(datasetId, layers, field);+ }+ return Array.from({length: dataset.length}, (_, i) => dataset.getValue(variableName, i));+ }+ return [];+}++export function isVectorTileLayer(layer: Layer): layer is VectorTileLayer {+ return layer.type === LAYER_TYPES.vectorTile;+}++export function getValuesFromVectorTileLayer(datasetId: string, layers: Layer[], field: Field) {+ const layerIndex = layers.findIndex(layer => layer.config.dataId === datasetId);+ if (layerIndex === -1) return [];+ const layer = layers[layerIndex];+ if (!isVectorTileLayer(layer)) return [];+ const accessor = layer.accessRowValue(field);+ const values: unknown[] = [];+ // Iterate the layer's tiles through the public `TileDataset.getTiles()` seam+ // (the same tile->features unwrap the layer itself uses in renderLayer) —+ // not the private `tileSet` field, which is an implementation detail that+ // can change with internal refactors. `tileDataset` is protected, so it+ // needs a cast, but `getTiles()` is a stable public method.+ const tiles = (layer as any).tileDataset?.getTiles?.() ?? [];+ for (const tile of tiles) {+ const content = (tile as any)?.content;+ const features = content?.shape === 'geojson-table' ? content.features : content;+ if (!Array.isArray(features)) continue;+ for (const row of features) {+ const value = accessor(field, row);+ // Nulls mean "skip this row" (as in kepler's own TileDataset iteration),+ // not "end of data" — breaking here would truncate the values array.+ if (value === null) continue;+ values.push(value);+ }+ }+ return values;+}++/**+ * Whether a column holds any non-null object value — e.g. the `_geojson` column,+ * which stores whole GeoJSON Feature objects. Such columns must NOT be handed to+ * `tableFromArrays` raw: Arrow infers ONE type per column from the first value,+ * and a dataset mixing Polygon (depth-3 `coordinates`) and MultiPolygon (depth-4)+ * features gets the shallower type, so the MultiPolygon coordinates come back as+ * `null` and the geometry disappears. Serialize them to JSON strings for the+ * DuckDB round-trip and restore with `restoreObjectColumns`.+ */+export function isObjectColumn(values: unknown[]): boolean {+ return values.some(v => v !== null && v !== undefined && typeof v === 'object');+}++/**+ * Serialize object values to JSON strings (nulls/primitives pass through+ * unchanged) so `tableFromArrays` never has to infer a nested-struct type.+ */+export function stringifyObjectColumn(values: unknown[]): unknown[] {+ if (!isObjectColumn(values)) return values;+ return values.map(v => {+ if (v === null || v === undefined) return null;+ return typeof v === 'object' ? JSON.stringify(v) : v;+ });+}++/**+ * Restore object-valued columns that `stringifyObjectColumn` serialized back to+ * their object form, in place. Used after a DuckDB query returns those columns+ * as JSON strings (e.g. `_geojson` after `SELECT *`).+ */+export function restoreObjectColumns(rows: Record<string, unknown>[], columnNames: string[]): void {+ if (columnNames.length === 0) return;+ for (const row of rows) {+ for (const name of columnNames) {+ const value = row[name];+ if (typeof value === 'string') {+ try {+ const parsed = JSON.parse(value);+ // Only restore object/array values. A column may mix objects with+ // primitives (e.g. a string "1" alongside real objects), and+ // JSON-parsing those would coerce "1" → 1 / "true" → true, silently+ // changing their types. Leave primitives as the original string.+ if (parsed !== null && typeof parsed === 'object') {+ row[name] = parsed;+ }+ } catch {+ // Not JSON — leave the string as-is.+ }+ }+ }+ }+}++/**+ * Build an `updateDataset` payload that appends ONE new column to an existing+ * kepler dataset, keeping every existing column byte-for-byte identical.+ *+ * Existing columns are read straight from the kepler dataset (via+ * `getValuesFromDataset`) and NEVER round-tripped through Arrow/DuckDB. That+ * matters for `_geojson`: `tableFromArrays` infers a single Arrow type for the+ * whole column, and a dataset mixing Polygon and MultiPolygon features gets the+ * shallower type — the MultiPolygon's deeper coordinate nesting comes back as+ * nulls and the geometry disappears. Only the NEW column's values come from the+ * computation (DuckDB expression / copy, or geoda write-back).+ *+ * @param datasets kepler datasets (visState.datasets)+ * @param layers kepler layers (visState.layers) — needed for vector-tile datasets+ * @param datasetName the dataset label+ * @param newColumnName name of the column being appended+ * @param newColumnArrow single-column arrow table holding the new column's values+ * @returns an `updateDataset` `data` payload: `{rows, fields}`+ */+export function buildAddColumnPayload(+ datasets: Datasets,+ layers: Layer[],+ datasetName: string,+ newColumnName: string,+ newColumnArrow: any+): {rows: unknown[][]; fields: any[]} {+ // Match by id or label, consistent with getValuesFromDataset and the+ // commands' "name (label) or id" contract.+ const datasetId = Object.keys(datasets).find(+ id => id === datasetName || datasets[id].label === datasetName+ );+ if (!datasetId) {+ throw new Error(`Dataset "${datasetName}" not found.`);+ }+ const dataset = datasets[datasetId];+ const originalFields = dataset.fields;++ // The new column's values + field descriptor come from the computation's+ // arrow result (DuckDB expression / copy, or geoda write-back).+ const newColumnValues = arrowTableToObjects(newColumnArrow).map(o => o[newColumnName]);+ if (newColumnValues.length !== dataset.length) {+ throw new Error(+ `Computed column "${newColumnName}" produced ${newColumnValues.length} rows, but dataset ` ++ `"${datasetName}" has ${dataset.length} rows. The expression must produce exactly one ` ++ `value per row — check for filters, joins, or a non-1:1 query.`+ );+ }+ const newField = arrowSchemaToFields(newColumnArrow)[0];++ // Existing columns come from the original kepler dataset, never Arrow/DuckDB.+ const columns = originalFields.map(f => ({+ name: f.name,+ values: getValuesFromDataset(datasets, layers, datasetName, f.name)+ }));++ // RowDataContainer format: one array per row, indexed by field position.+ const rows = Array.from({length: dataset.length}, (_, i) => [+ ...columns.map(c => c.values[i]),+ newColumnValues[i]+ ]);++ const fields = [...originalFields, newField];+ return {rows, fields};+}++/**+ * Default number of first rows to format and return to the LLM as a preview.+ * Mirrors spatial-agent's NUMBER_OF_ROWS_RETURN_TO_LLM.+ */+export const NUMBER_OF_ROWS_RETURN_TO_LLM = 5;++/**+ * Default total character budget for the LLM-facing preview. Capped at ~1000+ * chars so the preview stays small in context, matching spatial-agent's+ * formatResultsForLLM default.+ */+export const LLM_PREVIEW_MAX_TOTAL_LENGTH = 1000;+export const LLM_PREVIEW_MAX_VALUE_LENGTH = 80;++/**+ * Format a query result table as a pipe-delimited string suitable for LLM+ * consumption. Truncates individual cell values and total output to stay within+ * a token budget. Shared by the stock @sqlrooms/ai query tool wrapper and the+ * skill executeApi data.query path.+ */+export function tableToLLMResult(+ table: Record<string, unknown>[],+ maxTotalLength: number = LLM_PREVIEW_MAX_TOTAL_LENGTH,+ maxValueLength: number = LLM_PREVIEW_MAX_VALUE_LENGTH+): string {+ if (table.length === 0) return 'No rows returned';++ const truncateValue = (value: unknown): string => {+ if (value === null || value === undefined) return '';+ let str: string;+ if (typeof value === 'bigint') {+ str = value.toString();+ } else if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {+ const byteLen =+ value instanceof ArrayBuffer ? value.byteLength : (value as ArrayBufferView).byteLength;+ str = `<${byteLen} bytes>`;+ } else if (Array.isArray(value)) {+ // Format each element through truncateValue so object elements render+ // as JSON (not "[object Object]") and bigints/typed values stay+ // consistent with the scalar branches — String(v) would lose that+ // structure and bypass the bigint-safe stringify.+ str = value.map(v => truncateValue(v)).join(', ');+ } else if (typeof value === 'object') {+ try {+ str = JSON.stringify(value, (_k, v) => (typeof v === 'bigint' ? v.toString() : v));+ } catch {+ str = String(value);+ }+ } else {+ str = String(value);+ }+ return str.length > maxValueLength ? `${str.slice(0, maxValueLength)}...` : str;+ };++ const columns = Object.keys(table[0] || {});+ const headerRow = `| ${columns.join(' | ')} |`;+ const separatorRow = `| ${columns.map(() => '---').join(' | ')} |`;+ const lines = [headerRow, separatorRow];+ // Track the joined length incrementally instead of re-joining the whole+ // array on every row (O(n²) in the number of preview rows).+ let currentLength = headerRow.length + separatorRow.length + 1; // +1 for the '\n' between them++ for (const row of table) {+ const values = columns.map(col => truncateValue(row[col]));+ const line = `| ${values.join(' | ')} |`;+ lines.push(line);+ currentLength += line.length + 1; // +1 for the '\n' separator++ if (currentLength > maxTotalLength - 100) {+ lines.push('...');+ break;+ }+ }++ let result = lines.join('\n');+ if (result.length > maxTotalLength) {+ result = `${result.slice(0, maxTotalLength)}\n...`;+ }+ return result;+}++/**+ * Format the first N rows of an Arrow result as a pipe-delimited string for the+ * LLM, capped at maxTotalLength chars. Convenience wrapper combining+ * arrowTableToObjects + tableToLLMResult: slices the first `numberOfRows`+ * rows, normalizes Decimal columns via arrowTableToObjects (applying each+ * column's declared scale so previews don't leak opaque BigNum word objects),+ * then renders the pipe table.+ */+export function formatResultsForLLM(+ result: {+ toArray: () => any[];+ schema?: {fields: {name: string; type?: {typeId?: number; scale?: number}}[]};+ },+ numberOfRows: number = NUMBER_OF_ROWS_RETURN_TO_LLM,+ options?: {maxTotalLength?: number; maxValueLength?: number}+): string {+ const rows = arrowTableToObjects({+ toArray: () => result.toArray().slice(0, numberOfRows),+ schema: result.schema+ });+ return tableToLLMResult(+ rows,+ options?.maxTotalLength ?? LLM_PREVIEW_MAX_TOTAL_LENGTH,+ options?.maxValueLength ?? LLM_PREVIEW_MAX_VALUE_LENGTH+ );+}diff --git a/src/mcp/src/commands/view-mode-command.spec.ts b/src/mcp/src/commands/view-mode-command.spec.tsnew file mode 100644index 000000000..bbfe26510--- /dev/null+++ b/src/mcp/src/commands/view-mode-command.spec.ts@@ -0,0 +1,62 @@+import {getViewModeCommand} from './view-mode-command';+import {ActionTypes} from '@kepler.gl/actions';++/** Mock context: the command only dispatches setMapViewMode. */+function makeCtx() {+ const dispatched: any[] = [];+ const ctx = {+ getVisState: () => ({datasets: {}, layers: [], filters: []}),+ dispatch: (action: any) => {+ dispatched.push(action);+ },+ getValuesFromDataset: () => [],+ getMapBoundary: () => null,+ getMapboxToken: () => undefined,+ getDatasetContext: () => ''+ };+ return {ctx, getDispatched: () => dispatched};+}++type CommandResult = {success: boolean; error?: string; data?: Record<string, unknown>};++describe('map.set-view-mode', () => {+ it('switches to the 3D globe', async () => {+ const {ctx, getDispatched} = makeCtx();+ const cmd = getViewModeCommand(ctx as any);+ const result = (await cmd.execute({} as any, {mode: 'globe'})) as CommandResult;++ expect(result.success).toBe(true);+ const actions = getDispatched().filter((a: any) => a.type === ActionTypes.SET_MAP_VIEW_MODE);+ expect(actions).toHaveLength(1);+ expect(actions[0].payload.mapViewMode).toBe('MODE_GLOBE');+ expect(result.data?.details).toMatch(/3D globe/);+ });++ it('switches back to the flat 2D map', async () => {+ const {ctx, getDispatched} = makeCtx();+ const cmd = getViewModeCommand(ctx as any);+ const result = (await cmd.execute({} as any, {mode: '2d'})) as CommandResult;++ expect(result.success).toBe(true);+ expect(getDispatched()[0].payload.mapViewMode).toBe('MODE_2D');+ });++ it('accepts the enum value as well as the short name', async () => {+ const {ctx, getDispatched} = makeCtx();+ const cmd = getViewModeCommand(ctx as any);+ const result = (await cmd.execute({} as any, {mode: 'MODE_3D'})) as CommandResult;++ expect(result.success).toBe(true);+ expect(getDispatched()[0].payload.mapViewMode).toBe('MODE_3D');+ });++ it('rejects an unknown mode without dispatching', async () => {+ const {ctx, getDispatched} = makeCtx();+ const cmd = getViewModeCommand(ctx as any);+ const result = (await cmd.execute({} as any, {mode: 'space'})) as CommandResult;++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/Invalid view mode/);+ expect(getDispatched()).toEqual([]);+ });+});diff --git a/src/mcp/src/commands/view-mode-command.ts b/src/mcp/src/commands/view-mode-command.tsnew file mode 100644index 000000000..c6f5fa37e--- /dev/null+++ b/src/mcp/src/commands/view-mode-command.ts@@ -0,0 +1,70 @@+import type {RoomCommand} from './types';+import {z} from 'zod';+import {MapViewMode} from '@kepler.gl/constants';+import {setMapViewMode} from '@kepler.gl/actions';+import type {KeplerContext} from './types';++export const viewModeCommandId = 'map.set-view-mode' as const;++/** Agent-facing names for the three camera modes. */+const VIEW_MODE_BY_INPUT: Record<string, MapViewMode> = {+ '2d': MapViewMode.MODE_2D,+ '3d': MapViewMode.MODE_3D,+ globe: MapViewMode.MODE_GLOBE+};++/**+ * Accept the short names (`2d`, `3d`, `globe`) as well as the enum values+ * (`MODE_2D`, …) — the bridge and WebMCP callers reach execute without zod+ * parsing, so the runtime guard must understand both.+ */+function resolveViewMode(input: unknown): MapViewMode | null {+ if (typeof input !== 'string') return null;+ const short = input.toLowerCase();+ if (VIEW_MODE_BY_INPUT[short]) return VIEW_MODE_BY_INPUT[short];+ return (Object.values(MapViewMode) as string[]).includes(input) ? (input as MapViewMode) : null;+}++export function getViewModeCommand(ctx: KeplerContext): RoomCommand {+ return {+ id: viewModeCommandId,+ name: 'Set map view mode',+ group: 'Map',+ description: `Switch the map between the flat 2D map, the tilted 3D map and the 3D globe.+- '2d': flat map, no tilt.+- '3d': flat map tilted (pitch 50), for extruded/3D layers.+- 'globe': the 3D globe — use it when the data spans the world and the user is looking at global patterns.+Globe support: point, arc, line, trip, cluster, hexagon, grid, geojson and vector-tile layers render on the globe. The 'flow' and 'flowField' layers are NOT supported there yet (flow arrows collapse edge-on; flow field clipping is mercator-only), so keep those on the 2d/3d map.`,+ metadata: {readOnly: false, riskLevel: 'low', idempotent: true},+ inputSchema: z.object({+ mode: z.enum(['2d', '3d', 'globe'])+ }) as any,+ execute: async (_execCtx, input) => {+ const {mode} = (input ?? {}) as {mode: unknown};+ const viewMode = resolveViewMode(mode);+ if (!viewMode) {+ return {+ success: false,+ commandId: viewModeCommandId,+ error: `Invalid view mode: ${String(mode)}. Use "2d", "3d" or "globe".`,+ data: {+ instruction: 'Call map.set-view-mode with mode "2d", "3d" or "globe".'+ }+ };+ }++ ctx.dispatch(setMapViewMode(viewMode));+ const label =+ viewMode === MapViewMode.MODE_GLOBE+ ? '3D globe'+ : viewMode === MapViewMode.MODE_3D+ ? '3D tilted map'+ : '2D flat map';+ return {+ success: true,+ commandId: viewModeCommandId,+ data: {details: `Map view switched to ${label}.`}+ };+ }+ };+}diff --git a/src/mcp/src/index.ts b/src/mcp/src/index.tsnew file mode 100644index 000000000..8d21acb10--- /dev/null+++ b/src/mcp/src/index.ts@@ -0,0 +1,16 @@+/**+ * @kepler.gl/mcp — the kepler.gl map surface.+ *+ * Only the map contract + the map.* commands live here, plus dependency-light+ * helper utilities (e.g. `commands/utils.ts`) that hosts are meant to reuse.+ * No analysis and no app-specific wiring glue — those belong to+ * kepler-assistant, which imports this package for the commands and implements+ * the `KeplerContext` glue seam.+ *+ * This root entry stays browser-safe. The stdio MCP server (which needs `ws`+ * and Node APIs) lives in the `./server` subpath and is never imported here.+ */++export * from './map-contract';+export * from './types';+export * from './commands';diff --git a/src/mcp/src/map-contract.ts b/src/mcp/src/map-contract.tsnew file mode 100644index 000000000..5961c1022--- /dev/null+++ b/src/mcp/src/map-contract.ts@@ -0,0 +1,29 @@+/**+ * The kepler.gl map tool contract — the "map surface".+ *+ * kepler.gl's contract is "accept data, actuate the map, introspect, render."+ * The surface is map-focused: no spatial analysis and no charts — those belong+ * to the analysis service (kepler-assistant). A few table ops (map.create-table,+ * map.add-column, map.save-data) are DuckDB-backed and mutate the map's datasets+ * in place; they are part of the surface because they change what the map shows.+ *+ * This module is intentionally dependency-light. It defines the map.* tool ids+ * and a `MapContract` interface so any host (the demo-app browser page, the+ * kepler-assistant library, or a future MCP server) can implement or consume+ * the same contract.+ */++import type {MapToolId, ToolResult} from './types';++/**+ * The map tool surface. Mostly pure map actuation (set-basemap, add-layer, ...);+ * a few table ops (map.create-table, map.add-column, map.save-data) are included+ * because they mutate the map's datasets in place.+ */+export interface MapContract {+ readonly toolIds: readonly MapToolId[];+ /** List the tools this surface exposes (id + input JSON Schema, if known). */+ listTools(): Array<{id: MapToolId; inputSchema?: unknown; description?: string}>;+ /** Execute a map tool. Returns a trimmed, model-facing result. */+ callTool(id: MapToolId, input: Record<string, unknown>): Promise<ToolResult>;+}diff --git a/src/mcp/src/server/bridge-server.spec.ts b/src/mcp/src/server/bridge-server.spec.tsnew file mode 100644index 000000000..16dcf44e8--- /dev/null+++ b/src/mcp/src/server/bridge-server.spec.ts@@ -0,0 +1,140 @@+/**+ * @jest-environment node+ *+ * jsdom makes jest resolve `ws` through its `browser` condition, which is a+ * throwing shim with no WebSocketServer; this suite needs the Node build.+ */+import WebSocket from 'ws';+import {KeplerMcpBridge, toToolName} from './bridge-server';+import type {KeplerMcpBridgeStart} from './bridge-server';++async function waitFor(condition: () => boolean, timeoutMs = 3000): Promise<void> {+ const startedAt = Date.now();+ while (!condition()) {+ if (Date.now() - startedAt > timeoutMs) throw new Error('waitFor timed out');+ await new Promise(resolve => setTimeout(resolve, 10));+ }+}++function connect(port: number, token: string): WebSocket {+ return new WebSocket(`ws://127.0.0.1:${port}/ws?token=${token}`);+}++function nextMessage(socket: WebSocket): Promise<any> {+ return new Promise(resolve => socket.once('message', data => resolve(JSON.parse(String(data)))));+}++describe('kepler-mcp bridge server', () => {+ let bridge: KeplerMcpBridge;+ let started: KeplerMcpBridgeStart;++ beforeEach(async () => {+ bridge = new KeplerMcpBridge({port: 0, callTimeoutMs: 1000});+ started = await bridge.start();+ });++ afterEach(async () => {+ await bridge.close();+ });++ it('advertises the map tools before any page connects', () => {+ const names = bridge.getTools().map(tool => tool.name);+ // MCP tool names fold the dot: map.add-layer → map_add_layer+ expect(names).toContain(toToolName('map.add-layer'));+ expect(names).toContain(toToolName('map.set-basemap'));+ expect(names.length).toBeGreaterThan(8);+ });++ it('builds the page URL with the token', () => {+ expect(started.pageUrl).toBe(`http://localhost:8080?mcp=${started.token}`);+ });++ it('redirects a browser on / to the map page with the token', async () => {+ const response = await fetch(`http://127.0.0.1:${started.port}/`, {redirect: 'manual'});+ expect(response.status).toBe(302);+ expect(response.headers.get('location')).toBe(started.pageUrl);+ });++ it('exposes the full add-layer schema, including flowField', () => {+ const addLayer = bridge.getTools().find(tool => tool.name === toToolName('map.add-layer'));+ expect(JSON.stringify(addLayer?.inputSchema)).toContain('flowField');+ });++ it('rejects a connection with the wrong token', async () => {+ const socket = connect(started.port, 'not-the-token');+ const code = await new Promise<number>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error('timed out waiting for close')), 3000);+ socket.on('close', closeCode => {+ clearTimeout(timer);+ resolve(closeCode);+ });+ socket.on('error', error => {+ clearTimeout(timer);+ reject(error);+ });+ });+ expect(code).toBe(1008);+ expect(bridge.connected).toBe(false);+ });++ it('explains a call made before a page connects', async () => {+ await expect(bridge.callTool(toToolName('map.add-layer'), {})).rejects.toThrow(+ /No kepler.gl map page is connected/+ );+ });++ it('forwards a call to the page and resolves with its result', async () => {+ const socket = connect(started.port, started.token);+ await new Promise(resolve => socket.on('open', resolve));++ // The page's own catalog replaces the static one on hello.+ socket.send(+ JSON.stringify({+ type: 'hello',+ commands: [+ {+ id: 'map.add-layer',+ name: 'Add map layer',+ description: 'Add a layer',+ inputSchema: {type: 'object'}+ }+ ]+ })+ );+ await waitFor(() => bridge.getTools().length === 1);+ expect(bridge.getTools()[0]).toMatchObject({+ name: toToolName('map.add-layer'),+ commandId: 'map.add-layer'+ });++ const pending = bridge.callTool(toToolName('map.add-layer'), {+ datasetName: 'shops',+ layerType: 'point'+ });+ const message = await nextMessage(socket);+ expect(message).toMatchObject({type: 'call', tool: 'map.add-layer'});+ expect(message.input).toEqual({datasetName: 'shops', layerType: 'point'});++ socket.send(+ JSON.stringify({+ type: 'result',+ callId: message.callId,+ result: {success: true, commandId: 'map.add-layer', data: {details: 'added'}}+ })+ );+ await expect(pending).resolves.toMatchObject({success: true});+ socket.close();+ });++ it('rejects pending calls when the page disconnects', async () => {+ const socket = connect(started.port, started.token);+ await new Promise(resolve => socket.on('open', resolve));+ await waitFor(() => bridge.connected);++ const pending = bridge.callTool(toToolName('map.set-basemap'), {styleType: 'dark-matter'});+ await nextMessage(socket);+ socket.close();++ await expect(pending).rejects.toThrow(/disconnected/);+ });+});diff --git a/src/mcp/src/server/bridge-server.ts b/src/mcp/src/server/bridge-server.tsnew file mode 100644index 000000000..f11009f6f--- /dev/null+++ b/src/mcp/src/server/bridge-server.ts@@ -0,0 +1,293 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++/**+ * The bridge between an MCP client and a kepler.gl page.+ *+ * Browsers cannot listen on a port, so the page is a WebSocket CLIENT that+ * connects OUT to `ws://127.0.0.1:<port>/ws?token=...` (the reverse-connect+ * pattern). This server holds that socket, advertises the `map.*` tools to the+ * MCP client, and forwards each call to the page, where the command registry+ * executes against the live map.+ *+ * The tool list comes from the package itself (`getKeplerCommands`), so tools+ * exist before a page connects; a call without a page returns a clear error.+ * Once a page says `hello` its own catalog replaces the static one, because a+ * page may not serve every command (the demo app omits the DuckDB-backed ones).+ */++import {randomUUID} from 'node:crypto';+import {createServer} from 'node:http';+import type {Server as HttpServer} from 'node:http';+import {WebSocket, WebSocketServer} from 'ws';+import {z} from 'zod';+import {getKeplerCommands} from '../commands';+import type {KeplerContext, RoomCommandResult, ToolDescriptor} from '../commands/types';++const DEFAULT_PORT = 8765;+const DEFAULT_HOST = '127.0.0.1';+const DEFAULT_CALL_TIMEOUT_MS = 60_000;++export type MapTool = {+ /** MCP tool name, e.g. `map_add_layer` (dots are not allowed in tool names). */+ name: string;+ /** The `map.*` command id the call is forwarded to. */+ commandId: string;+ description: string;+ inputSchema: Record<string, unknown>;+};++export type KeplerMcpBridgeOptions = {+ port?: number;+ host?: string;+ /** Base URL of the map page, printed with the token. */+ mapUrl?: string;+ callTimeoutMs?: number;+};++export type KeplerMcpBridgeStart = {+ host: string;+ port: number;+ token: string;+ /** What a human should open: `<mapUrl>?mcp=<token>`. */+ pageUrl: string;+};++type PendingCall = {+ resolve: (result: RoomCommandResult) => void;+ reject: (error: Error) => void;+ timer: ReturnType<typeof setTimeout>;+};++/** MCP tool names are commonly restricted to [A-Za-z0-9_-]; `map.add-layer` → `map_add_layer`. */+export function toToolName(commandId: string): string {+ return commandId.replace(/\./g, '_');+}++function toInputSchema(command: {inputSchema?: unknown}): Record<string, unknown> {+ if (command.inputSchema) {+ try {+ const schema = z.toJSONSchema(command.inputSchema as z.ZodType);+ if (schema) return schema as Record<string, unknown>;+ } catch {+ // Not every command ships a zod schema; fall back to a free-form object.+ }+ }+ return {type: 'object'};+}++/** The map surface as declared by this package, independent of any page. */+export function getMapTools(): MapTool[] {+ const commands = getKeplerCommands({} as KeplerContext);+ return Object.values(commands).map(command => ({+ name: toToolName(command.id),+ commandId: command.id,+ description: command.description || command.name,+ inputSchema: toInputSchema(command)+ }));+}++function toolsFromDescriptors(descriptors: ToolDescriptor[]): MapTool[] {+ return descriptors+ .filter(descriptor => descriptor && descriptor.id)+ .map(descriptor => ({+ name: toToolName(descriptor.id),+ commandId: descriptor.id,+ description: descriptor.description || descriptor.name || descriptor.id,+ inputSchema: (descriptor.inputSchema as Record<string, unknown>) || {type: 'object'}+ }));+}++/** RoomCommandResult → the text an MCP client shows for a tool call. */+export function formatResult(result: RoomCommandResult): {text: string; isError: boolean} {+ if (result && typeof result === 'object' && result.success === false) {+ return {text: `✗ ${result.commandId}: ${result.error ?? 'failed'}`, isError: true};+ }+ if (result && typeof result === 'object' && result.error) {+ return {text: `✗ ${result.commandId}: ${result.error}`, isError: true};+ }+ const data = result?.data as {details?: string} | undefined;+ if (data && typeof data.details === 'string') return {text: data.details, isError: false};+ return {text: JSON.stringify(result?.data ?? result ?? null, null, 2), isError: false};+}++export class KeplerMcpBridge {+ private readonly options: Required<KeplerMcpBridgeOptions>;+ private readonly staticTools: MapTool[];+ private pageTools: MapTool[] | null = null;+ private socket: WebSocket | null = null;+ private wss: WebSocketServer | null = null;+ private httpServer: HttpServer | null = null;+ private readonly pending = new Map<string, PendingCall>();+ private token = '';+ private pageUrl = '';++ constructor(options: KeplerMcpBridgeOptions = {}) {+ this.options = {+ port: options.port ?? DEFAULT_PORT,+ host: options.host ?? DEFAULT_HOST,+ mapUrl: options.mapUrl ?? 'http://localhost:8080',+ callTimeoutMs: options.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS+ };+ this.staticTools = getMapTools();+ }++ /** Tools the MCP client can call right now. */+ getTools(): MapTool[] {+ return this.pageTools ?? this.staticTools;+ }++ get connected(): boolean {+ return this.socket?.readyState === WebSocket.OPEN;+ }++ async start(): Promise<KeplerMcpBridgeStart> {+ if (this.wss) throw new Error('The kepler.gl bridge is already running.');++ this.token = randomUUID().replace(/-/g, '');++ // A plain HTTP GET on `/` redirects to the map page carrying the token, so+ // the user can open `http://127.0.0.1:<port>/` even when the MCP client+ // never shows the server's stderr. Only `/ws` upgrades to a WebSocket.+ const httpServer = createServer((request, response) => {+ if (request.url === '/' || request.url?.startsWith('/?')) {+ response.writeHead(302, {Location: this.pageUrl});+ response.end();+ return;+ }+ response.writeHead(404, {'content-type': 'text/plain'});+ response.end('kepler-mcp: the map page connects at /ws');+ });+ this.httpServer = httpServer;++ const wss = new WebSocketServer({server: httpServer, path: '/ws'});+ this.wss = wss;+ wss.on('connection', (socket, request) => this.handleConnection(socket, request.url));++ await new Promise<void>((resolve, reject) => {+ httpServer.once('error', reject);+ httpServer.listen(this.options.port, this.options.host, () => resolve());+ });++ const address = httpServer.address();+ const port = typeof address === 'object' && address ? address.port : this.options.port;+ const mapUrl = this.options.mapUrl.replace(/\/$/, '');+ this.pageUrl = `${mapUrl}${mapUrl.includes('?') ? '&' : '?'}mcp=${encodeURIComponent(+ this.token+ )}`;+ return {host: this.options.host, port, token: this.token, pageUrl: this.pageUrl};+ }++ async callTool(name: string, input: Record<string, unknown> = {}): Promise<RoomCommandResult> {+ const tool =+ this.getTools().find(candidate => candidate.name === name) ??+ this.staticTools.find(candidate => candidate.name === name);+ if (!tool) {+ throw new Error(+ `Unknown map tool "${name}". Available: ${this.getTools()+ .map(candidate => candidate.name)+ .join(', ')}.`+ );+ }+ const socket = this.socket;+ if (!socket || socket.readyState !== WebSocket.OPEN) {+ throw new Error(+ 'No kepler.gl map page is connected. Open the page URL printed at startup ' ++ '(it carries ?mcp=<token>), then call the tool again.'+ );+ }++ const callId = randomUUID();+ const reply = new Promise<RoomCommandResult>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pending.delete(callId);+ reject(+ new Error(`Timed out after ${this.options.callTimeoutMs} ms waiting for the map page.`)+ );+ }, this.options.callTimeoutMs);+ this.pending.set(callId, {resolve, reject, timer});+ });++ socket.send(JSON.stringify({type: 'call', callId, tool: tool.commandId, input}));+ return reply;+ }++ async close(): Promise<void> {+ this.rejectPending('The bridge was closed.');+ this.pageTools = null;+ this.socket?.close(1000, 'bridge closed');+ this.socket = null;+ const wss = this.wss;+ const httpServer = this.httpServer;+ this.wss = null;+ this.httpServer = null;+ if (!wss) return;+ // close() only stops listening and waits for clients; terminate them so+ // shutdown (and tests) do not hang on a page that never closes its socket.+ for (const client of wss.clients) client.terminate();+ await new Promise<void>(resolve => wss.close(() => resolve()));+ if (httpServer) {+ await new Promise<void>(resolve => httpServer.close(() => resolve()));+ }+ }++ private handleConnection(socket: WebSocket, requestUrl: string | undefined): void {+ let token: string | null = null;+ try {+ token = new URL(requestUrl ?? '/ws', 'http://127.0.0.1').searchParams.get('token');+ } catch {+ token = null;+ }+ // The token is the only thing keeping other local pages/processes from+ // driving the map; reject a mismatch before accepting any message.+ if (token !== this.token) {+ socket.close(1008, 'invalid token');+ return;+ }++ // One map page at a time: a second tab takes over so calls never race+ // between two live maps.+ this.socket?.close(1000, 'replaced by a newer connection');+ this.socket = socket;+ this.pageTools = null;++ socket.on('message', data => this.handleMessage(data));+ socket.on('close', () => {+ if (this.socket === socket) {+ this.socket = null;+ this.pageTools = null;+ this.rejectPending('The kepler.gl page disconnected.');+ }+ });+ // Errors are followed by close; the close handler resets state.+ socket.on('error', () => undefined);+ }++ private handleMessage(raw: unknown): void {+ let message: any;+ try {+ message = JSON.parse(String(raw));+ } catch {+ return;+ }+ if (message?.type === 'hello' && Array.isArray(message.commands)) {+ this.pageTools = toolsFromDescriptors(message.commands as ToolDescriptor[]);+ return;+ }+ if (message?.type === 'result' && typeof message.callId === 'string') {+ const pendingCall = this.pending.get(message.callId);+ if (!pendingCall) return;+ clearTimeout(pendingCall.timer);+ this.pending.delete(message.callId);+ pendingCall.resolve(message.result as RoomCommandResult);+ }+ }++ private rejectPending(reason: string): void {+ for (const [callId, pendingCall] of this.pending) {+ clearTimeout(pendingCall.timer);+ this.pending.delete(callId);+ pendingCall.reject(new Error(reason));+ }+ }+}diff --git a/src/mcp/src/server/index.ts b/src/mcp/src/server/index.tsnew file mode 100644index 000000000..00169b54c--- /dev/null+++ b/src/mcp/src/server/index.ts@@ -0,0 +1,13 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++/**+ * Server-side entry point of `@kepler.gl/mcp`.+ *+ * Browser bundles must not import this module: it pulls in `ws` and Node APIs.+ * The map contracts and commands stay in the package root; this subpath is for+ * the stdio MCP server (`kepler-mcp`) and for tests.+ */++export {KeplerMcpBridge, formatResult, getMapTools, toToolName} from './bridge-server';+export type {KeplerMcpBridgeOptions, KeplerMcpBridgeStart, MapTool} from './bridge-server';diff --git a/src/mcp/src/server/stdio.ts b/src/mcp/src/server/stdio.tsnew file mode 100644index 000000000..700429417--- /dev/null+++ b/src/mcp/src/server/stdio.ts@@ -0,0 +1,138 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++/**+ * `kepler-mcp` — a stdio MCP server for the kepler.gl map surface.+ *+ * The agent starts this process (it speaks MCP on stdin/stdout); the process+ * also listens for the map page on a loopback WebSocket. It prints a URL that+ * carries the one-time token — open that URL and the page connects, after which+ * every map.* tool call executes against the live map.+ *+ * stdout belongs to the MCP protocol: every log line here goes to stderr.+ */++import {readFileSync} from 'node:fs';+import {dirname, join} from 'node:path';+import {Server} from '@modelcontextprotocol/sdk/server/index.js';+import {StdioServerTransport} from '@modelcontextprotocol/sdk/server/stdio.js';+import {CallToolRequestSchema, ListToolsRequestSchema} from '@modelcontextprotocol/sdk/types.js';+import {KeplerMcpBridge, formatResult} from './bridge-server';+import type {KeplerMcpBridgeOptions} from './bridge-server';++const DEFAULT_MAP_URL = 'http://localhost:8080';++function readVersion(): string {+ if (typeof __dirname === 'undefined') return '0.0.0';+ let directory = __dirname;+ // Walk up until the package manifest is found, so this works both from src/+ // (babel-node, tests) and from dist/cjs/server (the published bin).+ for (let depth = 0; depth < 5; depth++) {+ try {+ const manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'));+ if (manifest.name === '@kepler.gl/mcp') return manifest.version;+ } catch {+ // no manifest at this level — keep walking+ }+ directory = dirname(directory);+ }+ return '0.0.0';+}++function usage(): string {+ return [+ 'Usage: kepler-mcp [--port <n>] [--host <h>] [--map-url <url>]',+ '',+ 'Runs a stdio MCP server for the kepler.gl map surface and waits for a',+ 'kepler.gl page to connect over a loopback WebSocket.',+ '',+ ' --port <n> WebSocket port for the page (default 8765)',+ ' --host <h> loopback host to bind (default 127.0.0.1)',+ ` --map-url <url> page URL printed with the token (default ${DEFAULT_MAP_URL})`+ ].join('\n');+}++function parseArgs(argv: string[]): KeplerMcpBridgeOptions & {help?: boolean} {+ const options: KeplerMcpBridgeOptions & {help?: boolean} = {};+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--help' || arg === '-h') {+ options.help = true;+ } else if (arg === '--port') {+ const value = Number(argv[++i]);+ if (!Number.isInteger(value) || value < 0 || value > 65535) {+ throw new Error(`Invalid --port value: ${argv[i]}`);+ }+ options.port = value;+ } else if (arg === '--host') {+ options.host = argv[++i];+ } else if (arg === '--map-url') {+ options.mapUrl = argv[++i];+ } else {+ throw new Error(`Unknown argument: ${arg}`);+ }+ }+ return options;+}++async function main(): Promise<void> {+ const options = parseArgs(process.argv.slice(2));+ if (options.help) {+ console.error(usage());+ return;+ }++ const bridge = new KeplerMcpBridge(options);+ const started = await bridge.start();++ const server = new Server(+ {name: 'kepler-mcp', version: readVersion()},+ {capabilities: {tools: {}}}+ );++ server.setRequestHandler(ListToolsRequestSchema, async () => ({+ tools: bridge.getTools().map(tool => ({+ name: tool.name,+ description: tool.description,+ inputSchema: tool.inputSchema as {type: 'object'; [key: string]: unknown}+ }))+ }));++ server.setRequestHandler(CallToolRequestSchema, async request => {+ const {name, arguments: args} = request.params;+ try {+ const result = await bridge.callTool(name, (args ?? {}) as Record<string, unknown>);+ const {text, isError} = formatResult(result);+ return {content: [{type: 'text' as const, text}], ...(isError ? {isError: true} : {})};+ } catch (error) {+ return {+ content: [+ {type: 'text' as const, text: error instanceof Error ? error.message : String(error)}+ ],+ isError: true+ };+ }+ });++ const shutdown = async () => {+ await bridge.close();+ process.exit(0);+ };+ process.on('SIGINT', shutdown);+ process.on('SIGTERM', shutdown);++ await server.connect(new StdioServerTransport());++ console.error(`[kepler-mcp] bridge listening on ws://${started.host}:${started.port}/ws`);+ console.error(+ `[kepler-mcp] open http://${started.host}:${started.port}/ in a browser — it redirects ` ++ 'to the map page with the token — so the agent can drive the map'+ );+ console.error(`[kepler-mcp] or open ${started.pageUrl}`);+}++main().catch(error => {+ console.error(`[kepler-mcp] ${error instanceof Error ? error.message : String(error)}`);+ process.exit(1);+});diff --git a/src/mcp/src/types.ts b/src/mcp/src/types.tsnew file mode 100644index 000000000..93c6c0847--- /dev/null+++ b/src/mcp/src/types.ts@@ -0,0 +1,40 @@+/**+ * Shared contract types for the kepler.gl map surface.+ *+ * This module is the home of the reusable *map surface* contract — the map.*+ * tool namespace that any AI client can drive. It defines the map.* tool ids+ * and the `ToolResult` shape so any host (the demo-app browser page, the+ * kepler-assistant library, or a future MCP server) can implement or consume+ * the same contract.+ */++/** A command/tool execution result. */+export interface ToolResult {+ success: boolean;+ data?: unknown;+ error?: string;+}++/**+ * The v1 map tool surface. These are the command ids the kepler.gl demo-app's+ * assistant actually registers, reconciled with the kepler-mcp proposal. Most+ * commands are pure map actuation (set-basemap, add-layer, ...); the table ops+ * (map.create-table, map.add-column, map.save-data) are DuckDB-backed and are+ * included because they mutate the map's datasets in place.+ */+export const MAP_TOOL_IDS = [+ 'map.set-basemap',+ 'map.get-boundary',+ 'map.add-layer',+ 'map.update-layer-color',+ 'map.load-data',+ 'map.save-data',+ 'map.create-table',+ 'map.add-column',+ 'map.add-time-filter',+ 'map.toggle-time-filter',+ 'map.split-view',+ 'map.get-dataset-context'+] as const;++export type MapToolId = (typeof MAP_TOOL_IDS)[number];diff --git a/src/mcp/tsconfig.production.json b/src/mcp/tsconfig.production.jsonnew file mode 100644index 000000000..cf388af94--- /dev/null+++ b/src/mcp/tsconfig.production.json@@ -0,0 +1,29 @@+{+ "compilerOptions": {+ "target": "es2020",+ "allowJs": false,+ "checkJs": false,+ "jsx": "react",+ "module": "esnext",+ "moduleResolution": "node",+ "declaration": true,+ "emitDeclarationOnly": true,+ "noImplicitAny": false,+ "noImplicitReturns": true,+ "noImplicitThis": true,+ "noUnusedLocals": true,+ "outDir": "dist",+ "sourceMap": true,+ "strictNullChecks": true,+ "suppressImplicitAnyIndexErrors": false,+ "esModuleInterop": true,+ "allowSyntheticDefaultImports": true,+ "skipLibCheck": true,+ "strict": true,+ "resolveJsonModule": true,+ "isolatedModules": true,+ "baseUrl": "./src"+ },+ "include": ["src"],+ "exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"]+}diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.jsindex f86e201bf..affc64602 100644--- a/test/node/reducers/vis-state-test.js+++ b/test/node/reducers/vis-state-test.js@@ -10215,7 +10215,11 @@ test('VisStateUpdater -> refreshDataset keeps Arrow point layers valid through econst expected = values.flatMap((value, index) =>!withFilter || value < 2 || value > 3 ? [index] : []);- t.deepEqual(state.datasets[dataId].filteredIndex, expected, 'refresh reapplies active filters');+ t.deepEqual(+ state.datasets[dataId].filteredIndex,+ expected,+ 'refresh reapplies active filters'+ );t.deepEqual(values.flatMap((_, index) => (state.layerData[0].getFiltered({index}) ? [index] : [])),expected,@@ -10264,7 +10268,10 @@ test('VisStateUpdater -> refreshDataset reapplies active filters to Arrow snapshfor (const [values, expected] of [[[1, 2, 3], [0]],[[3, 1, 2], [1]],- [[2, 1, 3, 4], [1, 3]],+ [+ [2, 1, 3, 4],+ [1, 3]+ ],[[], []],[[3, 2, 1], [2]],[[2], []]diff --git a/website/esbuild.config.mjs b/website/esbuild.config.mjsindex 717abb9d4..d13734202 100644--- a/website/esbuild.config.mjs+++ b/website/esbuild.config.mjs@@ -75,6 +75,16 @@ workspaces.forEach(workspace => {RESOLVE_LOCAL_ALIASES[`@kepler.gl/${moduleName}`] = join(SRC_DIR, `${moduleName}/src`);});+// mcp ships the map-management skill markdown as a subpath export; the+// longer key wins over the `@kepler.gl/mcp` src alias above.+RESOLVE_LOCAL_ALIASES['@kepler.gl/mcp/skill/kepler/SKILL.md'] = join(+ SRC_DIR,+ 'mcp',+ 'skill',+ 'kepler',+ 'SKILL.md'+);+const config = {platform: 'browser',format: 'iife',@@ -83,6 +93,7 @@ const config = {loader: {'.js': 'jsx','.css': 'css',+ '.md': 'text','.png': 'file','.jpg': 'file','.svg': 'file',diff --git a/yarn.lock b/yarn.lockindex 2e39c3957..81bfc3e3d 100644--- a/yarn.lock+++ b/yarn.lock@@ -3230,6 +3230,15 @@ __metadata:languageName: nodelinkType: hard+"@hono/node-server@npm:^1.19.9 || ^2.0.5":+ version: 2.1.5+ resolution: "@hono/node-server@npm:2.1.5"+ peerDependencies:+ hono: ^4 || ^5.0.0-0+ checksum: 10c0/3c3d5ffcc4a229e532530729b64db623493171bcda7b40ffbac3a46489884f700c881439d8c0d0413cd18793458ca252acedf6a9c13c8c3a024037e47974cacb+ languageName: node+ linkType: hard+"@hookform/resolvers@npm:^5.0.0":version: 5.9.1resolution: "@hookform/resolvers@npm:5.9.1"@@ -4415,6 +4424,29 @@ __metadata:languageName: unknownlinkType: soft+"@kepler.gl/mcp@workspace:src/mcp":+ version: 0.0.0-use.local+ resolution: "@kepler.gl/mcp@workspace:src/mcp"+ dependencies:+ "@babel/cli": "npm:^7.12.1"+ "@babel/node": "npm:^7.12.1"+ "@kepler.gl/actions": "npm:3.3.0-alpha.18"+ "@kepler.gl/constants": "npm:3.3.0-alpha.18"+ "@kepler.gl/layers": "npm:3.3.0-alpha.18"+ "@kepler.gl/processors": "npm:3.3.0-alpha.18"+ "@kepler.gl/reducers": "npm:3.3.0-alpha.18"+ "@kepler.gl/table": "npm:3.3.0-alpha.18"+ "@kepler.gl/types": "npm:3.3.0-alpha.18"+ "@modelcontextprotocol/sdk": "npm:^1.32.2"+ "@types/ws": "npm:^8.18.2"+ apache-arrow: "npm:^17.0.0"+ ws: "npm:^8.22.0"+ zod: "npm:^4.4.0"+ bin:+ kepler-mcp: dist/cjs/server/stdio.js+ languageName: unknown+ linkType: soft+"@kepler.gl/processors@npm:3.3.0-alpha.18, @kepler.gl/processors@workspace:src/processors":version: 0.0.0-use.localresolution: "@kepler.gl/processors@workspace:src/processors"@@ -6484,6 +6516,39 @@ __metadata:languageName: nodelinkType: hard+"@modelcontextprotocol/sdk@npm:^1.32.2":+ version: 1.32.2+ resolution: "@modelcontextprotocol/sdk@npm:1.32.2"+ dependencies:+ "@hono/node-server": "npm:^1.19.9 || ^2.0.5"+ ajv: "npm:^8.17.1"+ ajv-formats: "npm:^3.0.1"+ content-type: "npm:^1.0.5"+ cors: "npm:^2.8.5"+ cross-spawn: "npm:^7.0.5"+ eventsource: "npm:^3.0.2"+ eventsource-parser: "npm:^3.0.0"+ express: "npm:^5.2.1"+ express-rate-limit: "npm:^8.2.1"+ hono: "npm:^4.11.4"+ jose: "npm:^6.1.3"+ json-schema-typed: "npm:^8.0.2"+ pkce-challenge: "npm:^5.0.0"+ raw-body: "npm:^3.0.0"+ zod: "npm:^3.25 || ^4.0"+ zod-to-json-schema: "npm:^3.25.1"+ peerDependencies:+ "@cfworker/json-schema": ^4.1.1+ zod: ^3.25 || ^4.0+ peerDependenciesMeta:+ "@cfworker/json-schema":+ optional: true+ zod:+ optional: false+ checksum: 10c0/31d045fe1121242ee7871f5fc9d5dc1f2ad622d9a9750fab5c14d1a1da227dd7225b16df0e8f22783356981255b22f5da84d1f74985df264ad79f2f00cc6ac7b+ languageName: node+ linkType: hard+"@monaco-editor/loader@npm:^1.5.0":version: 1.7.0resolution: "@monaco-editor/loader@npm:1.7.0"@@ -11114,6 +11179,15 @@ __metadata:languageName: nodelinkType: hard+"@types/ws@npm:^8.18.2":+ version: 8.18.2+ resolution: "@types/ws@npm:8.18.2"+ dependencies:+ "@types/node": "npm:*"+ checksum: 10c0/8cf79499d26df06ffc27109fc86f1400371a5932082a4c1269be3f11e22b9e5a403a4ba2c1a3245d5fae420c270571aa833142a3d7fdce8f6cd24a45c52a98e4+ languageName: node+ linkType: hard+"@types/ws@npm:^8.5.10":version: 8.18.1resolution: "@types/ws@npm:8.18.1"@@ -11797,6 +11871,16 @@ __metadata:languageName: nodelinkType: hard+"accepts@npm:^2.0.0":+ version: 2.0.0+ resolution: "accepts@npm:2.0.0"+ dependencies:+ mime-types: "npm:^3.0.0"+ negotiator: "npm:^1.0.0"+ checksum: 10c0/98374742097e140891546076215f90c32644feacf652db48412329de4c2a529178a81aa500fbb13dd3e6cbf6e68d829037b123ac037fc9a08bcec4b87b358eef+ languageName: node+ linkType: hard+"accepts@npm:~1.3.4, accepts@npm:~1.3.8":version: 1.3.8resolution: "accepts@npm:1.3.8"@@ -11961,6 +12045,20 @@ __metadata:languageName: nodelinkType: hard+"ajv-formats@npm:^3.0.1":+ version: 3.0.1+ resolution: "ajv-formats@npm:3.0.1"+ dependencies:+ ajv: "npm:^8.0.0"+ peerDependencies:+ ajv: ^8.0.0+ peerDependenciesMeta:+ ajv:+ optional: true+ checksum: 10c0/168d6bca1ea9f163b41c8147bae537e67bd963357a5488a1eaf3abe8baa8eec806d4e45f15b10767e6020679315c7e1e5e6803088dfb84efa2b4e9353b83dd0a+ languageName: node+ linkType: hard+"ajv-keywords@npm:^3.5.2":version: 3.5.2resolution: "ajv-keywords@npm:3.5.2"@@ -11993,7 +12091,7 @@ __metadata:languageName: nodelinkType: hard-"ajv@npm:^8.0.0, ajv@npm:^8.9.0":+"ajv@npm:^8.0.0, ajv@npm:^8.17.1, ajv@npm:^8.9.0":version: 8.20.0resolution: "ajv@npm:8.20.0"dependencies:@@ -13238,6 +13336,23 @@ __metadata:languageName: nodelinkType: hard+"body-parser@npm:^2.3.0":+ version: 2.4.0+ resolution: "body-parser@npm:2.4.0"+ dependencies:+ bytes: "npm:^3.1.2"+ content-type: "npm:^2.1.0"+ debug: "npm:^4.4.3"+ http-errors: "npm:^2.0.1"+ iconv-lite: "npm:^0.7.3"+ on-finished: "npm:^2.4.1"+ qs: "npm:^6.16.1"+ raw-body: "npm:^3.0.2"+ type-is: "npm:^2.1.0"+ checksum: 10c0/247b891a27f661410b149c8a4771d3a9a076c86f41fff033d87b8bc828198195bd03ba321e3a8993ac37abca5a7ffeb62c96ea41f7ad3f11c170b73de5c27afe+ languageName: node+ linkType: hard+"body-parser@npm:~1.20.5":version: 1.20.6resolution: "body-parser@npm:1.20.6"@@ -13701,7 +13816,7 @@ __metadata:languageName: nodelinkType: hard-"bytes@npm:3.1.2, bytes@npm:~3.1.2":+"bytes@npm:3.1.2, bytes@npm:^3.1.2, bytes@npm:~3.1.2":version: 3.1.2resolution: "bytes@npm:3.1.2"checksum: 10c0/76d1c43cbd602794ad8ad2ae94095cddeb1de78c5dddaa7005c51af10b0176c69971a6d88e805a90c2b6550d76636e43c40d8427a808b8645ede885de4a0358e@@ -14791,6 +14906,13 @@ __metadata:languageName: nodelinkType: hard+"content-disposition@npm:^2.0.1":+ version: 2.0.1+ resolution: "content-disposition@npm:2.0.1"+ checksum: 10c0/8ba0e1f95102343a69a9a4b6f17728209d4ff0402b830b7cda91dcdfbb12eed0201dcd02aaa1e56f9bcf1c5b8ccef4a70e83b58292cf26588d8d5f7d05a0c006+ languageName: node+ linkType: hard+"content-disposition@npm:~0.5.4":version: 0.5.4resolution: "content-disposition@npm:0.5.4"@@ -14800,13 +14922,20 @@ __metadata:languageName: nodelinkType: hard-"content-type@npm:~1.0.4, content-type@npm:~1.0.5":+"content-type@npm:^1.0.5, content-type@npm:~1.0.4, content-type@npm:~1.0.5":version: 1.0.5resolution: "content-type@npm:1.0.5"checksum: 10c0/b76ebed15c000aee4678c3707e0860cb6abd4e680a598c0a26e17f0bfae723ec9cc2802f0ff1bc6e4d80603719010431d2231018373d4dde10f9ccff9dadf5aflanguageName: nodelinkType: hard+"content-type@npm:^2.0.0, content-type@npm:^2.1.0":+ version: 2.1.0+ resolution: "content-type@npm:2.1.0"+ checksum: 10c0/f5d420f55fd0c7a7f7cbae9637777ce67a074aa79b489d8d9fee8599089592b5f8bb194e1d6885741fee20271034baca0d68d5419535b52d070c4f7e39f4b448+ languageName: node+ linkType: hard+"contentstream@npm:^1.0.0":version: 1.0.0resolution: "contentstream@npm:1.0.0"@@ -14937,6 +15066,13 @@ __metadata:languageName: nodelinkType: hard+"cookie-signature@npm:^1.2.1":+ version: 1.2.2+ resolution: "cookie-signature@npm:1.2.2"+ checksum: 10c0/54e05df1a293b3ce81589b27dddc445f462f6fa6812147c033350cd3561a42bc14481674e05ed14c7bd0ce1e8bb3dc0e40851bad75415733711294ddce0b7bc6+ languageName: node+ linkType: hard+"cookie-signature@npm:~1.0.6":version: 1.0.7resolution: "cookie-signature@npm:1.0.7"@@ -14944,7 +15080,7 @@ __metadata:languageName: nodelinkType: hard-"cookie@npm:~0.7.1":+"cookie@npm:^0.7.1, cookie@npm:~0.7.1":version: 0.7.2resolution: "cookie@npm:0.7.2"checksum: 10c0/9596e8ccdbf1a3a88ae02cf5ee80c1c50959423e1022e4e60b91dd87c622af1da309253d8abdb258fb5e3eacb4f08e579dc58b4897b8087574eee0fd35dfa5d2@@ -15014,6 +15150,16 @@ __metadata:languageName: nodelinkType: hard+"cors@npm:^2.8.5":+ version: 2.8.6+ resolution: "cors@npm:2.8.6"+ dependencies:+ object-assign: "npm:^4"+ vary: "npm:^1"+ checksum: 10c0/ab2bc57b8af8ef8476682a59647f7c55c1a7d406b559ac06119aa1c5f70b96d35036864d197b24cf86e228e4547231088f1f94ca05061dbb14d89cc0bc9d4cab+ languageName: node+ linkType: hard+"cosmiconfig@npm:9.0.0, cosmiconfig@npm:^9.0.0":version: 9.0.0resolution: "cosmiconfig@npm:9.0.0"@@ -15150,6 +15296,17 @@ __metadata:languageName: nodelinkType: hard+"cross-spawn@npm:^7.0.5":+ version: 7.0.6+ resolution: "cross-spawn@npm:7.0.6"+ dependencies:+ path-key: "npm:^3.1.0"+ shebang-command: "npm:^2.0.0"+ which: "npm:^2.0.1"+ checksum: 10c0/053ea8b2135caff68a9e81470e845613e374e7309a47731e81639de3eaeb90c3d01af0e0b44d2ab9d50b43467223b88567dfeb3262db942dc063b9976718ffc1+ languageName: node+ linkType: hard+"crypt@npm:0.0.2":version: 0.0.2resolution: "crypt@npm:0.0.2"@@ -15783,7 +15940,7 @@ __metadata:languageName: nodelinkType: hard-"debug@npm:^4.4.3":+"debug@npm:^4.4.0, debug@npm:^4.4.3":version: 4.4.3resolution: "debug@npm:4.4.3"dependencies:@@ -16064,7 +16221,7 @@ __metadata:languageName: nodelinkType: hard-"depd@npm:2.0.0, depd@npm:~2.0.0":+"depd@npm:2.0.0, depd@npm:^2.0.0, depd@npm:~2.0.0":version: 2.0.0resolution: "depd@npm:2.0.0"checksum: 10c0/58bd06ec20e19529b06f7ad07ddab60e504d9e0faca4bd23079fac2d279c3594334d736508dc350e06e510aba5e22e4594483b3a6562ce7c17dd797f4cc4ad2c@@ -16875,7 +17032,7 @@ __metadata:languageName: nodelinkType: hard-"encodeurl@npm:~2.0.0":+"encodeurl@npm:^2.0.0, encodeurl@npm:~2.0.0":version: 2.0.0resolution: "encodeurl@npm:2.0.0"checksum: 10c0/5d317306acb13e6590e28e27924c754163946a2480de11865c991a3a7eed4315cd3fba378b543ca145829569eefe9b899f3d84bb09870f675ae60bc924b01ceb@@ -17362,7 +17519,7 @@ __metadata:languageName: nodelinkType: hard-"escape-html@npm:~1.0.3":+"escape-html@npm:^1.0.3, escape-html@npm:~1.0.3":version: 1.0.3resolution: "escape-html@npm:1.0.3"checksum: 10c0/524c739d776b36c3d29fa08a22e03e8824e3b2fd57500e5e44ecf3cc4707c34c60f9ca0781c0e33d191f2991161504c295e98f68c78fe7baa6e57081ec6ac0a3@@ -17813,7 +17970,7 @@ __metadata:languageName: nodelinkType: hard-"etag@npm:~1.8.1":+"etag@npm:^1.8.1, etag@npm:~1.8.1":version: 1.8.1resolution: "etag@npm:1.8.1"checksum: 10c0/12be11ef62fb9817314d790089a0a49fae4e1b50594135dcb8076312b7d7e470884b5100d249b28c18581b7fd52f8b485689ffae22a11ed9ec17377a33a08f84@@ -17864,6 +18021,22 @@ __metadata:languageName: nodelinkType: hard+"eventsource-parser@npm:^3.0.0, eventsource-parser@npm:^3.0.1":+ version: 3.1.1+ resolution: "eventsource-parser@npm:3.1.1"+ checksum: 10c0/dd3236c61140587253dcaaf947de528ac0e7371caffdc53c77afaeee36a17661f00e251a6ea16af56c99be5ac138303e67b5d750630e7c41b02e3564e8ad8c44+ languageName: node+ linkType: hard++"eventsource@npm:^3.0.2":+ version: 3.0.7+ resolution: "eventsource@npm:3.0.7"+ dependencies:+ eventsource-parser: "npm:^3.0.1"+ checksum: 10c0/c48a73c38f300e33e9f11375d4ee969f25cbb0519608a12378a38068055ae8b55b6e0e8a49c3f91c784068434efe1d9f01eb49b6315b04b0da9157879ce2f67d+ languageName: node+ linkType: hard+"evp_bytestokey@npm:^1.0.0, evp_bytestokey@npm:^1.0.3":version: 1.0.3resolution: "evp_bytestokey@npm:1.0.3"@@ -17989,6 +18162,18 @@ __metadata:languageName: nodelinkType: hard+"express-rate-limit@npm:^8.2.1":+ version: 8.7.1+ resolution: "express-rate-limit@npm:8.7.1"+ dependencies:+ debug: "npm:^4.4.3"+ ip-address: "npm:^10.2.0"+ peerDependencies:+ express: ">= 4.11"+ checksum: 10c0/575afb52d84242325450794ff2dc4fbe6e913e081fe6fe857541201b7c159661a9a7d5ac7573679b68b67bf9af8f0205b9539777373ad34617814dc6057a6b3b+ languageName: node+ linkType: hard+"express@npm:^4.22.1":version: 4.22.2resolution: "express@npm:4.22.2"@@ -18028,6 +18213,42 @@ __metadata:languageName: nodelinkType: hard+"express@npm:^5.2.1":+ version: 5.3.0+ resolution: "express@npm:5.3.0"+ dependencies:+ accepts: "npm:^2.0.0"+ body-parser: "npm:^2.3.0"+ content-disposition: "npm:^2.0.1"+ content-type: "npm:^2.0.0"+ cookie: "npm:^0.7.1"+ cookie-signature: "npm:^1.2.1"+ debug: "npm:^4.4.0"+ depd: "npm:^2.0.0"+ encodeurl: "npm:^2.0.0"+ escape-html: "npm:^1.0.3"+ etag: "npm:^1.8.1"+ finalhandler: "npm:^2.1.0"+ fresh: "npm:^2.0.0"+ http-errors: "npm:^2.0.0"+ merge-descriptors: "npm:^2.0.0"+ mime-types: "npm:^3.0.0"+ on-finished: "npm:^2.4.1"+ once: "npm:^1.4.0"+ parseurl: "npm:^1.3.3"+ proxy-addr: "npm:^2.0.8"+ qs: "npm:^6.16.0"+ range-parser: "npm:^1.2.1"+ router: "npm:^2.2.0"+ send: "npm:^1.1.0"+ serve-static: "npm:^2.2.0"+ statuses: "npm:^2.0.1"+ type-is: "npm:^2.1.0"+ vary: "npm:^1.1.2"+ checksum: 10c0/7d6c1a3e404db0a26f7ed1143ad6bb0bcf33fec8dc66b3e56b59f94f4660e7d3d8395bf03f80e51f6b74ce976856a3e97133a371ec4d012409729fff9233eb15+ languageName: node+ linkType: hard+"extend-shallow@npm:^2.0.1":version: 2.0.1resolution: "extend-shallow@npm:2.0.1"@@ -18380,6 +18601,20 @@ __metadata:languageName: nodelinkType: hard+"finalhandler@npm:^2.1.0":+ version: 2.1.1+ resolution: "finalhandler@npm:2.1.1"+ dependencies:+ debug: "npm:^4.4.0"+ encodeurl: "npm:^2.0.0"+ escape-html: "npm:^1.0.3"+ on-finished: "npm:^2.4.1"+ parseurl: "npm:^1.3.3"+ statuses: "npm:^2.0.1"+ checksum: 10c0/6bd664e21b7b2e79efcaace7d1a427169f61cce048fae68eb56290e6934e676b78e55d89f5998c5508871345bc59a61f47002dc505dc7288be68cceac1b701e2+ languageName: node+ linkType: hard+"finalhandler@npm:~1.3.1":version: 1.3.2resolution: "finalhandler@npm:1.3.2"@@ -18690,6 +18925,13 @@ __metadata:languageName: nodelinkType: hard+"fresh@npm:^2.0.0":+ version: 2.0.0+ resolution: "fresh@npm:2.0.0"+ checksum: 10c0/0557548194cb9a809a435bf92bcfbc20c89e8b5eb38861b73ced36750437251e39a111fc3a18b98531be9dd91fe1411e4969f229dc579ec0251ce6c5d4900bbc+ languageName: node+ linkType: hard+"fresh@npm:~0.5.2":version: 0.5.2resolution: "fresh@npm:0.5.2"@@ -20002,6 +20244,13 @@ __metadata:languageName: nodelinkType: hard+"hono@npm:^4.11.4":+ version: 4.13.14+ resolution: "hono@npm:4.13.14"+ checksum: 10c0/fdedcb49186e3a5eb0fff39c4fd66112718dc1a98c6df9a385f2fc4799c0e59140e3c45fbac12929d658b659d9eb9ddb9ac09161104336023c23f335668c93fd+ languageName: node+ linkType: hard+"hosted-git-info@npm:^2.1.4":version: 2.8.9resolution: "hosted-git-info@npm:2.8.9"@@ -20177,19 +20426,7 @@ __metadata:languageName: nodelinkType: hard-"http-errors@npm:~1.6.2":- version: 1.6.3- resolution: "http-errors@npm:1.6.3"- dependencies:- depd: "npm:~1.1.2"- inherits: "npm:2.0.3"- setprototypeof: "npm:1.1.0"- statuses: "npm:>= 1.4.0 < 2"- checksum: 10c0/17ec4046ee974477778bfdd525936c254b872054703ec2caa4d6f099566b8adade636ae6aeeacb39302c5cd6e28fb407ebd937f500f5010d0b6850750414ff78- languageName: node- linkType: hard--"http-errors@npm:~2.0.0, http-errors@npm:~2.0.1":+"http-errors@npm:^2.0.0, http-errors@npm:^2.0.1, http-errors@npm:~2.0.0, http-errors@npm:~2.0.1":version: 2.0.1resolution: "http-errors@npm:2.0.1"dependencies:@@ -20202,6 +20439,18 @@ __metadata:languageName: nodelinkType: hard+"http-errors@npm:~1.6.2":+ version: 1.6.3+ resolution: "http-errors@npm:1.6.3"+ dependencies:+ depd: "npm:~1.1.2"+ inherits: "npm:2.0.3"+ setprototypeof: "npm:1.1.0"+ statuses: "npm:>= 1.4.0 < 2"+ checksum: 10c0/17ec4046ee974477778bfdd525936c254b872054703ec2caa4d6f099566b8adade636ae6aeeacb39302c5cd6e28fb407ebd937f500f5010d0b6850750414ff78+ languageName: node+ linkType: hard+"http-parser-js@npm:>=0.5.1":version: 0.5.8resolution: "http-parser-js@npm:0.5.8"@@ -20358,7 +20607,7 @@ __metadata:languageName: nodelinkType: hard-"iconv-lite@npm:^0.7.0":+"iconv-lite@npm:^0.7.0, iconv-lite@npm:^0.7.3, iconv-lite@npm:~0.7.0":version: 0.7.3resolution: "iconv-lite@npm:0.7.3"dependencies:@@ -21236,6 +21485,13 @@ __metadata:languageName: nodelinkType: hard+"is-promise@npm:^4.0.0":+ version: 4.0.0+ resolution: "is-promise@npm:4.0.0"+ checksum: 10c0/ebd5c672d73db781ab33ccb155fb9969d6028e37414d609b115cc534654c91ccd061821d5b987eefaa97cf4c62f0b909bb2f04db88306de26e91bfe8ddc01503+ languageName: node+ linkType: hard+"is-regex@npm:^1.1.4, is-regex@npm:~1.1.4":version: 1.1.4resolution: "is-regex@npm:1.1.4"@@ -22196,6 +22452,13 @@ __metadata:languageName: nodelinkType: hard+"jose@npm:^6.1.3":+ version: 6.2.13+ resolution: "jose@npm:6.2.13"+ checksum: 10c0/a7a175057fd42e129200026320d535deba5c869e764bdb130d4aecb7cc2a22c07eab2bf9fc848188b45b89d95f8e0ba4ce01a8259a4fa45c84bec34f66f2918e+ languageName: node+ linkType: hard+"jpeg-js@npm:^0.4.3":version: 0.4.4resolution: "jpeg-js@npm:0.4.4"@@ -22403,6 +22666,13 @@ __metadata:languageName: nodelinkType: hard+"json-schema-typed@npm:^8.0.2":+ version: 8.0.2+ resolution: "json-schema-typed@npm:8.0.2"+ checksum: 10c0/89f5e2fb1495483b705c027203c07277ee6bf2665165ad25a9cb55de5af7f72570326d13d32565180781e4083ad5c9688102f222baed7b353c2f39c1e02b0428+ languageName: node+ linkType: hard+"json-schema@npm:0.4.0":version: 0.4.0resolution: "json-schema@npm:0.4.0"@@ -24039,6 +24309,13 @@ __metadata:languageName: nodelinkType: hard+"media-typer@npm:^1.1.0":+ version: 1.1.1+ resolution: "media-typer@npm:1.1.1"+ checksum: 10c0/924644de220c3107fc53ec0299b7c1488503470265d32f1492535bd798cc369ba7ceaf9c2a4533361590dcf7208d1cc7b7032dbc1a5918773f5f5d912cab5211+ languageName: node+ linkType: hard+"mem@npm:^4.0.0":version: 4.3.0resolution: "mem@npm:4.3.0"@@ -24129,6 +24406,13 @@ __metadata:languageName: nodelinkType: hard+"merge-descriptors@npm:^2.0.0":+ version: 2.0.0+ resolution: "merge-descriptors@npm:2.0.0"+ checksum: 10c0/95389b7ced3f9b36fbdcf32eb946dc3dd1774c2fdf164609e55b18d03aa499b12bd3aae3a76c1c7185b96279e9803525550d3eb292b5224866060a288f335cb3+ languageName: node+ linkType: hard+"merge-stream@npm:^2.0.0":version: 2.0.0resolution: "merge-stream@npm:2.0.0"@@ -24579,7 +24863,7 @@ __metadata:languageName: nodelinkType: hard-"mime-types@npm:^3.0.1":+"mime-types@npm:^3.0.0, mime-types@npm:^3.0.1, mime-types@npm:^3.0.2":version: 3.0.2resolution: "mime-types@npm:3.0.2"dependencies:@@ -25226,6 +25510,15 @@ __metadata:languageName: nodelinkType: hard+"negotiator@npm:^1.0.0":+ version: 1.1.0+ resolution: "negotiator@npm:1.1.0"+ dependencies:+ content-type: "npm:^2.1.0"+ checksum: 10c0/656fa57de02f1a0c4c09f9e17eb78e8182547c07093e810ff8f16249b6ae31f2c546a3d457905e94f3276b25f0e2741ea1a3bc3912192932ed7e493adfea535e+ languageName: node+ linkType: hard+"negotiator@npm:~0.6.4":version: 0.6.4resolution: "negotiator@npm:0.6.4"@@ -25789,7 +26082,7 @@ __metadata:languageName: nodelinkType: hard-"object-assign@npm:^4.0.1, object-assign@npm:^4.1.0, object-assign@npm:^4.1.1":+"object-assign@npm:^4, object-assign@npm:^4.0.1, object-assign@npm:^4.1.0, object-assign@npm:^4.1.1":version: 4.1.1resolution: "object-assign@npm:4.1.1"checksum: 10c0/1f4df9945120325d041ccf7b86f31e8bcc14e73d29171e37a7903050e96b81323784ec59f93f102ec635bcf6fa8034ba3ea0a8c7e69fa202b87ae3b6cec5a414@@ -26686,7 +26979,7 @@ __metadata:languageName: nodelinkType: hard-"parseurl@npm:~1.3.2, parseurl@npm:~1.3.3":+"parseurl@npm:^1.3.3, parseurl@npm:~1.3.2, parseurl@npm:~1.3.3":version: 1.3.3resolution: "parseurl@npm:1.3.3"checksum: 10c0/90dd4760d6f6174adb9f20cf0965ae12e23879b5f5464f38e92fce8073354341e4b3b76fa3d878351efe7d01e617121955284cfd002ab087fba1a0726ec0b4f5@@ -26822,6 +27115,13 @@ __metadata:languageName: nodelinkType: hard+"path-to-regexp@npm:^8.0.0":+ version: 8.4.2+ resolution: "path-to-regexp@npm:8.4.2"+ checksum: 10c0/05b115c49b47ad252ce05faa32930f643f23769c68b8bcfe78ad833545140c48bbffb3266986d6c8d5db13a64cf12e07e0d72d9882cab830efeefa553533ebaf+ languageName: node+ linkType: hard+"path-to-regexp@npm:~0.1.12":version: 0.1.13resolution: "path-to-regexp@npm:0.1.13"@@ -26966,6 +27266,13 @@ __metadata:languageName: nodelinkType: hard+"pkce-challenge@npm:^5.0.0":+ version: 5.0.1+ resolution: "pkce-challenge@npm:5.0.1"+ checksum: 10c0/207f4cb976682f27e8324eb49cf71937c98fbb8341a0b8f6142bc6f664825b30e049a54a21b5c034e823ee3c3d412f10d74bd21de78e17452a6a496c2991f57c+ languageName: node+ linkType: hard+"pkg-dir@npm:^3.0.0":version: 3.0.0resolution: "pkg-dir@npm:3.0.0"@@ -27944,6 +28251,18 @@ __metadata:languageName: nodelinkType: hard+"raw-body@npm:^3.0.0, raw-body@npm:^3.0.2":+ version: 3.0.2+ resolution: "raw-body@npm:3.0.2"+ dependencies:+ bytes: "npm:~3.1.2"+ http-errors: "npm:~2.0.1"+ iconv-lite: "npm:~0.7.0"+ unpipe: "npm:~1.0.0"+ checksum: 10c0/d266678d08e1e7abea62c0ce5864344e980fa81c64f6b481e9842c5beaed2cdcf975f658a3ccd67ad35fc919c1f6664ccc106067801850286a6cbe101de89f29+ languageName: node+ linkType: hard+"raw-body@npm:~1.1.0":version: 1.1.7resolution: "raw-body@npm:1.1.7"@@ -29619,6 +29938,19 @@ __metadata:languageName: nodelinkType: hard+"router@npm:^2.2.0":+ version: 2.2.0+ resolution: "router@npm:2.2.0"+ dependencies:+ debug: "npm:^4.4.0"+ depd: "npm:^2.0.0"+ is-promise: "npm:^4.0.0"+ parseurl: "npm:^1.3.3"+ path-to-regexp: "npm:^8.0.0"+ checksum: 10c0/3279de7450c8eae2f6e095e9edacbdeec0abb5cb7249c6e719faa0db2dba43574b4fff5892d9220631c9abaff52dd3cad648cfea2aaace845e1a071915ac8867+ languageName: node+ linkType: hard+"rrweb-cssom@npm:^0.6.0":version: 0.6.0resolution: "rrweb-cssom@npm:0.6.0"@@ -29905,6 +30237,25 @@ __metadata:languageName: nodelinkType: hard+"send@npm:^1.1.0, send@npm:^1.2.0":+ version: 1.2.1+ resolution: "send@npm:1.2.1"+ dependencies:+ debug: "npm:^4.4.3"+ encodeurl: "npm:^2.0.0"+ escape-html: "npm:^1.0.3"+ etag: "npm:^1.8.1"+ fresh: "npm:^2.0.0"+ http-errors: "npm:^2.0.1"+ mime-types: "npm:^3.0.2"+ ms: "npm:^2.1.3"+ on-finished: "npm:^2.4.1"+ range-parser: "npm:^1.2.1"+ statuses: "npm:^2.0.2"+ checksum: 10c0/fbbbbdc902a913d65605274be23f3d604065cfc3ee3d78bf9fc8af1dc9fc82667c50d3d657f5e601ac657bac9b396b50ee97bd29cd55436320cf1cddebdcec72+ languageName: node+ linkType: hard+"send@npm:~0.19.0, send@npm:~0.19.1":version: 0.19.2resolution: "send@npm:0.19.2"@@ -29941,6 +30292,18 @@ __metadata:languageName: nodelinkType: hard+"serve-static@npm:^2.2.0":+ version: 2.2.1+ resolution: "serve-static@npm:2.2.1"+ dependencies:+ encodeurl: "npm:^2.0.0"+ escape-html: "npm:^1.0.3"+ parseurl: "npm:^1.3.3"+ send: "npm:^1.2.0"+ checksum: 10c0/37986096e8572e2dfaad35a3925fa8da0c0969f8814fd7788e84d4d388bc068cf0c06d1658509788e55bed942a6b6d040a8a267fa92bb9ffb1179f8bacde5fd7+ languageName: node+ linkType: hard+"serve-static@npm:~1.16.2":version: 1.16.3resolution: "serve-static@npm:1.16.3"@@ -30785,7 +31148,7 @@ __metadata:languageName: nodelinkType: hard-"statuses@npm:~2.0.1, statuses@npm:~2.0.2":+"statuses@npm:^2.0.1, statuses@npm:^2.0.2, statuses@npm:~2.0.1, statuses@npm:~2.0.2":version: 2.0.2resolution: "statuses@npm:2.0.2"checksum: 10c0/a9947d98ad60d01f6b26727570f3bcceb6c8fa789da64fe6889908fe2e294d57503b14bf2b5af7605c2d36647259e856635cd4c49eab41667658ec9d0080ec3f@@ -32456,6 +32819,17 @@ __metadata:languageName: nodelinkType: hard+"type-is@npm:^2.1.0":+ version: 2.1.0+ resolution: "type-is@npm:2.1.0"+ dependencies:+ content-type: "npm:^2.0.0"+ media-typer: "npm:^1.1.0"+ mime-types: "npm:^3.0.0"+ checksum: 10c0/a6018f8f509de48f2c7429305e3a920e73b374fa93127dd0877ae1c2df65a5d33907caac8afb0c37a9b9fc7c49f29e3f55d668963dc845d966930b667c07f50e+ languageName: node+ linkType: hard+"type-is@npm:~1.6.18":version: 1.6.18resolution: "type-is@npm:1.6.18"@@ -33375,7 +33749,7 @@ __metadata:languageName: nodelinkType: hard-"vary@npm:~1.1.2":+"vary@npm:^1, vary@npm:^1.1.2, vary@npm:~1.1.2":version: 1.1.2resolution: "vary@npm:1.1.2"checksum: 10c0/f15d588d79f3675135ba783c91a4083dcd290a2a5be9fcb6514220a1634e23df116847b1cc51f66bfb0644cf9353b2abb7815ae499bab06e46dd33c1a6bf1f4f@@ -34422,6 +34796,21 @@ __metadata:languageName: nodelinkType: hard+"ws@npm:^8.22.0":+ version: 8.22.0+ resolution: "ws@npm:8.22.0"+ peerDependencies:+ bufferutil: ^4.0.1+ utf-8-validate: ">=5.0.2"+ peerDependenciesMeta:+ bufferutil:+ optional: true+ utf-8-validate:+ optional: true+ checksum: 10c0/7304d14ef38898dd366a528a85e2da389c4eebf30f4ce8a007bd2dce6025f9b619cefe44fe2354f0bad0ec541b1c9a4da06a3f3e046ab56f01fd52d5784ecfb2+ languageName: node+ linkType: hard+"wsl-utils@npm:^0.1.0":version: 0.1.0resolution: "wsl-utils@npm:0.1.0"@@ -34686,6 +35075,15 @@ __metadata:languageName: nodelinkType: hard+"zod-to-json-schema@npm:^3.25.1":+ version: 3.25.2+ resolution: "zod-to-json-schema@npm:3.25.2"+ peerDependencies:+ zod: ^3.25.28 || ^4+ checksum: 10c0/dd300554393903022487688af14fbda5c719ba8179702bb55b3aa86318830467f0f7beb7d654036975ac963dc4843b72e59636448bfff9a0608f277bb6a14939+ languageName: node+ linkType: hard+"zod@npm:^3.24.1":version: 3.25.76resolution: "zod@npm:3.25.76"@@ -34693,6 +35091,13 @@ __metadata:languageName: nodelinkType: hard+"zod@npm:^3.25 || ^4.0, zod@npm:^4.4.0":+ version: 4.6.7+ resolution: "zod@npm:4.6.7"+ checksum: 10c0/4ce2eb14034317b7254e347ca37b5ad591cf8333147030cf05b9b5d31692d45073f7f2747aa50cf8c6b29012194d2b22978cecc89969cf34a0d18e89d0ee7d7b+ languageName: node+ linkType: hard+"zod@npm:^4.1.11":version: 4.4.3resolution: "zod@npm:4.4.3"