MCP Server & Client

MCP Server & Client - 附代码

出发点

    1. 构建MCP Server ,分别通过fastapi_mcp 和 底层SSE协议
    1. 构建 MCP Client, 通过Cursor IDEMCP 框架

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/4e2be21fa1554331ba5bae767fbbf108.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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值