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

McpToolExposure.ts

157 lines5.1 KB

1import type { McpToolExposureMode } from "@t3tools/provider-core/server/mcpSession";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4​
5export const TOOL_SEARCH = "tool_search";
6export const TOOL_CALL = "tool_call";
7​
8/** What a deferring client lists before it searches. Pi's extension declares the same three. */
9const DIRECT_TOOLS: ReadonlySet<string> = new Set([
10 "orchestrator_capabilities",
11 "delegate_task",
12 "task_status",
13 TOOL_SEARCH,
14]);
15​
16const PROXY_DIRECT_TOOLS: ReadonlySet<string> = new Set([...DIRECT_TOOLS, TOOL_CALL]);
17​
18const MAX_RESULTS = 10;
19// Antigravity caps inline MCP tool results around 10 KB; stay comfortably under it so JSON schemas never truncate.
20const MAX_PROXY_SCHEMA_BYTES = 8_000;
21// Sessions that ended are never reported here, so keep only the newest.
22const MAX_SESSIONS = 256;
23​
24export interface ListedTool {
25 readonly name: string;
26 readonly description: string;
27 readonly inputSchema?: unknown;
29​
30export interface SearchableTool {
31 readonly name: string;
32 readonly description: string;
33 readonly inputSchema: unknown;
34 readonly isEnabled?: () => boolean;
36​
37export class McpToolExposure extends Context.Service<
38 McpToolExposure,
39 {
40 /** Finds tools for the query and, in dynamic mode, lists them to the session from now on. */
41 readonly search: (
42 providerSessionId: string,
43 query: string,
44 options?: { readonly mode?: McpToolExposureMode | undefined },
45 ) => Effect.Effect<ReadonlyArray<ListedTool>>;
46 readonly isListed: (
47 providerSessionId: string,
48 tool: string,
49 mode?: McpToolExposureMode,
50 ) => boolean;
51 }
52>()("t3/mcp/McpToolExposure") {}
53​
54const score = (
55 tool: Pick<SearchableTool, "name" | "description">,
56 terms: ReadonlyArray<string>,
57) => {
58 const name = tool.name.toLowerCase();
59 const description = tool.description.toLowerCase();
60 let total = 0;
61 for (const term of terms) {
62 if (term === name) total += 100;
63 else if (name.includes(term)) total += 3;
64 else if (description.includes(term)) total += 1;
65 }
66 return total;
67};
68​
69const utf8Bytes = (value: unknown): number => {
70 try {
71 return Buffer.byteLength(JSON.stringify(value) ?? "", "utf8");
72 } catch {
73 return Number.POSITIVE_INFINITY;
74 }
75};
76​
77export const make = (
78 tools: () => ReadonlyArray<SearchableTool>,
79 announceListChanged: () => Effect.Effect<void>,
80) => {
81 const loaded = new Map<string, Set<string>>();
82 const load = (providerSessionId: string, names: ReadonlyArray<string>) => {
83 const listed = loaded.get(providerSessionId) ?? new Set<string>();
84 loaded.delete(providerSessionId);
85 loaded.set(providerSessionId, listed);
86 for (const name of names) listed.add(name);
87 for (const oldest of loaded.keys()) {
88 if (loaded.size <= MAX_SESSIONS) break;
89 loaded.delete(oldest);
90 }
91 };
92 return McpToolExposure.of({
93 search: Effect.fn("McpToolExposure.search")(function* (providerSessionId, query, options) {
94 const terms = query
95 .toLowerCase()
96 .split(/[^a-z0-9_]+/u)
97 .filter(Boolean);
98 if (
99 options?.mode === "deferred-proxy" &&
100 terms.some((term) => term === "remind" || term === "reminder" || term === "reminders")
101 ) {
102 terms.push("schedule_task");
103 }
104 const found = tools()
105 .filter(
106 (tool) =>
107 tool.name !== TOOL_SEARCH &&
108 tool.name !== TOOL_CALL &&
109 (tool.isEnabled === undefined || tool.isEnabled()),
110 )
111 .map((tool) => ({ tool, score: score(tool, terms) }))
112 .filter((match) => match.score > 0)
113 .sort((a, b) => b.score - a.score)
114 .slice(0, MAX_RESULTS)
115 .map((match) => match.tool);
116 if (options?.mode === "deferred-proxy") {
117 const results: Array<ListedTool> = [];
118 for (const tool of found) {
119 const withSchema: ListedTool = {
120 name: tool.name,
121 description: tool.description,
122 inputSchema: tool.inputSchema,
123 };
124 if (utf8Bytes({ tools: [...results, withSchema] }) <= MAX_PROXY_SCHEMA_BYTES) {
125 results.push(withSchema);
126 continue;
127 }
128 const compact: ListedTool = { name: tool.name, description: tool.description };
129 if (utf8Bytes({ tools: [...results, compact] }) <= MAX_PROXY_SCHEMA_BYTES) {
130 results.push(compact);
131 continue;
132 }
133 if (results.length === 0) {
134 results.push({
135 name: tool.name,
136 description: `${tool.description.slice(0, 200)} (Truncated: exceeds response budget.)`,
137 });
138 }
139 break;
140 }
141 return results;
142 }
143 if (found.length > 0) {
144 load(
145 providerSessionId,
146 found.map((tool) => tool.name),
147 );
148 yield* announceListChanged();
149 }
150 return found.map(({ name, description }) => ({ name, description }));
151 }),
152 isListed: (providerSessionId, tool, mode = "deferred") =>
153 mode === "deferred-proxy"
154 ? PROXY_DIRECT_TOOLS.has(tool)
155 : DIRECT_TOOLS.has(tool) || loaded.get(providerSessionId)?.has(tool) === true,
156 });
157};