football-docs 0.14.0 → 0.15.1

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.
Files changed (62) hide show
  1. package/README.md +26 -11
  2. package/bin/serve.js +10 -0
  3. package/data/docs.db +0 -0
  4. package/dist/data-format.d.ts +9 -4
  5. package/dist/data-format.js +15 -8
  6. package/dist/index.d.ts +3 -3
  7. package/dist/index.js +6 -6
  8. package/dist/ingest.js +6 -7
  9. package/dist/opta-truth.d.ts +44 -0
  10. package/dist/opta-truth.js +158 -0
  11. package/dist/sportmonks-truth.d.ts +37 -0
  12. package/dist/sportmonks-truth.js +87 -0
  13. package/dist/sqlite.d.ts +18 -0
  14. package/dist/sqlite.js +31 -0
  15. package/dist/statsbomb-truth.d.ts +48 -0
  16. package/dist/statsbomb-truth.js +193 -0
  17. package/dist/tools.d.ts +8 -8
  18. package/dist/tools.js +106 -10
  19. package/docs/firstbeat/api-access.md +127 -0
  20. package/docs/firstbeat/api-endpoints.md +434 -0
  21. package/docs/firstbeat/data-model.md +325 -0
  22. package/docs/firstbeat/data-provenance.md +36 -0
  23. package/docs/firstbeat/identity-surfaces.md +57 -0
  24. package/docs/firstbeat/variables.md +208 -0
  25. package/docs/hawkin-dynamics/api-access.md +112 -0
  26. package/docs/hawkin-dynamics/api-endpoints.md +258 -0
  27. package/docs/hawkin-dynamics/data-model.md +207 -0
  28. package/docs/hawkin-dynamics/data-provenance.md +36 -0
  29. package/docs/hawkin-dynamics/identity-surfaces.md +49 -0
  30. package/docs/hawkin-dynamics/test-metrics.md +670 -0
  31. package/docs/kloppy/event-derived-metrics.md +2 -2
  32. package/docs/opta/api-access.md +0 -1
  33. package/docs/opta/charting-game-state.md +7 -5
  34. package/docs/opta/charting-passmaps.md +3 -2
  35. package/docs/opta/charting-shot-placement.md +14 -12
  36. package/docs/opta/coordinate-system.md +9 -3
  37. package/docs/opta/event-types.md +54 -50
  38. package/docs/opta/qualifiers.md +6 -4
  39. package/docs/sportmonks/charting-season-stories.md +3 -3
  40. package/docs/sportmonks/data-model.md +9 -9
  41. package/docs/sportmonks/event-types.md +81 -59
  42. package/docs/statsbomb/event-types.md +83 -4
  43. package/docs/statsports/api-access.md +96 -0
  44. package/docs/statsports/api-endpoints.md +97 -0
  45. package/docs/statsports/data-model.md +399 -0
  46. package/docs/statsports/data-provenance.md +35 -0
  47. package/docs/statsports/drill-kpi-metrics.md +549 -0
  48. package/docs/statsports/identity-surfaces.md +67 -0
  49. package/docs/vald/api-access.md +131 -0
  50. package/docs/vald/api-endpoints.md +106 -0
  51. package/docs/vald/data-provenance.md +40 -0
  52. package/docs/vald/dynamo.md +566 -0
  53. package/docs/vald/forcedecks.md +839 -0
  54. package/docs/vald/forceframe.md +668 -0
  55. package/docs/vald/humantrak.md +286 -0
  56. package/docs/vald/identity-surfaces.md +67 -0
  57. package/docs/vald/nordbord.md +694 -0
  58. package/docs/vald/profiles.md +302 -0
  59. package/docs/vald/smartspeed.md +490 -0
  60. package/docs/vald/tenants.md +413 -0
  61. package/package.json +3 -4
  62. package/providers.json +116 -2
package/README.md CHANGED
@@ -4,7 +4,7 @@ Searchable football data provider and tooling documentation for AI coding agents
4
4
 
5
5
  **Who it's for:** Developers and analysts who use AI coding tools (Claude Code, Cursor, VS Code Copilot) to work with football data. Works with any tool that supports MCP.
6
6
 
7
- **What it does:** Gives your AI agent a searchable index of documentation for 24 football data providers and tools — event types, qualifier IDs, coordinate systems, API endpoints, data models, identity surfaces, and cross-provider comparisons for the data providers (StatsBomb, Opta, Wyscout, Impect, SkillCorner, Sportradar, TheSportsDB, FMDB Pro, TransferRoom, and more), plus the open-source libraries people build with (kloppy, mplsoccer, socceraction, soccerdata, floodlight, fast-forward, unravelsports, and more). Your agent looks up the real docs instead of guessing from training data.
7
+ **What it does:** Gives your AI agent a searchable index of documentation for 30 football data providers and tools — event types, qualifier IDs, coordinate systems, API endpoints, data models, identity surfaces, and cross-provider comparisons for the data providers (StatsBomb, Opta, Wyscout, Impect, SkillCorner, Sportradar, TheSportsDB, FMDB Pro, TransferRoom, and more), the open-source libraries people build with (kloppy, mplsoccer, socceraction, soccerdata, floodlight, fast-forward, unravelsports, and more), and the APIs of wearable and sports-science vendors (STATSports, Firstbeat, Hawkin Dynamics, VALD). Your agent looks up the real docs instead of guessing from training data.
8
8
 
9
9
  **Why not just let the AI figure it out?** LLMs get football data specifics wrong constantly — Opta qualifier IDs, StatsBomb coordinate ranges, API endpoint URLs, library method signatures. These are mutable facts that change across versions. football-docs gives the agent verified, sourced documentation with provenance tracking so you know where every answer came from.
10
10
 
@@ -29,6 +29,9 @@ MCP ([Model Context Protocol](https://modelcontextprotocol.io)) is a standard fo
29
29
 
30
30
  ## Quick start
31
31
 
32
+ The server needs Node.js 22.13 or newer. It uses Node's built-in SQLite, so no
33
+ native module is compiled at install time.
34
+
32
35
  ### Claude Code
33
36
 
34
37
  ```bash
@@ -84,7 +87,7 @@ Add to `claude_desktop_config.json`:
84
87
 
85
88
  | Tool | Description |
86
89
  |------|-------------|
87
- | `search_docs` | Full-text search across all provider docs. Filter by provider. Results include provenance (source URL, version). |
90
+ | `search_docs` | Full-text search across all provider docs. Filter by provider. Results include provenance (source URL, version), mark partial matches, name query terms that no indexed doc mentions, and say when a query names a provider that is not indexed (the `not_indexed` list in `providers.json` gives the reason). |
88
91
  | `resolve_provider_id` | Resolve provider names and aliases to canonical indexed provider keys before searching. |
89
92
  | `get_provider_docs` | Retrieve docs for a resolved provider, optionally filtered by topic or category. |
90
93
  | `list_providers` | List all indexed providers and their doc coverage. |
@@ -92,7 +95,7 @@ Add to `claude_desktop_config.json`:
92
95
  | `request_update` | Request a new provider, flag outdated docs, or suggest a better doc source. Queues locally and points to the matching public GitHub issue template. |
93
96
  | `resolve_entity` | Map a player, coach, referee, team, competition, season, stage or match to its IDs at every provider through the [Reep register](https://reep.football). Uses a local copy of the free register (`REEP_DUCKDB_PATH`), else the Reep API (`REEP_API_KEY`; keys are issued by hand on request to getintouch+nutmeg@withqwerty.com, with no self-service sign-up), else returns setup steps and a DuckDB query. See [Reep through football-docs](docs/reep/overview.md#using-reep-through-football-docs). |
94
97
 
95
- Provider filters use the indexed provider keys shown by `list_providers`, but common aliases are accepted. Examples: `fbref`, `understat`, `ClubElo`, `football-data.co.uk`, and `engsoccerdata` search `free-sources`; `Sofascore` searches `soccerdata`; `ESPN`, `ESPN FC`, and `espn-soccer` search `espn`; `FMDB` searches `fmdb-pro`; `Transfer Room` searches `transferroom`; `Hudl Wyscout` searches `wyscout`; `Stats Perform` / `Opta F24` / `WhoScored` search `opta`; `Metrica`, `Sportec` / `DFL`, and `TRACAB` search `databallpy`; `Second Spectrum` searches `kloppy`; `Hawk-Eye`, `SciSports`, `Signality`, `Respovision`, `GradientSports` and `OptaVision` search `fast-forward`; `unravel` searches `unravelsports`; `SportRadar API` / `Soccer Extended` search `sportradar`; `The Sports DB` / `TSDB` search `thesportsdb`; `StatsBomb Open Data` searches `statsbomb`.
98
+ Provider filters use the indexed provider keys shown by `list_providers`, but common aliases are accepted. Examples: `fbref`, `understat`, `ClubElo`, `football-data.co.uk`, and `engsoccerdata` search `free-sources`; `Sofascore` searches `soccerdata`; `ESPN`, `ESPN FC`, and `espn-soccer` search `espn`; `FMDB` searches `fmdb-pro`; `Transfer Room` searches `transferroom`; `Hudl Wyscout` searches `wyscout`; `Stats Perform` / `Opta F24` / `WhoScored` search `opta`; `Metrica`, `Sportec` / `DFL`, and `TRACAB` search `databallpy`; `Second Spectrum` searches `kloppy`; `Hawk-Eye`, `SciSports`, `Signality`, `Respovision`, `GradientSports` and `OptaVision` search `fast-forward`; `unravel` searches `unravelsports`; `SportRadar API` / `Soccer Extended` search `sportradar`; `Sonra` / `Apex` search `statsports`; `Hawkin` searches `hawkin-dynamics`; `ForceDecks` / `NordBord` / `ForceFrame` search `vald`; `The Sports DB` / `TSDB` search `thesportsdb`; `StatsBomb Open Data` searches `statsbomb`.
96
99
 
97
100
  ## How the index stays current
98
101
 
@@ -135,7 +138,7 @@ development and tests always use the working tree's docs.
135
138
 
136
139
  ## Example queries
137
140
 
138
- - "What is Opta qualifier 76?" (big chance)
141
+ - "What is Opta qualifier 214?" (big chance)
139
142
  - "How does StatsBomb represent shot events?"
140
143
  - "Compare Opta and Wyscout coordinate systems"
141
144
  - "What player ID fields does Transfermarkt expose?"
@@ -148,12 +151,12 @@ development and tests always use the working tree's docs.
148
151
  | Provider | Chunks | Categories |
149
152
  |----------|--------|------------|
150
153
  | fast-forward | 250 | overview, getting-started, data-model, coordinate-system, orientations, layouts, transformations, distributed-compute, api-reference, 12 provider format pages |
151
- | StatsBomb | 237 | event-types, data-model, coordinate-system, api-access, api-endpoints, charting-lineups, xg-model, iq-metrics, player/team stats, player-mapping, identity-surfaces, data-provenance |
154
+ | StatsBomb | 244 | event-types, data-model, coordinate-system, api-access, api-endpoints, charting-lineups, xg-model, iq-metrics, player/team stats, player-mapping, identity-surfaces, data-provenance |
152
155
  | unravelsports | 202 | overview, installation, quickstart, concepts, graph converters, pressing intensity, formation detection, models, utils, american-football |
153
156
  | Wyscout | 165 | event-types, data-model, coordinate-system, api-access, api-endpoints, charting-analysis-metrics, glossary, identity-surfaces, data-provenance |
154
157
  | kloppy | 126 | data-model, usage, provider-mapping, tracking-rendering, event-derived-metrics |
155
158
  | floodlight | 144 | core data objects, io parsers (Tracab, DFL, Kinexon, Opta, SkillCorner, StatsBomb, StatsPerform, Second Spectrum), transforms, metrics, models, visualisation, guides |
156
- | SportMonks | 567 | full v3 endpoint reference (fixtures, livescores, leagues, seasons, states, types, statistics, brackets), syntax and includes, filtering, rate limits, error codes, changelog, plus curated event-types, data-model, api-access, charting-season-stories, identity-surfaces, data-provenance |
159
+ | SportMonks | 568 | full v3 endpoint reference (fixtures, livescores, leagues, seasons, states, types, statistics, brackets), syntax and includes, filtering, rate limits, error codes, changelog, plus curated event-types, data-model, api-access, charting-season-stories, identity-surfaces, data-provenance |
157
160
  | databallpy | 63 | data-model, overview, usage |
158
161
  | mplsoccer | 65 | overview, pitch-types, visualizations |
159
162
  | Impect | 79 | overview, data-model, event-types, coordinate-system, concepts, kpi-definitions, identity-surfaces, data-provenance |
@@ -173,8 +176,18 @@ development and tests always use the working tree's docs.
173
176
  | FotMob | 5 | identity-surfaces, data-provenance |
174
177
  | Soccerdonna | 5 | identity-surfaces, data-provenance |
175
178
  | Transfermarkt | 5 | identity-surfaces, data-provenance |
179
+ | STATSports | 70 | api-access, api-endpoints, data-model, drill-kpi-metrics (all 319 DrillKpiV7 fields), identity-surfaces, data-provenance |
180
+ | Firstbeat | 79 | api-access, api-endpoints, data-model, variables (100 scalars, 17 time series), identity-surfaces, data-provenance |
181
+ | Hawkin Dynamics | 67 | api-access, api-endpoints, data-model, test-metrics (535 metrics across 13 test types), identity-surfaces, data-provenance |
182
+ | VALD | 318 | api-access, api-endpoints, per-product endpoints and schemas (tenants, profiles, forcedecks, nordbord, forceframe, smartspeed, dynamo, humantrak), identity-surfaces, data-provenance |
183
+
184
+ **3,394 searchable chunks** across 30 providers and tools.
176
185
 
177
- **2,852 searchable chunks** across 26 providers and tools.
186
+ STATSports, Firstbeat, Hawkin Dynamics and VALD sell wearables and testing devices.
187
+ Their APIs return a customer's own athlete data, which includes personal and health
188
+ data. The docs describe the API surface only: endpoints, field names, types and
189
+ units as each vendor's public spec or reference page states them. They contain no
190
+ athlete data, and none of these vendors' IDs join to a football data provider's IDs.
178
191
 
179
192
  ESPN coverage consists of curated, dated observations of ESPN-hosted soccer
180
193
  endpoints, checked for eng.1 and esp.1. These observations are not an official API
@@ -205,7 +218,11 @@ trusting them.
205
218
  | BeSoccer | The vendor's published Postman collection — request vocabulary and parameters | `src/__tests__/provider-truth.test.ts` |
206
219
  | Driblab | The vendor's published API guide — endpoint paths and methods. Field and group names are not in CI: the guide disagrees with the live API on them, so the docs follow the live API, checked by hand on 2026-09-22 | `src/__tests__/provider-truth.test.ts` |
207
220
  | Impect | The public [open-data](https://github.com/ImpectAPI/open-data) repository | `src/__tests__/impect-open-data-validation.test.ts` |
221
+ | StatsBomb | ID and name pairs observed in a sample of the public [open data](https://github.com/statsbomb/open-data) (three matches per competition-season, at a pinned commit). IDs the sample lacks must be listed in both the Open Data Events specification and kloppy's parser. Regenerate with `pnpm statsbomb:truth` | `src/__tests__/statsbomb-truth.test.ts` |
222
+ | Opta | Stats Perform's F24 appendices, which have no machine-readable form. `data/opta-truth.json` holds each ID the docs use, with its label, checked by hand. The test also rejects the wrong meanings earlier docs gave some IDs (`WRONG_MEANINGS` in `src/opta-truth.ts`) | `src/__tests__/opta-truth.test.ts` |
223
+ | SportMonks | Type and state IDs as SportMonks publishes them on its definitions pages and in the types spreadsheet linked from its Types page (`data/sportmonks-types-truth.json`, fetched 2026-09-30). Not the full list: the complete one needs an API key | `src/__tests__/sportmonks-truth.test.ts` |
208
224
  | Reep | The public OpenAPI spec (endpoint paths and methods), and one release's manifest and column schema (CSV table list, columns used in the SQL examples, licence and exclusions) | `src/__tests__/provider-truth.test.ts`, `src/__tests__/reep.test.ts` |
225
+ | STATSports, Firstbeat, Hawkin Dynamics, VALD | Each vendor's public OpenAPI spec (STATSports v5 to v7, Firstbeat's `openapi.json`, the document inline on Hawkin's API reference page, VALD's eight product specs) — endpoint paths and methods, and every field name in the docs' schema tables. The STATSports `DrillKpiV7` table and the Hawkin metric tables must list the spec's and `metrics.json`'s entries in full. Firstbeat's variable list has no machine-readable source and is copied by hand from its public variables page | `src/__tests__/provider-truth.test.ts`, `src/__tests__/wearable-vendors.test.ts` |
209
226
 
210
227
  ESPN has a separate observation check in `src/__tests__/espn.test.ts`. It validates
211
228
  documented endpoint paths, field-table names and types, and source URLs against
@@ -393,10 +410,8 @@ workflow run without the workflow asking for it.
393
410
  Two consequences worth knowing:
394
411
 
395
412
  - **The release job runs on Node 24.** Trusted publishing needs npm >= 11.5.1 and
396
- Node 22 still ships npm 10. The whole job uses one Node version, because
397
- switching mid-job would leave `better-sqlite3`'s native binding built for the
398
- wrong ABI and `pnpm ingest` would fail on it. Node 24 is in the CI matrix for
399
- the same reason: a release must not be the first time the suite meets it.
413
+ Node 22 still ships npm 10. Node 24 is in the CI matrix so that a release is
414
+ not the first time the suite meets it.
400
415
  - **The release job does not cache dependencies.** This is the tree that gets
401
416
  published, so it is resolved fresh from the lockfile rather than rehydrated
402
417
  from a cache that earlier runs could have poisoned.
package/bin/serve.js CHANGED
@@ -2,6 +2,16 @@
2
2
  import { resolve, dirname } from "node:path";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
4
 
5
+ // node:sqlite prints an ExperimentalWarning on Node 22 and 24. It is expected
6
+ // here, and MCP clients show a server's stderr to users, so drop that one warning.
7
+ const emitWarning = process.emitWarning;
8
+ process.emitWarning = (warning, ...args) => {
9
+ const type = typeof args[0] === "string" ? args[0] : args[0]?.type;
10
+ const message = typeof warning === "string" ? warning : warning?.message;
11
+ if (type === "ExperimentalWarning" && message?.includes("SQLite")) return;
12
+ return emitWarning.call(process, warning, ...args);
13
+ };
14
+
5
15
  const __dirname = dirname(fileURLToPath(import.meta.url));
6
16
  const { main } = await import(pathToFileURL(resolve(__dirname, "..", "dist", "index.js")).href);
7
17
 
package/data/docs.db CHANGED
Binary file
@@ -6,8 +6,8 @@
6
6
  * on what a usable file looks like, so the schema, the metadata keys and the
7
7
  * validation all live here.
8
8
  */
9
- import Database from "better-sqlite3";
10
9
  import { z } from "zod";
10
+ import { type Database } from "./sqlite.js";
11
11
  /** Bump when the table layout changes. Servers only use data with their own version. */
12
12
  export declare const DATA_SCHEMA_VERSION = 1;
13
13
  /**
@@ -48,6 +48,11 @@ export declare const providersFileSchema: z.ZodObject<{
48
48
  }, z.core.$loose>>;
49
49
  last_crawled: z.ZodNullable<z.ZodString>;
50
50
  }, z.core.$loose>>;
51
+ not_indexed: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
52
+ display_name: z.ZodString;
53
+ aliases: z.ZodArray<z.ZodString>;
54
+ reason: z.ZodString;
55
+ }, z.core.$loose>>>;
51
56
  }, z.core.$loose>;
52
57
  export type ProvidersFile = z.infer<typeof providersFileSchema>;
53
58
  export type ProviderRegistryEntry = z.infer<typeof providerEntrySchema>;
@@ -67,16 +72,16 @@ export declare function compareVersions(a: string, b: string): number;
67
72
  * Read and check the meta table. Returns null when the file predates the table
68
73
  * (older releases, and the in-memory databases some tests build).
69
74
  */
70
- export declare function readMeta(db: Database.Database): DataMeta | null;
75
+ export declare function readMeta(db: Database): DataMeta | null;
71
76
  export interface MetaInput {
72
77
  dataStamp: string;
73
78
  commit: string | null;
74
79
  providersJson: string;
75
80
  }
76
81
  /** Replace the meta table's contents. Used by ingest. */
77
- export declare function writeMeta(db: Database.Database, input: MetaInput): void;
82
+ export declare function writeMeta(db: Database, input: MetaInput): void;
78
83
  /** Settings for any docs database this process opens, bundled or downloaded. */
79
- export declare function hardenConnection(db: Database.Database): void;
84
+ export declare function hardenConnection(db: Database): void;
80
85
  export type ValidationResult = {
81
86
  ok: true;
82
87
  meta: DataMeta;
@@ -6,8 +6,8 @@
6
6
  * on what a usable file looks like, so the schema, the metadata keys and the
7
7
  * validation all live here.
8
8
  */
9
- import Database from "better-sqlite3";
10
9
  import { z } from "zod";
10
+ import { openDatabase, pragmaValue, transaction } from "./sqlite.js";
11
11
  /** Bump when the table layout changes. Servers only use data with their own version. */
12
12
  export const DATA_SCHEMA_VERSION = 1;
13
13
  /**
@@ -65,8 +65,15 @@ const providerEntrySchema = z.looseObject({
65
65
  sources: z.array(providerSourceSchema),
66
66
  last_crawled: z.string().nullable(),
67
67
  });
68
+ /** A provider that was assessed and is not indexed, with the reason. */
69
+ const notIndexedEntrySchema = z.looseObject({
70
+ display_name: z.string(),
71
+ aliases: z.array(z.string()),
72
+ reason: z.string(),
73
+ });
68
74
  export const providersFileSchema = z.looseObject({
69
75
  providers: z.record(z.string(), providerEntrySchema),
76
+ not_indexed: z.record(z.string(), notIndexedEntrySchema).optional(),
70
77
  });
71
78
  /** Compare two x.y.z versions; a pre-release suffix is ignored. */
72
79
  export function compareVersions(a, b) {
@@ -126,7 +133,7 @@ export function readMeta(db) {
126
133
  /** Replace the meta table's contents. Used by ingest. */
127
134
  export function writeMeta(db, input) {
128
135
  const insert = db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)");
129
- db.transaction(() => {
136
+ transaction(db, () => {
130
137
  db.prepare("DELETE FROM meta").run();
131
138
  insert.run("schema_version", String(DATA_SCHEMA_VERSION));
132
139
  insert.run("min_server_version", MIN_SERVER_VERSION);
@@ -134,7 +141,7 @@ export function writeMeta(db, input) {
134
141
  if (input.commit)
135
142
  insert.run("commit", input.commit);
136
143
  insert.run("providers_json", input.providersJson);
137
- })();
144
+ });
138
145
  }
139
146
  /** FTS5's internal tables. Their SQL is written by SQLite, not by us. */
140
147
  const FTS_SHADOW_TABLE = /^docs_fts_(data|idx|content|docsize|config)$/;
@@ -154,7 +161,7 @@ let referenceSchema;
154
161
  /** The exact sqlite_master rows a database built from SCHEMA_SQL has. */
155
162
  function expectedSchema() {
156
163
  if (!referenceSchema) {
157
- const reference = new Database(":memory:");
164
+ const reference = openDatabase(":memory:");
158
165
  reference.exec(SCHEMA_SQL);
159
166
  referenceSchema = JSON.stringify(schemaRows(reference));
160
167
  reference.close();
@@ -163,8 +170,8 @@ function expectedSchema() {
163
170
  }
164
171
  /** Settings for any docs database this process opens, bundled or downloaded. */
165
172
  export function hardenConnection(db) {
166
- db.pragma("trusted_schema = OFF");
167
- db.pragma("cell_size_check = ON");
173
+ db.exec("PRAGMA trusted_schema = OFF");
174
+ db.exec("PRAGMA cell_size_check = ON");
168
175
  }
169
176
  /**
170
177
  * Decide whether a file is a docs index this server can use: the exact schema,
@@ -175,10 +182,10 @@ export function hardenConnection(db) {
175
182
  export function validateDatabase(path, serverVersion, options = {}) {
176
183
  let db;
177
184
  try {
178
- db = new Database(path, { readonly: true, fileMustExist: true });
185
+ db = openDatabase(path, { readonly: true });
179
186
  hardenConnection(db);
180
187
  if (options.integrity) {
181
- const check = db.pragma("quick_check", { simple: true });
188
+ const check = pragmaValue(db, "quick_check");
182
189
  if (check !== "ok")
183
190
  return { ok: false, reason: `integrity check failed (${String(check)})` };
184
191
  }
package/dist/index.d.ts CHANGED
@@ -10,9 +10,9 @@
10
10
  * location (XDG_DATA_HOME or ~/.local/share).
11
11
  */
12
12
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
13
- import Database from "better-sqlite3";
13
+ import { type Database } from "./sqlite.js";
14
14
  export { sanitiseFtsQuery } from "./tools.js";
15
- export declare function openDb(): Database.Database;
16
- export declare function openQueueDb(): Database.Database;
15
+ export declare function openDb(): Database;
16
+ export declare function openQueueDb(): Database;
17
17
  export declare function createFootballDocsServer(): McpServer;
18
18
  export declare function main(): Promise<void>;
package/dist/index.js CHANGED
@@ -15,12 +15,12 @@ import { dirname, resolve } from "node:path";
15
15
  import { fileURLToPath } from "node:url";
16
16
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
17
17
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
18
- import Database from "better-sqlite3";
19
18
  import { z } from "zod";
20
19
  import { hardenConnection } from "./data-format.js";
21
20
  import { cleanDataDir, dataModeFor, defaultDataDir, IndexChooser } from "./data-source.js";
22
21
  import { checkForUpdate } from "./data-update.js";
23
22
  import { ENTITY_TYPES } from "./reep.js";
23
+ import { openDatabase } from "./sqlite.js";
24
24
  import { compareProviders, getProviderDocs, listProviders, requestUpdate, resolveEntity, resolveProviderId, searchDocs, } from "./tools.js";
25
25
  export { sanitiseFtsQuery } from "./tools.js";
26
26
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -51,9 +51,9 @@ export function openDb() {
51
51
  if (!existsSync(path)) {
52
52
  throw new Error(`Docs database not found at ${path}. Run 'npm run ingest' first to build the index.`);
53
53
  }
54
- const db = new Database(path, { readonly: true });
54
+ const db = openDatabase(path, { readonly: true });
55
55
  hardenConnection(db);
56
- const columns = db.pragma("table_info(docs)");
56
+ const columns = db.prepare("PRAGMA table_info(docs)").all();
57
57
  const hasProvenance = columns.some((column) => column.name === "source_type");
58
58
  if (!hasProvenance) {
59
59
  db.close();
@@ -63,8 +63,8 @@ export function openDb() {
63
63
  }
64
64
  export function openQueueDb() {
65
65
  mkdirSync(QUEUE_DB_DIR, { recursive: true });
66
- const db = new Database(QUEUE_DB_PATH);
67
- db.pragma("journal_mode = WAL");
66
+ const db = openDatabase(QUEUE_DB_PATH);
67
+ db.exec("PRAGMA journal_mode = WAL");
68
68
  db.exec(`
69
69
  CREATE TABLE IF NOT EXISTS requests (
70
70
  id TEXT PRIMARY KEY,
@@ -101,7 +101,7 @@ export function createFootballDocsServer() {
101
101
  name: "nutmeg-football-docs",
102
102
  version: PKG_VERSION,
103
103
  });
104
- server.tool("search_docs", "Search football data provider documentation. Use for finding event types, qualifier IDs, API endpoints, coordinate systems, data models, and cross-provider mappings. Returns the most relevant documentation chunks.", {
104
+ server.tool("search_docs", "Search football data provider documentation. Use for finding event types, qualifier IDs, API endpoints, coordinate systems, data models, and cross-provider mappings. Returns the most relevant documentation chunks. Results that do not contain every query term are marked \"partial\", and the reply names any query term that no indexed doc mentions: if the question is about that term, it is not indexed. It also says when the query names a provider that is not indexed, and why.", {
105
105
  query: z.string().describe("Search query. Examples: 'Opta goal qualifier', 'StatsBomb shot event type', 'coordinate system differences', 'xG qualifier ID', 'SportMonks fixture endpoint', 'FMDB Pro players endpoint'"),
106
106
  provider: z
107
107
  .string()
package/dist/ingest.js CHANGED
@@ -22,8 +22,8 @@ import { execFileSync } from "node:child_process";
22
22
  import { existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
23
23
  import { basename, dirname, resolve } from "node:path";
24
24
  import { fileURLToPath } from "node:url";
25
- import Database from "better-sqlite3";
26
25
  import { SCHEMA_SQL, writeMeta } from "./data-format.js";
26
+ import { openDatabase, transaction } from "./sqlite.js";
27
27
  const __dirname = dirname(fileURLToPath(import.meta.url));
28
28
  const DOCS_DIR = resolve(__dirname, "..", "docs");
29
29
  const DB_DIR = resolve(__dirname, "..", "data");
@@ -158,14 +158,14 @@ function main() {
158
158
  const providerArg = process.argv.indexOf("--provider");
159
159
  const singleProvider = providerArg >= 0 ? process.argv[providerArg + 1] : undefined;
160
160
  mkdirSync(DB_DIR, { recursive: true });
161
- const db = new Database(DB_PATH);
162
- db.pragma("journal_mode = WAL");
161
+ const db = openDatabase(DB_PATH);
162
+ db.exec("PRAGMA journal_mode = WAL");
163
163
  if (singleProvider) {
164
164
  // Single-provider mode: only rebuild that provider's data
165
165
  // Ensure tables exist (in case DB is fresh)
166
166
  ensureSchema(db);
167
167
  // Atomically delete existing data and re-ingest for this provider
168
- const deleteAndReinsert = db.transaction(() => {
168
+ transaction(db, () => {
169
169
  const rows = db.prepare("SELECT id, provider, category, title, content FROM docs WHERE provider = ?").all(singleProvider);
170
170
  const ftsDelete = db.prepare("INSERT INTO docs_fts(docs_fts, rowid, provider, category, title, content) VALUES('delete', ?, ?, ?, ?, ?)");
171
171
  for (const row of rows) {
@@ -173,7 +173,6 @@ function main() {
173
173
  }
174
174
  db.prepare("DELETE FROM docs WHERE provider = ?").run(singleProvider);
175
175
  });
176
- deleteAndReinsert();
177
176
  console.log(`Ingesting ${singleProvider}...\n`);
178
177
  const count = ingestProvider(db, singleProvider);
179
178
  console.log(`\nDone: ${count} chunks from ${singleProvider}`);
@@ -186,7 +185,7 @@ function main() {
186
185
  console.log(`No docs directory at ${DOCS_DIR}`);
187
186
  console.log("Create docs/{provider}/*.md files first.");
188
187
  recordMeta(db);
189
- db.pragma("journal_mode = DELETE");
188
+ db.exec("PRAGMA journal_mode = DELETE");
190
189
  db.close();
191
190
  return;
192
191
  }
@@ -207,7 +206,7 @@ function main() {
207
206
  // A shipped or downloaded file must not be in WAL mode: opening it read-only
208
207
  // would try to create -wal/-shm files next to it, which fails in a read-only
209
208
  // install and leaves side files behind in the cache.
210
- db.pragma("journal_mode = DELETE");
209
+ db.exec("PRAGMA journal_mode = DELETE");
211
210
  db.close();
212
211
  }
213
212
  // Only run when executed directly, not when imported for tests
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Validation for the Opta ID tables.
3
+ *
4
+ * Opta's reference, the Stats Perform F24 appendices, has no machine-readable
5
+ * form, so data/opta-truth.json is kept by hand: each ID the docs use,
6
+ * with the label the docs give it, checked against F24. The tests then hold the
7
+ * docs to that file, and reject meanings that were wrong in earlier versions of
8
+ * the docs (Q76 as big chance, Q213 as xG and so on) wherever they reappear.
9
+ */
10
+ export declare const OPTA_TRUTH_PATH: string;
11
+ export interface OptaTruth {
12
+ source: {
13
+ reference: string;
14
+ url: string;
15
+ checked: string;
16
+ note: string;
17
+ };
18
+ /** typeId -> event type name. */
19
+ eventTypes: Record<string, string>;
20
+ /** qualifierId -> the label docs/opta/qualifiers.md gives it. */
21
+ qualifiers: Record<string, string>;
22
+ }
23
+ export interface OptaDoc {
24
+ path: string;
25
+ text: string;
26
+ }
27
+ export interface OptaViolation {
28
+ path: string;
29
+ line: number;
30
+ message: string;
31
+ }
32
+ export declare function loadOptaTruth(): OptaTruth;
33
+ /**
34
+ * Meanings earlier docs gave these IDs, all wrong. The pattern matches the ID
35
+ * and the wrong meaning in one clause, in either order, and in a row of an Opta
36
+ * qualifier table. A clause that negates the claim ("Q213 is the pass angle, not
37
+ * xG", "Do not read qualifier 213 as xG") is allowed.
38
+ */
39
+ export declare const WRONG_MEANINGS: Array<{
40
+ id: number;
41
+ meaning: string;
42
+ pattern: RegExp;
43
+ }>;
44
+ export declare function validateOptaDocs(docs: OptaDoc[], truth: OptaTruth): OptaViolation[];
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Validation for the Opta ID tables.
3
+ *
4
+ * Opta's reference, the Stats Perform F24 appendices, has no machine-readable
5
+ * form, so data/opta-truth.json is kept by hand: each ID the docs use,
6
+ * with the label the docs give it, checked against F24. The tests then hold the
7
+ * docs to that file, and reject meanings that were wrong in earlier versions of
8
+ * the docs (Q76 as big chance, Q213 as xG and so on) wherever they reappear.
9
+ */
10
+ import { readFileSync } from "node:fs";
11
+ import { dirname, resolve } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ const __dirname = dirname(fileURLToPath(import.meta.url));
14
+ export const OPTA_TRUTH_PATH = resolve(__dirname, "..", "data", "opta-truth.json");
15
+ export function loadOptaTruth() {
16
+ return JSON.parse(readFileSync(OPTA_TRUTH_PATH, "utf-8"));
17
+ }
18
+ /**
19
+ * Meanings earlier docs gave these IDs, all wrong. The pattern matches the ID
20
+ * and the wrong meaning in one clause, in either order, and in a row of an Opta
21
+ * qualifier table. A clause that negates the claim ("Q213 is the pass angle, not
22
+ * xG", "Do not read qualifier 213 as xG") is allowed.
23
+ */
24
+ export const WRONG_MEANINGS = [
25
+ { id: 7, meaning: "goal kick (goal kick is Q124)", pattern: /goal[- ]?kick/ },
26
+ { id: 17, meaning: "blocked x (blocked x is Q146)", pattern: /block(ed)?[ _-]?x/ },
27
+ { id: 18, meaning: "blocked y (blocked y is Q147)", pattern: /block(ed)?[ _-]?y/ },
28
+ { id: 20, meaning: "an involved-player field (Q20 is right foot)", pattern: /involved/ },
29
+ { id: 22, meaning: "other body part (other body part is Q21)", pattern: /other[ _-]?body/ },
30
+ { id: 24, meaning: "assisted shot (Q24 is set piece; assisted is Q29)", pattern: /assisted[ _-]?shot/ },
31
+ { id: 26, meaning: "low drive (Q26 is a direct free-kick shot)", pattern: /low[ _-]?drive/ },
32
+ { id: 31, meaning: "second yellow (Q31 is yellow card; second yellow is Q32)", pattern: /second[ _-]?yellow/ },
33
+ { id: 56, meaning: "right foot (Q56 is zone; right foot is Q20)", pattern: /right[ _-]?foot/ },
34
+ { id: 72, meaning: "angle (Q72 is left foot; angle is Q213)", pattern: /\bangle\b/ },
35
+ { id: 76, meaning: "big chance (Q76 is low left; big chance is Q214)", pattern: /big[ _-]?chance/ },
36
+ { id: 108, meaning: "penalty (Q108 is volley; penalty is Q9)", pattern: /penalt/ },
37
+ { id: 136, meaning: "direct free kick (Q136 is keeper touched)", pattern: /direct[ _-]?(free|fk)/ },
38
+ { id: 154, meaning: "volley (Q154 is intentional assist; volley is Q108)", pattern: /volley/ },
39
+ { id: 213, meaning: "xG (Q213 is angle; xG is Q321)", pattern: /\bxg\b|\bexpected[ _-]?goals\b/ },
40
+ { id: 214, meaning: "length or xA (Q214 is big chance)", pattern: /\blength\b|\bxa\b|\bexpected[ _-]?assist/ },
41
+ { id: 328, meaning: "strong or big chance (Q328 is first touch)", pattern: /strong|powerful|big[ _-]?chance/ },
42
+ { id: 468, meaning: "xG (Q468 is related error 1 ID)", pattern: /\bxg\b|\bexpected[ _-]?goals/ },
43
+ ];
44
+ const NEGATION = /\bnot\b|\bnever\b|n't\b|\binstead\b/;
45
+ /** A clause ends at a full stop, semicolon or table cell. */
46
+ const CLAUSE = "[^.;|\\n]{0,60}?";
47
+ function idPattern(id) {
48
+ return `(?:\\bq|\\bqualifier\\s*(?:id\\s*)?\`?)${id}\\b\`?`;
49
+ }
50
+ function lineOf(text, index) {
51
+ return text.slice(0, index).split("\n").length;
52
+ }
53
+ /** The start of the clause that ends at `index`, for a negation before the match. */
54
+ function clauseBefore(text, index) {
55
+ const before = text.slice(Math.max(0, index - 40), index);
56
+ return before.split(/[.;|\n]/).pop() ?? "";
57
+ }
58
+ function findWrongMeanings(doc) {
59
+ const text = doc.text.toLowerCase();
60
+ const violations = [];
61
+ const report = (id, meaning, index, length) => violations.push({
62
+ path: doc.path,
63
+ line: lineOf(doc.text, index),
64
+ message: `states qualifier ${id} as ${meaning}: "${doc.text.slice(index, index + length)}"`,
65
+ });
66
+ for (const { id, meaning, pattern } of WRONG_MEANINGS) {
67
+ const forward = new RegExp(`${idPattern(id)}(${CLAUSE})(?:${pattern.source})`, "g");
68
+ const backward = new RegExp(`(?:${pattern.source})(${CLAUSE})${idPattern(id)}`, "g");
69
+ for (const regex of [forward, backward]) {
70
+ for (const match of text.matchAll(regex)) {
71
+ const index = match.index ?? 0;
72
+ if (NEGATION.test(match[1] ?? "") || NEGATION.test(clauseBefore(text, index)))
73
+ continue;
74
+ report(id, meaning, index, match[0].length);
75
+ }
76
+ }
77
+ }
78
+ // Opta tables give the ID a cell of its own ("| 76 | bigChance |"). The typeId
79
+ // table is skipped: its IDs are event types, not qualifiers.
80
+ if (doc.path.includes("opta/") && !doc.path.endsWith("event-types.md")) {
81
+ let offset = 0;
82
+ for (const line of text.split("\n")) {
83
+ const row = line.match(/^\|\s*`?(\d+)`?\s*\|(.*)$/);
84
+ const entry = row && WRONG_MEANINGS.find((candidate) => String(candidate.id) === row[1]);
85
+ if (row && entry) {
86
+ const hit = row[2].match(entry.pattern);
87
+ if (hit && !NEGATION.test(row[2].slice(0, hit.index)))
88
+ report(entry.id, entry.meaning, offset, line.length);
89
+ }
90
+ offset += line.length + 1;
91
+ }
92
+ }
93
+ return violations;
94
+ }
95
+ /** Rows of every table whose header starts with the given first column name. */
96
+ function idTableRows(text, firstColumn) {
97
+ const rows = [];
98
+ let inTable = false;
99
+ text.split("\n").forEach((line, index) => {
100
+ const cells = line.trim().replace(/^\||\|$/g, "").split("|").map((cell) => cell.trim());
101
+ if (line.startsWith("|") && cells[0] === firstColumn) {
102
+ inTable = true;
103
+ return;
104
+ }
105
+ if (!line.startsWith("|")) {
106
+ inTable = false;
107
+ return;
108
+ }
109
+ if (inTable && /^\d+$/.test(cells[0]))
110
+ rows.push({ id: cells[0], name: cells[1], line: index + 1 });
111
+ });
112
+ return rows;
113
+ }
114
+ export function validateOptaDocs(docs, truth) {
115
+ const violations = [];
116
+ for (const doc of docs) {
117
+ if (doc.path.endsWith("opta/qualifiers.md")) {
118
+ for (const row of idTableRows(doc.text, "ID")) {
119
+ const expected = truth.qualifiers[row.id];
120
+ if (expected === undefined) {
121
+ violations.push({
122
+ path: doc.path,
123
+ line: row.line,
124
+ message: `qualifier ${row.id} is not in data/opta-truth.json; check it against F24 and add it`,
125
+ });
126
+ }
127
+ else if (row.name !== expected) {
128
+ violations.push({
129
+ path: doc.path,
130
+ line: row.line,
131
+ message: `qualifier ${row.id} is labelled "${row.name}"; the checked label is "${expected}"`,
132
+ });
133
+ }
134
+ }
135
+ }
136
+ if (doc.path.endsWith("opta/event-types.md")) {
137
+ for (const row of idTableRows(doc.text, "typeId")) {
138
+ const expected = truth.eventTypes[row.id];
139
+ if (expected === undefined) {
140
+ violations.push({
141
+ path: doc.path,
142
+ line: row.line,
143
+ message: `typeId ${row.id} is not in data/opta-truth.json; check it against F24 and add it`,
144
+ });
145
+ }
146
+ else if (row.name.toLowerCase() !== expected.toLowerCase()) {
147
+ violations.push({
148
+ path: doc.path,
149
+ line: row.line,
150
+ message: `typeId ${row.id} is named "${row.name}"; F24 names it "${expected}"`,
151
+ });
152
+ }
153
+ }
154
+ }
155
+ violations.push(...findWrongMeanings(doc));
156
+ }
157
+ return violations;
158
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Validation for the SportMonks ID tables.
3
+ *
4
+ * SportMonks publishes its type and state IDs on its definitions pages and in a
5
+ * types spreadsheet linked from the Types page. data/sportmonks-types-truth.json
6
+ * holds those ID, name, developer name and code values as published. The tests
7
+ * hold every ID table in docs/sportmonks to it: an ID must be published, and the
8
+ * name the doc gives it must be SportMonks' own (or an alias listed below).
9
+ */
10
+ export declare const SPORTMONKS_TRUTH_PATH: string;
11
+ type Published = {
12
+ name?: string;
13
+ developer_name?: string;
14
+ code?: string;
15
+ state?: string;
16
+ };
17
+ export interface SportMonksTruth {
18
+ source: {
19
+ pages: string;
20
+ fetched: string;
21
+ note: string;
22
+ };
23
+ types: Record<string, Published>;
24
+ states: Record<string, Published>;
25
+ }
26
+ export interface SportMonksDoc {
27
+ path: string;
28
+ text: string;
29
+ }
30
+ export interface SportMonksViolation {
31
+ path: string;
32
+ line: number;
33
+ message: string;
34
+ }
35
+ export declare function loadSportMonksTruth(): SportMonksTruth;
36
+ export declare function validateSportMonksDocs(docs: SportMonksDoc[], truth: SportMonksTruth): SportMonksViolation[];
37
+ export {};