专栏名称: 阿里云开发者
阿里巴巴官方技术号,关于阿里的技术创新均将呈现于此
目录
相关文章推荐
51好读  ›  专栏  ›  阿里云开发者

100行代码讲透MCP原理

阿里云开发者  · 公众号  · 科技公司  · 2025-04-17 08:30

主要观点总结

本文详细介绍了Model Context Protocol(MCP)的原理、通信机制和编程模型本质。通过探讨MCP的设计特点和优势,展示了其如何结合AI应用与外部系统集成进行优化。同时,通过100行左右的代码实现了一个简易版本的MCP服务,体现了MCP的灵活性和可扩展性。

关键观点总结

关键观点1: MCP的原理和通信机制


关键观点2: MCP的编程模型本质


关键观点3: 简易MCP服务的实现


关键观点4: MCP的优势和应用场景


关键观点5: 湖仓一体架构的简介




正文

请到「今天看啥」查看全文


),数据格式为纯文本的同域名URL字符串。

2.client使用POST向 endpoint(/message) 发送调用请求,POST中的body满足JSON-RPC规范,包含字段 jsonrpc method params id

3.在 /sse 长连接中返回的event满足JSON-RPC规范,包含字段 jsonrpc result id error(执行错误时)

看起好像并不复杂,我们尝试用Python来实现一下(不使用MCP Python SDK)。

from fastapi import FastAPI, Requestimport uuidfrom sse_starlette.sse import EventSourceResponsefrom pydantic import BaseModelimport json
app = FastAPI()mcpHub = {}
class McpRequest(BaseModel):    idOptional[int] = None    jsonrpc: str    method: str    params: Optional[dict] = None
class MCPServer:    def __init__(self):      self.queue = asyncio.Queue()            async def reader(self):        while True:            event = await self.queue.get()            yield event
    async def request(self, payload: McpRequest):        if payload.method == "initialize":            await self.queue.put({"event""message""data": ..})        elif payload.method == "tools/list":            ...
@app.get("/sse")async def sse():    client_id = str(uuid.uuid4())    mcp = MCPServer()    mcpHub[client_id] = mcp    await mcp.queue.put({"event""endpoint""data"f"/message?client_id={client_id}"})    return EventSourceResponse(mcp.reader())    @app.post("/message")async def message(request: Request, payload: McpRequest):    client_id = request.query_params.get("client_id")    if client_id not in mcpHub:        return "no client"    await mcpHub[client_id].request(payload)    return "ok"

在这段代码中,我们引入了这样几个设计:

1.我们使用了 asyncio.Queue() 来解耦业务流和MCP服务流。这个消息队列联动 EventSourceResponse 的数据流。每往这个消息队列打一个消息,就会自动通过 EventSourceResponse







请到「今天看啥」查看全文


推荐文章
南方人物周刊  ·  商业丨造星推手任兆年
8 年前
大爱狗狗控  ·  这令人悲痛的一幕,希望不要再重演
8 年前
中国好文章  ·  北大博士:退朋友圈保智商
7 年前
姑婆那些事儿  ·  18条APP推广经验,条条都是钱!
7 年前