Skip to content

Latest commit

 

History

History
310 lines (252 loc) · 8.08 KB

MCP_RUNTIME_INTENT_INTEGRATION.md

File metadata and controls

310 lines (252 loc) · 8.08 KB

MCP运行时意图配置集成方案

在npm run dev时从运行的MCP Server动态获取tools schema生成意图配置

🎯 方案概述

该方案实现了在开发环境下,当MCP Server启动完成后,自动从运行时的工具注册表中获取所有tools的schema信息,动态生成意图识别配置文件,实现真正的实时同步。

🏗️ 架构设计

核心组件

graph TD
    A[npm run dev] --> B[Electron Main Process]
    B --> C[MCP Server启动]
    C --> D[MCPRuntimeIntentIntegration]
    D --> E[RuntimeMCPIntentGenerator]
    E --> F[获取运行时Tools Schema]
    F --> G[生成意图配置]
    G --> H[保存runtime配置文件]
    H --> I[通知OptimizedRuleStrategy重载]
Loading

关键文件

  1. RuntimeMCPIntentGenerator.ts - 运行时意图生成器核心
  2. MCPRuntimeIntentIntegration.ts - MCP Server集成控制器
  3. main-dev-integration.ts - 主进程集成代码

🚀 集成方式

方法1: 在main.ts中直接集成

import './main-dev-integration'; // 在main.ts顶部添加这一行

// 或者在MCP Server启动完成后调用
import { addRuntimeIntentToExistingMCPServer } from './main-dev-integration';

async function startMcpServer() {
  const mcpServer = await createMcpServer(port);
  
  // 添加运行时意图集成
  addRuntimeIntentToExistingMCPServer(mcpServer);
  
  return mcpServer;
}

方法2: 包装现有的MCP启动函数

import { wrapMCPServerStartup } from './main-dev-integration';

// 包装现有的startMcpServerWithRetry函数
const originalStartMcpServer = startMcpServerWithRetry;
startMcpServerWithRetry = wrapMCPServerStartup(originalStartMcpServer);

🔄 工作流程

1. 开发环境检测

const isDevMode = process.env.NODE_ENV === 'development' || 
                 process.argv.includes('--dev');

2. MCP Server启动监听

当MCP Server启动完成时,自动触发:

ipcMain.emit('mcp-server-initialized', {
  server: mcpServer,
  timestamp: Date.now(),
  port: mcpServer.port
});

3. 运行时Schema获取

// 方法1: 从toolRegistry直接获取
const toolSchemas = mcpServer.toolRegistry.getToolSchemas();

// 方法2: 通过MCP协议获取
const response = await handleMCPRequest({
  method: 'tools/list',
  params: {}
});

4. 动态意图生成

for (const tool of toolDefinitions) {
  const toolIntents = await generateIntentFromToolDefinition(tool);
  intents.push(...toolIntents);
}

5. 配置文件保存

// 保存到 electron/ai-kernel/intent-system/config/intents-runtime.json
await saveRuntimeConfig({
  version: "4.0.0-runtime",
  intents: generatedIntents,
  metadata: {
    generatedFromRuntime: true,
    mcpToolsCount: toolDefinitions.length
  }
});

📊 生成的配置特点

智能Schema解析

  • Operation枚举识别: 自动从properties.operation.enum提取操作类型
  • 参数分析: 从inputSchema.properties推导实体提取模式
  • 描述解析: 从tool描述和operation描述提取语义信息

中英文关键词生成

// 自动映射表
private chineseMapping = new Map([
  ['compile', ['编译', '构建', '生成']],
  ['read', ['读取', '查看', '显示', '打开']],
  ['create', ['创建', '新建', '建立']],
  // ... 更多映射
]);

运行时标记

{
  "intent": "gamecontrol_resetGame", 
  "runtimeGenerated": true,
  "sourceTools": ["GameControlTool"],
  "generationTimestamp": 1672531200000
}

🔧 配置示例

从运行时MCP Server生成的配置示例:

{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "title": "AVG Maker Runtime Generated Intent Configuration", 
  "version": "4.0.0-runtime",
  "lastGenerated": "2024-09-08T10:30:00.000Z",
  "runtimeSource": "MCP Server Runtime",
  "intents": [
    {
      "intent": "inkcompiler_compile",
      "description": "编译操作", 
      "category": "action",
      "keywords": [
        {"term": "compile", "weight": 1.0},
        {"term": "编译", "weight": 1.0},
        {"term": "构建", "weight": 0.9}
      ],
      "runtimeGenerated": true,
      "sourceTools": ["InkCompilerTool"]
    }
  ],
  "metadata": {
    "totalIntents": 65,
    "mcpToolsCount": 12, 
    "generatedFromRuntime": true,
    "mcpServerPort": 3006,
    "generationTimestamp": 1672531200000
  }
}

⚡ 实时更新机制

工具注册监听

// 包装toolRegistry.register方法
const originalRegister = mcpServer.toolRegistry.register;
mcpServer.toolRegistry.register = function(toolHandler) {
  const result = originalRegister.call(this, toolHandler);
  
  // 触发配置重新生成
  ipcMain.emit('mcp-tool-registry-updated', {
    toolName: toolHandler.name,
    toolCount: this.getToolNames().length
  });
  
  return result;
};

防抖机制

private scheduleConfigRegeneration(): void {
  const now = Date.now();
  if (now - this.lastGeneration < 5000) { // 5秒内不重复生成
    return;
  }
  
  setTimeout(() => {
    this.generateRuntimeConfig();
  }, 2000); // 延迟2秒执行
}

周期性检查

setInterval(() => {
  if (this.mcpServerInstance && this.isEnabled) {
    console.log('🔄 周期性检查MCP工具变更...');
    this.generateRuntimeConfig();
  }
}, 30000); // 每30秒检查一次

🎛️ 前端集成

状态监听

// 监听运行时配置更新
ipcRenderer.on('runtime-intent-config-updated', (event, data) => {
  console.log('🔄 运行时意图配置已更新:', data);
  // 重新加载OptimizedRuleStrategy
});

// 监听MCP工具变更
ipcRenderer.on('mcp-runtime-intent-updated', (event, data) => {
  console.log('🆕 发现新工具,意图配置已更新:', data);
});

开发者工具界面

// 获取运行时状态
const status = await ipcRenderer.invoke('get-runtime-intent-status');

// 手动触发生成
const config = await ipcRenderer.invoke('generate-runtime-intents');

🔍 调试和监控

日志输出

🚀 开发模式已启动
📡 MCP Server已初始化: { port: 3006, toolCount: 12 }
🔄 开始生成运行时意图配置...
📊 处理 12 个运行时工具定义...
✅ InkCompilerTool: 生成 4 个意图
✅ GameControlTool: 生成 11 个意图
✅ 运行时配置生成完成: 65 个意图
💾 运行时配置已保存: intents-runtime.json
⏰ 已启动周期性配置生成 (间隔: 30秒)

性能监控

const generationStart = Date.now();
const config = await generateRuntimeConfig();
const generationTime = Date.now() - generationStart;

console.log(`⚡ 运行时配置生成耗时: ${generationTime}ms`);

📈 优势对比

特性 静态Schema读取 运行时Schema获取
同步性 需要手动更新 ✅ 实时自动同步
准确性 可能过时 ✅ 始终最新
工具覆盖 依赖文件扫描 ✅ 获取所有已注册工具
开发体验 需要重启生成 ✅ 热更新
配置完整性 可能遗漏 ✅ 100%覆盖运行时工具

🚀 部署建议

package.json脚本增强

{
  "scripts": {
    "dev": "NODE_ENV=development concurrently \"npm run dev:vite\" \"npm run dev:electron\"",
    "dev:electron": "electron . --dev",
    "dev:with-intent-gen": "NODE_ENV=development MCP_INTENT_RUNTIME=true electron . --dev"
  }
}

环境变量控制

# 启用运行时意图生成
export MCP_INTENT_RUNTIME=true
export NODE_ENV=development

npm run dev

🎯 总结

这个方案实现了:

  1. ✅ 真正的运行时集成 - 直接从MCP Server获取schema
  2. 🔄 实时热更新 - 工具变更时自动重新生成配置
  3. 🎯 零配置维护 - 无需手动维护两套配置文件
  4. ⚡ 开发友好 - 集成到npm run dev流程
  5. 🛡️ 生产安全 - 仅在开发环境启用
  6. 📊 完整覆盖 - 100%覆盖所有已注册的MCP工具

现在,每当您添加新的MCP工具或修改现有工具时,意图识别配置将自动更新,实现真正的"一次定义,处处同步"! 🎉