timetable-api-node 1.7.3 → 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
@@ -92,7 +92,7 @@ Or pin the config:
92
92
  }
93
93
  ```
94
94
 
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.
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`).
96
96
 
97
97
  ### MCP Inspector (testing)
98
98
 
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
@@ -447,8 +491,9 @@ All stops as a JSON array, sorted by code.
447
491
  The upstream route list for a stop is sometimes behind reality. `GET /stops`
448
492
  applies a stored override to its `Маршрути` column — removed routes shown red and
449
493
  struck through, added ones green — and hangs the matching `?add=`/`?remove=` on
450
- that row's SVG and PDF links, which `offline.lad.lviv.ua` and `pdf.lad.lviv.ua`
451
- 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.
452
497
 
453
498
  The route column is always clickable: click a route to drop or restore it, type
454
499
  one into the `+` box to add it.
@@ -532,3 +577,35 @@ Look up a vehicle ID by its license plate. Short-cached (5 s).
532
577
  Vehicles within 1 km of a point. Short-cached (10 s).
533
578
 
534
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,88 +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
- CompleteRequestSchema,
20
- } from "@modelcontextprotocol/sdk/types.js";
21
-
22
- const upstreamUrl = new URL(
23
- process.env.MCP_URL || "https://api.lad.lviv.ua/mcp",
24
- );
25
-
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");
26
12
  async function main() {
27
- const upstream = new Client(
28
- { name: "lviv-timetable-stdio-proxy", version: pkg.version },
29
- { capabilities: {} },
30
- );
31
-
32
- await upstream.connect(new StreamableHTTPClientTransport(upstreamUrl));
33
-
34
- const [{ tools }, { resources }, { resourceTemplates }, { prompts }] = await Promise.all([
35
- upstream.listTools(),
36
- upstream.listResources(),
37
- upstream.listResourceTemplates(),
38
- upstream.listPrompts(),
39
- ]);
40
-
41
- // Pass the upstream identity and instructions through: the instructions
42
- // carry the tool-selection guidance, and without them a stdio client gets
43
- // the bare tool list only.
44
- const upstreamInfo = upstream.getServerVersion() ?? {};
45
- const upstreamCapabilities = upstream.getServerCapabilities() ?? {};
46
- const server = new Server(
47
- {
48
- ...upstreamInfo,
49
- name: upstreamInfo.name ?? "com.lad.lviv/timetable-api",
50
- version: pkg.version,
51
- },
52
- {
53
- capabilities: {
54
- ...(tools.length && { tools: {} }),
55
- ...(resources.length || resourceTemplates.length ? { resources: {} } : {}),
56
- ...(prompts.length && { prompts: {} }),
57
- ...(upstreamCapabilities.completions && { completions: {} }),
58
- },
59
- instructions: upstream.getInstructions(),
60
- },
61
- );
62
-
63
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
64
- server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources }));
65
- server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({ resourceTemplates }));
66
- server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts }));
67
-
68
- server.setRequestHandler(CallToolRequestSchema, async (req) =>
69
- upstream.callTool(req.params),
70
- );
71
- server.setRequestHandler(ReadResourceRequestSchema, async (req) =>
72
- upstream.readResource(req.params),
73
- );
74
- server.setRequestHandler(GetPromptRequestSchema, async (req) =>
75
- upstream.getPrompt(req.params),
76
- );
77
- if (upstreamCapabilities.completions) {
78
- server.setRequestHandler(CompleteRequestSchema, async (req) =>
79
- upstream.complete(req.params),
80
- );
81
- }
82
-
83
- 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());
84
50
  }
85
-
86
51
  main().catch((err) => {
87
- process.stderr.write(`Error: ${err.message}\n`);
88
- process.exit(1);
52
+ process.stderr.write(`Error: ${err.message}\n`);
53
+ process.exit(1);
89
54
  });
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "timetable-api-node",
3
- "version": "1.7.3",
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
  }