@mcp-ts/sdk 1.6.2 → 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.
Files changed (113) hide show
  1. package/README.md +12 -6
  2. package/dist/adapters/agui-adapter.d.mts +3 -3
  3. package/dist/adapters/agui-adapter.d.ts +3 -3
  4. package/dist/adapters/agui-adapter.js +4 -5
  5. package/dist/adapters/agui-adapter.js.map +1 -1
  6. package/dist/adapters/agui-adapter.mjs +4 -5
  7. package/dist/adapters/agui-adapter.mjs.map +1 -1
  8. package/dist/adapters/agui-middleware.d.mts +3 -3
  9. package/dist/adapters/agui-middleware.d.ts +3 -3
  10. package/dist/adapters/ai-adapter.d.mts +9 -3
  11. package/dist/adapters/ai-adapter.d.ts +9 -3
  12. package/dist/adapters/ai-adapter.js +20 -6
  13. package/dist/adapters/ai-adapter.js.map +1 -1
  14. package/dist/adapters/ai-adapter.mjs +20 -6
  15. package/dist/adapters/ai-adapter.mjs.map +1 -1
  16. package/dist/adapters/langchain-adapter.d.mts +3 -3
  17. package/dist/adapters/langchain-adapter.d.ts +3 -3
  18. package/dist/adapters/langchain-adapter.js +9 -6
  19. package/dist/adapters/langchain-adapter.js.map +1 -1
  20. package/dist/adapters/langchain-adapter.mjs +9 -6
  21. package/dist/adapters/langchain-adapter.mjs.map +1 -1
  22. package/dist/adapters/mastra-adapter.d.mts +1 -1
  23. package/dist/adapters/mastra-adapter.d.ts +1 -1
  24. package/dist/adapters/mastra-adapter.js +5 -1
  25. package/dist/adapters/mastra-adapter.js.map +1 -1
  26. package/dist/adapters/mastra-adapter.mjs +5 -1
  27. package/dist/adapters/mastra-adapter.mjs.map +1 -1
  28. package/dist/bin/mcp-ts.js +7 -1
  29. package/dist/bin/mcp-ts.js.map +1 -1
  30. package/dist/bin/mcp-ts.mjs +7 -1
  31. package/dist/bin/mcp-ts.mjs.map +1 -1
  32. package/dist/client/index.d.mts +2 -2
  33. package/dist/client/index.d.ts +2 -2
  34. package/dist/client/index.js +9 -13
  35. package/dist/client/index.js.map +1 -1
  36. package/dist/client/index.mjs +9 -13
  37. package/dist/client/index.mjs.map +1 -1
  38. package/dist/client/react.d.mts +7 -7
  39. package/dist/client/react.d.ts +7 -7
  40. package/dist/client/react.js +15 -19
  41. package/dist/client/react.js.map +1 -1
  42. package/dist/client/react.mjs +15 -19
  43. package/dist/client/react.mjs.map +1 -1
  44. package/dist/client/vue.d.mts +7 -7
  45. package/dist/client/vue.d.ts +7 -7
  46. package/dist/client/vue.js +14 -18
  47. package/dist/client/vue.js.map +1 -1
  48. package/dist/client/vue.mjs +14 -18
  49. package/dist/client/vue.mjs.map +1 -1
  50. package/dist/{index-DhA-OEAe.d.ts → index-C9gvpxy5.d.ts} +5 -5
  51. package/dist/{index-bFL4ZF2N.d.mts → index-eaH14_5u.d.mts} +5 -5
  52. package/dist/index.d.mts +6 -6
  53. package/dist/index.d.ts +6 -6
  54. package/dist/index.js +616 -370
  55. package/dist/index.js.map +1 -1
  56. package/dist/index.mjs +615 -370
  57. package/dist/index.mjs.map +1 -1
  58. package/dist/{multi-session-client-CHE8QpVE.d.ts → multi-session-client-BYtguGJm.d.ts} +22 -22
  59. package/dist/{multi-session-client-CQsRbxYI.d.mts → multi-session-client-DYNe6az3.d.mts} +22 -22
  60. package/dist/server/index.d.mts +31 -34
  61. package/dist/server/index.d.ts +31 -34
  62. package/dist/server/index.js +531 -256
  63. package/dist/server/index.js.map +1 -1
  64. package/dist/server/index.mjs +530 -256
  65. package/dist/server/index.mjs.map +1 -1
  66. package/dist/shared/index.d.mts +5 -5
  67. package/dist/shared/index.d.ts +5 -5
  68. package/dist/shared/index.js +76 -101
  69. package/dist/shared/index.js.map +1 -1
  70. package/dist/shared/index.mjs +76 -101
  71. package/dist/shared/index.mjs.map +1 -1
  72. package/dist/{tool-router-Dh2804tM.d.ts → tool-router-Ddtybmr0.d.ts} +71 -73
  73. package/dist/{tool-router-BVaV1udm.d.mts → tool-router-Dnd6IOKC.d.mts} +71 -73
  74. package/dist/{types-rIuN1CQi.d.mts → types-BCAG20P6.d.mts} +4 -4
  75. package/dist/{types-rIuN1CQi.d.ts → types-BCAG20P6.d.ts} +4 -4
  76. package/dist/{utils-0qmYrqoa.d.mts → utils-DELRKQPU.d.mts} +1 -1
  77. package/dist/{utils-0qmYrqoa.d.ts → utils-DELRKQPU.d.ts} +1 -1
  78. package/migrations/neon/20260513010000_install_mcp_sessions.sql +69 -0
  79. package/migrations/neon/20260513020000_add_session_cleanup_cron.sql +35 -0
  80. package/{supabase/migrations → migrations/supabase}/20260330195700_install_mcp_sessions.sql +7 -9
  81. package/package.json +14 -5
  82. package/src/adapters/ai-adapter.ts +30 -1
  83. package/src/adapters/langchain-adapter.ts +6 -2
  84. package/src/adapters/mastra-adapter.ts +6 -2
  85. package/src/bin/mcp-ts.ts +8 -1
  86. package/src/client/core/app-host.ts +1 -1
  87. package/src/client/core/sse-client.ts +12 -14
  88. package/src/client/core/types.ts +1 -1
  89. package/src/client/react/use-mcp-apps.tsx +1 -1
  90. package/src/client/react/use-mcp.ts +11 -11
  91. package/src/client/vue/use-mcp.ts +10 -10
  92. package/src/server/handlers/nextjs-handler.ts +18 -15
  93. package/src/server/handlers/sse-handler.ts +29 -29
  94. package/src/server/index.ts +1 -1
  95. package/src/server/mcp/multi-session-client.ts +17 -17
  96. package/src/server/mcp/oauth-client.ts +37 -37
  97. package/src/server/mcp/storage-oauth-provider.ts +17 -17
  98. package/src/server/storage/file-backend.ts +25 -25
  99. package/src/server/storage/index.ts +67 -10
  100. package/src/server/storage/memory-backend.ts +34 -34
  101. package/src/server/storage/neon-backend.ts +281 -0
  102. package/src/server/storage/redis-backend.ts +64 -64
  103. package/src/server/storage/sqlite-backend.ts +33 -33
  104. package/src/server/storage/supabase-backend.ts +23 -24
  105. package/src/server/storage/types.ts +18 -21
  106. package/src/shared/errors.ts +1 -1
  107. package/src/shared/index.ts +1 -2
  108. package/src/shared/meta-tools.ts +4 -6
  109. package/src/shared/schema-compressor.ts +2 -42
  110. package/src/shared/tool-index.ts +89 -84
  111. package/src/shared/tool-router.ts +0 -24
  112. package/src/shared/types.ts +4 -4
  113. /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-rIuN1CQi.js';
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-BCAG20P6.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 {
@@ -163,8 +109,6 @@ declare class ToolIndex {
163
109
  private docLengths;
164
110
  /** BM25: average document length across the entire index. */
165
111
  private avgDocLength;
166
- /** Cached total estimated token cost across all indexed tools. */
167
- private totalTokenCost;
168
112
  private options;
169
113
  constructor(options?: ToolIndexOptions);
170
114
  /**
@@ -203,17 +147,11 @@ declare class ToolIndex {
203
147
  }): ToolListResult;
204
148
  /** Number of indexed tools (including duplicates). */
205
149
  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
150
  /** Build a single searchable string from tool metadata. */
216
151
  private buildSearchableText;
152
+ /** Recursively collect JSON Schema argument names and descriptions. */
153
+ private collectSchemaSearchText;
154
+ private pushStringValue;
217
155
  private getDocumentKey;
218
156
  private matchesServer;
219
157
  /** Simple whitespace + camelCase + snake_case tokenizer. */
@@ -222,6 +160,72 @@ declare class ToolIndex {
222
160
  private cosineSimilarity;
223
161
  }
224
162
 
163
+ /**
164
+ * SchemaCompressor — Utilities for compact tool representations.
165
+ *
166
+ * Provides compact representations of tools (name + description only,
167
+ * no inputSchema).
168
+ *
169
+ * @packageDocumentation
170
+ */
171
+
172
+ /**
173
+ * A minimal tool representation containing only what an LLM needs to
174
+ * *decide whether* to use a tool. The full `inputSchema` is deferred.
175
+ */
176
+ interface CompactTool {
177
+ name: string;
178
+ description?: string;
179
+ /**
180
+ * Human-readable hint about the expected parameters.
181
+ * e.g. "(location: string, unit?: 'celsius' | 'fahrenheit')"
182
+ */
183
+ parameterHint?: string;
184
+ }
185
+ declare class SchemaCompressor {
186
+ /**
187
+ * Convert a full MCP Tool definition to a compact summary.
188
+ *
189
+ * The compact form omits `inputSchema` entirely and optionally generates
190
+ * a short `parameterHint` from the schema's top-level properties.
191
+ */
192
+ static toCompact(tool: Tool): CompactTool;
193
+ /**
194
+ * Convert an array of tools to compact form, optionally limiting the count.
195
+ */
196
+ static compactAll(tools: Tool[], options?: {
197
+ maxTools?: number;
198
+ }): CompactTool[];
199
+ }
200
+
201
+ /**
202
+ * ToolRouter — Middleware layer for intelligent MCP tool selection.
203
+ *
204
+ * Sits between your AI framework adapter and MultiSessionClient to reduce
205
+ * context window usage. Supports three strategies:
206
+ *
207
+ * • `all` — Pass through every tool (backward-compatible default)
208
+ * • `search` — Expose only meta-tools; LLM discovers tools on-demand
209
+ * • `groups` — Expose tools from active groups only
210
+ *
211
+ * Inspired by Anthropic's `defer_loading` + `tool_search_tool` pattern.
212
+ *
213
+ * @example
214
+ * ```ts
215
+ * import { ToolRouter } from '@mcp-ts/sdk/shared';
216
+ * import { AIAdapter } from '@mcp-ts/sdk/adapters/ai';
217
+ *
218
+ * const router = new ToolRouter(multiSessionClient, {
219
+ * strategy: 'search',
220
+ * maxTools: 5,
221
+ * });
222
+ *
223
+ * const tools = await AIAdapter.getTools(multiSessionClient, { toolRouter: router });
224
+ * ```
225
+ *
226
+ * @packageDocumentation
227
+ */
228
+
225
229
  type ToolRouterStrategy = 'all' | 'search' | 'groups';
226
230
  interface ToolRouterOptions {
227
231
  /**
@@ -340,12 +344,6 @@ declare class ToolRouter {
340
344
  setActiveGroups(groups: string[]): void;
341
345
  /** Get the names of currently active groups. */
342
346
  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
347
  /** Number of total indexed tools. */
350
348
  get totalToolCount(): number;
351
349
  /** Change strategy at runtime. */
@@ -374,4 +372,4 @@ declare class ToolRouter {
374
372
  private getMetaToolDefinitions;
375
373
  }
376
374
 
377
- export { type CompactTool as C, type EmbedFn as E, type IndexedTool as I, SchemaCompressor as S, type ToolGroupInfo as T, type CompressionStats as a, ToolIndex as b, type ToolIndexOptions as c, type ToolListResult as d, ToolRouter as e, type ToolRouterClientInput as f, type ToolRouterOptions as g, type ToolRouterStrategy as h, type ToolSearchOptions as i, type ToolServerSummary as j, type ToolSummary as k };
375
+ 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-rIuN1CQi.mjs';
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-BCAG20P6.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 {
@@ -163,8 +109,6 @@ declare class ToolIndex {
163
109
  private docLengths;
164
110
  /** BM25: average document length across the entire index. */
165
111
  private avgDocLength;
166
- /** Cached total estimated token cost across all indexed tools. */
167
- private totalTokenCost;
168
112
  private options;
169
113
  constructor(options?: ToolIndexOptions);
170
114
  /**
@@ -203,17 +147,11 @@ declare class ToolIndex {
203
147
  }): ToolListResult;
204
148
  /** Number of indexed tools (including duplicates). */
205
149
  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
150
  /** Build a single searchable string from tool metadata. */
216
151
  private buildSearchableText;
152
+ /** Recursively collect JSON Schema argument names and descriptions. */
153
+ private collectSchemaSearchText;
154
+ private pushStringValue;
217
155
  private getDocumentKey;
218
156
  private matchesServer;
219
157
  /** Simple whitespace + camelCase + snake_case tokenizer. */
@@ -222,6 +160,72 @@ declare class ToolIndex {
222
160
  private cosineSimilarity;
223
161
  }
224
162
 
163
+ /**
164
+ * SchemaCompressor — Utilities for compact tool representations.
165
+ *
166
+ * Provides compact representations of tools (name + description only,
167
+ * no inputSchema).
168
+ *
169
+ * @packageDocumentation
170
+ */
171
+
172
+ /**
173
+ * A minimal tool representation containing only what an LLM needs to
174
+ * *decide whether* to use a tool. The full `inputSchema` is deferred.
175
+ */
176
+ interface CompactTool {
177
+ name: string;
178
+ description?: string;
179
+ /**
180
+ * Human-readable hint about the expected parameters.
181
+ * e.g. "(location: string, unit?: 'celsius' | 'fahrenheit')"
182
+ */
183
+ parameterHint?: string;
184
+ }
185
+ declare class SchemaCompressor {
186
+ /**
187
+ * Convert a full MCP Tool definition to a compact summary.
188
+ *
189
+ * The compact form omits `inputSchema` entirely and optionally generates
190
+ * a short `parameterHint` from the schema's top-level properties.
191
+ */
192
+ static toCompact(tool: Tool): CompactTool;
193
+ /**
194
+ * Convert an array of tools to compact form, optionally limiting the count.
195
+ */
196
+ static compactAll(tools: Tool[], options?: {
197
+ maxTools?: number;
198
+ }): CompactTool[];
199
+ }
200
+
201
+ /**
202
+ * ToolRouter — Middleware layer for intelligent MCP tool selection.
203
+ *
204
+ * Sits between your AI framework adapter and MultiSessionClient to reduce
205
+ * context window usage. Supports three strategies:
206
+ *
207
+ * • `all` — Pass through every tool (backward-compatible default)
208
+ * • `search` — Expose only meta-tools; LLM discovers tools on-demand
209
+ * • `groups` — Expose tools from active groups only
210
+ *
211
+ * Inspired by Anthropic's `defer_loading` + `tool_search_tool` pattern.
212
+ *
213
+ * @example
214
+ * ```ts
215
+ * import { ToolRouter } from '@mcp-ts/sdk/shared';
216
+ * import { AIAdapter } from '@mcp-ts/sdk/adapters/ai';
217
+ *
218
+ * const router = new ToolRouter(multiSessionClient, {
219
+ * strategy: 'search',
220
+ * maxTools: 5,
221
+ * });
222
+ *
223
+ * const tools = await AIAdapter.getTools(multiSessionClient, { toolRouter: router });
224
+ * ```
225
+ *
226
+ * @packageDocumentation
227
+ */
228
+
225
229
  type ToolRouterStrategy = 'all' | 'search' | 'groups';
226
230
  interface ToolRouterOptions {
227
231
  /**
@@ -340,12 +344,6 @@ declare class ToolRouter {
340
344
  setActiveGroups(groups: string[]): void;
341
345
  /** Get the names of currently active groups. */
342
346
  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
347
  /** Number of total indexed tools. */
350
348
  get totalToolCount(): number;
351
349
  /** Change strategy at runtime. */
@@ -374,4 +372,4 @@ declare class ToolRouter {
374
372
  private getMetaToolDefinitions;
375
373
  }
376
374
 
377
- export { type CompactTool as C, type EmbedFn as E, type IndexedTool as I, SchemaCompressor as S, type ToolGroupInfo as T, type CompressionStats as a, ToolIndex as b, type ToolIndexOptions as c, type ToolListResult as d, ToolRouter as e, type ToolRouterClientInput as f, type ToolRouterOptions as g, type ToolRouterStrategy as h, type ToolSearchOptions as i, type ToolServerSummary as j, type ToolSummary as k };
375
+ 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 };
@@ -81,8 +81,8 @@ type ToolInfo = {
81
81
  description?: string;
82
82
  inputSchema?: unknown;
83
83
  };
84
- type TransportType = 'sse' | 'streamable_http';
85
- type McpRpcMethod = 'connect' | 'disconnect' | 'listTools' | 'callTool' | 'getSessions' | 'restoreSession' | 'finishAuth' | 'listPrompts' | 'getPrompt' | 'listResources' | 'readResource';
84
+ type TransportType = 'sse' | 'streamable-http';
85
+ type McpRpcMethod = 'connect' | 'disconnect' | 'listTools' | 'callTool' | 'listSessions' | 'getSession' | 'finishAuth' | 'listPrompts' | 'getPrompt' | 'listResources' | 'readResource';
86
86
  interface McpRpcRequest {
87
87
  id: string;
88
88
  method: McpRpcMethod;
@@ -152,7 +152,7 @@ interface ConnectResult {
152
152
  interface DisconnectResult {
153
153
  success: boolean;
154
154
  }
155
- interface RestoreSessionResult {
155
+ interface GetSessionResult {
156
156
  success: boolean;
157
157
  toolCount: number;
158
158
  }
@@ -183,4 +183,4 @@ interface ListResourcesResult {
183
183
  }>;
184
184
  }
185
185
 
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 ListResourcesResult as l, type ListToolsResponse as m, type ListToolsRpcResult as n, type McpRpcParams as o, type McpRpcRequest as p, type McpRpcResponse as q, type RestoreSessionResult 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 };
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 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 };
@@ -81,8 +81,8 @@ type ToolInfo = {
81
81
  description?: string;
82
82
  inputSchema?: unknown;
83
83
  };
84
- type TransportType = 'sse' | 'streamable_http';
85
- type McpRpcMethod = 'connect' | 'disconnect' | 'listTools' | 'callTool' | 'getSessions' | 'restoreSession' | 'finishAuth' | 'listPrompts' | 'getPrompt' | 'listResources' | 'readResource';
84
+ type TransportType = 'sse' | 'streamable-http';
85
+ type McpRpcMethod = 'connect' | 'disconnect' | 'listTools' | 'callTool' | 'listSessions' | 'getSession' | 'finishAuth' | 'listPrompts' | 'getPrompt' | 'listResources' | 'readResource';
86
86
  interface McpRpcRequest {
87
87
  id: string;
88
88
  method: McpRpcMethod;
@@ -152,7 +152,7 @@ interface ConnectResult {
152
152
  interface DisconnectResult {
153
153
  success: boolean;
154
154
  }
155
- interface RestoreSessionResult {
155
+ interface GetSessionResult {
156
156
  success: boolean;
157
157
  toolCount: number;
158
158
  }
@@ -183,4 +183,4 @@ interface ListResourcesResult {
183
183
  }>;
184
184
  }
185
185
 
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 ListResourcesResult as l, type ListToolsResponse as m, type ListToolsRpcResult as n, type McpRpcParams as o, type McpRpcRequest as p, type McpRpcResponse as q, type RestoreSessionResult 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 };
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 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 MISSING_IDENTITY: "MISSING_IDENTITY";
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 MISSING_IDENTITY: "MISSING_IDENTITY";
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
+ );
@@ -2,7 +2,7 @@
2
2
  CREATE TABLE IF NOT EXISTS public.mcp_sessions (
3
3
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
4
4
  session_id TEXT NOT NULL UNIQUE,
5
- user_id TEXT NOT NULL, -- Will store the Next.js user's ID or identity
5
+ user_id TEXT NOT NULL, -- Will store the application user's ID
6
6
  server_id TEXT,
7
7
  server_name TEXT,
8
8
  server_url TEXT NOT NULL,
@@ -12,7 +12,6 @@ CREATE TABLE IF NOT EXISTS public.mcp_sessions (
12
12
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
13
13
  expires_at TIMESTAMPTZ NOT NULL,
14
14
  active BOOLEAN DEFAULT false,
15
- identity TEXT NOT NULL,
16
15
  headers JSONB,
17
16
  client_information JSONB,
18
17
  tokens JSONB,
@@ -20,8 +19,7 @@ CREATE TABLE IF NOT EXISTS public.mcp_sessions (
20
19
  client_id TEXT
21
20
  );
22
21
 
23
- -- Add an index on identity and user_id for faster lookups
24
- CREATE INDEX IF NOT EXISTS idx_mcp_sessions_identity ON public.mcp_sessions(identity);
22
+ -- Add an index on user_id for faster lookups
25
23
  CREATE INDEX IF NOT EXISTS idx_mcp_sessions_user_id ON public.mcp_sessions(user_id);
26
24
  -- Add an index on expires_at to speed up the cleanup job
27
25
  CREATE INDEX IF NOT EXISTS idx_mcp_sessions_expires_at ON public.mcp_sessions(expires_at);
@@ -50,7 +48,7 @@ ON public.mcp_sessions
50
48
  FOR SELECT
51
49
  TO authenticated
52
50
  USING (
53
- auth.uid()::text = user_id OR auth.uid()::text = identity
51
+ auth.uid()::text = user_id
54
52
  );
55
53
 
56
54
  -- Policy 2: Users can insert their own sessions
@@ -59,7 +57,7 @@ ON public.mcp_sessions
59
57
  FOR INSERT
60
58
  TO authenticated
61
59
  WITH CHECK (
62
- auth.uid()::text = user_id OR auth.uid()::text = identity
60
+ auth.uid()::text = user_id
63
61
  );
64
62
 
65
63
  -- Policy 3: Users can update their own sessions
@@ -68,10 +66,10 @@ ON public.mcp_sessions
68
66
  FOR UPDATE
69
67
  TO authenticated
70
68
  USING (
71
- auth.uid()::text = user_id OR auth.uid()::text = identity
69
+ auth.uid()::text = user_id
72
70
  )
73
71
  WITH CHECK (
74
- auth.uid()::text = user_id OR auth.uid()::text = identity
72
+ auth.uid()::text = user_id
75
73
  );
76
74
 
77
75
  -- Policy 4: Users can delete their own sessions
@@ -80,5 +78,5 @@ ON public.mcp_sessions
80
78
  FOR DELETE
81
79
  TO authenticated
82
80
  USING (
83
- auth.uid()::text = user_id OR auth.uid()::text = identity
81
+ auth.uid()::text = user_id
84
82
  );