@mcpilotx/intentorch 0.5.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.
Files changed (101) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +545 -0
  3. package/dist/ai/ai.d.ts +205 -0
  4. package/dist/ai/ai.js +1200 -0
  5. package/dist/ai/cloud-intent-engine.d.ts +270 -0
  6. package/dist/ai/cloud-intent-engine.js +956 -0
  7. package/dist/ai/command.d.ts +59 -0
  8. package/dist/ai/command.js +285 -0
  9. package/dist/ai/config.d.ts +66 -0
  10. package/dist/ai/config.js +211 -0
  11. package/dist/ai/enhanced-intent.d.ts +17 -0
  12. package/dist/ai/enhanced-intent.js +32 -0
  13. package/dist/ai/index.d.ts +29 -0
  14. package/dist/ai/index.js +44 -0
  15. package/dist/ai/intent.d.ts +16 -0
  16. package/dist/ai/intent.js +30 -0
  17. package/dist/core/ai-config.d.ts +25 -0
  18. package/dist/core/ai-config.js +326 -0
  19. package/dist/core/config-manager.d.ts +36 -0
  20. package/dist/core/config-manager.js +400 -0
  21. package/dist/core/config-validator.d.ts +9 -0
  22. package/dist/core/config-validator.js +184 -0
  23. package/dist/core/constants.d.ts +34 -0
  24. package/dist/core/constants.js +37 -0
  25. package/dist/core/error-ai.d.ts +23 -0
  26. package/dist/core/error-ai.js +217 -0
  27. package/dist/core/error-handler.d.ts +197 -0
  28. package/dist/core/error-handler.js +467 -0
  29. package/dist/core/index.d.ts +13 -0
  30. package/dist/core/index.js +17 -0
  31. package/dist/core/logger.d.ts +27 -0
  32. package/dist/core/logger.js +108 -0
  33. package/dist/core/performance-monitor.d.ts +74 -0
  34. package/dist/core/performance-monitor.js +260 -0
  35. package/dist/core/providers.d.ts +36 -0
  36. package/dist/core/providers.js +304 -0
  37. package/dist/core/retry-manager.d.ts +41 -0
  38. package/dist/core/retry-manager.js +204 -0
  39. package/dist/core/types.d.ts +155 -0
  40. package/dist/core/types.js +2 -0
  41. package/dist/daemon/index.d.ts +10 -0
  42. package/dist/daemon/index.js +15 -0
  43. package/dist/daemon/intent-engine.d.ts +22 -0
  44. package/dist/daemon/intent-engine.js +50 -0
  45. package/dist/daemon/orchestrator.d.ts +24 -0
  46. package/dist/daemon/orchestrator.js +100 -0
  47. package/dist/daemon/pm.d.ts +33 -0
  48. package/dist/daemon/pm.js +127 -0
  49. package/dist/daemon/process.d.ts +11 -0
  50. package/dist/daemon/process.js +49 -0
  51. package/dist/daemon/server.d.ts +17 -0
  52. package/dist/daemon/server.js +435 -0
  53. package/dist/daemon/service.d.ts +36 -0
  54. package/dist/daemon/service.js +278 -0
  55. package/dist/index.d.ts +30 -0
  56. package/dist/index.js +36 -0
  57. package/dist/mcp/client.d.ts +51 -0
  58. package/dist/mcp/client.js +276 -0
  59. package/dist/mcp/index.d.ts +162 -0
  60. package/dist/mcp/index.js +199 -0
  61. package/dist/mcp/tool-registry.d.ts +71 -0
  62. package/dist/mcp/tool-registry.js +308 -0
  63. package/dist/mcp/transport.d.ts +83 -0
  64. package/dist/mcp/transport.js +515 -0
  65. package/dist/mcp/types.d.ts +136 -0
  66. package/dist/mcp/types.js +31 -0
  67. package/dist/runtime/adapter-advanced.d.ts +184 -0
  68. package/dist/runtime/adapter-advanced.js +160 -0
  69. package/dist/runtime/adapter.d.ts +9 -0
  70. package/dist/runtime/adapter.js +2 -0
  71. package/dist/runtime/detector-advanced.d.ts +59 -0
  72. package/dist/runtime/detector-advanced.js +487 -0
  73. package/dist/runtime/detector.d.ts +5 -0
  74. package/dist/runtime/detector.js +56 -0
  75. package/dist/runtime/docker-adapter.d.ts +18 -0
  76. package/dist/runtime/docker-adapter.js +170 -0
  77. package/dist/runtime/docker.d.ts +17 -0
  78. package/dist/runtime/docker.js +71 -0
  79. package/dist/runtime/executable-analyzer.d.ts +56 -0
  80. package/dist/runtime/executable-analyzer.js +391 -0
  81. package/dist/runtime/go-adapter.d.ts +19 -0
  82. package/dist/runtime/go-adapter.js +190 -0
  83. package/dist/runtime/index.d.ts +9 -0
  84. package/dist/runtime/index.js +10 -0
  85. package/dist/runtime/node-adapter.d.ts +10 -0
  86. package/dist/runtime/node-adapter.js +23 -0
  87. package/dist/runtime/node.d.ts +20 -0
  88. package/dist/runtime/node.js +86 -0
  89. package/dist/runtime/python-adapter.d.ts +11 -0
  90. package/dist/runtime/python-adapter.js +102 -0
  91. package/dist/runtime/python.d.ts +17 -0
  92. package/dist/runtime/python.js +72 -0
  93. package/dist/runtime/rust-adapter.d.ts +21 -0
  94. package/dist/runtime/rust-adapter.js +267 -0
  95. package/dist/sdk.d.ts +500 -0
  96. package/dist/sdk.js +904 -0
  97. package/docs/README.ZH_CN.md +545 -0
  98. package/docs/api.md +888 -0
  99. package/docs/architecture.md +731 -0
  100. package/docs/development.md +744 -0
  101. package/package.json +112 -0
@@ -0,0 +1,744 @@
1
+ # 开发指南
2
+
3
+ ## 概述
4
+
5
+ 本文档为 IntentOrch SDK Core 的开发者提供详细的开发指南,包括环境设置、代码结构、开发流程、测试和贡献指南。
6
+
7
+ ## 开发环境设置
8
+
9
+ ### 系统要求
10
+
11
+ - **Node.js**: 18.x 或更高版本
12
+ - **npm**: 9.x 或更高版本(或 yarn/pnpm)
13
+ - **TypeScript**: 5.x 或更高版本
14
+ - **Git**: 版本控制系统
15
+
16
+ ### 环境设置步骤
17
+
18
+ 1. **克隆仓库**
19
+
20
+ ```bash
21
+ git clone https://github.com/MCPilotX/IntentOrch.git
22
+ cd IntentOrch
23
+ ```
24
+
25
+ 2. **安装依赖**
26
+
27
+ ```bash
28
+ npm install
29
+ # 或使用 yarn
30
+ yarn install
31
+ # 或使用 pnpm
32
+ pnpm install
33
+ ```
34
+
35
+ 3. **构建项目**
36
+
37
+ ```bash
38
+ npm run build
39
+ ```
40
+
41
+ 4. **运行测试**
42
+
43
+ ```bash
44
+ npm test
45
+ ```
46
+
47
+ ### 开发工具推荐
48
+
49
+ - **编辑器**: VS Code 或 WebStorm
50
+ - **TypeScript 插件**: 确保 TypeScript 支持
51
+ - **ESLint**: 代码质量检查
52
+ - **Prettier**: 代码格式化
53
+ - **Jest**: 测试运行器
54
+
55
+ ## 项目结构
56
+
57
+ ### 目录结构
58
+
59
+ ```
60
+ intentorch/
61
+ ├── src/ # 源代码
62
+ │ ├── index.ts # 主入口文件
63
+ │ ├── sdk.ts # SDK 主类
64
+ │ ├── ai/ # AI 集成模块
65
+ │ │ ├── ai.ts # AI 核心功能
66
+ │ │ ├── cloud-intent-engine.ts # 云意图引擎
67
+ │ │ ├── command.ts # 命令处理
68
+ │ │ ├── config.ts # AI 配置
69
+ │ │ ├── enhanced-intent.ts # 增强意图识别
70
+ │ │ ├── index.ts # AI 模块导出
71
+ │ │ └── intent.ts # 意图处理
72
+ │ ├── core/ # 核心功能模块
73
+ │ │ ├── ai-config.ts # AI 配置管理
74
+ │ │ ├── config-manager.ts # 配置管理器
75
+ │ │ ├── config-validator.ts # 配置验证器
76
+ │ │ ├── constants.ts # 常量定义
77
+ │ │ ├── error-ai.ts # AI 错误处理
78
+ │ │ ├── error-handler.ts # 错误处理器
79
+ │ │ ├── index.ts # 核心模块导出
80
+ │ │ ├── logger.ts # 日志系统
81
+ │ │ ├── performance-monitor.ts # 性能监控
82
+ │ │ ├── providers.ts # 服务提供商
83
+ │ │ ├── retry-manager.ts # 重试管理器
84
+ │ │ └── types.ts # 类型定义
85
+ │ ├── daemon/ # 守护进程功能
86
+ │ │ ├── index.ts # 守护进程模块导出
87
+ │ │ ├── intent-engine.ts # 意图引擎
88
+ │ │ ├── orchestrator.ts # 编排器
89
+ │ │ ├── pm.ts # 进程管理
90
+ │ │ ├── process.ts # 进程处理
91
+ │ │ ├── server.ts # 服务器
92
+ │ │ └── service.ts # 服务管理
93
+ │ ├── mcp/ # MCP 协议模块
94
+ │ │ ├── client.ts # MCP 客户端
95
+ │ │ ├── index.ts # MCP 模块导出
96
+ │ │ ├── tool-registry.ts # 工具注册表
97
+ │ │ ├── transport.ts # 传输层
98
+ │ │ └── types.ts # MCP 类型定义
99
+ │ └── runtime/ # 运行时适配器
100
+ │ ├── adapter-advanced.ts # 高级适配器
101
+ │ ├── adapter.ts # 基础适配器接口
102
+ │ ├── detector-advanced.ts # 高级检测器
103
+ │ ├── detector.ts # 运行时检测器
104
+ │ ├── docker-adapter.ts # Docker 适配器
105
+ │ ├── docker.ts # Docker 运行时
106
+ │ ├── executable-analyzer.ts # 可执行文件分析器
107
+ │ ├── go-adapter.ts # Go 适配器
108
+ │ ├── index.ts # 运行时模块导出
109
+ │ ├── node-adapter.ts # Node.js 适配器
110
+ │ ├── node.ts # Node.js 运行时
111
+ │ ├── python-adapter.ts # Python 适配器
112
+ │ ├── python.ts # Python 运行时
113
+ │ ├── rust-adapter.ts # Rust 适配器
114
+ │ └── rust.ts # Rust 运行时
115
+ ├── tests/ # 测试文件(实际目录)
116
+ │ ├── improvements.test.ts
117
+ │ ├── logger.test.ts
118
+ │ ├── sdk-simple.test.ts
119
+ │ ├── sdk.test.ts
120
+ │ └── setup.ts
121
+ ├── examples/ # 示例代码
122
+ │ ├── 1-basic-sdk-usage.js
123
+ │ ├── 2-ai-integration.js
124
+ │ ├── 3-mcp-tools.js
125
+ │ ├── analyze-readme-example.ts
126
+ │ ├── basic-usage.ts
127
+ │ ├── cloud-intent-engine-demo.ts
128
+ │ ├── developer-starter-kit.js
129
+ │ ├── end-to-end-test.ts
130
+ │ ├── enhanced-intent-tracking-demo.ts
131
+ │ ├── filesystem-server-demo.ts
132
+ │ ├── fix-ask-method-example.ts
133
+ │ ├── http-transport-demo.ts
134
+ │ ├── improved-stdio-transport.ts
135
+ │ ├── mcp-integration-test.js
136
+ │ ├── mcp-tool-discovery.md
137
+ │ ├── mock-filesystem-server.cjs
138
+ │ ├── mock-mcp-server.js
139
+ │ ├── quick-test.js
140
+ │ ├── real-world-scenarios.ts
141
+ │ ├── run-all-examples.sh
142
+ │ └── zero-config-demo.ts
143
+ ├── docs/ # 文档
144
+ │ ├── api.md
145
+ │ ├── architecture.md
146
+ │ ├── development.md
147
+ │ └── README.ZH_CN.md
148
+ ├── dist/ # 构建输出
149
+ ├── package.json # 项目配置
150
+ ├── tsconfig.json # TypeScript 配置
151
+ ├── jest.config.js # Jest 配置
152
+ └── README.md # 项目说明
153
+ ```
154
+
155
+ ### 代码组织原则
156
+
157
+ 1. **单一职责**: 每个文件/类只负责一个功能
158
+ 2. **模块化**: 相关功能组织在同一目录
159
+ 3. **依赖注入**: 通过构造函数注入依赖
160
+ 4. **接口隔离**: 使用接口定义契约
161
+
162
+ ## 开发流程
163
+
164
+ ### 1. 功能开发
165
+
166
+ #### 创建新功能
167
+
168
+ 1. **分析需求**: 明确功能目标和范围
169
+ 2. **设计接口**: 设计公共 API 接口
170
+ 3. **实现功能**: 编写实现代码
171
+ 4. **编写测试**: 创建单元测试
172
+ 5. **更新文档**: 更新 API 文档
173
+
174
+ #### 示例:添加新的运行时适配器
175
+
176
+ ```typescript
177
+ // 1. 创建适配器类
178
+ import { RuntimeAdapter, ServiceConfig, ProcessInfo, ServiceStatus } from '../runtime/adapter';
179
+
180
+ export class GoRuntimeAdapter implements RuntimeAdapter {
181
+ async start(config: ServiceConfig): Promise<ProcessInfo> {
182
+ // 实现 Go 服务启动逻辑
183
+ return {
184
+ id: `go-${Date.now()}`,
185
+ pid: 12345,
186
+ status: 'running',
187
+ startedAt: new Date(),
188
+ config
189
+ };
190
+ }
191
+
192
+ async stop(processId: string): Promise<void> {
193
+ // 实现 Go 服务停止逻辑
194
+ }
195
+
196
+ async status(processId: string): Promise<ServiceStatus> {
197
+ // 实现状态检查逻辑
198
+ return {
199
+ running: true,
200
+ pid: 12345,
201
+ uptime: 3600000,
202
+ memory: 1024 * 1024 * 50, // 50MB
203
+ cpu: 0.3
204
+ };
205
+ }
206
+
207
+ supports(runtimeType: string): boolean {
208
+ return runtimeType === 'go';
209
+ }
210
+ }
211
+
212
+ // 2. 注册适配器
213
+ import { RuntimeAdapterRegistry } from '../runtime/adapter-advanced';
214
+
215
+ RuntimeAdapterRegistry.registerAdapter('go', GoRuntimeAdapter);
216
+ ```
217
+
218
+ ### 2. 代码规范
219
+
220
+ #### TypeScript 规范
221
+
222
+ - 使用严格模式 (`strict: true`)
223
+ - 明确的类型注解
224
+ - 避免使用 `any` 类型
225
+ - 使用接口定义数据结构
226
+
227
+ ```typescript
228
+ // 好的示例
229
+ interface UserConfig {
230
+ name: string;
231
+ age: number;
232
+ email?: string;
233
+ }
234
+
235
+ function createUser(config: UserConfig): User {
236
+ // 实现
237
+ }
238
+
239
+ // 避免的示例
240
+ function createUser(config: any): any {
241
+ // 实现
242
+ }
243
+ ```
244
+
245
+ #### 命名规范
246
+
247
+ - **类名**: PascalCase (例如: `MCPilotSDK`)
248
+ - **方法名**: camelCase (例如: `executeTool`)
249
+ - **变量名**: camelCase (例如: `serviceConfig`)
250
+ - **常量名**: UPPER_SNAKE_CASE (例如: `MAX_RETRIES`)
251
+ - **接口名**: PascalCase,前缀 `I` 可选 (例如: `IServiceConfig` 或 `ServiceConfig`)
252
+
253
+ #### 错误处理
254
+
255
+ - 使用自定义错误类
256
+ - 提供有意义的错误信息
257
+ - 包含错误代码和重试建议
258
+
259
+ ```typescript
260
+ class MCPilotError extends Error {
261
+ constructor(
262
+ message: string,
263
+ public code: string,
264
+ public shouldRetry: boolean = false
265
+ ) {
266
+ super(message);
267
+ this.name = 'MCPilotError';
268
+ }
269
+ }
270
+
271
+ // 使用示例
272
+ throw new MCPilotError('Connection failed', 'CONNECTION_ERROR', true);
273
+ ```
274
+
275
+ ### 3. 测试开发
276
+
277
+ #### 单元测试
278
+
279
+ 使用 Jest 编写单元测试:
280
+
281
+ ```typescript
282
+ import { MCPilotSDK } from '../src/sdk';
283
+ import { describe, it, expect, beforeEach, afterEach } from '@jest/globals';
284
+
285
+ describe('MCPilotSDK', () => {
286
+ let sdk: MCPilotSDK;
287
+
288
+ beforeEach(() => {
289
+ sdk = new MCPilotSDK({ autoInit: false });
290
+ });
291
+
292
+ afterEach(() => {
293
+ // 清理资源
294
+ });
295
+
296
+ describe('init', () => {
297
+ it('should initialize successfully', async () => {
298
+ await expect(sdk.init()).resolves.not.toThrow();
299
+ });
300
+
301
+ it('should throw error when already initialized', async () => {
302
+ await sdk.init();
303
+ await expect(sdk.init()).rejects.toThrow('Already initialized');
304
+ });
305
+ });
306
+
307
+ describe('executeTool', () => {
308
+ it('should execute tool successfully', async () => {
309
+ // 模拟工具执行
310
+ const result = await sdk.executeTool('mock_tool', { param: 'value' });
311
+ expect(result.isError).toBe(false);
312
+ expect(result.content).toHaveLength(1);
313
+ });
314
+
315
+ it('should throw error for non-existent tool', async () => {
316
+ await expect(
317
+ sdk.executeTool('non_existent_tool', {})
318
+ ).rejects.toThrow('Tool not found');
319
+ });
320
+ });
321
+ });
322
+ ```
323
+
324
+ #### 集成测试
325
+
326
+ ```typescript
327
+ import { mcpilot } from '../src';
328
+ import { describe, it, expect, beforeAll, afterAll } from '@jest/globals';
329
+
330
+ describe('Integration Tests', () => {
331
+ beforeAll(async () => {
332
+ // 启动测试服务器
333
+ });
334
+
335
+ afterAll(async () => {
336
+ // 停止测试服务器
337
+ });
338
+
339
+ it('should connect to MCP server and list tools', async () => {
340
+ await mcpilot.initMCP();
341
+
342
+ await mcpilot.connectMCPServer({
343
+ transport: {
344
+ type: 'stdio',
345
+ command: 'node',
346
+ args: ['examples/mock-mcp-server.js']
347
+ }
348
+ }, 'test-server');
349
+
350
+ const tools = mcpilot.listTools();
351
+ expect(tools.length).toBeGreaterThan(0);
352
+ expect(tools[0]).toHaveProperty('name');
353
+ expect(tools[0]).toHaveProperty('description');
354
+ });
355
+ });
356
+ ```
357
+
358
+ #### 测试覆盖率
359
+
360
+ 运行测试覆盖率检查:
361
+
362
+ ```bash
363
+ npm test -- --coverage
364
+ ```
365
+
366
+ 目标覆盖率:
367
+ - 语句覆盖率: > 85%
368
+ - 分支覆盖率: > 80%
369
+ - 函数覆盖率: > 85%
370
+ - 行覆盖率: > 85%
371
+
372
+ ### 4. 文档更新
373
+
374
+ #### API 文档
375
+
376
+ 更新 API 文档时:
377
+ 1. 添加新方法的文档
378
+ 2. 更新类型定义
379
+ 3. 提供使用示例
380
+ 4. 说明错误情况
381
+
382
+ #### 示例代码
383
+
384
+ 为每个新功能添加示例:
385
+
386
+ ```typescript
387
+ // examples/new-feature-usage.ts
388
+ import { mcpilot } from '@mcpilotx/intentorch';
389
+
390
+ async function demonstrateNewFeature() {
391
+ // 初始化 SDK
392
+ await mcpilot.initMCP();
393
+
394
+ // 使用新功能
395
+ const result = await mcpilot.newFeatureMethod({
396
+ param1: 'value1',
397
+ param2: 'value2'
398
+ });
399
+
400
+ console.log('Result:', result);
401
+
402
+ // 清理
403
+ await mcpilot.cleanup();
404
+ }
405
+
406
+ demonstrateNewFeature().catch(console.error);
407
+ ```
408
+
409
+ ## 构建和发布
410
+
411
+ ### 开发构建
412
+
413
+ ```bash
414
+ # 开发构建(TypeScript 编译 + 导入扩展处理)
415
+ npm run build
416
+
417
+ # 清理构建输出
418
+ npm run clean
419
+
420
+ # 运行测试
421
+ npm test
422
+
423
+ # 监视模式运行测试
424
+ npm run test:watch
425
+
426
+ # 代码检查
427
+ npm run lint
428
+ ```
429
+
430
+ ### 文档相关命令
431
+
432
+ ```bash
433
+ # 验证文档一致性
434
+ npm run docs:validate
435
+
436
+ # 准备文档发布
437
+ npm run docs:prepare
438
+
439
+ # 同步所有文档
440
+ npm run docs:sync
441
+
442
+ # 验证文档
443
+ npm run docs:verify
444
+ ```
445
+
446
+ ### 发布流程
447
+
448
+ 1. **版本管理**
449
+
450
+ ```bash
451
+ # 更新版本号
452
+ npm version patch # 修复版本
453
+ npm version minor # 小版本
454
+ npm version major # 大版本
455
+ ```
456
+
457
+ 2. **构建发布包**
458
+
459
+ ```bash
460
+ # 运行测试
461
+ npm test
462
+
463
+ # 构建生产版本
464
+ npm run build:prod
465
+
466
+ # 准备发布
467
+ npm run prepublishOnly
468
+ ```
469
+
470
+ 3. **发布到 npm**
471
+
472
+ ```bash
473
+ # 发布到 npm
474
+ npm publish --access public
475
+ ```
476
+
477
+ ### 版本策略
478
+
479
+ - **主版本 (Major)**: 不兼容的 API 变更
480
+ - **次版本 (Minor)**: 向后兼容的功能添加
481
+ - **修订版本 (Patch)**: 向后兼容的错误修复
482
+
483
+ ## 调试技巧
484
+
485
+ ### 1. 日志调试
486
+
487
+ 启用调试日志:
488
+
489
+ ```typescript
490
+ const sdk = new MCPilotSDK({
491
+ logger: {
492
+ info: (msg) => console.log(`[INFO] ${msg}`),
493
+ error: (msg) => console.error(`[ERROR] ${msg}`),
494
+ debug: (msg) => console.debug(`[DEBUG] ${msg}`),
495
+ }
496
+ });
497
+ ```
498
+
499
+ ### 2. TypeScript 调试
500
+
501
+ 使用 VS Code 调试配置:
502
+
503
+ ```json
504
+ {
505
+ "version": "0.2.0",
506
+ "configurations": [
507
+ {
508
+ "type": "node",
509
+ "request": "launch",
510
+ "name": "Debug Tests",
511
+ "program": "${workspaceFolder}/node_modules/.bin/jest",
512
+ "args": ["--runInBand"],
513
+ "console": "integratedTerminal",
514
+ "internalConsoleOptions": "neverOpen",
515
+ "disableOptimisticBPs": true
516
+ },
517
+ {
518
+ "type": "node",
519
+ "request": "launch",
520
+ "name": "Debug Example",
521
+ "program": "${workspaceFolder}/examples/basic-usage.ts",
522
+ "runtimeArgs": ["-r", "ts-node/register"],
523
+ "console": "integratedTerminal"
524
+ }
525
+ ]
526
+ }
527
+ ```
528
+
529
+ ### 3. 网络调试
530
+
531
+ 调试 MCP 通信:
532
+
533
+ ```typescript
534
+ // 启用详细日志
535
+ const sdk = new MCPilotSDK({
536
+ mcp: {
537
+ debug: true, // 启用调试模式
538
+ servers: [
539
+ {
540
+ transport: {
541
+ type: 'stdio',
542
+ command: 'npx',
543
+ args: ['@modelcontextprotocol/server-filesystem'],
544
+ env: {
545
+ DEBUG: 'mcp:*' // 启用服务器调试
546
+ }
547
+ }
548
+ }
549
+ ]
550
+ }
551
+ });
552
+ ```
553
+
554
+ ## 性能优化
555
+
556
+ ### 1. 工具缓存
557
+
558
+ 实现工具缓存机制:
559
+
560
+ ```typescript
561
+ class ToolRegistry {
562
+ private toolCache = new Map<string, Tool>();
563
+ private cacheTTL = 5 * 60 * 1000; // 5分钟
564
+
565
+ async getTool(name: string): Promise<Tool | null> {
566
+ const cached = this.toolCache.get(name);
567
+
568
+ if (cached && Date.now() - cached.cachedAt < this.cacheTTL) {
569
+ return cached.tool;
570
+ }
571
+
572
+ // 从服务器获取工具
573
+ const tool = await this.fetchToolFromServer(name);
574
+ if (tool) {
575
+ this.toolCache.set(name, {
576
+ tool,
577
+ cachedAt: Date.now()
578
+ });
579
+ }
580
+
581
+ return tool;
582
+ }
583
+ }
584
+ ```
585
+
586
+ ### 2. 连接池
587
+
588
+ 管理 MCP 连接:
589
+
590
+ ```typescript
591
+ class ConnectionPool {
592
+ private connections: Map<string, MCPClient[]> = new Map();
593
+ private maxConnections = 10;
594
+
595
+ async getConnection(serverName: string): Promise<MCPClient> {
596
+ const pool = this.connections.get(serverName) || [];
597
+
598
+ // 查找空闲连接
599
+ const available = pool.filter(conn => !conn.isBusy);
600
+ if (available.length > 0) {
601
+ return available[0];
602
+ }
603
+
604
+ // 创建新连接
605
+ if (pool.length < this.maxConnections) {
606
+ const newConn = await this.createConnection(serverName);
607
+ pool.push(newConn);
608
+ this.connections.set(serverName, pool);
609
+ return newConn;
610
+ }
611
+
612
+ // 等待连接释放
613
+ return this.waitForConnection(serverName);
614
+ }
615
+ }
616
+ ```
617
+
618
+ ### 3. 批量操作
619
+
620
+ 优化批量工具执行:
621
+
622
+ ```typescript
623
+ async function executeToolsInBatch(
624
+ toolCalls: Array<{ name: string; args: any }>,
625
+ batchSize = 5
626
+ ): Promise<ToolResult[]> {
627
+ const results: ToolResult[] = [];
628
+
629
+ for (let i = 0; i < toolCalls.length; i += batchSize) {
630
+ const batch = toolCalls.slice(i, i + batchSize);
631
+ const batchResults = await Promise.all(
632
+ batch.map(({ name, args }) => sdk.executeTool(name, args))
633
+ );
634
+ results.push(...batchResults);
635
+ }
636
+
637
+ return results;
638
+ }
639
+ ```
640
+
641
+ ## 错误处理和监控
642
+
643
+ ### 1. 错误追踪
644
+
645
+ 实现错误追踪:
646
+
647
+ ```typescript
648
+ class ErrorTracker {
649
+ private errors: Array<{
650
+ timestamp: Date;
651
+ error: Error;
652
+ context: Record<string, any>;
653
+ }> = [];
654
+
655
+ trackError(error: Error, context: Record<string, any> = {}) {
656
+ this.errors.push({
657
+ timestamp: new Date(),
658
+ error,
659
+ context
660
+ });
661
+
662
+ // 限制错误数量
663
+ if (this.errors.length > 1000) {
664
+ this.errors = this.errors.slice(-1000);
665
+ }
666
+
667
+ // 发送到监控服务(可选)
668
+ this.sendToMonitoring(error, context);
669
+ }
670
+
671
+ getErrorStats(): ErrorStatistics {
672
+ const lastHour = this.errors.filter(
673
+ e => Date.now() - e.timestamp.getTime() < 3600000
674
+ );
675
+
676
+ return {
677
+ totalErrors: this.errors.length,
678
+ lastHourErrors: lastHour.length,
679
+ errorTypes: this.groupByErrorType(lastHour),
680
+ mostCommonContext: this.findMostCommonContext(lastHour)
681
+ };
682
+ }
683
+ }
684
+ ```
685
+
686
+ ### 2. 性能监控
687
+
688
+ 监控 SDK 性能:
689
+
690
+ ```typescript
691
+ class PerformanceMonitor {
692
+ private metrics: Map<string, PerformanceMetric[]> = new Map();
693
+
694
+ startMeasurement(operation: string): () => void {
695
+ const startTime = performance.now();
696
+
697
+ return () => {
698
+ const duration = performance.now() - startTime;
699
+ this.recordMetric(operation, duration);
700
+ };
701
+ }
702
+
703
+ private recordMetric(operation: string, duration: number) {
704
+ const metrics = this.metrics.get(operation) || [];
705
+ metrics.push({
706
+ timestamp: new Date(),
707
+ duration,
708
+ success: true
709
+ });
710
+
711
+ this.metrics.set(operation, metrics.slice(-100)); // 保留最近100个
712
+ }
713
+
714
+ getPerformanceReport(): PerformanceReport {
715
+ const report: PerformanceReport = {};
716
+
717
+ for (const [operation, metrics] of this.metrics) {
718
+ const durations = metrics.map(m => m.duration);
719
+ report[operation] = {
720
+ count: metrics.length,
721
+ avgDuration: durations.reduce((a, b) => a + b, 0) / durations.length,
722
+ p95Duration: this.percentile(durations, 95),
723
+ p99Duration: this.percentile(durations, 99),
724
+ minDuration: Math.min(...durations),
725
+ maxDuration: Math.max(...durations)
726
+ };
727
+ }
728
+
729
+ return report;
730
+ }
731
+ }
732
+ ```
733
+
734
+ ## 贡献指南
735
+
736
+ ### 1. 贡献流程
737
+
738
+ 1. **Fork 仓库**: 创建个人 fork
739
+ 2. **创建分支**: 基于 main 创建功能分支
740
+ 3. **开发功能**: 实现新功能或修复错误
741
+ 4. **编写测试**: 添加相应的测试
742
+ 5. **运行测试**: 确保所有测试通过
743
+ 6. **提交更改**: 使用规范的提交信息
744
+ 7. **创建 PR**: 提交 Pull Request