- 教程
- 文档
- 人工智能
【免费下载链接】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.
本文以 mcp-for-beginners 仓库中《Streamlining AI Workflows: Building an MCP Server with Microsoft Foundry Toolkit》工作坊文档为骨架,系统讲解如何将 Model Context Protocol(MCP)与 Microsoft Foundry Toolkit 扩展组合使用,从零完成 AI 应用的智能化升级。读完本文,你将掌握 Model Catalog 与 Agent Builder 的完整用法、MCP 客户端-服务器架构、基于 MCP Python SDK 编写自定义服务器(Weather 与 GitHub Clone 两个实战案例),以及结合 VS Code 调试器与 MCP Inspector 的专业调试工作流,最终具备把 AI 模型接入真实业务工具与服务的实战能力。
工作坊概览:MCP × Microsoft Foundry Toolkit
该工作坊将两项前沿技术组合成一条完整的动手实践(Hands-On)学习路径:
- Model Context Protocol(MCP):连接 AI 模型与外部工具、数据源和服务的开放标准,实现"一次协议、无限接入";
- Microsoft Foundry Toolkit 扩展(VS Code):微软推出的 AI 开发扩展,把 VS Code 打造成集模型管理、提示词工程、Agent 构建与 MCP 集成于一体的 AI 开发环境。
工作坊以"从自动化测试到自定义 API 集成"为线索,覆盖会话建立(session setup)到服务编排(service orchestration)的完整链路,最终目标是培养读者解决复杂业务问题的实战能力。
兼容性说明:工作坊代码基于 MCP
2025-11-25规范构建与验证(见文档徽标);对于新的协议实现,应使用当前的2026-07-28规范,并在迁移实验室代码前查看 SDK 发布说明。此外,Lab 3 中明确提示:其 Inspector 调试地址使用传统的/sse端点,并锁定 MCP SDK1.9.3与 Inspector0.14.0依赖,并非2026-07-28规范的 Streamable HTTP 示例——动手前务必先确认你使用的规范版本与依赖组合。
核心技术栈拆解
MCP:AI 应用的"USB-C"
MCP 被誉为"AI 的 USB-C"——正如 USB-C 终结了线缆混战的乱局,MCP 用一套统一协议消除了 AI 集成中的碎片化。其关键特性包括:
- 标准化集成:提供 AI 与工具连接的通用接口;
- 灵活架构:通过 stdio / SSE(Server-Sent Events)等传输方式同时支持本地与远程服务器;
- 丰富生态:工具(Tools)、提示词(Prompts)与资源(Resources)统一在一个协议内;
- 企业就绪:内置安全与可靠性设计。
MCP 解决的痛点:在 MCP 之前,每种工具都需要定制集成、专有方案造成厂商锁定、临时连接带来安全隐患、基础集成往往耗费数月开发周期;引入 MCP 之后,工具接入即插即用、架构与厂商无关、内置安全最佳实践、新增能力只需数分钟。
MCP 架构采用客户端-服务器模型,构成一个安全、可扩展的生态:
四个核心组件各司其职:
| 组件 | 角色 | 示例 |
|---|---|---|
| MCP Hosts | 消费 MCP 服务的主机 | VS Code、Foundry Toolkit |
| MCP Clients | 处理协议连接 | 内置于 Hosts 中 |
| MCP Servers | 提供能力 | Playwright、Files、Azure、GitHub |
| Transport Layer | 连接客户端与服务器 | stdio、HTTP、WebSockets |
Microsoft Foundry Toolkit:VS Code 的 AI 增强引擎
微软的旗舰级 AI 开发扩展,核心能力包括:
- Model Catalog(模型目录):接入 GitHub、ONNX、OpenAI、Anthropic、Google 等来源的 100+ 模型,一站式发现与对比;
- 本地推理:ONNX 优化的 CPU / GPU / NPU 执行;
- Agent Builder(智能体构建器):可视化开发 AI Agent,并内置 MCP 集成;
- 多模态支持:文本、视觉与结构化输出。
对开发者而言,它带来零配置模型部署、可视化提示词工程、实时测试 Playground、无缝 MCP 服务器集成的开发体验。
四模块学习路径总览
工作坊由 4 个递进式模块组成,形成"工具基础 → MCP 集成 → 自定义开发 → 生产落地"的完整闭环:
模块一:Microsoft Foundry Toolkit 基础(15 分钟)
对应文档 10-StreamliningAIWorkflowsBuildingAnMCPServerWithAIToolkit/lab1/README.md,学习目标:
- 安装并配置 VS Code 的 Microsoft Foundry Toolkit 扩展;
- 探索 Model Catalog(100+ 模型,覆盖 GitHub、ONNX、OpenAI、Anthropic、Google);
- 掌握 Interactive Playground 的实时模型测试;
- 用 Agent Builder 构建第一个 AI Agent;
- 使用内置指标(F1、relevance、similarity、coherence)评估模型性能;
- 了解批量处理与多模态支持。
产出:创建可运行的 AI Agent,并全面理解 Foundry Toolkit 能力边界。
模块二:MCP + Foundry Toolkit 基础(20 分钟)
对应 10-StreamliningAIWorkflowsBuildingAnMCPServerWithAIToolkit/lab2/README.md,学习目标:
- 掌握 MCP 架构与核心概念;
- 探索微软 MCP 服务器生态(Azure、Dataverse、Playwright、Files、MarkItDown、Clarity 等);
- 基于 Playwright MCP 服务器构建浏览器自动化 Agent;
- 在 Agent Builder 中集成、配置与测试 MCP 工具;
- 导出并部署由 MCP 驱动的 Agent。
产出:部署一个通过 MCP 外接工具的"超级 Agent"。
模块三:Foundry Toolkit 高级 MCP 开发(20 分钟)
对应 10-StreamliningAIWorkflowsBuildingAnMCPServerWithAIToolkit/lab3/README.md,学习目标:
- 使用 Foundry Toolkit 模板创建自定义 MCP 服务器;
- 配置并使用 MCP Python SDK(实验室文档锁定 v1.9.3);
- 搭建 MCP Inspector 调试环境;
- 构建 Weather MCP 服务器并掌握专业调试流程;
- 在 Agent Builder 与 Inspector 双环境下调试服务器。
产出:掌握现代工具链下的自定义 MCP 服务器开发与调试。
模块四:实战——自定义 GitHub Clone 服务器(30 分钟)
对应 10-StreamliningAIWorkflowsBuildingAnMCPServerWithAIToolkit/lab4/README.md,学习目标:
- 构建真实场景的 GitHub Clone MCP 服务器;
- 实现带校验与错误处理的智能仓库克隆;
- 实现目录管理与 VS Code 集成;
- 在 GitHub Copilot Agent Mode 中使用自定义 MCP 工具;
- 应用生产级可靠性与跨平台兼容设计。
产出:部署一个能简化真实开发流程的生产级 MCP 服务器。
环境准备与前置条件
系统要求
| 组件 | 要求 | 说明 |
|---|---|---|
| 操作系统 | Windows 10+、macOS 10.15+、Linux | 任意现代操作系统 |
| Visual Studio Code | 最新稳定版 | Foundry Toolkit 必需 |
| Node.js | v18.0+ 与 npm | 用于 MCP 服务器开发与 Inspector |
| Python | 3.10+ | 构建 Python MCP 服务器 |
| 内存 | 最低 8GB | 本地模型建议 16GB |
推荐的 VS Code 扩展
- Microsoft Foundry Toolkit(
ms-windows-ai-studio.windows-ai-studio) - Python(
ms-python.python) - Python Debugger(
ms-python.debugpy) - GitHub Copilot(
GitHub.copilot)——可选但有帮助
可选工具
- uv:现代 Python 包管理器(
uv sync安装依赖); - MCP Inspector:MCP 服务器的可视化调试工具;
- Playwright:用于 Web 自动化示例。
源码剖析一:基于 MCP Python SDK 的 Weather 服务器
Lab 3 引导你通过 Agent Builder 的Tools → Add Tool → MCP Server → Create A new MCP Server →python-weather模板生成weather_mcp项目。仓库中的完整工程位于 10-StreamliningAIWorkflowsBuildingAnMCPServerWithAIToolkit/lab3/code/weather_mcp/,结构如下:
weather_mcp/ ├── src/ │ ├── __init__.py # 入口:按参数选择 sse / stdio 传输 │ └── server.py # FastMCP 服务器与工具定义 ├── inspector/ │ ├── package.json # MCP Inspector 启动脚本 │ └── package-lock.json ├── pyproject.toml # Python 依赖声明 ├── uv.lock └── README.md服务器实现:server.py
核心代码见 server.py:
import json import random from mcp.server.fastmcp import FastMCP # Initialize FastMCP server server = FastMCP("weather_mcp") @server.tool() async def get_weather(location: str) -> str: """Get weather for a location. Args: location: Location to get weather for, e.g., city name, state, or coordinates """ if not location: return "Location is required." # mock weather data conditions = [ "Sunny", "Rainy", "Cloudy", "Snowy" ] weather = { "location": location, "temperature": f"{random.randint(10, 90)}°F", "condition": random.choice(conditions), } return json.dumps(weather, ensure_ascii=False)关键点:FastMCP("weather_mcp")初始化服务器实例,@server.tool()装饰器把异步函数注册为可供 LLM 调用的 MCP 工具;工具函数通过类型注解(location: str)自动生成 JSON Schema 供模型感知;返回值以 JSON 字符串形式返回结构化结果。当前版本使用模拟天气数据演示,你可以在真实项目中替换为外部天气 API 调用。
入口点:init.py
见init.py,它决定了服务器以何种传输方式运行:
import os import sys from server import server if __name__ == "__main__": """Main entry point""" 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") else: print("Invalid transport type. Use 'sse' or 'stdio'.") sys.exit(1)入口逻辑清晰:通过命令行第一个参数选择传输类型——sse模式监听PORT环境变量(默认 3001)并绑定127.0.0.1,适合配合 Inspector 调试;stdio模式用于被 Host 进程直接拉起;日志级别通过LOG_LEVEL环境变量控制,默认DEBUG。
依赖声明:pyproject.toml
仓库内 pyproject.toml 声明:
[project] name = "weather_mcp" version = "0.1.0" description = "A simple MCP weather server" readme = "README.md" requires-python = ">=3.10" dependencies = [ "mcp>=1.26.0" ] [project.optional-dependencies] dev = ["debugpy==1.8.8"]注意:Lab 3 文档正文标注锁定 MCP SDK1.9.3与 Inspector0.14.0,而仓库中提交的代码文件已升级为mcp>=1.26.0,Inspector 依赖为@modelcontextprotocol/inspector2.0.0(见 inspector/package.json,其dev:inspector脚本直接运行mcp-inspector,并通过overrides将shell-quote锁定到1.8.4)。动手时请以你实际安装的 SDK 版本为准,并注意版本差异带来的行为变化。
专业调试工作流:VS Code 调试配置深度解读
Lab 3 的核心亮点是双环境调试。先安装依赖:
# Python 依赖(项目根目录) uv sync # Inspector 依赖 cd inspector npm installlaunch.json:三种调试入口
{ "version": "0.2.0", "configurations": [ { "name": "Attach to Local MCP", "type": "debugpy", "request": "attach", "connect": { "host": "localhost", "port": 5678 }, "presentation": { "hidden": true }, "internalConsoleOptions": "neverOpen", "postDebugTask": "Terminate All Tasks" }, { "name": "Launch Inspector (Edge)", "type": "msedge", "request": "launch", "url": "http://localhost:6274?timeout=60000&serverUrl=http://localhost:3001/sse#tools", "cascadeTerminateToConfigurations": ["Attach to Local MCP"], "presentation": { "hidden": true }, "internalConsoleOptions": "neverOpen" }, { "name": "Launch Inspector (Chrome)", "type": "chrome", "request": "launch", "url": "http://localhost:6274?timeout=60000&serverUrl=http://localhost:3001/sse#tools", "cascadeTerminateToConfigurations": ["Attach to Local MCP"], "presentation": { "hidden": true }, "internalConsoleOptions": "neverOpen" } ], "compounds": [ { "name": "Debug in Agent Builder", "configurations": ["Attach to Local MCP"], "preLaunchTask": "Open Agent Builder" }, { "name": "Debug in Inspector (Edge)", "configurations": ["Launch Inspector (Edge)", "Attach to Local MCP"], "preLaunchTask": "Start MCP Inspector", "stopAll": true }, { "name": "Debug in Inspector (Chrome)", "configurations": ["Launch Inspector (Chrome)", "Attach to Local MCP"], "preLaunchTask": "Start MCP Inspector", "stopAll": true } ] }三个入口的含义:
- Attach to Local MCP:用 debugpy 附加到
5678端口上已由任务启动的 MCP 服务器进程,实现断点调试; - Launch Inspector (Edge / Chrome):用浏览器打开
http://localhost:6274,并携带serverUrl=http://localhost:3001/sse指向本地 SSE 服务器,#tools锚点直达工具面板; - 两个 compound 配置:一键组合"启动服务器 + 打开 Agent Builder"或"启动服务器 + 启动 Inspector + 附加调试器",按下 F5 即可进入完整调试会话。
tasks.json:后台任务的编排
{ "version": "2.0.0", "tasks": [ { "label": "Start MCP Server", "type": "shell", "command": "python -m debugpy --listen 127.0.0.1:5678 src/__init__.py sse", "isBackground": true, "options": { "cwd": "${workspaceFolder}", "env": { "PORT": "3001" } }, "problemMatcher": { "pattern": [ { "regexp": "^.*$", "file": 0, "location": 1, "message": 2 } ], "background": { "activeOnStart": true, "beginsPattern": ".*", "endsPattern": "Application startup complete|running" } } }, { "label": "Start MCP Inspector", "type": "shell", "command": "npm run dev:inspector", "isBackground": true, "options": { "cwd": "${workspaceFolder}/inspector", "env": { "CLIENT_PORT": "6274", "SERVER_PORT": "6277" } }, "problemMatcher": { "pattern": [ { "regexp": "^.*$", "file": 0, "location": 1, "message": 2 } ], "background": { "activeOnStart": true, "beginsPattern": "Starting MCP inspector", "endsPattern": "Proxy server listening on port" } }, "dependsOn": [ "Start MCP Server" ] }, { "label": "Open Agent Builder", "type": "shell", "command": "echo ${input:openAgentBuilder}", "presentation": { "reveal": "never" }, "dependsOn": [ "Start MCP Server" ] }, { "label": "Terminate All Tasks", "command": "echo ${input:terminate}", "type": "shell", "problemMatcher": [] } ], "inputs": [ { "id": "openAgentBuilder", "type": "command", "command": "ai-mlstudio.agentBuilder", "args": { "initialMCPs": [ "local-server-weather_mcp" ], "triggeredFrom": "vsc-tasks" } }, { "id": "terminate", "type": "command", "command": "workbench.action.tasks.terminate", "args": "terminateAll" } ] }编排逻辑要点:
- Start MCP Server:以
python -m debugpy --listen 127.0.0.1:5678启动带调试监听的服务器(SSE 传输、端口 3001),并配置 background problemMatcher 识别启动完成标志; - Start MCP Inspector:在 inspector 目录运行
npm run dev:inspector,占用CLIENT_PORT=6274与SERVER_PORT=6277,且依赖服务器已启动; - Open Agent Builder:通过
ai-mlstudio.agentBuilder命令直接打开 Agent Builder,并用initialMCPs: ["local-server-weather_mcp"]预挂载本地服务器,实现"启动即连接"。
双环境测试
Agent Builder 调试:选择 "Debug in Agent Builder" 配置 → F5 → 等待服务器启动并自动打开 Agent Builder,用自然语言测试:
SYSTEM_PROMPT You are my weather assistant USER_PROMPT How's the weather like in SeattleInspector 调试:选择 "Debug in Inspector (Edge/Chrome)",打开http://localhost:6274后可以:查看可用工具列表、执行工具调用、监控网络请求、调试服务器响应——这是验证工具参数与返回结构的最高效途径。
源码剖析二:生产级 GitHub Clone 服务器
Lab 4 针对一个真实痛点:手动克隆 GitHub 仓库并打开 VS Code 需要"开终端 → 切目录 →git clone→ 打开编辑器"四步操作。MCP 方案将其压缩为一条智能指令。仓库中的完整实现位于 10-StreamliningAIWorkflowsBuildingAnMCPServerWithAIToolkit/lab4/code/github_mcp_server/,提供三个能力:
| 能力 | 说明 |
|---|---|
| 🔄 智能仓库克隆 | 带校验的git clone,自动化错误检查 |
| 📁 智能目录管理 | 安全地检查与创建目录,防止覆盖 |
| 🚀 跨平台 VS Code 集成 | 打开 VS Code / Insiders,Windows/Linux/macOS 全覆盖 |
git_clone_repo:带完整校验的克隆工具
见 server.py,工具按"先校验、再执行"的原则实现:
@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."}) except subprocess.CalledProcessError: return json.dumps({"success": False, "error": "Error checking Git installation."}) # 3. 递归创建父目录 target_path.parent.mkdir(parents=True, exist_ok=True) # 4. 执行克隆并捕获失败原因 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}"})该校验链与 Lab 4 文档中要求完全一致:检查目标目录是否存在(存在即报错)、验证 GitHub URL 格式、确认 git 命令可用(缺失时提示安装)、处理网络问题,并为所有失败场景返回明确错误信息。所有返回统一为{success, ...}JSON 结构,便于 LLM 与调用方解析。
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 路径,兜底使用 code/code-insiders 命令 ... elif system == "Linux": # 先尝试 xdg-open 唤起桌面应用,失败后回退 code 命令 ... return json.dumps({"success": True, "message": f"Opened {str(folder_path)} in ..."}) 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"})实现细节:macOS 用open -a指定应用名;Windows 先探测LOCALAPPDATA与 Program Files 下的Code.exe(支持 Insiders),找不到再回退到code/code-insiders命令行,并刻意以无 shell 方式启动可执行文件以避免路径元字符的命令注入;Linux 优先xdg-open唤起桌面应用,失败后回退命令行。use_insiders参数统一控制是否使用 Insiders 版本。
借助 Copilot Agent Mode 生成与测试
Lab 4 的推荐路径是用 GitHub Copilot Agent Mode(选择 Claude 3.7 模型以增强推理能力)配合一段详细提示词自动生成上述工具代码,然后:
- 在 Agent Builder 中配置系统提示词(如"You are my intelligent coding repository assistant...");
- 用真实场景测试:"Clone https://github.com/kinfey/GHCAgentWorkshop and save to {目标路径}, then open it with VS Code Insiders";
- 在 Agent Builder 与 MCP Inspector 双环境验证工具调用与错误处理。
企业级应用场景
工作坊文档还给出了四类企业落地方向,用于启发读者把所学技能映射到业务中:
- DevOps 自动化:智能仓库管理(AI 驱动的代码审查与合并决策)、智能 CI/CD(基于代码变更的流水线优化)、Issue 自动分类与指派;
- 质量保障革命:智能测试生成、AI 驱动的视觉回归检测、主动式性能监控;
- 数据管道智能化:自适应 ETL、实时数据质量异常检测、智能数据流路由;
- 客户体验增强:具备客户历史访问能力的上下文感知支持、预测式问题解决、多渠道统一 AI 体验。
技能掌握清单
完成工作坊后,用以下清单自检:
核心能力
- MCP 协议掌握:深入理解架构与实现模式
- Foundry Toolkit 熟练运用:快速开发 AI 应用
- 自定义服务器开发:构建、部署与维护生产级 MCP 服务器
- 工具集成:把 AI 无缝接入既有开发工作流
- 问题解决应用:将所学技能用于真实业务挑战
技术技能
- 在 VS Code 中配置 Foundry Toolkit
- 设计与实现自定义 MCP 服务器
- 将 Foundry 模型与 MCP 架构集成
- 用 Playwright 构建自动化测试工作流
- 部署生产级 AI Agent
- 调试与优化 MCP 服务器性能
进阶能力
- 设计企业级 AI 集成架构
- 落地 AI 应用安全最佳实践
- 设计可扩展的 MCP 服务器架构
- 为特定领域创建自定义工具链
后续学习路径
完成本工作坊后,可继续深入仓库中的其他专题:MCP 核心概念与协议细节见 01-CoreConcepts/README.md(含 01-CoreConcepts/mcp-2026-07-28.md 规范笔记);安全设计参考 02-Security/README.md 与其中的 02-Security/mcp-security-best-practices.md;进阶主题(传输、采样、OAuth2、路由、扩展等)见 05-AdvancedTopics/README.md。工作坊文档也推荐继续进入 11-MCPServerHandsOnLabs/README.md 的服务器实操实验室,从架构、安全、数据库、工具到部署监控,把本工作坊的 MCP 技能落地成完整的生产级 MCP 服务。
- 教程
- 文档
- 人工智能
【免费下载链接】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.
相关推荐
mcp-for-beginners 实战:使用 Microsoft Foundry Toolkit 构建与调试 Weather MCP Server
mcp for beginners 实战:使用 Microsoft Foundry Toolkit 构建与调试 Weather MCP Server 本文是 m
教程文档人工智能mcp-for-beginners 实战指南:Microsoft Foundry Toolkit 基础与 AI Agent 构建(Module 1)
mcp for beginners 实战指南:Microsoft Foundry Toolkit 基础与 AI Agent 构建(Module 1) 本篇文章对
教程文档人工智能.NET 9 构建 MCP stdio 服务器实战:传输机制、工具实现与 MCP Inspector 调试指南(mcp-for-beginners)
.NET 9 构建 MCP stdio 服务器实战:传输机制、工具实现与 MCP Inspector 调试指南(mcp for beginners) 本文以 m
教程文档人工智能
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考