|
| 1 | +/** |
| 2 | + * Simple interactive task client demonstrating elicitation and sampling responses. |
| 3 | + * |
| 4 | + * This client connects to simpleTaskInteractive.ts server and demonstrates: |
| 5 | + * - Handling elicitation requests (y/n confirmation) |
| 6 | + * - Handling sampling requests (returns a hardcoded haiku) |
| 7 | + * - Using task-based tool execution with streaming |
| 8 | + */ |
| 9 | + |
| 10 | +import { Client } from '../../client/index.js'; |
| 11 | +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; |
| 12 | +import { createInterface } from 'node:readline'; |
| 13 | +import { |
| 14 | + CallToolResultSchema, |
| 15 | + TextContent, |
| 16 | + ElicitRequestSchema, |
| 17 | + CreateMessageRequestSchema, |
| 18 | + CreateMessageRequest, |
| 19 | + CreateMessageResult, |
| 20 | + ErrorCode, |
| 21 | + McpError |
| 22 | +} from '../../types.js'; |
| 23 | + |
| 24 | +// Create readline interface for user input |
| 25 | +const readline = createInterface({ |
| 26 | + input: process.stdin, |
| 27 | + output: process.stdout |
| 28 | +}); |
| 29 | + |
| 30 | +function question(prompt: string): Promise<string> { |
| 31 | + return new Promise(resolve => { |
| 32 | + readline.question(prompt, answer => { |
| 33 | + resolve(answer.trim()); |
| 34 | + }); |
| 35 | + }); |
| 36 | +} |
| 37 | + |
| 38 | +function getTextContent(result: { content: Array<{ type: string; text?: string }> }): string { |
| 39 | + const textContent = result.content.find((c): c is TextContent => c.type === 'text'); |
| 40 | + return textContent?.text ?? '(no text)'; |
| 41 | +} |
| 42 | + |
| 43 | +async function elicitationCallback(params: { |
| 44 | + mode?: string; |
| 45 | + message: string; |
| 46 | + requestedSchema?: object; |
| 47 | +}): Promise<{ action: string; content?: Record<string, unknown> }> { |
| 48 | + console.log(`\n[Elicitation] Server asks: ${params.message}`); |
| 49 | + |
| 50 | + // Simple terminal prompt for y/n |
| 51 | + const response = await question('Your response (y/n): '); |
| 52 | + const confirmed = ['y', 'yes', 'true', '1'].includes(response.toLowerCase()); |
| 53 | + |
| 54 | + console.log(`[Elicitation] Responding with: confirm=${confirmed}`); |
| 55 | + return { action: 'accept', content: { confirm: confirmed } }; |
| 56 | +} |
| 57 | + |
| 58 | +async function samplingCallback(params: CreateMessageRequest['params']): Promise<CreateMessageResult> { |
| 59 | + // Get the prompt from the first message |
| 60 | + let prompt = 'unknown'; |
| 61 | + if (params.messages && params.messages.length > 0) { |
| 62 | + const firstMessage = params.messages[0]; |
| 63 | + const content = firstMessage.content; |
| 64 | + if (typeof content === 'object' && !Array.isArray(content) && content.type === 'text' && 'text' in content) { |
| 65 | + prompt = content.text; |
| 66 | + } else if (Array.isArray(content)) { |
| 67 | + const textPart = content.find(c => c.type === 'text' && 'text' in c); |
| 68 | + if (textPart && 'text' in textPart) { |
| 69 | + prompt = textPart.text; |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + console.log(`\n[Sampling] Server requests LLM completion for: ${prompt}`); |
| 75 | + |
| 76 | + // Return a hardcoded haiku (in real use, call your LLM here) |
| 77 | + const haiku = `Cherry blossoms fall |
| 78 | +Softly on the quiet pond |
| 79 | +Spring whispers goodbye`; |
| 80 | + |
| 81 | + console.log('[Sampling] Responding with haiku'); |
| 82 | + return { |
| 83 | + model: 'mock-haiku-model', |
| 84 | + role: 'assistant', |
| 85 | + content: { type: 'text', text: haiku } |
| 86 | + }; |
| 87 | +} |
| 88 | + |
| 89 | +async function run(url: string): Promise<void> { |
| 90 | + console.log('Simple Task Interactive Client'); |
| 91 | + console.log('=============================='); |
| 92 | + console.log(`Connecting to ${url}...`); |
| 93 | + |
| 94 | + // Create client with elicitation and sampling capabilities |
| 95 | + const client = new Client( |
| 96 | + { name: 'simple-task-interactive-client', version: '1.0.0' }, |
| 97 | + { |
| 98 | + capabilities: { |
| 99 | + elicitation: { form: {} }, |
| 100 | + sampling: {} |
| 101 | + } |
| 102 | + } |
| 103 | + ); |
| 104 | + |
| 105 | + // Set up elicitation request handler |
| 106 | + client.setRequestHandler(ElicitRequestSchema, async request => { |
| 107 | + if (request.params.mode && request.params.mode !== 'form') { |
| 108 | + throw new McpError(ErrorCode.InvalidParams, `Unsupported elicitation mode: ${request.params.mode}`); |
| 109 | + } |
| 110 | + return elicitationCallback(request.params); |
| 111 | + }); |
| 112 | + |
| 113 | + // Set up sampling request handler |
| 114 | + client.setRequestHandler(CreateMessageRequestSchema, async request => { |
| 115 | + return samplingCallback(request.params) as unknown as ReturnType<typeof samplingCallback>; |
| 116 | + }); |
| 117 | + |
| 118 | + // Connect to server |
| 119 | + const transport = new StreamableHTTPClientTransport(new URL(url)); |
| 120 | + await client.connect(transport); |
| 121 | + console.log('Connected!\n'); |
| 122 | + |
| 123 | + // List tools |
| 124 | + const toolsResult = await client.listTools(); |
| 125 | + console.log(`Available tools: ${toolsResult.tools.map(t => t.name).join(', ')}`); |
| 126 | + |
| 127 | + // Demo 1: Elicitation (confirm_delete) |
| 128 | + console.log('\n--- Demo 1: Elicitation ---'); |
| 129 | + console.log('Calling confirm_delete tool...'); |
| 130 | + |
| 131 | + const confirmStream = client.experimental.tasks.callToolStream( |
| 132 | + { name: 'confirm_delete', arguments: { filename: 'important.txt' } }, |
| 133 | + CallToolResultSchema, |
| 134 | + { task: { ttl: 60000 } } |
| 135 | + ); |
| 136 | + |
| 137 | + for await (const message of confirmStream) { |
| 138 | + switch (message.type) { |
| 139 | + case 'taskCreated': |
| 140 | + console.log(`Task created: ${message.task.taskId}`); |
| 141 | + break; |
| 142 | + case 'taskStatus': |
| 143 | + console.log(`Task status: ${message.task.status}`); |
| 144 | + break; |
| 145 | + case 'result': |
| 146 | + console.log(`Result: ${getTextContent(message.result)}`); |
| 147 | + break; |
| 148 | + case 'error': |
| 149 | + console.error(`Error: ${message.error}`); |
| 150 | + break; |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + // Demo 2: Sampling (write_haiku) |
| 155 | + console.log('\n--- Demo 2: Sampling ---'); |
| 156 | + console.log('Calling write_haiku tool...'); |
| 157 | + |
| 158 | + const haikuStream = client.experimental.tasks.callToolStream( |
| 159 | + { name: 'write_haiku', arguments: { topic: 'autumn leaves' } }, |
| 160 | + CallToolResultSchema, |
| 161 | + { |
| 162 | + task: { ttl: 60000 } |
| 163 | + } |
| 164 | + ); |
| 165 | + |
| 166 | + for await (const message of haikuStream) { |
| 167 | + switch (message.type) { |
| 168 | + case 'taskCreated': |
| 169 | + console.log(`Task created: ${message.task.taskId}`); |
| 170 | + break; |
| 171 | + case 'taskStatus': |
| 172 | + console.log(`Task status: ${message.task.status}`); |
| 173 | + break; |
| 174 | + case 'result': |
| 175 | + console.log(`Result:\n${getTextContent(message.result)}`); |
| 176 | + break; |
| 177 | + case 'error': |
| 178 | + console.error(`Error: ${message.error}`); |
| 179 | + break; |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + // Cleanup |
| 184 | + console.log('\nDemo complete. Closing connection...'); |
| 185 | + await transport.close(); |
| 186 | + readline.close(); |
| 187 | +} |
| 188 | + |
| 189 | +// Parse command line arguments |
| 190 | +const args = process.argv.slice(2); |
| 191 | +let url = 'http://localhost:8000/mcp'; |
| 192 | + |
| 193 | +for (let i = 0; i < args.length; i++) { |
| 194 | + if (args[i] === '--url' && args[i + 1]) { |
| 195 | + url = args[i + 1]; |
| 196 | + i++; |
| 197 | + } |
| 198 | +} |
| 199 | + |
| 200 | +// Run the client |
| 201 | +run(url).catch(error => { |
| 202 | + console.error('Error running client:', error); |
| 203 | + process.exit(1); |
| 204 | +}); |
0 commit comments