fastapi-gql-mcp Skill 技能

FastAPI→GraphQL→MCP 零改造把任意 API 变成稳定的 2-6 tool MCP 服务

fastapi-gql-mcp 是什么

fastapi-gql-mcp(GitHub: KLR-Pattern/fastapi-gql-mcp)是把任意 FastAPI 应用零改造地变成 MCP 服务器的开源库,思路与 Tadata 的 fastapi-mcp、FastMCP.from_openapi 完全不同:它不是给每个 endpoint 映射一个 tool,而是借鉴 Apollo 提出的"GraphQL as MCP contract"模式,从 FastAPI 路由里自动派生出一份 GraphQL schema,agent 只看到 2-6 个稳定的 tool(get_schema、graphql_query、按需 progressive disclosure 出的查询),然后用 GraphQL 的字段选择 + 单次 query 多调用能力去探索和访问整个 API。

核心能力

  • 零装饰器 / 零模型改动:用户只需把 FastAPI app 传给 RouterMCP(app, name="my-app") 然后 .run(),所有契约都是从 app.routes 自动派生的,不要求用户在 route 上加任何装饰器或修改 Pydantic 模型。
  • 稳定的小 tool 集合:简单模式下只有 2 个 tool(get_schema、graphql_query),最多 6 个(包含 progressive disclosure);不像传统 FastAPI→MCP bridge 那样 endpoint 数线性膨胀、agent 上下文被打爆。
  • 字段级选择(Field Selection):agent 可写 { id name } 而不是拉整个 list 响应,把 2.8KB 的全量响应压到 610B,节省 80% 以上 token。
  • 单次 query 多 endpoint:用一份 query 同时访问多条路由,一条 query = 1 个 agent turn,对比传统 bridge 的 N 次 tool call。
  • 真实 auth 传递:query 通过真实的 ASGI app 执行,Depends、middleware、headers 都跟 HTTP 一致,per-caller header passthrough 把调用者凭据透传下去。
  • 保留所有文档:docstring、Field(description=...)、summary=、Query()/Path()/Body(description=...) 全部进 schema,agent 直接读到这些描述。
  • 失败路径清晰:返回 dict/Any 的、含 response_model_exclude_unset 的、union 类型的都降级为 JSON scalar,schema description + 启动日志同时说明降级原因与修复方法。

安装配置

  • 基础安装:uv add fastapi-gql-mcp 即可使用 GraphQL handler。
  • MCP Server 安装:uv add 'fastapi-gql-mcp[mcp]' 加上 fastmcp 集成。
  • 环境要求:Python ≥ 3.10。

使用步骤

  1. 在应用入口导入:from fastapi_gql_mcp import RouterMCP,实例化 mcp = RouterMCP(app, name="my-app")。
  2. 调用 mcp.run() 启动 HTTP MCP server(含 get_schema + graphql_query 两个 tool)。
  3. 在 MCP 客户端先调用 get_schema 拿到契约,然后调用 graphql_query 用字段选择与组合查询访问 API,例如一次取 shop.catalog.list_products { name } 与 analytics.shop_stats { revenue_cents }。
  4. 需要写操作时显式启用:RouterMCP(app, name="my-app", allow_mutation=True, mutation_include=["orders.*"]),未启用时删除 / 写入类请求在 root 拒绝;按 fnmatch glob 控制白名单。

适用场景

  • 大型 FastAPI 应用接入 Agent:endpoint 数超过 50、单 endpoint 响应超过 100KB,agent 上下文扛不住时。
  • 读多写少的内部 API:CRUD + 列表查询类,让 agent 一次拉多个 endpoint 拼装数据看板。
  • 多团队 / 多端的同一份契约:除了 Web / Mobile 之外再接入 Agent 客户端时,不需要再写一份 API 镜像。
  • 复杂权限 / 中间件链:ASGI 中间件、OAuth2 / API key 鉴权、租户隔离等要求 agent 调用和 HTTP 走同一链路时。

适用人群

  • Agent 应用开发者:正在构建 Claude / Cursor / Claude Code / Codex 插件、要把自家或客户的 API 暴露给 agent 的工程师。
  • FastAPI 重度用户:把 GraphQL 视为"按需查询的中间层"、认同 Apollo 模式的架构师。
  • **B 端 SaaS 公司:要把 MCP 能力内嵌进产品、不希望 endpoint 列表线性泄露给 agent 的工程团队。

工作原理

库内部由三个核心组件构成:RouterScanner 读 app.routes 抽取出 verb / path / params / response_model / tags / docstring;Build 阶段把这些信息用 graphql-core 拼成一份 schema——tags 变成域名分组(tags=["shop:catalog"] → { shop { catalog { ... } } })、函数名变成 leaf 字段、Pydantic 模型变成 GraphQL type、docstring 全部进 description;Execute 阶段每个 field 的 resolver 通过真实 ASGI app 调用对应 route,Depends、middleware、auth 一致,兄弟 field 并发执行,单 field 失败只 null 自己的字段。allow_mutation=False(默认)拒绝所有写入,开启写入需要显式 allow_mutation=True 并配合 mutation_include fnmatch 白名单。

官方链接

团队信息

由 AI 猎手自动发现

评论与建议

0 条评论