Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

t3ToolSummary.ts

190 lines6.8 KB

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;
14​
15function id(value: unknown): string | undefined {
16 return typeof value === "string" && value.trim() !== "" ? value : undefined;
18​
19interface ToolResult {
20 readonly data?: Record<string, unknown>;
21 readonly failed: boolean;
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 text = asRecord(block)?.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 record._tag === "OrchestratorMcpFailure" ||
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 };
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;
65​
66function countEntities(ids: ReadonlyArray<string | undefined>): number {
67 return (
68 new Set(ids.filter((value) => value !== undefined)).size +
69 ids.filter((value) => value === undefined).length
70 );
72​
73function quantity(count: number, noun: string): string {
74 return `${count} ${noun}${count === 1 ? "" : "s"}`;
76​
77/** Counts successful effects separately from failed or unfinished tool calls. */
78export function summarizeT3ToolCalls(
79 action: T3McpToolSummaryAction,
80 calls: ReadonlyArray<T3ToolSummaryCall>,
81): { label: string; failedCount: number } {
82 const results = calls.map((call) => {
83 const result = readResult(call.output);
84 return {
85 input: readInput(call.input),
86 output: result.data,
87 outcome: result.failed ? ("failed" as const) : call.outcome,
88 };
89 });
90 const completed = results.filter((call) => call.outcome === "completed");
91 const failedCount = results.filter((call) => call.outcome === "failed").length;
92 const selected = completed.length > 0 ? completed : results;
93 const times = quantity(selected.length, "time");
94 const phrase = (past: string, infinitive: string, object: string) =>
95 `${completed.length > 0 ? past : `Tried to ${infinitive}`} ${object}`;
96 const entityIds = (key: string) =>
97 selected.map((call) => id(call.output?.[key]) ?? id(call.input?.[key]));
98 const threadIds = selected.map(
99 (call) =>
100 id(call.output?.threadId) ??
101 id(asRecord(call.output?.thread)?.threadId) ??
102 id(call.input?.threadId),
103 );
104 let label: string;
105 switch (action) {
106 case "thread-send": {
107 const messages = countEntities(selected.map((call) => id(call.output?.messageId)));
108 const targetsKnown = threadIds.every((value) => value !== undefined);
109 const threads = new Set(threadIds).size;
110 const object = targetsKnown
111 ? messages === threads && messages > 1
112 ? `messages to ${quantity(threads, "thread")}`
113 : `${quantity(messages, "message")} to ${quantity(threads, "thread")}`
114 : quantity(messages, "message");
115 label = phrase("Sent", "send", object);
116 break;
117 }
118 case "thread-create": {
119 const createdIds: string[] = [];
120 const resultsKnown =
121 completed.length > 0 &&
122 completed.every((call) => {
123 const threads = Array.isArray(call.output?.threads) ? call.output.threads : [call.output];
124 return threads.every((thread) => {
125 const record = asRecord(thread);
126 if (record?.status === "rolled_back") return true;
127 const threadId = id(record?.threadId);
128 if (!threadId) return false;
129 createdIds.push(threadId);
130 return true;
131 });
132 });
133 label = resultsKnown
134 ? `Created ${quantity(new Set(createdIds).size, "thread")}`
135 : `Requested thread creation ${times}`;
136 break;
137 }
138 case "delegate":
139 label = phrase("Delegated", "delegate", quantity(countEntities(entityIds("taskId")), "task"));
140 break;
141 case "thread-read":
142 case "thread-wait": {
143 const targets = threadIds.every((value) => value !== undefined)
144 ? quantity(new Set(threadIds).size, "thread")
145 : `threads ${times}`;
146 label =
147 action === "thread-read"
148 ? phrase("Read", "read", targets)
149 : phrase("Waited on", "wait on", targets);
150 break;
151 }
152 case "thread-list":
153 label = phrase("Listed", "list", `threads ${times}`);
154 break;
155 case "thread-interrupt":
156 label = `Requested interrupts for ${quantity(countEntities(threadIds), "thread")}`;
157 break;
158 case "task-status":
159 label = phrase("Checked", "check", `task status ${times}`);
160 break;
161 case "task-cancel":
162 label = `Requested cancellation of ${quantity(countEntities(entityIds("taskId")), "task")}`;
163 break;
164 case "schedule-create":
165 label = phrase(
166 "Scheduled",
167 "schedule",
168 quantity(countEntities(entityIds("scheduledTaskId")), "task"),
169 );
170 break;
171 case "schedule-list":
172 label = phrase("Listed", "list", `scheduled tasks ${times}`);
173 break;
174 case "schedule-update":
175 label = phrase(
176 "Updated",
177 "update",
178 quantity(countEntities(entityIds("scheduledTaskId")), "scheduled task"),
179 );
180 break;
181 case "schedule-delete":
182 // A successful delete can report deleted:false; it still represents a deletion request.
183 label = `Requested deletion of ${quantity(countEntities(entityIds("scheduledTaskId")), "scheduled task")}`;
184 break;
185 case "capabilities":
186 label = phrase("Checked", "check", `orchestration capabilities ${times}`);
187 break;
188 }
189 return { label, failedCount };