@lushly-dev/afd-client 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js ADDED
@@ -0,0 +1,677 @@
1
+ /**
2
+ * @fileoverview MCP Client implementation
3
+ */
4
+ import { createMcpErrorResponse, createMcpRequest, failure, isCompleteChunk, isDataChunk, isErrorChunk, isProgressChunk, McpErrorCodes, success, wrapError, } from '@lushly-dev/afd-core';
5
+ import { createTransport } from './transport.js';
6
+ /**
7
+ * MCP Client for connecting to MCP servers.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * const client = new McpClient({ url: 'http://localhost:3100/sse' });
12
+ *
13
+ * await client.connect();
14
+ *
15
+ * // List available tools
16
+ * const tools = await client.listTools();
17
+ *
18
+ * // Call a tool
19
+ * const result = await client.call('document.create', { title: 'Test' });
20
+ *
21
+ * await client.disconnect();
22
+ * ```
23
+ */
24
+ export class McpClient {
25
+ config;
26
+ transport = null;
27
+ state = 'disconnected';
28
+ serverInfo = null;
29
+ capabilities = null;
30
+ tools = [];
31
+ connectedAt = null;
32
+ reconnectAttempts = 0;
33
+ pendingRequests = new Map();
34
+ eventHandlers = {
35
+ stateChange: [],
36
+ connected: [],
37
+ disconnected: [],
38
+ reconnecting: [],
39
+ error: [],
40
+ message: [],
41
+ toolsChanged: [],
42
+ };
43
+ constructor(config) {
44
+ this.config = {
45
+ url: config.url,
46
+ transport: config.transport ?? 'sse',
47
+ clientName: config.clientName ?? '@lushly-dev/afd-client',
48
+ clientVersion: config.clientVersion ?? '0.1.0',
49
+ timeout: config.timeout ?? 30000,
50
+ autoReconnect: config.autoReconnect ?? true,
51
+ maxReconnectAttempts: config.maxReconnectAttempts ?? 5,
52
+ reconnectDelay: config.reconnectDelay ?? 1000,
53
+ headers: config.headers ?? {},
54
+ debug: config.debug ?? false,
55
+ };
56
+ }
57
+ // ═══════════════════════════════════════════════════════════════════════════
58
+ // CONNECTION MANAGEMENT
59
+ // ═══════════════════════════════════════════════════════════════════════════
60
+ /**
61
+ * Connect to the MCP server.
62
+ */
63
+ async connect() {
64
+ if (this.state === 'connected') {
65
+ throw new Error('Already connected');
66
+ }
67
+ this.setState('connecting');
68
+ try {
69
+ // Create transport
70
+ if (this.config.transport === 'stdio') {
71
+ throw new Error('stdio transport not yet implemented');
72
+ }
73
+ if (this.config.transport === 'direct') {
74
+ throw new Error('Direct transport requires a registry. Use DirectClient or DirectTransport instead.');
75
+ }
76
+ this.transport = createTransport(this.config.transport, this.config.url, this.config.headers);
77
+ // Set up transport handlers
78
+ this.transport.onMessage((response) => this.handleMessage(response));
79
+ this.transport.onError((error) => this.handleError(error));
80
+ this.transport.onClose(() => this.handleClose());
81
+ // Connect transport
82
+ await this.transport.connect();
83
+ // Initialize MCP session
84
+ const initResult = await this.initialize();
85
+ this.serverInfo = initResult.serverInfo;
86
+ this.capabilities = initResult.capabilities;
87
+ this.connectedAt = new Date();
88
+ this.reconnectAttempts = 0;
89
+ this.setState('connected');
90
+ this.emit('connected', initResult);
91
+ // Fetch initial tools list
92
+ await this.refreshTools();
93
+ return initResult;
94
+ }
95
+ catch (error) {
96
+ this.setState('error');
97
+ const err = error instanceof Error ? error : new Error(String(error));
98
+ this.emit('error', err);
99
+ throw err;
100
+ }
101
+ }
102
+ /**
103
+ * Disconnect from the MCP server.
104
+ */
105
+ async disconnect() {
106
+ if (this.transport) {
107
+ this.transport.disconnect();
108
+ this.transport = null;
109
+ }
110
+ // Reject all pending requests
111
+ for (const [id, pending] of this.pendingRequests) {
112
+ clearTimeout(pending.timeout);
113
+ pending.reject(new Error('Client disconnected'));
114
+ }
115
+ this.pendingRequests.clear();
116
+ this.setState('disconnected');
117
+ this.emit('disconnected', 'Manual disconnect');
118
+ this.serverInfo = null;
119
+ this.capabilities = null;
120
+ this.connectedAt = null;
121
+ this.tools = [];
122
+ }
123
+ /**
124
+ * Get current client status.
125
+ */
126
+ getStatus() {
127
+ return {
128
+ state: this.state,
129
+ url: this.state !== 'disconnected' ? this.config.url : null,
130
+ serverInfo: this.serverInfo,
131
+ capabilities: this.capabilities,
132
+ connectedAt: this.connectedAt,
133
+ reconnectAttempts: this.reconnectAttempts,
134
+ pendingRequests: this.pendingRequests.size,
135
+ };
136
+ }
137
+ /**
138
+ * Check if connected.
139
+ */
140
+ isConnected() {
141
+ return this.state === 'connected' && this.transport?.isConnected() === true;
142
+ }
143
+ // ═══════════════════════════════════════════════════════════════════════════
144
+ // MCP OPERATIONS
145
+ // ═══════════════════════════════════════════════════════════════════════════
146
+ /**
147
+ * List available tools.
148
+ */
149
+ async listTools() {
150
+ const response = await this.request('tools/list');
151
+ this.tools = response.tools;
152
+ return this.tools;
153
+ }
154
+ /**
155
+ * Get cached tools list.
156
+ */
157
+ getTools() {
158
+ return this.tools;
159
+ }
160
+ /**
161
+ * Refresh tools list from server.
162
+ */
163
+ async refreshTools() {
164
+ const tools = await this.listTools();
165
+ this.emit('toolsChanged', tools);
166
+ return tools;
167
+ }
168
+ /**
169
+ * Call a tool and return raw MCP result.
170
+ *
171
+ * @param name - Tool name
172
+ * @param args - Tool arguments
173
+ */
174
+ async callTool(name, args) {
175
+ const params = {
176
+ name,
177
+ arguments: args,
178
+ };
179
+ return this.request('tools/call', params);
180
+ }
181
+ /**
182
+ * Call a command and return a CommandResult.
183
+ *
184
+ * This is the preferred method for AFD - it wraps the MCP response
185
+ * in a standardized CommandResult.
186
+ *
187
+ * @param name - Command/tool name
188
+ * @param args - Command arguments
189
+ */
190
+ async call(name, args) {
191
+ try {
192
+ const result = await this.callTool(name, args);
193
+ if (result.isError) {
194
+ // Extract error from content
195
+ const errorText = result.content
196
+ .filter((c) => c.type === 'text')
197
+ .map((c) => c.text)
198
+ .join('\n');
199
+ return failure({
200
+ code: 'TOOL_ERROR',
201
+ message: errorText || 'Tool execution failed',
202
+ suggestion: 'Check the tool arguments and try again',
203
+ });
204
+ }
205
+ // Try to parse JSON from text content
206
+ const textContent = result.content
207
+ .filter((c) => c.type === 'text')
208
+ .map((c) => c.text)
209
+ .join('');
210
+ try {
211
+ const data = JSON.parse(textContent);
212
+ // If the data is already a CommandResult, return it directly
213
+ if (typeof data === 'object' && data !== null && 'success' in data) {
214
+ return data;
215
+ }
216
+ // Wrap raw data in a success result
217
+ return success(data);
218
+ }
219
+ catch {
220
+ // Return raw text as data
221
+ return success(textContent);
222
+ }
223
+ }
224
+ catch (error) {
225
+ return failure(wrapError(error));
226
+ }
227
+ }
228
+ /**
229
+ * Execute multiple commands in a single batch request.
230
+ *
231
+ * Batch execution provides partial success semantics - the batch
232
+ * succeeds if at least one command succeeds, with aggregated
233
+ * confidence scores and detailed timing information.
234
+ *
235
+ * @param commands - Array of commands to execute
236
+ * @param options - Batch execution options
237
+ * @returns BatchResult with individual command results
238
+ *
239
+ * @example
240
+ * ```typescript
241
+ * const result = await client.batch([
242
+ * { name: 'todo.create', input: { title: 'First' } },
243
+ * { name: 'todo.create', input: { title: 'Second' } },
244
+ * { name: 'todo.list', input: {} }
245
+ * ], { stopOnError: false });
246
+ *
247
+ * console.log(`${result.summary.successCount}/${result.summary.total} succeeded`);
248
+ * console.log(`Confidence: ${(result.confidence * 100).toFixed(1)}%`);
249
+ * ```
250
+ */
251
+ async batch(commands, options) {
252
+ const startedAt = new Date().toISOString();
253
+ try {
254
+ const result = await this.callTool('afd.batch', {
255
+ commands,
256
+ options,
257
+ });
258
+ if (result.isError) {
259
+ const errorText = result.content
260
+ .filter((c) => c.type === 'text')
261
+ .map((c) => c.text)
262
+ .join('\n');
263
+ // Return failed batch result
264
+ return {
265
+ success: false,
266
+ results: [],
267
+ summary: {
268
+ total: commands.length,
269
+ successCount: 0,
270
+ failureCount: commands.length,
271
+ skippedCount: 0,
272
+ },
273
+ timing: {
274
+ startedAt,
275
+ completedAt: new Date().toISOString(),
276
+ totalMs: 0,
277
+ averageMs: 0,
278
+ },
279
+ confidence: 0,
280
+ reasoning: `Batch execution failed: ${errorText || 'Unknown error'}`,
281
+ error: {
282
+ code: 'BATCH_ERROR',
283
+ message: errorText || 'Batch execution failed',
284
+ suggestion: 'Check the batch commands and try again',
285
+ },
286
+ };
287
+ }
288
+ // Parse batch result from response
289
+ const textContent = result.content
290
+ .filter((c) => c.type === 'text')
291
+ .map((c) => c.text)
292
+ .join('');
293
+ try {
294
+ return JSON.parse(textContent);
295
+ }
296
+ catch {
297
+ return {
298
+ success: false,
299
+ results: [],
300
+ summary: {
301
+ total: commands.length,
302
+ successCount: 0,
303
+ failureCount: commands.length,
304
+ skippedCount: 0,
305
+ },
306
+ timing: {
307
+ startedAt,
308
+ completedAt: new Date().toISOString(),
309
+ totalMs: 0,
310
+ averageMs: 0,
311
+ },
312
+ confidence: 0,
313
+ reasoning: 'Failed to parse batch result',
314
+ error: {
315
+ code: 'PARSE_ERROR',
316
+ message: 'Failed to parse batch result',
317
+ suggestion: 'The server returned an invalid response',
318
+ },
319
+ };
320
+ }
321
+ }
322
+ catch (error) {
323
+ const err = error instanceof Error ? error.message : String(error);
324
+ return {
325
+ success: false,
326
+ results: [],
327
+ summary: {
328
+ total: commands.length,
329
+ successCount: 0,
330
+ failureCount: commands.length,
331
+ skippedCount: 0,
332
+ },
333
+ timing: {
334
+ startedAt,
335
+ completedAt: new Date().toISOString(),
336
+ totalMs: 0,
337
+ averageMs: 0,
338
+ },
339
+ confidence: 0,
340
+ reasoning: `Batch execution failed: ${err}`,
341
+ error: {
342
+ code: 'BATCH_ERROR',
343
+ message: err,
344
+ suggestion: 'Check the connection and try again',
345
+ },
346
+ };
347
+ }
348
+ }
349
+ /**
350
+ * Stream command execution results with real-time progress.
351
+ *
352
+ * Returns an async generator that yields StreamChunk objects
353
+ * containing progress updates, incremental data, completion,
354
+ * or error information.
355
+ *
356
+ * @param name - Command name to execute
357
+ * @param args - Command arguments
358
+ * @param options - Stream options (abort signal, timeout)
359
+ * @returns AsyncGenerator of StreamChunk objects
360
+ *
361
+ * @example
362
+ * ```typescript
363
+ * for await (const chunk of client.stream('llm.generate', { prompt: 'Hello' })) {
364
+ * if (chunk.type === 'progress') {
365
+ * console.log(`Progress: ${(chunk.progress * 100).toFixed(0)}%`);
366
+ * } else if (chunk.type === 'data') {
367
+ * process.stdout.write(String(chunk.data));
368
+ * } else if (chunk.type === 'complete') {
369
+ * console.log('Done!', chunk.data);
370
+ * } else if (chunk.type === 'error') {
371
+ * console.error('Error:', chunk.error.message);
372
+ * }
373
+ * }
374
+ * ```
375
+ */
376
+ async *stream(name, args, options) {
377
+ const url = new URL(this.config.url);
378
+ // Use the stream endpoint relative to base URL
379
+ const streamUrl = `${url.protocol}//${url.host}/stream/${encodeURIComponent(name)}`;
380
+ const controller = new AbortController();
381
+ const signal = options?.signal
382
+ ? this.combineSignals(options.signal, controller.signal)
383
+ : controller.signal;
384
+ // Setup timeout if specified
385
+ let timeoutId;
386
+ if (options?.timeout) {
387
+ timeoutId = setTimeout(() => controller.abort(), options.timeout);
388
+ }
389
+ try {
390
+ const response = await fetch(streamUrl, {
391
+ method: 'POST',
392
+ headers: {
393
+ 'Content-Type': 'application/json',
394
+ Accept: 'text/event-stream',
395
+ ...this.config.headers,
396
+ },
397
+ body: JSON.stringify(args ?? {}),
398
+ signal,
399
+ });
400
+ if (!response.ok) {
401
+ yield {
402
+ type: 'error',
403
+ error: {
404
+ code: 'STREAM_ERROR',
405
+ message: `HTTP ${response.status}: ${response.statusText}`,
406
+ suggestion: 'Check the command name and arguments',
407
+ },
408
+ chunksBeforeError: 0,
409
+ recoverable: false,
410
+ };
411
+ return;
412
+ }
413
+ const reader = response.body?.getReader();
414
+ if (!reader) {
415
+ yield {
416
+ type: 'error',
417
+ error: {
418
+ code: 'STREAM_ERROR',
419
+ message: 'Response body is not readable',
420
+ suggestion: 'The server does not support streaming',
421
+ },
422
+ chunksBeforeError: 0,
423
+ recoverable: false,
424
+ };
425
+ return;
426
+ }
427
+ const decoder = new TextDecoder();
428
+ let buffer = '';
429
+ let chunksReceived = 0;
430
+ while (true) {
431
+ const { done, value } = await reader.read();
432
+ if (done)
433
+ break;
434
+ buffer += decoder.decode(value, { stream: true });
435
+ // Process SSE events
436
+ const lines = buffer.split('\n');
437
+ buffer = lines.pop() ?? ''; // Keep incomplete line in buffer
438
+ for (const line of lines) {
439
+ if (line.startsWith('data: ')) {
440
+ const data = line.slice(6).trim();
441
+ if (data === '[DONE]') {
442
+ return;
443
+ }
444
+ try {
445
+ const chunk = JSON.parse(data);
446
+ chunksReceived++;
447
+ yield chunk;
448
+ // Stop on complete or error
449
+ if (isCompleteChunk(chunk) || isErrorChunk(chunk)) {
450
+ return;
451
+ }
452
+ }
453
+ catch {
454
+ // Ignore malformed JSON
455
+ this.debug('Malformed stream chunk:', data);
456
+ }
457
+ }
458
+ }
459
+ }
460
+ }
461
+ catch (error) {
462
+ if (signal.aborted) {
463
+ yield {
464
+ type: 'error',
465
+ error: {
466
+ code: 'STREAM_CANCELLED',
467
+ message: 'Stream was cancelled',
468
+ suggestion: 'The request was aborted by the client',
469
+ },
470
+ chunksBeforeError: 0,
471
+ recoverable: false,
472
+ };
473
+ }
474
+ else {
475
+ yield {
476
+ type: 'error',
477
+ error: wrapError(error),
478
+ chunksBeforeError: 0,
479
+ recoverable: true,
480
+ };
481
+ }
482
+ }
483
+ finally {
484
+ if (timeoutId) {
485
+ clearTimeout(timeoutId);
486
+ }
487
+ }
488
+ }
489
+ /**
490
+ * Stream with callback-style API for convenience.
491
+ *
492
+ * This is a convenience wrapper around stream() that uses callbacks
493
+ * instead of async iteration.
494
+ *
495
+ * @param name - Command name to execute
496
+ * @param args - Command arguments
497
+ * @param callbacks - Callback handlers for stream events
498
+ * @param options - Stream options
499
+ * @returns Promise that resolves when stream completes
500
+ *
501
+ * @example
502
+ * ```typescript
503
+ * await client.streamWithCallbacks('llm.generate', { prompt: 'Hello' }, {
504
+ * onProgress: (chunk) => console.log(`${(chunk.progress * 100).toFixed(0)}% - ${chunk.message}`),
505
+ * onData: (chunk) => process.stdout.write(String(chunk.data)),
506
+ * onComplete: (chunk) => console.log('Done!', chunk.data),
507
+ * onError: (chunk) => console.error('Error:', chunk.error.message),
508
+ * });
509
+ * ```
510
+ */
511
+ async streamWithCallbacks(name, args, callbacks, options) {
512
+ for await (const chunk of this.stream(name, args, options)) {
513
+ if (isProgressChunk(chunk) && callbacks.onProgress) {
514
+ callbacks.onProgress(chunk);
515
+ }
516
+ else if (isDataChunk(chunk) && callbacks.onData) {
517
+ callbacks.onData(chunk);
518
+ }
519
+ else if (isCompleteChunk(chunk) && callbacks.onComplete) {
520
+ callbacks.onComplete(chunk);
521
+ }
522
+ else if (isErrorChunk(chunk) && callbacks.onError) {
523
+ callbacks.onError(chunk);
524
+ }
525
+ }
526
+ }
527
+ /**
528
+ * Combine two AbortSignals into one.
529
+ */
530
+ combineSignals(signal1, signal2) {
531
+ const controller = new AbortController();
532
+ const abort = () => controller.abort();
533
+ signal1.addEventListener('abort', abort);
534
+ signal2.addEventListener('abort', abort);
535
+ // Abort if either is already aborted
536
+ if (signal1.aborted || signal2.aborted) {
537
+ controller.abort();
538
+ }
539
+ return controller.signal;
540
+ }
541
+ // ═══════════════════════════════════════════════════════════════════════════
542
+ // LOW-LEVEL REQUEST/RESPONSE
543
+ // ═══════════════════════════════════════════════════════════════════════════
544
+ /**
545
+ * Send a raw MCP request and wait for response.
546
+ */
547
+ async request(method, params) {
548
+ // Allow requests during 'connecting' (for initialize) and 'connected' states
549
+ const canRequest = this.transport &&
550
+ (this.state === 'connected' || this.state === 'connecting') &&
551
+ this.transport.isConnected();
552
+ if (!canRequest || !this.transport) {
553
+ throw new Error('Not connected');
554
+ }
555
+ const request = createMcpRequest(method, params);
556
+ this.debug(`Request [${request.id}]: ${method}`, params);
557
+ // For transports that return response directly
558
+ const response = await this.transport.send(request);
559
+ this.debug(`Response [${request.id}]:`, response);
560
+ if (response.error) {
561
+ throw new Error(response.error.message);
562
+ }
563
+ return response.result;
564
+ }
565
+ // ═══════════════════════════════════════════════════════════════════════════
566
+ // EVENT HANDLING
567
+ // ═══════════════════════════════════════════════════════════════════════════
568
+ /**
569
+ * Subscribe to an event.
570
+ */
571
+ on(event, handler) {
572
+ this.eventHandlers[event].push(handler);
573
+ // Return unsubscribe function
574
+ return () => {
575
+ const index = this.eventHandlers[event].indexOf(handler);
576
+ if (index > -1) {
577
+ this.eventHandlers[event].splice(index, 1);
578
+ }
579
+ };
580
+ }
581
+ /**
582
+ * Emit an event.
583
+ */
584
+ emit(event, ...args) {
585
+ for (const handler of this.eventHandlers[event]) {
586
+ try {
587
+ handler(...args);
588
+ }
589
+ catch (error) {
590
+ console.error(`Error in event handler for '${event}':`, error);
591
+ }
592
+ }
593
+ }
594
+ // ═══════════════════════════════════════════════════════════════════════════
595
+ // INTERNAL
596
+ // ═══════════════════════════════════════════════════════════════════════════
597
+ async initialize() {
598
+ const params = {
599
+ protocolVersion: '2024-11-05',
600
+ capabilities: {
601
+ roots: { listChanged: false },
602
+ },
603
+ clientInfo: {
604
+ name: this.config.clientName,
605
+ version: this.config.clientVersion,
606
+ },
607
+ };
608
+ return this.request('initialize', params);
609
+ }
610
+ setState(state) {
611
+ if (this.state !== state) {
612
+ this.state = state;
613
+ this.emit('stateChange', state);
614
+ }
615
+ }
616
+ handleMessage(response) {
617
+ this.emit('message', response);
618
+ // Handle pending request if this is a response
619
+ const pending = this.pendingRequests.get(response.id);
620
+ if (pending) {
621
+ clearTimeout(pending.timeout);
622
+ this.pendingRequests.delete(response.id);
623
+ if (response.error) {
624
+ pending.reject(new Error(response.error.message));
625
+ }
626
+ else {
627
+ pending.resolve(response.result);
628
+ }
629
+ }
630
+ }
631
+ handleError(error) {
632
+ this.emit('error', error);
633
+ }
634
+ handleClose() {
635
+ if (this.state === 'connected' && this.config.autoReconnect) {
636
+ this.attemptReconnect();
637
+ }
638
+ else {
639
+ this.setState('disconnected');
640
+ this.emit('disconnected', 'Connection closed');
641
+ }
642
+ }
643
+ async attemptReconnect() {
644
+ if (this.reconnectAttempts >= this.config.maxReconnectAttempts) {
645
+ this.setState('error');
646
+ this.emit('error', new Error('Max reconnection attempts reached'));
647
+ return;
648
+ }
649
+ this.reconnectAttempts++;
650
+ this.setState('reconnecting');
651
+ this.emit('reconnecting', this.reconnectAttempts, this.config.maxReconnectAttempts);
652
+ // Exponential backoff
653
+ const delay = this.config.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
654
+ await new Promise((resolve) => setTimeout(resolve, delay));
655
+ try {
656
+ await this.connect();
657
+ }
658
+ catch {
659
+ // Will trigger another reconnect via handleClose
660
+ }
661
+ }
662
+ debug(message, data) {
663
+ if (this.config.debug) {
664
+ console.log(`[McpClient] ${message}`, data ?? '');
665
+ }
666
+ }
667
+ }
668
+ /**
669
+ * Create a new MCP client.
670
+ *
671
+ * @param config - Client configuration
672
+ * @returns New McpClient instance
673
+ */
674
+ export function createClient(config) {
675
+ return new McpClient(config);
676
+ }
677
+ //# sourceMappingURL=client.js.map