MCP服务器与客户端开发工具

提供MCP服务器与客户端的开发、测试及集成功能,支持Python项目管理和Kubernetes集群管理。

  • by shubheshswain91
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 shubheshswain91/MCP

使用说明

建立MCP项目

遵循官方的MCP文档,您将使用uv for Python项目管理来设置自己的MCP项目。

    1. 如果终端尚未打开,请在VSCode中打开终端(终端→ 新航站楼)
    1. 使用uv创建新的MCP项目
    1. 使用CLI工具添加MCP依赖项
    1. 验证您的项目结构

要运行的命令:

cd /home/lab-user
uv init flight-booking-server
cd flight-booking-server
uv add "mcp[cli]"

为什么是这些命令?

  • uv init使用pyproject.toml创建一个合适的Python项目
  • mcp[cli]包括mcp SDK和开发工具(mcp检查器)
  • 这遵循官方的MCP开发工作流程

我们创建了一个具有机场数据功能的基本服务器结构。您的任务是通过添加正确的装饰器使其成为MCP资源。

  • 打开项目目录中的server.py文件
  • 查找get_airports()函数
  • 在上面添加正确的MCP资源装饰器
  • 资源提供对AI系统的只读数据访问

⚠️ 重要提示:必须使用URI方案定义资源file://airportsMCP资源需要适当的URI方案才能被AI系统正确识别。

🦘 将您的MCP服务器连接到Roo代码 现在,让我们通过将MCP服务器连接到Roo Code AI助手来测试它!

🔧 配置MCP服务器:

  • 1.寻找roo代码插件图标(袋鼠标志🦘) 在左侧边栏中
  • 2.点击顶部的“MCP服务器”(堆叠服务器图标📚)
  • 3.点击“编辑项目MCP”按钮
  • 4.用此MCP配置替换文件内容:
{
  "mcpServers": {
    "flight-booking": {
      "command": "uv",
      "args": ["run", "python", "server.py"],
      "cwd": "/home/lab-user/flight-booking-server"
    }
  }
}

🔄 激活和测试

  • 5.保存文件并单击“刷新MCP服务器”按钮
  • 6.验证“航班预订”是否出现在服务器列表中
  • 7.点击“完成”返回聊天界面
  • 8.使用以下命令测试您的MCP服务器:
"Search for flights from LAX to JFK using the flight-booking server"
"Get airport information using the flight-booking MCP server"
"Book flight FL123 for John Doe using flight-booking server"

✅ MCP服务器完成! 您已经按照官方模式成功构建了一个完整的MCP服务器:

✅ 使用uv和官方MCP包进行正确的项目设置 ✅ 机场信息资源 ✅ 航班搜索和预订工具 ✅ AI指导提示 ✅ 使用官方MCP开发工具进行测试 ✅ 与Roo Code AI助手集成

🚀 你学到了什么:

  • 使用uv的MCP官方开发工作流程
  • 来自mcp.server.FastMCP的FastMCP框架
  • 资源、工具和即时实现模式
  • 用于服务器测试和验证的MCP检查员
  • 现实世界中的MCP服务器与AI助手的集成

🔜 下一步:

  • 探索HTTP传输:mcp.run(传输=“HTTP”)
  • 添加错误处理和输入验证
  • 与真实航班API集成

🤖 MCP客户端开发 在本实验中,您将学习如何构建以编程方式与MCP服务器交互的Python客户端。超越检查器,创建自定义自动化和集成解决方案。

您将构建的内容:

  1. 用于服务器发现的基本连接客户端
  2. 自动化工具执行客户端
  3. 具有根、采样和启发功能的高级客户
  4. 生产就绪集成模式

🌐 云环境:您将开发Python客户端,并通过HTTP传输将其连接到MCP服务器。

步骤1:启动MCP服务器

在测试MCP客户端之前,我们需要启动客户端将连接到的航班预订服务器。

  1. 打开终端并导航到服务器目录
  2. 使用具有流式http传输的MCP CLI启动MCP服务器
  3. 验证服务器是否在端口8000上运行
  4. 保持此终端打开-服务器必须继续运行
  5. 要运行的命令:
cd /home/lab-user/flight-booking-server
uv run mcp run server.py --transport streamable-http

⚠️ 重要提示:

  • 服务器在127.0.0.1:8000上运行(MCP CLI默认值)
  • 服务器启动时,您应该看到“服务器在127.0.0.1:8000上运行”
  • 所有客户端都配置为连接到http://localhost:8000/mcp/
  • 让这个终端在整个实验室都保持开放!

服务器资源发现

运行基本客户端以发现航班预订服务器提供的资源。服务器提供客户端可以访问的多种资源。

🔍 发现任务:

  1. 打开一个新终端(保持服务器终端运行!)
  2. 导航到mcp客户端项目目录
  3. 运行基本客户端以查看所有可用资源
  4. 识别机场数据之外的额外资源
  5. 运行命令:
cd /home/lab-user/mcp-client
uv run python basic_client.py

💡 在输出中查找“可用资源”部分!

输出

🔌 BASIC MCP CLIENT
========================================
🎯 Goal: Connect to flight booking server and discover capabilities
========================================
✅ Connected to MCP server successfully!

🔧 Available Tools:
  - search_flights: Search for flights between two airports
  - create_booking: Create a flight booking

📊 Available Resources:
  - file://airports/: get_airports
  - file://airlines/: get_airlines

💬 Available Prompts:
  - find_best_flight: Generate a prompt for finding the best flight within budget
  - handle_disruption: Generate a prompt for handling flight disruptions

🎉 Basic client connection successful!
✨ Server capabilities discovered successfully!


刀具参数分析

检查tools_client.py文件,了解MCP客户端如何使用特定参数调用服务器工具。

📋 分析任务:

  1. 打开并检查文件:/home/lab user/mcp client/tools_client.py
  2. 查看测试1中的search_flights工具调用
  3. 确定目的地机场参数值
  4. (可选)运行客户端以查看正在运行的工具

🔍 代码位置:

flight_result = await client.call_tool("search_flights", {
    "origin": "LAX",
    "destination": "???"
})

测试命令:

cd /home/lab-user/mcp-client
uv run python tools_client.py

输出

mcp-client on  master [?] ➜  uv run python tools_client.py 
🛠️ TOOLS & PROMPTS CLIENT
========================================
🎯 Goal: Test flight booking server tools and prompts
========================================
✅ Connected to flight booking server!

✈️ Test 1: Searching for flights...
🎯 Flight search result:
   {
  "flights": [
    {
      "id": "FL123",
      "origin": "LAX",
      "destination": "JFK",
      "price": 299
    },
    {
      "id": "FL456",
      "origin": "LAX",
      "destination": "JFK",
      "price": 399
    }
  ]
}

🎫 Test 2: Creating a booking...
🎯 Booking result:
   {
  "booking_id": "BK123",
  "flight_id": "FL123",
  "passenger": "Alice Johnson",
  "status": "confirmed"
}

🏢 Test 3: Getting airport information...
🎯 Airport information:
   {
  "LAX": {
    "name": "Los Angeles International",
    "city": "Los Angeles"
  },
  "JFK": {
    "name": "John F. Kennedy International",
    "city": "New York"
  },
  "LHR": {
    "name": "London ...

💡 Test 4: Getting flight recommendations...
🎯 Flight recommendation prompt:
   Please help me find the best flight within a $500.0 budget.
    
My preferences: economy class, direct flight

Please consider:
- Price (must be under $500.0)
- Flight duration  
- Airline reputation
- Departure times

Use the search_flights tool to find available options and provide a recommendatio...

🚨 Test 5: Getting disruption handling prompt...
🎯 Disruption handling prompt:
   A passenger's flight FL123 has been disrupted due to: weather delay

Please help resolve this by:
1. Understanding the passenger's situation
2. Finding alternative flight options using search_flights
3. Providing clear rebooking steps
4. Offering appropriate compensation if applicable

Be empathetic...

🎉 All tools and prompts tested successfully!
✨ Flight booking server is fully functional!

MCP根配置

检查roots_client.py文件,了解哪些目录作为文件系统根提供给服务器。

📋 分析任务:

  1. 打开并检查文件:/home/lab user/mcp client/roots_client.py
  2. 查看顶部定义的project_roots列表
  3. 确定当前根目录中不包括哪个目录路径
  4. (可选)运行客户端以查看根功能

🔍 代码位置:

project_roots = [
    "file:///home/lab-user/",
    "file:///home/lab-user/flight-booking-server/",
    "file:///home/lab-user/mcp-client/"
]

测试命令:

cd /home/lab-user/mcp-client
uv run python roots_client.py

输出

mcp-client on  master [?] ➜  uv run python roots_client.py 
📁 ROOTS MCP CLIENT
========================================
🎯 Goal: Provide file system access to server via roots
========================================
✅ Connected to server with roots support!

🔧 Available tools:
  - search_flights: Search for flights between two airports
  - create_booking: Create a flight booking

📊 Available resources:
  - file://airports/: get_airports
  - file://airlines/: get_airlines

📄 Testing file access capabilities...
✅ Successfully accessed airports resource
   Content length: 237 characters

🌳 Roots configuration summary:
📁 Provided 3 project roots:
   1. file:///home/lab-user/
   2. file:///home/lab-user/flight-booking-server/
   3. file:///home/lab-user/mcp-client/

💡 The server can now access files within these directories
   if it has file-related tools implemented!

🎉 Roots functionality test completed!
✨ Server now has potential access to specified directories!

实施采样支持

采样允许服务器向客户端请求LLM响应。了解如何处理这些请求。

  1. 检查sampling_client.py文件
  2. 运行它以查看采样回调的实际情况
  3. 了解如何处理CreateMessageRequestParams
  4. 查看如何返回CreateMessageResult响应

运行命令:

cd /home/lab-user/mcp-client
uv run python sampling_client.py

输出

mcp-client on  master [?] ➜  uv run python sampling_client.py 
🎭 SAMPLING MCP CLIENT
========================================
🎯 Goal: Handle server LLM sampling requests
========================================
✅ Connected to server with sampling support!

🔧 Checking for sampling-enabled tools...
  📝 create_booking: Create a flight booking

🧪 Testing potential sampling scenarios...
💡 Testing flight recommendation prompt...
✅ Prompt generated successfully (no sampling required)

🎭 Sampling callback is ready!
   If the server had tools that use ctx.session.create_message(),
   our sampling callback would handle those requests.

📋 Sampling callback features:
   - Handles travel explanation requests
   - Provides travel/flight explanations
   - Creates stories and recommendations
   - Returns contextual responses

🎉 Sampling client test completed!
✨ Ready to handle server LLM requests!

实施互动启发式

Elicitation允许服务器向客户端请求用户输入。体验真正的交互式MCP通信,服务器可以直接向您索取信息。

  1. 检查启发_client.py文件
  2. 运行它以查看交互式启发回调
  3. 了解如何捕获真实的用户输入
  4. 体验实时服务器到用户的通信

运行命令:

cd /home/lab-user/mcp-client
uv run python elicitation_client.py

输出

mcp-client on  master [?] ➜  uv run python elicitation_client.py 
🔔 ELICITATION MCP CLIENT
========================================
🎯 Goal: Handle server user input requests
========================================
✅ Connected to server with elicitation support!

🔧 Checking for interactive tools...
  ⚠️  No obvious interactive tools found
     This is normal - the basic flight server doesn't have user input tools

🧪 Testing for potential elicitation triggers...
🎫 Testing booking creation (might ask for user details)...
✅ Booking result: {
  "booking_id": "BK456",
  "flight_id": "FL456",
  "passenger": "Test User",
  "status": "confirmed"
}

🔔 Elicitation callback is ready!
   If the server had tools that use ctx.session.elicit(),
   our elicitation callback would handle those requests.

📋 Elicitation callback features:
   - Prompts user for real input when server requests
   - Handles text responses and JSON input
   - Intelligently parses responses based on request type
   - Allows user to decline with Ctrl+C
   - Supports various input formats

🎯 Example user interaction:
   • Server asks: 'Please enter your name'
   • Client prompts: 'Please enter your response: '
   • User types: 'John Smith'
   • Client sends: {'name': 'John Smith'}

💡 Supported input formats:
   • Simple text: 'John Smith' → {'name': 'John Smith'}
   • JSON: '{"name": "John", "age": 30}' → parsed as JSON
   • Numbers: '500' for budget → {'budget': 500.0, 'currency': 'USD'}
   • Confirmations: 'yes' → {'confirmation': 'yes'}

🎉 Elicitation client test completed!
✨ Ready to handle server user input requests!

完成MCP客户端实施

现在,让我们测试一个完整的客户端,它将所有MCP功能组合在一个全面的实现中。

  1. 检查complete_client.py文件
  2. 运行它以查看所有功能是否协同工作
  3. 观察分阶段测试方法
  4. 查看所有回调如何协调工作

运行命令:

cd /home/lab-user/mcp-client
uv run python complete_client.py

输出

mcp-client on  master [?] ➜  uv run python complete_client.py 
🌟 COMPLETE MCP CLIENT
==================================================
🎯 Goal: Demonstrate full MCP client capabilities
==================================================
✅ Connected with full MCP capabilities!

🔍 PHASE 1: Discovery
------------------------------
🔧 Found 2 tools:
  • search_flights: Search for flights between two airports
  • create_booking: Create a flight booking

📊 Found 2 resources:
  • file://airports/
  • file://airlines/

💬 Found 2 prompts:
  • find_best_flight: Generate a prompt for finding the best flight within budget
  • handle_disruption: Generate a prompt for handling flight disruptions

🛠️ PHASE 2: Tools Testing
------------------------------
✈️ Testing flight search...
   ✅ Result: {
  "flights": [
    {
      "id": "FL123",
      "origin": "SFO",
      "destination": "NYC",
      "price": 299
    },
    {
      "id": "FL456",
      "origin": "SFO",
      "destination": "NYC",
      "price": 399
    }
  ]
}

🎫 Testing booking creation...
   ✅ Result: {
  "booking_id": "BK789",
  "flight_id": "UA789",
  "passenger": "Sarah Wilson",
  "status": "confirmed"
}

📊 PHASE 3: Resources Testing
------------------------------
🏢 Testing airport resource...
   ✅ Retrieved 237 characters of airport data

💡 PHASE 4: Prompts Testing
------------------------------
🎯 Testing flight recommendation prompt...
   ✅ Prompt generated successfully
   📝 Message count: 1

🚨 Testing disruption handling prompt...
   ✅ Disruption prompt generated successfully

🎊 PHASE 5: Test Summary
------------------------------
✅ Client Capabilities Demonstrated:
   🔌 Basic connection and initialization
   🔧 Tool discovery and execution
   📊 Resource access and reading
   💬 Prompt generation and parameterization
   📁 Project roots provision
   🤖 LLM sampling response handling
   🔔 User input elicitation handling

🌟 Complete MCP client implementation successful!
✨ Ready for production use and integration!

建筑生产MCP客户

了解构建强大的、可投入生产的MCP客户端的关键考虑因素。

  1. 错误处理和连接重试逻辑
  2. 正确的异步/等待模式和资源清理
  3. 根和回调的安全考虑
  4. MCP客户端应用程序的测试策略

🏗️ 涵盖的最佳实践:

  • 连接管理和错误恢复
  • 回调实现模式
  • 与现有Python应用程序集成
  • MCP操作的监控和记录

Kubernetes MCP服务器与Roo代码的集成

🤖 基于人工智能的Kubernetes集群管理 在本实验中,您将学习如何将Kubernetes MCP服务器与Roo Code集成,以使用自然语言命令管理您的Kubernetes集群。这种强大的组合允许您通过AI辅助与集群进行交互。

您将完成的任务:

  1. 建筑生产MCP客户
  2. Kubernetes MCP服务器与Roo代码的集成
    1. 第一步:探索Kubernetes环境
    2. 步骤2:了解k8s mcp服务器
    3. 步骤3:拉取Docker镜像
    4. 步骤4:在Roo代码中配置MCP服务器
    5. 步骤5:连接并测试MCP服务器
    6. 第六步:实际操作任务

🌐 云环境:您将使用预配置的Kubernetes集群,并将其与Roo Code的AI功能集成。

第一步:探索Kubernetes环境

让我们从探索Kubernetes集群中已经运行的内容开始。使用kubectl命令来发现集群的当前状态。

🔍 勘探任务:

  1. 检查群集中存在哪些命名空间
  2. 列出所有命名空间中的所有Pod
  3. 检查哪些节点可用
  4. 探索任何正在运行的服务

要运行的命令:

kubectl get namespaces
kubectl get pods --all-namespaces
kubectl get nodes
kubectl get services --all-namespaces
~ ➜  k get ns
NAME              STATUS   AGE
default           Active   10h
kube-node-lease   Active   10h
kube-public       Active   10h
kube-system       Active   10h

~ ➜  k get pods --all-namespaces
NAMESPACE     NAME                                      READY   STATUS      RESTARTS   AGE
kube-system   coredns-697968c856-f5crd                  1/1     Running     0          10h
kube-system   helm-install-traefik-crd-4k8nz            0/1     Completed   0          10h
kube-system   helm-install-traefik-r5dml                0/1     Completed   2          10h
kube-system   local-path-provisioner-774c6665dc-b6jbv   1/1     Running     0          10h
kube-system   metrics-server-6f4c6675d5-t8v5k           1/1     Running     0          10h
kube-system   svclb-traefik-c6146fd4-2q72v              2/2     Running     0          10h
kube-system   traefik-c98fdf6fb-jprlp                   1/1     Running     0          10h

~ ➜  k get nodes
NAME          STATUS   ROLES                  AGE   VERSION
clusternode   Ready    control-plane,master   10h   v1.33.0+k3s1

~ ➜  kubectl get services --all-namespaces
NAMESPACE     NAME             TYPE           CLUSTER-IP      EXTERNAL-IP       PORT(S)                      AGE
default       kubernetes       ClusterIP      10.43.0.1       <none>            443/TCP                      10h
kube-system   kube-dns         ClusterIP      10.43.0.10      <none>            53/UDP,53/TCP,9153/TCP       10h
kube-system   metrics-server   ClusterIP      10.43.101.106   <none>            443/TCP                      10h
kube-system   traefik          LoadBalancer   10.43.124.103   192.168.139.224   80:31342/TCP,443:30964/TCP   10h

步骤2:了解k8s mcp服务器

在配置MCP服务器之前,让我们了解一下k8s MCP服务器提供了什么。

🔍 主要特点:

  • 16个Kubernetes工具-完整的集群管理功能
  • Pod操作-列出、描述、获取日志、删除Pod
  • 节点管理-获取节点信息和指标
  • 资源操作-创建、更新和管理Kubernetes资源
  • Helm集成-安装、升级和管理Helm图表
  • 事件监视-获取群集事件和故障排除信息

🚀 优点:

  • 自然语言集群管理
  • 人工智能故障排除
  • 自动化资源管理
  • 与Roo Code无缝集成

步骤3:拉取Docker镜像

现在,让我们准备好k8s-mcp服务器Docker镜像以供使用。

🐳 Docker任务:

  1. 从Docker Hub中提取最新的k8s mcp服务器映像
  2. 验证图像是否已成功下载
  3. 检查图像详细信息

要运行的命令:

sudo docker pull ginnux/k8s-mcp-server:latest
sudo docker images | grep k8s-mcp-server
sudo docker inspect ginnux/k8s-mcp-server:latest

步骤4:在Roo代码中配置MCP服务器

现在,让我们将k8s-mcp服务器与Roo Code集成,以便您可以使用自然语言管理Kubernetes集群。

⚙️ 配置步骤:

  1. 点击🦘 袋鼠图标打开Roo Code
  2. 点击Roo Code顶部的3台服务器图标
  3. 转到编辑项目MCP
  4. 将以下配置添加到MCP设置中

📋 要添加的配置:


{
  "mcpServers": {
    "k8s-mcp-server": {
      "command": "sudo",
      "args": [
        "docker",
        "run",
        "-i",
        "--rm",
        "-v",
        "/home/lab-user/.kube/config:/home/appuser/.kube/config:ro",
        "ginnux/k8s-mcp-server:latest",
        "--mode",
        "stdio"
      ]
    }
  }
}

🔧 配置说明:

  • sudo docker run-以提升的权限运行容器
  • -i--rm-交互模式,使用后移除容器
  • -v/home/lab user/.kube/config:/home/appuser/.kube-config:ro-将kubeconfig挂载为只读
  • --模式stdio-使用标准I/O进行MCP通信

步骤5:连接并测试MCP服务器

现在k8s mcp服务器已经配置好了,让我们测试一下连接,并开始使用它来管理您的集群。

🔗 连接测试:

让Roo Code连接到Kubernetes集群 验证连接是否正常工作

💬 试试这些自然语言命令:

  • “连接到我的Kubernetes集群”
  • “显示集群的状态”
  • “列出我集群中的所有命名空间”
  • “我有哪些节点?”

🎯 预期行为:

  • Roo代码应能识别k8s mcp服务器
  • 它应该能够执行类似kubectl的命令
  • 您应该看到自然语言的集群信息

第六步:实际操作任务

现在让我们用真实的Kubernetes操作测试k8s-mcp服务器。我们将创建资源,然后模拟故障排除场景。

🚀 任务1:创建Nginx Pod

  1. 问Roo代码:“用nginx镜像创建nginx pod”
  2. 验证pod是否已成功创建
  3. 使用Roo代码检查吊舱状态

🔍 任务2:验证Pod创建

  1. 询问Roo代码:“显示nginx pod的状态”
  2. 确认吊舱正在运行
  3. 如果需要,检查吊舱详细信息和日志

⚠️ 任务3:模拟一个破碎的场景

  1. 使用不正确的图像创建一个pod:“使用图像BUSYYBOX创建一个名为测试pod的pod”
  2. 请Roo Code确定问题的根本原因
  3. 使用自然语言进行故障排除:“为什么我的测试舱无法启动?”

🎯 学习目标:

  • 练习用AI创建Kubernetes资源
  • 学习验证资源创建
  • 体验AI驱动的故障排除
  • 了解如何在资源中断时寻求帮助