【MCP 实战3】从零搭建一个简单的示例

227 阅读1分钟

1. 第一个 MCP Server:Hello World

创建基础服务器

# src/hello_mcp/server.py
from fastmcp import FastMCP

# 创建 MCP 服务器实例
mcp = FastMCP("hello-mcp-server")

@mcp.tool(description="Say hello to someone")
async def say_hello(name: str = "World") -> str:
    """Say hello to someone."""
    message = f"Hello, {name}! Welcome to MCP!"
    return message

@mcp.tool(description="Get current server time")
async def get_time() -> str:
    """Get the current server time."""
    import datetime
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return f"Current time: {current_time}"

def main():
    """Main entry point."""
    print("Starting Hello MCP Server...")
    # 使用 HTTP 传输模式
    mcp.run(transport="streamable-http")

if __name__ == "__main__":
    main()

项目配置

# pyproject.toml
[project]
name = "hello-mcp-server"
version = "0.1.0"
description = "A simple Hello World MCP Server"
requires-python = ">=3.10"
dependencies = [
    "fastmcp>=2.8.0",
]

[project.scripts]
hello-mcp-server = "hello_mcp:main"

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
packages = ["src/hello_mcp"]

运行测试

# 创建虚拟环境
python -m venv .venv
# 激活虚拟环境
source .venv/bin/active
#安装 uv
pip install uv
# 安装项目
uv pip install -e .
# 运行服务器
hello-mcp-server

# 服务器将在 HTTP 模式下启动,默认地址: http://127.0.0.1:8000

image.png

5. 与客户端集成

Cursor 配置(HTTP 模式)

{
  "mcpServers": {
    "hello-mcp": {
      "url": "http://127.0.0.1:8000/mcp"
    }
  }
}

image.png

6. 下一步

这一篇主要内容如下:

✅ 创建基础 MCP 服务器
✅ 使用现代 fastmcp 模式
✅ 实现 MCP 工具
✅ 与 Cursor 集成

关键词AI AI 编程 Cursor MCP Python