@pipeworx/mcp-bts-ontime 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +203 -2
- package/bin/cli.js +17 -0
- package/package.json +30 -4
- package/server.json +18 -0
- package/src/index.ts +362 -0
- package/src/server.ts +45 -0
- package/src/store.ts +360 -0
- package/tsconfig.json +18 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mojibake Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,204 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @pipeworx/bts-ontime
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
US domestic airline on-time performance and delay causes: monthly on-time %,
|
|
4
|
+
average arrival delay, cancellations, diversions, and delay minutes broken
|
|
5
|
+
down by cause (carrier, weather, air-traffic-control/NAS, security, late
|
|
6
|
+
aircraft) — by route, by carrier, and by arrival airport. Fleet #2953.
|
|
7
|
+
|
|
8
|
+
Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 1779+ live data sources. This is an independent, unofficial integration — not affiliated with, endorsed by, or published by the upstream provider.
|
|
9
|
+
|
|
10
|
+
## Tools
|
|
11
|
+
|
|
12
|
+
- `route_ontime(origin, dest, carrier?, months?)` — monthly on-time
|
|
13
|
+
performance for one origin->destination route, optionally scoped to one
|
|
14
|
+
carrier. Each month carries flights, completed flights, on-time arrivals
|
|
15
|
+
and on-time %, average arrival delay, cancellations, diversions, and delay
|
|
16
|
+
minutes by cause.
|
|
17
|
+
- `carrier_ontime(carrier, airport?, months?)` — the same monthly shape,
|
|
18
|
+
aggregated across one airline's whole network (or just the flights
|
|
19
|
+
touching one airport).
|
|
20
|
+
- `bts_airport_delays(airport, year?, month?, limit?, offset?)` —
|
|
21
|
+
delay-cause breakdown by carrier for flights ARRIVING at one airport,
|
|
22
|
+
optionally scoped to a year and/or month. `limit` defaults to 50 (max
|
|
23
|
+
200); a response with more matching rows than returned carries
|
|
24
|
+
`truncated: true` and `total_matching` rather than silently dropping them.
|
|
25
|
+
- `delay_causes(year, carrier?, airport?, limit?, offset?)` — the same
|
|
26
|
+
delay-cause rows, organized by year first, for scanning a whole year
|
|
27
|
+
across carriers or airports. Same `limit`/`truncated`/`total_matching`
|
|
28
|
+
pagination as `bts_airport_delays`.
|
|
29
|
+
- `list_coverage()` — the earliest/latest month actually loaded, and when.
|
|
30
|
+
Call this first if you're not sure a given period is covered.
|
|
31
|
+
|
|
32
|
+
Carrier accepts either the 2-letter reporting-carrier code (`"DL"`) or a
|
|
33
|
+
common airline name (`"Delta"`). Airport codes are validated against what is
|
|
34
|
+
actually loaded (not a static list) — an unrecognized code is refused with a
|
|
35
|
+
clear error, never an empty success.
|
|
36
|
+
|
|
37
|
+
## Auth
|
|
38
|
+
|
|
39
|
+
Keyless. The tools answer only through the Pipeworx gateway, which holds the
|
|
40
|
+
data; a standalone `npm install` has no data to read, and every tool throws
|
|
41
|
+
a clear "not bound in this runtime" error there instead of returning an
|
|
42
|
+
empty list.
|
|
43
|
+
|
|
44
|
+
## Data sources
|
|
45
|
+
|
|
46
|
+
- US DOT Bureau of Transportation Statistics (BTS), TranStats — "Reporting
|
|
47
|
+
Carrier On-Time Performance" monthly bulk data. US federal government
|
|
48
|
+
work: public domain (17 U.S.C. §105). The agency publishes bulk files
|
|
49
|
+
only (no live query API for this dataset), so this pack builds a copy
|
|
50
|
+
(`scripts/bts-ontime/load-data.mjs`) rather than proxying — raw
|
|
51
|
+
flight-level rows (~600k/month) are never stored; the loader aggregates
|
|
52
|
+
each month down to two small tables and discards the raw file before
|
|
53
|
+
moving to the next one.
|
|
54
|
+
|
|
55
|
+
### What `delay_cause` is, and is not
|
|
56
|
+
|
|
57
|
+
BTS separately publishes its own "Airline Delay Cause" product, which
|
|
58
|
+
apportions each delayed flight's minutes into fractional per-cause *counts*
|
|
59
|
+
via a methodology this pack does not reimplement. The `delay_cause` table
|
|
60
|
+
here is derived from the same underlying per-flight delay-minute fields
|
|
61
|
+
(carrier/weather/NAS/security/late-aircraft) as `route_month`, rolled up by
|
|
62
|
+
carrier x arrival-airport x month, and reported as **minute sums**, not
|
|
63
|
+
fractional counts. It will be consistent with BTS's own published cause
|
|
64
|
+
breakdown but is not guaranteed to match it row-for-row — this is one
|
|
65
|
+
pipeline over one raw source, not a second download of BTS's own aggregate.
|
|
66
|
+
|
|
67
|
+
### Known gaps — read before extending this pack
|
|
68
|
+
|
|
69
|
+
**Coverage is the most recent months as of the load, not full history.**
|
|
70
|
+
BTS's bulk-file server throttles hard per connection — one file download
|
|
71
|
+
measured ~170 seconds regardless of a modest concurrency increase helping
|
|
72
|
+
(3 concurrent downloads of this upstream finished in about the same wall
|
|
73
|
+
time as 1 serial one, measured 2026-10-12), so pulling the full 1987-present
|
|
74
|
+
archive (400+ monthly files) in one sitting is a multi-hour job, not a
|
|
75
|
+
pack-build step. This first load covers the most recent 12 months as of
|
|
76
|
+
2026-10-12 (call `list_coverage` for the exact range) for BOTH tables —
|
|
77
|
+
there is no separate 2003-onward backfill for `delay_cause` in this
|
|
78
|
+
commit; it is derived from the same months as `route_month`.
|
|
79
|
+
|
|
80
|
+
**Extending coverage is mechanical, not research** — see "Refreshing or
|
|
81
|
+
extending the data" below. Re-running the loader with a larger `--months`
|
|
82
|
+
(and a `--concurrency` tuned to be polite to the upstream) pulls further
|
|
83
|
+
back; nothing about the schema or the tools changes.
|
|
84
|
+
|
|
85
|
+
### Refreshing or extending the data
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
node scripts/bts-ontime/load-data.mjs --months 12 # default: most recent 12 months
|
|
89
|
+
node scripts/bts-ontime/load-data.mjs --months 36 --concurrency 4 # extend further back
|
|
90
|
+
node scripts/bts-ontime/load-data.mjs --through 2026-7 # pin the "latest" month instead of probing
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Needs `wrangler` logged in to the Pipeworx Cloudflare account. Each run
|
|
94
|
+
**replaces** `route_month`, `delay_cause` and `bts_ontime_meta` (DROP +
|
|
95
|
+
reload) rather than appending — BTS's own monthly files are themselves
|
|
96
|
+
revised occasionally, so a clean reload is the only way to be sure stale
|
|
97
|
+
rows from a withdrawn/corrected file don't linger. A monthly refresh (BTS
|
|
98
|
+
publishes with a roughly 2-month lag) should re-run this with a `--months`
|
|
99
|
+
large enough to cover the gap since the last load, not just `12`, or the
|
|
100
|
+
oldest previously-loaded months will quietly drop off the window.
|
|
101
|
+
|
|
102
|
+
## Quick Start
|
|
103
|
+
|
|
104
|
+
Add to your MCP client (Claude Desktop, Cursor, Windsurf, etc.):
|
|
105
|
+
|
|
106
|
+
```json
|
|
107
|
+
{
|
|
108
|
+
"mcpServers": {
|
|
109
|
+
"bts-ontime": {
|
|
110
|
+
"url": "https://gateway.pipeworx.io/bts-ontime/mcp"
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### What this endpoint actually serves
|
|
117
|
+
|
|
118
|
+
`tools/list` at `https://gateway.pipeworx.io/bts-ontime/mcp` returns the tools in the table
|
|
119
|
+
above **plus the shared Pipeworx meta-tools** — `ask_pipeworx`,
|
|
120
|
+
`discover_tools`, `search_within`, `remember`/`recall` and the rest of the
|
|
121
|
+
gateway-wide set. So the tool count you see is larger than this table: a
|
|
122
|
+
single-pack endpoint currently lists roughly 30 shared tools alongside the
|
|
123
|
+
pack's own. The connection's `initialize` response states its exact scope, and
|
|
124
|
+
is the authoritative answer for a given day.
|
|
125
|
+
|
|
126
|
+
This is deliberate, not multiplexing by accident. The meta-tools are what let a
|
|
127
|
+
scoped connection answer a question this pack does not cover — via
|
|
128
|
+
`ask_pipeworx`, which routes across the whole catalog — without you adding a
|
|
129
|
+
second MCP server. There is currently no way to mount a pack endpoint without
|
|
130
|
+
them; if the extra schemas cost you more context than the routing is worth,
|
|
131
|
+
connect to the full gateway once rather than to several pack endpoints.
|
|
132
|
+
|
|
133
|
+
Or connect to the full Pipeworx gateway to get every pack's tools listed
|
|
134
|
+
directly, instead of just this one's:
|
|
135
|
+
|
|
136
|
+
```json
|
|
137
|
+
{
|
|
138
|
+
"mcpServers": {
|
|
139
|
+
"pipeworx": {
|
|
140
|
+
"url": "https://gateway.pipeworx.io/mcp"
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Both URLs reach the same gateway and the same 1779+ data sources. The
|
|
147
|
+
only difference is which pack's tools are listed **directly**; `ask_pipeworx`
|
|
148
|
+
reaches all of them from either one.
|
|
149
|
+
|
|
150
|
+
## No MCP client? Call it over HTTP
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
curl -X POST https://gateway.pipeworx.io/v1/tools/route_ontime \
|
|
154
|
+
-H 'Content-Type: application/json' \
|
|
155
|
+
-d '{"origin":"JFK","dest":"LAX","months":3}'
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
No account needed for the first calls. Inspect any tool: `GET https://gateway.pipeworx.io/v1/tools/route_ontime`. Find one: `POST https://gateway.pipeworx.io/v1/tools/search_packs` with `{"query":"..."}`.
|
|
159
|
+
|
|
160
|
+
## Standalone (no gateway account)
|
|
161
|
+
|
|
162
|
+
This package also runs as a local stdio MCP server — no Pipeworx account, no
|
|
163
|
+
gateway round-trip:
|
|
164
|
+
|
|
165
|
+
```json
|
|
166
|
+
{
|
|
167
|
+
"mcpServers": {
|
|
168
|
+
"bts-ontime": {
|
|
169
|
+
"command": "npx",
|
|
170
|
+
"args": ["-y", "@pipeworx/mcp-bts-ontime"]
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Or run it directly to confirm it starts:
|
|
177
|
+
|
|
178
|
+
```bash
|
|
179
|
+
npx -y @pipeworx/mcp-bts-ontime
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
It speaks MCP over stdin/stdout and answers `initialize`/`tools/list`/`tools/call`
|
|
183
|
+
for **only** this pack's tools — none of the shared meta-tools the gateway
|
|
184
|
+
connection above adds. Same source, same tools, no ask_pipeworx routing.
|
|
185
|
+
|
|
186
|
+
## Using with ask_pipeworx
|
|
187
|
+
|
|
188
|
+
Instead of calling tools directly, you can ask questions in plain English —
|
|
189
|
+
this works on the pack endpoint above as well as on the full gateway:
|
|
190
|
+
|
|
191
|
+
```
|
|
192
|
+
ask_pipeworx({ question: "your question about Bts Ontime data" })
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
The gateway picks the right tool and fills the arguments automatically.
|
|
196
|
+
|
|
197
|
+
## More
|
|
198
|
+
|
|
199
|
+
- [Docs and guides](https://pipeworx.io/docs)
|
|
200
|
+
- [pipeworx.io](https://pipeworx.io)
|
|
201
|
+
|
|
202
|
+
## License
|
|
203
|
+
|
|
204
|
+
MIT
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
//
|
|
3
|
+
// Entry point for `npx @pipeworx/mcp-<slug>`.
|
|
4
|
+
//
|
|
5
|
+
// Packs ship as raw TypeScript (no build step — see publish-pack.sh for why:
|
|
6
|
+
// tsx sidesteps every extensionless-import / bare-JSON-import edge case a
|
|
7
|
+
// per-pack tsc build would have to solve one pack at a time). This file
|
|
8
|
+
// registers tsx's ESM loader programmatically, then hands off to src/server.ts,
|
|
9
|
+
// which wraps the pack's {tools, callTool} export in a stdio MCP server.
|
|
10
|
+
//
|
|
11
|
+
// Copied verbatim into every published pack repo by scripts/publish-pack.sh —
|
|
12
|
+
// edit this file, not a per-pack copy.
|
|
13
|
+
import { register } from 'tsx/esm/api';
|
|
14
|
+
|
|
15
|
+
register();
|
|
16
|
+
|
|
17
|
+
await import('../src/server.ts');
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pipeworx/mcp-bts-ontime",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "bts-ontime -- US airline on-time performance and delay causes (fleet #2953).",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.ts",
|
|
7
|
+
"types": "src/index.ts",
|
|
8
|
+
"bin": {
|
|
9
|
+
"mcp-bts-ontime": "bin/cli.js"
|
|
10
|
+
},
|
|
11
|
+
"keywords": ["mcp", "mcp-server", "model-context-protocol", "pipeworx", "bts-ontime"],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/pipeworx-io/mcp-bts-ontime.git"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"typecheck": "tsc --noEmit"
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
22
|
+
"tsx": "^4.19.0"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"typescript": "^5.9.3",
|
|
26
|
+
"@cloudflare/workers-types": "^4.20260405.1"
|
|
27
|
+
},
|
|
28
|
+
"pipeworx": {
|
|
29
|
+
"sourceHash": "v1-4ccab4bb85e41d533d5ea978010ca37919c66c7500930b64b48559de10ab041c",
|
|
30
|
+
"sourceCommit": "c1590c25b5e94f477a53686cb61bd09cc196c1ee"
|
|
31
|
+
}
|
|
32
|
+
}
|
package/server.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
|
3
|
+
"name": "io.github.pipeworx-io/bts-ontime",
|
|
4
|
+
"title": "Bts Ontime",
|
|
5
|
+
"description": "bts-ontime -- US airline on-time performance and delay causes (fleet #2953).",
|
|
6
|
+
"version": "0.1.0",
|
|
7
|
+
"websiteUrl": "https://pipeworx.io/packs/bts-ontime",
|
|
8
|
+
"repository": {
|
|
9
|
+
"url": "https://github.com/pipeworx-io/mcp-bts-ontime",
|
|
10
|
+
"source": "github"
|
|
11
|
+
},
|
|
12
|
+
"remotes": [
|
|
13
|
+
{
|
|
14
|
+
"type": "streamable-http",
|
|
15
|
+
"url": "https://gateway.pipeworx.io/bts-ontime/mcp"
|
|
16
|
+
}
|
|
17
|
+
]
|
|
18
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
interface McpToolDefinition {
|
|
2
|
+
name: string;
|
|
3
|
+
description: string;
|
|
4
|
+
/** Human-facing one-liner (fleet #1967). Optional; consumers fall back to
|
|
5
|
+
* description. Kept in step with shared/src/types.ts — scripts/lib/
|
|
6
|
+
* check-inlined-types.mjs reports drift at publish time. */
|
|
7
|
+
summary?: string;
|
|
8
|
+
inputSchema: {
|
|
9
|
+
type: 'object';
|
|
10
|
+
properties: Record<string, unknown>;
|
|
11
|
+
required?: string[];
|
|
12
|
+
anyOf?: Array<{ required: string[] }>;
|
|
13
|
+
oneOf?: Array<{ required: string[] }>;
|
|
14
|
+
allOf?: Array<{ required: string[] }>;
|
|
15
|
+
};
|
|
16
|
+
outputSchema?: Record<string, unknown>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface McpToolExport {
|
|
20
|
+
tools: McpToolDefinition[];
|
|
21
|
+
callTool: (name: string, args: Record<string, unknown>) => Promise<unknown>;
|
|
22
|
+
meter?: { credits: number };
|
|
23
|
+
cost?: Record<string, unknown>;
|
|
24
|
+
provider?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* bts-ontime -- US airline on-time performance and delay causes (fleet #2953).
|
|
29
|
+
*
|
|
30
|
+
* Data: US DOT Bureau of Transportation Statistics (BTS) TranStats,
|
|
31
|
+
* "Reporting Carrier On-Time Performance (1987-present)" monthly bulk CSVs
|
|
32
|
+
* (transtats.bts.gov/PREZIP). US federal government work -- public domain
|
|
33
|
+
* (17 U.S.C. §105). The site publishes bulk files only (no live API), so
|
|
34
|
+
* this pack builds a copy (scripts/bts-ontime/load-data.mjs) into a D1
|
|
35
|
+
* database the gateway hands it as `_d1` (pack-manifest "d1Binding":
|
|
36
|
+
* "BTS_ONTIME_DB"). Raw flight-level rows are NEVER stored -- the loader
|
|
37
|
+
* aggregates each month to two small tables and discards the ~600k-row raw
|
|
38
|
+
* file before moving to the next month. Design note: this file + store.ts.
|
|
39
|
+
*
|
|
40
|
+
* SCOPE: the most recent N months as of the load (see bts_ontime_meta /
|
|
41
|
+
* list_coverage below) -- not the full 1987-present or 2003-present history,
|
|
42
|
+
* because BTS throttles per connection hard enough that a multi-decade
|
|
43
|
+
* backfill is a multi-hour job better run as a scheduled extension than
|
|
44
|
+
* inline in one build. See README.md "Known gaps" / "Refresh".
|
|
45
|
+
*
|
|
46
|
+
* Every response carries `source`, `source_url`, `license` and `data_as_of`
|
|
47
|
+
* (the latest BTS month actually loaded).
|
|
48
|
+
*/
|
|
49
|
+
import {
|
|
50
|
+
carrierMonths,
|
|
51
|
+
clampLimit,
|
|
52
|
+
clampMonths,
|
|
53
|
+
delayCauses,
|
|
54
|
+
delayCausesAtAirport,
|
|
55
|
+
getMeta,
|
|
56
|
+
normAirport,
|
|
57
|
+
requireDb,
|
|
58
|
+
resolveCarrierCode,
|
|
59
|
+
routeMonths,
|
|
60
|
+
SOURCE,
|
|
61
|
+
validAirport,
|
|
62
|
+
validCarrier,
|
|
63
|
+
type D1Like,
|
|
64
|
+
} from './store.js';
|
|
65
|
+
|
|
66
|
+
const tools: McpToolExport['tools'] = [
|
|
67
|
+
{
|
|
68
|
+
name: 'route_ontime',
|
|
69
|
+
description:
|
|
70
|
+
'Monthly on-time performance for one US domestic flight route (origin airport -> destination airport), from BTS TranStats Reporting Carrier On-Time Performance. Returns, per month (and per carrier if more than one serves the route): flights, completed flights, on-time arrivals and on-time %, average arrival delay in minutes, cancellations, diversions, and delay minutes broken down by cause (carrier, weather, NAS/air-traffic-control, security, late aircraft). Pass carrier (2-letter code like "DL", or a common name like "Delta") to scope to one airline; omit it to see every carrier that flew the route. months caps how many of the most recently loaded months to return (default 12). Covers the most recent months loaded (see data_as_of and the earliest/latest fields), not full history. Unknown origin/destination airport codes are refused with a clear error, never an empty success.',
|
|
71
|
+
summary: 'Monthly on-time %, average delay and delay causes for one origin->destination route.',
|
|
72
|
+
inputSchema: {
|
|
73
|
+
type: 'object' as const,
|
|
74
|
+
properties: {
|
|
75
|
+
origin: { type: 'string', description: 'Origin airport code, e.g. "JFK".' },
|
|
76
|
+
dest: { type: 'string', description: 'Destination airport code, e.g. "LAX".' },
|
|
77
|
+
carrier: { type: 'string', description: 'Optional: 2-letter carrier code ("DL") or common name ("Delta") to scope to one airline.' },
|
|
78
|
+
months: { type: 'number', description: 'How many of the most recently loaded months to return, most recent first. Default 12.' },
|
|
79
|
+
},
|
|
80
|
+
required: ['origin', 'dest'],
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
name: 'carrier_ontime',
|
|
85
|
+
description:
|
|
86
|
+
'Monthly on-time performance for one airline, aggregated across all its routes (or just the routes touching one airport), from BTS TranStats Reporting Carrier On-Time Performance. Pass carrier as a 2-letter code ("WN") or common name ("Southwest"). Pass airport to scope to flights where that airport is the origin or destination. Returns the same per-month shape as route_ontime (flights, on-time %, average arrival delay, cancellations, diversions, delay minutes by cause). months caps how many of the most recently loaded months to return (default 12). Unknown carrier codes are refused with a clear error, never an empty success.',
|
|
87
|
+
summary: "Monthly on-time %, average delay and delay causes for one airline, system-wide or at one airport.",
|
|
88
|
+
inputSchema: {
|
|
89
|
+
type: 'object' as const,
|
|
90
|
+
properties: {
|
|
91
|
+
carrier: { type: 'string', description: '2-letter carrier code ("WN") or common name ("Southwest").' },
|
|
92
|
+
airport: { type: 'string', description: 'Optional: scope to flights where this airport is the origin or destination.' },
|
|
93
|
+
months: { type: 'number', description: 'How many of the most recently loaded months to return, most recent first. Default 12.' },
|
|
94
|
+
},
|
|
95
|
+
required: ['carrier'],
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
name: 'bts_airport_delays',
|
|
100
|
+
description:
|
|
101
|
+
'Delay-cause breakdown at one US airport (as the ARRIVAL airport), by carrier, from BTS TranStats on-time data: arriving flights, how many arrived 15+ minutes late, cancellations, diversions, and delay minutes attributed to carrier, weather, NAS (air-traffic-control/system), security, and late-aircraft causes. Pass year and/or month to scope to a specific period; omit both to get every loaded month, most recent first. Rows beyond `limit` are reported via truncated/total_matching rather than silently dropped -- narrow with year/month or page with limit/offset to see the rest. Unknown airport codes are refused with a clear error, never an empty success.',
|
|
102
|
+
summary: 'Delay-cause breakdown by carrier for arrivals at one airport.',
|
|
103
|
+
inputSchema: {
|
|
104
|
+
type: 'object' as const,
|
|
105
|
+
properties: {
|
|
106
|
+
airport: { type: 'string', description: 'Airport code, e.g. "ORD".' },
|
|
107
|
+
year: { type: 'number', description: 'Optional: scope to one calendar year.' },
|
|
108
|
+
month: { type: 'number', description: 'Optional: scope to one month (1-12). Requires year to be meaningful alongside it, but works alone too (matches that month in any loaded year).' },
|
|
109
|
+
limit: { type: 'number', description: 'Max rows to return, 1-200. Default 50. A truncated response carries truncated:true and total_matching.' },
|
|
110
|
+
offset: { type: 'number', description: 'Pagination offset. Default 0.' },
|
|
111
|
+
},
|
|
112
|
+
required: ['airport'],
|
|
113
|
+
},
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
name: 'delay_causes',
|
|
117
|
+
description:
|
|
118
|
+
'Delay-cause rows for a given year, optionally scoped to one carrier and/or one (arrival) airport, from BTS TranStats on-time data. Same fields as bts_airport_delays (arriving flights, 15+ minute-late arrivals, cancellations, diversions, delay minutes by cause) but organized by year first rather than by airport first -- use this to scan a whole year across carriers/airports, or to compare one carrier\'s delay profile across the airports it serves. Rows beyond `limit` are reported via truncated/total_matching rather than silently dropped -- narrow with carrier/airport or page with limit/offset to see the rest. Unknown carrier or airport codes are refused with a clear error, never an empty success.',
|
|
119
|
+
summary: 'Year-scoped delay-cause rows, optionally filtered by carrier and/or airport.',
|
|
120
|
+
inputSchema: {
|
|
121
|
+
type: 'object' as const,
|
|
122
|
+
properties: {
|
|
123
|
+
year: { type: 'number', description: 'Calendar year, e.g. 2026.' },
|
|
124
|
+
carrier: { type: 'string', description: 'Optional: 2-letter carrier code ("AA") or common name ("American").' },
|
|
125
|
+
airport: { type: 'string', description: 'Optional: arrival-airport code, e.g. "DFW".' },
|
|
126
|
+
limit: { type: 'number', description: 'Max rows to return, 1-200. Default 50. A truncated response carries truncated:true and total_matching.' },
|
|
127
|
+
offset: { type: 'number', description: 'Pagination offset. Default 0.' },
|
|
128
|
+
},
|
|
129
|
+
required: ['year'],
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
{
|
|
133
|
+
name: 'list_coverage',
|
|
134
|
+
description:
|
|
135
|
+
'What this pack actually has loaded right now: the earliest and latest BTS month covered, how many months, and when it was last loaded. Call this before route_ontime/carrier_ontime/bts_airport_delays/delay_causes if you are not sure a given month or year is covered.',
|
|
136
|
+
summary: 'Earliest/latest BTS month loaded, and when.',
|
|
137
|
+
inputSchema: { type: 'object' as const, properties: {} },
|
|
138
|
+
},
|
|
139
|
+
];
|
|
140
|
+
|
|
141
|
+
function notFoundAirport(code: unknown) {
|
|
142
|
+
return {
|
|
143
|
+
found: false,
|
|
144
|
+
reason: 'unknown_airport',
|
|
145
|
+
message: `${JSON.stringify(code)} is not a recognized airport code in this pack's loaded data (it may be a valid IATA code that simply had no flights in the loaded window, or a typo). Call list_coverage to see the loaded date range.`,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
function notFoundCarrier(code: unknown) {
|
|
149
|
+
return {
|
|
150
|
+
found: false,
|
|
151
|
+
reason: 'unknown_carrier',
|
|
152
|
+
message: `${JSON.stringify(code)} is not a recognized carrier code in this pack's loaded data. Use a 2-letter Reporting Carrier code (e.g. "DL", "WN", "AA") or a common airline name.`,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function routeOntimeTool(db: D1Like, args: Record<string, unknown>) {
|
|
157
|
+
const meta = await getMeta(db);
|
|
158
|
+
const origin = normAirport(args.origin);
|
|
159
|
+
const dest = normAirport(args.dest);
|
|
160
|
+
if (!origin) return { found: false, reason: 'invalid_origin', message: `${JSON.stringify(args.origin)} is not a valid airport code (3-4 letters).`, data_as_of: meta.latest_month };
|
|
161
|
+
if (!dest) return { found: false, reason: 'invalid_dest', message: `${JSON.stringify(args.dest)} is not a valid airport code (3-4 letters).`, data_as_of: meta.latest_month };
|
|
162
|
+
if (!(await validAirport(db, origin))) return { ...notFoundAirport(args.origin), data_as_of: meta.latest_month };
|
|
163
|
+
if (!(await validAirport(db, dest))) return { ...notFoundAirport(args.dest), data_as_of: meta.latest_month };
|
|
164
|
+
|
|
165
|
+
let carrierCode: string | null = null;
|
|
166
|
+
if (args.carrier != null && args.carrier !== '') {
|
|
167
|
+
carrierCode = resolveCarrierCode(args.carrier);
|
|
168
|
+
if (!carrierCode || !(await validCarrier(db, carrierCode))) return { ...notFoundCarrier(args.carrier), data_as_of: meta.latest_month };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const months = clampMonths(args.months, meta.months_loaded);
|
|
172
|
+
const rows = await routeMonths(db, origin, dest, carrierCode, months);
|
|
173
|
+
if (!rows.length) {
|
|
174
|
+
return {
|
|
175
|
+
found: false,
|
|
176
|
+
reason: 'no_flights',
|
|
177
|
+
origin,
|
|
178
|
+
dest,
|
|
179
|
+
carrier: carrierCode,
|
|
180
|
+
message: `No ${origin}->${dest} flights found in the loaded window (${meta.earliest_month} to ${meta.latest_month})${carrierCode ? ` for carrier ${carrierCode}` : ''}. The airports are valid but this route may not have been flown (or not by that carrier) in that window.`,
|
|
181
|
+
coverage: { earliest_month: meta.earliest_month, latest_month: meta.latest_month },
|
|
182
|
+
...SOURCE,
|
|
183
|
+
data_as_of: meta.latest_month,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
found: true,
|
|
188
|
+
origin,
|
|
189
|
+
dest,
|
|
190
|
+
carrier: carrierCode,
|
|
191
|
+
returned: rows.length,
|
|
192
|
+
coverage: { earliest_month: meta.earliest_month, latest_month: meta.latest_month },
|
|
193
|
+
months: rows,
|
|
194
|
+
...SOURCE,
|
|
195
|
+
data_as_of: meta.latest_month,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function carrierOntimeTool(db: D1Like, args: Record<string, unknown>) {
|
|
200
|
+
const meta = await getMeta(db);
|
|
201
|
+
const carrierCode = resolveCarrierCode(args.carrier);
|
|
202
|
+
if (!carrierCode || !(await validCarrier(db, carrierCode))) return { ...notFoundCarrier(args.carrier), data_as_of: meta.latest_month };
|
|
203
|
+
|
|
204
|
+
let airport: string | null = null;
|
|
205
|
+
if (args.airport != null && args.airport !== '') {
|
|
206
|
+
airport = normAirport(args.airport);
|
|
207
|
+
if (!airport) return { found: false, reason: 'invalid_airport', message: `${JSON.stringify(args.airport)} is not a valid airport code.`, data_as_of: meta.latest_month };
|
|
208
|
+
if (!(await validAirport(db, airport))) return { ...notFoundAirport(args.airport), data_as_of: meta.latest_month };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const months = clampMonths(args.months, meta.months_loaded);
|
|
212
|
+
const rows = await carrierMonths(db, carrierCode, airport, months);
|
|
213
|
+
if (!rows.length) {
|
|
214
|
+
return {
|
|
215
|
+
found: false,
|
|
216
|
+
reason: 'no_flights',
|
|
217
|
+
carrier: carrierCode,
|
|
218
|
+
airport,
|
|
219
|
+
message: `No flights found for carrier ${carrierCode}${airport ? ` at ${airport}` : ''} in the loaded window (${meta.earliest_month} to ${meta.latest_month}).`,
|
|
220
|
+
coverage: { earliest_month: meta.earliest_month, latest_month: meta.latest_month },
|
|
221
|
+
...SOURCE,
|
|
222
|
+
data_as_of: meta.latest_month,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
return {
|
|
226
|
+
found: true,
|
|
227
|
+
carrier: carrierCode,
|
|
228
|
+
airport,
|
|
229
|
+
returned: rows.length,
|
|
230
|
+
coverage: { earliest_month: meta.earliest_month, latest_month: meta.latest_month },
|
|
231
|
+
months: rows,
|
|
232
|
+
...SOURCE,
|
|
233
|
+
data_as_of: meta.latest_month,
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async function airportDelaysTool(db: D1Like, args: Record<string, unknown>) {
|
|
238
|
+
const meta = await getMeta(db);
|
|
239
|
+
const airport = normAirport(args.airport);
|
|
240
|
+
if (!airport) return { found: false, reason: 'invalid_airport', message: `${JSON.stringify(args.airport)} is not a valid airport code.`, data_as_of: meta.latest_month };
|
|
241
|
+
if (!(await validAirport(db, airport))) return { ...notFoundAirport(args.airport), data_as_of: meta.latest_month };
|
|
242
|
+
|
|
243
|
+
const year = args.year != null && args.year !== '' ? Math.floor(Number(args.year)) : null;
|
|
244
|
+
if (args.year != null && args.year !== '' && !Number.isFinite(year)) throw new Error('year must be a valid number');
|
|
245
|
+
const month = args.month != null && args.month !== '' ? Math.floor(Number(args.month)) : null;
|
|
246
|
+
if (args.month != null && args.month !== '' && (!Number.isFinite(month) || (month as number) < 1 || (month as number) > 12)) {
|
|
247
|
+
return { found: false, reason: 'invalid_month', message: `month must be 1-12 (got ${JSON.stringify(args.month)}).`, data_as_of: meta.latest_month };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const limit = clampLimit(args.limit);
|
|
251
|
+
const offset = Math.max(0, Math.floor(Number(args.offset) || 0));
|
|
252
|
+
const { rows, total_matching, truncated } = await delayCausesAtAirport(db, airport, year, month, limit, offset);
|
|
253
|
+
if (!rows.length) {
|
|
254
|
+
return {
|
|
255
|
+
found: false,
|
|
256
|
+
reason: 'no_data',
|
|
257
|
+
airport,
|
|
258
|
+
year,
|
|
259
|
+
month,
|
|
260
|
+
message: `No delay-cause rows for ${airport}${year ? ` in ${year}` : ''}${month ? ` month ${month}` : ''} in the loaded window (${meta.earliest_month} to ${meta.latest_month}).`,
|
|
261
|
+
coverage: { earliest_month: meta.earliest_month, latest_month: meta.latest_month },
|
|
262
|
+
...SOURCE,
|
|
263
|
+
data_as_of: meta.latest_month,
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
return {
|
|
267
|
+
found: true,
|
|
268
|
+
airport,
|
|
269
|
+
year,
|
|
270
|
+
month,
|
|
271
|
+
returned: rows.length,
|
|
272
|
+
total_matching,
|
|
273
|
+
truncated,
|
|
274
|
+
...(truncated ? { hint: 'More rows exist than were returned. Narrow with year/month, or page with limit/offset.' } : {}),
|
|
275
|
+
coverage: { earliest_month: meta.earliest_month, latest_month: meta.latest_month },
|
|
276
|
+
rows,
|
|
277
|
+
...SOURCE,
|
|
278
|
+
data_as_of: meta.latest_month,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async function delayCausesTool(db: D1Like, args: Record<string, unknown>) {
|
|
283
|
+
const meta = await getMeta(db);
|
|
284
|
+
const year = Math.floor(Number(args.year));
|
|
285
|
+
if (!Number.isFinite(year)) throw new Error('year must be a valid number');
|
|
286
|
+
|
|
287
|
+
let carrierCode: string | null = null;
|
|
288
|
+
if (args.carrier != null && args.carrier !== '') {
|
|
289
|
+
carrierCode = resolveCarrierCode(args.carrier);
|
|
290
|
+
if (!carrierCode || !(await validCarrier(db, carrierCode))) return { ...notFoundCarrier(args.carrier), data_as_of: meta.latest_month };
|
|
291
|
+
}
|
|
292
|
+
let airport: string | null = null;
|
|
293
|
+
if (args.airport != null && args.airport !== '') {
|
|
294
|
+
airport = normAirport(args.airport);
|
|
295
|
+
if (!airport) return { found: false, reason: 'invalid_airport', message: `${JSON.stringify(args.airport)} is not a valid airport code.`, data_as_of: meta.latest_month };
|
|
296
|
+
if (!(await validAirport(db, airport))) return { ...notFoundAirport(args.airport), data_as_of: meta.latest_month };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const limit = clampLimit(args.limit);
|
|
300
|
+
const offset = Math.max(0, Math.floor(Number(args.offset) || 0));
|
|
301
|
+
const { rows, total_matching, truncated } = await delayCauses(db, carrierCode, airport, year, limit, offset);
|
|
302
|
+
if (!rows.length) {
|
|
303
|
+
return {
|
|
304
|
+
found: false,
|
|
305
|
+
reason: 'no_data',
|
|
306
|
+
year,
|
|
307
|
+
carrier: carrierCode,
|
|
308
|
+
airport,
|
|
309
|
+
message: `No delay-cause rows for ${year}${carrierCode ? ` carrier ${carrierCode}` : ''}${airport ? ` airport ${airport}` : ''} in the loaded window (${meta.earliest_month} to ${meta.latest_month}).`,
|
|
310
|
+
coverage: { earliest_month: meta.earliest_month, latest_month: meta.latest_month },
|
|
311
|
+
...SOURCE,
|
|
312
|
+
data_as_of: meta.latest_month,
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
return {
|
|
316
|
+
found: true,
|
|
317
|
+
year,
|
|
318
|
+
carrier: carrierCode,
|
|
319
|
+
airport,
|
|
320
|
+
returned: rows.length,
|
|
321
|
+
total_matching,
|
|
322
|
+
truncated,
|
|
323
|
+
...(truncated ? { hint: 'More rows exist than were returned. Narrow with carrier/airport, or page with limit/offset.' } : {}),
|
|
324
|
+
coverage: { earliest_month: meta.earliest_month, latest_month: meta.latest_month },
|
|
325
|
+
rows,
|
|
326
|
+
...SOURCE,
|
|
327
|
+
data_as_of: meta.latest_month,
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
async function listCoverageTool(db: D1Like) {
|
|
332
|
+
const meta = await getMeta(db);
|
|
333
|
+
return {
|
|
334
|
+
earliest_month: meta.earliest_month,
|
|
335
|
+
latest_month: meta.latest_month,
|
|
336
|
+
months_loaded: meta.months_loaded,
|
|
337
|
+
loaded_at: meta.loaded_at,
|
|
338
|
+
note: 'Scoped to the most recent months as of the load, not full BTS history (1987-present). Re-run the loader with a larger --months to extend further back.',
|
|
339
|
+
...SOURCE,
|
|
340
|
+
data_as_of: meta.latest_month,
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
async function callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
|
|
345
|
+
const bound = requireDb(args._d1);
|
|
346
|
+
switch (name) {
|
|
347
|
+
case 'route_ontime':
|
|
348
|
+
return routeOntimeTool(bound, args);
|
|
349
|
+
case 'carrier_ontime':
|
|
350
|
+
return carrierOntimeTool(bound, args);
|
|
351
|
+
case 'bts_airport_delays':
|
|
352
|
+
return airportDelaysTool(bound, args);
|
|
353
|
+
case 'delay_causes':
|
|
354
|
+
return delayCausesTool(bound, args);
|
|
355
|
+
case 'list_coverage':
|
|
356
|
+
return listCoverageTool(bound);
|
|
357
|
+
default:
|
|
358
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
export default { tools, callTool, meter: { credits: 1 } } satisfies McpToolExport;
|
package/src/server.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stdio MCP server entry point for @pipeworx/mcp-bts-ontime.
|
|
3
|
+
* Generated by scripts/publish-pack.sh — do not hand-edit in the pack repo;
|
|
4
|
+
* edit scripts/publish-pack.sh (the server.ts heredoc) and republish instead.
|
|
5
|
+
*/
|
|
6
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
7
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
8
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
9
|
+
import pack from './index.js';
|
|
10
|
+
|
|
11
|
+
const server = new Server(
|
|
12
|
+
{ name: '@pipeworx/mcp-bts-ontime', version: '0.1.0' },
|
|
13
|
+
{ capabilities: { tools: {} } },
|
|
14
|
+
);
|
|
15
|
+
|
|
16
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
17
|
+
tools: pack.tools.map((t) => ({
|
|
18
|
+
name: t.name,
|
|
19
|
+
description: t.description,
|
|
20
|
+
inputSchema: t.inputSchema,
|
|
21
|
+
})),
|
|
22
|
+
}));
|
|
23
|
+
|
|
24
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
25
|
+
const { name, arguments: args } = request.params;
|
|
26
|
+
try {
|
|
27
|
+
const result = await pack.callTool(name, (args ?? {}) as Record<string, unknown>);
|
|
28
|
+
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
29
|
+
} catch (err) {
|
|
30
|
+
return {
|
|
31
|
+
content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }],
|
|
32
|
+
isError: true,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
async function main() {
|
|
38
|
+
const transport = new StdioServerTransport();
|
|
39
|
+
await server.connect(transport);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
main().catch((err) => {
|
|
43
|
+
console.error('Fatal error running server:', err);
|
|
44
|
+
process.exit(1);
|
|
45
|
+
});
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads for bts-ontime (fleet #2953).
|
|
3
|
+
*
|
|
4
|
+
* Data: US DOT Bureau of Transportation Statistics (BTS) TranStats,
|
|
5
|
+
* "Reporting Carrier On-Time Performance (1987-present)" monthly bulk CSVs
|
|
6
|
+
* (https://transtats.bts.gov/PREZIP/). US federal government work -- public
|
|
7
|
+
* domain, 17 U.S.C. §105. Loaded into a D1 database the gateway hands this
|
|
8
|
+
* pack as `_d1` (pack-manifest "d1Binding": "BTS_ONTIME_DB") by
|
|
9
|
+
* scripts/bts-ontime/load-data.mjs -- never by a deploy.
|
|
10
|
+
*
|
|
11
|
+
* Two tables, both derived from the SAME monthly raw file:
|
|
12
|
+
* - route_month: carrier x origin x dest x month.
|
|
13
|
+
* - delay_cause: carrier x (arrival) airport x month -- delay-minute sums
|
|
14
|
+
* by cause, rolled up by arrival airport instead of by route. This is
|
|
15
|
+
* NOT the separately-published BTS "Airline Delay Cause" product (which
|
|
16
|
+
* apportions delay into fractional per-cause counts); it is the same
|
|
17
|
+
* underlying CarrierDelay/WeatherDelay/NASDelay/SecurityDelay/
|
|
18
|
+
* LateAircraftDelay minute fields, summed. See README.md.
|
|
19
|
+
*
|
|
20
|
+
* SCOPE, found 2026-10-13: loaded the most recent N months as of the run
|
|
21
|
+
* (see bts_ontime_meta for the exact range) rather than back to 2003 -- BTS's
|
|
22
|
+
* per-connection throttling (measured: one download ~170s regardless of file
|
|
23
|
+
* size vs wall time, 3 concurrent downloads of the same upstream in the same
|
|
24
|
+
* wall time as 1 serial one) makes a multi-decade backfill a multi-hour job
|
|
25
|
+
* better run as a scheduled extension than inline in one pack-build session.
|
|
26
|
+
* Re-run the loader with a larger --months to extend further back -- see
|
|
27
|
+
* README.md "Refresh".
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
export interface D1Like {
|
|
31
|
+
prepare(sql: string): D1StmtLike;
|
|
32
|
+
}
|
|
33
|
+
export interface D1StmtLike {
|
|
34
|
+
bind(...values: unknown[]): D1StmtLike;
|
|
35
|
+
all<T = Record<string, unknown>>(): Promise<{ results: T[] }>;
|
|
36
|
+
first<T = Record<string, unknown>>(): Promise<T | null>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class StoreUnavailableError extends Error {
|
|
40
|
+
constructor() {
|
|
41
|
+
super(
|
|
42
|
+
'bts-ontime: the on-time performance store is not bound in this runtime (no _d1). These tools only answer through the Pipeworx gateway; a standalone install has no data to read.',
|
|
43
|
+
);
|
|
44
|
+
this.name = 'StoreUnavailableError';
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export function requireDb(d1: unknown): D1Like {
|
|
48
|
+
if (!d1 || typeof (d1 as D1Like).prepare !== 'function') throw new StoreUnavailableError();
|
|
49
|
+
return d1 as D1Like;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export const SOURCE = {
|
|
53
|
+
source: 'US DOT Bureau of Transportation Statistics (BTS), TranStats "Reporting Carrier On-Time Performance (1987-present)"',
|
|
54
|
+
source_url: 'https://transtats.bts.gov/PREZIP/',
|
|
55
|
+
license: 'US federal government work -- public domain (17 U.S.C. §105)',
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
// ── carrier code resolution ─────────────────────────────────────────────
|
|
59
|
+
// Reporting_Airline in the raw file is already a short code (e.g. "DL",
|
|
60
|
+
// "AA", "WN"); this just lets a caller say a common name instead. Codes NOT
|
|
61
|
+
// in this alias table still work fine as long as they're typed as the code
|
|
62
|
+
// itself -- validity is checked against what the DB actually holds
|
|
63
|
+
// (validCarrier below), not against this list.
|
|
64
|
+
const CARRIER_ALIASES: Record<string, string> = {
|
|
65
|
+
AA: 'AA', AMERICAN: 'AA', 'AMERICAN AIRLINES': 'AA',
|
|
66
|
+
DL: 'DL', DELTA: 'DL', 'DELTA AIR LINES': 'DL',
|
|
67
|
+
UA: 'UA', UNITED: 'UA', 'UNITED AIRLINES': 'UA',
|
|
68
|
+
WN: 'WN', SOUTHWEST: 'WN', 'SOUTHWEST AIRLINES': 'WN',
|
|
69
|
+
B6: 'B6', JETBLUE: 'B6', 'JETBLUE AIRWAYS': 'B6',
|
|
70
|
+
AS: 'AS', ALASKA: 'AS', 'ALASKA AIRLINES': 'AS',
|
|
71
|
+
NK: 'NK', SPIRIT: 'NK', 'SPIRIT AIRLINES': 'NK',
|
|
72
|
+
F9: 'F9', FRONTIER: 'F9', 'FRONTIER AIRLINES': 'F9',
|
|
73
|
+
G4: 'G4', ALLEGIANT: 'G4', 'ALLEGIANT AIR': 'G4',
|
|
74
|
+
HA: 'HA', HAWAIIAN: 'HA', 'HAWAIIAN AIRLINES': 'HA',
|
|
75
|
+
OO: 'OO', SKYWEST: 'OO', 'SKYWEST AIRLINES': 'OO',
|
|
76
|
+
MQ: 'MQ', ENVOY: 'MQ', 'ENVOY AIR': 'MQ',
|
|
77
|
+
YX: 'YX', REPUBLIC: 'YX', 'REPUBLIC AIRWAYS': 'YX',
|
|
78
|
+
OH: 'OH', PSA: 'OH', 'PSA AIRLINES': 'OH',
|
|
79
|
+
'9E': '9E', ENDEAVOR: '9E', 'ENDEAVOR AIR': '9E',
|
|
80
|
+
YV: 'YV', MESA: 'YV', 'MESA AIRLINES': 'YV',
|
|
81
|
+
QX: 'QX', HORIZON: 'QX', 'HORIZON AIR': 'QX',
|
|
82
|
+
ZW: 'ZW', 'AIR WISCONSIN': 'ZW',
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
/** Normalize caller input to a candidate carrier code -- does NOT guarantee
|
|
86
|
+
* the code actually exists in this pack's data; call validCarrier() for that. */
|
|
87
|
+
export function resolveCarrierCode(input: unknown): string | null {
|
|
88
|
+
if (input == null) return null;
|
|
89
|
+
const s = String(input).trim().toUpperCase();
|
|
90
|
+
if (!s) return null;
|
|
91
|
+
return CARRIER_ALIASES[s] ?? (/^[0-9A-Z]{2}$/.test(s) ? s : null);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function validCarrier(db: D1Like, code: string): Promise<boolean> {
|
|
95
|
+
const r = await db.prepare('SELECT 1 AS x FROM route_month WHERE carrier = ? LIMIT 1').bind(code).first<{ x: number }>();
|
|
96
|
+
return r != null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export async function validAirport(db: D1Like, code: string): Promise<boolean> {
|
|
100
|
+
const r = await db
|
|
101
|
+
.prepare('SELECT 1 AS x FROM route_month WHERE origin = ? OR dest = ? LIMIT 1')
|
|
102
|
+
.bind(code, code)
|
|
103
|
+
.first<{ x: number }>();
|
|
104
|
+
return r != null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function normAirport(input: unknown): string | null {
|
|
108
|
+
if (input == null) return null;
|
|
109
|
+
const s = String(input).trim().toUpperCase();
|
|
110
|
+
return /^[A-Z]{3,4}$/.test(s) ? s : null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface Meta {
|
|
114
|
+
loaded_at: string;
|
|
115
|
+
earliest_month: string; // "YYYY-MM"
|
|
116
|
+
latest_month: string; // "YYYY-MM"
|
|
117
|
+
months_loaded: number;
|
|
118
|
+
}
|
|
119
|
+
let cachedMeta: Meta | null = null;
|
|
120
|
+
export async function getMeta(db: D1Like): Promise<Meta> {
|
|
121
|
+
if (cachedMeta) return cachedMeta;
|
|
122
|
+
const r = await db.prepare('SELECT key, value FROM bts_ontime_meta').all<{ key: string; value: string }>();
|
|
123
|
+
const m = Object.fromEntries(r.results.map((row) => [row.key, row.value]));
|
|
124
|
+
cachedMeta = {
|
|
125
|
+
loaded_at: m.loaded_at ?? '',
|
|
126
|
+
earliest_month: m.earliest_month ?? '',
|
|
127
|
+
latest_month: m.latest_month ?? '',
|
|
128
|
+
months_loaded: Number(m.months_loaded ?? 0),
|
|
129
|
+
};
|
|
130
|
+
return cachedMeta;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Row-count limit for the delay-cause listing tools: default 50, max 200,
|
|
134
|
+
* so a default call stays well under the ~40KB response-size guidance. */
|
|
135
|
+
export function clampLimit(requested: unknown, dflt = 50, max = 200): number {
|
|
136
|
+
const n = Math.floor(Number(requested));
|
|
137
|
+
if (!Number.isFinite(n) || n <= 0) return dflt;
|
|
138
|
+
return Math.min(n, max);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** How many of the most recent loaded months to look back, clamped to what
|
|
142
|
+
* is actually loaded. */
|
|
143
|
+
export function clampMonths(requested: unknown, monthsLoaded: number, dflt = 12): number {
|
|
144
|
+
const n = Math.floor(Number(requested));
|
|
145
|
+
if (!Number.isFinite(n) || n <= 0) return Math.min(dflt, monthsLoaded);
|
|
146
|
+
return Math.min(n, monthsLoaded);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface RouteMonthRow {
|
|
150
|
+
year: number;
|
|
151
|
+
month: number;
|
|
152
|
+
carrier: string;
|
|
153
|
+
origin: string;
|
|
154
|
+
dest: string;
|
|
155
|
+
flights: number;
|
|
156
|
+
completed_flights: number;
|
|
157
|
+
ontime_arrivals: number;
|
|
158
|
+
sum_arr_delay: number;
|
|
159
|
+
cancelled: number;
|
|
160
|
+
diverted: number;
|
|
161
|
+
carrier_delay_min: number;
|
|
162
|
+
weather_delay_min: number;
|
|
163
|
+
nas_delay_min: number;
|
|
164
|
+
security_delay_min: number;
|
|
165
|
+
late_aircraft_delay_min: number;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function shapeRoute(r: RouteMonthRow) {
|
|
169
|
+
return {
|
|
170
|
+
year: r.year,
|
|
171
|
+
month: r.month,
|
|
172
|
+
carrier: r.carrier,
|
|
173
|
+
origin: r.origin,
|
|
174
|
+
dest: r.dest,
|
|
175
|
+
flights: r.flights,
|
|
176
|
+
completed_flights: r.completed_flights,
|
|
177
|
+
cancelled: r.cancelled,
|
|
178
|
+
diverted: r.diverted,
|
|
179
|
+
ontime_arrivals: r.ontime_arrivals,
|
|
180
|
+
ontime_pct: r.completed_flights > 0 ? round2((r.ontime_arrivals / r.completed_flights) * 100) : null,
|
|
181
|
+
avg_arr_delay_min: r.completed_flights > 0 ? round2(r.sum_arr_delay / r.completed_flights) : null,
|
|
182
|
+
delay_minutes_by_cause: {
|
|
183
|
+
carrier: round2(r.carrier_delay_min),
|
|
184
|
+
weather: round2(r.weather_delay_min),
|
|
185
|
+
nas: round2(r.nas_delay_min),
|
|
186
|
+
security: round2(r.security_delay_min),
|
|
187
|
+
late_aircraft: round2(r.late_aircraft_delay_min),
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
function round2(n: number): number {
|
|
192
|
+
return Math.round(n * 100) / 100;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Same shape as shapeRoute, but for a carrier-level aggregate that has no
|
|
196
|
+
* single origin/dest (it is summed across every route that matched). */
|
|
197
|
+
function shapeCarrierMonth(carrier: string, r: Omit<RouteMonthRow, 'carrier' | 'origin' | 'dest'>) {
|
|
198
|
+
return {
|
|
199
|
+
year: r.year,
|
|
200
|
+
month: r.month,
|
|
201
|
+
carrier,
|
|
202
|
+
flights: r.flights,
|
|
203
|
+
completed_flights: r.completed_flights,
|
|
204
|
+
cancelled: r.cancelled,
|
|
205
|
+
diverted: r.diverted,
|
|
206
|
+
ontime_arrivals: r.ontime_arrivals,
|
|
207
|
+
ontime_pct: r.completed_flights > 0 ? round2((r.ontime_arrivals / r.completed_flights) * 100) : null,
|
|
208
|
+
avg_arr_delay_min: r.completed_flights > 0 ? round2(r.sum_arr_delay / r.completed_flights) : null,
|
|
209
|
+
delay_minutes_by_cause: {
|
|
210
|
+
carrier: round2(r.carrier_delay_min),
|
|
211
|
+
weather: round2(r.weather_delay_min),
|
|
212
|
+
nas: round2(r.nas_delay_min),
|
|
213
|
+
security: round2(r.security_delay_min),
|
|
214
|
+
late_aircraft: round2(r.late_aircraft_delay_min),
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export async function routeMonths(db: D1Like, origin: string, dest: string, carrier: string | null, limitMonths: number) {
|
|
220
|
+
const where = ['origin = ?', 'dest = ?'];
|
|
221
|
+
const params: unknown[] = [origin, dest];
|
|
222
|
+
if (carrier) {
|
|
223
|
+
where.push('carrier = ?');
|
|
224
|
+
params.push(carrier);
|
|
225
|
+
}
|
|
226
|
+
const sql = `SELECT year, month, carrier, origin, dest, flights, completed_flights, ontime_arrivals, sum_arr_delay, cancelled, diverted, carrier_delay_min, weather_delay_min, nas_delay_min, security_delay_min, late_aircraft_delay_min
|
|
227
|
+
FROM route_month WHERE ${where.join(' AND ')}
|
|
228
|
+
ORDER BY year DESC, month DESC, carrier
|
|
229
|
+
LIMIT ?`;
|
|
230
|
+
params.push(limitMonths * 20); // generous cap: several carriers per route per month
|
|
231
|
+
const r = await db.prepare(sql).bind(...params).all<RouteMonthRow>();
|
|
232
|
+
return r.results.map(shapeRoute);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export async function carrierMonths(db: D1Like, carrier: string, airport: string | null, limitMonths: number) {
|
|
236
|
+
const where = ['carrier = ?'];
|
|
237
|
+
const params: unknown[] = [carrier];
|
|
238
|
+
if (airport) {
|
|
239
|
+
where.push('(origin = ? OR dest = ?)');
|
|
240
|
+
params.push(airport, airport);
|
|
241
|
+
}
|
|
242
|
+
const sql = `SELECT year, month,
|
|
243
|
+
SUM(flights) AS flights, SUM(completed_flights) AS completed_flights, SUM(ontime_arrivals) AS ontime_arrivals,
|
|
244
|
+
SUM(sum_arr_delay) AS sum_arr_delay, SUM(cancelled) AS cancelled, SUM(diverted) AS diverted,
|
|
245
|
+
SUM(carrier_delay_min) AS carrier_delay_min, SUM(weather_delay_min) AS weather_delay_min,
|
|
246
|
+
SUM(nas_delay_min) AS nas_delay_min, SUM(security_delay_min) AS security_delay_min, SUM(late_aircraft_delay_min) AS late_aircraft_delay_min
|
|
247
|
+
FROM route_month WHERE ${where.join(' AND ')}
|
|
248
|
+
GROUP BY year, month
|
|
249
|
+
ORDER BY year DESC, month DESC
|
|
250
|
+
LIMIT ?`;
|
|
251
|
+
params.push(limitMonths);
|
|
252
|
+
const r = await db.prepare(sql).bind(...params).all<Omit<RouteMonthRow, 'carrier' | 'origin' | 'dest'>>();
|
|
253
|
+
return r.results.map((row) => shapeCarrierMonth(carrier, row));
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export interface DelayCauseRow {
|
|
257
|
+
year: number;
|
|
258
|
+
month: number;
|
|
259
|
+
carrier: string;
|
|
260
|
+
airport: string;
|
|
261
|
+
arr_flights: number;
|
|
262
|
+
arr_del15: number;
|
|
263
|
+
arr_cancelled: number;
|
|
264
|
+
arr_diverted: number;
|
|
265
|
+
carrier_delay_min: number;
|
|
266
|
+
weather_delay_min: number;
|
|
267
|
+
nas_delay_min: number;
|
|
268
|
+
security_delay_min: number;
|
|
269
|
+
late_aircraft_delay_min: number;
|
|
270
|
+
}
|
|
271
|
+
function shapeCause(r: DelayCauseRow) {
|
|
272
|
+
return {
|
|
273
|
+
year: r.year,
|
|
274
|
+
month: r.month,
|
|
275
|
+
carrier: r.carrier,
|
|
276
|
+
airport: r.airport,
|
|
277
|
+
arr_flights: r.arr_flights,
|
|
278
|
+
arr_del15: r.arr_del15,
|
|
279
|
+
arr_del15_pct: r.arr_flights > 0 ? round2((r.arr_del15 / r.arr_flights) * 100) : null,
|
|
280
|
+
arr_cancelled: r.arr_cancelled,
|
|
281
|
+
arr_diverted: r.arr_diverted,
|
|
282
|
+
delay_minutes_by_cause: {
|
|
283
|
+
carrier: round2(r.carrier_delay_min),
|
|
284
|
+
weather: round2(r.weather_delay_min),
|
|
285
|
+
nas: round2(r.nas_delay_min),
|
|
286
|
+
security: round2(r.security_delay_min),
|
|
287
|
+
late_aircraft: round2(r.late_aircraft_delay_min),
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export interface PagedResult<T> {
|
|
293
|
+
rows: T[];
|
|
294
|
+
total_matching: number;
|
|
295
|
+
truncated: boolean;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export async function delayCausesAtAirport(
|
|
299
|
+
db: D1Like,
|
|
300
|
+
airport: string,
|
|
301
|
+
year: number | null,
|
|
302
|
+
month: number | null,
|
|
303
|
+
limit: number,
|
|
304
|
+
offset: number,
|
|
305
|
+
): Promise<PagedResult<ReturnType<typeof shapeCause>>> {
|
|
306
|
+
const where = ['airport = ?'];
|
|
307
|
+
const params: unknown[] = [airport];
|
|
308
|
+
if (year != null) {
|
|
309
|
+
where.push('year = ?');
|
|
310
|
+
params.push(year);
|
|
311
|
+
}
|
|
312
|
+
if (month != null) {
|
|
313
|
+
where.push('month = ?');
|
|
314
|
+
params.push(month);
|
|
315
|
+
}
|
|
316
|
+
const whereSql = where.join(' AND ');
|
|
317
|
+
const sql = `SELECT year, month, carrier, airport, arr_flights, arr_del15, arr_cancelled, arr_diverted, carrier_delay_min, weather_delay_min, nas_delay_min, security_delay_min, late_aircraft_delay_min
|
|
318
|
+
FROM delay_cause WHERE ${whereSql}
|
|
319
|
+
ORDER BY year DESC, month DESC, arr_flights DESC
|
|
320
|
+
LIMIT ? OFFSET ?`;
|
|
321
|
+
const countSql = `SELECT COUNT(*) AS n FROM delay_cause WHERE ${whereSql}`;
|
|
322
|
+
const [r, c] = await Promise.all([
|
|
323
|
+
db.prepare(sql).bind(...params, limit, offset).all<DelayCauseRow>(),
|
|
324
|
+
db.prepare(countSql).bind(...params).first<{ n: number }>(),
|
|
325
|
+
]);
|
|
326
|
+
const total = c?.n ?? r.results.length;
|
|
327
|
+
return { rows: r.results.map(shapeCause), total_matching: total, truncated: offset + r.results.length < total };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export async function delayCauses(
|
|
331
|
+
db: D1Like,
|
|
332
|
+
carrier: string | null,
|
|
333
|
+
airport: string | null,
|
|
334
|
+
year: number,
|
|
335
|
+
limit: number,
|
|
336
|
+
offset: number,
|
|
337
|
+
): Promise<PagedResult<ReturnType<typeof shapeCause>>> {
|
|
338
|
+
const where = ['year = ?'];
|
|
339
|
+
const params: unknown[] = [year];
|
|
340
|
+
if (carrier) {
|
|
341
|
+
where.push('carrier = ?');
|
|
342
|
+
params.push(carrier);
|
|
343
|
+
}
|
|
344
|
+
if (airport) {
|
|
345
|
+
where.push('airport = ?');
|
|
346
|
+
params.push(airport);
|
|
347
|
+
}
|
|
348
|
+
const whereSql = where.join(' AND ');
|
|
349
|
+
const sql = `SELECT year, month, carrier, airport, arr_flights, arr_del15, arr_cancelled, arr_diverted, carrier_delay_min, weather_delay_min, nas_delay_min, security_delay_min, late_aircraft_delay_min
|
|
350
|
+
FROM delay_cause WHERE ${whereSql}
|
|
351
|
+
ORDER BY month DESC, arr_flights DESC
|
|
352
|
+
LIMIT ? OFFSET ?`;
|
|
353
|
+
const countSql = `SELECT COUNT(*) AS n FROM delay_cause WHERE ${whereSql}`;
|
|
354
|
+
const [r, c] = await Promise.all([
|
|
355
|
+
db.prepare(sql).bind(...params, limit, offset).all<DelayCauseRow>(),
|
|
356
|
+
db.prepare(countSql).bind(...params).first<{ n: number }>(),
|
|
357
|
+
]);
|
|
358
|
+
const total = c?.n ?? r.results.length;
|
|
359
|
+
return { rows: r.results.map(shapeCause), total_matching: total, truncated: offset + r.results.length < total };
|
|
360
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"module": "ESNext",
|
|
5
|
+
"moduleResolution": "bundler",
|
|
6
|
+
"lib": ["ES2022"],
|
|
7
|
+
"types": ["@cloudflare/workers-types"],
|
|
8
|
+
"strict": true,
|
|
9
|
+
"esModuleInterop": true,
|
|
10
|
+
"skipLibCheck": true,
|
|
11
|
+
"resolveJsonModule": true,
|
|
12
|
+
"outDir": "dist",
|
|
13
|
+
"rootDir": "src",
|
|
14
|
+
"declaration": true
|
|
15
|
+
},
|
|
16
|
+
"include": ["src"],
|
|
17
|
+
"exclude": ["src/server.ts"]
|
|
18
|
+
}
|