@mcp-ts/sdk 1.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 (107) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +297 -0
  3. package/dist/adapters/agui-adapter.d.mts +119 -0
  4. package/dist/adapters/agui-adapter.d.ts +119 -0
  5. package/dist/adapters/agui-adapter.js +109 -0
  6. package/dist/adapters/agui-adapter.js.map +1 -0
  7. package/dist/adapters/agui-adapter.mjs +107 -0
  8. package/dist/adapters/agui-adapter.mjs.map +1 -0
  9. package/dist/adapters/agui-middleware.d.mts +171 -0
  10. package/dist/adapters/agui-middleware.d.ts +171 -0
  11. package/dist/adapters/agui-middleware.js +429 -0
  12. package/dist/adapters/agui-middleware.js.map +1 -0
  13. package/dist/adapters/agui-middleware.mjs +417 -0
  14. package/dist/adapters/agui-middleware.mjs.map +1 -0
  15. package/dist/adapters/ai-adapter.d.mts +38 -0
  16. package/dist/adapters/ai-adapter.d.ts +38 -0
  17. package/dist/adapters/ai-adapter.js +82 -0
  18. package/dist/adapters/ai-adapter.js.map +1 -0
  19. package/dist/adapters/ai-adapter.mjs +80 -0
  20. package/dist/adapters/ai-adapter.mjs.map +1 -0
  21. package/dist/adapters/langchain-adapter.d.mts +46 -0
  22. package/dist/adapters/langchain-adapter.d.ts +46 -0
  23. package/dist/adapters/langchain-adapter.js +102 -0
  24. package/dist/adapters/langchain-adapter.js.map +1 -0
  25. package/dist/adapters/langchain-adapter.mjs +100 -0
  26. package/dist/adapters/langchain-adapter.mjs.map +1 -0
  27. package/dist/adapters/mastra-adapter.d.mts +49 -0
  28. package/dist/adapters/mastra-adapter.d.ts +49 -0
  29. package/dist/adapters/mastra-adapter.js +95 -0
  30. package/dist/adapters/mastra-adapter.js.map +1 -0
  31. package/dist/adapters/mastra-adapter.mjs +93 -0
  32. package/dist/adapters/mastra-adapter.mjs.map +1 -0
  33. package/dist/client/index.d.mts +119 -0
  34. package/dist/client/index.d.ts +119 -0
  35. package/dist/client/index.js +225 -0
  36. package/dist/client/index.js.map +1 -0
  37. package/dist/client/index.mjs +223 -0
  38. package/dist/client/index.mjs.map +1 -0
  39. package/dist/client/react.d.mts +151 -0
  40. package/dist/client/react.d.ts +151 -0
  41. package/dist/client/react.js +492 -0
  42. package/dist/client/react.js.map +1 -0
  43. package/dist/client/react.mjs +489 -0
  44. package/dist/client/react.mjs.map +1 -0
  45. package/dist/client/vue.d.mts +157 -0
  46. package/dist/client/vue.d.ts +157 -0
  47. package/dist/client/vue.js +474 -0
  48. package/dist/client/vue.js.map +1 -0
  49. package/dist/client/vue.mjs +471 -0
  50. package/dist/client/vue.mjs.map +1 -0
  51. package/dist/events-BP6WyRNh.d.mts +110 -0
  52. package/dist/events-BP6WyRNh.d.ts +110 -0
  53. package/dist/index.d.mts +10 -0
  54. package/dist/index.d.ts +10 -0
  55. package/dist/index.js +2784 -0
  56. package/dist/index.js.map +1 -0
  57. package/dist/index.mjs +2723 -0
  58. package/dist/index.mjs.map +1 -0
  59. package/dist/multi-session-client-BOFgPypS.d.ts +389 -0
  60. package/dist/multi-session-client-DMF3ED2O.d.mts +389 -0
  61. package/dist/server/index.d.mts +269 -0
  62. package/dist/server/index.d.ts +269 -0
  63. package/dist/server/index.js +2444 -0
  64. package/dist/server/index.js.map +1 -0
  65. package/dist/server/index.mjs +2414 -0
  66. package/dist/server/index.mjs.map +1 -0
  67. package/dist/shared/index.d.mts +24 -0
  68. package/dist/shared/index.d.ts +24 -0
  69. package/dist/shared/index.js +223 -0
  70. package/dist/shared/index.js.map +1 -0
  71. package/dist/shared/index.mjs +190 -0
  72. package/dist/shared/index.mjs.map +1 -0
  73. package/dist/types-SbDlA2VX.d.mts +153 -0
  74. package/dist/types-SbDlA2VX.d.ts +153 -0
  75. package/dist/utils-0qmYrqoa.d.mts +92 -0
  76. package/dist/utils-0qmYrqoa.d.ts +92 -0
  77. package/package.json +165 -0
  78. package/src/adapters/agui-adapter.ts +210 -0
  79. package/src/adapters/agui-middleware.ts +512 -0
  80. package/src/adapters/ai-adapter.ts +115 -0
  81. package/src/adapters/langchain-adapter.ts +127 -0
  82. package/src/adapters/mastra-adapter.ts +126 -0
  83. package/src/client/core/sse-client.ts +340 -0
  84. package/src/client/index.ts +26 -0
  85. package/src/client/react/index.ts +10 -0
  86. package/src/client/react/useMcp.ts +558 -0
  87. package/src/client/vue/index.ts +10 -0
  88. package/src/client/vue/useMcp.ts +542 -0
  89. package/src/index.ts +11 -0
  90. package/src/server/handlers/nextjs-handler.ts +216 -0
  91. package/src/server/handlers/sse-handler.ts +699 -0
  92. package/src/server/index.ts +57 -0
  93. package/src/server/mcp/multi-session-client.ts +132 -0
  94. package/src/server/mcp/oauth-client.ts +1168 -0
  95. package/src/server/mcp/storage-oauth-provider.ts +239 -0
  96. package/src/server/storage/file-backend.ts +169 -0
  97. package/src/server/storage/index.ts +115 -0
  98. package/src/server/storage/memory-backend.ts +132 -0
  99. package/src/server/storage/redis-backend.ts +210 -0
  100. package/src/server/storage/redis.ts +160 -0
  101. package/src/server/storage/types.ts +109 -0
  102. package/src/shared/constants.ts +29 -0
  103. package/src/shared/errors.ts +133 -0
  104. package/src/shared/events.ts +166 -0
  105. package/src/shared/index.ts +70 -0
  106. package/src/shared/types.ts +274 -0
  107. package/src/shared/utils.ts +16 -0
@@ -0,0 +1,389 @@
1
+ import { b as Event, M as McpConnectionEvent, d as McpObservabilityEvent, c as McpConnectionState } from './events-BP6WyRNh.mjs';
2
+ import { ListToolsResult, CallToolResult, ListPromptsResult, GetPromptResult, ListResourcesResult, ReadResourceResult } from '@modelcontextprotocol/sdk/types.js';
3
+ import { OAuthClientMetadata, OAuthClientInformation, OAuthClientInformationFull, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
4
+ import { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';
5
+
6
+ /**
7
+ * Extension of OAuthClientProvider interface with additional methods
8
+ * Enables server-specific tracking and state management
9
+ */
10
+ interface AgentsOAuthProvider extends OAuthClientProvider {
11
+ authUrl: string | undefined;
12
+ clientId: string | undefined;
13
+ serverId: string | undefined;
14
+ checkState(state: string): Promise<{
15
+ valid: boolean;
16
+ serverId?: string;
17
+ error?: string;
18
+ }>;
19
+ consumeState(state: string): Promise<void>;
20
+ deleteCodeVerifier(): Promise<void>;
21
+ isTokenExpired(): boolean;
22
+ setTokenExpiresAt(expiresAt: number): void;
23
+ }
24
+ /**
25
+ * Storage-backed OAuth provider implementation for MCP
26
+ * Stores OAuth tokens, client information, and PKCE verifiers using the configured StorageBackend
27
+ */
28
+ declare class StorageOAuthClientProvider implements AgentsOAuthProvider {
29
+ identity: string;
30
+ serverId: string;
31
+ sessionId: string;
32
+ clientName: string;
33
+ baseRedirectUrl: string;
34
+ private _authUrl;
35
+ private _clientId;
36
+ private onRedirectCallback?;
37
+ private tokenExpiresAt?;
38
+ /**
39
+ * Creates a new Storage-backed OAuth provider
40
+ * @param identity - User/Client identifier
41
+ * @param serverId - Server identifier (for tracking which server this OAuth session belongs to)
42
+ * @param sessionId - Session identifier (used as OAuth state)
43
+ * @param clientName - OAuth client name
44
+ * @param baseRedirectUrl - OAuth callback URL
45
+ * @param onRedirect - Optional callback when redirect to authorization is needed
46
+ */
47
+ constructor(identity: string, serverId: string, sessionId: string, clientName: string, baseRedirectUrl: string, onRedirect?: (url: string) => void);
48
+ get clientMetadata(): OAuthClientMetadata;
49
+ get clientUri(): string;
50
+ get redirectUrl(): string;
51
+ get clientId(): string | undefined;
52
+ set clientId(clientId_: string | undefined);
53
+ /**
54
+ * Loads OAuth data from storage session
55
+ * @private
56
+ */
57
+ private getSessionData;
58
+ /**
59
+ * Saves OAuth data to storage
60
+ * @param data - Partial OAuth data to save
61
+ * @private
62
+ * @throws Error if session doesn't exist (session must be created by controller layer)
63
+ */
64
+ private saveSessionData;
65
+ /**
66
+ * Retrieves stored OAuth client information
67
+ */
68
+ clientInformation(): Promise<OAuthClientInformation | undefined>;
69
+ /**
70
+ * Stores OAuth client information
71
+ */
72
+ saveClientInformation(clientInformation: OAuthClientInformationFull): Promise<void>;
73
+ /**
74
+ * Stores OAuth tokens
75
+ */
76
+ saveTokens(tokens: OAuthTokens): Promise<void>;
77
+ get authUrl(): string | undefined;
78
+ state(): Promise<string>;
79
+ checkState(state: string): Promise<{
80
+ valid: boolean;
81
+ serverId?: string;
82
+ error?: string;
83
+ }>;
84
+ consumeState(state: string): Promise<void>;
85
+ redirectToAuthorization(authUrl: URL): Promise<void>;
86
+ invalidateCredentials(scope: "all" | "client" | "tokens" | "verifier"): Promise<void>;
87
+ saveCodeVerifier(verifier: string): Promise<void>;
88
+ codeVerifier(): Promise<string>;
89
+ deleteCodeVerifier(): Promise<void>;
90
+ tokens(): Promise<OAuthTokens | undefined>;
91
+ isTokenExpired(): boolean;
92
+ setTokenExpiresAt(expiresAt: number): void;
93
+ }
94
+
95
+ /**
96
+ * Supported MCP transport types
97
+ */
98
+ type TransportType = 'sse' | 'streamable_http';
99
+ interface MCPOAuthClientOptions {
100
+ serverUrl?: string;
101
+ serverName?: string;
102
+ callbackUrl?: string;
103
+ onRedirect?: (url: string) => void;
104
+ identity: string;
105
+ serverId?: string; /** Optional - loaded from session if not provided */
106
+ sessionId: string; /** Required - primary key for session lookup */
107
+ transportType?: TransportType;
108
+ tokens?: OAuthTokens;
109
+ tokenExpiresAt?: number;
110
+ clientInformation?: OAuthClientInformationFull;
111
+ clientId?: string;
112
+ clientSecret?: string;
113
+ onSaveTokens?: (tokens: OAuthTokens) => void;
114
+ headers?: Record<string, string>;
115
+ /** OAuth Client Metadata (optional - user application info) */
116
+ clientName?: string;
117
+ clientUri?: string;
118
+ logoUri?: string;
119
+ policyUri?: string;
120
+ }
121
+ /**
122
+ * MCP Client with OAuth 2.1 authentication support
123
+ * Manages connections to MCP servers with automatic token refresh and session restoration
124
+ * Emits connection lifecycle events for observability
125
+ */
126
+ declare class MCPClient {
127
+ private client;
128
+ oauthProvider: AgentsOAuthProvider | null;
129
+ private transport;
130
+ private identity;
131
+ private serverId?;
132
+ private sessionId;
133
+ private serverName?;
134
+ private transportType;
135
+ private serverUrl;
136
+ private callbackUrl;
137
+ private onRedirect;
138
+ private tokens?;
139
+ private tokenExpiresAt?;
140
+ private clientInformation?;
141
+ private clientId?;
142
+ private clientSecret?;
143
+ private onSaveTokens?;
144
+ private headers?;
145
+ /** OAuth Client Metadata */
146
+ private clientName?;
147
+ private clientUri?;
148
+ private logoUri?;
149
+ private policyUri?;
150
+ /** Event emitters for connection lifecycle */
151
+ private readonly _onConnectionEvent;
152
+ readonly onConnectionEvent: Event<McpConnectionEvent>;
153
+ private readonly _onObservabilityEvent;
154
+ readonly onObservabilityEvent: Event<McpObservabilityEvent>;
155
+ private currentState;
156
+ /**
157
+ * Creates a new MCP client instance
158
+ * Can be initialized with minimal options (identity + sessionId) for session restoration
159
+ * @param options - Client configuration options
160
+ */
161
+ constructor(options: MCPOAuthClientOptions);
162
+ /**
163
+ * Emit a connection state change event
164
+ * @private
165
+ */
166
+ private emitStateChange;
167
+ /**
168
+ * Emit an error event
169
+ * @private
170
+ */
171
+ private emitError;
172
+ /**
173
+ * Emit a progress event
174
+ * @private
175
+ */
176
+ private emitProgress;
177
+ /**
178
+ * Get current connection state
179
+ */
180
+ getConnectionState(): McpConnectionState;
181
+ /**
182
+ * Helper to create a transport instance
183
+ * @param type - The transport type to create
184
+ * @returns Configured transport instance
185
+ * @private
186
+ */
187
+ private getTransport;
188
+ /**
189
+ * Initializes client components (client, transport, OAuth provider)
190
+ * Loads missing configuration from Redis session store if needed
191
+ * This method is idempotent and safe to call multiple times
192
+ * @private
193
+ */
194
+ private initialize;
195
+ /**
196
+ * Saves current session state to storage
197
+ * Creates new session if it doesn't exist, updates if it does
198
+ * @param ttl - Time-to-live in seconds (defaults to 12hr for connected sessions)
199
+ * @private
200
+ */
201
+ private saveSession;
202
+ /**
203
+ * Try to connect using available transports
204
+ * @returns The corrected transport type object if successful
205
+ * @private
206
+ */
207
+ private tryConnect;
208
+ /**
209
+ * Connects to the MCP server
210
+ * Automatically validates and refreshes OAuth tokens if needed
211
+ * Saves session to Redis on first successful connection
212
+ * @throws {UnauthorizedError} When OAuth authorization is required
213
+ * @throws {Error} When connection fails for other reasons
214
+ */
215
+ connect(): Promise<void>;
216
+ /**
217
+ * Completes OAuth authorization flow by exchanging authorization code for tokens
218
+ * Creates new authenticated client and transport, then establishes connection
219
+ * Saves active session to Redis after successful authentication
220
+ * @param authCode - Authorization code received from OAuth callback
221
+ */
222
+ finishAuth(authCode: string): Promise<void>;
223
+ /**
224
+ * Lists all available tools from the connected MCP server
225
+ * @returns List of tools with their schemas and descriptions
226
+ * @throws {Error} When client is not connected
227
+ */
228
+ listTools(): Promise<ListToolsResult>;
229
+ /**
230
+ * Executes a tool on the connected MCP server
231
+ * @param toolName - Name of the tool to execute
232
+ * @param toolArgs - Arguments to pass to the tool
233
+ * @returns Tool execution result
234
+ * @throws {Error} When client is not connected
235
+ */
236
+ callTool(toolName: string, toolArgs: Record<string, unknown>): Promise<CallToolResult>;
237
+ /**
238
+ * Lists all available prompts from the connected MCP server
239
+ * @returns List of available prompts
240
+ * @throws {Error} When client is not connected
241
+ */
242
+ listPrompts(): Promise<ListPromptsResult>;
243
+ /**
244
+ * Gets a specific prompt with arguments
245
+ * @param name - Name of the prompt
246
+ * @param args - Arguments for the prompt
247
+ * @returns Prompt content
248
+ * @throws {Error} When client is not connected
249
+ */
250
+ getPrompt(name: string, args?: Record<string, string>): Promise<GetPromptResult>;
251
+ /**
252
+ * Lists all available resources from the connected MCP server
253
+ * @returns List of available resources
254
+ * @throws {Error} When client is not connected
255
+ */
256
+ listResources(): Promise<ListResourcesResult>;
257
+ /**
258
+ * Reads a specific resource
259
+ * @param uri - URI of the resource to read
260
+ * @returns Resource content
261
+ * @throws {Error} When client is not connected
262
+ */
263
+ readResource(uri: string): Promise<ReadResourceResult>;
264
+ /**
265
+ * Refreshes the OAuth access token using the refresh token
266
+ * Discovers OAuth metadata from server and exchanges refresh token for new access token
267
+ * @returns True if refresh was successful, false otherwise
268
+ */
269
+ refreshToken(): Promise<boolean>;
270
+ /**
271
+ * Ensures OAuth tokens are valid, refreshing them if expired
272
+ * Called automatically by connect() - rarely needs to be called manually
273
+ * @returns True if valid tokens are available, false otherwise
274
+ */
275
+ getValidTokens(): Promise<boolean>;
276
+ /**
277
+ * Reconnects to MCP server using existing OAuth provider from Redis
278
+ * Used for session restoration in serverless environments
279
+ * Creates new client and transport without re-initializing OAuth provider
280
+ * @throws {Error} When OAuth provider is not initialized
281
+ */
282
+ reconnect(): Promise<void>;
283
+ /**
284
+ * Completely removes the session from Redis including all OAuth data
285
+ * Invalidates credentials and disconnects the client
286
+ */
287
+ clearSession(): Promise<void>;
288
+ /**
289
+ * Checks if the client is currently connected to an MCP server
290
+ * @returns True if connected, false otherwise
291
+ */
292
+ isConnected(): boolean;
293
+ /**
294
+ * Disconnects from the MCP server and cleans up resources
295
+ * Does not remove session from Redis - use clearSession() for that
296
+ */
297
+ disconnect(reason?: string): void;
298
+ /**
299
+ * Dispose of all event emitters
300
+ * Call this when the client is no longer needed
301
+ */
302
+ dispose(): void;
303
+ /**
304
+ * Gets the server URL
305
+ * @returns Server URL or empty string if not set
306
+ */
307
+ getServerUrl(): string;
308
+ /**
309
+ * Gets the OAuth callback URL
310
+ * @returns Callback URL or empty string if not set
311
+ */
312
+ getCallbackUrl(): string;
313
+ /**
314
+ * Gets the transport type being used
315
+ * @returns Transport type (defaults to 'streamable_http')
316
+ */
317
+ getTransportType(): TransportType;
318
+ /**
319
+ * Gets the human-readable server name
320
+ * @returns Server name or undefined
321
+ */
322
+ getServerName(): string | undefined;
323
+ /**
324
+ * Gets the server ID
325
+ * @returns Server ID or undefined
326
+ */
327
+ getServerId(): string | undefined;
328
+ /**
329
+ * Gets the session ID
330
+ * @returns Session ID
331
+ */
332
+ getSessionId(): string;
333
+ /**
334
+ * Gets MCP server configuration for all active user sessions
335
+ * Loads sessions from Redis, validates OAuth tokens, refreshes if expired
336
+ * Returns ready-to-use configuration with valid auth headers
337
+ * @param identity - User ID to fetch sessions for
338
+ * @returns Object keyed by sanitized server labels containing transport, url, headers, etc.
339
+ * @static
340
+ */
341
+ static getMcpServerConfig(identity: string): Promise<Record<string, any>>;
342
+ }
343
+
344
+ /**
345
+ * Manages multiple MCP connections for a single user identity.
346
+ * Allows aggregating tools from all connected servers.
347
+ */
348
+ interface MultiSessionOptions {
349
+ /**
350
+ * Connection timeout in milliseconds
351
+ * @default 15000
352
+ */
353
+ timeout?: number;
354
+ /**
355
+ * Maximum number of retry attempts
356
+ * @default 2
357
+ */
358
+ maxRetries?: number;
359
+ /**
360
+ * Delay between retries in milliseconds
361
+ * @default 1000
362
+ */
363
+ retryDelay?: number;
364
+ }
365
+ /**
366
+ * Manages multiple MCP connections for a single user identity.
367
+ * Allows aggregating tools from all connected servers.
368
+ */
369
+ declare class MultiSessionClient {
370
+ private clients;
371
+ private identity;
372
+ private options;
373
+ constructor(identity: string, options?: MultiSessionOptions);
374
+ private getActiveSessions;
375
+ private connectInBatches;
376
+ private connectSession;
377
+ private createAndConnectClient;
378
+ connect(): Promise<void>;
379
+ /**
380
+ * Returns the array of currently connected clients.
381
+ */
382
+ getClients(): MCPClient[];
383
+ /**
384
+ * Disconnects all clients.
385
+ */
386
+ disconnect(): void;
387
+ }
388
+
389
+ export { MCPClient as M, StorageOAuthClientProvider as S, MultiSessionClient as a };
@@ -0,0 +1,269 @@
1
+ export { M as MCPClient, a as MultiSessionClient, S as StorageOAuthClientProvider } from '../multi-session-client-DMF3ED2O.mjs';
2
+ export { U as UnauthorizedError, s as sanitizeServerLabel } from '../utils-0qmYrqoa.mjs';
3
+ import { OAuthClientInformationMixed, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
4
+ export { OAuthClientInformation, OAuthClientInformationFull, OAuthClientMetadata, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
5
+ import { M as McpConnectionEvent, d as McpObservabilityEvent } from '../events-BP6WyRNh.mjs';
6
+ export { D as Disposable, E as Emitter, b as Event, c as McpConnectionState } from '../events-BP6WyRNh.mjs';
7
+ import { q as McpRpcResponse, p as McpRpcRequest } from '../types-SbDlA2VX.mjs';
8
+ export { a as CallToolRequest, b as CallToolResponse, f as ConnectRequest, g as ConnectResponse, m as ListToolsResponse, T as ToolInfo } from '../types-SbDlA2VX.mjs';
9
+ export { CallToolResult, ListToolsResult, Tool } from '@modelcontextprotocol/sdk/types.js';
10
+ import '@modelcontextprotocol/sdk/client/auth.js';
11
+
12
+ interface SessionData {
13
+ sessionId: string;
14
+ serverId?: string;
15
+ serverName?: string;
16
+ serverUrl: string;
17
+ transportType: 'sse' | 'streamable_http';
18
+ callbackUrl: string;
19
+ createdAt: number;
20
+ identity?: string;
21
+ headers?: Record<string, string>;
22
+ clientInformation?: OAuthClientInformationMixed;
23
+ tokens?: OAuthTokens;
24
+ codeVerifier?: string;
25
+ clientId?: string;
26
+ }
27
+ /**
28
+ * Interface for MCP Session Storage Backends
29
+ */
30
+ interface StorageBackend {
31
+ /**
32
+ * Optional initialization (e.g., database connection)
33
+ */
34
+ init?(): Promise<void>;
35
+ /**
36
+ * Generates a unique session ID
37
+ */
38
+ generateSessionId(): string;
39
+ /**
40
+ * Stores or updates a session
41
+ */
42
+ /**
43
+ * Creates a new session. Throws if session already exists.
44
+ * @param session - Session data to create
45
+ * @param ttl - Optional TTL in seconds (defaults to backend's default)
46
+ */
47
+ createSession(session: SessionData, ttl?: number): Promise<void>;
48
+ /**
49
+ * Updates an existing session with partial data. Throws if session does not exist.
50
+ * @param identity - User identity
51
+ * @param sessionId - Session identifier
52
+ * @param data - Partial session data to update
53
+ * @param ttl - Optional TTL in seconds (defaults to backend's default)
54
+ */
55
+ updateSession(identity: string, sessionId: string, data: Partial<SessionData>, ttl?: number): Promise<void>;
56
+ /**
57
+ * Retrieves a session
58
+ */
59
+ getSession(identity: string, sessionId: string): Promise<SessionData | null>;
60
+ /**
61
+ * Gets full session data for all of an identity's sessions
62
+ */
63
+ getIdentitySessionsData(identity: string): Promise<SessionData[]>;
64
+ /**
65
+ * Removes a session
66
+ */
67
+ removeSession(identity: string, sessionId: string): Promise<void>;
68
+ /**
69
+ * Gets all sessions IDs of an identity
70
+ */
71
+ getIdentityMcpSessions(identity: string): Promise<string[]>;
72
+ /**
73
+ * Gets all session IDs across all users (Admin)
74
+ */
75
+ getAllSessionIds(): Promise<string[]>;
76
+ /**
77
+ * Clears all sessions (Admin)
78
+ */
79
+ clearAll(): Promise<void>;
80
+ /**
81
+ * Clean up expired sessions
82
+ */
83
+ cleanupExpiredSessions(): Promise<void>;
84
+ /**
85
+ * Disconnect from storage backend
86
+ */
87
+ disconnect(): Promise<void>;
88
+ }
89
+
90
+ /**
91
+ * Global session store instance
92
+ * Uses lazy initialization with a Proxy to handle async setup transparently
93
+ */
94
+ declare const storage: StorageBackend;
95
+
96
+ /**
97
+ * SSE (Server-Sent Events) Handler for MCP Connections
98
+ * Provides real-time connection state updates to clients
99
+ * Based on Cloudflare's agents pattern but adapted for HTTP/SSE
100
+ */
101
+
102
+ interface ClientMetadata {
103
+ clientName?: string;
104
+ clientUri?: string;
105
+ logoUri?: string;
106
+ policyUri?: string;
107
+ }
108
+ interface SSEHandlerOptions {
109
+ /**
110
+ * User/Client identifier
111
+ */
112
+ identity: string;
113
+ /**
114
+ * Optional callback for authentication/authorization
115
+ */
116
+ onAuth?: (identity: string) => Promise<boolean>;
117
+ /**
118
+ * Heartbeat interval in ms (default: 30000)
119
+ */
120
+ heartbeatInterval?: number;
121
+ /**
122
+ * Static OAuth client metadata defaults (for all connections)
123
+ */
124
+ clientDefaults?: ClientMetadata;
125
+ /**
126
+ * Dynamic OAuth client metadata getter (per-request, useful for multi-tenant)
127
+ * Takes precedence over clientDefaults
128
+ */
129
+ getClientMetadata?: (request?: any) => ClientMetadata | Promise<ClientMetadata>;
130
+ }
131
+ /**
132
+ * SSE Connection Manager
133
+ * Handles a single SSE connection and manages MCP operations
134
+ */
135
+ declare class SSEConnectionManager {
136
+ private options;
137
+ private sendEvent;
138
+ private identity;
139
+ private clients;
140
+ private heartbeatTimer?;
141
+ private isActive;
142
+ constructor(options: SSEHandlerOptions, sendEvent: (event: McpConnectionEvent | McpObservabilityEvent | McpRpcResponse) => void);
143
+ /**
144
+ * Get resolved client metadata (dynamic > static > defaults)
145
+ */
146
+ private getResolvedClientMetadata;
147
+ /**
148
+ * Start heartbeat to keep connection alive
149
+ */
150
+ private startHeartbeat;
151
+ /**
152
+ * Handle incoming RPC requests
153
+ */
154
+ handleRequest(request: McpRpcRequest): Promise<void>;
155
+ /**
156
+ * Get all user sessions
157
+ */
158
+ private getSessions;
159
+ /**
160
+ * Connect to an MCP server
161
+ */
162
+ private connect;
163
+ /**
164
+ * Disconnect from an MCP server
165
+ */
166
+ private disconnect;
167
+ /**
168
+ * Helper to get or restore a client
169
+ */
170
+ private getOrCreateClient;
171
+ /**
172
+ * List tools from a session
173
+ */
174
+ private listTools;
175
+ /**
176
+ * Call a tool
177
+ */
178
+ private callTool;
179
+ /**
180
+ * Refresh/validate a session
181
+ */
182
+ private restoreSession;
183
+ /**
184
+ * Complete OAuth authorization
185
+ */
186
+ private finishAuth;
187
+ /**
188
+ * List prompts from a session
189
+ */
190
+ private listPrompts;
191
+ /**
192
+ * Get a specific prompt
193
+ */
194
+ private getPrompt;
195
+ /**
196
+ * List resources from a session
197
+ */
198
+ private listResources;
199
+ /**
200
+ * Read a specific resource
201
+ */
202
+ private readResource;
203
+ /**
204
+ * Emit connection event
205
+ */
206
+ private emitConnectionEvent;
207
+ /**
208
+ * Cleanup and close all connections
209
+ */
210
+ dispose(): void;
211
+ }
212
+ /**
213
+ * Create SSE endpoint handler
214
+ * Compatible with various Node.js frameworks
215
+ */
216
+ declare function createSSEHandler(options: SSEHandlerOptions): (req: any, res: any) => Promise<void>;
217
+
218
+ /**
219
+ * Next.js App Router Handler for MCP SSE
220
+ * Provides a clean, zero-boilerplate API for Next.js applications
221
+ */
222
+
223
+ interface NextMcpHandlerOptions {
224
+ /**
225
+ * Extract identity from request (default: from 'identity' query param)
226
+ */
227
+ getIdentity?: (request: Request) => string | null;
228
+ /**
229
+ * Extract auth token from request (default: from 'token' query param or Authorization header)
230
+ */
231
+ getAuthToken?: (request: Request) => string | null;
232
+ /**
233
+ * Authenticate user and verify access (optional)
234
+ * Return true if user is authenticated, false otherwise
235
+ */
236
+ authenticate?: (identity: string, token: string | null) => Promise<boolean> | boolean;
237
+ /**
238
+ * Heartbeat interval in milliseconds (default: 30000)
239
+ */
240
+ heartbeatInterval?: number;
241
+ /**
242
+ * Static OAuth client metadata defaults (for all connections)
243
+ * Use this for single-tenant applications with fixed branding
244
+ */
245
+ clientDefaults?: ClientMetadata;
246
+ /**
247
+ * Dynamic OAuth client metadata getter (per-request, useful for multi-tenant)
248
+ * Use this when you need different branding based on request (tenant, domain, etc.)
249
+ * Takes precedence over clientDefaults
250
+ */
251
+ getClientMetadata?: (request: Request) => ClientMetadata | Promise<ClientMetadata>;
252
+ }
253
+ /**
254
+ * Creates Next.js App Router handlers (GET and POST) for MCP SSE endpoint
255
+ *
256
+ * @example
257
+ * ```typescript
258
+ * // app/api/mcp/route.ts
259
+ * import { createNextMcpHandler } from '@mcp-ts/core/server';
260
+ *
261
+ * export const { GET, POST } = createNextMcpHandler();
262
+ * ```
263
+ */
264
+ declare function createNextMcpHandler(options?: NextMcpHandlerOptions): {
265
+ GET: (request: Request) => Promise<Response>;
266
+ POST: (request: Request) => Promise<Response>;
267
+ };
268
+
269
+ export { type ClientMetadata, McpConnectionEvent, McpObservabilityEvent, McpRpcRequest, McpRpcResponse, type NextMcpHandlerOptions, SSEConnectionManager, type SSEHandlerOptions, type StorageBackend, createNextMcpHandler, createSSEHandler, storage };