timetable-api-node 1.7.1 → 1.7.4

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
@@ -23,6 +23,44 @@ Open **Settings → Connectors → Add custom connector** and paste `https://api
23
23
 
24
24
  `claude_desktop_config.json` only takes stdio servers (`command`/`args`), not a `url` — to go through the config file instead, use the stdio entry below.
25
25
 
26
+ ### ChatGPT
27
+
28
+ Paid plans (Plus, Pro, Business, Enterprise, Edu), on the web:
29
+
30
+ 1. **Settings → Apps & Connectors → Advanced settings** → turn on **Developer mode**.
31
+ 2. Back in **Apps & Connectors**, click **Create** (Business/Enterprise/Edu: an admin can also publish it to the whole workspace).
32
+ 3. Name it (e.g. "Lviv transport"), set the MCP server URL to `https://api.lad.lviv.ua/mcp`, and authentication to **No authentication**.
33
+ 4. In a chat, enable the connector from the **+** menu and ask, e.g. "When is the next tram at stop 707?"
34
+
35
+ ChatGPT shows the text and data of each result; whether it draws the `map` / `arrival_list` blocks is up to its UI. Menu names move between ChatGPT releases — if they differ, look for *Developer mode* and *custom connector / app*.
36
+
37
+ ### OpenAI Responses API
38
+
39
+ ```python
40
+ from openai import OpenAI
41
+
42
+ client = OpenAI()
43
+ response = client.responses.create(
44
+ model="your-model",
45
+ tools=[{
46
+ "type": "mcp",
47
+ "server_label": "lviv_transport",
48
+ "server_url": "https://api.lad.lviv.ua/mcp",
49
+ "require_approval": "never", # every tool is read-only
50
+ }],
51
+ input="How do I get from Рясне-1 to Сихівська?",
52
+ )
53
+ print(response.output_text)
54
+ ```
55
+
56
+ ### Gemini
57
+
58
+ - **Gemini Enterprise** — an admin opens the Gemini Enterprise app in the Google Cloud console, goes to **Data stores → Add data store → MCP server** (custom MCP), and enters `https://api.lad.lviv.ua/mcp` with no authentication. Users then pick it as a source in chat.
59
+ - **Gemini app (consumer)** — adding a remote MCP server by URL is part of Gemini Spark (Google AI Ultra plan): add a custom connector and paste `https://api.lad.lviv.ua/mcp`.
60
+ - **Antigravity CLI and other Gemini-based agents** — register it as a remote (HTTP / streamable HTTP) MCP server with URL `https://api.lad.lviv.ua/mcp`; no headers or key needed.
61
+
62
+ As with ChatGPT, these menus are new and still moving; the constant is the URL and "no authentication".
63
+
26
64
  ### Cursor / Windsurf / other clients with remote MCP support
27
65
 
28
66
  ```json
@@ -54,7 +92,7 @@ Or pin the config:
54
92
  }
55
93
  ```
56
94
 
57
- The `npx` entry is a thin stdio proxy — it forwards every request to the live API, so there is no database or config to set up. npx still installs the package's npm dependencies on first run, so expect a short download.
95
+ The `npx` entry is a thin stdio proxy — it forwards every request to the live API, so there is no database or config to set up. npx still installs the package's npm dependencies on first run, so expect a short download. Set `MCP_URL` to point it at another deployment (default `https://api.lad.lviv.ua/mcp`).
58
96
 
59
97
  ### MCP Inspector (testing)
60
98
 
@@ -73,7 +111,7 @@ All tools are read-only. Argument names are **exact** — pass them as shown.
73
111
  | `search_stops` | `query` (string), `limit` (int 1–25, optional) | Stop IDs by name — Ukrainian or English, partial, inflection-tolerant. |
74
112
  | `get_stops_around_location` | `latitude`, `longitude` (numbers), `radius_meters` (int 50–3000, optional) | Stop IDs near a coordinate, with serving routes. |
75
113
  | `get_stop_realtime` | `stop_id` (number or digit string) | Live arrivals at a stop: route, destination, minutes to arrival. |
76
- | `find_routes_between` | `from_stop_id`, `to_stop_id` | Direct routes from A to B: where to board and get off, walk at each end. |
114
+ | `find_routes_between` | `from_stop_id`, `to_stop_id` | Routes from A to B, direct or with one interchange in a nearby-stop cluster: where to board, transfer and get off. |
77
115
  | `get_route_static` | `route_name` (string, e.g. `"T30"`), `include_shapes` (bool, optional) | Stop lists (both directions), first-stop timetable; polylines on request. |
78
116
  | `get_route_realtime` | `route_name` (string) | Live vehicles on a route with destination and next stop. |
79
117
  | `get_nearby_vehicles` | `latitude`, `longitude` (numbers), `radius_meters`, `route`, `limit` (optional) | Live vehicles near a coordinate, nearest first. |
package/README.md CHANGED
@@ -20,24 +20,68 @@ Express-based API for Lviv transport timetable data with a read-only MCP endpoin
20
20
 
21
21
  ```bash
22
22
  nvm use
23
+ npm install
24
+ cp .env.dist .env
25
+ make import # first run, and whenever the GTFS feed changes
23
26
  make start
24
27
  ```
25
28
 
29
+ `make import` downloads the static GTFS feed (`gtfs-import-config.json`) and
30
+ writes the two stores the server reads: `database/Timetable` (LokiJS: stops,
31
+ routes, shapes, first-stop schedules) and `database/gtfs` (SQLite: trips and
32
+ calendars). Both are gitignored, so a fresh clone has no data until it runs.
33
+ `make import-slim` re-imports only the light tables into SQLite and leaves
34
+ `database/Timetable` alone.
35
+
36
+ ### Configuration
37
+
38
+ All variables are optional; see `.env.dist`.
39
+
40
+ | Variable | Default | Purpose |
41
+ |----------|---------|---------|
42
+ | `PORT` | `8080` | HTTP port. |
43
+ | `VEHICLES_LOCATION_URL` | `https://track.ua-gis.com/gtfs/lviv/vehicle_position` | GTFS-RT vehicle positions feed. |
44
+ | `TRIP_UDPDATES_URL` | `https://track.ua-gis.com/gtfs/lviv/trip_updates` | GTFS-RT trip updates feed (the misspelling is the real name). |
45
+ | `MCP_PUBLIC_BASE_URL` | `https://api.lad.lviv.ua` | Base URL used in MCP metadata (icon URL). |
46
+ | `NEW_RELIC_LICENSE_KEY` | — | Enables New Relic APM (see [Monitoring](#monitoring)). |
47
+ | `NEW_RELIC_APP_NAME`, `NEW_RELIC_LOG_LEVEL` | `timetable-api-node`, `info` | New Relic agent settings. |
48
+ | `PULSE_WORKER_URL`, `PULSE_SIGNAL_SECRET` | — | Signal a Pulse worker on each `/stops/:code/timetable` request; both must be set. |
49
+ | `MCP_URL` | `https://api.lad.lviv.ua/mcp` | Only for the `timetable-mcp` stdio proxy: the remote endpoint it forwards to. |
50
+
26
51
  ## Test
27
52
 
28
53
  ```bash
29
54
  nvm use && make test
30
55
  ```
31
56
 
57
+ ## TypeScript
58
+
59
+ The code is TypeScript and runs straight from the `.ts` sources under Node's
60
+ built-in type stripping — there is no build step for the server, the GTFS
61
+ import or the scripts. That means only erasable syntax (no `enum`,
62
+ `namespace` or parameter properties), `import type` for type-only imports, and
63
+ relative imports that name the `.ts` file; `tsconfig.json` enforces all three.
64
+
65
+ ```bash
66
+ npm run typecheck # tsc, no emit
67
+ ```
68
+
69
+ `npm run build` emits just `mcp/stdio.js`, the published `bin`: Node does not
70
+ strip types inside `node_modules`, so the npm package has to ship JavaScript.
71
+ It runs on `npm pack`/`npm publish`; the output is not committed.
72
+
73
+ `public/stopOverrides.js` is served to browsers as-is, so it stays JavaScript
74
+ and is type-checked from its JSDoc.
75
+
32
76
  ## Monitoring
33
77
 
34
78
  New Relic APM, off unless `NEW_RELIC_LICENSE_KEY` is set. It also carries
35
- errors and the custom metrics recorded through `utils/metrics.js`.
79
+ errors and the custom metrics recorded through `utils/metrics.ts`.
36
80
 
37
81
  New Relic runs as a preloaded agent, so `npm start` carries the flags:
38
82
 
39
83
  ```bash
40
- node -r dotenv/config -r newrelic --import newrelic/esm-loader.mjs index.js
84
+ node -r dotenv/config -r newrelic --import newrelic/esm-loader.mjs index.ts
41
85
  ```
42
86
 
43
87
  `dotenv/config` is preloaded first so `.env` is populated before the agent
@@ -147,7 +191,7 @@ All tools are read-only. Stop IDs are the numeric codes on stop signs, returned
147
191
  | `search_stops` | `query` (string, ≥ 2 chars), `limit` (1–25, default 10) | Stops whose Ukrainian or English name contains every query word (inflection-tolerant: `"опера"` finds «Театр опери та балету»), with `routes`. |
148
192
  | `get_stops_around_location` | `latitude`, `longitude`, `radius_meters` (50–3000, default 1000) | Stops near a point, nearest first, with `distance_meters` and `routes`. |
149
193
  | `get_stop_realtime` | `stop_id` | Live arrivals: `route`, `direction` (destination), `vehicle_type`, `arrival_minutes`, vehicle position. |
150
- | `find_routes_between` | `from_stop_id`, `to_stop_id` | Direct routes within a 300 m walk of each end, best first: `board_stop`, `alight_stop`, `destination`, `stops_count`, walk at each end. |
194
+ | `find_routes_between` | `from_stop_id`, `to_stop_id` | Routes within a 300 m walk of each end, best first: direct `options` (`board_stop`, `alight_stop`, `destination`, `stops_count`, walk at each end) and `transfer_options` with exactly one interchange inside a 300 m stop cluster. |
151
195
  | `get_route_static` | `route_name`, `include_shapes` (default false) | Name, type, colour, stop lists for both directions, first-stop timetable; polylines only on request. |
152
196
  | `get_route_realtime` | `route_name` | Vehicles on the route with `destination` and `next_stop` (`id`, `name`, ISO `arrival`). |
153
197
  | `get_nearby_vehicles` | `latitude`, `longitude`, `radius_meters` (100–1000, default 500), `route`, `limit` (1–50, default 15) | Live vehicles nearest first, with `destination` and `distance_meters`; `total` counts all in range. |
@@ -241,13 +285,24 @@ Text summary: *"3 direct routes «Площа Ринок» → «Залізнич
241
285
  "walk_from_alight_meters": 0
242
286
  }
243
287
  ],
288
+ "transfer_options": [],
289
+ "map_stops": [
290
+ { "id": "58", "name": "Руська", "lat": 49.84186, "lng": 24.03408, "role": "board" },
291
+ { "id": "118", "name": "Залізничний вокзал", "lat": 49.839, "lng": 23.99677, "role": "alight" }
292
+ ],
244
293
  "updated_at": "2026-09-23T09:36:53Z"
245
294
  },
246
- "ui_blocks": []
295
+ "ui_blocks": [
296
+ { "type": "map", "data": { "center": [49.84043, 24.01543], "zoom": 13, "layers": { "stops": "data.map_stops" } } }
297
+ ]
247
298
  }
248
299
  ```
249
300
 
250
- 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. Only direct routes are listed; an empty `options` means a transfer is needed.
301
+ 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.
302
+
303
+ `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.
304
+
305
+ `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.
251
306
 
252
307
  </details>
253
308
 
@@ -386,13 +441,15 @@ Each end covers every stop within a 300 m walk (`stop_ids`): a line's two direct
386
441
 
387
442
  ### Prompts
388
443
 
389
- Reusable instruction templates for rendering workflows. Each takes one argument, `stop_id` (positive integer or digits-only string).
444
+ Reusable instruction templates. `stop_id` is a positive integer or digits-only string.
390
445
 
391
- | Prompt | Use case |
392
- |--------|----------|
393
- | `transit-map-view` | Map-first rendering of live vehicles for a stop. |
394
- | `transit-arrival-list` | Arrival list for a stop, sorted by ETA and grouped by route. |
395
- | `transit-hybrid-view` | Map block first, arrival-list block second, with ETA values kept consistent across both. |
446
+ | Prompt | Arguments | Use case |
447
+ |--------|-----------|----------|
448
+ | `plan-trip` | `from`, `to` | Routes between two named places (or stop IDs), direct or with one transfer, with live departures from the boarding stop. |
449
+ | `route-status` | `route_name` | Where a route's vehicles are right now, by direction. `route_name` supports completion. |
450
+ | `transit-map-view` | `stop_id` | Map-first rendering of live vehicles for a stop. |
451
+ | `transit-arrival-list` | `stop_id` | Arrival list for a stop, sorted by ETA and grouped by route. |
452
+ | `transit-hybrid-view` | `stop_id` | Map block first, arrival-list block second, with ETA values kept consistent across both. |
396
453
 
397
454
  ### Resources and resource templates
398
455
 
@@ -406,6 +463,8 @@ In addition to tools, the server exposes MCP **resources** for reference data th
406
463
  | `timetable://stop/{code}` | Static info for a stop by numeric code — name, coordinates, serving routes (JSON) |
407
464
  | `timetable://route/{name}` | Static metadata for a route by short name — color, type, stop counts (JSON) |
408
465
 
466
+ `{name}` in `timetable://route/{name}` supports `completion/complete` ("t3" → "Т30", "a1" → "А01"). Unknown stops or routes fail with JSON-RPC error `-32002` (resource not found).
467
+
409
468
  ### Security model
410
469
 
411
470
  - Public read-only (no authentication).
@@ -432,8 +491,9 @@ All stops as a JSON array, sorted by code.
432
491
  The upstream route list for a stop is sometimes behind reality. `GET /stops`
433
492
  applies a stored override to its `Маршрути` column — removed routes shown red and
434
493
  struck through, added ones green — and hangs the matching `?add=`/`?remove=` on
435
- that row's SVG and PDF links, which `offline.lad.lviv.ua` and `pdf.lad.lviv.ua`
436
- both understand.
494
+ that row's SVG and PDF links in both the `Табличка` (stop sign) and `Мапа`
495
+ (network poster, `/:code/schema`) columns, which `offline.lad.lviv.ua` and
496
+ `pdf.lad.lviv.ua` both understand.
437
497
 
438
498
  The route column is always clickable: click a route to drop or restore it, type
439
499
  one into the `+` box to add it.
@@ -517,3 +577,35 @@ Look up a vehicle ID by its license plate. Short-cached (5 s).
517
577
  Vehicles within 1 km of a point. Short-cached (10 s).
518
578
 
519
579
  - **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`.
580
+
581
+ ### Service and discovery
582
+
583
+ | Endpoint | Returns |
584
+ |----------|---------|
585
+ | `GET /health` | `{ status: "ok" }`, or 503 while the timetable store is not loaded. Does not probe the upstream feed. |
586
+ | `GET /ping` | `{}` |
587
+ | `GET /openapi.yaml` (also `/.well-known/openapi.yaml`) | OpenAPI 3.0 description of the REST API. |
588
+ | `GET /llms.txt`, `GET /INTEGRATION.md` | LLM-oriented overview and the [integration guide](INTEGRATION.md). |
589
+ | `GET /.well-known/ai-plugin.json`, `GET /.well-known/agent.json` | OpenAI plugin manifest and A2A agent card. |
590
+ | `GET /server.json`, `GET /smithery.json` | MCP Registry and Smithery manifests. |
591
+ | `GET /sitemap.xml` | Sitemap of the public `lad.lviv.ua` pages. |
592
+
593
+ ## Deployment
594
+
595
+ Production runs on Cloud Run (`timetable-api-node`, `us-central1`, project
596
+ `timetable-252615`) behind Cloudflare.
597
+
598
+ - **Image.** The Dockerfile imports the GTFS feed at build time
599
+ (`gtfs-import.ts`, then `scripts/slim-gtfs-db.ts` empties the SQLite tables
600
+ the server never reads), so every image carries its own data snapshot.
601
+ `last-modified.txt` records the feed's `Last-Modified` header.
602
+ - **Cloud Build.** `cloudbuild.yaml` builds, pushes and deploys the image. A
603
+ daily scheduled run sets `_DATA_REFRESH=1` and skips the whole build when
604
+ the upstream `static.zip` is unchanged since the deployed revision.
605
+ - **Manual.** `make deploy` builds a `linux/amd64` image, pushes it and deploys
606
+ it. `make smoke` checks a few production endpoints; `make clear-short-cache`,
607
+ `clear-long-cache` and `clear-all-cache` purge Cloudflare by cache tag.
608
+ - **npm package.** `make publish` bumps the patch version (which also syncs
609
+ `server.json` and `openapi.yaml`) and pushes the tag; the tag triggers
610
+ `.github/workflows/publish.yml`, which publishes to npm and the MCP Registry.
611
+ The package ships only the `timetable-mcp` stdio proxy.
@@ -10,30 +10,31 @@ import { readFile } from "fs/promises";
10
10
  import cors from "cors";
11
11
  import rateLimit, { ipKeyGenerator } from "express-rate-limit";
12
12
  import express from "express";
13
- import localDb from "./connections/timetableSqliteDb.js";
14
-
15
- import notFoundAction from "./actions/notFoundAction.js";
16
- import validateStopCode from "./utils/stopCodeMiddleware.js";
17
-
18
- import getClosestStopsAction from "./actions/getClosestStopsAction.js";
19
- import getSingleStopAction from "./actions/getSingleStopAction.js";
20
- import getStopTimetableAction from "./actions/getStopTimetableAction.js";
21
- import getStopStaticDataAction from "./actions/getStopStaticDataAction.js";
22
- import getAllStopsAction from "./actions/getAllStopsAction.js";
23
- import routeInfoDynamicAction from "./actions/routeDynamicInfoAction.js";
24
- import routeInfoStaticAction from "./actions/routeStaticInfoAction.js";
25
- import vehicleInfoAction from "./actions/vehicleInfoAction.js";
26
- import vehicleByPlateAction from "./actions/vehicleByPlateAction.js";
27
- import closestTransportAction from "./actions/closestTransportAction.js";
28
- import getAllRoutesAction from "./actions/getAllRoutesAction.js";
29
- import sitemapAction from "./actions/sitemapAction.js";
13
+ import type { Request, Response } from "express";
14
+ import localDb from "./connections/timetableSqliteDb.ts";
15
+
16
+ import notFoundAction from "./actions/notFoundAction.ts";
17
+ import validateStopCode from "./utils/stopCodeMiddleware.ts";
18
+
19
+ import getClosestStopsAction from "./actions/getClosestStopsAction.ts";
20
+ import getSingleStopAction from "./actions/getSingleStopAction.ts";
21
+ import getStopTimetableAction from "./actions/getStopTimetableAction.ts";
22
+ import getStopStaticDataAction from "./actions/getStopStaticDataAction.ts";
23
+ import getAllStopsAction from "./actions/getAllStopsAction.ts";
24
+ import routeInfoDynamicAction from "./actions/routeDynamicInfoAction.ts";
25
+ import routeInfoStaticAction from "./actions/routeStaticInfoAction.ts";
26
+ import vehicleInfoAction from "./actions/vehicleInfoAction.ts";
27
+ import vehicleByPlateAction from "./actions/vehicleByPlateAction.ts";
28
+ import closestTransportAction from "./actions/closestTransportAction.ts";
29
+ import getAllRoutesAction from "./actions/getAllRoutesAction.ts";
30
+ import sitemapAction from "./actions/sitemapAction.ts";
30
31
  import {
31
32
  buildMcpServerCard,
32
33
  handleMcpPostRequest,
33
- } from "./mcp/timetableMcpServer.js";
34
- import { renderMcpDocsPage, wantsHtmlDocs } from "./mcp/docsPage.js";
35
- import healthAction from "./actions/healthAction.js";
36
- import errorHandler from "./utils/errorHandler.js";
34
+ } from "./mcp/timetableMcpServer.ts";
35
+ import { renderMcpDocsPage, wantsHtmlDocs } from "./mcp/docsPage.ts";
36
+ import healthAction from "./actions/healthAction.ts";
37
+ import errorHandler from "./utils/errorHandler.ts";
37
38
 
38
39
  const app = express();
39
40
 
@@ -46,7 +47,7 @@ app.set("trust proxy", true);
46
47
  * (see the DropCache step in cloudbuild.yaml). GTFS-derived responses use
47
48
  * "short" instead and are purged by every build.
48
49
  */
49
- const setStaticAssetCache = (res, maxAgeSeconds = 3600 * 24) =>
50
+ const setStaticAssetCache = (res: Response, maxAgeSeconds = 3600 * 24) =>
50
51
  res
51
52
  .set("Cache-Control", `public, max-age=0, s-maxage=${maxAgeSeconds}`)
52
53
  .set("Cache-Tag", "long");
@@ -76,8 +77,8 @@ app.use(express.json({ limit: "100kb" }));
76
77
  // back to req.ip only for a request that did not arrive through the edge.
77
78
  // ipKeyGenerator collapses IPv6 to a /56, so a single allocation cannot spread
78
79
  // its hits across addresses either.
79
- const clientIpKey = (req) =>
80
- ipKeyGenerator(req.headers["cf-connecting-ip"] ?? req.ip ?? "");
80
+ const clientIpKey = (req: Request) =>
81
+ ipKeyGenerator((req.headers["cf-connecting-ip"] as string | undefined) ?? req.ip ?? "");
81
82
 
82
83
  // Limits are per client address and sit well above what a person browsing
83
84
  // generates. They exist to bound the unattended callers: a scraper looping a
@@ -454,18 +455,14 @@ app.use(notFoundAction);
454
455
 
455
456
  app.use(errorHandler);
456
457
 
457
- app.on("ready", () => {
458
- app.listen(PORT, () => {
459
- console.log(`Started! http://localhost:${PORT}`);
460
- });
461
- });
462
-
463
458
  localDb.loadDatabase({}, async () => {
464
459
  const gtfsDbConfig = JSON.parse(
465
- await readFile(new URL("./gtfs-import-config.json", import.meta.url)),
460
+ await readFile(new URL("./gtfs-import-config.json", import.meta.url), "utf8"),
466
461
  );
467
462
 
468
463
  await openDb(gtfsDbConfig);
469
464
 
470
- app.emit("ready");
465
+ app.listen(PORT, () => {
466
+ console.log(`Started! http://localhost:${PORT}`);
467
+ });
471
468
  });
package/mcp/stdio.js CHANGED
@@ -2,71 +2,53 @@
2
2
  // Stdio-to-HTTP proxy — bridges local MCP clients (Claude Desktop, Cursor, etc.)
3
3
  // to the live Lviv Public Transport MCP server without requiring a local database.
4
4
  import "dotenv/config";
5
-
6
5
  import pkg from "../package.json" with { type: "json" };
7
6
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
8
7
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
9
8
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
10
9
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
11
- import {
12
- CallToolRequestSchema,
13
- ListToolsRequestSchema,
14
- ListResourcesRequestSchema,
15
- ListResourceTemplatesRequestSchema,
16
- ReadResourceRequestSchema,
17
- ListPromptsRequestSchema,
18
- GetPromptRequestSchema,
19
- } from "@modelcontextprotocol/sdk/types.js";
20
-
21
- const upstreamUrl = new URL(
22
- process.env.MCP_URL || "https://api.lad.lviv.ua/mcp",
23
- );
24
-
10
+ import { CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, ListPromptsRequestSchema, GetPromptRequestSchema, CompleteRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
11
+ const upstreamUrl = new URL(process.env.MCP_URL || "https://api.lad.lviv.ua/mcp");
25
12
  async function main() {
26
- const upstream = new Client(
27
- { name: "lviv-timetable-stdio-proxy", version: pkg.version },
28
- { capabilities: {} },
29
- );
30
-
31
- await upstream.connect(new StreamableHTTPClientTransport(upstreamUrl));
32
-
33
- const [{ tools }, { resources }, { resourceTemplates }, { prompts }] = await Promise.all([
34
- upstream.listTools(),
35
- upstream.listResources(),
36
- upstream.listResourceTemplates(),
37
- upstream.listPrompts(),
38
- ]);
39
-
40
- const server = new Server(
41
- { name: "com.lad.lviv/timetable-api", version: pkg.version },
42
- {
43
- capabilities: {
44
- ...(tools.length && { tools: {} }),
45
- ...(resources.length || resourceTemplates.length ? { resources: {} } : {}),
46
- ...(prompts.length && { prompts: {} }),
47
- },
48
- },
49
- );
50
-
51
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
52
- server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources }));
53
- server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({ resourceTemplates }));
54
- server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts }));
55
-
56
- server.setRequestHandler(CallToolRequestSchema, async (req) =>
57
- upstream.callTool(req.params),
58
- );
59
- server.setRequestHandler(ReadResourceRequestSchema, async (req) =>
60
- upstream.readResource(req.params),
61
- );
62
- server.setRequestHandler(GetPromptRequestSchema, async (req) =>
63
- upstream.getPrompt(req.params),
64
- );
65
-
66
- await server.connect(new StdioServerTransport());
13
+ const upstream = new Client({ name: "lviv-timetable-stdio-proxy", version: pkg.version }, { capabilities: {} });
14
+ await upstream.connect(new StreamableHTTPClientTransport(upstreamUrl));
15
+ const [{ tools }, { resources }, { resourceTemplates }, { prompts }] = await Promise.all([
16
+ upstream.listTools(),
17
+ upstream.listResources(),
18
+ upstream.listResourceTemplates(),
19
+ upstream.listPrompts(),
20
+ ]);
21
+ // Pass the upstream identity and instructions through: the instructions
22
+ // carry the tool-selection guidance, and without them a stdio client gets
23
+ // the bare tool list only.
24
+ const upstreamInfo = upstream.getServerVersion() ?? {};
25
+ const upstreamCapabilities = upstream.getServerCapabilities() ?? {};
26
+ const server = new Server({
27
+ ...upstreamInfo,
28
+ name: upstreamInfo.name ?? "com.lad.lviv/timetable-api",
29
+ version: pkg.version,
30
+ }, {
31
+ capabilities: {
32
+ ...(tools.length && { tools: {} }),
33
+ ...(resources.length || resourceTemplates.length ? { resources: {} } : {}),
34
+ ...(prompts.length && { prompts: {} }),
35
+ ...(upstreamCapabilities.completions && { completions: {} }),
36
+ },
37
+ instructions: upstream.getInstructions(),
38
+ });
39
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
40
+ server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources }));
41
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({ resourceTemplates }));
42
+ server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts }));
43
+ server.setRequestHandler(CallToolRequestSchema, async (req) => upstream.callTool(req.params));
44
+ server.setRequestHandler(ReadResourceRequestSchema, async (req) => upstream.readResource(req.params));
45
+ server.setRequestHandler(GetPromptRequestSchema, async (req) => upstream.getPrompt(req.params));
46
+ if (upstreamCapabilities.completions) {
47
+ server.setRequestHandler(CompleteRequestSchema, async (req) => upstream.complete(req.params));
48
+ }
49
+ await server.connect(new StdioServerTransport());
67
50
  }
68
-
69
51
  main().catch((err) => {
70
- process.stderr.write(`Error: ${err.message}\n`);
71
- process.exit(1);
52
+ process.stderr.write(`Error: ${err.message}\n`);
53
+ process.exit(1);
72
54
  });
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "timetable-api-node",
3
- "version": "1.7.1",
3
+ "version": "1.7.4",
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
- "main": "index.js",
5
+ "main": "index.ts",
6
6
  "type": "module",
7
7
  "engines": {
8
8
  "node": ">=22"
@@ -47,16 +47,26 @@
47
47
  "zod": "^4.4.3"
48
48
  },
49
49
  "scripts": {
50
- "import": "node gtfs-import.js",
51
- "import-slim": "node gtfs-import-slim.js",
52
- "start": "node -r dotenv/config -r newrelic --import newrelic/esm-loader.mjs index.js",
50
+ "import": "node gtfs-import.ts",
51
+ "import-slim": "node gtfs-import-slim.ts",
52
+ "start": "node -r dotenv/config -r newrelic --import newrelic/esm-loader.mjs index.ts",
53
+ "build": "tsc -p tsconfig.build.json",
54
+ "prepack": "npm run build",
55
+ "typecheck": "tsc",
53
56
  "test": "vitest run",
54
57
  "test:watch": "vitest",
55
- "version": "node scripts/sync-manifest-versions.js && git add server.json openapi.yaml"
58
+ "version": "node scripts/sync-manifest-versions.ts && git add server.json openapi.yaml"
56
59
  },
57
60
  "author": "vbhjckfd@gmail.com",
58
61
  "license": "WTFPL",
59
62
  "devDependencies": {
63
+ "@types/better-sqlite3": "^9.6.0",
64
+ "@types/cors": "^2.8.19",
65
+ "@types/express": "^5.0.6",
66
+ "@types/lokijs": "^1.5.14",
67
+ "@types/newrelic": "^9.14.8",
68
+ "@types/node": "^22.20.5",
69
+ "typescript": "^7.0.2",
60
70
  "vitest": "^5.0.0"
61
71
  }
62
72
  }