football-docs 0.11.1 → 0.12.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 +25 -4
- package/data/docs.db +0 -0
- package/dist/index.js +23 -8
- package/dist/reep.d.ts +47 -0
- package/dist/reep.js +381 -0
- package/dist/tools.d.ts +1 -12
- package/dist/tools.js +1 -57
- package/docs/espn/api-access.md +64 -0
- package/docs/espn/identity-and-coverage.md +77 -0
- package/docs/espn/match-summary.md +106 -0
- package/docs/espn/scoreboard.md +74 -0
- package/docs/espn/teams-and-standings.md +64 -0
- package/docs/reep/api.md +92 -0
- package/docs/reep/download-duckdb-csv.md +138 -0
- package/docs/reep/identity-and-ids.md +96 -0
- package/docs/reep/overview.md +98 -0
- package/package.json +5 -2
- package/providers.json +33 -1
package/README.md
CHANGED
|
@@ -90,9 +90,9 @@ Add to `claude_desktop_config.json`:
|
|
|
90
90
|
| `list_providers` | List all indexed providers and their doc coverage. |
|
|
91
91
|
| `compare_providers` | Compare how different providers handle the same concept. |
|
|
92
92
|
| `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
|
-
| `resolve_entity` |
|
|
93
|
+
| `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
94
|
|
|
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`
|
|
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`.
|
|
96
96
|
|
|
97
97
|
## Example queries
|
|
98
98
|
|
|
@@ -128,12 +128,20 @@ Provider filters use the indexed provider keys shown by `list_providers`, but co
|
|
|
128
128
|
| socceraction | 34 | SPADL format, VAEP, Expected Threat |
|
|
129
129
|
| BeSoccer | 14 | api-access, api-endpoints |
|
|
130
130
|
| Driblab | 30 | api-access, api-endpoints, data-model |
|
|
131
|
+
| ESPN | 20 | api-access, scoreboard, match-summary, teams-and-standings, identity-and-coverage |
|
|
132
|
+
| Reep | 26 | overview, identity-and-ids, download-duckdb-csv, api |
|
|
131
133
|
| TheSportsDB | 18 | api-access, api-endpoints, livescore, identity-surfaces |
|
|
132
134
|
| FotMob | 3 | identity-surfaces |
|
|
133
135
|
| Soccerdonna | 3 | identity-surfaces |
|
|
134
136
|
| Transfermarkt | 3 | identity-surfaces |
|
|
135
137
|
|
|
136
|
-
**2,
|
|
138
|
+
**2,371 searchable chunks** across 26 providers and tools.
|
|
139
|
+
|
|
140
|
+
ESPN coverage consists of curated, dated observations of ESPN-hosted soccer
|
|
141
|
+
endpoints, checked for eng.1 and esp.1. These observations are not an official API
|
|
142
|
+
contract or an open-data licence. See [ESPN access notes](docs/espn/api-access.md)
|
|
143
|
+
for source status and [coverage notes](docs/espn/identity-and-coverage.md) for the
|
|
144
|
+
tested requests and limitations.
|
|
137
145
|
|
|
138
146
|
> **Impect** documentation is built solely from the public
|
|
139
147
|
> [ImpectAPI/open-data](https://github.com/ImpectAPI/open-data) repository — a
|
|
@@ -156,8 +164,21 @@ trusting them.
|
|
|
156
164
|
| kloppy, socceraction, soccerdata, mplsoccer, floodlight, databallpy, skillcorner, fast-forward, unravelsports | The installed package itself — enum members, importable symbols, class constants, `Literal` parameter vocabularies | `src/__tests__/provider-truth.test.ts` |
|
|
157
165
|
| Wyscout, SkillCorner, FMDB Pro, Sportradar | The vendor's own publicly published OpenAPI spec — endpoint paths and methods | `src/__tests__/provider-truth.test.ts` |
|
|
158
166
|
| BeSoccer | The vendor's published Postman collection — request vocabulary and parameters | `src/__tests__/provider-truth.test.ts` |
|
|
159
|
-
| Driblab | The vendor's published API guide — endpoint paths
|
|
167
|
+
| 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` |
|
|
160
168
|
| Impect | The public [open-data](https://github.com/ImpectAPI/open-data) repository | `src/__tests__/impect-open-data-validation.test.ts` |
|
|
169
|
+
| 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` |
|
|
170
|
+
|
|
171
|
+
ESPN has a separate observation check in `src/__tests__/espn.test.ts`. It validates
|
|
172
|
+
documented endpoint paths, field-table names and types, and source URLs against
|
|
173
|
+
`data/espn-observations.json`. These are selected structural observations, not a
|
|
174
|
+
published specification. CI reads them offline and does not contact ESPN.
|
|
175
|
+
Refresh manually with `python3 scripts/observe_espn.py --scheduled-date YYYYMMDD`,
|
|
176
|
+
choosing a future fixture date and using permitted access. The script stores no
|
|
177
|
+
raw responses. Review the diff, update the docs and dates, then rebuild the index.
|
|
178
|
+
|
|
179
|
+
Reep's snapshots age weekly, as a new release is cut each week. Run
|
|
180
|
+
`python3 scripts/check_reep_live.py` to check every download link and list what
|
|
181
|
+
has changed since the snapshots; the refresh steps are in [specs/README.md](specs/README.md#reep).
|
|
161
182
|
|
|
162
183
|
Truth files live in `data/provider-truth/` and are generated, not hand-written:
|
|
163
184
|
|
package/data/docs.db
CHANGED
|
Binary file
|
package/dist/index.js
CHANGED
|
@@ -17,6 +17,7 @@ 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 { ENTITY_TYPES } from "./reep.js";
|
|
20
21
|
import { compareProviders, getProviderDocs, listProviders, requestUpdate, resolveEntity, resolveProviderId, searchDocs, } from "./tools.js";
|
|
21
22
|
export { sanitiseFtsQuery } from "./tools.js";
|
|
22
23
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
@@ -133,18 +134,32 @@ export function createFootballDocsServer() {
|
|
|
133
134
|
.optional()
|
|
134
135
|
.describe("URLs for documentation sources (readthedocs, GitHub, llms.txt, etc.)"),
|
|
135
136
|
}, { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, async (args) => withQueueDb((db) => requestUpdate(db, args)));
|
|
136
|
-
server.tool("resolve_entity",
|
|
137
|
-
|
|
137
|
+
server.tool("resolve_entity", [
|
|
138
|
+
"Map a football entity (player, coach, referee, team, competition, season, stage or match) to its IDs at every provider",
|
|
139
|
+
"through the Reep register: Opta, Transfermarkt, Wyscout, SkillCorner, StatsBomb, FotMob, API-Football and more.",
|
|
140
|
+
"Look up by provider + id (pass namespace too, e.g. transfermarkt 'spieler', opta 'person'), by reep_id, or by name.",
|
|
141
|
+
"Sources, in order: a local copy of the free register (REEP_DUCKDB_PATH), then the Reep API (REEP_API_KEY; keys are",
|
|
142
|
+
"issued by hand on request, never self-service). With neither set, it returns setup steps and a DuckDB query.",
|
|
143
|
+
"Keeping the local file current: Reep releases weekly. Every local answer ends with the file's release stamp checked",
|
|
144
|
+
"against https://data.reep.football/releases/latest.json. If it says the file is out of date, tell the user and offer",
|
|
145
|
+
"to run the curl command it gives, which downloads https://reep.football/downloads/duckdb over the same path; the",
|
|
146
|
+
"next call uses the new file without a restart. Before bulk matching, make sure the file is current.",
|
|
147
|
+
].join(" "), {
|
|
148
|
+
provider: z
|
|
138
149
|
.string()
|
|
139
150
|
.optional()
|
|
140
|
-
.describe("
|
|
141
|
-
|
|
151
|
+
.describe("Provider key for an ID lookup, e.g. 'transfermarkt', 'opta', 'wyscout', 'skillcorner', 'fotmob'"),
|
|
152
|
+
id: z.string().optional().describe("The provider's own ID, used with provider"),
|
|
153
|
+
namespace: z
|
|
154
|
+
.string()
|
|
155
|
+
.optional()
|
|
156
|
+
.describe("The provider's namespace for that ID, e.g. 'spieler' or 'verein' for Transfermarkt, 'person' or 'team' for Opta, 'player' for Wyscout. Recommended: some providers reuse numbers across entity types."),
|
|
157
|
+
reep_id: z.string().optional().describe("A Reep ID (e.g. 'rp1b829f1d3468c4') to list every provider ID for"),
|
|
158
|
+
name: z
|
|
142
159
|
.string()
|
|
143
160
|
.optional()
|
|
144
|
-
.describe("
|
|
145
|
-
|
|
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"),
|
|
161
|
+
.describe("Name to search, at least 3 characters (e.g. 'Declan Rice'). A name match is a shortlist, not an answer."),
|
|
162
|
+
type: z.enum(ENTITY_TYPES).optional().describe("Restrict results to one entity type"),
|
|
148
163
|
}, { readOnlyHint: true, destructiveHint: false, openWorldHint: true }, async (args) => resolveEntity(args));
|
|
149
164
|
return server;
|
|
150
165
|
}
|
package/dist/reep.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* resolve_entity: map a football entity to its IDs at every provider, through
|
|
3
|
+
* the Reep register (https://reep.football).
|
|
4
|
+
*
|
|
5
|
+
* Three sources, tried in this order:
|
|
6
|
+
* 1. A local copy of the free register (REEP_DUCKDB_PATH). No key, whole
|
|
7
|
+
* register, queried on this machine. The tool checks the file's release
|
|
8
|
+
* stamp against the published latest.json and tells the agent when a
|
|
9
|
+
* newer release exists.
|
|
10
|
+
* 2. The Reep API (REEP_API_KEY). Keys are issued by hand on request; there
|
|
11
|
+
* is no self-service sign-up.
|
|
12
|
+
* 3. Neither: no network call. The answer says how to set up either source
|
|
13
|
+
* and gives the DuckDB query that answers the question from the download.
|
|
14
|
+
*/
|
|
15
|
+
export declare const REEP_CONTACT = "getintouch+nutmeg@withqwerty.com";
|
|
16
|
+
export declare const REEP_DOWNLOAD_URL = "https://reep.football/downloads/duckdb";
|
|
17
|
+
export declare const REEP_LATEST_URL = "https://data.reep.football/releases/latest.json";
|
|
18
|
+
export declare const ENTITY_TYPES: readonly ["player", "coach", "referee", "team", "competition", "season", "stage", "match"];
|
|
19
|
+
export type EntityType = (typeof ENTITY_TYPES)[number];
|
|
20
|
+
export type ResolveEntityArgs = {
|
|
21
|
+
name?: string;
|
|
22
|
+
provider?: string;
|
|
23
|
+
id?: string;
|
|
24
|
+
namespace?: string;
|
|
25
|
+
reep_id?: string;
|
|
26
|
+
type?: EntityType;
|
|
27
|
+
};
|
|
28
|
+
type ToolResponse = {
|
|
29
|
+
isError?: boolean;
|
|
30
|
+
content: Array<{
|
|
31
|
+
type: "text";
|
|
32
|
+
text: string;
|
|
33
|
+
}>;
|
|
34
|
+
};
|
|
35
|
+
type Row = Record<string, unknown>;
|
|
36
|
+
/** A read-only view of a local register file. Injectable so tests need no 700 MB file. */
|
|
37
|
+
export interface LocalRegister {
|
|
38
|
+
stamp: string | null;
|
|
39
|
+
query(sql: string, params: Record<string, string>): Promise<Row[]>;
|
|
40
|
+
}
|
|
41
|
+
export type ResolveEntityOptions = {
|
|
42
|
+
env?: Record<string, string | undefined>;
|
|
43
|
+
fetchImpl?: typeof fetch;
|
|
44
|
+
openLocal?: (path: string) => Promise<LocalRegister>;
|
|
45
|
+
};
|
|
46
|
+
export declare function resolveEntity(args: ResolveEntityArgs, options?: ResolveEntityOptions): Promise<ToolResponse>;
|
|
47
|
+
export {};
|
package/dist/reep.js
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
import { statSync } from "node:fs";
|
|
2
|
+
/**
|
|
3
|
+
* resolve_entity: map a football entity to its IDs at every provider, through
|
|
4
|
+
* the Reep register (https://reep.football).
|
|
5
|
+
*
|
|
6
|
+
* Three sources, tried in this order:
|
|
7
|
+
* 1. A local copy of the free register (REEP_DUCKDB_PATH). No key, whole
|
|
8
|
+
* register, queried on this machine. The tool checks the file's release
|
|
9
|
+
* stamp against the published latest.json and tells the agent when a
|
|
10
|
+
* newer release exists.
|
|
11
|
+
* 2. The Reep API (REEP_API_KEY). Keys are issued by hand on request; there
|
|
12
|
+
* is no self-service sign-up.
|
|
13
|
+
* 3. Neither: no network call. The answer says how to set up either source
|
|
14
|
+
* and gives the DuckDB query that answers the question from the download.
|
|
15
|
+
*/
|
|
16
|
+
export const REEP_CONTACT = "getintouch+nutmeg@withqwerty.com";
|
|
17
|
+
export const REEP_DOWNLOAD_URL = "https://reep.football/downloads/duckdb";
|
|
18
|
+
export const REEP_LATEST_URL = "https://data.reep.football/releases/latest.json";
|
|
19
|
+
const DEFAULT_API_URL = "https://reep.football/api/v1";
|
|
20
|
+
// Cloudflare refuses some default client User-Agents.
|
|
21
|
+
const USER_AGENT = "football-docs (+https://github.com/withqwerty/football-docs)";
|
|
22
|
+
const MAX_RESULTS = 10;
|
|
23
|
+
const FRESHNESS_TTL_MS = 60 * 60 * 1000;
|
|
24
|
+
export const ENTITY_TYPES = ["player", "coach", "referee", "team", "competition", "season", "stage", "match"];
|
|
25
|
+
const textResult = (text, isError = false) => ({
|
|
26
|
+
isError: isError || undefined,
|
|
27
|
+
content: [{ type: "text", text }],
|
|
28
|
+
});
|
|
29
|
+
function parseQuery(args) {
|
|
30
|
+
const provider = args.provider?.trim().toLowerCase();
|
|
31
|
+
const id = args.id?.trim();
|
|
32
|
+
if (provider && id) {
|
|
33
|
+
return { kind: "provider", provider, id, namespace: args.namespace?.trim() || undefined, type: args.type };
|
|
34
|
+
}
|
|
35
|
+
if (args.reep_id?.trim())
|
|
36
|
+
return { kind: "reep_id", reepId: args.reep_id.trim() };
|
|
37
|
+
const name = args.name?.trim();
|
|
38
|
+
if (name) {
|
|
39
|
+
if (name.length < 3)
|
|
40
|
+
return "A name search needs at least 3 characters.";
|
|
41
|
+
return { kind: "name", name, type: args.type };
|
|
42
|
+
}
|
|
43
|
+
return [
|
|
44
|
+
"Provide one of: provider + id, reep_id, or name. Examples:",
|
|
45
|
+
"- provider: 'transfermarkt', namespace: 'spieler', id: '28003'",
|
|
46
|
+
"- provider: 'wyscout', namespace: 'player', id: '379209'",
|
|
47
|
+
"- reep_id: 'rp1b829f1d3468c4'",
|
|
48
|
+
"- name: 'Declan Rice', type: 'player'",
|
|
49
|
+
].join("\n");
|
|
50
|
+
}
|
|
51
|
+
const openFiles = new Map();
|
|
52
|
+
async function openDuckdb(path) {
|
|
53
|
+
const duckdb = await import("@duckdb/node-api");
|
|
54
|
+
const instance = await duckdb.DuckDBInstance.create(path, { access_mode: "READ_ONLY" });
|
|
55
|
+
const connection = await instance.connect();
|
|
56
|
+
const query = async (sql, params) => (await connection.runAndReadAll(sql, params)).getRowObjectsJson();
|
|
57
|
+
const meta = await query("SELECT value FROM release_metadata WHERE key = 'source_stamp'", {});
|
|
58
|
+
return {
|
|
59
|
+
register: { stamp: meta.length ? String(meta[0].value) : null, query },
|
|
60
|
+
close: () => connection.closeSync(),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/** Open once per path; reopen when the file changes, so a fresh download needs no restart. */
|
|
64
|
+
async function localRegister(path, options) {
|
|
65
|
+
if (options.openLocal)
|
|
66
|
+
return options.openLocal(path);
|
|
67
|
+
const mtimeMs = statSync(path).mtimeMs;
|
|
68
|
+
const cached = openFiles.get(path);
|
|
69
|
+
if (cached && cached.mtimeMs === mtimeMs)
|
|
70
|
+
return cached.register;
|
|
71
|
+
cached?.close();
|
|
72
|
+
const opened = await openDuckdb(path);
|
|
73
|
+
openFiles.set(path, { mtimeMs, ...opened });
|
|
74
|
+
return opened.register;
|
|
75
|
+
}
|
|
76
|
+
async function localLookup(register, q) {
|
|
77
|
+
let ids = [];
|
|
78
|
+
if (q.kind === "provider") {
|
|
79
|
+
const params = { provider: q.provider, id: q.id };
|
|
80
|
+
let sql = "SELECT DISTINCT b.reep_id, b.namespace FROM bridges b JOIN entities e USING (reep_id) " +
|
|
81
|
+
"WHERE b.provider = $provider AND b.external_id = $id";
|
|
82
|
+
if (q.namespace) {
|
|
83
|
+
sql += " AND b.namespace = $namespace";
|
|
84
|
+
params.namespace = q.namespace;
|
|
85
|
+
}
|
|
86
|
+
if (q.type) {
|
|
87
|
+
sql += " AND e.entity_type = $type";
|
|
88
|
+
params.type = q.type;
|
|
89
|
+
}
|
|
90
|
+
ids = (await register.query(`${sql} LIMIT ${MAX_RESULTS}`, params)).map((r) => ({
|
|
91
|
+
reep_id: String(r.reep_id),
|
|
92
|
+
matched: `${q.provider} / ${String(r.namespace ?? "")}: ${q.id}`,
|
|
93
|
+
}));
|
|
94
|
+
}
|
|
95
|
+
else if (q.kind === "reep_id") {
|
|
96
|
+
// Follow merge redirects to the survivor (bounded, in case of a chain).
|
|
97
|
+
let current = q.reepId;
|
|
98
|
+
for (let hop = 0; hop < 5; hop++) {
|
|
99
|
+
const next = await register.query("SELECT to_id FROM redirects WHERE from_id = $id", { id: current });
|
|
100
|
+
if (!next.length)
|
|
101
|
+
break;
|
|
102
|
+
current = String(next[0].to_id);
|
|
103
|
+
}
|
|
104
|
+
ids = [{ reep_id: current, requested_id: current === q.reepId ? undefined : q.reepId }];
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
const pattern = `%${q.name.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
|
|
108
|
+
const params = { pattern };
|
|
109
|
+
let sql = "SELECT reep_id, bridge_count FROM entity_search WHERE search_text ILIKE $pattern ESCAPE '\\'";
|
|
110
|
+
if (q.type) {
|
|
111
|
+
sql += " AND entity_type = $type";
|
|
112
|
+
params.type = q.type;
|
|
113
|
+
}
|
|
114
|
+
ids = (await register.query(`${sql} ORDER BY bridge_count DESC LIMIT ${MAX_RESULTS}`, params)).map((r) => ({
|
|
115
|
+
reep_id: String(r.reep_id),
|
|
116
|
+
bridge_count: Number(r.bridge_count),
|
|
117
|
+
}));
|
|
118
|
+
}
|
|
119
|
+
const found = [];
|
|
120
|
+
for (const hit of ids) {
|
|
121
|
+
const entity = await register.query("SELECT reep_id, label, entity_type FROM entities WHERE reep_id = $id", {
|
|
122
|
+
id: hit.reep_id,
|
|
123
|
+
});
|
|
124
|
+
if (!entity.length)
|
|
125
|
+
continue;
|
|
126
|
+
const bridges = await register.query("SELECT provider, namespace, external_id FROM bridges WHERE reep_id = $id ORDER BY provider, namespace, external_id", { id: hit.reep_id });
|
|
127
|
+
found.push({
|
|
128
|
+
reep_id: hit.reep_id,
|
|
129
|
+
label: String(entity[0].label),
|
|
130
|
+
entity_type: String(entity[0].entity_type),
|
|
131
|
+
requested_id: hit.requested_id,
|
|
132
|
+
matched: hit.matched,
|
|
133
|
+
bridges: bridges.map((b) => ({
|
|
134
|
+
provider: String(b.provider),
|
|
135
|
+
namespace: String(b.namespace ?? ""),
|
|
136
|
+
external_id: String(b.external_id),
|
|
137
|
+
})),
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return found;
|
|
141
|
+
}
|
|
142
|
+
// Keyed by the fetch implementation, so an injected fetch never sees another's cache.
|
|
143
|
+
const latestCache = new WeakMap();
|
|
144
|
+
/** The current published stamp, from the public latest.json (no key). Cached for an hour. */
|
|
145
|
+
async function latestStamp(fetchImpl) {
|
|
146
|
+
const cached = latestCache.get(fetchImpl);
|
|
147
|
+
if (cached && Date.now() - cached.at < FRESHNESS_TTL_MS)
|
|
148
|
+
return cached.stamp;
|
|
149
|
+
const response = await fetchImpl(REEP_LATEST_URL, {
|
|
150
|
+
headers: { "User-Agent": USER_AGENT },
|
|
151
|
+
signal: AbortSignal.timeout(5000),
|
|
152
|
+
});
|
|
153
|
+
if (!response.ok)
|
|
154
|
+
throw new Error(`HTTP ${response.status}`);
|
|
155
|
+
const stamp = String((await response.json()).stamp ?? "");
|
|
156
|
+
if (!stamp)
|
|
157
|
+
throw new Error("latest.json has no stamp");
|
|
158
|
+
latestCache.set(fetchImpl, { at: Date.now(), stamp });
|
|
159
|
+
return stamp;
|
|
160
|
+
}
|
|
161
|
+
/** Instructions for the agent about the local file's age. */
|
|
162
|
+
async function freshnessNote(path, local, fetchImpl) {
|
|
163
|
+
const update = [
|
|
164
|
+
"To update it, download the file again to the same path:",
|
|
165
|
+
` curl -L -o "${path}" ${REEP_DOWNLOAD_URL}`,
|
|
166
|
+
"The file is several hundred MB. The next resolve_entity call opens the new file; no restart is needed.",
|
|
167
|
+
].join("\n");
|
|
168
|
+
let current;
|
|
169
|
+
try {
|
|
170
|
+
current = await latestStamp(fetchImpl);
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
return (`Local register release: ${local ?? "unknown"}. Could not check for a newer release ` +
|
|
174
|
+
`(${error instanceof Error ? error.message : String(error)}). The current stamp is at ${REEP_LATEST_URL}; ` +
|
|
175
|
+
`releases are weekly. If it differs from the local release:\n${update}`);
|
|
176
|
+
}
|
|
177
|
+
if (local === current)
|
|
178
|
+
return `Local register release: ${local} (current).`;
|
|
179
|
+
return (`**The local register is out of date.** Local release: ${local ?? "unknown"}; current release: ${current}. ` +
|
|
180
|
+
`Tell the user, and offer to update it before relying on these results.\n${update}`);
|
|
181
|
+
}
|
|
182
|
+
// ---------------------------------------------------------------------------
|
|
183
|
+
// Source 2: the API
|
|
184
|
+
function apiRequest(base, q) {
|
|
185
|
+
const root = base.replace(/\/+$/, "");
|
|
186
|
+
if (q.kind === "provider") {
|
|
187
|
+
const url = new URL(`${root}/resolve/${encodeURIComponent(q.provider)}/${encodeURIComponent(q.id)}`);
|
|
188
|
+
url.searchParams.set("include", "bridges");
|
|
189
|
+
if (q.namespace)
|
|
190
|
+
url.searchParams.set("namespace", q.namespace);
|
|
191
|
+
if (q.type)
|
|
192
|
+
url.searchParams.set("type", q.type);
|
|
193
|
+
return url.href;
|
|
194
|
+
}
|
|
195
|
+
if (q.kind === "reep_id") {
|
|
196
|
+
const url = new URL(`${root}/entities/${encodeURIComponent(q.reepId)}`);
|
|
197
|
+
url.searchParams.set("include", "bridges");
|
|
198
|
+
return url.href;
|
|
199
|
+
}
|
|
200
|
+
const url = new URL(`${root}/search`);
|
|
201
|
+
url.searchParams.set("q", q.name);
|
|
202
|
+
url.searchParams.set("sort", "bridges");
|
|
203
|
+
url.searchParams.set("limit", String(MAX_RESULTS));
|
|
204
|
+
if (q.type)
|
|
205
|
+
url.searchParams.set("type", q.type);
|
|
206
|
+
return url.href;
|
|
207
|
+
}
|
|
208
|
+
function fromApi(e) {
|
|
209
|
+
return {
|
|
210
|
+
reep_id: e.reep_id,
|
|
211
|
+
label: e.name_en ?? e.label ?? e.reep_id,
|
|
212
|
+
entity_type: e.entity_type,
|
|
213
|
+
requested_id: e.redirected_to ? e.requested_id : undefined,
|
|
214
|
+
bridges: e.bridges,
|
|
215
|
+
bridge_count: e.bridge_count,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
async function apiLookup(q, key, base, fetchImpl) {
|
|
219
|
+
let response;
|
|
220
|
+
try {
|
|
221
|
+
response = await fetchImpl(apiRequest(base, q), {
|
|
222
|
+
headers: { Authorization: `Bearer ${key}`, "User-Agent": USER_AGENT, Accept: "application/json" },
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
return textResult(`Could not reach the Reep API: ${error instanceof Error ? error.message : String(error)}`, true);
|
|
227
|
+
}
|
|
228
|
+
const stamp = response.headers.get("X-Reep-Release-Stamp");
|
|
229
|
+
const credits = response.headers.get("X-Reep-Credits-Remaining");
|
|
230
|
+
const footer = [stamp && `Release: ${stamp}`, credits && `Lookups remaining this month: ${credits}`]
|
|
231
|
+
.filter(Boolean)
|
|
232
|
+
.join(" · ");
|
|
233
|
+
if (response.status === 401 || response.status === 403) {
|
|
234
|
+
return textResult(`The Reep API refused the key in REEP_API_KEY (HTTP ${response.status}). It may be mistyped, revoked or expired. ` +
|
|
235
|
+
`Keys are issued by hand: email ${REEP_CONTACT}. Without a key, the free download answers the same ` +
|
|
236
|
+
`question locally: set REEP_DUCKDB_PATH to a copy of ${REEP_DOWNLOAD_URL}.`, true);
|
|
237
|
+
}
|
|
238
|
+
if (response.status === 429) {
|
|
239
|
+
return textResult("The Reep API rate limit or monthly lookup allowance is used up (HTTP 429). For bulk work, use the free " +
|
|
240
|
+
`download instead: set REEP_DUCKDB_PATH to a copy of ${REEP_DOWNLOAD_URL}. To raise the limit, email ${REEP_CONTACT}.`, true);
|
|
241
|
+
}
|
|
242
|
+
if (response.status === 404)
|
|
243
|
+
return textResult(`No Reep entity matches that query.${footer ? `\n\n${footer}` : ""}`);
|
|
244
|
+
let body;
|
|
245
|
+
try {
|
|
246
|
+
body = (await response.json());
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
return textResult(`Reep API error: HTTP ${response.status} ${response.statusText}`, true);
|
|
250
|
+
}
|
|
251
|
+
if (response.status === 409) {
|
|
252
|
+
const candidates = (body.results ?? []).map(fromApi);
|
|
253
|
+
return textResult(`That provider ID maps to ${candidates.length} Reep entities, so it is ambiguous. Pass namespace or type ` +
|
|
254
|
+
`to narrow it, or check each candidate:\n\n${formatFound(candidates)}${footer ? `\n\n${footer}` : ""}`);
|
|
255
|
+
}
|
|
256
|
+
if (!response.ok)
|
|
257
|
+
return textResult(`Reep API error: HTTP ${response.status} ${response.statusText}`, true);
|
|
258
|
+
const found = (q.kind === "reep_id" ? [body] : (body.results ?? [])).map(fromApi);
|
|
259
|
+
if (!found.length)
|
|
260
|
+
return textResult(`No Reep entity matches that query.${footer ? `\n\n${footer}` : ""}`);
|
|
261
|
+
const hint = q.kind === "name" ? "\n\nSearch results carry no provider IDs. Call again with reep_id to get every provider ID." : "";
|
|
262
|
+
return textResult(`Found ${found.length} result(s) via the Reep API:\n\n${formatFound(found)}${hint}${footer ? `\n\n${footer}` : ""}`);
|
|
263
|
+
}
|
|
264
|
+
// ---------------------------------------------------------------------------
|
|
265
|
+
// Source 3: neither configured
|
|
266
|
+
function sqlFor(q) {
|
|
267
|
+
const quote = (s) => `'${s.replace(/'/g, "''")}'`;
|
|
268
|
+
if (q.kind === "provider") {
|
|
269
|
+
return [
|
|
270
|
+
"SELECT e.reep_id, e.label, e.entity_type, o.provider, o.namespace, o.external_id",
|
|
271
|
+
"FROM bridges b",
|
|
272
|
+
"JOIN entities e USING (reep_id)",
|
|
273
|
+
"JOIN bridges o ON o.reep_id = e.reep_id",
|
|
274
|
+
`WHERE b.provider = ${quote(q.provider)}${q.namespace ? ` AND b.namespace = ${quote(q.namespace)}` : ""}`,
|
|
275
|
+
` AND b.external_id = ${quote(q.id)}`,
|
|
276
|
+
"ORDER BY o.provider, o.namespace;",
|
|
277
|
+
].join("\n");
|
|
278
|
+
}
|
|
279
|
+
if (q.kind === "reep_id") {
|
|
280
|
+
return [
|
|
281
|
+
"-- Follow a merge redirect first, then list every provider ID.",
|
|
282
|
+
"SELECT e.reep_id, e.label, e.entity_type, b.provider, b.namespace, b.external_id",
|
|
283
|
+
"FROM entities e JOIN bridges b USING (reep_id)",
|
|
284
|
+
`WHERE e.reep_id = coalesce((SELECT to_id FROM redirects WHERE from_id = ${quote(q.reepId)}), ${quote(q.reepId)})`,
|
|
285
|
+
"ORDER BY b.provider, b.namespace;",
|
|
286
|
+
].join("\n");
|
|
287
|
+
}
|
|
288
|
+
return [
|
|
289
|
+
"SELECT reep_id, label, entity_type, bridge_count",
|
|
290
|
+
"FROM entity_search",
|
|
291
|
+
`WHERE search_text ILIKE ${quote(`%${q.name}%`)}${q.type ? ` AND entity_type = ${quote(q.type)}` : ""}`,
|
|
292
|
+
"ORDER BY bridge_count DESC",
|
|
293
|
+
"LIMIT 10;",
|
|
294
|
+
].join("\n");
|
|
295
|
+
}
|
|
296
|
+
function setupGuidance(q, note) {
|
|
297
|
+
return [
|
|
298
|
+
...(note ? [note, ""] : []),
|
|
299
|
+
"Reep entity resolution is not set up in this MCP server. Two ways to enable it:",
|
|
300
|
+
"",
|
|
301
|
+
`1. Free, no key: download the whole register (${REEP_DOWNLOAD_URL}, one DuckDB file of several hundred MB)`,
|
|
302
|
+
" and set REEP_DUCKDB_PATH to its path in this server's MCP configuration. Lookups then run locally.",
|
|
303
|
+
" Reep releases weekly; this tool reports when the local file is out of date and how to refresh it.",
|
|
304
|
+
`2. The Reep API: set REEP_API_KEY. Keys are issued by hand on request, with no self-service sign-up;`,
|
|
305
|
+
` email ${REEP_CONTACT} with your organisation and what you are matching.`,
|
|
306
|
+
"",
|
|
307
|
+
"Meanwhile, this query answers the question against the downloaded file (duckdb reep-register-v1.duckdb):",
|
|
308
|
+
"",
|
|
309
|
+
"```sql",
|
|
310
|
+
sqlFor(q),
|
|
311
|
+
"```",
|
|
312
|
+
"",
|
|
313
|
+
"Guides: https://reep.football/get-started · Namespaces matter: bridges key on (provider, namespace, external_id).",
|
|
314
|
+
].join("\n");
|
|
315
|
+
}
|
|
316
|
+
// ---------------------------------------------------------------------------
|
|
317
|
+
function formatFound(found) {
|
|
318
|
+
return found
|
|
319
|
+
.map((f) => {
|
|
320
|
+
const lines = [`### ${f.label} (${f.entity_type})`, `Reep ID: ${f.reep_id}`];
|
|
321
|
+
if (f.matched)
|
|
322
|
+
lines.push(`Matched: ${f.matched}`);
|
|
323
|
+
if (f.requested_id)
|
|
324
|
+
lines.push(`Redirected: ${f.requested_id} was merged into ${f.reep_id}; store the new ID.`);
|
|
325
|
+
if (f.bridges) {
|
|
326
|
+
lines.push("Provider IDs:");
|
|
327
|
+
if (!f.bridges.length)
|
|
328
|
+
lines.push(" (none)");
|
|
329
|
+
for (const b of f.bridges) {
|
|
330
|
+
const role = b.role && b.role !== "canonical_bridge" ? ` (${b.role})` : "";
|
|
331
|
+
lines.push(` ${b.provider}${b.namespace ? ` / ${b.namespace}` : ""}: ${b.external_id}${role}`);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
else if (f.bridge_count !== undefined) {
|
|
335
|
+
lines.push(`Providers bridged: ${f.bridge_count}`);
|
|
336
|
+
}
|
|
337
|
+
return lines.join("\n");
|
|
338
|
+
})
|
|
339
|
+
.join("\n\n");
|
|
340
|
+
}
|
|
341
|
+
export async function resolveEntity(args, options = {}) {
|
|
342
|
+
const env = options.env ?? process.env;
|
|
343
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
344
|
+
const q = parseQuery(args);
|
|
345
|
+
if (typeof q === "string")
|
|
346
|
+
return textResult(q, true);
|
|
347
|
+
const path = env.REEP_DUCKDB_PATH?.trim();
|
|
348
|
+
const key = env.REEP_API_KEY?.trim();
|
|
349
|
+
let localProblem;
|
|
350
|
+
if (path) {
|
|
351
|
+
try {
|
|
352
|
+
const register = await localRegister(path, options);
|
|
353
|
+
const found = await localLookup(register, q);
|
|
354
|
+
const note = await freshnessNote(path, register.stamp, fetchImpl);
|
|
355
|
+
if (!found.length)
|
|
356
|
+
return textResult(`No Reep entity matches that query in the local register.\n\n${note}`);
|
|
357
|
+
const namespaces = new Set(found.map((f) => f.matched?.split(":")[0]));
|
|
358
|
+
const warning = q.kind === "provider" && !q.namespace && namespaces.size > 1
|
|
359
|
+
? `\n\n**No namespace was given, and this ID matches in ${namespaces.size} namespaces.** ${q.provider} reuses ` +
|
|
360
|
+
"numbers across entity types. Pass namespace to pick the one you mean."
|
|
361
|
+
: "";
|
|
362
|
+
return textResult(`Found ${found.length} result(s) in the local Reep register:\n\n${formatFound(found)}${warning}\n\n${note}`);
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
366
|
+
localProblem = /Cannot find (package|module) '@duckdb\/node-api'/.test(reason)
|
|
367
|
+
? "REEP_DUCKDB_PATH is set, but the DuckDB client that reads it is not installed. It is an optional " +
|
|
368
|
+
"dependency whose native build can fail on some systems; reinstall football-docs, or install " +
|
|
369
|
+
"@duckdb/node-api alongside it."
|
|
370
|
+
: `REEP_DUCKDB_PATH is set to "${path}", but the file could not be read (${reason}). ` +
|
|
371
|
+
`Download it with: curl -L -o "${path}" ${REEP_DOWNLOAD_URL}`;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
if (key) {
|
|
375
|
+
const result = await apiLookup(q, key, env.REEP_API_URL?.trim() || DEFAULT_API_URL, fetchImpl);
|
|
376
|
+
if (localProblem)
|
|
377
|
+
result.content[0].text = `${localProblem}\n\n${result.content[0].text}`;
|
|
378
|
+
return result;
|
|
379
|
+
}
|
|
380
|
+
return textResult(setupGuidance(q, localProblem), Boolean(localProblem));
|
|
381
|
+
}
|
package/dist/tools.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type Database from "better-sqlite3";
|
|
2
|
+
export { type ResolveEntityArgs, resolveEntity } from "./reep.js";
|
|
2
3
|
export declare const TOOL_NAMES: readonly ["search_docs", "resolve_provider_id", "get_provider_docs", "list_providers", "compare_providers", "request_update", "resolve_entity"];
|
|
3
4
|
type TextContent = {
|
|
4
5
|
type: "text";
|
|
@@ -32,13 +33,6 @@ export type RequestUpdateArgs = {
|
|
|
32
33
|
reason: string;
|
|
33
34
|
suggested_urls?: string[];
|
|
34
35
|
};
|
|
35
|
-
export type ResolveEntityArgs = {
|
|
36
|
-
name?: string;
|
|
37
|
-
provider?: string;
|
|
38
|
-
id?: string;
|
|
39
|
-
qid?: string;
|
|
40
|
-
type?: "player" | "team" | "coach";
|
|
41
|
-
};
|
|
42
36
|
/**
|
|
43
37
|
* Build a safe FTS5 MATCH query from user text.
|
|
44
38
|
*
|
|
@@ -63,8 +57,3 @@ export declare function requestUpdate(db: Database.Database, args: RequestUpdate
|
|
|
63
57
|
now?: Date;
|
|
64
58
|
requestId?: string;
|
|
65
59
|
}): ToolResponse;
|
|
66
|
-
export declare function resolveEntity(args: ResolveEntityArgs, options?: {
|
|
67
|
-
baseUrl?: string;
|
|
68
|
-
fetchImpl?: typeof fetch;
|
|
69
|
-
}): Promise<ToolResponse>;
|
|
70
|
-
export {};
|
package/dist/tools.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { dirname, resolve } from "node:path";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
|
+
export { resolveEntity } from "./reep.js";
|
|
4
5
|
export const TOOL_NAMES = [
|
|
5
6
|
"search_docs",
|
|
6
7
|
"resolve_provider_id",
|
|
@@ -480,60 +481,3 @@ export function requestUpdate(db, args, options = {}) {
|
|
|
480
481
|
? `\nSuggested URLs:\n${args.suggested_urls.map((url) => ` - ${url}`).join("\n")}`
|
|
481
482
|
: ""}\n\nThis local request will be reviewed by maintainers. For community visibility, also open the matching GitHub issue: ${requestIssueUrl(args)}`);
|
|
482
483
|
}
|
|
483
|
-
export async function resolveEntity(args, options = {}) {
|
|
484
|
-
const baseUrl = options.baseUrl ?? "https://reep-api.rahulkeerthi2-95d.workers.dev";
|
|
485
|
-
const fetchImpl = options.fetchImpl ?? fetch;
|
|
486
|
-
let url;
|
|
487
|
-
if (args.qid) {
|
|
488
|
-
url = `${baseUrl}/lookup?qid=${encodeURIComponent(args.qid)}`;
|
|
489
|
-
}
|
|
490
|
-
else if (args.provider && args.id) {
|
|
491
|
-
url = `${baseUrl}/resolve?provider=${encodeURIComponent(args.provider)}&id=${encodeURIComponent(args.id)}`;
|
|
492
|
-
}
|
|
493
|
-
else if (args.name) {
|
|
494
|
-
url = `${baseUrl}/search?name=${encodeURIComponent(args.name)}&limit=10`;
|
|
495
|
-
if (args.type)
|
|
496
|
-
url += `&type=${encodeURIComponent(args.type)}`;
|
|
497
|
-
}
|
|
498
|
-
else {
|
|
499
|
-
return textResult("Provide at least one of: name, qid, or provider+id. Examples:\n- name: 'Cole Palmer'\n- provider: 'transfermarkt', id: '568177'\n- qid: 'Q99760796'", true);
|
|
500
|
-
}
|
|
501
|
-
try {
|
|
502
|
-
const response = await fetchImpl(url);
|
|
503
|
-
if (!response.ok) {
|
|
504
|
-
if (response.status === 401 || response.status === 403) {
|
|
505
|
-
return textResult(`Reep API authentication failed (${response.status} ${response.statusText}). Entity resolution is optional and needs a Reep API credential/configured endpoint before provider ID lookup can work. Docs search tools still work without Reep access.`, true);
|
|
506
|
-
}
|
|
507
|
-
return textResult(`Reep API error: ${response.status} ${response.statusText}`, true);
|
|
508
|
-
}
|
|
509
|
-
const data = (await response.json());
|
|
510
|
-
if (!data.results?.length) {
|
|
511
|
-
return textResult("No entities found matching the query.");
|
|
512
|
-
}
|
|
513
|
-
const formatted = data.results
|
|
514
|
-
.map((entity) => {
|
|
515
|
-
const ids = entity.external_ids;
|
|
516
|
-
const idLines = ids
|
|
517
|
-
? Object.entries(ids)
|
|
518
|
-
.map(([provider, id]) => ` ${provider}: ${id}`)
|
|
519
|
-
.join("\n")
|
|
520
|
-
: " (none)";
|
|
521
|
-
const bio = [
|
|
522
|
-
entity.date_of_birth && `DOB: ${entity.date_of_birth}`,
|
|
523
|
-
entity.nationality && `Nationality: ${entity.nationality}`,
|
|
524
|
-
entity.position && `Position: ${entity.position}`,
|
|
525
|
-
entity.height_cm && `Height: ${entity.height_cm}cm`,
|
|
526
|
-
entity.country && `Country: ${entity.country}`,
|
|
527
|
-
entity.stadium && `Stadium: ${entity.stadium}`,
|
|
528
|
-
]
|
|
529
|
-
.filter(Boolean)
|
|
530
|
-
.join(" | ");
|
|
531
|
-
return `### ${entity.name_en} (${entity.type})\nWikidata: ${entity.qid}${entity.aliases_en ? `\nAliases: ${entity.aliases_en}` : ""}${bio ? `\n${bio}` : ""}\nProvider IDs:\n${idLines}`;
|
|
532
|
-
})
|
|
533
|
-
.join("\n\n");
|
|
534
|
-
return textResult(`Found ${data.results.length} result(s):\n\n${formatted}`);
|
|
535
|
-
}
|
|
536
|
-
catch (error) {
|
|
537
|
-
return textResult(`Failed to reach Reep API: ${error instanceof Error ? error.message : String(error)}`, true);
|
|
538
|
-
}
|
|
539
|
-
}
|