MCP Server & Client - 附代码
出发点
-
- 构建MCP Server ,分别通过fastapi_mcp 和 底层SSE协议
-
- 构建 MCP Client, 通过Cursor IDE 和 MCP 框架
1. MCP Server
1.1 fastapi_mcp 构建
github code
如名,在fastapi后端服务框架基础上快速构建一个mcp服务,本质上给已有的服务添加一个可供LLM Agent识别的“Card”。这里是基本的用法和案例:Code
```python
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP
app = FastAPI(title="fastapi_mcp_server测试案例")
mcp = FastApiMCP(
app,
name="Item API MCP",
description="MCP server for the Item API",
base_url="http://localhost:8000",
)
mcp.mount()
"""
@app.get("/health")
async def health():
return {"status": "ok"}"""
# 中间加入你的业务模块
...
#最后在update一下
mcp.setup_server()
得到如下的“Card”
](https://i-blog.csdnimg.cn/direct/d8bfd956ce044cffb06693af59a4e235.png)
1.2 SSE协议构建
基本的用法和案例:Code
核心代码如下
## sse传输
def create_starlette_app(mcp_server: Server, *, debug: bool = False) -> Starlette:
"""Create a Starlette application that can serve the provided mcp server with SSE."""
sse = SseServerTransport("/messages/")
async def handle_sse(request: Request) -> None:
async with sse.connect_sse(
request.scope,
request.receive,
request._send, # noqa: SLF001
) as (read_stream, write_stream):
await mcp_server.run(
read_stream,
write_stream,
mcp_server.create_initialization_options(),
)
return Starlette(
debug=debug,
routes=[
Route("/sse", endpoint=handle_sse),
Mount("/messages/", app=sse.handle_post_message),
],
)
2. MCP Client
2.1 通过Cursor构建
实际上就是为LLM配置上Agent的IP,LLM在运行时会考虑通过Tools解决一些复杂业务,首先是MCP Server Setting:

然后添加MCP Server:

添加成功后正常会在标题栏那显示为绿灯,如果为红色或者黄色,则服务可能未能配额成功,考虑的问题有:1. command环境,在conda虚拟环境中执行 python3 -m pip install mcp-proxy 然后通过 which mcp-proxy 找到mcp-proxy的绝对位置;2. ip和端口检查,ip换为本机ip。
2.2 MCP 框架
这里与前面1.2小节相匹配,实际上与fastapi_mcp构建一样,取到后端服务的功能模块作为一个 “Card", 将这些tools 统一喂给LLM,所以并不是什么难点,如何合理调用tool还是根据基础LLM的能力来决定。基本示例:Code
1246

被折叠的 条评论
为什么被折叠?



