Coverage for mt_mcp/server.py: 96.69%
141 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
1"""The mt-mcp server: tools, tier gate, HTTP app (SB-1302).
3Tool logic lives in plain Python (`mt_ai.tools`) with its own tests; this module
4adapts it to MCP. Every tool here:
6- takes the viewer from the authenticated caller, never from its arguments;
7- returns its Pydantic result model, so the SDK publishes a typed output schema
8 and sends the result as structuredContent;
9- runs the synchronous DAO-backed logic off the event loop;
10- turns an unexpected failure into a generic message — the SDK would otherwise
11 send `str(exc)` to the client.
13`TierGate` filters `tools/list` and refuses `tools/call` for tools outside the
14caller's tiers (role and client, see scopes.py). A refused call reads exactly like
15an unknown tool, so a hidden tool's existence is not disclosed.
16"""
18from collections.abc import Callable, Mapping
19from typing import Annotated, Any, Literal
21import anyio.to_thread
22import structlog
23from mcp.server.auth.settings import AuthSettings
24from mcp.server.context import CallNext, HandlerResult, ServerRequestContext
25from mcp.server.mcpserver import MCPServer
26from mcp.server.mcpserver.exceptions import ToolError
27from mcp.server.transport_security import TransportSecuritySettings
28from mcp.types import CallToolResult, ListToolsResult, TextContent
29from pydantic import Field
30from starlette.applications import Starlette
32from mt_ai.tools import (
33 ToolDeps,
34 Viewer,
35 get_live_match,
36 get_recent_results,
37 get_standings,
38 get_upcoming_matches,
39 list_divisions,
40 search_teams,
41)
42from mt_ai.tools.schemas import (
43 DivisionsResult,
44 LiveMatchResult,
45 RecentResultsResult,
46 ResolveResult,
47 StandingsResult,
48 UpcomingMatchesResult,
49)
50from mt_mcp.auth import MTTokenVerifier, Principal, current_principal
51from mt_mcp.observe import ToolCallObserver
52from mt_mcp.scopes import CLIENT_HEADER, Tier, allowed_tiers
53from mt_tools.ingest import (
54 IngestFailuresResult,
55 IngestSource,
56 ResolveIngestFailureResult,
57 list_ingest_failures,
58 resolve_ingest_failure,
59)
60from mt_tools.leaderboards import DEFAULT_LIMIT as LEADERS_DEFAULT_LIMIT
61from mt_tools.leaderboards import MAX_LIMIT as LEADERS_MAX_LIMIT
62from mt_tools.leaderboards import LeaderboardsResult, get_leaderboards
63from mt_tools.matchup import MatchupResult, get_matchup
64from mt_tools.motw_candidates import MotwCandidatesResult, suggest_from_deps
65from mt_tools.my_team import MyTeamResult, resolve_my_team
66from mt_tools.power_rating_read import (
67 PowerRatingResult,
68 PowerRatingTeamResult,
69 get_power_rating,
70 get_power_rating_team,
71)
72from mt_tools.team_dossier import TeamDossierResult, get_team_dossier
74logger = structlog.get_logger()
76SERVER_NAME = "mt-mcp"
77SERVER_VERSION = "0.1.0"
79INSTRUCTIONS = """\
80MissingTable (MT) data for youth soccer: teams, matches and standings.
81Resolve a team with search_teams (or get_my_team) before using its id elsewhere.
82Past results ("last weekend", "last 5 games", head-to-head): get_recent_results.
83A match in progress or just played ("what's the score?", "who scored?"): find its
84match_id with get_upcoming_matches or get_recent_results, then get_live_match.
85Resolve a division by name ("U15 Northeast") with list_divisions before calling
86get_standings by division: pass its division.id and the age_groups[].id.
87Standings ship with their coverage: say how many matches were played of how many
88scheduled, and for a combined view how many were against teams outside the table.
89Results distinguish "not tracked" (null) from "none" ([]); never report an absent
90value as zero.
91Match of the Week ideas: suggest_motw_candidates. Every claim about a candidate must
92come from one of its facts; a fact with confirmed=false may only be stated as
93unconfirmed.
94Cross-conference stat boards (points, goals, unbeaten): get_leaderboards. State its
95coverage; it is a stat board, not a ranking, because conferences only meet at tournaments.
96Describing one team (a match preview, Match of the Day): get_team_dossier. Cite its fact
97ids, and never say one team is better than another from a different conference.
98Previewing one match (a Fest scouting report): get_matchup, both dossiers side by side.
99Cite its fact ids, and never compare the two teams across conferences.
100The MT Power Rating (an Elo rating from results): get_power_rating, and
101get_power_rating_team for one team's "why it moved". State coverage.note. Without a
102national list, teams are ranked within their conference only: never compare two
103conferences' ranks. An unranked team is "4 of 6 matches", never rank 0.
104"""
106UNAVAILABLE = "MT could not answer that right now."
108# Every tool, and the tier that may use it. A tool missing here is never listed
109# and never callable.
110TOOL_TIERS: dict[str, Tier] = {
111 "search_teams": "read",
112 "get_upcoming_matches": "read",
113 "get_recent_results": "read",
114 "get_live_match": "read",
115 "get_standings": "read",
116 "list_divisions": "read",
117 "suggest_motw_candidates": "read",
118 "get_leaderboards": "read",
119 "get_team_dossier": "read",
120 "get_matchup": "read",
121 "get_power_rating": "read",
122 "get_power_rating_team": "read",
123 "get_my_team": "my",
124 "list_ingest_failures": "admin",
125 "resolve_ingest_failure": "admin",
126}
128DepsProvider = Callable[[], ToolDeps]
129IngestProvider = Callable[[], IngestSource]
132def _caller() -> Principal:
133 principal = current_principal()
134 if principal is None: # RequireAuthMiddleware makes this unreachable over HTTP 134 ↛ 135line 134 didn't jump to line 135 because the condition on line 134 was never true
135 raise ToolError("Authentication required.")
136 return principal
139async def _run(fn: Callable[[], Any], tool: str) -> Any:
140 try:
141 return await anyio.to_thread.run_sync(fn)
142 except ToolError:
143 raise
144 except Exception:
145 logger.exception("mt_mcp tool failed", tool=tool)
146 raise ToolError(UNAVAILABLE) from None
149def register_tools(server: MCPServer, deps: DepsProvider, ingest: IngestProvider) -> None:
150 @server.tool(name="search_teams")
151 async def search_teams_tool(query: str, age_group: str | None = None) -> ResolveResult:
152 """Find an MT team by name. Returns resolved, ambiguous (with candidates)
153 or not_found. `age_group` is like "U15" when the user gave one."""
154 viewer = Viewer.from_user(_caller().as_user())
155 return await _run(lambda: search_teams(deps(), query, viewer, age_group=age_group), "search_teams")
157 @server.tool(name="get_upcoming_matches")
158 async def get_upcoming_matches_tool(
159 team_id: int, age_group_id: int | None = None, limit: int = 5
160 ) -> UpcomingMatchesResult:
161 """A team's next matches, today or later in the club's time zone: scheduled,
162 tbd, live or postponed. Use team_id and age_group.id from search_teams.
163 "matches" is [] when nothing is scheduled and null when it could not be
164 checked (see "error")."""
165 viewer = Viewer.from_user(_caller().as_user())
166 return await _run(
167 lambda: get_upcoming_matches(deps(), team_id, viewer, age_group_id=age_group_id, limit=limit),
168 "get_upcoming_matches",
169 )
171 @server.tool(name="get_recent_results")
172 async def get_recent_results_tool(
173 team_id: int,
174 age_group_id: int | None = None,
175 limit: int = 5,
176 opponent_id: int | None = None,
177 ) -> RecentResultsResult:
178 """A team's last played matches, newest first, scored from its side:
179 "result" W/D/L, goals_for, goals_against, plus a "summary" over the
180 matches returned. Use team_id and age_group.id from search_teams. For
181 head-to-head, pass the other team's team_id as opponent_id (any season).
182 A level match decided on penalties is a draw with the shootout alongside.
183 "matches" is [] when none were played and null when it could not be
184 checked (see "error"); meta.truncated means there are older ones."""
185 viewer = Viewer.from_user(_caller().as_user())
186 return await _run(
187 lambda: get_recent_results(
188 deps(), team_id, viewer, age_group_id=age_group_id, limit=limit, opponent_id=opponent_id
189 ),
190 "get_recent_results",
191 )
193 @server.tool(name="get_live_match")
194 async def get_live_match_tool(match_id: int) -> LiveMatchResult:
195 """One match's live state: score (and any shootout), period and running
196 minute, and every goal and card with its minute, team and player. Take
197 match_id from get_upcoming_matches (status "live") or get_recent_results.
198 Players are "#7 Tom D." at most. "events" is [] when none were recorded
199 and null when they could not be checked; meta.coverage says when a match
200 was not tracked live (score only)."""
201 viewer = Viewer.from_user(_caller().as_user())
202 return await _run(lambda: get_live_match(deps(), match_id, viewer), "get_live_match")
204 @server.tool(name="get_standings")
205 async def get_standings_tool(
206 team_id: int | None = None,
207 age_group_id: int | None = None,
208 division_id: int | None = None,
209 competition: str = "League",
210 season_id: int | None = None,
211 ) -> StandingsResult:
212 """One standings table and its coverage. Give team_id (from search_teams or
213 get_my_team, plus age_group.id when known) for that team's table, or
214 division_id with age_group_id. competition: a name ("League", "Flex"),
215 "qualifying" (every competition that qualifies for the cup, League + Flex,
216 combined: a record, not a standing) or "all". Season defaults to the
217 current one. "ambiguous" lists "options": pick one (a Flex table is the
218 option whose division league is Flex) and call again with its
219 age_group.id and division.id, or ask. "rows" [] with coverage.fixtures > 0
220 means no match played yet; fixtures 0 means nothing scheduled there;
221 null means it could not be checked (see "error"). Always state the
222 coverage. A team with no row has not played a counted match yet."""
223 viewer = Viewer.from_user(_caller().as_user())
224 return await _run(
225 lambda: get_standings(
226 deps(),
227 viewer,
228 team_id=team_id,
229 age_group_id=age_group_id,
230 division_id=division_id,
231 competition=competition,
232 season_id=season_id,
233 ),
234 "get_standings",
235 )
237 @server.tool(name="list_divisions")
238 async def list_divisions_tool(
239 age_group: str | None = None, league: str | None = None, query: str | None = None
240 ) -> DivisionsResult:
241 """Divisions (conferences and Flex brackets) with teams, each with its
242 league and the age groups it runs (id, name, number of teams). Use it to
243 resolve a division by name, then call get_standings with division.id and
244 the age group's id. Filters are optional and combine: age_group like
245 "U15", league like "Homegrown" or "Flex", query part of a division or
246 league name ("Northeast"). "not_found" lists "alternatives" that exist
247 with fewer filters: pick one or ask."""
248 viewer = Viewer.from_user(_caller().as_user())
249 return await _run(
250 lambda: list_divisions(deps(), viewer, age_group=age_group, league=league, query=query),
251 "list_divisions",
252 )
254 @server.tool(name="suggest_motw_candidates")
255 async def suggest_motw_candidates_tool(
256 week: str | None = None,
257 limit: Annotated[int, Field(ge=1, le=10)] = 5,
258 pool: Literal["main", "pathway"] = "main",
259 age_group: str | None = None,
260 ) -> MotwCandidatesResult:
261 """Match of the Week candidates for one slot: a pool and an age group. There is
262 one Match of the Week per age group in each pool. pool "main" = Homegrown
263 Northeast League + Flex Empire/New England/Turnpike, U15/U16/U17/U19; pool
264 "pathway" = Northeast Pro Player Pathway League, U16/U17/U19. `age_group`
265 (e.g. "U16") narrows to that slot; omitted ranks every age in the pool.
266 Ranked by score (quality, closeness, stakes, form). `week` is any YYYY-MM-DD
267 date in the wanted Monday-Sunday week; default this week (New York time).
268 Each candidate carries "facts" with ids ("<match_id>:<slug>") and the
269 qualification "rules" its table feeds: cite a fact id for every claim, and
270 state a fact with confirmed=false only as unconfirmed. "current_pick" is the
271 slot's existing pick: never replace it without asking. "candidates" [] with
272 "reason" means nothing eligible that week; null with "error" means MT could
273 not check. Always state "coverage"."""
274 _caller()
275 return await _run(
276 lambda: suggest_from_deps(deps(), week, limit=limit, pool=pool, age_group=age_group),
277 "suggest_motw_candidates",
278 )
280 @server.tool(name="get_leaderboards")
281 async def get_leaderboards_tool(
282 age_group: str,
283 league: str = "Homegrown",
284 season: str | None = None,
285 limit: Annotated[int, Field(ge=1, le=LEADERS_MAX_LIMIT)] = LEADERS_DEFAULT_LIMIT,
286 ) -> LeaderboardsResult:
287 """Season stat boards for one league (with its Flex) at one age group, across
288 every conference: points and points per game (W=3, D=1; a level score is a
289 draw even when a Flex shootout decided it), goals for, goals
290 against (fewest), goal difference, each total and per game; unbeaten; wins
291 over pro academies. Counts completed/forfeit League + Flex results of the
292 season (default current; a name like "2026-2027"). age_group like "U15".
293 Ties share a rank. Every board ranks only teams with coverage.min_gp games;
294 teams under it are listed once, in "unranked" (most games first, at most
295 `limit`), of "unranked_count", and each board has its own "unranked_count".
296 league is a top-level league (Homegrown, Academy). "no_conference" marks a
297 team with no Homegrown conference (Flex only): name it as such. A team
298 missing from "pro_wins" never played a pro academy: not 0 wins. This is a
299 stat board, not a ranking: conferences only meet at tournaments. Always
300 state coverage.note. "rows" [] with "reason" means nothing played yet;
301 null "boards" with "error" means MT could not check."""
302 _caller()
303 return await _run(
304 lambda: get_leaderboards(deps(), league, age_group, season, limit=limit),
305 "get_leaderboards",
306 )
308 @server.tool(name="get_team_dossier")
309 async def get_team_dossier_tool(
310 team_id: int, age_group_id: int | None = None, for_match_id: int | None = None
311 ) -> TeamDossierResult:
312 """One team at one age group this season, measured inside its own tables: per
313 competition (Homegrown conference, Flex conference and Pro Player Pathway kept
314 separate) its position of N, W-D-L, goals, points per game and strength
315 percentile within that table; clean sheets; key wins (League or Flex wins over
316 teams in the top third of their own table; never a Friendly, and a pro
317 academy is no key win by itself), strongest first; last 5 League/Flex results, newest
318 first; streaks. Give team_id and age_group_id (from search_teams), or
319 for_match_id to use the team's age in that match: "context" then says whether
320 it is playing up ("playing_up_inferred" when the match does not record it;
321 "playing_down" for an older side, which is not playing up).
322 Every claim must cite a fact id from "facts". Never say a team is better than
323 one from another conference: two conferences share no table. Null stats mean
324 no counted result yet, never 0; flags "low_sample" (under 3 games) and
325 "no_results" must be stated."""
326 viewer = Viewer.from_user(_caller().as_user())
327 return await _run(
328 lambda: get_team_dossier(deps(), team_id, age_group_id, for_match_id=for_match_id, viewer=viewer),
329 "get_team_dossier",
330 )
332 @server.tool(name="get_matchup")
333 async def get_matchup_tool(match_id: int) -> MatchupResult:
334 """Both teams of one match this season, side by side, each measured inside its
335 own tables: "home" and "away" each carry a team dossier (as get_team_dossier
336 returns for this match, so with "context" saying whether the side is playing
337 up) and "badges": stat boards for the team's league at its season age where it
338 is in the top 10 and top third, "rank" of "of" teams with enough games, best first, at most
339 3. Badges are stat boards, not rankings: state "badges_note". "badges" null
340 means MT could not check; [] means none. "match" gives the date, bracket age,
341 tournament, round and "stakes" (group, elimination, none; null outside a
342 tournament). "shares_conference" says whether the teams share a table;
343 "previous_meetings" lists their past results at this age, every season, home
344 team's goals first. A side with "dossier.error" could not be described; say
345 so, the other side still stands. Every claim must cite a fact id (dossier
346 "facts" or a badge "fact_id"). Never compare the two teams across
347 conferences: two conferences share no table."""
348 viewer = Viewer.from_user(_caller().as_user())
349 return await _run(lambda: get_matchup(deps(), match_id, viewer=viewer), "get_matchup")
351 @server.tool(name="get_power_rating")
352 async def get_power_rating_tool(
353 age_group: str,
354 league: str = "Homegrown",
355 season: str | None = None,
356 view: Literal["national", "conference"] | None = None,
357 conference: str | None = None,
358 ) -> PowerRatingResult:
359 """The MT Power Rating for one league at one age group (like "U17"), from its
360 latest nightly run: an Elo rating from League, Flex and tournament results
361 (a shoot-out is a draw), rounded. view "national" is served only when the run
362 is national (publication.national); otherwise the result is conference lists,
363 "view" says which was served and publication.reason why. National view: "rank"
364 and "tier" (cut-offs in "tiers"). Conference view: "rank" is null, use
365 "conference_rank", and never compare ranks across conferences. "conference"
366 filters to one of "conferences". rank_change_7d (places, up positive) and
367 rating_change_7d compare with the run a week earlier ("movement_since"): null
368 means no such run or the team was not in it, never 0. "unranked" teams have
369 under coverage.min_matches matches: say "mp of needed matches", never a rank.
370 Badges: "provisional", "low_cross_conference". Always state coverage.note.
371 "teams" [] with "reason" means no run yet or nothing rated; null with "error"
372 means MT could not check."""
373 _caller()
374 return await _run(
375 lambda: get_power_rating(deps(), age_group, league, season, view=view, conference=conference),
376 "get_power_rating",
377 )
379 @server.tool(name="get_power_rating_team")
380 async def get_power_rating_team_tool(
381 team_id: int, age_group: str, league: str = "Homegrown", season: str | None = None
382 ) -> PowerRatingTeamResult:
383 """One team in the latest MT Power Rating run at one age group (team_id from
384 search_teams, age_group like "U17"): rating, national "rank" (null without a
385 national list) and "conference_rank", tier, badges, "sos" (mean opponent rating
386 before each match, ranked toughest first within "scope"), "biggest_movers" (the
387 3 matches that moved it most: opponent, score from the team's side, "expected"
388 share of the points, "delta"), every rated match in "deltas", and "history" (one
389 point per week). "in_run" false with "reason" means the team has no rated
390 match (or there is no run yet): say so, it is not a rating of 0. An unranked
391 team needs "needed" more matches."""
392 _caller()
393 return await _run(
394 lambda: get_power_rating_team(deps(), team_id, age_group, league, season),
395 "get_power_rating_team",
396 )
398 # --- my tier --------------------------------------------------------------
400 @server.tool(name="get_my_team")
401 async def get_my_team_tool(include_inactive: bool = False) -> MyTeamResult:
402 """The caller's own team: status "team" (their team, one entry per age
403 group, or just the age group they picked as "my team" — then that one
404 entry is the squad they mean), "club" (their club and its teams) or
405 "no_team" when none is set —
406 a normal answer, not an error. Each team carries "active": it has a match
407 in the current "season". A club lists only its active teams; pass
408 include_inactive=true when the user asks for all of them, including
409 past ones. "inactive_hidden" is how many teams were left out — say so
410 when it is not 0: "teams" [] with inactive_hidden 7 means the club has
411 teams but none playing this season, while [] with 0 means none you can
412 see. The caller's own team is always returned, even if inactive. Use
413 team_id and age_group.id from "teams" with the other tools."""
414 user = _caller().as_user()
415 return await _run(
416 lambda: resolve_my_team(deps(), user, Viewer.from_user(user), include_inactive=include_inactive),
417 "get_my_team",
418 )
420 # --- admin tier -----------------------------------------------------------
422 @server.tool(name="list_ingest_failures")
423 async def list_ingest_failures_tool(
424 since: str | None = None, limit: int = 50, conflicts: bool = False
425 ) -> IngestFailuresResult:
426 """Admin. Names the match ingest could not resolve (team, division, league),
427 open ones only, newest first; one row per name with the matches it cost.
428 `since` (ISO 8601) limits to names seen since then. `stale` means unseen for
429 a while: a hint to de-emphasise, never proof it is fixed. `conflicts` lists
430 instead the matches where the feed disagreed with a person's result
431 (score_locked, scraped_overrode_manual), one row per match."""
432 _caller()
433 return await _run(
434 lambda: list_ingest_failures(ingest(), since=since, limit=limit, conflicts=conflicts),
435 "list_ingest_failures",
436 )
438 @server.tool(name="resolve_ingest_failure")
439 async def resolve_ingest_failure_tool(
440 failure_id: int, note: Annotated[str | None, Field(max_length=500)] = None, dry_run: bool = True
441 ) -> ResolveIngestFailureResult:
442 """Admin. Close one ingest failure by hand, recording who and why — for a
443 name fixed at the sender, which never resolves on its own. Defaults to a dry
444 run that changes nothing: call again with dry_run=false to close it. The
445 note should say which: "fixed at the sender" and "not a real team" differ."""
446 caller = _caller()
447 return await _run(
448 lambda: resolve_ingest_failure(ingest(), failure_id, caller.user_id, note=note, dry_run=dry_run),
449 "resolve_ingest_failure",
450 )
453def _client_of(ctx: ServerRequestContext[Any, Any]) -> str | None:
454 request = ctx.request
455 headers = getattr(request, "headers", None)
456 return headers.get(CLIENT_HEADER) if headers is not None else None
459class TierGate:
460 """ServerMiddleware: tools/list and tools/call see only the caller's tiers."""
462 def __init__(self, tool_tiers: Mapping[str, Tier]) -> None:
463 self.tool_tiers = tool_tiers
465 def _allowed(self, ctx: ServerRequestContext[Any, Any]) -> frozenset[Tier]:
466 principal = current_principal()
467 if principal is None: 467 ↛ 468line 467 didn't jump to line 468 because the condition on line 467 was never true
468 return frozenset()
469 return allowed_tiers(principal.role, _client_of(ctx), principal.delegated)
471 def _visible(self, name: str, tiers: frozenset[Tier]) -> bool:
472 tier = self.tool_tiers.get(name)
473 return tier is not None and tier in tiers
475 async def __call__(self, ctx: ServerRequestContext[Any, Any], call_next: CallNext) -> HandlerResult:
476 if ctx.method == "tools/call":
477 name = str((ctx.params or {}).get("name", ""))
478 if not self._visible(name, self._allowed(ctx)):
479 return CallToolResult(content=[TextContent(type="text", text=f"Unknown tool: {name}")], is_error=True)
480 return await call_next(ctx)
482 if ctx.method == "tools/list":
483 result = await call_next(ctx)
484 tiers = self._allowed(ctx)
485 listed = result if isinstance(result, ListToolsResult) else ListToolsResult.model_validate(result)
486 listed.tools = [t for t in listed.tools if self._visible(t.name, tiers)]
487 return listed
489 return await call_next(ctx)
492def build_server(
493 verifier: MTTokenVerifier, deps: DepsProvider, *, issuer_url: str, ingest: IngestProvider
494) -> MCPServer:
495 server = MCPServer(
496 name=SERVER_NAME,
497 version=SERVER_VERSION,
498 instructions=INSTRUCTIONS,
499 token_verifier=verifier,
500 # Resource-server mode only: tokens come from MT's existing login, and the
501 # verifier checks each token's audience itself.
502 auth=AuthSettings(issuer_url=issuer_url, resource_server_url=None, validate_token_resource=False),
503 # Outermost first: the observer also sees calls the gate refuses.
504 middleware=[ToolCallObserver(TOOL_TIERS), TierGate(TOOL_TIERS)],
505 )
506 register_tools(server, deps, ingest)
507 return server
510def build_http_app(server: MCPServer, allowed_hosts: list[str]) -> Starlette:
511 """The streamable-HTTP app, served at the root of wherever it is mounted.
513 Stateless and JSON-only: each request stands alone, so any replica can
514 answer and there is no session to pin. DNS-rebinding protection stays on,
515 with the API's real host names allowed.
516 """
517 return server.streamable_http_app(
518 streamable_http_path="/",
519 stateless_http=True,
520 json_response=True,
521 transport_security=TransportSecuritySettings(
522 enable_dns_rebinding_protection=True,
523 allowed_hosts=allowed_hosts,
524 allowed_origins=[],
525 ),
526 )