football-docs 0.4.0 → 0.7.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.
Files changed (193) hide show
  1. package/README.md +53 -53
  2. package/bin/serve.js +6 -1
  3. package/data/docs.db +0 -0
  4. package/dist/crawl.js +59 -1
  5. package/dist/impect-truth.d.ts +61 -0
  6. package/dist/impect-truth.js +250 -0
  7. package/dist/index.d.ts +11 -6
  8. package/dist/index.js +104 -304
  9. package/dist/ingest.js +5 -2
  10. package/dist/tools.d.ts +63 -0
  11. package/dist/tools.js +526 -0
  12. package/docs/_reference/skillcorner-crunch-help/getting-started-api-access-dynamic-events.md +134 -0
  13. package/docs/_reference/skillcorner-crunch-help/getting-started-api-access-our-tracking-data.md +160 -0
  14. package/docs/_reference/skillcorner-crunch-help/getting-started-best-practice-analysis-guidance.md +16 -0
  15. package/docs/_reference/skillcorner-crunch-help/getting-started-dynamic-events-check.md +33 -0
  16. package/docs/_reference/skillcorner-crunch-help/getting-started-explore-game-intelligence-data-1.md +37 -0
  17. package/docs/_reference/skillcorner-crunch-help/getting-started-explore-game-intelligence-data.md +29 -0
  18. package/docs/_reference/skillcorner-crunch-help/getting-started-first-requests.md +99 -0
  19. package/docs/_reference/skillcorner-crunch-help/getting-started-generate-visual-reports.md +90 -0
  20. package/docs/_reference/skillcorner-crunch-help/getting-started-make-your-first-queries.md +92 -0
  21. package/docs/_reference/skillcorner-crunch-help/getting-started-off-ball-run-sportscode-xml.md +32 -0
  22. package/docs/_reference/skillcorner-crunch-help/getting-started-on-ball-engagement-video-definitio.md +15 -0
  23. package/docs/_reference/skillcorner-crunch-help/getting-started-python-retrieve-dynamic-events-fil.md +102 -0
  24. package/docs/_reference/skillcorner-crunch-help/getting-started-python-retrieve-game-intelligence-.md +158 -0
  25. package/docs/_reference/skillcorner-crunch-help/getting-started-python-sync-your-database-with-ski.md +192 -0
  26. package/docs/_reference/skillcorner-crunch-help/getting-started-run-detection-and-classification.md +131 -0
  27. package/docs/_reference/skillcorner-crunch-help/getting-started-skill-corner-tracking-data.md +82 -0
  28. package/docs/_reference/skillcorner-crunch-help/getting-started-skillcorner-python-client.md +70 -0
  29. package/docs/_reference/skillcorner-crunch-help/getting-started-using-skillcorner-api.md +146 -0
  30. package/docs/_reference/skillcorner-crunch-help/getting-started.md +43 -0
  31. package/docs/_reference/skillcorner-crunch-help/glossaries-coordinates-distance-speeds-and-directi.md +149 -0
  32. package/docs/_reference/skillcorner-crunch-help/glossaries-dynamic-events-csv-specifications.md +15 -0
  33. package/docs/_reference/skillcorner-crunch-help/glossaries-forward-momentum.md +13 -0
  34. package/docs/_reference/skillcorner-crunch-help/glossaries-game-intelligence-v2-metrics.md +17 -0
  35. package/docs/_reference/skillcorner-crunch-help/glossaries-in-possession-package-content.md +19 -0
  36. package/docs/_reference/skillcorner-crunch-help/glossaries-line-breaking-passes.md +103 -0
  37. package/docs/_reference/skillcorner-crunch-help/glossaries-off-ball-run-dynamic-events.md +197 -0
  38. package/docs/_reference/skillcorner-crunch-help/glossaries-overcoming-pressure.md +105 -0
  39. package/docs/_reference/skillcorner-crunch-help/glossaries-passing-metrics-1.md +144 -0
  40. package/docs/_reference/skillcorner-crunch-help/glossaries-passing-moment-frame-selection.md +19 -0
  41. package/docs/_reference/skillcorner-crunch-help/glossaries-peak-sprint-velocity.md +26 -0
  42. package/docs/_reference/skillcorner-crunch-help/glossaries-phases-of-play-video-definitions.md +15 -0
  43. package/docs/_reference/skillcorner-crunch-help/glossaries-physical-data-glossary.md +127 -0
  44. package/docs/_reference/skillcorner-crunch-help/glossaries-running-off-ball-metrics-1.md +135 -0
  45. package/docs/_reference/skillcorner-crunch-help/glossaries.md +43 -0
  46. package/docs/_reference/skillcorner-crunch-help/index.md +33 -0
  47. package/docs/_reference/skillcorner-crunch-help/models-general-concepts-pass-completion-probabilit.md +15 -0
  48. package/docs/_reference/skillcorner-crunch-help/models-general-concepts-passing-option.md +30 -0
  49. package/docs/_reference/skillcorner-crunch-help/models-general-concepts-physical-load-prediction-m.md +63 -0
  50. package/docs/_reference/skillcorner-crunch-help/models-general-concepts-pressure-detection.md +46 -0
  51. package/docs/_reference/skillcorner-crunch-help/models-general-concepts-pressure-intensity.md +80 -0
  52. package/docs/_reference/skillcorner-crunch-help/models-general-concepts-threat.md +40 -0
  53. package/docs/_reference/skillcorner-crunch-help/models-general-concepts.md +37 -0
  54. package/docs/_reference/skillcorner-crunch-help/product-updates-1-changelog-2025.md +57 -0
  55. package/docs/_reference/skillcorner-crunch-help/product-updates-1-game-intelligence-v2-migration.md +64 -0
  56. package/docs/_reference/skillcorner-crunch-help/product-updates-1-product-updates.md +200 -0
  57. package/docs/_reference/skillcorner-crunch-help/product-updates-1.md +25 -0
  58. package/docs/_reference/skillcorner-crunch-help/tool-box-api-data-version.md +255 -0
  59. package/docs/_reference/skillcorner-crunch-help/tool-box-data-availability.md +55 -0
  60. package/docs/_reference/skillcorner-crunch-help/tool-box-python-event-tracking-synchronization-1.md +442 -0
  61. package/docs/_reference/skillcorner-crunch-help/tool-box-python-event-tracking-synchronization.md +276 -0
  62. package/docs/_reference/skillcorner-crunch-help/tool-box-python-off-ball-runs-radar-plots.md +69 -0
  63. package/docs/_reference/skillcorner-crunch-help/tool-box-rule-based-event-synchronisation.md +44 -0
  64. package/docs/_reference/skillcorner-crunch-help/tool-box.md +35 -0
  65. package/docs/_reference/skillcorner-crunch-help/working-with-the-data-averaging-per-match-per-even.md +179 -0
  66. package/docs/_reference/skillcorner-crunch-help/working-with-the-data-benchmarking-normalisation.md +27 -0
  67. package/docs/_reference/skillcorner-crunch-help/working-with-the-data-data-quality-standards.md +45 -0
  68. package/docs/_reference/skillcorner-crunch-help/working-with-the-data-physical-data-glossary-1-1.md +54 -0
  69. package/docs/_reference/skillcorner-crunch-help/working-with-the-data-physical-data-glossary-1.md +25 -0
  70. package/docs/_reference/skillcorner-crunch-help/working-with-the-data-pitch-modelisation.md +27 -0
  71. package/docs/_reference/skillcorner-crunch-help/working-with-the-data-playing-time-info.md +133 -0
  72. package/docs/_reference/skillcorner-crunch-help/working-with-the-data.md +43 -0
  73. package/docs/floodlight/compendium-0-compendium.md +21 -0
  74. package/docs/floodlight/compendium-1-data.md +54 -0
  75. package/docs/floodlight/compendium-2-design.md +49 -0
  76. package/docs/floodlight/compendium-3-time.md +57 -0
  77. package/docs/floodlight/compendium-4-space.md +137 -0
  78. package/docs/floodlight/compendium-5-identifier.md +63 -0
  79. package/docs/floodlight/core-code.md +85 -0
  80. package/docs/floodlight/core-core.md +39 -0
  81. package/docs/floodlight/core-definitions.md +128 -0
  82. package/docs/floodlight/core-events.md +177 -0
  83. package/docs/floodlight/core-pitch.md +87 -0
  84. package/docs/floodlight/core-property.md +107 -0
  85. package/docs/floodlight/core-teamsheet.md +86 -0
  86. package/docs/floodlight/core-xy.md +192 -0
  87. package/docs/floodlight/guides-contrib-manual.md +462 -0
  88. package/docs/floodlight/guides-getting-started.md +194 -0
  89. package/docs/floodlight/guides-tutorial-analysis.md +245 -0
  90. package/docs/floodlight/guides-tutorial-matchsheets.md +439 -0
  91. package/docs/floodlight/index.md +17 -0
  92. package/docs/floodlight/io-datasets.md +365 -0
  93. package/docs/floodlight/io-dfl.md +107 -0
  94. package/docs/floodlight/io-io.md +131 -0
  95. package/docs/floodlight/io-kinexon.md +119 -0
  96. package/docs/floodlight/io-opta.md +49 -0
  97. package/docs/floodlight/io-secondspectrum.md +121 -0
  98. package/docs/floodlight/io-skillcorner.md +40 -0
  99. package/docs/floodlight/io-sportradar.md +35 -0
  100. package/docs/floodlight/io-statsbomb.md +61 -0
  101. package/docs/floodlight/io-statsperform.md +239 -0
  102. package/docs/floodlight/io-tracab.md +78 -0
  103. package/docs/floodlight/io-utils.md +59 -0
  104. package/docs/floodlight/metrics-entropy.md +36 -0
  105. package/docs/floodlight/metrics-metrics.md +15 -0
  106. package/docs/floodlight/metrics-trajectory-clustering.md +51 -0
  107. package/docs/floodlight/metrics-zone-aggregation.md +116 -0
  108. package/docs/floodlight/models-geometry.md +411 -0
  109. package/docs/floodlight/models-kinematics.md +251 -0
  110. package/docs/floodlight/models-kinetics.md +137 -0
  111. package/docs/floodlight/models-models.md +89 -0
  112. package/docs/floodlight/models-space.md +202 -0
  113. package/docs/floodlight/transforms-filter.md +412 -0
  114. package/docs/floodlight/transforms-interpolation.md +230 -0
  115. package/docs/floodlight/transforms-permutation.md +36 -0
  116. package/docs/floodlight/transforms-spatial.md +54 -0
  117. package/docs/floodlight/transforms-temporal.md +42 -0
  118. package/docs/floodlight/transforms-transforms.md +57 -0
  119. package/docs/floodlight/utils-types.md +13 -0
  120. package/docs/floodlight/utils-utils.md +17 -0
  121. package/docs/floodlight/vis-pitches.md +111 -0
  122. package/docs/floodlight/vis-positions.md +129 -0
  123. package/docs/floodlight/vis-vis.md +19 -0
  124. package/docs/fmdb-pro/api-access.md +120 -0
  125. package/docs/fmdb-pro/api-endpoints.md +123 -0
  126. package/docs/fmdb-pro/data-model.md +124 -0
  127. package/docs/fmdb-pro/identity-surfaces.md +108 -0
  128. package/docs/fotmob/identity-surfaces.md +16 -44
  129. package/docs/free-sources/contextual-story-joins.md +110 -0
  130. package/docs/free-sources/overview.md +60 -13
  131. package/docs/free-sources/understat.md +15 -6
  132. package/docs/free-sources/xg-timelines.md +123 -0
  133. package/docs/impect/concepts.md +183 -0
  134. package/docs/impect/coordinate-system.md +136 -0
  135. package/docs/impect/data-model.md +276 -0
  136. package/docs/impect/event-types.md +226 -0
  137. package/docs/impect/identity-surfaces.md +123 -51
  138. package/docs/impect/kpi-definitions.md +154 -0
  139. package/docs/impect/overview.md +152 -0
  140. package/docs/kloppy/event-derived-metrics.md +337 -0
  141. package/docs/kloppy/tracking-rendering.md +420 -0
  142. package/docs/mplsoccer/visualizations.md +363 -6
  143. package/docs/opta/charting-game-state.md +216 -0
  144. package/docs/opta/charting-lineups.md +90 -0
  145. package/docs/opta/charting-passmaps.md +130 -0
  146. package/docs/opta/charting-set-pieces.md +106 -0
  147. package/docs/opta/charting-shot-placement.md +233 -0
  148. package/docs/opta/event-types.md +44 -0
  149. package/docs/opta/identity-surfaces.md +31 -59
  150. package/docs/opta/qualifiers.md +16 -7
  151. package/docs/skillcorner/api-access.md +68 -0
  152. package/docs/skillcorner/api-endpoints.md +79 -0
  153. package/docs/skillcorner/concepts.md +58 -0
  154. package/docs/skillcorner/coordinate-system.md +34 -0
  155. package/docs/skillcorner/data-model.md +79 -0
  156. package/docs/skillcorner/identity-surfaces.md +26 -43
  157. package/docs/skillcorner/physical-data.md +106 -0
  158. package/docs/socceraction/spadl.md +21 -0
  159. package/docs/soccerdata/data-sources.md +37 -0
  160. package/docs/soccerdonna/identity-surfaces.md +16 -45
  161. package/docs/sportmonks/charting-season-stories.md +125 -0
  162. package/docs/sportmonks/data-model.md +35 -12
  163. package/docs/sportmonks/event-types.md +1 -1
  164. package/docs/sportmonks/identity-surfaces.md +33 -56
  165. package/docs/sportradar/api-access.md +75 -0
  166. package/docs/sportradar/api-endpoints.md +92 -0
  167. package/docs/sportradar/charting-and-stories.md +57 -0
  168. package/docs/sportradar/data-model.md +84 -0
  169. package/docs/sportradar/integration-notes.md +58 -0
  170. package/docs/statsbomb/charting-lineups.md +79 -0
  171. package/docs/statsbomb/identity-surfaces.md +33 -61
  172. package/docs/statsbomb/player-mapping.md +9 -10
  173. package/docs/thesportsdb/api-access.md +68 -0
  174. package/docs/thesportsdb/api-endpoints.md +55 -0
  175. package/docs/thesportsdb/identity-surfaces.md +48 -0
  176. package/docs/thesportsdb/livescore.md +70 -0
  177. package/docs/transfermarkt/identity-surfaces.md +23 -53
  178. package/docs/transferroom/api-access.md +91 -0
  179. package/docs/transferroom/api-endpoints.md +257 -0
  180. package/docs/transferroom/charting-availability.md +74 -0
  181. package/docs/transferroom/data-model.md +143 -0
  182. package/docs/transferroom/identity-surfaces.md +132 -0
  183. package/docs/wyscout/api-access.md +86 -127
  184. package/docs/wyscout/api-endpoints.md +136 -0
  185. package/docs/wyscout/charting-analysis-metrics.md +124 -0
  186. package/docs/wyscout/coordinate-system.md +35 -107
  187. package/docs/wyscout/data-model.md +185 -231
  188. package/docs/wyscout/event-types.md +59 -180
  189. package/docs/wyscout/glossary-events.md +1956 -0
  190. package/docs/wyscout/glossary-metrics-concepts.md +812 -0
  191. package/docs/wyscout/identity-surfaces.md +21 -42
  192. package/package.json +6 -14
  193. package/providers.json +167 -62
package/dist/index.js CHANGED
@@ -3,11 +3,11 @@
3
3
  *
4
4
  * A Context7-style searchable index of football data provider documentation.
5
5
  * Exposes tools for searching docs, listing providers, comparing providers,
6
- * and requesting documentation updates.
6
+ * requesting documentation updates, and resolving football entities.
7
7
  *
8
- * Data is stored in a SQLite FTS5 index for fast offline search.
9
- * Update requests are stored in a separate writable SQLite DB in a
10
- * user-writable location (XDG_DATA_HOME or ~/.local/share).
8
+ * Data is stored in a SQLite FTS5 index for fast offline search. Update
9
+ * requests are stored in a separate writable SQLite DB in a user-writable
10
+ * location (XDG_DATA_HOME or ~/.local/share).
11
11
  */
12
12
  import { existsSync, mkdirSync, readFileSync } from "node:fs";
13
13
  import { homedir } from "node:os";
@@ -17,28 +17,27 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
17
17
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
18
18
  import Database from "better-sqlite3";
19
19
  import { z } from "zod";
20
+ import { compareProviders, getProviderDocs, listProviders, requestUpdate, resolveEntity, resolveProviderId, searchDocs, } from "./tools.js";
21
+ export { sanitiseFtsQuery } from "./tools.js";
20
22
  const __dirname = dirname(fileURLToPath(import.meta.url));
21
23
  const DB_PATH = resolve(__dirname, "..", "data", "docs.db");
22
24
  const PKG_VERSION = JSON.parse(readFileSync(resolve(__dirname, "..", "package.json"), "utf-8")).version;
23
- // Request queue DB goes in a user-writable location, not inside the npm package
24
25
  const QUEUE_DB_DIR = resolve(process.env.XDG_DATA_HOME ?? resolve(homedir(), ".local", "share"), "football-docs");
25
26
  const QUEUE_DB_PATH = resolve(QUEUE_DB_DIR, "requests.db");
26
- // ── Database ────────────────────────────────────────────────────────────
27
- function openDb() {
27
+ export function openDb() {
28
28
  if (!existsSync(DB_PATH)) {
29
29
  throw new Error(`Docs database not found at ${DB_PATH}. Run 'npm run ingest' first to build the index.`);
30
30
  }
31
31
  const db = new Database(DB_PATH, { readonly: true });
32
- // Check schema version — source_type column was added in v0.2.0
33
32
  const columns = db.pragma("table_info(docs)");
34
- const hasProvenance = columns.some((c) => c.name === "source_type");
33
+ const hasProvenance = columns.some((column) => column.name === "source_type");
35
34
  if (!hasProvenance) {
36
35
  db.close();
37
- throw new Error(`Docs database is outdated (missing provenance columns). Run 'npm run ingest' to rebuild.`);
36
+ throw new Error("Docs database is outdated (missing provenance columns). Run 'npm run ingest' to rebuild.");
38
37
  }
39
38
  return db;
40
39
  }
41
- function openQueueDb() {
40
+ export function openQueueDb() {
42
41
  mkdirSync(QUEUE_DB_DIR, { recursive: true });
43
42
  const db = new Database(QUEUE_DB_PATH);
44
43
  db.pragma("journal_mode = WAL");
@@ -55,309 +54,110 @@ function openQueueDb() {
55
54
  `);
56
55
  return db;
57
56
  }
58
- /** Sanitise a query string for FTS5 MATCH by wrapping in double quotes (phrase search). */
59
- export function sanitiseFtsQuery(query) {
60
- // FTS5 special syntax (AND, OR, NOT, NEAR, column:, *, ^) can cause errors.
61
- // Wrap the user query in double quotes to treat it as a phrase search,
62
- // escaping any embedded double quotes first.
63
- return `"${query.replace(/"/g, '""')}"`;
64
- }
65
- // ── Server ──────────────────────────────────────────────────────────────
66
- const server = new McpServer({
67
- name: "nutmeg-football-docs",
68
- version: PKG_VERSION,
69
- });
70
- // Tool: search_docs
71
- 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.", {
72
- query: z.string().describe("Search query. Examples: 'Opta goal qualifier', 'StatsBomb shot event type', 'coordinate system differences', 'xG qualifier ID', 'SportMonks fixture endpoint'"),
73
- provider: z
74
- .string()
75
- .optional()
76
- .describe("Filter to a specific provider: opta, statsbomb, wyscout, sportmonks, fbref, understat, kloppy, or leave empty for all"),
77
- max_results: z
78
- .number()
79
- .optional()
80
- .default(10)
81
- .describe("Maximum number of results to return (default 10)"),
82
- }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async ({ query, provider, max_results }) => {
83
- const db = openDb();
84
- try {
85
- const safeQuery = sanitiseFtsQuery(query);
86
- let sql = `
87
- SELECT d.provider, d.category, d.title, d.content,
88
- d.source_type, d.source_url, d.upstream_version,
89
- rank * -1 as relevance
90
- FROM docs_fts
91
- JOIN docs d ON d.id = docs_fts.rowid
92
- WHERE docs_fts MATCH ?
93
- `;
94
- const params = [safeQuery];
95
- if (provider) {
96
- sql += ` AND d.provider = ?`;
97
- params.push(provider.toLowerCase());
98
- }
99
- sql += ` ORDER BY rank LIMIT ?`;
100
- params.push(max_results);
101
- const rows = db.prepare(sql).all(...params);
102
- if (rows.length === 0) {
103
- return {
104
- content: [
105
- {
106
- type: "text",
107
- text: `No results found for "${query}"${provider ? ` in ${provider}` : ""}. Try broader terms or remove the provider filter.`,
108
- },
109
- ],
110
- };
111
- }
112
- const results = rows
113
- .map((r, i) => {
114
- const source = r.source_type === "curated"
115
- ? "**Source:** curated by football-docs contributors"
116
- : `**Source:** ${r.source_type}${r.source_url ? ` (${r.source_url})` : ""}${r.upstream_version ? ` | v${r.upstream_version}` : ""}`;
117
- return `## [${i + 1}] ${r.title}\n**Provider:** ${r.provider} | **Category:** ${r.category} | ${source}\n\n${r.content}`;
118
- })
119
- .join("\n\n---\n\n");
120
- return {
121
- content: [
122
- {
123
- type: "text",
124
- text: `Found ${rows.length} result(s) for "${query}"${provider ? ` in ${provider}` : ""}:\n\n${results}`,
125
- },
126
- ],
127
- };
128
- }
129
- finally {
130
- db.close();
131
- }
132
- });
133
- // Tool: list_providers
134
- 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 () => {
57
+ function withDocsDb(handler) {
135
58
  const db = openDb();
136
59
  try {
137
- const rows = db
138
- .prepare(`SELECT provider, category, COUNT(*) as chunks
139
- FROM docs
140
- GROUP BY provider, category
141
- ORDER BY provider, category`)
142
- .all();
143
- const byProvider = new Map();
144
- for (const r of rows) {
145
- const entry = byProvider.get(r.provider) ?? { categories: [], total: 0 };
146
- entry.categories.push(`${r.category} (${r.chunks})`);
147
- entry.total += r.chunks;
148
- byProvider.set(r.provider, entry);
149
- }
150
- const lines = [...byProvider.entries()]
151
- .map(([p, info]) => `**${p}** (${info.total} chunks): ${info.categories.join(", ")}`)
152
- .join("\n");
153
- return {
154
- content: [
155
- {
156
- type: "text",
157
- text: `Indexed providers:\n\n${lines}`,
158
- },
159
- ],
160
- };
60
+ return handler(db);
161
61
  }
162
62
  finally {
163
63
  db.close();
164
64
  }
165
- });
166
- // Tool: compare_providers
167
- 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?'", {
168
- topic: z.string().describe("The concept to compare across providers. Examples: 'shot events', 'coordinate systems', 'xG', 'pass types'"),
169
- providers: z.array(z.string()).optional().describe("Providers to compare. If omitted, compares all indexed providers."),
170
- }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async ({ topic, providers }) => {
171
- const db = openDb();
65
+ }
66
+ function withQueueDb(handler) {
67
+ const db = openQueueDb();
172
68
  try {
173
- const safeTopic = sanitiseFtsQuery(topic);
174
- let sql = `
175
- SELECT d.provider, d.category, d.title, d.content,
176
- rank * -1 as relevance
177
- FROM docs_fts
178
- JOIN docs d ON d.id = docs_fts.rowid
179
- WHERE docs_fts MATCH ?
180
- `;
181
- const params = [safeTopic];
182
- if (providers && providers.length > 0) {
183
- const placeholders = providers.map(() => "?").join(", ");
184
- sql += ` AND d.provider IN (${placeholders})`;
185
- params.push(...providers.map((p) => p.toLowerCase()));
186
- }
187
- sql += ` ORDER BY d.provider, rank LIMIT 30`;
188
- const rows = db.prepare(sql).all(...params);
189
- if (rows.length === 0) {
190
- return {
191
- content: [
192
- {
193
- type: "text",
194
- text: `No documentation found for "${topic}". Try different terms.`,
195
- },
196
- ],
197
- };
198
- }
199
- // Group by provider
200
- const grouped = new Map();
201
- for (const r of rows) {
202
- const entries = grouped.get(r.provider) ?? [];
203
- entries.push(`### ${r.title}\n${r.content}`);
204
- grouped.set(r.provider, entries);
205
- }
206
- const sections = [...grouped.entries()]
207
- .map(([p, chunks]) => `## ${p}\n\n${chunks.slice(0, 3).join("\n\n")}`)
208
- .join("\n\n---\n\n");
209
- return {
210
- content: [
211
- {
212
- type: "text",
213
- text: `Comparison for "${topic}" across ${grouped.size} provider(s):\n\n${sections}`,
214
- },
215
- ],
216
- };
69
+ return handler(db);
217
70
  }
218
71
  finally {
219
72
  db.close();
220
73
  }
221
- });
222
- // Tool: request_update
223
- 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.", {
224
- 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)"),
225
- provider: z.string().max(100).describe("Provider name (existing or proposed). Examples: 'statsbomb', 'mplsoccer', 'floodlight'"),
226
- reason: z.string().max(2000).describe("Why this update is needed. Be specific: version bump, missing event types, new API endpoints, etc."),
227
- suggested_urls: z.array(z.string().url().max(500)).max(10).optional().describe("URLs for documentation sources (readthedocs, GitHub, llms.txt, etc.)"),
228
- }, { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, async ({ type, provider, reason, suggested_urls }) => {
229
- const qdb = openQueueDb();
230
- try {
231
- // Hard cap on queue size
232
- const countRow = qdb.prepare("SELECT COUNT(*) as cnt FROM requests").get();
233
- if (countRow.cnt >= 500) {
234
- return {
235
- isError: true,
236
- content: [
237
- {
238
- type: "text",
239
- text: `Request queue is full (${countRow.cnt} entries). Please file an issue at https://github.com/withqwerty/football-docs/issues instead.`,
240
- },
241
- ],
242
- };
243
- }
244
- // Cooldown: reject if same provider was requested in last 7 days
245
- const recentRequest = qdb.prepare(`SELECT id, requested_at FROM requests
246
- WHERE lower(provider) = lower(?) AND status = 'pending'
247
- AND datetime(requested_at) > datetime('now', '-7 days')
248
- LIMIT 1`).get(provider);
249
- if (recentRequest) {
250
- return {
251
- isError: true,
252
- content: [
253
- {
254
- type: "text",
255
- text: `A pending request for "${provider}" already exists (from ${recentRequest.requested_at}). Requests have a 7-day cooldown to prevent duplicate work. Request ID: ${recentRequest.id}`,
256
- },
257
- ],
258
- };
259
- }
260
- const id = `req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
261
- qdb.prepare(`INSERT INTO requests (id, type, provider, reason, suggested_urls, requested_at, status)
262
- VALUES (?, ?, ?, ?, ?, ?, 'pending')`).run(id, type, provider.toLowerCase(), reason, suggested_urls ? JSON.stringify(suggested_urls) : null, new Date().toISOString());
263
- const typeLabel = {
264
- new_provider: "New provider request",
265
- recrawl: "Recrawl request",
266
- flag_outdated: "Outdated docs flag",
267
- suggest_source: "Source suggestion",
268
- }[type];
269
- return {
270
- content: [
271
- {
272
- type: "text",
273
- text: `${typeLabel} queued for "${provider}" (ID: ${id}).\n\nReason: ${reason}${suggested_urls?.length ? `\nSuggested URLs:\n${suggested_urls.map((u) => ` - ${u}`).join("\n")}` : ""}\n\nThis request will be reviewed by maintainers. You can also file an issue at https://github.com/withqwerty/football-docs/issues for community visibility.`,
274
- },
275
- ],
276
- };
277
- }
278
- finally {
279
- qdb.close();
280
- }
281
- });
282
- // Tool: resolve_entity
283
- const REEP_API = "https://reep-api.rahulkeerthi2-95d.workers.dev";
284
- server.tool("resolve_entity", "Resolve a football entity (player, team, or coach) to get cross-provider IDs. Use when you need to map between Transfermarkt, FBref, Sofascore, Opta, and other provider IDs, or when you need to look up a player/team/coach by name.", {
285
- name: z.string().optional().describe("Entity name to search for (e.g. 'Cole Palmer', 'Arsenal'). Fuzzy match on name and aliases."),
286
- provider: z.string().optional().describe("Source provider for ID resolution (e.g. 'transfermarkt', 'fbref', 'sofascore', 'opta', 'soccerway')"),
287
- id: z.string().optional().describe("ID from the source provider to resolve to all other IDs"),
288
- qid: z.string().optional().describe("Wikidata QID for direct lookup (e.g. 'Q99760796')"),
289
- type: z.enum(["player", "team", "coach"]).optional().describe("Filter results by entity type"),
290
- }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async ({ name, provider, id, qid, type }) => {
291
- let url;
292
- if (qid) {
293
- url = `${REEP_API}/lookup?qid=${encodeURIComponent(qid)}`;
294
- }
295
- else if (provider && id) {
296
- url = `${REEP_API}/resolve?provider=${encodeURIComponent(provider)}&id=${encodeURIComponent(id)}`;
297
- }
298
- else if (name) {
299
- url = `${REEP_API}/search?name=${encodeURIComponent(name)}&limit=10`;
300
- if (type)
301
- url += `&type=${encodeURIComponent(type)}`;
302
- }
303
- else {
304
- return {
305
- isError: true,
306
- content: [{
307
- type: "text",
308
- text: "Provide at least one of: name, qid, or provider+id. Examples:\n- name: 'Cole Palmer'\n- provider: 'transfermarkt', id: '568177'\n- qid: 'Q99760796'",
309
- }],
310
- };
311
- }
312
- try {
313
- const resp = await fetch(url);
314
- if (!resp.ok) {
315
- return {
316
- isError: true,
317
- content: [{ type: "text", text: `Reep API error: ${resp.status} ${resp.statusText}` }],
318
- };
319
- }
320
- const data = await resp.json();
321
- if (!data.results?.length) {
322
- return {
323
- content: [{ type: "text", text: "No entities found matching the query." }],
324
- };
325
- }
326
- const formatted = data.results.map((e) => {
327
- const ids = e.external_ids;
328
- const idLines = ids
329
- ? Object.entries(ids).map(([k, v]) => ` ${k}: ${v}`).join("\n")
330
- : " (none)";
331
- const bio = [
332
- e.date_of_birth && `DOB: ${e.date_of_birth}`,
333
- e.nationality && `Nationality: ${e.nationality}`,
334
- e.position && `Position: ${e.position}`,
335
- e.height_cm && `Height: ${e.height_cm}cm`,
336
- e.country && `Country: ${e.country}`,
337
- e.stadium && `Stadium: ${e.stadium}`,
338
- ].filter(Boolean).join(" | ");
339
- return `### ${e.name_en} (${e.type})\nWikidata: ${e.qid}${e.aliases_en ? `\nAliases: ${e.aliases_en}` : ""}${bio ? `\n${bio}` : ""}\nProvider IDs:\n${idLines}`;
340
- }).join("\n\n");
341
- return {
342
- content: [{
343
- type: "text",
344
- text: `Found ${data.results.length} result(s):\n\n${formatted}`,
345
- }],
346
- };
347
- }
348
- catch (err) {
349
- return {
350
- isError: true,
351
- content: [{ type: "text", text: `Failed to reach Reep API: ${err instanceof Error ? err.message : String(err)}` }],
352
- };
353
- }
354
- });
355
- // ── Start ───────────────────────────────────────────────────────────────
356
- async function main() {
74
+ }
75
+ export function createFootballDocsServer() {
76
+ const server = new McpServer({
77
+ name: "nutmeg-football-docs",
78
+ version: PKG_VERSION,
79
+ });
80
+ 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.", {
81
+ 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'"),
82
+ provider: z
83
+ .string()
84
+ .optional()
85
+ .describe("Optional provider filter. Use list_providers for indexed provider keys. Common aliases such as fbref, understat, ClubElo, football-data.co.uk, engsoccerdata, Sofascore, ESPN, FMDB, TransferRoom, Hudl Wyscout, Stats Perform, Opta F24, WhoScored, Metrica, Sportec/DFL, TRACAB, Second Spectrum, SportRadar API, Soccer Extended, TheSportsDB, and TSDB are accepted."),
86
+ max_results: z
87
+ .number()
88
+ .optional()
89
+ .default(10)
90
+ .describe("Maximum number of results to return (default 10)"),
91
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async (args) => withDocsDb((db) => searchDocs(db, args)));
92
+ 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.", {
93
+ query: z
94
+ .string()
95
+ .describe("Provider name, brand, product, or alias to resolve to a canonical provider key."),
96
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async (args) => withDocsDb((db) => resolveProviderId(db, args)));
97
+ 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.", {
98
+ provider: z
99
+ .string()
100
+ .describe("Provider key or alias. Use resolve_provider_id first when the provider name is ambiguous."),
101
+ topic: z.string().optional().describe("Optional topic to search within this provider's docs."),
102
+ category: z
103
+ .string()
104
+ .optional()
105
+ .describe("Optional indexed category to restrict results, such as api-endpoints, qualifiers, identity-surfaces, or tracking-rendering."),
106
+ max_results: z
107
+ .number()
108
+ .optional()
109
+ .default(10)
110
+ .describe("Maximum number of provider docs to return (default 10)."),
111
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async (args) => withDocsDb((db) => getProviderDocs(db, args)));
112
+ 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)));
113
+ 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?'", {
114
+ topic: z.string().describe("The concept to compare across providers. Examples: 'shot events', 'coordinate systems', 'xG', 'pass types'"),
115
+ providers: z
116
+ .array(z.string())
117
+ .optional()
118
+ .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."),
119
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, async (args) => withDocsDb((db) => compareProviders(db, args)));
120
+ 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.", {
121
+ 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)"),
122
+ provider: z
123
+ .string()
124
+ .max(100)
125
+ .describe("Provider name (existing or proposed). Examples: 'statsbomb', 'mplsoccer', 'floodlight'"),
126
+ reason: z
127
+ .string()
128
+ .max(2000)
129
+ .describe("Why this update is needed. Be specific: version bump, missing event types, new API endpoints, etc."),
130
+ suggested_urls: z
131
+ .array(z.string().url().max(500))
132
+ .max(10)
133
+ .optional()
134
+ .describe("URLs for documentation sources (readthedocs, GitHub, llms.txt, etc.)"),
135
+ }, { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, async (args) => withQueueDb((db) => requestUpdate(db, args)));
136
+ server.tool("resolve_entity", "Resolve a football entity (player, team, or coach) to get cross-provider IDs. Use when you need to map between Transfermarkt, FBref, Sofascore, Opta, and other provider IDs, or when you need to look up a player/team/coach by name.", {
137
+ name: z
138
+ .string()
139
+ .optional()
140
+ .describe("Entity name to search for (e.g. 'Cole Palmer', 'Arsenal'). Fuzzy match on name and aliases."),
141
+ provider: z
142
+ .string()
143
+ .optional()
144
+ .describe("Source provider for ID resolution (e.g. 'transfermarkt', 'fbref', 'sofascore', 'opta', 'soccerway')"),
145
+ id: z.string().optional().describe("ID from the source provider to resolve to all other IDs"),
146
+ qid: z.string().optional().describe("Wikidata QID for direct lookup (e.g. 'Q99760796')"),
147
+ type: z.enum(["player", "team", "coach"]).optional().describe("Filter results by entity type"),
148
+ }, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => resolveEntity(args));
149
+ return server;
150
+ }
151
+ export async function main() {
357
152
  const transport = new StdioServerTransport();
358
- await server.connect(transport);
153
+ await createFootballDocsServer().connect(transport);
154
+ }
155
+ const isDirectRun = process.argv[1]
156
+ ? resolve(process.argv[1]) === fileURLToPath(import.meta.url)
157
+ : false;
158
+ if (isDirectRun) {
159
+ main().catch((error) => {
160
+ console.error("Failed to start nutmeg docs server:", error);
161
+ process.exit(1);
162
+ });
359
163
  }
360
- main().catch((err) => {
361
- console.error("Failed to start nutmeg docs server:", err);
362
- process.exit(1);
363
- });
package/dist/ingest.js CHANGED
@@ -18,7 +18,7 @@
18
18
  * npm run ingest # ingest all providers
19
19
  * npm run ingest -- --provider opta # ingest one provider
20
20
  */
21
- import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
21
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
22
22
  import { basename, dirname, resolve } from "node:path";
23
23
  import { fileURLToPath } from "node:url";
24
24
  import Database from "better-sqlite3";
@@ -184,7 +184,10 @@ function main() {
184
184
  }
185
185
  const providers = readdirSync(DOCS_DIR).filter((d) => {
186
186
  const full = resolve(DOCS_DIR, d);
187
- return existsSync(full) && readdirSync(full).some((f) => f.endsWith(".md"));
187
+ // Skip non-directory entries (e.g. macOS .DS_Store) so listing can't throw ENOTDIR.
188
+ return (existsSync(full) &&
189
+ statSync(full).isDirectory() &&
190
+ readdirSync(full).some((f) => f.endsWith(".md")));
188
191
  });
189
192
  let total = 0;
190
193
  for (const provider of providers) {
@@ -0,0 +1,63 @@
1
+ import type Database from "better-sqlite3";
2
+ export declare const TOOL_NAMES: readonly ["search_docs", "resolve_provider_id", "get_provider_docs", "list_providers", "compare_providers", "request_update", "resolve_entity"];
3
+ type TextContent = {
4
+ type: "text";
5
+ text: string;
6
+ };
7
+ export type ToolResponse = {
8
+ isError?: boolean;
9
+ content: TextContent[];
10
+ };
11
+ export type SearchDocsArgs = {
12
+ query: string;
13
+ provider?: string;
14
+ max_results?: number;
15
+ };
16
+ export type ResolveProviderIdArgs = {
17
+ query: string;
18
+ };
19
+ export type GetProviderDocsArgs = {
20
+ provider: string;
21
+ topic?: string;
22
+ category?: string;
23
+ max_results?: number;
24
+ };
25
+ export type CompareProvidersArgs = {
26
+ topic: string;
27
+ providers?: string[];
28
+ };
29
+ export type RequestUpdateArgs = {
30
+ type: "new_provider" | "recrawl" | "flag_outdated" | "suggest_source";
31
+ provider: string;
32
+ reason: string;
33
+ suggested_urls?: string[];
34
+ };
35
+ export type ResolveEntityArgs = {
36
+ name?: string;
37
+ provider?: string;
38
+ id?: string;
39
+ qid?: string;
40
+ type?: "player" | "team" | "coach";
41
+ };
42
+ /**
43
+ * Build a safe FTS5 MATCH query from user text.
44
+ *
45
+ * User questions are usually natural language, not exact doc phrases. Joining
46
+ * searchable tokens with AND keeps results precise while still allowing queries
47
+ * like "Opta qualifier 76" to match docs that contain those tokens separately.
48
+ */
49
+ export declare function sanitiseFtsQuery(query: string): string;
50
+ export declare function resolveProviderId(db: Database.Database, args: ResolveProviderIdArgs): ToolResponse;
51
+ export declare function getProviderDocs(db: Database.Database, args: GetProviderDocsArgs): ToolResponse;
52
+ export declare function searchDocs(db: Database.Database, args: SearchDocsArgs): ToolResponse;
53
+ export declare function listProviders(db: Database.Database): ToolResponse;
54
+ export declare function compareProviders(db: Database.Database, args: CompareProvidersArgs): ToolResponse;
55
+ export declare function requestUpdate(db: Database.Database, args: RequestUpdateArgs, options?: {
56
+ now?: Date;
57
+ requestId?: string;
58
+ }): ToolResponse;
59
+ export declare function resolveEntity(args: ResolveEntityArgs, options?: {
60
+ baseUrl?: string;
61
+ fetchImpl?: typeof fetch;
62
+ }): Promise<ToolResponse>;
63
+ export {};