模型上下文协议工具

一个用于构建和管理AI模型工具的协议,支持多种集成和自动化任务。

  • by bachir00
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 bachir00/mcp_course

使用说明

🚀 Projet MCP(模型上下文协议)-指南完成

📋 环境配置

创建Python虚拟环境

# Créer l'environnement virtuel
python -m venv mcp_env

# Activation selon votre système :
.\mcp_env\Scripts\Activate.ps1    # PowerShell
.\mcp_env\Scripts\Activate.bat     # CMD
source mcp_env/bin/activate        # Linux/Unix

# Installation de MCP
pip install "mcp[cli]"

🔧 使用检查器测试MCP服务器

# Démarrer l'inspecteur MCP
(mcp_env) PS D:\CoursMCP> mcp dev server.py

# Sortie attendue :
Starting MCP inspector...
⚙️ Proxy server listening on 127.0.0.1:6277
🔑 Session token: 9fc29f021dc16f4b836a3623ba87aa1c9acfe21baa664195aa890c7a4c42a5f0
Use this token to authenticate requests or set DANGEROUSLY_OMIT_AUTH=true to disable auth

🔗 Open inspector with token pre-filled:
   http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=9fc29f021dc16f4b836a3623ba87aa1c9acfe21baa664195aa890c7a4c42a5f0

# Dans l'interface web, cliquez sur "Connect"
# Vous verrez tous les tools, prompts, resources disponibles

🌤️ 以天气为例进行测试

# Tester le serveur weather.py
(mcp_env) PS D:\CoursMCP> mcp dev weather.py

# Données de test :
{
  "latitude": 40.7128,
  "longitude": -74.0060
}

🛡️ 配置保护MCP

参考课程: https://huggingface.co/learn/mcp-course/unit1/gradio-mcp

使用Gradio进行情绪分析

# Installation des dépendances pour Guardio
pip install "gradio[mcp]" textblob

# Démarrage du serveur Guardio
(mcp_env) PS D:\CoursMCP\GuardioMCP> python .\server.py

# Sortie attendue :
* Running on local URL:  http://127.0.0.1:7860
* Running on public URL: https://c4d429503771a11265.gradio.live

# Interfaces disponibles :
# Interface web : http://127.0.0.1:7860
# Schéma MCP   : http://127.0.0.1:7860/gradio_api/mcp/schema

🤖 将Claude配置为MCP客户端

文档: https://modelcontextprotocol.io/docs/develop/build-server

与Claude Desktop集成

# Après avoir développé les tools du serveur MCP

# 1. Aller dans Claude > Settings > Developer
# 2. Modifier le fichier claude-desktop.json
# Configuration avec Python (ou uv si environnement créé avec uv) :

{
  "mcpServers": {
    "weather": {
      "command": "python",
      "args": [
        "D:\\CoursMCP\\weather.py"
      ]
    }
  }
}

# 3. Activer le tool dans le menu des outils de Claude
# 4. Tester avec une requête

🧪 利用率测试

# Exemple de requête à Claude :
"Donne-moi la météo du point :"
40.7128, -74.0060

# Claude démarrera automatiquement le serveur MCP
# Les logs se trouvent dans :
# C:\Users\sirou\AppData\Roaming\Claude\logs\mcp-server-weather

🏗️ 使用Guardio构建MCP客户端

# Installation des dépendances
pip install "smolagents[mcp]" "gradio[mcp]" mcp fastmcp

# Utilisation d'un serveur MCP depuis Hugging Face (construit avec Guardio)
# Exécuter le code dans l'environnement et tester les outils
# Fichier : mcp_client_guardio

🚀 Hugging Face Spaces的部署

指南: https://huggingface.co/learn/mcp-course/unit2/gradio-client

# 1. Créer un nouveau Space sur Hugging Face :
# - Aller sur huggingface.co/spaces
# - Cliquer "Create new Space"
# - Choisir "Gradio" comme SDK
# - Nommer le space (ex: "mcp-client")

# 2. Mettre à jour l'URL du serveur MCP dans le code :
mcp_client = MCPClient(
    {"url": "https://abidlabs-mcp-tool-http.hf.space/gradio_api/mcp/sse", "transport": "sse"}
)

# 3. Créer requirements.txt :
gradio[mcp]
smolagents[mcp]

# 4. Pousser le code sur le Space :
git init
git add app.py requirements.txt
git commit -m "Initial commit"
git remote add origin https://huggingface.co/spaces/YOUR_USERNAME/mcp-client
git push -u origin main

⚠️ 注: 对于Git身份验证,请参阅:https://huggingface.co/blog/password-git-deprecation

🔧 使用MCP和Hugging Face Hub构建微型代理

安装依赖项

# Installation Node.js
npm install -g npx
npm i mcp-remote

# Installation Python avec support MCP
pip install "huggingface_hub[mcp]>=0.32.0"

# Connexion à Hugging Face (pas besoin de configurer GitHub)
huggingface-cli login

客户端微型代理的配置

创建文件 agent.json :

{
  "model": "Qwen/Qwen2.5-72B-Instruct",
  "servers": [
    {
      "type": "stdio",
      "command": "npx",
      "args": [
        "mcp-remote", 
        "http://localhost:7860/gradio_api/mcp/sse"
      ]
    }
  ]
}

🚀 使用

# 1. Lancer d'abord le serveur MCP
(mcp_env) PS D:\CoursMCP\GuardioMCP> python .\mcp_server.py  

# 2. Lancer tiny-agents (🤗 client MCP)
(mcp_env) PS D:\CoursMCP\GuardioMCP> tiny-agents run agent.json

# Sortie attendue :
Agent loaded with 1 tools:
 • letter_counter

# Exemple d'utilisation :
» Count how many times the letter 'a' appears in "banana"
<Tool call_MA8wX6jgnOfblzrRAbrCuQlm>letter_counter {"letter": "a", "word": "banana"}

Tool call_MA8wX6jgnOfblzrRAbrCuQlm
3

The letter 'a' appears 3 times in the word "banana".

📚 文档:

🌐 具有AMD NPU和IGPU加速的小型本地代理

使用Guardio+柠檬水服务器进行测试

# Avec lemonade server, on peut faire tourner un modèle local accéléré

# Configuration avec Desktop Commander
# Installation : https://github.com/wonderwhy-er/DesktopCommanderMCP
npx @wonderwhy-er/desktop-commander@latest setup

# Démarrer lemonade server
lemonade-server serve 
# Docs: https://lemonade-server.ai/docs/server/server_integration/
# GitHub: https://github.com/lemonade-sdk/lemonade

使用Desktop Commander进行配置

创建文件 agent_desktop_commander.json :

{
  "model": "user.jan-nano",
  "endpointUrl": "http://localhost:8000/api/",
  "servers": [
    {
      "type": "stdio",
      "command": "C:\\Program Files\\nodejs\\npx.cmd",
      "args": [
        "-y",
        "@wonderwhy-er/desktop-commander"
      ]
    }
  ]
}

📁 创建测试文件

# Créer les fichiers pour les tests
# job_description.md
# candidates/john_resume.md

🧪 利用率测试

# Lancer tiny-agents
(mcp_env) PS D:\CoursMCP\GuardioMCP> tiny-agents run .\agent_desktop_commander.json

# Sortie attendue :
Agent loaded with 25 tools:
 • get_config
 • set_config_value
 # ... et autres tools

# Exemples de requêtes :
» Read the contents of C:\Users\your_username\file-assistant\job_description.md
» Inside the same folder you can find a candidates folder. Check for john_resume.md and let me know if he is a good fit for the job.
» Create a file called "invitation.md" in the "file-assistant" folder and write a short invitation to John to come in for an interview.

📚 第3单元-高级MCP课程

模块1:构建MCP服务器

注: 我们使用微型代理而不是Claude代码(付费)

# Cloner le dépôt du cours
git clone https://github.com/huggingface/mcp-course.git 

# Naviguer vers le code de démarrage
cd mcp-course/projects/unit3/build-mcp-server/starter

# Installer les dépendances avec Python (pas uv)
pip install .
pip install -e ".[dev]"

# Après implémentation des outils
# Tests de validation
python validate_starter.py
pytest test_server.py -v

使用Lemonade服务器配置PR代理

创建文件 agent_pr.json :

{
  "model": "user.jan-nano",
  "endpointUrl": "http://localhost:8000/api/",
  "servers": [
    {
      "type": "stdio",
      "command": "python",
      "args": [
        "d:\\CoursMCP\\mcp-course\\projects\\unit3\\build-mcp-server\\starter\\server.py"
      ]
    }
  ]
}

🚀 执行

PS D:\CoursMCP> .\mcp_env\Scripts\Activate.ps1; cd "d:\CoursMCP\mcp-course\projects\unit3\build-mcp-server\starter"; tiny-agents run agent_pr.json

# Questions de test :
» Analyze my git changes
» What PR templates are available?
» Suggest a template for my feature change

模块2:GitHub操作集成

工作流程: GitHub操作→ 网络钩子→ JSON文件→ MCP工具→ 微小的代理人→ user

# Le serveur webhook est déjà fourni :
# D:\CoursMCP\mcp-course\projects\unit3\github-actions-integration\starter\webhook_server.py

# Implémenter les outils du serveur MCP :
# D:\CoursMCP\mcp-course\projects\unit3\github-actions-integration\starter\server.py
# ⚠️ Attention avec les commandes git pour l'utilisation du même terminal

代理模块2的配置

{
  "model": "user.jan-nano",
  "endpointUrl": "http://localhost:8000/api/",
  "servers": [
    {
      "type": "stdio",
      "command": "python",
      "args": [
        "-u",
        "server.py"
      ]
    }
  ]
}

🌐 要启动的服务

# 1. Serveur webhook
(mcp_env) PS D:\CoursMCP> cd "d:\CoursMCP\mcp-course\projects\unit3\github-actions-integration\starter"; python webhook_server.py

# 2. Serveur MCP avec tiny-agents
(mcp_env) PS D:\CoursMCP\mcp-course\projects\unit3\github-actions-integration\starter> tiny-agents run agent_config.json

# Sortie attendue :
Agent loaded with 5 tools:
 • analyze_file_changes
 • get_pr_templates
 • suggest_template

# 3. Lemonade server (dans un autre terminal)
PS D:\CoursMCP> lemonade-server serve

# 4. Cloudflare Tunnel pour GitHub
cloudflared tunnel --url http://localhost:8080
# URL finale : https://deutsche-alternate-undefined-hundred.trycloudflare.com/webhook/github

⚠️ 重要提示: Cloudflared URL是临时的。如果重新启动Cloudflared,URL将更改,必须在GitHub上更新。

配置GitHub

# Dans votre repo GitHub :
# Settings → Webhooks → Add webhook
# URL → L'URL Cloudflare + /webhook/github
# Content type → application/json
# Events → Workflow runs, Check runs, Push, etc.

# Développer un petit workflow avec vérification du README pour tester
# Pusher le workflow et le README

🧪 完整MCP代理测试

# Exemple de question :
» Call get_workflow_status for Simple CI
<Tool epfNp9F7SOpIYsoWuBKO2pLFvUNJ4rJg>get_workflow_status {"workflow_name":"Simple CI"}

# Réponse attendue :
{
  "workflows": {
    "Simple CI": {
      "name": "Simple CI",
      "status": "completed",
      "conclusion": "success",
      "last_run": "2025-11-14T11:27:19.025573",
      "repository": "bachir00/mcp_course",
      "run_id": 19363165948,
      "html_url": "https://github.com/bachir00/mcp_course/actions/runs/19363165948",
      "head_branch": "main",
      "triggering_actor": "bachir00"
    }
  },
  "workflow_count": 1,
  "filter": "Simple CI",
  "last_updated": "2025-11-14T12:25:30.086457"
}

模块3:通知延迟

工作流程: GitHub操作→ 网络钩子→ MCP服务器→ Slack通知
数据流: github@events.json→智能分析→格式化消息

配置webhook Slack

# 1. Aller sur https://api.slack.com/apps
# 2. Créer une nouvelle app → "From scratch"
# 3. Choisir votre workspace
# 4. Aller dans "Features (sidebar)" → "Incoming Webhooks"
# 5. Activer les incoming webhooks
# 6. Cliquer "Add New Webhook to Workspace"
# 7. Choisir un canal (ex: #dev-notifications)
# 8. Copier l'URL du webhook

# Test du webhook
curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello from MCP Course!"}' "VOTRE_URL_WEBHOOK"

# ⚠️ Attention : Valider le payload selon votre terminal (cmd/powershell/linux)

环境变量配置

# IMPORTANT : L'URL webhook est sensible - ne jamais la mettre dans le code !
# Dans PowerShell avec Python env :
$env:SLACK_WEBHOOK_URL="https://hooks.slack.com/services/VOTRE/URL/WEBHOOK"

🛠️ 实施

# Fichier principal :
# D:\CoursMCP\mcp-course\projects\unit3\slack-notification\starter\server.py

# Serveur webhook (même que Module 2) :
# D:\CoursMCP\mcp-course\projects\unit3\slack-notification\starter\webhook_server.py

# Configuration identique à Module 2 :
# - Même github_events.json
# - Même cloudflare tunnel
# - On ajoute juste l'outil d'envoi de messages Slack après configuration

📌 重要提示: 小型LLM可能存在长提示的问题。你必须减少并收集一些工具。


🔗 有用链接

  • MCP文件: https://modelcontextprotocol.io/docs/develop/build-server
  • 拥抱面部MCP课程: https://huggingface.co/learn/mcp-course/
  • 微型代理: https://huggingface.co/docs/huggingface.js/main/en/tiny-agents/README
  • 柠檬水服务器: https://lemonade-server.ai/docs/server/server_integration/
  • 桌面指挥官MCP: https://github.com/wonderwhy-er/DesktopCommanderMCP

📦 主要依赖项

看 requirements.txt 和 requirements_mcp_project.txt 有关包的完整列表。

核心MCP:

  • fastmcp==2.11.2
  • mcp==1.10.1
  • python-dotenv==1.2.1
  • GitPython==3.1.45
  • requests==2.32.5

🚨 安全说明

  • ❌ 从不提交 文件 .env
  • ❌ 永远不要暴露 Webhook Slack的URL
  • ✅ Toujours利用者 敏感数据的环境变量
  • ✅ 检查 了 .gitignore 每次推之前