Timetable API Node
[CI]
[Node.js]
[License: WTFPL]
[MCP Registry]
Express-based API for Lviv transport timetable data with a read-only MCP endpoint.
[smithery badge]
[vbhjckfd/timetable-api-node MCP server]
[timetable-api-node MCP server]
Requirements
Run locally
make import downloads the static GTFS feed (gtfs-import-config.json) and
writes the two stores the server reads: database/Timetable (LokiJS: stops,
routes, shapes, first-stop schedules) and database/gtfs (SQLite: trips and
calendars). Both are gitignored, so a fresh clone has no data until it runs.
make import-slim re-imports only the light tables into SQLite and leaves
database/Timetable alone.
Configuration
All variables are optional; see .env.dist.
Test
TypeScript
The code is TypeScript and runs straight from the .ts sources under Node's
built-in type stripping — there is no build step for the server, the GTFS
import or the scripts. That means only erasable syntax (no enum,
namespace or parameter properties), import type for type-only imports, and
relative imports that name the .ts file; tsconfig.json enforces all three.
npm run build emits just mcp/stdio.js, the published bin: Node does not
strip types inside node_modules, so the npm package has to ship JavaScript.
It runs on npm pack/npm publish; the output is not committed.
public/stopOverrides.js is served to browsers as-is, so it stays JavaScript
and is type-checked from its JSDoc.
Monitoring
New Relic APM, off unless NEW_RELIC_LICENSE_KEY is set. It also carries
errors and the custom metrics recorded through utils/metrics.ts.
New Relic runs as a preloaded agent, so npm start carries the flags:
dotenv/config is preloaded first so .env is populated before the agent
reads its configuration. The config file is newrelic.cjs (the agent is
CommonJS and this project is ESM) and holds no secrets — the key comes from the
environment. /health is excluded from transactions via rules.ignore.
The account is in the EU region; its license key starts with eu01xx and
the agent picks the collector from that prefix. Use the 40-character ingest
license key, not an NRAK-... user API key.
Cloud Run reads the key from Secret Manager:
MCP Server
This service exposes a public read-only MCP endpoint over Streamable HTTP. It speaks MCP revision 2026-07-28 (stateless: server/discover, a per-request _meta envelope, cacheable list results) and still serves 2025-era clients that open with initialize (2025-11-25 back to 2024-11-05).
- MCP endpoint:
/mcp
- Server card:
/.well-known/mcp/server-card.json
- Discovery hint:
/robots.txt (non-standard comment hint)
Production deployment (see cloudbuild.yaml for Cloud Run) serves REST and MCP from api.lad.lviv.ua. The main site lad.lviv.ua is the public transport website (this repo still links there in HTML sitemap and tables for people, not for the API host). Use your own origin when running locally.
LLM and /mcp flow
An MCP client (Claude, Cursor, or the MCP SDK) talks JSON-RPC over Streamable HTTP to POST /mcp. Tool handlers reuse the same Express actions as the REST API, backed by LokiJS timetable data, GTFS SQLite (via gtfs), and live GTFS-RT feeds (for example track.ua-gis.com).
Try the live API
[MCP server card]
[REST stops.json]
[REST routes.json]
MCP Inspector (local): run npx @modelcontextprotocol/inspector, then open the UI with transport and server URL prefilled (from the inspector README):
http://localhost:6274/?transport=streamable-http&serverUrl=https%3A%2F%2Fapi.lad.lviv.ua%2Fmcp
Postman / curl: call a tool on production
POST https://api.lad.lviv.ua/mcp with Content-Type: application/json and Accept: application/json, text/event-stream — the Streamable HTTP transport rejects a request that does not accept both. The server is stateless: there is no session, so tools/call works on its own without an initialize first. The response arrives as a single SSE event: message frame carrying the JSON-RPC result. This is the 2025-era request shape; a 2026-07-28 request also sends MCP-Protocol-Version: 2026-07-28 and Mcp-Method headers, plus io.modelcontextprotocol/protocolVersion and io.modelcontextprotocol/clientCapabilities in params._meta.
Example tools/call body shape:
Successful tool responses return a natural-language text summary inside MCP content items (type: "text") — e.g. "Stop «Площа Ринок»: 6 arrivals. Next: Т02 → «Пасічна» in 3 min." The full structured payload is in the structuredContent field (for schema-aware clients). Each structuredContent payload follows one contract:
ui_blocks point into data instead of repeating it. A map block gives the centre and zoom, and layers maps stops, vehicles and polylines to a dot path in the result; every stop and vehicle there has lat/lng, vehicles also bearing. An arrival_list block names the arrivals array to render, already sorted by arrival_minutes (null = no ETA).
Exposed tools
All tools are read-only. Stop IDs are the numeric codes on stop signs, returned as strings ("707"). Route names are the short names on vehicles ("Т30", "А1"); Latin "T30"/"A01" work too, and a bare number is read as an internal route ID. An unknown route or vehicle returns isError: true with a hint on what to pass instead.
get_stop_realtime — example
search_stops — example
One stop name usually covers both sides of the street under different IDs; each is returned, and routes tells them apart. get_stops_around_location returns the same stop objects plus distance_meters.
find_routes_between — example
Text summary: "3 direct routes «Площа Ринок» → «Залізничний вокзал». Best: Т01 towards «Залізничний вокзал», 8 stops, board at «Руська» (137m walk)."
Each end covers every stop within a 300 m walk (stop_ids): a line's two directions often stop on opposite sides of a street under different names, as here, where Т01 towards the station leaves from «Руська», not «Площа Ринок». Options are ranked by stops plus walking (150 m of walking weighs as one stop), one per route and direction. A direction's last stop counts as a place to get off, not to board.
transfer_options hold trips with exactly one interchange, never more. Each has two legs (same fields as a direct option, minus the walks) and transfer_walk_meters: the interchange may be the same stop (0) or any stop within 300 m of where the first leg ends, so a cluster of stops around a square or junction works as one interchange. A line that already reaches the destination directly is never used as either leg, and a transfer costs as much as 5 extra stops in the ranking. Transfer options are listed (up to 5) when there is no direct route, or when they beat the best direct one. Both lists empty means the trip needs two or more transfers.
map_stops is the best trip's stops in riding order (a transfer option when one is listed, since those only appear when they beat every direct one), each with a role: board, transfer (same-stop interchange) or transfer_alight + transfer_board (walking interchange), and alight. The map block plots them, centred on the box around all of them (interchange included) with zoom 14–11 by its size.
get_route_static — example
stops[0] is direction 0 (outbound), stops[1] direction 1 (return). departures and schedule are populated for the first stop of each direction; other stops have empty arrays. schedule.workday is Monday–Friday, schedule.saturday / schedule.sunday the two weekend days (they can differ); schedule.weekend merges both and is kept for backward compatibility; departures keeps today's schedule for backward compatibility. With include_shapes: true, data.shapes holds one [lat, lng] polyline per direction and the map block adds "polylines": "data.shapes".
get_route_realtime — example
route_name is the canonical short name whatever form was passed. direction indexes get_route_static's stops (0 = outbound, 1 = return) and destinations. next_stop is null when the feed has no trip update for the vehicle.
get_nearby_vehicles — example
get_vehicle_info — example
route is the route short name, falling back to the opaque GTFS route ID only when the route is missing from the local data. Either value is accepted as route_name by get_route_static and get_route_realtime. license_plate is null when the feed has none.
Prompts
Reusable instruction templates. stop_id is a positive integer or digits-only string.
Resources and resource templates
In addition to tools, the server exposes MCP resources for reference data that doesn't require a tool call:
{name} in timetable://route/{name} supports completion/complete ("t3" → "Т30", "a1" → "А01"). Unknown stops or routes fail with JSON-RPC error -32602 and data.uri (resource not found, per MCP 2026-07-28).
Security model
- Public read-only (no authentication).
- No mutating tools are exposed.
POST /mcp is rate-limited to 60 requests/min per IP (in-memory, resets on restart). Excess requests receive HTTP 429 with a JSON-RPC error body.
- Requests carrying
X-Internal-Key equal to the INTERNAL_API_KEY env var (the lad.lviv.ua frontend server) skip every rate limit.
robots.txt is only a best-effort discovery hint and not a protocol contract.
REST API
All endpoints return JSON. :code is a numeric stop code; :name is a route short name (e.g. T1, 32A) or numeric external ID.
Stops
GET /stops.json
All stops as a JSON array, sorted by code.
- Response: array of
{ code, name, eng_name, location: [lat, lng], routes, sign, sign_pdf }.
(GET /stops returns an HTML table instead.)
Per-stop route overrides
The upstream route list for a stop is sometimes behind reality. GET /stops
applies a stored override to its Маршрути column — removed routes shown red and
struck through, added ones green — and hangs the matching ?add=/?remove= on
that row's SVG and PDF links in the Табличка (stop sign), Мапа
(network poster, /:code/schema) and Панель (/:code/panel) columns, which offline.lad.lviv.ua and
pdf.lad.lviv.ua both understand.
The route column is always clickable: click a route to drop or restore it, type
one into the + box to add it.
Overrides live in the browser's own localStorage (see
public/stopOverrides.js), not on a server — no
account to edit through, no cache to purge, an edit applies at once. The trade
is scope: an override is visible only in the browser that made it, not to
anyone else who opens /stops.
/stops.json reports sign and sign_pdf without overrides applied.
GET /stops/:code
Single stop with live realtime timetable. Short-cached (5–10 s).
- Optional:
skipTimetableData=1 — omit live arrivals (long-cached response).
- Response:
{ code, name, eng_name, latitude, longitude, transfers, timetable }.
GET /stops/:code/timetable
Live timetable only for a stop. Short-cached (5–10 s).
- Response: array of timetable items.
GET /stops/:code/static
Static stop info without live data. Long-cached (30 days).
- Response:
{ code, name, eng_name, latitude, longitude, transfers }.
GET /closest?latitude={lat}&longitude={lng}
Nearby stops — same search as get_stops_around_location, for non-MCP clients.
- Optional:
radius — meters, clamped between 50 and 3000 (default 1000).
- Response: JSON array of
{ code, name, latitude, longitude, distance_meters } (sorted by distance).
Routes
GET /routes.json
All routes as a JSON array, sorted by short name.
- Optional:
full=1 — raw route objects from the timetable store (trip maps, shapes, departure maps; ~9 MB) instead of the list fields.
- Response: array of
{ external_id, short_name, long_name, color, type, stops_by_shape } (~20 KB). stops_by_shape holds stop codes per direction, keyed "0" and "1".
(GET /routes returns an HTML table.)
GET /routes/static/:name
Route shape, stop list, and metadata. Long-cached (30 days).
- Response:
{ id, color, type, route_short_name, route_long_name, stops: [[dir0…], [dir1…]], shapes }.
- Each stop object:
{ code, name, loc, transfers, departures, schedule }.
departures — today's departure times (HH:MM), populated only for direction 0 first stop. Kept for backward compatibility.
schedule — { workday: string[], saturday: string[], sunday: string[], weekend: string[] } departure times by day type (weekend = Saturday ∪ Sunday, deprecated), populated only for direction 0 first stop.
GET /routes/dynamic/:name
Live vehicle positions for a route. Short-cached (10 s).
- Response: array of
{ id, direction, location: [lat, lng], bearing, speed, lowfloor }. speed is m/s from the GPS unit, or null when not reported.
Vehicles
GET /vehicle/:vehicleId
Live position and upcoming stop arrivals for one vehicle. Short-cached (5 s).
- Response:
{ location: [lat, lng], routeId, bearing, speed, direction, licensePlate, arrivals }. speed is m/s from the GPS unit, or null when not reported.
GET /vehicle-by-plate/:plate
Look up a vehicle ID by its license plate. Short-cached (5 s).
- The plate is matched case-insensitively with spaces and dashes ignored (
BC-1234-AA, bc 1234 aa, and bc1234aa are all equivalent).
- Response:
{ vehicleId } — use the returned ID with GET /vehicle/:vehicleId.
GET /transport?latitude={lat}&longitude={lng}
Vehicles within 1 km of a point. Short-cached (10 s).
- Response: array of
{ id, route, routeId, direction, vehicle_type, color, location: [lat, lng], bearing, speed, lowfloor }. routeId is usable as :name in /routes/static/:name; direction matches the index into stops/shapes (0 = outbound, 1 = return, null if unknown). speed is m/s or null.
GET /disruptions?route={name}&stop={code}
Closures, detours and moved stops the city announced that are in force today. The GTFS feed carries none of them. Cached 5 min at the CDN.
- Hand-curated in
data/disruptions.json, checked against a schema at startup and in tests; add or edit an entry there and deploy. An entry is served from its since day through its until day (Kyiv time), so a stale one hides itself.
route (Cyrillic or Latin short name) and stop (numeric code) are optional filters; with either, only entries touching it are listed.
- Response:
{ disruptions, updated_at }. Each item: { id, kind, reason, since, until, until_text, routes, stops, alternatives, detour, note, source, url }. kind is suspended, detour, stop_moved or stop_closed; routes and alternatives are { name, id } (name like Т33, id the Latin form used in lad.lviv.ua URLs); detour is { via: [streets], skipped_stops: [codes] } or null.
Service and discovery
Deployment
Production runs on Cloud Run (timetable-api-node, europe-north1, project
timetable-252615) behind Cloudflare.
- Image. The Dockerfile imports the GTFS feed at build time
(
gtfs-import.ts, then scripts/slim-gtfs-db.ts empties the SQLite tables
the server never reads), so every image carries its own data snapshot.
last-modified.txt records the feed's Last-Modified header.
- Cloud Build.
cloudbuild.yaml builds, pushes and deploys the image. A
daily scheduled run sets _DATA_REFRESH=1 and skips the whole build when
the upstream static.zip is unchanged since the deployed revision.
- Manual.
make deploy builds a linux/amd64 image, pushes it and deploys
it. make smoke checks a few production endpoints; make clear-short-cache,
clear-long-cache and clear-all-cache purge Cloudflare by cache tag.
- npm package.
make publish bumps the patch version (which also syncs
server.json and openapi.yaml) and pushes the tag; the tag triggers
.github/workflows/publish.yml, which publishes to npm and the MCP Registry.
The package ships only the timetable-mcp stdio proxy.