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