Metadata-Version: 2.5
Name: mcp-export
Version: 1.0.0
Summary: Export FastMCP tools, resources and prompts to OpenAPI 3.x or MCP JSON documents for gateway import.
Author: mcp-export
License: MIT
License-File: LICENSE
Keywords: cli,fastmcp,gateway,mcp,openapi
Requires-Python: >=3.10
Requires-Dist: fastmcp>=2.0.0
Requires-Dist: importlib-metadata>=7.0.0
Requires-Dist: openapi-spec-validator>=0.7.0
Requires-Dist: pydantic>=2.7.0
Requires-Dist: tomli>=2.0.0; python_version < '3.11'
Requires-Dist: typer>=0.12.0
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: pytest-cov>=4.1; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: pyyaml>=6.0; extra == 'dev'
Provides-Extra: yaml
Requires-Dist: pyyaml>=6.0; extra == 'yaml'
Description-Content-Type: text/markdown

# mcp-export

从项目目录扫描 Python 模块，提取通过 **`@mcp.tool()` / `@mcp.resource()` / `@mcp.prompt()` 注册的 FastMCP 能力**（tools、resources、resourceTemplates、prompts），生成可直接导入自研网关的 **OpenAPI 3.x JSON / YAML**，或生成 **MCP 能力清单（tools/list、resources/list、prompts/list）**。

> 只有注册到 FastMCP 实例上的工具 / 资源 / 提示词才会导出；普通模块级函数一律忽略。

## 特性

- 递归扫描 `.py`，自动跳过 `.venv`、`venv`、`__pycache__`、`tests`、`.git`、`node_modules` 等目录
- 反射 FastMCP 实例的 `get_tools()/get_resources()/get_prompts()`（2.x）或 `list_tools()/list_resources()/list_prompts()`（4.x），同步 / 异步、子类实例均可
- 同时导出静态资源、资源模板（`uriTemplate`）和提示词（含参数定义）
- 自动把 OpenAPI 3.1 风格 schema 降级到 3.0（`anyOf` → `nullable`、`const` → `enum`、`type` 数组、数值型 `exclusiveMinimum` 等），并把内联 `$defs` 提升到 `components.schemas`、重写 `$ref`
- 无参数工具不生成 `requestBody`；有 `outputSchema` 时生成 200 响应 schema
- 工具路径做 URL 编码（`/tools/{name}`），`operationId` 保留原始工具名；与 `/resources/read`、`/prompts/get` 的固定 id 冲突时自动加 `_endpoint` 后缀
- 使用 `openapi-spec-validator` 校验，校验失败默认以非零码退出（不会静默产出非法文档）
- 配置校验：`version` / `include` / `exclude` / `strict` / `cache` / `title` / `api_version` 一次报全
- 新增 `--diff`（按 git 变更筛选）、`--dry-run`（只打印计划）、`--format json|yaml|mcp`
- 默认多文件导出：不指定 `--out` 时按源文件拆分到 `dist/`，文件名为「源文件名 + 格式标识」；显式 `-o 文件` 时合并为单文档
- `--split`：强制按源文件拆分（即使给了 `-o`），并自动清理过期产物
- 标准库 logging：INFO→stdout、WARNING/ERROR→stderr，导入失败与重名工具不再静默
- 基于文件摘要 + mtime 的缓存 `.mcp-export-cache.json`：未变更模块**不再重复 import**，并感知项目内依赖与 `fastmcp`/`pydantic` 版本变化
- 支持配置文件（`mcp-export.toml` 或 `pyproject.toml` 的 `[tool.mcp-export]`），命令行参数优先

## 安装

全局安装（推荐，一次安装处处可用）：

```bash
pipx install .
# 或
uv tool install .
# 开发模式（修改代码立即生效）
pip install -e .
```

全局安装的是工具本身，扫描目标是「当前工作目录」，cd 到任意项目根目录执行即可；被扫描项目的依赖由项目自身提供。

## 使用

`root` 是**位置参数**（默认 `.`）：

```bash
mcp-export                             # 自动读取配置，默认拆分到 dist/<源文件名>.openapi.json
mcp-export examples                    # 扫描 examples 目录
mcp-export examples --format mcp       # 拆分到 dist/<源文件名>.mcp.json
mcp-export examples -o openapi.json    # 合并为单个文档
mcp-export examples --split -o out     # 强制拆分到 out/ 目录
mcp-export --config ci.toml            # 指定配置文件
mcp-export . --out other.json          # 覆盖输出路径
mcp-export . --openapi-version 3.1.0
mcp-export . --path-prefix /v1 --server https://api.example.com
mcp-export . --include "search" --exclude "internal*"
mcp-export . --no-cache --no-strict
mcp-export . --format mcp -o tools.mcp.json   # 单文件 MCP 清单
```

参数优先级：**命令行参数 > 配置文件 > 内置默认值**。

| 参数 | 默认 | 说明 |
|---|---|---|
| `root`（位置参数） | `.` | 扫描根目录 |
| `--config` | 无 | 指定配置文件路径 |
| `--out/-o` | `dist/` | 输出文件（合并为单文档）；`--split` 或省略时为输出目录，相对当前工作目录 |
| `--openapi-version/-V` | `3.0.3` | OpenAPI 版本 |
| `--version` | 无 | 打印 mcp-export 版本并退出 |
| `--title` | `mcp-export` | `info.title` |
| `--api-version` | `1.0.0` | `info.version` |
| `--path-prefix` | 空 | 所有生成路径统一加前缀（仅 OpenAPI） |
| `--server` | 空 | OpenAPI `servers` URL，可重复；传入后覆盖配置中的 `servers`（仅 OpenAPI） |
| `--no-cache` | 关 | 忽略缓存 |
| `--strict/--no-strict` | 关 | 导入失败 / 重名时非零退出（校验失败始终非零） |
| `--include` | 空 | 逗号分隔的 include glob（`模块名` 或 能力名） |
| `--exclude` | 空 | 逗号分隔的 exclude glob（`模块名` 或 能力名） |
| `--diff` | 关 | 只导出 git 变更涉及的能力 |
| `--dry-run` | 关 | 只打印导出计划，不扫描不写文件 |
| `--format` | `json` | 输出格式：`json` / `yaml` / `mcp` |
| `--split` | 未指定 `-o` 时自动开启 | 强制按源文件拆分：`--out` 视为输出目录 |
| `--verbose` | 关 | 开启 debug 日志 |

### 退出码

| 码 | 含义 |
|---|---|
| `0` | 成功 |
| `1` | 过滤后无匹配的工具/资源/提示词；生成的文档校验失败；strict 模式下导入失败或工具重名 |
| `2` | 配置错误（配置文件无法解析、取值非法、`--format` 非法、root 不存在、写入失败） |

## 配置文件

查找顺序（找到即用）：`--config` 显式路径 > 项目根 `mcp-export.toml` > 项目根 `pyproject.toml` 的 `[tool.mcp-export]`。

`mcp-export.toml` 完整示例：

```toml
root = "."
out = "dist"
version = "3.0.3"
title = "my-gateway"
api_version = "1.0.0"
strict = true
include = ["tools.*"]
exclude = ["tools.internal.*"]
cache = true
split = true
path_prefix = ""          # 可选：统一路径前缀，如 "/v1"
servers = []              # 可选：OpenAPI servers，如 ["https://api.example.com"]
cache_dependencies = []   # 可选：影响缓存的额外文件 glob（相对 root）
```

`pyproject.toml` 写法：

```toml
[tool.mcp-export]
root = "."
out = "dist"
version = "3.0.3"
title = "my-gateway"
api_version = "1.0.0"
strict = false
include = []
exclude = []
cache = true
split = true
path_prefix = ""          # 可选：统一路径前缀，如 "/v1"
servers = []              # 可选：OpenAPI servers，如 ["https://api.example.com"]
cache_dependencies = []   # 可选：影响缓存的额外文件 glob（相对 root）
```

三种典型命令：

```bash
mcp-export                    # 自动读 mcp-export.toml
mcp-export --config ci.toml   # 指定配置
mcp-export . --out other.json # 命令行覆盖配置
```

### 配置校验

以下写法会在启动阶段被拒绝（退出码 `2`，stderr 一次性列出全部问题）：

```toml
version = "9.9.9"          # 仅支持 3.0.0 / 3.0.1 / 3.0.2 / 3.0.3 / 3.1.0
include = "search"         # 必须是字符串列表 ["search"]
strict = "yes"             # 必须是布尔值 true / false
title = 123                # 必须是非空字符串
```

修复方式：把 `include`/`exclude` 写成 `["..."]`，`strict`/`cache` 写成 `true`/`false`，`version` 换成受支持的值。

### 通用 OpenAPI 字段（可选）

- `path_prefix`：给所有生成路径加统一前缀，如 `"/v1"` → `/v1/tools/{name}`、`/v1/resources/read`、`/v1/prompts/get`；默认空，不改变路径。
- `servers`：写入 OpenAPI 的 `servers` 字段，支持 URL 字符串或 `{ url = "...", description = "..." }` 表；默认 `[]`（不输出，保持网关无关）。
- 两项只影响 OpenAPI 格式；`--format mcp` 会忽略它们。
- 也可用命令行覆盖：`--path-prefix /v1 --server https://api.example.com`；`--server` 可重复，传入后整体覆盖配置中的 `servers`。

### 新参数示例

```bash
# 只导出本次 git 变更涉及的工具
mcp-export . --diff -o openapi.diff.json

# 先看看会做什么，不写文件
mcp-export . --dry-run

# 输出 YAML（需 pip install 'mcp-export[yaml]'）
mcp-export . --format yaml -o openapi.yaml

# 组合：变更 + 单个工具 + YAML + 严格模式
mcp-export . --diff --include "my_new_tool" --format yaml -o openapi.new.yaml --strict

# CI 中无需额外参数：spec 校验不过会自动非零退出
mcp-export . -o openapi.json
```

YAML 输出片段：

```yaml
openapi: 3.0.3
info:
  title: mcp-export
  version: 1.0.0
paths:
  /tools/search:
    post:
      summary: search
      operationId: search
```

### MCP 格式输出

`--format mcp` 输出 MCP 各 `*/list` 方法的返回内容（`tools` 必有，其余按实际能力出现），schema 保持原始 JSON Schema（不做 OpenAPI 3.0 降级）：

```bash
mcp-export . --format mcp -o tools.json
```

```json
{
  "tools": [
    {
      "name": "search",
      "description": "Search documents by query.",
      "inputSchema": {
        "type": "object",
        "properties": {
          "query": {"type": "string"},
          "top_k": {"type": "integer", "default": 5}
        },
        "required": ["query"]
      },
      "outputSchema": {"type": "array", "items": {"type": "string"}}
    }
  ],
  "resources": [
    {"uri": "file:///readme.txt", "name": "readme", "mimeType": "text/plain"}
  ],
  "resourceTemplates": [
    {"uriTemplate": "file:///users/{uid}", "name": "user_profile"}
  ],
  "prompts": [
    {"name": "greet", "arguments": [{"name": "name", "required": true}]}
  ]
}
```

说明：MCP 模式下 `--openapi-version` / `--title` / `--api-version` 不生效，也会跳过 OpenAPI spec 校验；输出固定为 JSON（`--format yaml` 与 `mcp` 不能同时使用）。

### OpenAPI 格式下的 resources / prompts

`--format json|yaml` 仍以 OpenAPI 为主体。除每个工具一个 `POST /tools/{name}` 外：

- 存在资源或资源模板时，追加 `POST /resources/read`（body：`{"uri": "..."}`），对应 MCP `resources/read`
- 存在提示词时，追加 `POST /prompts/get`（body：`{"name": "...", "arguments": {...}}`），对应 MCP `prompts/get`
- 完整清单放在顶层扩展字段 `x-mcp-resources` / `x-mcp-resource-templates` / `x-mcp-prompts`，结构与 MCP 输出一致，网关可据此做权限与路由

这样资源模板（动态 URI）不需要逐个展开成路径，网关按 MCP 方法代理即可。

## 全量 / 增量导出

- 默认 **全量导出**：扫描根目录下全部 `.py`（跳过约定目录）→ 全量反射 → 全量重写输出文件，不做 diff 或合并旧文件。
- 缓存只跳过重复 `import`（未变更模块直接复用上次提取结果），导出范围仍是全量。
- 缓存会记录每个模块 import 过的项目内依赖摘要，并校验 `fastmcp` / `pydantic` / Python 版本：共享注册代码或环境变化时自动失效。
- `cache_dependencies`：额外的非 Python 依赖文件 glob（相对 root），如 `["conf/*.yaml", "data/tools.json"]`；这些文件内容变化时整份缓存失效，默认 `[]`。
- 只导部分：用 `root` 缩小目录，或用 `--include/--exclude` 按模块/工具名 glob 过滤。

## 只导出新增的单个工具

`--include` 按「工具名」或「`模块名.工具名`」做 glob 匹配，**不带通配符时即精确匹配**，因此只导出本次新增的一个工具，只需把它的工具名传给 `--include`：

```bash
# 方式一：命令行精确指定（最常用）
mcp-export . --include "my_new_tool"

# 方式二：写进配置文件固定下来（mcp-export.toml 或 pyproject.toml 的 [tool.mcp-export]）
include = ["my_new_tool"]

# 方式三：CI 中只导出/校验这个新工具，输出到单独文件
mcp-export . --include "my_new_tool" -o openapi.new.json --strict
```

要点：

- `--include` 是「命中即保留、未命中全部排除」；配合 `--out` 指定单独文件即可只产出这一个工具的 spec。
- 多个工具用逗号分隔：`--include "tool_a,tool_b"`。
- `--exclude` 是**减法且优先级更高**，会覆盖 `--include`；不要用 `--exclude "*" --include "单个"` 想“先排除再放行”，那样会得到空集。
- 过滤发生在去重**之前**：被排除的模块不会触发重名告警，也不会占用同名工具。
- `--include/--exclude` 同样作用于 resources / resourceTemplates / prompts（按名称匹配）；因此 `--include "search"` 时不会附带资源或提示词端点。
- 需要“只导出本次改动涉及的工具”时，直接用内置的 `--diff`（基于 `git status --porcelain -z`，含未跟踪的新文件）；不是 git 仓库时会告警并回退全量。

## 分文件导出（默认）

默认就是多文件导出：不指定 `--out` 时输出到 `./dist`，每个源文件生成一份独立文档，文件名为「源文件名 + 格式标识」。显式 `-o 文件` 会把所有能力合并为单文档；`--split` 用于在给了 `-o` 的情况下强制拆分。

```bash
mcp-export examples --split -o dist                 # OpenAPI JSON
mcp-export examples --split --format yaml -o dist   # OpenAPI YAML
mcp-export examples --split --format mcp -o dist    # MCP 能力清单
```

三种格式的产物树（以仓库示例 `sample_mcp.py`、`sample_mcp2.py` 为例）：

`--format json`（默认，OpenAPI）：

```
dist/
├── sample_mcp.openapi.json
└── sample_mcp2.openapi.json
```

`--format yaml`（OpenAPI）：

```
dist/
├── sample_mcp.openapi.yaml
└── sample_mcp2.openapi.yaml
```

`--format mcp`（MCP 能力清单）：

```
dist/
├── .mcp-export-manifest.json
├── sample_mcp.mcp.json
└── sample_mcp2.mcp.json
```

嵌套目录同样保留，例如 `pkg/tools/search.py`：

```
dist/
└── pkg/
    └── tools/
        └── search.mcp.json
```

每个 `.mcp.json` 只包含**本文件对应源模块**的能力，没有的能力段会省略。`sample_mcp.mcp.json` 的实际内容（截取）：

```json
{
  "tools": [
    {
      "name": "search",
      "description": "Search documents by query.",
      "inputSchema": {
        "type": "object",
        "properties": {"query": {"type": "string"}},
        "required": ["query"]
      },
      "outputSchema": {"type": "array", "items": {"type": "string"}}
    },
    {
      "name": "ping",
      "description": "Return a simple health-check message.",
      "inputSchema": {
        "type": "object",
        "properties": {"message": {"type": "string", "default": "pong"}}
      },
      "outputSchema": {"type": "string"}
    }
  ],
  "resources": [
    {"uri": "file:///readme.txt", "name": "readme", "mimeType": "text/plain"}
  ],
  "resourceTemplates": [
    {"uriTemplate": "file:///users/{uid}", "name": "user_profile", "mimeType": "text/plain"}
  ],
  "prompts": [
    {"name": "greet", "arguments": [{"name": "name", "required": true}]}
  ]
}
```

MCP 模式使用原始 JSON Schema（`inputSchema` / `outputSchema`），不做 OpenAPI 3.0 降级；`--openapi-version` / `--title` / `--api-version` 在此模式下不生效。`sample_mcp2.mcp.json` 结构相同，只包含 `sample_mcp2.py` 注册的能力。

目录层级随源文件保留。例如 `pkg/tools/search.py` 在三种格式下分别生成：

```
dist/
└── pkg/
    └── tools/
        ├── search.openapi.json    # --format json
        ├── search.openapi.yaml    # --format yaml
        └── search.mcp.json        # --format mcp
```

规则：

- 每份文件都是**完整文档**（OpenAPI 或 MCP），可单独导入网关
- 文件名 = 源文件名 + 格式标识：
  - `--format json` → `<name>.openapi.json`
  - `--format yaml` → `<name>.openapi.yaml`
  - `--format mcp` → `<name>.mcp.json`
- 没有注册任何能力的模块（如空的 `__init__.py`）不会生成文件
- 不指定 `-o` 时默认输出到 `./dist` 目录
- `--include/--exclude`、`--diff`、缓存、`--strict` 同样生效
- 分文件模式只在**模块内部**去重：不同模块定义同名工具/资源时会各自保留在自己的文件里（单文件模式仍是全局去重、后出现的忽略）
- 输出目录会写入 `.mcp-export-manifest.json`，下次运行自动删除「上次生成、本次不再产出」的文件；`--diff` 模式不会删除其他产物

## 示例项目

仓库内有两份示例模块：`examples/sample_mcp.py` 与 `examples/sample_mcp2.py`。每份都包含三个 `@mcp.tool()` 工具、一个静态资源、一个资源模板、一个提示词，以及一个未被装饰、不会被导出的普通函数。

生成单文件（OpenAPI，合并所有能力）：

```bash
mcp-export examples -o examples/openapi.json
```

默认多文件（OpenAPI，写入 `dist/`）：

```bash
mcp-export examples
# dist/sample_mcp.openapi.json
# dist/sample_mcp2.openapi.json
```

默认多文件（MCP 能力清单）：

```bash
mcp-export examples --format mcp
# dist/sample_mcp.mcp.json
# dist/sample_mcp2.mcp.json
```

## CI 集成

```yaml
- name: Install mcp-export
  run: pipx install .
- name: Generate OpenAPI
  run: mcp-export . -o openapi.json --strict
- name: Upload artifact
  uses: actions/upload-artifact@v4
  with:
    name: openapi
    path: openapi.json
```

需要按源文件拆分时，把生成步骤换成目录输出并上传整个目录：

```yaml
- name: Generate split documents
  run: mcp-export . --split -o dist --strict
- uses: actions/upload-artifact@v4
  with:
    name: openapi-split
    path: dist/
```

## pre-commit 集成

`.pre-commit-hooks.yaml` 已提供，仓库根 `.pre-commit-config.yaml` 可写：

```yaml
repos:
  - repo: https://github.com/your-org/mcp-export
    rev: v1.0.0
    hooks:
      - id: mcp-export
        args: [".", "-o", "openapi.json", "--strict"]
```

或本地钩子：

```yaml
repos:
  - repo: local
    hooks:
      - id: mcp-export
        name: mcp-export
        entry: mcp-export
        language: system
        args: [".", "-o", "openapi.json", "--strict"]
        pass_filenames: false
```

## 说明

- 模块会被真实 `import`，请在模块顶层避免启动逻辑，或使用 `if __name__ == "__main__":` 保护。
- 安全提示：扫描会执行项目内代码，只应对可信代码运行；CI 中处理不可信 PR 时请放在隔离容器/沙箱内。
- 每个模块独立导入：扫描完一个模块后，会把本次新导入的项目内模块从 `sys.modules` 清理，因此 `server.py` 定义 `mcp`、各工具模块 `from server import mcp` 的共享实例写法不会互相污染。
- 导入时会把扫描根目录临时加入 `sys.path`，因此模块内 `from pkg.sub import x` 这类绝对导入可以正常工作。
- 导入失败的文件会被跳过并输出 warning（含异常类型与消息）；`--strict` 下计入失败并返回 `1`。
- 工具名重复会输出 warning（含保留/忽略的模块），`--strict` 下同样返回 `1`。
- 生成路径统一为 `/tools/{name}`（name 会做 URL 编码），`operationId` 为原始工具名；如网关有额外字段要求，可在 `openapi.py` 中扩展。
- 不带参数的工具有默认值时不会生成 `requestBody`；有 `outputSchema` 时会在 `responses.200.content` 中输出 schema。

## 测试与覆盖率

```bash
pip install -e ".[dev]"
pytest --cov=mcp_export --cov-report=term-missing
```

仓库内 `.github/workflows/ci.yml` 在 Python 3.10/3.11/3.12 上跑 pytest，覆盖率门槛 70%。

## 许可证

MIT，见 `LICENSE`。
