Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x | /**
* AgentKits — MCP (Model Context Protocol) Client
*
* Connect to any MCP server and use its tools as LLM function definitions.
* Supports stdio and SSE transports.
*
* Usage:
* import { createMCPClient } from 'agentkits/mcp-client';
* const mcp = await createMCPClient({ serverUrl: 'http://localhost:3001/sse' });
* const tools = await mcp.listTools();
* const result = await mcp.callTool('search', { query: 'hello' });
*/
// ── Types ──────────────────────────────────────────────────────────
export interface MCPToolParameter {
name: string;
type: string;
description?: string;
required?: boolean;
}
export interface MCPTool {
name: string;
description: string;
inputSchema: Record<string, any>;
}
export interface MCPClientConfig {
/** SSE server URL (e.g. http://localhost:3001/sse) */
serverUrl?: string;
/** Stdio command (e.g. 'npx @modelcontextprotocol/server-filesystem /tmp') */
command?: string;
/** Arguments for stdio command */
args?: string[];
/** Environment variables for stdio process */
env?: Record<string, string>;
/** Connection timeout in ms (default: 10000) */
timeout?: number;
/** Request timeout in ms (default: 30000) */
requestTimeout?: number;
}
export interface MCPToolResult {
content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;
isError?: boolean;
}
export interface MCPResource {
uri: string;
name: string;
description?: string;
mimeType?: string;
}
export interface MCPClient {
config: MCPClientConfig;
/** List available tools from the MCP server */
listTools(): Promise<MCPTool[]>;
/** Call a tool on the MCP server */
callTool(name: string, args?: Record<string, any>): Promise<MCPToolResult>;
/** Convert MCP tools to OpenAI function definitions */
toFunctionDefs(): Promise<Array<{ type: 'function'; function: { name: string; description: string; parameters: Record<string, any> } }>>;
/** List available resources */
listResources(): Promise<MCPResource[]>;
/** Read a resource by URI */
readResource(uri: string): Promise<{ contents: Array<{ uri: string; text?: string; blob?: string; mimeType?: string }> }>;
/** Disconnect from the server */
disconnect(): Promise<void>;
}
// ── JSON-RPC Helpers ───────────────────────────────────────────────
interface JsonRpcRequest {
jsonrpc: '2.0';
id: number;
method: string;
params?: Record<string, any>;
}
interface JsonRpcResponse {
jsonrpc: '2.0';
id: number;
result?: any;
error?: { code: number; message: string; data?: any };
}
let _nextId = 1;
function makeRequest(method: string, params?: Record<string, any>): JsonRpcRequest {
return { jsonrpc: '2.0', id: _nextId++, method, params };
}
// ── SSE Transport ──────────────────────────────────────────────────
class SSETransport {
private endpointUrl: string | null = null;
private abortController: AbortController | null = null;
private pendingRequests = new Map<number, { resolve: (v: any) => void; reject: (e: Error) => void }>();
private connected = false;
constructor(private serverUrl: string, private timeout: number) {}
async connect(): Promise<void> {
this.abortController = new AbortController();
const response = await fetch(this.serverUrl, {
headers: { Accept: 'text/event-stream' },
signal: this.abortController.signal,
});
if (!response.ok) throw new Error(`MCP SSE connect failed: ${response.status}`);
if (!response.body) throw new Error('MCP SSE: no response body');
const reader = response.body.getReader();
const decoder = new TextDecoder();
// Read endpoint from first event
const endpointPromise = new Promise<string>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('MCP SSE: timeout waiting for endpoint')), this.timeout);
let buffer = '';
const readChunk = async () => {
try {
const { value, done } = await reader.read();
if (done) { reject(new Error('MCP SSE: stream ended before endpoint')); return; }
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() ?? '';
for (const line of lines) {
if (line.startsWith('event: endpoint')) {
// next data: line has the endpoint
} else if (line.startsWith('data: ') && !this.endpointUrl) {
clearTimeout(timer);
resolve(line.slice(6).trim());
return;
}
}
readChunk();
} catch (e: any) {
if (e.name !== 'AbortError') reject(e);
}
};
readChunk();
});
this.endpointUrl = await endpointPromise;
// Resolve relative URL
if (this.endpointUrl.startsWith('/')) {
const base = new URL(this.serverUrl);
this.endpointUrl = `${base.origin}${this.endpointUrl}`;
}
// Continue reading events in background
this._readEvents(reader, decoder);
this.connected = true;
}
private async _readEvents(reader: ReadableStreamDefaultReader<Uint8Array>, decoder: TextDecoder) {
let buffer = '';
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() ?? '';
let currentData = '';
for (const line of lines) {
if (line.startsWith('data: ')) {
currentData = line.slice(6);
} else if (line === '' && currentData) {
try {
const msg: JsonRpcResponse = JSON.parse(currentData);
if (msg.id && this.pendingRequests.has(msg.id)) {
const { resolve, reject } = this.pendingRequests.get(msg.id)!;
this.pendingRequests.delete(msg.id);
if (msg.error) reject(new Error(`MCP error ${msg.error.code}: ${msg.error.message}`));
else resolve(msg.result);
}
} catch {}
currentData = '';
}
}
}
} catch (e: any) {
if (e.name !== 'AbortError') {
for (const { reject } of this.pendingRequests.values()) reject(e);
this.pendingRequests.clear();
}
}
}
async send(request: JsonRpcRequest, timeout: number): Promise<any> {
if (!this.endpointUrl) throw new Error('MCP SSE: not connected');
const promise = new Promise<any>((resolve, reject) => {
const timer = setTimeout(() => {
this.pendingRequests.delete(request.id);
reject(new Error(`MCP request timeout: ${request.method}`));
}, timeout);
this.pendingRequests.set(request.id, {
resolve: (v) => { clearTimeout(timer); resolve(v); },
reject: (e) => { clearTimeout(timer); reject(e); },
});
});
const resp = await fetch(this.endpointUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
});
if (!resp.ok) {
this.pendingRequests.delete(request.id);
throw new Error(`MCP POST failed: ${resp.status}`);
}
return promise;
}
disconnect() {
this.abortController?.abort();
this.connected = false;
for (const { reject } of this.pendingRequests.values()) reject(new Error('Disconnected'));
this.pendingRequests.clear();
}
}
// ── Stdio Transport ────────────────────────────────────────────────
class StdioTransport {
private process: any = null;
private pendingRequests = new Map<number, { resolve: (v: any) => void; reject: (e: Error) => void }>();
private buffer = '';
constructor(private command: string, private args: string[], private env: Record<string, string>) {}
async connect(): Promise<void> {
const { spawn } = await import('child_process');
this.process = spawn(this.command, this.args, {
env: { ...process.env, ...this.env },
stdio: ['pipe', 'pipe', 'pipe'],
});
this.process.stdout!.on('data', (data: Buffer) => {
this.buffer += data.toString();
const lines = this.buffer.split('\n');
this.buffer = lines.pop() ?? '';
for (const line of lines) {
if (!line.trim()) continue;
try {
const msg: JsonRpcResponse = JSON.parse(line);
if (msg.id && this.pendingRequests.has(msg.id)) {
const { resolve, reject } = this.pendingRequests.get(msg.id)!;
this.pendingRequests.delete(msg.id);
if (msg.error) reject(new Error(`MCP error ${msg.error.code}: ${msg.error.message}`));
else resolve(msg.result);
}
} catch {}
}
});
this.process.on('exit', () => {
for (const { reject } of this.pendingRequests.values()) reject(new Error('MCP process exited'));
this.pendingRequests.clear();
});
}
async send(request: JsonRpcRequest, timeout: number): Promise<any> {
if (!this.process) throw new Error('MCP stdio: not connected');
return new Promise<any>((resolve, reject) => {
const timer = setTimeout(() => {
this.pendingRequests.delete(request.id);
reject(new Error(`MCP request timeout: ${request.method}`));
}, timeout);
this.pendingRequests.set(request.id, {
resolve: (v) => { clearTimeout(timer); resolve(v); },
reject: (e) => { clearTimeout(timer); reject(e); },
});
this.process.stdin!.write(JSON.stringify(request) + '\n');
});
}
disconnect() {
this.process?.kill();
this.process = null;
for (const { reject } of this.pendingRequests.values()) reject(new Error('Disconnected'));
this.pendingRequests.clear();
}
}
// ── Factory ────────────────────────────────────────────────────────
export async function createMCPClient(config: MCPClientConfig): Promise<MCPClient> {
const timeout = config.timeout ?? 10000;
const requestTimeout = config.requestTimeout ?? 30000;
let transport: SSETransport | StdioTransport;
if (config.serverUrl) {
transport = new SSETransport(config.serverUrl, timeout);
} else if (config.command) {
transport = new StdioTransport(config.command, config.args ?? [], config.env ?? {});
} else {
throw new Error('MCPClient requires either serverUrl (SSE) or command (stdio)');
}
await transport.connect();
// Initialize
await transport.send(makeRequest('initialize', {
protocolVersion: '2024-11-05',
capabilities: {},
clientInfo: { name: 'agentkits', version: '1.4.0' },
}), requestTimeout);
// Send initialized notification (no id)
if (config.serverUrl && transport instanceof SSETransport) {
// For SSE, we just fire a notification
try {
await transport.send({ jsonrpc: '2.0', id: _nextId++, method: 'notifications/initialized', params: {} } as any, 5000).catch(() => {});
} catch {}
}
let cachedTools: MCPTool[] | null = null;
return {
config,
async listTools(): Promise<MCPTool[]> {
if (cachedTools) return cachedTools;
const result = await transport.send(makeRequest('tools/list'), requestTimeout);
cachedTools = (result.tools ?? []).map((t: any) => ({
name: t.name,
description: t.description ?? '',
inputSchema: t.inputSchema ?? { type: 'object', properties: {} },
}));
return cachedTools!;
},
async callTool(name: string, args?: Record<string, any>): Promise<MCPToolResult> {
const result = await transport.send(makeRequest('tools/call', { name, arguments: args ?? {} }), requestTimeout);
return result as MCPToolResult;
},
async toFunctionDefs() {
if (!cachedTools) {
const result = await transport.send(makeRequest('tools/list'), requestTimeout);
cachedTools = (result.tools ?? []).map((t: any) => ({
name: t.name,
description: t.description ?? '',
inputSchema: t.inputSchema ?? { type: 'object', properties: {} },
}));
}
return cachedTools!.map((t: MCPTool) => ({
type: 'function' as const,
function: {
name: t.name,
description: t.description,
parameters: t.inputSchema,
},
}));
},
async listResources(): Promise<MCPResource[]> {
const result = await transport.send(makeRequest('resources/list'), requestTimeout);
return (result.resources ?? []) as MCPResource[];
},
async readResource(uri: string) {
return await transport.send(makeRequest('resources/read', { uri }), requestTimeout);
},
async disconnect() {
transport.disconnect();
},
};
}
|