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

ToolFailures.ts

56 lines2.5 KB

1// The MCP result of a failed tool call keeps the failure's message and drops its code. So the
2// code travels beside the result: the handler leaves it in the call's cell for analytics, and the
3// latest one per thread and tool stays in memory for a feedback report to name.
4import { OrchestratorMcpFailure, type ThreadId } from "@t3tools/contracts";
5import * as Context from "effect/Context";
6import * as Layer from "effect/Layer";
7import * as Schema from "effect/Schema";
8​
9/** One tool call's declared failure code, written by its handler. */
10export const ToolCallFailure = Context.Reference<{ code?: string } | undefined>(
11 "t3/mcp/ToolCallFailure",
12 { defaultValue: () => undefined },
13);
14​
15const isOrchestratorFailure = Schema.is(OrchestratorMcpFailure);
16​
17/**
18 * A declared failure's closed code: the orchestrator's `code`, else the error's tag. Any other
19 * field can hold a value, so none is read.
20 */
21export const declaredFailureCode = (error: unknown) => {
22 if (isOrchestratorFailure(error)) return error.code;
23 const tag = typeof error === "object" && error !== null && "_tag" in error ? error._tag : null;
24 return typeof tag === "string" ? tag : undefined;
25};
26​
27/** How long after a tool failed a feedback report about that tool is taken to mean that failure. */
28export const TOOL_FAILURE_REPORT_WINDOW_MS = 10 * 60_000;
29const MAX_THREADS = 256;
30​
31const makeToolFailures = () => {
32 // Insertion order is recency, so the first key is the thread that failed longest ago.
33 const byThread = new Map<ThreadId, Map<string, { readonly code: string; readonly at: number }>>();
34 return {
35 note: (threadId: ThreadId, tool: string, code: string, at: number) => {
36 const tools = byThread.get(threadId) ?? new Map();
37 byThread.delete(threadId);
38 byThread.set(threadId, tools.set(tool, { code, at }));
39 if (byThread.size > MAX_THREADS) byThread.delete(byThread.keys().next().value!);
40 },
41 latest: (threadId: ThreadId, tool: string, now: number) => {
42 const failure = byThread.get(threadId)?.get(tool);
43 return failure !== undefined && now - failure.at <= TOOL_FAILURE_REPORT_WINDOW_MS
44 ? failure.code
45 : undefined;
46 },
47 };
48};
49​
50/** The latest failed call of each tool in each thread; remembers nothing without `layer`. */
51export const ToolFailures = Context.Reference<ReturnType<typeof makeToolFailures>>(
52 "t3/mcp/ToolFailures",
53 { defaultValue: () => ({ note: () => {}, latest: () => undefined }) },
54);
55​
56export const layer = Layer.sync(ToolFailures, makeToolFailures);