MonkeyCode icon indicating copy to clipboard operation
MonkeyCode copied to clipboard

怎么设置MCP、怎么设置系统提示词

Open tabtan99 opened this issue 5 months ago • 4 comments

怎么设置MCP、怎么设置系统提示词

tabtan99 avatar Jul 25 '25 04:07 tabtan99

1. 项目目录下创建 .roo/mcp.json。For example:

{
  "mcpServers": {
    "python-mcp-server": {
      "type": "stdio",
      "command": "python3",
      "args": ["local_mcp_server.py"],
      "cwd": "/Users/caiqj/project/company/monkeyCode/mcp",
      "timeout": 60,
      "disabled": false,
      "alwaysAllow": ["get_current_time", "get_system_info", "file_operations"],
      "watchPaths": ["local_mcp_server.py"]
    }
  }
}

2. 启动 mcp server: local_mcp_server.py

#!/usr/bin/env python3
"""
简单的 Python MCP Server 示例
支持工具调用和资源访问
"""

import json
import sys
import os
from typing import Dict, Any, List
from datetime import datetime

class SimpleMcpServer:
    def __init__(self):
        self.server_name = "simple-python-mcp"
        self.version = "1.0.0"
        
    def handle_initialize(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """处理初始化请求"""
        return {
            "protocolVersion": "2024-11-05",
            "capabilities": {
                "tools": {},
                "resources": {},
                "prompts": {}
            },
            "serverInfo": {
                "name": self.server_name,
                "version": self.version
            }
        }
    
    def handle_tools_list(self) -> Dict[str, Any]:
        """列出可用工具"""
        return {
            "tools": [
                {
                    "name": "get_current_time",
                    "description": "获取当前时间",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "format": {
                                "type": "string",
                                "description": "时间格式 (iso, timestamp, readable)",
                                "default": "readable"
                            }
                        }
                    }
                },
                {
                    "name": "get_system_info",
                    "description": "获取系统信息",
                    "inputSchema": {
                        "type": "object",
                        "properties": {}
                    }
                },
                {
                    "name": "file_operations",
                    "description": "文件操作工具",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "operation": {
                                "type": "string",
                                "enum": ["read", "write", "list", "exists"],
                                "description": "操作类型"
                            },
                            "path": {
                                "type": "string",
                                "description": "文件路径"
                            },
                            "content": {
                                "type": "string",
                                "description": "写入内容(仅写操作需要)"
                            }
                        },
                        "required": ["operation", "path"]
                    }
                }
            ]
        }
    
    def handle_tool_call(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        """处理工具调用"""
        if name == "get_current_time":
            return self._get_current_time(arguments)
        elif name == "get_system_info":
            return self._get_system_info()
        elif name == "file_operations":
            return self._file_operations(arguments)
        else:
            raise ValueError(f"未知工具: {name}")
    
    def _get_current_time(self, args: Dict[str, Any]) -> Dict[str, Any]:
        """获取当前时间"""
        format_type = args.get("format", "readable")
        now = datetime.now()
        
        if format_type == "iso":
            time_str = now.isoformat()
        elif format_type == "timestamp":
            time_str = str(now.timestamp())
        else:  # readable
            time_str = now.strftime("%Y-%m-%d %H:%M:%S")
        
        return {
            "content": [
                {
                    "type": "text",
                    "text": f"当前时间: {time_str}"
                }
            ]
        }
    
    def _get_system_info(self) -> Dict[str, Any]:
        """获取系统信息"""
        import platform
        
        info = {
            "系统": platform.system(),
            "版本": platform.version(),
            "架构": platform.machine(),
            "处理器": platform.processor(),
            "Python版本": platform.python_version(),
            "工作目录": os.getcwd()
        }
        
        return {
            "content": [
                {
                    "type": "text",
                    "text": json.dumps(info, ensure_ascii=False, indent=2)
                }
            ]
        }
    
    def _file_operations(self, args: Dict[str, Any]) -> Dict[str, Any]:
        """文件操作"""
        operation = args["operation"]
        path = args["path"]
        
        try:
            if operation == "read":
                if os.path.exists(path):
                    with open(path, 'r', encoding='utf-8') as f:
                        content = f.read()
                    return {
                        "content": [
                            {
                                "type": "text",
                                "text": f"文件内容:\n{content}"
                            }
                        ]
                    }
                else:
                    return {
                        "content": [
                            {
                                "type": "text",
                                "text": f"文件不存在: {path}"
                            }
                        ]
                    }
            
            elif operation == "write":
                content = args.get("content", "")
                with open(path, 'w', encoding='utf-8') as f:
                    f.write(content)
                return {
                    "content": [
                        {
                            "type": "text",
                            "text": f"文件已写入: {path}"
                        }
                    ]
                }
            
            elif operation == "list":
                if os.path.isdir(path):
                    files = os.listdir(path)
                    return {
                        "content": [
                            {
                                "type": "text",
                                "text": f"目录内容:\n" + "\n".join(files)
                            }
                        ]
                    }
                else:
                    return {
                        "content": [
                            {
                                "type": "text",
                                "text": f"不是目录: {path}"
                            }
                        ]
                    }
            
            elif operation == "exists":
                exists = os.path.exists(path)
                return {
                    "content": [
                        {
                            "type": "text",
                            "text": f"文件存在: {exists}"
                        }
                    ]
                }
        
        except Exception as e:
            return {
                "content": [
                    {
                        "type": "text",
                        "text": f"操作失败: {str(e)}"
                    }
                ]
            }
    
    def handle_resources_list(self) -> Dict[str, Any]:
        """列出可用资源"""
        return {
            "resources": [
                {
                    "uri": "file:///tmp/example.txt",
                    "name": "示例文件",
                    "description": "一个示例文本文件",
                    "mimeType": "text/plain"
                }
            ]
        }
    
    def handle_resource_read(self, uri: str) -> Dict[str, Any]:
        """读取资源"""
        if uri == "file:///tmp/example.txt":
            # 创建示例文件
            os.makedirs("/tmp", exist_ok=True)
            with open("/tmp/example.txt", "w", encoding="utf-8") as f:
                f.write("这是一个示例文件的内容。\n由 Python MCP Server 创建。")
            
            with open("/tmp/example.txt", "r", encoding="utf-8") as f:
                content = f.read()
            
            return {
                "contents": [
                    {
                        "uri": uri,
                        "mimeType": "text/plain",
                        "text": content
                    }
                ]
            }
        
        return {
            "contents": [
                {
                    "uri": uri,
                    "mimeType": "text/plain",
                    "text": f"无法读取资源: {uri}"
                }
            ]
        }

def main():
    """主函数 - 处理 MCP 协议"""
    server = SimpleMcpServer()
    
    # 读取初始化请求
    init_request = json.loads(sys.stdin.readline())
    
    if init_request["method"] == "initialize":
        # 发送初始化响应
        response = {
            "jsonrpc": "2.0",
            "id": init_request["id"],
            "result": server.handle_initialize(init_request["params"])
        }
        print(json.dumps(response))
        sys.stdout.flush()
    
    # 主循环
    while True:
        try:
            line = sys.stdin.readline()
            if not line:
                break
            
            request = json.loads(line)
            method = request.get("method")
            params = request.get("params", {})
            
            if method == "tools/list":
                response = {
                    "jsonrpc": "2.0",
                    "id": request["id"],
                    "result": server.handle_tools_list()
                }
            
            elif method == "tools/call":
                tool_name = params["name"]
                arguments = params.get("arguments", {})
                response = {
                    "jsonrpc": "2.0",
                    "id": request["id"],
                    "result": server.handle_tool_call(tool_name, arguments)
                }
            
            elif method == "resources/list":
                response = {
                    "jsonrpc": "2.0",
                    "id": request["id"],
                    "result": server.handle_resources_list()
                }
            
            elif method == "resources/read":
                uri = params["uri"]
                response = {
                    "jsonrpc": "2.0",
                    "id": request["id"],
                    "result": server.handle_resource_read(uri)
                }
            
            else:
                # 未知方法
                response = {
                    "jsonrpc": "2.0",
                    "id": request["id"],
                    "error": {
                        "code": -32601,
                        "message": f"方法不存在: {method}"
                    }
                }
            
            print(json.dumps(response))
            sys.stdout.flush()
        
        except Exception as e:
            error_response = {
                "jsonrpc": "2.0",
                "id": request.get("id"),
                "error": {
                    "code": -32603,
                    "message": f"内部错误: {str(e)}"
                }
            }
            print(json.dumps(error_response))
            sys.stdout.flush()

if __name__ == "__main__":
    main() 

3. 和 MonkeyCode 对话

请使用 get_current_time 获取时间

4. 猴子输出

[ask_followup_question for '系统中是否有提供 get_current_time 工具的MCP服务器?'] Result:

<answer>
有 python-mcp-server
</answer>

<environment_details>
# VSCode Visible Files
.roo/mcp.json

# VSCode Open Tabs
.roo/mcp.json,start_mcp_server.sh

# Current Time
2025/8/4 下午2:52:50 (Asia/Shanghai, UTC+8:00)

# Current Context Size (Tokens)
9,716 (15%)

# Current Cost
$0.00

# Current Mode
<slug>code</slug>
<name>💻 Code</name>
<model>deepseek-v3</model>
</environment_details>

LydiaCai1203 avatar Aug 04 '25 06:08 LydiaCai1203

自定义系统提示词

全局规则作为基础:.roo/rules/ 中的规则定义了项目的基础编码规范、风格等 模式特定规则作为补充:.roo/rules-{mode}/ 中的规则针对特定模式进行优化

1. 针对不同模式的特定规则

.roo/
├── rules/
│   ├── rules.md              # 全局规则
│   └── rules-code/           # Code 模式特定规则
│       ├── frontend.md
│       └── backend.md
├── rules-architect/          # Architect 模式特定规则
│   └── architecture.md
└── rules-debug/              # Debug 模式特定规则
    └── debugging.md

2. For Example

rules/rules.md

# 项目开发规则

## 通用指导原则
1. **代码质量优先**:始终编写清晰、可维护的代码
2. **测试驱动**:新功能必须包含相应的测试
3. **文档完善**:重要功能需要编写文档

## 技术栈偏好
- **前端**:React + TypeScript + Tailwind CSS
- **后端**:Node.js + Express + TypeScript
- **数据库**:PostgreSQL
- **测试**:Jest + React Testing Library

## 代码规范
- 使用 ESLint 和 Prettier 保持代码风格一致
- 函数长度不超过 50 行
- 文件长度不超过 300 行
- 使用有意义的变量和函数名

## 项目特定要求
- 所有 API 响应必须包含错误处理
- 使用环境变量管理配置
- 遵循 RESTful API 设计原则

rules-architect/architecture.md

# 架构设计指导提示词

## 系统概述
- 系统名称: [填写系统名称]
- 主要功能: [简要描述系统核心功能]
- 预期用户量: [预估用户规模]

## 技术选型要求
- 编程语言: [Python/Java/Go等]
- 数据库: [关系型/NoSQL/其他]
- 框架选择: [列出候选框架]
- 部署环境: [云服务/本地/混合]

## 架构设计原则
1. 可扩展性: [描述扩展性需求]
2. 可用性: [SLA要求]
3. 安全性: [安全合规要求]
4. 性能: [预期QPS/响应时间]

## 组件设计
- 核心模块划分: [列出主要模块]
- 模块交互方式: [同步/异步/事件驱动]
- 数据流设计: [描述关键数据流]

## 非功能性需求
- 监控告警: [监控指标要求]
- 日志记录: [日志级别和存储]
- 容灾备份: [RTO/RPO要求]

## 交付物要求
- 架构图类型: [C4/部署图/序列图]
- 文档输出: [架构决策记录/API文档]

LydiaCai1203 avatar Aug 04 '25 08:08 LydiaCai1203

@monkeycode-ai 这个需求要如何实现

safe1ine avatar Sep 20 '25 02:09 safe1ine

GitHub Issue 深度评估报告

1. 整体摘要 (Executive Summary)

这是一个关于MonkeyCode MCP(Model Context Protocol)配置和系统提示词设置的功能咨询问题。用户询问如何设置MCP服务器和系统提示词,已有社区成员提供了详细的配置示例和实现代码。问题质量较高,建议作为文档补充需求处理。

2. 详细评估 (Detailed Assessment)

评估维度 评分 (1-5) 评估说明
清晰度 4 问题表述清晰,明确询问MCP和系统提示词的设置方法
完整性 5 已有详细的技术回复,包含完整配置示例和代码实现
可复现性/可行性 5 基于提供的示例代码,实现完全可行且可复现

3. 分类与优先级 (Classification & Priority)

  • 建议标签: documentation, feature-request, help-wanted
  • 严重等级: Minor
  • 建议优先级: Medium

4. 影响与风险 (Impact & Risks)

  • 影响范围: 影响所有使用MonkeyCode MCP功能的开发者用户,特别是需要自定义工具和提示词的场景
  • 潜在风险: 无破坏性变更风险,主要是文档完善和功能易用性提升

5. 行动建议 (Actionable Suggestions)

  • 对提交者的回应:
    • 感谢提交问题和社区成员的详细解答
    • "我们将把您的需求整理为官方文档,方便更多用户参考"
  • 对维护团队的建议:
    • 下一步: 将现有解答整理为官方文档,创建MCP配置指南
    • 初步解决方案构想: 1) 在文档中新增MCP配置章节 2) 提供标准化的配置模板 3) 创建示例项目仓库

MonkeyCode-AI avatar Sep 20 '25 02:09 MonkeyCode-AI