@mcp-ts/sdk 1.6.2 → 2.1.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 +5 -5
- package/dist/adapters/agui-adapter.js.map +1 -1
- package/dist/adapters/agui-adapter.mjs +5 -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 +21 -6
- package/dist/adapters/ai-adapter.js.map +1 -1
- package/dist/adapters/ai-adapter.mjs +21 -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 +10 -6
- package/dist/adapters/langchain-adapter.js.map +1 -1
- package/dist/adapters/langchain-adapter.mjs +10 -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 +15 -19
- package/dist/client/react.js.map +1 -1
- package/dist/client/react.mjs +15 -19
- 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-bFL4ZF2N.d.mts → index-Cfjsme-a.d.mts} +5 -5
- package/dist/{index-DhA-OEAe.d.ts → index-CmjMd2ac.d.ts} +5 -5
- package/dist/index.d.mts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +643 -374
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +642 -374
- 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 +7 -7
- package/dist/shared/index.d.ts +7 -7
- package/dist/shared/index.js +103 -105
- package/dist/shared/index.js.map +1 -1
- package/dist/shared/index.mjs +103 -105
- package/dist/shared/index.mjs.map +1 -1
- package/dist/{tool-router-BVaV1udm.d.mts → tool-router-BP8TT9mI.d.ts} +87 -73
- package/dist/{tool-router-Dh2804tM.d.ts → tool-router-BkQnso27.d.mts} +87 -73
- package/dist/{types-rIuN1CQi.d.mts → types-CxFaaZrM.d.mts} +6 -5
- package/dist/{types-rIuN1CQi.d.ts → types-CxFaaZrM.d.ts} +6 -5
- 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/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 +9 -10
- package/src/shared/schema-compressor.ts +2 -42
- package/src/shared/tool-index.ts +90 -84
- package/src/shared/tool-router.ts +38 -27
- package/src/shared/types.ts +6 -5
- /package/{supabase/migrations → migrations/supabase}/20260421010000_add_session_cleanup_cron.sql +0 -0
|
@@ -1,57 +1,5 @@
|
|
|
1
1
|
import { Tool } from '@modelcontextprotocol/sdk/types.js';
|
|
2
|
-
import { u as ToolClientProvider, T as ToolClient } from './types-
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* SchemaCompressor — Utilities for reducing tool schema token overhead.
|
|
6
|
-
*
|
|
7
|
-
* Provides compact representations of tools (name + description only,
|
|
8
|
-
* no inputSchema) and token savings estimation.
|
|
9
|
-
*
|
|
10
|
-
* @packageDocumentation
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* A minimal tool representation containing only what an LLM needs to
|
|
15
|
-
* *decide whether* to use a tool. The full `inputSchema` is deferred.
|
|
16
|
-
*/
|
|
17
|
-
interface CompactTool {
|
|
18
|
-
name: string;
|
|
19
|
-
description?: string;
|
|
20
|
-
/**
|
|
21
|
-
* Human-readable hint about the expected parameters.
|
|
22
|
-
* e.g. "(location: string, unit?: 'celsius' | 'fahrenheit')"
|
|
23
|
-
*/
|
|
24
|
-
parameterHint?: string;
|
|
25
|
-
}
|
|
26
|
-
interface CompressionStats {
|
|
27
|
-
/** Estimated tokens for the *full* tool list. */
|
|
28
|
-
fullTokens: number;
|
|
29
|
-
/** Estimated tokens for the *compact* tool list. */
|
|
30
|
-
compactTokens: number;
|
|
31
|
-
/** Absolute token savings. */
|
|
32
|
-
savedTokens: number;
|
|
33
|
-
/** Percentage savings as a human-readable string, e.g. "82.3%". */
|
|
34
|
-
savingsPercent: string;
|
|
35
|
-
}
|
|
36
|
-
declare class SchemaCompressor {
|
|
37
|
-
/**
|
|
38
|
-
* Convert a full MCP Tool definition to a compact summary.
|
|
39
|
-
*
|
|
40
|
-
* The compact form omits `inputSchema` entirely and optionally generates
|
|
41
|
-
* a short `parameterHint` from the schema's top-level properties.
|
|
42
|
-
*/
|
|
43
|
-
static toCompact(tool: Tool): CompactTool;
|
|
44
|
-
/**
|
|
45
|
-
* Convert an array of tools to compact form, optionally limiting the count.
|
|
46
|
-
*/
|
|
47
|
-
static compactAll(tools: Tool[], options?: {
|
|
48
|
-
maxTools?: number;
|
|
49
|
-
}): CompactTool[];
|
|
50
|
-
/**
|
|
51
|
-
* Estimate token savings from using compact vs full tool schemas.
|
|
52
|
-
*/
|
|
53
|
-
static estimateSavings(tools: Tool[]): CompressionStats;
|
|
54
|
-
}
|
|
2
|
+
import { u as ToolClientProvider, T as ToolClient } from './types-CxFaaZrM.js';
|
|
55
3
|
|
|
56
4
|
/**
|
|
57
5
|
* ToolIndex — Lightweight in-memory search index for MCP tool discovery.
|
|
@@ -77,8 +25,6 @@ interface ToolSummary {
|
|
|
77
25
|
serverId: string;
|
|
78
26
|
/** Session the tool belongs to */
|
|
79
27
|
sessionId: string;
|
|
80
|
-
/** Estimated token cost of the full inputSchema */
|
|
81
|
-
estimatedTokens: number;
|
|
82
28
|
}
|
|
83
29
|
/** Server-level summary derived from indexed tools. */
|
|
84
30
|
interface ToolServerSummary {
|
|
@@ -118,6 +64,7 @@ interface IndexedTool extends Tool {
|
|
|
118
64
|
sessionId: string;
|
|
119
65
|
serverId: string;
|
|
120
66
|
serverName: string;
|
|
67
|
+
outputSchema?: Tool['outputSchema'];
|
|
121
68
|
}
|
|
122
69
|
/**
|
|
123
70
|
* An optional embedding function supplied by the consumer.
|
|
@@ -163,8 +110,6 @@ declare class ToolIndex {
|
|
|
163
110
|
private docLengths;
|
|
164
111
|
/** BM25: average document length across the entire index. */
|
|
165
112
|
private avgDocLength;
|
|
166
|
-
/** Cached total estimated token cost across all indexed tools. */
|
|
167
|
-
private totalTokenCost;
|
|
168
113
|
private options;
|
|
169
114
|
constructor(options?: ToolIndexOptions);
|
|
170
115
|
/**
|
|
@@ -203,17 +148,11 @@ declare class ToolIndex {
|
|
|
203
148
|
}): ToolListResult;
|
|
204
149
|
/** Number of indexed tools (including duplicates). */
|
|
205
150
|
get size(): number;
|
|
206
|
-
/** Total estimated token cost of all indexed tool schemas. */
|
|
207
|
-
getTotalTokenCost(): number;
|
|
208
|
-
/**
|
|
209
|
-
* Estimate token count of a tool's full schema (name + description + inputSchema).
|
|
210
|
-
*
|
|
211
|
-
* Uses character-class weighted counting calibrated against cl100k_base.
|
|
212
|
-
* Accuracy is typically within ±10% for JSON Schema payloads.
|
|
213
|
-
*/
|
|
214
|
-
static estimateTokens(tool: Tool): number;
|
|
215
151
|
/** Build a single searchable string from tool metadata. */
|
|
216
152
|
private buildSearchableText;
|
|
153
|
+
/** Recursively collect JSON Schema argument names and descriptions. */
|
|
154
|
+
private collectSchemaSearchText;
|
|
155
|
+
private pushStringValue;
|
|
217
156
|
private getDocumentKey;
|
|
218
157
|
private matchesServer;
|
|
219
158
|
/** Simple whitespace + camelCase + snake_case tokenizer. */
|
|
@@ -222,6 +161,72 @@ declare class ToolIndex {
|
|
|
222
161
|
private cosineSimilarity;
|
|
223
162
|
}
|
|
224
163
|
|
|
164
|
+
/**
|
|
165
|
+
* SchemaCompressor — Utilities for compact tool representations.
|
|
166
|
+
*
|
|
167
|
+
* Provides compact representations of tools (name + description only,
|
|
168
|
+
* no inputSchema).
|
|
169
|
+
*
|
|
170
|
+
* @packageDocumentation
|
|
171
|
+
*/
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* A minimal tool representation containing only what an LLM needs to
|
|
175
|
+
* *decide whether* to use a tool. The full `inputSchema` is deferred.
|
|
176
|
+
*/
|
|
177
|
+
interface CompactTool {
|
|
178
|
+
name: string;
|
|
179
|
+
description?: string;
|
|
180
|
+
/**
|
|
181
|
+
* Human-readable hint about the expected parameters.
|
|
182
|
+
* e.g. "(location: string, unit?: 'celsius' | 'fahrenheit')"
|
|
183
|
+
*/
|
|
184
|
+
parameterHint?: string;
|
|
185
|
+
}
|
|
186
|
+
declare class SchemaCompressor {
|
|
187
|
+
/**
|
|
188
|
+
* Convert a full MCP Tool definition to a compact summary.
|
|
189
|
+
*
|
|
190
|
+
* The compact form omits `inputSchema` entirely and optionally generates
|
|
191
|
+
* a short `parameterHint` from the schema's top-level properties.
|
|
192
|
+
*/
|
|
193
|
+
static toCompact(tool: Tool): CompactTool;
|
|
194
|
+
/**
|
|
195
|
+
* Convert an array of tools to compact form, optionally limiting the count.
|
|
196
|
+
*/
|
|
197
|
+
static compactAll(tools: Tool[], options?: {
|
|
198
|
+
maxTools?: number;
|
|
199
|
+
}): CompactTool[];
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* ToolRouter — Middleware layer for intelligent MCP tool selection.
|
|
204
|
+
*
|
|
205
|
+
* Sits between your AI framework adapter and MultiSessionClient to reduce
|
|
206
|
+
* context window usage. Supports three strategies:
|
|
207
|
+
*
|
|
208
|
+
* • `all` — Pass through every tool (backward-compatible default)
|
|
209
|
+
* • `search` — Expose only meta-tools; LLM discovers tools on-demand
|
|
210
|
+
* • `groups` — Expose tools from active groups only
|
|
211
|
+
*
|
|
212
|
+
* Inspired by Anthropic's `defer_loading` + `tool_search_tool` pattern.
|
|
213
|
+
*
|
|
214
|
+
* @example
|
|
215
|
+
* ```ts
|
|
216
|
+
* import { ToolRouter } from '@mcp-ts/sdk/shared';
|
|
217
|
+
* import { AIAdapter } from '@mcp-ts/sdk/adapters/ai';
|
|
218
|
+
*
|
|
219
|
+
* const router = new ToolRouter(multiSessionClient, {
|
|
220
|
+
* strategy: 'search',
|
|
221
|
+
* maxTools: 5,
|
|
222
|
+
* });
|
|
223
|
+
*
|
|
224
|
+
* const tools = await AIAdapter.getTools(multiSessionClient, { toolRouter: router });
|
|
225
|
+
* ```
|
|
226
|
+
*
|
|
227
|
+
* @packageDocumentation
|
|
228
|
+
*/
|
|
229
|
+
|
|
225
230
|
type ToolRouterStrategy = 'all' | 'search' | 'groups';
|
|
226
231
|
interface ToolRouterOptions {
|
|
227
232
|
/**
|
|
@@ -264,6 +269,15 @@ interface ToolRouterOptions {
|
|
|
264
269
|
* @default false
|
|
265
270
|
*/
|
|
266
271
|
compactSchemas?: boolean;
|
|
272
|
+
/**
|
|
273
|
+
* Tool names to expose directly when using `search` strategy.
|
|
274
|
+
* Pinned tools are removed from discovery results and should be called directly.
|
|
275
|
+
*/
|
|
276
|
+
pinnedTools?: string[];
|
|
277
|
+
/**
|
|
278
|
+
* Tool names or glob-style patterns to omit entirely from the router catalog.
|
|
279
|
+
*/
|
|
280
|
+
excludeTools?: string[];
|
|
267
281
|
/**
|
|
268
282
|
* Optional embedding function for semantic search.
|
|
269
283
|
* When not provided, keyword TF-IDF matching is used.
|
|
@@ -291,12 +305,16 @@ declare class ToolRouter {
|
|
|
291
305
|
private options;
|
|
292
306
|
private index;
|
|
293
307
|
private allTools;
|
|
308
|
+
private pinnedTools;
|
|
309
|
+
private discoverableTools;
|
|
294
310
|
private groupsMap;
|
|
295
311
|
private strategy;
|
|
296
312
|
private maxTools;
|
|
297
313
|
private compactSchemas;
|
|
298
314
|
private activeGroups;
|
|
299
315
|
private customGroups?;
|
|
316
|
+
private pinnedToolNames;
|
|
317
|
+
private excludeToolMatchers;
|
|
300
318
|
private initialized;
|
|
301
319
|
constructor(client: ToolRouterClientInput, options?: ToolRouterOptions);
|
|
302
320
|
/**
|
|
@@ -340,12 +358,6 @@ declare class ToolRouter {
|
|
|
340
358
|
setActiveGroups(groups: string[]): void;
|
|
341
359
|
/** Get the names of currently active groups. */
|
|
342
360
|
getActiveGroups(): string[];
|
|
343
|
-
/** Total token cost of all tools if loaded without filtering. */
|
|
344
|
-
getTotalTokenCost(): number;
|
|
345
|
-
/** Estimate token cost of the currently filtered tool set. */
|
|
346
|
-
getFilteredTokenCost(): Promise<number>;
|
|
347
|
-
/** Get compression stats showing savings from current strategy. */
|
|
348
|
-
getCompressionStats(): CompressionStats;
|
|
349
361
|
/** Number of total indexed tools. */
|
|
350
362
|
get totalToolCount(): number;
|
|
351
363
|
/** Change strategy at runtime. */
|
|
@@ -372,6 +384,8 @@ declare class ToolRouter {
|
|
|
372
384
|
private getGroupFilteredTools;
|
|
373
385
|
/** The 4 meta-tool definitions exposed in `search` strategy. */
|
|
374
386
|
private getMetaToolDefinitions;
|
|
387
|
+
private matchesPinnedTool;
|
|
388
|
+
private matchesExcludedTool;
|
|
375
389
|
}
|
|
376
390
|
|
|
377
|
-
export { type CompactTool as C, type EmbedFn as E, type IndexedTool as I, SchemaCompressor as S, type ToolGroupInfo as T,
|
|
391
|
+
export { type CompactTool as C, type EmbedFn as E, type IndexedTool as I, SchemaCompressor as S, type ToolGroupInfo as T, ToolIndex as a, type ToolIndexOptions as b, type ToolListResult as c, ToolRouter as d, type ToolRouterClientInput as e, type ToolRouterOptions as f, type ToolRouterStrategy as g, type ToolSearchOptions as h, type ToolServerSummary as i, type ToolSummary as j };
|
|
@@ -1,57 +1,5 @@
|
|
|
1
1
|
import { Tool } from '@modelcontextprotocol/sdk/types.js';
|
|
2
|
-
import { u as ToolClientProvider, T as ToolClient } from './types-
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* SchemaCompressor — Utilities for reducing tool schema token overhead.
|
|
6
|
-
*
|
|
7
|
-
* Provides compact representations of tools (name + description only,
|
|
8
|
-
* no inputSchema) and token savings estimation.
|
|
9
|
-
*
|
|
10
|
-
* @packageDocumentation
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* A minimal tool representation containing only what an LLM needs to
|
|
15
|
-
* *decide whether* to use a tool. The full `inputSchema` is deferred.
|
|
16
|
-
*/
|
|
17
|
-
interface CompactTool {
|
|
18
|
-
name: string;
|
|
19
|
-
description?: string;
|
|
20
|
-
/**
|
|
21
|
-
* Human-readable hint about the expected parameters.
|
|
22
|
-
* e.g. "(location: string, unit?: 'celsius' | 'fahrenheit')"
|
|
23
|
-
*/
|
|
24
|
-
parameterHint?: string;
|
|
25
|
-
}
|
|
26
|
-
interface CompressionStats {
|
|
27
|
-
/** Estimated tokens for the *full* tool list. */
|
|
28
|
-
fullTokens: number;
|
|
29
|
-
/** Estimated tokens for the *compact* tool list. */
|
|
30
|
-
compactTokens: number;
|
|
31
|
-
/** Absolute token savings. */
|
|
32
|
-
savedTokens: number;
|
|
33
|
-
/** Percentage savings as a human-readable string, e.g. "82.3%". */
|
|
34
|
-
savingsPercent: string;
|
|
35
|
-
}
|
|
36
|
-
declare class SchemaCompressor {
|
|
37
|
-
/**
|
|
38
|
-
* Convert a full MCP Tool definition to a compact summary.
|
|
39
|
-
*
|
|
40
|
-
* The compact form omits `inputSchema` entirely and optionally generates
|
|
41
|
-
* a short `parameterHint` from the schema's top-level properties.
|
|
42
|
-
*/
|
|
43
|
-
static toCompact(tool: Tool): CompactTool;
|
|
44
|
-
/**
|
|
45
|
-
* Convert an array of tools to compact form, optionally limiting the count.
|
|
46
|
-
*/
|
|
47
|
-
static compactAll(tools: Tool[], options?: {
|
|
48
|
-
maxTools?: number;
|
|
49
|
-
}): CompactTool[];
|
|
50
|
-
/**
|
|
51
|
-
* Estimate token savings from using compact vs full tool schemas.
|
|
52
|
-
*/
|
|
53
|
-
static estimateSavings(tools: Tool[]): CompressionStats;
|
|
54
|
-
}
|
|
2
|
+
import { u as ToolClientProvider, T as ToolClient } from './types-CxFaaZrM.mjs';
|
|
55
3
|
|
|
56
4
|
/**
|
|
57
5
|
* ToolIndex — Lightweight in-memory search index for MCP tool discovery.
|
|
@@ -77,8 +25,6 @@ interface ToolSummary {
|
|
|
77
25
|
serverId: string;
|
|
78
26
|
/** Session the tool belongs to */
|
|
79
27
|
sessionId: string;
|
|
80
|
-
/** Estimated token cost of the full inputSchema */
|
|
81
|
-
estimatedTokens: number;
|
|
82
28
|
}
|
|
83
29
|
/** Server-level summary derived from indexed tools. */
|
|
84
30
|
interface ToolServerSummary {
|
|
@@ -118,6 +64,7 @@ interface IndexedTool extends Tool {
|
|
|
118
64
|
sessionId: string;
|
|
119
65
|
serverId: string;
|
|
120
66
|
serverName: string;
|
|
67
|
+
outputSchema?: Tool['outputSchema'];
|
|
121
68
|
}
|
|
122
69
|
/**
|
|
123
70
|
* An optional embedding function supplied by the consumer.
|
|
@@ -163,8 +110,6 @@ declare class ToolIndex {
|
|
|
163
110
|
private docLengths;
|
|
164
111
|
/** BM25: average document length across the entire index. */
|
|
165
112
|
private avgDocLength;
|
|
166
|
-
/** Cached total estimated token cost across all indexed tools. */
|
|
167
|
-
private totalTokenCost;
|
|
168
113
|
private options;
|
|
169
114
|
constructor(options?: ToolIndexOptions);
|
|
170
115
|
/**
|
|
@@ -203,17 +148,11 @@ declare class ToolIndex {
|
|
|
203
148
|
}): ToolListResult;
|
|
204
149
|
/** Number of indexed tools (including duplicates). */
|
|
205
150
|
get size(): number;
|
|
206
|
-
/** Total estimated token cost of all indexed tool schemas. */
|
|
207
|
-
getTotalTokenCost(): number;
|
|
208
|
-
/**
|
|
209
|
-
* Estimate token count of a tool's full schema (name + description + inputSchema).
|
|
210
|
-
*
|
|
211
|
-
* Uses character-class weighted counting calibrated against cl100k_base.
|
|
212
|
-
* Accuracy is typically within ±10% for JSON Schema payloads.
|
|
213
|
-
*/
|
|
214
|
-
static estimateTokens(tool: Tool): number;
|
|
215
151
|
/** Build a single searchable string from tool metadata. */
|
|
216
152
|
private buildSearchableText;
|
|
153
|
+
/** Recursively collect JSON Schema argument names and descriptions. */
|
|
154
|
+
private collectSchemaSearchText;
|
|
155
|
+
private pushStringValue;
|
|
217
156
|
private getDocumentKey;
|
|
218
157
|
private matchesServer;
|
|
219
158
|
/** Simple whitespace + camelCase + snake_case tokenizer. */
|
|
@@ -222,6 +161,72 @@ declare class ToolIndex {
|
|
|
222
161
|
private cosineSimilarity;
|
|
223
162
|
}
|
|
224
163
|
|
|
164
|
+
/**
|
|
165
|
+
* SchemaCompressor — Utilities for compact tool representations.
|
|
166
|
+
*
|
|
167
|
+
* Provides compact representations of tools (name + description only,
|
|
168
|
+
* no inputSchema).
|
|
169
|
+
*
|
|
170
|
+
* @packageDocumentation
|
|
171
|
+
*/
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* A minimal tool representation containing only what an LLM needs to
|
|
175
|
+
* *decide whether* to use a tool. The full `inputSchema` is deferred.
|
|
176
|
+
*/
|
|
177
|
+
interface CompactTool {
|
|
178
|
+
name: string;
|
|
179
|
+
description?: string;
|
|
180
|
+
/**
|
|
181
|
+
* Human-readable hint about the expected parameters.
|
|
182
|
+
* e.g. "(location: string, unit?: 'celsius' | 'fahrenheit')"
|
|
183
|
+
*/
|
|
184
|
+
parameterHint?: string;
|
|
185
|
+
}
|
|
186
|
+
declare class SchemaCompressor {
|
|
187
|
+
/**
|
|
188
|
+
* Convert a full MCP Tool definition to a compact summary.
|
|
189
|
+
*
|
|
190
|
+
* The compact form omits `inputSchema` entirely and optionally generates
|
|
191
|
+
* a short `parameterHint` from the schema's top-level properties.
|
|
192
|
+
*/
|
|
193
|
+
static toCompact(tool: Tool): CompactTool;
|
|
194
|
+
/**
|
|
195
|
+
* Convert an array of tools to compact form, optionally limiting the count.
|
|
196
|
+
*/
|
|
197
|
+
static compactAll(tools: Tool[], options?: {
|
|
198
|
+
maxTools?: number;
|
|
199
|
+
}): CompactTool[];
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* ToolRouter — Middleware layer for intelligent MCP tool selection.
|
|
204
|
+
*
|
|
205
|
+
* Sits between your AI framework adapter and MultiSessionClient to reduce
|
|
206
|
+
* context window usage. Supports three strategies:
|
|
207
|
+
*
|
|
208
|
+
* • `all` — Pass through every tool (backward-compatible default)
|
|
209
|
+
* • `search` — Expose only meta-tools; LLM discovers tools on-demand
|
|
210
|
+
* • `groups` — Expose tools from active groups only
|
|
211
|
+
*
|
|
212
|
+
* Inspired by Anthropic's `defer_loading` + `tool_search_tool` pattern.
|
|
213
|
+
*
|
|
214
|
+
* @example
|
|
215
|
+
* ```ts
|
|
216
|
+
* import { ToolRouter } from '@mcp-ts/sdk/shared';
|
|
217
|
+
* import { AIAdapter } from '@mcp-ts/sdk/adapters/ai';
|
|
218
|
+
*
|
|
219
|
+
* const router = new ToolRouter(multiSessionClient, {
|
|
220
|
+
* strategy: 'search',
|
|
221
|
+
* maxTools: 5,
|
|
222
|
+
* });
|
|
223
|
+
*
|
|
224
|
+
* const tools = await AIAdapter.getTools(multiSessionClient, { toolRouter: router });
|
|
225
|
+
* ```
|
|
226
|
+
*
|
|
227
|
+
* @packageDocumentation
|
|
228
|
+
*/
|
|
229
|
+
|
|
225
230
|
type ToolRouterStrategy = 'all' | 'search' | 'groups';
|
|
226
231
|
interface ToolRouterOptions {
|
|
227
232
|
/**
|
|
@@ -264,6 +269,15 @@ interface ToolRouterOptions {
|
|
|
264
269
|
* @default false
|
|
265
270
|
*/
|
|
266
271
|
compactSchemas?: boolean;
|
|
272
|
+
/**
|
|
273
|
+
* Tool names to expose directly when using `search` strategy.
|
|
274
|
+
* Pinned tools are removed from discovery results and should be called directly.
|
|
275
|
+
*/
|
|
276
|
+
pinnedTools?: string[];
|
|
277
|
+
/**
|
|
278
|
+
* Tool names or glob-style patterns to omit entirely from the router catalog.
|
|
279
|
+
*/
|
|
280
|
+
excludeTools?: string[];
|
|
267
281
|
/**
|
|
268
282
|
* Optional embedding function for semantic search.
|
|
269
283
|
* When not provided, keyword TF-IDF matching is used.
|
|
@@ -291,12 +305,16 @@ declare class ToolRouter {
|
|
|
291
305
|
private options;
|
|
292
306
|
private index;
|
|
293
307
|
private allTools;
|
|
308
|
+
private pinnedTools;
|
|
309
|
+
private discoverableTools;
|
|
294
310
|
private groupsMap;
|
|
295
311
|
private strategy;
|
|
296
312
|
private maxTools;
|
|
297
313
|
private compactSchemas;
|
|
298
314
|
private activeGroups;
|
|
299
315
|
private customGroups?;
|
|
316
|
+
private pinnedToolNames;
|
|
317
|
+
private excludeToolMatchers;
|
|
300
318
|
private initialized;
|
|
301
319
|
constructor(client: ToolRouterClientInput, options?: ToolRouterOptions);
|
|
302
320
|
/**
|
|
@@ -340,12 +358,6 @@ declare class ToolRouter {
|
|
|
340
358
|
setActiveGroups(groups: string[]): void;
|
|
341
359
|
/** Get the names of currently active groups. */
|
|
342
360
|
getActiveGroups(): string[];
|
|
343
|
-
/** Total token cost of all tools if loaded without filtering. */
|
|
344
|
-
getTotalTokenCost(): number;
|
|
345
|
-
/** Estimate token cost of the currently filtered tool set. */
|
|
346
|
-
getFilteredTokenCost(): Promise<number>;
|
|
347
|
-
/** Get compression stats showing savings from current strategy. */
|
|
348
|
-
getCompressionStats(): CompressionStats;
|
|
349
361
|
/** Number of total indexed tools. */
|
|
350
362
|
get totalToolCount(): number;
|
|
351
363
|
/** Change strategy at runtime. */
|
|
@@ -372,6 +384,8 @@ declare class ToolRouter {
|
|
|
372
384
|
private getGroupFilteredTools;
|
|
373
385
|
/** The 4 meta-tool definitions exposed in `search` strategy. */
|
|
374
386
|
private getMetaToolDefinitions;
|
|
387
|
+
private matchesPinnedTool;
|
|
388
|
+
private matchesExcludedTool;
|
|
375
389
|
}
|
|
376
390
|
|
|
377
|
-
export { type CompactTool as C, type EmbedFn as E, type IndexedTool as I, SchemaCompressor as S, type ToolGroupInfo as T,
|
|
391
|
+
export { type CompactTool as C, type EmbedFn as E, type IndexedTool as I, SchemaCompressor as S, type ToolGroupInfo as T, ToolIndex as a, type ToolIndexOptions as b, type ToolListResult as c, ToolRouter as d, type ToolRouterClientInput as e, type ToolRouterOptions as f, type ToolRouterStrategy as g, type ToolSearchOptions as h, type ToolServerSummary as i, type ToolSummary as j };
|
|
@@ -79,10 +79,11 @@ declare function isCallToolSuccess(response: CallToolResponse): response is Call
|
|
|
79
79
|
type ToolInfo = {
|
|
80
80
|
name: string;
|
|
81
81
|
description?: string;
|
|
82
|
-
inputSchema?:
|
|
82
|
+
inputSchema?: Tool['inputSchema'];
|
|
83
|
+
outputSchema?: Tool['outputSchema'];
|
|
83
84
|
};
|
|
84
|
-
type TransportType = 'sse' | '
|
|
85
|
-
type McpRpcMethod = 'connect' | 'disconnect' | 'listTools' | 'callTool' | '
|
|
85
|
+
type TransportType = 'sse' | 'streamable-http';
|
|
86
|
+
type McpRpcMethod = 'connect' | 'disconnect' | 'listTools' | 'callTool' | 'listSessions' | 'getSession' | 'finishAuth' | 'listPrompts' | 'getPrompt' | 'listResources' | 'readResource';
|
|
86
87
|
interface McpRpcRequest {
|
|
87
88
|
id: string;
|
|
88
89
|
method: McpRpcMethod;
|
|
@@ -152,7 +153,7 @@ interface ConnectResult {
|
|
|
152
153
|
interface DisconnectResult {
|
|
153
154
|
success: boolean;
|
|
154
155
|
}
|
|
155
|
-
interface
|
|
156
|
+
interface GetSessionResult {
|
|
156
157
|
success: boolean;
|
|
157
158
|
toolCount: number;
|
|
158
159
|
}
|
|
@@ -183,4 +184,4 @@ interface ListResourcesResult {
|
|
|
183
184
|
}>;
|
|
184
185
|
}
|
|
185
186
|
|
|
186
|
-
export { isConnectSuccess as A, isListToolsSuccess as B, type CallToolParams as C, type DisconnectParams as D, type FinishAuthParams as F, type GetPromptParams as G, type ListPromptsResult as L, type McpRpcMethod as M, type ReadResourceParams as R, type SessionInfo as S, type ToolClient as T, type CallToolRequest as a, type CallToolResponse as b, type ConnectAuthRequiredResponse as c, type ConnectErrorResponse as d, type ConnectParams as e, type ConnectRequest as f, type ConnectResponse as g, type ConnectResult as h, type ConnectSuccessResponse as i, type DisconnectResult as j, type FinishAuthResult as k, type
|
|
187
|
+
export { isConnectSuccess as A, isListToolsSuccess as B, type CallToolParams as C, type DisconnectParams as D, type FinishAuthParams as F, type GetPromptParams as G, type ListPromptsResult as L, type McpRpcMethod as M, type ReadResourceParams as R, type SessionInfo as S, type ToolClient as T, type CallToolRequest as a, type CallToolResponse as b, type ConnectAuthRequiredResponse as c, type ConnectErrorResponse as d, type ConnectParams as e, type ConnectRequest as f, type ConnectResponse as g, type ConnectResult as h, type ConnectSuccessResponse as i, type DisconnectResult as j, type FinishAuthResult as k, type GetSessionResult as l, type ListResourcesResult as m, type ListToolsResponse as n, type ListToolsRpcResult as o, type McpRpcParams as p, type McpRpcRequest as q, type McpRpcResponse as r, type SessionListResult as s, type SessionParams as t, type ToolClientProvider as u, type ToolInfo as v, type TransportType as w, isCallToolSuccess as x, isConnectAuthRequired as y, isConnectError as z };
|
|
@@ -79,10 +79,11 @@ declare function isCallToolSuccess(response: CallToolResponse): response is Call
|
|
|
79
79
|
type ToolInfo = {
|
|
80
80
|
name: string;
|
|
81
81
|
description?: string;
|
|
82
|
-
inputSchema?:
|
|
82
|
+
inputSchema?: Tool['inputSchema'];
|
|
83
|
+
outputSchema?: Tool['outputSchema'];
|
|
83
84
|
};
|
|
84
|
-
type TransportType = 'sse' | '
|
|
85
|
-
type McpRpcMethod = 'connect' | 'disconnect' | 'listTools' | 'callTool' | '
|
|
85
|
+
type TransportType = 'sse' | 'streamable-http';
|
|
86
|
+
type McpRpcMethod = 'connect' | 'disconnect' | 'listTools' | 'callTool' | 'listSessions' | 'getSession' | 'finishAuth' | 'listPrompts' | 'getPrompt' | 'listResources' | 'readResource';
|
|
86
87
|
interface McpRpcRequest {
|
|
87
88
|
id: string;
|
|
88
89
|
method: McpRpcMethod;
|
|
@@ -152,7 +153,7 @@ interface ConnectResult {
|
|
|
152
153
|
interface DisconnectResult {
|
|
153
154
|
success: boolean;
|
|
154
155
|
}
|
|
155
|
-
interface
|
|
156
|
+
interface GetSessionResult {
|
|
156
157
|
success: boolean;
|
|
157
158
|
toolCount: number;
|
|
158
159
|
}
|
|
@@ -183,4 +184,4 @@ interface ListResourcesResult {
|
|
|
183
184
|
}>;
|
|
184
185
|
}
|
|
185
186
|
|
|
186
|
-
export { isConnectSuccess as A, isListToolsSuccess as B, type CallToolParams as C, type DisconnectParams as D, type FinishAuthParams as F, type GetPromptParams as G, type ListPromptsResult as L, type McpRpcMethod as M, type ReadResourceParams as R, type SessionInfo as S, type ToolClient as T, type CallToolRequest as a, type CallToolResponse as b, type ConnectAuthRequiredResponse as c, type ConnectErrorResponse as d, type ConnectParams as e, type ConnectRequest as f, type ConnectResponse as g, type ConnectResult as h, type ConnectSuccessResponse as i, type DisconnectResult as j, type FinishAuthResult as k, type
|
|
187
|
+
export { isConnectSuccess as A, isListToolsSuccess as B, type CallToolParams as C, type DisconnectParams as D, type FinishAuthParams as F, type GetPromptParams as G, type ListPromptsResult as L, type McpRpcMethod as M, type ReadResourceParams as R, type SessionInfo as S, type ToolClient as T, type CallToolRequest as a, type CallToolResponse as b, type ConnectAuthRequiredResponse as c, type ConnectErrorResponse as d, type ConnectParams as e, type ConnectRequest as f, type ConnectResponse as g, type ConnectResult as h, type ConnectSuccessResponse as i, type DisconnectResult as j, type FinishAuthResult as k, type GetSessionResult as l, type ListResourcesResult as m, type ListToolsResponse as n, type ListToolsRpcResult as o, type McpRpcParams as p, type McpRpcRequest as q, type McpRpcResponse as r, type SessionListResult as s, type SessionParams as t, type ToolClientProvider as u, type ToolInfo as v, type TransportType as w, isCallToolSuccess as x, isConnectAuthRequired as y, isConnectError as z };
|
|
@@ -75,7 +75,7 @@ declare class ToolExecutionError extends McpError {
|
|
|
75
75
|
*/
|
|
76
76
|
declare const RpcErrorCodes: {
|
|
77
77
|
readonly EXECUTION_ERROR: "EXECUTION_ERROR";
|
|
78
|
-
readonly
|
|
78
|
+
readonly MISSING_USER_ID: "MISSING_USER_ID";
|
|
79
79
|
readonly UNAUTHORIZED: "UNAUTHORIZED";
|
|
80
80
|
readonly NO_CONNECTION: "NO_CONNECTION";
|
|
81
81
|
readonly UNKNOWN_METHOD: "UNKNOWN_METHOD";
|
|
@@ -75,7 +75,7 @@ declare class ToolExecutionError extends McpError {
|
|
|
75
75
|
*/
|
|
76
76
|
declare const RpcErrorCodes: {
|
|
77
77
|
readonly EXECUTION_ERROR: "EXECUTION_ERROR";
|
|
78
|
-
readonly
|
|
78
|
+
readonly MISSING_USER_ID: "MISSING_USER_ID";
|
|
79
79
|
readonly UNAUTHORIZED: "UNAUTHORIZED";
|
|
80
80
|
readonly NO_CONNECTION: "NO_CONNECTION";
|
|
81
81
|
readonly UNKNOWN_METHOD: "UNKNOWN_METHOD";
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
-- Create the mcp_sessions table for Neon Postgres.
|
|
2
|
+
-- Run this with an owner/admin role, then grant app access with the least-privilege SQL below.
|
|
3
|
+
|
|
4
|
+
CREATE TABLE IF NOT EXISTS public.mcp_sessions (
|
|
5
|
+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
6
|
+
session_id TEXT NOT NULL UNIQUE,
|
|
7
|
+
user_id TEXT NOT NULL,
|
|
8
|
+
server_id TEXT,
|
|
9
|
+
server_name TEXT,
|
|
10
|
+
server_url TEXT NOT NULL,
|
|
11
|
+
transport_type TEXT NOT NULL,
|
|
12
|
+
callback_url TEXT NOT NULL,
|
|
13
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
14
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
15
|
+
expires_at TIMESTAMPTZ NOT NULL,
|
|
16
|
+
active BOOLEAN DEFAULT false,
|
|
17
|
+
headers JSONB,
|
|
18
|
+
client_information JSONB,
|
|
19
|
+
tokens JSONB,
|
|
20
|
+
code_verifier TEXT,
|
|
21
|
+
client_id TEXT
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
CREATE INDEX IF NOT EXISTS idx_mcp_sessions_user_id ON public.mcp_sessions(user_id);
|
|
25
|
+
CREATE INDEX IF NOT EXISTS idx_mcp_sessions_expires_at ON public.mcp_sessions(expires_at);
|
|
26
|
+
|
|
27
|
+
CREATE OR REPLACE FUNCTION public.set_current_timestamp_updated_at()
|
|
28
|
+
RETURNS TRIGGER AS $$
|
|
29
|
+
BEGIN
|
|
30
|
+
NEW.updated_at = now();
|
|
31
|
+
RETURN NEW;
|
|
32
|
+
END;
|
|
33
|
+
$$ LANGUAGE plpgsql;
|
|
34
|
+
|
|
35
|
+
DROP TRIGGER IF EXISTS trg_mcp_sessions_updated_at ON public.mcp_sessions;
|
|
36
|
+
|
|
37
|
+
CREATE TRIGGER trg_mcp_sessions_updated_at
|
|
38
|
+
BEFORE UPDATE ON public.mcp_sessions
|
|
39
|
+
FOR EACH ROW
|
|
40
|
+
EXECUTE FUNCTION public.set_current_timestamp_updated_at();
|
|
41
|
+
|
|
42
|
+
-- Optional production configuration:
|
|
43
|
+
-- Create a dedicated app role and use its credentials in NEON_DATABASE_URL.
|
|
44
|
+
-- Replace neondb and the password before running.
|
|
45
|
+
--
|
|
46
|
+
-- CREATE ROLE mcp_service_role LOGIN PASSWORD 'replace-with-a-strong-password';
|
|
47
|
+
-- GRANT CONNECT ON DATABASE neondb TO mcp_service_role;
|
|
48
|
+
-- GRANT USAGE ON SCHEMA public TO mcp_service_role;
|
|
49
|
+
-- GRANT SELECT, INSERT, UPDATE, DELETE ON public.mcp_sessions TO mcp_service_role;
|
|
50
|
+
-- GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO mcp_service_role;
|
|
51
|
+
|
|
52
|
+
-- Optional RLS configuration:
|
|
53
|
+
-- Uncomment and run this block after creating mcp_service_role if you want
|
|
54
|
+
-- to enforce access through Row Level Security for the dedicated app role.
|
|
55
|
+
--
|
|
56
|
+
-- REVOKE ALL ON public.mcp_sessions FROM PUBLIC;
|
|
57
|
+
-- REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM PUBLIC;
|
|
58
|
+
--
|
|
59
|
+
-- GRANT SELECT, INSERT, UPDATE, DELETE ON public.mcp_sessions TO mcp_service_role;
|
|
60
|
+
-- GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO mcp_service_role;
|
|
61
|
+
--
|
|
62
|
+
-- ALTER TABLE public.mcp_sessions ENABLE ROW LEVEL SECURITY;
|
|
63
|
+
--
|
|
64
|
+
-- CREATE POLICY mcp_service_role_full_access
|
|
65
|
+
-- ON public.mcp_sessions
|
|
66
|
+
-- FOR ALL
|
|
67
|
+
-- TO mcp_service_role
|
|
68
|
+
-- USING (true)
|
|
69
|
+
-- WITH CHECK (true);
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
-- Optional Neon pg_cron cleanup jobs.
|
|
2
|
+
--
|
|
3
|
+
-- Neon pg_cron requires endpoint-level setup before this migration can run:
|
|
4
|
+
-- configure cron.database_name for your compute endpoint, restart the compute,
|
|
5
|
+
-- then install/schedule jobs from the target database.
|
|
6
|
+
--
|
|
7
|
+
-- If pg_cron is not enabled for your Neon project, skip this migration and run
|
|
8
|
+
-- storage.cleanupExpiredSessions() from your application scheduler instead.
|
|
9
|
+
|
|
10
|
+
CREATE EXTENSION IF NOT EXISTS pg_cron;
|
|
11
|
+
|
|
12
|
+
-- Keep reruns idempotent without NOTICE noise.
|
|
13
|
+
SELECT cron.unschedule(jobname)
|
|
14
|
+
FROM cron.job
|
|
15
|
+
WHERE jobname IN (
|
|
16
|
+
'mcp-cleanup-transient-sessions',
|
|
17
|
+
'mcp-cleanup-dormant-sessions'
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
-- Stage 1: Short-term Transient Purge (every 5 minutes)
|
|
21
|
+
-- Removes failed connections, abandoned OAuth flows, and other inactive
|
|
22
|
+
-- sessions whose TTL has expired.
|
|
23
|
+
SELECT cron.schedule(
|
|
24
|
+
'mcp-cleanup-transient-sessions',
|
|
25
|
+
'*/5 * * * *',
|
|
26
|
+
$$DELETE FROM public.mcp_sessions WHERE expires_at < now() AND active IS NOT TRUE;$$
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
-- Stage 2: Long-term Dormancy Eviction (daily at midnight UTC)
|
|
30
|
+
-- Removes active sessions that have not been touched for 30+ days.
|
|
31
|
+
SELECT cron.schedule(
|
|
32
|
+
'mcp-cleanup-dormant-sessions',
|
|
33
|
+
'0 0 * * *',
|
|
34
|
+
$$DELETE FROM public.mcp_sessions WHERE active = true AND updated_at < now() - interval '30 days';$$
|
|
35
|
+
);
|