@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/LICENSE ADDED
@@ -0,0 +1,26 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lushly
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ NOTE: This license applies to the compiled npm packages (dist/).
26
+ Source code repository access is separate and not included.
package/README.md ADDED
@@ -0,0 +1,240 @@
1
+ # @afd/client
2
+
3
+ MCP client library for Agent-First Development.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @afd/client
9
+ # or
10
+ pnpm add @afd/client
11
+ ```
12
+
13
+ ## Overview
14
+
15
+ This package provides a client for connecting to MCP (Model Context Protocol) servers. It supports:
16
+
17
+ - **SSE Transport**: Real-time streaming with Server-Sent Events
18
+ - **HTTP Transport**: Simple request/response communication
19
+ - **Direct Transport**: Zero-overhead in-process execution for co-located agents
20
+ - **Auto-reconnection**: Automatic reconnection with exponential backoff
21
+ - **Type-safe API**: Full TypeScript support with CommandResult integration
22
+
23
+ ## Usage
24
+
25
+ ### Basic Connection
26
+
27
+ ```typescript
28
+ import { createClient } from '@afd/client';
29
+
30
+ // Create client
31
+ const client = createClient({
32
+ url: 'http://localhost:3100/sse',
33
+ transport: 'sse', // or 'http'
34
+ });
35
+
36
+ // Connect
37
+ await client.connect();
38
+
39
+ // List available tools
40
+ const tools = await client.listTools();
41
+ console.log('Available tools:', tools.map(t => t.name));
42
+
43
+ // Disconnect when done
44
+ await client.disconnect();
45
+ ```
46
+
47
+ ### Calling Commands
48
+
49
+ ```typescript
50
+ import { createClient, type CommandResult } from '@afd/client';
51
+ import { isSuccess, isFailure } from '@afd/core';
52
+
53
+ const client = createClient({ url: 'http://localhost:3100/sse' });
54
+ await client.connect();
55
+
56
+ // Call a command - returns CommandResult
57
+ const result = await client.call<Document>('document.create', {
58
+ title: 'My Document',
59
+ content: 'Hello, world!'
60
+ });
61
+
62
+ if (isSuccess(result)) {
63
+ console.log('Created document:', result.data);
64
+ console.log('Confidence:', result.confidence);
65
+ console.log('Reasoning:', result.reasoning);
66
+ } else {
67
+ console.error('Error:', result.error.message);
68
+ console.error('Suggestion:', result.error.suggestion);
69
+ }
70
+ ```
71
+
72
+ ### Event Handling
73
+
74
+ ```typescript
75
+ const client = createClient({
76
+ url: 'http://localhost:3100/sse',
77
+ autoReconnect: true,
78
+ maxReconnectAttempts: 5,
79
+ });
80
+
81
+ // Subscribe to events
82
+ client.on('connected', (info) => {
83
+ console.log('Connected to:', info.serverInfo.name);
84
+ });
85
+
86
+ client.on('disconnected', (reason) => {
87
+ console.log('Disconnected:', reason);
88
+ });
89
+
90
+ client.on('reconnecting', (attempt, max) => {
91
+ console.log(`Reconnecting... (${attempt}/${max})`);
92
+ });
93
+
94
+ client.on('error', (error) => {
95
+ console.error('Client error:', error);
96
+ });
97
+
98
+ client.on('toolsChanged', (tools) => {
99
+ console.log('Tools updated:', tools.length);
100
+ });
101
+
102
+ await client.connect();
103
+ ```
104
+
105
+ ### Client Status
106
+
107
+ ```typescript
108
+ const status = client.getStatus();
109
+
110
+ console.log('State:', status.state);
111
+ console.log('Server:', status.serverInfo?.name);
112
+ console.log('Connected at:', status.connectedAt);
113
+ console.log('Pending requests:', status.pendingRequests);
114
+ ```
115
+
116
+ ### Raw Tool Calls
117
+
118
+ For low-level access, use `callTool` which returns the raw MCP response:
119
+
120
+ ```typescript
121
+ // Raw MCP response
122
+ const rawResult = await client.callTool('document.create', {
123
+ title: 'Test'
124
+ });
125
+
126
+ console.log('Content:', rawResult.content);
127
+ console.log('Is error:', rawResult.isError);
128
+ ```
129
+
130
+ ## Configuration
131
+
132
+ ```typescript
133
+ interface McpClientConfig {
134
+ // Required
135
+ url: string; // Server URL
136
+
137
+ // Optional
138
+ transport?: 'sse' | 'http'; // Default: 'sse'
139
+ clientName?: string; // Default: '@afd/client'
140
+ clientVersion?: string; // Default: '0.1.0'
141
+ timeout?: number; // Default: 30000 (30s)
142
+ autoReconnect?: boolean; // Default: true
143
+ maxReconnectAttempts?: number; // Default: 5
144
+ reconnectDelay?: number; // Default: 1000 (1s)
145
+ headers?: Record<string, string>;
146
+ debug?: boolean; // Default: false
147
+ }
148
+ ```
149
+
150
+ ## Transports
151
+
152
+ ### SSE Transport (Default)
153
+
154
+ Best for real-time applications. Maintains a persistent connection for server-pushed events.
155
+
156
+ ```typescript
157
+ const client = createClient({
158
+ url: 'http://localhost:3100/sse',
159
+ transport: 'sse',
160
+ });
161
+ ```
162
+
163
+ ### HTTP Transport
164
+
165
+ Simple request/response. Good for serverless environments or when SSE isn't supported.
166
+
167
+ ```typescript
168
+ const client = createClient({
169
+ url: 'http://localhost:3100/message',
170
+ transport: 'http',
171
+ });
172
+ ```
173
+
174
+ ### Direct Transport (Zero Overhead)
175
+
176
+ For co-located agents (same runtime as the application), use `DirectClient` to bypass all transport overhead:
177
+
178
+ ```typescript
179
+ import { DirectClient } from '@afd/client';
180
+ import { registry } from '@my-app/commands';
181
+
182
+ // Direct execution - ~0.01ms latency vs 10-100ms for MCP
183
+ const client = new DirectClient(registry);
184
+
185
+ const result = await client.call<Todo>('todo-create', { title: 'Fast!' });
186
+ if (result.success) {
187
+ console.log('Created:', result.data.id);
188
+ }
189
+ ```
190
+
191
+ **Performance comparison:**
192
+
193
+ | Transport | Avg Latency | Use Case |
194
+ |-----------|-------------|----------|
195
+ | Direct | ~0.01ms | Same runtime, max performance |
196
+ | SSE | ~20-50ms | Real-time streaming |
197
+ | HTTP | ~20-100ms | Request/response, serverless |
198
+
199
+ Your registry must implement the `DirectRegistry` interface:
200
+
201
+ ```typescript
202
+ import { DirectRegistry } from '@afd/client';
203
+ import type { CommandResult } from '@afd/core';
204
+
205
+ class MyRegistry implements DirectRegistry {
206
+ async execute<T>(name: string, input?: unknown): Promise<CommandResult<T>>;
207
+ listCommandNames(): string[];
208
+ listCommands(): Array<{ name: string; description: string }>;
209
+ hasCommand(name: string): boolean;
210
+ }
211
+ ```
212
+
213
+ ## Error Handling
214
+
215
+ The client wraps all errors in the standard `CommandResult` format:
216
+
217
+ ```typescript
218
+ const result = await client.call('document.get', { id: 'not-found' });
219
+
220
+ if (isFailure(result)) {
221
+ // Error contains:
222
+ // - code: Machine-readable error code
223
+ // - message: Human-readable message
224
+ // - suggestion: What the user can do
225
+ // - retryable: Whether retrying might help
226
+ console.error(`[${result.error.code}] ${result.error.message}`);
227
+
228
+ if (result.error.suggestion) {
229
+ console.log('Suggestion:', result.error.suggestion);
230
+ }
231
+
232
+ if (result.error.retryable) {
233
+ // Consider retrying
234
+ }
235
+ }
236
+ ```
237
+
238
+ ## License
239
+
240
+ MIT
@@ -0,0 +1,192 @@
1
+ /**
2
+ * @fileoverview MCP Client implementation
3
+ */
4
+ import type { BatchCommand, BatchOptions, BatchResult, CommandResult, McpInitializeResult, McpTool, McpToolCallResult, StreamCallbacks, StreamChunk, StreamOptions } from '@lushly-dev/afd-core';
5
+ import type { ClientStatus, McpClientConfig, McpClientEvents } from './types.js';
6
+ /**
7
+ * Type-safe event emitter mixin.
8
+ */
9
+ type EventHandler<T extends (...args: never[]) => void> = T;
10
+ /**
11
+ * MCP Client for connecting to MCP servers.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * const client = new McpClient({ url: 'http://localhost:3100/sse' });
16
+ *
17
+ * await client.connect();
18
+ *
19
+ * // List available tools
20
+ * const tools = await client.listTools();
21
+ *
22
+ * // Call a tool
23
+ * const result = await client.call('document.create', { title: 'Test' });
24
+ *
25
+ * await client.disconnect();
26
+ * ```
27
+ */
28
+ export declare class McpClient {
29
+ private readonly config;
30
+ private transport;
31
+ private state;
32
+ private serverInfo;
33
+ private capabilities;
34
+ private tools;
35
+ private connectedAt;
36
+ private reconnectAttempts;
37
+ private pendingRequests;
38
+ private eventHandlers;
39
+ constructor(config: McpClientConfig);
40
+ /**
41
+ * Connect to the MCP server.
42
+ */
43
+ connect(): Promise<McpInitializeResult>;
44
+ /**
45
+ * Disconnect from the MCP server.
46
+ */
47
+ disconnect(): Promise<void>;
48
+ /**
49
+ * Get current client status.
50
+ */
51
+ getStatus(): ClientStatus;
52
+ /**
53
+ * Check if connected.
54
+ */
55
+ isConnected(): boolean;
56
+ /**
57
+ * List available tools.
58
+ */
59
+ listTools(): Promise<McpTool[]>;
60
+ /**
61
+ * Get cached tools list.
62
+ */
63
+ getTools(): McpTool[];
64
+ /**
65
+ * Refresh tools list from server.
66
+ */
67
+ refreshTools(): Promise<McpTool[]>;
68
+ /**
69
+ * Call a tool and return raw MCP result.
70
+ *
71
+ * @param name - Tool name
72
+ * @param args - Tool arguments
73
+ */
74
+ callTool(name: string, args?: Record<string, unknown>): Promise<McpToolCallResult>;
75
+ /**
76
+ * Call a command and return a CommandResult.
77
+ *
78
+ * This is the preferred method for AFD - it wraps the MCP response
79
+ * in a standardized CommandResult.
80
+ *
81
+ * @param name - Command/tool name
82
+ * @param args - Command arguments
83
+ */
84
+ call<T = unknown>(name: string, args?: Record<string, unknown>): Promise<CommandResult<T>>;
85
+ /**
86
+ * Execute multiple commands in a single batch request.
87
+ *
88
+ * Batch execution provides partial success semantics - the batch
89
+ * succeeds if at least one command succeeds, with aggregated
90
+ * confidence scores and detailed timing information.
91
+ *
92
+ * @param commands - Array of commands to execute
93
+ * @param options - Batch execution options
94
+ * @returns BatchResult with individual command results
95
+ *
96
+ * @example
97
+ * ```typescript
98
+ * const result = await client.batch([
99
+ * { name: 'todo.create', input: { title: 'First' } },
100
+ * { name: 'todo.create', input: { title: 'Second' } },
101
+ * { name: 'todo.list', input: {} }
102
+ * ], { stopOnError: false });
103
+ *
104
+ * console.log(`${result.summary.successCount}/${result.summary.total} succeeded`);
105
+ * console.log(`Confidence: ${(result.confidence * 100).toFixed(1)}%`);
106
+ * ```
107
+ */
108
+ batch<T = unknown>(commands: BatchCommand[], options?: BatchOptions): Promise<BatchResult<T>>;
109
+ /**
110
+ * Stream command execution results with real-time progress.
111
+ *
112
+ * Returns an async generator that yields StreamChunk objects
113
+ * containing progress updates, incremental data, completion,
114
+ * or error information.
115
+ *
116
+ * @param name - Command name to execute
117
+ * @param args - Command arguments
118
+ * @param options - Stream options (abort signal, timeout)
119
+ * @returns AsyncGenerator of StreamChunk objects
120
+ *
121
+ * @example
122
+ * ```typescript
123
+ * for await (const chunk of client.stream('llm.generate', { prompt: 'Hello' })) {
124
+ * if (chunk.type === 'progress') {
125
+ * console.log(`Progress: ${(chunk.progress * 100).toFixed(0)}%`);
126
+ * } else if (chunk.type === 'data') {
127
+ * process.stdout.write(String(chunk.data));
128
+ * } else if (chunk.type === 'complete') {
129
+ * console.log('Done!', chunk.data);
130
+ * } else if (chunk.type === 'error') {
131
+ * console.error('Error:', chunk.error.message);
132
+ * }
133
+ * }
134
+ * ```
135
+ */
136
+ stream<T = unknown>(name: string, args?: Record<string, unknown>, options?: StreamOptions): AsyncGenerator<StreamChunk<T>, void, unknown>;
137
+ /**
138
+ * Stream with callback-style API for convenience.
139
+ *
140
+ * This is a convenience wrapper around stream() that uses callbacks
141
+ * instead of async iteration.
142
+ *
143
+ * @param name - Command name to execute
144
+ * @param args - Command arguments
145
+ * @param callbacks - Callback handlers for stream events
146
+ * @param options - Stream options
147
+ * @returns Promise that resolves when stream completes
148
+ *
149
+ * @example
150
+ * ```typescript
151
+ * await client.streamWithCallbacks('llm.generate', { prompt: 'Hello' }, {
152
+ * onProgress: (chunk) => console.log(`${(chunk.progress * 100).toFixed(0)}% - ${chunk.message}`),
153
+ * onData: (chunk) => process.stdout.write(String(chunk.data)),
154
+ * onComplete: (chunk) => console.log('Done!', chunk.data),
155
+ * onError: (chunk) => console.error('Error:', chunk.error.message),
156
+ * });
157
+ * ```
158
+ */
159
+ streamWithCallbacks<T = unknown>(name: string, args: Record<string, unknown> | undefined, callbacks: StreamCallbacks<T>, options?: StreamOptions): Promise<void>;
160
+ /**
161
+ * Combine two AbortSignals into one.
162
+ */
163
+ private combineSignals;
164
+ /**
165
+ * Send a raw MCP request and wait for response.
166
+ */
167
+ request<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T>;
168
+ /**
169
+ * Subscribe to an event.
170
+ */
171
+ on<K extends keyof McpClientEvents>(event: K, handler: EventHandler<McpClientEvents[K]>): () => void;
172
+ /**
173
+ * Emit an event.
174
+ */
175
+ private emit;
176
+ private initialize;
177
+ private setState;
178
+ private handleMessage;
179
+ private handleError;
180
+ private handleClose;
181
+ private attemptReconnect;
182
+ private debug;
183
+ }
184
+ /**
185
+ * Create a new MCP client.
186
+ *
187
+ * @param config - Client configuration
188
+ * @returns New McpClient instance
189
+ */
190
+ export declare function createClient(config: McpClientConfig): McpClient;
191
+ export {};
192
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EACX,YAAY,EACZ,YAAY,EACZ,WAAW,E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