football-docs 0.16.2 → 0.17.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/README.md CHANGED
@@ -83,6 +83,14 @@ Add to `claude_desktop_config.json`:
83
83
  }
84
84
  ```
85
85
 
86
+ ### After an update
87
+
88
+ `npx` updates its cached copy of football-docs in place. A server that was
89
+ already running keeps the old version until it restarts, and its replies then
90
+ start with a note: "football-docs on disk is now vX, but this server is still
91
+ running vY". Reconnect the server to fix it (in Claude Code: `/mcp`, then
92
+ reconnect football-docs).
93
+
86
94
  ## Tools
87
95
 
88
96
  | Tool | Description |
@@ -94,6 +102,8 @@ Add to `claude_desktop_config.json`:
94
102
  | `compare_providers` | Compare how different providers handle the same concept. |
95
103
  | `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. |
96
104
  | `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). |
105
+ | `get_metric` | Read a metric card: one checked definition of a football metric with each published variant under its own ID, its formula, source and a checked quote, reference code with test values on open data, and caveats. See [Metric cards](#metric-cards). |
106
+ | `list_metrics` | List the metric cards and their variant IDs. |
97
107
  | `search_papers` | Search scholarly papers on football analytics and sport science in [OpenAlex](https://openalex.org) (title, abstract and full text), [arXiv](https://arxiv.org) and [SportRxiv](https://sportrxiv.org), and, when asked, your Zotero library. See [Papers and web sources](#papers-and-web-sources). |
98
108
  | `get_paper` | Look up one paper by DOI, arXiv ID, OpenAlex ID or Zotero item: authors, date, venue, all IDs, licence, open copies with their licences, abstract and a citation line. |
99
109
  | `get_web_source` | Read a public web page or PDF (a blog post, newsletter, club or vendor article, or an author's copy of a paper) as text, with its author, date, licence and Wayback Machine snapshots. Long pages come back by section. |
@@ -232,6 +242,41 @@ As environment variables in the server's MCP configuration:
232
242
  - Linux (needs `secret-tool`, from libsecret): `secret-tool store --label=football-docs service football-docs key OPENALEX_API_KEY`
233
243
  - Windows: use the environment variable; the tools do not read Windows Credential Manager.
234
244
 
245
+ ## Metric cards
246
+
247
+ A metric card is one checked definition of a football metric. Many metrics have
248
+ several published definitions that give different numbers: on the 2022 World
249
+ Cup final, Argentina's PPDA is 7.42 by the StatsBomb/Hudl formula and 9.77 by
250
+ Trainor's original. A card lists each definition as a variant with its own ID
251
+ (`ppda.statsbomb-hudl`), so an agent can cite exactly which one it used.
252
+
253
+ Each variant has:
254
+
255
+ - the definition, formula and zone, in words accurate to the source;
256
+ - the source, with one short quote checked by `match_quote` (or in a browser
257
+ where the page builds its text with JavaScript) and the date of the check;
258
+ - where possible, reference code (`metrics/reference/`), marked exact when it is
259
+ the source's own formula on the source's own data and approximation
260
+ otherwise, with test values on public open data (StatsBomb open data, at a
261
+ pinned commit, downloaded at test time).
262
+
263
+ Cards so far: `xg`, `npxg`, `xg_assisted` and `xa` (the two metrics called "xA"),
264
+ `ppda`, `progressive_passes`, `progressive_carries`, `xt`, `vaep`, `field_tilt`
265
+ and `pass_completion`. VAEP's values come from a trained model, so its card has
266
+ no reference code or test values; neither do variants that are a provider's
267
+ closed model (Opta's xA, for example).
268
+
269
+ Read a card with `get_metric("ppda")` or one variant with
270
+ `get_metric("ppda.statsbomb-hudl")`; `list_metrics` lists them. Cards are also in
271
+ `search_docs` under the provider `metric-cards`.
272
+
273
+ For maintainers: cards are written in `metrics/cards/<id>.toml`.
274
+ `python3 scripts/gen_metric_cards.py` builds `metrics/cards.json` (stored in the
275
+ index for `get_metric`) and `docs/metric-cards/<id>.md` (for search); CI fails if they
276
+ are out of date. `python3 -m pytest metrics/tests` checks every reference
277
+ implementation against its card's test values. Before a release, `pnpm
278
+ metrics:sources` re-checks every card quote against its live source.
279
+
235
280
  ## Example queries
236
281
 
237
282
  - "What is Opta qualifier 214?" (big chance)
@@ -259,7 +304,7 @@ As environment variables in the server's MCP configuration:
259
304
  | mplsoccer | 65 | overview, pitch-types, visualizations |
260
305
  | Impect | 79 | overview, data-model, event-types, coordinate-system, concepts, kpi-definitions, identity-surfaces, data-provenance |
261
306
  | SkillCorner | 51 | api-access, api-endpoints, data-model, physical-data, coordinate-system, concepts, identity-surfaces, data-provenance |
262
- | Free sources | 60 | overview, fbref, understat, contextual-story-joins, xg-timelines, data-provenance |
307
+ | Free sources | 69 | overview, fbref, understat, football-data-columns, contextual-story-joins, xg-timelines, data-provenance |
263
308
  | soccerdata | 40 | overview, data-sources, usage |
264
309
  | TransferRoom | 45 | api-access, api-endpoints, charting-availability, data-model, identity-surfaces, data-provenance |
265
310
  | Opta | 73 | event-types, qualifiers, coordinate-system, api-access, charting-game-state, charting-lineups, charting-passmaps, charting-set-pieces, charting-shot-placement, identity-surfaces, data-provenance |
@@ -278,8 +323,9 @@ As environment variables in the server's MCP configuration:
278
323
  | Firstbeat | 79 | api-access, api-endpoints, data-model, variables (100 scalars, 17 time series), identity-surfaces, data-provenance |
279
324
  | Hawkin Dynamics | 69 | api-access, api-endpoints, data-model, test-metrics (535 metrics across 13 test types), identity-surfaces, data-provenance |
280
325
  | VALD | 318 | api-access, api-endpoints, per-product endpoints and schemas (tenants, profiles, forcedecks, nordbord, forceframe, smartspeed, dynamo, humantrak), identity-surfaces, data-provenance |
326
+ | Metric cards | 101 | xg, npxg, xg_assisted, xa, ppda, progressive_passes, progressive_carries, xt, vaep, field_tilt, pass_completion; see [Metric cards](#metric-cards) |
281
327
 
282
- **3,396 searchable chunks** across 30 providers and tools.
328
+ **3,506 searchable chunks** across 31 providers and tools (the metric cards count as one).
283
329
 
284
330
  STATSports, Firstbeat, Hawkin Dynamics and VALD sell wearables and testing devices.
285
331
  Their APIs return a customer's own athlete data, which includes personal and health
package/data/docs.db CHANGED
Binary file
@@ -77,6 +77,8 @@ export interface MetaInput {
77
77
  dataStamp: string;
78
78
  commit: string | null;
79
79
  providersJson: string;
80
+ /** metrics/cards.json, when the build has metric cards. Servers before 0.17 ignore the key. */
81
+ metricCardsJson?: string;
80
82
  }
81
83
  /** Replace the meta table's contents. Used by ingest. */
82
84
  export declare function writeMeta(db: Database, input: MetaInput): void;
@@ -141,6 +141,8 @@ export function writeMeta(db, input) {
141
141
  if (input.commit)
142
142
  insert.run("commit", input.commit);
143
143
  insert.run("providers_json", input.providersJson);
144
+ if (input.metricCardsJson)
145
+ insert.run("metric_cards", input.metricCardsJson);
144
146
  });
145
147
  }
146
148
  /** FTS5's internal tables. Their SQL is written by SQLite, not by us. */
package/dist/index.js CHANGED
@@ -20,9 +20,11 @@ import { z } from "zod";
20
20
  import { hardenConnection } from "./data-format.js";
21
21
  import { cleanDataDir, dataModeFor, defaultDataDir, IndexChooser } from "./data-source.js";
22
22
  import { checkForUpdate } from "./data-update.js";
23
+ import { getMetric, listMetrics } from "./metrics.js";
23
24
  import { addLocalPaper, forgetPaper, getPaper, getWebSource, matchQuote, purgeCache, readPaper, SEARCH_SOURCES, searchPapers, } from "./papers/tools.js";
24
25
  import { ENTITY_TYPES } from "./reep.js";
25
26
  import { openDatabase } from "./sqlite.js";
27
+ import { InstallWatch } from "./stale-install.js";
26
28
  import { compareProviders, getProviderDocs, listProviders, requestUpdate, resolveEntity, resolveProviderId, searchDocs, } from "./tools.js";
27
29
  export { sanitiseFtsQuery } from "./tools.js";
28
30
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -33,6 +35,8 @@ const QUEUE_DB_DIR = resolve(process.env.XDG_DATA_HOME ?? resolve(homedir(), ".l
33
35
  const QUEUE_DB_PATH = resolve(QUEUE_DB_DIR, "requests.db");
34
36
  const DATA_DIR = defaultDataDir();
35
37
  const DATA_MODE = dataModeFor(process.env, PACKAGE_ROOT);
38
+ /** Notices when npx updates this install while the server is running. */
39
+ const install = new InstallWatch(resolve(PACKAGE_ROOT, "package.json"), PKG_VERSION);
36
40
  function logToStderr(message) {
37
41
  // stdout is the MCP channel; anything else written there corrupts it.
38
42
  process.stderr.write(`${message}\n`);
@@ -114,12 +118,12 @@ export function createFootballDocsServer() {
114
118
  .optional()
115
119
  .default(10)
116
120
  .describe("Maximum number of results to return (default 10)"),
117
- }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async (args) => withDocsDb((db) => searchDocs(db, args)));
121
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async (args) => install.wrap(() => withDocsDb((db) => searchDocs(db, args))));
118
122
  server.tool("resolve_provider_id", "Resolve a football data provider name or alias to the canonical football-docs provider key before searching. Use when users mention brands, vendors, products, or aliases such as Stats Perform, Opta F24, Hudl Wyscout, Second Spectrum, FMDB, Transfer Room, FBref, Sofascore, or TheSportsDB.", {
119
123
  query: z
120
124
  .string()
121
125
  .describe("Provider name, brand, product, or alias to resolve to a canonical provider key."),
122
- }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async (args) => withDocsDb((db) => resolveProviderId(db, args)));
126
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async (args) => install.wrap(() => withDocsDb((db) => resolveProviderId(db, args))));
123
127
  server.tool("get_provider_docs", "Retrieve documentation for a resolved provider, optionally filtered by topic or indexed category. Use after resolve_provider_id when you know which provider to inspect and want provenance-bearing docs.", {
124
128
  provider: z
125
129
  .string()
@@ -134,15 +138,15 @@ export function createFootballDocsServer() {
134
138
  .optional()
135
139
  .default(10)
136
140
  .describe("Maximum number of provider docs to return (default 10)."),
137
- }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async (args) => withDocsDb((db) => getProviderDocs(db, args)));
138
- server.tool("list_providers", "List all indexed football data providers, their document count, and coverage categories. Use to understand what documentation is available. Call this first to see what providers are indexed before searching.", {}, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async () => withDocsDb((db) => listProviders(db, { source: currentSelection().source })));
141
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async (args) => install.wrap(() => withDocsDb((db) => getProviderDocs(db, args))));
142
+ server.tool("list_providers", "List all indexed football data providers, their document count, and coverage categories. Use to understand what documentation is available. Call this first to see what providers are indexed before searching.", {}, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async () => install.wrap(() => withDocsDb((db) => listProviders(db, { source: currentSelection().source }))));
139
143
  server.tool("compare_providers", "Compare what two or more providers offer for a specific data type or concept. For example: 'How do Opta and StatsBomb represent shot events differently?'", {
140
144
  topic: z.string().describe("The concept to compare across providers. Examples: 'shot events', 'coordinate systems', 'xG', 'pass types'"),
141
145
  providers: z
142
146
  .array(z.string())
143
147
  .optional()
144
148
  .describe("Providers to compare. If omitted, compares all indexed providers. Use list_providers for indexed keys; common aliases such as ClubElo, football-data.co.uk, engsoccerdata, Sofascore, ESPN, StatsBomb Open Data, Opta F24, WhoScored, SkillCorner, Metrica, Sportec/DFL, TRACAB, Second Spectrum, SportRadar API, Soccer Extended, TheSportsDB, and TSDB are accepted."),
145
- }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async (args) => withDocsDb((db) => compareProviders(db, args)));
149
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async (args) => install.wrap(() => withDocsDb((db) => compareProviders(db, args))));
146
150
  server.tool("request_update", "Request that a provider's documentation be added, updated, or recrawled. Use when you notice docs are outdated, a provider is missing, or you know of a better documentation source. Requests are queued for review.", {
147
151
  type: z.enum(["new_provider", "recrawl", "flag_outdated", "suggest_source"]).describe("Type of request: new_provider (add a new tool/library), recrawl (refresh existing docs), flag_outdated (mark docs as stale), suggest_source (recommend a better doc source like llms.txt)"),
148
152
  provider: z
@@ -158,7 +162,16 @@ export function createFootballDocsServer() {
158
162
  .max(10)
159
163
  .optional()
160
164
  .describe("URLs for documentation sources (readthedocs, GitHub, llms.txt, etc.)"),
161
- }, { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, async (args) => withQueueDb((db) => requestUpdate(db, args)));
165
+ }, { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, async (args) => install.wrap(() => withQueueDb((db) => requestUpdate(db, args))));
166
+ server.tool("get_metric", [
167
+ "Read a metric card: one checked definition of a football metric (for example PPDA), with every published",
168
+ "variant under its own ID (ppda.statsbomb-hudl, ppda.trainor-2014 ...), its formula, zone, source and a checked",
169
+ "quote, reference code with test values on public open data where it exists, and caveats. Values from different",
170
+ "variants are not comparable, so cite the exact variant ID. Use list_metrics to see the cards.",
171
+ ].join(" "), {
172
+ id: z.string().describe("A card ID (ppda), a variant ID (ppda.statsbomb-hudl), or a metric name or alias (passes per defensive action)."),
173
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async (args) => install.wrap(() => withDocsDb((db) => getMetric(db, args))));
174
+ server.tool("list_metrics", "List the metric cards and their variant IDs, with which variants have reference code. Read one with get_metric.", {}, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async () => install.wrap(() => withDocsDb((db) => listMetrics(db))));
162
175
  server.tool("resolve_entity", [
163
176
  "Map a football entity (player, coach, referee, team, competition, season, stage or match) to its IDs at every provider",
164
177
  "through the Reep register: Opta, Transfermarkt, Wyscout, SkillCorner, StatsBomb, FotMob, API-Football and more.",
@@ -185,7 +198,7 @@ export function createFootballDocsServer() {
185
198
  .optional()
186
199
  .describe("Name to search, at least 3 characters (e.g. 'Declan Rice'). A name match is a shortlist, not an answer."),
187
200
  type: z.enum(ENTITY_TYPES).optional().describe("Restrict results to one entity type"),
188
- }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => resolveEntity(args));
201
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => install.wrap(() => resolveEntity(args)));
189
202
  server.tool("search_papers", [
190
203
  "Search scholarly papers on football analytics and sport science: OpenAlex (title, abstract and full text),",
191
204
  "arXiv (title, abstract, authors) and SportRxiv (title, abstract, keywords). Use it to find the paper behind a",
@@ -204,7 +217,7 @@ export function createFootballDocsServer() {
204
217
  max_results: z.number().optional().default(10).describe("Results per source, 1 to 25 (default 10)."),
205
218
  year_from: z.number().int().optional().describe("Only papers published in or after this year."),
206
219
  year_to: z.number().int().optional().describe("Only papers published in or before this year."),
207
- }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => searchPapers(args));
220
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => install.wrap(() => searchPapers(args)));
208
221
  server.tool("get_paper", [
209
222
  "Look up one paper by DOI, arXiv ID, OpenAlex ID, zotero: ID or local: ID: title, authors, date, venue, all IDs, licence, open copies",
210
223
  "with their licences, abstract and a citation line. arXiv IDs come from arXiv with the paper's licence; DOIs",
@@ -213,7 +226,7 @@ export function createFootballDocsServer() {
213
226
  id: z
214
227
  .string()
215
228
  .describe("A DOI (10.1145/3292500.3330758 or https://doi.org/...), an arXiv ID or URL (1802.07127, arxiv.org/abs/1802.07127), or an OpenAlex ID (W4288278931)."),
216
- }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => getPaper(args));
229
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => install.wrap(() => getPaper(args)));
217
230
  server.tool("get_web_source", [
218
231
  "Read a public web page (blog post, newsletter, club or vendor article) as text, with its author, date,",
219
232
  "licence and Wayback Machine snapshots. Use it for methods first published on the web, such as Karun Singh's",
@@ -228,7 +241,7 @@ export function createFootballDocsServer() {
228
241
  .min(0)
229
242
  .optional()
230
243
  .describe("For a long page, the section number from the outline of an earlier call."),
231
- }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => getWebSource(args));
244
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => install.wrap(() => getWebSource(args)));
232
245
  const paperId = z
233
246
  .string()
234
247
  .describe("A DOI, arXiv ID, OpenAlex ID, zotero:KEY from search_papers, or local:… from add_local_paper.");
@@ -242,7 +255,7 @@ export function createFootballDocsServer() {
242
255
  id: paperId,
243
256
  section: z.number().int().min(0).optional().describe("Section number from the outline of an earlier call (open copies only)."),
244
257
  query: z.string().optional().describe("Words to find: returns passages that hold all of them, with their section and page."),
245
- }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => readPaper(args));
258
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => install.wrap(() => readPaper(args)));
246
259
  server.tool("match_quote", [
247
260
  "Check that a quote appears in its source: a paper (any ID read_paper takes) or a web page URL. Reports exact,",
248
261
  "normalised (same words; case, spacing, quote marks, ligatures or hyphens differ), close (with a similarity",
@@ -251,7 +264,7 @@ export function createFootballDocsServer() {
251
264
  ].join(" "), {
252
265
  source: z.string().describe("A paper ID or an http(s) URL."),
253
266
  quote: z.string().min(10).describe("The quote to check, at least 10 characters."),
254
- }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => matchQuote(args));
267
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => install.wrap(() => matchQuote(args)));
255
268
  server.tool("add_local_paper", [
256
269
  "Add a PDF the user has (for example a paper from their library's subscription) to their football-docs library.",
257
270
  "Only PDF files are read; the text stays on this computer and is never sent anywhere. Returns a local: ID for",
@@ -259,9 +272,9 @@ export function createFootballDocsServer() {
259
272
  ].join(" "), {
260
273
  path: z.string().describe("The full path to the PDF, for example /Users/me/Downloads/paper.pdf or ~/Downloads/paper.pdf."),
261
274
  id: z.string().optional().describe("The paper's DOI or arXiv ID, to fill in its title and authors. Found in the PDF when omitted."),
262
- }, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, async (args) => addLocalPaper(args));
263
- server.tool("forget_paper", "Remove one paper's text from the user's football-docs library. The user's own file and Zotero are not touched.", { id: paperId }, { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }, async (args) => forgetPaper(args));
264
- server.tool("purge_cache", "Delete the user's whole football-docs paper library and the SportRxiv copy. Call with confirm: true only when the user asked for it.", { confirm: z.boolean().describe("Must be true to delete.") }, { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }, async (args) => purgeCache(args));
275
+ }, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, async (args) => install.wrap(() => addLocalPaper(args)));
276
+ server.tool("forget_paper", "Remove one paper's text from the user's football-docs library. The user's own file and Zotero are not touched.", { id: paperId }, { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }, async (args) => install.wrap(() => forgetPaper(args)));
277
+ server.tool("purge_cache", "Delete the user's whole football-docs paper library and the SportRxiv copy. Call with confirm: true only when the user asked for it.", { confirm: z.boolean().describe("Must be true to delete.") }, { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }, async (args) => install.wrap(() => purgeCache(args)));
265
278
  return server;
266
279
  }
267
280
  /**
package/dist/ingest.js CHANGED
@@ -29,6 +29,7 @@ const DOCS_DIR = resolve(__dirname, "..", "docs");
29
29
  const DB_DIR = resolve(__dirname, "..", "data");
30
30
  const DB_PATH = resolve(DB_DIR, "docs.db");
31
31
  const PROVIDERS_PATH = resolve(__dirname, "..", "providers.json");
32
+ const METRIC_CARDS_PATH = resolve(__dirname, "..", "metrics", "cards.json");
32
33
  /** Parse optional YAML frontmatter from a markdown file. */
33
34
  export function parseFrontmatter(raw) {
34
35
  // A Windows checkout reads docs with CRLF endings. Left in, the \r stops the
@@ -148,6 +149,7 @@ function recordMeta(db) {
148
149
  dataStamp: dataStamp(),
149
150
  commit: process.env.GITHUB_SHA || git(["rev-parse", "HEAD"]),
150
151
  providersJson: readFileSync(PROVIDERS_PATH, "utf-8"),
152
+ metricCardsJson: existsSync(METRIC_CARDS_PATH) ? readFileSync(METRIC_CARDS_PATH, "utf-8") : undefined,
151
153
  });
152
154
  }
153
155
  /** Drop everything and recreate from scratch. */
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Metric cards: one checked definition per football metric, with each
3
+ * published variant under its own ID, its source and a checked quote, and
4
+ * where possible reference code with test values on public open data.
5
+ *
6
+ * Cards are written in metrics/cards/*.toml. scripts/gen_metric_cards.py turns
7
+ * them into metrics/cards.json, which ingest stores in the index's meta table
8
+ * (key metric_cards), and into docs/metric-cards/<id>.md pages for search_docs.
9
+ * get_metric and list_metrics read the meta copy, so a card update reaches
10
+ * installed servers with the next data release.
11
+ */
12
+ import { z } from "zod";
13
+ import type { Database } from "./sqlite.js";
14
+ declare const variantSchema: z.ZodObject<{
15
+ id: z.ZodString;
16
+ name: z.ZodString;
17
+ definition: z.ZodString;
18
+ formula: z.ZodString;
19
+ zone: z.ZodString;
20
+ counts: z.ZodOptional<z.ZodString>;
21
+ notes: z.ZodOptional<z.ZodArray<z.ZodString>>;
22
+ source: z.ZodObject<{
23
+ kind: z.ZodEnum<{
24
+ web: "web";
25
+ paper: "paper";
26
+ }>;
27
+ id: z.ZodString;
28
+ title: z.ZodString;
29
+ author: z.ZodString;
30
+ date: z.ZodOptional<z.ZodString>;
31
+ quote: z.ZodString;
32
+ check: z.ZodEnum<{
33
+ exact: "exact";
34
+ normalised: "normalised";
35
+ browser: "browser";
36
+ }>;
37
+ checked: z.ZodString;
38
+ check_note: z.ZodOptional<z.ZodString>;
39
+ }, z.core.$strip>;
40
+ reference: z.ZodOptional<z.ZodObject<{
41
+ function: z.ZodString;
42
+ dataset: z.ZodString;
43
+ exact: z.ZodBoolean;
44
+ mapping: z.ZodString;
45
+ requires: z.ZodOptional<z.ZodArray<z.ZodString>>;
46
+ }, z.core.$strip>>;
47
+ fixtures: z.ZodOptional<z.ZodArray<z.ZodObject<{
48
+ match_id: z.ZodNumber;
49
+ label: z.ZodString;
50
+ team: z.ZodString;
51
+ expected: z.ZodNumber;
52
+ tolerance: z.ZodOptional<z.ZodNumber>;
53
+ }, z.core.$strip>>>;
54
+ }, z.core.$strip>;
55
+ export declare const metricCardSchema: z.ZodObject<{
56
+ id: z.ZodString;
57
+ name: z.ZodString;
58
+ aliases: z.ZodOptional<z.ZodArray<z.ZodString>>;
59
+ data: z.ZodEnum<{
60
+ event: "event";
61
+ tracking: "tracking";
62
+ }>;
63
+ unit: z.ZodString;
64
+ measures: z.ZodString;
65
+ direction: z.ZodString;
66
+ version: z.ZodNumber;
67
+ updated: z.ZodString;
68
+ summary: z.ZodString;
69
+ caveats: z.ZodArray<z.ZodString>;
70
+ related: z.ZodOptional<z.ZodArray<z.ZodString>>;
71
+ origin: z.ZodObject<{
72
+ text: z.ZodString;
73
+ source: z.ZodString;
74
+ }, z.core.$strip>;
75
+ variants: z.ZodArray<z.ZodObject<{
76
+ id: z.ZodString;
77
+ name: z.ZodString;
78
+ definition: z.ZodString;
79
+ formula: z.ZodString;
80
+ zone: z.ZodString;
81
+ counts: z.ZodOptional<z.ZodString>;
82
+ notes: z.ZodOptional<z.ZodArray<z.ZodString>>;
83
+ source: z.ZodObject<{
84
+ kind: z.ZodEnum<{
85
+ web: "web";
86
+ paper: "paper";
87
+ }>;
88
+ id: z.ZodString;
89
+ title: z.ZodString;
90
+ author: z.ZodString;
91
+ date: z.ZodOptional<z.ZodString>;
92
+ quote: z.ZodString;
93
+ check: z.ZodEnum<{
94
+ exact: "exact";
95
+ normalised: "normalised";
96
+ browser: "browser";
97
+ }>;
98
+ checked: z.ZodString;
99
+ check_note: z.ZodOptional<z.ZodString>;
100
+ }, z.core.$strip>;
101
+ reference: z.ZodOptional<z.ZodObject<{
102
+ function: z.ZodString;
103
+ dataset: z.ZodString;
104
+ exact: z.ZodBoolean;
105
+ mapping: z.ZodString;
106
+ requires: z.ZodOptional<z.ZodArray<z.ZodString>>;
107
+ }, z.core.$strip>>;
108
+ fixtures: z.ZodOptional<z.ZodArray<z.ZodObject<{
109
+ match_id: z.ZodNumber;
110
+ label: z.ZodString;
111
+ team: z.ZodString;
112
+ expected: z.ZodNumber;
113
+ tolerance: z.ZodOptional<z.ZodNumber>;
114
+ }, z.core.$strip>>>;
115
+ }, z.core.$strip>>;
116
+ }, z.core.$strip>;
117
+ export declare const metricCardsFileSchema: z.ZodObject<{
118
+ format: z.ZodLiteral<"football-docs/metric-cards/v1">;
119
+ cards: z.ZodArray<z.ZodObject<{
120
+ id: z.ZodString;
121
+ name: z.ZodString;
122
+ aliases: z.ZodOptional<z.ZodArray<z.ZodString>>;
123
+ data: z.ZodEnum<{
124
+ event: "event";
125
+ tracking: "tracking";
126
+ }>;
127
+ unit: z.ZodString;
128
+ measures: z.ZodString;
129
+ direction: z.ZodString;
130
+ version: z.ZodNumber;
131
+ updated: z.ZodString;
132
+ summary: z.ZodString;
133
+ caveats: z.ZodArray<z.ZodString>;
134
+ related: z.ZodOptional<z.ZodArray<z.ZodString>>;
135
+ origin: z.ZodObject<{
136
+ text: z.ZodString;
137
+ source: z.ZodString;
138
+ }, z.core.$strip>;
139
+ variants: z.ZodArray<z.ZodObject<{
140
+ id: z.ZodString;
141
+ name: z.ZodString;
142
+ definition: z.ZodString;
143
+ formula: z.ZodString;
144
+ zone: z.ZodString;
145
+ counts: z.ZodOptional<z.ZodString>;
146
+ notes: z.ZodOptional<z.ZodArray<z.ZodString>>;
147
+ source: z.ZodObject<{
148
+ kind: z.ZodEnum<{
149
+ web: "web";
150
+ paper: "paper";
151
+ }>;
152
+ id: z.ZodString;
153
+ title: z.ZodString;
154
+ author: z.ZodString;
155
+ date: z.ZodOptional<z.ZodString>;
156
+ quote: z.ZodString;
157
+ check: z.ZodEnum<{
158
+ exact: "exact";
159
+ normalised: "normalised";
160
+ browser: "browser";
161
+ }>;
162
+ checked: z.ZodString;
163
+ check_note: z.ZodOptional<z.ZodString>;
164
+ }, z.core.$strip>;
165
+ reference: z.ZodOptional<z.ZodObject<{
166
+ function: z.ZodString;
167
+ dataset: z.ZodString;
168
+ exact: z.ZodBoolean;
169
+ mapping: z.ZodString;
170
+ requires: z.ZodOptional<z.ZodArray<z.ZodString>>;
171
+ }, z.core.$strip>>;
172
+ fixtures: z.ZodOptional<z.ZodArray<z.ZodObject<{
173
+ match_id: z.ZodNumber;
174
+ label: z.ZodString;
175
+ team: z.ZodString;
176
+ expected: z.ZodNumber;
177
+ tolerance: z.ZodOptional<z.ZodNumber>;
178
+ }, z.core.$strip>>>;
179
+ }, z.core.$strip>>;
180
+ }, z.core.$strip>>;
181
+ }, z.core.$strip>;
182
+ export type MetricCard = z.infer<typeof metricCardSchema>;
183
+ export type MetricVariant = z.infer<typeof variantSchema>;
184
+ type ToolResponse = {
185
+ isError?: boolean;
186
+ content: Array<{
187
+ type: "text";
188
+ text: string;
189
+ }>;
190
+ };
191
+ /** The cards stored in the index, or [] for an index built before cards existed. */
192
+ export declare function readMetricCards(db: Database): MetricCard[];
193
+ export declare function findMetric(cards: MetricCard[], rawId: string): {
194
+ card: MetricCard;
195
+ variant?: MetricVariant;
196
+ } | null;
197
+ export declare function getMetric(db: Database, args: {
198
+ id: string;
199
+ }): ToolResponse;
200
+ export declare function listMetrics(db: Database): ToolResponse;
201
+ export {};
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Metric cards: one checked definition per football metric, with each
3
+ * published variant under its own ID, its source and a checked quote, and
4
+ * where possible reference code with test values on public open data.
5
+ *
6
+ * Cards are written in metrics/cards/*.toml. scripts/gen_metric_cards.py turns
7
+ * them into metrics/cards.json, which ingest stores in the index's meta table
8
+ * (key metric_cards), and into docs/metric-cards/<id>.md pages for search_docs.
9
+ * get_metric and list_metrics read the meta copy, so a card update reaches
10
+ * installed servers with the next data release.
11
+ */
12
+ import { z } from "zod";
13
+ const sourceSchema = z.object({
14
+ kind: z.enum(["web", "paper"]),
15
+ id: z.string(),
16
+ title: z.string(),
17
+ author: z.string(),
18
+ date: z.string().optional(),
19
+ quote: z.string().max(400),
20
+ check: z.enum(["exact", "normalised", "browser"]),
21
+ checked: z.string(),
22
+ check_note: z.string().optional(),
23
+ });
24
+ const fixtureSchema = z.object({
25
+ match_id: z.number().int(),
26
+ label: z.string(),
27
+ team: z.string(),
28
+ expected: z.number(),
29
+ tolerance: z.number().optional(),
30
+ });
31
+ const variantSchema = z.object({
32
+ id: z.string().regex(/^[a-z][a-z0-9_]*\.[a-z0-9][a-z0-9.-]*$/),
33
+ name: z.string(),
34
+ definition: z.string(),
35
+ formula: z.string(),
36
+ zone: z.string(),
37
+ counts: z.string().optional(),
38
+ notes: z.array(z.string()).optional(),
39
+ source: sourceSchema,
40
+ reference: z
41
+ .object({
42
+ function: z.string(),
43
+ dataset: z.string(),
44
+ exact: z.boolean(),
45
+ mapping: z.string(),
46
+ /** Pinned extra inputs from metrics/fixtures.json, such as a published xT surface. */
47
+ requires: z.array(z.string()).optional(),
48
+ })
49
+ .optional(),
50
+ fixtures: z.array(fixtureSchema).optional(),
51
+ });
52
+ export const metricCardSchema = z.object({
53
+ id: z.string().regex(/^[a-z][a-z0-9_]*$/),
54
+ name: z.string(),
55
+ aliases: z.array(z.string()).optional(),
56
+ data: z.enum(["event", "tracking"]),
57
+ unit: z.string(),
58
+ measures: z.string(),
59
+ direction: z.string(),
60
+ version: z.number().int(),
61
+ updated: z.string(),
62
+ summary: z.string(),
63
+ caveats: z.array(z.string()),
64
+ related: z.array(z.string()).optional(),
65
+ origin: z.object({ text: z.string(), source: z.string() }),
66
+ variants: z.array(variantSchema).min(1),
67
+ });
68
+ export const metricCardsFileSchema = z.object({
69
+ format: z.literal("football-docs/metric-cards/v1"),
70
+ cards: z.array(metricCardSchema),
71
+ });
72
+ const textResult = (text, isError = false) => ({ isError: isError || undefined, content: [{ type: "text", text }] });
73
+ /** The cards stored in the index, or [] for an index built before cards existed. */
74
+ export function readMetricCards(db) {
75
+ const hasMeta = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'meta'").get();
76
+ if (!hasMeta)
77
+ return [];
78
+ const row = db.prepare("SELECT value FROM meta WHERE key = 'metric_cards'").get();
79
+ if (!row)
80
+ return [];
81
+ const parsed = metricCardsFileSchema.safeParse(JSON.parse(row.value));
82
+ return parsed.success ? parsed.data.cards : [];
83
+ }
84
+ const NO_CARDS = "This docs index has no metric cards yet. They arrive with a newer docs index; the server checks for one daily.";
85
+ function clean(text) {
86
+ return text.replace(/\s+/g, " ").trim();
87
+ }
88
+ function referenceLine(variant) {
89
+ const ref = variant.reference;
90
+ if (!ref)
91
+ return "none yet";
92
+ return `${ref.exact ? "exact" : "approximation"} (${ref.function} on ${ref.dataset})`;
93
+ }
94
+ function formatVariant(variant) {
95
+ const source = variant.source;
96
+ const lines = [`## ${variant.id}: ${variant.name}`, "", clean(variant.definition), ""];
97
+ lines.push(`- **Formula:** ${clean(variant.formula)}`);
98
+ lines.push(`- **Zone:** ${clean(variant.zone)}`);
99
+ if (variant.counts)
100
+ lines.push(`- **Passes counted:** ${clean(variant.counts)}`);
101
+ lines.push(`- **Source:** ${source.title} (${[source.author, source.date].filter(Boolean).join(", ")}): ${source.id}`);
102
+ lines.push(`- **Quote** (${source.check}, checked ${source.checked}): "${source.quote}"`);
103
+ if (source.check_note)
104
+ lines.push(`- **Quote check note:** ${clean(source.check_note)}`);
105
+ lines.push(`- **Reference code:** ${referenceLine(variant)}`);
106
+ if (variant.reference)
107
+ lines.push(`- **Mapping:** ${clean(variant.reference.mapping)}`);
108
+ for (const fixture of variant.fixtures ?? []) {
109
+ lines.push(`- **Test value:** ${fixture.team}, ${fixture.label} (match ${fixture.match_id}): ${fixture.expected}`);
110
+ }
111
+ for (const note of variant.notes ?? [])
112
+ lines.push(`- ${clean(note)}`);
113
+ return lines.join("\n");
114
+ }
115
+ function formatCardHead(card) {
116
+ return [
117
+ `# ${card.name}`,
118
+ "",
119
+ `Card \`${card.id}\`, version ${card.version}, updated ${card.updated}.`,
120
+ "",
121
+ clean(card.summary),
122
+ "",
123
+ `- **Measures:** ${clean(card.measures)}`,
124
+ `- **Direction:** ${clean(card.direction)}`,
125
+ `- **Unit:** ${card.unit}`,
126
+ `- **Origin:** ${clean(card.origin.text)} (${card.origin.source})`,
127
+ "",
128
+ ];
129
+ }
130
+ export function findMetric(cards, rawId) {
131
+ const id = rawId.trim().toLowerCase();
132
+ for (const card of cards) {
133
+ if (card.id === id)
134
+ return { card };
135
+ const variant = card.variants.find((entry) => entry.id === id);
136
+ if (variant)
137
+ return { card, variant };
138
+ }
139
+ // Names and aliases ("passes per defensive action", "PPDA").
140
+ for (const card of cards) {
141
+ if (card.name.toLowerCase() === id || (card.aliases ?? []).some((alias) => alias.toLowerCase() === id))
142
+ return { card };
143
+ }
144
+ return null;
145
+ }
146
+ export function getMetric(db, args) {
147
+ const cards = readMetricCards(db);
148
+ if (!cards.length)
149
+ return textResult(NO_CARDS, true);
150
+ const found = findMetric(cards, args.id);
151
+ if (!found) {
152
+ return textResult(`No metric card or variant "${args.id}". Cards: ${cards.map((card) => card.id).join(", ")}. Use list_metrics for variants.`, true);
153
+ }
154
+ const { card, variant } = found;
155
+ const lines = formatCardHead(card);
156
+ if (variant) {
157
+ lines.push(formatVariant(variant), "", `Other variants: ${card.variants.filter((v) => v !== variant).map((v) => v.id).join(", ")}.`);
158
+ }
159
+ else {
160
+ lines.push("## Variants", "");
161
+ for (const entry of card.variants)
162
+ lines.push(`- \`${entry.id}\`: ${entry.name}. ${clean(entry.zone)} Reference code: ${referenceLine(entry)}.`);
163
+ lines.push("");
164
+ for (const entry of card.variants)
165
+ lines.push(formatVariant(entry), "");
166
+ }
167
+ lines.push("", "## Caveats", "", ...card.caveats.map((caveat) => `- ${clean(caveat)}`));
168
+ if (card.related?.length) {
169
+ const known = new Set(cards.map((entry) => entry.id));
170
+ lines.push("", `Related: ${card.related.map((id) => (known.has(id) ? id : `${id} (no card yet)`)).join(", ")}.`);
171
+ }
172
+ lines.push("", "Cite a value with the exact variant ID: values from different variants are not comparable.");
173
+ return textResult(lines.join("\n").trimEnd());
174
+ }
175
+ export function listMetrics(db) {
176
+ const cards = readMetricCards(db);
177
+ if (!cards.length)
178
+ return textResult(NO_CARDS, true);
179
+ const lines = [`# Metric cards (${cards.length})`, ""];
180
+ for (const card of cards) {
181
+ lines.push(`## ${card.id}: ${card.name}`, "", clean(card.measures), "");
182
+ for (const variant of card.variants)
183
+ lines.push(`- \`${variant.id}\`: ${variant.name} (reference code: ${referenceLine(variant)})`);
184
+ lines.push("");
185
+ }
186
+ lines.push("Read a card or one variant with get_metric(id).");
187
+ return textResult(lines.join("\n").trimEnd());
188
+ }