File size: 27,056 Bytes
a5d718a | 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 | // Run with: npx tsx src/examples/client/elicitationUrlExample.ts
//
// This example demonstrates how to use URL elicitation to securely
// collect 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.
import { Client } from '../../client/index.js';
import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js';
import { createInterface } from 'node:readline';
import { ListToolsResultSchema, CallToolResultSchema, ElicitRequestSchema, McpError, ErrorCode, UrlElicitationRequiredError, ElicitationCompleteNotificationSchema } from '../../types.js';
import { getDisplayName } from '../../shared/metadataUtils.js';
import { InMemoryOAuthClientProvider } from './simpleOAuthClientProvider.js';
import { UnauthorizedError } from '../../client/auth.js';
import { createServer } from 'node:http';
// Set up OAuth (required for this example)
const OAUTH_CALLBACK_PORT = 8090; // Use different port than auth server (3001)
const OAUTH_CALLBACK_URL = `http://localhost:${OAUTH_CALLBACK_PORT}/callback`;
let oauthProvider = undefined;
console.log('Getting OAuth token...');
const clientMetadata = {
client_name: 'Elicitation MCP Client',
redirect_uris: [OAUTH_CALLBACK_URL],
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
token_endpoint_auth_method: 'client_secret_post',
scope: 'mcp:tools'
};
oauthProvider = new InMemoryOAuthClientProvider(OAUTH_CALLBACK_URL, clientMetadata, (redirectUrl) => {
console.log(`\nπ Please open this URL in your browser to authorize:\n ${redirectUrl.toString()}`);
});
// Create readline interface for user input
const readline = createInterface({
input: process.stdin,
output: process.stdout
});
let abortCommand = new AbortController();
// Global client and transport for interactive commands
let client = null;
let transport = null;
let serverUrl = 'http://localhost:3000/mcp';
let sessionId = undefined;
let isProcessingCommand = false;
let isProcessingElicitations = false;
const elicitationQueue = [];
let elicitationQueueSignal = null;
let elicitationsCompleteSignal = null;
// Map to track pending URL elicitations waiting for completion notifications
const pendingURLElicitations = new Map();
async function main() {
console.log('MCP Interactive Client');
console.log('=====================');
// Connect to server immediately with default settings
await connect();
// Start the elicitation loop in the background
elicitationLoop().catch(error => {
console.error('Unexpected error in elicitation loop:', error);
process.exit(1);
});
// Short delay allowing the server to send any SSE elicitations on connection
await new Promise(resolve => setTimeout(resolve, 200));
// Wait until we are done processing any initial elicitations
await waitForElicitationsToComplete();
// Print help and start the command loop
printHelp();
await commandLoop();
}
async function waitForElicitationsToComplete() {
// Wait until the queue is empty and nothing is being processed
while (elicitationQueue.length > 0 || isProcessingElicitations) {
await new Promise(resolve => setTimeout(resolve, 100));
}
}
function printHelp() {
console.log('\nAvailable commands:');
console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)');
console.log(' disconnect - Disconnect from server');
console.log(' terminate-session - Terminate the current session');
console.log(' reconnect - Reconnect to the server');
console.log(' list-tools - List available tools');
console.log(' call-tool <name> [args] - Call a tool with optional JSON arguments');
console.log(' payment-confirm - Test URL elicitation via error response with payment-confirm tool');
console.log(' third-party-auth - Test tool that requires third-party OAuth credentials');
console.log(' help - Show this help');
console.log(' quit - Exit the program');
}
async function commandLoop() {
await new Promise(resolve => {
if (!isProcessingElicitations) {
resolve();
}
else {
elicitationsCompleteSignal = resolve;
}
});
readline.question('\n> ', { signal: abortCommand.signal }, async (input) => {
isProcessingCommand = true;
const args = input.trim().split(/\s+/);
const command = args[0]?.toLowerCase();
try {
switch (command) {
case 'connect':
await connect(args[1]);
break;
case 'disconnect':
await disconnect();
break;
case 'terminate-session':
await terminateSession();
break;
case 'reconnect':
await reconnect();
break;
case 'list-tools':
await listTools();
break;
case 'call-tool':
if (args.length < 2) {
console.log('Usage: call-tool <name> [args]');
}
else {
const toolName = args[1];
let toolArgs = {};
if (args.length > 2) {
try {
toolArgs = JSON.parse(args.slice(2).join(' '));
}
catch {
console.log('Invalid JSON arguments. Using empty args.');
}
}
await callTool(toolName, toolArgs);
}
break;
case 'payment-confirm':
await callPaymentConfirmTool();
break;
case 'third-party-auth':
await callThirdPartyAuthTool();
break;
case 'help':
printHelp();
break;
case 'quit':
case 'exit':
await cleanup();
return;
default:
if (command) {
console.log(`Unknown command: ${command}`);
}
break;
}
}
catch (error) {
console.error(`Error executing command: ${error}`);
}
finally {
isProcessingCommand = false;
}
// Process another command after we've processed the this one
await commandLoop();
});
}
async function elicitationLoop() {
while (true) {
// Wait until we have elicitations to process
await new Promise(resolve => {
if (elicitationQueue.length > 0) {
resolve();
}
else {
elicitationQueueSignal = resolve;
}
});
isProcessingElicitations = true;
abortCommand.abort(); // Abort the command loop if it's running
// Process all queued elicitations
while (elicitationQueue.length > 0) {
const queued = elicitationQueue.shift();
console.log(`π€ Processing queued elicitation (${elicitationQueue.length} remaining)`);
try {
const result = await handleElicitationRequest(queued.request);
queued.resolve(result);
}
catch (error) {
queued.reject(error instanceof Error ? error : new Error(String(error)));
}
}
console.log('β
All queued elicitations processed. Resuming command loop...\n');
isProcessingElicitations = false;
// Reset the abort controller for the next command loop
abortCommand = new AbortController();
// Resume the command loop
if (elicitationsCompleteSignal) {
elicitationsCompleteSignal();
elicitationsCompleteSignal = null;
}
}
}
/**
* Enqueues an elicitation request and returns the result.
*
* This function is used so that our CLI (which can only handle one input request at a time)
* can handle elicitation requests and the command loop.
*
* @param request - The elicitation request to be handled
* @returns The elicitation result
*/
async function elicitationRequestHandler(request) {
// If we are processing a command, handle this elicitation immediately
if (isProcessingCommand) {
console.log('π Processing elicitation immediately (during command execution)');
return await handleElicitationRequest(request);
}
// Otherwise, queue the request to be handled by the elicitation loop
console.log(`π₯ Queueing elicitation request (queue size will be: ${elicitationQueue.length + 1})`);
return new Promise((resolve, reject) => {
elicitationQueue.push({
request,
resolve,
reject
});
// Signal the elicitation loop that there's work to do
if (elicitationQueueSignal) {
elicitationQueueSignal();
elicitationQueueSignal = null;
}
});
}
/**
* Handles an elicitation request.
*
* This function is used to handle the elicitation request and return the result.
*
* @param request - The elicitation request to be handled
* @returns The elicitation result
*/
async function handleElicitationRequest(request) {
const mode = request.params.mode;
console.log('\nπ Elicitation Request Received:');
console.log(`Mode: ${mode}`);
if (mode === 'url') {
return {
action: await handleURLElicitation(request.params)
};
}
else {
// Should not happen because the client declares its capabilities to the server,
// but being defensive is a good practice:
throw new McpError(ErrorCode.InvalidParams, `Unsupported elicitation mode: ${mode}`);
}
}
/**
* Handles a URL elicitation by opening the URL in the browser.
*
* Note: This is a shared code for both request handlers and error handlers.
* As a result of sharing schema, there is no big forking of logic for the client.
*
* @param params - The URL elicitation request parameters
* @returns The action to take (accept, cancel, or decline)
*/
async function handleURLElicitation(params) {
const url = params.url;
const elicitationId = params.elicitationId;
const message = params.message;
console.log(`π Elicitation ID: ${elicitationId}`); // Print for illustration
// Parse URL to show domain for security
let domain = 'unknown domain';
try {
const parsedUrl = new URL(url);
domain = parsedUrl.hostname;
}
catch {
console.error('Invalid URL provided by server');
return 'decline';
}
// Example security warning to help prevent phishing attacks
console.log('\nβ οΈ \x1b[33mSECURITY WARNING\x1b[0m β οΈ');
console.log('\x1b[33mThe server is requesting you to open an external URL.\x1b[0m');
console.log('\x1b[33mOnly proceed if you trust this server and understand why it needs this.\x1b[0m\n');
console.log(`π Target domain: \x1b[36m${domain}\x1b[0m`);
console.log(`π Full URL: \x1b[36m${url}\x1b[0m`);
console.log(`\nβΉοΈ Server's reason:\n\n\x1b[36m${message}\x1b[0m\n`);
// 1. Ask for user consent to open the URL
const consent = await new Promise(resolve => {
readline.question('\nDo you want to open this URL in your browser? (y/n): ', input => {
resolve(input.trim().toLowerCase());
});
});
// 2. If user did not consent, return appropriate result
if (consent === 'no' || consent === 'n') {
console.log('β URL navigation declined.');
return 'decline';
}
else if (consent !== 'yes' && consent !== 'y') {
console.log('π« Invalid response. Cancelling elicitation.');
return 'cancel';
}
// 3. Wait for completion notification in the background
const completionPromise = new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
pendingURLElicitations.delete(elicitationId);
console.log(`\x1b[31mβ Elicitation ${elicitationId} timed out waiting for completion.\x1b[0m`);
reject(new Error('Elicitation completion timeout'));
}, 5 * 60 * 1000); // 5 minute timeout
pendingURLElicitations.set(elicitationId, {
resolve: () => {
clearTimeout(timeout);
resolve();
},
reject,
timeout
});
});
completionPromise.catch(error => {
console.error('Background completion wait failed:', error);
});
// 4. Direct user to open the URL in their browser
console.log(`\nπ Please open this URL in your browser:\n ${url}`);
console.log('\nβ³ Waiting for you to complete the interaction in your browser...');
console.log(' The server will send a notification once you complete the action.');
// 5. Acknowledge the user accepted the elicitation
return 'accept';
}
/**
* Example OAuth callback handler - in production, use a more robust approach
* for handling callbacks and storing tokens
*/
/**
* Starts a temporary HTTP server to receive the OAuth callback
*/
async function waitForOAuthCallback() {
return new Promise((resolve, reject) => {
const server = createServer((req, res) => {
// Ignore favicon requests
if (req.url === '/favicon.ico') {
res.writeHead(404);
res.end();
return;
}
console.log(`π₯ Received callback: ${req.url}`);
const parsedUrl = new URL(req.url || '', 'http://localhost');
const code = parsedUrl.searchParams.get('code');
const error = parsedUrl.searchParams.get('error');
if (code) {
console.log(`β
Authorization code received: ${code?.substring(0, 10)}...`);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<html>
<body>
<h1>Authorization Successful!</h1>
<p>This simulates successful authorization of the MCP client, which now has an access token for the MCP server.</p>
<p>This window will close automatically in 10 seconds.</p>
<script>setTimeout(() => window.close(), 10000);</script>
</body>
</html>
`);
resolve(code);
setTimeout(() => server.close(), 15000);
}
else if (error) {
console.log(`β Authorization error: ${error}`);
res.writeHead(400, { 'Content-Type': 'text/html' });
res.end(`
<html>
<body>
<h1>Authorization Failed</h1>
<p>Error: ${error}</p>
</body>
</html>
`);
reject(new Error(`OAuth authorization failed: ${error}`));
}
else {
console.log(`β No authorization code or error in callback`);
res.writeHead(400);
res.end('Bad request');
reject(new Error('No authorization code provided'));
}
});
server.listen(OAUTH_CALLBACK_PORT, () => {
console.log(`OAuth callback server started on http://localhost:${OAUTH_CALLBACK_PORT}`);
});
});
}
/**
* Attempts to connect to the MCP server with OAuth authentication.
* Handles OAuth flow recursively if authorization is required.
*/
async function attemptConnection(oauthProvider) {
console.log('π’ Creating transport with OAuth provider...');
const baseUrl = new URL(serverUrl);
transport = new StreamableHTTPClientTransport(baseUrl, {
sessionId: sessionId,
authProvider: oauthProvider
});
console.log('π’ Transport created');
try {
console.log('π Attempting connection (this will trigger OAuth redirect if needed)...');
await client.connect(transport);
sessionId = transport.sessionId;
console.log('Transport created with session ID:', sessionId);
console.log('β
Connected successfully');
}
catch (error) {
if (error instanceof UnauthorizedError) {
console.log('π OAuth required - waiting for authorization...');
const callbackPromise = waitForOAuthCallback();
const authCode = await callbackPromise;
await transport.finishAuth(authCode);
console.log('π Authorization code received:', authCode);
console.log('π Reconnecting with authenticated transport...');
// Recursively retry connection after OAuth completion
await attemptConnection(oauthProvider);
}
else {
console.error('β Connection failed with non-auth error:', error);
throw error;
}
}
}
async function connect(url) {
if (client) {
console.log('Already connected. Disconnect first.');
return;
}
if (url) {
serverUrl = url;
}
console.log(`π Attempting to connect to ${serverUrl}...`);
// Create a new client with elicitation capability
console.log('π€ Creating MCP client...');
client = new Client({
name: 'example-client',
version: '1.0.0'
}, {
capabilities: {
elicitation: {
// Only URL elicitation is supported in this demo
// (see server/elicitationExample.ts for a demo of form mode elicitation)
url: {}
}
}
});
console.log('π€ Client created');
// Set up elicitation request handler with proper validation
client.setRequestHandler(ElicitRequestSchema, elicitationRequestHandler);
// Set up notification handler for elicitation completion
client.setNotificationHandler(ElicitationCompleteNotificationSchema, notification => {
const { elicitationId } = notification.params;
const pending = pendingURLElicitations.get(elicitationId);
if (pending) {
clearTimeout(pending.timeout);
pendingURLElicitations.delete(elicitationId);
console.log(`\x1b[32mβ
Elicitation ${elicitationId} completed!\x1b[0m`);
pending.resolve();
}
else {
// Shouldn't happen - discard it!
console.warn(`Received completion notification for unknown elicitation: ${elicitationId}`);
}
});
try {
console.log('π Starting OAuth flow...');
await attemptConnection(oauthProvider);
console.log('Connected to MCP server');
// Set up error handler after connection is established so we don't double log errors
client.onerror = error => {
console.error('\x1b[31mClient error:', error, '\x1b[0m');
};
}
catch (error) {
console.error('Failed to connect:', error);
client = null;
transport = null;
return;
}
}
async function disconnect() {
if (!client || !transport) {
console.log('Not connected.');
return;
}
try {
await transport.close();
console.log('Disconnected from MCP server');
client = null;
transport = null;
}
catch (error) {
console.error('Error disconnecting:', error);
}
}
async function terminateSession() {
if (!client || !transport) {
console.log('Not connected.');
return;
}
try {
console.log('Terminating session with ID:', transport.sessionId);
await transport.terminateSession();
console.log('Session terminated successfully');
// Check if sessionId was cleared after termination
if (!transport.sessionId) {
console.log('Session ID has been cleared');
sessionId = undefined;
// Also close the transport and clear client objects
await transport.close();
console.log('Transport closed after session termination');
client = null;
transport = null;
}
else {
console.log('Server responded with 405 Method Not Allowed (session termination not supported)');
console.log('Session ID is still active:', transport.sessionId);
}
}
catch (error) {
console.error('Error terminating session:', error);
}
}
async function reconnect() {
if (client) {
await disconnect();
}
await connect();
}
async function listTools() {
if (!client) {
console.log('Not connected to server.');
return;
}
try {
const toolsRequest = {
method: 'tools/list',
params: {}
};
const toolsResult = await client.request(toolsRequest, ListToolsResultSchema);
console.log('Available tools:');
if (toolsResult.tools.length === 0) {
console.log(' No tools available');
}
else {
for (const tool of toolsResult.tools) {
console.log(` - id: ${tool.name}, name: ${getDisplayName(tool)}, description: ${tool.description}`);
}
}
}
catch (error) {
console.log(`Tools not supported by this server (${error})`);
}
}
async function callTool(name, args) {
if (!client) {
console.log('Not connected to server.');
return;
}
try {
const request = {
method: 'tools/call',
params: {
name,
arguments: args
}
};
console.log(`Calling tool '${name}' with args:`, args);
const result = await client.request(request, CallToolResultSchema);
console.log('Tool result:');
const resourceLinks = [];
result.content.forEach(item => {
if (item.type === 'text') {
console.log(` ${item.text}`);
}
else if (item.type === 'resource_link') {
const resourceLink = item;
resourceLinks.push(resourceLink);
console.log(` π Resource Link: ${resourceLink.name}`);
console.log(` URI: ${resourceLink.uri}`);
if (resourceLink.mimeType) {
console.log(` Type: ${resourceLink.mimeType}`);
}
if (resourceLink.description) {
console.log(` Description: ${resourceLink.description}`);
}
}
else if (item.type === 'resource') {
console.log(` [Embedded Resource: ${item.resource.uri}]`);
}
else if (item.type === 'image') {
console.log(` [Image: ${item.mimeType}]`);
}
else if (item.type === 'audio') {
console.log(` [Audio: ${item.mimeType}]`);
}
else {
console.log(` [Unknown content type]:`, item);
}
});
// Offer to read resource links
if (resourceLinks.length > 0) {
console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource <uri>' to read their content.`);
}
}
catch (error) {
if (error instanceof UrlElicitationRequiredError) {
console.log('\nπ Elicitation Required Error Received:');
console.log(`Message: ${error.message}`);
for (const e of error.elicitations) {
await handleURLElicitation(e); // For the error handler, we discard the action result because we don't respond to an error response
}
return;
}
console.log(`Error calling tool ${name}: ${error}`);
}
}
async function cleanup() {
if (client && transport) {
try {
// First try to terminate the session gracefully
if (transport.sessionId) {
try {
console.log('Terminating session before exit...');
await transport.terminateSession();
console.log('Session terminated successfully');
}
catch (error) {
console.error('Error terminating session:', error);
}
}
// Then close the transport
await transport.close();
}
catch (error) {
console.error('Error closing transport:', error);
}
}
process.stdin.setRawMode(false);
readline.close();
console.log('\nGoodbye!');
process.exit(0);
}
async function callPaymentConfirmTool() {
console.log('Calling payment-confirm tool...');
await callTool('payment-confirm', { cartId: 'cart_123' });
}
async function callThirdPartyAuthTool() {
console.log('Calling third-party-auth tool...');
await callTool('third-party-auth', { param1: 'test' });
}
// Set up raw mode for keyboard input to capture Escape key
process.stdin.setRawMode(true);
process.stdin.on('data', async (data) => {
// Check for Escape key (27)
if (data.length === 1 && data[0] === 27) {
console.log('\nESC key pressed. Disconnecting from server...');
// Abort current operation and disconnect from server
if (client && transport) {
await disconnect();
console.log('Disconnected. Press Enter to continue.');
}
else {
console.log('Not connected to server.');
}
// Re-display the prompt
process.stdout.write('> ');
}
});
// Handle Ctrl+C
process.on('SIGINT', async () => {
console.log('\nReceived SIGINT. Cleaning up...');
await cleanup();
});
// Start the interactive client
main().catch((error) => {
console.error('Error running MCP client:', error);
process.exit(1);
});
//# sourceMappingURL=elicitationUrlExample.js.map |