timetable-api-node 1.1.9 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/INTEGRATION.md CHANGED
@@ -54,6 +54,22 @@ npx @modelcontextprotocol/inspector \
54
54
  --url https://api.lad.lviv.ua/mcp
55
55
  ```
56
56
 
57
+ ### MCP tools & arguments
58
+
59
+ All tools are read-only. Argument names are **exact** — pass them as shown.
60
+
61
+ | Tool | Arguments | Purpose |
62
+ |------|-----------|---------|
63
+ | `get_stop_realtime` | `stop_id` (number or digit string) | Live arrivals + vehicle positions for a stop. |
64
+ | `get_route_static` | `route_name` (string, e.g. `"T30"`) | Stop lists (both directions), departures, polylines. |
65
+ | `get_route_realtime` | `route_name` (string) | Live positions of all vehicles on a route. |
66
+ | `get_stop_geometry` | `stop_id` (number or digit string) | Stop marker + route polylines (no live data). |
67
+ | `get_stops_around_location` | `latitude`, `longitude` (numbers), `radius_meters` (int 50–3000, optional) | Discover stops near a coordinate. |
68
+ | `get_nearby_vehicles` | `latitude`, `longitude` (numbers) | Live vehicles within 1 km of a coordinate. |
69
+ | `get_vehicle_info` | `vehicle_id` (string) | Position, route, plate, upcoming stops for one vehicle. |
70
+
71
+ Every tool result is JSON with three keys — `view`, `data` (raw payload), and `ui_blocks` (ordered map/arrival-list rendering hints). Resolve a place name or address to a `stop_id` with `get_stops_around_location` before calling stop-based tools.
72
+
57
73
  ---
58
74
 
59
75
  ## LangChain (Python)
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Timetable API Node
2
2
 
3
3
  [![CI](https://img.shields.io/github/actions/workflow/status/vbhjckfd/timetable-api-node/ci.yml?branch=master&logo=github&label=CI)](https://github.com/vbhjckfd/timetable-api-node/actions/workflows/ci.yml)
4
- [![Node.js](https://img.shields.io/badge/node.js-24-43853d?logo=node.js&logoColor=white)](https://github.com/vbhjckfd/timetable-api-node/blob/master/.nvmrc)
4
+ [![Node.js](https://img.shields.io/badge/node.js-26-43853d?logo=node.js&logoColor=white)](https://github.com/vbhjckfd/timetable-api-node/blob/master/.nvmrc)
5
5
  [![License: WTFPL](https://img.shields.io/github/license/vbhjckfd/timetable-api-node?label=license)](https://github.com/vbhjckfd/timetable-api-node/blob/master/LICENSE)
6
6
  [![MCP Registry](https://img.shields.io/badge/MCP_Registry-listed-6366f1?style=flat-square)](https://registry.modelcontextprotocol.io/v0/servers/io.github.vbhjckfd%2Ftimetable-api-node/versions)
7
7
 
@@ -14,7 +14,7 @@ Express-based API for Lviv transport timetable data with a read-only MCP endpoin
14
14
 
15
15
  ## Requirements
16
16
 
17
- - Node.js 24 (see `.nvmrc`)
17
+ - Node.js 26 (see `.nvmrc`)
18
18
 
19
19
  ## Run locally
20
20
 
@@ -29,6 +29,36 @@ make start
29
29
  nvm use && make test
30
30
  ```
31
31
 
32
+ ## Monitoring
33
+
34
+ Two optional integrations, both off unless their environment variable is set:
35
+
36
+ | Variable | Effect |
37
+ | --- | --- |
38
+ | `SENTRY_DSN` | Error reporting via `instrument.js` |
39
+ | `NEW_RELIC_LICENSE_KEY` | New Relic APM via `newrelic.cjs` |
40
+
41
+ New Relic runs as a preloaded agent, so `npm start` carries the flags:
42
+
43
+ ```bash
44
+ node -r dotenv/config -r newrelic --import newrelic/esm-loader.mjs index.js
45
+ ```
46
+
47
+ `dotenv/config` is preloaded first so `.env` is populated before the agent
48
+ reads its configuration. The config file is `newrelic.cjs` (the agent is
49
+ CommonJS and this project is ESM) and holds no secrets — the key comes from the
50
+ environment. `/health` is excluded from transactions via `rules.ignore`.
51
+
52
+ The account is in the **EU** region; its license key starts with `eu01xx` and
53
+ the agent picks the collector from that prefix. Use the 40-character ingest
54
+ license key, not an `NRAK-...` user API key.
55
+
56
+ Cloud Run reads the key from Secret Manager:
57
+
58
+ ```bash
59
+ gcloud run services update timetable-api-node --region=us-central1 --project=timetable-252615 --set-secrets=NEW_RELIC_LICENSE_KEY=new-relic-license-key:latest
60
+ ```
61
+
32
62
  ## MCP Server
33
63
 
34
64
  This service exposes a public read-only MCP endpoint over Streamable HTTP.
@@ -86,7 +116,7 @@ graph LR;
86
116
  }
87
117
  ```
88
118
 
89
- Successful tool responses return **stringified JSON** inside MCP `content` items (`type: "text"`), and each payload follows a strict UI contract:
119
+ Successful tool responses return a **natural-language text summary** inside MCP `content` items (`type: "text"`) — e.g. *"Stop «Opera»: 3 arrivals. Next: T01 → «Rynok» in 2 min."* The full structured payload is in the `structuredContent` field (for schema-aware clients). Each `structuredContent` payload follows a strict UI contract:
90
120
 
91
121
  ```json
92
122
  {
@@ -110,6 +140,8 @@ Consistency rule: each vehicle rendered on map must either have a matching ETA i
110
140
  - `get_route_realtime`
111
141
  - `get_stop_geometry`
112
142
  - `get_stops_around_location`
143
+ - `get_nearby_vehicles`
144
+ - `get_vehicle_info`
113
145
 
114
146
  <details>
115
147
  <summary><code>get_stop_realtime</code> — input &amp; example</summary>
@@ -179,12 +211,16 @@ Consistency rule: each vehicle rendered on map must either have a matching ETA i
179
211
  },
180
212
  "stops": [
181
213
  [
182
- { "id": "101", "name": "Головний вокзал", "lat": 49.841, "lng": 24.003, "departures": ["05:30", "05:52"] },
183
- { "id": "707", "name": "Стадіон Сільмаш", "lat": 49.838, "lng": 24.021, "departures": [] }
214
+ {
215
+ "id": "101", "name": "Головний вокзал", "lat": 49.841, "lng": 24.003,
216
+ "departures": ["05:30", "05:52"],
217
+ "schedule": { "workday": ["05:30", "05:52", "06:10"], "weekend": ["07:00", "07:30"] }
218
+ },
219
+ { "id": "707", "name": "Стадіон Сільмаш", "lat": 49.838, "lng": 24.021, "departures": [], "schedule": { "workday": [], "weekend": [] } }
184
220
  ],
185
221
  [
186
- { "id": "707", "name": "Стадіон Сільмаш", "lat": 49.838, "lng": 24.021, "departures": [] },
187
- { "id": "101", "name": "Головний вокзал", "lat": 49.841, "lng": 24.003, "departures": [] }
222
+ { "id": "707", "name": "Стадіон Сільмаш", "lat": 49.838, "lng": 24.021, "departures": [], "schedule": { "workday": [], "weekend": [] } },
223
+ { "id": "101", "name": "Головний вокзал", "lat": 49.841, "lng": 24.003, "departures": [], "schedule": { "workday": [], "weekend": [] } }
188
224
  ]
189
225
  ],
190
226
  "shapes": [
@@ -211,7 +247,7 @@ Consistency rule: each vehicle rendered on map must either have a matching ETA i
211
247
  }
212
248
  ```
213
249
 
214
- `stops[0]` is direction 0 (outbound), `stops[1]` is direction 1 (return). `departures` is populated only for direction 0. `shapes` follows the same two-element order. The map block uses direction-0 polyline and all unique stops as markers.
250
+ `stops[0]` is direction 0 (outbound), `stops[1]` is direction 1 (return). `departures` and `schedule` are populated only for the **first stop of direction 0**; all other stops have empty arrays. `schedule.workday` contains Monday–Friday departure times; `schedule.weekend` contains Saturday–Sunday departure times. `departures` keeps today's schedule for backward compatibility. `shapes` follows the same two-element order. The map block uses direction-0 polyline and all unique stops as markers.
215
251
 
216
252
  </details>
217
253
 
@@ -357,10 +393,113 @@ Map zoom is **15** for radius ≤ 1500 m and **14** for larger radii (up to 3000
357
393
 
358
394
  </details>
359
395
 
396
+ <details>
397
+ <summary><code>get_nearby_vehicles</code> — input &amp; example</summary>
398
+
399
+ Returns live positions for all transit vehicles within 1 km of given coordinates. Wraps the same backend as `GET /transport`.
400
+
401
+ **Arguments (JSON):**
402
+
403
+ | Field | Type | Required |
404
+ |-------|------|----------|
405
+ | `latitude` | number, −90…90 | yes |
406
+ | `longitude` | number, −180…180 | yes |
407
+
408
+ **Example result** (shape only):
409
+
410
+ ```json
411
+ {
412
+ "view": "transit_realtime",
413
+ "data": {
414
+ "center_lat": 49.84,
415
+ "center_lng": 24.03,
416
+ "vehicles": [
417
+ {
418
+ "id": "tram_123",
419
+ "route": "T01",
420
+ "vehicle_type": "tram",
421
+ "lat": 49.841,
422
+ "lng": 24.031,
423
+ "bearing": 90,
424
+ "lowfloor": true
425
+ }
426
+ ],
427
+ "updated_at": "2026-01-23T12:00:00Z"
428
+ },
429
+ "ui_blocks": [
430
+ {
431
+ "type": "map",
432
+ "data": {
433
+ "center": [49.84, 24.03],
434
+ "zoom": 14,
435
+ "vehicles": [{ "id": "tram_123", "route": "T01", "lat": 49.841, "lng": 24.031, "bearing": 90, "eta_status": "unassigned" }]
436
+ }
437
+ }
438
+ ]
439
+ }
440
+ ```
441
+
442
+ </details>
443
+
444
+ <details>
445
+ <summary><code>get_vehicle_info</code> — input &amp; example</summary>
446
+
447
+ Full details for one vehicle by its ID: position, route, license plate, direction, and upcoming stop arrival times. Vehicle IDs come from `get_route_realtime`, `get_nearby_vehicles`, or `get_stop_realtime`.
448
+
449
+ **Arguments (JSON):**
450
+
451
+ | Field | Type | Required |
452
+ |-------|------|----------|
453
+ | `vehicle_id` | string | yes |
454
+
455
+ **Example result** (shape only):
456
+
457
+ ```json
458
+ {
459
+ "view": "transit_realtime",
460
+ "data": {
461
+ "vehicle_id": "tram_123",
462
+ "route": "route-ext-1",
463
+ "license_plate": "BC-1234-AB",
464
+ "lat": 49.841,
465
+ "lng": 24.031,
466
+ "bearing": 90,
467
+ "direction": 0,
468
+ "upcoming_stops": [
469
+ { "code": 707, "arrival": "2026-01-23T12:05:00Z", "departure": null },
470
+ { "code": 708, "arrival": "2026-01-23T12:08:00Z", "departure": null }
471
+ ],
472
+ "updated_at": "2026-01-23T12:00:00Z"
473
+ },
474
+ "ui_blocks": [
475
+ {
476
+ "type": "map",
477
+ "data": { "center": [49.841, 24.031], "zoom": 15, "vehicles": [{ "id": "tram_123", "eta_status": "unassigned" }] }
478
+ }
479
+ ]
480
+ }
481
+ ```
482
+
483
+ </details>
484
+
485
+
486
+ ### Resources and resource templates
487
+
488
+ In addition to tools, the server exposes MCP **resources** for reference data that doesn't require a tool call:
489
+
490
+ | URI | Description |
491
+ |-----|-------------|
492
+ | `timetable://about` | Scope, usage, and data caveats for this server (Markdown) |
493
+ | `timetable://reference/tools` | Tools reference table (Markdown) |
494
+ | `timetable://reference/prompts` | Prompt templates catalog (Markdown) |
495
+ | `timetable://stop/{code}` | Static info for a stop by numeric code — name, coordinates, serving routes (JSON) |
496
+ | `timetable://route/{name}` | Static metadata for a route by short name — color, type, stop counts (JSON) |
497
+
360
498
  ### Security model
361
499
 
362
500
  - Public read-only (no authentication).
363
501
  - No mutating tools are exposed.
502
+ - `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.
364
503
  - `robots.txt` is only a best-effort discovery hint and not a protocol contract.
365
504
 
366
505
  ## REST API
@@ -377,6 +516,25 @@ All stops as a JSON array, sorted by code.
377
516
 
378
517
  (`GET /stops` returns an HTML table instead.)
379
518
 
519
+ #### Per-stop route overrides
520
+
521
+ The upstream route list for a stop is sometimes behind reality. `GET /stops`
522
+ applies a stored override to its `Маршрути` column — removed routes shown red and
523
+ struck through, added ones green — and hangs the matching `?add=`/`?remove=` on
524
+ that row's SVG and PDF links, which `offline.lad.lviv.ua` and `pdf.lad.lviv.ua`
525
+ both understand.
526
+
527
+ The route column is always clickable: click a route to drop or restore it, type
528
+ one into the `+` box to add it.
529
+
530
+ Overrides live in the browser's own `localStorage` (see
531
+ [`public/stopOverrides.js`](public/stopOverrides.js)), not on a server — no
532
+ account to edit through, no cache to purge, an edit applies at once. The trade
533
+ is scope: an override is visible only in the browser that made it, not to
534
+ anyone else who opens `/stops`.
535
+
536
+ `/stops.json` reports `sign` and `sign_pdf` without overrides applied.
537
+
380
538
  #### `GET /stops/:code`
381
539
 
382
540
  Single stop with live realtime timetable. Short-cached (5–10 s).
@@ -418,12 +576,15 @@ All routes as a JSON array, sorted by short name.
418
576
  Route shape, stop list, and metadata. Long-cached (30 days).
419
577
 
420
578
  - **Response:** `{ id, color, type, route_short_name, route_long_name, stops: [[dir0…], [dir1…]], shapes }`.
579
+ - Each stop object: `{ code, name, loc, transfers, departures, schedule }`.
580
+ - `departures` — today's departure times (HH:MM), populated only for direction 0 first stop. Kept for backward compatibility.
581
+ - `schedule` — `{ workday: string[], weekend: string[] }` departure times by day type, populated only for direction 0 first stop.
421
582
 
422
583
  #### `GET /routes/dynamic/:name`
423
584
 
424
585
  Live vehicle positions for a route. Short-cached (10 s).
425
586
 
426
- - **Response:** array of `{ id, direction, location: [lat, lng], bearing, lowfloor }`.
587
+ - **Response:** array of `{ id, direction, location: [lat, lng], bearing, speed, lowfloor }`. `speed` is m/s from the GPS unit, or `null` when not reported.
427
588
 
428
589
  ### Vehicles
429
590
 
@@ -431,7 +592,7 @@ Live vehicle positions for a route. Short-cached (10 s).
431
592
 
432
593
  Live position and upcoming stop arrivals for one vehicle. Short-cached (5 s).
433
594
 
434
- - **Response:** `{ location: [lat, lng], routeId, bearing, direction, licensePlate, arrivals }`.
595
+ - **Response:** `{ location: [lat, lng], routeId, bearing, speed, direction, licensePlate, arrivals }`. `speed` is m/s from the GPS unit, or `null` when not reported.
435
596
 
436
597
  #### `GET /vehicle-by-plate/:plate`
437
598
 
@@ -444,4 +605,4 @@ Look up a vehicle ID by its license plate. Short-cached (5 s).
444
605
 
445
606
  Vehicles within 1 km of a point. Short-cached (10 s).
446
607
 
447
- - **Response:** array of `{ id, route, vehicle_type, color, location: [lat, lng], bearing, lowfloor }`.
608
+ - **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`.
package/index.js CHANGED
@@ -2,6 +2,7 @@ import "./instrument.js";
2
2
  import "dotenv/config";
3
3
 
4
4
  import * as Sentry from "@sentry/node";
5
+ import pkg from "./package.json" with { type: "json" };
5
6
  import path from "path";
6
7
  const __dirname = import.meta.dirname;
7
8
  const PORT = process.env.PORT || 8080;
@@ -9,8 +10,8 @@ const PORT = process.env.PORT || 8080;
9
10
  import { openDb } from "gtfs";
10
11
  import { readFile } from "fs/promises";
11
12
  import cors from "cors";
13
+ import rateLimit, { ipKeyGenerator } from "express-rate-limit";
12
14
  import express from "express";
13
- import bodyParser from "body-parser";
14
15
  import localDb from "./connections/timetableSqliteDb.js";
15
16
 
16
17
  import notFoundAction from "./actions/notFoundAction.js";
@@ -32,15 +33,29 @@ import {
32
33
  buildMcpServerCard,
33
34
  handleMcpPostRequest,
34
35
  } from "./mcp/timetableMcpServer.js";
36
+ import healthAction from "./actions/healthAction.js";
37
+ import errorHandler from "./utils/errorHandler.js";
35
38
 
36
39
  const app = express();
37
40
 
38
41
  app.set("trust proxy", true);
39
42
 
43
+ /**
44
+ * Cache headers for responses baked into the image: docs, manifests, icons.
45
+ * A GTFS data refresh never changes these, so they are tagged "long" and the
46
+ * daily refresh build leaves them alone; only code-push builds purge the tag
47
+ * (see the DropCache step in cloudbuild.yaml). GTFS-derived responses use
48
+ * "short" instead and are purged by every build.
49
+ */
50
+ const setStaticAssetCache = (res, maxAgeSeconds = 3600 * 24) =>
51
+ res
52
+ .set("Cache-Control", `public, max-age=0, s-maxage=${maxAgeSeconds}`)
53
+ .set("Cache-Tag", "long");
54
+
40
55
  app.use(cors());
41
56
 
42
57
  app.use((req, res, next) => {
43
- const baseUrl = `${req.protocol}://${req.hostname}`;
58
+ const baseUrl = `${req.protocol}://${req.host}`;
44
59
  res.set(
45
60
  "Link",
46
61
  [
@@ -53,27 +68,93 @@ app.use((req, res, next) => {
53
68
  next();
54
69
  });
55
70
 
56
- app.use(bodyParser.json({ limit: "100kb" }));
71
+ app.use(express.json({ limit: "100kb" }));
72
+
73
+ // `trust proxy` is true above, which makes req.ip the leftmost X-Forwarded-For
74
+ // entry — a value the caller writes, so keying a limiter on it would let one
75
+ // client mint a fresh bucket per request. Cloudflare sets CF-Connecting-IP at
76
+ // the edge and overwrites whatever the client sent, so prefer that and fall
77
+ // back to req.ip only for a request that did not arrive through the edge.
78
+ // ipKeyGenerator collapses IPv6 to a /56, so a single allocation cannot spread
79
+ // its hits across addresses either.
80
+ const clientIpKey = (req) =>
81
+ ipKeyGenerator(req.headers["cf-connecting-ip"] ?? req.ip ?? "");
82
+
83
+ // Limits are per client address and sit well above what a person browsing
84
+ // generates. They exist to bound the unattended callers: a scraper looping a
85
+ // fixed set of stop codes, or an app under development replaying deploy
86
+ // loops, both of which otherwise run against the origin with nothing to push
87
+ // back. Liveness paths are exempt so a probe never trips a limit some abusive
88
+ // neighbour filled, and /mcp is exempt because it carries its own limiter
89
+ // below: sharing this bucket meant the global one always emptied first (it
90
+ // counts every path) and answered MCP clients with a body that is not
91
+ // JSON-RPC.
92
+ const globalRateLimiter = rateLimit({
93
+ windowMs: 60_000,
94
+ limit: 60,
95
+ standardHeaders: true,
96
+ legacyHeaders: false,
97
+ keyGenerator: clientIpKey,
98
+ skip: (req) =>
99
+ req.path === "/health" || req.path === "/ping" || req.path === "/mcp",
100
+ message: { error: "Rate limit exceeded. Try again later." },
101
+ });
102
+
103
+ // /routes/dynamic/:name and /transport both fan out over the live vehicle
104
+ // feed, which makes them the most expensive responses here and the pair a
105
+ // single client can do the most damage with. Their bucket is drawn on top of
106
+ // the global one, so this only ever narrows what that already allows.
107
+ const liveDataRateLimiter = rateLimit({
108
+ windowMs: 60_000,
109
+ limit: 40,
110
+ standardHeaders: true,
111
+ legacyHeaders: false,
112
+ keyGenerator: clientIpKey,
113
+ message: { error: "Rate limit exceeded. Try again later." },
114
+ });
115
+
116
+ // Where the unattended traffic actually lands. The stop endpoints are what a
117
+ // scraper loops over, and it runs round the clock at a rate that sits under
118
+ // the global 60/minute ceiling by design, so that bucket never catches it —
119
+ // the giveaway is a request curve with no diurnal shape at all, roughly as
120
+ // busy at 04:00 as at midday. Neither stop view polls (unlike the route page,
121
+ // which refreshes every 10s), so a stop is one or two requests per
122
+ // navigation: 20/minute is around ten stop views a minute from one address,
123
+ // far above a person browsing and well under the observed scraping rate.
124
+ // /stops/:code/static is left out deliberately — it is cheap, cached, and
125
+ // loaded alongside a timetable, so counting it would halve the real budget.
126
+ // Drawn on top of the global bucket, so like the live-data one it only ever
127
+ // narrows what that already allows.
128
+ const stopDataRateLimiter = rateLimit({
129
+ windowMs: 60_000,
130
+ limit: 20,
131
+ standardHeaders: true,
132
+ legacyHeaders: false,
133
+ keyGenerator: clientIpKey,
134
+ message: { error: "Rate limit exceeded. Try again later." },
135
+ });
136
+
137
+ app.use(globalRateLimiter);
57
138
 
58
- app.get("/stops/:code/timetable", validateStopCode, getStopTimetableAction);
139
+ app.get("/stops/:code/timetable", stopDataRateLimiter, validateStopCode, getStopTimetableAction);
59
140
  app.get("/stops/:code/static", validateStopCode, getStopStaticDataAction);
60
- app.get("/stops/:code", validateStopCode, getSingleStopAction);
141
+ app.get("/stops/:code", stopDataRateLimiter, validateStopCode, getSingleStopAction);
61
142
  app.get("/stops.json", getAllStopsAction);
62
143
  app.get("/stops", getAllStopsAction);
63
144
  app.get("/closest", getClosestStopsAction);
64
145
 
65
146
  app.get("/routes.json", getAllRoutesAction);
66
147
  app.get("/routes", getAllRoutesAction);
67
- app.get("/routes/dynamic/:name", routeInfoDynamicAction);
148
+ app.get("/routes/dynamic/:name", liveDataRateLimiter, routeInfoDynamicAction);
68
149
  app.get("/routes/static/:name", routeInfoStaticAction);
69
150
  app.get("/vehicle/:vehicleId", vehicleInfoAction);
70
151
  app.get("/vehicle-by-plate/:plate", vehicleByPlateAction);
71
- app.get("/transport", closestTransportAction);
152
+ app.get("/transport", liveDataRateLimiter, closestTransportAction);
72
153
 
73
154
  app.get("/sitemap.xml", sitemapAction);
74
155
 
75
156
  app.get("/openapi.yaml", (req, res) => {
76
- res.set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24}`);
157
+ setStaticAssetCache(res);
77
158
  res.type("application/yaml");
78
159
  res.sendFile(path.join(__dirname, "openapi.yaml"));
79
160
  });
@@ -83,8 +164,8 @@ app.get("/.well-known/openapi.yaml", (req, res) => {
83
164
  });
84
165
 
85
166
  app.get("/.well-known/ai-plugin.json", (req, res) => {
86
- const baseUrl = `${req.protocol}://${req.hostname}`;
87
- res.set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24}`);
167
+ const baseUrl = `${req.protocol}://${req.host}`;
168
+ setStaticAssetCache(res);
88
169
  res.json({
89
170
  schema_version: "v1",
90
171
  name_for_human: "Lviv Public Transport",
@@ -105,14 +186,14 @@ app.get("/.well-known/ai-plugin.json", (req, res) => {
105
186
  });
106
187
 
107
188
  app.get("/.well-known/agent.json", (req, res) => {
108
- const baseUrl = `${req.protocol}://${req.hostname}`;
109
- res.set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24}`);
189
+ const baseUrl = `${req.protocol}://${req.host}`;
190
+ setStaticAssetCache(res);
110
191
  res.json({
111
192
  name: "Lviv Public Transport",
112
193
  description:
113
194
  "Real-time and static public transport data for Lviv, Ukraine: stops, routes, timetables, and live vehicle positions. No API key required.",
114
195
  url: baseUrl,
115
- version: "1.1.0",
196
+ version: pkg.version,
116
197
  iconUrl: `${baseUrl}/favicon.png`,
117
198
  documentationUrl: `${baseUrl}/llms.txt`,
118
199
  capabilities: {
@@ -171,6 +252,26 @@ app.get("/.well-known/agent.json", (req, res) => {
171
252
  outputModes: ["application/json"],
172
253
  examples: ["Get map data for stop 707"],
173
254
  },
255
+ {
256
+ id: "get_nearby_vehicles",
257
+ name: "Get Nearby Vehicles",
258
+ description:
259
+ "Live positions for all transit vehicles within 1 km of a given latitude/longitude.",
260
+ tags: ["transit", "realtime", "vehicles", "location", "lviv"],
261
+ inputModes: ["text/plain", "application/json"],
262
+ outputModes: ["application/json"],
263
+ examples: ["What transport is near 49.84, 24.03?", "Live vehicles around me"],
264
+ },
265
+ {
266
+ id: "get_vehicle_info",
267
+ name: "Get Vehicle Info",
268
+ description:
269
+ "Full details for one vehicle by ID: position, bearing, route, license plate, and upcoming stops.",
270
+ tags: ["transit", "realtime", "vehicle", "tracking", "lviv"],
271
+ inputModes: ["text/plain"],
272
+ outputModes: ["application/json"],
273
+ examples: ["Track vehicle 12345", "Where is vehicle 12345 heading?"],
274
+ },
174
275
  ],
175
276
  authentication: { schemes: [] },
176
277
  provider: {
@@ -184,13 +285,13 @@ app.get("/.well-known/agent.json", (req, res) => {
184
285
  });
185
286
 
186
287
  app.get("/llms.txt", (req, res) => {
187
- res.set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24}`);
288
+ setStaticAssetCache(res);
188
289
  res.type("text/plain");
189
290
  res.sendFile(path.join(__dirname, "llms.txt"));
190
291
  });
191
292
 
192
293
  app.get("/INTEGRATION.md", (req, res) => {
193
- res.set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24}`);
294
+ setStaticAssetCache(res);
194
295
  res.type("text/markdown");
195
296
  res.sendFile(path.join(__dirname, "INTEGRATION.md"));
196
297
  });
@@ -199,7 +300,26 @@ app.get("/ping", (req, res) => {
199
300
  res.json({});
200
301
  });
201
302
 
202
- app.post("/mcp", async (req, res) => {
303
+ app.get("/health", healthAction);
304
+
305
+ // express-rate-limit rather than a hand-rolled counter map: its MemoryStore
306
+ // drops the whole hit table each window, so the key space cannot grow without
307
+ // bound across the instance's lifetime.
308
+ const mcpRateLimiter = rateLimit({
309
+ windowMs: 60_000,
310
+ limit: 60,
311
+ standardHeaders: true,
312
+ legacyHeaders: false,
313
+ keyGenerator: clientIpKey,
314
+ handler: (req, res) =>
315
+ res.status(429).json({
316
+ jsonrpc: "2.0",
317
+ error: { code: -32000, message: "Rate limit exceeded. Try again later." },
318
+ id: null,
319
+ }),
320
+ });
321
+
322
+ app.post("/mcp", mcpRateLimiter, async (req, res) => {
203
323
  try {
204
324
  await handleMcpPostRequest(req, res);
205
325
  } catch (error) {
@@ -218,6 +338,10 @@ app.post("/mcp", async (req, res) => {
218
338
  });
219
339
 
220
340
  app.all("/mcp", (req, res) => {
341
+ // RFC 9110: a 405 has to say which methods the resource does take. The
342
+ // transport is stateless, so there is no SSE stream for GET to open and
343
+ // no session for DELETE to end — POST is the whole surface.
344
+ res.set("Allow", "POST");
221
345
  res.status(405).json({
222
346
  jsonrpc: "2.0",
223
347
  error: {
@@ -229,8 +353,8 @@ app.all("/mcp", (req, res) => {
229
353
  });
230
354
 
231
355
  app.get("/.well-known/oauth-protected-resource", (req, res) => {
232
- const baseUrl = `${req.protocol}://${req.hostname}`;
233
- res.set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24}`);
356
+ const baseUrl = `${req.protocol}://${req.host}`;
357
+ setStaticAssetCache(res);
234
358
  res.json({
235
359
  resource: baseUrl,
236
360
  authorization_required: false,
@@ -245,18 +369,24 @@ app.get("/.well-known/oauth-protected-resource", (req, res) => {
245
369
  });
246
370
 
247
371
  app.get("/.well-known/mcp/server-card.json", (req, res) => {
248
- const baseUrl = `${req.protocol}://${req.hostname}`;
372
+ const baseUrl = `${req.protocol}://${req.host}`;
373
+ // The card carries pkg.version, so a code push has to be able to purge it;
374
+ // without the "long" tag the DropCache step in cloudbuild.yaml could not
375
+ // reach it and clients kept a stale version for a day.
376
+ setStaticAssetCache(res);
249
377
  res.json(buildMcpServerCard(baseUrl));
250
378
  });
251
379
 
252
380
  app.get("/mcp-icon.svg", (req, res) => {
253
381
  res.type("image/svg+xml");
254
- res.set("Cache-Control", "public, max-age=86400");
382
+ // Was a browser-side max-age=86400, which no purge can reach; moved to
383
+ // s-maxage so a code push actually invalidates it.
384
+ setStaticAssetCache(res);
255
385
  res.sendFile(path.join(__dirname, "mcp", "mcp-icon.svg"));
256
386
  });
257
387
 
258
388
  app.get("/robots.txt", (req, res) => {
259
- const baseUrl = `${req.protocol}://${req.hostname}`;
389
+ const baseUrl = `${req.protocol}://${req.host}`;
260
390
  const lines = [
261
391
  "User-agent: *",
262
392
  "Disallow: /private/",
@@ -273,23 +403,37 @@ app.get("/last-modified.txt", (req, res, next) => {
273
403
  });
274
404
 
275
405
  app.get("/favicon.ico", (req, res, next) => {
276
- res
277
- .set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24 * 31}`)
278
- .set("Cache-Tag", "long");
406
+ setStaticAssetCache(res, 3600 * 24 * 31);
279
407
  res.sendFile(path.join(__dirname, "favicon.ico"));
280
408
  });
281
409
 
410
+ // Applies the per-stop route overrides to the /stops listing in the browser.
411
+ // Tagged "long" like the other baked-in assets: it ships with the image, so a
412
+ // GTFS refresh leaves it alone and a code push purges it. Cloudflare caches it
413
+ // for a day on that tag, so an uncached request reaching this far is rare —
414
+ // the limiter is here so a cache-bypassing client can't turn the file read
415
+ // underneath sendFile into an amplifier.
416
+ const staticFileRateLimiter = rateLimit({
417
+ windowMs: 60_000,
418
+ limit: 60,
419
+ standardHeaders: true,
420
+ legacyHeaders: false,
421
+ keyGenerator: clientIpKey,
422
+ });
423
+
424
+ app.get("/stop-overrides.js", staticFileRateLimiter, (req, res) => {
425
+ setStaticAssetCache(res);
426
+ res.type("text/javascript");
427
+ res.sendFile(path.join(__dirname, "public", "stopOverrides.js"));
428
+ });
429
+
282
430
  app.get("/smithery.json", (req, res) => {
283
- res
284
- .set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24 * 7}`)
285
- .set("Cache-Tag", "long");
431
+ setStaticAssetCache(res, 3600 * 24 * 7);
286
432
  res.sendFile(path.join(__dirname, "smithery.json"));
287
433
  });
288
434
 
289
435
  app.get("/server.json", (req, res) => {
290
- res
291
- .set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24 * 7}`)
292
- .set("Cache-Tag", "long");
436
+ setStaticAssetCache(res, 3600 * 24 * 7);
293
437
  res.sendFile(path.join(__dirname, "server.json"));
294
438
  });
295
439
 
@@ -297,14 +441,11 @@ app.use(notFoundAction);
297
441
 
298
442
  Sentry.setupExpressErrorHandler(app);
299
443
 
300
- app.use(function (err, req, res, next) {
301
- console.error(err.stack);
302
- res.status(500).json({ error: "Internal server error" });
303
- });
444
+ app.use(errorHandler);
304
445
 
305
446
  app.on("ready", () => {
306
447
  app.listen(PORT, () => {
307
- console.log("Started!");
448
+ console.log(`Started! http://localhost:${PORT}`);
308
449
  });
309
450
  });
310
451
 
package/mcp/stdio.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // to the live Lviv Public Transport MCP server without requiring a local database.
4
4
  import "dotenv/config";
5
5
 
6
+ import pkg from "../package.json" with { type: "json" };
6
7
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
7
8
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8
9
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -11,6 +12,7 @@ import {
11
12
  CallToolRequestSchema,
12
13
  ListToolsRequestSchema,
13
14
  ListResourcesRequestSchema,
15
+ ListResourceTemplatesRequestSchema,
14
16
  ReadResourceRequestSchema,
15
17
  ListPromptsRequestSchema,
16
18
  GetPromptRequestSchema,
@@ -22,24 +24,25 @@ const upstreamUrl = new URL(
22
24
 
23
25
  async function main() {
24
26
  const upstream = new Client(
25
- { name: "lviv-timetable-stdio-proxy", version: "1.0.0" },
27
+ { name: "lviv-timetable-stdio-proxy", version: pkg.version },
26
28
  { capabilities: {} },
27
29
  );
28
30
 
29
31
  await upstream.connect(new StreamableHTTPClientTransport(upstreamUrl));
30
32
 
31
- const [{ tools }, { resources }, { prompts }] = await Promise.all([
33
+ const [{ tools }, { resources }, { resourceTemplates }, { prompts }] = await Promise.all([
32
34
  upstream.listTools(),
33
35
  upstream.listResources(),
36
+ upstream.listResourceTemplates(),
34
37
  upstream.listPrompts(),
35
38
  ]);
36
39
 
37
40
  const server = new Server(
38
- { name: "com.lad.lviv/timetable-api", version: "1.0.0" },
41
+ { name: "com.lad.lviv/timetable-api", version: pkg.version },
39
42
  {
40
43
  capabilities: {
41
44
  ...(tools.length && { tools: {} }),
42
- ...(resources.length && { resources: {} }),
45
+ ...(resources.length || resourceTemplates.length ? { resources: {} } : {}),
43
46
  ...(prompts.length && { prompts: {} }),
44
47
  },
45
48
  },
@@ -47,6 +50,7 @@ async function main() {
47
50
 
48
51
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
49
52
  server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources }));
53
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({ resourceTemplates }));
50
54
  server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts }));
51
55
 
52
56
  server.setRequestHandler(CallToolRequestSchema, async (req) =>
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "timetable-api-node",
3
- "version": "1.1.9",
3
+ "version": "1.4.0",
4
4
  "description": "Lviv (Ukraine) public transport REST API and read-only Model Context Protocol (MCP) server: stops, timetables, routes, live vehicle positions, GTFS/GTFS-RT. No API key required.",
5
5
  "main": "index.js",
6
6
  "type": "module",
7
+ "engines": {
8
+ "node": ">=22"
9
+ },
7
10
  "bin": {
8
11
  "timetable-mcp": "mcp/stdio.js"
9
12
  },
@@ -34,10 +37,11 @@
34
37
  "cors": "^2.8.5",
35
38
  "dotenv": "^17.4",
36
39
  "express": "^5.2.1",
40
+ "express-rate-limit": "^8.6.2",
37
41
  "gtfs": "^4.18.5",
38
42
  "gtfs-realtime-bindings": "^2.0.0",
39
43
  "lokijs": "^1.5.12",
40
- "npm-config": "^0.2.0",
44
+ "newrelic": "^14.3.4",
41
45
  "protobufjs": ">=8.2.0",
42
46
  "public-google-sheets-parser": "^1.3.2",
43
47
  "tar": ">=7.5.15",
@@ -46,7 +50,7 @@
46
50
  "scripts": {
47
51
  "import": "node gtfs-import.js",
48
52
  "import-slim": "node gtfs-import-slim.js",
49
- "start": "node index.js",
53
+ "start": "node -r dotenv/config -r newrelic --import newrelic/esm-loader.mjs index.js",
50
54
  "test": "vitest run",
51
55
  "test:watch": "vitest"
52
56
  },