@mcp-ts/sdk 1.6.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -6
- package/dist/adapters/agui-adapter.d.mts +3 -3
- package/dist/adapters/agui-adapter.d.ts +3 -3
- package/dist/adapters/agui-adapter.js +4 -5
- package/dist/adapters/agui-adapter.js.map +1 -1
- package/dist/adapters/agui-adapter.mjs +4 -5
- package/dist/adapters/agui-adapter.mjs.map +1 -1
- package/dist/adapters/agui-middleware.d.mts +3 -3
- package/dist/adapters/agui-middleware.d.ts +3 -3
- package/dist/adapters/ai-adapter.d.mts +9 -3
- package/dist/adapters/ai-adapter.d.ts +9 -3
- package/dist/adapters/ai-adapter.js +20 -6
- package/dist/adapters/ai-adapter.js.map +1 -1
- package/dist/adapters/ai-adapter.mjs +20 -6
- package/dist/adapters/ai-adapter.mjs.map +1 -1
- package/dist/adapters/langchain-adapter.d.mts +3 -3
- package/dist/adapters/langchain-adapter.d.ts +3 -3
- package/dist/adapters/langchain-adapter.js +9 -6
- package/dist/adapters/langchain-adapter.js.map +1 -1
- package/dist/adapters/langchain-adapter.mjs +9 -6
- package/dist/adapters/langchain-adapter.mjs.map +1 -1
- package/dist/adapters/mastra-adapter.d.mts +1 -1
- package/dist/adapters/mastra-adapter.d.ts +1 -1
- package/dist/adapters/mastra-adapter.js +5 -1
- package/dist/adapters/mastra-adapter.js.map +1 -1
- package/dist/adapters/mastra-adapter.mjs +5 -1
- package/dist/adapters/mastra-adapter.mjs.map +1 -1
- package/dist/bin/mcp-ts.js +7 -1
- package/dist/bin/mcp-ts.js.map +1 -1
- package/dist/bin/mcp-ts.mjs +7 -1
- package/dist/bin/mcp-ts.mjs.map +1 -1
- package/dist/client/index.d.mts +2 -2
- package/dist/client/index.d.ts +2 -2
- package/dist/client/index.js +9 -13
- package/dist/client/index.js.map +1 -1
- package/dist/client/index.mjs +9 -13
- package/dist/client/index.mjs.map +1 -1
- package/dist/client/react.d.mts +7 -7
- package/dist/client/react.d.ts +7 -7
- package/dist/client/react.js +111 -63
- package/dist/client/react.js.map +1 -1
- package/dist/client/react.mjs +111 -63
- package/dist/client/react.mjs.map +1 -1
- package/dist/client/vue.d.mts +7 -7
- package/dist/client/vue.d.ts +7 -7
- package/dist/client/vue.js +14 -18
- package/dist/client/vue.js.map +1 -1
- package/dist/client/vue.mjs +14 -18
- package/dist/client/vue.mjs.map +1 -1
- package/dist/{index-DhA-OEAe.d.ts → index-C9gvpxy5.d.ts} +5 -5
- package/dist/{index-bFL4ZF2N.d.mts → index-eaH14_5u.d.mts} +5 -5
- package/dist/index.d.mts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +616 -370
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +615 -370
- package/dist/index.mjs.map +1 -1
- package/dist/{multi-session-client-CHE8QpVE.d.ts → multi-session-client-BYtguGJm.d.ts} +22 -22
- package/dist/{multi-session-client-CQsRbxYI.d.mts → multi-session-client-DYNe6az3.d.mts} +22 -22
- package/dist/server/index.d.mts +31 -34
- package/dist/server/index.d.ts +31 -34
- package/dist/server/index.js +531 -256
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.mjs +530 -256
- package/dist/server/index.mjs.map +1 -1
- package/dist/shared/index.d.mts +5 -5
- package/dist/shared/index.d.ts +5 -5
- package/dist/shared/index.js +76 -101
- package/dist/shared/index.js.map +1 -1
- package/dist/shared/index.mjs +76 -101
- package/dist/shared/index.mjs.map +1 -1
- package/dist/{tool-router-Dh2804tM.d.ts → tool-router-Ddtybmr0.d.ts} +71 -73
- package/dist/{tool-router-BVaV1udm.d.mts → tool-router-Dnd6IOKC.d.mts} +71 -73
- package/dist/{types-rIuN1CQi.d.mts → types-BCAG20P6.d.mts} +4 -4
- package/dist/{types-rIuN1CQi.d.ts → types-BCAG20P6.d.ts} +4 -4
- package/dist/{utils-0qmYrqoa.d.mts → utils-DELRKQPU.d.mts} +1 -1
- package/dist/{utils-0qmYrqoa.d.ts → utils-DELRKQPU.d.ts} +1 -1
- package/migrations/neon/20260513010000_install_mcp_sessions.sql +69 -0
- package/migrations/neon/20260513020000_add_session_cleanup_cron.sql +35 -0
- package/{supabase/migrations → migrations/supabase}/20260330195700_install_mcp_sessions.sql +7 -9
- package/package.json +14 -5
- package/src/adapters/ai-adapter.ts +30 -1
- package/src/adapters/langchain-adapter.ts +6 -2
- package/src/adapters/mastra-adapter.ts +6 -2
- package/src/bin/mcp-ts.ts +8 -1
- package/src/client/core/app-host.ts +1 -1
- package/src/client/core/sse-client.ts +12 -14
- package/src/client/core/types.ts +1 -1
- package/src/client/react/oauth-popup.tsx +111 -51
- package/src/client/react/use-mcp-apps.tsx +1 -1
- package/src/client/react/use-mcp.ts +11 -11
- package/src/client/vue/use-mcp.ts +10 -10
- package/src/server/handlers/nextjs-handler.ts +18 -15
- package/src/server/handlers/sse-handler.ts +29 -29
- package/src/server/index.ts +1 -1
- package/src/server/mcp/multi-session-client.ts +17 -17
- package/src/server/mcp/oauth-client.ts +37 -37
- package/src/server/mcp/storage-oauth-provider.ts +17 -17
- package/src/server/storage/file-backend.ts +25 -25
- package/src/server/storage/index.ts +67 -10
- package/src/server/storage/memory-backend.ts +34 -34
- package/src/server/storage/neon-backend.ts +281 -0
- package/src/server/storage/redis-backend.ts +64 -64
- package/src/server/storage/sqlite-backend.ts +33 -33
- package/src/server/storage/supabase-backend.ts +23 -24
- package/src/server/storage/types.ts +18 -21
- package/src/shared/errors.ts +1 -1
- package/src/shared/index.ts +1 -2
- package/src/shared/meta-tools.ts +4 -6
- package/src/shared/schema-compressor.ts +2 -42
- package/src/shared/tool-index.ts +89 -84
- package/src/shared/tool-router.ts +0 -24
- package/src/shared/types.ts +4 -4
- /package/{supabase/migrations → migrations/supabase}/20260421010000_add_session_cleanup_cron.sql +0 -0
|
@@ -2,13 +2,13 @@ import { Observable } from 'rxjs';
|
|
|
2
2
|
import { Middleware, RunAgentInput, AbstractAgent, BaseEvent } from '@ag-ui/client';
|
|
3
3
|
export { AbstractAgent, BaseEvent, EventType, Middleware, RunAgentInput, Tool, ToolCallEndEvent } from '@ag-ui/client';
|
|
4
4
|
import { AguiTool } from './agui-adapter.mjs';
|
|
5
|
-
import '../multi-session-client-
|
|
5
|
+
import '../multi-session-client-DYNe6az3.mjs';
|
|
6
6
|
import '../events-CK3N--3g.mjs';
|
|
7
7
|
import '@modelcontextprotocol/sdk/types.js';
|
|
8
8
|
import '@modelcontextprotocol/sdk/client/auth.js';
|
|
9
9
|
import '@modelcontextprotocol/sdk/shared/auth.js';
|
|
10
|
-
import '../tool-router-
|
|
11
|
-
import '../types-
|
|
10
|
+
import '../tool-router-Dnd6IOKC.mjs';
|
|
11
|
+
import '../types-BCAG20P6.mjs';
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
14
|
* AG-UI Middleware for MCP Tool Execution
|
|
@@ -2,13 +2,13 @@ import { Observable } from 'rxjs';
|
|
|
2
2
|
import { Middleware, RunAgentInput, AbstractAgent, BaseEvent } from '@ag-ui/client';
|
|
3
3
|
export { AbstractAgent, BaseEvent, EventType, Middleware, RunAgentInput, Tool, ToolCallEndEvent } from '@ag-ui/client';
|
|
4
4
|
import { AguiTool } from './agui-adapter.js';
|
|
5
|
-
import '../multi-session-client-
|
|
5
|
+
import '../multi-session-client-BYtguGJm.js';
|
|
6
6
|
import '../events-CK3N--3g.js';
|
|
7
7
|
import '@modelcontextprotocol/sdk/types.js';
|
|
8
8
|
import '@modelcontextprotocol/sdk/client/auth.js';
|
|
9
9
|
import '@modelcontextprotocol/sdk/shared/auth.js';
|
|
10
|
-
import '../tool-router-
|
|
11
|
-
import '../types-
|
|
10
|
+
import '../tool-router-Ddtybmr0.js';
|
|
11
|
+
import '../types-BCAG20P6.js';
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
14
|
* AG-UI Middleware for MCP Tool Execution
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { M as MCPClient, a as MultiSessionClient } from '../multi-session-client-
|
|
1
|
+
import { M as MCPClient, a as MultiSessionClient } from '../multi-session-client-DYNe6az3.mjs';
|
|
2
2
|
import { ToolSet } from 'ai';
|
|
3
|
-
import {
|
|
3
|
+
import { d as ToolRouter } from '../tool-router-Dnd6IOKC.mjs';
|
|
4
4
|
import '../events-CK3N--3g.mjs';
|
|
5
5
|
import '@modelcontextprotocol/sdk/types.js';
|
|
6
6
|
import '@modelcontextprotocol/sdk/client/auth.js';
|
|
7
7
|
import '@modelcontextprotocol/sdk/shared/auth.js';
|
|
8
|
-
import '../types-
|
|
8
|
+
import '../types-BCAG20P6.mjs';
|
|
9
9
|
|
|
10
10
|
interface AIAdapterOptions {
|
|
11
11
|
/**
|
|
@@ -23,6 +23,12 @@ interface AIAdapterOptions {
|
|
|
23
23
|
* When not provided, all tools are returned as before (backward-compatible).
|
|
24
24
|
*/
|
|
25
25
|
toolRouter?: ToolRouter;
|
|
26
|
+
/**
|
|
27
|
+
* Optional custom callback to determine if a tool requires user approval.
|
|
28
|
+
* Can return a boolean or a Promise<boolean>.
|
|
29
|
+
* If not provided, defaults to checking the tool's `destructiveHint` annotation.
|
|
30
|
+
*/
|
|
31
|
+
needsApproval?: (tool: any, args: any) => boolean | Promise<boolean>;
|
|
26
32
|
}
|
|
27
33
|
/**
|
|
28
34
|
* Adapter to use MCP tools with the Vercel AI SDK.
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { M as MCPClient, a as MultiSessionClient } from '../multi-session-client-
|
|
1
|
+
import { M as MCPClient, a as MultiSessionClient } from '../multi-session-client-BYtguGJm.js';
|
|
2
2
|
import { ToolSet } from 'ai';
|
|
3
|
-
import {
|
|
3
|
+
import { d as ToolRouter } from '../tool-router-Ddtybmr0.js';
|
|
4
4
|
import '../events-CK3N--3g.js';
|
|
5
5
|
import '@modelcontextprotocol/sdk/types.js';
|
|
6
6
|
import '@modelcontextprotocol/sdk/client/auth.js';
|
|
7
7
|
import '@modelcontextprotocol/sdk/shared/auth.js';
|
|
8
|
-
import '../types-
|
|
8
|
+
import '../types-BCAG20P6.js';
|
|
9
9
|
|
|
10
10
|
interface AIAdapterOptions {
|
|
11
11
|
/**
|
|
@@ -23,6 +23,12 @@ interface AIAdapterOptions {
|
|
|
23
23
|
* When not provided, all tools are returned as before (backward-compatible).
|
|
24
24
|
*/
|
|
25
25
|
toolRouter?: ToolRouter;
|
|
26
|
+
/**
|
|
27
|
+
* Optional custom callback to determine if a tool requires user approval.
|
|
28
|
+
* Can return a boolean or a Promise<boolean>.
|
|
29
|
+
* If not provided, defaults to checking the tool's `destructiveHint` annotation.
|
|
30
|
+
*/
|
|
31
|
+
needsApproval?: (tool: any, args: any) => boolean | Promise<boolean>;
|
|
26
32
|
}
|
|
27
33
|
/**
|
|
28
34
|
* Adapter to use MCP tools with the Vercel AI SDK.
|
|
@@ -80,7 +80,7 @@ async function executeMetaTool(toolName, args, router, callToolFn) {
|
|
|
80
80
|
const lines = [];
|
|
81
81
|
if (found.length > 0) {
|
|
82
82
|
lines.push(...found.map(
|
|
83
|
-
(t, i) => `${i + 1}. **${t.name}** (
|
|
83
|
+
(t, i) => `${i + 1}. **${t.name}** (serverName: ${t.serverName}, serverId: ${t.serverId})
|
|
84
84
|
${t.description}`
|
|
85
85
|
));
|
|
86
86
|
}
|
|
@@ -108,7 +108,7 @@ async function executeMetaTool(toolName, args, router, callToolFn) {
|
|
|
108
108
|
serverName: query || void 0
|
|
109
109
|
});
|
|
110
110
|
const text = servers.length === 0 ? "No connected servers found." : servers.map(
|
|
111
|
-
(server, i) => `${i + 1}. **${server.serverName}** (serverId: ${server.serverId}
|
|
111
|
+
(server, i) => `${i + 1}. **${server.serverName}** (serverId: ${server.serverId})
|
|
112
112
|
Tool count: ${server.toolCount}`
|
|
113
113
|
).join("\n");
|
|
114
114
|
return {
|
|
@@ -215,9 +215,8 @@ async function executeMetaTool(toolName, args, router, callToolFn) {
|
|
|
215
215
|
}
|
|
216
216
|
function formatToolSummaries(tools) {
|
|
217
217
|
return tools.map(
|
|
218
|
-
(t, i) => `${i + 1}. **${t.name}** (
|
|
219
|
-
${t.description}
|
|
220
|
-
Estimated tokens: ${t.estimatedTokens}`
|
|
218
|
+
(t, i) => `${i + 1}. **${t.name}** (serverName: ${t.serverName}, serverId: ${t.serverId})
|
|
219
|
+
${t.description}`
|
|
221
220
|
);
|
|
222
221
|
}
|
|
223
222
|
function isMetaTool(toolName) {
|
|
@@ -263,7 +262,8 @@ var AIAdapter = class _AIAdapter {
|
|
|
263
262
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
264
263
|
throw new Error(`Tool execution failed: ${errorMessage}`);
|
|
265
264
|
}
|
|
266
|
-
}
|
|
265
|
+
},
|
|
266
|
+
needsApproval: this.options.needsApproval ? (args) => this.options.needsApproval(tool, args) : tool.annotations?.destructiveHint === true ? () => true : void 0
|
|
267
267
|
}
|
|
268
268
|
];
|
|
269
269
|
})
|
|
@@ -324,6 +324,20 @@ var AIAdapter = class _AIAdapter {
|
|
|
324
324
|
}
|
|
325
325
|
}
|
|
326
326
|
return await router.callTool(tool.name, args, namespace);
|
|
327
|
+
},
|
|
328
|
+
needsApproval: this.options.needsApproval ? (args) => this.options.needsApproval(tool, args) : (args) => {
|
|
329
|
+
if (tool.name === "mcp_execute_tool") {
|
|
330
|
+
const targetToolName = String(args?.toolName ?? "");
|
|
331
|
+
const targetNamespace = String(args?.serverId ?? "") || void 0;
|
|
332
|
+
if (!targetToolName) return false;
|
|
333
|
+
try {
|
|
334
|
+
const targetTool = router.getToolSchema(targetToolName, targetNamespace);
|
|
335
|
+
return targetTool?.annotations?.destructiveHint === true;
|
|
336
|
+
} catch {
|
|
337
|
+
return false;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return tool.annotations?.destructiveHint === true;
|
|
327
341
|
}
|
|
328
342
|
}
|
|
329
343
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/shared/meta-tools.ts","../../src/adapters/ai-adapter.ts"],"names":["limit","text"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M,UAAU,eAAe;AAAA,iBACxF;AACA,gBAAA,IAAI,MAAA,EAAQ;AACV,kBAAA,OAAO,MAAA;AAAA,gBACT;AAAA,cACJ;AAIA,cAAA,OAAO,MAAM,MAAA,CAAO,QAAA,CAAS,IAAA,CAAK,IAAA,EAAM,MAAM,SAAS,CAAA;AAAA,YAC3D;AAAA;AACJ,SACJ;AAAA,MACJ,CAAC;AAAA,KACL;AAAA,EACJ;AAAA,EAEQ,gBAAA,CAAiB,QAAA,EAAkB,SAAA,EAAoB,QAAA,EAA2B;AACtF,IAAA,MAAM,SAAA,GAAY,aAAa,QAAA,IAAY,KAAA;AAC3C,IAAA,MAAM,UAAA,GAAa,SAAA,CACd,WAAA,EAAY,CACZ,OAAA,CAAQ,aAAA,EAAe,GAAG,CAAA,CAC1B,OAAA,CAAQ,UAAA,EAAY,EAAE,CAAA,IAAK,KAAA;AAChC,IAAA,OAAO,CAAA,KAAA,EAAQ,UAAU,CAAA,CAAA,EAAI,QAAQ,CAAA,CAAA;AAAA,EACzC;AAAA;AAAA;AAAA;AAAA,EAKA,aAAa,QAAA,CAAS,MAAA,EAAwC,OAAA,GAA4B,EAAC,EAAqB;AAC5G,IAAA,OAAO,IAAI,UAAA,CAAU,MAAA,EAAQ,OAAO,EAAE,QAAA,EAAS;AAAA,EACnD;AACJ","file":"ai-adapter.js","sourcesContent":["/**\n * Meta-tools — Injectable tool definitions that let the LLM discover and\n * load MCP tools on-demand, following Anthropic's Tool Search pattern.\n *\n * Instead of injecting 50+ full tool schemas into the context window, you\n * inject just these 4 meta-tools. The LLM calls them to find and load\n * only the tools it actually needs.\n *\n * Meta-tools:\n * • `mcp_search_tools` — Search/list available tools\n * • `mcp_search_tool_regex` — Regex pattern search\n * • `mcp_get_tool_schema` — Get full inputSchema for a discovered tool\n * • `mcp_execute_tool` — Execute a discovered tool\n *\n * @packageDocumentation\n */\n\nimport type { Tool, CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolRouter } from './tool-router.js';\nimport type { IndexedTool, ToolLookupOptions } from './tool-index.js';\n\n// ---------------------------------------------------------------------------\n// Tool Definitions\n// ---------------------------------------------------------------------------\n\n/**\n * Creates the `mcp_search_tools` tool definition.\n *\n * This tool lets the LLM search the full catalog of available MCP tools\n * using a BM25 natural-language query. Returns tool names and descriptions\n * without the full inputSchema to save context space.\n */\nexport function createSearchToolDefinition(): Tool {\n return {\n name: 'mcp_search_tools',\n description:\n 'Search the catalog of available tools. Returns tool names, descriptions, and server info. ' +\n 'Use this FIRST to find relevant tools before calling them.\\n\\n' +\n 'Query forms:\\n' +\n '- \"select:Read,Edit,Grep\" — fetch these exact tools by name\\n' +\n '- \"notebook jupyter\" — keyword search, up to limit best matches\\n' +\n '- \"+slack send\" — require \"slack\" in the name, rank by remaining terms',\n inputSchema: {\n type: 'object' as const,\n properties: {\n query: {\n type: 'string',\n description: 'Query to find tools. Use \"select:<tool_name>\" for direct selection, or keywords to search. Prefix keywords with + to require them.',\n },\n operation: {\n type: 'string',\n enum: ['search', 'list'],\n description:\n 'Operation to perform. Use \"search\" to find relevant tools by capability. Use \"list\" with serverId or serverName when the user asks for every tool from a connected MCP server.',\n },\n serverId: {\n type: 'string',\n description: 'Optional server ID to restrict search/list results to one MCP server.',\n },\n serverName: {\n type: 'string',\n description:\n 'Optional server name fragment to restrict search/list results to matching MCP servers, e.g. \"supabase\".',\n },\n limit: {\n type: 'number',\n description: 'Maximum number of results to return (default: 5 for search, 20 for list; max: 20 for search, 100 for list).',\n },\n cursor: {\n type: 'string',\n description: 'Optional pagination cursor returned by operation \"list\".',\n },\n },\n required: ['query'],\n },\n };\n}\n\n/**\n * Creates the `mcp_list_servers` tool definition.\n *\n * This tool lets the LLM inspect connected MCP servers before doing\n * server-scoped tool discovery.\n */\nexport function createListServersToolDefinition(): Tool {\n return {\n name: 'mcp_list_servers',\n description:\n 'List connected MCP servers and their tool counts. ' +\n 'Use this when mcp_search_tools returns no matches, then retry mcp_search_tools with serverId or serverName.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n query: {\n type: 'string',\n description:\n 'Optional server filter text. Matches server name or serverId, e.g. \"web\" or \"supabase\".',\n },\n },\n },\n };\n}\n\n/**\n * Creates the `mcp_search_tool_regex` tool definition.\n * \n * Matches Anthropic's tool_search_tool_regex exactly (takes a 'query' regex pattern).\n */\nexport function createRegexSearchToolDefinition(): Tool {\n return {\n name: 'mcp_search_tool_regex',\n description:\n 'Search the catalog of available tools using a Python-style regex pattern. ' +\n 'Matches against tool names, descriptions, and parameter descriptions. ' +\n 'Example patterns: \"^github_\", \"weather\", \"(?i)slack\".',\n inputSchema: {\n type: 'object' as const,\n properties: {\n query: {\n type: 'string',\n description: 'Regex pattern to search for (e.g., \"^get_.*_data\", \"database\").',\n },\n limit: {\n type: 'number',\n description: 'Maximum number of results to return (default: 5, max: 20).',\n },\n },\n required: ['query'],\n },\n };\n}\n\n/**\n * Creates the `mcp_get_tool_schema` tool definition.\n *\n * After discovering tools via `mcp_search_tools` or\n * `mcp_search_tool_regex`, the LLM calls this to load the full\n * inputSchema for a specific tool so it can construct the correct\n * arguments.\n */\nexport function createGetSchemaToolDefinition(): Tool {\n return {\n name: 'mcp_get_tool_schema',\n description:\n 'Get the full input schema (parameters) for a specific tool. ' +\n 'Call this after mcp_search_tools to get the parameter details ' +\n 'needed to call a tool correctly. ' +\n 'Do NOT call the discovered tool directly; after reading the schema, call mcp_execute_tool.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n toolName: {\n type: 'string',\n description: 'The exact tool name returned by mcp_search_tools.',\n },\n serverId: {\n type: 'string',\n description:\n 'Optional: The server ID provided in mcp_search_tools. Required if multiple tools have the same name.',\n },\n },\n required: ['toolName'],\n },\n };\n}\n\n/**\n * Creates the `mcp_execute_tool` tool definition.\n *\n * This is the execution meta-tool — the LLM calls this to execute any\n * tool discovered via `mcp_search_tools` or `mcp_search_tool_regex`.\n * The LLM should first call `mcp_get_tool_schema` to know the correct\n * arguments.\n *\n * Instead of registering every real tool with the framework, we proxy\n * all execution through a single meta-tool.\n */\nexport function createExecuteToolDefinition(): Tool {\n return {\n name: 'mcp_execute_tool',\n description:\n 'Execute a tool that was discovered via mcp_search_tools. ' +\n 'You MUST call mcp_get_tool_schema first to know the correct parameters. ' +\n 'Pass the exact tool name and its arguments.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n toolName: {\n type: 'string',\n description: 'The exact tool name from mcp_search_tools results.',\n },\n serverId: {\n type: 'string',\n description:\n 'Optional: The server ID provided in mcp_search_tools. Required if multiple tools have the same name.',\n },\n args: {\n type: 'object',\n description:\n \"Arguments matching the tool's inputSchema. Omit or pass {} if the tool takes no parameters.\",\n additionalProperties: true,\n },\n },\n required: ['toolName'],\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Meta-tool Executors\n// ---------------------------------------------------------------------------\n\n/**\n * Callback for executing a real MCP tool via the correct client.\n * Provided by adapters that wire up client routing.\n */\nexport type CallToolFn = (\n toolName: string,\n args: Record<string, unknown>,\n namespace?: string\n) => Promise<any>;\n\n/**\n * Execute a meta-tool call and return the result in MCP CallToolResult format.\n *\n * @param toolName - One of the meta-tool names (mcp_search_tools, mcp_list_servers, mcp_search_tool_regex, etc.)\n * @param args - The arguments from the LLM's tool call\n * @param router - The ToolRouter to query\n * @param callToolFn - Optional callback for executing real tools (required for mcp_execute_tool)\n * @returns MCP-compatible CallToolResult, or null if this isn't a meta-tool\n */\nexport async function executeMetaTool(\n toolName: string,\n args: Record<string, unknown>,\n router: ToolRouter,\n callToolFn?: CallToolFn\n): Promise<CallToolResult | null> {\n const resolveToolSchema = (\n name: string,\n namespace?: string,\n options?: ToolLookupOptions\n ): { tool?: IndexedTool; error?: CallToolResult } => {\n try {\n return { tool: router.getToolSchema(name, namespace, options) };\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n return {\n error: {\n content: [{ type: 'text', text: errorMessage }],\n isError: true,\n },\n };\n }\n };\n\n switch (toolName) {\n case 'mcp_search_tools': {\n const query = String(args.query ?? '');\n const operation = String(args.operation ?? 'search');\n const serverId = String(args.serverId ?? '') || undefined;\n const serverName = String(args.serverName ?? '') || undefined;\n\n if (operation === 'list') {\n const limit = Math.min(Number(args.limit) || 20, 100);\n const cursor = String(args.cursor ?? '') || undefined;\n const result = await router.listTools({\n serverId,\n serverName: serverName ?? (!serverId && query ? query : undefined),\n limit,\n cursor,\n });\n\n const serverText = result.servers.length > 0\n ? result.servers\n .map((server) => `${server.serverName} (serverId: ${server.serverId}, tools: ${server.toolCount})`)\n .join(', ')\n : 'none';\n\n const lines: string[] = [\n 'operation: list',\n `servers: ${serverText}`,\n `totalCount: ${result.totalCount}`,\n `returnedCount: ${result.returnedCount}`,\n `nextCursor: ${result.nextCursor ?? 'null'}`,\n '',\n ];\n\n if (result.tools.length > 0) {\n lines.push(...formatToolSummaries(result.tools));\n } else {\n lines.push(\n serverId || serverName\n ? 'No tools found for the requested server scope.'\n : 'No tools found. Try operation \"search\" or provide serverId/serverName.'\n );\n }\n\n return {\n content: [{ type: 'text', text: lines.join('\\n') }],\n isError: false,\n };\n }\n\n const limit = Math.min(Number(args.limit) || 5, 20);\n const searchOptions = { serverId, serverName };\n\n // Fast path: Check for select: prefix\n const selectMatch = query.match(/^select:(.+)$/i);\n if (selectMatch) {\n await router.listTools({ serverId, serverName, limit: 1 });\n\n const requested = selectMatch[1]!\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n\n const found: any[] = [];\n const errors: string[] = [];\n \n const namespace = serverId ?? serverName;\n\n for (const requestedToolName of requested) {\n const { tool, error } = resolveToolSchema(requestedToolName, namespace, {\n allowServerNameFragment: Boolean(serverName && !serverId),\n });\n if (error) {\n const errorMsg = error.content[0]?.type === 'text' ? error.content[0].text : 'Unknown error';\n errors.push(`- **${requestedToolName}**: ${errorMsg}`);\n } else if (tool) {\n found.push(tool);\n } else {\n errors.push(`- **${requestedToolName}**: Tool not found. Try searching with mcp_search_tools.`);\n }\n }\n\n const lines: string[] = [];\n\n if (found.length > 0) {\n lines.push(...found.map((t, i) =>\n `${i + 1}. **${t.name}** (server: ${t.serverName}, serverId: ${t.serverId})\\n ${t.description}`\n ));\n }\n \n if (errors.length > 0) {\n if (lines.length > 0) lines.push(\"\"); // Add empty line spacing\n lines.push(\"Errors resolving some tools:\");\n lines.push(...errors);\n }\n\n const text = lines.length > 0 \n ? lines.join('\\n') \n : `No tools found matching select query: ${requested.join(', ')}`;\n\n return {\n content: [{ type: 'text', text }],\n isError: found.length === 0,\n };\n }\n\n const results = await router.searchTools(query, limit, searchOptions);\n\n const text = results.length === 0\n ? 'No tools found matching your query. Call mcp_list_servers to inspect connected servers, then retry mcp_search_tools with serverId or serverName.'\n : formatToolSummaries(results).join('\\n');\n\n return {\n content: [{ type: 'text', text }],\n isError: false,\n };\n }\n\n case 'mcp_list_servers': {\n const query = String(args.query ?? '').trim();\n const servers = await router.listServers({\n serverName: query || undefined,\n });\n\n const text = servers.length === 0\n ? 'No connected servers found.'\n : servers\n .map(\n (server, i) =>\n `${i + 1}. **${server.serverName}** (serverId: ${server.serverId}, sessionId: ${server.sessionId})\\n` +\n ` Tool count: ${server.toolCount}`\n )\n .join('\\n');\n\n return {\n content: [{ type: 'text', text }],\n isError: false,\n };\n }\n\n case 'mcp_search_tool_regex': {\n const pattern = String(args.query ?? '');\n const limit = Math.min(Number(args.limit) || 5, 20);\n\n const results = await router.searchToolsRegex(pattern, limit);\n\n const text = results.length === 0\n ? 'No tools matched your regex pattern. Try a broader pattern.'\n : formatToolSummaries(results).join('\\n');\n\n return {\n content: [{ type: 'text', text }],\n isError: false,\n };\n }\n\n case 'mcp_get_tool_schema': {\n const name = String(args.toolName ?? '');\n const namespace = String(args.serverId ?? '') || undefined;\n const { tool, error } = resolveToolSchema(name, namespace);\n\n if (error) {\n return error;\n }\n\n if (!tool) {\n return {\n content: [\n {\n type: 'text',\n text: `Tool \"${name}\" not found. Use mcp_search_tools to find available tools first.`,\n },\n ],\n isError: true,\n };\n }\n\n const schema = {\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n executionInstructions: {\n nextTool: 'mcp_execute_tool',\n toolName: tool.name,\n serverId: tool.serverId,\n note:\n 'Do not call this discovered tool directly unless it was explicitly registered as a runtime tool. Execute it via mcp_execute_tool and pass these parameters inside args.',\n },\n };\n\n return {\n content: [{ type: 'text', text: JSON.stringify(schema, null, 2) }],\n isError: false,\n };\n }\n\n case 'mcp_execute_tool': {\n const targetToolName = String(args.toolName ?? '');\n const namespace = String(args.serverId ?? '') || undefined;\n const toolArgs = (args.args as Record<string, unknown>) ?? {};\n\n if (!targetToolName) {\n return {\n content: [{ type: 'text', text: 'Missing required parameter \"toolName\". Specify which tool to execute.' }],\n isError: true,\n };\n }\n\n // Verify the tool exists in our index\n const { tool, error } = resolveToolSchema(targetToolName, namespace);\n if (error) {\n return error;\n }\n\n if (!tool) {\n return {\n content: [\n {\n type: 'text',\n text: `Tool \"${targetToolName}\" not found. Use mcp_search_tools to discover available tools first.`,\n },\n ],\n isError: true,\n };\n }\n\n if (!callToolFn) {\n return {\n content: [{ type: 'text', text: 'Tool execution is not available. No callToolFn was configured.' }],\n isError: true,\n };\n }\n\n try {\n const result = await callToolFn(targetToolName, toolArgs, namespace);\n\n // Normalize result to text\n if (result && typeof result === 'object' && 'content' in result) {\n // Already MCP CallToolResult format\n return result as CallToolResult;\n }\n\n const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2);\n return {\n content: [{ type: 'text', text }],\n isError: false,\n };\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: 'text', text: `Tool execution failed: ${errorMessage}` }],\n isError: true,\n };\n }\n }\n\n default:\n return null;\n }\n}\n\nfunction formatToolSummaries(\n tools: Array<{\n name: string;\n description: string;\n serverName: string;\n serverId: string;\n estimatedTokens: number;\n }>\n): string[] {\n return tools.map(\n (t, i) =>\n `${i + 1}. **${t.name}** (server: ${t.serverName}, serverId: ${t.serverId})\\n` +\n ` ${t.description}\\n` +\n ` Estimated tokens: ${t.estimatedTokens}`\n );\n}\n\n/** Check if a tool name is one of the meta-tools. */\nexport function isMetaTool(toolName: string): boolean {\n return (\n toolName === 'mcp_search_tools' ||\n toolName === 'mcp_list_servers' ||\n toolName === 'mcp_search_tool_regex' ||\n toolName === 'mcp_get_tool_schema' ||\n toolName === 'mcp_execute_tool'\n );\n}\n\n/**\n * Unwraps a meta-tool proxy call (like mcp_execute_tool) to find the real target tool name and arguments.\n * Also automatically strips routing prefixes like tool_{serverId}_.\n * \n * Useful for frontend components that need to determine the actual tool being executed by an AI agent.\n */\nexport function resolveMetaToolProxy(\n toolName: string,\n args: Record<string, unknown> | null | undefined\n): { toolName: string; args: Record<string, unknown> } {\n // Unwrap mcp_execute_tool proxy arguments\n if (toolName === 'mcp_execute_tool') {\n const innerName = args?.toolName;\n const innerArgs = args?.args;\n return {\n toolName: typeof innerName === 'string' && innerName ? innerName : toolName,\n args: innerArgs && typeof innerArgs === 'object' && !Array.isArray(innerArgs)\n ? (innerArgs as Record<string, unknown>)\n : {},\n };\n }\n\n // Strip tool_<serverId>_ prefix used by AIAdapter\n const match = toolName.match(/(?:tool_[^_]+_)?(.+)$/);\n const resolvedName = match?.[1] ?? toolName;\n\n return { toolName: resolvedName, args: args ?? {} };\n}\n\n","import { MCPClient } from '../server/mcp/oauth-client';\nimport { MultiSessionClient } from '../server/mcp/multi-session-client';\nimport type { JSONSchema7 } from 'json-schema';\nimport type { ToolSet } from 'ai';\nimport { ToolRouter } from '../shared/tool-router.js';\nimport { executeMetaTool, isMetaTool } from '../shared/meta-tools.js';\n\nexport interface AIAdapterOptions {\n /** \n * Prefix for tool names to avoid collision with other tools.\n * Defaults to the client's serverId.\n */\n prefix?: string;\n\n /**\n * Optional ToolRouter for intelligent tool selection.\n *\n * When provided with `strategy: 'search'`, the adapter exposes only\n * meta-tools (search_tools, get_tool_schema) instead of all tool schemas,\n * reducing context window usage by 80–95%.\n *\n * When not provided, all tools are returned as before (backward-compatible).\n */\n toolRouter?: ToolRouter;\n}\n\n/**\n * Adapter to use MCP tools with the Vercel AI SDK.\n */\nexport class AIAdapter {\n private jsonSchema: typeof import('ai').jsonSchema | undefined;\n\n constructor(\n private client: MCPClient | MultiSessionClient,\n private options: AIAdapterOptions = {}\n ) { }\n\n\n\n /**\n * Lazy-loads the jsonSchema function from the AI SDK.\n */\n private async ensureJsonSchema() {\n if (!this.jsonSchema) {\n const { jsonSchema } = await import('ai');\n this.jsonSchema = jsonSchema;\n }\n }\n\n private async transformTools(client: MCPClient): Promise<ToolSet> {\n // Safe check for isConnected method (duck typing for bundler compatibility)\n const isConnected = typeof client.isConnected === 'function'\n ? client.isConnected()\n : false;\n\n if (!isConnected) {\n return {};\n }\n\n const result = await client.listTools();\n\n // @ts-ignore: ToolSet type inference can be tricky with dynamic imports\n return Object.fromEntries(\n result.tools.map((tool) => {\n // Safe access to getServerId\n const serverId = typeof client.getServerId === 'function'\n ? client.getServerId()\n : undefined;\n const prefix = this.options.prefix ?? serverId?.replace(/-/g, '').substring(0, 8) ?? 'mcp';\n return [\n `tool_${prefix}_${tool.name}`,\n {\n description: tool.description,\n inputSchema: this.jsonSchema!(tool.inputSchema as JSONSchema7),\n execute: async (args: any) => {\n try {\n const response = await client.callTool(tool.name, args);\n return response;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(`Tool execution failed: ${errorMessage}`);\n }\n }\n }\n ];\n })\n );\n }\n\n /**\n * Fetches tools from the client(s) and converts them to AI SDK tools.\n */\n async getTools(): Promise<ToolSet> {\n await this.ensureJsonSchema();\n\n // If a ToolRouter is provided, use its filtered output\n if (this.options.toolRouter) {\n return this.getToolsViaRouter(this.options.toolRouter);\n }\n\n // Use duck typing instead of instanceof to handle module bundling issues\n // MultiSessionClient has getClients(), MCPClient does not\n const isMultiSession = typeof (this.client as any).getClients === 'function';\n const clients = isMultiSession\n ? (this.client as MultiSessionClient).getClients()\n : [this.client as MCPClient];\n\n const results = await Promise.all(\n clients.map(async (client) => {\n try {\n return await this.transformTools(client);\n } catch (error) {\n // For multi-client, we log and continue.\n // This is safer than throwing.\n const serverId = typeof client.getServerId === 'function'\n ? client.getServerId() ?? 'unknown'\n : 'unknown';\n console.error(`[AIAdapter] Failed to fetch tools from ${serverId}:`, error);\n return {};\n }\n })\n );\n\n return results.reduce((acc, tools) => ({ ...acc, ...tools }), {});\n }\n\n /**\n * Build a ToolSet from a ToolRouter's filtered output.\n *\n * In `search` strategy, only meta-tools are registered with the framework.\n * Real tool execution is proxied through `mcp_execute_tool` which uses\n * `router.callTool()` to route to the correct MCP client.\n */\n private async getToolsViaRouter(router: ToolRouter): Promise<ToolSet> {\n const filteredTools = await router.getFilteredTools();\n\n // @ts-ignore: ToolSet type inference can be tricky with dynamic imports\n return Object.fromEntries(\n filteredTools.map((tool) => {\n const routedTool = tool as typeof tool & { sessionId?: string; serverId?: string; serverName?: string };\n const namespace = routedTool.serverId ?? routedTool.sessionId;\n const toolKey = isMetaTool(tool.name)\n ? tool.name\n : this.getRouterToolKey(tool.name, routedTool.sessionId, routedTool.serverId);\n\n return [\n toolKey,\n {\n description: tool.description,\n inputSchema: this.jsonSchema!(tool.inputSchema as JSONSchema7),\n execute: async (args: any) => {\n // Handle meta-tool calls via the router\n if (isMetaTool(tool.name)) {\n const result = await executeMetaTool(\n tool.name,\n args,\n router,\n (name, toolArgs, targetNamespace) => router.callTool(name, toolArgs, targetNamespace)\n );\n if (result) {\n return result;\n }\n }\n\n // For non-meta tools in 'all' or 'groups' strategy,\n // route directly to the correct MCP client\n return await router.callTool(tool.name, args, namespace);\n },\n },\n ];\n })\n );\n }\n\n private getRouterToolKey(toolName: string, sessionId?: string, serverId?: string): string {\n const namespace = sessionId ?? serverId ?? 'mcp';\n const normalized = namespace\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '') || 'mcp';\n return `tool_${normalized}_${toolName}`;\n }\n\n /**\n * Convenience static method to fetch tools in a single line.\n */\n static async getTools(client: MCPClient | MultiSessionClient, options: AIAdapterOptions = {}): Promise<ToolSet> {\n return new AIAdapter(client, options).getTools();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/shared/meta-tools.ts","../../src/adapters/ai-adapter.ts"],"names":["limit","text"],"mappings":";;;;;;;AAuOA,eAAsB,eAAA,CACpB,QAAA,EACA,IAAA,EACA,MAAA,EACA,UAAA,EACgC;AAChC,EAAA,MAAM,iBAAA,GAAoB,CACxB,IAAA,EACA,SAAA,EACA,OAAA,KACmD;AACnD,IAAA,IAAI;AACF,MAAA,OAAO,EAAE,IAAA,EAAM,MAAA,CAAO,cAAc,IAAA,EAAM,SAAA,EAAW,OAAO,CAAA,EAAE;AAAA,IAChE,SAAS,GAAA,EAAK;AACZ,MAAA,MAAM,eAAe,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AACpE,MAAA,OAAO;AAAA,QACL,KAAA,EAAO;AAAA,UACL,SAAS,CAAC,EAAE,MAAM,MAAA,EAAQ,IAAA,EAAM,cAAc,CAAA;AAAA,UAC9C,OAAA,EAAS;AAAA;AACX,OACF;AAAA,IACF;AAAA,EACF,CAAA;AAEA,EAAA,QAAQ,QAAA;AAAU,IAChB,KAAK,kBAAA,EAAoB;AACvB,MAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,IAAA,CAAK,KAAA,IAAS,EAAE,CAAA;AACrC,MAAA,MAAM,SAAA,GAAY,MAAA,CAAO,IAAA,CAAK,SAAA,IAAa,QAAQ,CAAA;AACnD,MAAA,MAAM,QAAA,GAAW,MAAA,CAAO,IAAA,CAAK,QAAA,IAAY,EAAE,CAAA,IAAK,MAAA;AAChD,MAAA,MAAM,UAAA,GAAa,MAAA,CAAO,IAAA,CAAK,UAAA,IAAc,EAAE,CAAA,IAAK,MAAA;AAEpD,MAAA,IAAI,cAAc,MAAA,EAAQ;AACxB,QAAA,MAAMA,MAAAA,GAAQ,KAAK,GAAA,CAAI,MAAA,CAA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AqB,eAAA,KAAoB,IAAA;AAAA,YAC1D;AAAA;AACR,SACJ;AAAA,MACJ,CAAC;AAAA,KACL;AAAA,EACJ;AAAA,EAEQ,gBAAA,CAAiB,QAAA,EAAkB,SAAA,EAAoB,QAAA,EAA2B;AACtF,IAAA,MAAM,SAAA,GAAY,aAAa,QAAA,IAAY,KAAA;AAC3C,IAAA,MAAM,UAAA,GAAa,SAAA,CACd,WAAA,EAAY,CACZ,OAAA,CAAQ,aAAA,EAAe,GAAG,CAAA,CAC1B,OAAA,CAAQ,UAAA,EAAY,EAAE,CAAA,IAAK,KAAA;AAChC,IAAA,OAAO,CAAA,KAAA,EAAQ,UAAU,CAAA,CAAA,EAAI,QAAQ,CAAA,CAAA;AAAA,EACzC;AAAA;AAAA;AAAA;AAAA,EAKA,aAAa,QAAA,CAAS,MAAA,EAAwC,OAAA,GAA4B,EAAC,EAAqB;AAC5G,IAAA,OAAO,IAAI,UAAA,CAAU,MAAA,EAAQ,OAAO,EAAE,QAAA,EAAS;AAAA,EACnD;AACJ","file":"ai-adapter.js","sourcesContent":["/**\n * Meta-tools — Injectable tool definitions that let the LLM discover and\n * load MCP tools on-demand, following Anthropic's Tool Search pattern.\n *\n * Instead of injecting 50+ full tool schemas into the context window, you\n * inject just these 4 meta-tools. The LLM calls them to find and load\n * only the tools it actually needs.\n *\n * Meta-tools:\n * • `mcp_search_tools` — Search/list available tools\n * • `mcp_search_tool_regex` — Regex pattern search\n * • `mcp_get_tool_schema` — Get full inputSchema for a discovered tool\n * • `mcp_execute_tool` — Execute a discovered tool\n *\n * @packageDocumentation\n */\n\nimport type { Tool, CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport type { ToolRouter } from './tool-router.js';\nimport type { IndexedTool, ToolLookupOptions } from './tool-index.js';\n\n// ---------------------------------------------------------------------------\n// Tool Definitions\n// ---------------------------------------------------------------------------\n\n/**\n * Creates the `mcp_search_tools` tool definition.\n *\n * This tool lets the LLM search the full catalog of available MCP tools\n * using a BM25 natural-language query. Returns tool names and descriptions\n * without the full inputSchema to save context space.\n */\nexport function createSearchToolDefinition(): Tool {\n return {\n name: 'mcp_search_tools',\n description:\n 'Search the catalog of available tools. Returns tool names, descriptions, and server info. ' +\n 'Use this FIRST to find relevant tools before calling them.\\n\\n' +\n 'Query forms:\\n' +\n '- \"select:Read,Edit,Grep\" — fetch these exact tools by name\\n' +\n '- \"notebook jupyter\" — keyword search, up to limit best matches\\n' +\n '- \"+slack send\" — require \"slack\" in the name, rank by remaining terms',\n inputSchema: {\n type: 'object' as const,\n properties: {\n query: {\n type: 'string',\n description: 'Query to find tools. Use \"select:<tool_name>\" for direct selection, or keywords to search. Prefix keywords with + to require them.',\n },\n operation: {\n type: 'string',\n enum: ['search', 'list'],\n description:\n 'Operation to perform. Use \"search\" to find relevant tools by capability. Use \"list\" with serverId or serverName when the user asks for every tool from a connected MCP server.',\n },\n serverId: {\n type: 'string',\n description: 'Optional server ID to restrict search/list results to one MCP server.',\n },\n serverName: {\n type: 'string',\n description:\n 'Optional server name fragment to restrict search/list results to matching MCP servers, e.g. \"supabase\".',\n },\n limit: {\n type: 'number',\n description: 'Maximum number of results to return (default: 5 for search, 20 for list; max: 20 for search, 100 for list).',\n },\n cursor: {\n type: 'string',\n description: 'Optional pagination cursor returned by operation \"list\".',\n },\n },\n required: ['query'],\n },\n };\n}\n\n/**\n * Creates the `mcp_list_servers` tool definition.\n *\n * This tool lets the LLM inspect connected MCP servers before doing\n * server-scoped tool discovery.\n */\nexport function createListServersToolDefinition(): Tool {\n return {\n name: 'mcp_list_servers',\n description:\n 'List connected MCP servers and their tool counts. ' +\n 'Use this when mcp_search_tools returns no matches, then retry mcp_search_tools with serverId or serverName.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n query: {\n type: 'string',\n description:\n 'Optional server filter text. Matches server name or serverId, e.g. \"web\" or \"supabase\".',\n },\n },\n },\n };\n}\n\n/**\n * Creates the `mcp_search_tool_regex` tool definition.\n * \n * Matches Anthropic's tool_search_tool_regex exactly (takes a 'query' regex pattern).\n */\nexport function createRegexSearchToolDefinition(): Tool {\n return {\n name: 'mcp_search_tool_regex',\n description:\n 'Search the catalog of available tools using a Python-style regex pattern. ' +\n 'Matches against tool names, descriptions, and parameter descriptions. ' +\n 'Example patterns: \"^github_\", \"weather\", \"(?i)slack\".',\n inputSchema: {\n type: 'object' as const,\n properties: {\n query: {\n type: 'string',\n description: 'Regex pattern to search for (e.g., \"^get_.*_data\", \"database\").',\n },\n limit: {\n type: 'number',\n description: 'Maximum number of results to return (default: 5, max: 20).',\n },\n },\n required: ['query'],\n },\n };\n}\n\n/**\n * Creates the `mcp_get_tool_schema` tool definition.\n *\n * After discovering tools via `mcp_search_tools` or\n * `mcp_search_tool_regex`, the LLM calls this to load the full\n * inputSchema for a specific tool so it can construct the correct\n * arguments.\n */\nexport function createGetSchemaToolDefinition(): Tool {\n return {\n name: 'mcp_get_tool_schema',\n description:\n 'Get the full input schema (parameters) for a specific tool. ' +\n 'Call this after mcp_search_tools to get the parameter details ' +\n 'needed to call a tool correctly. ' +\n 'Do NOT call the discovered tool directly; after reading the schema, call mcp_execute_tool.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n toolName: {\n type: 'string',\n description: 'The exact tool name returned by mcp_search_tools.',\n },\n serverId: {\n type: 'string',\n description:\n 'Optional: The server ID provided in mcp_search_tools. Required if multiple tools have the same name.',\n },\n },\n required: ['toolName'],\n },\n };\n}\n\n/**\n * Creates the `mcp_execute_tool` tool definition.\n *\n * This is the execution meta-tool — the LLM calls this to execute any\n * tool discovered via `mcp_search_tools` or `mcp_search_tool_regex`.\n * The LLM should first call `mcp_get_tool_schema` to know the correct\n * arguments.\n *\n * Instead of registering every real tool with the framework, we proxy\n * all execution through a single meta-tool.\n */\nexport function createExecuteToolDefinition(): Tool {\n return {\n name: 'mcp_execute_tool',\n description:\n 'Execute a tool that was discovered via mcp_search_tools. ' +\n 'You MUST call mcp_get_tool_schema first to know the correct parameters. ' +\n 'Pass the exact tool name and its arguments.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n toolName: {\n type: 'string',\n description: 'The exact tool name from mcp_search_tools results.',\n },\n serverId: {\n type: 'string',\n description:\n 'Optional: The server ID provided in mcp_search_tools. Required if multiple tools have the same name.',\n },\n args: {\n type: 'object',\n description:\n \"Arguments matching the tool's inputSchema. Omit or pass {} if the tool takes no parameters.\",\n additionalProperties: true,\n },\n },\n required: ['toolName'],\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Meta-tool Executors\n// ---------------------------------------------------------------------------\n\n/**\n * Callback for executing a real MCP tool via the correct client.\n * Provided by adapters that wire up client routing.\n */\nexport type CallToolFn = (\n toolName: string,\n args: Record<string, unknown>,\n namespace?: string\n) => Promise<any>;\n\n/**\n * Execute a meta-tool call and return the result in MCP CallToolResult format.\n *\n * @param toolName - One of the meta-tool names (mcp_search_tools, mcp_list_servers, mcp_search_tool_regex, etc.)\n * @param args - The arguments from the LLM's tool call\n * @param router - The ToolRouter to query\n * @param callToolFn - Optional callback for executing real tools (required for mcp_execute_tool)\n * @returns MCP-compatible CallToolResult, or null if this isn't a meta-tool\n */\nexport async function executeMetaTool(\n toolName: string,\n args: Record<string, unknown>,\n router: ToolRouter,\n callToolFn?: CallToolFn\n): Promise<CallToolResult | null> {\n const resolveToolSchema = (\n name: string,\n namespace?: string,\n options?: ToolLookupOptions\n ): { tool?: IndexedTool; error?: CallToolResult } => {\n try {\n return { tool: router.getToolSchema(name, namespace, options) };\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n return {\n error: {\n content: [{ type: 'text', text: errorMessage }],\n isError: true,\n },\n };\n }\n };\n\n switch (toolName) {\n case 'mcp_search_tools': {\n const query = String(args.query ?? '');\n const operation = String(args.operation ?? 'search');\n const serverId = String(args.serverId ?? '') || undefined;\n const serverName = String(args.serverName ?? '') || undefined;\n\n if (operation === 'list') {\n const limit = Math.min(Number(args.limit) || 20, 100);\n const cursor = String(args.cursor ?? '') || undefined;\n const result = await router.listTools({\n serverId,\n serverName: serverName ?? (!serverId && query ? query : undefined),\n limit,\n cursor,\n });\n\n const serverText = result.servers.length > 0\n ? result.servers\n .map((server) => `${server.serverName} (serverId: ${server.serverId}, tools: ${server.toolCount})`)\n .join(', ')\n : 'none';\n\n const lines: string[] = [\n 'operation: list',\n `servers: ${serverText}`,\n `totalCount: ${result.totalCount}`,\n `returnedCount: ${result.returnedCount}`,\n `nextCursor: ${result.nextCursor ?? 'null'}`,\n '',\n ];\n\n if (result.tools.length > 0) {\n lines.push(...formatToolSummaries(result.tools));\n } else {\n lines.push(\n serverId || serverName\n ? 'No tools found for the requested server scope.'\n : 'No tools found. Try operation \"search\" or provide serverId/serverName.'\n );\n }\n\n return {\n content: [{ type: 'text', text: lines.join('\\n') }],\n isError: false,\n };\n }\n\n const limit = Math.min(Number(args.limit) || 5, 20);\n const searchOptions = { serverId, serverName };\n\n // Fast path: Check for select: prefix\n const selectMatch = query.match(/^select:(.+)$/i);\n if (selectMatch) {\n await router.listTools({ serverId, serverName, limit: 1 });\n\n const requested = selectMatch[1]!\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n\n const found: any[] = [];\n const errors: string[] = [];\n \n const namespace = serverId ?? serverName;\n\n for (const requestedToolName of requested) {\n const { tool, error } = resolveToolSchema(requestedToolName, namespace, {\n allowServerNameFragment: Boolean(serverName && !serverId),\n });\n if (error) {\n const errorMsg = error.content[0]?.type === 'text' ? error.content[0].text : 'Unknown error';\n errors.push(`- **${requestedToolName}**: ${errorMsg}`);\n } else if (tool) {\n found.push(tool);\n } else {\n errors.push(`- **${requestedToolName}**: Tool not found. Try searching with mcp_search_tools.`);\n }\n }\n\n const lines: string[] = [];\n\n if (found.length > 0) {\n lines.push(...found.map((t, i) =>\n `${i + 1}. **${t.name}** (serverName: ${t.serverName}, serverId: ${t.serverId})\\n ${t.description}`\n ));\n }\n \n if (errors.length > 0) {\n if (lines.length > 0) lines.push(\"\"); // Add empty line spacing\n lines.push(\"Errors resolving some tools:\");\n lines.push(...errors);\n }\n\n const text = lines.length > 0 \n ? lines.join('\\n') \n : `No tools found matching select query: ${requested.join(', ')}`;\n\n return {\n content: [{ type: 'text', text }],\n isError: found.length === 0,\n };\n }\n\n const results = await router.searchTools(query, limit, searchOptions);\n\n const text = results.length === 0\n ? 'No tools found matching your query. Call mcp_list_servers to inspect connected servers, then retry mcp_search_tools with serverId or serverName.'\n : formatToolSummaries(results).join('\\n');\n\n return {\n content: [{ type: 'text', text }],\n isError: false,\n };\n }\n\n case 'mcp_list_servers': {\n const query = String(args.query ?? '').trim();\n const servers = await router.listServers({\n serverName: query || undefined,\n });\n\n const text = servers.length === 0\n ? 'No connected servers found.'\n : servers\n .map(\n (server, i) =>\n `${i + 1}. **${server.serverName}** (serverId: ${server.serverId})\\n` +\n ` Tool count: ${server.toolCount}`\n )\n .join('\\n');\n\n return {\n content: [{ type: 'text', text }],\n isError: false,\n };\n }\n\n case 'mcp_search_tool_regex': {\n const pattern = String(args.query ?? '');\n const limit = Math.min(Number(args.limit) || 5, 20);\n\n const results = await router.searchToolsRegex(pattern, limit);\n\n const text = results.length === 0\n ? 'No tools matched your regex pattern. Try a broader pattern.'\n : formatToolSummaries(results).join('\\n');\n\n return {\n content: [{ type: 'text', text }],\n isError: false,\n };\n }\n\n case 'mcp_get_tool_schema': {\n const name = String(args.toolName ?? '');\n const namespace = String(args.serverId ?? '') || undefined;\n const { tool, error } = resolveToolSchema(name, namespace);\n\n if (error) {\n return error;\n }\n\n if (!tool) {\n return {\n content: [\n {\n type: 'text',\n text: `Tool \"${name}\" not found. Use mcp_search_tools to find available tools first.`,\n },\n ],\n isError: true,\n };\n }\n\n const schema = {\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n executionInstructions: {\n nextTool: 'mcp_execute_tool',\n toolName: tool.name,\n serverId: tool.serverId,\n note:\n 'Do not call this discovered tool directly unless it was explicitly registered as a runtime tool. Execute it via mcp_execute_tool and pass these parameters inside args.',\n },\n };\n\n return {\n content: [{ type: 'text', text: JSON.stringify(schema, null, 2) }],\n isError: false,\n };\n }\n\n case 'mcp_execute_tool': {\n const targetToolName = String(args.toolName ?? '');\n const namespace = String(args.serverId ?? '') || undefined;\n const toolArgs = (args.args as Record<string, unknown>) ?? {};\n\n if (!targetToolName) {\n return {\n content: [{ type: 'text', text: 'Missing required parameter \"toolName\". Specify which tool to execute.' }],\n isError: true,\n };\n }\n\n // Verify the tool exists in our index\n const { tool, error } = resolveToolSchema(targetToolName, namespace);\n if (error) {\n return error;\n }\n\n if (!tool) {\n return {\n content: [\n {\n type: 'text',\n text: `Tool \"${targetToolName}\" not found. Use mcp_search_tools to discover available tools first.`,\n },\n ],\n isError: true,\n };\n }\n\n if (!callToolFn) {\n return {\n content: [{ type: 'text', text: 'Tool execution is not available. No callToolFn was configured.' }],\n isError: true,\n };\n }\n\n try {\n const result = await callToolFn(targetToolName, toolArgs, namespace);\n\n // Normalize result to text\n if (result && typeof result === 'object' && 'content' in result) {\n // Already MCP CallToolResult format\n return result as CallToolResult;\n }\n\n const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2);\n return {\n content: [{ type: 'text', text }],\n isError: false,\n };\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: 'text', text: `Tool execution failed: ${errorMessage}` }],\n isError: true,\n };\n }\n }\n\n default:\n return null;\n }\n}\n\nfunction formatToolSummaries(\n tools: Array<{\n name: string;\n description: string;\n serverName: string;\n serverId: string;\n }>\n): string[] {\n return tools.map(\n (t, i) =>\n `${i + 1}. **${t.name}** (serverName: ${t.serverName}, serverId: ${t.serverId})\\n` +\n ` ${t.description}`\n );\n}\n\n/** Check if a tool name is one of the meta-tools. */\nexport function isMetaTool(toolName: string): boolean {\n return (\n toolName === 'mcp_search_tools' ||\n toolName === 'mcp_list_servers' ||\n toolName === 'mcp_search_tool_regex' ||\n toolName === 'mcp_get_tool_schema' ||\n toolName === 'mcp_execute_tool'\n );\n}\n\n/**\n * Unwraps a meta-tool proxy call (like mcp_execute_tool) to find the real target tool name and arguments.\n * Also automatically strips routing prefixes like tool_{serverId}_.\n * \n * Useful for frontend components that need to determine the actual tool being executed by an AI agent.\n */\nexport function resolveMetaToolProxy(\n toolName: string,\n args: Record<string, unknown> | null | undefined\n): { toolName: string; args: Record<string, unknown> } {\n // Unwrap mcp_execute_tool proxy arguments\n if (toolName === 'mcp_execute_tool') {\n const innerName = args?.toolName;\n const innerArgs = args?.args;\n return {\n toolName: typeof innerName === 'string' && innerName ? innerName : toolName,\n args: innerArgs && typeof innerArgs === 'object' && !Array.isArray(innerArgs)\n ? (innerArgs as Record<string, unknown>)\n : {},\n };\n }\n\n // Strip tool_<serverId>_ prefix used by AIAdapter\n const match = toolName.match(/(?:tool_[^_]+_)?(.+)$/);\n const resolvedName = match?.[1] ?? toolName;\n\n return { toolName: resolvedName, args: args ?? {} };\n}\n\n","import { MCPClient } from '../server/mcp/oauth-client';\nimport { MultiSessionClient } from '../server/mcp/multi-session-client';\nimport type { JSONSchema7 } from 'json-schema';\nimport type { ToolSet } from 'ai';\nimport { ToolRouter } from '../shared/tool-router.js';\nimport { executeMetaTool, isMetaTool } from '../shared/meta-tools.js';\n\nexport interface AIAdapterOptions {\n /** \n * Prefix for tool names to avoid collision with other tools.\n * Defaults to the client's serverId.\n */\n prefix?: string;\n\n /**\n * Optional ToolRouter for intelligent tool selection.\n *\n * When provided with `strategy: 'search'`, the adapter exposes only\n * meta-tools (search_tools, get_tool_schema) instead of all tool schemas,\n * reducing context window usage by 80–95%.\n *\n * When not provided, all tools are returned as before (backward-compatible).\n */\n toolRouter?: ToolRouter;\n\n /**\n * Optional custom callback to determine if a tool requires user approval.\n * Can return a boolean or a Promise<boolean>.\n * If not provided, defaults to checking the tool's `destructiveHint` annotation.\n */\n needsApproval?: (tool: any, args: any) => boolean | Promise<boolean>;\n}\n\n/**\n * Adapter to use MCP tools with the Vercel AI SDK.\n */\nexport class AIAdapter {\n private jsonSchema: typeof import('ai').jsonSchema | undefined;\n\n constructor(\n private client: MCPClient | MultiSessionClient,\n private options: AIAdapterOptions = {}\n ) { }\n\n\n\n /**\n * Lazy-loads the jsonSchema function from the AI SDK.\n */\n private async ensureJsonSchema() {\n if (!this.jsonSchema) {\n const { jsonSchema } = await import('ai');\n this.jsonSchema = jsonSchema;\n }\n }\n\n private async transformTools(client: MCPClient): Promise<ToolSet> {\n // Safe check for isConnected method (duck typing for bundler compatibility)\n const isConnected = typeof client.isConnected === 'function'\n ? client.isConnected()\n : false;\n\n if (!isConnected) {\n return {};\n }\n\n const result = await client.listTools();\n\n // @ts-ignore: ToolSet type inference can be tricky with dynamic imports\n return Object.fromEntries(\n result.tools.map((tool) => {\n // Safe access to getServerId\n const serverId = typeof client.getServerId === 'function'\n ? client.getServerId()\n : undefined;\n const prefix = this.options.prefix ?? serverId?.replace(/-/g, '').substring(0, 8) ?? 'mcp';\n return [\n `tool_${prefix}_${tool.name}`,\n {\n description: tool.description,\n inputSchema: this.jsonSchema!(tool.inputSchema as JSONSchema7),\n execute: async (args: any) => {\n try {\n const response = await client.callTool(tool.name, args);\n return response;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(`Tool execution failed: ${errorMessage}`);\n }\n },\n needsApproval: this.options.needsApproval\n ? (args: any) => this.options.needsApproval!(tool, args)\n : (tool.annotations as any)?.destructiveHint === true\n ? () => true\n : undefined\n }\n ];\n })\n );\n }\n\n /**\n * Fetches tools from the client(s) and converts them to AI SDK tools.\n */\n async getTools(): Promise<ToolSet> {\n await this.ensureJsonSchema();\n\n // If a ToolRouter is provided, use its filtered output\n if (this.options.toolRouter) {\n return this.getToolsViaRouter(this.options.toolRouter);\n }\n\n // Use duck typing instead of instanceof to handle module bundling issues\n // MultiSessionClient has getClients(), MCPClient does not\n const isMultiSession = typeof (this.client as any).getClients === 'function';\n const clients = isMultiSession\n ? (this.client as MultiSessionClient).getClients()\n : [this.client as MCPClient];\n\n const results = await Promise.all(\n clients.map(async (client) => {\n try {\n return await this.transformTools(client);\n } catch (error) {\n // For multi-client, we log and continue.\n // This is safer than throwing.\n const serverId = typeof client.getServerId === 'function'\n ? client.getServerId() ?? 'unknown'\n : 'unknown';\n console.error(`[AIAdapter] Failed to fetch tools from ${serverId}:`, error);\n return {};\n }\n })\n );\n\n return results.reduce((acc, tools) => ({ ...acc, ...tools }), {});\n }\n\n /**\n * Build a ToolSet from a ToolRouter's filtered output.\n *\n * In `search` strategy, only meta-tools are registered with the framework.\n * Real tool execution is proxied through `mcp_execute_tool` which uses\n * `router.callTool()` to route to the correct MCP client.\n */\n private async getToolsViaRouter(router: ToolRouter): Promise<ToolSet> {\n const filteredTools = await router.getFilteredTools();\n\n // @ts-ignore: ToolSet type inference can be tricky with dynamic imports\n return Object.fromEntries(\n filteredTools.map((tool) => {\n const routedTool = tool as typeof tool & { sessionId?: string; serverId?: string; serverName?: string };\n const namespace = routedTool.serverId ?? routedTool.sessionId;\n const toolKey = isMetaTool(tool.name)\n ? tool.name\n : this.getRouterToolKey(tool.name, routedTool.sessionId, routedTool.serverId);\n\n return [\n toolKey,\n {\n description: tool.description,\n inputSchema: this.jsonSchema!(tool.inputSchema as JSONSchema7),\n execute: async (args: any) => {\n // Handle meta-tool calls via the router\n if (isMetaTool(tool.name)) {\n const result = await executeMetaTool(\n tool.name,\n args,\n router,\n (name, toolArgs, targetNamespace) => router.callTool(name, toolArgs, targetNamespace)\n );\n if (result) {\n return result;\n }\n }\n\n // For non-meta tools in 'all' or 'groups' strategy,\n // route directly to the correct MCP client\n return await router.callTool(tool.name, args, namespace);\n },\n needsApproval: this.options.needsApproval\n ? (args: any) => this.options.needsApproval!(tool, args)\n : (args: any) => {\n // Default HITL logic using annotations\n if (tool.name === 'mcp_execute_tool') {\n const targetToolName = String(args?.toolName ?? \"\");\n const targetNamespace = String(args?.serverId ?? \"\") || undefined;\n if (!targetToolName) return false;\n try {\n const targetTool = router.getToolSchema(targetToolName, targetNamespace);\n return (targetTool as any)?.annotations?.destructiveHint === true;\n } catch {\n return false;\n }\n }\n return (tool.annotations as any)?.destructiveHint === true;\n }\n },\n ];\n })\n );\n }\n\n private getRouterToolKey(toolName: string, sessionId?: string, serverId?: string): string {\n const namespace = sessionId ?? serverId ?? 'mcp';\n const normalized = namespace\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '') || 'mcp';\n return `tool_${normalized}_${toolName}`;\n }\n\n /**\n * Convenience static method to fetch tools in a single line.\n */\n static async getTools(client: MCPClient | MultiSessionClient, options: AIAdapterOptions = {}): Promise<ToolSet> {\n return new AIAdapter(client, options).getTools();\n }\n}\n"]}
|
|
@@ -78,7 +78,7 @@ async function executeMetaTool(toolName, args, router, callToolFn) {
|
|
|
78
78
|
const lines = [];
|
|
79
79
|
if (found.length > 0) {
|
|
80
80
|
lines.push(...found.map(
|
|
81
|
-
(t, i) => `${i + 1}. **${t.name}** (
|
|
81
|
+
(t, i) => `${i + 1}. **${t.name}** (serverName: ${t.serverName}, serverId: ${t.serverId})
|
|
82
82
|
${t.description}`
|
|
83
83
|
));
|
|
84
84
|
}
|
|
@@ -106,7 +106,7 @@ async function executeMetaTool(toolName, args, router, callToolFn) {
|
|
|
106
106
|
serverName: query || void 0
|
|
107
107
|
});
|
|
108
108
|
const text = servers.length === 0 ? "No connected servers found." : servers.map(
|
|
109
|
-
(server, i) => `${i + 1}. **${server.serverName}** (serverId: ${server.serverId}
|
|
109
|
+
(server, i) => `${i + 1}. **${server.serverName}** (serverId: ${server.serverId})
|
|
110
110
|
Tool count: ${server.toolCount}`
|
|
111
111
|
).join("\n");
|
|
112
112
|
return {
|
|
@@ -213,9 +213,8 @@ async function executeMetaTool(toolName, args, router, callToolFn) {
|
|
|
213
213
|
}
|
|
214
214
|
function formatToolSummaries(tools) {
|
|
215
215
|
return tools.map(
|
|
216
|
-
(t, i) => `${i + 1}. **${t.name}** (
|
|
217
|
-
${t.description}
|
|
218
|
-
Estimated tokens: ${t.estimatedTokens}`
|
|
216
|
+
(t, i) => `${i + 1}. **${t.name}** (serverName: ${t.serverName}, serverId: ${t.serverId})
|
|
217
|
+
${t.description}`
|
|
219
218
|
);
|
|
220
219
|
}
|
|
221
220
|
function isMetaTool(toolName) {
|
|
@@ -261,7 +260,8 @@ var AIAdapter = class _AIAdapter {
|
|
|
261
260
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
262
261
|
throw new Error(`Tool execution failed: ${errorMessage}`);
|
|
263
262
|
}
|
|
264
|
-
}
|
|
263
|
+
},
|
|
264
|
+
needsApproval: this.options.needsApproval ? (args) => this.options.needsApproval(tool, args) : tool.annotations?.destructiveHint === true ? () => true : void 0
|
|
265
265
|
}
|
|
266
266
|
];
|
|
267
267
|
})
|
|
@@ -322,6 +322,20 @@ var AIAdapter = class _AIAdapter {
|
|
|
322
322
|
}
|
|
323
323
|
}
|
|
324
324
|
return await router.callTool(tool.name, args, namespace);
|
|
325
|
+
},
|
|
326
|
+
needsApproval: this.options.needsApproval ? (args) => this.options.needsApproval(tool, args) : (args) => {
|
|
327
|
+
if (tool.name === "mcp_execute_tool") {
|
|
328
|
+
const targetToolName = String(args?.toolName ?? "");
|
|
329
|
+
const targetNamespace = String(args?.serverId ?? "") || void 0;
|
|
330
|
+
if (!targetToolName) return false;
|
|
331
|
+
try {
|
|
332
|
+
const targetTool = router.getToolSchema(targetToolName, targetNamespace);
|
|
333
|
+
return targetTool?.annotations?.destructiveHint === true;
|
|
334
|
+
} catch {
|
|
335
|
+
return false;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return tool.annotations?.destructiveHint === true;
|
|
325
339
|
}
|
|
326
340
|
}
|
|
327
341
|
];
|