背景

https://github.com/tadata-org/fastapi_mcp/tree/main


一个零配置工具,用于自动将FastAPI端点作为模型上下文协议(MCP)工具公开,极大简化了工具型 API 的接入和管理。

安装依赖

pip install uvicorn fastapi-mcp

一个最简单的例子

以下代码演示了如何用 fastapi_mcp  快速实现一个 MCP 工具:

from fastapi import FastAPI  
from fastapi_mcp import FastApiMCP  

app = FastAPI()  


@app.get("/text", operation_id="text")  
asyncdef hello_world():
    """  
    测试mcp  
    """    return"Hello World!"


mcp = FastApiMCP(  
    app, name="测试MCP",  
    description="测试",  

)  
mcp.mount(mount_path='/test-mcp')  

if __name__ == '__main__':  
    import uvicorn  

    uvicorn.run(app, host="0.0.0.0", port=8000)

使用Cherry Studio进行测试

image.png
image.png

选择「服务器发送事件(see)」
URL:http://127.0.0.1:8000/mcp
在工具中可以看到编写的工具
image.png
image.png

直接问AI「测试MCP」就会调用MCP里面的工具完成Hello World的输出
image.png
image.png

通过路由区分多个 MCP 工具

fastapi_mcp 支持一个 FastAPI 应用公开多个 MCP 接口,每个接口根据不同业务场景和权限独立管理。

import httpx
from fastapi import FastAPI, Query
from pydantic import BaseModel, Field
from fastapi_mcp import FastApiMCP

app = FastAPI()


class PageRequest(BaseModel):
    pageId: str = Field(description="查询的页面ID")


class PageInfo(BaseModel):
    title: str = Field(description="页面标题")
    html: str = Field(description="页面HTML")
    htmlAfter: str
    markdown: str = Field(description="页面Markdown")


@app.get("/text", operation_id="text")
asyncdef get_text(pageId: str = Query(..., description="要查询的页面ID")):
    """
    测试mcp
    """
    return"Hello World!"


@app.get("/page_info", response_model=PageInfo, operation_id="get_cf_page_info")
asyncdef get_page_info(pageId: str = Query(..., description="要查询的页面ID")):
    """通过 pageId 获取 CF 网页详细信息
    Args:
        pageId: 需要查询的页面唯一标识符 例如https://cf.qunhequnhe.com/pages/viewpage.action?pageId=pageId
    Returns:
        包含标题、页面信息markdown
    """
    target_url = f"http://saas-help-backend-sit.k8s-qunhe.qunhequnhe.com/saas/help/backend/article/pageInfo?pageId={pageId}"
    try:
        response = httpx.get(target_url)
        return response.json()['d']
    except Exception as e:
        raise Exception(f"Error: {e}")


cf_mcp = FastApiMCP(
    app, name="CF相关MCP",
    description="获取CF文档",
    describe_full_response_schema=True,
    describe_all_responses=True,
    include_operations=["get_cf_page_info"],
)
cf_mcp.mount(mount_path='/cf-mcp')

test_mcp = FastApiMCP(
    app, name="测试MCP",
    description="测试",
    describe_full_response_schema=True,
    describe_all_responses=True,
    include_operations=["test"],
)
test_mcp.mount(mount_path='/test-mcp')

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

使用include_operations=["get_cf_page_info"]控制mcp包含的工具
通过cf_mcp.mount(mount_path='/cf-mcp') 来让mcp对外暴露的url变化

image.png
image.png

image.png
image.png

提示词:pageId=80524359477根据这篇文章编写几个选择题(ABCD四个选项)用于新人考试
image.png
image.png

小结

fastapi_mcp 极大简化了将 FastAPI 应用接口开放为 AI 工具集的流程,仅需少量代码即可自动适配 MCP 协议,无需手动配置和维护繁琐的 OpenAPI 文档,让工具型接口更容易被大模型/智能助手集成调用。

核心优势

  • 零配置开箱即用

    通过几行代码即可将现有 FastAPI 路由暴露为标准 MCP 工具,极大缩短开发周期。

  • 灵活路由隔离

    支持多组 MCP 工具挂载在不同路径,便于按业务线、角色或权限隔离管理,满足多样化需求。

  • 自动化文档与 Schema 支持

    结合 Pydantic 能力,可自动生成响应/入参描述,提升工具的可发现性和可维护性。

  • 易于扩展与集成

    适用于内部辅助、知识库问答、流程自动化等一系列智能应用场景,助力快速将传统后端服务能力赋能 LLM 智能生态。

  • 高效协同

    多人团队协作时,前端/智能体/业务方无需关心底层接口细节,无缝实现智能助手对后端服务的能力调用。

适用场景举例

  • 企业内部知识库/业务工具曝光

    快速将已有 API 功能变为智能助手工具,让员工/客户通过对话实现复杂查询和操作。

  • 多团队多角色权限管理

    例如将管理工具、数据查询、内容生成等分别拆分为不同 MCP 接口,实现灵活的权限控制和能力组合。

  • 研发测试与迭代

    支持本地环境下热部署和多工具集成,极大提高测试效率和开发体验。

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐