Coverage for mt_mcp/observe.py: 93.67%

61 statements  

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

1"""What mt-mcp is asked, by whom, and how it went (SB-1302). 

2 

3`ToolCallObserver` is the outermost server middleware. For every tools/call it 

4emits one structlog event and two Prometheus series (served on the backend's 

5existing /metrics, scraped by Grafana Alloy): 

6 

7 mt_mcp_tool_calls_total{tool, client, role, outcome} 

8 mt_mcp_tool_call_seconds{tool, outcome} 

9 

10HTTP metrics see only "POST /mcp"; these say which tool. `outcome` is the 

11tool's own verdict where it has one — `resolved` / `ambiguous` / `not_found` 

12for search_teams, `team` / `club` / `no_team` for get_my_team, `empty` for a 

13list tool that checked and found nothing (no upcoming matches), an error kind 

14(`unavailable`, ...) — so "what do people ask for that MT cannot find" is a 

15query, not a log trawl. Calls refused by the tier gate are `refused`; 

16protocol-level failures are `failed`. 

17 

18Every label is bounded: names outside the known sets collapse to "other". 

19Arguments are not labels; the log carries their names only. Recording argument 

20values for replay is a separate decision (tool arguments can name minors). 

21""" 

22 

23import time 

24from collections.abc import Iterable 

25from typing import Any 

26 

27import structlog 

28from mcp.server.context import CallNext, HandlerResult, ServerRequestContext 

29from prometheus_client import Counter, Histogram 

30 

31from mt_mcp.auth import current_principal 

32from mt_mcp.scopes import CLIENT_HEADER, KNOWN_CLIENTS, ROLE_TIERS 

33 

34logger = structlog.get_logger() 

35 

36TOOL_CALLS = Counter( 

37 "mt_mcp_tool_calls_total", 

38 "mt-mcp tool calls by tool, client, caller role and outcome", 

39 ["tool", "client", "role", "outcome"], 

40) 

41TOOL_SECONDS = Histogram( 

42 "mt_mcp_tool_call_seconds", 

43 "mt-mcp tool call duration", 

44 ["tool", "outcome"], 

45 buckets=(0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10), 

46) 

47 

48# The tool's own verdicts and MT's error kinds; anything else is "other". 

49KNOWN_OUTCOMES = frozenset( 

50 { 

51 "ok", 

52 "empty", 

53 "resolved", 

54 "ambiguous", 

55 "not_found", 

56 "would_resolve", 

57 "already_resolved", 

58 "team", 

59 "club", 

60 "no_team", 

61 "unavailable", 

62 "invalid", 

63 "refused", 

64 "failed", 

65 "error", 

66 } 

67) 

68 

69 

70# A list tool's result list: [] means it checked and found nothing. 

71LIST_KEYS = ("matches", "failures", "candidates") 

72 

73 

74def bounded(value: str | None, known: Iterable[str], *, missing: str = "none") -> str: 

75 if not value: 

76 return missing 

77 value = value.strip().lower() 

78 return value if value in known else "other" 

79 

80 

81def outcome_of(result: Any) -> str: 

82 """A tools/call result → one bounded outcome label.""" 

83 if result is None: 83 ↛ 84line 83 didn't jump to line 84 because the condition on line 83 was never true

84 return "failed" 

85 data = result.model_dump(by_alias=True) if hasattr(result, "model_dump") else result 

86 if not isinstance(data, dict): 86 ↛ 87line 86 didn't jump to line 87 because the condition on line 86 was never true

87 return "ok" 

88 structured = data.get("structuredContent") 

89 if data.get("isError"): 

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

91 return "refused" if text.startswith("Unknown tool:") else "error" 

92 if isinstance(structured, dict): 92 ↛ 102line 92 didn't jump to line 102 because the condition on line 92 was always true

93 error = structured.get("error") 

94 if isinstance(error, dict) and error.get("kind"): 

95 return bounded(str(error["kind"]), KNOWN_OUTCOMES) 

96 status = structured.get("status") 

97 if isinstance(status, str): 

98 return bounded(status, KNOWN_OUTCOMES) 

99 # [] is "checked, none" — worth telling apart from a full answer. 

100 if any(structured.get(key) == [] for key in LIST_KEYS): 

101 return "empty" 

102 return "ok" 

103 

104 

105class ToolCallObserver: 

106 """ServerMiddleware: one log line and two metric samples per tools/call.""" 

107 

108 def __init__(self, tool_names: Iterable[str], clock: Any = time.perf_counter) -> None: 

109 self.tool_names = frozenset(tool_names) 

110 self.clock = clock 

111 

112 async def __call__(self, ctx: ServerRequestContext[Any, Any], call_next: CallNext) -> HandlerResult: 

113 if ctx.method != "tools/call": 

114 return await call_next(ctx) 

115 

116 params = ctx.params or {} 

117 tool = bounded(str(params.get("name", "")), self.tool_names, missing="other") 

118 headers = getattr(ctx.request, "headers", None) 

119 client = bounded(headers.get(CLIENT_HEADER) if headers is not None else None, KNOWN_CLIENTS) 

120 principal = current_principal() 

121 role = bounded(principal.role if principal else None, ROLE_TIERS) 

122 

123 started = self.clock() 

124 result: HandlerResult = None 

125 try: 

126 result = await call_next(ctx) 

127 return result 

128 finally: 

129 seconds = self.clock() - started 

130 outcome = outcome_of(result) 

131 TOOL_CALLS.labels(tool=tool, client=client, role=role, outcome=outcome).inc() 

132 TOOL_SECONDS.labels(tool=tool, outcome=outcome).observe(seconds) 

133 logger.info( 

134 "mt_mcp.tool_call", 

135 tool=tool, 

136 client=client, 

137 role=role, 

138 outcome=outcome, 

139 duration_ms=round(seconds * 1000), 

140 user_id=principal.user_id if principal else None, 

141 arg_names=sorted((params.get("arguments") or {}).keys()), 

142 )