ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

用 MCP 与 Microsoft Foundry Toolkit 构建 GitHub Clone 服务器:将仓库克隆与 VS Code 打开压缩为一条智能指令

用 MCP 与 Microsoft Foundry Toolkit 构建 GitHub Clone 服务器:将仓库克隆与 VS Code 打开压缩为一条智能指令 教程文档人工智能【免费下载链接】mcp-for-beginnersThis open-source curriculum introduces the fundamentals of Model Context Protocol (MCP) through real-world, cross-language examples in .NET, Java, TypeScript, JavaScript, Rust and Python. Designed for developers, it focuses on practical techniques for building modular, scalable, and secure AI workflows from session setup to service orchestration.项目地址https://gitcode.com/GitHub_Trending/mc/mcp-for-beginners点击查看免费下载本指南基于仓库中 lab4 实战模块 及配套源码 github_mcp_server完整讲解如何用 Python SDK 从零构建一个生产可用的 MCP 服务器git_mcp_server把打开终端 → 进入目录 →git clone→ 用 VS Code 打开这一重复流程整合为一句自然语言指令。读完本文你将掌握在 Agent Builder 中创建自定义 Agent、为 MCP 工具编写带完整校验与跨平台能力的实现、以及在 Agent Builder 与 MCP Inspector 两种环境中调试和验证服务器。 学习目标完成本实验后你将具备以下能力创建用于真实开发工作流的自定义 MCP 服务器通过 MCP 工具实现 GitHub 仓库克隆功能将自定义 MCP 服务器与 VS Code、Agent Builder 集成使用 GitHub Copilot Agent Mode 调用自定义 MCP 工具在生产环境中测试与部署自定义 MCP 服务器。 前置条件已完成本模块 Lab 1-3MCP 基础与进阶开发GitHub Copilot 订阅VS Code 中安装 Microsoft Foundry Toolkit 与 GitHub Copilot 扩展已安装并配置好 Git 命令行工具。️ 项目概览解决真实的开发工作流难题现实中的开发挑战开发者经常需要在 GitHub 上克隆仓库并在 VS Code / VS Code Insiders 中打开手动操作通常包含四步打开终端 / 命令提示符切换到目标目录执行git clone命令在克隆出的目录中打开 VS Code。本实验的 MCP 方案将这四步压缩为一条智能指令。你将构建的内容一个GitHub Clone MCP 服务器git_mcp_server提供如下能力功能说明收益智能仓库克隆带校验地克隆 GitHub 仓库自动化错误检查智能目录管理安全检查并创建目录防止覆盖已有目录跨平台 VS Code 集成在 VS Code / Insiders 中打开项目工作流无缝衔接️健壮的错误处理处理网络、权限与路径问题生产级可靠性 分步实现Step 1在 Agent Builder 中创建 GitHub Agent通过 Microsoft Foundry Toolkit 扩展启动Agent Builder创建新 Agent配置如下Agent Name: GitHubAgent初始化自定义 MCP 服务器导航到Tools → Add Tool → MCP Server选择Create A new MCP Server选择Python 模板以获得最大灵活性Server Name:git_mcp_server。Step 2配置 GitHub Copilot Agent Mode在 VS Code 中打开 GitHub CopilotCtrl/Cmd Shift P → GitHub Copilot: Open在 Copilot 界面中选择Agent Model选择Claude 3.7 模型以获得更强的推理能力启用MCP 集成以获得工具访问能力。提示Claude 3.7 对开发工作流与错误处理模式有更好的理解。Step 3实现核心 MCP 服务器功能使用以下详细提示词驱动 GitHub Copilot Agent Mode 生成两个 MCP 工具Create two MCP tools with the following comprehensive requirements: TOOL A: clone_repository Requirements: - Clone any GitHub repository to a specified local folder - Return the absolute path of the successfully cloned project - Implement comprehensive validation: ✓ Check if target directory already exists (return error if exists) ✓ Validate GitHub URL format (https://github.com/user/repo) ✓ Verify git command availability (prompt installation if missing) ✓ Handle network connectivity issues ✓ Provide clear error messages for all failure scenarios TOOL B: open_in_vscode Requirements: - Open specified folder in VS Code or VS Code Insiders - Cross-platform compatibility (Windows/Linux/macOS) - Use direct application launch (not terminal commands) - Auto-detect available VS Code installations - Handle cases where VS Code is not installed - Provide user-friendly error messages Additional Requirements: - Follow MCP 1.9.3 best practices - Include proper type hints and documentation - Implement logging for debugging purposes - Add input validation for all parameters - Include comprehensive error handling源码级实现github_mcp_server/src/server.py仓库中 server.py 给出了该实验的完整可运行实现。服务器基于mcp.server.fastmcp.FastMCP初始化并暴露三个工具from mcp.server.fastmcp import FastMCP # Initialize FastMCP server server FastMCP(github_mcp_server)需要说明的是提示词中描述的 Tool A 名为clone_repository而实际源码将其实现为git_clone_repoTool B 名称与提示词一致为open_in_vscode此外模板还保留了自带的get_weather天气模拟工具作为脚手架示例。下面按源码逐项拆解。工具 Agit_clone_repo仓库克隆server.tool() async def git_clone_repo(repo_url: str, target_folder: str) - str: Clone a git repository to a specified folder. # 1) 目标目录已存在 → 直接报错防止覆盖 target_path Path(target_folder).expanduser().absolute() if target_path.exists(): return json.dumps({success: False, error: fTarget folder already exists: {str(target_path)}}) # 2) 检查 git 是否可用 try: subprocess.run([git, --version], checkTrue, capture_outputTrue, textTrue) except FileNotFoundError: return json.dumps({success: False, error: Git is not installed. Please install Git first.}) ... # 3) 创建父目录递归、幂等 target_path.parent.mkdir(parentsTrue, exist_okTrue) # 4) 执行克隆并捕获 stderr 输出 try: result subprocess.run([git, clone, repo_url, str(target_path)], checkTrue, capture_outputTrue, textTrue) return json.dumps({success: True, target_folder: str(target_path)}) except subprocess.CalledProcessError as e: return json.dumps({success: False, error: fGit clone failed: {e.stderr}})实现要点对应提示词中的校验清单防覆盖target_path.exists()检查目标目录是否已存在存在即返回错误避免静默覆盖环境自检先执行git --version探测 Git 是否安装区分FileNotFoundError未安装与CalledProcessError检查失败两种错误场景父目录幂等创建target_path.parent.mkdir(parentsTrue, exist_okTrue)可递归创建父路径且重复执行不报错统一返回契约无论成功失败都以 JSON 返回成功时带target_folder绝对路径失败时带error信息方便 Agent 与客户端解析。工具 Bopen_in_vscode跨平台 VS Code 集成server.tool() async def open_in_vscode(folder_path: str, use_insiders: bool False) - str: Open a folder in VS Code or VS Code Insiders application. folder_path Path(folder_path).expanduser().absolute() if not folder_path.exists(): return json.dumps({success: False, error: fFolder does not exist: {str(folder_path)}}) system platform.system() try: if system Darwin: # macOS app_name Visual Studio Code - Insiders if use_insiders else Visual Studio Code subprocess.run([open, -a, app_name, str(folder_path)], checkTrue) elif system Windows: # 依次探测 LOCALAPPDATA 与 Program Files / Program Files (x86) 下的 Code.exe ... # 直接启动解析出的可执行文件不经过 shell避免路径中的 shell 元字符注入 subprocess.run([vscode_path, str(folder_path)], checkTrue) ... elif system Linux: # 优先 xdg-open 调用桌面应用失败则回退到 code / code-insiders 命令 try: subprocess.run([xdg-open, str(folder_path)], checkTrue) except (FileNotFoundError, subprocess.CalledProcessError): subprocess.run([app_name, str(folder_path)], checkTrue) else: return json.dumps({success: False, error: fUnsupported operating system: {system}}) ... except subprocess.CalledProcessError as e: return json.dumps({success: False, error: fFailed to open VS Code: {str(e)}}) except FileNotFoundError: return json.dumps({success: False, error: VS Code ... is not installed or not in PATH})实现要点跨平台分发按platform.system()分支处理——macOS 用open -aWindows 用可执行文件路径并回退code/code-insiders命令行Linux 优先xdg-open再回退命令行路径安全Windows 分支直接启动解析出的Code.exe可执行文件而非经由 shell源码注释明确指出这是为了避免folder_path中的 shell 元字符引发命令注入自动探测Windows 分支依次检查LOCALAPPDATA、Program Files、Program Files (x86)等常见安装位置找不到才回退命令行方式友好报错分别捕获CalledProcessError与FileNotFoundError提示 VS Code 未安装或不在 PATH。服务器入口与传输层src/__init__.py是服务器入口支持两种 MCP 传输方式transport_type sys.argv[1] if len(sys.argv) 1 else None server.settings.log_level os.environ.get(LOG_LEVEL, DEBUG) if transport_type sse: port int(os.environ.get(PORT, 3001)) server.settings.port port server.settings.host 127.0.0.1 server.run(transportsse) elif transport_type stdio: server.run(transportstdio)关键点通过命令行参数sse/stdio选择传输方式默认端口3001默认监听127.0.0.1日志级别可由环境变量LOG_LEVEL控制默认DEBUG便于联调排错。工程配置与依赖pyproject.toml声明了项目依赖Python3.10、核心依赖mcp1.28.1开发依赖debugpy1.8.8配合 VS Code 断点调试使用。仓库模块级 READMEcode/github_mcp_server/README.md还指出Git 是git_clone_repo工具的运行前提VS Code / VS Code Insiders 是open_in_vscode工具的运行前提。Step 4测试你的 MCP 服务器4a. 在 Agent Builder 中测试启动 Agent Builder 的调试配置为你的 Agent 配置系统提示词SYSTEM_PROMPT: You are my intelligent coding repository assistant. You help developers efficiently clone GitHub repositories and set up their development environment. Always provide clear feedback about operations and handle errors gracefully.用贴近真实的用户场景进行测试USER_PROMPT EXAMPLES: Scenario : Basic Clone and Open Clone {Your GitHub Repo link such as https://github.com/kinfey/GHCAgentWorkshop } and save to {The global path you specify}, then open it with VS Code Insiders预期结果✅ 克隆成功并返回路径确认✅ 自动启动 VS Code✅ 对无效场景给出清晰错误信息✅ 正确处理各类边界情况。4b. 在 MCP Inspector 中测试仓库配套目录 inspector 提供了 Inspector 所需的package.json与package-lock.json。参考模块级 READMEcode/github_mcp_server/README.md完整的 Inspector 调试流程为安装 Node.js进入 Inspector 目录并安装依赖cd inspector npm install在 VS Code 调试面板中选择Debug SSE in Inspector (Edge)或Debug SSE in Inspector (Chrome)按 F5 启动浏览器中启动 MCP Inspector 后点击Connect按钮连接本 MCP 服务器使用List Tools列出工具选择工具、填入参数并Run Tool调试服务器代码。默认端口约定Agent Builder 调试模式与 MCP Inspector 模式下服务器均使用端口3001ServerInspector 前端使用5173与3000Inspector。所有调试模式均支持断点可把断点直接加在工具实现代码上。从 Inspector 界面可以看到服务器暴露了get_weather、git_clone_repo、open_in_vscode三个工具并在initialize、tools/list、tools/call等请求的历史记录中展示完整交互过程。⚙️ 本地环境准备uv 与 pip 两种方式根据 code/github_mcp_server/README.md搭建本地运行环境有两种方式任选其一即可方式步骤使用uv1. 创建虚拟环境uv venv2. 在 VS Code 中执行命令Python: Select Interpreter选择虚拟环境中的 Python3. 安装依赖含开发依赖uv pip install -r pyproject.toml --extra dev使用pip1. 创建虚拟环境python -m venv .venv2. 在 VS Code 中执行命令Python: Select Interpreter选择虚拟环境中的 Python3. 安装依赖含开发依赖pip install -e .[dev]注意创建虚拟环境后需重载 VS Code 或终端确保使用的是虚拟环境中的 Python。环境就绪后即可在 VS Code 调试面板中选择Debug in Agent Builder或按 F5启动 MCP 服务器以 Agent Builder 作为 MCP 客户端开始联调也可以在终端中直接以python src配合sse或stdio参数启动服务器进程。 解锁成就与后续进阶完成本实验后你将解锁✅MCP Developer创建了自定义 MCP 服务器✅Workflow Automator简化了开发流程✅Integration Expert打通多个开发工具✅Production Ready构建了可部署的解决方案。继续学习路线Module 10 总览 → Module 11MCP Server Hands-On Labs。前序模块见 Lab 1、Lab 2、Lab 3。进阶提示将本实验服务器投入生产时可以从以下几点继续加强为repo_url增加https://github.com/user/repo格式的显式校验当前源码主要通过git clone自身报错来兜底在 Windows 与 Linux 上验证命令行回退路径的可用性结合仓库 02-Security 与 mcp-security-best-practices.md 中关于工具输入校验、最小权限与日志脱敏的最佳实践进一步加固服务器。祝编码愉快赞分享教程文档人工智能【免费下载链接】mcp-for-beginnersThis open-source curriculum introduces the fundamentals of Model Context Protocol (MCP) through real-world, cross-language examples in .NET, Java, TypeScript, JavaScript, Rust and Python. Designed for developers, it focuses on practical techniques for building modular, scalable, and secure AI workflows from session setup to service orchestration.项目地址https://gitcode.com/GitHub_Trending/mc/mcp-for-beginners点击查看免费下载相关推荐OpenSpeedy资源使用分析PerfMon计数器配置OpenSpeedy资源使用分析PerfMon计数器配置 你是否在使用OpenSpeedy时遇到过进程监控延迟、资源占用过高或加速效果不稳定的问题本文将通过教程文档人工智能连接真实宿主用同一条命令将 MCP 服务器接入 Claude Desktop、Claude Code、Cursor 与 VS Code连接真实宿主用同一条命令将 MCP 服务器接入 Claude Desktop、Claude Code、Cursor 与 VS Code 宿主host 是人工智能MCP 服务MCP Clients使用 Microsoft Foundry Toolkit 在 VS Code 中消费 MCP 计算器服务器从 Agent 创建到自然语言调用工具使用 Microsoft Foundry Toolkit 在 VS Code 中消费 MCP 计算器服务器从 Agent 创建到自然语言调用工具 本教程基于开教程文档人工智能上一篇Taste-Skill终结AI设计平庸化重塑企业级前端开发的投资回报率下一篇EGADS大规模时间序列数据异常检测的开源Java库创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表