Files
ai-agent/backend/conversations/mcpresult.py
Gabriel VidalandClaude Opus 5.5 ec9db75cb3 feat(viewer): cards for background-work, agent/session and MCP tool calls
Monitor (live watch: state, time left, the events it delivered), ScheduleWakeup
(countdown, re-fire prompt), TaskStop/TaskOutput (link back to the call that
started the task), background-Bash state; SendMessage (resolved recipient),
ListAgents, SubagentHandback, Workflow, Enter/ExitWorktree, PushNotification,
AskUserQuestion; and every mcp__ call gets a server badge, a readable name, an
args grid + JSON tree, with dedicated Linear / Slack / Chrome / Metabase /
Sentry / Notion cards. Live Monitors, pending wake-ups, AskUserQuestion and
Workflow stand on their own in the thread. Three visibility switches
(Background-work, Agent & session, MCP cards). Backend: SendMessage → Agent
card link, MCP JSON results compacted instead of clipped mid-value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 00:24:52 +02:00

50 lines
2.0 KiB
Python

"""Keep an MCP tool's JSON result parseable on its card.
A tool result is clipped to ``MAX_BLOCK`` characters before it ships, which
cuts a big JSON payload mid-value — a Linear issue whose description runs past
8 kB, a Metabase query whose column fingerprints come before its rows — and the
viewer can no longer read it. For an ``mcp__*`` result that parses as JSON and
is over the cap, this re-serializes it smaller instead: long strings shortened,
long arrays cut (with a marker), and the bulk no card reads dropped. Anything
else passes through untouched."""
from __future__ import annotations
import json
# Keys that are pure bulk for every card that renders them (Metabase's column
# metadata/fingerprints repeat what `cols` already says).
_DROP = {"results_metadata", "fingerprint", "insights", "json_query", "native_form"}
def _shrink(v, max_str: int, max_list: int):
if isinstance(v, str):
return v if len(v) <= max_str else v[:max_str] + f"… [{len(v) - max_str} more chars]"
if isinstance(v, list):
out = [_shrink(x, max_str, max_list) for x in v[:max_list]]
if len(v) > max_list:
out.append(f"… {len(v) - max_list} more")
return out
if isinstance(v, dict):
return {k: _shrink(x, max_str, max_list) for k, x in v.items() if k not in _DROP}
return v
def compact(name: str | None, text: str, cap: int) -> str:
"""``text`` made to fit ``cap`` as valid JSON when it is an MCP tool's JSON
result that would otherwise be clipped; else ``text`` unchanged."""
if not name or not name.startswith("mcp__") or not text or len(text) <= cap:
return text
s = text.lstrip()
if not s or s[0] not in "[{":
return text
try:
data = json.loads(s)
except ValueError:
return text
for max_str, max_list in ((1500, 60), (400, 25), (150, 10)):
out = json.dumps(_shrink(data, max_str, max_list), ensure_ascii=False, separators=(",", ":"))
if len(out) <= cap:
return out
return out