@xiaozhi-client/mcp-core 1.9.7-beta.3 → 1.9.7-beta.6

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/index.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import { Tool } from '@modelcontextprotocol/sdk/types.js';
2
+ import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
3
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
4
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
2
5
  import { EventEmitter } from 'node:events';
3
6
 
4
7
  /**
@@ -6,6 +9,11 @@ import { EventEmitter } from 'node:events';
6
9
  * 统一管理所有 MCP 相关的类型定义
7
10
  */
8
11
 
12
+ /**
13
+ * MCP 传输层联合类型定义
14
+ * 支持 STDIO、SSE、StreamableHTTP 三种传输协议
15
+ */
16
+ type MCPServerTransport = StdioClientTransport | SSEClientTransport | StreamableHTTPClientTransport;
9
17
  /**
10
18
  * 通信方式枚举
11
19
  * 定义 MCP 支持的传输类型
@@ -15,6 +23,30 @@ declare enum MCPTransportType {
15
23
  SSE = "sse",
16
24
  STREAMABLE_HTTP = "streamable-http"
17
25
  }
26
+ /**
27
+ * MCP 服务事件回调接口
28
+ * 用于替代 EventBus 依赖,提供灵活的事件处理机制
29
+ */
30
+ interface MCPServiceEventCallbacks {
31
+ /** 连接成功回调 */
32
+ onConnected?: (data: {
33
+ serviceName: string;
34
+ tools: Tool[];
35
+ connectionTime: Date;
36
+ }) => void;
37
+ /** 断开连接回调 */
38
+ onDisconnected?: (data: {
39
+ serviceName: string;
40
+ reason?: string;
41
+ disconnectionTime: Date;
42
+ }) => void;
43
+ /** 连接失败回调 */
44
+ onConnectionFailed?: (data: {
45
+ serviceName: string;
46
+ error: Error;
47
+ attempt: number;
48
+ }) => void;
49
+ }
18
50
  /**
19
51
  * ModelScope SSE 自定义选项接口
20
52
  */
@@ -122,10 +154,6 @@ interface ToolInfo {
122
154
  originalName: string;
123
155
  tool: Tool;
124
156
  }
125
- /**
126
- * 工具状态过滤选项
127
- */
128
- type ToolStatusFilter = "enabled" | "disabled" | "all";
129
157
  /**
130
158
  * 增强的工具信息接口
131
159
  */
@@ -227,69 +255,345 @@ declare class ToolCallError extends Error {
227
255
  }
228
256
 
229
257
  /**
230
- * 简化版 MCP 服务管理器
231
- * 专门为 endpoint 包设计,提供核心 MCP 服务管理功能
258
+ * MCP 连接类
259
+ * 负责管理单个 MCP 服务的连接、工具管理和调用
232
260
  */
261
+ declare class MCPConnection {
262
+ private config;
263
+ private client;
264
+ private transport;
265
+ private tools;
266
+ private connectionState;
267
+ private connectionTimeout;
268
+ private initialized;
269
+ private callbacks?;
270
+ constructor(config: MCPServiceConfig, callbacks?: MCPServiceEventCallbacks);
271
+ /**
272
+ * 验证配置
273
+ */
274
+ private validateConfig;
275
+ /**
276
+ * 连接到 MCP 服务
277
+ */
278
+ connect(): Promise<void>;
279
+ /**
280
+ * 尝试建立连接
281
+ */
282
+ private attemptConnection;
283
+ /**
284
+ * 处理连接成功
285
+ */
286
+ private handleConnectionSuccess;
287
+ /**
288
+ * 处理连接错误
289
+ */
290
+ private handleConnectionError;
291
+ /**
292
+ * 清理连接资源
293
+ */
294
+ private cleanupConnection;
295
+ /**
296
+ * 刷新工具列表
297
+ */
298
+ private refreshTools;
299
+ /**
300
+ * 断开连接
301
+ */
302
+ disconnect(): Promise<void>;
303
+ /**
304
+ * 获取工具列表
305
+ */
306
+ getTools(): Tool[];
307
+ /**
308
+ * 调用工具
309
+ */
310
+ callTool(name: string, arguments_: Record<string, unknown>): Promise<ToolCallResult>;
311
+ /**
312
+ * 获取服务配置
313
+ */
314
+ getConfig(): MCPServiceConfig;
315
+ /**
316
+ * 获取服务状态
317
+ */
318
+ getStatus(): MCPServiceStatus;
319
+ /**
320
+ * 检查是否已连接
321
+ */
322
+ isConnected(): boolean;
323
+ }
233
324
 
234
325
  /**
235
- * 简化版 MCP 服务管理器
236
- * 提供 MCP 服务的核心管理功能
326
+ * MCP 服务管理器
327
+ * 提供简洁的 API 来管理多个 MCP 服务
237
328
  */
238
- declare class MCPServiceManager extends EventEmitter {
329
+
330
+ /**
331
+ * 用户友好的传输类型
332
+ * 用于简化和标准化用户输入
333
+ */
334
+ type UserFriendlyTransportType = "stdio" | "sse" | "http" | MCPTransportType;
335
+ /**
336
+ * MCP 服务管理器
337
+ * 提供简洁的 API 来管理多个 MCP 服务
338
+ *
339
+ * @example
340
+ * ```typescript
341
+ * const manager = new MCPManager();
342
+ *
343
+ * // 添加服务
344
+ * manager.addServer('datetime', {
345
+ * type: 'stdio',
346
+ * command: 'node',
347
+ * args: ['datetime.js']
348
+ * });
349
+ *
350
+ * // 连接所有服务
351
+ * await manager.connect();
352
+ *
353
+ * // 调用工具
354
+ * const result = await manager.callTool('datetime', 'get_current_time', {
355
+ * format: 'YYYY-MM-DD HH:mm:ss'
356
+ * });
357
+ *
358
+ * // 断开连接
359
+ * await manager.disconnect();
360
+ * ```
361
+ */
362
+ declare class MCPManager extends EventEmitter {
363
+ private connections;
239
364
  private configs;
240
- private tools;
241
- private isInitialized;
242
- constructor(configs?: Record<string, MCPServiceConfig>);
365
+ constructor();
243
366
  /**
244
- * 添加服务配置
367
+ * 添加 MCP 服务器配置
368
+ * @param name 服务器名称
369
+ * @param config 服务器配置
370
+ *
371
+ * @example
372
+ * ```typescript
373
+ * // 添加 stdio 服务
374
+ * manager.addServer('calculator', {
375
+ * type: 'stdio',
376
+ * command: 'node',
377
+ * args: ['calculator.js']
378
+ * });
379
+ *
380
+ * // 添加 HTTP 服务
381
+ * manager.addServer('web-search', {
382
+ * type: 'http',
383
+ * url: 'https://api.example.com/mcp',
384
+ * headers: {
385
+ * Authorization: 'Bearer your-api-key'
386
+ * }
387
+ * });
388
+ * ```
245
389
  */
246
- addServiceConfig(name: string, config: MCPServiceConfig): void;
390
+ addServer(name: string, config: Omit<MCPServiceConfig, "name"> & {
391
+ type?: UserFriendlyTransportType;
392
+ }): void;
247
393
  /**
248
- * 更新服务配置
394
+ * 移除服务器配置
395
+ * @param name 服务器名称
249
396
  */
250
- updateServiceConfig(name: string, config: MCPServiceConfig): void;
397
+ removeServer(name: string): boolean;
251
398
  /**
252
- * 移除服务配置
399
+ * 连接所有已添加的 MCP 服务
400
+ * 所有服务并行连接,单个服务失败不会影响其他服务
401
+ *
402
+ * @example
403
+ * ```typescript
404
+ * await manager.connect();
405
+ * ```
253
406
  */
254
- removeServiceConfig(name: string): void;
407
+ connect(): Promise<void>;
255
408
  /**
256
- * 获取所有服务配置
409
+ * 断开所有 MCP 服务连接
410
+ *
411
+ * @example
412
+ * ```typescript
413
+ * await manager.disconnect();
414
+ * ```
257
415
  */
258
- getServiceConfigs(): Record<string, MCPServiceConfig>;
416
+ disconnect(): Promise<void>;
259
417
  /**
260
- * 启动所有服务
418
+ * 调用指定服务的工具
419
+ * @param serverName 服务名称
420
+ * @param toolName 工具名称
421
+ * @param args 工具参数
422
+ *
423
+ * @example
424
+ * ```typescript
425
+ * const result = await manager.callTool('datetime', 'get_current_time', {
426
+ * format: 'YYYY-MM-DD HH:mm:ss'
427
+ * });
428
+ * ```
261
429
  */
262
- startAllServices(): Promise<void>;
430
+ callTool(serverName: string, toolName: string, args: Record<string, unknown>): Promise<ToolCallResult>;
263
431
  /**
264
- * 启动单个服务
432
+ * 列出所有可用的工具
433
+ * @returns 工具列表,格式为 [{ name, serverName, description, inputSchema }]
434
+ *
435
+ * @example
436
+ * ```typescript
437
+ * const tools = manager.listTools();
438
+ * console.log('可用工具:', tools.map(t => `${t.serverName}/${t.name}`));
439
+ * ```
265
440
  */
266
- startService(serviceName: string): Promise<void>;
441
+ listTools(): Array<{
442
+ name: string;
443
+ serverName: string;
444
+ description: string;
445
+ inputSchema: unknown;
446
+ }>;
267
447
  /**
268
- * 获取所有工具列表
448
+ * 获取服务状态
449
+ * @param serverName 服务名称
450
+ * @returns 服务状态,如果服务不存在则返回 null
451
+ *
452
+ * @example
453
+ * ```typescript
454
+ * const status = manager.getServerStatus('datetime');
455
+ * if (status) {
456
+ * console.log(`已连接: ${status.connected}, 工具数: ${status.toolCount}`);
457
+ * }
458
+ * ```
269
459
  */
270
- getAllTools(status?: ToolStatusFilter): EnhancedToolInfo[];
460
+ getServerStatus(serverName: string): {
461
+ connected: boolean;
462
+ toolCount: number;
463
+ } | null;
271
464
  /**
272
- * 调用工具
465
+ * 获取所有服务的状态
466
+ * @returns 所有服务的状态映射
467
+ *
468
+ * @example
469
+ * ```typescript
470
+ * const statuses = manager.getAllServerStatus();
471
+ * console.log(statuses);
472
+ * // {
473
+ * // datetime: { connected: true, toolCount: 3 },
474
+ * // calculator: { connected: true, toolCount: 1 }
475
+ * // }
476
+ * ```
273
477
  */
274
- callTool(toolName: string, _arguments_: Record<string, unknown>, _options?: {
275
- timeout?: number;
276
- }): Promise<ToolCallResult>;
478
+ getAllServerStatus(): Record<string, {
479
+ connected: boolean;
480
+ toolCount: number;
481
+ }>;
277
482
  /**
278
- * 添加工具(用于测试或自定义工具)
483
+ * 检查服务是否已连接
484
+ * @param serverName 服务名称
485
+ *
486
+ * @example
487
+ * ```typescript
488
+ * if (manager.isConnected('datetime')) {
489
+ * console.log('datetime 服务已连接');
490
+ * }
491
+ * ```
279
492
  */
280
- addTool(tool: EnhancedToolInfo): void;
493
+ isConnected(serverName: string): boolean;
281
494
  /**
282
- * 移除工具
495
+ * 获取已配置的服务列表
496
+ * @returns 服务名称数组
497
+ *
498
+ * @example
499
+ * ```typescript
500
+ * const servers = manager.getServerNames();
501
+ * console.log('已配置的服务:', servers);
502
+ * ```
283
503
  */
284
- removeTool(toolName: string): void;
504
+ getServerNames(): string[];
285
505
  /**
286
- * 获取管理器状态
506
+ * 获取已连接的服务列表
507
+ * @returns 已连接的服务名称数组
508
+ *
509
+ * @example
510
+ * ```typescript
511
+ * const connectedServers = manager.getConnectedServerNames();
512
+ * console.log('已连接的服务:', connectedServers);
513
+ * ```
287
514
  */
288
- getStatus(): ManagerStatus;
515
+ getConnectedServerNames(): string[];
516
+ }
517
+
518
+ /**
519
+ * 创建 transport 实例
520
+ * @param config MCP 服务配置
521
+ * @returns transport 实例
522
+ */
523
+ declare function createTransport(config: MCPServiceConfig): MCPServerTransport;
524
+ /**
525
+ * 验证配置
526
+ */
527
+ declare function validateConfig(config: MCPServiceConfig): void;
528
+ /**
529
+ * 获取支持的传输类型列表
530
+ */
531
+ declare function getSupportedTypes(): MCPTransportType[];
532
+ /**
533
+ * Transport 工厂对象(保持 API 兼容性)
534
+ */
535
+ declare const TransportFactory: {
536
+ create: typeof createTransport;
537
+ validateConfig: typeof validateConfig;
538
+ getSupportedTypes: typeof getSupportedTypes;
539
+ };
540
+
541
+ /**
542
+ * MCP 服务器配置 Type 字段标准化工具
543
+ * 支持将各种 type 字段格式转换为标准的中划线格式
544
+ */
545
+ /**
546
+ * MCP 服务器配置的基础接口
547
+ * 定义包含可选 type 字段的配置对象结构
548
+ */
549
+ interface MCPBaseConfig {
550
+ type?: string;
551
+ [key: string]: unknown;
552
+ }
553
+ /**
554
+ * MCP 服务器配置 Type 字段标准化工具类
555
+ */
556
+ declare namespace TypeFieldNormalizer {
289
557
  /**
290
- * 清理资源
558
+ * 标准化type字段格式
559
+ * 支持将各种格式转换为标准的中划线格式
291
560
  */
292
- cleanup(): Promise<void>;
561
+ function normalizeTypeField<T extends MCPBaseConfig>(config: T): T;
562
+ function normalizeTypeField(config: unknown): unknown;
293
563
  }
564
+ /**
565
+ * 导出便捷函数
566
+ */
567
+ declare function normalizeTypeField<T extends MCPBaseConfig>(config: T): T;
568
+ declare function normalizeTypeField(config: unknown): unknown;
569
+
570
+ /**
571
+ * 根据 URL 路径推断传输类型
572
+ * 基于路径末尾推断,支持包含多个 / 的复杂路径
573
+ *
574
+ * @param url - 要推断的 URL
575
+ * @param options - 可选配置项
576
+ * @returns 推断出的传输类型
577
+ */
578
+ declare function inferTransportTypeFromUrl(url: string, options?: {
579
+ serviceName?: string;
580
+ }): MCPTransportType;
581
+ /**
582
+ * 完整的配置类型推断(包括 command 字段)
583
+ *
584
+ * @param config - MCP 服务配置
585
+ * @returns 完整的配置对象,包含推断出的类型
586
+ */
587
+ declare function inferTransportTypeFromConfig(config: MCPServiceConfig): MCPServiceConfig;
588
+ /**
589
+ * 验证工具调用参数
590
+ * 对传入的参数进行完整性和格式验证
591
+ *
592
+ * @param params 待验证的参数
593
+ * @param options 验证选项
594
+ * @returns 验证后的参数
595
+ * @throws ToolCallError 验证失败时抛出
596
+ */
597
+ declare function validateToolCallParams(params: unknown, options?: ToolCallValidationOptions): ValidatedToolCallParams;
294
598
 
295
- export { ConnectionState, type CustomMCPTool, type EnhancedToolInfo, type JSONSchema, type MCPServiceConfig, type MCPServiceConnectionStatus, MCPServiceManager, type MCPServiceStatus, MCPTransportType, type ManagerStatus, type ModelScopeSSEOptions, ToolCallError, ToolCallErrorCode, type ToolCallParams, type ToolCallResult, type ToolCallValidationOptions, type ToolInfo, type UnifiedServerConfig, type UnifiedServerStatus, type ValidatedToolCallParams, ensureToolJSONSchema, isValidToolJSONSchema };
599
+ export { ConnectionState, type CustomMCPTool, type EnhancedToolInfo, type JSONSchema, MCPConnection, MCPManager, type MCPServerTransport, type MCPServiceConfig, type MCPServiceConnectionStatus, type MCPServiceEventCallbacks, MCPManager as MCPServiceManager, type MCPServiceStatus, MCPTransportType, type ManagerStatus, type ModelScopeSSEOptions, ToolCallError, ToolCallErrorCode, type ToolCallParams, type ToolCallResult, type ToolCallValidationOptions, type ToolInfo, TransportFactory, TypeFieldNormalizer, type UnifiedServerConfig, type UnifiedServerStatus, type ValidatedToolCallParams, ensureToolJSONSchema, inferTransportTypeFromConfig, inferTransportTypeFromUrl, isValidToolJSONSchema, normalizeTypeField, validateToolCallParams };