MCP服务器工具

MCP是一个用于构建和测试AI协议的工具,支持快速创建和运行MCP服务器以及客户端脚本。

  • by Nasreen1717
  • 本地部署
  • 更新于
在 GitHub 查看 nasreen1717/mcp-server

使用说明

🧑‍💻 MCP项目设置指南(使用uv、MCP和uvicorn)

GitHub链接: https://github.com/panaversity/learn-agentic-ai/tree/main/03_ai_protocols/01_mcp/04_fundamental_%20primitives/01_hello_mcp_server


📁 第一步:打开终端

在VS Code中打开您的系统终端或集成终端。


📂 步骤2:创建并输入项目文件夹

uv init hello_mcp
cd hello_mcp

📦 步骤3:安装所需的软件包

a.安装MCP包:

uv add mcp

b.安装Uvicorn:

uv add uvicorn

c.在VS代码中打开项目:

code .

⚙️ 步骤4:设置Python虚拟环境

a.定位 .venv 文件夹:

  • 右键单击 .venv 文件夹和 复制完整路径.

b.在VS代码中设置Python解释器:

  1. 按 Ctrl + Shift + P 打开命令面板。
  2. 类型 Python: Select Interpreter 并选择它。
  3. 粘贴复制的路径以激活环境。

📝 第五步:做好准备 main.py 文件

a.开放 main.py

b.删除所有现有代码

c.添加以下MCP服务器代码:

from mcp.server.fastmcp import FastMCP

mcp = FastMCP(name="hello-mcp", stateless_http=True)
mcp_app = mcp.streamable_http_app()

🚀 步骤6:运行MCP服务器

uv run uvicorn main:mcp_app

或者使用端口和热重新加载:

uv run uvicorn main:mcp_app --port 8000 --reload

✅ 您的MCP服务器应已成功启动。 🔗 单击终端中显示的URL以测试服务器。


🤖 步骤7:创建并运行客户端脚本

a.停止服务器

  • 按 Ctrl + C 在终端中停止服务器。

b.安装 requests 包裹:

uv add requests

c.重新启动服务器:

uv run uvicorn main:mcp_app

d.创建新文件 client.py 并添加以下代码:

import requests

# Define the MCP server URL
url = "http://localhost:8000/mcp/"

# Set the headers to accept JSON and event-stream responses
headers = {
    "Accept": "application/json, text/event-stream",
}

# Create the JSON-RPC request body to list available tools
body = {
    "jsonrpc": "2.0",
    "method": "tools/list",
    "id": 1,
    "params": {},
}

# Send the POST request
response = requests.post(url, headers=headers, json=body)

# Stream and print each line of the response
for line in response.iter_lines():
    if line:
        print(line)

e.运行客户端脚本:

uv run client.py

✅ 您应该看到MCP服务器响应中逐行打印的工具列表。


🏁 安装完成——您现在可以构建和测试MCP工具了!