{
  "canonical_name": "tadata-org/fastapi_mcp",
  "compilation_id": "pack_680e72a88a9f45b4bb43c3d64019bf6d",
  "created_at": "2026-05-17T18:37:00.380344+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=mcp_config, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=mcp_config, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `pip install fastapi-mcp` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "pip install fastapi-mcp",
      "sandbox_container_image": "python:3.12-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "llm_execute_isolated_install",
      "sandbox_validation_id": "sbx_6f9066a0e8974b1f9c5806a71a62aa7f"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_d2ac08df8bf30708fdde983e161c77dc",
    "canonical_name": "tadata-org/fastapi_mcp",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/tadata-org/fastapi_mcp",
    "slug": "fastapi-mcp",
    "source_packet_id": "phit_4bf312ca960544fc9bb7c00aa31281f5",
    "source_validation_id": "dval_246d8351a869475d81589da59486f339"
  },
  "merchandising": {
    "best_for": "需要工具连接与集成能力，并使用 mcp_host的用户",
    "github_forks": 946,
    "github_stars": 11857,
    "one_liner_en": "Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!",
    "one_liner_zh": "Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!",
    "primary_category": {
      "category_id": "tool-integrations",
      "confidence": "high",
      "name_en": "Tool Integrations",
      "name_zh": "工具连接与集成",
      "reason": "matched_keywords:mcp, api, github"
    },
    "target_user": "使用 mcp_host, claude, cursor 等宿主 AI 的用户",
    "title_en": "fastapi_mcp",
    "title_zh": "fastapi_mcp 能力包",
    "visible_tags": [
      {
        "label_en": "Security & Permissions",
        "label_zh": "安全审查与权限治理",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-security-permissions",
        "type": "product_domain"
      },
      {
        "label_en": "Web Task Automation",
        "label_zh": "网页任务自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-web-task-automation",
        "type": "user_job"
      },
      {
        "label_en": "Browser Automation",
        "label_zh": "浏览器自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-browser-automation",
        "type": "core_capability"
      },
      {
        "label_en": "Automated Workflow",
        "label_zh": "自动化工作流",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-automated-workflow",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Local-first",
        "label_zh": "本地优先",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-local-first",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_4bf312ca960544fc9bb7c00aa31281f5",
  "page_model": {
    "artifacts": {
      "artifact_slug": "fastapi-mcp",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "pip install fastapi-mcp",
          "label": "Python / pip · 官方安装入口",
          "source": "https://github.com/tadata-org/fastapi_mcp#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "安全审查与权限治理",
        "网页任务自动化",
        "浏览器自动化",
        "自动化工作流",
        "本地优先"
      ],
      "eyebrow": "工具连接与集成",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要工具连接与集成能力，并使用 mcp_host的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "mcp_host, claude, cursor",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[BUG] MCP session 404 in multi worker production environment",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_f318cbe8fc55407da8cb88f5418cce0d | https://github.com/tadata-org/fastapi_mcp/issues/189 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[BUG] MCP session 404 in multi worker production environment",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.1.8",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_11a827f3808141e4bd7b0541a8628af0 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.1.8 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.1.8",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.2.0",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_a145fff6c53f4e709ef1bb7bc291216c | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.2.0 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.2.0",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.3.4",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_6dcb58f1897f46a188514e2714e5896d | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.4 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.3.4",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。",
            "category": "配置坑",
            "evidence": [
              "capability.host_targets | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | host_targets=mcp_host, claude, cursor"
            ],
            "severity": "medium",
            "suggested_check": "列出会写入的配置文件、目录和卸载/回滚步骤。",
            "title": "可能修改宿主 AI 配置",
            "user_impact": "安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Suggestion: MCPWatch observability example for fastapi_mcp users",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_dfa72f41f3094dd5b2ffe188889f2b4f | https://github.com/tadata-org/fastapi_mcp/issues/303 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Suggestion: MCPWatch observability example for fastapi_mcp users",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_74e4280da33d49e1a3a8d576c7bb78a6 | https://github.com/tadata-org/fastapi_mcp/issues/304 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：v0.3.6",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_bdc90006d16a437798ff2766d514f3d4 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.6 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.3.6",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[BUG] Description incorrectly passed as version to MCP Server",
            "category": "维护坑",
            "evidence": [
              "community_evidence:github | cevd_2e599a8b03d649d8a47efb6b4d49f5ca | https://github.com/tadata-org/fastapi_mcp/issues/293 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[BUG] Description incorrectly passed as version to MCP Server",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.3.0",
            "category": "维护坑",
            "evidence": [
              "community_evidence:github | cevd_bc6b7bd2988b48d48920e4ffb259f147 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.0 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.3.0",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.3.3 - Fix OpenAPI Conversion Regression",
            "category": "维护坑",
            "evidence": [
              "community_evidence:github | cevd_79b96b9d35b9444c938c355c081410ac | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.3 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.3.3 - Fix OpenAPI Conversion Regression",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.4.0",
            "category": "维护坑",
            "evidence": [
              "community_evidence:github | cevd_4382c9c951e14187b76777ad8561ded9 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.4.0 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.4.0",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | last_activity_observed missing"
            ],
            "severity": "medium",
            "suggested_check": "补 GitHub 最近 commit、release、issue/PR 响应信号。",
            "title": "维护活跃度未知",
            "user_impact": "新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "downstream_validation.risk_items | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "No sandbox install has been executed yet; downstream must verify before user use.",
            "category": "安全/权限坑",
            "evidence": [
              "risks.safety_notes | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | No sandbox install has been executed yet; downstream must verify before user use."
            ],
            "severity": "medium",
            "suggested_check": "转成明确权限清单和安全审查提示。",
            "title": "存在安全注意事项",
            "user_impact": "用户安装前需要知道权限边界和敏感操作。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 22 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：配置坑 - 来源证据：[BUG] MCP session 404 in multi worker production environment。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 18,
        "forks": 946,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 11857
      },
      "source_url": "https://github.com/tadata-org/fastapi_mcp",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!",
      "title": "fastapi_mcp 能力包",
      "trial_prompt": "# fastapi_mcp - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for tadata-org/fastapi_mcp.\n\nProject:\n- Name: fastapi_mcp\n- Repository: https://github.com/tadata-org/fastapi_mcp\n- Summary: Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!\n- Host target: mcp_host, claude, cursor\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. architecture: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n2. quickstart: Quickstart Guide. Produce one small intermediate artifact and wait for confirmation.\n3. examples: Examples Overview. Produce one small intermediate artifact and wait for confirmation.\n4. auth-overview: Authentication Overview. Produce one small intermediate artifact and wait for confirmation.\n5. auth-oauth: OAuth Authentication. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/tadata-org/fastapi_mcp\n- https://github.com/tadata-org/fastapi_mcp#readme\n- fastapi_mcp/server.py\n- fastapi_mcp/openapi/convert.py\n- fastapi_mcp/transport/http.py\n- fastapi_mcp/transport/sse.py\n- fastapi_mcp/types.py\n- examples/01_basic_usage_example.py\n- examples/shared/apps/items.py\n- examples/shared/setup.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：github。github/github_issue: [BUG] MCP session 404 in multi worker production environment（https://github.com/tadata-org/fastapi_mcp/issues/189）；github/github_issue: clean_schema_for_display() strips anyOf and loses items for Optional[Lis（https://github.com/tadata-org/fastapi_mcp/issues/304）；github/github_issue: Suggestion: MCPWatch observability example for fastapi_mcp users（https://github.com/tadata-org/fastapi_mcp/issues/303）；github/github_issue: [BUG] Description incorrectly passed as version to MCP Server（https://github.com/tadata-org/fastapi_mcp/issues/293）；github/github_release: v0.4.0（https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.4.0）；github/github_release: v0.3.7（https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.7）；github/github_release: v0.3.6（https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.6）；github/github_release: v0.3.4（https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.4）；github/github_release: v0.3.3 - Fix OpenAPI Conversion Regression（https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.3）；github/github_release: v0.3.2（https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.2）；github/github_release: v0.3.1 - Authorization（https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.1）；github/github_release: v0.3.0（https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.0）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[BUG] MCP session 404 in multi worker production environment",
              "url": "https://github.com/tadata-org/fastapi_mcp/issues/189"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "clean_schema_for_display() strips anyOf and loses items for Optional[Lis",
              "url": "https://github.com/tadata-org/fastapi_mcp/issues/304"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Suggestion: MCPWatch observability example for fastapi_mcp users",
              "url": "https://github.com/tadata-org/fastapi_mcp/issues/303"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[BUG] Description incorrectly passed as version to MCP Server",
              "url": "https://github.com/tadata-org/fastapi_mcp/issues/293"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.4.0",
              "url": "https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.4.0"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.3.7",
              "url": "https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.7"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.3.6",
              "url": "https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.6"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.3.4",
              "url": "https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.4"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.3.3 - Fix OpenAPI Conversion Regression",
              "url": "https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.3"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.3.2",
              "url": "https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.2"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.3.1 - Authorization",
              "url": "https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.1"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.3.0",
              "url": "https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.0"
            }
          ],
          "status": "已收录 12 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "工具连接与集成",
      "desc": "Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!",
      "effort": "安装已验证",
      "forks": 946,
      "icon": "link",
      "name": "fastapi_mcp 能力包",
      "risk": "可发布",
      "slug": "fastapi-mcp",
      "stars": 11857,
      "tags": [
        "安全审查与权限治理",
        "网页任务自动化",
        "浏览器自动化",
        "自动化工作流",
        "本地优先"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/tadata-org/fastapi_mcp 项目说明书\n\n生成时间：2026-05-17 18:19:42 UTC\n\n## 目录\n\n- [FastAPI-MCP Home](#home)\n- [System Architecture](#architecture)\n- [Installation](#installation)\n- [Quickstart Guide](#quickstart)\n- [Examples Overview](#examples)\n- [Authentication Overview](#auth-overview)\n- [OAuth Authentication](#auth-oauth)\n- [Endpoint Filtering and Selection](#endpoint-filtering)\n- [Tool Naming and Schema](#tool-naming)\n- [Transport Configuration](#transport-config)\n- [Deployment Options](#deployment)\n- [Dynamic Tool Registration](#dynamic-registration)\n\n<a id='home'></a>\n\n## FastAPI-MCP Home\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture), [Quickstart Guide](#quickstart), [Installation](#installation)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/README.md)\n- [fastapi_mcp/__init__.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/__init__.py)\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n- [examples/01_basic_usage_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)\n- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n- [CHANGELOG.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CHANGELOG.md)\n</details>\n\n# FastAPI-MCP Home\n\n## Overview\n\nFastAPI-MCP is a bridge library that converts FastAPI applications into MCP (Model Context Protocol) servers with minimal configuration. It allows developers to expose their existing FastAPI endpoints as MCP tools, enabling AI assistants to interact with FastAPI services through the MCP protocol.\n\n资料来源：[README.md]()\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| **Authentication Built-in** | Uses existing FastAPI dependencies for auth |\n| **FastAPI-Native** | Not just another OpenAPI → MCP converter |\n| **Zero/Minimal Configuration** | Point it at your FastAPI app and it works |\n| **Schema Preservation** | Maintains request and response model schemas |\n| **Documentation Preservation** | Keeps endpoint documentation from Swagger |\n| **Flexible Deployment** | Mount MCP servers separately or with the API |\n\n资料来源：[README.md]()\n\n## Requirements\n\n- Python 3.10+ (Recommended 3.12)\n- `uv` package manager\n\n资料来源：[README.md]()\n\n## Installation\n\nThe package can be installed using `uv`:\n\n```bash\nuv add fastapi-mcp\n```\n\nFor development dependencies:\n\n```bash\nuv add --group dev <package-name>\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n## Quick Start\n\nThe simplest way to use FastAPI-MCP is to create an instance and mount it to your FastAPI app:\n\n```python\nfrom examples.shared.apps.items import app  # Your FastAPI app\nfrom fastapi_mcp import FastApiMCP\n\n# Add MCP server to the FastAPI app\nmcp = FastApiMCP(app)\n\n# Mount the MCP server to the FastAPI app\nmcp.mount_http()\n\nif __name__ == \"__main__\":\n    import uvicorn\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\nAfter mounting, your MCP server will be available at `/mcp` endpoint by default.\n\n资料来源：[examples/01_basic_usage_example.py]()\n\n## Architecture\n\n### High-Level Architecture\n\n```mermaid\ngraph TD\n    A[FastAPI Application] --> B[FastApiMCP]\n    B --> C[MCP Tools]\n    B --> D[OpenAPI Schema]\n    C --> E[AI Assistant]\n    E --> F[MCP Protocol]\n    F --> C\n    G[Authentication] --> B\n```\n\n### Component Overview\n\nThe FastAPI-MCP library consists of the following key components:\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| `FastApiMCP` | `fastapi_mcp/__init__.py` | Main class for creating MCP servers from FastAPI apps |\n| `AuthConfig` | `fastapi_mcp/types.py` | Configuration for MCP authentication |\n| `OAuthMetadata` | `fastapi_mcp/types.py` | OAuth 2.0 Server Metadata |\n| Tool Conversion | `fastapi_mcp/openapi/convert.py` | Converts OpenAPI schemas to MCP tools |\n\n资料来源：[fastapi_mcp/types.py]()\n资料来源：[fastapi_mcp/server.py]()\n\n## Configuration Options\n\n### FastApiMCP Constructor Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `app` | FastAPI | Required | The FastAPI application instance |\n| `name` | str | `\"fastapi-mcp\"` | MCP server name |\n| `description` | str | `None` | MCP server description |\n| `describe_all_responses` | bool | `False` | Include all possible response schemas |\n| `describe_full_response_schema` | bool | `False` | Include full JSON schema for responses |\n| `http_client` | httpx.AsyncClient | `None` | Custom HTTP client for API calls |\n| `include_operations` | List[str] | `None` | Operation IDs to include |\n| `exclude_operations` | List[str] | `None` | Operation IDs to exclude |\n| `include_tags` | List[str] | `None` | Tags to include |\n| `exclude_tags` | List[str] | `None` | Tags to exclude |\n| `auth_config` | AuthConfig | `None` | Authentication configuration |\n| `headers` | List[str] | `[\"authorization\"]` | Headers to forward |\n\n资料来源：[fastapi_mcp/server.py]()\n\n### Mounting Options\n\nThe MCP server can be mounted using `mount_http()`:\n\n```python\nmcp.mount_http(mount_path=\"/custom-mcp-path\")\n```\n\nDefault mount path is `/mcp`.\n\n资料来源：[fastapi_mcp/server.py]()\n\n## Endpoint Filtering\n\nFastAPI-MCP supports filtering which endpoints are exposed as MCP tools through operation IDs and tags.\n\n### Filtering Rules\n\n- Cannot use both `include_operations` and `exclude_operations` simultaneously\n- Cannot use both `include_tags` and `exclude_tags` simultaneously\n- Can combine operation filtering with tag filtering (greedy approach)\n- Endpoints matching either criteria will be included when combining filters\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py]()\n\n### Filtering Examples\n\n```python\nfrom fastapi_mcp import FastApiMCP\n\n# Include specific operation IDs\nmcp1 = FastApiMCP(\n    app,\n    include_operations=[\"get_item\", \"list_items\"]\n)\n\n# Exclude specific operation IDs\nmcp2 = FastApiMCP(\n    app,\n    exclude_operations=[\"create_item\", \"update_item\", \"delete_item\"]\n)\n\n# Include specific tags\nmcp3 = FastApiMCP(\n    app,\n    include_tags=[\"items\"]\n)\n\n# Combine filters (include mode)\nmcp4 = FastApiMCP(\n    app,\n    include_operations=[\"delete_item\"],\n    include_tags=[\"search\"],\n)\n\n# Mount with different paths\nmcp1.mount_http(mount_path=\"/filtered-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py]()\n\n### Internal Filtering Logic\n\nThe `_filter_tools` method processes filtering based on operation IDs and tags:\n\n```mermaid\ngraph TD\n    A[Tools List] --> B{Any Filters Set?}\n    B -->|No| Z[Return All Tools]\n    B -->|Yes| C[Build Operations by Tag Map]\n    C --> D{Operation ID Filter?}\n    D -->|Include| E[Keep Matching Operations]\n    D -->|Exclude| F[Remove Matching Operations]\n    E --> G{Tag Filter?}\n    F --> G\n    G -->|Include Tags| H[Keep Matching Tags]\n    G -->|Exclude Tags| I[Remove Matching Tags]\n    H --> J[Return Filtered Tools]\n    I --> J\n```\n\n资料来源：[fastapi_mcp/server.py]()\n\n## Authentication Configuration\n\nFastAPI-MCP provides built-in support for MCP authentication using OAuth 2.0.\n\n### AuthConfig Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `version` | Literal[\"2025-03-26\"] | `\"2025-03-26\"` | MCP spec version |\n| `dependencies` | Sequence[Depends] | `None` | FastAPI auth dependencies |\n| `issuer` | str | `None` | OAuth 2.0 issuer URL |\n| `oauth_metadata_url` | StrHttpUrl | `None` | OAuth metadata endpoint |\n| `authorize_url` | StrHttpUrl | `None` | Authorization endpoint |\n| `token_endpoint` | StrHttpUrl | `None` | Token endpoint |\n| `revocation_endpoint` | StrHttpUrl | `None` | Token revocation endpoint |\n| `jwks_uri` | StrHttpUrl | `None` | JWKS URI |\n| `signing_key` | str | `None` | JWT signing key |\n\n资料来源：[fastapi_mcp/types.py]()\n\n### Token Passthrough Example\n\nTo reject requests without valid authorization tokens:\n\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\ntoken_auth_scheme = HTTPBearer()\n\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)],\n    ),\n)\n\nmcp.mount_http()\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py]()\n\n### OAuth Configuration\n\nThe MCP client configuration for remote servers with auth headers:\n\n```json\n{\n  \"mcpServers\": {\n    \"remote-example\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"mcp-remote\",\n        \"http://localhost:8000/mcp\",\n        \"--header\",\n        \"Authorization:${AUTH_HEADER}\"\n      ]\n    },\n    \"env\": {\n      \"AUTH_HEADER\": \"Bearer <your-token>\"\n    }\n  }\n}\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py]()\n\n## Development Setup\n\n### Local Development Environment\n\n1. Fork the repository\n2. Clone your fork:\n\n```bash\ngit clone https://github.com/YOUR-USERNAME/fastapi_mcp.git\ncd fastapi-mcp\ngit remote add upstream https://github.com/tadata-org/fastapi_mcp.git\n```\n\n3. Set up development environment:\n\n```bash\nuv sync\n```\n\n4. Install pre-commit hooks:\n\n```bash\nuv run pre-commit install\nuv run pre-commit run\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n### Running Tests and Checks\n\n```bash\n# Run all tests\npytest\n\n# Check code formatting and style\nruff check .\nruff format .\n\n# Check types\nmypy .\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n## Version History\n\n| Version | Changes |\n|---------|---------|\n| Latest | Support for deploying MCP servers separately; endpoint filtering capabilities; `setup_server()` for dynamic routes |\n| 0.1.8 | Removed unneeded dependency |\n| 0.1.7 | Fixed syntax error (Issue #34) |\n| 0.1.6 | Hid `handle_mcp_connection` tool (Issue #23) |\n\n资料来源：[CHANGELOG.md]()\n\n## Community\n\nJoin the [MCParty Slack community](https://join.slack.com/t/themcparty/shared_invite/zt-30yxr1zdi-2FG~XjBA0xIgYSYuKe7~Xg) to connect with other MCP enthusiasts, ask questions, and share experiences with FastAPI-MCP.\n\n资料来源：[README.md]()\n\n## License\n\nMIT License. Copyright (c) 2024-2025 Tadata Inc.\n\n资料来源：[README.md]()\n资料来源：[README_zh-CN.md]()\n\n---\n\n<a id='architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[FastAPI-MCP Home](#home), [Authentication Overview](#auth-overview), [Transport Configuration](#transport-config)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [fastapi_mcp/openapi/convert.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/openapi/convert.py)\n- [fastapi_mcp/transport/http.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/transport/http.py)\n- [fastapi_mcp/transport/sse.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/transport/sse.py)\n- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n</details>\n\n# System Architecture\n\n## Overview\n\nFastAPI-MCP is a framework that automatically generates MCP (Model Context Protocol) servers from existing FastAPI applications. The architecture follows a **FastAPI-first approach**, meaning it integrates directly with FastAPI's ASGI interface rather than functioning as a separate HTTP service.\n\nThe primary design goals are:\n\n- **Native dependencies**: Use familiar FastAPI `Depends()` for authentication\n- **ASGI transport**: Communicate directly with the FastAPI app through its ASGI interface\n- **Zero/minimal configuration**: Point it at a FastAPI app and it works immediately\n- **Schema preservation**: Maintain request/response model schemas and documentation\n\n资料来源：[README.md]()\n\n## Core Components\n\n### Component Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Client Layer\"\n        MCP_CLIENT[MCP Client<br/>Claude, etc.]\n    end\n    \n    subgraph \"FastAPI-MCP Core\"\n        MCP_SERVER[FastApiMCP Server]\n        TRANSPORT[Transport Layer<br/>HTTP/SSE]\n        CONVERT[OpenAPI Converter]\n        FILTER[Tool Filter]\n    end\n    \n    subgraph \"FastAPI Application\"\n        FASTAPI[FastAPI App]\n        DEPENDS[Dependencies<br/>Auth, etc.]\n        ROUTES[Routes]\n    end\n    \n    MCP_CLIENT <--> TRANSPORT\n    MCP_SERVER --> TRANSPORT\n    MCP_SERVER --> CONVERT\n    MCP_SERVER --> FILTER\n    TRANSPORT <--> FASTAPI\n    FASTAPI --> DEPENDS\n    FASTAPI --> ROUTES\n```\n\n### FastApiMCP Server\n\nThe `FastApiMCP` class is the main entry point for the library. It handles:\n\n- MCP server initialization and lifecycle\n- Tool discovery from FastAPI endpoints\n- HTTP client operations for invoking endpoints\n- Tool filtering based on operations and tags\n- Mounting the MCP server to FastAPI applications\n\n资料来源：[fastapi_mcp/server.py:1-100]()\n\n### Transport Layer\n\nFastAPI-MCP supports multiple transport mechanisms:\n\n| Transport | Description | Use Case |\n|-----------|-------------|----------|\n| HTTP | Standard HTTP transport with JSON-RPC | Default transport |\n| SSE | Server-Sent Events | Streaming responses |\n\nThe transport layer handles:\n- Request/response serialization\n- MCP protocol encoding/decoding\n- Connection management\n\n资料来源：[fastapi_mcp/transport/http.py](), [fastapi_mcp/transport/sse.py]()\n\n### OpenAPI Schema Converter\n\nThe converter transforms FastAPI endpoint definitions into MCP tool schemas:\n\n```mermaid\ngraph LR\n    subgraph \"FastAPI\"\n        OPERATION[Operation]\n        PARAMETERS[Parameters]\n        REQUEST_BODY[Request Body]\n        RESPONSE[Response Schema]\n    end\n    \n    subgraph \"Conversion Process\"\n        VALIDATE[Validate Schema]\n        ORGANIZE[Organize Params]\n        BUILD[Build Tool Description]\n    end\n    \n    subgraph \"MCP Tool\"\n        TOOL[Tool Definition]\n        INPUT_SCHEMA[Input Schema]\n        DESCRIPTION[Description]\n    end\n    \n    OPERATION --> VALIDATE\n    PARAMETERS --> ORGANIZE\n    REQUEST_BODY --> ORGANIZE\n    VALIDATE --> BUILD\n    ORGANIZE --> BUILD\n    RESPONSE --> BUILD\n    BUILD --> TOOL\n    BUILD --> INPUT_SCHEMA\n    BUILD --> DESCRIPTION\n```\n\nThe converter processes:\n- Path, query, and header parameters separately\n- Request body schemas\n- Response schemas with optional full schema inclusion\n- Documentation from OpenAPI descriptions\n\n资料来源：[fastapi_mcp/openapi/convert.py]()\n\n## Data Flow\n\n### Tool Invocation Flow\n\n```mermaid\nsequenceDiagram\n    participant Client as MCP Client\n    participant MCP as FastApiMCP Server\n    participant Filter as Tool Filter\n    participant Convert as OpenAPI Converter\n    participant API as FastAPI App\n    participant Auth as Auth Dependencies\n\n    Client->>MCP: ListTools Request\n    MCP->>Filter: Get filtered tools\n    Filter->>Convert: Request tool definitions\n    Convert->>API: Fetch OpenAPI schema\n    API-->>Convert: OpenAPI spec\n    Convert-->>Filter: Tool definitions\n    Filter-->>MCP: Filtered tools\n    MCP-->>Client: Tool list\n\n    Client->>MCP: CallTool Request\n    MCP->>Filter: Validate tool allowed\n    Filter-->>MCP: Tool valid\n    MCP->>API: Invoke endpoint (HTTP)\n    API->>Auth: Run dependencies\n    Auth-->>API: Auth OK\n    API-->>MCP: Response\n    MCP-->>Client: Tool result\n```\n\n### Parameter Organization\n\nThe converter organizes parameters into distinct categories:\n\n| Category | OpenAPI Location | Processing |\n|----------|------------------|------------|\n| Path | `parameters[in=path]` | Required for route matching |\n| Query | `parameters[in=query]` | Optional filters |\n| Header | `parameters[in=header]` | Metadata forwarding |\n| Body | `requestBody` | JSON payload |\n\n资料来源：[fastapi_mcp/openapi/convert.py:50-80]()\n\n## Tool Filtering System\n\n### Filter Types\n\nFastAPI-MCP provides granular control over which endpoints become MCP tools:\n\n```mermaid\ngraph TD\n    subgraph \"Filter Configuration\"\n        INCL_OPS[include_operations]\n        EXCL_OPS[exclude_operations]\n        INCL_TAGS[include_tags]\n        EXCL_TAGS[exclude_tags]\n    end\n    \n    subgraph \"Operations Index\"\n        OPS_BY_TAG[Operations by Tag]\n        OPS_BY_ID[Operations by ID]\n    end\n    \n    INCL_OPS --> OPS_BY_ID\n    EXCL_OPS --> OPS_BY_ID\n    INCL_TAGS --> OPS_BY_TAG\n    EXCL_TAGS --> OPS_BY_TAG\n```\n\n### Filter Rules\n\n| Filter Type | Description | Mutual Exclusion |\n|-------------|-------------|-------------------|\n| `include_operations` | Whitelist specific operation IDs | Cannot use with `exclude_operations` |\n| `exclude_operations` | Blacklist specific operation IDs | Cannot use with `include_operations` |\n| `include_tags` | Whitelist endpoints by tag | Cannot use with `exclude_tags` |\n| `exclude_tags` | Blacklist endpoints by tag | Cannot use with `include_tags` |\n\n**Greedy Matching**: When combining operation and tag filters, endpoints matching either criteria are included.\n\n资料来源：[fastapi_mcp/server.py:80-120](), [examples/03_custom_exposed_endpoints_example.py]()\n\n## Authentication Architecture\n\n### AuthConfig Structure\n\n```python\nclass AuthConfig(BaseType):\n    version: Literal[\"2025-03-26\"]  # MCP spec version\n    dependencies: Sequence[Depends]  # FastAPI auth dependencies\n    issuer: Optional[str]  # OAuth issuer URL\n    oauth_metadata_url: Optional[StrHttpUrl]  # OAuth metadata endpoint\n    authorize_url: Optional[StrHttpUrl]  # OAuth authorization endpoint\n```\n\n### Authentication Flow\n\n```mermaid\ngraph LR\n    subgraph \"Client\"\n        REQUEST[MCP Request]\n        HEADER[Auth Header]\n    end\n    \n    subgraph \"FastAPI-MCP\"\n        FORWARD[Forward Headers]\n        VALIDATE[Validate with Depends]\n    end\n    \n    subgraph \"FastAPI App\"\n        AUTH_DEP[Auth Dependency]\n        PROTECTED[Protected Endpoint]\n    end\n    \n    REQUEST --> HEADER\n    HEADER --> FORWARD\n    FORWARD --> VALIDATE\n    VALIDATE --> AUTH_DEP\n    AUTH_DEP --> PROTECTED\n```\n\n### Header Forwarding\n\nBy default, the `authorization` header is forwarded from MCP requests to FastAPI endpoint invocations. Additional headers can be configured:\n\n```python\nmcp = FastApiMCP(\n    app,\n    headers=[\"authorization\", \"x-custom-header\"]\n)\n```\n\n资料来源：[fastapi_mcp/types.py:100-150](), [examples/08_auth_example_token_passthrough.py]()\n\n## Configuration Options\n\n### FastApiMCP Constructor Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `app` | FastAPI | Required | FastAPI application instance |\n| `name` | str | Required | MCP server name |\n| `describe_all_responses` | bool | `False` | Include all possible response schemas |\n| `describe_full_response_schema` | bool | `False` | Include full JSON schema for responses |\n| `http_client` | httpx.AsyncClient | `None` | Custom HTTP client |\n| `include_operations` | List[str] | `None` | Operation IDs to include |\n| `exclude_operations` | List[str] | `None` | Operation IDs to exclude |\n| `include_tags` | List[str] | `None` | Tags to include |\n| `exclude_tags` | List[str] | `None` | Tags to exclude |\n| `auth_config` | AuthConfig | `None` | Authentication configuration |\n| `headers` | List[str] | `[\"authorization\"]` | Headers to forward |\n\n资料来源：[fastapi_mcp/server.py:150-200]()\n\n## Type System\n\n### Core Types\n\n```mermaid\nclassDiagram\n    class BaseType {\n        +model_config: ConfigDict\n        +model_dump() dict\n    }\n    \n    class HTTPRequestInfo {\n        +method: str\n        +path: str\n        +headers: Dict\n        +cookies: Dict\n        +query_params: Dict\n        +body: Any\n    }\n    \n    class OAuthMetadata {\n        +issuer: StrHttpUrl\n        +authorization_endpoint: StrHttpUrl\n        +token_endpoint: StrHttpUrl\n        +scopes_supported: List[str]\n    }\n    \n    class AuthConfig {\n        +version: str\n        +dependencies: Sequence\n        +issuer: str\n    }\n    \n    BaseType <|-- HTTPRequestInfo\n    BaseType <|-- OAuthMetadata\n    BaseType <|-- AuthConfig\n```\n\n### HTTPRequestInfo\n\nCaptures incoming HTTP request details for authentication and routing:\n\n```python\nclass HTTPRequestInfo(BaseType):\n    method: str           # HTTP method (GET, POST, etc.)\n    path: str             # Request path\n    headers: Dict[str, str]\n    cookies: Dict[str, str]\n    query_params: Dict[str, str]\n    body: Any             # Request body\n```\n\n资料来源：[fastapi_mcp/types.py:30-50]()\n\n## Deployment Models\n\n### Integrated Deployment (Default)\n\nThe MCP server is mounted directly into the FastAPI application:\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_mcp import FastApiMCP\n\napp = FastAPI()\nmcp = FastApiMCP(app, name=\"My MCP\")\nmcp.mount_http()\n\n# MCP available at /mcp endpoint\n```\n\n### Separate Deployment\n\nFastAPI-MCP also supports running the MCP server separately from the original FastAPI application for advanced deployment scenarios.\n\n资料来源：[README.md](), [fastapi_mcp/server.py]()\n\n## HTTP Client Operations\n\n### Supported Methods\n\n| Method | Handler | Body Support | Query Support |\n|--------|---------|--------------|---------------|\n| GET | `client.get()` | No | Yes |\n| POST | `client.post()` | Yes | Yes |\n| PUT | `client.put()` | Yes | Yes |\n| DELETE | `client.delete()` | No | Yes |\n| PATCH | `client.patch()` | Yes | Yes |\n\nThe internal HTTP client executes requests to FastAPI endpoints:\n\n```python\nasync def _make_request(\n    method: str,\n    path: str,\n    query: Dict[str, Any],\n    headers: Dict[str, str],\n    body: Any\n) -> httpx.Response:\n    if method.lower() == \"get\":\n        return await client.get(path, params=query, headers=headers)\n    elif method.lower() == \"post\":\n        return await client.post(path, params=query, headers=headers, json=body)\n    # ... other methods\n```\n\n资料来源：[fastapi_mcp/server.py:30-60]()\n\n## Summary\n\nThe FastAPI-MCP architecture provides a seamless bridge between FastAPI applications and the MCP protocol:\n\n1. **Non-intrusive integration**: Mounts directly onto existing FastAPI apps\n2. **Flexible filtering**: Fine-grained control over exposed tools\n3. **Native auth**: Leverages FastAPI's dependency injection system\n4. **Schema preservation**: Maintains OpenAPI documentation and type information\n5. **Multiple transports**: Supports both HTTP and SSE for different use cases\n\nThe system is designed for zero-configuration use while providing extensive customization options for advanced scenarios.\n\n---\n\n<a id='installation'></a>\n\n## Installation\n\n### 相关页面\n\n相关主题：[FastAPI-MCP Home](#home), [Quickstart Guide](#quickstart)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [CONTRIBUTING.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CONTRIBUTING.md)\n- [README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/README.md)\n- [README_zh-CN.md](https://github.com/tadata-org/fastapi_mcp/blob/main/README_zh-CN.md)\n- [pyproject.toml](https://github.com/tadata-org/fastapi_mcp/blob/main/pyproject.toml) (implicitly referenced through workflow descriptions)\n</details>\n\n# Installation\n\nThis page provides comprehensive instructions for setting up the **fastapi-mcp** development environment, including prerequisites, installation methods, and post-installation configuration.\n\n## Overview\n\nThe **fastapi-mcp** project enables bridging FastAPI applications with the Model Context Protocol (MCP). The installation process involves setting up the Python environment, configuring the `uv` package manager, and preparing development tools for code quality assurance.\n\n资料来源：[README.md]()\n\n## Prerequisites\n\nBefore installing fastapi-mcp, ensure your system meets the following requirements.\n\n### System Requirements\n\n| Requirement | Version | Description |\n|-------------|---------|-------------|\n| Python | 3.10+ | Minimum supported Python version |\n| Python (Recommended) | 3.12 | Preferred Python version for best compatibility |\n| uv | Latest | ASTRA's Python package manager |\n\n资料来源：[README.md](), [CONTRIBUTING.md:17]()\n\n### Installing uv\n\nThe project uses `uv` as its package manager. Install `uv` by following the official documentation:\n\n```bash\n# Installation command (refer to https://docs.astral.sh/uv/getting-started/installation/)\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n```\n\nAlternatively, for pip users:\n\n```bash\npip install uv\n```\n\n资料来源：[CONTRIBUTING.md:18]()\n\n## Installation Methods\n\n### For Users: Installing the Package\n\nFor end users who want to use fastapi-mcp as a dependency:\n\n```bash\n# Using uv\nuv add fastapi-mcp\n\n# Or using pip\npip install fastapi-mcp\n```\n\n### For Developers: Setting Up the Development Environment\n\nFor contributors setting up the local development environment:\n\n```mermaid\ngraph TD\n    A[Fork Repository] --> B[Clone Your Fork]\n    B --> C[Add Upstream Remote]\n    C --> D[uv sync]\n    D --> E[Install Pre-commit Hooks]\n    E --> F[Ready for Development]\n```\n\n#### Step 1: Fork and Clone\n\n```bash\n# Fork the repository on GitHub\n# Clone your fork\ngit clone https://github.com/YOUR-USERNAME/fastapi_mcp.git\ncd fastapi-mcp\n\n# Add the upstream remote\ngit remote add upstream https://github.com/tadata-org/fastapi_mcp.git\n```\n\n资料来源：[CONTRIBUTING.md:24-35]()\n\n#### Step 2: Sync Dependencies\n\nThe `uv sync` command automatically creates and manages a virtual environment:\n\n```bash\nuv sync\n```\n\nThis command will:\n- Create a `.venv` directory with a virtual environment\n- Install all runtime dependencies from `pyproject.toml`\n- Install development dependencies (marked with `--group dev`)\n\n资料来源：[CONTRIBUTING.md:37-43]()\n\n#### Step 3: Install Pre-commit Hooks\n\nPre-commit hooks automatically run code quality checks before each commit:\n\n```bash\n# Install the hooks\nuv run pre-commit install\n\n# Run all hooks manually (optional, for verification)\nuv run pre-commit run\n```\n\n资料来源：[CONTRIBUTING.md:45-51]()\n\n## Running Commands\n\nYou have two options for executing commands within the development environment.\n\n### Option 1: Activate the Virtual Environment\n\n```bash\n# On Unix/macOS\nsource .venv/bin/activate\n\n# On Windows\n.venv\\Scripts\\activate\n\n# Then run commands directly\npytest\nmypy .\nruff check .\nruff format .\n```\n\n### Option 2: Use uv run Prefix\n\n```bash\n# Without activating the environment\nuv run pytest\nuv run mypy .\nuv run ruff check .\nuv run ruff format .\n```\n\n资料来源：[CONTRIBUTING.md:53-75]()\n\n## Adding Dependencies\n\n### Runtime Dependencies\n\nPackages needed to run the application:\n\n```bash\nuv add new-package\n```\n\n### Development Dependencies\n\nPackages needed for development, testing, or CI:\n\n```bash\nuv add --group dev new-package\n```\n\nAfter adding dependencies:\n\n1. Test that everything works with the new package\n2. Commit both `pyproject.toml` and `uv.lock` files:\n\n```bash\ngit add pyproject.toml uv.lock\ngit commit -m \"Add new-package dependency\"\n```\n\n资料来源：[CONTRIBUTING.md:77-92]()\n\n## Code Quality Tools\n\nThe project enforces code quality using the following tools:\n\n| Tool | Purpose | Command |\n|------|---------|---------|\n| **ruff** | Linting and formatting | `ruff check .` / `ruff format .` |\n| **mypy** | Type checking | `mypy .` |\n| **pytest** | Testing | `pytest` |\n| **pre-commit** | Automated checks | `pre-commit run` |\n\n资料来源：[CONTRIBUTING.md:94-104]()\n\n### Running All Checks\n\nBefore submitting a pull request, ensure all checks pass:\n\n```bash\n# Format code\nruff format .\n\n# Check code style\nruff check .\n\n# Type checking\nmypy .\n\n# Run tests\npytest\n```\n\n## Quick Start Checklist\n\nUse this checklist to verify your installation is complete:\n\n- [ ] Python 3.10+ is installed (`python --version`)\n- [ ] uv is installed (`uv --version`)\n- [ ] Repository is forked and cloned\n- [ ] `uv sync` completed successfully\n- [ ] `uv run pre-commit install` executed\n- [ ] `uv run pre-commit run` passes (or first commit triggers it)\n- [ ] `uv run pytest` runs successfully\n- [ ] `uv run mypy .` passes type checking\n\n## Troubleshooting\n\n### Common Issues\n\n**Virtual environment not found**\n```bash\nuv sync\n```\n\n**Pre-commit hooks not running**\n```bash\nuv run pre-commit install\nuv run pre-commit run --all-files\n```\n\n**Dependency conflicts**\n```bash\nuv sync --refresh\n```\n\n## Related Documentation\n\n- [Contributing Guide](CONTRIBUTING.md) - Full development workflow\n- [README](README.md) - Project overview and features\n- [GitHub Repository](https://github.com/tadata-org/fastapi_mcp) - Source code\n\n---\n\n<a id='quickstart'></a>\n\n## Quickstart Guide\n\n### 相关页面\n\n相关主题：[FastAPI-MCP Home](#home), [Examples Overview](#examples), [Endpoint Filtering and Selection](#endpoint-filtering)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [examples/01_basic_usage_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)\n- [examples/shared/apps/items.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/shared/apps/items.py)\n- [examples/shared/setup.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/shared/setup.py)\n- [examples/02_full_schema_description_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/02_full_schema_description_example.py)\n- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n</details>\n\n# Quickstart Guide\n\nThis guide provides a comprehensive walkthrough for getting started with **FastAPI-MCP**, a library that seamlessly integrates FastAPI applications with the Model Context Protocol (MCP). It allows you to expose your FastAPI endpoints as MCP tools with minimal configuration.\n\n## Prerequisites\n\nBefore getting started, ensure you have the following installed:\n\n| Requirement | Version | Notes |\n|-------------|---------|-------|\n| Python | 3.10+ (Recommended 3.12) | The project uses modern Python features |\n| uv | Latest | Package manager for dependency installation |\n\n资料来源：[README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/README.md)\n\n## Installation\n\nInstall FastAPI-MCP using uv:\n\n```bash\nuv add fastapi-mcp\n```\n\nFor development setup with all dependencies:\n\n```bash\ngit clone https://github.com/YOUR-USERNAME/fastapi_mcp.git\ncd fastapi-mcp\nuv sync\n```\n\n资料来源：[CONTRIBUTING.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CONTRIBUTING.md)\n\n## Basic Usage\n\nThe simplest way to add an MCP server to your FastAPI application involves three steps:\n\n### 1. Import FastApiMCP\n\n```python\nfrom fastapi_mcp import FastApiMCP\n```\n\n资料来源：[examples/01_basic_usage_example.py:1]()\n\n### 2. Create the MCP Server Instance\n\nPass your FastAPI app to the `FastApiMCP` constructor:\n\n```python\nfrom examples.shared.apps.items import app  # Your FastAPI app\nfrom examples.shared.setup import setup_logging\n\nfrom fastapi_mcp import FastApiMCP\n\nsetup_logging()\n\n# Add MCP server to the FastAPI app\nmcp = FastApiMCP(app)\n```\n\n资料来源：[examples/01_basic_usage_example.py:1-9]()\n\n### 3. Mount the MCP Server\n\nMount the MCP server to your FastAPI app using `mount_http()`:\n\n```python\n# Mount the MCP server to the FastAPI app\nmcp.mount_http()\n```\n\n资料来源：[examples/01_basic_usage_example.py:12]()\n\n### 4. Run the Server\n\nStart the uvicorn server:\n\n```python\nif __name__ == \"__main__\":\n    import uvicorn\n\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\n资料来源：[examples/01_basic_usage_example.py:15-18]()\n\n## Complete Basic Example\n\nHere is the full minimal example from `examples/01_basic_usage_example.py`:\n\n```python\nfrom examples.shared.apps.items import app  # The FastAPI app\nfrom examples.shared.setup import setup_logging\n\nfrom fastapi_mcp import FastApiMCP\n\nsetup_logging()\n\n# Add MCP server to the FastAPI app\nmcp = FastApiMCP(app)\n\n# Mount the MCP server to the FastAPI app\nmcp.mount_http()\n\n\nif __name__ == \"__main__\":\n    import uvicorn\n\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\n资料来源：[examples/01_basic_usage_example.py:1-19]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[FastAPI Application] --> B[FastApiMCP]\n    B --> C[MCP Server]\n    C --> D[HTTP Endpoint /mcp]\n    D --> E[MCP Client]\n    \n    F[OpenAPI Schema] --> B\n    B --> G[MCP Tools]\n    \n    style A fill:#e1f5ff\n    style C fill:#fff3e0\n    style D fill:#e8f5e9\n```\n\n## Enhanced Schema Description\n\nBy default, FastAPI-MCP provides concise tool descriptions. You can enhance the descriptions by enabling additional options:\n\n```python\nmcp = FastApiMCP(\n    app,\n    name=\"Item API MCP\",\n    description=\"MCP server for the Item API\",\n    describe_full_response_schema=True,  # Describe the full response JSON-schema\n    describe_all_responses=True,         # Describe all possible responses, not just 2XX\n)\n\nmcp.mount_http()\n```\n\n资料来源：[examples/02_full_schema_description_example.py:1-18]()\n\n## Filtering Exposed Endpoints\n\nYou can control which endpoints are exposed as MCP tools using operation IDs or tags:\n\n### Filter by Operation IDs\n\n```python\n# Include specific operations\ninclude_operations_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Operations\",\n    include_operations=[\"get_item\", \"list_items\"],\n)\n\n# Exclude specific operations\nexclude_operations_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Operations\",\n    exclude_operations=[\"create_item\", \"update_item\", \"delete_item\"],\n)\n```\n\n### Filter by Tags\n\n```python\n# Include endpoints with specific tags\ninclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Tags\",\n    include_tags=[\"items\"],\n)\n\n# Exclude endpoints with specific tags\nexclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Tags\",\n    exclude_tags=[\"search\"],\n)\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:1-50]()\n\n## Adding Authentication\n\nFastAPI-MCP supports authentication by leveraging your existing FastAPI dependencies. Use the `AuthConfig` class to configure authentication:\n\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\n# Define your authentication scheme\ntoken_auth_scheme = HTTPBearer()\n\n# Create protected endpoint\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\n# Configure MCP with authentication\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)],\n    ),\n)\n\nmcp.mount_http()\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py:1-50]()\n\n## Key Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `app` | FastAPI | Required | The FastAPI application instance |\n| `name` | str | Auto-generated | Name of the MCP server |\n| `description` | str | Auto-generated | Description of the MCP server |\n| `describe_full_response_schema` | bool | False | Include full JSON schema for responses |\n| `describe_all_responses` | bool | False | Include all response types, not just success |\n| `include_operations` | List[str] | None | Operation IDs to include |\n| `exclude_operations` | List[str] | None | Operation IDs to exclude |\n| `include_tags` | List[str] | None | Tags to include |\n| `exclude_tags` | List[str] | None | Tags to exclude |\n| `auth_config` | AuthConfig | None | Authentication configuration |\n| `headers` | List[str] | [\"authorization\"] | Headers to forward to tool invocations |\n\n资料来源：[fastapi_mcp/server.py:1-100]()\n\n## Running the Quickstart\n\nTo run the basic example:\n\n```bash\n# Navigate to the examples directory\ncd examples\n\n# Run the basic usage example\nuv run python 01_basic_usage_example.py\n```\n\nOnce running, the MCP server will be available at `http://localhost:8000/mcp`.\n\n## Verification\n\nAfter starting the server, you can verify it's working by:\n\n1. Accessing the OpenAPI docs at `http://localhost:8000/docs`\n2. Checking the MCP endpoint at `http://localhost:8000/mcp`\n\n## Next Steps\n\n- Explore [Authentication Examples](examples/08_auth_example_token_passthrough.py) for securing your MCP server\n- Learn about [Custom Endpoint Filtering](examples/03_custom_exposed_endpoints_example.py) for granular control\n- Review the [Full Schema Description](examples/02_full_schema_description_example.py) for detailed tool documentation\n\n---\n\n<a id='examples'></a>\n\n## Examples Overview\n\n### 相关页面\n\n相关主题：[Quickstart Guide](#quickstart), [OAuth Authentication](#auth-oauth), [Deployment Options](#deployment), [Dynamic Tool Registration](#dynamic-registration)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [examples/README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/README.md)\n- [examples/01_basic_usage_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)\n- [examples/04_separate_server_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/04_separate_server_example.py)\n- [examples/05_reregister_tools_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/05_reregister_tools_example.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n- [examples/09_auth_example_auth0.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/09_auth_example_auth0.py)\n</details>\n\n# Examples Overview\n\nThe `examples/` directory in the FastAPI-MCP repository provides a comprehensive collection of runnable examples demonstrating the library's capabilities. These examples serve as practical guides for developers learning how to integrate FastAPI applications with the MCP (Model Context Protocol) server infrastructure.\n\n## Directory Structure\n\nThe examples directory follows a modular organization pattern:\n\n```\nexamples/\n├── README.md\n├── 01_basic_usage_example.py\n├── 02_multiple_apps_example.py\n├── 03_custom_exposed_endpoints_example.py\n├── 04_separate_server_example.py\n├── 05_reregister_tools_example.py\n├── 06_custom_tools_example.py\n├── 07_external_app_example.py\n├── 08_auth_example_token_passthrough.py\n├── 09_auth_example_auth0.py\n├── 10_standalone_server.py\n└── shared/\n    ├── apps/\n    │   └── items.py\n    └── setup.py\n```\n\n资料来源：[examples/README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/README.md)\n\n## Example Categories\n\n### Category 1: Basic Integration\n\nThe foundational examples demonstrate core FastAPI-MCP functionality.\n\n#### 01 - Basic Usage\n\nThis is the simplest possible integration demonstrating how to mount an MCP server onto a FastAPI application.\n\n```python\nfrom examples.shared.apps.items import app  # The FastAPI app\nfrom examples.shared.setup import setup_logging\nfrom fastapi_mcp import FastApiMCP\n\nsetup_logging()\n\n# Add MCP server to the FastAPI app\nmcp = FastApiMCP(app)\n\n# Mount the MCP server to the FastAPI app\nmcp.mount_http()\n\nif __name__ == \"__main__\":\n    import uvicorn\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\n**Key Components:**\n| Component | Purpose |\n|-----------|---------|\n| `FastApiMCP(app)` | Creates MCP server instance bound to FastAPI app |\n| `mcp.mount_http()` | Exposes MCP endpoint at `/mcp` path |\n| `setup_logging()` | Configures logging for debugging |\n\n资料来源：[examples/01_basic_usage_example.py:1-19](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)\n\n### Category 2: Endpoint Filtering\n\nThese examples demonstrate how to control which FastAPI endpoints are exposed as MCP tools.\n\n#### 03 - Custom Exposed Endpoints\n\nThe filtering system allows selective exposure of endpoints using operation IDs or tags.\n\n**Filtering Rules:**\n- Cannot use both `include_operations` and `exclude_operations` simultaneously\n- Cannot use both `include_tags` and `exclude_tags` simultaneously\n- Operation filtering can be combined with tag filtering (greedy approach)\n\n```python\n# Filter by including specific operation IDs\ninclude_operations_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Operations\",\n    include_operations=[\"get_item\", \"list_items\"],\n)\n\n# Filter by excluding specific operation IDs\nexclude_operations_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Operations\",\n    exclude_operations=[\"create_item\", \"update_item\", \"delete_item\"],\n)\n\n# Filter by including specific tags\ninclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Tags\",\n    include_tags=[\"items\"],\n)\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:1-39](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)\n\n**Filtering Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `include_operations` | `List[str]` | Operation IDs to include as MCP tools |\n| `exclude_operations` | `List[str]` | Operation IDs to exclude from MCP tools |\n| `include_tags` | `List[str]` | Tags to include as MCP tools |\n| `exclude_tags` | `List[str]` | Tags to exclude from MCP tools |\n\n资料来源：[fastapi_mcp/server.py:85-100](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n\n### Category 3: Authentication Examples\n\nFastAPI-MCP supports OAuth 2.0 authentication integration using FastAPI's dependency injection system.\n\n#### 08 - Token Passthrough Authentication\n\nThis example demonstrates protecting endpoints using HTTP Bearer tokens passed through the MCP client.\n\n**Configuration for MCP Client:**\n```json\n{\n  \"mcpServers\": {\n    \"remote-example\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"mcp-remote\",\n        \"http://localhost:8000/mcp\",\n        \"--header\",\n        \"Authorization:${AUTH_HEADER}\"\n      ]\n    }\n  }\n}\n```\n\n**Server Implementation:**\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\ntoken_auth_scheme = HTTPBearer()\n\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)],\n    ),\n)\nmcp.mount_http()\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py:1-47](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n\n#### 09 - Auth0 Integration\n\nThis example shows integration with Auth0 as an OAuth 2.0 provider, demonstrating the full OAuth flow setup.\n\n```python\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\nmcp = FastApiMCP(\n    app,\n    name=\"Auth0 Protected MCP\",\n    auth_config=AuthConfig(\n        issuer=\"https://your-tenant.auth0.com\",\n        # Additional OAuth configuration\n    ),\n)\n```\n\n**AuthConfig Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `version` | `Literal[\"2025-03-26\"]` | MCP spec version (currently only \"2025-03-26\") |\n| `dependencies` | `Sequence[Depends]` | FastAPI dependencies for auth checking |\n| `issuer` | `Optional[str]` | OAuth 2.0 server issuer URL |\n| `oauth_metadata_url` | `Optional[StrHttpUrl]` | Full OAuth provider metadata endpoint URL |\n| `authorize_url` | `Optional[StrHttpUrl]` | OAuth provider authorization endpoint |\n\n资料来源：[examples/09_auth_example_auth0.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/09_auth_example_auth0.py) and [fastapi_mcp/types.py:95-140](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n\n### Category 4: Advanced Integration Patterns\n\n#### 04 - Separate Server Example\n\nDemonstrates running the MCP server as a standalone process, separate from the main FastAPI application.\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_mcp import FastApiMCP\n\napp = FastAPI()\n\n# Create MCP server\nmcp = FastApiMCP(\n    app,\n    name=\"Separate MCP Server\",\n    # Configuration options\n)\n\n# Run MCP as standalone server\nif __name__ == \"__main__\":\n    mcp.run(...)\n```\n\n资料来源：[examples/04_separate_server_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/04_separate_server_example.py)\n\n#### 05 - Reregister Tools Example\n\nDemonstrates dynamic tool reregistration, useful for applications where available tools may change at runtime.\n\n```python\nfrom fastapi_mcp import FastApiMCP\n\nmcp = FastApiMCP(app)\n\n# Initial registration\nmcp.mount_http()\n\n# Later, reregister tools\nmcp.reregister_tools()\n```\n\n资料来源：[examples/05_reregister_tools_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/05_reregister_tools_example.py)\n\n## Architecture Diagram\n\n```mermaid\ngraph TD\n    A[FastAPI Application] --> B[FastApiMCP Instance]\n    B --> C[mount_http]\n    B --> D[Separate Server]\n    \n    C --> E[MCP Endpoint /mcp]\n    D --> F[Standalone MCP Server]\n    \n    E --> G[MCP Client]\n    F --> G\n    \n    G --> H[Tool Invocations]\n    H --> I[HTTP Requests to FastAPI]\n    I --> A\n    \n    J[AuthConfig] --> B\n    J --> K[OAuth 2.0 Flow]\n    K --> L[Auth0 / OAuth Provider]\n    \n    M[Filtering Options] --> B\n    M --> N[include_operations]\n    M --> O[exclude_operations]\n    M --> P[include_tags]\n    M --> Q[exclude_tags]\n```\n\n## Common Setup Module\n\nAll examples share a common setup module that configures logging:\n\n```python\nfrom examples.shared.setup import setup_logging\n\nsetup_logging()\n```\n\nThe shared items application provides a sample FastAPI app with CRUD operations for an `Item` model, used across multiple examples:\n\n资料来源：[examples/shared/apps/items.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/shared/apps/items.py)\n\n## Running Examples\n\n### Using uv (Recommended)\n\n```bash\n# Install dependencies\nuv sync\n\n# Run an example\nuv run python examples/01_basic_usage_example.py\n```\n\n### Using pre-commit hooks\n\n```bash\nuv run pre-commit install\nuv run pre-commit run\n```\n\n资料来源：[CONTRIBUTING.md:1-30](https://github.com/tadata-org/fastapi_mcp/blob/main/CONTRIBUTING.md)\n\n## Requirements Summary\n\n| Requirement | Version | Notes |\n|-------------|---------|-------|\n| Python | 3.10+ | Recommended 3.12 |\n| Package Manager | uv | Required for development |\n\n资料来源：[README.md:45-48](https://github.com/tadata-org/fastapi_mcp/blob/main/README.md)\n\n## Example Selection Guide\n\n| Use Case | Recommended Example |\n|----------|---------------------|\n| First-time integration | 01_basic_usage_example.py |\n| Selective endpoint exposure | 03_custom_exposed_endpoints_example.py |\n| OAuth with existing tokens | 08_auth_example_token_passthrough.py |\n| Auth0 integration | 09_auth_example_auth0.py |\n| Standalone MCP server | 04_separate_server_example.py |\n| Dynamic tool updates | 05_reregister_tools_example.py |\n\n---\n\n<a id='auth-overview'></a>\n\n## Authentication Overview\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture), [OAuth Authentication](#auth-oauth)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n- [fastapi_mcp/auth/proxy.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/auth/proxy.py)\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n- [examples/09_auth_example_auth0.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/09_auth_example_auth0.py)\n</details>\n\n# Authentication Overview\n\nFastAPI-MCP provides a built-in authentication system that leverages your existing FastAPI dependencies. This approach eliminates the need to configure a separate authentication mechanism and seamlessly integrates with MCP clients that support OAuth 2.0 flows.\n\n## Architecture Overview\n\nThe authentication system in FastAPI-MCP is built around the MCP specification version `2025-03-26`. It supports two primary authentication modes:\n\n1. **Token Passthrough** - Validates bearer tokens using FastAPI dependencies\n2. **OAuth 2.0 Flow** - Full OAuth 2.0 authorization code flow with proxy endpoints\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|HTTP Request| B[FastAPI-MCP Server]\n    B -->|Validate| C{FastAPI Dependencies}\n    C -->|Valid| D[Tool Execution]\n    C -->|Invalid| E[401 Unauthorized]\n    \n    F[OAuth Flow] -->|Token Request| G[OAuth Provider]\n    G -->|Access Token| F\n    \n    B -->|Proxy| H[OAuth Metadata Endpoint]\n    B -->|Proxy| I[Authorization Endpoint]\n```\n\n## Core Data Models\n\n### AuthConfig\n\nThe `AuthConfig` class is the central configuration model for authentication in FastAPI-MCP.\n\n资料来源：[fastapi_mcp/types.py:88-147]()\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `version` | `Literal[\"2025-03-26\"]` | `\"2025-03-26\"` | MCP spec version for authorization |\n| `dependencies` | `Sequence[Depends]` | `None` | FastAPI dependencies for authentication checks |\n| `custom_oauth_metadata` | `OAuthMetadataDict` | `None` | Custom OAuth metadata instead of proxy setup |\n| `issuer` | `str` | `None` | OAuth 2.0 server issuer URL |\n| `oauth_metadata_url` | `StrHttpUrl` | `None` | Full URL of OAuth provider's metadata endpoint |\n| `authorize_url` | `StrHttpUrl` | `None` | OAuth provider's authorization endpoint URL |\n| `token_endpoint` | `StrHttpUrl` | `None` | OAuth provider's token endpoint URL |\n| `metadata_path` | `str` | `\"/.well-known/oauth-authorization-server\"` | Path to serve OAuth metadata |\n| `client_id` | `str` | `None` | OAuth client ID |\n| `client_secret` | `str` | `None` | OAuth client secret |\n| `audience` | `str` | `None` | Expected audience claim in tokens |\n| `setup_proxies` | `bool` | `False` | Whether to set up OAuth proxy endpoints |\n| `setup_fake_dynamic_registration` | `bool` | `False` | Setup fake dynamic client registration endpoint |\n| `default_scope` | `str` | `\"openid profile email\"` | Default OAuth scope |\n\n### OAuthMetadata\n\nRepresents OAuth 2.0 Server Metadata according to RFC 8414.\n\n资料来源：[fastapi_mcp/types.py:33-86]()\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `issuer` | `StrHttpUrl` | Yes | Authorization server's issuer identifier (HTTPS URL) |\n| `authorization_endpoint` | `StrHttpUrl` | No | Authorization endpoint URL |\n| `token_endpoint` | `StrHttpUrl` | Yes | Token endpoint URL |\n| `scopes_supported` | `List[str]` | No | Supported OAuth 2.0 scopes |\n| `response_types_supported` | `List[str]` | No | Supported response types |\n| `grant_types_supported` | `List[str]` | No | Supported grant types |\n\n## Authentication Setup Flow\n\nThe authentication system is initialized during `FastApiMCP` construction. The `_setup_auth_2025_03_26()` method handles the setup based on the configuration.\n\n资料来源：[fastapi_mcp/server.py:150-190]()\n\n```mermaid\nsequenceDiagram\n    participant Client as MCP Client\n    participant Server as FastAPI-MCP\n    participant Proxy as OAuth Proxies\n    participant Provider as OAuth Provider\n    \n    Note over Server: AuthConfig provided\n    Server->>Server: _setup_auth_2025_03_26()\n    \n    alt Custom OAuth Metadata\n        Server->>Proxy: setup_oauth_custom_metadata()\n        Note over Proxy: Serve custom metadata at metadata_path\n    else Setup Proxies\n        Server->>Proxy: setup_oauth_metadata_proxy()\n        Server->>Proxy: setup_oauth_authorize_proxy()\n        \n        alt Fake Dynamic Registration\n            Server->>Proxy: setup_oauth_fake_dynamic_register_endpoint()\n        end\n    end\n    \n    Client->>Server: Request with Auth Header\n    Server->>Server: Run dependencies\n    alt Dependencies Pass\n        Server->>Server: Execute Tool\n    else Dependencies Fail\n        Server-->>Client: 401 Unauthorized\n    end\n```\n\n## Proxy Endpoints\n\nFastAPI-MCP automatically sets up proxy endpoints when `setup_proxies=True` is configured.\n\n资料来源：[fastapi_mcp/auth/proxy.py:1-50]()\n\n### Metadata Proxy\n\nServes OAuth 2.0 server metadata. When `oauth_metadata_url` is not provided, it constructs the URL from `issuer` and `metadata_path`.\n\n```python\nsetup_oauth_metadata_proxy(\n    app=self.fastapi,\n    metadata_url=f\"{issuer}{metadata_path}\",\n    path=\"/.well-known/oauth-authorization-server\",\n    register_path=\"/oauth/register\"  # if setup_fake_dynamic_registration is True\n)\n```\n\n### Authorization Proxy\n\nProxies authorization requests to the OAuth provider, with fallback handling for missing parameters.\n\n资料来源：[fastapi_mcp/auth/proxy.py:80-140]()\n\n| Parameter | Purpose |\n|-----------|---------|\n| `client_id` | Default client ID when not provided by client |\n| `authorize_url` | Target OAuth authorization endpoint |\n| `audience` | Default audience when not specified |\n| `default_scope` | Default scope (`openid profile email`) |\n\n### Fake Dynamic Registration\n\nFor development or testing environments, a fake dynamic client registration endpoint can be enabled.\n\n```python\nsetup_oauth_fake_dynamic_register_endpoint(\n    app=self.fastapi,\n    client_id=\"test-client-id\",\n    client_secret=\"test-client-secret\"\n)\n```\n\n## Usage Examples\n\n### Token Passthrough Authentication\n\nThe simplest form of authentication uses FastAPI dependencies to validate bearer tokens.\n\n资料来源：[examples/08_auth_example_token_passthrough.py:1-50]()\n\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\ntoken_auth_scheme = HTTPBearer()\n\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)]\n    )\n)\n\nmcp.mount_http()\n```\n\n### Auth0 Integration\n\nFull OAuth 2.0 flow with Auth0 as the identity provider.\n\n资料来源：[examples/09_auth_example_auth0.py:1-60]()\n\n```python\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\nmcp = FastApiMCP(\n    app,\n    name=\"MCP With Auth0\",\n    auth_config=AuthConfig(\n        issuer=f\"https://{settings.auth0_domain}/\",\n        authorize_url=f\"https://{settings.auth0_domain}/authorize\",\n        oauth_metadata_url=settings.auth0_oauth_metadata_url,\n        audience=settings.auth0_audience,\n        client_id=settings.auth0_client_id,\n        client_secret=settings.auth0_client_secret,\n        dependencies=[Depends(verify_auth)],\n        setup_proxies=True,\n    )\n)\n\nmcp.mount_http()\n```\n\n## MCP Client Configuration\n\nFor token passthrough authentication, configure your MCP client to include the authorization header.\n\n```json\n{\n  \"mcpServers\": {\n    \"remote-example\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"mcp-remote\",\n        \"http://localhost:8000/mcp\",\n        \"--header\",\n        \"Authorization:${AUTH_HEADER}\"\n      ]\n    },\n    \"env\": {\n      \"AUTH_HEADER\": \"Bearer <your-token>\"\n    }\n  }\n}\n```\n\n## Key Implementation Details\n\n### Dependency Injection\n\nAuthentication is enforced through standard FastAPI dependency injection. Any `Depends()` callable that raises `HTTPException(401)` or `HTTPException(403)` will trigger the OAuth flow in supporting clients.\n\n资料来源：[fastapi_mcp/types.py:103-130]()\n\n```python\nasync def authenticate_request(request: Request, token: str = Depends(oauth2_scheme)):\n    payload = verify_token(request, token)\n    if payload is None:\n        raise HTTPException(status_code=401, detail=\"Unauthorized\")\n    return payload\n```\n\n### Metadata Serialization\n\nThe `OAuthMetadata` model uses special serialization to ensure compatibility with OAuth clients:\n\n- `exclude_unset=True` - Never include unset fields\n- `exclude_none=True` - Never include fields with `None` values\n\n资料来源：[fastapi_mcp/types.py:69-86]()\n\n### Base Type Configuration\n\nAll authentication-related models inherit from `BaseType` which configures:\n\n- `extra=\"ignore\"` - Silently ignore unexpected fields\n- `arbitrary_types_allowed=True` - Allow complex type annotations\n\n## Workflow Summary\n\n| Step | Component | Action |\n|------|-----------|--------|\n| 1 | `FastApiMCP.__init__()` | Accept `AuthConfig` parameter |\n| 2 | `setup_server()` | Call `_setup_auth_2025_03_26()` |\n| 3 | Proxy Setup | Register endpoints based on config |\n| 4 | Request Handling | Dependencies validate tokens |\n| 5 | Tool Execution | Proceed if authentication succeeds |\n\nThe authentication system is designed to be non-intrusive, requiring minimal configuration while providing full OAuth 2.0 compatibility for production deployments.\n\n---\n\n<a id='auth-oauth'></a>\n\n## OAuth Authentication\n\n### 相关页面\n\n相关主题：[Authentication Overview](#auth-overview), [Deployment Options](#deployment)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [fastapi_mcp/auth/proxy.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/auth/proxy.py)\n- [examples/09_auth_example_auth0.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/09_auth_example_auth0.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n</details>\n\n# OAuth Authentication\n\n## Overview\n\nFastAPI-MCP provides built-in OAuth 2.0 authentication support that integrates seamlessly with your existing FastAPI dependencies. The authentication system follows the MCP (Model Context Protocol) specification version 2025-03-26, enabling MCP clients to authenticate requests using OAuth 2.0 flows.\n\nThe authentication layer serves three primary purposes:\n\n1. **Metadata Discovery** - Exposes OAuth server metadata at standardized endpoints\n2. **Authorization Flow** - Proxies authorization requests to your OAuth provider\n3. **Dynamic Client Registration** - Provides a fake dynamic client registration endpoint for clients that require it\n\n## Architecture\n\nThe OAuth authentication system consists of several coordinated components that work together to bridge MCP clients with your OAuth provider.\n\n```mermaid\ngraph TD\n    subgraph \"MCP Client\"\n        A[MCP Client] -->|OAuth Request| B[MCP Server]\n    end\n    \n    subgraph \"FastAPI-MCP Server\"\n        B --> C{Auth Dependencies Check}\n        C -->|Valid Token| D[MCP Tool Handler]\n        C -->|Invalid/Missing| E[401 Unauthorized]\n        C -->|Trigger OAuth| F[OAuth Proxy Endpoints]\n        \n        F --> G[Metadata Proxy<br/>/.well-known/oauth-authorization-server]\n        F --> H[Authorize Proxy<br/>/oauth/authorize]\n        F --> I[Dynamic Registration<br/>/oauth/register]\n    end\n    \n    subgraph \"External OAuth Provider\"\n        G -->|Fetch & Transform| J[Provider Metadata]\n        H -->|Redirect| K[Provider Authorization]\n        I -->|Fake Response| L[Client Credentials]\n    end\n```\n\n### Core Components\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| `AuthConfig` | `fastapi_mcp/types.py` | Configuration container for OAuth settings |\n| `OAuthMetadata` | `fastapi_mcp/types.py` | OAuth 2.0 Server Metadata model (RFC 8414) |\n| `setup_oauth_custom_metadata()` | `fastapi_mcp/auth/proxy.py` | Serves custom OAuth metadata |\n| `setup_oauth_metadata_proxy()` | `fastapi_mcp/auth/proxy.py` | Proxies external OAuth metadata with modifications |\n| `setup_oauth_authorize_proxy()` | `fastapi_mcp/auth/proxy.py` | Proxies authorization endpoint |\n| `setup_oauth_fake_dynamic_register_endpoint()` | `fastapi_mcp/auth/proxy.py` | Provides fake client registration |\n\n## AuthConfig Specification\n\nThe `AuthConfig` class is the central configuration point for OAuth authentication in FastAPI-MCP.\n\n资料来源：[fastapi_mcp/types.py:127-217]()\n\n### Configuration Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `version` | `Literal[\"2025-03-26\"]` | `\"2025-03-26\"` | MCP spec version for authorization |\n| `dependencies` | `Sequence[Depends]` | `None` | FastAPI dependencies for auth verification |\n| `issuer` | `str` | `None` | OAuth provider issuer URL |\n| `oauth_metadata_url` | `StrHttpUrl` | `None` | Full URL of OAuth provider's metadata endpoint |\n| `authorize_url` | `StrHttpUrl` | `None` | OAuth provider's authorization endpoint |\n| `audience` | `str` | `None` | Default audience for requests |\n| `default_scope` | `str` | `\"openid profile email\"` | Default OAuth scopes |\n| `client_id` | `str` | `None` | Default client ID |\n| `client_secret` | `str` | `None` | Client secret for dynamic registration |\n| `custom_oauth_metadata` | `OAuthMetadataDict` | `None` | Custom OAuth metadata object |\n| `setup_proxies` | `bool` | `False` | Enable OAuth proxy setup |\n| `setup_fake_dynamic_registration` | `bool` | `False` | Enable fake dynamic client registration |\n| `metadata_path` | `str` | `\"/.well-known/oauth-authorization-server\"` | Path for metadata endpoint |\n\n### Example Configuration\n\n```python\nfrom fastapi import Depends\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        issuer=\"https://your-tenant.auth0.com/\",\n        authorize_url=\"https://your-tenant.auth0.com/authorize\",\n        oauth_metadata_url=\"https://your-tenant.auth0.com/.well-known/openid-configuration\",\n        audience=\"https://your-tenant.auth0.com/api/v2/\",\n        client_id=\"your-client-id\",\n        client_secret=\"your-client-secret\",\n        dependencies=[Depends(verify_auth)],\n        setup_proxies=True,\n        setup_fake_dynamic_registration=True,\n    ),\n)\n```\n\n资料来源：[examples/09_auth_example_auth0.py:1-50]()\n\n## OAuthMetadata Model\n\nThe `OAuthMetadata` class represents OAuth 2.0 Authorization Server Metadata as defined in RFC 8414.\n\n资料来源：[fastapi_mcp/types.py:36-118]()\n\n### Metadata Fields\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `issuer` | `StrHttpUrl` | Yes | Authorization server issuer identifier (https URL) |\n| `authorization_endpoint` | `StrHttpUrl` | No | Authorization endpoint URL |\n| `token_endpoint` | `StrHttpUrl` | Yes | Token endpoint URL |\n| `scopes_supported` | `List[str]` | No | Supported OAuth 2.0 scopes (default: `[\"openid\", \"profile\", \"email\"]`) |\n| `response_types_supported` | `List[str]` | No | Supported response types (default: `[\"code\"]`) |\n| `grant_types_supported` | `List[str]` | No | Supported grant types (default: `[\"authorization_code\", \"client_credentials\"]`) |\n| `token_endpoint_auth_methods_supported` | `List[str]` | No | Client auth methods (default: `[\"none\"]`) |\n| `code_challenge_methods_supported` | `List[str]` | No | PKCE challenge methods (default: `[\"S256\"]`) |\n| `registration_endpoint` | `StrHttpUrl` | No | Client registration endpoint URL |\n\n## Authentication Dependencies\n\nFastAPI-MCP leverages FastAPI's dependency injection system for authentication checks. Dependencies must raise 401 or 403 errors when requests are unauthorized, which triggers the MCP client to initiate an OAuth flow.\n\n资料来源：[fastapi_mcp/types.py:149-174]()\n\n### Dependency Implementation Pattern\n\n```python\nfrom fastapi import Depends, HTTPException, Request\nfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentials\n\nsecurity = HTTPBearer()\n\nasync def verify_auth(request: Request, credentials: HTTPAuthorizationCredentials = Depends(security)):\n    \"\"\"Verify the bearer token and return user information.\"\"\"\n    token = credentials.credentials\n    \n    # Validate token with your OAuth provider\n    payload = verify_token(token)\n    \n    if payload is None:\n        raise HTTPException(\n            status_code=401,\n            detail=\"Unauthorized\",\n            headers={\"WWW-Authenticate\": \"Bearer\"},\n        )\n    \n    return payload\n\n# Usage with FastAPI-MCP\nmcp = FastApiMCP(\n    app,\n    auth_config=AuthConfig(dependencies=[Depends(verify_auth)]),\n)\n```\n\n资料来源：[fastapi_mcp/types.py:155-172]()\n\n## OAuth Proxy Setup Functions\n\n### setup_oauth_custom_metadata()\n\nServes custom OAuth metadata provided directly in the `AuthConfig`.\n\n资料来源：[fastapi_mcp/auth/proxy.py:50-75]()\n\n```python\ndef setup_oauth_custom_metadata(\n    app: FastAPI,\n    auth_config: AuthConfig,\n    metadata: OAuthMetadataDict,\n    include_in_schema: bool = False,\n) -> None:\n    \"\"\"\n    Serve custom metadata at the path specified in auth_config.metadata_path.\n    \"\"\"\n    auth_config = AuthConfig.model_validate(auth_config)\n    metadata = OAuthMetadata.model_validate(metadata)\n\n    @app.get(\n        auth_config.metadata_path,\n        response_model=OAuthMetadata,\n        response_model_exclude_unset=True,\n        response_model_exclude_none=True,\n        include_in_schema=include_in_schema,\n        operation_id=\"oauth_custom_metadata\",\n    )\n    async def oauth_metadata_proxy():\n        return metadata\n```\n\n### setup_oauth_metadata_proxy()\n\nProxies an external OAuth provider's metadata endpoint while modifying specific fields.\n\n资料来源：[fastapi_mcp/auth/proxy.py:78-135]()\n\n```python\ndef setup_oauth_metadata_proxy(\n    app: FastAPI,\n    metadata_url: str,\n    path: str = \"/.well-known/oauth-authorization-server\",\n    authorize_path: str = \"/oauth/authorize\",\n    register_path: Optional[str] = None,\n    include_in_schema: bool = False,\n) -> None:\n    \"\"\"\n    Fetch OAuth metadata from provider and override specific endpoints.\n    \"\"\"\n    @app.get(\n        path,\n        response_model=OAuthMetadata,\n        response_model_exclude_unset=True,\n        response_model_exclude_none=True,\n        include_in_schema=include_in_schema,\n        operation_id=\"oauth_metadata_proxy\",\n    )\n    async def oauth_metadata_proxy(request: Request):\n        base_url = str(request.base_url).rstrip(\"/\")\n\n        async with httpx.AsyncClient() as client:\n            response = await client.get(metadata_url)\n            if response.status_code != 200:\n                raise HTTPException(\n                    status_code=502,\n                    detail=\"Failed to fetch OAuth metadata\",\n                )\n            oauth_metadata = response.json()\n\n        # Override registration endpoint if provided\n        if register_path:\n            oauth_metadata[\"registration_endpoint\"] = f\"{base_url}{register_path}\"\n\n        # Replace authorization endpoint with our proxy\n        oauth_metadata[\"authorization_endpoint\"] = f\"{base_url}{authorize_path}\"\n\n        return OAuthMetadata.model_validate(oauth_metadata)\n```\n\n### setup_oauth_authorize_proxy()\n\nCreates a proxy for the OAuth provider's authorization endpoint.\n\n资料来源：[fastapi_mcp/auth/proxy.py:138-210]()\n\n```python\ndef setup_oauth_authorize_proxy(\n    app: FastAPI,\n    client_id: str,\n    authorize_url: Optional[StrHttpUrl] = None,\n    audience: Optional[str] = None,\n    default_scope: str = \"openid profile email\",\n    path: str = \"/oauth/authorize\",\n) -> None:\n    \"\"\"\n    Proxy authorization requests to the OAuth provider.\n    \"\"\"\n    @app.get(\n        path,\n        response_class=RedirectResponse,\n        operation_id=\"oauth_authorize_proxy\",\n    )\n    async def oauth_authorize_proxy(request: Request, redirect_uri: str):\n        params = {\n            \"client_id\": client_id,\n            \"redirect_uri\": redirect_uri,\n            \"response_type\": \"code\",\n            \"scope\": default_scope,\n        }\n        \n        if audience:\n            params[\"audience\"] = audience\n            \n        # Redirect to actual OAuth provider\n        query = urlencode(params)\n        return f\"{authorize_url}?{query}\"\n```\n\n## Authorization Flow\n\n### MCP Spec Version 2025-03-26 Setup\n\nThe auth setup is triggered in the `FastApiMCP` initialization flow.\n\n资料来源：[fastapi_mcp/server.py:1-50]()\n\n```mermaid\nsequenceDiagram\n    participant Client as MCP Client\n    participant FastAPI as FastAPI App\n    participant Proxy as OAuth Proxies\n    participant Provider as OAuth Provider\n\n    Client->>FastAPI: MCP Request with Bearer Token\n    FastAPI->>FastAPI: Run Auth Dependencies\n    alt Token Invalid or Missing\n        FastAPI-->>Client: 401 Unauthorized\n        Client->>Proxy: Discover OAuth Metadata\n        Proxy->>Provider: Fetch Metadata\n        Provider-->>Proxy: OAuth Metadata\n        Proxy-->>Client: Modified Metadata\n        Client->>Proxy: Authorization Request\n        Proxy->>Provider: Redirect to /authorize\n        Provider-->>Client: Authorization Code\n        Client->>Proxy: Token Request\n        Proxy->>Provider: Token Exchange\n        Provider-->>Proxy: Access Token\n        Proxy-->>Client: Access Token\n        Client->>FastAPI: MCP Request with Token\n        FastAPI->>FastAPI: Validate Token\n    end\n```\n\n### Server-Side Setup Logic\n\nThe `_setup_auth_2025_03_26()` method in `FastApiMCP` orchestrates the OAuth setup:\n\n资料来源：[fastapi_mcp/server.py:50-100]()\n\n```python\ndef _setup_auth_2025_03_26(self):\n    if self._auth_config:\n        if self._auth_config.custom_oauth_metadata:\n            setup_oauth_custom_metadata(\n                app=self.fastapi,\n                auth_config=self._auth_config,\n                metadata=self._auth_config.custom_oauth_metadata,\n            )\n        elif self._auth_config.setup_proxies:\n            metadata_url = self._auth_config.oauth_metadata_url\n            if not metadata_url:\n                metadata_url = f\"{self._auth_config.issuer}{self._auth_config.metadata_path}\"\n\n            setup_oauth_metadata_proxy(\n                app=self.fastapi,\n                metadata_url=metadata_url,\n                path=self._auth_config.metadata_path,\n                register_path=\"/oauth/register\" if self._auth_config.setup_fake_dynamic_registration else None,\n            )\n            setup_oauth_authorize_proxy(\n                app=self.fastapi,\n                client_id=self._auth_config.client_id,\n                authorize_url=self._auth_config.authorize_url,\n                audience=self._auth_config.audience,\n                default_scope=self._auth_config.default_scope,\n            )\n            if self._auth_config.setup_fake_dynamic_registration:\n                setup_oauth_fake_dynamic_register_endpoint(\n                    app=self.fastapi,\n                    client_id=self._auth_config.client_id,\n                    client_secret=self._auth_config.client_secret,\n                )\n```\n\n## Complete Example: Auth0 Integration\n\nThis example demonstrates a full OAuth authentication setup with Auth0.\n\n资料来源：[examples/09_auth_example_auth0.py:1-80]()\n\n```python\nfrom fastapi import FastAPI, Depends, HTTPException, Request, status\nfrom pydantic_settings import BaseSettings\nimport logging\n\nfrom fastapi_mcp import FastApiMCP, AuthConfig\nfrom examples.shared.auth import fetch_jwks_public_key\n\nsetup_logging()\nlogger = logging.getLogger(__name__)\n\nclass Settings(BaseSettings):\n    auth0_domain: str\n    auth0_audience: str\n    auth0_client_id: str\n    auth0_client_secret: str\n\n    @property\n    def auth0_oauth_metadata_url(self):\n        return f\"https://{self.auth0_domain}/.well-known/openid-configuration\"\n\n    class Config:\n        env_file = \".env\"\n\nsettings = Settings()\n\nasync def lifespan(app: FastAPI):\n    app.state.jwks_public_key = await fetch_jwks_public_key(\n        settings.auth0_jwks_url\n    )\n    logger.info(f\"Auth0 client ID: {settings.auth0_client_id}\")\n\napp = FastAPI(lifespan=lifespan)\n\nasync def verify_auth(request: Request):\n    \"\"\"Verify JWT token from Auth0.\"\"\"\n    # Token verification logic\n    pass\n\nmcp = FastApiMCP(\n    app,\n    name=\"MCP With Auth0\",\n    description=\"Example of FastAPI-MCP with Auth0 authentication\",\n    auth_config=AuthConfig(\n        issuer=f\"https://{settings.auth0_domain}/\",\n        authorize_url=f\"https://{settings.auth0_domain}/authorize\",\n        oauth_metadata_url=settings.auth0_oauth_metadata_url,\n        audience=settings.auth0_audience,\n        client_id=settings.auth0_client_id,\n        client_secret=settings.auth0_client_secret,\n        dependencies=[Depends(verify_auth)],\n        setup_proxies=True,\n    ),\n)\n\nmcp.mount_http()\n```\n\n## Token Passthrough Example\n\nFor simpler scenarios where you just need to verify bearer tokens:\n\n资料来源：[examples/08_auth_example_token_passthrough.py:1-60]()\n\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\n\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\ntoken_auth_scheme = HTTPBearer()\n\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)],\n    ),\n)\n\nmcp.mount_http()\n```\n\n## Environment Configuration\n\nFor Auth0, create a `.env` file:\n\n```bash\nAUTH0_DOMAIN=your-tenant.auth0.com\nAUTH0_AUDIENCE=https://your-tenant.auth0.com/api/v2/\nAUTH0_CLIENT_ID=your-client-id\nAUTH0_CLIENT_SECRET=your-client-secret\n```\n\n## MCP Client Configuration\n\nConfigure your MCP client to use OAuth authentication:\n\n```json\n{\n  \"mcpServers\": {\n    \"remote-example\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"mcp-remote\",\n        \"http://localhost:8000/mcp\",\n        \"--header\",\n        \"Authorization:${AUTH_HEADER}\"\n      ]\n    },\n    \"env\": {\n      \"AUTH_HEADER\": \"Bearer <your-token>\"\n    }\n  }\n}\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py:8-22]()\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue | Cause | Solution |\n|-------|-------|----------|\n| 401 on all requests | Auth dependencies always fail | Ensure token verification returns user info instead of raising 401 |\n| Metadata endpoint returns 502 | OAuth provider unreachable | Verify `oauth_metadata_url` is correct and accessible |\n| Client not triggering OAuth | Dependencies not raising 401 | Dependencies must raise HTTPException with 401 for OAuth flow |\n| Dynamic registration fails | Fake endpoint not enabled | Set `setup_fake_dynamic_registration=True` in AuthConfig |\n\n### Debug Logging\n\nEnable debug logging to trace authentication issues:\n\n```python\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\n---\n\n<a id='endpoint-filtering'></a>\n\n## Endpoint Filtering and Selection\n\n### 相关页面\n\n相关主题：[Quickstart Guide](#quickstart), [Tool Naming and Schema](#tool-naming)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [fastapi_mcp/openapi/convert.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/openapi/convert.py)\n- [CHANGELOG.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CHANGELOG.md)\n- [examples/README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/README.md)\n</details>\n\n# Endpoint Filtering and Selection\n\nThe Endpoint Filtering and Selection feature in FastAPI-MCP provides granular control over which FastAPI endpoints are exposed as MCP tools. This allows developers to create specialized MCP servers that expose only a subset of their FastAPI API, enabling targeted integrations, improved security through principle of least privilege, and support for multi-tenant or use-case-specific MCP deployments.\n\n## Overview\n\nFastAPI-MCP automatically converts FastAPI endpoints into MCP tools by analyzing the OpenAPI schema. The filtering system operates on top of this conversion, enabling selective exposure of endpoints based on operation IDs and tags defined in the OpenAPI specification.\n\nThis feature was introduced to support:\n- **Multi-tenant deployments**: Different MCP servers for different client types\n- **Security isolation**: Limiting exposed functionality to minimize attack surface\n- **Use-case specificity**: Creating focused MCP servers for particular workflows\n- **Separate deployment**: Deploying MCP servers independently from the main API service\n\n资料来源：[CHANGELOG.md:5-11]()\n\n## Filter Parameters\n\nThe filtering is controlled through four mutually-exclusive parameters in the `FastApiMCP` constructor:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `include_operations` | `Optional[List[str]]` | List of operation IDs to include as MCP tools |\n| `exclude_operations` | `Optional[List[str]]` | List of operation IDs to exclude from MCP tools |\n| `include_tags` | `Optional[List[str]]` | List of tags to include as MCP tools |\n| `exclude_tags` | `Optional[List[str]]` | List of tags to exclude from MCP tools |\n\n资料来源：[fastapi_mcp/server.py:1-100](fastapi_mcp/server.py)\n\n### Parameter Validation Rules\n\nThe filtering system enforces several validation constraints to prevent ambiguous configurations:\n\n1. **Operation exclusion**: `include_operations` and `exclude_operations` cannot be used together\n2. **Tag exclusion**: `include_tags` and `exclude_tags` cannot be used together\n3. **Flexible combination**: Operation filtering can be combined with tag filtering using a greedy approach\n\nWhen combining filters in include mode, endpoints matching **either** the operation criteria **or** the tag criteria will be included in the MCP server.\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:1-30]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[FastAPI Application] --> B[OpenAPI Schema Generation]\n    B --> C[FastApiMCP Constructor]\n    C --> D{Filtering Parameters?}\n    D -->|No filters| E[All Tools Exposed]\n    D -->|With filters| F[_filter_tools Method]\n    \n    F --> G{include_operations?}\n    G -->|Yes| H[Filter by Operation IDs]\n    \n    F --> I{exclude_operations?}\n    I -->|Yes| J[Exclude by Operation IDs]\n    \n    F --> K{include_tags?}\n    K -->|Yes| L[Filter by Tags]\n    \n    F --> M{exclude_tags?}\n    M -->|Yes| N[Exclude by Tags]\n    \n    H --> O[Build Operations Map]\n    J --> O\n    L --> O\n    N --> O\n    O --> P[Filtered Tool List]\n    \n    P --> Q[MCP Server]\n    E --> Q\n```\n\n### Filter Logic Flow\n\n```mermaid\ngraph LR\n    A[Tools List] --> B{_include_operations<br/>is None?}\n    B -->|Yes| C{_exclude_operations<br/>is None?}\n    B -->|No| D[Keep only tools with<br/>matching operationId]\n    C -->|No| E[Remove tools with<br/>matching operationId]\n    C -->|Yes| F{_include_tags<br/>is None?}\n    D --> G[Operations By Tag Map]\n    E --> G\n    F -->|No| H[Keep tools with<br/>matching tags]\n    F -->|Yes| I{_exclude_tags<br/>is None?}\n    H --> J[Final Tool Set]\n    I -->|No| K[Remove tools with<br/>matching tags]\n    I -->|Yes| J\n    K --> J\n```\n\n## Implementation Details\n\n### The `_filter_tools` Method\n\nThe core filtering logic resides in the `_filter_tools` method within `fastapi_mcp/server.py`. This method:\n\n1. Returns the original tool list if no filters are configured\n2. Builds a mapping of tags to operation IDs from the OpenAPI schema\n3. Applies inclusion/exclusion logic based on operation IDs and tags\n4. Returns the filtered tool list\n\n```python\ndef _filter_tools(self, tools: List[types.Tool], openapi_schema: Dict[str, Any]) -> List[types.Tool]:\n    \"\"\"\n    Filter tools based on operation IDs and tags.\n    \"\"\"\n    if (\n        self._include_operations is None\n        and self._exclude_operations is None\n        and self._include_tags is None\n        and self._exclude_tags is None\n    ):\n        return tools\n\n    operations_by_tag: Dict[str, List[str]] = {}\n    for path, path_item in openapi_schema.get(\"paths\", {}).items():\n        for method, operation in path_item.items():\n            if method not in [\"get\", \"post\", \"put\", \"delete\", \"patch\"]:\n                continue\n            # ... filtering logic continues\n```\n\n资料来源：[fastapi_mcp/server.py:1-50]()\n\n### Parameter Organization in OpenAPI Conversion\n\nWhen endpoints are converted to MCP tools, parameters are organized into four categories:\n\n| Parameter Type | OpenAPI Location | Description |\n|----------------|------------------|-------------|\n| Path Parameters | `parameters[in=path]` | URL path variables |\n| Query Parameters | `parameters[in=query]` | Query string parameters |\n| Header Parameters | `parameters[in=header]` | HTTP header values |\n| Body Parameters | `requestBody` | Request body content |\n\n资料来源：[fastapi_mcp/openapi/convert.py:1-80]()\n\n## Usage Examples\n\n### Basic Operation ID Filtering\n\n```python\nfrom fastapi_mcp import FastApiMCP\n\n# Include only specific operations\ninclude_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Operations\",\n    include_operations=[\"get_item\", \"list_items\"],\n)\n\n# Exclude specific operations\nexclude_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Operations\",\n    exclude_operations=[\"create_item\", \"update_item\", \"delete_item\"],\n)\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:18-30]()\n\n### Tag-Based Filtering\n\n```python\n# Include only operations with specific tags\ninclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Tags\",\n    include_tags=[\"items\"],\n)\n\n# Exclude operations with specific tags\nexclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Tags\",\n    exclude_tags=[\"search\"],\n)\n```\n\n### Combined Filtering\n\n```python\n# Combine operation IDs and tags in include mode\ncombined_include_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Combined Include\",\n    include_operations=[\"delete_item\"],\n    include_tags=[\"search\"],\n)\n```\n\nWhen using combined include filters, the MCP server exposes endpoints that match **either** criteria—the operation ID filter **or** the tag filter. This greedy approach ensures comprehensive coverage of relevant endpoints.\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:55-65]()\n\n## Available Examples\n\nFastAPI-MCP provides a dedicated example demonstrating endpoint filtering capabilities:\n\n| Example | File | Description |\n|---------|------|-------------|\n| Custom Exposed Endpoints | `03_custom_exposed_endpoints_example.py` | Comprehensive filtering examples |\n\n资料来源：[examples/README.md:1-15]()\n\nTo run the example:\n\n```bash\ncd examples\nuv run python 03_custom_exposed_endpoints_example.py\n```\n\n## Mounting Filtered Servers\n\nAfter creating filtered MCP servers, mount them at different HTTP paths:\n\n```python\ninclude_operations_mcp.mount_http(mount_path=\"/include-operations-mcp\")\nexclude_operations_mcp.mount_http(mount_path=\"/exclude-operations-mcp\")\ninclude_tags_mcp.mount_http(mount_path=\"/include-tags-mcp\")\nexclude_tags_mcp.mount_http(mount_path=\"/exclude-tags-mcp\")\ncombined_include_mcp.mount_http(mount_path=\"/combined-include-mcp\")\n```\n\nThis allows clients to connect to specific filtered MCP servers based on their needs.\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:68-74]()\n\n## Best Practices\n\n1. **Use descriptive operation IDs**: Ensure your FastAPI endpoints have clear, consistent `operationId` values for easier filtering\n2. **Leverage tags for organization**: Group related endpoints with consistent tags to enable effective tag-based filtering\n3. **Principle of least privilege**: Only expose the minimum set of endpoints required for each MCP use case\n4. **Combine filters strategically**: Use combined include filters to create focused MCP servers that serve specific workflows\n5. **Test filtering combinations**: Verify that the greedy approach of combined filters produces the expected tool set\n\n---\n\n<a id='tool-naming'></a>\n\n## Tool Naming and Schema\n\n### 相关页面\n\n相关主题：[Endpoint Filtering and Selection](#endpoint-filtering), [System Architecture](#architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [fastapi_mcp/openapi/convert.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/openapi/convert.py)\n- [fastapi_mcp/openapi/utils.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/openapi/utils.py)\n- [examples/shared/apps/items.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/shared/apps/items.py)\n</details>\n\n# Tool Naming and Schema\n\nThis page documents how FastAPI-MCP derives MCP tool names, descriptions, and input schemas from FastAPI/OpenAPI endpoint definitions.\n\n## Overview\n\nWhen a FastAPI application is mounted as an MCP server, every route operation becomes an MCP tool. The conversion pipeline performs the following high-level steps:\n\n1. **Resolve** all `$ref` references in the OpenAPI schema\n2. **Extract** operation metadata (operationId, summary, description)\n3. **Classify** parameters by location (path, query, header)\n4. **Parse** request body schemas into tool input schemas\n5. **Generate** human-readable tool descriptions including example values\n6. **Build** the `types.Tool` objects returned to the MCP runtime\n\n资料来源：[fastapi_mcp/openapi/convert.py:21-45]()\n\n```mermaid\ngraph TD\n    A[OpenAPI Schema] --> B[resolve_schema_references]\n    B --> C[Iterate paths]\n    C --> D[Extract operationId]\n    D --> E[Classify Parameters]\n    E --> F[Parse Request Body]\n    F --> G[Build Tool Description]\n    G --> H[types.Tool]\n```\n\n## Tool Naming\n\nTool names are derived directly from the `operationId` field in the OpenAPI operation object. The function `convert_openapi_to_mcp_tools` skips any operation that lacks an `operationId`:\n\n```python\noperation_id = operation.get(\"operationId\")\nif not operation_id:\n    logger.warning(f\"Skipping non-HTTP method: {method}\")\n    continue\n```\n\n资料来源：[fastapi_mcp/openapi/convert.py:56-62]()\n\nThe resulting tool names are exactly the `operationId` strings, without any namespace prefix. For example, given a FastAPI route:\n\n```python\n@app.get(\"/items/{item_id}\", response_model=Item, operation_id=\"get_item\")\nasync def get_item(item_id: int):\n    ...\n```\n\nThe MCP tool will be named `get_item`.\n\n## Schema Resolution\n\nBefore any schema processing occurs, all JSON Pointer references (`$ref`) are resolved upfront by calling `resolve_schema_references`:\n\n```python\nresolved_openapi_schema = resolve_schema_references(openapi_schema, openapi_schema)\n```\n\nThis single-pass resolution replaces all `$ref` values with their referenced definitions, ensuring that downstream code works with concrete schemas rather than indirection.\n\n资料来源：[fastapi_mcp/openapi/convert.py:50-53]()\n\n## Parameter Classification\n\nParameters are classified by their `in` field into four groups:\n\n| Group | `in` value | Description |\n|-------|------------|-------------|\n| Path parameters | `\"path\"` | Required URL segment parameters |\n| Query parameters | `\"query\"` | Optional query string parameters |\n| Header parameters | `\"header\"` | HTTP header parameters |\n| Body parameters | `\"requestBody\"` | JSON request body (handled separately) |\n\nThe classification code:\n\n```python\nfor param in operation.get(\"parameters\", []):\n    param_name = param.get(\"name\")\n    param_in = param.get(\"in\")\n    required = param.get(\"required\", False)\n\n    if param_in == \"path\":\n        path_params.append((param_name, param))\n    elif param_in == \"query\":\n        query_params.append((param_name, param))\n    elif param_in == \"header\":\n        header_params.append((param_name, param))\n```\n\n资料来源：[fastapi_mcp/openapi/convert.py:79-93]()\n\n## Example Generation\n\nThe utility `generate_example_from_schema` produces human-readable example values for each schema type to include in tool descriptions. The function handles the following OpenAPI types:\n\n| OpenAPI Type | Generated Example |\n|--------------|-------------------|\n| `string` (no format) | `\"string\"` or the `title` field value |\n| `string` with `format: date-time` | `\"2023-01-01T00:00:00Z\"` |\n| `string` with `format: date` | `\"2023-01-01\"` |\n| `string` with `format: email` | `\"user@example.com\"` |\n| `string` with `format: uri` | `\"https://example.com\"` |\n| `integer` | `1` |\n| `number` | `1.0` |\n| `boolean` | `true` |\n| `array` | A single-item array with an example of the `items` type |\n| `object` | A dict with one example per `properties` entry |\n| `null` | `null` |\n\n资料来源：[fastapi_mcp/openapi/utils.py:45-70]()\n\n### Object Schema Example\n\n```python\nelif schema_type == \"object\":\n    result = {}\n    if \"properties\" in schema:\n        for prop_name, prop_schema in schema[\"properties\"].items():\n            prop_example = generate_example_from_schema(prop_schema)\n            if prop_example is not None:\n                result[prop_name] = prop_example\n    return result\n```\n\n### Array Schema Example\n\n```python\nelif schema_type == \"array\":\n    if \"items\" in schema:\n        item_example = generate_example_from_schema(schema[\"items\"])\n        if item_example is not None:\n            return [item_example]\n    return []\n```\n\n## Tool Description Building\n\nThe `convert_openapi_to_mcp_tools` function constructs a human-readable `description` field for each tool by concatenating:\n\n1. The operation's `summary` and `description` fields from OpenAPI\n2. Parameter documentation with names, types, required status, and descriptions\n3. Request body schema details (if present)\n4. Output schema with example values\n\n```python\ntool_description += response_info\n```\n\nThe response information is only included when the `describe_all_responses` or `describe_full_response_schema` flags are set. The description includes:\n- The HTTP method and path\n- Parameter documentation grouped by type\n- Request body schema examples\n- Output schema examples for both array and object responses\n\n## Output Schema Handling\n\nResponse schemas are processed to produce two display formats:\n\n1. **Array responses**: The `items` schema is extracted and shown as an array of items with the item structure\n2. **Object responses**: The full `properties` schema is displayed\n\n```python\nif items_schema := schema.get(\"items\", {}).get(\"properties\"):\n    response_info += \"\\n\\n**Output Schema:** Array of items with the following structure:\\n```json\\n\"\n    response_info += json.dumps(items_schema, indent=2)\nelif \"properties\" in display_schema:\n    response_info += \"\\n\\n**Output Schema:**\\n```json\\n\"\n    response_info += json.dumps(display_schema, indent=2)\n```\n\n## Supported HTTP Methods\n\nOnly standard HTTP methods are converted to tools:\n\n```python\nif method not in [\"get\", \"post\", \"put\", \"delete\", \"patch\"]:\n    logger.warning(f\"Skipping non-HTTP method: {method}\")\n    continue\n```\n\n| Method | Supported |\n|--------|-----------|\n| GET | Yes |\n| POST | Yes |\n| PUT | Yes |\n| DELETE | Yes |\n| PATCH | Yes |\n| HEAD, OPTIONS, etc. | No (logged and skipped) |\n\n## Related Utilities\n\n| Function | File | Purpose |\n|----------|------|---------|\n| `resolve_schema_references` | `openapi/utils.py` | Resolves all `$ref` pointers in the schema |\n| `generate_example_from_schema` | `openapi/utils.py` | Creates example values for tool descriptions |\n| `clean_schema_for_display` | `openapi/utils.py` | Sanitizes schema for display |\n| `get_single_param_type_from_schema` | `openapi/utils.py` | Extracts parameter type from schema |\n| `convert_openapi_to_mcp_tools` | `openapi/convert.py` | Main conversion function |\n\n---\n\n<a id='transport-config'></a>\n\n## Transport Configuration\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture), [Deployment Options](#deployment)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n- [examples/01_basic_usage_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)\n- [examples/07_configure_http_timeout_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/07_configure_http_timeout_example.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n</details>\n\n# Transport Configuration\n\nFastAPI-MCP supports multiple transport mechanisms for exposing MCP (Model Context Protocol) servers. This document covers the available transport options, configuration parameters, and how to customize transport behavior for different deployment scenarios.\n\n## Overview\n\nFastAPI-MCP provides two primary transport mechanisms:\n\n| Transport Type | Method | Description |\n|----------------|--------|-------------|\n| HTTP | `mount_http()` | Standard HTTP transport for MCP communication |\n| SSE | `mount_sse()` | Server-Sent Events transport for streaming responses |\n| Legacy | `mount()` | Deprecated combined method (use `mount_http()` or `mount_sse()` instead) |\n\n资料来源：[fastapi_mcp/server.py:1-200]()\n\n## Transport Architecture\n\n```mermaid\ngraph TD\n    A[FastAPI Application] --> B[FastApiMCP Server]\n    B --> C[mount_http]\n    B --> D[mount_sse]\n    C --> E[HTTP Transport]\n    D --> F[SSE Transport]\n    E --> G[httpx.AsyncClient]\n    F --> H[FastApiSseTransport]\n    G --> I[ASGI Transport]\n    H --> I\n```\n\n## HTTP Transport Configuration\n\nThe HTTP transport is the recommended method for MCP communication. It uses an `httpx.AsyncClient` internally with ASGI transport.\n\n### Basic HTTP Mounting\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_mcp import FastApiMCP\n\napp = FastAPI()\nmcp = FastApiMCP(app)\nmcp.mount_http()\n```\n\n资料来源：[examples/01_basic_usage_example.py:1-15]()\n\n### HTTP Client Configuration\n\nThe `FastApiMCP` class accepts an optional `http_client` parameter for custom HTTP client configuration:\n\n```python\nimport httpx\nfrom fastapi_mcp import FastApiMCP\n\n# Custom HTTP client with specific timeout\ncustom_client = httpx.AsyncClient(\n    timeout=30.0\n)\n\nmcp = FastApiMCP(\n    app,\n    http_client=custom_client\n)\n```\n\n### Default Timeout Behavior\n\nWhen no custom client is provided, FastAPI-MCP creates an internal HTTP client with a default timeout of 10.0 seconds:\n\n```python\nself._http_client = http_client or httpx.AsyncClient(\n    transport=httpx.ASGITransport(app=self.fastapi, raise_app_exceptions=False),\n    base_url=self._base_url,\n    timeout=10.0,\n)\n```\n\n资料来源：[fastapi_mcp/server.py:1-100]()\n\n### Configuring Custom Timeouts\n\nFor long-running API operations, you can configure custom timeout values:\n\n```python\nimport httpx\nfrom fastapi_mcp import FastApiMCP\n\n# Create client with extended timeout\nclient = httpx.AsyncClient(timeout=httpx.Timeout(60.0))\n\nmcp = FastApiMCP(\n    app,\n    name=\"Extended Timeout MCP\",\n    http_client=client,\n)\n```\n\n资料来源：[examples/07_configure_http_timeout_example.py]()\n\n## SSE Transport Configuration\n\nThe SSE (Server-Send Events) transport provides streaming capabilities for MCP communication.\n\n### Basic SSE Mounting\n\n```python\nfrom fastapi_mcp import FastApiMCP\n\nmcp = FastApiMCP(app)\nmcp.mount_sse(router, mount_path=\"/sse\")\n```\n\n资料来源：[fastapi_mcp/server.py:1-200]()\n\n### SSE Endpoint Registration\n\nThe SSE transport registers two endpoints:\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `{mount_path}` | GET | SSE connection establishment |\n| `{mount_path}/messages/` | POST | Message handling |\n\n```python\ndef _register_mcp_connection_endpoint_sse(\n    self,\n    router: FastAPI | APIRouter,\n    transport: FastApiSseTransport,\n    mount_path: str,\n    dependencies: Optional[Sequence[params.Depends]],\n):\n    @router.get(mount_path, include_in_schema=False, operation_id=\"mcp_connection\", dependencies=dependencies)\n    async def handle_mcp_connection(request: Request):\n        async with transport.connect_sse(request.scope, request.receive, request._send) as (reader, writer):\n            await self.server.run(\n                reader,\n                writer,\n                self.server.create_initialization_options(notification_options=None, experimental_capabilities={}),\n                raise_exceptions=False,\n            )\n```\n\n资料来源：[fastapi_mcp/server.py:100-200]()\n\n## Header Forwarding Configuration\n\nFastAPI-MCP allows forwarding specific HTTP headers from incoming MCP requests to tool invocations.\n\n### Default Header Forwarding\n\nBy default, only the `authorization` header is forwarded:\n\n```python\nheaders: Annotated[\n    List[str],\n    Doc(\n        \"\"\"\n        List of HTTP header names to forward from the incoming MCP request into each tool invocation.\n        Only headers in this allowlist will be forwarded. Defaults to ['authorization'].\n        \"\"\"\n    ),\n] = [\"authorization\"],\n```\n\n资料来源：[fastapi_mcp/server.py:1-100]()\n\n### Custom Header Forwarding\n\n```python\nfrom fastapi_mcp import FastApiMCP\n\n# Forward multiple headers\nmcp = FastApiMCP(\n    app,\n    headers=[\"authorization\", \"x-api-key\", \"x-request-id\"],\n)\n```\n\n### Token Passthrough Example\n\nFor authenticated APIs, headers can be forwarded to maintain authentication:\n\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\ntoken_auth_scheme = HTTPBearer()\n\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)],\n    ),\n    headers=[\"authorization\"],  # Forward the auth header\n)\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py:1-50]()\n\n## Authentication Configuration\n\nThe `AuthConfig` class provides OAuth and authentication support:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `version` | Literal[\"2025-03-26\"] | MCP spec version for authorization |\n| `dependencies` | Optional[Sequence[params.Depends]] | FastAPI dependencies for auth checks |\n| `issuer` | Optional[str] | OAuth 2.0 issuer URL |\n| `oauth_metadata_url` | Optional[StrHttpUrl] | Full URL of OAuth metadata endpoint |\n| `authorize_url` | Optional[StrHttpUrl] | Authorization endpoint URL |\n\n资料来源：[fastapi_mcp/types.py:1-100]()\n\n### OAuth Configuration Example\n\n```python\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\nmcp = FastApiMCP(\n    app,\n    auth_config=AuthConfig(\n        version=\"2025-03-26\",\n        issuer=\"https://your-tenant.auth0.com\",\n        dependencies=[Depends(authenticate_request)],\n    ),\n)\n```\n\n## Tool Filtering by Transport\n\nWhen mounting the MCP server, you can filter which operations are exposed:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `include_operations` | Optional[List[str]] | Operation IDs to include |\n| `exclude_operations` | Optional[List[str]] | Operation IDs to exclude |\n| `include_tags` | Optional[List[str]] | Tags to include |\n| `exclude_tags` | Optional[List[str]] | Tags to exclude |\n\n```python\n# Include specific operations only\nmcp = FastApiMCP(\n    app,\n    name=\"Filtered MCP\",\n    include_operations=[\"get_item\", \"list_items\"],\n)\n\n# Exclude specific operations\nmcp = FastApiMCP(\n    app,\n    name=\"Filtered MCP\",\n    exclude_operations=[\"delete_item\", \"update_item\"],\n)\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py]()\n\n## Deprecation Notice\n\nThe legacy `mount()` method is deprecated and will be removed in a future version:\n\n```python\n# DEPRECATED - Do not use\nmcp.mount(router, mount_path, transport=\"sse\")\n\n# RECOMMENDED - Use these instead\nmcp.mount_http()\nmcp.mount_sse(router, mount_path)\n```\n\n资料来源：[fastapi_mcp/server.py:1-100]()\n\n## Complete Configuration Example\n\n```python\nimport httpx\nfrom fastapi import FastAPI, Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\napp = FastAPI()\ntoken_auth_scheme = HTTPBearer()\n\n# Custom authentication dependency\nasync def authenticate_request(request: Request, token: str = Depends(token_auth_scheme)):\n    payload = verify_token(request, token)\n    if payload is None:\n        raise HTTPException(status_code=401, detail=\"Unauthorized\")\n    return payload\n\n# Configure MCP with all transport options\nmcp = FastApiMCP(\n    app,\n    name=\"Complete Example MCP\",\n    describe_all_responses=True,\n    describe_full_response_schema=True,\n    http_client=httpx.AsyncClient(timeout=30.0),\n    include_tags=[\"items\", \"search\"],\n    auth_config=AuthConfig(\n        dependencies=[Depends(authenticate_request)],\n    ),\n    headers=[\"authorization\", \"x-api-key\"],\n)\n\n# Mount with HTTP transport\nmcp.mount_http()\n```\n\n## Summary\n\nFastAPI-MCP provides flexible transport configuration options:\n\n- **HTTP Transport**: Default transport using httpx.AsyncClient with configurable timeouts\n- **SSE Transport**: Server-Sent Events for streaming scenarios\n- **Header Forwarding**: Customizable header allowlist for request passthrough\n- **Authentication**: OAuth and dependency-based authentication support\n- **Tool Filtering**: Operation ID and tag-based filtering for exposed endpoints\n\nChoose the appropriate transport based on your deployment requirements, with HTTP being the recommended default for most use cases.\n\n---\n\n<a id='deployment'></a>\n\n## Deployment Options\n\n### 相关页面\n\n相关主题：[Transport Configuration](#transport-config), [Dynamic Tool Registration](#dynamic-registration), [Examples Overview](#examples)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [examples/04_separate_server_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/04_separate_server_example.py)\n- [examples/06_custom_mcp_router_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/06_custom_mcp_router_example.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)\n- [CHANGELOG.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CHANGELOG.md)\n</details>\n\n# Deployment Options\n\nFastAPI-MCP provides multiple deployment options for integrating MCP (Model Context Protocol) servers with FastAPI applications. These options allow developers to mount MCP servers using different transports (HTTP and SSE), deploy them separately from the main API service, or integrate them with custom APIRouter configurations.\n\n## Overview\n\nFastAPI-MCP supports three primary deployment patterns:\n\n| Deployment Mode | Transport | Description | Use Case |\n|-----------------|-----------|-------------|----------|\n| Integrated (HTTP) | HTTP | MCP server mounted directly into the FastAPI app | Default option, simple deployment |\n| Integrated (SSE) | Server-Sent Events | MCP server using SSE transport | Legacy support, browser compatibility |\n| Separate Server | HTTP | MCP server running as standalone service | Microservices architecture, independent scaling |\n\n资料来源：[fastapi_mcp/server.py:1-50]()\n\n## Transport Types\n\n### HTTP Transport\n\nHTTP transport is the **recommended** deployment option for FastAPI-MCP. It provides a FastAPI-native approach that integrates seamlessly with the existing FastAPI ecosystem.\n\n**Key characteristics:**\n- Uses `httpx.AsyncClient` for making HTTP requests\n- Supports streaming responses\n- Compatible with all major MCP clients\n- Better performance compared to SSE\n\n资料来源：[fastapi_mcp/server.py:85-120]()\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|HTTP Request| B[FastAPI App /mcp]\n    B --> C[FastApiMCP Server]\n    C -->|Tool Call| D[FastAPI Endpoints]\n    D -->|Response| C\n    C -->|MCP Response| A\n```\n\n### SSE Transport\n\nServer-Sent Events (SSE) transport is provided for legacy compatibility and specific use cases requiring browser-based connections.\n\n**Key characteristics:**\n- Bidirectional communication via SSE streams\n- Requires specific endpoint registration\n- Uses `FastApiSseTransport` class\n\n资料来源：[fastapi_mcp/server.py:150-200]()\n\n## Mounting Methods\n\n### Basic HTTP Mount\n\nThe simplest deployment option mounts the MCP server directly to the root FastAPI application using HTTP transport.\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_mcp import FastApiMCP\n\napp = FastAPI(__name__)\nmcp = FastApiMCP(app, name=\"My MCP Server\")\n\n# Mount with HTTP transport (default)\nmcp.mount_http()\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py:40-48]()\n\n### Custom Router Mount\n\nDeploy the MCP server to a specific `APIRouter` instead of the root application. This is useful for organizing endpoints under a specific path prefix.\n\n```python\nfrom fastapi import FastAPI, APIRouter\nfrom fastapi_mcp import FastApiMCP\n\napp = FastAPI(__name__)\n\n# Create a custom router with a prefix\nother_router = APIRouter(prefix=\"/other/route\")\napp.include_router(other_router)\n\nmcp = FastApiMCP(app)\n\n# Mount to the custom router\n# MCP will be available at /other/route/mcp\nmcp.mount_http(other_router)\n```\n\n资料来源：[examples/06_custom_mcp_router_example.py:1-28]()\n\n### SSE Mount\n\nFor SSE transport, the server provides dedicated mounting methods:\n\n```python\nmcp.mount_sse(router=app, mount_path=\"/mcp\")\n```\n\nThe SSE transport registers two endpoints:\n- `GET /mcp` - Connection endpoint\n- `POST /mcp/messages/` - Message handling endpoint\n\n资料来源：[fastapi_mcp/server.py:200-250]()\n\n## Separate Server Deployment\n\nFastAPI-MCP supports deploying MCP servers as separate, standalone services. This is particularly useful in microservices architectures where the MCP server and API service need independent scaling and deployment.\n\n### Architecture\n\n```mermaid\ngraph LR\n    subgraph \"API Service\"\n        A[FastAPI App] --> B[API Endpoints]\n    end\n    \n    subgraph \"MCP Server\"\n        C[MCP Server] --> D[Tool Definitions]\n        D --> E[HTTP Client]\n        E -->|Forward Requests| B\n    end\n    \n    F[MCP Client] --> C\n```\n\n### Configuration\n\nWhen deploying separately, the MCP server configuration specifies the remote server URL:\n\n```json\n{\n  \"mcpServers\": {\n    \"remote-example\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"mcp-remote\",\n        \"http://localhost:8000/mcp\"\n      ]\n    }\n  }\n}\n```\n\n### Implementation\n\nTo enable separate server deployment:\n\n1. Configure the API service to run normally\n2. Mount the MCP server with appropriate transport\n3. Configure the remote MCP client to connect to the API service\n\n资料来源：[examples/04_separate_server_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/04_separate_server_example.py)\n\n### Advantages\n\n| Benefit | Description |\n|---------|-------------|\n| Independent Scaling | Scale MCP server and API separately based on load |\n| Independent Deployment | Deploy updates without coordinating both services |\n| Resource Isolation | Different resource allocation for each service |\n| Network Flexibility | Services can run on different hosts/ports |\n\n## Endpoint Filtering\n\nWhen deploying MCP servers, you can control which FastAPI endpoints are exposed as MCP tools using operation IDs and tags.\n\n### Filter by Operation IDs\n\n```python\n# Include only specific operations\nmcp = FastApiMCP(\n    app,\n    include_operations=[\"get_item\", \"list_items\"]\n)\n\n# Exclude specific operations\nmcp = FastApiMCP(\n    app,\n    exclude_operations=[\"create_item\", \"update_item\", \"delete_item\"]\n)\n```\n\n### Filter by Tags\n\n```python\n# Include only operations with specific tags\nmcp = FastApiMCP(\n    app,\n    include_tags=[\"items\"]\n)\n\n# Exclude operations with specific tags\nmcp = FastApiMCP(\n    app,\n    exclude_tags=[\"search\"]\n)\n```\n\n### Combining Filters\n\nOperation and tag filters can be combined. When combining filters, a greedy approach is taken—endpoints matching **either** criteria will be included.\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:1-50]()\n\n## Authentication Integration\n\nFastAPI-MCP integrates with FastAPI's dependency injection system for authentication. When mounting the MCP server, you can configure authentication that will be applied to all MCP tool executions.\n\n### Token Passthrough\n\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\ntoken_auth_scheme = HTTPBearer()\n\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\nmcp = FastApiMCP(\n    app,\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)],\n    ),\n)\n\nmcp.mount_http()\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py:1-55]()\n\n### Auth Configuration Options\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `dependencies` | `List[Depends]` | FastAPI dependencies for authentication |\n| `issuer` | `str` | OAuth 2.0 issuer URL |\n| `oauth_metadata_url` | `StrHttpUrl` | Full OAuth metadata endpoint URL |\n| `authorize_url` | `StrHttpUrl` | OAuth authorization endpoint URL |\n\n## Running the Server\n\n### Development Mode\n\n```bash\nuvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\n### With uv\n\n```bash\n# Install dependencies\nuv sync\n\n# Run the server\nuv run uvicorn main:app --host 0.0.0.0 --port 8000\n```\n\n资料来源：[CONTRIBUTING.md:1-80]()\n\n## Migration from Deprecated `mount()`\n\nThe `mount()` method is deprecated. Use the specific transport methods instead:\n\n| Deprecated | Replacement |\n|------------|-------------|\n| `mount(transport=\"sse\")` | `mount_sse()` |\n| `mount(transport=\"http\")` | `mount_http()` |\n\n```python\n# Old (deprecated)\nmcp.mount(app, \"/mcp\", transport=\"sse\")\n\n# New (recommended)\nmcp.mount_sse(app, \"/mcp\")\n```\n\n资料来源：[CHANGELOG.md:1-50]()\n\n## Summary\n\nFastAPI-MCP provides flexible deployment options to accommodate various architectural requirements:\n\n- **HTTP Transport**: Recommended for most use cases, provides best performance\n- **SSE Transport**: Legacy support for browser-compatible deployments\n- **Separate Server**: Ideal for microservices architectures\n- **Custom Router**: Organize MCP endpoints under specific paths\n- **Endpoint Filtering**: Control which tools are exposed to MCP clients\n- **Auth Integration**: Leverage existing FastAPI authentication\n\n---\n\n<a id='dynamic-registration'></a>\n\n## Dynamic Tool Registration\n\n### 相关页面\n\n相关主题：[Deployment Options](#deployment), [Endpoint Filtering and Selection](#endpoint-filtering)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [examples/05_reregister_tools_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/05_reregister_tools_example.py)\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)\n- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n- [CHANGELOG.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CHANGELOG.md)\n</details>\n\n# Dynamic Tool Registration\n\nDynamic Tool Registration is a core feature of FastAPI-MCP that enables runtime filtering, registration, and management of MCP tools derived from FastAPI endpoints. This capability allows developers to create multiple MCP server instances with different tool subsets from a single FastAPI application, providing fine-grained control over which tools are exposed to MCP clients.\n\n## Overview\n\nFastAPI-MCP automatically converts FastAPI endpoints into MCP tools by analyzing the OpenAPI schema. Dynamic Tool Registration extends this capability by allowing selective exposure of tools based on operation IDs and tags, enabling scenarios such as:\n\n- Creating multiple specialized MCP servers from one FastAPI app\n- Protecting sensitive endpoints by excluding them from MCP exposure\n- Creating tenant-specific or role-based tool visibility\n- Supporting incremental updates to tool availability\n\nThe feature is implemented through the `FastApiMCP` class constructor parameters that control which operations are registered as MCP tools.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[FastAPI Application] --> B[OpenAPI Schema Analysis]\n    B --> C[All Discovered Endpoints]\n    C --> D{Filter Criteria}\n    D -->|include_operations| E[Whitelist Mode]\n    D -->|exclude_operations| F[Blacklist Mode]\n    D -->|include_tags| G[Tag Filter - Include]\n    D -->|exclude_tags| H[Tag Filter - Exclude]\n    E --> I[Filtered Tool Set]\n    F --> I\n    G --> I\n    H --> I\n    I --> J[MCP Server Instance]\n```\n\n## Core Filter Parameters\n\nThe `FastApiMCP` class accepts four mutually-exclusive filter parameters:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `include_operations` | `Optional[List[str]]` | List of operation IDs to **include** as MCP tools |\n| `exclude_operations` | `Optional[List[str]]` | List of operation IDs to **exclude** from MCP tools |\n| `include_tags` | `Optional[List[str]]` | List of tags to **include** as MCP tools |\n| `exclude_tags` | `Optional[List[str]]` | List of tags to **exclude** from MCP tools |\n\n资料来源：[fastapi_mcp/server.py:1-100]()\n\n### Mutual Exclusivity Rules\n\nThe filtering parameters follow strict mutual exclusivity rules:\n\n1. **Operation filters**: Cannot use `include_operations` and `exclude_operations` together\n2. **Tag filters**: Cannot use `include_tags` and `exclude_tags` together\n3. **Cross-type combination**: Can combine operation filters with tag filters (greedy approach)\n\nWhen combining filters, a greedy union strategy is applied: endpoints matching **either** the operation criteria **or** the tag criteria will be included.\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:1-30]()\n\n## Filter Implementation\n\nThe filtering logic is implemented in the `_filter_tools` method of the `FastApiMCP` class:\n\n```python\ndef _filter_tools(self, tools: List[types.Tool], openapi_schema: Dict[str, Any]) -> List[types.Tool]:\n    \"\"\"\n    Filter tools based on operation IDs and tags.\n\n    Args:\n        tools: List of tools to filter\n        openapi_schema: The OpenAPI schema\n\n    Returns:\n        Filtered list of tools\n    \"\"\"\n    if (\n        self._include_operations is None\n        and self._exclude_operations is None\n        and self._include_tags is None\n        and self._exclude_tags is None\n    ):\n        return tools\n```\n\n资料来源：[fastapi_mcp/server.py:85-105]()\n\n### Operation ID Mapping\n\nThe filtering mechanism builds an operations map indexed by both operation ID and tags:\n\n```python\noperations_by_tag: Dict[str, List[str]] = {}\nfor path, path_item in openapi_schema.get(\"paths\", {}).items():\n    for method, operation in path_item.items():\n        if method not in [\"get\", \"post\", \"put\", \"delete\", \"patch\"]:\n            continue\n\n        operation_id = operation.get(\"operationId\")\n        if not operation_id:\n            continue\n\n        tags = operation.get(\"tags\", [])\n        for tag in tags:\n            if tag not in operations_by_tag:\n                operations_by_tag[tag] = []\n            operations_by_tag[tag].append(operation_id)\n```\n\n资料来源：[fastapi_mcp/server.py:107-125]()\n\n## Usage Patterns\n\n### Include Specific Operations\n\nCreate an MCP server exposing only specified operation IDs:\n\n```python\ninclude_operations_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Operations\",\n    include_operations=[\"get_item\", \"list_items\"],\n)\ninclude_operations_mcp.mount_http(mount_path=\"/include-operations-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:20-26]()\n\n### Exclude Specific Operations\n\nCreate an MCP server with all operations except specified ones:\n\n```python\nexclude_operations_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Operations\",\n    exclude_operations=[\"create_item\", \"update_item\", \"delete_item\"],\n)\nexclude_operations_mcp.mount_http(mount_path=\"/exclude-operations-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:28-34]()\n\n### Tag-Based Inclusion\n\nFilter tools by including endpoints with specific OpenAPI tags:\n\n```python\ninclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Tags\",\n    include_tags=[\"items\"],\n)\ninclude_tags_mcp.mount_http(mount_path=\"/include-tags-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:36-41]()\n\n### Tag-Based Exclusion\n\nExclude all endpoints with specific tags:\n\n```python\nexclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Tags\",\n    exclude_tags=[\"search\"],\n)\nexclude_tags_mcp.mount_http(mount_path=\"/exclude-tags-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:43-48]()\n\n### Combined Filtering\n\nCombine operation ID and tag filters for complex scenarios:\n\n```python\ncombined_include_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Combined Include\",\n    include_operations=[\"delete_item\"],\n    include_tags=[\"search\"],\n)\ncombined_include_mcp.mount_http(mount_path=\"/combined-include-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:50-57]()\n\n## Re-registering Tools\n\nThe library supports re-registering tools at runtime through multiple `FastApiMCP` instances mounted on different paths:\n\n```python\n# Mount all MCP servers with different paths\ninclude_operations_mcp.mount_http(mount_path=\"/include-operations-mcp\")\nexclude_operations_mcp.mount_http(mount_path=\"/exclude-operations-mcp\")\ninclude_tags_mcp.mount_http(mount_path=\"/include-tags-mcp\")\nexclude_tags_mcp.mount_http(mount_path=\"/exclude-tags-mcp\")\ncombined_include_mcp.mount_http(mount_path=\"/combined-include-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:62-68]()\n\nEach mounted instance operates independently, allowing different clients to access different tool sets from the same underlying FastAPI application.\n\n## Custom Tools Integration\n\nBeyond API-derived tools, FastAPI-MCP supports adding custom MCP tools alongside auto-generated ones:\n\n### Added\n- Main `add_mcp_server` function for simple MCP server integration\n- Support for adding custom MCP tools alongside API-derived tools\n\n资料来源：[CHANGELOG.md:1-20]()\n\nThis enables scenarios where developers need to add supplementary tools that don't correspond to FastAPI endpoints, such as helper utilities or integration points with external services.\n\n## HTTP Client Configuration\n\nThe tool registration system includes support for custom HTTP client configuration:\n\n```python\nhttp_client: Annotated[\n    Optional[httpx.AsyncClient],\n    Doc(\n        \"\"\"\n        Optional custom HTTP client to use for API calls to the FastAPI app.\n        Has to be an instance of `httpx.AsyncClient`.\n        \"\"\"\n    ),\n] = None,\n```\n\n资料来源：[fastapi_mcp/server.py:50-58]()\n\nThis allows fine-grained control over the HTTP client used to invoke tools, enabling custom timeouts, authentication, or proxy configuration.\n\n## Header Passthrough\n\nThe system supports forwarding specific HTTP headers from MCP requests to tool invocations:\n\n```python\nheaders: Annotated[\n    List[str],\n    Doc(\n        \"\"\"\n        List of HTTP header names to forward from the incoming MCP request \n        into each tool invocation. Only headers in this allowlist will be \n        forwarded. Defaults to ['authorization'].\n        \"\"\"\n    ),\n] = [\"authorization\"],\n```\n\n资料来源：[fastapi_mcp/server.py:85-93]()\n\nThis is particularly important for maintaining authentication context when tools are invoked through the MCP protocol.\n\n## Summary\n\nDynamic Tool Registration in FastAPI-MCP provides a flexible mechanism for controlling which FastAPI endpoints become MCP tools. By supporting operation ID filtering, tag-based filtering, and their combinations, developers can:\n\n- Create specialized MCP servers for different use cases\n- Implement fine-grained access control\n- Support multi-tenant or role-based tool visibility\n- Combine auto-generated and custom tools in a single MCP server\n\nThe implementation uses a greedy union strategy when combining filters, ensuring maximum flexibility while maintaining predictable behavior. All filtering occurs at registration time, ensuring optimal runtime performance for tool invocation.\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：tadata-org/fastapi_mcp\n\n摘要：发现 22 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：配置坑 - 来源证据：[BUG] MCP session 404 in multi worker production environment。\n\n## 1. 配置坑 · 来源证据：[BUG] MCP session 404 in multi worker production environment\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[BUG] MCP session 404 in multi worker production environment\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f318cbe8fc55407da8cb88f5418cce0d | https://github.com/tadata-org/fastapi_mcp/issues/189 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：v0.1.8\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.1.8\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_11a827f3808141e4bd7b0541a8628af0 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.1.8 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 3. 安装坑 · 来源证据：v0.2.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.2.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a145fff6c53f4e709ef1bb7bc291216c | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.2.0 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 4. 安装坑 · 来源证据：v0.3.4\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.3.4\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_6dcb58f1897f46a188514e2714e5896d | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.4 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 5. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | host_targets=mcp_host, claude, cursor\n\n## 6. 配置坑 · 来源证据：Suggestion: MCPWatch observability example for fastapi_mcp users\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Suggestion: MCPWatch observability example for fastapi_mcp users\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_dfa72f41f3094dd5b2ffe188889f2b4f | https://github.com/tadata-org/fastapi_mcp/issues/303 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 7. 配置坑 · 来源证据：clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_74e4280da33d49e1a3a8d576c7bb78a6 | https://github.com/tadata-org/fastapi_mcp/issues/304 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 8. 配置坑 · 来源证据：v0.3.6\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：v0.3.6\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_bdc90006d16a437798ff2766d514f3d4 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.6 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 9. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | README/documentation is current enough for a first validation pass.\n\n## 10. 维护坑 · 来源证据：[BUG] Description incorrectly passed as version to MCP Server\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[BUG] Description incorrectly passed as version to MCP Server\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2e599a8b03d649d8a47efb6b4d49f5ca | https://github.com/tadata-org/fastapi_mcp/issues/293 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 11. 维护坑 · 来源证据：v0.3.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.3.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_bc6b7bd2988b48d48920e4ffb259f147 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.0 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 12. 维护坑 · 来源证据：v0.3.3 - Fix OpenAPI Conversion Regression\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.3.3 - Fix OpenAPI Conversion Regression\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_79b96b9d35b9444c938c355c081410ac | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.3 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 13. 维护坑 · 来源证据：v0.4.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.4.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4382c9c951e14187b76777ad8561ded9 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.4.0 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 14. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | last_activity_observed missing\n\n## 15. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | no_demo; severity=medium\n\n## 16. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 17. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | no_demo; severity=medium\n\n## 18. 安全/权限坑 · 来源证据：v0.3.1 - Authorization\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.3.1 - Authorization\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_41bf79ee5bd04da1b943d22449a0d649 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.1 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 19. 安全/权限坑 · 来源证据：v0.3.2\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.3.2\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_aa60828a6a6c4cc2b0b28fb72bf2ddad | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.2 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 20. 安全/权限坑 · 来源证据：v0.3.7\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.3.7\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_31faa7de6a364174958daaffa9d9204b | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.7 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 21. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | issue_or_pr_quality=unknown\n\n## 22. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | release_recency=unknown\n\n<!-- canonical_name: tadata-org/fastapi_mcp; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "fastapi-mcp",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:944976593",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/tadata-org/fastapi_mcp"
        },
        {
          "evidence_id": "art_99cbc803f3a64429a212f6cc476a29a1",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/tadata-org/fastapi_mcp#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "fastapi_mcp 说明书",
      "toc": [
        "https://github.com/tadata-org/fastapi_mcp 项目说明书",
        "目录",
        "FastAPI-MCP Home",
        "Overview",
        "Key Features",
        "Requirements",
        "Installation",
        "Quick Start",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "e5cad13cabfc725bbcb047e526816d887d96da62",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "pyproject.toml",
      "README.md",
      "uv.lock",
      "docs/docs.json",
      "docs/configurations/customization.mdx",
      "docs/configurations/tool-naming.mdx",
      "docs/getting-started/best-practices.mdx",
      "docs/getting-started/welcome.mdx",
      "docs/getting-started/installation.mdx",
      "docs/getting-started/quickstart.mdx",
      "docs/getting-started/FAQ.mdx",
      "docs/advanced/deploy.mdx",
      "docs/advanced/auth.mdx",
      "docs/advanced/transport.mdx",
      "docs/advanced/refresh.mdx",
      "docs/advanced/asgi.mdx",
      "examples/03_custom_exposed_endpoints_example.py",
      "examples/09_auth_example_auth0.py",
      "examples/05_reregister_tools_example.py",
      "examples/01_basic_usage_example.py",
      "examples/README.md",
      "examples/07_configure_http_timeout_example.py",
      "examples/__init__.py",
      "examples/04_separate_server_example.py",
      "examples/08_auth_example_token_passthrough.py",
      "examples/06_custom_mcp_router_example.py",
      "examples/02_full_schema_description_example.py",
      "examples/shared/setup.py",
      "examples/shared/auth.py",
      "examples/shared/__init__.py",
      "examples/shared/apps/items.py",
      "examples/shared/apps/__init__.py"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# fastapi-mcp - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 fastapi-mcp 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **想在安装前理解开源项目价值和边界的用户**：当前证据主要来自项目文档。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n## 它能做什么\n\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- `pip install fastapi-mcp` 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：先做权限沙盒试用\n- **为什么**：项目存在安装命令、宿主配置或本地写入线索，不建议直接进入主力环境，应先在隔离环境试装。\n\n### 30 秒判断\n\n- **现在怎么做**：先做权限沙盒试用\n- **最小安全下一步**：先跑 Prompt Preview；若仍要安装，只在隔离环境试装\n- **先别相信**：工具权限边界不能在安装前相信。\n- **继续会触碰**：命令执行、本地环境或项目文件、宿主 AI 上下文\n\n### 现在可以相信\n\n- **适合人群线索：想在安装前理解开源项目价值和边界的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n### 现在还不能相信\n\n- **工具权限边界不能在安装前相信。**（unverified）：MCP/tool 类项目通常会触碰文件、网络、浏览器或外部 API，必须真实检查权限和日志。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0004` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0005` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n### 上下文规模\n\n- 文件总数：80\n- 重要文件覆盖：37/80\n- 证据索引条目：35\n- 角色 / Skill 条目：9\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 fastapi-mcp 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 fastapi-mcp 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 fastapi-mcp 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 9 个角色 / Skill / 项目文档条目。\n\n- **Features**（project_doc）：Expose your FastAPI endpoints as Model Context Protocol MCP tools, with Auth! 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n- **FastAPI-MCP Examples**（project_doc）：The following examples demonstrate various features and usage patterns of FastAPI-MCP: 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/README.md`\n- **Contributing to FastAPI-MCP**（project_doc）：First off, thank you for considering contributing to FastAPI-MCP! 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CONTRIBUTING.md`\n- **Describe your changes**（project_doc）：Issue ticket number and link if applicable 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/pull_request_template.md`\n- **Changelog**（project_doc）：All notable changes to this project will be documented in this file. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CHANGELOG.md`\n- **特点**（project_doc）：FastAPI-MCP 一个零配置工具，用于自动将 FastAPI 端点公开为模型上下文协议（MCP）工具。 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README_zh-CN.md`\n- **Bug report**（project_doc）：Describe the bug A clear and concise description of what the bug is. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/ISSUE_TEMPLATE/bug_report.md`\n- **Documentation**（project_doc）： 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/ISSUE_TEMPLATE/documentation.md`\n- **Feature request**（project_doc）：Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when ... 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/ISSUE_TEMPLATE/feature_request.md`\n\n## 证据索引\n\n- 共索引 35 条证据。\n\n- **Features**（documentation）：Expose your FastAPI endpoints as Model Context Protocol MCP tools, with Auth! 证据：`README.md`\n- **FastAPI-MCP Examples**（documentation）：The following examples demonstrate various features and usage patterns of FastAPI-MCP: 证据：`examples/README.md`\n- **Contributing to FastAPI-MCP**（documentation）：First off, thank you for considering contributing to FastAPI-MCP! 证据：`CONTRIBUTING.md`\n- **License**（source_file）：Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files the \"Software\" , to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 证据：`LICENSE`\n- **Describe your changes**（documentation）：Issue ticket number and link if applicable 证据：`.github/pull_request_template.md`\n- **Changelog**（documentation）：All notable changes to this project will be documented in this file. 证据：`CHANGELOG.md`\n- **特点**（documentation）：FastAPI-MCP 一个零配置工具，用于自动将 FastAPI 端点公开为模型上下文协议（MCP）工具。 证据：`README_zh-CN.md`\n- **Bug Report**（documentation）：Describe the bug A clear and concise description of what the bug is. 证据：`.github/ISSUE_TEMPLATE/bug_report.md`\n- **Documentation**（documentation）：--- name: Documentation about: Report an issue related to the fastapi-mcp documentation/examples title: '' labels: documentation assignees: '' --- 证据：`.github/ISSUE_TEMPLATE/documentation.md`\n- **Feature Request**（documentation）：Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when ... 证据：`.github/ISSUE_TEMPLATE/feature_request.md`\n- **Docs**（structured_config）：{ \"$schema\": \"https://mintlify.com/docs.json\", \"name\": \"FastAPI MCP\", \"background\": { \"color\": { \"dark\": \" 222831\", \"light\": \" EEEEEE\" }, \"decoration\": \"windows\" }, \"colors\": { \"primary\": \" 6d45dc\", \"light\": \" 9f8ded\", \"dark\": \" 6a42d7\" }, \"description\": \"Convert your FastAPI app into a MCP server with zero configuration\", \"favicon\": \"media/favicon.png\", \"navigation\": { \"groups\": { \"group\": \"Getting Started\", \"pages\": \"getting-started/welcome\", \"getting-started/installation\", \"getting-started/quickstart\", \"getting-started/FAQ\", \"getting-started/best-practices\" }, { \"group\": \"Configurations\", \"pages\": \"configurations/tool-naming\", \"configurations/customization\" }, { \"group\": \"Advanced Usage\"… 证据：`docs/docs.json`\n- **.coveragerc**（source_file）：run omit = examples/ tests/ concurrency = multiprocessing parallel = true sigterm = true data file = .coverage source = fastapi mcp 证据：`.coveragerc`\n- **Repomix output**（source_file）：Repomix output !repomix-output.txt !repomix-output.xml 证据：`.cursorignore`\n- **Codecov**（source_file）：coverage: status: project: default: base: pr target: auto threshold: 0.5% informational: false only pulls: true 证据：`.github/codecov.yml`\n- **Dependabot**（source_file）：version: 2 updates: - package-ecosystem: \"github-actions\" directory: \"/\" schedule: interval: \"weekly\" open-pull-requests-limit: 10 labels: - \"dependencies\" - \"github-actions\" 证据：`.github/dependabot.yml`\n- **Byte-compiled / optimized / DLL files**（source_file）：Byte-compiled / optimized / DLL files pycache / .py cod $py.class 证据：`.gitignore`\n- **.Pre Commit Config**（source_file）：repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v5.0.0 hooks: - id: trailing-whitespace exclude: \\. md mdx $ - id: check-yaml - id: check-added-large-files 证据：`.pre-commit-config.yaml`\n- **.python-version**（source_file）：3.12 证据：`.python-version`\n- **Manifest**（source_file）：include LICENSE include README.md include INSTALL.md include pyproject.toml include setup.py 证据：`MANIFEST.in`\n- **Add MCP server to the FastAPI app**（source_file）：from examples.shared.apps.items import app The FastAPI app from examples.shared.setup import setup logging 证据：`examples/01_basic_usage_example.py`\n- **Add MCP server to the FastAPI app**（source_file）：\"\"\" This example shows how to describe the full response schema instead of just a response example. \"\"\" 证据：`examples/02_full_schema_description_example.py`\n- **Examples demonstrating how to filter MCP tools by operation IDs and tags**（source_file）：\"\"\" This example shows how to customize exposing endpoints by filtering operation IDs and tags. Notes on filtering: - You cannot use both include operations and exclude operations at the same time - You cannot use both include tags and exclude tags at the same time - You can combine operation filtering with tag filtering e.g., use include operations with include tags - When combining filters, a greedy approach will be taken. Endpoints matching either criteria will be included \"\"\" 证据：`examples/03_custom_exposed_endpoints_example.py`\n- **Take the FastAPI app only as a source for MCP server generation**（source_file）：\"\"\" This example shows how to run the MCP server and the FastAPI app separately. You can create an MCP server from one FastAPI app, and mount it to a different app. \"\"\" 证据：`examples/04_separate_server_example.py`\n- **This endpoint will not be registered as a tool, since it was added after the MCP instance was created**（source_file）：\"\"\" This example shows how to re-register tools if you add endpoints after the MCP server was created. \"\"\" 证据：`examples/05_reregister_tools_example.py`\n- **Mount the MCP server to a specific router.**（source_file）：\"\"\" This example shows how to mount the MCP server to a specific APIRouter, giving a custom mount path. \"\"\" 证据：`examples/06_custom_mcp_router_example.py`\n- **07 Configure Http Timeout Example**（source_file）：\"\"\" This example shows how to configure the HTTP client timeout for the MCP server. In case you have API endpoints that take longer than 5 seconds to respond, you can increase the timeout. \"\"\" 证据：`examples/07_configure_http_timeout_example.py`\n- **Scheme for the Authorization header**（source_file）：\"\"\" This example shows how to reject any request without a valid token passed in the Authorization header. 证据：`examples/08_auth_example_token_passthrough.py`\n- **Check if this is a JWE token encrypted token**（source_file）：from fastapi import FastAPI, Depends, HTTPException, Request, status from pydantic settings import BaseSettings from typing import Any import logging 证据：`examples/09_auth_example_auth0.py`\n- **Fallback for local development**（source_file）：\"\"\" FastAPI-MCP: Automatic MCP server generator for FastAPI applications. 证据：`fastapi_mcp/__init__.py`\n- **Validate operation and tag filtering options**（source_file）：import json import httpx from typing import Dict, Optional, Any, List, Union, Literal, Sequence from typing extensions import Annotated, Doc 证据：`fastapi_mcp/server.py`\n- **Always exclude unset and None fields, since clients don't take it well when**（source_file）：import time from typing import Any, Dict, Annotated, Union, Optional, Sequence, Literal, List from typing extensions import Doc from pydantic import BaseModel, ConfigDict, HttpUrl, field validator, model validator, from pydantic.main import IncEx from fastapi import params 证据：`fastapi_mcp/types.py`\n- **Mypy**（source_file）：mypy 证据：`mypy.ini`\n- **Pyproject**（source_file）：build-system requires = \"hatchling\", \"tomli\" build-backend = \"hatchling.build\" 证据：`pyproject.toml`\n- **Pytest**（source_file）：pytest addopts = -vvv --cov=. --cov-report xml --cov-report term-missing --cov-fail-under=80 --cov-config=.coveragerc asyncio mode = auto log cli = true log cli level = DEBUG log cli format = % asctime s - % name s - % levelname s - % message s 证据：`pytest.ini`\n- **Add the parent directory to the path**（source_file）：import sys import os import pytest import coverage 证据：`tests/conftest.py`\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`README.md`, `examples/README.md`, `CONTRIBUTING.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`README.md`, `examples/README.md`, `CONTRIBUTING.md`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\n下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。\n\n## Human Manual 骨架\n\n使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。\n\n宿主 AI 硬性规则：\n- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。\n- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。\n- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。\n\n- **FastAPI-MCP Home**：importance `high`\n  - source_paths: README.md, fastapi_mcp/__init__.py\n- **System Architecture**：importance `high`\n  - source_paths: fastapi_mcp/server.py, fastapi_mcp/openapi/convert.py, fastapi_mcp/transport/http.py, fastapi_mcp/transport/sse.py, fastapi_mcp/types.py\n- **Installation**：importance `high`\n  - source_paths: pyproject.toml, README.md\n- **Quickstart Guide**：importance `high`\n  - source_paths: examples/01_basic_usage_example.py, examples/shared/apps/items.py, examples/shared/setup.py\n- **Examples Overview**：importance `high`\n  - source_paths: examples/README.md, examples/01_basic_usage_example.py, examples/04_separate_server_example.py, examples/05_reregister_tools_example.py, examples/08_auth_example_token_passthrough.py\n- **Authentication Overview**：importance `high`\n  - source_paths: fastapi_mcp/types.py, fastapi_mcp/auth/proxy.py, examples/shared/auth.py, examples/08_auth_example_token_passthrough.py\n- **OAuth Authentication**：importance `high`\n  - source_paths: fastapi_mcp/auth/proxy.py, examples/09_auth_example_auth0.py, fastapi_mcp/types.py\n- **Endpoint Filtering and Selection**：importance `medium`\n  - source_paths: examples/03_custom_exposed_endpoints_example.py, fastapi_mcp/server.py, fastapi_mcp/openapi/convert.py\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `e5cad13cabfc725bbcb047e526816d887d96da62`\n- inspected_files: `pyproject.toml`, `README.md`, `uv.lock`, `docs/docs.json`, `docs/configurations/customization.mdx`, `docs/configurations/tool-naming.mdx`, `docs/getting-started/best-practices.mdx`, `docs/getting-started/welcome.mdx`, `docs/getting-started/installation.mdx`, `docs/getting-started/quickstart.mdx`, `docs/getting-started/FAQ.mdx`, `docs/advanced/deploy.mdx`, `docs/advanced/auth.mdx`, `docs/advanced/transport.mdx`, `docs/advanced/refresh.mdx`, `docs/advanced/asgi.mdx`, `examples/03_custom_exposed_endpoints_example.py`, `examples/09_auth_example_auth0.py`, `examples/05_reregister_tools_example.py`, `examples/01_basic_usage_example.py`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 来源证据：[BUG] MCP session 404 in multi worker production environment\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[BUG] MCP session 404 in multi worker production environment\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响升级、迁移或版本选择。\n- Evidence: community_evidence:github | cevd_f318cbe8fc55407da8cb88f5418cce0d | https://github.com/tadata-org/fastapi_mcp/issues/189 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 来源证据：v0.1.8\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.1.8\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_11a827f3808141e4bd7b0541a8628af0 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.1.8 | 来源类型 github_release 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 来源证据：v0.2.0\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.2.0\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能影响升级、迁移或版本选择。\n- Evidence: community_evidence:github | cevd_a145fff6c53f4e709ef1bb7bc291216c | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.2.0 | 来源类型 github_release 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 来源证据：v0.3.4\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.3.4\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能影响升级、迁移或版本选择。\n- Evidence: community_evidence:github | cevd_6dcb58f1897f46a188514e2714e5896d | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.4 | 来源类型 github_release 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 可能修改宿主 AI 配置\n\n- Trigger: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- Host AI rule: 列出会写入的配置文件、目录和卸载/回滚步骤。\n- Why it matters: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- Evidence: capability.host_targets | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | host_targets=mcp_host, claude, cursor\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 来源证据：Suggestion: MCPWatch observability example for fastapi_mcp users\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Suggestion: MCPWatch observability example for fastapi_mcp users\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_dfa72f41f3094dd5b2ffe188889f2b4f | https://github.com/tadata-org/fastapi_mcp/issues/303 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 来源证据：clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_74e4280da33d49e1a3a8d576c7bb78a6 | https://github.com/tadata-org/fastapi_mcp/issues/304 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 来源证据：v0.3.6\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：v0.3.6\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_bdc90006d16a437798ff2766d514f3d4 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.6 | 来源类型 github_release 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 9: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- Evidence: capability.assumptions | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | README/documentation is current enough for a first validation pass.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 10: 来源证据：[BUG] Description incorrectly passed as version to MCP Server\n\n- Trigger: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[BUG] Description incorrectly passed as version to MCP Server\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_2e599a8b03d649d8a47efb6b4d49f5ca | https://github.com/tadata-org/fastapi_mcp/issues/293 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n",
      "summary": "给宿主 AI 的上下文和工作边界。",
      "title": "AI Context Pack / 带给我的 AI"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card / 安装前决策卡\n\n项目：tadata-org/fastapi_mcp\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：mcp_host, claude, cursor\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- 无阻塞项。\n\n## 项目专属踩坑\n\n- 来源证据：[BUG] MCP session 404 in multi worker production environment（high）：可能影响升级、迁移或版本选择。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：v0.1.8（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：v0.2.0（medium）：可能影响升级、迁移或版本选择。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：v0.3.4（medium）：可能影响升级、迁移或版本选择。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 可能修改宿主 AI 配置（medium）：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/tadata-org/fastapi_mcp 项目说明书\n\n生成时间：2026-05-17 18:19:42 UTC\n\n## 目录\n\n- [FastAPI-MCP Home](#home)\n- [System Architecture](#architecture)\n- [Installation](#installation)\n- [Quickstart Guide](#quickstart)\n- [Examples Overview](#examples)\n- [Authentication Overview](#auth-overview)\n- [OAuth Authentication](#auth-oauth)\n- [Endpoint Filtering and Selection](#endpoint-filtering)\n- [Tool Naming and Schema](#tool-naming)\n- [Transport Configuration](#transport-config)\n- [Deployment Options](#deployment)\n- [Dynamic Tool Registration](#dynamic-registration)\n\n<a id='home'></a>\n\n## FastAPI-MCP Home\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture), [Quickstart Guide](#quickstart), [Installation](#installation)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/README.md)\n- [fastapi_mcp/__init__.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/__init__.py)\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n- [examples/01_basic_usage_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)\n- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n- [CHANGELOG.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CHANGELOG.md)\n</details>\n\n# FastAPI-MCP Home\n\n## Overview\n\nFastAPI-MCP is a bridge library that converts FastAPI applications into MCP (Model Context Protocol) servers with minimal configuration. It allows developers to expose their existing FastAPI endpoints as MCP tools, enabling AI assistants to interact with FastAPI services through the MCP protocol.\n\n资料来源：[README.md]()\n\n## Key Features\n\n| Feature | Description |\n|---------|-------------|\n| **Authentication Built-in** | Uses existing FastAPI dependencies for auth |\n| **FastAPI-Native** | Not just another OpenAPI → MCP converter |\n| **Zero/Minimal Configuration** | Point it at your FastAPI app and it works |\n| **Schema Preservation** | Maintains request and response model schemas |\n| **Documentation Preservation** | Keeps endpoint documentation from Swagger |\n| **Flexible Deployment** | Mount MCP servers separately or with the API |\n\n资料来源：[README.md]()\n\n## Requirements\n\n- Python 3.10+ (Recommended 3.12)\n- `uv` package manager\n\n资料来源：[README.md]()\n\n## Installation\n\nThe package can be installed using `uv`:\n\n```bash\nuv add fastapi-mcp\n```\n\nFor development dependencies:\n\n```bash\nuv add --group dev <package-name>\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n## Quick Start\n\nThe simplest way to use FastAPI-MCP is to create an instance and mount it to your FastAPI app:\n\n```python\nfrom examples.shared.apps.items import app  # Your FastAPI app\nfrom fastapi_mcp import FastApiMCP\n\n# Add MCP server to the FastAPI app\nmcp = FastApiMCP(app)\n\n# Mount the MCP server to the FastAPI app\nmcp.mount_http()\n\nif __name__ == \"__main__\":\n    import uvicorn\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\nAfter mounting, your MCP server will be available at `/mcp` endpoint by default.\n\n资料来源：[examples/01_basic_usage_example.py]()\n\n## Architecture\n\n### High-Level Architecture\n\n```mermaid\ngraph TD\n    A[FastAPI Application] --> B[FastApiMCP]\n    B --> C[MCP Tools]\n    B --> D[OpenAPI Schema]\n    C --> E[AI Assistant]\n    E --> F[MCP Protocol]\n    F --> C\n    G[Authentication] --> B\n```\n\n### Component Overview\n\nThe FastAPI-MCP library consists of the following key components:\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| `FastApiMCP` | `fastapi_mcp/__init__.py` | Main class for creating MCP servers from FastAPI apps |\n| `AuthConfig` | `fastapi_mcp/types.py` | Configuration for MCP authentication |\n| `OAuthMetadata` | `fastapi_mcp/types.py` | OAuth 2.0 Server Metadata |\n| Tool Conversion | `fastapi_mcp/openapi/convert.py` | Converts OpenAPI schemas to MCP tools |\n\n资料来源：[fastapi_mcp/types.py]()\n资料来源：[fastapi_mcp/server.py]()\n\n## Configuration Options\n\n### FastApiMCP Constructor Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `app` | FastAPI | Required | The FastAPI application instance |\n| `name` | str | `\"fastapi-mcp\"` | MCP server name |\n| `description` | str | `None` | MCP server description |\n| `describe_all_responses` | bool | `False` | Include all possible response schemas |\n| `describe_full_response_schema` | bool | `False` | Include full JSON schema for responses |\n| `http_client` | httpx.AsyncClient | `None` | Custom HTTP client for API calls |\n| `include_operations` | List[str] | `None` | Operation IDs to include |\n| `exclude_operations` | List[str] | `None` | Operation IDs to exclude |\n| `include_tags` | List[str] | `None` | Tags to include |\n| `exclude_tags` | List[str] | `None` | Tags to exclude |\n| `auth_config` | AuthConfig | `None` | Authentication configuration |\n| `headers` | List[str] | `[\"authorization\"]` | Headers to forward |\n\n资料来源：[fastapi_mcp/server.py]()\n\n### Mounting Options\n\nThe MCP server can be mounted using `mount_http()`:\n\n```python\nmcp.mount_http(mount_path=\"/custom-mcp-path\")\n```\n\nDefault mount path is `/mcp`.\n\n资料来源：[fastapi_mcp/server.py]()\n\n## Endpoint Filtering\n\nFastAPI-MCP supports filtering which endpoints are exposed as MCP tools through operation IDs and tags.\n\n### Filtering Rules\n\n- Cannot use both `include_operations` and `exclude_operations` simultaneously\n- Cannot use both `include_tags` and `exclude_tags` simultaneously\n- Can combine operation filtering with tag filtering (greedy approach)\n- Endpoints matching either criteria will be included when combining filters\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py]()\n\n### Filtering Examples\n\n```python\nfrom fastapi_mcp import FastApiMCP\n\n# Include specific operation IDs\nmcp1 = FastApiMCP(\n    app,\n    include_operations=[\"get_item\", \"list_items\"]\n)\n\n# Exclude specific operation IDs\nmcp2 = FastApiMCP(\n    app,\n    exclude_operations=[\"create_item\", \"update_item\", \"delete_item\"]\n)\n\n# Include specific tags\nmcp3 = FastApiMCP(\n    app,\n    include_tags=[\"items\"]\n)\n\n# Combine filters (include mode)\nmcp4 = FastApiMCP(\n    app,\n    include_operations=[\"delete_item\"],\n    include_tags=[\"search\"],\n)\n\n# Mount with different paths\nmcp1.mount_http(mount_path=\"/filtered-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py]()\n\n### Internal Filtering Logic\n\nThe `_filter_tools` method processes filtering based on operation IDs and tags:\n\n```mermaid\ngraph TD\n    A[Tools List] --> B{Any Filters Set?}\n    B -->|No| Z[Return All Tools]\n    B -->|Yes| C[Build Operations by Tag Map]\n    C --> D{Operation ID Filter?}\n    D -->|Include| E[Keep Matching Operations]\n    D -->|Exclude| F[Remove Matching Operations]\n    E --> G{Tag Filter?}\n    F --> G\n    G -->|Include Tags| H[Keep Matching Tags]\n    G -->|Exclude Tags| I[Remove Matching Tags]\n    H --> J[Return Filtered Tools]\n    I --> J\n```\n\n资料来源：[fastapi_mcp/server.py]()\n\n## Authentication Configuration\n\nFastAPI-MCP provides built-in support for MCP authentication using OAuth 2.0.\n\n### AuthConfig Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `version` | Literal[\"2025-03-26\"] | `\"2025-03-26\"` | MCP spec version |\n| `dependencies` | Sequence[Depends] | `None` | FastAPI auth dependencies |\n| `issuer` | str | `None` | OAuth 2.0 issuer URL |\n| `oauth_metadata_url` | StrHttpUrl | `None` | OAuth metadata endpoint |\n| `authorize_url` | StrHttpUrl | `None` | Authorization endpoint |\n| `token_endpoint` | StrHttpUrl | `None` | Token endpoint |\n| `revocation_endpoint` | StrHttpUrl | `None` | Token revocation endpoint |\n| `jwks_uri` | StrHttpUrl | `None` | JWKS URI |\n| `signing_key` | str | `None` | JWT signing key |\n\n资料来源：[fastapi_mcp/types.py]()\n\n### Token Passthrough Example\n\nTo reject requests without valid authorization tokens:\n\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\ntoken_auth_scheme = HTTPBearer()\n\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)],\n    ),\n)\n\nmcp.mount_http()\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py]()\n\n### OAuth Configuration\n\nThe MCP client configuration for remote servers with auth headers:\n\n```json\n{\n  \"mcpServers\": {\n    \"remote-example\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"mcp-remote\",\n        \"http://localhost:8000/mcp\",\n        \"--header\",\n        \"Authorization:${AUTH_HEADER}\"\n      ]\n    },\n    \"env\": {\n      \"AUTH_HEADER\": \"Bearer <your-token>\"\n    }\n  }\n}\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py]()\n\n## Development Setup\n\n### Local Development Environment\n\n1. Fork the repository\n2. Clone your fork:\n\n```bash\ngit clone https://github.com/YOUR-USERNAME/fastapi_mcp.git\ncd fastapi-mcp\ngit remote add upstream https://github.com/tadata-org/fastapi_mcp.git\n```\n\n3. Set up development environment:\n\n```bash\nuv sync\n```\n\n4. Install pre-commit hooks:\n\n```bash\nuv run pre-commit install\nuv run pre-commit run\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n### Running Tests and Checks\n\n```bash\n# Run all tests\npytest\n\n# Check code formatting and style\nruff check .\nruff format .\n\n# Check types\nmypy .\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n## Version History\n\n| Version | Changes |\n|---------|---------|\n| Latest | Support for deploying MCP servers separately; endpoint filtering capabilities; `setup_server()` for dynamic routes |\n| 0.1.8 | Removed unneeded dependency |\n| 0.1.7 | Fixed syntax error (Issue #34) |\n| 0.1.6 | Hid `handle_mcp_connection` tool (Issue #23) |\n\n资料来源：[CHANGELOG.md]()\n\n## Community\n\nJoin the [MCParty Slack community](https://join.slack.com/t/themcparty/shared_invite/zt-30yxr1zdi-2FG~XjBA0xIgYSYuKe7~Xg) to connect with other MCP enthusiasts, ask questions, and share experiences with FastAPI-MCP.\n\n资料来源：[README.md]()\n\n## License\n\nMIT License. Copyright (c) 2024-2025 Tadata Inc.\n\n资料来源：[README.md]()\n资料来源：[README_zh-CN.md]()\n\n---\n\n<a id='architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[FastAPI-MCP Home](#home), [Authentication Overview](#auth-overview), [Transport Configuration](#transport-config)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [fastapi_mcp/openapi/convert.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/openapi/convert.py)\n- [fastapi_mcp/transport/http.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/transport/http.py)\n- [fastapi_mcp/transport/sse.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/transport/sse.py)\n- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n</details>\n\n# System Architecture\n\n## Overview\n\nFastAPI-MCP is a framework that automatically generates MCP (Model Context Protocol) servers from existing FastAPI applications. The architecture follows a **FastAPI-first approach**, meaning it integrates directly with FastAPI's ASGI interface rather than functioning as a separate HTTP service.\n\nThe primary design goals are:\n\n- **Native dependencies**: Use familiar FastAPI `Depends()` for authentication\n- **ASGI transport**: Communicate directly with the FastAPI app through its ASGI interface\n- **Zero/minimal configuration**: Point it at a FastAPI app and it works immediately\n- **Schema preservation**: Maintain request/response model schemas and documentation\n\n资料来源：[README.md]()\n\n## Core Components\n\n### Component Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Client Layer\"\n        MCP_CLIENT[MCP Client<br/>Claude, etc.]\n    end\n    \n    subgraph \"FastAPI-MCP Core\"\n        MCP_SERVER[FastApiMCP Server]\n        TRANSPORT[Transport Layer<br/>HTTP/SSE]\n        CONVERT[OpenAPI Converter]\n        FILTER[Tool Filter]\n    end\n    \n    subgraph \"FastAPI Application\"\n        FASTAPI[FastAPI App]\n        DEPENDS[Dependencies<br/>Auth, etc.]\n        ROUTES[Routes]\n    end\n    \n    MCP_CLIENT <--> TRANSPORT\n    MCP_SERVER --> TRANSPORT\n    MCP_SERVER --> CONVERT\n    MCP_SERVER --> FILTER\n    TRANSPORT <--> FASTAPI\n    FASTAPI --> DEPENDS\n    FASTAPI --> ROUTES\n```\n\n### FastApiMCP Server\n\nThe `FastApiMCP` class is the main entry point for the library. It handles:\n\n- MCP server initialization and lifecycle\n- Tool discovery from FastAPI endpoints\n- HTTP client operations for invoking endpoints\n- Tool filtering based on operations and tags\n- Mounting the MCP server to FastAPI applications\n\n资料来源：[fastapi_mcp/server.py:1-100]()\n\n### Transport Layer\n\nFastAPI-MCP supports multiple transport mechanisms:\n\n| Transport | Description | Use Case |\n|-----------|-------------|----------|\n| HTTP | Standard HTTP transport with JSON-RPC | Default transport |\n| SSE | Server-Sent Events | Streaming responses |\n\nThe transport layer handles:\n- Request/response serialization\n- MCP protocol encoding/decoding\n- Connection management\n\n资料来源：[fastapi_mcp/transport/http.py](), [fastapi_mcp/transport/sse.py]()\n\n### OpenAPI Schema Converter\n\nThe converter transforms FastAPI endpoint definitions into MCP tool schemas:\n\n```mermaid\ngraph LR\n    subgraph \"FastAPI\"\n        OPERATION[Operation]\n        PARAMETERS[Parameters]\n        REQUEST_BODY[Request Body]\n        RESPONSE[Response Schema]\n    end\n    \n    subgraph \"Conversion Process\"\n        VALIDATE[Validate Schema]\n        ORGANIZE[Organize Params]\n        BUILD[Build Tool Description]\n    end\n    \n    subgraph \"MCP Tool\"\n        TOOL[Tool Definition]\n        INPUT_SCHEMA[Input Schema]\n        DESCRIPTION[Description]\n    end\n    \n    OPERATION --> VALIDATE\n    PARAMETERS --> ORGANIZE\n    REQUEST_BODY --> ORGANIZE\n    VALIDATE --> BUILD\n    ORGANIZE --> BUILD\n    RESPONSE --> BUILD\n    BUILD --> TOOL\n    BUILD --> INPUT_SCHEMA\n    BUILD --> DESCRIPTION\n```\n\nThe converter processes:\n- Path, query, and header parameters separately\n- Request body schemas\n- Response schemas with optional full schema inclusion\n- Documentation from OpenAPI descriptions\n\n资料来源：[fastapi_mcp/openapi/convert.py]()\n\n## Data Flow\n\n### Tool Invocation Flow\n\n```mermaid\nsequenceDiagram\n    participant Client as MCP Client\n    participant MCP as FastApiMCP Server\n    participant Filter as Tool Filter\n    participant Convert as OpenAPI Converter\n    participant API as FastAPI App\n    participant Auth as Auth Dependencies\n\n    Client->>MCP: ListTools Request\n    MCP->>Filter: Get filtered tools\n    Filter->>Convert: Request tool definitions\n    Convert->>API: Fetch OpenAPI schema\n    API-->>Convert: OpenAPI spec\n    Convert-->>Filter: Tool definitions\n    Filter-->>MCP: Filtered tools\n    MCP-->>Client: Tool list\n\n    Client->>MCP: CallTool Request\n    MCP->>Filter: Validate tool allowed\n    Filter-->>MCP: Tool valid\n    MCP->>API: Invoke endpoint (HTTP)\n    API->>Auth: Run dependencies\n    Auth-->>API: Auth OK\n    API-->>MCP: Response\n    MCP-->>Client: Tool result\n```\n\n### Parameter Organization\n\nThe converter organizes parameters into distinct categories:\n\n| Category | OpenAPI Location | Processing |\n|----------|------------------|------------|\n| Path | `parameters[in=path]` | Required for route matching |\n| Query | `parameters[in=query]` | Optional filters |\n| Header | `parameters[in=header]` | Metadata forwarding |\n| Body | `requestBody` | JSON payload |\n\n资料来源：[fastapi_mcp/openapi/convert.py:50-80]()\n\n## Tool Filtering System\n\n### Filter Types\n\nFastAPI-MCP provides granular control over which endpoints become MCP tools:\n\n```mermaid\ngraph TD\n    subgraph \"Filter Configuration\"\n        INCL_OPS[include_operations]\n        EXCL_OPS[exclude_operations]\n        INCL_TAGS[include_tags]\n        EXCL_TAGS[exclude_tags]\n    end\n    \n    subgraph \"Operations Index\"\n        OPS_BY_TAG[Operations by Tag]\n        OPS_BY_ID[Operations by ID]\n    end\n    \n    INCL_OPS --> OPS_BY_ID\n    EXCL_OPS --> OPS_BY_ID\n    INCL_TAGS --> OPS_BY_TAG\n    EXCL_TAGS --> OPS_BY_TAG\n```\n\n### Filter Rules\n\n| Filter Type | Description | Mutual Exclusion |\n|-------------|-------------|-------------------|\n| `include_operations` | Whitelist specific operation IDs | Cannot use with `exclude_operations` |\n| `exclude_operations` | Blacklist specific operation IDs | Cannot use with `include_operations` |\n| `include_tags` | Whitelist endpoints by tag | Cannot use with `exclude_tags` |\n| `exclude_tags` | Blacklist endpoints by tag | Cannot use with `include_tags` |\n\n**Greedy Matching**: When combining operation and tag filters, endpoints matching either criteria are included.\n\n资料来源：[fastapi_mcp/server.py:80-120](), [examples/03_custom_exposed_endpoints_example.py]()\n\n## Authentication Architecture\n\n### AuthConfig Structure\n\n```python\nclass AuthConfig(BaseType):\n    version: Literal[\"2025-03-26\"]  # MCP spec version\n    dependencies: Sequence[Depends]  # FastAPI auth dependencies\n    issuer: Optional[str]  # OAuth issuer URL\n    oauth_metadata_url: Optional[StrHttpUrl]  # OAuth metadata endpoint\n    authorize_url: Optional[StrHttpUrl]  # OAuth authorization endpoint\n```\n\n### Authentication Flow\n\n```mermaid\ngraph LR\n    subgraph \"Client\"\n        REQUEST[MCP Request]\n        HEADER[Auth Header]\n    end\n    \n    subgraph \"FastAPI-MCP\"\n        FORWARD[Forward Headers]\n        VALIDATE[Validate with Depends]\n    end\n    \n    subgraph \"FastAPI App\"\n        AUTH_DEP[Auth Dependency]\n        PROTECTED[Protected Endpoint]\n    end\n    \n    REQUEST --> HEADER\n    HEADER --> FORWARD\n    FORWARD --> VALIDATE\n    VALIDATE --> AUTH_DEP\n    AUTH_DEP --> PROTECTED\n```\n\n### Header Forwarding\n\nBy default, the `authorization` header is forwarded from MCP requests to FastAPI endpoint invocations. Additional headers can be configured:\n\n```python\nmcp = FastApiMCP(\n    app,\n    headers=[\"authorization\", \"x-custom-header\"]\n)\n```\n\n资料来源：[fastapi_mcp/types.py:100-150](), [examples/08_auth_example_token_passthrough.py]()\n\n## Configuration Options\n\n### FastApiMCP Constructor Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `app` | FastAPI | Required | FastAPI application instance |\n| `name` | str | Required | MCP server name |\n| `describe_all_responses` | bool | `False` | Include all possible response schemas |\n| `describe_full_response_schema` | bool | `False` | Include full JSON schema for responses |\n| `http_client` | httpx.AsyncClient | `None` | Custom HTTP client |\n| `include_operations` | List[str] | `None` | Operation IDs to include |\n| `exclude_operations` | List[str] | `None` | Operation IDs to exclude |\n| `include_tags` | List[str] | `None` | Tags to include |\n| `exclude_tags` | List[str] | `None` | Tags to exclude |\n| `auth_config` | AuthConfig | `None` | Authentication configuration |\n| `headers` | List[str] | `[\"authorization\"]` | Headers to forward |\n\n资料来源：[fastapi_mcp/server.py:150-200]()\n\n## Type System\n\n### Core Types\n\n```mermaid\nclassDiagram\n    class BaseType {\n        +model_config: ConfigDict\n        +model_dump() dict\n    }\n    \n    class HTTPRequestInfo {\n        +method: str\n        +path: str\n        +headers: Dict\n        +cookies: Dict\n        +query_params: Dict\n        +body: Any\n    }\n    \n    class OAuthMetadata {\n        +issuer: StrHttpUrl\n        +authorization_endpoint: StrHttpUrl\n        +token_endpoint: StrHttpUrl\n        +scopes_supported: List[str]\n    }\n    \n    class AuthConfig {\n        +version: str\n        +dependencies: Sequence\n        +issuer: str\n    }\n    \n    BaseType <|-- HTTPRequestInfo\n    BaseType <|-- OAuthMetadata\n    BaseType <|-- AuthConfig\n```\n\n### HTTPRequestInfo\n\nCaptures incoming HTTP request details for authentication and routing:\n\n```python\nclass HTTPRequestInfo(BaseType):\n    method: str           # HTTP method (GET, POST, etc.)\n    path: str             # Request path\n    headers: Dict[str, str]\n    cookies: Dict[str, str]\n    query_params: Dict[str, str]\n    body: Any             # Request body\n```\n\n资料来源：[fastapi_mcp/types.py:30-50]()\n\n## Deployment Models\n\n### Integrated Deployment (Default)\n\nThe MCP server is mounted directly into the FastAPI application:\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_mcp import FastApiMCP\n\napp = FastAPI()\nmcp = FastApiMCP(app, name=\"My MCP\")\nmcp.mount_http()\n\n# MCP available at /mcp endpoint\n```\n\n### Separate Deployment\n\nFastAPI-MCP also supports running the MCP server separately from the original FastAPI application for advanced deployment scenarios.\n\n资料来源：[README.md](), [fastapi_mcp/server.py]()\n\n## HTTP Client Operations\n\n### Supported Methods\n\n| Method | Handler | Body Support | Query Support |\n|--------|---------|--------------|---------------|\n| GET | `client.get()` | No | Yes |\n| POST | `client.post()` | Yes | Yes |\n| PUT | `client.put()` | Yes | Yes |\n| DELETE | `client.delete()` | No | Yes |\n| PATCH | `client.patch()` | Yes | Yes |\n\nThe internal HTTP client executes requests to FastAPI endpoints:\n\n```python\nasync def _make_request(\n    method: str,\n    path: str,\n    query: Dict[str, Any],\n    headers: Dict[str, str],\n    body: Any\n) -> httpx.Response:\n    if method.lower() == \"get\":\n        return await client.get(path, params=query, headers=headers)\n    elif method.lower() == \"post\":\n        return await client.post(path, params=query, headers=headers, json=body)\n    # ... other methods\n```\n\n资料来源：[fastapi_mcp/server.py:30-60]()\n\n## Summary\n\nThe FastAPI-MCP architecture provides a seamless bridge between FastAPI applications and the MCP protocol:\n\n1. **Non-intrusive integration**: Mounts directly onto existing FastAPI apps\n2. **Flexible filtering**: Fine-grained control over exposed tools\n3. **Native auth**: Leverages FastAPI's dependency injection system\n4. **Schema preservation**: Maintains OpenAPI documentation and type information\n5. **Multiple transports**: Supports both HTTP and SSE for different use cases\n\nThe system is designed for zero-configuration use while providing extensive customization options for advanced scenarios.\n\n---\n\n<a id='installation'></a>\n\n## Installation\n\n### 相关页面\n\n相关主题：[FastAPI-MCP Home](#home), [Quickstart Guide](#quickstart)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [CONTRIBUTING.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CONTRIBUTING.md)\n- [README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/README.md)\n- [README_zh-CN.md](https://github.com/tadata-org/fastapi_mcp/blob/main/README_zh-CN.md)\n- [pyproject.toml](https://github.com/tadata-org/fastapi_mcp/blob/main/pyproject.toml) (implicitly referenced through workflow descriptions)\n</details>\n\n# Installation\n\nThis page provides comprehensive instructions for setting up the **fastapi-mcp** development environment, including prerequisites, installation methods, and post-installation configuration.\n\n## Overview\n\nThe **fastapi-mcp** project enables bridging FastAPI applications with the Model Context Protocol (MCP). The installation process involves setting up the Python environment, configuring the `uv` package manager, and preparing development tools for code quality assurance.\n\n资料来源：[README.md]()\n\n## Prerequisites\n\nBefore installing fastapi-mcp, ensure your system meets the following requirements.\n\n### System Requirements\n\n| Requirement | Version | Description |\n|-------------|---------|-------------|\n| Python | 3.10+ | Minimum supported Python version |\n| Python (Recommended) | 3.12 | Preferred Python version for best compatibility |\n| uv | Latest | ASTRA's Python package manager |\n\n资料来源：[README.md](), [CONTRIBUTING.md:17]()\n\n### Installing uv\n\nThe project uses `uv` as its package manager. Install `uv` by following the official documentation:\n\n```bash\n# Installation command (refer to https://docs.astral.sh/uv/getting-started/installation/)\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n```\n\nAlternatively, for pip users:\n\n```bash\npip install uv\n```\n\n资料来源：[CONTRIBUTING.md:18]()\n\n## Installation Methods\n\n### For Users: Installing the Package\n\nFor end users who want to use fastapi-mcp as a dependency:\n\n```bash\n# Using uv\nuv add fastapi-mcp\n\n# Or using pip\npip install fastapi-mcp\n```\n\n### For Developers: Setting Up the Development Environment\n\nFor contributors setting up the local development environment:\n\n```mermaid\ngraph TD\n    A[Fork Repository] --> B[Clone Your Fork]\n    B --> C[Add Upstream Remote]\n    C --> D[uv sync]\n    D --> E[Install Pre-commit Hooks]\n    E --> F[Ready for Development]\n```\n\n#### Step 1: Fork and Clone\n\n```bash\n# Fork the repository on GitHub\n# Clone your fork\ngit clone https://github.com/YOUR-USERNAME/fastapi_mcp.git\ncd fastapi-mcp\n\n# Add the upstream remote\ngit remote add upstream https://github.com/tadata-org/fastapi_mcp.git\n```\n\n资料来源：[CONTRIBUTING.md:24-35]()\n\n#### Step 2: Sync Dependencies\n\nThe `uv sync` command automatically creates and manages a virtual environment:\n\n```bash\nuv sync\n```\n\nThis command will:\n- Create a `.venv` directory with a virtual environment\n- Install all runtime dependencies from `pyproject.toml`\n- Install development dependencies (marked with `--group dev`)\n\n资料来源：[CONTRIBUTING.md:37-43]()\n\n#### Step 3: Install Pre-commit Hooks\n\nPre-commit hooks automatically run code quality checks before each commit:\n\n```bash\n# Install the hooks\nuv run pre-commit install\n\n# Run all hooks manually (optional, for verification)\nuv run pre-commit run\n```\n\n资料来源：[CONTRIBUTING.md:45-51]()\n\n## Running Commands\n\nYou have two options for executing commands within the development environment.\n\n### Option 1: Activate the Virtual Environment\n\n```bash\n# On Unix/macOS\nsource .venv/bin/activate\n\n# On Windows\n.venv\\Scripts\\activate\n\n# Then run commands directly\npytest\nmypy .\nruff check .\nruff format .\n```\n\n### Option 2: Use uv run Prefix\n\n```bash\n# Without activating the environment\nuv run pytest\nuv run mypy .\nuv run ruff check .\nuv run ruff format .\n```\n\n资料来源：[CONTRIBUTING.md:53-75]()\n\n## Adding Dependencies\n\n### Runtime Dependencies\n\nPackages needed to run the application:\n\n```bash\nuv add new-package\n```\n\n### Development Dependencies\n\nPackages needed for development, testing, or CI:\n\n```bash\nuv add --group dev new-package\n```\n\nAfter adding dependencies:\n\n1. Test that everything works with the new package\n2. Commit both `pyproject.toml` and `uv.lock` files:\n\n```bash\ngit add pyproject.toml uv.lock\ngit commit -m \"Add new-package dependency\"\n```\n\n资料来源：[CONTRIBUTING.md:77-92]()\n\n## Code Quality Tools\n\nThe project enforces code quality using the following tools:\n\n| Tool | Purpose | Command |\n|------|---------|---------|\n| **ruff** | Linting and formatting | `ruff check .` / `ruff format .` |\n| **mypy** | Type checking | `mypy .` |\n| **pytest** | Testing | `pytest` |\n| **pre-commit** | Automated checks | `pre-commit run` |\n\n资料来源：[CONTRIBUTING.md:94-104]()\n\n### Running All Checks\n\nBefore submitting a pull request, ensure all checks pass:\n\n```bash\n# Format code\nruff format .\n\n# Check code style\nruff check .\n\n# Type checking\nmypy .\n\n# Run tests\npytest\n```\n\n## Quick Start Checklist\n\nUse this checklist to verify your installation is complete:\n\n- [ ] Python 3.10+ is installed (`python --version`)\n- [ ] uv is installed (`uv --version`)\n- [ ] Repository is forked and cloned\n- [ ] `uv sync` completed successfully\n- [ ] `uv run pre-commit install` executed\n- [ ] `uv run pre-commit run` passes (or first commit triggers it)\n- [ ] `uv run pytest` runs successfully\n- [ ] `uv run mypy .` passes type checking\n\n## Troubleshooting\n\n### Common Issues\n\n**Virtual environment not found**\n```bash\nuv sync\n```\n\n**Pre-commit hooks not running**\n```bash\nuv run pre-commit install\nuv run pre-commit run --all-files\n```\n\n**Dependency conflicts**\n```bash\nuv sync --refresh\n```\n\n## Related Documentation\n\n- [Contributing Guide](CONTRIBUTING.md) - Full development workflow\n- [README](README.md) - Project overview and features\n- [GitHub Repository](https://github.com/tadata-org/fastapi_mcp) - Source code\n\n---\n\n<a id='quickstart'></a>\n\n## Quickstart Guide\n\n### 相关页面\n\n相关主题：[FastAPI-MCP Home](#home), [Examples Overview](#examples), [Endpoint Filtering and Selection](#endpoint-filtering)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [examples/01_basic_usage_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)\n- [examples/shared/apps/items.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/shared/apps/items.py)\n- [examples/shared/setup.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/shared/setup.py)\n- [examples/02_full_schema_description_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/02_full_schema_description_example.py)\n- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n</details>\n\n# Quickstart Guide\n\nThis guide provides a comprehensive walkthrough for getting started with **FastAPI-MCP**, a library that seamlessly integrates FastAPI applications with the Model Context Protocol (MCP). It allows you to expose your FastAPI endpoints as MCP tools with minimal configuration.\n\n## Prerequisites\n\nBefore getting started, ensure you have the following installed:\n\n| Requirement | Version | Notes |\n|-------------|---------|-------|\n| Python | 3.10+ (Recommended 3.12) | The project uses modern Python features |\n| uv | Latest | Package manager for dependency installation |\n\n资料来源：[README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/README.md)\n\n## Installation\n\nInstall FastAPI-MCP using uv:\n\n```bash\nuv add fastapi-mcp\n```\n\nFor development setup with all dependencies:\n\n```bash\ngit clone https://github.com/YOUR-USERNAME/fastapi_mcp.git\ncd fastapi-mcp\nuv sync\n```\n\n资料来源：[CONTRIBUTING.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CONTRIBUTING.md)\n\n## Basic Usage\n\nThe simplest way to add an MCP server to your FastAPI application involves three steps:\n\n### 1. Import FastApiMCP\n\n```python\nfrom fastapi_mcp import FastApiMCP\n```\n\n资料来源：[examples/01_basic_usage_example.py:1]()\n\n### 2. Create the MCP Server Instance\n\nPass your FastAPI app to the `FastApiMCP` constructor:\n\n```python\nfrom examples.shared.apps.items import app  # Your FastAPI app\nfrom examples.shared.setup import setup_logging\n\nfrom fastapi_mcp import FastApiMCP\n\nsetup_logging()\n\n# Add MCP server to the FastAPI app\nmcp = FastApiMCP(app)\n```\n\n资料来源：[examples/01_basic_usage_example.py:1-9]()\n\n### 3. Mount the MCP Server\n\nMount the MCP server to your FastAPI app using `mount_http()`:\n\n```python\n# Mount the MCP server to the FastAPI app\nmcp.mount_http()\n```\n\n资料来源：[examples/01_basic_usage_example.py:12]()\n\n### 4. Run the Server\n\nStart the uvicorn server:\n\n```python\nif __name__ == \"__main__\":\n    import uvicorn\n\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\n资料来源：[examples/01_basic_usage_example.py:15-18]()\n\n## Complete Basic Example\n\nHere is the full minimal example from `examples/01_basic_usage_example.py`:\n\n```python\nfrom examples.shared.apps.items import app  # The FastAPI app\nfrom examples.shared.setup import setup_logging\n\nfrom fastapi_mcp import FastApiMCP\n\nsetup_logging()\n\n# Add MCP server to the FastAPI app\nmcp = FastApiMCP(app)\n\n# Mount the MCP server to the FastAPI app\nmcp.mount_http()\n\n\nif __name__ == \"__main__\":\n    import uvicorn\n\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\n资料来源：[examples/01_basic_usage_example.py:1-19]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[FastAPI Application] --> B[FastApiMCP]\n    B --> C[MCP Server]\n    C --> D[HTTP Endpoint /mcp]\n    D --> E[MCP Client]\n    \n    F[OpenAPI Schema] --> B\n    B --> G[MCP Tools]\n    \n    style A fill:#e1f5ff\n    style C fill:#fff3e0\n    style D fill:#e8f5e9\n```\n\n## Enhanced Schema Description\n\nBy default, FastAPI-MCP provides concise tool descriptions. You can enhance the descriptions by enabling additional options:\n\n```python\nmcp = FastApiMCP(\n    app,\n    name=\"Item API MCP\",\n    description=\"MCP server for the Item API\",\n    describe_full_response_schema=True,  # Describe the full response JSON-schema\n    describe_all_responses=True,         # Describe all possible responses, not just 2XX\n)\n\nmcp.mount_http()\n```\n\n资料来源：[examples/02_full_schema_description_example.py:1-18]()\n\n## Filtering Exposed Endpoints\n\nYou can control which endpoints are exposed as MCP tools using operation IDs or tags:\n\n### Filter by Operation IDs\n\n```python\n# Include specific operations\ninclude_operations_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Operations\",\n    include_operations=[\"get_item\", \"list_items\"],\n)\n\n# Exclude specific operations\nexclude_operations_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Operations\",\n    exclude_operations=[\"create_item\", \"update_item\", \"delete_item\"],\n)\n```\n\n### Filter by Tags\n\n```python\n# Include endpoints with specific tags\ninclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Tags\",\n    include_tags=[\"items\"],\n)\n\n# Exclude endpoints with specific tags\nexclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Tags\",\n    exclude_tags=[\"search\"],\n)\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:1-50]()\n\n## Adding Authentication\n\nFastAPI-MCP supports authentication by leveraging your existing FastAPI dependencies. Use the `AuthConfig` class to configure authentication:\n\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\n# Define your authentication scheme\ntoken_auth_scheme = HTTPBearer()\n\n# Create protected endpoint\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\n# Configure MCP with authentication\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)],\n    ),\n)\n\nmcp.mount_http()\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py:1-50]()\n\n## Key Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `app` | FastAPI | Required | The FastAPI application instance |\n| `name` | str | Auto-generated | Name of the MCP server |\n| `description` | str | Auto-generated | Description of the MCP server |\n| `describe_full_response_schema` | bool | False | Include full JSON schema for responses |\n| `describe_all_responses` | bool | False | Include all response types, not just success |\n| `include_operations` | List[str] | None | Operation IDs to include |\n| `exclude_operations` | List[str] | None | Operation IDs to exclude |\n| `include_tags` | List[str] | None | Tags to include |\n| `exclude_tags` | List[str] | None | Tags to exclude |\n| `auth_config` | AuthConfig | None | Authentication configuration |\n| `headers` | List[str] | [\"authorization\"] | Headers to forward to tool invocations |\n\n资料来源：[fastapi_mcp/server.py:1-100]()\n\n## Running the Quickstart\n\nTo run the basic example:\n\n```bash\n# Navigate to the examples directory\ncd examples\n\n# Run the basic usage example\nuv run python 01_basic_usage_example.py\n```\n\nOnce running, the MCP server will be available at `http://localhost:8000/mcp`.\n\n## Verification\n\nAfter starting the server, you can verify it's working by:\n\n1. Accessing the OpenAPI docs at `http://localhost:8000/docs`\n2. Checking the MCP endpoint at `http://localhost:8000/mcp`\n\n## Next Steps\n\n- Explore [Authentication Examples](examples/08_auth_example_token_passthrough.py) for securing your MCP server\n- Learn about [Custom Endpoint Filtering](examples/03_custom_exposed_endpoints_example.py) for granular control\n- Review the [Full Schema Description](examples/02_full_schema_description_example.py) for detailed tool documentation\n\n---\n\n<a id='examples'></a>\n\n## Examples Overview\n\n### 相关页面\n\n相关主题：[Quickstart Guide](#quickstart), [OAuth Authentication](#auth-oauth), [Deployment Options](#deployment), [Dynamic Tool Registration](#dynamic-registration)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [examples/README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/README.md)\n- [examples/01_basic_usage_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)\n- [examples/04_separate_server_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/04_separate_server_example.py)\n- [examples/05_reregister_tools_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/05_reregister_tools_example.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n- [examples/09_auth_example_auth0.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/09_auth_example_auth0.py)\n</details>\n\n# Examples Overview\n\nThe `examples/` directory in the FastAPI-MCP repository provides a comprehensive collection of runnable examples demonstrating the library's capabilities. These examples serve as practical guides for developers learning how to integrate FastAPI applications with the MCP (Model Context Protocol) server infrastructure.\n\n## Directory Structure\n\nThe examples directory follows a modular organization pattern:\n\n```\nexamples/\n├── README.md\n├── 01_basic_usage_example.py\n├── 02_multiple_apps_example.py\n├── 03_custom_exposed_endpoints_example.py\n├── 04_separate_server_example.py\n├── 05_reregister_tools_example.py\n├── 06_custom_tools_example.py\n├── 07_external_app_example.py\n├── 08_auth_example_token_passthrough.py\n├── 09_auth_example_auth0.py\n├── 10_standalone_server.py\n└── shared/\n    ├── apps/\n    │   └── items.py\n    └── setup.py\n```\n\n资料来源：[examples/README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/README.md)\n\n## Example Categories\n\n### Category 1: Basic Integration\n\nThe foundational examples demonstrate core FastAPI-MCP functionality.\n\n#### 01 - Basic Usage\n\nThis is the simplest possible integration demonstrating how to mount an MCP server onto a FastAPI application.\n\n```python\nfrom examples.shared.apps.items import app  # The FastAPI app\nfrom examples.shared.setup import setup_logging\nfrom fastapi_mcp import FastApiMCP\n\nsetup_logging()\n\n# Add MCP server to the FastAPI app\nmcp = FastApiMCP(app)\n\n# Mount the MCP server to the FastAPI app\nmcp.mount_http()\n\nif __name__ == \"__main__\":\n    import uvicorn\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\n**Key Components:**\n| Component | Purpose |\n|-----------|---------|\n| `FastApiMCP(app)` | Creates MCP server instance bound to FastAPI app |\n| `mcp.mount_http()` | Exposes MCP endpoint at `/mcp` path |\n| `setup_logging()` | Configures logging for debugging |\n\n资料来源：[examples/01_basic_usage_example.py:1-19](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)\n\n### Category 2: Endpoint Filtering\n\nThese examples demonstrate how to control which FastAPI endpoints are exposed as MCP tools.\n\n#### 03 - Custom Exposed Endpoints\n\nThe filtering system allows selective exposure of endpoints using operation IDs or tags.\n\n**Filtering Rules:**\n- Cannot use both `include_operations` and `exclude_operations` simultaneously\n- Cannot use both `include_tags` and `exclude_tags` simultaneously\n- Operation filtering can be combined with tag filtering (greedy approach)\n\n```python\n# Filter by including specific operation IDs\ninclude_operations_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Operations\",\n    include_operations=[\"get_item\", \"list_items\"],\n)\n\n# Filter by excluding specific operation IDs\nexclude_operations_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Operations\",\n    exclude_operations=[\"create_item\", \"update_item\", \"delete_item\"],\n)\n\n# Filter by including specific tags\ninclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Tags\",\n    include_tags=[\"items\"],\n)\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:1-39](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)\n\n**Filtering Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `include_operations` | `List[str]` | Operation IDs to include as MCP tools |\n| `exclude_operations` | `List[str]` | Operation IDs to exclude from MCP tools |\n| `include_tags` | `List[str]` | Tags to include as MCP tools |\n| `exclude_tags` | `List[str]` | Tags to exclude from MCP tools |\n\n资料来源：[fastapi_mcp/server.py:85-100](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n\n### Category 3: Authentication Examples\n\nFastAPI-MCP supports OAuth 2.0 authentication integration using FastAPI's dependency injection system.\n\n#### 08 - Token Passthrough Authentication\n\nThis example demonstrates protecting endpoints using HTTP Bearer tokens passed through the MCP client.\n\n**Configuration for MCP Client:**\n```json\n{\n  \"mcpServers\": {\n    \"remote-example\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"mcp-remote\",\n        \"http://localhost:8000/mcp\",\n        \"--header\",\n        \"Authorization:${AUTH_HEADER}\"\n      ]\n    }\n  }\n}\n```\n\n**Server Implementation:**\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\ntoken_auth_scheme = HTTPBearer()\n\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)],\n    ),\n)\nmcp.mount_http()\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py:1-47](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n\n#### 09 - Auth0 Integration\n\nThis example shows integration with Auth0 as an OAuth 2.0 provider, demonstrating the full OAuth flow setup.\n\n```python\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\nmcp = FastApiMCP(\n    app,\n    name=\"Auth0 Protected MCP\",\n    auth_config=AuthConfig(\n        issuer=\"https://your-tenant.auth0.com\",\n        # Additional OAuth configuration\n    ),\n)\n```\n\n**AuthConfig Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `version` | `Literal[\"2025-03-26\"]` | MCP spec version (currently only \"2025-03-26\") |\n| `dependencies` | `Sequence[Depends]` | FastAPI dependencies for auth checking |\n| `issuer` | `Optional[str]` | OAuth 2.0 server issuer URL |\n| `oauth_metadata_url` | `Optional[StrHttpUrl]` | Full OAuth provider metadata endpoint URL |\n| `authorize_url` | `Optional[StrHttpUrl]` | OAuth provider authorization endpoint |\n\n资料来源：[examples/09_auth_example_auth0.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/09_auth_example_auth0.py) and [fastapi_mcp/types.py:95-140](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n\n### Category 4: Advanced Integration Patterns\n\n#### 04 - Separate Server Example\n\nDemonstrates running the MCP server as a standalone process, separate from the main FastAPI application.\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_mcp import FastApiMCP\n\napp = FastAPI()\n\n# Create MCP server\nmcp = FastApiMCP(\n    app,\n    name=\"Separate MCP Server\",\n    # Configuration options\n)\n\n# Run MCP as standalone server\nif __name__ == \"__main__\":\n    mcp.run(...)\n```\n\n资料来源：[examples/04_separate_server_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/04_separate_server_example.py)\n\n#### 05 - Reregister Tools Example\n\nDemonstrates dynamic tool reregistration, useful for applications where available tools may change at runtime.\n\n```python\nfrom fastapi_mcp import FastApiMCP\n\nmcp = FastApiMCP(app)\n\n# Initial registration\nmcp.mount_http()\n\n# Later, reregister tools\nmcp.reregister_tools()\n```\n\n资料来源：[examples/05_reregister_tools_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/05_reregister_tools_example.py)\n\n## Architecture Diagram\n\n```mermaid\ngraph TD\n    A[FastAPI Application] --> B[FastApiMCP Instance]\n    B --> C[mount_http]\n    B --> D[Separate Server]\n    \n    C --> E[MCP Endpoint /mcp]\n    D --> F[Standalone MCP Server]\n    \n    E --> G[MCP Client]\n    F --> G\n    \n    G --> H[Tool Invocations]\n    H --> I[HTTP Requests to FastAPI]\n    I --> A\n    \n    J[AuthConfig] --> B\n    J --> K[OAuth 2.0 Flow]\n    K --> L[Auth0 / OAuth Provider]\n    \n    M[Filtering Options] --> B\n    M --> N[include_operations]\n    M --> O[exclude_operations]\n    M --> P[include_tags]\n    M --> Q[exclude_tags]\n```\n\n## Common Setup Module\n\nAll examples share a common setup module that configures logging:\n\n```python\nfrom examples.shared.setup import setup_logging\n\nsetup_logging()\n```\n\nThe shared items application provides a sample FastAPI app with CRUD operations for an `Item` model, used across multiple examples:\n\n资料来源：[examples/shared/apps/items.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/shared/apps/items.py)\n\n## Running Examples\n\n### Using uv (Recommended)\n\n```bash\n# Install dependencies\nuv sync\n\n# Run an example\nuv run python examples/01_basic_usage_example.py\n```\n\n### Using pre-commit hooks\n\n```bash\nuv run pre-commit install\nuv run pre-commit run\n```\n\n资料来源：[CONTRIBUTING.md:1-30](https://github.com/tadata-org/fastapi_mcp/blob/main/CONTRIBUTING.md)\n\n## Requirements Summary\n\n| Requirement | Version | Notes |\n|-------------|---------|-------|\n| Python | 3.10+ | Recommended 3.12 |\n| Package Manager | uv | Required for development |\n\n资料来源：[README.md:45-48](https://github.com/tadata-org/fastapi_mcp/blob/main/README.md)\n\n## Example Selection Guide\n\n| Use Case | Recommended Example |\n|----------|---------------------|\n| First-time integration | 01_basic_usage_example.py |\n| Selective endpoint exposure | 03_custom_exposed_endpoints_example.py |\n| OAuth with existing tokens | 08_auth_example_token_passthrough.py |\n| Auth0 integration | 09_auth_example_auth0.py |\n| Standalone MCP server | 04_separate_server_example.py |\n| Dynamic tool updates | 05_reregister_tools_example.py |\n\n---\n\n<a id='auth-overview'></a>\n\n## Authentication Overview\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture), [OAuth Authentication](#auth-oauth)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n- [fastapi_mcp/auth/proxy.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/auth/proxy.py)\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n- [examples/09_auth_example_auth0.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/09_auth_example_auth0.py)\n</details>\n\n# Authentication Overview\n\nFastAPI-MCP provides a built-in authentication system that leverages your existing FastAPI dependencies. This approach eliminates the need to configure a separate authentication mechanism and seamlessly integrates with MCP clients that support OAuth 2.0 flows.\n\n## Architecture Overview\n\nThe authentication system in FastAPI-MCP is built around the MCP specification version `2025-03-26`. It supports two primary authentication modes:\n\n1. **Token Passthrough** - Validates bearer tokens using FastAPI dependencies\n2. **OAuth 2.0 Flow** - Full OAuth 2.0 authorization code flow with proxy endpoints\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|HTTP Request| B[FastAPI-MCP Server]\n    B -->|Validate| C{FastAPI Dependencies}\n    C -->|Valid| D[Tool Execution]\n    C -->|Invalid| E[401 Unauthorized]\n    \n    F[OAuth Flow] -->|Token Request| G[OAuth Provider]\n    G -->|Access Token| F\n    \n    B -->|Proxy| H[OAuth Metadata Endpoint]\n    B -->|Proxy| I[Authorization Endpoint]\n```\n\n## Core Data Models\n\n### AuthConfig\n\nThe `AuthConfig` class is the central configuration model for authentication in FastAPI-MCP.\n\n资料来源：[fastapi_mcp/types.py:88-147]()\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `version` | `Literal[\"2025-03-26\"]` | `\"2025-03-26\"` | MCP spec version for authorization |\n| `dependencies` | `Sequence[Depends]` | `None` | FastAPI dependencies for authentication checks |\n| `custom_oauth_metadata` | `OAuthMetadataDict` | `None` | Custom OAuth metadata instead of proxy setup |\n| `issuer` | `str` | `None` | OAuth 2.0 server issuer URL |\n| `oauth_metadata_url` | `StrHttpUrl` | `None` | Full URL of OAuth provider's metadata endpoint |\n| `authorize_url` | `StrHttpUrl` | `None` | OAuth provider's authorization endpoint URL |\n| `token_endpoint` | `StrHttpUrl` | `None` | OAuth provider's token endpoint URL |\n| `metadata_path` | `str` | `\"/.well-known/oauth-authorization-server\"` | Path to serve OAuth metadata |\n| `client_id` | `str` | `None` | OAuth client ID |\n| `client_secret` | `str` | `None` | OAuth client secret |\n| `audience` | `str` | `None` | Expected audience claim in tokens |\n| `setup_proxies` | `bool` | `False` | Whether to set up OAuth proxy endpoints |\n| `setup_fake_dynamic_registration` | `bool` | `False` | Setup fake dynamic client registration endpoint |\n| `default_scope` | `str` | `\"openid profile email\"` | Default OAuth scope |\n\n### OAuthMetadata\n\nRepresents OAuth 2.0 Server Metadata according to RFC 8414.\n\n资料来源：[fastapi_mcp/types.py:33-86]()\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `issuer` | `StrHttpUrl` | Yes | Authorization server's issuer identifier (HTTPS URL) |\n| `authorization_endpoint` | `StrHttpUrl` | No | Authorization endpoint URL |\n| `token_endpoint` | `StrHttpUrl` | Yes | Token endpoint URL |\n| `scopes_supported` | `List[str]` | No | Supported OAuth 2.0 scopes |\n| `response_types_supported` | `List[str]` | No | Supported response types |\n| `grant_types_supported` | `List[str]` | No | Supported grant types |\n\n## Authentication Setup Flow\n\nThe authentication system is initialized during `FastApiMCP` construction. The `_setup_auth_2025_03_26()` method handles the setup based on the configuration.\n\n资料来源：[fastapi_mcp/server.py:150-190]()\n\n```mermaid\nsequenceDiagram\n    participant Client as MCP Client\n    participant Server as FastAPI-MCP\n    participant Proxy as OAuth Proxies\n    participant Provider as OAuth Provider\n    \n    Note over Server: AuthConfig provided\n    Server->>Server: _setup_auth_2025_03_26()\n    \n    alt Custom OAuth Metadata\n        Server->>Proxy: setup_oauth_custom_metadata()\n        Note over Proxy: Serve custom metadata at metadata_path\n    else Setup Proxies\n        Server->>Proxy: setup_oauth_metadata_proxy()\n        Server->>Proxy: setup_oauth_authorize_proxy()\n        \n        alt Fake Dynamic Registration\n            Server->>Proxy: setup_oauth_fake_dynamic_register_endpoint()\n        end\n    end\n    \n    Client->>Server: Request with Auth Header\n    Server->>Server: Run dependencies\n    alt Dependencies Pass\n        Server->>Server: Execute Tool\n    else Dependencies Fail\n        Server-->>Client: 401 Unauthorized\n    end\n```\n\n## Proxy Endpoints\n\nFastAPI-MCP automatically sets up proxy endpoints when `setup_proxies=True` is configured.\n\n资料来源：[fastapi_mcp/auth/proxy.py:1-50]()\n\n### Metadata Proxy\n\nServes OAuth 2.0 server metadata. When `oauth_metadata_url` is not provided, it constructs the URL from `issuer` and `metadata_path`.\n\n```python\nsetup_oauth_metadata_proxy(\n    app=self.fastapi,\n    metadata_url=f\"{issuer}{metadata_path}\",\n    path=\"/.well-known/oauth-authorization-server\",\n    register_path=\"/oauth/register\"  # if setup_fake_dynamic_registration is True\n)\n```\n\n### Authorization Proxy\n\nProxies authorization requests to the OAuth provider, with fallback handling for missing parameters.\n\n资料来源：[fastapi_mcp/auth/proxy.py:80-140]()\n\n| Parameter | Purpose |\n|-----------|---------|\n| `client_id` | Default client ID when not provided by client |\n| `authorize_url` | Target OAuth authorization endpoint |\n| `audience` | Default audience when not specified |\n| `default_scope` | Default scope (`openid profile email`) |\n\n### Fake Dynamic Registration\n\nFor development or testing environments, a fake dynamic client registration endpoint can be enabled.\n\n```python\nsetup_oauth_fake_dynamic_register_endpoint(\n    app=self.fastapi,\n    client_id=\"test-client-id\",\n    client_secret=\"test-client-secret\"\n)\n```\n\n## Usage Examples\n\n### Token Passthrough Authentication\n\nThe simplest form of authentication uses FastAPI dependencies to validate bearer tokens.\n\n资料来源：[examples/08_auth_example_token_passthrough.py:1-50]()\n\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\ntoken_auth_scheme = HTTPBearer()\n\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)]\n    )\n)\n\nmcp.mount_http()\n```\n\n### Auth0 Integration\n\nFull OAuth 2.0 flow with Auth0 as the identity provider.\n\n资料来源：[examples/09_auth_example_auth0.py:1-60]()\n\n```python\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\nmcp = FastApiMCP(\n    app,\n    name=\"MCP With Auth0\",\n    auth_config=AuthConfig(\n        issuer=f\"https://{settings.auth0_domain}/\",\n        authorize_url=f\"https://{settings.auth0_domain}/authorize\",\n        oauth_metadata_url=settings.auth0_oauth_metadata_url,\n        audience=settings.auth0_audience,\n        client_id=settings.auth0_client_id,\n        client_secret=settings.auth0_client_secret,\n        dependencies=[Depends(verify_auth)],\n        setup_proxies=True,\n    )\n)\n\nmcp.mount_http()\n```\n\n## MCP Client Configuration\n\nFor token passthrough authentication, configure your MCP client to include the authorization header.\n\n```json\n{\n  \"mcpServers\": {\n    \"remote-example\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"mcp-remote\",\n        \"http://localhost:8000/mcp\",\n        \"--header\",\n        \"Authorization:${AUTH_HEADER}\"\n      ]\n    },\n    \"env\": {\n      \"AUTH_HEADER\": \"Bearer <your-token>\"\n    }\n  }\n}\n```\n\n## Key Implementation Details\n\n### Dependency Injection\n\nAuthentication is enforced through standard FastAPI dependency injection. Any `Depends()` callable that raises `HTTPException(401)` or `HTTPException(403)` will trigger the OAuth flow in supporting clients.\n\n资料来源：[fastapi_mcp/types.py:103-130]()\n\n```python\nasync def authenticate_request(request: Request, token: str = Depends(oauth2_scheme)):\n    payload = verify_token(request, token)\n    if payload is None:\n        raise HTTPException(status_code=401, detail=\"Unauthorized\")\n    return payload\n```\n\n### Metadata Serialization\n\nThe `OAuthMetadata` model uses special serialization to ensure compatibility with OAuth clients:\n\n- `exclude_unset=True` - Never include unset fields\n- `exclude_none=True` - Never include fields with `None` values\n\n资料来源：[fastapi_mcp/types.py:69-86]()\n\n### Base Type Configuration\n\nAll authentication-related models inherit from `BaseType` which configures:\n\n- `extra=\"ignore\"` - Silently ignore unexpected fields\n- `arbitrary_types_allowed=True` - Allow complex type annotations\n\n## Workflow Summary\n\n| Step | Component | Action |\n|------|-----------|--------|\n| 1 | `FastApiMCP.__init__()` | Accept `AuthConfig` parameter |\n| 2 | `setup_server()` | Call `_setup_auth_2025_03_26()` |\n| 3 | Proxy Setup | Register endpoints based on config |\n| 4 | Request Handling | Dependencies validate tokens |\n| 5 | Tool Execution | Proceed if authentication succeeds |\n\nThe authentication system is designed to be non-intrusive, requiring minimal configuration while providing full OAuth 2.0 compatibility for production deployments.\n\n---\n\n<a id='auth-oauth'></a>\n\n## OAuth Authentication\n\n### 相关页面\n\n相关主题：[Authentication Overview](#auth-overview), [Deployment Options](#deployment)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [fastapi_mcp/auth/proxy.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/auth/proxy.py)\n- [examples/09_auth_example_auth0.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/09_auth_example_auth0.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n</details>\n\n# OAuth Authentication\n\n## Overview\n\nFastAPI-MCP provides built-in OAuth 2.0 authentication support that integrates seamlessly with your existing FastAPI dependencies. The authentication system follows the MCP (Model Context Protocol) specification version 2025-03-26, enabling MCP clients to authenticate requests using OAuth 2.0 flows.\n\nThe authentication layer serves three primary purposes:\n\n1. **Metadata Discovery** - Exposes OAuth server metadata at standardized endpoints\n2. **Authorization Flow** - Proxies authorization requests to your OAuth provider\n3. **Dynamic Client Registration** - Provides a fake dynamic client registration endpoint for clients that require it\n\n## Architecture\n\nThe OAuth authentication system consists of several coordinated components that work together to bridge MCP clients with your OAuth provider.\n\n```mermaid\ngraph TD\n    subgraph \"MCP Client\"\n        A[MCP Client] -->|OAuth Request| B[MCP Server]\n    end\n    \n    subgraph \"FastAPI-MCP Server\"\n        B --> C{Auth Dependencies Check}\n        C -->|Valid Token| D[MCP Tool Handler]\n        C -->|Invalid/Missing| E[401 Unauthorized]\n        C -->|Trigger OAuth| F[OAuth Proxy Endpoints]\n        \n        F --> G[Metadata Proxy<br/>/.well-known/oauth-authorization-server]\n        F --> H[Authorize Proxy<br/>/oauth/authorize]\n        F --> I[Dynamic Registration<br/>/oauth/register]\n    end\n    \n    subgraph \"External OAuth Provider\"\n        G -->|Fetch & Transform| J[Provider Metadata]\n        H -->|Redirect| K[Provider Authorization]\n        I -->|Fake Response| L[Client Credentials]\n    end\n```\n\n### Core Components\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| `AuthConfig` | `fastapi_mcp/types.py` | Configuration container for OAuth settings |\n| `OAuthMetadata` | `fastapi_mcp/types.py` | OAuth 2.0 Server Metadata model (RFC 8414) |\n| `setup_oauth_custom_metadata()` | `fastapi_mcp/auth/proxy.py` | Serves custom OAuth metadata |\n| `setup_oauth_metadata_proxy()` | `fastapi_mcp/auth/proxy.py` | Proxies external OAuth metadata with modifications |\n| `setup_oauth_authorize_proxy()` | `fastapi_mcp/auth/proxy.py` | Proxies authorization endpoint |\n| `setup_oauth_fake_dynamic_register_endpoint()` | `fastapi_mcp/auth/proxy.py` | Provides fake client registration |\n\n## AuthConfig Specification\n\nThe `AuthConfig` class is the central configuration point for OAuth authentication in FastAPI-MCP.\n\n资料来源：[fastapi_mcp/types.py:127-217]()\n\n### Configuration Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `version` | `Literal[\"2025-03-26\"]` | `\"2025-03-26\"` | MCP spec version for authorization |\n| `dependencies` | `Sequence[Depends]` | `None` | FastAPI dependencies for auth verification |\n| `issuer` | `str` | `None` | OAuth provider issuer URL |\n| `oauth_metadata_url` | `StrHttpUrl` | `None` | Full URL of OAuth provider's metadata endpoint |\n| `authorize_url` | `StrHttpUrl` | `None` | OAuth provider's authorization endpoint |\n| `audience` | `str` | `None` | Default audience for requests |\n| `default_scope` | `str` | `\"openid profile email\"` | Default OAuth scopes |\n| `client_id` | `str` | `None` | Default client ID |\n| `client_secret` | `str` | `None` | Client secret for dynamic registration |\n| `custom_oauth_metadata` | `OAuthMetadataDict` | `None` | Custom OAuth metadata object |\n| `setup_proxies` | `bool` | `False` | Enable OAuth proxy setup |\n| `setup_fake_dynamic_registration` | `bool` | `False` | Enable fake dynamic client registration |\n| `metadata_path` | `str` | `\"/.well-known/oauth-authorization-server\"` | Path for metadata endpoint |\n\n### Example Configuration\n\n```python\nfrom fastapi import Depends\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        issuer=\"https://your-tenant.auth0.com/\",\n        authorize_url=\"https://your-tenant.auth0.com/authorize\",\n        oauth_metadata_url=\"https://your-tenant.auth0.com/.well-known/openid-configuration\",\n        audience=\"https://your-tenant.auth0.com/api/v2/\",\n        client_id=\"your-client-id\",\n        client_secret=\"your-client-secret\",\n        dependencies=[Depends(verify_auth)],\n        setup_proxies=True,\n        setup_fake_dynamic_registration=True,\n    ),\n)\n```\n\n资料来源：[examples/09_auth_example_auth0.py:1-50]()\n\n## OAuthMetadata Model\n\nThe `OAuthMetadata` class represents OAuth 2.0 Authorization Server Metadata as defined in RFC 8414.\n\n资料来源：[fastapi_mcp/types.py:36-118]()\n\n### Metadata Fields\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `issuer` | `StrHttpUrl` | Yes | Authorization server issuer identifier (https URL) |\n| `authorization_endpoint` | `StrHttpUrl` | No | Authorization endpoint URL |\n| `token_endpoint` | `StrHttpUrl` | Yes | Token endpoint URL |\n| `scopes_supported` | `List[str]` | No | Supported OAuth 2.0 scopes (default: `[\"openid\", \"profile\", \"email\"]`) |\n| `response_types_supported` | `List[str]` | No | Supported response types (default: `[\"code\"]`) |\n| `grant_types_supported` | `List[str]` | No | Supported grant types (default: `[\"authorization_code\", \"client_credentials\"]`) |\n| `token_endpoint_auth_methods_supported` | `List[str]` | No | Client auth methods (default: `[\"none\"]`) |\n| `code_challenge_methods_supported` | `List[str]` | No | PKCE challenge methods (default: `[\"S256\"]`) |\n| `registration_endpoint` | `StrHttpUrl` | No | Client registration endpoint URL |\n\n## Authentication Dependencies\n\nFastAPI-MCP leverages FastAPI's dependency injection system for authentication checks. Dependencies must raise 401 or 403 errors when requests are unauthorized, which triggers the MCP client to initiate an OAuth flow.\n\n资料来源：[fastapi_mcp/types.py:149-174]()\n\n### Dependency Implementation Pattern\n\n```python\nfrom fastapi import Depends, HTTPException, Request\nfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentials\n\nsecurity = HTTPBearer()\n\nasync def verify_auth(request: Request, credentials: HTTPAuthorizationCredentials = Depends(security)):\n    \"\"\"Verify the bearer token and return user information.\"\"\"\n    token = credentials.credentials\n    \n    # Validate token with your OAuth provider\n    payload = verify_token(token)\n    \n    if payload is None:\n        raise HTTPException(\n            status_code=401,\n            detail=\"Unauthorized\",\n            headers={\"WWW-Authenticate\": \"Bearer\"},\n        )\n    \n    return payload\n\n# Usage with FastAPI-MCP\nmcp = FastApiMCP(\n    app,\n    auth_config=AuthConfig(dependencies=[Depends(verify_auth)]),\n)\n```\n\n资料来源：[fastapi_mcp/types.py:155-172]()\n\n## OAuth Proxy Setup Functions\n\n### setup_oauth_custom_metadata()\n\nServes custom OAuth metadata provided directly in the `AuthConfig`.\n\n资料来源：[fastapi_mcp/auth/proxy.py:50-75]()\n\n```python\ndef setup_oauth_custom_metadata(\n    app: FastAPI,\n    auth_config: AuthConfig,\n    metadata: OAuthMetadataDict,\n    include_in_schema: bool = False,\n) -> None:\n    \"\"\"\n    Serve custom metadata at the path specified in auth_config.metadata_path.\n    \"\"\"\n    auth_config = AuthConfig.model_validate(auth_config)\n    metadata = OAuthMetadata.model_validate(metadata)\n\n    @app.get(\n        auth_config.metadata_path,\n        response_model=OAuthMetadata,\n        response_model_exclude_unset=True,\n        response_model_exclude_none=True,\n        include_in_schema=include_in_schema,\n        operation_id=\"oauth_custom_metadata\",\n    )\n    async def oauth_metadata_proxy():\n        return metadata\n```\n\n### setup_oauth_metadata_proxy()\n\nProxies an external OAuth provider's metadata endpoint while modifying specific fields.\n\n资料来源：[fastapi_mcp/auth/proxy.py:78-135]()\n\n```python\ndef setup_oauth_metadata_proxy(\n    app: FastAPI,\n    metadata_url: str,\n    path: str = \"/.well-known/oauth-authorization-server\",\n    authorize_path: str = \"/oauth/authorize\",\n    register_path: Optional[str] = None,\n    include_in_schema: bool = False,\n) -> None:\n    \"\"\"\n    Fetch OAuth metadata from provider and override specific endpoints.\n    \"\"\"\n    @app.get(\n        path,\n        response_model=OAuthMetadata,\n        response_model_exclude_unset=True,\n        response_model_exclude_none=True,\n        include_in_schema=include_in_schema,\n        operation_id=\"oauth_metadata_proxy\",\n    )\n    async def oauth_metadata_proxy(request: Request):\n        base_url = str(request.base_url).rstrip(\"/\")\n\n        async with httpx.AsyncClient() as client:\n            response = await client.get(metadata_url)\n            if response.status_code != 200:\n                raise HTTPException(\n                    status_code=502,\n                    detail=\"Failed to fetch OAuth metadata\",\n                )\n            oauth_metadata = response.json()\n\n        # Override registration endpoint if provided\n        if register_path:\n            oauth_metadata[\"registration_endpoint\"] = f\"{base_url}{register_path}\"\n\n        # Replace authorization endpoint with our proxy\n        oauth_metadata[\"authorization_endpoint\"] = f\"{base_url}{authorize_path}\"\n\n        return OAuthMetadata.model_validate(oauth_metadata)\n```\n\n### setup_oauth_authorize_proxy()\n\nCreates a proxy for the OAuth provider's authorization endpoint.\n\n资料来源：[fastapi_mcp/auth/proxy.py:138-210]()\n\n```python\ndef setup_oauth_authorize_proxy(\n    app: FastAPI,\n    client_id: str,\n    authorize_url: Optional[StrHttpUrl] = None,\n    audience: Optional[str] = None,\n    default_scope: str = \"openid profile email\",\n    path: str = \"/oauth/authorize\",\n) -> None:\n    \"\"\"\n    Proxy authorization requests to the OAuth provider.\n    \"\"\"\n    @app.get(\n        path,\n        response_class=RedirectResponse,\n        operation_id=\"oauth_authorize_proxy\",\n    )\n    async def oauth_authorize_proxy(request: Request, redirect_uri: str):\n        params = {\n            \"client_id\": client_id,\n            \"redirect_uri\": redirect_uri,\n            \"response_type\": \"code\",\n            \"scope\": default_scope,\n        }\n        \n        if audience:\n            params[\"audience\"] = audience\n            \n        # Redirect to actual OAuth provider\n        query = urlencode(params)\n        return f\"{authorize_url}?{query}\"\n```\n\n## Authorization Flow\n\n### MCP Spec Version 2025-03-26 Setup\n\nThe auth setup is triggered in the `FastApiMCP` initialization flow.\n\n资料来源：[fastapi_mcp/server.py:1-50]()\n\n```mermaid\nsequenceDiagram\n    participant Client as MCP Client\n    participant FastAPI as FastAPI App\n    participant Proxy as OAuth Proxies\n    participant Provider as OAuth Provider\n\n    Client->>FastAPI: MCP Request with Bearer Token\n    FastAPI->>FastAPI: Run Auth Dependencies\n    alt Token Invalid or Missing\n        FastAPI-->>Client: 401 Unauthorized\n        Client->>Proxy: Discover OAuth Metadata\n        Proxy->>Provider: Fetch Metadata\n        Provider-->>Proxy: OAuth Metadata\n        Proxy-->>Client: Modified Metadata\n        Client->>Proxy: Authorization Request\n        Proxy->>Provider: Redirect to /authorize\n        Provider-->>Client: Authorization Code\n        Client->>Proxy: Token Request\n        Proxy->>Provider: Token Exchange\n        Provider-->>Proxy: Access Token\n        Proxy-->>Client: Access Token\n        Client->>FastAPI: MCP Request with Token\n        FastAPI->>FastAPI: Validate Token\n    end\n```\n\n### Server-Side Setup Logic\n\nThe `_setup_auth_2025_03_26()` method in `FastApiMCP` orchestrates the OAuth setup:\n\n资料来源：[fastapi_mcp/server.py:50-100]()\n\n```python\ndef _setup_auth_2025_03_26(self):\n    if self._auth_config:\n        if self._auth_config.custom_oauth_metadata:\n            setup_oauth_custom_metadata(\n                app=self.fastapi,\n                auth_config=self._auth_config,\n                metadata=self._auth_config.custom_oauth_metadata,\n            )\n        elif self._auth_config.setup_proxies:\n            metadata_url = self._auth_config.oauth_metadata_url\n            if not metadata_url:\n                metadata_url = f\"{self._auth_config.issuer}{self._auth_config.metadata_path}\"\n\n            setup_oauth_metadata_proxy(\n                app=self.fastapi,\n                metadata_url=metadata_url,\n                path=self._auth_config.metadata_path,\n                register_path=\"/oauth/register\" if self._auth_config.setup_fake_dynamic_registration else None,\n            )\n            setup_oauth_authorize_proxy(\n                app=self.fastapi,\n                client_id=self._auth_config.client_id,\n                authorize_url=self._auth_config.authorize_url,\n                audience=self._auth_config.audience,\n                default_scope=self._auth_config.default_scope,\n            )\n            if self._auth_config.setup_fake_dynamic_registration:\n                setup_oauth_fake_dynamic_register_endpoint(\n                    app=self.fastapi,\n                    client_id=self._auth_config.client_id,\n                    client_secret=self._auth_config.client_secret,\n                )\n```\n\n## Complete Example: Auth0 Integration\n\nThis example demonstrates a full OAuth authentication setup with Auth0.\n\n资料来源：[examples/09_auth_example_auth0.py:1-80]()\n\n```python\nfrom fastapi import FastAPI, Depends, HTTPException, Request, status\nfrom pydantic_settings import BaseSettings\nimport logging\n\nfrom fastapi_mcp import FastApiMCP, AuthConfig\nfrom examples.shared.auth import fetch_jwks_public_key\n\nsetup_logging()\nlogger = logging.getLogger(__name__)\n\nclass Settings(BaseSettings):\n    auth0_domain: str\n    auth0_audience: str\n    auth0_client_id: str\n    auth0_client_secret: str\n\n    @property\n    def auth0_oauth_metadata_url(self):\n        return f\"https://{self.auth0_domain}/.well-known/openid-configuration\"\n\n    class Config:\n        env_file = \".env\"\n\nsettings = Settings()\n\nasync def lifespan(app: FastAPI):\n    app.state.jwks_public_key = await fetch_jwks_public_key(\n        settings.auth0_jwks_url\n    )\n    logger.info(f\"Auth0 client ID: {settings.auth0_client_id}\")\n\napp = FastAPI(lifespan=lifespan)\n\nasync def verify_auth(request: Request):\n    \"\"\"Verify JWT token from Auth0.\"\"\"\n    # Token verification logic\n    pass\n\nmcp = FastApiMCP(\n    app,\n    name=\"MCP With Auth0\",\n    description=\"Example of FastAPI-MCP with Auth0 authentication\",\n    auth_config=AuthConfig(\n        issuer=f\"https://{settings.auth0_domain}/\",\n        authorize_url=f\"https://{settings.auth0_domain}/authorize\",\n        oauth_metadata_url=settings.auth0_oauth_metadata_url,\n        audience=settings.auth0_audience,\n        client_id=settings.auth0_client_id,\n        client_secret=settings.auth0_client_secret,\n        dependencies=[Depends(verify_auth)],\n        setup_proxies=True,\n    ),\n)\n\nmcp.mount_http()\n```\n\n## Token Passthrough Example\n\nFor simpler scenarios where you just need to verify bearer tokens:\n\n资料来源：[examples/08_auth_example_token_passthrough.py:1-60]()\n\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\n\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\ntoken_auth_scheme = HTTPBearer()\n\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)],\n    ),\n)\n\nmcp.mount_http()\n```\n\n## Environment Configuration\n\nFor Auth0, create a `.env` file:\n\n```bash\nAUTH0_DOMAIN=your-tenant.auth0.com\nAUTH0_AUDIENCE=https://your-tenant.auth0.com/api/v2/\nAUTH0_CLIENT_ID=your-client-id\nAUTH0_CLIENT_SECRET=your-client-secret\n```\n\n## MCP Client Configuration\n\nConfigure your MCP client to use OAuth authentication:\n\n```json\n{\n  \"mcpServers\": {\n    \"remote-example\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"mcp-remote\",\n        \"http://localhost:8000/mcp\",\n        \"--header\",\n        \"Authorization:${AUTH_HEADER}\"\n      ]\n    },\n    \"env\": {\n      \"AUTH_HEADER\": \"Bearer <your-token>\"\n    }\n  }\n}\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py:8-22]()\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue | Cause | Solution |\n|-------|-------|----------|\n| 401 on all requests | Auth dependencies always fail | Ensure token verification returns user info instead of raising 401 |\n| Metadata endpoint returns 502 | OAuth provider unreachable | Verify `oauth_metadata_url` is correct and accessible |\n| Client not triggering OAuth | Dependencies not raising 401 | Dependencies must raise HTTPException with 401 for OAuth flow |\n| Dynamic registration fails | Fake endpoint not enabled | Set `setup_fake_dynamic_registration=True` in AuthConfig |\n\n### Debug Logging\n\nEnable debug logging to trace authentication issues:\n\n```python\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\n---\n\n<a id='endpoint-filtering'></a>\n\n## Endpoint Filtering and Selection\n\n### 相关页面\n\n相关主题：[Quickstart Guide](#quickstart), [Tool Naming and Schema](#tool-naming)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [fastapi_mcp/openapi/convert.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/openapi/convert.py)\n- [CHANGELOG.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CHANGELOG.md)\n- [examples/README.md](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/README.md)\n</details>\n\n# Endpoint Filtering and Selection\n\nThe Endpoint Filtering and Selection feature in FastAPI-MCP provides granular control over which FastAPI endpoints are exposed as MCP tools. This allows developers to create specialized MCP servers that expose only a subset of their FastAPI API, enabling targeted integrations, improved security through principle of least privilege, and support for multi-tenant or use-case-specific MCP deployments.\n\n## Overview\n\nFastAPI-MCP automatically converts FastAPI endpoints into MCP tools by analyzing the OpenAPI schema. The filtering system operates on top of this conversion, enabling selective exposure of endpoints based on operation IDs and tags defined in the OpenAPI specification.\n\nThis feature was introduced to support:\n- **Multi-tenant deployments**: Different MCP servers for different client types\n- **Security isolation**: Limiting exposed functionality to minimize attack surface\n- **Use-case specificity**: Creating focused MCP servers for particular workflows\n- **Separate deployment**: Deploying MCP servers independently from the main API service\n\n资料来源：[CHANGELOG.md:5-11]()\n\n## Filter Parameters\n\nThe filtering is controlled through four mutually-exclusive parameters in the `FastApiMCP` constructor:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `include_operations` | `Optional[List[str]]` | List of operation IDs to include as MCP tools |\n| `exclude_operations` | `Optional[List[str]]` | List of operation IDs to exclude from MCP tools |\n| `include_tags` | `Optional[List[str]]` | List of tags to include as MCP tools |\n| `exclude_tags` | `Optional[List[str]]` | List of tags to exclude from MCP tools |\n\n资料来源：[fastapi_mcp/server.py:1-100](fastapi_mcp/server.py)\n\n### Parameter Validation Rules\n\nThe filtering system enforces several validation constraints to prevent ambiguous configurations:\n\n1. **Operation exclusion**: `include_operations` and `exclude_operations` cannot be used together\n2. **Tag exclusion**: `include_tags` and `exclude_tags` cannot be used together\n3. **Flexible combination**: Operation filtering can be combined with tag filtering using a greedy approach\n\nWhen combining filters in include mode, endpoints matching **either** the operation criteria **or** the tag criteria will be included in the MCP server.\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:1-30]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[FastAPI Application] --> B[OpenAPI Schema Generation]\n    B --> C[FastApiMCP Constructor]\n    C --> D{Filtering Parameters?}\n    D -->|No filters| E[All Tools Exposed]\n    D -->|With filters| F[_filter_tools Method]\n    \n    F --> G{include_operations?}\n    G -->|Yes| H[Filter by Operation IDs]\n    \n    F --> I{exclude_operations?}\n    I -->|Yes| J[Exclude by Operation IDs]\n    \n    F --> K{include_tags?}\n    K -->|Yes| L[Filter by Tags]\n    \n    F --> M{exclude_tags?}\n    M -->|Yes| N[Exclude by Tags]\n    \n    H --> O[Build Operations Map]\n    J --> O\n    L --> O\n    N --> O\n    O --> P[Filtered Tool List]\n    \n    P --> Q[MCP Server]\n    E --> Q\n```\n\n### Filter Logic Flow\n\n```mermaid\ngraph LR\n    A[Tools List] --> B{_include_operations<br/>is None?}\n    B -->|Yes| C{_exclude_operations<br/>is None?}\n    B -->|No| D[Keep only tools with<br/>matching operationId]\n    C -->|No| E[Remove tools with<br/>matching operationId]\n    C -->|Yes| F{_include_tags<br/>is None?}\n    D --> G[Operations By Tag Map]\n    E --> G\n    F -->|No| H[Keep tools with<br/>matching tags]\n    F -->|Yes| I{_exclude_tags<br/>is None?}\n    H --> J[Final Tool Set]\n    I -->|No| K[Remove tools with<br/>matching tags]\n    I -->|Yes| J\n    K --> J\n```\n\n## Implementation Details\n\n### The `_filter_tools` Method\n\nThe core filtering logic resides in the `_filter_tools` method within `fastapi_mcp/server.py`. This method:\n\n1. Returns the original tool list if no filters are configured\n2. Builds a mapping of tags to operation IDs from the OpenAPI schema\n3. Applies inclusion/exclusion logic based on operation IDs and tags\n4. Returns the filtered tool list\n\n```python\ndef _filter_tools(self, tools: List[types.Tool], openapi_schema: Dict[str, Any]) -> List[types.Tool]:\n    \"\"\"\n    Filter tools based on operation IDs and tags.\n    \"\"\"\n    if (\n        self._include_operations is None\n        and self._exclude_operations is None\n        and self._include_tags is None\n        and self._exclude_tags is None\n    ):\n        return tools\n\n    operations_by_tag: Dict[str, List[str]] = {}\n    for path, path_item in openapi_schema.get(\"paths\", {}).items():\n        for method, operation in path_item.items():\n            if method not in [\"get\", \"post\", \"put\", \"delete\", \"patch\"]:\n                continue\n            # ... filtering logic continues\n```\n\n资料来源：[fastapi_mcp/server.py:1-50]()\n\n### Parameter Organization in OpenAPI Conversion\n\nWhen endpoints are converted to MCP tools, parameters are organized into four categories:\n\n| Parameter Type | OpenAPI Location | Description |\n|----------------|------------------|-------------|\n| Path Parameters | `parameters[in=path]` | URL path variables |\n| Query Parameters | `parameters[in=query]` | Query string parameters |\n| Header Parameters | `parameters[in=header]` | HTTP header values |\n| Body Parameters | `requestBody` | Request body content |\n\n资料来源：[fastapi_mcp/openapi/convert.py:1-80]()\n\n## Usage Examples\n\n### Basic Operation ID Filtering\n\n```python\nfrom fastapi_mcp import FastApiMCP\n\n# Include only specific operations\ninclude_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Operations\",\n    include_operations=[\"get_item\", \"list_items\"],\n)\n\n# Exclude specific operations\nexclude_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Operations\",\n    exclude_operations=[\"create_item\", \"update_item\", \"delete_item\"],\n)\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:18-30]()\n\n### Tag-Based Filtering\n\n```python\n# Include only operations with specific tags\ninclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Tags\",\n    include_tags=[\"items\"],\n)\n\n# Exclude operations with specific tags\nexclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Tags\",\n    exclude_tags=[\"search\"],\n)\n```\n\n### Combined Filtering\n\n```python\n# Combine operation IDs and tags in include mode\ncombined_include_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Combined Include\",\n    include_operations=[\"delete_item\"],\n    include_tags=[\"search\"],\n)\n```\n\nWhen using combined include filters, the MCP server exposes endpoints that match **either** criteria—the operation ID filter **or** the tag filter. This greedy approach ensures comprehensive coverage of relevant endpoints.\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:55-65]()\n\n## Available Examples\n\nFastAPI-MCP provides a dedicated example demonstrating endpoint filtering capabilities:\n\n| Example | File | Description |\n|---------|------|-------------|\n| Custom Exposed Endpoints | `03_custom_exposed_endpoints_example.py` | Comprehensive filtering examples |\n\n资料来源：[examples/README.md:1-15]()\n\nTo run the example:\n\n```bash\ncd examples\nuv run python 03_custom_exposed_endpoints_example.py\n```\n\n## Mounting Filtered Servers\n\nAfter creating filtered MCP servers, mount them at different HTTP paths:\n\n```python\ninclude_operations_mcp.mount_http(mount_path=\"/include-operations-mcp\")\nexclude_operations_mcp.mount_http(mount_path=\"/exclude-operations-mcp\")\ninclude_tags_mcp.mount_http(mount_path=\"/include-tags-mcp\")\nexclude_tags_mcp.mount_http(mount_path=\"/exclude-tags-mcp\")\ncombined_include_mcp.mount_http(mount_path=\"/combined-include-mcp\")\n```\n\nThis allows clients to connect to specific filtered MCP servers based on their needs.\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:68-74]()\n\n## Best Practices\n\n1. **Use descriptive operation IDs**: Ensure your FastAPI endpoints have clear, consistent `operationId` values for easier filtering\n2. **Leverage tags for organization**: Group related endpoints with consistent tags to enable effective tag-based filtering\n3. **Principle of least privilege**: Only expose the minimum set of endpoints required for each MCP use case\n4. **Combine filters strategically**: Use combined include filters to create focused MCP servers that serve specific workflows\n5. **Test filtering combinations**: Verify that the greedy approach of combined filters produces the expected tool set\n\n---\n\n<a id='tool-naming'></a>\n\n## Tool Naming and Schema\n\n### 相关页面\n\n相关主题：[Endpoint Filtering and Selection](#endpoint-filtering), [System Architecture](#architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [fastapi_mcp/openapi/convert.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/openapi/convert.py)\n- [fastapi_mcp/openapi/utils.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/openapi/utils.py)\n- [examples/shared/apps/items.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/shared/apps/items.py)\n</details>\n\n# Tool Naming and Schema\n\nThis page documents how FastAPI-MCP derives MCP tool names, descriptions, and input schemas from FastAPI/OpenAPI endpoint definitions.\n\n## Overview\n\nWhen a FastAPI application is mounted as an MCP server, every route operation becomes an MCP tool. The conversion pipeline performs the following high-level steps:\n\n1. **Resolve** all `$ref` references in the OpenAPI schema\n2. **Extract** operation metadata (operationId, summary, description)\n3. **Classify** parameters by location (path, query, header)\n4. **Parse** request body schemas into tool input schemas\n5. **Generate** human-readable tool descriptions including example values\n6. **Build** the `types.Tool` objects returned to the MCP runtime\n\n资料来源：[fastapi_mcp/openapi/convert.py:21-45]()\n\n```mermaid\ngraph TD\n    A[OpenAPI Schema] --> B[resolve_schema_references]\n    B --> C[Iterate paths]\n    C --> D[Extract operationId]\n    D --> E[Classify Parameters]\n    E --> F[Parse Request Body]\n    F --> G[Build Tool Description]\n    G --> H[types.Tool]\n```\n\n## Tool Naming\n\nTool names are derived directly from the `operationId` field in the OpenAPI operation object. The function `convert_openapi_to_mcp_tools` skips any operation that lacks an `operationId`:\n\n```python\noperation_id = operation.get(\"operationId\")\nif not operation_id:\n    logger.warning(f\"Skipping non-HTTP method: {method}\")\n    continue\n```\n\n资料来源：[fastapi_mcp/openapi/convert.py:56-62]()\n\nThe resulting tool names are exactly the `operationId` strings, without any namespace prefix. For example, given a FastAPI route:\n\n```python\n@app.get(\"/items/{item_id}\", response_model=Item, operation_id=\"get_item\")\nasync def get_item(item_id: int):\n    ...\n```\n\nThe MCP tool will be named `get_item`.\n\n## Schema Resolution\n\nBefore any schema processing occurs, all JSON Pointer references (`$ref`) are resolved upfront by calling `resolve_schema_references`:\n\n```python\nresolved_openapi_schema = resolve_schema_references(openapi_schema, openapi_schema)\n```\n\nThis single-pass resolution replaces all `$ref` values with their referenced definitions, ensuring that downstream code works with concrete schemas rather than indirection.\n\n资料来源：[fastapi_mcp/openapi/convert.py:50-53]()\n\n## Parameter Classification\n\nParameters are classified by their `in` field into four groups:\n\n| Group | `in` value | Description |\n|-------|------------|-------------|\n| Path parameters | `\"path\"` | Required URL segment parameters |\n| Query parameters | `\"query\"` | Optional query string parameters |\n| Header parameters | `\"header\"` | HTTP header parameters |\n| Body parameters | `\"requestBody\"` | JSON request body (handled separately) |\n\nThe classification code:\n\n```python\nfor param in operation.get(\"parameters\", []):\n    param_name = param.get(\"name\")\n    param_in = param.get(\"in\")\n    required = param.get(\"required\", False)\n\n    if param_in == \"path\":\n        path_params.append((param_name, param))\n    elif param_in == \"query\":\n        query_params.append((param_name, param))\n    elif param_in == \"header\":\n        header_params.append((param_name, param))\n```\n\n资料来源：[fastapi_mcp/openapi/convert.py:79-93]()\n\n## Example Generation\n\nThe utility `generate_example_from_schema` produces human-readable example values for each schema type to include in tool descriptions. The function handles the following OpenAPI types:\n\n| OpenAPI Type | Generated Example |\n|--------------|-------------------|\n| `string` (no format) | `\"string\"` or the `title` field value |\n| `string` with `format: date-time` | `\"2023-01-01T00:00:00Z\"` |\n| `string` with `format: date` | `\"2023-01-01\"` |\n| `string` with `format: email` | `\"user@example.com\"` |\n| `string` with `format: uri` | `\"https://example.com\"` |\n| `integer` | `1` |\n| `number` | `1.0` |\n| `boolean` | `true` |\n| `array` | A single-item array with an example of the `items` type |\n| `object` | A dict with one example per `properties` entry |\n| `null` | `null` |\n\n资料来源：[fastapi_mcp/openapi/utils.py:45-70]()\n\n### Object Schema Example\n\n```python\nelif schema_type == \"object\":\n    result = {}\n    if \"properties\" in schema:\n        for prop_name, prop_schema in schema[\"properties\"].items():\n            prop_example = generate_example_from_schema(prop_schema)\n            if prop_example is not None:\n                result[prop_name] = prop_example\n    return result\n```\n\n### Array Schema Example\n\n```python\nelif schema_type == \"array\":\n    if \"items\" in schema:\n        item_example = generate_example_from_schema(schema[\"items\"])\n        if item_example is not None:\n            return [item_example]\n    return []\n```\n\n## Tool Description Building\n\nThe `convert_openapi_to_mcp_tools` function constructs a human-readable `description` field for each tool by concatenating:\n\n1. The operation's `summary` and `description` fields from OpenAPI\n2. Parameter documentation with names, types, required status, and descriptions\n3. Request body schema details (if present)\n4. Output schema with example values\n\n```python\ntool_description += response_info\n```\n\nThe response information is only included when the `describe_all_responses` or `describe_full_response_schema` flags are set. The description includes:\n- The HTTP method and path\n- Parameter documentation grouped by type\n- Request body schema examples\n- Output schema examples for both array and object responses\n\n## Output Schema Handling\n\nResponse schemas are processed to produce two display formats:\n\n1. **Array responses**: The `items` schema is extracted and shown as an array of items with the item structure\n2. **Object responses**: The full `properties` schema is displayed\n\n```python\nif items_schema := schema.get(\"items\", {}).get(\"properties\"):\n    response_info += \"\\n\\n**Output Schema:** Array of items with the following structure:\\n```json\\n\"\n    response_info += json.dumps(items_schema, indent=2)\nelif \"properties\" in display_schema:\n    response_info += \"\\n\\n**Output Schema:**\\n```json\\n\"\n    response_info += json.dumps(display_schema, indent=2)\n```\n\n## Supported HTTP Methods\n\nOnly standard HTTP methods are converted to tools:\n\n```python\nif method not in [\"get\", \"post\", \"put\", \"delete\", \"patch\"]:\n    logger.warning(f\"Skipping non-HTTP method: {method}\")\n    continue\n```\n\n| Method | Supported |\n|--------|-----------|\n| GET | Yes |\n| POST | Yes |\n| PUT | Yes |\n| DELETE | Yes |\n| PATCH | Yes |\n| HEAD, OPTIONS, etc. | No (logged and skipped) |\n\n## Related Utilities\n\n| Function | File | Purpose |\n|----------|------|---------|\n| `resolve_schema_references` | `openapi/utils.py` | Resolves all `$ref` pointers in the schema |\n| `generate_example_from_schema` | `openapi/utils.py` | Creates example values for tool descriptions |\n| `clean_schema_for_display` | `openapi/utils.py` | Sanitizes schema for display |\n| `get_single_param_type_from_schema` | `openapi/utils.py` | Extracts parameter type from schema |\n| `convert_openapi_to_mcp_tools` | `openapi/convert.py` | Main conversion function |\n\n---\n\n<a id='transport-config'></a>\n\n## Transport Configuration\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture), [Deployment Options](#deployment)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n- [examples/01_basic_usage_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/01_basic_usage_example.py)\n- [examples/07_configure_http_timeout_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/07_configure_http_timeout_example.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n</details>\n\n# Transport Configuration\n\nFastAPI-MCP supports multiple transport mechanisms for exposing MCP (Model Context Protocol) servers. This document covers the available transport options, configuration parameters, and how to customize transport behavior for different deployment scenarios.\n\n## Overview\n\nFastAPI-MCP provides two primary transport mechanisms:\n\n| Transport Type | Method | Description |\n|----------------|--------|-------------|\n| HTTP | `mount_http()` | Standard HTTP transport for MCP communication |\n| SSE | `mount_sse()` | Server-Sent Events transport for streaming responses |\n| Legacy | `mount()` | Deprecated combined method (use `mount_http()` or `mount_sse()` instead) |\n\n资料来源：[fastapi_mcp/server.py:1-200]()\n\n## Transport Architecture\n\n```mermaid\ngraph TD\n    A[FastAPI Application] --> B[FastApiMCP Server]\n    B --> C[mount_http]\n    B --> D[mount_sse]\n    C --> E[HTTP Transport]\n    D --> F[SSE Transport]\n    E --> G[httpx.AsyncClient]\n    F --> H[FastApiSseTransport]\n    G --> I[ASGI Transport]\n    H --> I\n```\n\n## HTTP Transport Configuration\n\nThe HTTP transport is the recommended method for MCP communication. It uses an `httpx.AsyncClient` internally with ASGI transport.\n\n### Basic HTTP Mounting\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_mcp import FastApiMCP\n\napp = FastAPI()\nmcp = FastApiMCP(app)\nmcp.mount_http()\n```\n\n资料来源：[examples/01_basic_usage_example.py:1-15]()\n\n### HTTP Client Configuration\n\nThe `FastApiMCP` class accepts an optional `http_client` parameter for custom HTTP client configuration:\n\n```python\nimport httpx\nfrom fastapi_mcp import FastApiMCP\n\n# Custom HTTP client with specific timeout\ncustom_client = httpx.AsyncClient(\n    timeout=30.0\n)\n\nmcp = FastApiMCP(\n    app,\n    http_client=custom_client\n)\n```\n\n### Default Timeout Behavior\n\nWhen no custom client is provided, FastAPI-MCP creates an internal HTTP client with a default timeout of 10.0 seconds:\n\n```python\nself._http_client = http_client or httpx.AsyncClient(\n    transport=httpx.ASGITransport(app=self.fastapi, raise_app_exceptions=False),\n    base_url=self._base_url,\n    timeout=10.0,\n)\n```\n\n资料来源：[fastapi_mcp/server.py:1-100]()\n\n### Configuring Custom Timeouts\n\nFor long-running API operations, you can configure custom timeout values:\n\n```python\nimport httpx\nfrom fastapi_mcp import FastApiMCP\n\n# Create client with extended timeout\nclient = httpx.AsyncClient(timeout=httpx.Timeout(60.0))\n\nmcp = FastApiMCP(\n    app,\n    name=\"Extended Timeout MCP\",\n    http_client=client,\n)\n```\n\n资料来源：[examples/07_configure_http_timeout_example.py]()\n\n## SSE Transport Configuration\n\nThe SSE (Server-Send Events) transport provides streaming capabilities for MCP communication.\n\n### Basic SSE Mounting\n\n```python\nfrom fastapi_mcp import FastApiMCP\n\nmcp = FastApiMCP(app)\nmcp.mount_sse(router, mount_path=\"/sse\")\n```\n\n资料来源：[fastapi_mcp/server.py:1-200]()\n\n### SSE Endpoint Registration\n\nThe SSE transport registers two endpoints:\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `{mount_path}` | GET | SSE connection establishment |\n| `{mount_path}/messages/` | POST | Message handling |\n\n```python\ndef _register_mcp_connection_endpoint_sse(\n    self,\n    router: FastAPI | APIRouter,\n    transport: FastApiSseTransport,\n    mount_path: str,\n    dependencies: Optional[Sequence[params.Depends]],\n):\n    @router.get(mount_path, include_in_schema=False, operation_id=\"mcp_connection\", dependencies=dependencies)\n    async def handle_mcp_connection(request: Request):\n        async with transport.connect_sse(request.scope, request.receive, request._send) as (reader, writer):\n            await self.server.run(\n                reader,\n                writer,\n                self.server.create_initialization_options(notification_options=None, experimental_capabilities={}),\n                raise_exceptions=False,\n            )\n```\n\n资料来源：[fastapi_mcp/server.py:100-200]()\n\n## Header Forwarding Configuration\n\nFastAPI-MCP allows forwarding specific HTTP headers from incoming MCP requests to tool invocations.\n\n### Default Header Forwarding\n\nBy default, only the `authorization` header is forwarded:\n\n```python\nheaders: Annotated[\n    List[str],\n    Doc(\n        \"\"\"\n        List of HTTP header names to forward from the incoming MCP request into each tool invocation.\n        Only headers in this allowlist will be forwarded. Defaults to ['authorization'].\n        \"\"\"\n    ),\n] = [\"authorization\"],\n```\n\n资料来源：[fastapi_mcp/server.py:1-100]()\n\n### Custom Header Forwarding\n\n```python\nfrom fastapi_mcp import FastApiMCP\n\n# Forward multiple headers\nmcp = FastApiMCP(\n    app,\n    headers=[\"authorization\", \"x-api-key\", \"x-request-id\"],\n)\n```\n\n### Token Passthrough Example\n\nFor authenticated APIs, headers can be forwarded to maintain authentication:\n\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\ntoken_auth_scheme = HTTPBearer()\n\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\nmcp = FastApiMCP(\n    app,\n    name=\"Protected MCP\",\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)],\n    ),\n    headers=[\"authorization\"],  # Forward the auth header\n)\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py:1-50]()\n\n## Authentication Configuration\n\nThe `AuthConfig` class provides OAuth and authentication support:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `version` | Literal[\"2025-03-26\"] | MCP spec version for authorization |\n| `dependencies` | Optional[Sequence[params.Depends]] | FastAPI dependencies for auth checks |\n| `issuer` | Optional[str] | OAuth 2.0 issuer URL |\n| `oauth_metadata_url` | Optional[StrHttpUrl] | Full URL of OAuth metadata endpoint |\n| `authorize_url` | Optional[StrHttpUrl] | Authorization endpoint URL |\n\n资料来源：[fastapi_mcp/types.py:1-100]()\n\n### OAuth Configuration Example\n\n```python\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\nmcp = FastApiMCP(\n    app,\n    auth_config=AuthConfig(\n        version=\"2025-03-26\",\n        issuer=\"https://your-tenant.auth0.com\",\n        dependencies=[Depends(authenticate_request)],\n    ),\n)\n```\n\n## Tool Filtering by Transport\n\nWhen mounting the MCP server, you can filter which operations are exposed:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `include_operations` | Optional[List[str]] | Operation IDs to include |\n| `exclude_operations` | Optional[List[str]] | Operation IDs to exclude |\n| `include_tags` | Optional[List[str]] | Tags to include |\n| `exclude_tags` | Optional[List[str]] | Tags to exclude |\n\n```python\n# Include specific operations only\nmcp = FastApiMCP(\n    app,\n    name=\"Filtered MCP\",\n    include_operations=[\"get_item\", \"list_items\"],\n)\n\n# Exclude specific operations\nmcp = FastApiMCP(\n    app,\n    name=\"Filtered MCP\",\n    exclude_operations=[\"delete_item\", \"update_item\"],\n)\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py]()\n\n## Deprecation Notice\n\nThe legacy `mount()` method is deprecated and will be removed in a future version:\n\n```python\n# DEPRECATED - Do not use\nmcp.mount(router, mount_path, transport=\"sse\")\n\n# RECOMMENDED - Use these instead\nmcp.mount_http()\nmcp.mount_sse(router, mount_path)\n```\n\n资料来源：[fastapi_mcp/server.py:1-100]()\n\n## Complete Configuration Example\n\n```python\nimport httpx\nfrom fastapi import FastAPI, Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\napp = FastAPI()\ntoken_auth_scheme = HTTPBearer()\n\n# Custom authentication dependency\nasync def authenticate_request(request: Request, token: str = Depends(token_auth_scheme)):\n    payload = verify_token(request, token)\n    if payload is None:\n        raise HTTPException(status_code=401, detail=\"Unauthorized\")\n    return payload\n\n# Configure MCP with all transport options\nmcp = FastApiMCP(\n    app,\n    name=\"Complete Example MCP\",\n    describe_all_responses=True,\n    describe_full_response_schema=True,\n    http_client=httpx.AsyncClient(timeout=30.0),\n    include_tags=[\"items\", \"search\"],\n    auth_config=AuthConfig(\n        dependencies=[Depends(authenticate_request)],\n    ),\n    headers=[\"authorization\", \"x-api-key\"],\n)\n\n# Mount with HTTP transport\nmcp.mount_http()\n```\n\n## Summary\n\nFastAPI-MCP provides flexible transport configuration options:\n\n- **HTTP Transport**: Default transport using httpx.AsyncClient with configurable timeouts\n- **SSE Transport**: Server-Sent Events for streaming scenarios\n- **Header Forwarding**: Customizable header allowlist for request passthrough\n- **Authentication**: OAuth and dependency-based authentication support\n- **Tool Filtering**: Operation ID and tag-based filtering for exposed endpoints\n\nChoose the appropriate transport based on your deployment requirements, with HTTP being the recommended default for most use cases.\n\n---\n\n<a id='deployment'></a>\n\n## Deployment Options\n\n### 相关页面\n\n相关主题：[Transport Configuration](#transport-config), [Dynamic Tool Registration](#dynamic-registration), [Examples Overview](#examples)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [examples/04_separate_server_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/04_separate_server_example.py)\n- [examples/06_custom_mcp_router_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/06_custom_mcp_router_example.py)\n- [examples/08_auth_example_token_passthrough.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/08_auth_example_token_passthrough.py)\n- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)\n- [CHANGELOG.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CHANGELOG.md)\n</details>\n\n# Deployment Options\n\nFastAPI-MCP provides multiple deployment options for integrating MCP (Model Context Protocol) servers with FastAPI applications. These options allow developers to mount MCP servers using different transports (HTTP and SSE), deploy them separately from the main API service, or integrate them with custom APIRouter configurations.\n\n## Overview\n\nFastAPI-MCP supports three primary deployment patterns:\n\n| Deployment Mode | Transport | Description | Use Case |\n|-----------------|-----------|-------------|----------|\n| Integrated (HTTP) | HTTP | MCP server mounted directly into the FastAPI app | Default option, simple deployment |\n| Integrated (SSE) | Server-Sent Events | MCP server using SSE transport | Legacy support, browser compatibility |\n| Separate Server | HTTP | MCP server running as standalone service | Microservices architecture, independent scaling |\n\n资料来源：[fastapi_mcp/server.py:1-50]()\n\n## Transport Types\n\n### HTTP Transport\n\nHTTP transport is the **recommended** deployment option for FastAPI-MCP. It provides a FastAPI-native approach that integrates seamlessly with the existing FastAPI ecosystem.\n\n**Key characteristics:**\n- Uses `httpx.AsyncClient` for making HTTP requests\n- Supports streaming responses\n- Compatible with all major MCP clients\n- Better performance compared to SSE\n\n资料来源：[fastapi_mcp/server.py:85-120]()\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|HTTP Request| B[FastAPI App /mcp]\n    B --> C[FastApiMCP Server]\n    C -->|Tool Call| D[FastAPI Endpoints]\n    D -->|Response| C\n    C -->|MCP Response| A\n```\n\n### SSE Transport\n\nServer-Sent Events (SSE) transport is provided for legacy compatibility and specific use cases requiring browser-based connections.\n\n**Key characteristics:**\n- Bidirectional communication via SSE streams\n- Requires specific endpoint registration\n- Uses `FastApiSseTransport` class\n\n资料来源：[fastapi_mcp/server.py:150-200]()\n\n## Mounting Methods\n\n### Basic HTTP Mount\n\nThe simplest deployment option mounts the MCP server directly to the root FastAPI application using HTTP transport.\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_mcp import FastApiMCP\n\napp = FastAPI(__name__)\nmcp = FastApiMCP(app, name=\"My MCP Server\")\n\n# Mount with HTTP transport (default)\nmcp.mount_http()\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py:40-48]()\n\n### Custom Router Mount\n\nDeploy the MCP server to a specific `APIRouter` instead of the root application. This is useful for organizing endpoints under a specific path prefix.\n\n```python\nfrom fastapi import FastAPI, APIRouter\nfrom fastapi_mcp import FastApiMCP\n\napp = FastAPI(__name__)\n\n# Create a custom router with a prefix\nother_router = APIRouter(prefix=\"/other/route\")\napp.include_router(other_router)\n\nmcp = FastApiMCP(app)\n\n# Mount to the custom router\n# MCP will be available at /other/route/mcp\nmcp.mount_http(other_router)\n```\n\n资料来源：[examples/06_custom_mcp_router_example.py:1-28]()\n\n### SSE Mount\n\nFor SSE transport, the server provides dedicated mounting methods:\n\n```python\nmcp.mount_sse(router=app, mount_path=\"/mcp\")\n```\n\nThe SSE transport registers two endpoints:\n- `GET /mcp` - Connection endpoint\n- `POST /mcp/messages/` - Message handling endpoint\n\n资料来源：[fastapi_mcp/server.py:200-250]()\n\n## Separate Server Deployment\n\nFastAPI-MCP supports deploying MCP servers as separate, standalone services. This is particularly useful in microservices architectures where the MCP server and API service need independent scaling and deployment.\n\n### Architecture\n\n```mermaid\ngraph LR\n    subgraph \"API Service\"\n        A[FastAPI App] --> B[API Endpoints]\n    end\n    \n    subgraph \"MCP Server\"\n        C[MCP Server] --> D[Tool Definitions]\n        D --> E[HTTP Client]\n        E -->|Forward Requests| B\n    end\n    \n    F[MCP Client] --> C\n```\n\n### Configuration\n\nWhen deploying separately, the MCP server configuration specifies the remote server URL:\n\n```json\n{\n  \"mcpServers\": {\n    \"remote-example\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"mcp-remote\",\n        \"http://localhost:8000/mcp\"\n      ]\n    }\n  }\n}\n```\n\n### Implementation\n\nTo enable separate server deployment:\n\n1. Configure the API service to run normally\n2. Mount the MCP server with appropriate transport\n3. Configure the remote MCP client to connect to the API service\n\n资料来源：[examples/04_separate_server_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/04_separate_server_example.py)\n\n### Advantages\n\n| Benefit | Description |\n|---------|-------------|\n| Independent Scaling | Scale MCP server and API separately based on load |\n| Independent Deployment | Deploy updates without coordinating both services |\n| Resource Isolation | Different resource allocation for each service |\n| Network Flexibility | Services can run on different hosts/ports |\n\n## Endpoint Filtering\n\nWhen deploying MCP servers, you can control which FastAPI endpoints are exposed as MCP tools using operation IDs and tags.\n\n### Filter by Operation IDs\n\n```python\n# Include only specific operations\nmcp = FastApiMCP(\n    app,\n    include_operations=[\"get_item\", \"list_items\"]\n)\n\n# Exclude specific operations\nmcp = FastApiMCP(\n    app,\n    exclude_operations=[\"create_item\", \"update_item\", \"delete_item\"]\n)\n```\n\n### Filter by Tags\n\n```python\n# Include only operations with specific tags\nmcp = FastApiMCP(\n    app,\n    include_tags=[\"items\"]\n)\n\n# Exclude operations with specific tags\nmcp = FastApiMCP(\n    app,\n    exclude_tags=[\"search\"]\n)\n```\n\n### Combining Filters\n\nOperation and tag filters can be combined. When combining filters, a greedy approach is taken—endpoints matching **either** criteria will be included.\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:1-50]()\n\n## Authentication Integration\n\nFastAPI-MCP integrates with FastAPI's dependency injection system for authentication. When mounting the MCP server, you can configure authentication that will be applied to all MCP tool executions.\n\n### Token Passthrough\n\n```python\nfrom fastapi import Depends\nfrom fastapi.security import HTTPBearer\nfrom fastapi_mcp import FastApiMCP, AuthConfig\n\ntoken_auth_scheme = HTTPBearer()\n\n@app.get(\"/private\")\nasync def private(token=Depends(token_auth_scheme)):\n    return token.credentials\n\nmcp = FastApiMCP(\n    app,\n    auth_config=AuthConfig(\n        dependencies=[Depends(token_auth_scheme)],\n    ),\n)\n\nmcp.mount_http()\n```\n\n资料来源：[examples/08_auth_example_token_passthrough.py:1-55]()\n\n### Auth Configuration Options\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `dependencies` | `List[Depends]` | FastAPI dependencies for authentication |\n| `issuer` | `str` | OAuth 2.0 issuer URL |\n| `oauth_metadata_url` | `StrHttpUrl` | Full OAuth metadata endpoint URL |\n| `authorize_url` | `StrHttpUrl` | OAuth authorization endpoint URL |\n\n## Running the Server\n\n### Development Mode\n\n```bash\nuvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\n### With uv\n\n```bash\n# Install dependencies\nuv sync\n\n# Run the server\nuv run uvicorn main:app --host 0.0.0.0 --port 8000\n```\n\n资料来源：[CONTRIBUTING.md:1-80]()\n\n## Migration from Deprecated `mount()`\n\nThe `mount()` method is deprecated. Use the specific transport methods instead:\n\n| Deprecated | Replacement |\n|------------|-------------|\n| `mount(transport=\"sse\")` | `mount_sse()` |\n| `mount(transport=\"http\")` | `mount_http()` |\n\n```python\n# Old (deprecated)\nmcp.mount(app, \"/mcp\", transport=\"sse\")\n\n# New (recommended)\nmcp.mount_sse(app, \"/mcp\")\n```\n\n资料来源：[CHANGELOG.md:1-50]()\n\n## Summary\n\nFastAPI-MCP provides flexible deployment options to accommodate various architectural requirements:\n\n- **HTTP Transport**: Recommended for most use cases, provides best performance\n- **SSE Transport**: Legacy support for browser-compatible deployments\n- **Separate Server**: Ideal for microservices architectures\n- **Custom Router**: Organize MCP endpoints under specific paths\n- **Endpoint Filtering**: Control which tools are exposed to MCP clients\n- **Auth Integration**: Leverage existing FastAPI authentication\n\n---\n\n<a id='dynamic-registration'></a>\n\n## Dynamic Tool Registration\n\n### 相关页面\n\n相关主题：[Deployment Options](#deployment), [Endpoint Filtering and Selection](#endpoint-filtering)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [examples/05_reregister_tools_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/05_reregister_tools_example.py)\n- [fastapi_mcp/server.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/server.py)\n- [examples/03_custom_exposed_endpoints_example.py](https://github.com/tadata-org/fastapi_mcp/blob/main/examples/03_custom_exposed_endpoints_example.py)\n- [fastapi_mcp/types.py](https://github.com/tadata-org/fastapi_mcp/blob/main/fastapi_mcp/types.py)\n- [CHANGELOG.md](https://github.com/tadata-org/fastapi_mcp/blob/main/CHANGELOG.md)\n</details>\n\n# Dynamic Tool Registration\n\nDynamic Tool Registration is a core feature of FastAPI-MCP that enables runtime filtering, registration, and management of MCP tools derived from FastAPI endpoints. This capability allows developers to create multiple MCP server instances with different tool subsets from a single FastAPI application, providing fine-grained control over which tools are exposed to MCP clients.\n\n## Overview\n\nFastAPI-MCP automatically converts FastAPI endpoints into MCP tools by analyzing the OpenAPI schema. Dynamic Tool Registration extends this capability by allowing selective exposure of tools based on operation IDs and tags, enabling scenarios such as:\n\n- Creating multiple specialized MCP servers from one FastAPI app\n- Protecting sensitive endpoints by excluding them from MCP exposure\n- Creating tenant-specific or role-based tool visibility\n- Supporting incremental updates to tool availability\n\nThe feature is implemented through the `FastApiMCP` class constructor parameters that control which operations are registered as MCP tools.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[FastAPI Application] --> B[OpenAPI Schema Analysis]\n    B --> C[All Discovered Endpoints]\n    C --> D{Filter Criteria}\n    D -->|include_operations| E[Whitelist Mode]\n    D -->|exclude_operations| F[Blacklist Mode]\n    D -->|include_tags| G[Tag Filter - Include]\n    D -->|exclude_tags| H[Tag Filter - Exclude]\n    E --> I[Filtered Tool Set]\n    F --> I\n    G --> I\n    H --> I\n    I --> J[MCP Server Instance]\n```\n\n## Core Filter Parameters\n\nThe `FastApiMCP` class accepts four mutually-exclusive filter parameters:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `include_operations` | `Optional[List[str]]` | List of operation IDs to **include** as MCP tools |\n| `exclude_operations` | `Optional[List[str]]` | List of operation IDs to **exclude** from MCP tools |\n| `include_tags` | `Optional[List[str]]` | List of tags to **include** as MCP tools |\n| `exclude_tags` | `Optional[List[str]]` | List of tags to **exclude** from MCP tools |\n\n资料来源：[fastapi_mcp/server.py:1-100]()\n\n### Mutual Exclusivity Rules\n\nThe filtering parameters follow strict mutual exclusivity rules:\n\n1. **Operation filters**: Cannot use `include_operations` and `exclude_operations` together\n2. **Tag filters**: Cannot use `include_tags` and `exclude_tags` together\n3. **Cross-type combination**: Can combine operation filters with tag filters (greedy approach)\n\nWhen combining filters, a greedy union strategy is applied: endpoints matching **either** the operation criteria **or** the tag criteria will be included.\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:1-30]()\n\n## Filter Implementation\n\nThe filtering logic is implemented in the `_filter_tools` method of the `FastApiMCP` class:\n\n```python\ndef _filter_tools(self, tools: List[types.Tool], openapi_schema: Dict[str, Any]) -> List[types.Tool]:\n    \"\"\"\n    Filter tools based on operation IDs and tags.\n\n    Args:\n        tools: List of tools to filter\n        openapi_schema: The OpenAPI schema\n\n    Returns:\n        Filtered list of tools\n    \"\"\"\n    if (\n        self._include_operations is None\n        and self._exclude_operations is None\n        and self._include_tags is None\n        and self._exclude_tags is None\n    ):\n        return tools\n```\n\n资料来源：[fastapi_mcp/server.py:85-105]()\n\n### Operation ID Mapping\n\nThe filtering mechanism builds an operations map indexed by both operation ID and tags:\n\n```python\noperations_by_tag: Dict[str, List[str]] = {}\nfor path, path_item in openapi_schema.get(\"paths\", {}).items():\n    for method, operation in path_item.items():\n        if method not in [\"get\", \"post\", \"put\", \"delete\", \"patch\"]:\n            continue\n\n        operation_id = operation.get(\"operationId\")\n        if not operation_id:\n            continue\n\n        tags = operation.get(\"tags\", [])\n        for tag in tags:\n            if tag not in operations_by_tag:\n                operations_by_tag[tag] = []\n            operations_by_tag[tag].append(operation_id)\n```\n\n资料来源：[fastapi_mcp/server.py:107-125]()\n\n## Usage Patterns\n\n### Include Specific Operations\n\nCreate an MCP server exposing only specified operation IDs:\n\n```python\ninclude_operations_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Operations\",\n    include_operations=[\"get_item\", \"list_items\"],\n)\ninclude_operations_mcp.mount_http(mount_path=\"/include-operations-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:20-26]()\n\n### Exclude Specific Operations\n\nCreate an MCP server with all operations except specified ones:\n\n```python\nexclude_operations_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Operations\",\n    exclude_operations=[\"create_item\", \"update_item\", \"delete_item\"],\n)\nexclude_operations_mcp.mount_http(mount_path=\"/exclude-operations-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:28-34]()\n\n### Tag-Based Inclusion\n\nFilter tools by including endpoints with specific OpenAPI tags:\n\n```python\ninclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Included Tags\",\n    include_tags=[\"items\"],\n)\ninclude_tags_mcp.mount_http(mount_path=\"/include-tags-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:36-41]()\n\n### Tag-Based Exclusion\n\nExclude all endpoints with specific tags:\n\n```python\nexclude_tags_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Excluded Tags\",\n    exclude_tags=[\"search\"],\n)\nexclude_tags_mcp.mount_http(mount_path=\"/exclude-tags-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:43-48]()\n\n### Combined Filtering\n\nCombine operation ID and tag filters for complex scenarios:\n\n```python\ncombined_include_mcp = FastApiMCP(\n    app,\n    name=\"Item API MCP - Combined Include\",\n    include_operations=[\"delete_item\"],\n    include_tags=[\"search\"],\n)\ncombined_include_mcp.mount_http(mount_path=\"/combined-include-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:50-57]()\n\n## Re-registering Tools\n\nThe library supports re-registering tools at runtime through multiple `FastApiMCP` instances mounted on different paths:\n\n```python\n# Mount all MCP servers with different paths\ninclude_operations_mcp.mount_http(mount_path=\"/include-operations-mcp\")\nexclude_operations_mcp.mount_http(mount_path=\"/exclude-operations-mcp\")\ninclude_tags_mcp.mount_http(mount_path=\"/include-tags-mcp\")\nexclude_tags_mcp.mount_http(mount_path=\"/exclude-tags-mcp\")\ncombined_include_mcp.mount_http(mount_path=\"/combined-include-mcp\")\n```\n\n资料来源：[examples/03_custom_exposed_endpoints_example.py:62-68]()\n\nEach mounted instance operates independently, allowing different clients to access different tool sets from the same underlying FastAPI application.\n\n## Custom Tools Integration\n\nBeyond API-derived tools, FastAPI-MCP supports adding custom MCP tools alongside auto-generated ones:\n\n### Added\n- Main `add_mcp_server` function for simple MCP server integration\n- Support for adding custom MCP tools alongside API-derived tools\n\n资料来源：[CHANGELOG.md:1-20]()\n\nThis enables scenarios where developers need to add supplementary tools that don't correspond to FastAPI endpoints, such as helper utilities or integration points with external services.\n\n## HTTP Client Configuration\n\nThe tool registration system includes support for custom HTTP client configuration:\n\n```python\nhttp_client: Annotated[\n    Optional[httpx.AsyncClient],\n    Doc(\n        \"\"\"\n        Optional custom HTTP client to use for API calls to the FastAPI app.\n        Has to be an instance of `httpx.AsyncClient`.\n        \"\"\"\n    ),\n] = None,\n```\n\n资料来源：[fastapi_mcp/server.py:50-58]()\n\nThis allows fine-grained control over the HTTP client used to invoke tools, enabling custom timeouts, authentication, or proxy configuration.\n\n## Header Passthrough\n\nThe system supports forwarding specific HTTP headers from MCP requests to tool invocations:\n\n```python\nheaders: Annotated[\n    List[str],\n    Doc(\n        \"\"\"\n        List of HTTP header names to forward from the incoming MCP request \n        into each tool invocation. Only headers in this allowlist will be \n        forwarded. Defaults to ['authorization'].\n        \"\"\"\n    ),\n] = [\"authorization\"],\n```\n\n资料来源：[fastapi_mcp/server.py:85-93]()\n\nThis is particularly important for maintaining authentication context when tools are invoked through the MCP protocol.\n\n## Summary\n\nDynamic Tool Registration in FastAPI-MCP provides a flexible mechanism for controlling which FastAPI endpoints become MCP tools. By supporting operation ID filtering, tag-based filtering, and their combinations, developers can:\n\n- Create specialized MCP servers for different use cases\n- Implement fine-grained access control\n- Support multi-tenant or role-based tool visibility\n- Combine auto-generated and custom tools in a single MCP server\n\nThe implementation uses a greedy union strategy when combining filters, ensuring maximum flexibility while maintaining predictable behavior. All filtering occurs at registration time, ensuring optimal runtime performance for tool invocation.\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：tadata-org/fastapi_mcp\n\n摘要：发现 22 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：配置坑 - 来源证据：[BUG] MCP session 404 in multi worker production environment。\n\n## 1. 配置坑 · 来源证据：[BUG] MCP session 404 in multi worker production environment\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[BUG] MCP session 404 in multi worker production environment\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f318cbe8fc55407da8cb88f5418cce0d | https://github.com/tadata-org/fastapi_mcp/issues/189 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：v0.1.8\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.1.8\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_11a827f3808141e4bd7b0541a8628af0 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.1.8 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 3. 安装坑 · 来源证据：v0.2.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.2.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a145fff6c53f4e709ef1bb7bc291216c | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.2.0 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 4. 安装坑 · 来源证据：v0.3.4\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.3.4\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_6dcb58f1897f46a188514e2714e5896d | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.4 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 5. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | host_targets=mcp_host, claude, cursor\n\n## 6. 配置坑 · 来源证据：Suggestion: MCPWatch observability example for fastapi_mcp users\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Suggestion: MCPWatch observability example for fastapi_mcp users\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_dfa72f41f3094dd5b2ffe188889f2b4f | https://github.com/tadata-org/fastapi_mcp/issues/303 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 7. 配置坑 · 来源证据：clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_74e4280da33d49e1a3a8d576c7bb78a6 | https://github.com/tadata-org/fastapi_mcp/issues/304 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 8. 配置坑 · 来源证据：v0.3.6\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：v0.3.6\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_bdc90006d16a437798ff2766d514f3d4 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.6 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 9. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | README/documentation is current enough for a first validation pass.\n\n## 10. 维护坑 · 来源证据：[BUG] Description incorrectly passed as version to MCP Server\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[BUG] Description incorrectly passed as version to MCP Server\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2e599a8b03d649d8a47efb6b4d49f5ca | https://github.com/tadata-org/fastapi_mcp/issues/293 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 11. 维护坑 · 来源证据：v0.3.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.3.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_bc6b7bd2988b48d48920e4ffb259f147 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.0 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 12. 维护坑 · 来源证据：v0.3.3 - Fix OpenAPI Conversion Regression\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.3.3 - Fix OpenAPI Conversion Regression\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_79b96b9d35b9444c938c355c081410ac | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.3 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 13. 维护坑 · 来源证据：v0.4.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.4.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4382c9c951e14187b76777ad8561ded9 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.4.0 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 14. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | last_activity_observed missing\n\n## 15. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | no_demo; severity=medium\n\n## 16. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 17. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | no_demo; severity=medium\n\n## 18. 安全/权限坑 · 来源证据：v0.3.1 - Authorization\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.3.1 - Authorization\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_41bf79ee5bd04da1b943d22449a0d649 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.1 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 19. 安全/权限坑 · 来源证据：v0.3.2\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.3.2\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_aa60828a6a6c4cc2b0b28fb72bf2ddad | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.2 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 20. 安全/权限坑 · 来源证据：v0.3.7\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.3.7\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_31faa7de6a364174958daaffa9d9204b | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.7 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 21. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | issue_or_pr_quality=unknown\n\n## 22. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | release_recency=unknown\n\n<!-- canonical_name: tadata-org/fastapi_mcp; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "Human Manual / 人类版说明书"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log / 踩坑日志\n\n项目：tadata-org/fastapi_mcp\n\n摘要：发现 22 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：配置坑 - 来源证据：[BUG] MCP session 404 in multi worker production environment。\n\n## 1. 配置坑 · 来源证据：[BUG] MCP session 404 in multi worker production environment\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[BUG] MCP session 404 in multi worker production environment\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f318cbe8fc55407da8cb88f5418cce0d | https://github.com/tadata-org/fastapi_mcp/issues/189 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：v0.1.8\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.1.8\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_11a827f3808141e4bd7b0541a8628af0 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.1.8 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 3. 安装坑 · 来源证据：v0.2.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.2.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a145fff6c53f4e709ef1bb7bc291216c | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.2.0 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 4. 安装坑 · 来源证据：v0.3.4\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.3.4\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_6dcb58f1897f46a188514e2714e5896d | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.4 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 5. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | host_targets=mcp_host, claude, cursor\n\n## 6. 配置坑 · 来源证据：Suggestion: MCPWatch observability example for fastapi_mcp users\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Suggestion: MCPWatch observability example for fastapi_mcp users\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_dfa72f41f3094dd5b2ffe188889f2b4f | https://github.com/tadata-org/fastapi_mcp/issues/303 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 7. 配置坑 · 来源证据：clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：clean_schema_for_display() strips anyOf and loses items for Optional[List[X]] parameters\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_74e4280da33d49e1a3a8d576c7bb78a6 | https://github.com/tadata-org/fastapi_mcp/issues/304 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 8. 配置坑 · 来源证据：v0.3.6\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：v0.3.6\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_bdc90006d16a437798ff2766d514f3d4 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.6 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 9. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | README/documentation is current enough for a first validation pass.\n\n## 10. 维护坑 · 来源证据：[BUG] Description incorrectly passed as version to MCP Server\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[BUG] Description incorrectly passed as version to MCP Server\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2e599a8b03d649d8a47efb6b4d49f5ca | https://github.com/tadata-org/fastapi_mcp/issues/293 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 11. 维护坑 · 来源证据：v0.3.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.3.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_bc6b7bd2988b48d48920e4ffb259f147 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.0 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 12. 维护坑 · 来源证据：v0.3.3 - Fix OpenAPI Conversion Regression\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.3.3 - Fix OpenAPI Conversion Regression\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_79b96b9d35b9444c938c355c081410ac | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.3 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 13. 维护坑 · 来源证据：v0.4.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.4.0\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4382c9c951e14187b76777ad8561ded9 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.4.0 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 14. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | last_activity_observed missing\n\n## 15. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | no_demo; severity=medium\n\n## 16. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 17. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | no_demo; severity=medium\n\n## 18. 安全/权限坑 · 来源证据：v0.3.1 - Authorization\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.3.1 - Authorization\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_41bf79ee5bd04da1b943d22449a0d649 | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.1 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 19. 安全/权限坑 · 来源证据：v0.3.2\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.3.2\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_aa60828a6a6c4cc2b0b28fb72bf2ddad | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.2 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 20. 安全/权限坑 · 来源证据：v0.3.7\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.3.7\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_31faa7de6a364174958daaffa9d9204b | https://github.com/tadata-org/fastapi_mcp/releases/tag/v0.3.7 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 21. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | issue_or_pr_quality=unknown\n\n## 22. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:944976593 | https://github.com/tadata-org/fastapi_mcp | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# fastapi_mcp - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for tadata-org/fastapi_mcp.\n\nProject:\n- Name: fastapi_mcp\n- Repository: https://github.com/tadata-org/fastapi_mcp\n- Summary: Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!\n- Host target: mcp_host, claude, cursor\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Expose your FastAPI endpoints as Model Context Protocol (MCP) tools, with Auth!\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. architecture: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n2. quickstart: Quickstart Guide. Produce one small intermediate artifact and wait for confirmation.\n3. examples: Examples Overview. Produce one small intermediate artifact and wait for confirmation.\n4. auth-overview: Authentication Overview. Produce one small intermediate artifact and wait for confirmation.\n5. auth-oauth: OAuth Authentication. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/tadata-org/fastapi_mcp\n- https://github.com/tadata-org/fastapi_mcp#readme\n- fastapi_mcp/server.py\n- fastapi_mcp/openapi/convert.py\n- fastapi_mcp/transport/http.py\n- fastapi_mcp/transport/sse.py\n- fastapi_mcp/types.py\n- examples/01_basic_usage_example.py\n- examples/shared/apps/items.py\n- examples/shared/setup.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start / 官方入口\n\n项目：tadata-org/fastapi_mcp\n\n## 官方安装入口\n\n### Python / pip · 官方安装入口\n\n```bash\npip install fastapi-mcp\n```\n\n来源：https://github.com/tadata-org/fastapi_mcp#readme\n\n## 来源\n\n- repo: https://github.com/tadata-org/fastapi_mcp\n- docs: https://github.com/tadata-org/fastapi_mcp#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_246d8351a869475d81589da59486f339"
}
