本文动手实现一个简单的MCP服务端的编写,并通过MCP Server 实现成绩查询的调用。
一、配置环境
安装mcp和uv, mcp要求python版本 Python >=3.10;
pip install mcp
pip install uv
二、编写并启用服务端
# get_score.py
from mcp.server.fastmcp import FastMCP
from typing import Dict, Union
import asyncio
# 创建MCP服务器实例
mcp = FastMCP("ScoreQueryServer")
# 学生成绩数据
scores: Dict[str, int] = {
"语文": 85,
"数学": 90,
"英语": 88,
}
@mcp.tool()
async def get_score(subject: str) -> Union[str, Dict[str, int]]:
"""
查询指定科目的分数
Args:
subject: 要查询的科目名称
Returns:
如果科目存在,返回包含分数的字典
如果科目不存在,返回错误信息字符串
"""
if subject in scores:
return {subject: scores[subject]}
return f"错误:没有找到科目 '{subject}' 的成绩"
if __name__ == "__main__":
try:
print("成绩查询服务正在启动,等待连接...")
mcp.run(transport='stdio')
except Exception as e:
print(f"服务器启动失败: {str(e)}")
此处使用简单的get_score函数模拟。
python get_score.py
使用上述命令运行代码
在vscode插件中安装cline,具体操作参考简单谈谈很火的MCP( Model Context Protocol,模型上下文协议)-CSDN博客
三、使用cline调用服务端
将下面的内容粘贴
"score": {
"autoApprove": [],
"disabled": false,
"timeout": 60,
"command": "python",
"args": [
"xxx/xxx/get_score.py"
],
"env": {},
"transportType": "stdio"
}
}
"xxx/xxx/get_score.py"应该为自己本地的绝对路径。
当左侧的指示灯为绿色时,表示连接成功。
在cline中输入“语文成绩是多少”。LLM会调用该工具进行查询。
“The Chinese language (语文) score is 85.”为LLM查询到的结果。
四、本地调试到服务端
mcp dev get_score.py
输入y,回车。出现下面的内容表示启用成功。进入http://127.0.0.1:6274
点击左侧的connect进行连接。
点击get_score这个Tool.
输出结果,表示server没有问题。
通过学习MCP服务端的编写,可以提高对MCP的深入理解。
官网MCP服务端代码。For Server Developers - Model Context Protocol