Coverage for mt_ai/tools/schemas.py: 100.00%

191 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 14:44 +0000

1"""Typed inputs and results shared by the MT AI tools. 

2 

3Two rules from docs/03-architecture/mt2/ai.md shape these models: 

4 

5- Errors are results, not exceptions. Every result carries an optional 

6 `ToolError` the agent can explain in plain language. 

7- Absent is not empty. A list field that is `None` means "not known / not 

8 tracked"; `[]` means "checked, and there are none". 

9""" 

10 

11from datetime import date, datetime 

12from typing import Any, Literal 

13 

14from pydantic import BaseModel, Field 

15 

16ErrorKind = Literal["not_found", "ambiguous", "invalid_args", "unavailable"] 

17Provenance = Literal["scraper", "user", "mixed"] 

18 

19 

20class Viewer(BaseModel): 

21 """Who a tool is answering for. Tools never see more than this viewer could.""" 

22 

23 include_test: bool = False 

24 

25 @classmethod 

26 def from_user(cls, user: dict[str, Any] | None) -> "Viewer": 

27 # Imported here: auth pulls in FastAPI and JWT setup the tools don't need. 

28 from auth import viewer_sees_test_content 

29 

30 return cls(include_test=viewer_sees_test_content(user)) 

31 

32 

33class ToolError(BaseModel): 

34 kind: ErrorKind 

35 message: str 

36 

37 

38class ToolMeta(BaseModel): 

39 """Where a result came from and how much of it there is.""" 

40 

41 source: Provenance | None = None 

42 as_of: datetime | None = None 

43 coverage: str | None = None 

44 truncated: bool = False 

45 

46 

47class AgeGroupRef(BaseModel): 

48 id: int 

49 name: str 

50 

51 

52class Registration(BaseModel): 

53 """One competition a team plays in at an age group (a team_mappings row).""" 

54 

55 league: str | None = None 

56 division: str | None = None 

57 

58 

59class TeamCandidate(BaseModel): 

60 """One team, optionally pinned to one of the age groups it plays in. 

61 

62 A team can play in several competitions at one age group — League and Flex, 

63 say. Those are `registrations` of this one candidate, never separate 

64 candidates: two competitions are not two teams (SB-1146). 

65 """ 

66 

67 team_id: int 

68 name: str 

69 club_name: str | None = None 

70 league_name: str | None = None 

71 age_group: AgeGroupRef | None = None 

72 registrations: list[Registration] = Field(default_factory=list) 

73 # Has a match in the current season (SB-1322). None = not checked: only 

74 # get_my_team checks it. 

75 active: bool | None = None 

76 

77 

78class ResolveResult(BaseModel): 

79 status: Literal["resolved", "ambiguous", "not_found"] 

80 team: TeamCandidate | None = None 

81 candidates: list[TeamCandidate] = Field(default_factory=list) 

82 # not_found only: the team exists, just not at the age asked for. Every age 

83 # group it does play in, even past the candidate limit (SB-1155). 

84 other_ages: list[str] = Field(default_factory=list) 

85 error: ToolError | None = None 

86 meta: ToolMeta = Field(default_factory=ToolMeta) 

87 

88 

89class TeamRef(BaseModel): 

90 id: int 

91 name: str 

92 club_name: str | None = None 

93 

94 

95class UpcomingMatch(BaseModel): 

96 match_id: int 

97 match_date: date 

98 kickoff: datetime | None = None # in the club's timezone; None when unscheduled 

99 status: str 

100 home_team: TeamRef 

101 away_team: TeamRef 

102 is_home: bool 

103 age_group: str | None = None 

104 division: str | None = None 

105 competition: str | None = None 

106 league: str | None = None 

107 

108 

109class UpcomingMatchesResult(BaseModel): 

110 team_id: int 

111 age_group_id: int | None = None 

112 today: date | None = None 

113 timezone: str | None = None 

114 # None = could not check; [] = checked, nothing scheduled. 

115 matches: list[UpcomingMatch] | None = None 

116 error: ToolError | None = None 

117 meta: ToolMeta = Field(default_factory=ToolMeta) 

118 

119 

120class RecentResult(BaseModel): 

121 """One played match, scored from the requested team's side.""" 

122 

123 match_id: int 

124 match_date: date 

125 status: str # "completed" or "forfeit" 

126 home_team: TeamRef 

127 away_team: TeamRef 

128 is_home: bool 

129 home_score: int 

130 away_score: int 

131 # A level match decided on penalties (Flex): the shootout, else None. Still a draw: 

132 # "result" is the result after regulation, as in the standings. 

133 home_penalty_score: int | None = None 

134 away_penalty_score: int | None = None 

135 result: Literal["W", "D", "L"] 

136 goals_for: int 

137 goals_against: int 

138 age_group: str | None = None 

139 division: str | None = None 

140 competition: str | None = None 

141 league: str | None = None 

142 season: str | None = None 

143 

144 

145class ResultsSummary(BaseModel): 

146 """Totals over the matches returned (not the whole season: see meta.truncated).""" 

147 

148 played: int 

149 wins: int 

150 draws: int 

151 losses: int 

152 goals_for: int 

153 goals_against: int 

154 

155 

156class RecentResultsResult(BaseModel): 

157 team_id: int 

158 age_group_id: int | None = None 

159 opponent_id: int | None = None # set: head-to-head against this team only 

160 today: date | None = None 

161 timezone: str | None = None 

162 # None = could not check (see "error"); [] = no played match found. 

163 matches: list[RecentResult] | None = None 

164 summary: ResultsSummary | None = None 

165 error: ToolError | None = None 

166 meta: ToolMeta = Field(default_factory=ToolMeta) 

167 

168 

169class SeasonRef(BaseModel): 

170 id: int 

171 name: str 

172 

173 

174class DivisionRef(BaseModel): 

175 """A division (conference or Flex bracket) and the league it belongs to.""" 

176 

177 id: int 

178 name: str 

179 league: str | None = None 

180 

181 

182class StandingsOption(BaseModel): 

183 """One table a team plays in: pass its ids back to get_standings to pick it.""" 

184 

185 age_group: AgeGroupRef 

186 division: DivisionRef 

187 

188 

189class StandingsRow(BaseModel): 

190 position: int # 1-based, in MLS NEXT table order: points per match, then the official tiebreaks 

191 team: TeamRef 

192 played: int 

193 wins: int 

194 draws: int # level after regulation, shootout or not 

195 losses: int 

196 shootout_wins: int # of the draws, won on penalties — worth 2 where the competition scores shootouts 

197 shootout_losses: int 

198 goals_for: int # regulation only; shootout kicks are not goals 

199 goals_against: int 

200 goal_difference: int 

201 points: int 

202 # Per match played, 2 decimals; None when the team hasn't played. The 

203 # table ranks by points_per_match, so quote it when explaining an order. 

204 points_per_match: float | None = None 

205 gd_per_match: float | None = None 

206 gf_per_match: float | None = None 

207 ga_per_match: float | None = None 

208 form: list[str] = Field(default_factory=list) # last five results, oldest first ("W", "D", "L") 

209 position_change: int = 0 # places moved since the previous match day; positive is up 

210 is_requested_team: bool = False 

211 

212 

213class StandingsCoverage(BaseModel): 

214 """What the table is made of, as MatchDAO.get_standings reports it. 

215 

216 `fixtures` counts every match scheduled for the selection, played or not; 

217 `matches_counted` only the played ones in the table. So `rows: []` with 

218 `fixtures > 0` is "none played yet", and `fixtures == 0` is "nothing 

219 scheduled here". `matches_vs_outside_table` > 0 means a combined view 

220 (qualifying, all) counts results against teams not in the table: a record, 

221 not a standing. 

222 """ 

223 

224 match_type: str | None = None 

225 competitions: list[str] | None = None # None = every competition ("all") 

226 matches_counted: int = 0 

227 fixtures: int = 0 

228 counted_by_competition: dict[str, int] = Field(default_factory=dict) 

229 matches_vs_outside_table: int = 0 

230 teams_outside_table: int = 0 

231 shootout_points: list[str] = Field(default_factory=list) # competitions scoring a shootout 2/1 

232 

233 

234class StandingsResult(BaseModel): 

235 team_id: int | None = None 

236 competition: str 

237 season: SeasonRef | None = None 

238 age_group: AgeGroupRef | None = None 

239 division: DivisionRef | None = None 

240 # None = could not build the table (see "error"); [] = no match played yet 

241 # (read coverage.fixtures to tell "none played" from "nothing scheduled"). 

242 rows: list[StandingsRow] | None = None 

243 coverage: StandingsCoverage | None = None 

244 # ambiguous: every table the team plays in. not_found with a team: the 

245 # tables it does play in, when none matched the ids given. 

246 options: list[StandingsOption] = Field(default_factory=list) 

247 error: ToolError | None = None 

248 meta: ToolMeta = Field(default_factory=ToolMeta) 

249 

250 

251class DivisionAgeGroup(BaseModel): 

252 """One age group a division runs, as far as MT's registrations show.""" 

253 

254 id: int 

255 name: str 

256 teams: int # visible teams registered in the division at this age 

257 

258 

259class DivisionSummary(BaseModel): 

260 """A division and its age groups: division.id and an age_groups[].id pick a table.""" 

261 

262 division: DivisionRef 

263 age_groups: list[DivisionAgeGroup] = Field(default_factory=list) 

264 

265 

266class DivisionsResult(BaseModel): 

267 age_group: str | None = None 

268 league: str | None = None 

269 query: str | None = None 

270 # None = could not check (see "error"). Never [] — no match is not_found. 

271 divisions: list[DivisionSummary] | None = None 

272 # not_found only: what does exist with fewer filters, so the agent can recover. 

273 alternatives: list[DivisionSummary] = Field(default_factory=list) 

274 error: ToolError | None = None 

275 meta: ToolMeta = Field(default_factory=ToolMeta) 

276 

277 

278LivePeriod = Literal["not_started", "first_half", "halftime", "second_half", "full_time"] 

279 

280 

281class LiveEvent(BaseModel): 

282 """A goal or card. Players are "#7 Tom D." at most (SB-1583): never a full surname.""" 

283 

284 type: Literal["goal", "yellow_card", "red_card"] 

285 minute: int | None = None 

286 extra_time: int | None = None # stoppage minutes: minute 45, extra_time 2 is 45+2 

287 team_id: int | None = None 

288 team: str | None = None 

289 player: str | None = None # None when no player was recorded 

290 assist: str | None = None 

291 

292 

293class LiveMatchResult(BaseModel): 

294 match_id: int 

295 status: str | None = None # scheduled, live, completed, ... 

296 period: LivePeriod | None = None 

297 # Current minute while the clock runs (minute 90, extra_time 3 is 90+3); None otherwise. 

298 minute: int | None = None 

299 extra_time: int | None = None 

300 home_team: TeamRef | None = None 

301 away_team: TeamRef | None = None 

302 home_score: int | None = None 

303 away_score: int | None = None 

304 home_penalty_score: int | None = None 

305 away_penalty_score: int | None = None 

306 age_group: str | None = None 

307 competition: str | None = None 

308 # Goals and cards, oldest first. None = could not check; [] = none recorded. 

309 events: list[LiveEvent] | None = None 

310 error: ToolError | None = None 

311 meta: ToolMeta = Field(default_factory=ToolMeta)