A web app where users describe dashboards in natural language and an AI agent produces live SDMx data visualizations for Pacific Island Countries and Territories.
Built on three existing components:
- sdmx-mcp-gateway — Python MCP server for progressive SDMx data discovery
- sdmx-dashboard-components — React library rendering dashboards from JSON configs via ECharts
- AI SDK v6 — connects a chat interface to the AI, which orchestrates discovery and produces dashboard configs
Access is limited to approved organisation domains and invited users. Users sign in with Google/Microsoft/GitHub (when configured), email magic links, or a password they set themselves by proving their address with one email they send us (see docs/email-proof-signup.md). Sessions and usage are persisted in PostgreSQL.
| Tool | Version | Purpose |
|---|---|---|
| Node.js | >= 22 | Next.js runtime |
| npm | >= 11 | Package management |
| Python | >= 3.12 | MCP gateway runtime |
| uv | latest | Python package manager (for the gateway) |
| Git | any | Cloning repositories |
You also need:
- A Google AI API key (Google AI Studio) for the catalogue embeddings (
gemini-embedding-001) - A model provider: a Vercel AI Gateway key (
AI_GATEWAY_API_KEYwithUSE_AI_GATEWAY=1, as in production) or an Anthropic API key for the direct path - A Resend account with a verified sender domain for magic-link emails
- A PostgreSQL database: Neon in deployment; any Postgres URL works locally
# 1. Clone and start the MCP gateway
git clone https://github.com/Baffelan/sdmx-mcp-gateway.git
cd sdmx-mcp-gateway
uv sync
uv run python main_server.py --transport streamable-http --host 0.0.0.0 --port 8000
# 2. In another terminal — install and configure the dashboard builder
cd dashboarder
cp .env.example .env.local
# Edit .env.local — set at minimum:
# DATABASE_URL, NEXTAUTH_SECRET, RESEND_API_KEY, EMAIL_FROM, GOOGLE_AI_API_KEY, ENCRYPTION_SECRET,
# and either AI_GATEWAY_API_KEY + USE_AI_GATEWAY=1 or ANTHROPIC_API_KEY
npm install
# 3. Apply the database migrations
npx drizzle-kit migrate
# 4. Add yourself as the first admin user
npx tsx scripts/add-pilot-user.ts you@example.com --admin
# 5. Start the dev server
npm run dev
# 6. Open http://localhost:3000 — sign in via magic link, then open /builderThe /explore page and the agent's catalogue search use a pre-built index. A daily GitHub Action refreshes it; to rebuild locally (requires the MCP gateway and GOOGLE_AI_API_KEY):
npm run build-indexThis fetches the Pacific Data Hub dataflows, embeds their descriptions with Google's gemini-embedding-001, and writes models/dataflow-index.json.
| Path | What lives there |
|---|---|
app/ |
App Router pages (/, /builder, /explore, /gallery, /dashboard/[id], /p/[id], /settings, /admin, /about, /login, /countrysnapshots) and API routes under app/api/ (agent loop in app/api/chat/route.ts) |
components/ |
Client UI; PDH chrome in app-header.tsx, app-footer.tsx, brand-field.tsx |
lib/ |
Server logic: auth, model routing, MCP client and tool policy, dashboard schema/compiler/safety, retention, rate limiting, Drizzle schema (lib/db/), coverage, Country Snapshots |
drizzle/ |
SQL migrations generated by drizzle-kit |
models/ |
dataflow-index.json and dataflow-coverage.json, refreshed daily by CI |
scripts/ |
Index building, imports, user and key maintenance |
tests/ |
Vitest suites |
docs/ |
Architecture, technical reference, SPC IT review |
AGENTS.md has the detailed map, conventions and patterns.
flowchart TB
subgraph Browser["Browser — React 19"]
direction LR
subgraph Chat["Chat Panel"]
UC["useChat hook"]
Input["Message Input"]
Messages["Message List\n+ Markdown"]
end
subgraph Preview["Dashboard Preview"]
SDX["SDMXDashboard\nComponent"]
JSON["JSON Editor"]
Skel["Loading\nSkeleton"]
end
end
subgraph Auth["Auth Layer"]
NX["NextAuth\nmagic-link"]
MW["Middleware\nproxy.ts"]
end
subgraph Server["Next.js Server — /api/chat"]
ST["streamText()\nModel Router"]
UD["update_dashboard\ncustom tool"]
PS["prepareStep\nnudge at step 20"]
Cache["Prompt Cache\nTier 1 + Tier 2"]
end
subgraph ModelRouter["Model Router"]
direction TB
Gateway["Platform models\nVercel AI Gateway\n(zero data retention)"]
BYOK["BYOK key\n(Anthropic / OpenAI / Google / Mistral)"]
Env["Direct fallback\nAnthropic"]
end
subgraph DB["Neon Postgres (Sydney)"]
Sessions["dashboard_sessions"]
UsageLogs["usage_logs"]
ApiKeys["user_api_keys"]
AllowList["allowed_emails"]
end
subgraph Gateway["MCP Gateway — Railway"]
MCP["sdmx-mcp-gateway\n:8000/mcp"]
Tools["SDMx Tools\nlist_dataflows\nget_structure\nget_codes\nprobe_data_url\nbuild_data_url\n..."]
end
STAT[(".Stat API\nstats-sdmx-disseminate\n.pacificdata.org")]
Resend["Resend\nMagic-link email"]
Input -->|"user message"| UC
UC -->|"POST SSE"| ST
MW -->|"session cookie"| ST
NX -->|"verify token"| DB
NX -->|"send link"| Resend
Cache -.->|"cached prefix"| ST
PS -.->|"system prompt\noverride"| ST
ST --> ModelRouter
ModelRouter --> BYOK
ModelRouter --> Gateway
ModelRouter --> Env
ST -->|"tool calls\n(streamable-http + token)"| MCP
MCP --- Tools
ST --> UD
UD -->|"config in\ntool output"| UC
UC -->|"extract config"| SDX
ST -->|"text deltas"| Messages
ST -->|"usage"| UsageLogs
UC -->|"session save"| Sessions
SDX -->|"fetch data\n(client-side)"| STAT
Tools -->|"discover\nmetadata"| STAT
SDX -.->|"render errors"| UC
UC -.->|"auto-fix\nmessage"| ST
style Browser fill:#f7fafc,stroke:#e5e9eb,color:#181c1e
style Chat fill:#f1f4f6,stroke:#c0c7d0,color:#181c1e
style Preview fill:#ffffff,stroke:#c0c7d0,color:#181c1e
style Auth fill:#244445,stroke:#006970,color:#ffffff
style Server fill:#004467,stroke:#005c8a,color:#ffffff
style ModelRouter fill:#005c8a,stroke:#004467,color:#ffffff
style DB fill:#1a3a4a,stroke:#004467,color:#ffffff
style Gateway fill:#006970,stroke:#006970,color:#ffffff
style STAT fill:#f1f4f6,stroke:#c0c7d0,color:#181c1e
style Resend fill:#f1f4f6,stroke:#c0c7d0,color:#181c1e
- User visits the app —
proxy.tsmiddleware checks for a valid NextAuth session; unauthenticated users are redirected to/login - User requests a magic link; Resend delivers it; NextAuth verifies the token against
allowed_emailsand creates a session - User types a message in the chat panel
useChatPOSTs to/api/chatwith the session ID header; the route verifies the session via NextAuth- The model router selects a model: BYOK key first, then platform Gemini 3 Flash, then env fallback
streamTextcalls the model with MCP tools +update_dashboardcustom tool- The model does progressive discovery via MCP (
list_dataflows→get_dataflow_structure→get_dimension_codes→build_data_url→probe_data_url→suggest_nonempty_queriesif empty) probe_data_urlvalidates a built URL before the model emits a dashboard, andsuggest_nonempty_queriesrecovers empty probes without the model guessing relaxations- The model calls
update_dashboardwith an authoring schema config; the server compiles it to native config - Tool output flows back to the client via the SSE stream
- Client extracts config from tool output in message parts
SDMXDashboardrenders the config, fetching live data directly from .Stat- If rendering fails, the error is debounced and automatically sent back to the AI
- Usage (tokens, steps, model) is logged to
usage_logs; session messages/config are saved todashboard_sessions
- OAuth (Google, Microsoft, GitHub), email magic-link via Resend, and passwords
- Admission: an
allowed_domainsrule, theallowed_emailsinvite list, or a provider opened inAUTH_OPEN_SIGNUP_PROVIDERS - Self-service password signup/reset proved by an inbound email (DMARC pass + exact From), no mail sent to the user
- All routes protected by NextAuth middleware (
proxy.ts) - Admin role for invite and user management
- Platform models: OpenAI, Anthropic and Google models through Vercel AI Gateway, with zero data retention and no prompt training requested on every call (
lib/platform-models.ts) - BYOK (Bring Your Own Key): users can add Anthropic, OpenAI, Google or Mistral API keys in
/settings; keys are encrypted at rest with AES-256-GCM - Model picker in the builder header to switch provider/model mid-session
- Model router (
lib/model-router.ts): a readable BYOK key takes priority, then platform models through the gateway, then the direct Anthropic path when the gateway is off
- Natural language requests produce live SDMx dashboards
- AI proposes structure for complex requests, builds panel-by-panel
- Multi-turn conversation to refine charts, add panels, change data
- The AI emits simplified intent visuals (
kpi,chart,map,note) rather than raw native configs - Server-side compiler (
lib/dashboard-authoring.ts) translates intent visuals to the nativesdmx-dashboard-componentsconfig format - Native passthrough (
mode: "native") available for advanced cases - Zod schema validates tool input before compilation
probe_data_urlMCP tool validates a candidate SDMx data URL before dashboard emission- Catches empty results, malformed keys, and missing dimensions early in the agent loop
- Reduces the feedback-loop round-trips caused by bad URLs reaching the live preview
- Real-time dashboard rendering via SDMXDashboard component
- Syntax-highlighted JSON editor with inline editing and apply/reset
- Loading skeleton matching the dashboard grid layout
- Conversation history, dashboard config, and undo stack saved to Postgres per user
- Survives page refresh and works across devices
- Session list on the welcome page; up to 20 sessions per user
- Sessions auto-titled from the first user message
- Every dashboard update (AI or manual) pushes to a 50-entry history stack
- Undo/redo buttons in the preview header
- History persisted in the database session record
- Invite management: add/remove emails from the allowlist
- User list with role badges, session count, and token usage
- Role toggle (user/admin) per user
- Accessible only to users with
role = 'admin'
- Store one API key per provider (Anthropic, OpenAI, Google)
- Select preferred model per provider
- Keys encrypted server-side before storage; never logged
- Data catalogue browser listing all SDMx dataflows on Pacific Data Hub
- Short queries use keyword filtering; three or more words trigger semantic search
- Semantic search compares the query's
gemini-embedding-001embedding (Google) with the pre-built index, so the search phrase is sent to Google - Country filter shows which dataflows have data for a selected Pacific territory
| Format | File | Offline | Interactive |
|---|---|---|---|
.pdf |
Yes | No | |
| HTML (static) | .html |
Yes | No |
| HTML (live) | -live.html |
No | Yes |
| JSON Config | .json |
Yes | N/A |
- Per-panel render status and typed error codes from the library (no crashes)
- Uncaught fetch failures still caught via
unhandledrejectionas a safety net - Errors debounced, deduplicated, and auto-sent to AI as system messages
- AI attempts to fix the dashboard config and re-emit; max 2 auto-retries
- Conversation history scanned for already-discovered dataflows and URLs
- Compact summary injected into the system prompt each turn
- Prevents redundant MCP discovery calls, saving tokens and steps
- Every chat request is written to the
usage_logstable in Postgres (session ID, user, tokens, model, duration) - The
logs/directory is legacy from the earlier JSONL logger and is no longer the active logging backend
Copy .env.example to .env.local and fill in the values; every variable is commented there. docs/technical-reference.md §19 groups them by purpose for production.
npm run dev # Start dev server (Turbopack)
npm run build # Production build (Webpack)
npm run lint # ESLint
npm run test # Vitest suite
npm run build-index # Build semantic search index (requires the MCP gateway)Tests use Vitest and live in tests/ (one file per lib/ module, plus tests/country-snapshots/). CI runs lint, tests and the build on every pull request and push to main.
proxy.ts at the project root is the Auth.js middleware. It protects every route except the public ones listed in its matcher (sign-in, about, gallery, published dashboards, public APIs, the SDMx relay, Country Snapshots, training and the cron route).
npx drizzle-kit generate # Generate migration SQL from lib/db/schema.ts
npx drizzle-kit migrate # Apply pending migrations (records them in drizzle.__drizzle_migrations)
npx drizzle-kit studio # Open Drizzle Studio to browse dataBack up production before migrating it; see the release procedure in docs/technical-reference.md §19.
The schema is defined in lib/db/schema.ts; docs/current-architecture.md §5 describes the persistence model.
Production (sdmxsurfer.net) builds from main; the development deployment (sdmx-surfer.vercel.app) builds from dev. Functions run in Sydney (vercel.json), next to the Neon database. See docs/technical-reference.md §19 for services, environment variables and the release procedure. To create the first admin user:
npx tsx scripts/add-pilot-user.ts admin@example.com --admin- Create a new Railway project and add a service from the
sdmx-mcp-gatewayGitHub repo - Set the start command:
uv run python main_server.py --transport streamable-http --host 0.0.0.0 --port 8000 - Set the
MCP_AUTH_TOKENenvironment variable in Railway (any strong random string) - Note the Railway service's public URL; set
MCP_GATEWAY_URL=https://<railway-url>/mcpin Vercel - Set the same
MCP_AUTH_TOKENvalue in Vercel so the Next.js app can authenticate to the gateway
The UI follows the Pacific Data Hub visual identity (guidelines V1.0, 2025); see docs/pdh-visual-alignment.md. Tokens live in app/globals.css and are mirrored in lib/brand-theme.ts. The earlier "Oceanic Data-Scapes" mockups in stitch_assets/ are superseded.
The session cookie is missing or expired. Sign out and sign in again via the magic-link flow at /login.
Ensure Python >= 3.12 and uv are installed. Run uv sync before starting.
Check that RESEND_API_KEY is set and EMAIL_FROM is a verified Resend sender. In development, Resend delivers to real addresses — there is no local preview mode.
The data URL is malformed or returned no data. The error is auto-sent to the AI for fixing. Check that probe_data_url is being used before update_dashboard — the system prompt instructs the agent to probe first.
The index is missing or stale, or GOOGLE_AI_API_KEY is not set (queries are embedded at request time). Run npm run build-index with the MCP gateway running.
Check the browser Network tab — SDMx REST requests to stats-sdmx-disseminate.pacificdata.org may be failing (CORS or network).
rm -rf .next && npm run devEnsure DATABASE_URL is set and the Neon branch is reachable. Use the direct (non-pooler) connection string for drizzle-kit migrate and pg_dump.
See docs/current-architecture.md for the implemented route/access/publication model, and docs/technical-reference.md for lower-level technical internals and module descriptions.
Copyright 2026 The Pacific Community (SPC). This project is licensed for noncommercial use, with two licenses covering different parts:
- Source code (the application and its scripts): PolyForm Noncommercial
License 1.0.0. See
LICENSE. - Documentation, specifications, and design assets (
docs/, the top-level architecture/spec documents,stitch_assets/): Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0). SeeLICENSE-DOCS.
Both require attribution to The Pacific Community (SPC) and prohibit commercial
use. Lead developer: Giulio Valentino Dalla Riva (SDD, SPC); copyright is held
by SPC. See AUTHORS for credits.
See dashboard-architecture.md for project context and phased delivery plan.