-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathelicitationUrlExample.ts
More file actions
733 lines (649 loc) · 28.4 KB
/
elicitationUrlExample.ts
File metadata and controls
733 lines (649 loc) · 28.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
// Run with: pnpm tsx src/elicitationUrlExample.ts
//
// This example demonstrates how to use URL elicitation to securely collect
// *sensitive* user input in a remote (HTTP) server.
// URL elicitation allows servers to prompt the end-user to open a URL in their browser
// to collect sensitive information.
// Note: See also elicitationFormExample.ts for an example of using form (not URL) elicitation
// to collect *non-sensitive* user input with a structured schema.
import { randomUUID } from 'node:crypto';
import {
createProtectedResourceMetadataRouter,
getOAuthProtectedResourceMetadataUrl,
requireBearerAuth,
setupAuthServer
} from '@modelcontextprotocol/examples-shared';
import { createMcpExpressApp } from '@modelcontextprotocol/express';
import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
import type { CallToolResult, ElicitRequestURLParams, ElicitResult } from '@modelcontextprotocol/server';
import { isInitializeRequest, McpServer, UrlElicitationRequiredError } from '@modelcontextprotocol/server';
import cors from 'cors';
import type { Request, Response } from 'express';
import express from 'express';
import * as z from 'zod/v4';
import { InMemoryEventStore } from './inMemoryEventStore.js';
// Create an MCP server with implementation details
const getServer = () => {
const mcpServer = new McpServer(
{
name: 'url-elicitation-http-server',
version: '1.0.0'
},
{
capabilities: { logging: {} }
}
);
mcpServer.registerTool(
'payment-confirm',
{
description: 'A tool that confirms a payment directly with a user',
inputSchema: z.object({
cartId: z.string().describe('The ID of the cart to confirm')
})
},
async ({ cartId }, ctx): Promise<CallToolResult> => {
/*
In a real world scenario, there would be some logic here to check if the user has the provided cartId.
For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to confirm payment)
*/
const sessionId = ctx.sessionId;
if (!sessionId) {
throw new Error('Expected a Session ID');
}
// Create and track the elicitation
const elicitationId = generateTrackedElicitation(sessionId, elicitationId =>
mcpServer.server.createElicitationCompletionNotifier(elicitationId)
);
throw new UrlElicitationRequiredError([
{
mode: 'url',
message: 'This tool requires a payment confirmation. Open the link to confirm payment!',
url: `http://localhost:${MCP_PORT}/confirm-payment?session=${sessionId}&elicitation=${elicitationId}&cartId=${encodeURIComponent(cartId)}`,
elicitationId
}
]);
}
);
mcpServer.registerTool(
'third-party-auth',
{
description: 'A demo tool that requires third-party OAuth credentials',
inputSchema: z.object({
param1: z.string().describe('First parameter')
})
},
async (_, ctx): Promise<CallToolResult> => {
/*
In a real world scenario, there would be some logic here to check if we already have a valid access token for the user.
Auth info (with a subject or `sub` claim) can be typically be found in `ctx.http?.authInfo`.
If we do, we can just return the result of the tool call.
If we don't, we can throw an ElicitationRequiredError to request the user to authenticate.
For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to authenticate).
*/
const sessionId = ctx.sessionId;
if (!sessionId) {
throw new Error('Expected a Session ID');
}
// Create and track the elicitation
const elicitationId = generateTrackedElicitation(sessionId, elicitationId =>
mcpServer.server.createElicitationCompletionNotifier(elicitationId)
);
// Simulate OAuth callback and token exchange after 5 seconds
// In a real app, this would be called from your OAuth callback handler
setTimeout(() => {
console.log(`Simulating OAuth token received for elicitation ${elicitationId}`);
completeURLElicitation(elicitationId);
}, 5000);
throw new UrlElicitationRequiredError([
{
mode: 'url',
message: 'This tool requires access to your example.com account. Open the link to authenticate!',
url: 'https://www.example.com/oauth/authorize',
elicitationId
}
]);
}
);
return mcpServer;
};
/**
* Elicitation Completion Tracking Utilities
**/
interface ElicitationMetadata {
status: 'pending' | 'complete';
completedPromise: Promise<void>;
completeResolver: () => void;
createdAt: Date;
sessionId: string;
completionNotifier?: () => Promise<void>;
}
const elicitationsMap = new Map<string, ElicitationMetadata>();
// Clean up old elicitations after 1 hour to prevent memory leaks
const ELICITATION_TTL_MS = 60 * 60 * 1000; // 1 hour
const CLEANUP_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
function cleanupOldElicitations() {
const now = new Date();
for (const [id, metadata] of elicitationsMap.entries()) {
if (now.getTime() - metadata.createdAt.getTime() > ELICITATION_TTL_MS) {
elicitationsMap.delete(id);
console.log(`Cleaned up expired elicitation: ${id}`);
}
}
}
setInterval(cleanupOldElicitations, CLEANUP_INTERVAL_MS);
/**
* Elicitation IDs must be unique strings within the MCP session
* UUIDs are used in this example for simplicity
*/
function generateElicitationId(): string {
return randomUUID();
}
/**
* Helper function to create and track a new elicitation.
*/
function generateTrackedElicitation(sessionId: string, createCompletionNotifier?: ElicitationCompletionNotifierFactory): string {
const elicitationId = generateElicitationId();
// Create a Promise and its resolver for tracking completion
let completeResolver: () => void;
const completedPromise = new Promise<void>(resolve => {
completeResolver = resolve;
});
const completionNotifier = createCompletionNotifier ? createCompletionNotifier(elicitationId) : undefined;
// Store the elicitation in our map
elicitationsMap.set(elicitationId, {
status: 'pending',
completedPromise,
completeResolver: completeResolver!,
createdAt: new Date(),
sessionId,
completionNotifier
});
return elicitationId;
}
/**
* Helper function to complete an elicitation.
*/
function completeURLElicitation(elicitationId: string) {
const elicitation = elicitationsMap.get(elicitationId);
if (!elicitation) {
console.warn(`Attempted to complete unknown elicitation: ${elicitationId}`);
return;
}
if (elicitation.status === 'complete') {
console.warn(`Elicitation already complete: ${elicitationId}`);
return;
}
// Update metadata
elicitation.status = 'complete';
// Send completion notification to the client
if (elicitation.completionNotifier) {
console.log(`Sending notifications/elicitation/complete notification for elicitation ${elicitationId}`);
elicitation.completionNotifier().catch(error => {
console.error(`Failed to send completion notification for elicitation ${elicitationId}:`, error);
});
}
// Resolve the promise to unblock any waiting code
elicitation.completeResolver();
}
const MCP_PORT = process.env.MCP_PORT ? Number.parseInt(process.env.MCP_PORT, 10) : 3000;
const AUTH_PORT = process.env.MCP_AUTH_PORT ? Number.parseInt(process.env.MCP_AUTH_PORT, 10) : 3001;
const app = createMcpExpressApp();
// Allow CORS all domains, expose the Mcp-Session-Id header
app.use(
cors({
origin: '*', // Allow all origins
exposedHeaders: ['Mcp-Session-Id'],
credentials: true // Allow cookies to be sent cross-origin
})
);
// Set up OAuth (required for this example)
let authMiddleware = null;
// Create auth middleware for MCP endpoints
const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`);
const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`);
setupAuthServer({ authServerUrl, mcpServerUrl, strictResource: true, demoMode: true });
// Add protected resource metadata route to the MCP server
// This allows clients to discover the auth server
// Pass the resource path so metadata is served at /.well-known/oauth-protected-resource/mcp
app.use(createProtectedResourceMetadataRouter('/mcp'));
authMiddleware = requireBearerAuth({
requiredScopes: [],
resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl),
strictResource: true,
expectedResource: mcpServerUrl
});
/**
* API Key Form Handling
*
* Many servers today require an API key to operate, but there's no scalable way to do this dynamically for remote servers within MCP protocol.
* URL-mode elicitation enables the server to host a simple form and get the secret data securely from the user without involving the LLM or client.
**/
async function sendApiKeyElicitation(
sessionId: string,
sender: ElicitationSender,
createCompletionNotifier: ElicitationCompletionNotifierFactory
) {
if (!sessionId) {
console.error('No session ID provided');
throw new Error('Expected a Session ID to track elicitation');
}
console.log('🔑 URL elicitation demo: Requesting API key from client...');
const elicitationId = generateTrackedElicitation(sessionId, createCompletionNotifier);
try {
const result = await sender({
mode: 'url',
message: 'Please provide your API key to authenticate with this server',
// Host the form on the same server. In a real app, you might coordinate passing these state variables differently.
url: `http://localhost:${MCP_PORT}/api-key-form?session=${sessionId}&elicitation=${elicitationId}`,
elicitationId
});
switch (result.action) {
case 'accept': {
console.log('🔑 URL elicitation demo: Client accepted the API key elicitation (now pending form submission)');
// Wait for the API key to be submitted via the form
// The form submission will complete the elicitation
break;
}
default: {
console.log('🔑 URL elicitation demo: Client declined to provide an API key');
// In a real app, this might close the connection, but for the demo, we'll continue
break;
}
}
} catch (error) {
console.error('Error during API key elicitation:', error);
}
}
// API Key Form endpoint - serves a simple HTML form
app.get('/api-key-form', (req: Request, res: Response) => {
const mcpSessionId = req.query.session as string | undefined;
const elicitationId = req.query.elicitation as string | undefined;
if (!mcpSessionId || !elicitationId) {
res.status(400).send('<h1>Error</h1><p>Missing required parameters</p>');
return;
}
// Check for user session cookie
// In production, this is often handled by some user auth middleware to ensure the user has a valid session
// This session is different from the MCP session.
// This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in.
const userSession = getUserSessionCookie(req.headers.cookie);
if (!userSession) {
res.status(401).send('<h1>Error</h1><p>Unauthorized - please reconnect to login again</p>');
return;
}
// Serve a simple HTML form
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Submit Your API Key</title>
<style>
body { font-family: sans-serif; max-width: 400px; margin: 50px auto; padding: 20px; }
input[type="text"] { width: 100%; padding: 8px; margin: 10px 0; box-sizing: border-box; }
button { background: #007bff; color: white; padding: 10px 20px; border: none; cursor: pointer; }
button:hover { background: #0056b3; }
.user { background: #d1ecf1; padding: 8px; margin-bottom: 10px; }
.info { color: #666; font-size: 0.9em; margin-top: 20px; }
</style>
</head>
<body>
<h1>API Key Required</h1>
<div class="user">✓ Logged in as: <strong>${userSession.name}</strong></div>
<form method="POST" action="/api-key-form">
<input type="hidden" name="session" value="${mcpSessionId}" />
<input type="hidden" name="elicitation" value="${elicitationId}" />
<label>API Key:<br>
<input type="text" name="apiKey" required placeholder="Enter your API key" />
</label>
<button type="submit">Submit</button>
</form>
<div class="info">This is a demo showing how a server can securely elicit sensitive data from a user using a URL.</div>
</body>
</html>
`);
});
// Handle API key form submission
app.post('/api-key-form', express.urlencoded(), (req: Request, res: Response) => {
const { session: sessionId, apiKey, elicitation: elicitationId } = req.body;
if (!sessionId || !apiKey || !elicitationId) {
res.status(400).send('<h1>Error</h1><p>Missing required parameters</p>');
return;
}
// Check for user session cookie here too
const userSession = getUserSessionCookie(req.headers.cookie);
if (!userSession) {
res.status(401).send('<h1>Error</h1><p>Unauthorized - please reconnect to login again</p>');
return;
}
// A real app might store this API key to be used later for the user.
console.log(`🔑 Received API key \u001B[32m${apiKey}\u001B[0m for session ${sessionId}`);
// If we have an elicitationId, complete the elicitation
completeURLElicitation(elicitationId);
// Send a success response
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Success</title>
<style>
body { font-family: sans-serif; max-width: 400px; margin: 50px auto; padding: 20px; text-align: center; }
.success { background: #d4edda; color: #155724; padding: 20px; margin: 20px 0; }
</style>
</head>
<body>
<div class="success">
<h1>Success ✓</h1>
<p>API key received.</p>
</div>
<p>You can close this window and return to your MCP client.</p>
</body>
</html>
`);
});
// Helper to get the user session from the demo_session cookie
function getUserSessionCookie(cookieHeader?: string): { userId: string; name: string; timestamp: number } | null {
if (!cookieHeader) return null;
const cookies = cookieHeader.split(';');
for (const cookie of cookies) {
const [name, value] = cookie.trim().split('=');
if (name === 'demo_session' && value) {
try {
return JSON.parse(decodeURIComponent(value));
} catch (error) {
console.error('Failed to parse demo_session cookie:', error);
return null;
}
}
}
return null;
}
/**
* Payment Confirmation Form Handling
*
* This demonstrates how a server can use URL-mode elicitation to get user confirmation
* for sensitive operations like payment processing.
**/
// Payment Confirmation Form endpoint - serves a simple HTML form
app.get('/confirm-payment', (req: Request, res: Response) => {
const mcpSessionId = req.query.session as string | undefined;
const elicitationId = req.query.elicitation as string | undefined;
const cartId = req.query.cartId as string | undefined;
if (!mcpSessionId || !elicitationId) {
res.status(400).send('<h1>Error</h1><p>Missing required parameters</p>');
return;
}
// Check for user session cookie
// In production, this is often handled by some user auth middleware to ensure the user has a valid session
// This session is different from the MCP session.
// This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in.
const userSession = getUserSessionCookie(req.headers.cookie);
if (!userSession) {
res.status(401).send('<h1>Error</h1><p>Unauthorized - please reconnect to login again</p>');
return;
}
// Serve a simple HTML form
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Confirm Payment</title>
<style>
body { font-family: sans-serif; max-width: 400px; margin: 50px auto; padding: 20px; }
button { background: #28a745; color: white; padding: 12px 24px; border: none; cursor: pointer; font-size: 16px; width: 100%; margin: 10px 0; }
button:hover { background: #218838; }
button.cancel { background: #6c757d; }
button.cancel:hover { background: #5a6268; }
.user { background: #d1ecf1; padding: 8px; margin-bottom: 10px; }
.cart-info { background: #f8f9fa; padding: 12px; margin: 15px 0; border-left: 4px solid #007bff; }
.info { color: #666; font-size: 0.9em; margin-top: 20px; }
.warning { background: #fff3cd; color: #856404; padding: 12px; margin: 15px 0; border-left: 4px solid #ffc107; }
</style>
</head>
<body>
<h1>Confirm Payment</h1>
<div class="user">✓ Logged in as: <strong>${userSession.name}</strong></div>
${cartId ? `<div class="cart-info"><strong>Cart ID:</strong> ${cartId}</div>` : ''}
<div class="warning">
<strong>⚠️ Please review your order before confirming.</strong>
</div>
<form method="POST" action="/confirm-payment">
<input type="hidden" name="session" value="${mcpSessionId}" />
<input type="hidden" name="elicitation" value="${elicitationId}" />
${cartId ? `<input type="hidden" name="cartId" value="${cartId}" />` : ''}
<button type="submit" name="action" value="confirm">Confirm Payment</button>
<button type="submit" name="action" value="cancel" class="cancel">Cancel</button>
</form>
<div class="info">This is a demo showing how a server can securely get user confirmation for sensitive operations using URL-mode elicitation.</div>
</body>
</html>
`);
});
// Handle Payment Confirmation form submission
app.post('/confirm-payment', express.urlencoded(), (req: Request, res: Response) => {
const { session: sessionId, elicitation: elicitationId, cartId, action } = req.body;
if (!sessionId || !elicitationId) {
res.status(400).send('<h1>Error</h1><p>Missing required parameters</p>');
return;
}
// Check for user session cookie here too
const userSession = getUserSessionCookie(req.headers.cookie);
if (!userSession) {
res.status(401).send('<h1>Error</h1><p>Unauthorized - please reconnect to login again</p>');
return;
}
if (action === 'confirm') {
// A real app would process the payment here
console.log(`💳 Payment confirmed for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`);
// Complete the elicitation
completeURLElicitation(elicitationId);
// Send a success response
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Payment Confirmed</title>
<style>
body { font-family: sans-serif; max-width: 400px; margin: 50px auto; padding: 20px; text-align: center; }
.success { background: #d4edda; color: #155724; padding: 20px; margin: 20px 0; }
</style>
</head>
<body>
<div class="success">
<h1>Payment Confirmed ✓</h1>
<p>Your payment has been successfully processed.</p>
${cartId ? `<p><strong>Cart ID:</strong> ${cartId}</p>` : ''}
</div>
<p>You can close this window and return to your MCP client.</p>
</body>
</html>
`);
} else if (action === 'cancel') {
console.log(`💳 Payment cancelled for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`);
// The client will still receive a notifications/elicitation/complete notification,
// which indicates that the out-of-band interaction is complete (but not necessarily successful)
completeURLElicitation(elicitationId);
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Payment Cancelled</title>
<style>
body { font-family: sans-serif; max-width: 400px; margin: 50px auto; padding: 20px; text-align: center; }
.info { background: #d1ecf1; color: #0c5460; padding: 20px; margin: 20px 0; }
</style>
</head>
<body>
<div class="info">
<h1>Payment Cancelled</h1>
<p>Your payment has been cancelled.</p>
</div>
<p>You can close this window and return to your MCP client.</p>
</body>
</html>
`);
} else {
res.status(400).send('<h1>Error</h1><p>Invalid action</p>');
}
});
// Map to store transports by session ID
const transports: { [sessionId: string]: NodeStreamableHTTPServerTransport } = {};
// Interface for a function that can send an elicitation request
type ElicitationSender = (params: ElicitRequestURLParams) => Promise<ElicitResult>;
type ElicitationCompletionNotifierFactory = (elicitationId: string) => () => Promise<void>;
// Track sessions that need an elicitation request to be sent
interface SessionElicitationInfo {
elicitationSender: ElicitationSender;
createCompletionNotifier: ElicitationCompletionNotifierFactory;
}
const sessionsNeedingElicitation: { [sessionId: string]: SessionElicitationInfo } = {};
// MCP POST endpoint
const mcpPostHandler = async (req: Request, res: Response) => {
const sessionId = req.headers['mcp-session-id'] as string | undefined;
console.debug(`Received MCP POST for session: ${sessionId || 'unknown'}`);
try {
let transport: NodeStreamableHTTPServerTransport;
if (sessionId && transports[sessionId]) {
// Reuse existing transport
transport = transports[sessionId];
} else if (!sessionId && isInitializeRequest(req.body)) {
const server = getServer();
// New initialization request
const eventStore = new InMemoryEventStore();
transport = new NodeStreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
eventStore, // Enable resumability
onsessioninitialized: sessionId => {
// Store the transport by session ID when session is initialized
// This avoids race conditions where requests might come in before the session is stored
console.log(`Session initialized with ID: ${sessionId}`);
transports[sessionId] = transport;
sessionsNeedingElicitation[sessionId] = {
elicitationSender: params => server.server.elicitInput(params),
createCompletionNotifier: elicitationId => server.server.createElicitationCompletionNotifier(elicitationId)
};
}
});
// Set up onclose handler to clean up transport when closed
transport.onclose = () => {
const sid = transport.sessionId;
if (sid && transports[sid]) {
console.log(`Transport closed for session ${sid}, removing from transports map`);
delete transports[sid];
delete sessionsNeedingElicitation[sid];
}
};
// Connect the transport to the MCP server BEFORE handling the request
// so responses can flow back through the same transport
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
return; // Already handled
} else {
// Invalid request - no session ID or not initialization request
res.status(400).json({
jsonrpc: '2.0',
error: {
code: -32_000,
message: 'Bad Request: No valid session ID provided'
},
id: null
});
return;
}
// Handle the request with existing transport - no need to reconnect
// The existing transport is already connected to the server
await transport.handleRequest(req, res, req.body);
} catch (error) {
console.error('Error handling MCP request:', error);
if (!res.headersSent) {
res.status(500).json({
jsonrpc: '2.0',
error: {
code: -32_603,
message: 'Internal server error'
},
id: null
});
}
}
};
// Set up routes with auth middleware
app.post('/mcp', authMiddleware, mcpPostHandler);
// Handle GET requests for SSE streams (using built-in support from StreamableHTTP)
const mcpGetHandler = async (req: Request, res: Response) => {
const sessionId = req.headers['mcp-session-id'] as string | undefined;
if (!sessionId || !transports[sessionId]) {
res.status(400).send('Invalid or missing session ID');
return;
}
// Check for Last-Event-ID header for resumability
const lastEventId = req.headers['last-event-id'] as string | undefined;
if (lastEventId) {
console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`);
} else {
console.log(`Establishing new SSE stream for session ${sessionId}`);
}
const transport = transports[sessionId];
await transport.handleRequest(req, res);
if (sessionsNeedingElicitation[sessionId]) {
const { elicitationSender, createCompletionNotifier } = sessionsNeedingElicitation[sessionId];
// Send an elicitation request to the client in the background
sendApiKeyElicitation(sessionId, elicitationSender, createCompletionNotifier)
.then(() => {
// Only delete on successful send for this demo
delete sessionsNeedingElicitation[sessionId];
console.log(`🔑 URL elicitation demo: Finished sending API key elicitation request for session ${sessionId}`);
})
.catch(error => {
console.error('Error sending API key elicitation:', error);
// Keep in map to potentially retry on next reconnect
});
}
};
// Set up GET route with conditional auth middleware
app.get('/mcp', authMiddleware, mcpGetHandler);
// Handle DELETE requests for session termination (according to MCP spec)
const mcpDeleteHandler = async (req: Request, res: Response) => {
const sessionId = req.headers['mcp-session-id'] as string | undefined;
if (!sessionId || !transports[sessionId]) {
res.status(400).send('Invalid or missing session ID');
return;
}
console.log(`Received session termination request for session ${sessionId}`);
try {
const transport = transports[sessionId];
await transport.handleRequest(req, res);
} catch (error) {
console.error('Error handling session termination:', error);
if (!res.headersSent) {
res.status(500).send('Error processing session termination');
}
}
};
// Set up DELETE route with auth middleware
app.delete('/mcp', authMiddleware, mcpDeleteHandler);
app.listen(MCP_PORT, error => {
if (error) {
console.error('Failed to start server:', error);
// eslint-disable-next-line unicorn/no-process-exit
process.exit(1);
}
console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`);
console.log(` Protected Resource Metadata: http://localhost:${MCP_PORT}/.well-known/oauth-protected-resource/mcp`);
});
// Handle server shutdown
process.on('SIGINT', async () => {
console.log('Shutting down server...');
// Close all active transports to properly clean up resources
for (const sessionId in transports) {
try {
console.log(`Closing transport for session ${sessionId}`);
await transports[sessionId]!.close();
delete transports[sessionId];
delete sessionsNeedingElicitation[sessionId];
} catch (error) {
console.error(`Error closing transport for session ${sessionId}:`, error);
}
}
console.log('Server shutdown complete');
process.exit(0);
});