MCPcopy Create free account
hub / github.com/modelcontextprotocol/typescript-sdk / connect

Function connect

src/examples/client/elicitationUrlExample.ts:502–566  ·  view source on GitHub ↗
(url?: string)

Source from the content-addressed store, hash-verified

500}
501
502async function connect(url?: string): Promise<void> {
503 if (client) {
504 console.log('Already connected. Disconnect first.');
505 return;
506 }
507
508 if (url) {
509 serverUrl = url;
510 }
511
512 console.log(`🔗 Attempting to connect to ${serverUrl}...`);
513
514 // Create a new client with elicitation capability
515 console.log('👤 Creating MCP client...');
516 client = new Client(
517 {
518 name: 'example-client',
519 version: '1.0.0'
520 },
521 {
522 capabilities: {
523 elicitation: {
524 // Only URL elicitation is supported in this demo
525 // (see server/elicitationExample.ts for a demo of form mode elicitation)
526 url: {}
527 }
528 }
529 }
530 );
531 console.log('👤 Client created');
532
533 // Set up elicitation request handler with proper validation
534 client.setRequestHandler(ElicitRequestSchema, elicitationRequestHandler);
535
536 // Set up notification handler for elicitation completion
537 client.setNotificationHandler(ElicitationCompleteNotificationSchema, notification => {
538 const { elicitationId } = notification.params;
539 const pending = pendingURLElicitations.get(elicitationId);
540 if (pending) {
541 clearTimeout(pending.timeout);
542 pendingURLElicitations.delete(elicitationId);
543 console.log(`\x1b[32m✅ Elicitation ${elicitationId} completed!\x1b[0m`);
544 pending.resolve();
545 } else {
546 // Shouldn't happen - discard it!
547 console.warn(`Received completion notification for unknown elicitation: ${elicitationId}`);
548 }
549 });
550
551 try {
552 console.log('🔐 Starting OAuth flow...');
553 await attemptConnection(oauthProvider!);
554 console.log('Connected to MCP server');
555
556 // Set up error handler after connection is established so we don't double log errors
557 client.onerror = error => {
558 console.error('\x1b[31mClient error:', error, '\x1b[0m');
559 };

Callers 3

mainFunction · 0.70
commandLoopFunction · 0.70
reconnectFunction · 0.70

Calls 2

attemptConnectionFunction · 0.85
setRequestHandlerMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…