Open History to see the last commit
1import type { T3McpToolSummaryAction } from "@t3tools/shared/t3McpToolPresentation";
2
3export interface T3ToolSummaryCall {
4 readonly input: unknown;
5 readonly output: unknown;
6 readonly outcome: "completed" | "failed" | "unfinished";
7}
8
9function asRecord(value: unknown): Record<string, unknown> | undefined {
10 return value !== null && typeof value === "object" && !Array.isArray(value)
11 ? (value as Record<string, unknown>)
12 : undefined;
13}
14
15function id(value: unknown): string | undefined {
16 return typeof value === "string" && value.trim() !== "" ? value : undefined;
17}
18
19interface ToolResult {
20 readonly data?: Record<string, unknown>;
21 readonly failed: boolean;
22}
23
24function readResult(value: unknown, depth = 0): ToolResult {
25 if (depth > 4) return { failed: false };
26 if (typeof value === "string") {
27 try {
28 return readResult(JSON.parse(value), depth + 1);
29 } catch {
30 return { failed: false };
31 }
32 }
33 if (Array.isArray(value)) {
34 let data: ToolResult["data"];
35 let failed = false;
36 for (const block of value) {
37 const record = asRecord(block);
38 const text = record?.text ?? asRecord(record?.content)?.text;
39 const result = readResult(asRecord(text)?.text ?? text, depth + 1);
40 data ??= result.data;
41 failed ||= result.failed;
42 }
43 return { ...(data ? { data } : {}), failed };
44 }
45 const record = asRecord(value);
46 if (!record) return { failed: false };
47 const failed =
48 record.isError === true ||
49 record.is_error === true ||
50 (typeof record._tag === "string" && /(?:Error|Failure)$/.test(record._tag)) ||
51 record.error != null;
52 const content = record.structuredContent ?? record.content;
53 if (content !== undefined) {
54 const result = readResult(content, depth + 1);
55 return { ...(result.data ? { data: result.data } : {}), failed: failed || result.failed };
56 }
57 return { data: record, failed };
58}
59
60function readInput(value: unknown): Record<string, unknown> | undefined {
61 const input = readResult(value).data;
62 // Cursor retains its MCP args envelope; other adapters retain the arguments directly.
63 return input && typeof input.toolName === "string" ? asRecord(input.args) : input;
64}
65
66/** MCP errors can be returned as data even when the provider completed the tool call. */
67export function t3ToolResultIndicatesFailure(output: unknown): boolean {
68 return readResult(output).failed;
69}
70
71function countEntities(ids: ReadonlyArray<string | undefined>): number {
72 return (
73 new Set(ids.filter((value) => value !== undefined)).size +
74 ids.filter((value) => value === undefined).length
75 );
76}
77
78function quantity(count: number, noun: string, plural = `${noun}s`): string {
79 return `${count} ${count === 1 ? noun : plural}`;
80}
81
82export function summarizeT3ToolCalls(
83 action: T3McpToolSummaryAction,
84 calls: ReadonlyArray<T3ToolSummaryCall>,
85): { label: string; failedCount: number } {
86 const results = calls.map((call) => {
87 const result = readResult(call.output);
88 return {
89 input: readInput(call.input),
90 output: result.data,
91 outcome: result.failed ? ("failed" as const) : call.outcome,
92 };
93 });
94 const completed = results.filter((call) => call.outcome === "completed");
95 let failedCount = results.filter((call) => call.outcome === "failed").length;
96 const selected = completed.length > 0 ? completed : results;
97 const times = quantity(selected.length, "time");
98 const phrase = (past: string, infinitive: string, object: string) =>
99 `${completed.length > 0 ? past : `Tried to ${infinitive}`} ${object}`;
100 const entityIds = (key: string) =>
101 selected.map((call) => id(call.output?.[key]) ?? id(call.input?.[key]));
102 const projectIds = selected.map(
103 (call) => id(call.output?.id) ?? id(call.output?.projectId) ?? id(call.input?.projectId),
104 );
105 const threadIds = selected.map(
106 (call) =>
107 id(call.output?.threadId) ??
108 id(asRecord(call.output?.thread)?.threadId) ??
109 id(call.input?.threadId),
110 );
111 let label: string;
112 switch (action) {
113 case "thread-send": {
114 const messages = countEntities(selected.map((call) => id(call.output?.messageId)));
115 const targetsKnown = threadIds.every((value) => value !== undefined);
116 const threads = new Set(threadIds).size;
117 const object = targetsKnown
118 ? messages === threads && messages > 1
119 ? `messages to ${quantity(threads, "thread")}`
120 : `${quantity(messages, "message")} to ${quantity(threads, "thread")}`
121 : quantity(messages, "message");
122 label = phrase("Sent", "send", object);
123 break;
124 }
125 case "thread-create": {
126 const createdIds: string[] = [];
127 const resultsKnown =
128 completed.length > 0 &&
129 completed.every((call) => {
130 const threads = Array.isArray(call.output?.threads) ? call.output.threads : [call.output];
131 return threads.every((thread) => {
132 const record = asRecord(thread);
133 if (record?.status === "rolled_back") return true;
134 const threadId = id(record?.threadId);
135 if (!threadId) return false;
136 createdIds.push(threadId);
137 return true;
138 });
139 });
140 label = resultsKnown
141 ? `Created ${quantity(new Set(createdIds).size, "thread")}`
142 : `Requested thread creation ${times}`;
143 break;
144 }
145 case "delegate":
146 label = phrase("Delegated", "delegate", quantity(countEntities(entityIds("taskId")), "task"));
147 break;
148 case "thread-read":
149 case "thread-wait": {
150 const targets = threadIds.every((value) => value !== undefined)
151 ? quantity(new Set(threadIds).size, "thread")
152 : `threads ${times}`;
153 label =
154 action === "thread-read"
155 ? phrase("Read", "read", targets)
156 : phrase("Waited on", "wait on", targets);
157 break;
158 }
159 case "thread-list":
160 label = phrase("Listed", "list", `threads ${times}`);
161 break;
162 case "thread-interrupt":
163 label = phrase(
164 "Requested interrupts for",
165 "interrupt",
166 quantity(countEntities(threadIds), "thread"),
167 );
168 break;
169 case "workflow-stop":
170 label = phrase(
171 "Requested stops for",
172 "stop",
173 quantity(countEntities(entityIds("subagentId")), "workflow"),
174 );
175 break;
176 case "task-status":
177 label = phrase("Checked", "check", `task status ${times}`);
178 break;
179 case "task-cancel":
180 label = phrase(
181 "Requested cancellation of",
182 "cancel",
183 quantity(countEntities(entityIds("taskId")), "task"),
184 );
185 break;
186 case "schedule-create":
187 label = phrase(
188 "Scheduled",
189 "schedule",
190 quantity(countEntities(entityIds("scheduledTaskId")), "task"),
191 );
192 break;
193 case "schedule-list":
194 label = phrase("Listed", "list", `scheduled tasks ${times}`);
195 break;
196 case "schedule-update":
197 label = phrase(
198 "Updated",
199 "update",
200 quantity(countEntities(entityIds("scheduledTaskId")), "scheduled task"),
201 );
202 break;
203 case "schedule-delete":
204 label = phrase(
205 "Requested deletion of",
206 "delete",
207 quantity(countEntities(entityIds("scheduledTaskId")), "scheduled task"),
208 );
209 break;
210 case "schedule-run":
211 label = phrase("Requested", "request", quantity(selected.length, "scheduled task run"));
212 break;
213 case "thread-configuration":
214 label = phrase("Checked", "check", `thread configuration ${times}`);
215 break;
216 case "thread-configure":
217 label = phrase("Set", "set", `thread model ${times}`);
218 break;
219 case "thread-fork":
220 label = phrase("Requested", "request", quantity(selected.length, "thread fork"));
221 break;
222 case "thread-merge":
223 label = phrase("Requested", "request", quantity(selected.length, "context merge"));
224 break;
225 case "thread-search":
226 label = phrase("Searched", "search", `threads ${times}`);
227 break;
228 case "thread-transfers":
229 label = phrase("Checked", "check", `thread transfers ${times}`);
230 break;
231 case "thread-organize":
232 label = phrase("Organized", "organize", `threads ${times}`);
233 break;
234 case "thread-update":
235 label = phrase("Updated", "update", quantity(countEntities(threadIds), "thread"));
236 break;
237 case "queue-list":
238 label = phrase("Listed", "list", `queued messages ${times}`);
239 break;
240 case "queue-read":
241 label = phrase(
242 "Read",
243 "read",
244 quantity(countEntities(entityIds("queuedRunId")), "queued message"),
245 );
246 break;
247 case "queue-edit":
248 label = phrase(
249 "Edited",
250 "edit",
251 quantity(countEntities(entityIds("queuedRunId")), "queued message"),
252 );
253 break;
254 case "queue-cancel":
255 label = phrase(
256 "Requested cancellation of",
257 "cancel",
258 quantity(countEntities(entityIds("queuedRunId")), "queued run"),
259 );
260 break;
261 case "queue-reorder":
262 label = phrase(
263 "Reordered",
264 "reorder",
265 quantity(countEntities(entityIds("queuedRunId")), "queued run"),
266 );
267 break;
268 case "queue-steer":
269 label = phrase(
270 "Requested steering with",
271 "steer with",
272 quantity(countEntities(entityIds("queuedRunId")), "queued message"),
273 );
274 break;
275 case "question-list":
276 label = phrase("Listed", "list", `pending questions ${times}`);
277 break;
278 case "question-read":
279 label = phrase(
280 "Read",
281 "read",
282 quantity(countEntities(entityIds("requestId")), "pending question request"),
283 );
284 break;
285 case "question-respond":
286 label = phrase(
287 "Answered",
288 "answer",
289 quantity(countEntities(entityIds("requestId")), "pending question request"),
290 );
291 break;
292 case "secret-request":
293 label = phrase("Asked for", "ask for", quantity(selected.length, "secret"));
294 break;
295 case "worktree-handoff":
296 label = phrase(
297 "Handed off to",
298 "hand off to",
299 quantity(countEntities(entityIds("worktreePath")), "worktree"),
300 );
301 break;
302 case "worktree-list":
303 label = phrase("Listed", "list", `workspace branches ${times}`);
304 break;
305 case "worktree-status":
306 label = phrase("Checked", "check", `worktree status ${times}`);
307 break;
308 case "project-list":
309 label = phrase("Listed", "list", `projects ${times}`);
310 break;
311 case "project-read":
312 label = phrase("Read", "read", quantity(countEntities(projectIds), "project"));
313 break;
314 case "project-create":
315 label = phrase("Registered", "register", quantity(countEntities(projectIds), "project"));
316 break;
317 case "project-update":
318 label = phrase("Updated", "update", quantity(countEntities(projectIds), "project"));
319 break;
320 case "project-delete":
321 label = phrase("Deleted", "delete", quantity(countEntities(projectIds), "project"));
322 break;
323 case "project-clone":
324 label = phrase(
325 "Cloned",
326 "clone",
327 quantity(countEntities(entityIds("cwd")), "repository", "repositories"),
328 );
329 break;
330 case "environment-read":
331 label = phrase("Checked", "check", `environment preferences ${times}`);
332 break;
333 case "environment-update":
334 label = phrase("Updated", "update", `environment preferences ${times}`);
335 break;
336 case "attachment-prepare":
337 label = phrase(
338 "Prepared",
339 "prepare",
340 quantity(countEntities(entityIds("attachmentId")), "attachment upload"),
341 );
342 break;
343 case "attachment-discard":
344 label = phrase(
345 "Discarded",
346 "discard",
347 quantity(countEntities(entityIds("attachmentId")), "pending attachment"),
348 );
349 break;
350 case "attachment-send": {
351 const messages = new Map<string, (typeof selected)[number]>();
352 selected.forEach((call, index) =>
353 messages.set(id(call.output?.messageId) ?? `call-${index}`, call),
354 );
355 const attachmentCount = [...messages.values()].reduce(
356 (count, call) =>
357 count + (Array.isArray(call.input?.attachments) ? call.input.attachments.length : 0),
358 0,
359 );
360 const countsKnown = [...messages.values()].every(
361 (call) => Array.isArray(call.input?.attachments) && call.input.attachments.length > 0,
362 );
363 const targets = threadIds.every((value) => value !== undefined)
364 ? ` to ${quantity(new Set(threadIds).size, "thread")}`
365 : "";
366 label = phrase(
367 "Sent",
368 "send",
369 countsKnown
370 ? `${quantity(attachmentCount, "attachment")}${targets}`
371 : `attachments${targets} ${times}`,
372 );
373 break;
374 }
375 case "link-pr":
376 label = phrase("Linked", "link", quantity(selected.length, "pull request"));
377 break;
378 case "unlink-pr":
379 label = phrase("Unlinked", "unlink", quantity(selected.length, "pull request"));
380 break;
381 case "watch-pr":
382 label = phrase("Watching", "watch", quantity(selected.length, "pull request"));
383 break;
384 case "unwatch-pr":
385 label = phrase(
386 "Stopped watching",
387 "stop watching",
388 quantity(selected.length, "pull request"),
389 );
390 break;
391 case "list-prs":
392 label = phrase(
393 "Checked",
394 "check",
395 `linked pull requests${selected.length === 1 ? "" : ` ${times}`}`,
396 );
397 break;
398 case "write-pr-guides": {
399 // One call writes many guides, and reports a refusal per guide rather than failing.
400 const outcomes = selected.flatMap((call) =>
401 Array.isArray(call.output?.guides)
402 ? call.output.guides.map((guide) => asRecord(guide)?.outcome)
403 : [],
404 );
405 const started = outcomes.filter((outcome) => outcome !== "failed").length;
406 const failed = outcomes.length - started;
407 failedCount += failed;
408 if (outcomes.length > 0 && started === 0) {
409 label = `Could not start ${quantity(failed, "review guide")}`;
410 } else {
411 label = phrase(
412 "Started",
413 "start",
414 outcomes.length === 0
415 ? `review guides ${times}`
416 : `${quantity(started, "review guide")}${failed > 0 ? `, ${failed} failed` : ""}`,
417 );
418 }
419 break;
420 }
421 case "read-pr-guide":
422 label = phrase("Read", "read", quantity(selected.length, "review guide"));
423 break;
424 case "browser":
425 label = phrase("Used", "use", `browser ${times}`);
426 break;
427 case "device":
428 label = phrase("Used", "use", `device controls ${times}`);
429 break;
430 case "html-preview":
431 label = phrase("Previewed", "preview", quantity(selected.length, "HTML page"));
432 break;
433 case "html-render":
434 label = phrase("Rendered", "render", quantity(selected.length, "HTML page"));
435 break;
436 case "capabilities":
437 label = phrase("Checked", "check", `orchestration capabilities ${times}`);
438 break;
439 }
440 return { label, failedCount };
441}