# {frontmatter.title}在这一章中,我们将学习如何编写一个简单的 MCP Server。我们将创建一个服务器,它能够提供用户的基本信息,如姓名、年龄、位置和兴趣爱好。
编写代码
让我们打开 main.py 文件,编写以下代码:
from mcp.server.fastmcp import FastMCP
# 初始化 FastMCP 服务器
mcp = FastMCP("about-me")
@mcp.tool()
async def get_user_name() -> str:
"""Get the user's name.
"""
return "Lucas Lee"
@mcp.tool()
async def get_user_age() -> int:
"""Get the user's age.
"""
return 30
@mcp.tool()
async def get_user_location() -> str:
"""Get the user's location.
"""
return "San Francisco, CA"
@mcp.tool()
async def get_user_interests() -> list[str]:
"""Get the user's interests.
"""
return ["travel", "food", "technology"]
if __name__ == "__main__":
# 初始化并运行服务器
mcp.run(transport='stdio')
让我们逐步解析这段代码:
## 代码解释
1. **导入必要的模块**
```python
from mcp.server.fastmcp import FastMCP我们从 MCP 库中导入 FastMCP 类,这是创建 MCP 服务器的主要类。
- 初始化服务器
mcp = FastMCP("about-me")
创建一个新的 MCP 服务器实例,名称为 "about-me"。
3. **定义工具函数**
```python
@mcp.tool()
async def get_user_name() -> str:- 使用
@mcp.tool()装饰器来标记这个函数是一个 MCP 工具 - 函数使用
async关键字,因为 MCP 服务器是异步的 - 使用类型注解
-> str指定返回值类型
实现各种信息获取功能
get_user_name(): 返回用户名get_user_age(): 返回用户年龄get_user_location(): 返回用户位置get_user_interests(): 返回用户兴趣列表
启动服务器
if __name__ == "__main__": mcp.run(transport='stdio')
- 使用 `mcp.run()` 启动服务器
- `transport='stdio'` 表示使用标准输入输出进行通信
## 自定义你的信息
你可以根据需要修改各个函数的返回值,例如:
- 修改 `get_user_name()` 返回你的真实姓名
- 在 `get_user_interests()` 中添加你的实际兴趣爱好
- 更新 `get_user_location()` 为你的所在地
## 运行服务器
完成代码编写后,你可以在终端中运行服务器:
```bash
python main.py