[v2] Мonorepo, sdk-client, sdk-server, sdk-core package split (#1279)
This commit is contained in:
parent
384311b9b8
commit
71ae3acee0
16 changed files with 12067 additions and 4817 deletions
52
examples/client/README.md
Normal file
52
examples/client/README.md
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
# MCP TypeScript SDK Examples (Client)
|
||||
|
||||
This directory contains runnable MCP **client** examples built with `@modelcontextprotocol/client`.
|
||||
|
||||
For server examples, see [`../server/README.md`](../server/README.md). For guided docs, see [`../../docs/client.md`](../../docs/client.md).
|
||||
|
||||
## Running examples
|
||||
|
||||
From the repo root:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleStreamableHttp.ts
|
||||
```
|
||||
|
||||
Or, from within this package:
|
||||
|
||||
```bash
|
||||
cd examples/client
|
||||
pnpm tsx src/simpleStreamableHttp.ts
|
||||
```
|
||||
|
||||
Most clients expect a server to be running. Start one from [`../server/README.md`](../server/README.md) (for example `src/simpleStreamableHttp.ts` in `examples/server`).
|
||||
|
||||
## Example index
|
||||
|
||||
| Scenario | Description | File |
|
||||
| --------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| Interactive Streamable HTTP client | CLI client that exercises tools/resources/prompts, notifications, elicitation, and tasks. | [`src/simpleStreamableHttp.ts`](src/simpleStreamableHttp.ts) |
|
||||
| Backwards-compatible client (Streamable HTTP → SSE) | Tries Streamable HTTP first, falls back to legacy SSE on 4xx responses. | [`src/streamableHttpWithSseFallbackClient.ts`](src/streamableHttpWithSseFallbackClient.ts) |
|
||||
| SSE polling client (legacy) | Polls a legacy HTTP+SSE server and demonstrates notification handling. | [`src/ssePollingClient.ts`](src/ssePollingClient.ts) |
|
||||
| Parallel tool calls | Runs multiple tool calls in parallel. | [`src/parallelToolCallsClient.ts`](src/parallelToolCallsClient.ts) |
|
||||
| Multiple clients in parallel | Connects multiple clients concurrently to the same server. | [`src/multipleClientsParallel.ts`](src/multipleClientsParallel.ts) |
|
||||
| OAuth client (interactive) | OAuth-enabled client (dynamic registration, auth flow). | [`src/simpleOAuthClient.ts`](src/simpleOAuthClient.ts) |
|
||||
| OAuth provider helper | Demonstrates reusable OAuth providers. | [`src/simpleOAuthClientProvider.ts`](src/simpleOAuthClientProvider.ts) |
|
||||
| Client credentials (M2M) | Machine-to-machine OAuth client credentials example. | [`src/simpleClientCredentials.ts`](src/simpleClientCredentials.ts) |
|
||||
| URL elicitation client | Drives URL-mode elicitation flows (sensitive input in a browser). | [`src/elicitationUrlExample.ts`](src/elicitationUrlExample.ts) |
|
||||
| Task interactive client | Demonstrates task-based execution + interactive server→client requests. | [`src/simpleTaskInteractiveClient.ts`](src/simpleTaskInteractiveClient.ts) |
|
||||
|
||||
## URL elicitation example (server + client)
|
||||
|
||||
Run the server first:
|
||||
|
||||
```bash
|
||||
pnpm --filter @modelcontextprotocol/examples-server exec tsx src/elicitationUrlExample.ts
|
||||
```
|
||||
|
||||
Then run the client:
|
||||
|
||||
```bash
|
||||
pnpm --filter @modelcontextprotocol/examples-client exec tsx src/elicitationUrlExample.ts
|
||||
```
|
||||
14
examples/client/eslint.config.mjs
Normal file
14
examples/client/eslint.config.mjs
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
// @ts-check
|
||||
|
||||
import baseConfig from '@modelcontextprotocol/eslint-config';
|
||||
|
||||
export default [
|
||||
...baseConfig,
|
||||
{
|
||||
files: ['src/**/*.{ts,tsx,js,jsx,mts,cts}'],
|
||||
rules: {
|
||||
// Allow console statements in examples only
|
||||
'no-console': 'off'
|
||||
}
|
||||
}
|
||||
];
|
||||
48
examples/client/package.json
Normal file
48
examples/client/package.json
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
{
|
||||
"name": "@modelcontextprotocol/examples-client",
|
||||
"private": true,
|
||||
"version": "2.0.0-alpha.0",
|
||||
"description": "Model Context Protocol implementation for TypeScript",
|
||||
"license": "MIT",
|
||||
"author": "Anthropic, PBC (https://anthropic.com)",
|
||||
"homepage": "https://modelcontextprotocol.io",
|
||||
"bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues",
|
||||
"type": "module",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20",
|
||||
"pnpm": ">=10.24.0"
|
||||
},
|
||||
"packageManager": "pnpm@10.24.0",
|
||||
"keywords": [
|
||||
"modelcontextprotocol",
|
||||
"mcp"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsgo -p tsconfig.json --noEmit",
|
||||
"build": "tsdown",
|
||||
"build:watch": "tsdown --watch",
|
||||
"prepack": "npm run build:esm && npm run build:cjs",
|
||||
"lint": "eslint src/ && prettier --ignore-path ../../.prettierignore --check .",
|
||||
"lint:fix": "eslint src/ --fix && prettier --ignore-path ../../.prettierignore --write .",
|
||||
"check": "npm run typecheck && npm run lint",
|
||||
"start": "npm run server",
|
||||
"server": "tsx watch --clear-screen=false scripts/cli.ts server",
|
||||
"client": "tsx scripts/cli.ts client"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/client": "workspace:^",
|
||||
"ajv": "catalog:runtimeShared",
|
||||
"zod": "catalog:runtimeShared"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/examples-shared": "workspace:^",
|
||||
"@modelcontextprotocol/tsconfig": "workspace:^",
|
||||
"@modelcontextprotocol/eslint-config": "workspace:^",
|
||||
"@modelcontextprotocol/vitest-config": "workspace:^",
|
||||
"tsdown": "catalog:devTools"
|
||||
}
|
||||
}
|
||||
795
examples/client/src/elicitationUrlExample.ts
Normal file
795
examples/client/src/elicitationUrlExample.ts
Normal file
|
|
@ -0,0 +1,795 @@
|
|||
// Run with: pnpm tsx src/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 { exec } from 'node:child_process';
|
||||
import { createServer } from 'node:http';
|
||||
import { createInterface } from 'node:readline';
|
||||
|
||||
import type {
|
||||
CallToolRequest,
|
||||
ElicitRequest,
|
||||
ElicitRequestURLParams,
|
||||
ElicitResult,
|
||||
ListToolsRequest,
|
||||
OAuthClientMetadata,
|
||||
ResourceLink
|
||||
} from '@modelcontextprotocol/client';
|
||||
import {
|
||||
CallToolResultSchema,
|
||||
Client,
|
||||
ElicitationCompleteNotificationSchema,
|
||||
ElicitRequestSchema,
|
||||
ErrorCode,
|
||||
getDisplayName,
|
||||
ListToolsResultSchema,
|
||||
McpError,
|
||||
StreamableHTTPClientTransport,
|
||||
UnauthorizedError,
|
||||
UrlElicitationRequiredError
|
||||
} from '@modelcontextprotocol/client';
|
||||
|
||||
import { InMemoryOAuthClientProvider } from './simpleOAuthClientProvider.js';
|
||||
|
||||
// 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: InMemoryOAuthClientProvider | undefined = undefined;
|
||||
|
||||
console.log('Getting OAuth token...');
|
||||
const clientMetadata: OAuthClientMetadata = {
|
||||
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: URL) => {
|
||||
console.log(`🌐 Opening browser for OAuth redirect: ${redirectUrl.toString()}`);
|
||||
openBrowser(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: Client | null = null;
|
||||
let transport: StreamableHTTPClientTransport | null = null;
|
||||
let serverUrl = 'http://localhost:3000/mcp';
|
||||
let sessionId: string | undefined = undefined;
|
||||
|
||||
// Elicitation queue management
|
||||
interface QueuedElicitation {
|
||||
request: ElicitRequest;
|
||||
resolve: (result: ElicitResult) => void;
|
||||
reject: (error: Error) => void;
|
||||
}
|
||||
|
||||
let isProcessingCommand = false;
|
||||
let isProcessingElicitations = false;
|
||||
const elicitationQueue: QueuedElicitation[] = [];
|
||||
let elicitationQueueSignal: (() => void) | null = null;
|
||||
let elicitationsCompleteSignal: (() => void) | null = null;
|
||||
|
||||
// Map to track pending URL elicitations waiting for completion notifications
|
||||
const pendingURLElicitations = new Map<
|
||||
string,
|
||||
{
|
||||
resolve: () => void;
|
||||
reject: (error: Error) => void;
|
||||
timeout: NodeJS.Timeout;
|
||||
}
|
||||
>();
|
||||
|
||||
async function main(): Promise<void> {
|
||||
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(): Promise<void> {
|
||||
// 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(): void {
|
||||
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(): Promise<void> {
|
||||
await new Promise<void>(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(): Promise<void> {
|
||||
while (true) {
|
||||
// Wait until we have elicitations to process
|
||||
await new Promise<void>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function openBrowser(url: string): Promise<void> {
|
||||
const command = `open "${url}"`;
|
||||
|
||||
exec(command, error => {
|
||||
if (error) {
|
||||
console.error(`Failed to open browser: ${error.message}`);
|
||||
console.log(`Please manually open: ${url}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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: ElicitRequest): Promise<ElicitResult> {
|
||||
// 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<ElicitResult>((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: ElicitRequest): Promise<ElicitResult> {
|
||||
const mode = request.params.mode;
|
||||
console.log('\n🔔 Elicitation Request Received:');
|
||||
console.log(`Mode: ${mode}`);
|
||||
|
||||
if (mode === 'url') {
|
||||
return {
|
||||
action: await handleURLElicitation(request.params as ElicitRequestURLParams)
|
||||
};
|
||||
} 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: ElicitRequestURLParams): Promise<ElicitResult['action']> {
|
||||
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<string>(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<void>((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. Open the URL in the browser
|
||||
console.log(`\n🚀 Opening browser to: ${url}`);
|
||||
await openBrowser(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(): Promise<string> {
|
||||
return new Promise<string>((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: InMemoryOAuthClientProvider): Promise<void> {
|
||||
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?: string): Promise<void> {
|
||||
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(): Promise<void> {
|
||||
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(): Promise<void> {
|
||||
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(): Promise<void> {
|
||||
if (client) {
|
||||
await disconnect();
|
||||
}
|
||||
await connect();
|
||||
}
|
||||
|
||||
async function listTools(): Promise<void> {
|
||||
if (!client) {
|
||||
console.log('Not connected to server.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const toolsRequest: ListToolsRequest = {
|
||||
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: string, args: Record<string, unknown>): Promise<void> {
|
||||
if (!client) {
|
||||
console.log('Not connected to server.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const request: CallToolRequest = {
|
||||
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: ResourceLink[] = [];
|
||||
|
||||
result.content.forEach(item => {
|
||||
if (item.type === 'text') {
|
||||
console.log(` ${item.text}`);
|
||||
} else if (item.type === 'resource_link') {
|
||||
const resourceLink = item as ResourceLink;
|
||||
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(): Promise<void> {
|
||||
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(): Promise<void> {
|
||||
console.log('Calling payment-confirm tool...');
|
||||
await callTool('payment-confirm', { cartId: 'cart_123' });
|
||||
}
|
||||
|
||||
async function callThirdPartyAuthTool(): Promise<void> {
|
||||
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: unknown) => {
|
||||
console.error('Error running MCP client:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
158
examples/client/src/multipleClientsParallel.ts
Normal file
158
examples/client/src/multipleClientsParallel.ts
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
import type { CallToolRequest, CallToolResult } from '@modelcontextprotocol/client';
|
||||
import {
|
||||
CallToolResultSchema,
|
||||
Client,
|
||||
LoggingMessageNotificationSchema,
|
||||
StreamableHTTPClientTransport
|
||||
} from '@modelcontextprotocol/client';
|
||||
|
||||
/**
|
||||
* Multiple Clients MCP Example
|
||||
*
|
||||
* This client demonstrates how to:
|
||||
* 1. Create multiple MCP clients in parallel
|
||||
* 2. Each client calls a single tool
|
||||
* 3. Track notifications from each client independently
|
||||
*/
|
||||
|
||||
// Command line args processing
|
||||
const args = process.argv.slice(2);
|
||||
const serverUrl = args[0] || 'http://localhost:3000/mcp';
|
||||
|
||||
interface ClientConfig {
|
||||
id: string;
|
||||
name: string;
|
||||
toolName: string;
|
||||
toolArguments: Record<string, string | number | boolean>;
|
||||
}
|
||||
|
||||
async function createAndRunClient(config: ClientConfig): Promise<{ id: string; result: CallToolResult }> {
|
||||
console.log(`[${config.id}] Creating client: ${config.name}`);
|
||||
|
||||
const client = new Client({
|
||||
name: config.name,
|
||||
version: '1.0.0'
|
||||
});
|
||||
|
||||
const transport = new StreamableHTTPClientTransport(new URL(serverUrl));
|
||||
|
||||
// Set up client-specific error handler
|
||||
client.onerror = error => {
|
||||
console.error(`[${config.id}] Client error:`, error);
|
||||
};
|
||||
|
||||
// Set up client-specific notification handler
|
||||
client.setNotificationHandler(LoggingMessageNotificationSchema, notification => {
|
||||
console.log(`[${config.id}] Notification: ${notification.params.data}`);
|
||||
});
|
||||
|
||||
try {
|
||||
// Connect to the server
|
||||
await client.connect(transport);
|
||||
console.log(`[${config.id}] Connected to MCP server`);
|
||||
|
||||
// Call the specified tool
|
||||
console.log(`[${config.id}] Calling tool: ${config.toolName}`);
|
||||
const toolRequest: CallToolRequest = {
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: config.toolName,
|
||||
arguments: {
|
||||
...config.toolArguments,
|
||||
// Add client ID to arguments for identification in notifications
|
||||
caller: config.id
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const result = await client.request(toolRequest, CallToolResultSchema);
|
||||
console.log(`[${config.id}] Tool call completed`);
|
||||
|
||||
// Keep the connection open for a bit to receive notifications
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
|
||||
// Disconnect
|
||||
await transport.close();
|
||||
console.log(`[${config.id}] Disconnected from MCP server`);
|
||||
|
||||
return { id: config.id, result };
|
||||
} catch (error) {
|
||||
console.error(`[${config.id}] Error:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
console.log('MCP Multiple Clients Example');
|
||||
console.log('============================');
|
||||
console.log(`Server URL: ${serverUrl}`);
|
||||
console.log('');
|
||||
|
||||
try {
|
||||
// Define client configurations
|
||||
const clientConfigs: ClientConfig[] = [
|
||||
{
|
||||
id: 'client1',
|
||||
name: 'basic-client-1',
|
||||
toolName: 'start-notification-stream',
|
||||
toolArguments: {
|
||||
interval: 3, // 1 second between notifications
|
||||
count: 5 // Send 5 notifications
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'client2',
|
||||
name: 'basic-client-2',
|
||||
toolName: 'start-notification-stream',
|
||||
toolArguments: {
|
||||
interval: 2, // 2 seconds between notifications
|
||||
count: 3 // Send 3 notifications
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'client3',
|
||||
name: 'basic-client-3',
|
||||
toolName: 'start-notification-stream',
|
||||
toolArguments: {
|
||||
interval: 1, // 0.5 second between notifications
|
||||
count: 8 // Send 8 notifications
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
// Start all clients in parallel
|
||||
console.log(`Starting ${clientConfigs.length} clients in parallel...`);
|
||||
console.log('');
|
||||
|
||||
const clientPromises = clientConfigs.map(config => createAndRunClient(config));
|
||||
const results = await Promise.all(clientPromises);
|
||||
|
||||
// Display results from all clients
|
||||
console.log('\n=== Final Results ===');
|
||||
results.forEach(({ id, result }) => {
|
||||
console.log(`\n[${id}] Tool result:`);
|
||||
if (Array.isArray(result.content)) {
|
||||
result.content.forEach((item: { type: string; text?: string }) => {
|
||||
if (item.type === 'text' && item.text) {
|
||||
console.log(` ${item.text}`);
|
||||
} else {
|
||||
console.log(` ${item.type} content:`, item);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
console.log(` Unexpected result format:`, result);
|
||||
}
|
||||
});
|
||||
|
||||
console.log('\n=== All clients completed successfully ===');
|
||||
} catch (error) {
|
||||
console.error('Error running multiple clients:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Start the example
|
||||
main().catch((error: unknown) => {
|
||||
console.error('Error running MCP multiple clients example:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
195
examples/client/src/parallelToolCallsClient.ts
Normal file
195
examples/client/src/parallelToolCallsClient.ts
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
import type { CallToolResult, ListToolsRequest } from '@modelcontextprotocol/client';
|
||||
import {
|
||||
CallToolResultSchema,
|
||||
Client,
|
||||
ListToolsResultSchema,
|
||||
LoggingMessageNotificationSchema,
|
||||
StreamableHTTPClientTransport
|
||||
} from '@modelcontextprotocol/client';
|
||||
|
||||
/**
|
||||
* Parallel Tool Calls MCP Client
|
||||
*
|
||||
* This client demonstrates how to:
|
||||
* 1. Start multiple tool calls in parallel
|
||||
* 2. Track notifications from each tool call using a caller parameter
|
||||
*/
|
||||
|
||||
// Command line args processing
|
||||
const args = process.argv.slice(2);
|
||||
const serverUrl = args[0] || 'http://localhost:3000/mcp';
|
||||
|
||||
async function main(): Promise<void> {
|
||||
console.log('MCP Parallel Tool Calls Client');
|
||||
console.log('==============================');
|
||||
console.log(`Connecting to server at: ${serverUrl}`);
|
||||
|
||||
let client: Client;
|
||||
let transport: StreamableHTTPClientTransport;
|
||||
|
||||
try {
|
||||
// Create client with streamable HTTP transport
|
||||
client = new Client({
|
||||
name: 'parallel-tool-calls-client',
|
||||
version: '1.0.0'
|
||||
});
|
||||
|
||||
client.onerror = error => {
|
||||
console.error('Client error:', error);
|
||||
};
|
||||
|
||||
// Connect to the server
|
||||
transport = new StreamableHTTPClientTransport(new URL(serverUrl));
|
||||
await client.connect(transport);
|
||||
console.log('Successfully connected to MCP server');
|
||||
|
||||
// Set up notification handler with caller identification
|
||||
client.setNotificationHandler(LoggingMessageNotificationSchema, notification => {
|
||||
console.log(`Notification: ${notification.params.data}`);
|
||||
});
|
||||
|
||||
console.log('List tools');
|
||||
const toolsRequest = await listTools(client);
|
||||
console.log('Tools: ', toolsRequest);
|
||||
|
||||
// 2. Start multiple notification tools in parallel
|
||||
console.log('\n=== Starting Multiple Notification Streams in Parallel ===');
|
||||
const toolResults = await startParallelNotificationTools(client);
|
||||
|
||||
// Log the results from each tool call
|
||||
for (const [caller, result] of Object.entries(toolResults)) {
|
||||
console.log(`\n=== Tool result for ${caller} ===`);
|
||||
result.content.forEach((item: { type: string; text?: string }) => {
|
||||
if (item.type === 'text') {
|
||||
console.log(` ${item.text}`);
|
||||
} else {
|
||||
console.log(` ${item.type} content:`, item);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 3. Wait for all notifications (10 seconds)
|
||||
console.log('\n=== Waiting for all notifications ===');
|
||||
await new Promise(resolve => setTimeout(resolve, 10000));
|
||||
|
||||
// 4. Disconnect
|
||||
console.log('\n=== Disconnecting ===');
|
||||
await transport.close();
|
||||
console.log('Disconnected from MCP server');
|
||||
} catch (error) {
|
||||
console.error('Error running client:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List available tools on the server
|
||||
*/
|
||||
async function listTools(client: Client): Promise<void> {
|
||||
try {
|
||||
const toolsRequest: ListToolsRequest = {
|
||||
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(` - ${tool.name}: ${tool.description}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`Tools not supported by this server: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start multiple notification tools in parallel with different configurations
|
||||
* Each tool call includes a caller parameter to identify its notifications
|
||||
*/
|
||||
async function startParallelNotificationTools(client: Client): Promise<Record<string, CallToolResult>> {
|
||||
try {
|
||||
// Define multiple tool calls with different configurations
|
||||
const toolCalls = [
|
||||
{
|
||||
caller: 'fast-notifier',
|
||||
request: {
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'start-notification-stream',
|
||||
arguments: {
|
||||
interval: 2, // 0.5 second between notifications
|
||||
count: 10, // Send 10 notifications
|
||||
caller: 'fast-notifier' // Identify this tool call
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
caller: 'slow-notifier',
|
||||
request: {
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'start-notification-stream',
|
||||
arguments: {
|
||||
interval: 5, // 2 seconds between notifications
|
||||
count: 5, // Send 5 notifications
|
||||
caller: 'slow-notifier' // Identify this tool call
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
caller: 'burst-notifier',
|
||||
request: {
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'start-notification-stream',
|
||||
arguments: {
|
||||
interval: 1, // 0.1 second between notifications
|
||||
count: 3, // Send just 3 notifications
|
||||
caller: 'burst-notifier' // Identify this tool call
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
console.log(`Starting ${toolCalls.length} notification tools in parallel...`);
|
||||
|
||||
// Start all tool calls in parallel
|
||||
const toolPromises = toolCalls.map(({ caller, request }) => {
|
||||
console.log(`Starting tool call for ${caller}...`);
|
||||
return client
|
||||
.request(request, CallToolResultSchema)
|
||||
.then(result => ({ caller, result }))
|
||||
.catch(error => {
|
||||
console.error(`Error in tool call for ${caller}:`, error);
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
|
||||
// Wait for all tool calls to complete
|
||||
const results = await Promise.all(toolPromises);
|
||||
|
||||
// Organize results by caller
|
||||
const resultsByTool: Record<string, CallToolResult> = {};
|
||||
results.forEach(({ caller, result }) => {
|
||||
resultsByTool[caller] = result;
|
||||
});
|
||||
|
||||
return resultsByTool;
|
||||
} catch (error) {
|
||||
console.error(`Error starting parallel notification tools:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Start the client
|
||||
main().catch((error: unknown) => {
|
||||
console.error('Error running MCP client:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
80
examples/client/src/simpleClientCredentials.ts
Normal file
80
examples/client/src/simpleClientCredentials.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Example demonstrating client_credentials grant for machine-to-machine authentication.
|
||||
*
|
||||
* Supports two authentication methods based on environment variables:
|
||||
*
|
||||
* 1. client_secret_basic (default):
|
||||
* MCP_CLIENT_ID - OAuth client ID (required)
|
||||
* MCP_CLIENT_SECRET - OAuth client secret (required)
|
||||
*
|
||||
* 2. private_key_jwt (when MCP_CLIENT_PRIVATE_KEY_PEM is set):
|
||||
* MCP_CLIENT_ID - OAuth client ID (required)
|
||||
* MCP_CLIENT_PRIVATE_KEY_PEM - PEM-encoded private key for JWT signing (required)
|
||||
* MCP_CLIENT_ALGORITHM - Signing algorithm (default: RS256)
|
||||
*
|
||||
* Common:
|
||||
* MCP_SERVER_URL - Server URL (default: http://localhost:3000/mcp)
|
||||
*/
|
||||
|
||||
import type { OAuthClientProvider } from '@modelcontextprotocol/client';
|
||||
import { Client, ClientCredentialsProvider, PrivateKeyJwtProvider, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
|
||||
|
||||
const DEFAULT_SERVER_URL = process.env.MCP_SERVER_URL || 'http://localhost:3000/mcp';
|
||||
|
||||
function createProvider(): OAuthClientProvider {
|
||||
const clientId = process.env.MCP_CLIENT_ID;
|
||||
if (!clientId) {
|
||||
console.error('MCP_CLIENT_ID environment variable is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// If private key is provided, use private_key_jwt authentication
|
||||
const privateKeyPem = process.env.MCP_CLIENT_PRIVATE_KEY_PEM;
|
||||
if (privateKeyPem) {
|
||||
const algorithm = process.env.MCP_CLIENT_ALGORITHM || 'RS256';
|
||||
console.log('Using private_key_jwt authentication');
|
||||
return new PrivateKeyJwtProvider({
|
||||
clientId,
|
||||
privateKey: privateKeyPem,
|
||||
algorithm
|
||||
});
|
||||
}
|
||||
|
||||
// Otherwise, use client_secret_basic authentication
|
||||
const clientSecret = process.env.MCP_CLIENT_SECRET;
|
||||
if (!clientSecret) {
|
||||
console.error('MCP_CLIENT_SECRET or MCP_CLIENT_PRIVATE_KEY_PEM environment variable is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log('Using client_secret_basic authentication');
|
||||
return new ClientCredentialsProvider({
|
||||
clientId,
|
||||
clientSecret
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const provider = createProvider();
|
||||
|
||||
const client = new Client({ name: 'client-credentials-example', version: '1.0.0' }, { capabilities: {} });
|
||||
|
||||
const transport = new StreamableHTTPClientTransport(new URL(DEFAULT_SERVER_URL), {
|
||||
authProvider: provider
|
||||
});
|
||||
|
||||
await client.connect(transport);
|
||||
console.log('Connected successfully.');
|
||||
|
||||
const tools = await client.listTools();
|
||||
console.log('Available tools:', tools.tools.map(t => t.name).join(', ') || '(none)');
|
||||
|
||||
await transport.close();
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
463
examples/client/src/simpleOAuthClient.ts
Normal file
463
examples/client/src/simpleOAuthClient.ts
Normal file
|
|
@ -0,0 +1,463 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import { exec } from 'node:child_process';
|
||||
import { createServer } from 'node:http';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { URL } from 'node:url';
|
||||
|
||||
import type { CallToolRequest, ListToolsRequest, OAuthClientMetadata } from '@modelcontextprotocol/client';
|
||||
import {
|
||||
CallToolResultSchema,
|
||||
Client,
|
||||
ListToolsResultSchema,
|
||||
StreamableHTTPClientTransport,
|
||||
UnauthorizedError
|
||||
} from '@modelcontextprotocol/client';
|
||||
|
||||
import { InMemoryOAuthClientProvider } from './simpleOAuthClientProvider.js';
|
||||
|
||||
// Configuration
|
||||
const DEFAULT_SERVER_URL = 'http://localhost:3000/mcp';
|
||||
const CALLBACK_PORT = 8090; // Use different port than auth server (3001)
|
||||
const CALLBACK_URL = `http://localhost:${CALLBACK_PORT}/callback`;
|
||||
|
||||
/**
|
||||
* Interactive MCP client with OAuth authentication
|
||||
* Demonstrates the complete OAuth flow with browser-based authorization
|
||||
*/
|
||||
class InteractiveOAuthClient {
|
||||
private client: Client | null = null;
|
||||
private readonly rl = createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
});
|
||||
|
||||
constructor(
|
||||
private serverUrl: string,
|
||||
private clientMetadataUrl?: string
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Prompts user for input via readline
|
||||
*/
|
||||
private async question(query: string): Promise<string> {
|
||||
return new Promise(resolve => {
|
||||
this.rl.question(query, resolve);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the authorization URL in the user's default browser
|
||||
*/
|
||||
private async openBrowser(url: string): Promise<void> {
|
||||
console.log(`🌐 Opening browser for authorization: ${url}`);
|
||||
|
||||
const command = `open "${url}"`;
|
||||
|
||||
exec(command, error => {
|
||||
if (error) {
|
||||
console.error(`Failed to open browser: ${error.message}`);
|
||||
console.log(`Please manually open: ${url}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
private async waitForOAuthCallback(): Promise<string> {
|
||||
return new Promise<string>((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>You can close this window and return to the terminal.</p>
|
||||
<script>setTimeout(() => window.close(), 2000);</script>
|
||||
</body>
|
||||
</html>
|
||||
`);
|
||||
|
||||
resolve(code);
|
||||
setTimeout(() => server.close(), 3000);
|
||||
} 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(CALLBACK_PORT, () => {
|
||||
console.log(`OAuth callback server started on http://localhost:${CALLBACK_PORT}`);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private async attemptConnection(oauthProvider: InMemoryOAuthClientProvider): Promise<void> {
|
||||
console.log('🚢 Creating transport with OAuth provider...');
|
||||
const baseUrl = new URL(this.serverUrl);
|
||||
const transport = new StreamableHTTPClientTransport(baseUrl, {
|
||||
authProvider: oauthProvider
|
||||
});
|
||||
console.log('🚢 Transport created');
|
||||
|
||||
try {
|
||||
console.log('🔌 Attempting connection (this will trigger OAuth redirect)...');
|
||||
await this.client!.connect(transport);
|
||||
console.log('✅ Connected successfully');
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthorizedError) {
|
||||
console.log('🔐 OAuth required - waiting for authorization...');
|
||||
const callbackPromise = this.waitForOAuthCallback();
|
||||
const authCode = await callbackPromise;
|
||||
await transport.finishAuth(authCode);
|
||||
console.log('🔐 Authorization code received:', authCode);
|
||||
console.log('🔌 Reconnecting with authenticated transport...');
|
||||
await this.attemptConnection(oauthProvider);
|
||||
} else {
|
||||
console.error('❌ Connection failed with non-auth error:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Establishes connection to the MCP server with OAuth authentication
|
||||
*/
|
||||
async connect(): Promise<void> {
|
||||
console.log(`🔗 Attempting to connect to ${this.serverUrl}...`);
|
||||
|
||||
const clientMetadata: OAuthClientMetadata = {
|
||||
client_name: 'Simple OAuth MCP Client',
|
||||
redirect_uris: [CALLBACK_URL],
|
||||
grant_types: ['authorization_code', 'refresh_token'],
|
||||
response_types: ['code'],
|
||||
token_endpoint_auth_method: 'client_secret_post'
|
||||
};
|
||||
|
||||
console.log('🔐 Creating OAuth provider...');
|
||||
const oauthProvider = new InMemoryOAuthClientProvider(
|
||||
CALLBACK_URL,
|
||||
clientMetadata,
|
||||
(redirectUrl: URL) => {
|
||||
console.log(`📌 OAuth redirect handler called - opening browser`);
|
||||
console.log(`Opening browser to: ${redirectUrl.toString()}`);
|
||||
this.openBrowser(redirectUrl.toString());
|
||||
},
|
||||
this.clientMetadataUrl
|
||||
);
|
||||
console.log('🔐 OAuth provider created');
|
||||
|
||||
console.log('👤 Creating MCP client...');
|
||||
this.client = new Client(
|
||||
{
|
||||
name: 'simple-oauth-client',
|
||||
version: '1.0.0'
|
||||
},
|
||||
{ capabilities: {} }
|
||||
);
|
||||
console.log('👤 Client created');
|
||||
|
||||
console.log('🔐 Starting OAuth flow...');
|
||||
|
||||
await this.attemptConnection(oauthProvider);
|
||||
|
||||
// Start interactive loop
|
||||
await this.interactiveLoop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Main interactive loop for user commands
|
||||
*/
|
||||
async interactiveLoop(): Promise<void> {
|
||||
console.log('\n🎯 Interactive MCP Client with OAuth');
|
||||
console.log('Commands:');
|
||||
console.log(' list - List available tools');
|
||||
console.log(' call <tool_name> [args] - Call a tool');
|
||||
console.log(' stream <tool_name> [args] - Call a tool with streaming (shows task status)');
|
||||
console.log(' quit - Exit the client');
|
||||
console.log();
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
const command = await this.question('mcp> ');
|
||||
|
||||
if (!command.trim()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (command === 'quit') {
|
||||
console.log('\n👋 Goodbye!');
|
||||
this.close();
|
||||
process.exit(0);
|
||||
} else if (command === 'list') {
|
||||
await this.listTools();
|
||||
} else if (command.startsWith('call ')) {
|
||||
await this.handleCallTool(command);
|
||||
} else if (command.startsWith('stream ')) {
|
||||
await this.handleStreamTool(command);
|
||||
} else {
|
||||
console.log("❌ Unknown command. Try 'list', 'call <tool_name>', 'stream <tool_name>', or 'quit'");
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === 'SIGINT') {
|
||||
console.log('\n\n👋 Goodbye!');
|
||||
break;
|
||||
}
|
||||
console.error('❌ Error:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async listTools(): Promise<void> {
|
||||
if (!this.client) {
|
||||
console.log('❌ Not connected to server');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const request: ListToolsRequest = {
|
||||
method: 'tools/list',
|
||||
params: {}
|
||||
};
|
||||
|
||||
const result = await this.client.request(request, ListToolsResultSchema);
|
||||
|
||||
if (result.tools && result.tools.length > 0) {
|
||||
console.log('\n📋 Available tools:');
|
||||
result.tools.forEach((tool, index) => {
|
||||
console.log(`${index + 1}. ${tool.name}`);
|
||||
if (tool.description) {
|
||||
console.log(` Description: ${tool.description}`);
|
||||
}
|
||||
console.log();
|
||||
});
|
||||
} else {
|
||||
console.log('No tools available');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to list tools:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleCallTool(command: string): Promise<void> {
|
||||
const parts = command.split(/\s+/);
|
||||
const toolName = parts[1];
|
||||
|
||||
if (!toolName) {
|
||||
console.log('❌ Please specify a tool name');
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse arguments (simple JSON-like format)
|
||||
let toolArgs: Record<string, unknown> = {};
|
||||
if (parts.length > 2) {
|
||||
const argsString = parts.slice(2).join(' ');
|
||||
try {
|
||||
toolArgs = JSON.parse(argsString);
|
||||
} catch {
|
||||
console.log('❌ Invalid arguments format (expected JSON)');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await this.callTool(toolName, toolArgs);
|
||||
}
|
||||
|
||||
private async callTool(toolName: string, toolArgs: Record<string, unknown>): Promise<void> {
|
||||
if (!this.client) {
|
||||
console.log('❌ Not connected to server');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const request: CallToolRequest = {
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: toolName,
|
||||
arguments: toolArgs
|
||||
}
|
||||
};
|
||||
|
||||
const result = await this.client.request(request, CallToolResultSchema);
|
||||
|
||||
console.log(`\n🔧 Tool '${toolName}' result:`);
|
||||
if (result.content) {
|
||||
result.content.forEach(content => {
|
||||
if (content.type === 'text') {
|
||||
console.log(content.text);
|
||||
} else {
|
||||
console.log(content);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
console.log(result);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`❌ Failed to call tool '${toolName}':`, error);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleStreamTool(command: string): Promise<void> {
|
||||
const parts = command.split(/\s+/);
|
||||
const toolName = parts[1];
|
||||
|
||||
if (!toolName) {
|
||||
console.log('❌ Please specify a tool name');
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse arguments (simple JSON-like format)
|
||||
let toolArgs: Record<string, unknown> = {};
|
||||
if (parts.length > 2) {
|
||||
const argsString = parts.slice(2).join(' ');
|
||||
try {
|
||||
toolArgs = JSON.parse(argsString);
|
||||
} catch {
|
||||
console.log('❌ Invalid arguments format (expected JSON)');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await this.streamTool(toolName, toolArgs);
|
||||
}
|
||||
|
||||
private async streamTool(toolName: string, toolArgs: Record<string, unknown>): Promise<void> {
|
||||
if (!this.client) {
|
||||
console.log('❌ Not connected to server');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Using the experimental tasks API - WARNING: may change without notice
|
||||
console.log(`\n🔧 Streaming tool '${toolName}'...`);
|
||||
|
||||
const stream = this.client.experimental.tasks.callToolStream(
|
||||
{
|
||||
name: toolName,
|
||||
arguments: toolArgs
|
||||
},
|
||||
CallToolResultSchema,
|
||||
{
|
||||
task: {
|
||||
taskId: `task-${Date.now()}`,
|
||||
ttl: 60000
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Iterate through all messages yielded by the generator
|
||||
for await (const message of stream) {
|
||||
switch (message.type) {
|
||||
case 'taskCreated':
|
||||
console.log(`✓ Task created: ${message.task.taskId}`);
|
||||
break;
|
||||
|
||||
case 'taskStatus':
|
||||
console.log(`⟳ Status: ${message.task.status}`);
|
||||
if (message.task.statusMessage) {
|
||||
console.log(` ${message.task.statusMessage}`);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'result':
|
||||
console.log('✓ Completed!');
|
||||
message.result.content.forEach(content => {
|
||||
if (content.type === 'text') {
|
||||
console.log(content.text);
|
||||
} else {
|
||||
console.log(content);
|
||||
}
|
||||
});
|
||||
break;
|
||||
|
||||
case 'error':
|
||||
console.log('✗ Error:');
|
||||
console.log(` ${message.error.message}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`❌ Failed to stream tool '${toolName}':`, error);
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.rl.close();
|
||||
if (this.client) {
|
||||
// Note: Client doesn't have a close method in the current implementation
|
||||
// This would typically close the transport connection
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main entry point
|
||||
*/
|
||||
async function main(): Promise<void> {
|
||||
const args = process.argv.slice(2);
|
||||
const serverUrl = args[0] || DEFAULT_SERVER_URL;
|
||||
const clientMetadataUrl = args[1];
|
||||
|
||||
console.log('🚀 Simple MCP OAuth Client');
|
||||
console.log(`Connecting to: ${serverUrl}`);
|
||||
if (clientMetadataUrl) {
|
||||
console.log(`Client Metadata URL: ${clientMetadataUrl}`);
|
||||
}
|
||||
console.log();
|
||||
|
||||
const client = new InteractiveOAuthClient(serverUrl, clientMetadataUrl);
|
||||
|
||||
// Handle graceful shutdown
|
||||
process.on('SIGINT', () => {
|
||||
console.log('\n\n👋 Goodbye!');
|
||||
client.close();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
} catch (error) {
|
||||
console.error('Failed to start client:', error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
// Run if this file is executed directly
|
||||
main().catch(error => {
|
||||
console.error('Unhandled error:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
65
examples/client/src/simpleOAuthClientProvider.ts
Normal file
65
examples/client/src/simpleOAuthClientProvider.ts
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
import type { OAuthClientInformationMixed, OAuthClientMetadata, OAuthClientProvider, OAuthTokens } from '@modelcontextprotocol/client';
|
||||
|
||||
/**
|
||||
* In-memory OAuth client provider for demonstration purposes
|
||||
* In production, you should persist tokens securely
|
||||
*/
|
||||
export class InMemoryOAuthClientProvider implements OAuthClientProvider {
|
||||
private _clientInformation?: OAuthClientInformationMixed;
|
||||
private _tokens?: OAuthTokens;
|
||||
private _codeVerifier?: string;
|
||||
|
||||
constructor(
|
||||
private readonly _redirectUrl: string | URL,
|
||||
private readonly _clientMetadata: OAuthClientMetadata,
|
||||
onRedirect?: (url: URL) => void,
|
||||
public readonly clientMetadataUrl?: string
|
||||
) {
|
||||
this._onRedirect =
|
||||
onRedirect ||
|
||||
(url => {
|
||||
console.log(`Redirect to: ${url.toString()}`);
|
||||
});
|
||||
}
|
||||
|
||||
private _onRedirect: (url: URL) => void;
|
||||
|
||||
get redirectUrl(): string | URL {
|
||||
return this._redirectUrl;
|
||||
}
|
||||
|
||||
get clientMetadata(): OAuthClientMetadata {
|
||||
return this._clientMetadata;
|
||||
}
|
||||
|
||||
clientInformation(): OAuthClientInformationMixed | undefined {
|
||||
return this._clientInformation;
|
||||
}
|
||||
|
||||
saveClientInformation(clientInformation: OAuthClientInformationMixed): void {
|
||||
this._clientInformation = clientInformation;
|
||||
}
|
||||
|
||||
tokens(): OAuthTokens | undefined {
|
||||
return this._tokens;
|
||||
}
|
||||
|
||||
saveTokens(tokens: OAuthTokens): void {
|
||||
this._tokens = tokens;
|
||||
}
|
||||
|
||||
redirectToAuthorization(authorizationUrl: URL): void {
|
||||
this._onRedirect(authorizationUrl);
|
||||
}
|
||||
|
||||
saveCodeVerifier(codeVerifier: string): void {
|
||||
this._codeVerifier = codeVerifier;
|
||||
}
|
||||
|
||||
codeVerifier(): string {
|
||||
if (!this._codeVerifier) {
|
||||
throw new Error('No code verifier saved');
|
||||
}
|
||||
return this._codeVerifier;
|
||||
}
|
||||
}
|
||||
927
examples/client/src/simpleStreamableHttp.ts
Normal file
927
examples/client/src/simpleStreamableHttp.ts
Normal file
|
|
@ -0,0 +1,927 @@
|
|||
import { createInterface } from 'node:readline';
|
||||
|
||||
import type {
|
||||
CallToolRequest,
|
||||
GetPromptRequest,
|
||||
ListPromptsRequest,
|
||||
ListResourcesRequest,
|
||||
ListToolsRequest,
|
||||
ReadResourceRequest,
|
||||
ResourceLink
|
||||
} from '@modelcontextprotocol/client';
|
||||
import {
|
||||
CallToolResultSchema,
|
||||
Client,
|
||||
ElicitRequestSchema,
|
||||
ErrorCode,
|
||||
getDisplayName,
|
||||
GetPromptResultSchema,
|
||||
ListPromptsResultSchema,
|
||||
ListResourcesResultSchema,
|
||||
ListToolsResultSchema,
|
||||
LoggingMessageNotificationSchema,
|
||||
McpError,
|
||||
ReadResourceResultSchema,
|
||||
RELATED_TASK_META_KEY,
|
||||
ResourceListChangedNotificationSchema,
|
||||
StreamableHTTPClientTransport
|
||||
} from '@modelcontextprotocol/client';
|
||||
import { Ajv } from 'ajv';
|
||||
|
||||
// Create readline interface for user input
|
||||
const readline = createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
});
|
||||
|
||||
// Track received notifications for debugging resumability
|
||||
let notificationCount = 0;
|
||||
|
||||
// Global client and transport for interactive commands
|
||||
let client: Client | null = null;
|
||||
let transport: StreamableHTTPClientTransport | null = null;
|
||||
let serverUrl = 'http://localhost:3000/mcp';
|
||||
let notificationsToolLastEventId: string | undefined = undefined;
|
||||
let sessionId: string | undefined = undefined;
|
||||
|
||||
async function main(): Promise<void> {
|
||||
console.log('MCP Interactive Client');
|
||||
console.log('=====================');
|
||||
|
||||
// Connect to server immediately with default settings
|
||||
await connect();
|
||||
|
||||
// Print help and start the command loop
|
||||
printHelp();
|
||||
commandLoop();
|
||||
}
|
||||
|
||||
function printHelp(): void {
|
||||
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(' call-tool-task <name> [args] - Call a tool with task-based execution (example: call-tool-task delay {"duration":3000})');
|
||||
console.log(' greet [name] - Call the greet tool');
|
||||
console.log(' multi-greet [name] - Call the multi-greet tool with notifications');
|
||||
console.log(' collect-info [type] - Test form elicitation with collect-user-info tool (contact/preferences/feedback)');
|
||||
console.log(' start-notifications [interval] [count] - Start periodic notifications');
|
||||
console.log(' run-notifications-tool-with-resumability [interval] [count] - Run notification tool with resumability');
|
||||
console.log(' list-prompts - List available prompts');
|
||||
console.log(' get-prompt [name] [args] - Get a prompt with optional JSON arguments');
|
||||
console.log(' list-resources - List available resources');
|
||||
console.log(' read-resource <uri> - Read a specific resource by URI');
|
||||
console.log(' help - Show this help');
|
||||
console.log(' quit - Exit the program');
|
||||
}
|
||||
|
||||
function commandLoop(): void {
|
||||
readline.question('\n> ', async input => {
|
||||
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 'greet':
|
||||
await callGreetTool(args[1] || 'MCP User');
|
||||
break;
|
||||
|
||||
case 'multi-greet':
|
||||
await callMultiGreetTool(args[1] || 'MCP User');
|
||||
break;
|
||||
|
||||
case 'collect-info':
|
||||
await callCollectInfoTool(args[1] || 'contact');
|
||||
break;
|
||||
|
||||
case 'start-notifications': {
|
||||
const interval = args[1] ? parseInt(args[1], 10) : 2000;
|
||||
const count = args[2] ? parseInt(args[2], 10) : 10;
|
||||
await startNotifications(interval, count);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'run-notifications-tool-with-resumability': {
|
||||
const interval = args[1] ? parseInt(args[1], 10) : 2000;
|
||||
const count = args[2] ? parseInt(args[2], 10) : 10;
|
||||
await runNotificationsToolWithResumability(interval, count);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'call-tool-task':
|
||||
if (args.length < 2) {
|
||||
console.log('Usage: call-tool-task <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 callToolTask(toolName, toolArgs);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'list-prompts':
|
||||
await listPrompts();
|
||||
break;
|
||||
|
||||
case 'get-prompt':
|
||||
if (args.length < 2) {
|
||||
console.log('Usage: get-prompt <name> [args]');
|
||||
} else {
|
||||
const promptName = args[1]!;
|
||||
let promptArgs = {};
|
||||
if (args.length > 2) {
|
||||
try {
|
||||
promptArgs = JSON.parse(args.slice(2).join(' '));
|
||||
} catch {
|
||||
console.log('Invalid JSON arguments. Using empty args.');
|
||||
}
|
||||
}
|
||||
await getPrompt(promptName, promptArgs);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'list-resources':
|
||||
await listResources();
|
||||
break;
|
||||
|
||||
case 'read-resource':
|
||||
if (args.length < 2) {
|
||||
console.log('Usage: read-resource <uri>');
|
||||
} else {
|
||||
await readResource(args[1]!);
|
||||
}
|
||||
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}`);
|
||||
}
|
||||
|
||||
// Continue the command loop
|
||||
commandLoop();
|
||||
});
|
||||
}
|
||||
|
||||
async function connect(url?: string): Promise<void> {
|
||||
if (client) {
|
||||
console.log('Already connected. Disconnect first.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (url) {
|
||||
serverUrl = url;
|
||||
}
|
||||
|
||||
console.log(`Connecting to ${serverUrl}...`);
|
||||
|
||||
try {
|
||||
// Create a new client with form elicitation capability
|
||||
client = new Client(
|
||||
{
|
||||
name: 'example-client',
|
||||
version: '1.0.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
elicitation: {
|
||||
form: {}
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
client.onerror = error => {
|
||||
console.error('\x1b[31mClient error:', error, '\x1b[0m');
|
||||
};
|
||||
|
||||
// Set up elicitation request handler with proper validation
|
||||
client.setRequestHandler(ElicitRequestSchema, async request => {
|
||||
if (request.params.mode !== 'form') {
|
||||
throw new McpError(ErrorCode.InvalidParams, `Unsupported elicitation mode: ${request.params.mode}`);
|
||||
}
|
||||
console.log('\n🔔 Elicitation (form) Request Received:');
|
||||
console.log(`Message: ${request.params.message}`);
|
||||
console.log(`Related Task: ${request.params._meta?.[RELATED_TASK_META_KEY]?.taskId}`);
|
||||
console.log('Requested Schema:');
|
||||
console.log(JSON.stringify(request.params.requestedSchema, null, 2));
|
||||
|
||||
const schema = request.params.requestedSchema;
|
||||
const properties = schema.properties;
|
||||
const required = schema.required || [];
|
||||
|
||||
// Set up AJV validator for the requested schema
|
||||
const ajv = new Ajv();
|
||||
const validate = ajv.compile(schema);
|
||||
|
||||
let attempts = 0;
|
||||
const maxAttempts = 3;
|
||||
|
||||
while (attempts < maxAttempts) {
|
||||
attempts++;
|
||||
console.log(`\nPlease provide the following information (attempt ${attempts}/${maxAttempts}):`);
|
||||
|
||||
const content: Record<string, unknown> = {};
|
||||
let inputCancelled = false;
|
||||
|
||||
// Collect input for each field
|
||||
for (const [fieldName, fieldSchema] of Object.entries(properties)) {
|
||||
const field = fieldSchema as {
|
||||
type?: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
default?: unknown;
|
||||
enum?: string[];
|
||||
minimum?: number;
|
||||
maximum?: number;
|
||||
minLength?: number;
|
||||
maxLength?: number;
|
||||
format?: string;
|
||||
};
|
||||
|
||||
const isRequired = required.includes(fieldName);
|
||||
let prompt = `${field.title || fieldName}`;
|
||||
|
||||
// Add helpful information to the prompt
|
||||
if (field.description) {
|
||||
prompt += ` (${field.description})`;
|
||||
}
|
||||
if (field.enum) {
|
||||
prompt += ` [options: ${field.enum.join(', ')}]`;
|
||||
}
|
||||
if (field.type === 'number' || field.type === 'integer') {
|
||||
if (field.minimum !== undefined && field.maximum !== undefined) {
|
||||
prompt += ` [${field.minimum}-${field.maximum}]`;
|
||||
} else if (field.minimum !== undefined) {
|
||||
prompt += ` [min: ${field.minimum}]`;
|
||||
} else if (field.maximum !== undefined) {
|
||||
prompt += ` [max: ${field.maximum}]`;
|
||||
}
|
||||
}
|
||||
if (field.type === 'string' && field.format) {
|
||||
prompt += ` [format: ${field.format}]`;
|
||||
}
|
||||
if (isRequired) {
|
||||
prompt += ' *required*';
|
||||
}
|
||||
if (field.default !== undefined) {
|
||||
prompt += ` [default: ${field.default}]`;
|
||||
}
|
||||
|
||||
prompt += ': ';
|
||||
|
||||
const answer = await new Promise<string>(resolve => {
|
||||
readline.question(prompt, input => {
|
||||
resolve(input.trim());
|
||||
});
|
||||
});
|
||||
|
||||
// Check for cancellation
|
||||
if (answer.toLowerCase() === 'cancel' || answer.toLowerCase() === 'c') {
|
||||
inputCancelled = true;
|
||||
break;
|
||||
}
|
||||
|
||||
// Parse and validate the input
|
||||
try {
|
||||
if (answer === '' && field.default !== undefined) {
|
||||
content[fieldName] = field.default;
|
||||
} else if (answer === '' && !isRequired) {
|
||||
// Skip optional empty fields
|
||||
continue;
|
||||
} else if (answer === '') {
|
||||
throw new Error(`${fieldName} is required`);
|
||||
} else {
|
||||
// Parse the value based on type
|
||||
let parsedValue: unknown;
|
||||
|
||||
if (field.type === 'boolean') {
|
||||
parsedValue = answer.toLowerCase() === 'true' || answer.toLowerCase() === 'yes' || answer === '1';
|
||||
} else if (field.type === 'number') {
|
||||
parsedValue = parseFloat(answer);
|
||||
if (isNaN(parsedValue as number)) {
|
||||
throw new Error(`${fieldName} must be a valid number`);
|
||||
}
|
||||
} else if (field.type === 'integer') {
|
||||
parsedValue = parseInt(answer, 10);
|
||||
if (isNaN(parsedValue as number)) {
|
||||
throw new Error(`${fieldName} must be a valid integer`);
|
||||
}
|
||||
} else if (field.enum) {
|
||||
if (!field.enum.includes(answer)) {
|
||||
throw new Error(`${fieldName} must be one of: ${field.enum.join(', ')}`);
|
||||
}
|
||||
parsedValue = answer;
|
||||
} else {
|
||||
parsedValue = answer;
|
||||
}
|
||||
|
||||
content[fieldName] = parsedValue;
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`❌ Error: ${error}`);
|
||||
// Continue to next attempt
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (inputCancelled) {
|
||||
return { action: 'cancel' };
|
||||
}
|
||||
|
||||
// If we didn't complete all fields due to an error, try again
|
||||
if (
|
||||
Object.keys(content).length !==
|
||||
Object.keys(properties).filter(name => required.includes(name) || content[name] !== undefined).length
|
||||
) {
|
||||
if (attempts < maxAttempts) {
|
||||
console.log('Please try again...');
|
||||
continue;
|
||||
} else {
|
||||
console.log('Maximum attempts reached. Declining request.');
|
||||
return { action: 'decline' };
|
||||
}
|
||||
}
|
||||
|
||||
// Validate the complete object against the schema
|
||||
const isValid = validate(content);
|
||||
|
||||
if (!isValid) {
|
||||
console.log('❌ Validation errors:');
|
||||
validate.errors?.forEach(error => {
|
||||
console.log(` - ${error.instancePath || 'root'}: ${error.message}`);
|
||||
});
|
||||
|
||||
if (attempts < maxAttempts) {
|
||||
console.log('Please correct the errors and try again...');
|
||||
continue;
|
||||
} else {
|
||||
console.log('Maximum attempts reached. Declining request.');
|
||||
return { action: 'decline' };
|
||||
}
|
||||
}
|
||||
|
||||
// Show the collected data and ask for confirmation
|
||||
console.log('\n✅ Collected data:');
|
||||
console.log(JSON.stringify(content, null, 2));
|
||||
|
||||
const confirmAnswer = await new Promise<string>(resolve => {
|
||||
readline.question('\nSubmit this information? (yes/no/cancel): ', input => {
|
||||
resolve(input.trim().toLowerCase());
|
||||
});
|
||||
});
|
||||
|
||||
if (confirmAnswer === 'yes' || confirmAnswer === 'y') {
|
||||
return {
|
||||
action: 'accept',
|
||||
content
|
||||
};
|
||||
} else if (confirmAnswer === 'cancel' || confirmAnswer === 'c') {
|
||||
return { action: 'cancel' };
|
||||
} else if (confirmAnswer === 'no' || confirmAnswer === 'n') {
|
||||
if (attempts < maxAttempts) {
|
||||
console.log('Please re-enter the information...');
|
||||
continue;
|
||||
} else {
|
||||
return { action: 'decline' };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Maximum attempts reached. Declining request.');
|
||||
return { action: 'decline' };
|
||||
});
|
||||
|
||||
transport = new StreamableHTTPClientTransport(new URL(serverUrl), {
|
||||
sessionId: sessionId
|
||||
});
|
||||
|
||||
// Set up notification handlers
|
||||
client.setNotificationHandler(LoggingMessageNotificationSchema, notification => {
|
||||
notificationCount++;
|
||||
console.log(`\nNotification #${notificationCount}: ${notification.params.level} - ${notification.params.data}`);
|
||||
// Re-display the prompt
|
||||
process.stdout.write('> ');
|
||||
});
|
||||
|
||||
client.setNotificationHandler(ResourceListChangedNotificationSchema, async _ => {
|
||||
console.log(`\nResource list changed notification received!`);
|
||||
try {
|
||||
if (!client) {
|
||||
console.log('Client disconnected, cannot fetch resources');
|
||||
return;
|
||||
}
|
||||
const resourcesResult = await client.request(
|
||||
{
|
||||
method: 'resources/list',
|
||||
params: {}
|
||||
},
|
||||
ListResourcesResultSchema
|
||||
);
|
||||
console.log('Available resources count:', resourcesResult.resources.length);
|
||||
} catch {
|
||||
console.log('Failed to list resources after change notification');
|
||||
}
|
||||
// Re-display the prompt
|
||||
process.stdout.write('> ');
|
||||
});
|
||||
|
||||
// Connect the client
|
||||
await client.connect(transport);
|
||||
sessionId = transport.sessionId;
|
||||
console.log('Transport created with session ID:', sessionId);
|
||||
console.log('Connected to MCP server');
|
||||
} catch (error) {
|
||||
console.error('Failed to connect:', error);
|
||||
client = null;
|
||||
transport = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function disconnect(): Promise<void> {
|
||||
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(): Promise<void> {
|
||||
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(): Promise<void> {
|
||||
if (client) {
|
||||
await disconnect();
|
||||
}
|
||||
await connect();
|
||||
}
|
||||
|
||||
async function listTools(): Promise<void> {
|
||||
if (!client) {
|
||||
console.log('Not connected to server.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const toolsRequest: ListToolsRequest = {
|
||||
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: string, args: Record<string, unknown>): Promise<void> {
|
||||
if (!client) {
|
||||
console.log('Not connected to server.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const request: CallToolRequest = {
|
||||
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: ResourceLink[] = [];
|
||||
|
||||
result.content.forEach(item => {
|
||||
if (item.type === 'text') {
|
||||
console.log(` ${item.text}`);
|
||||
} else if (item.type === 'resource_link') {
|
||||
const resourceLink = item as ResourceLink;
|
||||
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) {
|
||||
console.log(`Error calling tool ${name}: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function callGreetTool(name: string): Promise<void> {
|
||||
await callTool('greet', { name });
|
||||
}
|
||||
|
||||
async function callMultiGreetTool(name: string): Promise<void> {
|
||||
console.log('Calling multi-greet tool with notifications...');
|
||||
await callTool('multi-greet', { name });
|
||||
}
|
||||
|
||||
async function callCollectInfoTool(infoType: string): Promise<void> {
|
||||
console.log(`Testing form elicitation with collect-user-info tool (${infoType})...`);
|
||||
await callTool('collect-user-info', { infoType });
|
||||
}
|
||||
|
||||
async function startNotifications(interval: number, count: number): Promise<void> {
|
||||
console.log(`Starting notification stream: interval=${interval}ms, count=${count || 'unlimited'}`);
|
||||
await callTool('start-notification-stream', { interval, count });
|
||||
}
|
||||
|
||||
async function runNotificationsToolWithResumability(interval: number, count: number): Promise<void> {
|
||||
if (!client) {
|
||||
console.log('Not connected to server.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`Starting notification stream with resumability: interval=${interval}ms, count=${count || 'unlimited'}`);
|
||||
console.log(`Using resumption token: ${notificationsToolLastEventId || 'none'}`);
|
||||
|
||||
const request: CallToolRequest = {
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'start-notification-stream',
|
||||
arguments: { interval, count }
|
||||
}
|
||||
};
|
||||
|
||||
const onLastEventIdUpdate = (event: string) => {
|
||||
notificationsToolLastEventId = event;
|
||||
console.log(`Updated resumption token: ${event}`);
|
||||
};
|
||||
|
||||
const result = await client.request(request, CallToolResultSchema, {
|
||||
resumptionToken: notificationsToolLastEventId,
|
||||
onresumptiontoken: onLastEventIdUpdate
|
||||
});
|
||||
|
||||
console.log('Tool result:');
|
||||
result.content.forEach(item => {
|
||||
if (item.type === 'text') {
|
||||
console.log(` ${item.text}`);
|
||||
} else {
|
||||
console.log(` ${item.type} content:`, item);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(`Error starting notification stream: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function listPrompts(): Promise<void> {
|
||||
if (!client) {
|
||||
console.log('Not connected to server.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const promptsRequest: ListPromptsRequest = {
|
||||
method: 'prompts/list',
|
||||
params: {}
|
||||
};
|
||||
const promptsResult = await client.request(promptsRequest, ListPromptsResultSchema);
|
||||
console.log('Available prompts:');
|
||||
if (promptsResult.prompts.length === 0) {
|
||||
console.log(' No prompts available');
|
||||
} else {
|
||||
for (const prompt of promptsResult.prompts) {
|
||||
console.log(` - id: ${prompt.name}, name: ${getDisplayName(prompt)}, description: ${prompt.description}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`Prompts not supported by this server (${error})`);
|
||||
}
|
||||
}
|
||||
|
||||
async function getPrompt(name: string, args: Record<string, unknown>): Promise<void> {
|
||||
if (!client) {
|
||||
console.log('Not connected to server.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const promptRequest: GetPromptRequest = {
|
||||
method: 'prompts/get',
|
||||
params: {
|
||||
name,
|
||||
arguments: args as Record<string, string>
|
||||
}
|
||||
};
|
||||
|
||||
const promptResult = await client.request(promptRequest, GetPromptResultSchema);
|
||||
console.log('Prompt template:');
|
||||
promptResult.messages.forEach((msg, index) => {
|
||||
console.log(` [${index + 1}] ${msg.role}: ${msg.content.type === 'text' ? msg.content.text : JSON.stringify(msg.content)}`);
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(`Error getting prompt ${name}: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function listResources(): Promise<void> {
|
||||
if (!client) {
|
||||
console.log('Not connected to server.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const resourcesRequest: ListResourcesRequest = {
|
||||
method: 'resources/list',
|
||||
params: {}
|
||||
};
|
||||
const resourcesResult = await client.request(resourcesRequest, ListResourcesResultSchema);
|
||||
|
||||
console.log('Available resources:');
|
||||
if (resourcesResult.resources.length === 0) {
|
||||
console.log(' No resources available');
|
||||
} else {
|
||||
for (const resource of resourcesResult.resources) {
|
||||
console.log(` - id: ${resource.name}, name: ${getDisplayName(resource)}, description: ${resource.uri}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`Resources not supported by this server (${error})`);
|
||||
}
|
||||
}
|
||||
|
||||
async function readResource(uri: string): Promise<void> {
|
||||
if (!client) {
|
||||
console.log('Not connected to server.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const request: ReadResourceRequest = {
|
||||
method: 'resources/read',
|
||||
params: { uri }
|
||||
};
|
||||
|
||||
console.log(`Reading resource: ${uri}`);
|
||||
const result = await client.request(request, ReadResourceResultSchema);
|
||||
|
||||
console.log('Resource contents:');
|
||||
for (const content of result.contents) {
|
||||
console.log(` URI: ${content.uri}`);
|
||||
if (content.mimeType) {
|
||||
console.log(` Type: ${content.mimeType}`);
|
||||
}
|
||||
|
||||
if ('text' in content && typeof content.text === 'string') {
|
||||
console.log(' Content:');
|
||||
console.log(' ---');
|
||||
console.log(
|
||||
content.text
|
||||
.split('\n')
|
||||
.map((line: string) => ' ' + line)
|
||||
.join('\n')
|
||||
);
|
||||
console.log(' ---');
|
||||
} else if ('blob' in content && typeof content.blob === 'string') {
|
||||
console.log(` [Binary data: ${content.blob.length} bytes]`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`Error reading resource ${uri}: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function callToolTask(name: string, args: Record<string, unknown>): Promise<void> {
|
||||
if (!client) {
|
||||
console.log('Not connected to server.');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Calling tool '${name}' with task-based execution...`);
|
||||
console.log('Arguments:', args);
|
||||
|
||||
// Use task-based execution - call now, fetch later
|
||||
// Using the experimental tasks API - WARNING: may change without notice
|
||||
console.log('This will return immediately while processing continues in the background...');
|
||||
|
||||
try {
|
||||
// Call the tool with task metadata using streaming API
|
||||
const stream = client.experimental.tasks.callToolStream(
|
||||
{
|
||||
name,
|
||||
arguments: args
|
||||
},
|
||||
CallToolResultSchema,
|
||||
{
|
||||
task: {
|
||||
ttl: 60000 // Keep results for 60 seconds
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
console.log('Waiting for task completion...');
|
||||
|
||||
let lastStatus = '';
|
||||
for await (const message of stream) {
|
||||
switch (message.type) {
|
||||
case 'taskCreated':
|
||||
console.log('Task created successfully with ID:', message.task.taskId);
|
||||
break;
|
||||
case 'taskStatus':
|
||||
if (lastStatus !== message.task.status) {
|
||||
console.log(` ${message.task.status}${message.task.statusMessage ? ` - ${message.task.statusMessage}` : ''}`);
|
||||
}
|
||||
lastStatus = message.task.status;
|
||||
break;
|
||||
case 'result':
|
||||
console.log('Task completed!');
|
||||
console.log('Tool result:');
|
||||
message.result.content.forEach(item => {
|
||||
if (item.type === 'text') {
|
||||
console.log(` ${item.text}`);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case 'error':
|
||||
throw message.error;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`Error with task-based execution: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function cleanup(): Promise<void> {
|
||||
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);
|
||||
}
|
||||
|
||||
// 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: unknown) => {
|
||||
console.error('Error running MCP client:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
203
examples/client/src/simpleTaskInteractiveClient.ts
Normal file
203
examples/client/src/simpleTaskInteractiveClient.ts
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
/**
|
||||
* Simple interactive task client demonstrating elicitation and sampling responses.
|
||||
*
|
||||
* This client connects to simpleTaskInteractive.ts server and demonstrates:
|
||||
* - Handling elicitation requests (y/n confirmation)
|
||||
* - Handling sampling requests (returns a hardcoded haiku)
|
||||
* - Using task-based tool execution with streaming
|
||||
*/
|
||||
|
||||
import { createInterface } from 'node:readline';
|
||||
|
||||
import type { CreateMessageRequest, CreateMessageResult, TextContent } from '@modelcontextprotocol/client';
|
||||
import {
|
||||
CallToolResultSchema,
|
||||
Client,
|
||||
CreateMessageRequestSchema,
|
||||
ElicitRequestSchema,
|
||||
ErrorCode,
|
||||
McpError,
|
||||
StreamableHTTPClientTransport
|
||||
} from '@modelcontextprotocol/client';
|
||||
|
||||
// Create readline interface for user input
|
||||
const readline = createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
});
|
||||
|
||||
function question(prompt: string): Promise<string> {
|
||||
return new Promise(resolve => {
|
||||
readline.question(prompt, answer => {
|
||||
resolve(answer.trim());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function getTextContent(result: { content: Array<{ type: string; text?: string }> }): string {
|
||||
const textContent = result.content.find((c): c is TextContent => c.type === 'text');
|
||||
return textContent?.text ?? '(no text)';
|
||||
}
|
||||
|
||||
async function elicitationCallback(params: {
|
||||
mode?: string;
|
||||
message: string;
|
||||
requestedSchema?: object;
|
||||
}): Promise<{ action: string; content?: Record<string, unknown> }> {
|
||||
console.log(`\n[Elicitation] Server asks: ${params.message}`);
|
||||
|
||||
// Simple terminal prompt for y/n
|
||||
const response = await question('Your response (y/n): ');
|
||||
const confirmed = ['y', 'yes', 'true', '1'].includes(response.toLowerCase());
|
||||
|
||||
console.log(`[Elicitation] Responding with: confirm=${confirmed}`);
|
||||
return { action: 'accept', content: { confirm: confirmed } };
|
||||
}
|
||||
|
||||
async function samplingCallback(params: CreateMessageRequest['params']): Promise<CreateMessageResult> {
|
||||
// Get the prompt from the first message
|
||||
let prompt = 'unknown';
|
||||
if (params.messages && params.messages.length > 0) {
|
||||
const firstMessage = params.messages[0]!;
|
||||
const content = firstMessage.content;
|
||||
if (typeof content === 'object' && !Array.isArray(content) && content.type === 'text' && 'text' in content) {
|
||||
prompt = content.text;
|
||||
} else if (Array.isArray(content)) {
|
||||
const textPart = content.find(c => c.type === 'text' && 'text' in c);
|
||||
if (textPart && 'text' in textPart) {
|
||||
prompt = textPart.text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n[Sampling] Server requests LLM completion for: ${prompt}`);
|
||||
|
||||
// Return a hardcoded haiku (in real use, call your LLM here)
|
||||
const haiku = `Cherry blossoms fall
|
||||
Softly on the quiet pond
|
||||
Spring whispers goodbye`;
|
||||
|
||||
console.log('[Sampling] Responding with haiku');
|
||||
return {
|
||||
model: 'mock-haiku-model',
|
||||
role: 'assistant',
|
||||
content: { type: 'text', text: haiku }
|
||||
};
|
||||
}
|
||||
|
||||
async function run(url: string): Promise<void> {
|
||||
console.log('Simple Task Interactive Client');
|
||||
console.log('==============================');
|
||||
console.log(`Connecting to ${url}...`);
|
||||
|
||||
// Create client with elicitation and sampling capabilities
|
||||
const client = new Client(
|
||||
{ name: 'simple-task-interactive-client', version: '1.0.0' },
|
||||
{
|
||||
capabilities: {
|
||||
elicitation: { form: {} },
|
||||
sampling: {}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Set up elicitation request handler
|
||||
client.setRequestHandler(ElicitRequestSchema, async request => {
|
||||
if (request.params.mode && request.params.mode !== 'form') {
|
||||
throw new McpError(ErrorCode.InvalidParams, `Unsupported elicitation mode: ${request.params.mode}`);
|
||||
}
|
||||
return elicitationCallback(request.params);
|
||||
});
|
||||
|
||||
// Set up sampling request handler
|
||||
client.setRequestHandler(CreateMessageRequestSchema, async request => {
|
||||
return samplingCallback(request.params) as unknown as ReturnType<typeof samplingCallback>;
|
||||
});
|
||||
|
||||
// Connect to server
|
||||
const transport = new StreamableHTTPClientTransport(new URL(url));
|
||||
await client.connect(transport);
|
||||
console.log('Connected!\n');
|
||||
|
||||
// List tools
|
||||
const toolsResult = await client.listTools();
|
||||
console.log(`Available tools: ${toolsResult.tools.map(t => t.name).join(', ')}`);
|
||||
|
||||
// Demo 1: Elicitation (confirm_delete)
|
||||
console.log('\n--- Demo 1: Elicitation ---');
|
||||
console.log('Calling confirm_delete tool...');
|
||||
|
||||
const confirmStream = client.experimental.tasks.callToolStream(
|
||||
{ name: 'confirm_delete', arguments: { filename: 'important.txt' } },
|
||||
CallToolResultSchema,
|
||||
{ task: { ttl: 60000 } }
|
||||
);
|
||||
|
||||
for await (const message of confirmStream) {
|
||||
switch (message.type) {
|
||||
case 'taskCreated':
|
||||
console.log(`Task created: ${message.task.taskId}`);
|
||||
break;
|
||||
case 'taskStatus':
|
||||
console.log(`Task status: ${message.task.status}`);
|
||||
break;
|
||||
case 'result':
|
||||
console.log(`Result: ${getTextContent(message.result)}`);
|
||||
break;
|
||||
case 'error':
|
||||
console.error(`Error: ${message.error}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Demo 2: Sampling (write_haiku)
|
||||
console.log('\n--- Demo 2: Sampling ---');
|
||||
console.log('Calling write_haiku tool...');
|
||||
|
||||
const haikuStream = client.experimental.tasks.callToolStream(
|
||||
{ name: 'write_haiku', arguments: { topic: 'autumn leaves' } },
|
||||
CallToolResultSchema,
|
||||
{
|
||||
task: { ttl: 60000 }
|
||||
}
|
||||
);
|
||||
|
||||
for await (const message of haikuStream) {
|
||||
switch (message.type) {
|
||||
case 'taskCreated':
|
||||
console.log(`Task created: ${message.task.taskId}`);
|
||||
break;
|
||||
case 'taskStatus':
|
||||
console.log(`Task status: ${message.task.status}`);
|
||||
break;
|
||||
case 'result':
|
||||
console.log(`Result:\n${getTextContent(message.result)}`);
|
||||
break;
|
||||
case 'error':
|
||||
console.error(`Error: ${message.error}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
console.log('\nDemo complete. Closing connection...');
|
||||
await transport.close();
|
||||
readline.close();
|
||||
}
|
||||
|
||||
// Parse command line arguments
|
||||
const args = process.argv.slice(2);
|
||||
let url = 'http://localhost:8000/mcp';
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === '--url' && args[i + 1]) {
|
||||
url = args[i + 1]!;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
// Run the client
|
||||
run(url).catch(error => {
|
||||
console.error('Error running client:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
109
examples/client/src/ssePollingClient.ts
Normal file
109
examples/client/src/ssePollingClient.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
/**
|
||||
* SSE Polling Example Client (SEP-1699)
|
||||
*
|
||||
* This example demonstrates client-side behavior during server-initiated
|
||||
* SSE stream disconnection and automatic reconnection.
|
||||
*
|
||||
* Key features demonstrated:
|
||||
* - Automatic reconnection when server closes SSE stream
|
||||
* - Event replay via Last-Event-ID header
|
||||
* - Resumption token tracking via onresumptiontoken callback
|
||||
*
|
||||
* Run with: pnpm tsx src/ssePollingClient.ts
|
||||
* Requires: ssePollingExample.ts server running on port 3001
|
||||
*/
|
||||
import {
|
||||
CallToolResultSchema,
|
||||
Client,
|
||||
LoggingMessageNotificationSchema,
|
||||
StreamableHTTPClientTransport
|
||||
} from '@modelcontextprotocol/client';
|
||||
|
||||
const SERVER_URL = 'http://localhost:3001/mcp';
|
||||
|
||||
async function main(): Promise<void> {
|
||||
console.log('SSE Polling Example Client');
|
||||
console.log('==========================');
|
||||
console.log(`Connecting to ${SERVER_URL}...`);
|
||||
console.log('');
|
||||
|
||||
// Create transport with reconnection options
|
||||
const transport = new StreamableHTTPClientTransport(new URL(SERVER_URL), {
|
||||
// Use default reconnection options - SDK handles automatic reconnection
|
||||
});
|
||||
|
||||
// Track the last event ID for debugging
|
||||
let lastEventId: string | undefined;
|
||||
|
||||
// Set up transport error handler to observe disconnections
|
||||
// Filter out expected errors from SSE reconnection
|
||||
transport.onerror = error => {
|
||||
// Skip abort errors during intentional close
|
||||
if (error.message.includes('AbortError')) return;
|
||||
// Show SSE disconnect (expected when server closes stream)
|
||||
if (error.message.includes('Unexpected end of JSON')) {
|
||||
console.log('[Transport] SSE stream disconnected - client will auto-reconnect');
|
||||
return;
|
||||
}
|
||||
console.log(`[Transport] Error: ${error.message}`);
|
||||
};
|
||||
|
||||
// Set up transport close handler
|
||||
transport.onclose = () => {
|
||||
console.log('[Transport] Connection closed');
|
||||
};
|
||||
|
||||
// Create and connect client
|
||||
const client = new Client({
|
||||
name: 'sse-polling-client',
|
||||
version: '1.0.0'
|
||||
});
|
||||
|
||||
// Set up notification handler to receive progress updates
|
||||
client.setNotificationHandler(LoggingMessageNotificationSchema, notification => {
|
||||
const data = notification.params.data;
|
||||
console.log(`[Notification] ${data}`);
|
||||
});
|
||||
|
||||
try {
|
||||
await client.connect(transport);
|
||||
console.log('[Client] Connected successfully');
|
||||
console.log('');
|
||||
|
||||
// Call the long-task tool
|
||||
console.log('[Client] Calling long-task tool...');
|
||||
console.log('[Client] Server will disconnect mid-task to demonstrate polling');
|
||||
console.log('');
|
||||
|
||||
const result = await client.request(
|
||||
{
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'long-task',
|
||||
arguments: {}
|
||||
}
|
||||
},
|
||||
CallToolResultSchema,
|
||||
{
|
||||
// Track resumption tokens for debugging
|
||||
onresumptiontoken: token => {
|
||||
lastEventId = token;
|
||||
console.log(`[Event ID] ${token}`);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
console.log('');
|
||||
console.log('[Client] Tool completed!');
|
||||
console.log(`[Result] ${JSON.stringify(result.content, null, 2)}`);
|
||||
console.log('');
|
||||
console.log(`[Debug] Final event ID: ${lastEventId}`);
|
||||
} catch (error) {
|
||||
console.error('[Error]', error);
|
||||
} finally {
|
||||
await transport.close();
|
||||
console.log('[Client] Disconnected');
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
190
examples/client/src/streamableHttpWithSseFallbackClient.ts
Normal file
190
examples/client/src/streamableHttpWithSseFallbackClient.ts
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
import type { CallToolRequest, ListToolsRequest } from '@modelcontextprotocol/client';
|
||||
import {
|
||||
CallToolResultSchema,
|
||||
Client,
|
||||
ListToolsResultSchema,
|
||||
LoggingMessageNotificationSchema,
|
||||
SSEClientTransport,
|
||||
StreamableHTTPClientTransport
|
||||
} from '@modelcontextprotocol/client';
|
||||
|
||||
/**
|
||||
* Simplified Backwards Compatible MCP Client
|
||||
*
|
||||
* This client demonstrates backward compatibility with both:
|
||||
* 1. Modern servers using Streamable HTTP transport (protocol version 2025-03-26)
|
||||
* 2. Older servers using HTTP+SSE transport (protocol version 2024-11-05)
|
||||
*
|
||||
* Following the MCP specification for backwards compatibility:
|
||||
* - Attempts to POST an initialize request to the server URL first (modern transport)
|
||||
* - If that fails with 4xx status, falls back to GET request for SSE stream (older transport)
|
||||
*/
|
||||
|
||||
// Command line args processing
|
||||
const args = process.argv.slice(2);
|
||||
const serverUrl = args[0] || 'http://localhost:3000/mcp';
|
||||
|
||||
async function main(): Promise<void> {
|
||||
console.log('MCP Backwards Compatible Client');
|
||||
console.log('===============================');
|
||||
console.log(`Connecting to server at: ${serverUrl}`);
|
||||
|
||||
let client: Client;
|
||||
let transport: StreamableHTTPClientTransport | SSEClientTransport;
|
||||
|
||||
try {
|
||||
// Try connecting with automatic transport detection
|
||||
const connection = await connectWithBackwardsCompatibility(serverUrl);
|
||||
client = connection.client;
|
||||
transport = connection.transport;
|
||||
|
||||
// Set up notification handler
|
||||
client.setNotificationHandler(LoggingMessageNotificationSchema, notification => {
|
||||
console.log(`Notification: ${notification.params.level} - ${notification.params.data}`);
|
||||
});
|
||||
|
||||
// DEMO WORKFLOW:
|
||||
// 1. List available tools
|
||||
console.log('\n=== Listing Available Tools ===');
|
||||
await listTools(client);
|
||||
|
||||
// 2. Call the notification tool
|
||||
console.log('\n=== Starting Notification Stream ===');
|
||||
await startNotificationTool(client);
|
||||
|
||||
// 3. Wait for all notifications (5 seconds)
|
||||
console.log('\n=== Waiting for all notifications ===');
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
|
||||
// 4. Disconnect
|
||||
console.log('\n=== Disconnecting ===');
|
||||
await transport.close();
|
||||
console.log('Disconnected from MCP server');
|
||||
} catch (error) {
|
||||
console.error('Error running client:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to an MCP server with backwards compatibility
|
||||
* Following the spec for client backward compatibility
|
||||
*/
|
||||
async function connectWithBackwardsCompatibility(url: string): Promise<{
|
||||
client: Client;
|
||||
transport: StreamableHTTPClientTransport | SSEClientTransport;
|
||||
transportType: 'streamable-http' | 'sse';
|
||||
}> {
|
||||
console.log('1. Trying Streamable HTTP transport first...');
|
||||
|
||||
// Step 1: Try Streamable HTTP transport first
|
||||
const client = new Client({
|
||||
name: 'backwards-compatible-client',
|
||||
version: '1.0.0'
|
||||
});
|
||||
|
||||
client.onerror = error => {
|
||||
console.error('Client error:', error);
|
||||
};
|
||||
const baseUrl = new URL(url);
|
||||
|
||||
try {
|
||||
// Create modern transport
|
||||
const streamableTransport = new StreamableHTTPClientTransport(baseUrl);
|
||||
await client.connect(streamableTransport);
|
||||
|
||||
console.log('Successfully connected using modern Streamable HTTP transport.');
|
||||
return {
|
||||
client,
|
||||
transport: streamableTransport,
|
||||
transportType: 'streamable-http'
|
||||
};
|
||||
} catch (error) {
|
||||
// Step 2: If transport fails, try the older SSE transport
|
||||
console.log(`StreamableHttp transport connection failed: ${error}`);
|
||||
console.log('2. Falling back to deprecated HTTP+SSE transport...');
|
||||
|
||||
try {
|
||||
// Create SSE transport pointing to /sse endpoint
|
||||
const sseTransport = new SSEClientTransport(baseUrl);
|
||||
const sseClient = new Client({
|
||||
name: 'backwards-compatible-client',
|
||||
version: '1.0.0'
|
||||
});
|
||||
await sseClient.connect(sseTransport);
|
||||
|
||||
console.log('Successfully connected using deprecated HTTP+SSE transport.');
|
||||
return {
|
||||
client: sseClient,
|
||||
transport: sseTransport,
|
||||
transportType: 'sse'
|
||||
};
|
||||
} catch (sseError) {
|
||||
console.error(`Failed to connect with either transport method:\n1. Streamable HTTP error: ${error}\n2. SSE error: ${sseError}`);
|
||||
throw new Error('Could not connect to server with any available transport');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List available tools on the server
|
||||
*/
|
||||
async function listTools(client: Client): Promise<void> {
|
||||
try {
|
||||
const toolsRequest: ListToolsRequest = {
|
||||
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(` - ${tool.name}: ${tool.description}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`Tools not supported by this server: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a notification stream by calling the notification tool
|
||||
*/
|
||||
async function startNotificationTool(client: Client): Promise<void> {
|
||||
try {
|
||||
// Call the notification tool using reasonable defaults
|
||||
const request: CallToolRequest = {
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'start-notification-stream',
|
||||
arguments: {
|
||||
interval: 1000, // 1 second between notifications
|
||||
count: 5 // Send 5 notifications
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
console.log('Calling notification tool...');
|
||||
const result = await client.request(request, CallToolResultSchema);
|
||||
|
||||
console.log('Tool result:');
|
||||
result.content.forEach(item => {
|
||||
if (item.type === 'text') {
|
||||
console.log(` ${item.text}`);
|
||||
} else {
|
||||
console.log(` ${item.type} content:`, item);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(`Error calling notification tool: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Start the client
|
||||
main().catch((error: unknown) => {
|
||||
console.error('Error running MCP client:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
17
examples/client/tsconfig.json
Normal file
17
examples/client/tsconfig.json
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"extends": "@modelcontextprotocol/tsconfig",
|
||||
"include": ["./"],
|
||||
"exclude": ["node_modules", "dist"],
|
||||
"compilerOptions": {
|
||||
"paths": {
|
||||
"*": ["./*"],
|
||||
"@modelcontextprotocol/client": ["./node_modules/@modelcontextprotocol/client/src/index.ts"],
|
||||
"@modelcontextprotocol/core": [
|
||||
"./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/src/index.ts"
|
||||
],
|
||||
"@modelcontextprotocol/eslint-config": ["./node_modules/@modelcontextprotocol/eslint-config/tsconfig.json"],
|
||||
"@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"],
|
||||
"@modelcontextprotocol/examples-shared": ["./node_modules/@modelcontextprotocol/examples-shared/src/index.ts"]
|
||||
}
|
||||
}
|
||||
}
|
||||
25
examples/client/tsdown.config.ts
Normal file
25
examples/client/tsdown.config.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { defineConfig } from 'tsdown';
|
||||
|
||||
export default defineConfig({
|
||||
// 1. Entry Points
|
||||
// Directly matches package.json include/exclude globs
|
||||
entry: ['src/**/*.ts'],
|
||||
|
||||
// 2. Output Configuration
|
||||
format: ['esm'],
|
||||
outDir: 'dist',
|
||||
clean: true, // Recommended: Cleans 'dist' before building
|
||||
sourcemap: true,
|
||||
|
||||
// 3. Platform & Target
|
||||
target: 'esnext',
|
||||
platform: 'node',
|
||||
shims: true, // Polyfills common Node.js shims (__dirname, etc.)
|
||||
|
||||
// 4. Type Definitions
|
||||
// Bundles d.ts files into a single output
|
||||
dts: false,
|
||||
// 5. Vendoring Strategy - Bundle the code for this specific package into the output,
|
||||
// but treat all other dependencies as external (require/import).
|
||||
noExternal: ['@modelcontextprotocol/examples-shared']
|
||||
});
|
||||
3
examples/client/vitest.config.js
Normal file
3
examples/client/vitest.config.js
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import baseConfig from '@modelcontextprotocol/vitest-config';
|
||||
|
||||
export default baseConfig;
|
||||
Loading…
Reference in a new issue