From 5a16cb4c0656e5fca4b84c8bd648881d35965851 Mon Sep 17 00:00:00 2001 From: robbertjanssen85 <91183957+robbertjanssen85@users.noreply.github.com> Date: Thu, 23 Apr 2026 14:52:51 +0200 Subject: [PATCH] Add REST API, MCP server, OpenAPI/ReDoc docs, and client connect page - /api/v1/* REST endpoints: health, model catalog (vehicles, functions, distributions, profiles, defaults), and simulate. Accepts functionCounts and/or functionBvoM2 (auto-converted via DEFAULT_BVO_PER_UNIT). Runs 2500 Monte Carlo iterations by default; response adds a labeled `summary` (totalLengthM, totalAreaM2, per-vehicle + per-cluster) alongside the raw SimulationResult. - /api/mcp Streamable-HTTP MCP endpoint (hand-rolled JSON-RPC 2.0, no new deps). Tools: get_model_info, list_vehicles/functions/distributions, get_delivery_profile, run_simulation. - /api/v1/openapi.json + /api-docs: OpenAPI 3.0.3 spec rendered with ReDoc, themed to DMI palette + IBM Plex typography, DMI logo in the sidebar. - /mcp-connect: DMI-styled page with copy-paste config blocks for Claude Code, Claude Desktop, Cursor, Codex CLI, Windsurf, and VS Code. MCP URL substituted from window.location.origin. - Cover page gets an "Integraties" section with pill buttons linking to API-referentie and MCP instellen. Co-Authored-By: Claude Opus 4.7 (1M context) --- README.md | 6 + docs/API.md | 180 +++++ docs/MCP.md | 97 +++ src/app/api-docs/route.ts | 286 ++++++++ src/app/api/mcp/route.ts | 245 +++++++ src/app/api/v1/health/route.ts | 16 + src/app/api/v1/model/distributions/route.ts | 12 + src/app/api/v1/model/functions/route.ts | 12 + src/app/api/v1/model/profiles/route.ts | 36 + src/app/api/v1/model/route.ts | 36 + src/app/api/v1/model/vehicles/route.ts | 12 + src/app/api/v1/openapi.json/route.ts | 12 + src/app/api/v1/simulate/route.ts | 45 ++ src/app/mcp-connect/route.ts | 335 ++++++++++ src/components/layouts/DmiCockpitLayout.tsx | 42 +- src/components/layouts/WebappLayout.tsx | 42 +- src/lib/api/cors.ts | 26 + src/lib/api/mcp-tools.ts | 177 +++++ src/lib/api/openapi.ts | 706 ++++++++++++++++++++ src/lib/api/summary.ts | 59 ++ src/lib/api/validate.ts | 239 +++++++ src/lib/content.ts | 10 + 22 files changed, 2629 insertions(+), 2 deletions(-) create mode 100644 docs/API.md create mode 100644 docs/MCP.md create mode 100644 src/app/api-docs/route.ts create mode 100644 src/app/api/mcp/route.ts create mode 100644 src/app/api/v1/health/route.ts create mode 100644 src/app/api/v1/model/distributions/route.ts create mode 100644 src/app/api/v1/model/functions/route.ts create mode 100644 src/app/api/v1/model/profiles/route.ts create mode 100644 src/app/api/v1/model/route.ts create mode 100644 src/app/api/v1/model/vehicles/route.ts create mode 100644 src/app/api/v1/openapi.json/route.ts create mode 100644 src/app/api/v1/simulate/route.ts create mode 100644 src/app/mcp-connect/route.ts create mode 100644 src/lib/api/cors.ts create mode 100644 src/lib/api/mcp-tools.ts create mode 100644 src/lib/api/openapi.ts create mode 100644 src/lib/api/summary.ts create mode 100644 src/lib/api/validate.ts diff --git a/README.md b/README.md index e215bc4..f528ad8 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,12 @@ Open [http://localhost:3000](http://localhost:3000) with your browser to see the You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. +## External integrations + +- **REST API** — see [`docs/API.md`](docs/API.md). JSON endpoints under `/api/v1/*` for model metadata and running simulations. +- **OpenAPI spec** — machine-readable at `/api/v1/openapi.json`; human-readable ReDoc view at `/api-docs`. +- **MCP server** — see [`docs/MCP.md`](docs/MCP.md). Model Context Protocol endpoint at `/api/mcp` for AI agents. + This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. ## Learn More diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..fca78ab --- /dev/null +++ b/docs/API.md @@ -0,0 +1,180 @@ +# Ruimtemodel Stadslogistiek — REST API + +External systems can drive the Monte Carlo simulation engine and read the +model catalog via a JSON REST API. + +All endpoints: +- Return `application/json`. +- Send permissive CORS headers (`Access-Control-Allow-Origin: *`), so browser + clients on any origin may call them. +- Are read-only or idempotent — no authentication is required. The simulation + endpoint caps `numSimulations` at 5000 to bound cost. + +Base path: `/api/v1` + +**Machine-readable spec:** [`/api/v1/openapi.json`](../src/lib/api/openapi.ts) (OpenAPI 3.0.3) +**Rendered reference:** `/api-docs` (ReDoc) — also works in Redocly's hosted service and `redocly preview-docs` against the JSON URL. + +--- + +## Health + +``` +GET /api/v1/health +``` + +Response: +```json +{ "status": "ok", "service": "ruimtemodel-api", "version": "1.0.0", "timestamp": "…" } +``` + +--- + +## Model catalog + +### Full catalog + +``` +GET /api/v1/model +``` + +Returns vehicles, functions, distributions, periods, service levels, default +cluster assignments, default cluster service levels, simulation parameters, +loading-bay width, and all delivery profiles. + +### Individual resources + +``` +GET /api/v1/model/vehicles → { vehicles: [...] } +GET /api/v1/model/functions → { functions: [...] } +GET /api/v1/model/distributions → { distributions: [...] } +GET /api/v1/model/profiles → { profiles: { "F1_D7": {...}, … } } +``` + +The `profiles` endpoint also accepts query parameters: + +``` +GET /api/v1/model/profiles?function=F1 # filter by function +GET /api/v1/model/profiles?distribution=D7 # filter by distribution +GET /api/v1/model/profiles?function=F1&distribution=D7 # exact match → { key, profile } +``` + +--- + +## Run simulation + +``` +POST /api/v1/simulate +Content-Type: application/json +``` + +Supply either **number of units** or **BVO in m²** per function (or mix the two +— one mode per function). The simulation runs **2500 Monte Carlo iterations by +default**. Every other field has a sensible default. + +Minimal body (units): +```json +{ "functionCounts": { "F1": 362, "F2": 2, "F10": 5 } } +``` + +Minimal body (BVO): +```json +{ "functionBvoM2": { "F1": 32580, "F10": 6250 } } +``` + +All fields: +```json +{ + "functionCounts": { "F1": 362 }, // units per function + "functionBvoM2": { "F10": 6250 }, // OR BVO (m²) per function + "bvoPerUnit": { "F1": 90 }, // optional override for BVO→units conversion + "clusterAssignments": { "V1": 1, "V2": 1, "V3": 2 }, // optional, defaults to DEFAULT_CLUSTERS + "clusterServiceLevels": { "1": 0.95, "2": 0.95 }, // optional, defaults to 0.95 per cluster + "numSimulations": 2500, // optional, default 2500, max 5000 + "vehicles": [...], // optional override + "functions": [...], // optional override + "distributions": [...], // optional override + "vehicleLengths": { "V1": 2 }, // optional override + "deliveryDays": { "D7": 6 }, // optional override + "deliveryProfiles": { "F1_D7": {...} }, // optional override/merge + "intervalMinutes": 10 // optional override +} +``` + +At least one of `functionCounts` or `functionBvoM2` must be provided. A single +function may **not** appear in both — choose one mode per function. + +Response: +```json +{ + "summary": { + "loadingBayWidthM": 3, + "totalLengthM": 27.4, + "totalAreaM2": 82.2, + "vehicles": [ + { + "vehicleId": "V3", + "vehicleName": "Bestelwagen <3,5 ton (N1)", + "vehicleLengthM": 8, + "clusterId": 2, + "totalArrivalsPerDay": 86.1, + "requiredLengthM": 16, + "requiredAreaM2": 48 + } + ], + "clusters": [ + { "clusterId": 1, "serviceLevel": 0.95, "vehicleIds": ["V1","V2"], "requiredLengthM": 0, "requiredAreaM2": 0 }, + { "clusterId": 2, "serviceLevel": 0.95, "vehicleIds": ["V3","V4","V5"], "requiredLengthM": 24, "requiredAreaM2": 72 } + ] + }, + "result": { + "vehicleResults": [ { "vehicleId": "V1", "requiredSpaceM2": 4.0, … } ], + "clusterResults": [ { "clusterId": 1, "totalSpaceM2": 14.2, … } ], + "totalSpaceM2": 27.4, + "peakByPeriod": [ { "period": "0:00 - 6:00", "space": 0 }, … ], + "serviceLevelCurve": [ { "serviceLevel": 0.5, "space": 8.1 }, … ] + }, + "meta": { + "numSimulations": 2500, + "inputCounts": { "F1": 362, "F10": 5 }, + "durationMs": 312 + } +} +``` + +`summary` is the recommended consumer field — lengths and areas are clearly +labeled. The `result` block preserves the raw engine output for callers that +need it. Note: the field names `totalSpaceM2` and `requiredSpaceM2` inside +`result` are legacy — they hold **length in meters**, not area. Multiply by +`summary.loadingBayWidthM` (3) for actual m². + +Errors: +- `400` — invalid input, with `{ "error": "…" }` describing what was wrong. +- `500` — internal error (should not happen; file a bug). + +### Example + +```bash +curl -X POST https://your-host/api/v1/simulate \ + -H 'Content-Type: application/json' \ + -d '{ "functionBvoM2": { "F1": 32580, "F2": 3000 } }' +``` + +--- + +## Notes on IDs + +- Vehicles: `V1` (fiets/cargobike) … `V6` (service bestelwagen) — see + `/api/v1/model/vehicles`. +- Functions: `F1` (woningen) … `F12` (kantoor groot) — see + `/api/v1/model/functions`. +- Distributions: `D1` (afval bedrijven) … `D15` (verhuizingen) — see + `/api/v1/model/distributions`. +- Cluster IDs are integers ≥ 1 chosen by the caller. Vehicles sharing a + cluster share physical space; each cluster has its own service level. + +## Notes on the model + +See `CLAUDE.md` and `src/lib/simulation.ts` for an in-depth description of +the Monte Carlo model, including how arrival probabilities are computed and +how percentile analysis converts per-iteration peaks into a required space. diff --git a/docs/MCP.md b/docs/MCP.md new file mode 100644 index 0000000..f26128a --- /dev/null +++ b/docs/MCP.md @@ -0,0 +1,97 @@ +# Ruimtemodel Stadslogistiek — MCP server + +The webapp exposes a [Model Context Protocol](https://modelcontextprotocol.io/) +server so AI agents (Claude Desktop, Claude Code, Cursor, IDE plugins, custom +LLM clients, …) can inspect the model and run simulations. + +- **Transport:** Streamable HTTP (JSON-RPC 2.0 over HTTPS). +- **Endpoint:** `POST /api/mcp` +- **Protocol version:** `2025-03-26` +- **Auth:** none (public, read/compute only). + +`GET /api/mcp` returns a small discovery document useful when hitting the URL +in a browser. + +**Quickest way to wire up a client:** open **[`/mcp-connect`](/mcp-connect)** +— it renders ready-to-paste config blocks for Claude Desktop, Claude Code, +Cursor, Codex CLI, Windsurf, and VS Code, with the deployed MCP URL already +filled in and a Copy button per block. + +--- + +## Tools + +| Name | Purpose | +| ---------------------- | ---------------------------------------------------------------- | +| `get_model_info` | Full metadata: vehicles, functions, distributions, defaults. | +| `list_vehicles` | 6 vehicle types with length in meters. | +| `list_functions` | 12 urban function types. | +| `list_distributions` | 15 distribution / delivery profile types. | +| `get_delivery_profile` | Look up one delivery profile by function + distribution ID. | +| `run_simulation` | Run the Monte Carlo simulation; see REST API for input schema. | + +Each tool's `inputSchema` is returned by the standard `tools/list` method. + +--- + +## Connecting from Claude Desktop / Claude Code + +Claude clients speak MCP natively but (as of early 2026) the built-in stdio +client is what most people use. To bridge stdio ↔ HTTP use `mcp-remote`: + +```jsonc +// claude_desktop_config.json +{ + "mcpServers": { + "ruimtemodel": { + "command": "npx", + "args": ["-y", "mcp-remote", "https://your-host/api/mcp"] + } + } +} +``` + +For Claude Code, run: + +```bash +claude mcp add --transport http ruimtemodel https://your-host/api/mcp +``` + +## Connecting from a custom MCP client + +Any client that speaks the Streamable HTTP transport can connect by POSTing +JSON-RPC 2.0 requests to `/api/mcp`. Minimal handshake: + +```bash +# 1. initialize +curl -s -X POST https://your-host/api/mcp \ + -H 'Content-Type: application/json' \ + -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"example","version":"0.1"}}}' + +# 2. list tools +curl -s -X POST https://your-host/api/mcp \ + -H 'Content-Type: application/json' \ + -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' + +# 3. call run_simulation +curl -s -X POST https://your-host/api/mcp \ + -H 'Content-Type: application/json' \ + -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"run_simulation","arguments":{"functionCounts":{"F1":362,"F2":2},"numSimulations":1000}}}' +``` + +`tools/call` responses wrap the tool output in a `content[]` array containing +a single `{type: "text", text: ""}` entry per the MCP spec. The +JSON string is the same shape the REST API returns for `/api/v1/simulate`. + +--- + +## Notes / limits + +- The server is stateless — every request is independent; no Mcp-Session-Id + is required. Clients that send one will get it echoed back. +- `numSimulations` is capped at 5000 to keep response times under a minute. +- Resources and prompts are not implemented; every capability is exposed as + a tool. + +See `src/app/api/mcp/route.ts` for the JSON-RPC dispatch logic and +`src/lib/api/mcp-tools.ts` for tool definitions. diff --git a/src/app/api-docs/route.ts b/src/app/api-docs/route.ts new file mode 100644 index 0000000..e5ac3f7 --- /dev/null +++ b/src/app/api-docs/route.ts @@ -0,0 +1,286 @@ +/** + * Renders the OpenAPI spec at /api/v1/openapi.json using ReDoc. + * + * Served as a Route Handler (not a Page) so it escapes the root layout and + * owns the full viewport. Styled to match the DMI palette and IBM Plex + * typography used by the rest of the app (see src/lib/dmi-theme.ts). + * + * Theming has three layers: + * 1. `redocTheme` — ReDoc's own theme object (colors, typography, sidebar). + * 2. `x-logo` in the OpenAPI spec — puts the DMI logo in the sidebar. + * 3. A small + + + +
+ + + + +`; + +export function GET() { + return new Response(html, { + status: 200, + headers: { + 'Content-Type': 'text/html; charset=utf-8', + 'Cache-Control': 'public, max-age=300', + }, + }); +} diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.ts new file mode 100644 index 0000000..78a7a16 --- /dev/null +++ b/src/app/api/mcp/route.ts @@ -0,0 +1,245 @@ +import { MCP_TOOLS, MCP_TOOLS_BY_NAME } from '@/lib/api/mcp-tools'; +import { corsPreflight, corsRaw } from '@/lib/api/cors'; + +/** + * Model Context Protocol (MCP) endpoint — Streamable HTTP transport. + * + * This implements a minimal compliant MCP server over HTTP using JSON-RPC 2.0. + * It supports both single requests/responses and batched requests. + * + * Spec reference: + * https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http + * + * Supported methods: + * - initialize + * - ping + * - tools/list + * - tools/call + * - notifications/initialized (no response, per spec) + * + * Resources and prompts are not implemented; clients that require them should + * fall back to tools (every resource is also exposed as a tool). + * + * Transport: we return plain `application/json` responses. The spec also + * permits `text/event-stream`, but this stateless handler has no server- + * initiated messages, so simple JSON is sufficient and widely supported. + */ + +export const runtime = 'nodejs'; +export const maxDuration = 60; + +const PROTOCOL_VERSION = '2025-03-26'; + +const SERVER_INFO = { + name: 'ruimtemodel-stadslogistiek', + version: '1.0.0', +}; + +const CAPABILITIES = { + tools: { listChanged: false }, +}; + +interface JsonRpcRequest { + jsonrpc: '2.0'; + id?: string | number | null; + method: string; + params?: unknown; +} + +interface JsonRpcSuccess { + jsonrpc: '2.0'; + id: string | number | null; + result: unknown; +} + +interface JsonRpcError { + jsonrpc: '2.0'; + id: string | number | null; + error: { code: number; message: string; data?: unknown }; +} + +type JsonRpcResponse = JsonRpcSuccess | JsonRpcError; + +const ERROR_CODES = { + PARSE_ERROR: -32700, + INVALID_REQUEST: -32600, + METHOD_NOT_FOUND: -32601, + INVALID_PARAMS: -32602, + INTERNAL_ERROR: -32603, +}; + +function isJsonRpcRequest(x: unknown): x is JsonRpcRequest { + return ( + typeof x === 'object' && + x !== null && + (x as { jsonrpc?: unknown }).jsonrpc === '2.0' && + typeof (x as { method?: unknown }).method === 'string' + ); +} + +function success(id: string | number | null, result: unknown): JsonRpcSuccess { + return { jsonrpc: '2.0', id, result }; +} + +function failure( + id: string | number | null, + code: number, + message: string, + data?: unknown, +): JsonRpcError { + return { jsonrpc: '2.0', id, error: { code, message, ...(data !== undefined && { data }) } }; +} + +function handleRequest(req: JsonRpcRequest): JsonRpcResponse | null { + const id = req.id ?? null; + + // Notifications (no id) get no response. + const isNotification = req.id === undefined || req.id === null; + + try { + switch (req.method) { + case 'initialize': { + // Client supplies { protocolVersion, capabilities, clientInfo }. We ignore + // the requested protocolVersion and reply with our supported version; the + // client is responsible for compatibility. Per spec we may negotiate, but + // sticking to one version keeps this server simple. + if (isNotification) return null; + return success(id, { + protocolVersion: PROTOCOL_VERSION, + capabilities: CAPABILITIES, + serverInfo: SERVER_INFO, + }); + } + case 'notifications/initialized': { + return null; + } + case 'ping': { + if (isNotification) return null; + return success(id, {}); + } + case 'tools/list': { + if (isNotification) return null; + return success(id, { + tools: MCP_TOOLS.map((t) => ({ + name: t.name, + description: t.description, + inputSchema: t.inputSchema, + })), + }); + } + case 'tools/call': { + if (isNotification) return null; + const params = (req.params ?? {}) as { name?: unknown; arguments?: unknown }; + if (typeof params.name !== 'string') { + return failure(id, ERROR_CODES.INVALID_PARAMS, 'tools/call requires params.name (string)'); + } + const tool = MCP_TOOLS_BY_NAME[params.name]; + if (!tool) { + return failure(id, ERROR_CODES.METHOD_NOT_FOUND, `Unknown tool: ${params.name}`); + } + const args = (params.arguments ?? {}) as Record; + try { + const out = tool.handler(args); + return success(id, { + content: [{ type: 'text', text: JSON.stringify(out) }], + isError: false, + }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + return success(id, { + content: [{ type: 'text', text: message }], + isError: true, + }); + } + } + default: { + if (isNotification) return null; + return failure(id, ERROR_CODES.METHOD_NOT_FOUND, `Unknown method: ${req.method}`); + } + } + } catch (err) { + if (isNotification) return null; + const message = err instanceof Error ? err.message : String(err); + return failure(id, ERROR_CODES.INTERNAL_ERROR, message); + } +} + +export async function POST(request: Request) { + let body: unknown; + try { + body = await request.json(); + } catch { + return corsRaw( + JSON.stringify(failure(null, ERROR_CODES.PARSE_ERROR, 'Invalid JSON')), + { status: 400, headers: { 'Content-Type': 'application/json' } }, + ); + } + + // Handle batched requests + if (Array.isArray(body)) { + if (body.length === 0) { + return corsRaw( + JSON.stringify(failure(null, ERROR_CODES.INVALID_REQUEST, 'Empty batch')), + { status: 400, headers: { 'Content-Type': 'application/json' } }, + ); + } + const responses: JsonRpcResponse[] = []; + for (const item of body) { + if (!isJsonRpcRequest(item)) { + const id = (item as { id?: string | number | null } | null)?.id ?? null; + responses.push(failure(id, ERROR_CODES.INVALID_REQUEST, 'Invalid JSON-RPC request')); + continue; + } + const res = handleRequest(item); + if (res) responses.push(res); + } + // If every request was a notification, respond 202 with empty body per spec. + if (responses.length === 0) { + return corsRaw(null, { status: 202 }); + } + return corsRaw(JSON.stringify(responses), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + } + + if (!isJsonRpcRequest(body)) { + return corsRaw( + JSON.stringify(failure(null, ERROR_CODES.INVALID_REQUEST, 'Invalid JSON-RPC request')), + { status: 400, headers: { 'Content-Type': 'application/json' } }, + ); + } + + const response = handleRequest(body); + if (!response) { + // Notification — no body, 202 Accepted per spec. + return corsRaw(null, { status: 202 }); + } + + return corsRaw(JSON.stringify(response), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); +} + +export function GET() { + // The Streamable HTTP transport allows GET for server-initiated SSE streams. + // This server is stateless and has no such stream, so we return a small + // discovery payload to help humans who hit the URL in a browser. + return corsRaw( + JSON.stringify({ + service: SERVER_INFO.name, + version: SERVER_INFO.version, + protocolVersion: PROTOCOL_VERSION, + transport: 'streamable-http', + endpoint: '/api/mcp', + method: 'POST with JSON-RPC 2.0 body', + tools: MCP_TOOLS.map((t) => t.name), + }), + { status: 200, headers: { 'Content-Type': 'application/json' } }, + ); +} + +export function OPTIONS() { + return corsPreflight(); +} diff --git a/src/app/api/v1/health/route.ts b/src/app/api/v1/health/route.ts new file mode 100644 index 0000000..c16d82a --- /dev/null +++ b/src/app/api/v1/health/route.ts @@ -0,0 +1,16 @@ +import { corsPreflight, withCors } from '@/lib/api/cors'; + +export const runtime = 'nodejs'; + +export function GET() { + return withCors({ + status: 'ok', + service: 'ruimtemodel-api', + version: '1.0.0', + timestamp: new Date().toISOString(), + }); +} + +export function OPTIONS() { + return corsPreflight(); +} diff --git a/src/app/api/v1/model/distributions/route.ts b/src/app/api/v1/model/distributions/route.ts new file mode 100644 index 0000000..501d066 --- /dev/null +++ b/src/app/api/v1/model/distributions/route.ts @@ -0,0 +1,12 @@ +import { DISTRIBUTIONS } from '@/lib/model-data'; +import { corsPreflight, withCors } from '@/lib/api/cors'; + +export const runtime = 'nodejs'; + +export function GET() { + return withCors({ distributions: DISTRIBUTIONS }); +} + +export function OPTIONS() { + return corsPreflight(); +} diff --git a/src/app/api/v1/model/functions/route.ts b/src/app/api/v1/model/functions/route.ts new file mode 100644 index 0000000..3044826 --- /dev/null +++ b/src/app/api/v1/model/functions/route.ts @@ -0,0 +1,12 @@ +import { FUNCTIONS } from '@/lib/model-data'; +import { corsPreflight, withCors } from '@/lib/api/cors'; + +export const runtime = 'nodejs'; + +export function GET() { + return withCors({ functions: FUNCTIONS }); +} + +export function OPTIONS() { + return corsPreflight(); +} diff --git a/src/app/api/v1/model/profiles/route.ts b/src/app/api/v1/model/profiles/route.ts new file mode 100644 index 0000000..ed5ad55 --- /dev/null +++ b/src/app/api/v1/model/profiles/route.ts @@ -0,0 +1,36 @@ +import { DELIVERY_PROFILES } from '@/lib/model-data'; +import { corsPreflight, withCors } from '@/lib/api/cors'; + +export const runtime = 'nodejs'; + +export function GET(request: Request) { + const url = new URL(request.url); + const functionId = url.searchParams.get('function'); + const distributionId = url.searchParams.get('distribution'); + + if (functionId && distributionId) { + const key = `${functionId}_${distributionId}`; + const profile = DELIVERY_PROFILES[key]; + if (!profile) { + return withCors({ error: `No delivery profile for ${key}` }, { status: 404 }); + } + return withCors({ key, profile }); + } + + let filtered: Record = DELIVERY_PROFILES; + if (functionId || distributionId) { + filtered = {}; + for (const [key, profile] of Object.entries(DELIVERY_PROFILES)) { + const [f, d] = key.split('_'); + if (functionId && f !== functionId) continue; + if (distributionId && d !== distributionId) continue; + filtered[key] = profile; + } + } + + return withCors({ profiles: filtered }); +} + +export function OPTIONS() { + return corsPreflight(); +} diff --git a/src/app/api/v1/model/route.ts b/src/app/api/v1/model/route.ts new file mode 100644 index 0000000..d2b6edc --- /dev/null +++ b/src/app/api/v1/model/route.ts @@ -0,0 +1,36 @@ +import { + VEHICLES, + FUNCTIONS, + DISTRIBUTIONS, + PERIODS, + SIM_PARAMS, + SERVICE_LEVELS, + DEFAULT_CLUSTERS, + DEFAULT_CLUSTER_SERVICE_LEVELS, + DEFAULT_BVO_PER_UNIT, + DELIVERY_PROFILES, + LOADING_BAY_WIDTH_M, +} from '@/lib/model-data'; +import { corsPreflight, withCors } from '@/lib/api/cors'; + +export const runtime = 'nodejs'; + +export function GET() { + return withCors({ + vehicles: VEHICLES, + functions: FUNCTIONS, + distributions: DISTRIBUTIONS, + periods: PERIODS, + serviceLevels: SERVICE_LEVELS, + defaultClusters: DEFAULT_CLUSTERS, + defaultClusterServiceLevels: DEFAULT_CLUSTER_SERVICE_LEVELS, + defaultBvoPerUnit: DEFAULT_BVO_PER_UNIT, + simParams: SIM_PARAMS, + loadingBayWidthM: LOADING_BAY_WIDTH_M, + deliveryProfiles: DELIVERY_PROFILES, + }); +} + +export function OPTIONS() { + return corsPreflight(); +} diff --git a/src/app/api/v1/model/vehicles/route.ts b/src/app/api/v1/model/vehicles/route.ts new file mode 100644 index 0000000..5950603 --- /dev/null +++ b/src/app/api/v1/model/vehicles/route.ts @@ -0,0 +1,12 @@ +import { VEHICLES } from '@/lib/model-data'; +import { corsPreflight, withCors } from '@/lib/api/cors'; + +export const runtime = 'nodejs'; + +export function GET() { + return withCors({ vehicles: VEHICLES }); +} + +export function OPTIONS() { + return corsPreflight(); +} diff --git a/src/app/api/v1/openapi.json/route.ts b/src/app/api/v1/openapi.json/route.ts new file mode 100644 index 0000000..c8ef1cd --- /dev/null +++ b/src/app/api/v1/openapi.json/route.ts @@ -0,0 +1,12 @@ +import { openApiSpec } from '@/lib/api/openapi'; +import { corsPreflight, withCors } from '@/lib/api/cors'; + +export const runtime = 'nodejs'; + +export function GET() { + return withCors(openApiSpec); +} + +export function OPTIONS() { + return corsPreflight(); +} diff --git a/src/app/api/v1/simulate/route.ts b/src/app/api/v1/simulate/route.ts new file mode 100644 index 0000000..44658a7 --- /dev/null +++ b/src/app/api/v1/simulate/route.ts @@ -0,0 +1,45 @@ +import { runSimulation } from '@/lib/simulation'; +import { SIM_PARAMS } from '@/lib/model-data'; +import { parseSimulationInput, ValidationError } from '@/lib/api/validate'; +import { buildSummary } from '@/lib/api/summary'; +import { corsPreflight, withCors } from '@/lib/api/cors'; + +export const runtime = 'nodejs'; +export const maxDuration = 60; + +export async function POST(request: Request) { + let rawBody: unknown; + try { + rawBody = await request.json(); + } catch { + return withCors({ error: 'Request body must be valid JSON' }, { status: 400 }); + } + + let parsed; + try { + parsed = parseSimulationInput(rawBody); + } catch (err) { + if (err instanceof ValidationError) { + return withCors({ error: err.message }, { status: 400 }); + } + throw err; + } + + const startedAt = Date.now(); + const result = runSimulation(parsed.input); + const durationMs = Date.now() - startedAt; + + return withCors({ + summary: buildSummary(result), + result, + meta: { + numSimulations: parsed.input.numSimulations ?? SIM_PARAMS.numSimulations, + inputCounts: parsed.resolvedCounts, + durationMs, + }, + }); +} + +export function OPTIONS() { + return corsPreflight(); +} diff --git a/src/app/mcp-connect/route.ts b/src/app/mcp-connect/route.ts new file mode 100644 index 0000000..f663b58 --- /dev/null +++ b/src/app/mcp-connect/route.ts @@ -0,0 +1,335 @@ +/** + * /mcp-connect — copy-paste configuration snippets for common MCP clients. + * + * Served as a Route Handler so it renders outside the app layout. The MCP URL + * is substituted into each snippet client-side from `window.location.origin`, + * so the page works in any environment (localhost, staging, production). + * + * Styling follows the DMI palette and IBM Plex typography used by the rest + * of the app — see src/lib/dmi-theme.ts. + */ + +export const runtime = 'nodejs'; + +const html = ` + + + + Connect MCP — Ruimtemodel Stadslogistiek + + + + + + + + + + +
+ +
+
+

Connect the Ruimtemodel MCP server

+

Paste one of the blocks below into your MCP client's configuration file. The URL has already been filled in for this deployment.

+
+ MCP URL + {{MCP_URL}} +
+
+ +
+
Claude Code — CLI
+

One-liner

+

Run this once from any directory. Add --scope user for a global install; omit for project-local.

+
+
claude mcp add --transport http ruimtemodel {{MCP_URL}}
+ +
+
+ +
+
Claude Code — file
+

.mcp.json

+

Drop in .mcp.json at the project root, or merge into ~/.claude.json.

+
+
{
+  "mcpServers": {
+    "ruimtemodel": {
+      "type": "http",
+      "url": "{{MCP_URL}}"
+    }
+  }
+}
+ +
+
+ +
+
Claude Desktop
+

claude_desktop_config.json

+

Merge into ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\\Claude\\claude_desktop_config.json (Windows). Uses mcp-remote to bridge stdio to HTTP — npx fetches it on first run.

+
+
{
+  "mcpServers": {
+    "ruimtemodel": {
+      "command": "npx",
+      "args": ["-y", "mcp-remote", "{{MCP_URL}}"]
+    }
+  }
+}
+ +
+
+ +
+
Cursor
+

mcp.json

+

Merge into ~/.cursor/mcp.json (global) or .cursor/mcp.json in a project.

+
+
{
+  "mcpServers": {
+    "ruimtemodel": {
+      "url": "{{MCP_URL}}"
+    }
+  }
+}
+ +
+
+ +
+
Codex CLI — OpenAI
+

config.toml

+

Append to ~/.codex/config.toml.

+
+
[mcp_servers.ruimtemodel]
+type = "http"
+url = "{{MCP_URL}}"
+ +
+
+ +
+
Windsurf — Codeium
+

mcp_config.json

+

Merge into ~/.codeium/windsurf/mcp_config.json.

+
+
{
+  "mcpServers": {
+    "ruimtemodel": {
+      "serverUrl": "{{MCP_URL}}"
+    }
+  }
+}
+ +
+
+ +
+
VS Code — Copilot / MCP
+

.vscode/mcp.json

+

Create .vscode/mcp.json in your workspace, or merge into user settings.

+
+
{
+  "servers": {
+    "ruimtemodel": {
+      "type": "http",
+      "url": "{{MCP_URL}}"
+    }
+  }
+}
+ +
+
+ +
+
Verify
+

Quick test with curl

+

Lists the tools exposed by the server — useful to verify reachability before wiring up a client.

+
+
curl -s -X POST {{MCP_URL}} \\
+  -H 'Content-Type: application/json' \\
+  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
+ +
+
+ + +
+ + + + +`; + +export function GET() { + return new Response(html, { + status: 200, + headers: { + 'Content-Type': 'text/html; charset=utf-8', + 'Cache-Control': 'public, max-age=300', + }, + }); +} diff --git a/src/components/layouts/DmiCockpitLayout.tsx b/src/components/layouts/DmiCockpitLayout.tsx index ef5b786..b0188f0 100644 --- a/src/components/layouts/DmiCockpitLayout.tsx +++ b/src/components/layouts/DmiCockpitLayout.tsx @@ -18,7 +18,7 @@ import { import { Slider } from '@/components/ui/slider'; import { VEHICLES, FUNCTIONS, LOADING_BAY_WIDTH_M } from '@/lib/model-data'; import type { SimulationState, LayoutType } from '@/lib/use-simulation-state'; -import { COVER, HANDLEIDING_SECTIONS, PARTNER_SECTIONS, CONTACT, CASUS_GERARD_DOUSTRAAT, renderBold } from '@/lib/content'; +import { COVER, HANDLEIDING_SECTIONS, PARTNER_SECTIONS, CONTACT, INTEGRATIONS, CASUS_GERARD_DOUSTRAAT, renderBold } from '@/lib/content'; import { HandleidingDiagram } from '@/components/HandleidingDiagrams'; import { HandleidingTableRenderer } from '@/components/HandleidingTable'; import FeedbackButton from '@/components/FeedbackButton'; @@ -529,6 +529,46 @@ export default function DmiCockpitLayout({ ))} + {/* Integrations */} +
+

{INTEGRATIONS.label}

+

+ {INTEGRATIONS.intro} +

+ +
+ {/* Layout toggle */}

Weergave

diff --git a/src/components/layouts/WebappLayout.tsx b/src/components/layouts/WebappLayout.tsx index 9ce5818..f34a72f 100644 --- a/src/components/layouts/WebappLayout.tsx +++ b/src/components/layouts/WebappLayout.tsx @@ -10,7 +10,7 @@ import { Slider } from '@/components/ui/slider'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import FeedbackButton from '@/components/FeedbackButton'; import { useIsMobile } from '@/lib/useIsMobile'; -import { COVER, HANDLEIDING_SECTIONS, PARTNER_SECTIONS, CONTACT, CASUS_GERARD_DOUSTRAAT, renderBold } from '@/lib/content'; +import { COVER, HANDLEIDING_SECTIONS, PARTNER_SECTIONS, CONTACT, INTEGRATIONS, CASUS_GERARD_DOUSTRAAT, renderBold } from '@/lib/content'; import { HandleidingDiagram } from '@/components/HandleidingDiagrams'; import { HandleidingTableRenderer } from '@/components/HandleidingTable'; import { AlgemeenEditor, DeliveryProfileEditor } from '@/components/ParameterEditor'; @@ -540,6 +540,46 @@ export default function WebappLayout({ ))}
+ {/* Integrations */} +
+

{INTEGRATIONS.label}

+

+ {INTEGRATIONS.intro} +

+ +
+ {/* Layout toggle */}

Weergave

diff --git a/src/lib/api/cors.ts b/src/lib/api/cors.ts new file mode 100644 index 0000000..555aa9f --- /dev/null +++ b/src/lib/api/cors.ts @@ -0,0 +1,26 @@ +import { NextResponse } from 'next/server'; + +const CORS_HEADERS = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Mcp-Session-Id, MCP-Protocol-Version', + 'Access-Control-Max-Age': '86400', +}; + +export function withCors(data: T, init?: ResponseInit): NextResponse { + const response = NextResponse.json(data, init); + for (const [k, v] of Object.entries(CORS_HEADERS)) { + response.headers.set(k, v); + } + return response; +} + +export function corsPreflight(): Response { + return new Response(null, { status: 204, headers: CORS_HEADERS }); +} + +export function corsRaw(body: BodyInit | null, init?: ResponseInit): Response { + const headers = new Headers(init?.headers); + for (const [k, v] of Object.entries(CORS_HEADERS)) headers.set(k, v); + return new Response(body, { ...init, headers }); +} diff --git a/src/lib/api/mcp-tools.ts b/src/lib/api/mcp-tools.ts new file mode 100644 index 0000000..c75f0ef --- /dev/null +++ b/src/lib/api/mcp-tools.ts @@ -0,0 +1,177 @@ +import { + VEHICLES, + FUNCTIONS, + DISTRIBUTIONS, + PERIODS, + SIM_PARAMS, + SERVICE_LEVELS, + DEFAULT_CLUSTERS, + DEFAULT_CLUSTER_SERVICE_LEVELS, + DEFAULT_BVO_PER_UNIT, + DELIVERY_PROFILES, + LOADING_BAY_WIDTH_M, +} from '@/lib/model-data'; +import { runSimulation } from '@/lib/simulation'; +import { parseSimulationInput, ValidationError } from '@/lib/api/validate'; +import { buildSummary } from '@/lib/api/summary'; + +/** + * MCP tool definitions + handlers for the Ruimtemodel Stadslogistiek. + * + * Each tool entry supplies the schema used by `tools/list` and a handler + * used by `tools/call`. Handlers may throw — the caller wraps thrown + * errors into MCP `isError` responses. + */ + +export interface McpTool { + name: string; + description: string; + inputSchema: Record; + handler: (args: Record) => unknown; +} + +const simulationInputSchema = { + type: 'object', + description: + 'Either functionCounts, functionBvoM2, or both must be provided. A single function may not appear in both objects.', + properties: { + functionCounts: { + type: 'object', + description: + 'Number of units per function ID (e.g. {"F1": 362, "F2": 2}). Function IDs are F1..F12 — see list_functions.', + additionalProperties: { type: 'number', minimum: 0 }, + }, + functionBvoM2: { + type: 'object', + description: + 'Alternative to functionCounts: BVO (gross floor area) in m² per function. Converted to unit counts via bvoPerUnit (defaults to DEFAULT_BVO_PER_UNIT).', + additionalProperties: { type: 'number', minimum: 0 }, + }, + bvoPerUnit: { + type: 'object', + description: + 'Optional. m² BVO per unit for BVO→units conversion. Defaults to DEFAULT_BVO_PER_UNIT (see get_model_info).', + additionalProperties: { type: 'number', minimum: 0.01 }, + }, + clusterAssignments: { + type: 'object', + description: + 'Optional. Maps vehicle ID (V1..V6) to cluster ID (integer >= 1). Defaults to DEFAULT_CLUSTERS from get_model_info.', + additionalProperties: { type: 'integer', minimum: 1 }, + }, + clusterServiceLevels: { + type: 'object', + description: + 'Optional. Maps cluster ID to service level in [0.5, 1.0]. Defaults to 0.95 per cluster.', + additionalProperties: { type: 'number', minimum: 0.5, maximum: 1 }, + }, + numSimulations: { + type: 'integer', + description: 'Optional. Number of Monte Carlo iterations (default 2500, max 5000).', + minimum: 1, + maximum: 5000, + }, + }, + additionalProperties: true, +} as const; + +export const MCP_TOOLS: McpTool[] = [ + { + name: 'get_model_info', + description: + 'Get all model metadata at once: vehicles, functions, distributions, periods, service levels, default cluster assignments, simulation parameters, and default BVO-per-unit values for BVO→count conversion.', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + handler: () => ({ + vehicles: VEHICLES, + functions: FUNCTIONS, + distributions: DISTRIBUTIONS, + periods: PERIODS, + serviceLevels: SERVICE_LEVELS, + defaultClusters: DEFAULT_CLUSTERS, + defaultClusterServiceLevels: DEFAULT_CLUSTER_SERVICE_LEVELS, + defaultBvoPerUnit: DEFAULT_BVO_PER_UNIT, + simParams: SIM_PARAMS, + loadingBayWidthM: LOADING_BAY_WIDTH_M, + }), + }, + { + name: 'list_vehicles', + description: + 'List the 6 vehicle types used in the model (V1..V6): fietskoerier, LEVV, bestelwagen, vrachtwagen N2, vrachtwagen N3, service bestelwagen. Each has an id, name, and length in meters.', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + handler: () => ({ vehicles: VEHICLES }), + }, + { + name: 'list_functions', + description: + 'List the 12 urban function types (F1..F12): woningen, supermarkt, retail food, retail keten/onafh., restaurant high/basis, café, hotel, kantoor klein/middel/groot. Each has an id, name, unit, and description.', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + handler: () => ({ functions: FUNCTIONS }), + }, + { + name: 'list_distributions', + description: + 'List the 15 distribution types (delivery profiles) D1..D15: afval, bouw, facilitair, horeca, pakket, retail, service, specialisten, supermarkt, thuisbezorging, verhuizing.', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + handler: () => ({ distributions: DISTRIBUTIONS }), + }, + { + name: 'get_delivery_profile', + description: + 'Get a single delivery profile by function and distribution ID. Returns stopsPerWeekPerUnit, duration, and periodDistribution for each of the 6 vehicle types, or an error if the combination has no profile.', + inputSchema: { + type: 'object', + required: ['functionId', 'distributionId'], + properties: { + functionId: { type: 'string', description: 'Function ID like F1' }, + distributionId: { type: 'string', description: 'Distribution ID like D7' }, + }, + additionalProperties: false, + }, + handler: (args) => { + const fid = args.functionId; + const did = args.distributionId; + if (typeof fid !== 'string' || typeof did !== 'string') { + throw new Error('functionId and distributionId must be strings'); + } + const key = `${fid}_${did}`; + const profile = DELIVERY_PROFILES[key]; + if (!profile) { + throw new Error(`No delivery profile for ${key}`); + } + return { key, profile }; + }, + }, + { + name: 'run_simulation', + description: + 'Run the Monte Carlo simulation for urban logistics loading/unloading space. Supply counts of each function type (functionCounts) and/or BVO in m² (functionBvoM2); 2500 iterations by default. Returns a labeled summary (total length in meters, total area in m²) plus the full SimulationResult.', + inputSchema: simulationInputSchema, + handler: (args) => { + let parsed; + try { + parsed = parseSimulationInput(args); + } catch (err) { + if (err instanceof ValidationError) { + throw new Error(err.message); + } + throw err; + } + const startedAt = Date.now(); + const result = runSimulation(parsed.input); + return { + summary: buildSummary(result), + result, + meta: { + numSimulations: parsed.input.numSimulations ?? SIM_PARAMS.numSimulations, + inputCounts: parsed.resolvedCounts, + durationMs: Date.now() - startedAt, + }, + }; + }, + }, +]; + +export const MCP_TOOLS_BY_NAME: Record = Object.fromEntries( + MCP_TOOLS.map((t) => [t.name, t]), +); diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.ts new file mode 100644 index 0000000..3c9b4ab --- /dev/null +++ b/src/lib/api/openapi.ts @@ -0,0 +1,706 @@ +import { MAX_NUM_SIMULATIONS } from './validate'; + +/** + * OpenAPI 3.0.3 specification for the Ruimtemodel Stadslogistiek REST API. + * + * This is the source of truth — served at /api/v1/openapi.json and rendered + * at /api-docs via ReDoc. Any schema change should land here. + */ +export const openApiSpec = { + openapi: '3.0.3', + info: { + title: 'Ruimtemodel Stadslogistiek API', + version: '1.0.0', + description: [ + 'JSON REST API for the Ruimtemodel Stadslogistiek (Urban Logistics Space Model).', + '', + 'The model is a Monte Carlo simulation that estimates the loading/unloading', + "space required by a mix of urban functions. It replicates the logic of Rebel Group's", + 'original Excel workbook.', + '', + '## Quick start', + '', + '```bash', + 'curl -X POST https://your-host/api/v1/simulate \\', + " -H 'Content-Type: application/json' \\", + ' -d \'{"functionCounts": {"F1": 362, "F2": 2}, "numSimulations": 1000}\'', + '```', + '', + '## IDs', + '', + '- **Vehicles** — `V1`..`V6`. Fetch `/api/v1/model/vehicles`.', + '- **Functions** — `F1`..`F12`. Fetch `/api/v1/model/functions`.', + '- **Distributions** — `D1`..`D15`. Fetch `/api/v1/model/distributions`.', + '', + '## No authentication', + '', + 'The API is read-only or bounded (simulation capped at ' + MAX_NUM_SIMULATIONS + ' Monte Carlo iterations).', + 'CORS is permissive so browser clients from any origin may call it.', + '', + 'For AI agents, an [MCP server](https://modelcontextprotocol.io/) is also available at `/api/mcp`.', + '', + '## Contact', + '', + '- Rebel: [info@Rebelgroup.com](mailto:info@Rebelgroup.com)', + '- DMI: [dmiteam@minienw.nl](mailto:dmiteam@minienw.nl)', + ].join('\n'), + contact: { + name: 'Ruimtemodel team', + email: 'info@Rebelgroup.com', + }, + license: { + name: 'EUPL-1.2', + url: 'https://eupl.eu/1.2/en/', + }, + 'x-logo': { + url: '/dmi-logo.png', + altText: 'DMI Ecosysteem', + href: '/', + }, + }, + servers: [ + { url: '/', description: 'Current host' }, + ], + security: [], + tags: [ + { name: 'System', description: 'Liveness and service metadata.' }, + { name: 'Model', description: 'Static catalog of vehicles, functions, distributions, and delivery profiles.' }, + { name: 'Simulation', description: 'Run the Monte Carlo simulation.' }, + ], + paths: { + '/api/v1/health': { + get: { + tags: ['System'], + summary: 'Health check', + description: 'Liveness probe. Returns a tiny JSON object with service metadata.', + operationId: 'getHealth', + responses: { + '200': { + description: 'Service is healthy.', + content: { + 'application/json': { + schema: { $ref: '#/components/schemas/Health' }, + example: { + status: 'ok', + service: 'ruimtemodel-api', + version: '1.0.0', + timestamp: '2026-04-23T11:44:56.542Z', + }, + }, + }, + }, + '400': { $ref: '#/components/responses/BadRequest' }, + }, + }, + }, + '/api/v1/model': { + get: { + tags: ['Model'], + summary: 'Full model catalog', + description: + 'Return vehicles, functions, distributions, periods, service levels, default cluster assignments, simulation parameters, and all delivery profiles in a single payload.', + operationId: 'getModel', + responses: { + '200': { + description: 'Full model catalog.', + content: { + 'application/json': { + schema: { $ref: '#/components/schemas/ModelCatalog' }, + }, + }, + }, + '400': { $ref: '#/components/responses/BadRequest' }, + }, + }, + }, + '/api/v1/model/vehicles': { + get: { + tags: ['Model'], + summary: 'List vehicles', + description: 'Return the six vehicle types, each with its ID, name, and length in meters.', + operationId: 'getVehicles', + responses: { + '200': { + description: 'List of vehicles.', + content: { + 'application/json': { + schema: { + type: 'object', + required: ['vehicles'], + properties: { + vehicles: { type: 'array', items: { $ref: '#/components/schemas/Vehicle' } }, + }, + }, + }, + }, + }, + '400': { $ref: '#/components/responses/BadRequest' }, + }, + }, + }, + '/api/v1/model/functions': { + get: { + tags: ['Model'], + summary: 'List functions', + description: 'Return the twelve urban function types.', + operationId: 'getFunctions', + responses: { + '200': { + description: 'List of functions.', + content: { + 'application/json': { + schema: { + type: 'object', + required: ['functions'], + properties: { + functions: { type: 'array', items: { $ref: '#/components/schemas/Function' } }, + }, + }, + }, + }, + }, + '400': { $ref: '#/components/responses/BadRequest' }, + }, + }, + }, + '/api/v1/model/distributions': { + get: { + tags: ['Model'], + summary: 'List distributions', + description: 'Return the fifteen distribution types (delivery profiles).', + operationId: 'getDistributions', + responses: { + '200': { + description: 'List of distributions.', + content: { + 'application/json': { + schema: { + type: 'object', + required: ['distributions'], + properties: { + distributions: { type: 'array', items: { $ref: '#/components/schemas/Distribution' } }, + }, + }, + }, + }, + }, + '400': { $ref: '#/components/responses/BadRequest' }, + }, + }, + }, + '/api/v1/model/profiles': { + get: { + tags: ['Model'], + summary: 'List delivery profiles', + description: [ + 'Return delivery profiles. Profiles encode stops-per-week-per-unit, stop duration, and period distribution per vehicle type.', + '', + '- Without parameters: every profile keyed by `"{functionId}_{distributionId}"`.', + '- With a single filter (`function` *or* `distribution`): the filtered subset.', + '- With both filters: a single profile returned as `{ key, profile }`.', + ].join('\n'), + operationId: 'getProfiles', + parameters: [ + { + name: 'function', + in: 'query', + required: false, + description: 'Filter by function ID (e.g. `F1`).', + schema: { type: 'string', pattern: '^F[0-9]+$' }, + }, + { + name: 'distribution', + in: 'query', + required: false, + description: 'Filter by distribution ID (e.g. `D7`).', + schema: { type: 'string', pattern: '^D[0-9]+$' }, + }, + ], + responses: { + '200': { + description: 'Delivery profiles.', + content: { + 'application/json': { + schema: { + oneOf: [ + { + type: 'object', + required: ['profiles'], + properties: { + profiles: { + type: 'object', + additionalProperties: { $ref: '#/components/schemas/DeliveryProfile' }, + }, + }, + }, + { + type: 'object', + required: ['key', 'profile'], + properties: { + key: { type: 'string', example: 'F1_D7' }, + profile: { $ref: '#/components/schemas/DeliveryProfile' }, + }, + }, + ], + }, + }, + }, + }, + '400': { $ref: '#/components/responses/BadRequest' }, + '404': { + description: 'No profile for the requested function+distribution pair.', + content: { + 'application/json': { schema: { $ref: '#/components/schemas/Error' } }, + }, + }, + }, + }, + }, + '/api/v1/simulate': { + post: { + tags: ['Simulation'], + summary: 'Run Monte Carlo simulation', + description: [ + 'Run the Monte Carlo simulation for a given set of function counts.', + '', + 'At minimum, supply `functionCounts` — the number of units per function ID.', + 'All other fields fall back to sensible defaults pulled from the model catalog.', + '', + '`numSimulations` is capped at **' + MAX_NUM_SIMULATIONS + '** to bound response time.', + ].join('\n'), + operationId: 'runSimulation', + requestBody: { + required: true, + content: { + 'application/json': { + schema: { $ref: '#/components/schemas/SimulationInput' }, + examples: { + units: { + summary: 'Units input', + value: { functionCounts: { F1: 362, F2: 2, F10: 5 } }, + }, + bvo: { + summary: 'BVO (m²) input', + value: { functionBvoM2: { F1: 32580, F10: 6250 } }, + }, + mixed: { + summary: 'Mixed units + BVO', + value: { + functionCounts: { F2: 2 }, + functionBvoM2: { F1: 32580, F10: 6250 }, + }, + }, + withOverrides: { + summary: 'With cluster + sim overrides', + value: { + functionCounts: { F1: 500 }, + clusterAssignments: { V1: 1, V2: 1, V3: 2, V4: 2, V5: 2, V6: 3 }, + clusterServiceLevels: { '1': 0.95, '2': 0.9, '3': 0.75 }, + numSimulations: 1000, + }, + }, + }, + }, + }, + }, + responses: { + '200': { + description: 'Simulation result.', + content: { + 'application/json': { + schema: { $ref: '#/components/schemas/SimulationResponse' }, + }, + }, + }, + '400': { $ref: '#/components/responses/BadRequest' }, + }, + }, + }, + }, + components: { + responses: { + BadRequest: { + description: 'Invalid request.', + content: { + 'application/json': { schema: { $ref: '#/components/schemas/Error' } }, + }, + }, + }, + schemas: { + Health: { + type: 'object', + required: ['status', 'service', 'version', 'timestamp'], + properties: { + status: { type: 'string', enum: ['ok'] }, + service: { type: 'string' }, + version: { type: 'string' }, + timestamp: { type: 'string', format: 'date-time' }, + }, + }, + Error: { + type: 'object', + required: ['error'], + properties: { + error: { type: 'string', description: 'Human-readable error message.' }, + }, + }, + Vehicle: { + type: 'object', + required: ['id', 'name', 'length'], + properties: { + id: { type: 'string', example: 'V1', description: 'Vehicle ID (V1..V6).' }, + name: { type: 'string', example: 'Fiets, cargobike, scooter' }, + length: { type: 'number', example: 2, description: 'Vehicle length in meters.' }, + }, + }, + Function: { + type: 'object', + required: ['id', 'name', 'unit', 'description'], + properties: { + id: { type: 'string', example: 'F1', description: 'Function ID (F1..F12).' }, + name: { type: 'string', example: 'Woningen' }, + unit: { type: 'string', example: 'woningen' }, + description: { type: 'string' }, + }, + }, + Distribution: { + type: 'object', + required: ['id', 'name', 'deliveryDays'], + properties: { + id: { type: 'string', example: 'D7', description: 'Distribution ID (D1..D15).' }, + name: { type: 'string', example: 'Pakket' }, + deliveryDays: { type: 'integer', example: 6, description: 'Delivery days per week.' }, + }, + }, + Period: { + type: 'object', + required: ['id', 'name', 'hours'], + properties: { + id: { type: 'string', example: 'P1' }, + name: { type: 'string', example: '0:00 - 6:00' }, + hours: { type: 'integer', example: 6 }, + }, + }, + DeliveryProfile: { + type: 'object', + description: + 'Delivery profile for one (function, distribution) pair. Each array has six entries corresponding to vehicles V1..V6.', + required: ['stopsPerWeekPerUnit', 'duration', 'periodDistribution'], + properties: { + stopsPerWeekPerUnit: { + type: 'array', + description: 'Stops per week per unit, per vehicle type.', + minItems: 6, + maxItems: 6, + items: { type: 'number' }, + }, + duration: { + type: 'array', + description: 'Stop duration in minutes, per vehicle type.', + minItems: 6, + maxItems: 6, + items: { type: 'number' }, + }, + periodDistribution: { + type: 'array', + description: + 'For each vehicle (V1..V6), a 4-element array giving the fraction of arrivals in periods P1..P4.', + minItems: 6, + maxItems: 6, + items: { + type: 'array', + minItems: 4, + maxItems: 4, + items: { type: 'number' }, + }, + }, + }, + }, + SimParams: { + type: 'object', + required: ['intervalMinutes', 'minutesPerHour', 'hoursPerDay', 'numSimulations'], + properties: { + intervalMinutes: { type: 'integer', example: 10 }, + minutesPerHour: { type: 'integer', example: 60 }, + hoursPerDay: { type: 'integer', example: 24 }, + numSimulations: { type: 'integer', example: 2500 }, + }, + }, + ModelCatalog: { + type: 'object', + required: [ + 'vehicles', + 'functions', + 'distributions', + 'periods', + 'serviceLevels', + 'defaultClusters', + 'defaultClusterServiceLevels', + 'simParams', + 'loadingBayWidthM', + 'deliveryProfiles', + ], + properties: { + vehicles: { type: 'array', items: { $ref: '#/components/schemas/Vehicle' } }, + functions: { type: 'array', items: { $ref: '#/components/schemas/Function' } }, + distributions: { type: 'array', items: { $ref: '#/components/schemas/Distribution' } }, + periods: { type: 'array', items: { $ref: '#/components/schemas/Period' } }, + serviceLevels: { type: 'array', items: { type: 'number' } }, + defaultClusters: { + type: 'object', + additionalProperties: { type: 'integer' }, + description: 'Mapping of vehicle ID to default cluster ID.', + }, + defaultClusterServiceLevels: { + type: 'object', + additionalProperties: { type: 'number' }, + description: 'Mapping of cluster ID (as string key) to default service level.', + }, + defaultBvoPerUnit: { + type: 'object', + additionalProperties: { type: 'number' }, + description: + 'Indicative gemiddelde BVO in m² per unit per function, used for BVO→units conversion when callers submit `functionBvoM2`.', + example: { F1: 90, F2: 1500, F10: 1250 }, + }, + simParams: { $ref: '#/components/schemas/SimParams' }, + loadingBayWidthM: { type: 'number', example: 3 }, + deliveryProfiles: { + type: 'object', + additionalProperties: { $ref: '#/components/schemas/DeliveryProfile' }, + }, + }, + }, + SimulationInput: { + type: 'object', + description: + 'Either `functionCounts`, `functionBvoM2`, or both must be supplied. A single function may not appear in both. All other fields fall back to model defaults.', + properties: { + functionCounts: { + type: 'object', + description: 'Number of units per function ID (F1..F12).', + additionalProperties: { type: 'number', minimum: 0 }, + example: { F1: 362, F2: 2, F10: 5 }, + }, + functionBvoM2: { + type: 'object', + description: + 'Alternative to `functionCounts`: BVO (gross floor area) in m² per function. Converted to unit counts via `bvoPerUnit`.', + additionalProperties: { type: 'number', minimum: 0 }, + example: { F1: 32580, F10: 6250 }, + }, + bvoPerUnit: { + type: 'object', + description: + 'Optional. m² BVO per unit, used for BVO→units conversion. Defaults are available from `/api/v1/model` (`defaultClusters` sibling key).', + additionalProperties: { type: 'number', minimum: 0.01 }, + }, + clusterAssignments: { + type: 'object', + description: 'Optional. Vehicle ID → cluster ID. Defaults to DEFAULT_CLUSTERS.', + additionalProperties: { type: 'integer', minimum: 1 }, + }, + clusterServiceLevels: { + type: 'object', + description: 'Optional. Cluster ID (as string key) → service level in [0.5, 1.0]. Defaults to 0.95 per cluster.', + additionalProperties: { type: 'number', minimum: 0.5, maximum: 1 }, + }, + numSimulations: { + type: 'integer', + description: 'Optional. Number of Monte Carlo iterations. Default 2500.', + minimum: 1, + maximum: MAX_NUM_SIMULATIONS, + }, + vehicles: { + type: 'array', + description: 'Optional. Override the built-in vehicle list.', + items: { $ref: '#/components/schemas/Vehicle' }, + }, + functions: { + type: 'array', + description: 'Optional. Override the built-in function list.', + items: { $ref: '#/components/schemas/Function' }, + }, + distributions: { + type: 'array', + description: 'Optional. Override the built-in distribution list.', + items: { $ref: '#/components/schemas/Distribution' }, + }, + vehicleLengths: { + type: 'object', + description: 'Optional. Override vehicle length (m) by vehicle ID.', + additionalProperties: { type: 'number', minimum: 0 }, + }, + deliveryDays: { + type: 'object', + description: 'Optional. Override delivery days by distribution ID.', + additionalProperties: { type: 'integer', minimum: 1, maximum: 7 }, + }, + deliveryProfiles: { + type: 'object', + description: 'Optional. Override/merge delivery profiles by key (e.g. "F1_D7").', + additionalProperties: { $ref: '#/components/schemas/DeliveryProfile' }, + }, + intervalMinutes: { + type: 'number', + description: 'Optional. Override simulation interval in minutes (0 < x <= 60).', + minimum: 0, + exclusiveMinimum: true, + maximum: 60, + }, + }, + }, + VehicleResult: { + type: 'object', + required: [ + 'vehicleId', + 'vehicleName', + 'vehicleLength', + 'totalArrivalsPerDay', + 'maxVehiclesPerServiceLevel', + 'requiredSpaceM2', + 'clusterId', + ], + properties: { + vehicleId: { type: 'string' }, + vehicleName: { type: 'string' }, + vehicleLength: { type: 'number' }, + totalArrivalsPerDay: { type: 'number' }, + maxVehiclesPerServiceLevel: { + type: 'object', + description: 'Peak simultaneous vehicles at each service level (as integer percent key).', + additionalProperties: { type: 'number' }, + }, + requiredSpaceM2: { type: 'number' }, + clusterId: { type: 'integer' }, + }, + }, + ClusterResult: { + type: 'object', + required: ['clusterId', 'serviceLevel', 'totalSpaceM2', 'vehicleIds', 'maxVehiclesPerServiceLevel'], + properties: { + clusterId: { type: 'integer' }, + serviceLevel: { type: 'number' }, + totalSpaceM2: { type: 'number' }, + vehicleIds: { type: 'array', items: { type: 'string' } }, + maxVehiclesPerServiceLevel: { + type: 'object', + additionalProperties: { type: 'number' }, + }, + }, + }, + SimulationResult: { + type: 'object', + description: + 'Raw simulation output. Legacy field names `totalSpaceM2` and `requiredSpaceM2` actually hold **length in meters**, not area — multiply by `loadingBayWidthM` for m². Prefer the top-level `summary` in the response for clearly-labeled values.', + required: ['vehicleResults', 'clusterResults', 'totalSpaceM2', 'peakByPeriod', 'serviceLevelCurve'], + properties: { + vehicleResults: { type: 'array', items: { $ref: '#/components/schemas/VehicleResult' } }, + clusterResults: { type: 'array', items: { $ref: '#/components/schemas/ClusterResult' } }, + totalSpaceM2: { + type: 'number', + description: 'Total required length in meters. Misleading legacy name — not actually m².', + }, + peakByPeriod: { + type: 'array', + items: { + type: 'object', + required: ['period', 'space'], + properties: { + period: { type: 'string' }, + space: { type: 'number', description: 'Required length in meters during this period.' }, + }, + }, + }, + serviceLevelCurve: { + type: 'array', + items: { + type: 'object', + required: ['serviceLevel', 'space'], + properties: { + serviceLevel: { type: 'number' }, + space: { type: 'number', description: 'Required length in meters at this service level.' }, + }, + }, + }, + }, + }, + SimulationSummary: { + type: 'object', + description: + 'Clearly-labeled summary of the simulation result. Lengths are in meters; areas are in m² (= length × loadingBayWidthM).', + required: ['loadingBayWidthM', 'totalLengthM', 'totalAreaM2', 'vehicles', 'clusters'], + properties: { + loadingBayWidthM: { type: 'number', example: 3, description: 'Assumed bay width in meters (currently 3).' }, + totalLengthM: { type: 'number', example: 27.4, description: 'Total required length across all clusters.' }, + totalAreaM2: { type: 'number', example: 82.2, description: 'Total required area = totalLengthM × loadingBayWidthM.' }, + vehicles: { + type: 'array', + items: { + type: 'object', + required: [ + 'vehicleId', + 'vehicleName', + 'vehicleLengthM', + 'clusterId', + 'totalArrivalsPerDay', + 'requiredLengthM', + 'requiredAreaM2', + ], + properties: { + vehicleId: { type: 'string' }, + vehicleName: { type: 'string' }, + vehicleLengthM: { type: 'number', description: 'Length of a single vehicle of this type.' }, + clusterId: { type: 'integer' }, + totalArrivalsPerDay: { type: 'number' }, + requiredLengthM: { type: 'number' }, + requiredAreaM2: { type: 'number' }, + }, + }, + }, + clusters: { + type: 'array', + items: { + type: 'object', + required: ['clusterId', 'serviceLevel', 'vehicleIds', 'requiredLengthM', 'requiredAreaM2'], + properties: { + clusterId: { type: 'integer' }, + serviceLevel: { type: 'number' }, + vehicleIds: { type: 'array', items: { type: 'string' } }, + requiredLengthM: { type: 'number' }, + requiredAreaM2: { type: 'number' }, + }, + }, + }, + }, + }, + SimulationResponseMeta: { + type: 'object', + required: ['numSimulations', 'inputCounts', 'durationMs'], + properties: { + numSimulations: { + type: 'integer', + description: 'Number of Monte Carlo iterations actually run (default 2500).', + }, + inputCounts: { + type: 'object', + description: + 'Function counts actually fed to the simulation after any BVO→units conversion. Useful for verifying what was simulated.', + additionalProperties: { type: 'number' }, + example: { F1: 362, F10: 5 }, + }, + durationMs: { type: 'integer', description: 'Server-side simulation duration in milliseconds.' }, + }, + }, + SimulationResponse: { + type: 'object', + required: ['summary', 'result', 'meta'], + properties: { + summary: { $ref: '#/components/schemas/SimulationSummary' }, + result: { $ref: '#/components/schemas/SimulationResult' }, + meta: { $ref: '#/components/schemas/SimulationResponseMeta' }, + }, + }, + }, + }, +} as const; diff --git a/src/lib/api/summary.ts b/src/lib/api/summary.ts new file mode 100644 index 0000000..47b216e --- /dev/null +++ b/src/lib/api/summary.ts @@ -0,0 +1,59 @@ +import type { SimulationResult } from '@/lib/simulation'; +import { LOADING_BAY_WIDTH_M } from '@/lib/model-data'; + +/** + * Clean, clearly-labeled summary of a SimulationResult. + * + * Historical note: `SimulationResult.totalSpaceM2` and `requiredSpaceM2` hold + * length in meters, not area — the Excel model and UI always multiply by + * `LOADING_BAY_WIDTH_M` to get m². The `SimulationResult` shape is frozen for + * backwards compatibility with the UI's state store. At the API boundary we + * expose this richer summary so external clients don't have to learn that + * quirk. + */ +export interface SimulationSummary { + loadingBayWidthM: number; + totalLengthM: number; + totalAreaM2: number; + vehicles: Array<{ + vehicleId: string; + vehicleName: string; + vehicleLengthM: number; + clusterId: number; + totalArrivalsPerDay: number; + requiredLengthM: number; + requiredAreaM2: number; + }>; + clusters: Array<{ + clusterId: number; + serviceLevel: number; + vehicleIds: string[]; + requiredLengthM: number; + requiredAreaM2: number; + }>; +} + +export function buildSummary(result: SimulationResult): SimulationSummary { + const width = LOADING_BAY_WIDTH_M; + return { + loadingBayWidthM: width, + totalLengthM: result.totalSpaceM2, + totalAreaM2: result.totalSpaceM2 * width, + vehicles: result.vehicleResults.map((vr) => ({ + vehicleId: vr.vehicleId, + vehicleName: vr.vehicleName, + vehicleLengthM: vr.vehicleLength, + clusterId: vr.clusterId, + totalArrivalsPerDay: vr.totalArrivalsPerDay, + requiredLengthM: vr.requiredSpaceM2, + requiredAreaM2: vr.requiredSpaceM2 * width, + })), + clusters: result.clusterResults.map((cr) => ({ + clusterId: cr.clusterId, + serviceLevel: cr.serviceLevel, + vehicleIds: cr.vehicleIds, + requiredLengthM: cr.totalSpaceM2, + requiredAreaM2: cr.totalSpaceM2 * width, + })), + }; +} diff --git a/src/lib/api/validate.ts b/src/lib/api/validate.ts new file mode 100644 index 0000000..bec2ab2 --- /dev/null +++ b/src/lib/api/validate.ts @@ -0,0 +1,239 @@ +import type { SimulationInput } from '@/lib/simulation'; +import { + VEHICLES, + FUNCTIONS, + DEFAULT_CLUSTERS, + DEFAULT_CLUSTER_SERVICE_LEVELS, + DEFAULT_BVO_PER_UNIT, +} from '@/lib/model-data'; + +export const MAX_NUM_SIMULATIONS = 5000; + +export class ValidationError extends Error { + constructor(message: string) { + super(message); + this.name = 'ValidationError'; + } +} + +/** + * Return value of parseSimulationInput — includes the simulation input plus + * diagnostic info about how the input was normalized (e.g. BVO → counts). + */ +export interface ParsedSimulationInput { + input: SimulationInput; + /** Function counts after any BVO→units conversion. Matches input.functionCounts. */ + resolvedCounts: Record; +} + +function isPlainObject(x: unknown): x is Record { + return typeof x === 'object' && x !== null && !Array.isArray(x); +} + +function assertNumberRecord( + value: unknown, + field: string, + { min = -Infinity, max = Infinity }: { min?: number; max?: number } = {}, +): Record { + if (!isPlainObject(value)) { + throw new ValidationError(`${field} must be an object mapping IDs to numbers`); + } + const out: Record = {}; + for (const [k, v] of Object.entries(value)) { + if (typeof v !== 'number' || !Number.isFinite(v)) { + throw new ValidationError(`${field}.${k} must be a finite number`); + } + if (v < min || v > max) { + throw new ValidationError(`${field}.${k} must be between ${min} and ${max}`); + } + out[k] = v; + } + return out; +} + +/** + * Parse + validate a raw JSON body into a SimulationInput. + * Throws ValidationError with a user-friendly message on invalid input. + * + * Accepts either `functionCounts` (number of units per function), or + * `functionBvoM2` (BVO in m² per function), or both — but a single function + * may not appear in both. BVO values are converted to unit counts using + * `bvoPerUnit[funcId]` if supplied, otherwise `DEFAULT_BVO_PER_UNIT[funcId]`. + */ +export function parseSimulationInput(raw: unknown): ParsedSimulationInput { + if (!isPlainObject(raw)) { + throw new ValidationError('Request body must be a JSON object'); + } + + const hasCounts = 'functionCounts' in raw && raw.functionCounts !== undefined; + const hasBvo = 'functionBvoM2' in raw && raw.functionBvoM2 !== undefined; + if (!hasCounts && !hasBvo) { + throw new ValidationError('At least one of functionCounts or functionBvoM2 is required'); + } + + const countsFromInput = hasCounts + ? assertNumberRecord(raw.functionCounts, 'functionCounts', { min: 0 }) + : {}; + const bvoInput = hasBvo + ? assertNumberRecord(raw.functionBvoM2, 'functionBvoM2', { min: 0 }) + : {}; + + // Per-unit BVO overrides (optional). Start with defaults, layer overrides. + const bvoPerUnit: Record = { ...DEFAULT_BVO_PER_UNIT }; + if ('bvoPerUnit' in raw && raw.bvoPerUnit !== undefined) { + const overrides = assertNumberRecord(raw.bvoPerUnit, 'bvoPerUnit', { min: 0.01 }); + Object.assign(bvoPerUnit, overrides); + } + + const knownFunctionIds = new Set([ + ...FUNCTIONS.map((f) => f.id), + ...(Array.isArray(raw.functions) ? (raw.functions as Array<{ id?: string }>).map((f) => f?.id).filter((x): x is string => typeof x === 'string') : []), + ]); + for (const id of Object.keys(countsFromInput)) { + if (!knownFunctionIds.has(id)) { + throw new ValidationError( + `functionCounts contains unknown function ID "${id}". Pass a custom functions[] array to use non-standard IDs.`, + ); + } + } + for (const id of Object.keys(bvoInput)) { + if (!knownFunctionIds.has(id)) { + throw new ValidationError( + `functionBvoM2 contains unknown function ID "${id}". Pass a custom functions[] array to use non-standard IDs.`, + ); + } + if (id in countsFromInput) { + throw new ValidationError( + `Function "${id}" appears in both functionCounts and functionBvoM2. Choose one input mode per function.`, + ); + } + if (!(id in bvoPerUnit) || bvoPerUnit[id] <= 0) { + throw new ValidationError( + `No bvoPerUnit available for "${id}". Supply bvoPerUnit.${id} explicitly when converting BVO for custom functions.`, + ); + } + } + + // Convert BVO → units, round to nearest whole unit. + const functionCounts: Record = { ...countsFromInput }; + for (const [id, bvo] of Object.entries(bvoInput)) { + functionCounts[id] = Math.round(bvo / bvoPerUnit[id]); + } + + // clusterAssignments: optional, defaults to DEFAULT_CLUSTERS + let clusterAssignments: Record; + if ('clusterAssignments' in raw && raw.clusterAssignments !== undefined) { + clusterAssignments = assertNumberRecord(raw.clusterAssignments, 'clusterAssignments', { + min: 1, + max: 100, + }); + // Ensure integers + for (const [k, v] of Object.entries(clusterAssignments)) { + if (!Number.isInteger(v)) { + throw new ValidationError(`clusterAssignments.${k} must be an integer cluster ID`); + } + } + } else { + clusterAssignments = { ...DEFAULT_CLUSTERS }; + } + + // Ensure every vehicle is assigned to a cluster + const knownVehicleIds = new Set([ + ...VEHICLES.map((v) => v.id), + ...(Array.isArray(raw.vehicles) ? (raw.vehicles as Array<{ id?: string }>).map((v) => v?.id).filter((x): x is string => typeof x === 'string') : []), + ]); + for (const vid of knownVehicleIds) { + if (!(vid in clusterAssignments)) { + clusterAssignments[vid] = DEFAULT_CLUSTERS[vid] ?? 1; + } + } + + // clusterServiceLevels: optional, defaults to DEFAULT_CLUSTER_SERVICE_LEVELS + let clusterServiceLevels: Record; + if ('clusterServiceLevels' in raw && raw.clusterServiceLevels !== undefined) { + const parsed = assertNumberRecord(raw.clusterServiceLevels, 'clusterServiceLevels', { + min: 0.5, + max: 1, + }); + clusterServiceLevels = {}; + for (const [k, v] of Object.entries(parsed)) { + const clusterId = Number(k); + if (!Number.isInteger(clusterId)) { + throw new ValidationError(`clusterServiceLevels keys must be integer cluster IDs (got "${k}")`); + } + clusterServiceLevels[clusterId] = v; + } + } else { + clusterServiceLevels = { ...DEFAULT_CLUSTER_SERVICE_LEVELS }; + } + + // numSimulations: optional, capped + let numSimulations: number | undefined; + if ('numSimulations' in raw && raw.numSimulations !== undefined) { + if (typeof raw.numSimulations !== 'number' || !Number.isInteger(raw.numSimulations)) { + throw new ValidationError('numSimulations must be an integer'); + } + if (raw.numSimulations < 1) { + throw new ValidationError('numSimulations must be >= 1'); + } + if (raw.numSimulations > MAX_NUM_SIMULATIONS) { + throw new ValidationError( + `numSimulations must be <= ${MAX_NUM_SIMULATIONS} (got ${raw.numSimulations})`, + ); + } + numSimulations = raw.numSimulations; + } + + // Advanced overrides — passed through with shallow validation + const input: SimulationInput = { + functionCounts, + clusterAssignments, + clusterServiceLevels, + ...(numSimulations !== undefined && { numSimulations }), + }; + + if (Array.isArray(raw.vehicles)) { + for (const v of raw.vehicles as unknown[]) { + if (!isPlainObject(v) || typeof v.id !== 'string' || typeof v.name !== 'string' || typeof v.length !== 'number') { + throw new ValidationError('vehicles[] entries must have {id: string, name: string, length: number}'); + } + } + input.vehicles = raw.vehicles as SimulationInput['vehicles']; + } + if (Array.isArray(raw.functions)) { + for (const f of raw.functions as unknown[]) { + if (!isPlainObject(f) || typeof f.id !== 'string' || typeof f.name !== 'string' || typeof f.unit !== 'string') { + throw new ValidationError('functions[] entries must have {id, name, unit, description}'); + } + } + input.functions = raw.functions as SimulationInput['functions']; + } + if (Array.isArray(raw.distributions)) { + for (const d of raw.distributions as unknown[]) { + if (!isPlainObject(d) || typeof d.id !== 'string' || typeof d.name !== 'string' || typeof d.deliveryDays !== 'number') { + throw new ValidationError('distributions[] entries must have {id, name, deliveryDays}'); + } + } + input.distributions = raw.distributions as SimulationInput['distributions']; + } + if ('vehicleLengths' in raw && raw.vehicleLengths !== undefined) { + input.vehicleLengths = assertNumberRecord(raw.vehicleLengths, 'vehicleLengths', { min: 0, max: 100 }); + } + if ('deliveryDays' in raw && raw.deliveryDays !== undefined) { + input.deliveryDays = assertNumberRecord(raw.deliveryDays, 'deliveryDays', { min: 1, max: 7 }); + } + if ('deliveryProfiles' in raw && raw.deliveryProfiles !== undefined) { + if (!isPlainObject(raw.deliveryProfiles)) { + throw new ValidationError('deliveryProfiles must be an object'); + } + input.deliveryProfiles = raw.deliveryProfiles as SimulationInput['deliveryProfiles']; + } + if ('intervalMinutes' in raw && raw.intervalMinutes !== undefined) { + if (typeof raw.intervalMinutes !== 'number' || raw.intervalMinutes <= 0 || raw.intervalMinutes > 60) { + throw new ValidationError('intervalMinutes must be a number in (0, 60]'); + } + input.intervalMinutes = raw.intervalMinutes; + } + + return { input, resolvedCounts: functionCounts }; +} diff --git a/src/lib/content.ts b/src/lib/content.ts index 055e217..51c0fe7 100644 --- a/src/lib/content.ts +++ b/src/lib/content.ts @@ -105,6 +105,16 @@ export const CONTACT = { ], }; +export const INTEGRATIONS = { + label: 'Integraties', + intro: + 'Externe systemen kunnen het model aanroepen via een REST API of via het Model Context Protocol (voor AI-agents).', + links: [ + { label: 'API-referentie (ReDoc)', href: '/api-docs' }, + { label: 'MCP instellen', href: '/mcp-connect' }, + ], +}; + // --------------------------------------------------------------------------- // Cover page data // ---------------------------------------------------------------------------