tff-mcp 0.1.0__py3-none-any.whl

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.
tff_mcp/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """TFF (Turkish Football Federation) MCP server package."""
tff_mcp/football.py ADDED
@@ -0,0 +1,454 @@
1
+ """Stdlib parsing for tff.org (Turkish Football Federation) pages.
2
+
3
+ Verified live 2026-11-09 against real pages (fixtures in tests/):
4
+ - League page (/default.aspx?pageID=<id>, ~330KB for Süper Lig):
5
+ standings = <table class="s-table">, header O G B M A Y AV P
6
+ (played/won/drawn/lost/goals-for/goals-against/goal-diff/points),
7
+ rows "1.GALATASARAY A.Ş." with a kulupID club link; fixtures =
8
+ <table class="fiksturListesiTable"> with "N.Hafta" header rows and
9
+ match rows (home club link, score link pageID=29&macId=..., away
10
+ club link). Unplayed matches show " - " as the score; the date
11
+ lives on the match-detail page. Weeks 1..34 (Süper Lig).
12
+ Multi-group leagues (2./3. Lig, BAL, women's, youth) expose their
13
+ groups as ?pageID=<id>&grupID=<n> links (#grp / #hmac, deduped).
14
+ - Match detail (pageID=29&macId=..., ~165KB): team names in
15
+ lnkTakim1/lnkTakim2, scores in MacDetaySayi spans, league/season
16
+ in lblOrganizasyonAdi, match code in lblKod, date/time in lblTarih
17
+ ("6.11.2026 - 20:00"), stadium as plain text between the code and
18
+ the date, officials as NAME(ROLE) pairs (Hakem, 1./2. Yardımcı
19
+ Hakem, Dördüncü Hakem, VAR, AVAR, Gözlemci, Temsilci), goals as
20
+ "NAME,3.dk (F)" entries after the "Goller" heading, starting XIs
21
+ in the grdTakim1/2_rptKadrolar repeaters (formaNo + lnkOyuncu).
22
+ - Top scorers (pageID=821/822/823/824): rptGolKralligi repeater —
23
+ lblOyuncu (player, kisiID link), lblKulup (club, kulupID link),
24
+ lblGolSayisi (goals). Süper Lig lists ~140 scorers.
25
+ - The weekly referees page (pageID=600) is NOT parsed: its Hakemler
26
+ columns are empty (&nbsp;) for the upcoming 2./3. Lig rounds —
27
+ referees are only announced close to match day — so referees are
28
+ served from the match-detail page instead (played matches carry
29
+ the full officiating team).
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import html
34
+ import re
35
+
36
+ # slug -> league page. "multi_group" leagues expose ?grupID= links.
37
+ # scorers_page_id is None where TFF publishes no Gol Krallığı page.
38
+ LEAGUES = {
39
+ "trendyol-super-lig": {
40
+ "page_id": "198", "name": "Trendyol Süper Lig",
41
+ "multi_group": False, "scorers_page_id": "821",
42
+ },
43
+ "trendyol-1-lig": {
44
+ "page_id": "142", "name": "Trendyol 1. Lig",
45
+ "multi_group": False, "scorers_page_id": "822",
46
+ },
47
+ "nesine-2-lig": {
48
+ "page_id": "976", "name": "Nesine 2. Lig",
49
+ "multi_group": True, "scorers_page_id": "823",
50
+ },
51
+ "nesine-3-lig": {
52
+ "page_id": "971", "name": "Nesine 3. Lig",
53
+ "multi_group": True, "scorers_page_id": "824",
54
+ },
55
+ "regional-amateur-league-bal": {
56
+ "page_id": "1596", "name": "Bölgesel Amatör Lig",
57
+ "multi_group": True, "scorers_page_id": None,
58
+ },
59
+ "turkcell-womens-super-lig": {
60
+ "page_id": "1000", "name": "Suwen Kadın Futbol Süper Ligi",
61
+ "multi_group": False, "scorers_page_id": None,
62
+ },
63
+ "womens-1-league": {
64
+ "page_id": "1602", "name": "TFF Kadınlar 1. Ligi",
65
+ "multi_group": True, "scorers_page_id": None,
66
+ },
67
+ "womens-2-league": {
68
+ "page_id": "1001", "name": "TFF Kadınlar 2. Ligi",
69
+ "multi_group": True, "scorers_page_id": None,
70
+ },
71
+ "womens-3-league": {
72
+ "page_id": "1298", "name": "TFF Kadınlar 3. Ligi",
73
+ "multi_group": True, "scorers_page_id": None,
74
+ },
75
+ "turk-telekom-e-super-lig": {
76
+ "page_id": "1610", "name": "Türk Telekom eSüper Lig",
77
+ "multi_group": False, "scorers_page_id": None,
78
+ },
79
+ "u19-paf-league": {
80
+ "page_id": "1750", "name": "U19 PAF Ligi",
81
+ "multi_group": True, "scorers_page_id": None,
82
+ },
83
+ "u19-development-league": {
84
+ "page_id": "1751", "name": "U19 Gelişim Ligi",
85
+ "multi_group": True, "scorers_page_id": None,
86
+ },
87
+ "u17-development-league": {
88
+ "page_id": "1752", "name": "U17 Gelişim Ligi",
89
+ "multi_group": True, "scorers_page_id": None,
90
+ },
91
+ "u16-development-league": {
92
+ "page_id": "1753", "name": "U16 Gelişim Ligi",
93
+ "multi_group": True, "scorers_page_id": None,
94
+ },
95
+ "u15-development-league": {
96
+ "page_id": "1754", "name": "U15 Gelişim Ligi",
97
+ "multi_group": True, "scorers_page_id": None,
98
+ },
99
+ "u14-development-league": {
100
+ "page_id": "1755", "name": "U14 Gelişim Ligi",
101
+ "multi_group": True, "scorers_page_id": None,
102
+ },
103
+ "u13-development-league": {
104
+ "page_id": "1762", "name": "U13 Gelişim Ligi",
105
+ "multi_group": True, "scorers_page_id": None,
106
+ },
107
+ "youth-infrastructure-development": {
108
+ "page_id": "1494", "name": "Futbol Altyapı Gelişim Ligi",
109
+ "multi_group": True, "scorers_page_id": None,
110
+ },
111
+ }
112
+
113
+ _TR_UPPER_TO_LOWER = str.maketrans({
114
+ "İ": "i", "I": "ı", "Ş": "ş", "Ğ": "ğ",
115
+ "Ü": "ü", "Ö": "ö", "Ç": "ç",
116
+ })
117
+
118
+
119
+ def tr_lower(s: str) -> str:
120
+ """Turkish-aware lowercase (str.lower() mangles İ -> i + dot)."""
121
+ return s.translate(_TR_UPPER_TO_LOWER).lower()
122
+
123
+
124
+ def _clean(text: str | None) -> str:
125
+ if not text:
126
+ return ""
127
+ text = re.sub(r"<[^>]+>", " ", text)
128
+ text = html.unescape(text)
129
+ return re.sub(r"\s+", " ", text).strip()
130
+
131
+
132
+ def _int_or_none(text: str) -> int | None:
133
+ text = _clean(text).replace(".", "").replace(",", "")
134
+ try:
135
+ return int(text)
136
+ except (ValueError, TypeError):
137
+ return None
138
+
139
+
140
+ # ---------------------------------------------------------------- groups
141
+
142
+ _GROUP_LINK_RE = re.compile(
143
+ r'<a[^>]*href="[^"]*grupID=(\d+)[^"]*"[^>]*>(.*?)</a>', re.S | re.I
144
+ )
145
+
146
+
147
+ def parse_groups(html_text: str) -> list[dict]:
148
+ """Multi-group league page -> [{id, name}] in page order.
149
+
150
+ Each group appears twice (#grp / #hmac links); dedup by id.
151
+ """
152
+ groups: list[dict] = []
153
+ seen: set[str] = set()
154
+ for m in _GROUP_LINK_RE.finditer(html_text):
155
+ gid, raw_name = m.group(1), _clean(m.group(2))
156
+ if gid in seen:
157
+ continue
158
+ seen.add(gid)
159
+ groups.append({"id": gid, "name": raw_name or f"Grup {gid}"})
160
+ return groups
161
+
162
+
163
+ def resolve_group(groups: list[dict], group: str | None) -> dict | None:
164
+ """Pick a group by index ("0"), id, or name substring (TR-aware).
165
+
166
+ Returns the group dict, or None when `group` is None (caller uses
167
+ the default = first group) — the caller decides the default.
168
+ """
169
+ if group is None:
170
+ return None
171
+ g = group.strip()
172
+ if g.isdigit():
173
+ idx = int(g)
174
+ if 0 <= idx < len(groups):
175
+ return groups[idx]
176
+ for grp in groups:
177
+ if grp["id"] == g:
178
+ return grp
179
+ raise ValueError(
180
+ f"group {g!r} not found — this league has {len(groups)} "
181
+ f"groups: {', '.join(x['name'] for x in groups)}"
182
+ )
183
+ needle = tr_lower(g)
184
+ for grp in groups:
185
+ if needle in tr_lower(grp["name"]):
186
+ return grp
187
+ raise ValueError(
188
+ f"group {g!r} not found — available groups: "
189
+ f"{', '.join(x['name'] for x in groups)}"
190
+ )
191
+
192
+
193
+ # ---------------------------------------------------------------- standings
194
+
195
+ def parse_standings(html_text: str) -> list[dict]:
196
+ """s-table -> [{rank, team, club_id, played, won, drawn, lost,
197
+ goals_for, goals_against, goal_difference, points}]."""
198
+ m = re.search(
199
+ r'<table[^>]*class="s-table"[^>]*>(.*?)</table>', html_text, re.S
200
+ )
201
+ if not m:
202
+ raise ValueError("no standings table (s-table) found on this page")
203
+ rows: list[dict] = []
204
+ for rm in re.finditer(r"<tr[^>]*>(.*?)</tr>", m.group(1), re.S):
205
+ cells = re.findall(r"<td[^>]*>(.*?)</td>", rm.group(1), re.S)
206
+ if len(cells) < 9:
207
+ continue
208
+ first = _clean(cells[0])
209
+ rank_m = re.match(r"(\d+)\.\s*(.+)", first)
210
+ if not rank_m:
211
+ continue # header row ("O G B M ...") or spacer
212
+ club_m = re.search(r"kulupID=(\d+)", cells[0], re.I)
213
+ nums = [_int_or_none(c) for c in cells[1:9]]
214
+ if any(n is None for n in nums):
215
+ continue
216
+ rows.append({
217
+ "rank": int(rank_m.group(1)),
218
+ "team": rank_m.group(2).strip(),
219
+ "club_id": club_m.group(1) if club_m else None,
220
+ "played": nums[0],
221
+ "won": nums[1],
222
+ "drawn": nums[2],
223
+ "lost": nums[3],
224
+ "goals_for": nums[4],
225
+ "goals_against": nums[5],
226
+ "goal_difference": nums[6],
227
+ "points": nums[7],
228
+ })
229
+ if not rows:
230
+ raise ValueError("standings table found but no team rows parsed")
231
+ return rows
232
+
233
+
234
+ # ---------------------------------------------------------------- fixtures
235
+
236
+ _WEEK_RE = re.compile(r"(\d+)\.Hafta")
237
+ _FIX_ANCHOR_RE = re.compile(
238
+ r'<a[^>]*href="([^"]*?pageID=(?:28|29)[^"]*)"[^>]*>([^<]*)</a>', re.I
239
+ )
240
+
241
+
242
+ def parse_fixtures(html_text: str) -> list[dict]:
243
+ """Fixture table(s) -> [{week, home, home_club_id, away,
244
+ away_club_id, score_home, score_away, status, mac_id, match_url}].
245
+
246
+ Scans from the first fiksturListesiTable; week headers ("N.Hafta")
247
+ set the week for the matches that follow. Unplayed matches show
248
+ " - " as the score (status "scheduled"); played ones "2 - 2".
249
+ """
250
+ start = html_text.find("fiksturListesiTable")
251
+ if start < 0:
252
+ raise ValueError("no fixture table (fiksturListesiTable) found")
253
+ region = html_text[start:]
254
+ # Week header positions, in order.
255
+ weeks = [(m.start(), int(m.group(1))) for m in _WEEK_RE.finditer(region)]
256
+ matches: list[dict] = []
257
+ pending: list[tuple[str, str, str]] = [] # (kind, href, text)
258
+ for m in _FIX_ANCHOR_RE.finditer(region):
259
+ href, text = m.group(1), _clean(m.group(2))
260
+ if "pageID=28" in href or "pageId=28" in href:
261
+ kind = "club"
262
+ elif "pageID=29" in href or "pageId=29" in href:
263
+ kind = "score"
264
+ else:
265
+ continue
266
+ pending.append((kind, href, text, m.start()))
267
+ if len(pending) == 3 and [p[0] for p in pending] == [
268
+ "club", "score", "club",
269
+ ]:
270
+ ( _, home_href, home, home_pos), (
271
+ _, score_href, score, _,
272
+ ), (_, away_href, away, _) = pending
273
+ mac_m = re.search(r"macId=(\d+)", score_href, re.I)
274
+ home_m = re.search(r"kulupId=(\d+)", home_href, re.I)
275
+ away_m = re.search(r"kulupId=(\d+)", away_href, re.I)
276
+ week = 0
277
+ for pos, w in weeks:
278
+ if pos <= home_pos:
279
+ week = w
280
+ else:
281
+ break
282
+ score_m = re.match(r"(\d+)\s*-\s*(\d+)", score)
283
+ if score_m:
284
+ sh, sa, status = int(score_m.group(1)), int(score_m.group(2)), "played"
285
+ else:
286
+ sh, sa, status = None, None, "scheduled"
287
+ mac_id = mac_m.group(1) if mac_m else None
288
+ matches.append({
289
+ "week": week,
290
+ "home": home,
291
+ "home_club_id": home_m.group(1) if home_m else None,
292
+ "away": away,
293
+ "away_club_id": away_m.group(1) if away_m else None,
294
+ "score_home": sh,
295
+ "score_away": sa,
296
+ "status": status,
297
+ "mac_id": mac_id,
298
+ "match_url": (
299
+ "https://www.tff.org/Default.aspx?pageID=29&macId=" + mac_id
300
+ if mac_id else None
301
+ ),
302
+ })
303
+ pending = []
304
+ elif len(pending) >= 3:
305
+ pending = pending[-2:]
306
+ if not matches:
307
+ raise ValueError("fixture table found but no matches parsed")
308
+ return matches
309
+
310
+
311
+ # ---------------------------------------------------------------- match detail
312
+
313
+ _OFFICIAL_ROLES = {
314
+ "Hakem", "1. Yardımcı Hakem", "2. Yardımcı Hakem",
315
+ "Dördüncü Hakem", "VAR", "AVAR", "Gözlemci", "Temsilci",
316
+ }
317
+
318
+ _TEAM_RE = re.compile(
319
+ r'lnkTakim([12])[^>]*href="[^"]*kulupId=(\d+)[^"]*"[^>]*>([^<]+)</a>'
320
+ )
321
+ _SCORE_RE = re.compile(
322
+ r'<p class="MacDetaySayi">\s*<span[^>]*>(\d+)</span>', re.S
323
+ )
324
+ _SPAN_RE = re.compile(r'{id}[^>]*>([^<]*)</')
325
+
326
+
327
+ def _span(html_text: str, frag: str) -> str:
328
+ # Span content may hold a <br/> (lblOrganizasyonAdi does), so
329
+ # capture up to </span> and strip tags afterwards.
330
+ m = re.search(rf'{re.escape(frag)}[^>]*>(.*?)</span>', html_text, re.S)
331
+ return _clean(m.group(1)) if m else ""
332
+
333
+
334
+ def parse_match_detail(html_text: str) -> dict:
335
+ """Match detail page -> teams, score, date/time, stadium, league,
336
+ match code, officials, goals, starting lineups."""
337
+ teams: dict[str, dict] = {}
338
+ for m in _TEAM_RE.finditer(html_text):
339
+ teams[m.group(1)] = {
340
+ "name": _clean(m.group(3)),
341
+ "club_id": m.group(2),
342
+ }
343
+ if "1" not in teams or "2" not in teams:
344
+ raise ValueError("match detail page: team names not found")
345
+ scores = [int(x) for x in _SCORE_RE.findall(html_text)[:2]]
346
+ if len(scores) != 2:
347
+ raise ValueError("match detail page: scores not found")
348
+
349
+ out: dict = {
350
+ "home": teams["1"]["name"],
351
+ "home_club_id": teams["1"]["club_id"],
352
+ "away": teams["2"]["name"],
353
+ "away_club_id": teams["2"]["club_id"],
354
+ "score_home": scores[0],
355
+ "score_away": scores[1],
356
+ "league": _span(html_text, "lblOrganizasyonAdi"),
357
+ "match_code": _span(html_text, "lblKod"),
358
+ }
359
+ date_raw = _span(html_text, "lblTarih") # "6.11.2026 - 20:00"
360
+ dm = re.match(r"(\d{1,2}\.\d{1,2}\.\d{4})\s*-\s*(\d{2}:\d{2})", date_raw)
361
+ if dm:
362
+ out["date"], out["time"] = dm.group(1), dm.group(2)
363
+
364
+ text = _clean(html_text)
365
+ # Stadium: plain text between the match code and the date.
366
+ sm = re.search(
367
+ r"Maç Kodu:\s*\d+\s+(.+?)\s+\d{1,2}\.\d{1,2}\.\d{4}\s*-\s*\d{2}:\d{2}",
368
+ text,
369
+ )
370
+ if sm:
371
+ out["stadium"] = sm.group(1).strip()
372
+
373
+ # Officials: NAME(ROLE) pairs after the date, before the lineups.
374
+ tail = text
375
+ if dm:
376
+ tail = text[text.find(dm.group(0)) + len(dm.group(0)):]
377
+ tail = tail.split("İlk 11")[0]
378
+ officials: list[dict] = []
379
+ for om in re.finditer(
380
+ r"([A-ZÇĞİÖŞÜ][A-ZÇĞİÖŞÜ ]+?)\(([^)]+)\)", tail
381
+ ):
382
+ name, role = om.group(1).strip(), om.group(2).strip()
383
+ if role in _OFFICIAL_ROLES and len(name) >= 3:
384
+ officials.append({"name": name, "role": role})
385
+ if officials:
386
+ out["officials"] = officials
387
+
388
+ # Goals: "NAME,3.dk (F)" entries after the Goller heading.
389
+ gm = re.search(r"\bGoller\b\s*(.*?)(?:İlk 11|$)", text, re.S)
390
+ goals: list[dict] = []
391
+ if gm:
392
+ for g in re.finditer(
393
+ r"([^,()]+?),\s*(\d+)\.dk\s*\(([^)]*)\)", gm.group(1)
394
+ ):
395
+ goals.append({
396
+ "player": g.group(1).strip(),
397
+ "minute": int(g.group(2)),
398
+ "type": g.group(3).strip(),
399
+ })
400
+ out["goals"] = goals
401
+
402
+ # Starting XIs: grdTakim1/2_rptKadrolar (formaNo + lnkOyuncu).
403
+ for side, key in (("1", "home_lineup"), ("2", "away_lineup")):
404
+ lineup: list[dict] = []
405
+ for lm in re.finditer(
406
+ rf"grdTakim{side}_rptKadrolar_ctl\d+_formaNo[^>]*>"
407
+ r"(\d+)\.</span>\s*<a[^>]*lnkOyuncu[^>]*>([^<]+)</a>",
408
+ html_text,
409
+ ):
410
+ lineup.append({
411
+ "number": int(lm.group(1)),
412
+ "player": _clean(lm.group(2)),
413
+ })
414
+ if lineup:
415
+ out[key] = lineup
416
+ return {k: v for k, v in out.items() if v not in (None, "", [])}
417
+
418
+
419
+ # ---------------------------------------------------------------- top scorers
420
+
421
+ _SCORER_RE = re.compile(
422
+ r"rptGolKralligi_ctl\d+_lblOyuncu[^>]*"
423
+ r'href="[^"]*kisiID=(\d+)[^"]*"[^>]*>([^<]+)</a>',
424
+ re.I,
425
+ )
426
+
427
+
428
+ def parse_scorers(html_text: str) -> list[dict]:
429
+ """Top-scorers repeater -> [{rank, player, player_id, club,
430
+ club_id, goals}] in table order (most goals first)."""
431
+ rows: list[dict] = []
432
+ for m in _SCORER_RE.finditer(html_text):
433
+ player_id, player = m.group(1), _clean(m.group(2))
434
+ rest = html_text[m.end():m.end() + 800]
435
+ club_m = re.search(
436
+ r"lblKulup[^>]*href=\"[^\"]*kulupID=(\d+)[^\"]*\"[^>]*>"
437
+ r"([^<]+)</a>",
438
+ rest,
439
+ re.I,
440
+ )
441
+ goals_m = re.search(r"lblGolSayisi[^>]*>(\d+)<", rest)
442
+ if not club_m or not goals_m:
443
+ continue
444
+ rows.append({
445
+ "rank": len(rows) + 1,
446
+ "player": player,
447
+ "player_id": player_id,
448
+ "club": _clean(club_m.group(2)),
449
+ "club_id": club_m.group(1),
450
+ "goals": int(goals_m.group(1)),
451
+ })
452
+ if not rows:
453
+ raise ValueError("no top scorers parsed from this page")
454
+ return rows
tff_mcp/http.py ADDED
@@ -0,0 +1,87 @@
1
+ """HTTP layer for tff_mcp.
2
+
3
+ tff.org (Turkish Football Federation) serves its league pages fully
4
+ server-rendered — standings (``s-table``), fixtures
5
+ (``fiksturListesiTable``), top scorers (``rptGolKralligi`` repeater)
6
+ and match details (pageID=29&macId=...) — with plain HTTP 200, no
7
+ login, no API key, no session cookies (verified live 2026-11-09).
8
+ The site is legacy ASP.NET and answers in windows-1254, so bodies
9
+ are decoded explicitly instead of trusting the transport's guess.
10
+ Transport still uses curl-cffi chrome120 impersonation, the proven
11
+ pattern of the other Turkey-factory servers. Requests are kept
12
+ gentle (one at a time, ~0.8s apart) and read-only. GET only.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import time
17
+ from urllib.parse import quote
18
+
19
+ from curl_cffi import requests as _r
20
+
21
+ BASE = "https://www.tff.org"
22
+ TIMEOUT = 30.0
23
+ MIN_INTERVAL = 0.8 # seconds between requests — be polite
24
+
25
+ _HEADERS = {
26
+ "Accept-Language": "tr-TR,tr;q=0.9,en;q=0.8",
27
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
28
+ }
29
+
30
+ _last_fetch = 0.0
31
+
32
+
33
+ class TffError(RuntimeError):
34
+ pass
35
+
36
+
37
+ def _get(url: str) -> str:
38
+ global _last_fetch
39
+ wait = MIN_INTERVAL - (time.monotonic() - _last_fetch)
40
+ if wait > 0:
41
+ time.sleep(wait)
42
+ try:
43
+ resp = _r.get(url, impersonate="chrome120", headers=_HEADERS, timeout=TIMEOUT)
44
+ except Exception as e:
45
+ raise TffError(f"network error fetching {url}: {e}") from e
46
+ finally:
47
+ _last_fetch = time.monotonic()
48
+ if resp.status_code == 403:
49
+ raise TffError(
50
+ "tff.org refused the request (HTTP 403, bot wall) — try again later"
51
+ )
52
+ if resp.status_code == 429:
53
+ raise TffError(
54
+ "tff.org rate-limited the request (HTTP 429) — try again later"
55
+ )
56
+ if resp.status_code in (404, 410):
57
+ raise TffError(
58
+ f"page not found (HTTP {resp.status_code}): {url} — check the "
59
+ "league / match id"
60
+ )
61
+ if resp.status_code != 200:
62
+ raise TffError(f"unexpected HTTP {resp.status_code} fetching {url}")
63
+ # Legacy ASP.NET site: windows-1254, declared in the content-type.
64
+ # Decode explicitly — the transport's charset guess is unreliable.
65
+ try:
66
+ return resp.content.decode("windows-1254")
67
+ except (UnicodeDecodeError, LookupError):
68
+ return resp.text
69
+
70
+
71
+ def fetch_league_html(page_id: str, grup_id: str | None = None) -> str:
72
+ """League standings+fixtures page: /default.aspx?pageID=<id>
73
+ (optionally &grupID=<id> for one group of a multi-group league)."""
74
+ url = f"{BASE}/default.aspx?pageID={quote(page_id)}"
75
+ if grup_id:
76
+ url += f"&grupID={quote(grup_id)}"
77
+ return _get(url)
78
+
79
+
80
+ def fetch_match_html(mac_id: str) -> str:
81
+ """Match detail page: /Default.aspx?pageID=29&macId=<id>."""
82
+ return _get(f"{BASE}/Default.aspx?pageID=29&macId={quote(str(mac_id))}")
83
+
84
+
85
+ def fetch_scorers_html(page_id: str) -> str:
86
+ """Top-scorers page: /default.aspx?pageID=<id> (821/822/823/824)."""
87
+ return _get(f"{BASE}/default.aspx?pageID={quote(page_id)}")
tff_mcp/server.py ADDED
@@ -0,0 +1,220 @@
1
+ """MCP server: unofficial read-only access to tff.org (Turkish
2
+ Football Federation)."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+ from . import football as _F
10
+ from . import http as _http
11
+
12
+ mcp = FastMCP("tff-mcp")
13
+
14
+ INSTRUCTIONS = """\
15
+ Unofficial read-only MCP server for tff.org, the Turkish Football
16
+ Federation (TFF) — league standings (puan cetveli), fixtures
17
+ (fikstür), match details, and top scorers (gol krallığı) for 18
18
+ Turkish leagues, from the Süper Lig down to the youth development
19
+ leagues. Data comes from the site's server-rendered pages — no
20
+ login, no API key. Standings and fixtures live on each league's
21
+ page (/default.aspx?pageID=<id>); multi-group leagues (Nesine 2.
22
+ Lig, Nesine 3. Lig, BAL, women's and youth leagues) take a group
23
+ (by index, group id, or name — "Kırmızı", "Beyaz", "01" ...).
24
+ Match details (/Default.aspx?pageID=29&macId=<id>) carry the date
25
+ and time, stadium, league/season, match code, the full officiating
26
+ team (referee, assistants, VAR/AVAR, observer, representative),
27
+ goals with minutes, and both starting XIs. Note: TFF's own weekly
28
+ referees page (pageID=600) lists the 2./3. Lig rounds with EMPTY
29
+ referee columns until appointments are announced close to match
30
+ day, so referee data here comes from the match-detail page. The
31
+ site is legacy ASP.NET served as windows-1254. Read-only; transport
32
+ uses Chrome TLS impersonation; requests are spaced ~0.8s apart.
33
+ Built by Mohammad Abbasi (mohammad-abbasi-sh) — Turkey MCP
34
+ factory.\
35
+ """
36
+
37
+
38
+ def _err(e: Exception) -> str:
39
+ return json.dumps({"error": str(e)}, ensure_ascii=False)
40
+
41
+
42
+ def _validate_limit(limit: int, lo: int = 1, hi: int = 50) -> int:
43
+ if not lo <= limit <= hi:
44
+ raise ValueError(f"limit must be between {lo} and {hi}")
45
+ return limit
46
+
47
+
48
+ def _league(slug: str) -> tuple[str, dict]:
49
+ slug = (slug or "trendyol-super-lig").strip().lower()
50
+ if slug not in _F.LEAGUES:
51
+ raise ValueError(
52
+ "unknown league — use tff_list_leagues for the 18 slugs: "
53
+ + ", ".join(_F.LEAGUES)
54
+ )
55
+ return slug, _F.LEAGUES[slug]
56
+
57
+
58
+ def _league_html(slug: str, group: str | None) -> tuple[dict, str, list[dict]]:
59
+ """Fetch a league page, resolving the group for multi-group leagues.
60
+
61
+ Returns (league, html, groups). For a multi-group league with no
62
+ group given, the first group is used and the groups list is
63
+ included in the output so the caller can pick another one.
64
+ """
65
+ slug, league = _league(slug)
66
+ html_text = _http.fetch_league_html(league["page_id"])
67
+ groups: list[dict] = []
68
+ if league["multi_group"]:
69
+ groups = _F.parse_groups(html_text)
70
+ if groups:
71
+ # Always fetch with the resolved grupID: the default page
72
+ # mixes both groups' fixture tables, so resolve explicitly
73
+ # (default = first group) to keep the data single-group.
74
+ target = _F.resolve_group(groups, group) or groups[0]
75
+ html_text = _http.fetch_league_html(
76
+ league["page_id"], target["id"]
77
+ )
78
+ return league, html_text, groups
79
+
80
+
81
+ @mcp.tool()
82
+ def tff_list_leagues() -> str:
83
+ """The 18 Turkish leagues covered (slug, Turkish name, TFF page
84
+ id, whether it has groups, whether a top-scorers page exists).
85
+ No arguments. Use a slug with tff_standings, tff_fixtures and
86
+ tff_top_scorers."""
87
+ return json.dumps(
88
+ {
89
+ "leagues": [
90
+ {
91
+ "slug": slug,
92
+ "name": info["name"],
93
+ "page_id": info["page_id"],
94
+ "multi_group": info["multi_group"],
95
+ "has_top_scorers": info["scorers_page_id"] is not None,
96
+ }
97
+ for slug, info in _F.LEAGUES.items()
98
+ ]
99
+ },
100
+ ensure_ascii=False,
101
+ )
102
+
103
+
104
+ @mcp.tool()
105
+ def tff_standings(league: str = "trendyol-super-lig", group: str | None = None) -> str:
106
+ """League standings (puan cetveli): rank, team, played/won/drawn/
107
+ lost, goals for/against, goal difference, points. league: a slug
108
+ from tff_list_leagues (default "trendyol-super-lig"). group: for
109
+ multi-group leagues only — index ("0"), group id, or name
110
+ ("Kırmızı", "Beyaz", "01"); default is the first group, and the
111
+ response lists all groups."""
112
+ try:
113
+ league_info, html_text, groups = _league_html(league, group)
114
+ rows = _F.parse_standings(html_text)
115
+ except (ValueError, _http.TffError) as e:
116
+ return _err(e)
117
+ out: dict = {
118
+ "league": league_info["name"],
119
+ "count": len(rows),
120
+ "standings": rows,
121
+ }
122
+ if groups:
123
+ out["groups"] = groups
124
+ out["group"] = (
125
+ _F.resolve_group(groups, group) or groups[0]
126
+ )["name"]
127
+ return json.dumps(out, ensure_ascii=False)
128
+
129
+
130
+ @mcp.tool()
131
+ def tff_fixtures(
132
+ league: str = "trendyol-super-lig",
133
+ week: int | None = None,
134
+ group: str | None = None,
135
+ ) -> str:
136
+ """League fixtures and results (fikstür): every match-week with
137
+ home/away teams, score (null when not yet played), status
138
+ ("played"/"scheduled"), TFF match id and match-detail URL.
139
+ league: a slug from tff_list_leagues (default
140
+ "trendyol-super-lig"). week: filter to one match-week (e.g. 12);
141
+ omit for all weeks. group: for multi-group leagues only — index,
142
+ group id, or name; default is the first group."""
143
+ try:
144
+ league_info, html_text, groups = _league_html(league, group)
145
+ rows = _F.parse_fixtures(html_text)
146
+ except (ValueError, _http.TffError) as e:
147
+ return _err(e)
148
+ if week is not None:
149
+ rows = [r for r in rows if r["week"] == week]
150
+ if not rows:
151
+ return _err(ValueError(f"no matches in week {week}"))
152
+ out: dict = {
153
+ "league": league_info["name"],
154
+ "count": len(rows),
155
+ "matches": rows,
156
+ }
157
+ if week is not None:
158
+ out["week"] = week
159
+ if groups:
160
+ out["groups"] = groups
161
+ out["group"] = (
162
+ _F.resolve_group(groups, group) or groups[0]
163
+ )["name"]
164
+ return json.dumps(out, ensure_ascii=False)
165
+
166
+
167
+ @mcp.tool()
168
+ def tff_match_detail(mac_id: str) -> str:
169
+ """Full detail of one TFF match. mac_id: the TFF match id, as
170
+ returned by tff_fixtures (e.g. "317874"). Returns teams and
171
+ score, date and time, stadium, league/season, match code, the
172
+ officiating team (referee, assistants, VAR/AVAR, observer,
173
+ representative), goals with minutes, and both starting XIs."""
174
+ try:
175
+ if not mac_id or not str(mac_id).strip():
176
+ raise ValueError("mac_id must not be empty")
177
+ html_text = _http.fetch_match_html(str(mac_id).strip())
178
+ data = _F.parse_match_detail(html_text)
179
+ except (ValueError, _http.TffError) as e:
180
+ return _err(e)
181
+ data["mac_id"] = str(mac_id).strip()
182
+ return json.dumps(data, ensure_ascii=False)
183
+
184
+
185
+ @mcp.tool()
186
+ def tff_top_scorers(league: str = "trendyol-super-lig", limit: int = 10) -> str:
187
+ """Top scorers (gol krallığı): rank, player, club, goals.
188
+ league: "trendyol-super-lig" (default), "trendyol-1-lig",
189
+ "nesine-2-lig" or "nesine-3-lig" — the four leagues with a TFF
190
+ scorers page. limit 1..50."""
191
+ try:
192
+ _validate_limit(limit)
193
+ _, league_info = _league(league)
194
+ if not league_info["scorers_page_id"]:
195
+ raise ValueError(
196
+ f"TFF publishes no top-scorers page for "
197
+ f"{league_info['name']} — scorers exist only for "
198
+ "trendyol-super-lig, trendyol-1-lig, nesine-2-lig "
199
+ "and nesine-3-lig"
200
+ )
201
+ html_text = _http.fetch_scorers_html(league_info["scorers_page_id"])
202
+ rows = _F.parse_scorers(html_text)
203
+ except (ValueError, _http.TffError) as e:
204
+ return _err(e)
205
+ return json.dumps(
206
+ {
207
+ "league": league_info["name"],
208
+ "count": min(limit, len(rows)),
209
+ "scorers": rows[:limit],
210
+ },
211
+ ensure_ascii=False,
212
+ )
213
+
214
+
215
+ def main() -> None:
216
+ mcp.run()
217
+
218
+
219
+ if __name__ == "__main__":
220
+ main()
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.5
2
+ Name: tff-mcp
3
+ Version: 0.1.0
4
+ Summary: Unofficial read-only MCP server for tff.org (Turkish Football Federation): standings, fixtures, match details, scorers
5
+ Author: Mohammad Abbasi
6
+ License: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: curl-cffi>=0.7
10
+ Requires-Dist: mcp<2
11
+ Description-Content-Type: text/markdown
12
+
13
+ # tff-mcp 🇹🇷
14
+
15
+ mcp-name: io.github.mohammad-abbasi-sh/tff-mcp
16
+
17
+ Unofficial **read-only** MCP server for tff.org, the Turkish Football Federation (TFF) — league standings (puan cetveli), fixtures and results (fikstür), full match details, and top scorers (gol krallığı) for 18 Turkish leagues, from the Süper Lig down to the youth development leagues.
18
+
19
+ > Built by Mohammad Abbasi as part of the "Turkey MCP factory" (Sepehr-style pipeline). Not affiliated with tff.org or the TFF.
20
+
21
+ ## For AI agents
22
+
23
+ Add to your MCP client config (stdio):
24
+
25
+ ```json
26
+ {
27
+ "mcpServers": {
28
+ "tff": {
29
+ "command": "uvx",
30
+ "args": ["tff-mcp"]
31
+ }
32
+ }
33
+ }
34
+ ```
35
+
36
+ Or run locally: `python -m tff_mcp.server` (needs `mcp<2`, `curl-cffi`).
37
+
38
+ ## Tools
39
+
40
+ | Tool | Description |
41
+ |------|-------------|
42
+ | `tff_list_leagues` | The 18 covered leagues (slug, Turkish name, TFF page id, multi-group flag, top-scorers availability) |
43
+ | `tff_standings` | League standings — `league` slug (default "trendyol-super-lig"); `group` for multi-group leagues: index ("0"), group id, or name ("Kırmızı", "Beyaz", "01"); rank, team, played/won/drawn/lost, goals for/against, goal difference, points |
44
+ | `tff_fixtures` | Fixtures and results — `league` slug; `week` to filter to one match-week; `group` for multi-group leagues; home/away, score (null when not yet played), status ("played"/"scheduled"), TFF match id and match-detail URL |
45
+ | `tff_match_detail` | Full detail of one match — `mac_id` (as returned by `tff_fixtures`, e.g. "317874"); teams and score, date/time, stadium, league/season, match code, the officiating team (referee, assistants, VAR/AVAR, observer, representative), goals with minutes, both starting XIs |
46
+ | `tff_top_scorers` | Top scorers — `league`: "trendyol-super-lig" (default), "trendyol-1-lig", "nesine-2-lig" or "nesine-3-lig" (the four leagues with a TFF scorers page); `limit` 1..50 |
47
+
48
+ Example output (`tff_match_detail` / Gaziantep FK 0–2 Kasımpaşa, 6 Nov 2026):
49
+
50
+ ```json
51
+ {"home": "GAZİANTEP FUTBOL KULÜBÜ A.Ş.", "away": "KASIMPAŞA A.Ş.",
52
+ "score_home": 0, "score_away": 2, "date": "6.11.2026", "time": "20:00",
53
+ "stadium": "GAZİANTEP STADYUMU - GAZİANTEP - ŞEHİTKAMİL",
54
+ "league": "Trendyol Süper Lig Adnan Süvari Sezonu (Profesyonel Takım)",
55
+ "match_code": "1091",
56
+ "officials": [{"name": "ÜMİT ÖZTÜRK", "role": "Hakem"},
57
+ {"name": "ERKAN ENGİN", "role": "VAR"}],
58
+ "goals": [{"player": "HARIS HAJRADINOVIC", "minute": 3, "type": "F"},
59
+ {"player": "ADRIAN DAWID BENEDYCZAK", "minute": 21, "type": "P"}]}
60
+ ```
61
+
62
+ ## How it works
63
+
64
+ tff.org serves its league pages fully server-rendered — no login, no API key, no session cookies. Standings live in `<table class="s-table">` (header O G B M A Y AV P); fixtures in `<table class="fiksturListesiTable">` ("N.Hafta" headers, match rows with home club link, score link `pageID=29&macId=...`, away club link — unplayed matches show " - "). Multi-group leagues (Nesine 2. Lig, Nesine 3. Lig, BAL, women's and youth leagues) expose their groups as `?pageID=<id>&grupID=<n>` links. Match details carry the teams in `lnkTakim1`/`lnkTakim2`, scores in `MacDetaySayi` spans, league/season in `lblOrganizasyonAdi`, match code in `lblKod`, date/time in `lblTarih`, the stadium as text between the code and the date, officials as `NAME(ROLE)` pairs, goals as "NAME,3.dk (F)" entries, and the starting XIs in the `grdTakim1/2_rptKadrolar` repeaters. Top scorers come from the `rptGolKralligi` repeater (pages 821/822/823/824). The site is legacy ASP.NET served as windows-1254, decoded explicitly. One site feature is documented, not faked: the weekly referees page (`pageID=600`) lists the 2./3. Lig rounds with EMPTY referee columns until appointments are announced close to match day — so referee data comes from the match-detail page instead. Transport uses Chrome TLS impersonation (`curl-cffi`, `chrome120`); requests are spaced ~0.8s apart; everything is read-only.
65
+
66
+ ## Install
67
+
68
+ ```bash
69
+ uvx tff-mcp # run directly (needs uv)
70
+ # or
71
+ pip install tff-mcp
72
+ tff-mcp # starts the MCP server on stdio
73
+ ```
74
+
75
+ ## Tests
76
+
77
+ ```bash
78
+ python -m venv .venv && .venv/bin/pip install -e .
79
+ .venv/bin/python -m unittest discover -s tests -v
80
+ ```
81
+
82
+ Offline tests run on recorded fixtures (real pages fetched 2026-11-09); live tests hit tff.org. 37/37 green at build time (20 offline + 17 live) plus an MCP stdio smoke test.
83
+
84
+ ## Roadmap
85
+
86
+ - Disciplinary decisions (PFDK/AFDK pages) and suspended players (pageID=633)
87
+ - Club pages (pageID=28&kulupID=...) — squad lists
88
+ - National-team matches (pageID=425)
89
+
90
+ ## License
91
+
92
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,9 @@
1
+ tff_mcp/__init__.py,sha256=vuGxEqIryLd6vibE1MPmSUVHM--i_PH9XddabIyzavw,60
2
+ tff_mcp/football.py,sha256=BeYndk3LkmuOXY4E1fIFXjoG-2CnjuwGUKmTkEmTgeI,16741
3
+ tff_mcp/http.py,sha256=9fEgOPUg05QJ725yyu8s03jWNP1MTpyxjT4E0HYHOjU,3106
4
+ tff_mcp/server.py,sha256=v9he2H8jfKcB94_pFHX6Ye2cTtcCOKf9CToN8yNlTJU,8093
5
+ tff_mcp-0.1.0.dist-info/METADATA,sha256=3aGmc8M2YVDFX0Rx6Z_jq73Ws_Cn0N4fhfellAz3yRc,4990
6
+ tff_mcp-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ tff_mcp-0.1.0.dist-info/entry_points.txt,sha256=ojjRzhnZ0tf9p4jKze2gtentdzaXKQYgAQIjAu_Vapg,48
8
+ tff_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=HsN4iUNpKeikxp-vzzw-M0KlwyflwVQKzIFR7COhaHs,1072
9
+ tff_mcp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tff-mcp = tff_mcp.server:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohammad Abbasi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.