AI - MCP - MCP的服务开发及测试
原文链接
https://blog.csdn.net/m0_37879087/article/details/147306857
文章目录
前言
一、MCM是什么?
二、MCP Server
1.安装库
2.编写服务端代码
3.运行服务
4.调测
浏览器打开配置mcp服务:
配置 mcp服务:
查看工具
5 Client 使用MCP
总结
前言
最近MCP的发展算是非常迅猛,所以第一时间去学习了下。
一、MCM是什么?
用官方的内容
"The Model Context Protocol (MCP) is an open protocol that enables seamless integration between LLM applications and external data sources and tools. Whether you’re building an AI-powered IDE, enhancing a chat interface, or creating custom AI workflows, MCP provides a standardized way to connect LLMs with the context they need.“
翻译:
模型上下文协议 (MCP) 是一种开放协议,可在 LLM 应用程序与外部数据源和工具之间实现无缝集成。无论您是构建 AI 驱动的 IDE、增强聊天界面还是创建自定义 AI 工作流,MCP 都提供了一种标准化的方式来将 LLM 与它们所需的上下文连接起来。
我的就理解他就是中间件。在程序中似乎没有什么是中间件没法解决的,MCP就是大模型和应用之间的中间件。现在一堆大佬说的mcp是啥,大家想了解可以去搜索下。
二、MCP Server
1.安装库
pip install mcp[cli]
AI写代码
shell
1
2.编写服务端代码
代码如下:
# demo_server.py
from mcp.server.fastmcp import FastMCP
import re
mcp = FastMCP("check")
@mcp.tool()
def validate_email(email: str) -> bool:
"""判断邮箱格式是否合法"""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
@mcp.tool()
def validate_phone(phone: str) -> bool:
"""判断电话号码格式是否合法(支持中国大陆手机号码)"""
pattern = r'^1[3-9]\d{9}$'
return bool(re.match(pattern, phone))
if __name__ == "__main__":
mcp.run(transport='stdio')
AI写代码
python
运行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
3.运行服务
python demo_server.py
AI写代码
shell
1
4.调测
这里用map他们自己的工具inspector 来调测。
要先安装node 后执行下面的命令 就可以自动 安装/启动
npx @modelcontextprotocol/inspector node build/index.js
AI写代码
shell
1
看到🔍 MCP Inspector is up and running at http://127.0.0.1:6274 🚀就是启动成功了。
浏览器打开配置mcp服务:
配置 mcp服务:
Transport Type: 选择STDIO 调用本地服务。
Command : 运行指令。因为我这是python 就选择了python具体的路径E:\\APP\\Anaconda3\\envs\\mcp_env\\python.exe
Arguments: 执行参数。这里填入具体的python文件路径。
查看工具
点击 connect 、出现绿点就是成功了,然后点击 Tools -> List Tools 成功看到我们的方法
选择工具后就可以调测了。
5 Client 使用MCP
MCP 服务搞定啦。现在,就让大模型用上它,我直接用 Cursor 里的 MCP 来演示咋配置。
点击Cursor 右上角 设置 -> MCP
加入配置
{
"mcpServers": {
"hello": {
"disabled": false,
"timeout": 60,
"command": "E:\\APP\\Anaconda3\\envs\\mcp_env\\python.exe",
"args": [
"E:\\mcp\\demo_server.py"
],
"transportType": "stdio"
}
}
}
AI写代码
json
1
2
3
4
5
6
7
8
9
10
11
12
13
然后就能在对话中让Cursor调用我的方法
注意:这里对话要选Agent,对话过程要介入
总结
哎呀,AI 这发展速度真是有点让人反应不过来呀。就说去年吧,还处在用 function call 的阶段呢,近期这 MCP 好像就成大趋势了,更别说还有个 agent2Agent 了,AI 应用的开发那可以说是越来越便捷了。
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/m0_37879087/article/details/147306857
浙公网安备 33010602011771号