Coverage for mt_ai/agent.py: 99.34%

133 statements  

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

1"""The MT assistant: one ADK agent with four tools (SB-1143, SB-1152, SB-1496, SB-1503). 

2 

3With `mcp` given (SB-1302, SB-1303), every tool comes from mt-mcp over MCP, 

4called with the end user's own token, so the server — not this module — 

5decides what the caller may see. Without it (MT_MCP_ENABLED off, the rollback 

6path) the same tool functions are registered in-process. 

7 

8This module is the only place that knows about ADK. It takes plain inputs 

9(history as text, a message, a viewer, a budget) and returns a plain 

10`TurnOutcome`; the conversation service and the API never see ADK objects, 

11and the tools never see ADK or HTTP. 

12 

13The ADK session is in-memory and lives for one request. It is rebuilt from 

14MT's own `ai_messages` rows each time, so MT owns the conversation record and 

15ADK's session format can change without a migration. 

16""" 

17 

18import json 

19import os 

20from collections.abc import Callable 

21from dataclasses import dataclass 

22from typing import Any, Literal 

23 

24import structlog 

25from google.adk.agents import LlmAgent 

26from google.adk.agents.invocation_context import LlmCallsLimitExceededError 

27from google.adk.agents.run_config import RunConfig 

28from google.adk.events import Event 

29from google.adk.models.base_llm import BaseLlm 

30from google.adk.runners import Runner 

31from google.adk.sessions import InMemorySessionService 

32from google.adk.tools.mcp_tool import McpToolset, StreamableHTTPConnectionParams 

33from google.genai import types 

34 

35from mt_ai.budget import Budget, BudgetExhaustedError, BudgetLimit, ToolCallGuard 

36from mt_ai.tools import ToolDeps, Viewer, get_standings, get_upcoming_matches, list_divisions, search_teams 

37from mt_ai.trace import ToolCallRecord, TurnRecorder 

38 

39logger = structlog.get_logger() 

40 

41# ADK's MCP client tries Google mTLS before every new MCP session by probing for 

42# Google credentials — off-GCP, a 3-10 s wait on the metadata server — and caches 

43# a failure only per toolset, which here is per turn. mt-mcp is not a Google API. 

44# An explicit setting still wins (SB-1302). 

45os.environ.setdefault("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") 

46 

47APP_NAME = "mt_ai" 

48AGENT_NAME = "mt_assistant" 

49AGENT_VERSION = "mt-assistant/0.4.0" 

50 

51INSTRUCTION = """\ 

52You are MT, the assistant for MissingTable, a youth soccer site for players, 

53parents and fans. Answer questions about MT teams, their upcoming matches and 

54standings using your tools. 

55 

56- To find a team, use search_teams. 

57- To say when a team plays next, first resolve the team with search_teams, then 

58 call get_upcoming_matches with that team's team_id and its age_group id. 

59 Kickoff times are in the club's local time; dates are on or after "today" in 

60 the result. 

61- If get_upcoming_matches returns "matches": [], say nothing is scheduled yet 

62 as of that "today". Only say match data is unavailable when the result has 

63 an "error". A postponed match is still listed: say it was postponed. 

64- For standings, resolve the team with search_teams, then call get_standings 

65 with its team_id and age_group id (competition "League" unless the user asks 

66 for Flex, or "qualifying" for the combined League + Flex record). If it says 

67 "ambiguous", pick from "options" when the question decides it (a Flex table 

68 is the option whose division league is Flex) and call again with that 

69 age_group id and division id; otherwise ask. Always say how many matches the 

70 table counts of how many are scheduled (coverage), and for "qualifying" that 

71 it is a record that includes matches against teams outside the table. "rows" 

72 [] with fixtures above 0 means no match has been played yet. Never claim who 

73 qualifies: MT has no qualification cutoff. 

74- For a division's table named without a team ("who leads U15 Northeast?"), 

75 call list_divisions (age_group, and query with the division name), then 

76 get_standings with that division.id and the matching age_groups id. If 

77 several divisions match, pick the one whose league fits the question (a 

78 Flex division only when the user asks for Flex); otherwise ask, naming each 

79 with its league. If it says "not_found", offer the "alternatives" it lists. 

80- Never guess a team. If search_teams says "ambiguous", ask which one the user 

81 means and list the candidates (name, age group, league). If it says 

82 "not_found" with "other_ages", the team exists but not at that age: say so, 

83 and list the age groups it does play in. Otherwise say plainly that no such 

84 team was found. 

85- A team can play in several competitions at one age group (for example a 

86 League and Flex). Those are the "registrations" of one team: report them 

87 all, and never treat them as different teams. 

88- If a tool result has an "error", explain in one sentence that the data is 

89 unavailable right now. Do not invent an answer. 

90- Only state facts that appear in tool results. Keep answers short. 

91""" 

92 

93 

94@dataclass(frozen=True) 

95class HistoryTurn: 

96 user: str 

97 assistant: str 

98 

99 

100@dataclass(frozen=True) 

101class TurnOutcome: 

102 status: Literal["ok", "budget_exhausted"] 

103 answer: str | None 

104 llm_calls: int 

105 tool_calls: int 

106 exhausted: BudgetLimit | None = None 

107 # What the turn did (SB-1197): every completed tool call, and model time. 

108 trace: tuple[ToolCallRecord, ...] = () 

109 llm_ms: int | None = None 

110 # Only the sb-agents backend sets these (SB-1500); the in-app agent leaves them empty. 

111 outcome: str | None = None 

112 escalation: str | None = None 

113 routed_to: tuple[str, ...] = () 

114 tables: tuple[dict[str, Any], ...] = () 

115 

116 

117class AIRunError(Exception): 

118 """The model or the agent run failed. The message is for logs, not clients. 

119 

120 Carries the trace up to the failure, so a failed turn can be inspected too. 

121 """ 

122 

123 def __init__(self, message: str, trace: tuple[ToolCallRecord, ...] = (), llm_ms: int | None = None) -> None: 

124 super().__init__(message) 

125 self.trace = trace 

126 self.llm_ms = llm_ms 

127 

128 

129@dataclass(frozen=True) 

130class McpAccess: 

131 """How this turn reaches mt-mcp: where, and as whom. 

132 

133 `bearer` is the end user's own token, forwarded unchanged; the client 

134 header caps the tool tiers at what MT AI may use (scopes.py), and 

135 `tool_filter` repeats that cap on this side. 

136 """ 

137 

138 url: str 

139 bearer: str 

140 tools: tuple[str, ...] = ("search_teams", "get_upcoming_matches", "get_standings", "list_divisions") 

141 timeout_s: float = 10.0 

142 httpx_client_factory: Any = None # tests inject an in-process transport 

143 

144 def toolset(self) -> McpToolset: 

145 params: dict[str, Any] = { 

146 "url": self.url, 

147 "headers": {"Authorization": f"Bearer {self.bearer}", "X-MT-Client": "mt-ai"}, 

148 "timeout": self.timeout_s, 

149 "sse_read_timeout": self.timeout_s, 

150 } 

151 if self.httpx_client_factory is not None: 151 ↛ 153line 151 didn't jump to line 153 because the condition on line 151 was always true

152 params["httpx_client_factory"] = self.httpx_client_factory 

153 return McpToolset(connection_params=StreamableHTTPConnectionParams(**params), tool_filter=list(self.tools)) 

154 

155 

156def unwrap_mcp_result(tool_response: Any) -> Any: 

157 """An MCP tool's CallToolResult → the tool's own dict, as an in-process tool returns it. 

158 

159 The model then sees one copy of the result (not a text copy plus 

160 structuredContent), and the trace records the same shape for both kinds of 

161 tool. A protocol-level error (unknown tool, refused call) becomes a tool 

162 error the agent's instruction already handles. 

163 """ 

164 if not isinstance(tool_response, dict) or "content" not in tool_response: 

165 return tool_response 

166 structured = tool_response.get("structuredContent") 

167 if isinstance(structured, dict) and not tool_response.get("isError"): 

168 return structured 

169 text = "".join(c.get("text", "") for c in tool_response.get("content") or [] if isinstance(c, dict)) 

170 if tool_response.get("isError"): 

171 return {"error": {"kind": "unavailable", "message": text or "Tool failed."}} 

172 try: 

173 parsed = json.loads(text) 

174 except ValueError: 

175 return {"value": text} 

176 return parsed if isinstance(parsed, dict) else {"value": parsed} 

177 

178 

179def model_name(model: BaseLlm | str | None) -> str | None: 

180 return model if isinstance(model, str) or model is None else model.model 

181 

182 

183def make_upcoming_matches_tool(deps: ToolDeps, viewer: Viewer) -> Callable[..., dict[str, Any]]: 

184 """Bind get_upcoming_matches like search_teams: the viewer (and so test 

185 visibility) and the clock are the server's; the model picks only the team.""" 

186 

187 def get_upcoming_matches_tool(team_id: int, age_group_id: int | None = None, limit: int = 5) -> dict[str, Any]: 

188 """A team's next matches, today or later in the club's time zone: scheduled, 

189 tbd, live or postponed. Use team_id and age_group.id from search_teams. 

190 "matches" is [] when nothing is scheduled and null when it could not be 

191 checked (see "error").""" 

192 return get_upcoming_matches(deps, team_id, viewer, age_group_id=age_group_id, limit=limit).model_dump( 

193 mode="json" 

194 ) 

195 

196 get_upcoming_matches_tool.__name__ = "get_upcoming_matches" 

197 return get_upcoming_matches_tool 

198 

199 

200def make_standings_tool(deps: ToolDeps, viewer: Viewer) -> Callable[..., dict[str, Any]]: 

201 """Bind get_standings like the others: the viewer is the server's; the model 

202 picks only which table.""" 

203 

204 def get_standings_tool( 

205 team_id: int | None = None, 

206 age_group_id: int | None = None, 

207 division_id: int | None = None, 

208 competition: str = "League", 

209 season_id: int | None = None, 

210 ) -> dict[str, Any]: 

211 """One standings table and its coverage. Give team_id (from search_teams or 

212 get_my_team, plus age_group.id when known) for that team's table, or 

213 division_id with age_group_id. competition: a name ("League", "Flex"), 

214 "qualifying" (every competition that qualifies for the cup, League + Flex, 

215 combined: a record, not a standing) or "all". Season defaults to the 

216 current one. "ambiguous" lists "options": pick one (a Flex table is the 

217 option whose division league is Flex) and call again with its 

218 age_group.id and division.id, or ask. "rows" [] with coverage.fixtures > 0 

219 means no match played yet; fixtures 0 means nothing scheduled there; 

220 null means it could not be checked (see "error"). Always state the 

221 coverage. A team with no row has not played a counted match yet.""" 

222 return get_standings( 

223 deps, 

224 viewer, 

225 team_id=team_id, 

226 age_group_id=age_group_id, 

227 division_id=division_id, 

228 competition=competition, 

229 season_id=season_id, 

230 ).model_dump(mode="json") 

231 

232 get_standings_tool.__name__ = "get_standings" 

233 return get_standings_tool 

234 

235 

236def make_list_divisions_tool(deps: ToolDeps, viewer: Viewer) -> Callable[..., dict[str, Any]]: 

237 """Bind list_divisions like the others: the viewer is the server's; the 

238 model picks only the filters.""" 

239 

240 def list_divisions_tool( 

241 age_group: str | None = None, league: str | None = None, query: str | None = None 

242 ) -> dict[str, Any]: 

243 """Divisions (conferences and Flex brackets) with teams, each with its 

244 league and the age groups it runs (id, name, number of teams). Use it to 

245 resolve a division by name, then call get_standings with division.id and 

246 the age group's id. Filters are optional and combine: age_group like 

247 "U15", league like "Homegrown" or "Flex", query part of a division or 

248 league name ("Northeast"). "not_found" lists "alternatives" that exist 

249 with fewer filters: pick one or ask.""" 

250 return list_divisions(deps, viewer, age_group=age_group, league=league, query=query).model_dump(mode="json") 

251 

252 list_divisions_tool.__name__ = "list_divisions" 

253 return list_divisions_tool 

254 

255 

256def make_search_teams_tool(deps: ToolDeps, viewer: Viewer) -> Callable[..., dict[str, Any]]: 

257 """Bind the tool to this request's data sources and viewer. 

258 

259 The model supplies only `query` and `age_group`; who is asking — and so 

260 whether test teams are visible — is fixed here and cannot be argued with. 

261 """ 

262 

263 def search_teams_tool(query: str, age_group: str | None = None) -> dict[str, Any]: 

264 """Find an MT team by name. Returns resolved, ambiguous (with candidates) 

265 or not_found. `age_group` is like "U15" when the user gave one.""" 

266 return search_teams(deps, query, viewer, age_group=age_group).model_dump(mode="json") 

267 

268 search_teams_tool.__name__ = "search_teams" 

269 return search_teams_tool 

270 

271 

272async def run_turn( 

273 model: BaseLlm | str, 

274 deps: ToolDeps, 

275 viewer: Viewer, 

276 history: list[HistoryTurn], 

277 message: str, 

278 budget: Budget, 

279 session_id: str, 

280 mcp: McpAccess | None = None, 

281) -> TurnOutcome: 

282 guard = ToolCallGuard(budget.max_tool_calls) 

283 recorder = TurnRecorder() 

284 llm_calls = 0 

285 

286 def after_tool(tool: Any, args: dict[str, Any], tool_context: Any, tool_response: Any) -> Any: 

287 result = unwrap_mcp_result(tool_response) 

288 recorder.after_tool(tool, args, tool_context, result) 

289 # None keeps ADK's own response; a value replaces it. 

290 return None if result is tool_response else result 

291 

292 toolset = mcp.toolset() if mcp else None 

293 tools: list[Any] = ( 

294 [toolset] 

295 if toolset 

296 else [ 

297 make_search_teams_tool(deps, viewer), 

298 make_upcoming_matches_tool(deps, viewer), 

299 make_standings_tool(deps, viewer), 

300 make_list_divisions_tool(deps, viewer), 

301 ] 

302 ) 

303 

304 def count_llm_call(callback_context: Any, llm_request: Any) -> None: 

305 nonlocal llm_calls 

306 llm_calls += 1 

307 

308 agent = LlmAgent( 

309 name=AGENT_NAME, 

310 model=model, 

311 instruction=INSTRUCTION, 

312 tools=tools, 

313 # The guard runs first: a call over budget is stopped, never timed. 

314 before_model_callback=[count_llm_call, recorder.before_model], 

315 after_model_callback=recorder.after_model, 

316 before_tool_callback=[guard.before_tool, recorder.before_tool], 

317 after_tool_callback=after_tool, 

318 ) 

319 sessions = InMemorySessionService() 

320 session = await sessions.create_session(app_name=APP_NAME, user_id="viewer", session_id=session_id) 

321 for turn in history: 

322 await sessions.append_event(session, _text_event("user", "user", turn.user)) 

323 await sessions.append_event(session, _text_event(AGENT_NAME, "model", turn.assistant)) 

324 

325 runner = Runner(app_name=APP_NAME, agent=agent, session_service=sessions) 

326 answer_parts: list[str] = [] 

327 try: 

328 async for event in runner.run_async( 

329 user_id="viewer", 

330 session_id=session_id, 

331 new_message=types.Content(role="user", parts=[types.Part(text=message)]), 

332 run_config=RunConfig(max_llm_calls=budget.max_llm_calls), 

333 ): 

334 if event.is_final_response() and event.content: 

335 answer_parts.extend(p.text for p in event.content.parts or [] if p.text) 

336 except LlmCallsLimitExceededError: 

337 return TurnOutcome( 

338 "budget_exhausted", None, llm_calls, guard.calls, "llm_calls", tuple(recorder.calls), recorder.llm_ms 

339 ) 

340 except BudgetExhaustedError as exc: 

341 return TurnOutcome( 

342 "budget_exhausted", None, llm_calls, guard.calls, exc.limit, tuple(recorder.calls), recorder.llm_ms 

343 ) 

344 except Exception as exc: 

345 logger.exception("mt_ai run failed", session_id=session_id, llm_calls=llm_calls) 

346 raise AIRunError(type(exc).__name__, tuple(recorder.calls), recorder.llm_ms) from exc 

347 finally: 

348 if toolset is not None: 

349 await toolset.close() 

350 

351 answer = "".join(answer_parts).strip() 

352 if not answer: 

353 raise AIRunError("model returned no text", tuple(recorder.calls), recorder.llm_ms) 

354 return TurnOutcome("ok", answer, llm_calls, guard.calls, trace=tuple(recorder.calls), llm_ms=recorder.llm_ms) 

355 

356 

357def _text_event(author: str, role: str, text: str) -> Event: 

358 return Event( 

359 author=author, invocation_id="history", content=types.Content(role=role, parts=[types.Part(text=text)]) 

360 )