elicitationUrlExample.js 28 KB

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