Skip to content

Latest commit

 

History

History
860 lines (704 loc) · 23.9 KB

MCP_DEVELOPER_GUIDE.md

File metadata and controls

860 lines (704 loc) · 23.9 KB

AVG Maker MCP 开发指南

目录

  1. 概述
  2. 架构总览
  3. 内部MCP工具系统
  4. CLI集成架构
  5. 外部MCP服务集成
  6. 开发自定义MCP工具
  7. 最佳实践
  8. 故障排除

概述

AVG Maker 实现了一个现代化的 MCP(Model Context Protocol)架构,专为交互式小说游戏开发优化。系统特色:

  • 14个内部工具:专门为 AVG 开发设计的工具集
  • 模块化架构:基于 MCP SDK 的标准实现
  • 双重集成:支持内部工具和外部MCP服务
  • CLI友好:完整的命令行接口集成
  • 高性能:异步处理、性能监控、缓存优化

架构总览

┌─────────────────────────────────────────────────────────────────┐
│                     AVG Maker MCP 架构                          │
├─────────────────────────────────────────────────────────────────┤
│                                                               │
│  ┌─────────────────┐    ┌──────────────────┐    ┌─────────────┐ │
│  │   CLI 引擎      │    │   MCP 服务器      │    │  外部服务    │ │
│  │                │    │                 │    │            │ │
│  │ SimpleCLIEngine │◄──┤ ToolRegistry    │    │ FileSystem │ │
│  │ InteractionMgr  │    │ ToolFactory     │◄──┤ GitHub     │ │
│  │ ResultFormatter │    │ McpSdkServer    │    │ SQLite     │ │
│  └─────────────────┘    └──────────────────┘    └─────────────┘ │
│           │                       │                            │
│           │ IPC (mcp-request)     │                            │
│           │                       │                            │
│  ┌─────────────────┐    ┌──────────────────┐                   │
│  │   主进程         │    │   14个内部工具    │                   │
│  │                │    │                 │                   │
│  │ ipcMain.handle  │    │ BasicCLITool    │                   │
│  │ MCP Handler     │    │ NodeTreeTool    │                   │
│  │ Project Bridge  │    │ GameControlTool │                   │
│  └─────────────────┘    │ ... 11 more     │                   │
│                         └──────────────────┘                   │
└─────────────────────────────────────────────────────────────────┘

内部MCP工具系统

核心组件

1. MCP SDK Server 集成

位置: electron/mcp/server.js

基于官方 MCP SDK 实现的服务器:

// 动态导入 MCP SDK
const { Server } = await import('@modelcontextprotocol/sdk/server/index.js');

// 创建 MCP SDK Server 实例
mcpSdkServer = new Server(
  {
    name: "avg-maker-mcp-server",
    version: "1.0.0",
  },
  {
    capabilities: {
      resources: {},
      tools: {},
    }
  }
);

2. ToolRegistry (工具注册器)

位置: electron/mcp/tools/ToolRegistry.js

管理所有内部MCP工具的生命周期:

class ToolRegistry {
    constructor() {
        this.tools = new Map();
        this.initialized = false;
    }

    // 自动注册所有可用工具
    registerAllAvailableTools(mcpBridge = null) {
        const validationResults = ToolFactory.validateAllTools();
        const tools = ToolFactory.createAllTools(mcpBridge);
        
        for (const tool of tools) {
            this.register(tool);
        }
    }

    // 获取工具Schema列表
    getToolSchemas() {
        const schemas = [];
        for (const [name, tool] of this.tools) {
            schemas.push(tool.getDefinition());
        }
        return schemas;
    }
}

3. ToolFactory (工具工厂)

位置: electron/mcp/tools/ToolFactory.js

统一创建和管理14个工具实例:

class ToolFactory {
    static getAvailableTools() {
        return [
            BasicCLITool,              // 基础CLI命令
            MCPServiceTool,            // MCP服务管理
            InkCompilerTool,           // Ink脚本编译
            NodeBasicOperationsTool,   // 节点基础操作
            NodeTreeTool,              // 节点树管理
            NodeSearchTool,            // 节点搜索
            NodeContentTool,           // 节点内容管理
            NodeConnectionTool,        // 节点连接
            NodeCreationTool,          // 节点创建
            NodeDeletionTool,          // 节点删除
            NodeEditingTool,           // 节点编辑
            GameControlTool,           // 游戏控制
            ErrorInfoTool,             // 错误信息
            DeadEndDetectorTool        // 死循环检测
        ];
    }
}

14个内部工具详解

工具名称 功能描述 主要操作
BasicCLITool CLI基础命令处理 help, version, echo, clear, exit
MCPServiceTool MCP服务管理 install, uninstall, enable, disable, restart, set-env
InkCompilerTool Ink脚本编译 compile, compileProject, validate
NodeBasicOperationsTool 节点基础操作 getCurrentNode, makeChoice, navigateToHistory
NodeTreeTool 节点树管理 getNodeTree, getNodeStatistics, validateTree
NodeSearchTool 节点搜索 search, find, filter, query
NodeContentTool 节点内容管理 get, update, analyze, parse
NodeConnectionTool 节点连接管理 get, create, remove, validate
NodeCreationTool 节点创建 createNode, createWithContent, duplicate
NodeDeletionTool 节点删除 delete, batchDelete, safeDelete
NodeEditingTool 节点编辑 edit, update, modify, insertContent
GameControlTool 游戏控制 start, pause, reset, save, load
ErrorInfoTool 错误信息管理 get, getByCategory, clear, analyze
DeadEndDetectorTool 死循环检测 detectDeadEnds, analyze, report

IPC 通信机制

直接 MCP 请求处理器

位置: electron/main.ts

// MCP 直接请求处理器
ipcMain.handle('mcp-request', async (_, request: any) => {
    try {
        const mcpSdkServer = mcpServer.mcpSdkServer;
        
        if (mcpSdkServer && mcpSdkServer._requestHandlers) {
            const handlers = mcpSdkServer._requestHandlers;
            const handler = handlers.get(request.method);
            
            if (handler) {
                const mockExtra = {
                    signal: new AbortController().signal,
                    requestId: request.id,
                };
                
                const result = await handler(request, mockExtra);
                return { jsonrpc: '2.0', id: request.id, result: result };
            }
        }
        
        // 回退到工具调用
        if (request.method === 'tools/call') {
            const { name, arguments: args } = request.params;
            const result = await mcpServer.toolRegistry.executeTool(name, args || {});
            return { jsonrpc: '2.0', id: request.id, result: result };
        }
        
    } catch (error) {
        return {
            jsonrpc: '2.0',
            id: request.id,
            error: { code: -1, message: error.message }
        };
    }
});

CLI集成架构

SimpleCLIEngine 集成

位置: src/services/cli/SimpleCLIEngine.ts

CLI引擎通过模块化架构集成MCP工具:

export class SimpleCLIEngine {
    // 核心组件
    private matchers = IntentMatcherFactory.createMatchers();
    private executors = ExecutorFactory.createExecutors();
    private formatter = new ResultFormatter();
    private interactionManager = new InteractionManager();
    private monitor = new PerformanceMonitor();
    private toolProvider = MCPToolProvider.getInstance();

    // 执行命令
    private async executeCommand(input: string, terminal: Terminal): Promise<void> {
        // 1. 意图识别
        const intent = this.identifyIntent(input);
        
        // 2. 选择执行器
        const executor = this.selectExecutor(intent);
        
        // 3. 执行命令
        const result = await executor.execute(intent, this.getContext());
        
        // 4. 格式化输出
        const formattedResult = this.formatter.format(result);
        
        // 5. 显示结果
        terminal.writeln(formattedResult);
    }
}

MCP工具调用流程

  1. 用户输入 → CLI终端
  2. 意图识别 → IntentMatcher
  3. 执行器选择 → ExecutorFactory
  4. MCP调用 → MCPToolExecutor
  5. IPC通信 → electron main process
  6. 工具执行 → ToolRegistry.executeTool()
  7. 结果返回 → ResultFormatter
  8. 终端输出 → Terminal display

函数式语法支持

CLI支持函数式语法调用MCP工具:

# 基础节点操作
> nodeBasicOperations(operation:"getCurrentNode")
> nodeBasicOperations(operation:"makeChoice", choiceIndex:0)

# 节点搜索
> nodeSearch(query:"hello", type:"knot", limit:10)

# 游戏控制
> gameControl(operation:"resetGame")
> gameControl(operation:"save", slotName:"quicksave")

# 死循环检测
> deadEndDetector(operation:"detectDeadEnds", reportLevel:"detailed")

外部MCP服务集成

配置文件

位置: mcp_config/mcp-services.json

{
  "services": [
    {
      "id": "enhanced-filesystem",
      "name": "Enhanced File System",
      "transport": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
      "autoStart": true,
      "enabled": true,
      "description": "Enhanced file operations with safety checks"
    },
    {
      "id": "github",
      "name": "GitHub Integration",
      "transport": "stdio",
      "command": "npx", 
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "autoStart": false,
      "enabled": true,
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  ],
  "settings": {
    "compatibility": {
      "preferInternal": true,
      "fallbackEnabled": true
    },
    "performance": {
      "connectionTimeout": 10000,
      "requestTimeout": 30000
    }
  }
}

CLI 服务管理命令

AVG Maker 提供了完整的 CLI 命令来管理外部 MCP 服务:

服务安装

# 安装 MCP 服务包
> mcp service install @modelcontextprotocol/server-filesystem
> mcp service install @modelcontextprotocol/server-github
> mcp service install @modelcontextprotocol/server-sqlite

# 带选项安装
> mcp service install @modelcontextprotocol/server-brave-search --auto-start --enable

服务管理

# 列出所有服务
> mcp service list

# 启用/禁用服务
> mcp service enable filesystem
> mcp service disable github

# 重启服务
> mcp service restart filesystem

# 卸载服务
> mcp service uninstall sqlite
> mcp service remove brave-search

环境变量管理

# 设置环境变量
> mcp env set GITHUB_TOKEN your_token_here
> mcp env set BRAVE_API_KEY your_api_key

# 查看配置
> mcp service config

函数式语法

# MCP 服务管理的函数式调用
> mcpService(action:"install", packageName:"@modelcontextprotocol/server-filesystem")
> mcpService(action:"enable", serviceId:"filesystem")
> mcpService(action:"set-env", variableName:"GITHUB_TOKEN", variableValue:"token123")
> mcpService(action:"list")

外部服务管理机制

服务管理器支持:

  • 动态连接:根据项目路径启动服务
  • 环境变量:支持 ${VAR} 形式的变量替换
  • 错误恢复:连接失败时自动重试
  • 工作目录:自动设置为当前项目路径
  • 热重载:配置文件修改后自动重启服务

开发自定义MCP工具

创建内部工具

1. 创建工具类

// electron/mcp/tools/MyCustomTool.js
const BaseToolHandler = require('./BaseToolHandler');

class MyCustomTool extends BaseToolHandler {
    constructor() {
        super('myCustomTool', '我的自定义工具描述');
    }

    getSchema() {
        return {
            type: 'object',
            properties: {
                operation: {
                    type: 'string',
                    enum: ['action1', 'action2', 'analyze'],
                    description: '操作类型'
                },
                target: {
                    type: 'string',
                    description: '目标对象'
                },
                options: {
                    type: 'object',
                    properties: {
                        verbose: { type: 'boolean', default: false },
                        format: { type: 'string', default: 'json' }
                    }
                }
            },
            required: ['operation']
        };
    }

    async execute(args) {
        // 使用统一的执行器模板
        return await this.executeWithHandlers(args, {
            action1: this.handleAction1,
            action2: this.handleAction2,
            analyze: this.handleAnalyze
        });
    }

    async handleAction1(args) {
        // 实现具体逻辑
        const { target, options = {} } = args;
        
        // 使用基类提供的游戏状态访问
        const gameState = await this.getGameState();
        
        return this.formatMcpResponse({
            success: true,
            action: 'action1',
            target: target,
            data: gameState.currentNode
        });
    }

    async handleAction2(args) {
        // 另一个操作的实现
        return this.formatMcpResponse({
            success: true,
            message: `执行了 action2: ${args.target}`
        });
    }

    async handleAnalyze(args) {
        // 分析操作
        const nodes = await this.getAllNodes();
        
        return this.formatMcpResponse({
            success: true,
            analysis: {
                totalNodes: nodes.length,
                target: args.target,
                timestamp: new Date().toISOString()
            }
        });
    }
}

module.exports = MyCustomTool;

2. 注册到工厂

// electron/mcp/tools/ToolFactory.js
const MyCustomTool = require('./MyCustomTool');

class ToolFactory {
    static getAvailableTools() {
        return [
            // ... 现有工具
            MyCustomTool, // 添加新工具
        ];
    }
}

3. CLI集成

工具会自动被CLI系统识别:

# 自动发现新工具
> tools

# 函数式调用
> myCustomTool(operation:"action1", target:"test")

# 获取帮助
> help myCustomTool

开发外部MCP服务

1. 创建独立MCP服务器

// my-avg-service/server.js
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const server = new Server(
    {
        name: 'avg-custom-service',
        version: '1.0.0',
    },
    {
        capabilities: {
            tools: {},
        },
    }
);

// 注册工具
server.setRequestHandler('tools/list', async () => {
    return {
        tools: [
            {
                name: 'story_analyzer',
                description: '分析故事结构和质量',
                inputSchema: {
                    type: 'object',
                    properties: {
                        filePath: {
                            type: 'string',
                            description: '故事文件路径'
                        },
                        analysisType: {
                            type: 'string',
                            enum: ['structure', 'quality', 'both'],
                            description: '分析类型'
                        }
                    },
                    required: ['filePath']
                }
            }
        ]
    };
});

server.setRequestHandler('tools/call', async (request) => {
    const { name, arguments: args } = request.params;
    
    if (name === 'story_analyzer') {
        // 实现故事分析逻辑
        const analysis = await analyzeStory(args.filePath, args.analysisType);
        
        return {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify(analysis, null, 2)
                }
            ]
        };
    }
    
    throw new Error(`Unknown tool: ${name}`);
});

async function main() {
    const transport = new StdioServerTransport();
    await server.connect(transport);
}

main().catch(console.error);

2. 添加到配置

使用 CLI 命令安装:

# 如果服务已发布到npm
> mcp service install my-avg-service

# 或手动添加到配置文件

手动配置:

{
  "id": "story-analyzer",
  "name": "Story Analyzer Service",
  "transport": "stdio",
  "command": "node",
  "args": ["./my-avg-service/server.js"],
  "autoStart": true,
  "enabled": true,
  "description": "Advanced story structure analysis"
}

3. CLI 测试

安装后可通过 CLI 测试:

# 验证服务安装
> mcp service list

# 测试工具调用
> tools

# 直接调用自定义工具
> storyAnalyzer(filePath:"main.ink", analysisType:"structure")

最佳实践

工具设计原则

  1. 继承BaseToolHandler:获得统一的错误处理、日志记录、游戏状态访问
  2. 使用executeWithHandlers:标准化操作分发模式
  3. 完善的Schema:详细的参数描述和类型定义
  4. 异步优先:所有I/O操作使用async/await
  5. 错误友好:提供清晰的错误信息和恢复建议

Schema设计规范

getSchema() {
    return {
        type: 'object',
        properties: {
            operation: {
                type: 'string',
                enum: ['action1', 'action2'], // 明确的操作列表
                description: '具体描述每个操作的用途'
            },
            // 使用描述性的参数名
            targetNodeName: { // 而不是 'target'
                type: 'string',
                description: '目标节点的完整名称',
                minLength: 1
            },
            options: {
                type: 'object',
                properties: {
                    includeMetadata: {
                        type: 'boolean',
                        default: false,
                        description: '是否包含节点元数据'
                    }
                }
            }
        },
        required: ['operation'], // 明确必需参数
        examples: [ // 提供使用示例
            {
                operation: 'action1',
                targetNodeName: 'start',
                options: { includeMetadata: true }
            }
        ]
    };
}

错误处理模式

async execute(args) {
    try {
        // 1. 参数验证
        this.validate(args);
        
        // 2. 业务逻辑
        const result = await this.performOperation(args);
        
        // 3. 标准响应
        return this.formatMcpResponse({
            success: true,
            data: result,
            timestamp: new Date().toISOString()
        });
        
    } catch (error) {
        // 4. 统一错误处理
        this.handleError(error, {
            operation: args.operation,
            context: 'tool execution'
        });
        
        return this.formatMcpResponse({
            success: false,
            error: error.message,
            code: error.code || 'EXECUTION_ERROR'
        });
    }
}

性能优化

class MyOptimizedTool extends BaseToolHandler {
    constructor() {
        super('myTool', 'description');
        this.cache = new Map();
        this.cacheTtl = 30000; // 30秒缓存
    }

    async execute(args) {
        // 缓存查询结果
        const cacheKey = JSON.stringify(args);
        const cached = this.cache.get(cacheKey);
        
        if (cached && Date.now() - cached.timestamp < this.cacheTtl) {
            return cached.result;
        }

        const result = await this.performExpensiveOperation(args);
        
        // 缓存结果
        this.cache.set(cacheKey, {
            result: result,
            timestamp: Date.now()
        });

        return result;
    }
}

故障排除

常见问题

1. 工具未注册

# 检查工具是否正确注册
> tools
# 查看工具定义
> mcp list_tools

# 检查控制台日志
Console → ✅ 已注册工具: myTool

2. Schema验证失败

// 确保Schema格式正确
getSchema() {
    return {
        type: 'object', // 必须是 'object'
        properties: {   // 必须有 properties
            operation: {
                type: 'string', // 类型必须正确
                enum: ['valid_op'] // enum值必须匹配
            }
        },
        required: ['operation'] // 必需字段必须存在
    };
}

3. IPC通信错误

// 检查IPC调用格式
const response = await window.electronAPI.cliExecuteCommand({
    id: `request-${Date.now()}`, // 唯一ID
    method: 'tools/call',        // 正确的方法名
    params: {
        name: 'myTool',          // 工具名必须匹配
        arguments: {             // 参数对象
            operation: 'action1'
        }
    },
    timestamp: Date.now()
});

调试工具

1. 启用详细日志

> status verbose=true
> tools debug=true

2. 性能监控

// 查看工具性能统计
const stats = await mcpServer.toolRegistry.getStats();
console.log('Tool performance:', stats);

3. Schema验证测试

// 测试工具Schema
const tool = new MyCustomTool();
const schema = tool.getSchema();
console.log('Schema validation:', ToolFactory.validateToolSchema(schema));

配置验证

外部服务配置检查

# CLI 命令检查服务状态
> mcp service list                    # 列出所有服务
> mcp service config                  # 查看配置详情
> status                             # 查看系统整体状态

# 验证服务配置文件
cat mcp_config/mcp-services.json | jq .

# 测试服务连接
npx @modelcontextprotocol/server-filesystem --help

# 重启有问题的服务
> mcp service restart filesystem
> mcp service restart github

MCP 服务诊断

# 服务连接诊断
> mcp service list --verbose          # 详细服务状态
> tools --debug                      # 调试模式显示工具

# 测试特定服务
> mcp service enable filesystem       # 启用服务
> listFiles(pattern:"*.ink")         # 测试文件系统工具

# 环境变量检查
> mcp env list                       # 列出所有环境变量
> mcp env check GITHUB_TOKEN         # 检查特定变量

环境变量检查

# Windows
echo %GITHUB_TOKEN%

# Unix/Linux
echo $GITHUB_TOKEN

总结

AVG Maker的MCP架构提供了:

  1. 完整的工具生态系统:14个内部工具 + 外部服务支持
  2. 模块化设计:清晰的组件分离和职责划分
  3. CLI深度集成:函数式语法、智能匹配、性能监控
  4. 标准化实现:基于官方MCP SDK,确保兼容性
  5. 开发者友好:完整的工具开发框架和调试支持

这种架构使得AVG Maker既能提供专业的游戏开发功能,又能通过MCP生态系统获得广泛的外部工具支持,真正实现了"AI时代的交互式小说游戏引擎"的定位。