GridWatch MCP
by mohithchow
README.md
# GridWatch MCP
**An MCP interface layer for a distributed industrial asset platform.**
Industrial operators — battery energy storage sites, EV charger networks, solar
arrays, IoT sensor fleets — manage assets spread across geography, with health,
telemetry, and alert data usually locked behind a dashboard. GridWatch exposes
that operational data to AI assistants via the [Model Context Protocol
(MCP)](https://modelcontextprotocol.io), so instead of clicking through charts,
an engineer can ask Claude *"which sites near Aachen have critical alerts?"*
and get a live, tool-backed answer grounded in real data.
This is a demo/portfolio build: the platform and its data are synthetic, but
the MCP server, auth, geospatial queries, and data model are real and meant to
mirror how an actual industrial platform would expose itself as an MCP server.
▶ **Live demo:** https://map-beta-plum.vercel.app
▶ **MCP endpoint:** `https://map-beta-plum.vercel.app/api/mcp` (Streamable HTTP transport, bearer-token auth)
---
## Why this exists
Model Context Protocol is a young interface layer between AI assistants and
software platforms — the patterns for *how* an industrial platform should
expose itself (which operations, what auth model, what the tool surface looks
like) are still forming. This project is my attempt to work through that
problem concretely: design a tool surface for a real operational domain
(distributed energy/industrial assets), and build it to a standard where
security, latency, and scale are treated as first-class constraints, not
afterthoughts.
## Architecture
```mermaid
flowchart LR
subgraph Client["AI Assistant"]
C[Claude / any MCP client]
end
subgraph Vercel["Vercel — Fluid Compute"]
MCP["/api/mcp\nStreamable HTTP handler"]
Auth["Bearer-token auth\n(withMcpAuth)"]
RateLimit["Rate limiter\n(sliding window)"]
Dash["/ dashboard\n(Next.js RSC)"]
MCP --> Tools
subgraph Tools["MCP Tools"]
T1[get_asset_status]
T2[find_assets_near]
T3[list_alerts]
T4[explain_anomaly]
T5[simulate_load]
end
end
subgraph DB["Neon Postgres + PostGIS"]
Assets[(assets)]
Telemetry[(telemetry_readings)]
Alerts[(alerts)]
end
C -- "JSON-RPC over HTTPS" --> RateLimit --> Auth --> MCP
Dash --> Assets
Dash --> Telemetry
Dash --> Alerts
Tools --> Assets
Tools --> Telemetry
Tools --> Alerts
```
**Stack:**
- **Next.js (App Router)** on Vercel Fluid Compute — one deployable for both
the MCP server and the human-facing dashboard
- **`mcp-handler`** — wraps the official MCP SDK as a Web-standard
`Request → Response` handler; handles the Streamable HTTP transport and
bearer-token auth (`withMcpAuth`)
- **Neon Postgres + PostGIS** — relational data plus real geospatial queries
(`ST_DWithin`, `ST_Distance`) for the `find_assets_near` tool
- **Drizzle ORM** — typed schema and queries
- **Leaflet** — the human-facing map view (not part of the MCP surface itself)
## MCP tool surface
| Tool | Purpose |
|---|---|
| `get_asset_status` | Current status + latest telemetry for one asset, by external ID |
| `find_assets_near` | Geospatial radius search (PostGIS `ST_DWithin`), optional asset-type filter |
| `list_alerts` | Fleet-wide alert feed, filterable by severity/category/resolution state |
| `explain_anomaly` | Root-cause explanation for one alert, grounded in surrounding telemetry |
| `simulate_load` | Deterministic what-if projection under a named stress scenario |
Each tool call is authenticated, rate-limited, and logged — see
[Security, latency, scale](#security-latency-scale) below.
## Data model
```mermaid
erDiagram
assets ||--o{ telemetry_readings : has
assets ||--o{ alerts : raises
assets {
int id PK
text external_id UK
text name
text asset_type
double latitude
double longitude
text status
}
telemetry_readings {
bigint id PK
int asset_id FK
timestamp recorded_at
double soc_percent
double temperature_c
double voltage
double health_score
}
alerts {
int id PK
int asset_id FK
text event_id UK
int severity
text category
text message
boolean resolved
}
```
35 synthetic assets are seeded across 9 European cities (battery storage, EV
chargers, solar arrays, IoT sensors), each with ~48 hours of hourly telemetry
and a realistic spread of alerts. See `scripts/seed.ts`.
## Security, latency, scale
This is the part of the ACCURE thesis prompt ("evaluated for security,
latency, and scale") I tried to take seriously rather than hand-wave:
**Security**
- Every tool call requires a bearer token, verified via `withMcpAuth` before
the request reaches any tool (`src/app/api/mcp/route.ts`)
- Input validation on every tool via Zod schemas — the MCP layer rejects
malformed calls before they touch the database
- No raw SQL string interpolation — all queries go through Drizzle or Neon's
parameterized tagged templates, including the PostGIS raw-SQL queries
**Latency**
- Neon's HTTP driver (`@neondatabase/serverless`) avoids TCP connection
setup cost per request, which matters on serverless/Fluid Compute where
instances scale to zero
- Vercel Fluid Compute reuses warm instances across requests instead of
cold-starting per call, which is the main latency lever at this scale
**Scale**
- The rate limiter (`src/lib/rate-limit.ts`) is in-memory and documented as
such — it's effective per-instance under Fluid Compute's instance reuse,
but not distributed. The honest note in that file explains exactly what
would change (swap for Upstash Redis + `@upstash/ratelimit`) to make it
correct across many concurrent instances.
- `list_alerts` and `find_assets_near` cap result sets (50/100 rows) rather
than returning unbounded fleets — a real platform integration needs
pagination once fleets grow past a few thousand assets, which this
intentionally punts on for demo scope.
## Running locally
```bash
npm install
vercel env pull .env.local # or copy .env.local from your own Neon/Vercel setup
npx dotenv -e .env.local -- npx tsx scripts/enable-postgis.ts
npx dotenv -e .env.local -- npx drizzle-kit generate
npx dotenv -e .env.local -- npx drizzle-kit migrate
npx dotenv -e .env.local -- npx tsx scripts/seed.ts
npx dotenv -e .env.local -- npm run dev
```
Set `MCP_API_KEY` in `.env.local` — it's the bearer token required to call
`/api/mcp`. Without it set, local dev falls back to an open (logged-loudly)
mode so `npm run dev` works out of the box; production deployments should
always set it.
## Connecting an MCP client
```json
{
"mcpServers": {
"gridwatch": {
"url": "https://<your-deployment>.vercel.app/api/mcp",
"headers": { "Authorization": "Bearer <MCP_API_KEY>" }
}
}
}
```
## What I'd build next
- Distributed rate limiting (Upstash Redis) for true multi-instance correctness
- OAuth/CIMD-based auth instead of a static bearer token, for multi-tenant access
- Pagination on `list_alerts` / `find_assets_near`
- A real anomaly-detection model behind `explain_anomaly` (currently
rule-based heuristics per alert category) — natural extension of prior work
on [smart-building-fault-detection](https://github.com/mohithchow/smart-building-fault-detection)
This server cannot be deployed
Maintenance
ActivitySlowing
ResponsivenessNo issues