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 // Historical Cursor items retain the MCP args envelope.
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 "background-wait":
180 label = phrase("Updated", "update", `background waits ${times}`);
181 break;
182 case "task-cancel":
183 label = phrase(
184 "Requested cancellation of",
185 "cancel",
186 quantity(countEntities(entityIds("taskId")), "task"),
187 );
188 break;
189 case "schedule-create":
190 label = phrase(
191 "Scheduled",
192 "schedule",
193 quantity(countEntities(entityIds("scheduledTaskId")), "task"),
194 );
195 break;
196 case "schedule-list":
197 label = phrase("Listed", "list", `scheduled tasks ${times}`);
198 break;
199 case "schedule-update":
200 label = phrase(
201 "Updated",
202 "update",
203 quantity(countEntities(entityIds("scheduledTaskId")), "scheduled task"),
204 );
205 break;
206 case "schedule-delete":
207 label = phrase(
208 "Requested deletion of",
209 "delete",
210 quantity(countEntities(entityIds("scheduledTaskId")), "scheduled task"),
211 );
212 break;
213 case "schedule-run":
214 label = phrase("Requested", "request", quantity(selected.length, "scheduled task run"));
215 break;
216 case "thread-configuration":
217 label = phrase("Checked", "check", `thread configuration ${times}`);
218 break;
219 case "thread-configure":
220 label = phrase("Set", "set", `thread model ${times}`);
221 break;
222 case "thread-fork":
223 label = phrase("Requested", "request", quantity(selected.length, "thread fork"));
224 break;
225 case "thread-merge":
226 label = phrase("Requested", "request", quantity(selected.length, "context merge"));
227 break;
228 case "thread-search":
229 label = phrase("Searched", "search", `threads ${times}`);
230 break;
231 case "thread-transfers":
232 label = phrase("Checked", "check", `thread transfers ${times}`);
233 break;
234 case "thread-organize":
235 label = phrase("Organized", "organize", `threads ${times}`);
236 break;
237 case "thread-update":
238 label = phrase("Updated", "update", quantity(countEntities(threadIds), "thread"));
239 break;
240 case "queue-list":
241 label = phrase("Listed", "list", `queued messages ${times}`);
242 break;
243 case "queue-read":
244 label = phrase(
245 "Read",
246 "read",
247 quantity(countEntities(entityIds("queuedRunId")), "queued message"),
248 );
249 break;
250 case "queue-edit":
251 label = phrase(
252 "Edited",
253 "edit",
254 quantity(countEntities(entityIds("queuedRunId")), "queued message"),
255 );
256 break;
257 case "queue-cancel":
258 label = phrase(
259 "Requested cancellation of",
260 "cancel",
261 quantity(countEntities(entityIds("queuedRunId")), "queued run"),
262 );
263 break;
264 case "queue-reorder":
265 label = phrase(
266 "Reordered",
267 "reorder",
268 quantity(countEntities(entityIds("queuedRunId")), "queued run"),
269 );
270 break;
271 case "queue-steer":
272 label = phrase(
273 "Requested steering with",
274 "steer with",
275 quantity(countEntities(entityIds("queuedRunId")), "queued message"),
276 );
277 break;
278 case "question-list":
279 label = phrase("Listed", "list", `pending questions ${times}`);
280 break;
281 case "question-read":
282 label = phrase(
283 "Read",
284 "read",
285 quantity(countEntities(entityIds("requestId")), "pending question request"),
286 );
287 break;
288 case "question-respond":
289 label = phrase(
290 "Answered",
291 "answer",
292 quantity(countEntities(entityIds("requestId")), "pending question request"),
293 );
294 break;
295 case "secret-request":
296 label = phrase("Asked for", "ask for", quantity(selected.length, "secret"));
297 break;
298 case "worktree-handoff":
299 label = phrase(
300 "Handed off to",
301 "hand off to",
302 quantity(countEntities(entityIds("worktreePath")), "worktree"),
303 );
304 break;
305 case "worktree-list":
306 label = phrase("Listed", "list", `workspace branches ${times}`);
307 break;
308 case "worktree-status":
309 label = phrase("Checked", "check", `worktree status ${times}`);
310 break;
311 case "project-list":
312 label = phrase("Listed", "list", `projects ${times}`);
313 break;
314 case "project-read":
315 label = phrase("Read", "read", quantity(countEntities(projectIds), "project"));
316 break;
317 case "project-create":
318 label = phrase("Registered", "register", quantity(countEntities(projectIds), "project"));
319 break;
320 case "project-update":
321 label = phrase("Updated", "update", quantity(countEntities(projectIds), "project"));
322 break;
323 case "project-delete":
324 label = phrase("Deleted", "delete", quantity(countEntities(projectIds), "project"));
325 break;
326 case "project-clone":
327 label = phrase(
328 "Cloned",
329 "clone",
330 quantity(countEntities(entityIds("cwd")), "repository", "repositories"),
331 );
332 break;
333 case "environment-read":
334 label = phrase("Checked", "check", `environment preferences ${times}`);
335 break;
336 case "environment-update":
337 label = phrase("Updated", "update", `environment preferences ${times}`);
338 break;
339 case "attachment-prepare":
340 label = phrase(
341 "Prepared",
342 "prepare",
343 quantity(countEntities(entityIds("attachmentId")), "attachment upload"),
344 );
345 break;
346 case "attachment-discard":
347 label = phrase(
348 "Discarded",
349 "discard",
350 quantity(countEntities(entityIds("attachmentId")), "pending attachment"),
351 );
352 break;
353 case "attachment-send": {
354 const messages = new Map<string, (typeof selected)[number]>();
355 selected.forEach((call, index) =>
356 messages.set(id(call.output?.messageId) ?? `call-${index}`, call),
357 );
358 const attachmentCount = [...messages.values()].reduce(
359 (count, call) =>
360 count + (Array.isArray(call.input?.attachments) ? call.input.attachments.length : 0),
361 0,
362 );
363 const countsKnown = [...messages.values()].every(
364 (call) => Array.isArray(call.input?.attachments) && call.input.attachments.length > 0,
365 );
366 const targets = threadIds.every((value) => value !== undefined)
367 ? ` to ${quantity(new Set(threadIds).size, "thread")}`
368 : "";
369 label = phrase(
370 "Sent",
371 "send",
372 countsKnown
373 ? `${quantity(attachmentCount, "attachment")}${targets}`
374 : `attachments${targets} ${times}`,
375 );
376 break;
377 }
378 case "link-pr":
379 label = phrase("Linked", "link", quantity(selected.length, "pull request"));
380 break;
381 case "unlink-pr":
382 label = phrase("Unlinked", "unlink", quantity(selected.length, "pull request"));
383 break;
384 case "watch-pr":
385 label = phrase("Watching", "watch", quantity(selected.length, "pull request"));
386 break;
387 case "unwatch-pr":
388 label = phrase(
389 "Stopped watching",
390 "stop watching",
391 quantity(selected.length, "pull request"),
392 );
393 break;
394 case "list-prs":
395 label = phrase(
396 "Checked",
397 "check",
398 `linked pull requests${selected.length === 1 ? "" : ` ${times}`}`,
399 );
400 break;
401 case "write-pr-guides": {
402 // One call writes many guides, and reports a refusal per guide rather than failing.
403 const outcomes = selected.flatMap((call) =>
404 Array.isArray(call.output?.guides)
405 ? call.output.guides.map((guide) => asRecord(guide)?.outcome)
406 : [],
407 );
408 const started = outcomes.filter((outcome) => outcome !== "failed").length;
409 const failed = outcomes.length - started;
410 failedCount += failed;
411 if (outcomes.length === 0) {
412 label = phrase(
413 "Started writing",
414 "start writing",
415 `review guides${selected.length === 1 ? "" : ` ${times}`}`,
416 );
417 } else if (started === 0) {
418 label = `Could not start ${quantity(failed, "review guide")}`;
419 } else {
420 label = phrase(
421 "Started",
422 "start",
423 `${quantity(started, "review guide")}${failed > 0 ? `, ${failed} failed` : ""}`,
424 );
425 }
426 break;
427 }
428 case "read-pr-guide":
429 label = phrase("Read", "read", quantity(selected.length, "review guide"));
430 break;
431 case "browser":
432 label = phrase("Used", "use", `browser ${times}`);
433 break;
434 case "device":
435 label = phrase("Used", "use", `device controls ${times}`);
436 break;
437 case "html-preview":
438 label = phrase("Previewed", "preview", quantity(selected.length, "HTML page"));
439 break;
440 case "html-render":
441 label = phrase("Rendered", "render", quantity(selected.length, "HTML page"));
442 break;
443 case "capabilities":
444 label = phrase("Checked", "check", `orchestration capabilities ${times}`);
445 break;
446 }
447 return { label, failedCount };
448}