- 教程
- 文档
- 人工智能
【免费下载链接】mcp-for-beginners
This 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.
本指南基于仓库中 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-3(MCP 基础与进阶开发);
- 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 Copilot(Ctrl/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_repo(Tool B 名称与提示词一致,为open_in_vscode);此外模板还保留了自带的get_weather天气模拟工具作为脚手架示例。下面按源码逐项拆解。
工具 A:git_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": f"Target folder already exists: {str(target_path)}"}) # 2) 检查 git 是否可用 try: subprocess.run(["git", "--version"], check=True, capture_output=True, text=True) except FileNotFoundError: return json.dumps({"success": False, "error": "Git is not installed. Please install Git first."}) ... # 3) 创建父目录(递归、幂等) target_path.parent.mkdir(parents=True, exist_ok=True) # 4) 执行克隆并捕获 stderr 输出 try: result = subprocess.run(["git", "clone", repo_url, str(target_path)], check=True, capture_output=True, text=True) return json.dumps({"success": True, "target_folder": str(target_path)}) except subprocess.CalledProcessError as e: return json.dumps({"success": False, "error": f"Git clone failed: {e.stderr}"})实现要点(对应提示词中的校验清单):
- 防覆盖:
target_path.exists()检查目标目录是否已存在,存在即返回错误,避免静默覆盖; - 环境自检:先执行
git --version探测 Git 是否安装,区分FileNotFoundError(未安装)与CalledProcessError(检查失败)两种错误场景; - 父目录幂等创建:
target_path.parent.mkdir(parents=True, exist_ok=True)可递归创建父路径且重复执行不报错; - 统一返回契约:无论成功失败都以 JSON 返回,成功时带
target_folder绝对路径,失败时带error信息,方便 Agent 与客户端解析。
工具 B:open_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": f"Folder 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)], check=True) elif system == "Windows": # 依次探测 LOCALAPPDATA 与 Program Files / Program Files (x86) 下的 Code.exe ... # 直接启动解析出的可执行文件(不经过 shell),避免路径中的 shell 元字符注入 subprocess.run([vscode_path, str(folder_path)], check=True) ... elif system == "Linux": # 优先 xdg-open 调用桌面应用,失败则回退到 code / code-insiders 命令 try: subprocess.run(["xdg-open", str(folder_path)], check=True) except (FileNotFoundError, subprocess.CalledProcessError): subprocess.run([app_name, str(folder_path)], check=True) else: return json.dumps({"success": False, "error": f"Unsupported operating system: {system}"}) ... except subprocess.CalledProcessError as e: return json.dumps({"success": False, "error": f"Failed 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 -a,Windows 用可执行文件路径(并回退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(transport="sse") elif transport_type == "stdio": server.run(transport="stdio")关键点:
- 通过命令行参数(
sse/stdio)选择传输方式,默认端口3001,默认监听127.0.0.1; - 日志级别可由环境变量
LOG_LEVEL控制,默认DEBUG,便于联调排错。
工程配置与依赖
pyproject.toml声明了项目依赖:Python>=3.10、核心依赖mcp>=1.28.1,开发依赖debugpy==1.8.8(配合 VS Code 断点调试使用)。仓库模块级 README(code/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。参考模块级 README(code/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 模式下服务器均使用端口3001(Server),Inspector 前端使用5173与3000(Inspector)。所有调试模式均支持断点,可把断点直接加在工具实现代码上。从 Inspector 界面可以看到,服务器暴露了get_weather、git_clone_repo、open_in_vscode三个工具,并在initialize、tools/list、tools/call等请求的历史记录中展示完整交互过程。
⚙️ 本地环境准备(uv 与 pip 两种方式)
根据 code/github_mcp_server/README.md,搭建本地运行环境有两种方式,任选其一即可:
| 方式 | 步骤 |
|---|---|
使用uv | 1. 创建虚拟环境:uv venv2. 在 VS Code 中执行命令"Python: Select Interpreter",选择虚拟环境中的 Python 3. 安装依赖(含开发依赖): uv pip install -r pyproject.toml --extra dev |
使用pip | 1. 创建虚拟环境:python -m venv .venv2. 在 VS Code 中执行命令"Python: Select Interpreter",选择虚拟环境中的 Python 3. 安装依赖(含开发依赖): 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 11:MCP 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-beginners
This 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.
相关推荐
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 创建到自然语言调用工具 本教程基于开
教程文档人工智能
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考