mcp-export 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mcp_export/__init__.py +3 -0
- mcp_export/cli.py +555 -0
- mcp_export/config.py +143 -0
- mcp_export/extractor.py +385 -0
- mcp_export/logging_setup.py +59 -0
- mcp_export/mcpspec.py +45 -0
- mcp_export/openapi.py +365 -0
- mcp_export/scanner.py +352 -0
- mcp_export-1.0.0.dist-info/METADATA +504 -0
- mcp_export-1.0.0.dist-info/RECORD +13 -0
- mcp_export-1.0.0.dist-info/WHEEL +4 -0
- mcp_export-1.0.0.dist-info/entry_points.txt +2 -0
- mcp_export-1.0.0.dist-info/licenses/LICENSE +21 -0
mcp_export/__init__.py
ADDED
mcp_export/cli.py
ADDED
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
"""Command line interface for mcp-export.
|
|
2
|
+
|
|
3
|
+
Exit codes
|
|
4
|
+
----------
|
|
5
|
+
0 : success
|
|
6
|
+
1 : no tool matched the filters, or validation/strict checks failed
|
|
7
|
+
2 : configuration error (bad config file / invalid values / bad arguments)
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import fnmatch
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Iterable, Optional
|
|
18
|
+
|
|
19
|
+
import typer
|
|
20
|
+
|
|
21
|
+
from . import __version__
|
|
22
|
+
from .config import DEFAULTS, ConfigError, load_config, validate
|
|
23
|
+
from .extractor import ExtractedModule, ToolDescriptor, extract_from_module
|
|
24
|
+
from .logging_setup import get_logger, setup_logging
|
|
25
|
+
from .mcpspec import build_mcp_document
|
|
26
|
+
from .openapi import build_spec, dump_spec, validate_spec
|
|
27
|
+
from .scanner import (
|
|
28
|
+
ImportFailure,
|
|
29
|
+
import_module_from_path,
|
|
30
|
+
iter_module_records,
|
|
31
|
+
project_dependencies,
|
|
32
|
+
purge_project_modules,
|
|
33
|
+
save_cache,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
app = typer.Typer(add_completion=False, help="Export FastMCP tools to an OpenAPI document.")
|
|
37
|
+
|
|
38
|
+
MANIFEST_NAME = ".mcp-export-manifest.json"
|
|
39
|
+
DEFAULT_OUT_DIR = "dist"
|
|
40
|
+
DEFAULT_OUT_FILES = {"json": "openapi.json", "yaml": "openapi.yaml", "mcp": "mcp.json"}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# --------------------------------------------------------------------------- #
|
|
44
|
+
# helpers
|
|
45
|
+
# --------------------------------------------------------------------------- #
|
|
46
|
+
def _matches(name: str, patterns: list[str]) -> bool:
|
|
47
|
+
return any(fnmatch.fnmatch(name, pattern) for pattern in patterns)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _filter_items(
|
|
51
|
+
items: list,
|
|
52
|
+
include: list[str],
|
|
53
|
+
exclude: list[str],
|
|
54
|
+
) -> list:
|
|
55
|
+
"""Filter tools/resources/prompts by module/name glob patterns.
|
|
56
|
+
|
|
57
|
+
An item is kept when it matches at least one ``include`` pattern (or when
|
|
58
|
+
``include`` is empty) and matches no ``exclude`` pattern. Patterns are
|
|
59
|
+
matched against ``module.name`` and the bare ``name``.
|
|
60
|
+
"""
|
|
61
|
+
if not include and not exclude:
|
|
62
|
+
return items
|
|
63
|
+
kept: list = []
|
|
64
|
+
for item in items:
|
|
65
|
+
targets = [f"{item.source}.{item.name}", item.name]
|
|
66
|
+
if include and not any(_matches(t, include) for t in targets):
|
|
67
|
+
continue
|
|
68
|
+
if any(_matches(t, exclude) for t in targets):
|
|
69
|
+
continue
|
|
70
|
+
kept.append(item)
|
|
71
|
+
return kept
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _dedupe(items: list, key: str) -> list:
|
|
75
|
+
"""Keep the first item for each value of ``key`` (deterministic order)."""
|
|
76
|
+
seen: set = set()
|
|
77
|
+
out: list = []
|
|
78
|
+
for item in items:
|
|
79
|
+
value = getattr(item, key)
|
|
80
|
+
if value in seen:
|
|
81
|
+
continue
|
|
82
|
+
seen.add(value)
|
|
83
|
+
out.append(item)
|
|
84
|
+
return out
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _dedupe_scoped(items: list, key: str) -> list:
|
|
88
|
+
"""Dedupe by ``(source module, key)`` so per-module documents stay complete."""
|
|
89
|
+
seen: set = set()
|
|
90
|
+
out: list = []
|
|
91
|
+
for item in items:
|
|
92
|
+
value = (item.source, getattr(item, key))
|
|
93
|
+
if value in seen:
|
|
94
|
+
continue
|
|
95
|
+
seen.add(value)
|
|
96
|
+
out.append(item)
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _write_file(path: Path, text: str) -> None:
|
|
101
|
+
"""Atomically write ``text`` to ``path`` (temp file + replace)."""
|
|
102
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
103
|
+
tmp = path.with_name(path.name + ".tmp")
|
|
104
|
+
tmp.write_text(text, encoding="utf-8")
|
|
105
|
+
os.replace(tmp, path)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _group_by_source(
|
|
109
|
+
tools: Iterable[ToolDescriptor],
|
|
110
|
+
resources: Iterable,
|
|
111
|
+
resource_templates: Iterable,
|
|
112
|
+
prompts: Iterable,
|
|
113
|
+
) -> dict[str, ExtractedModule]:
|
|
114
|
+
"""Group filtered capabilities by their source module (insertion ordered)."""
|
|
115
|
+
groups: dict[str, ExtractedModule] = {}
|
|
116
|
+
for tool in tools:
|
|
117
|
+
groups.setdefault(tool.source, ExtractedModule()).tools.append(tool)
|
|
118
|
+
for item in resources:
|
|
119
|
+
groups.setdefault(item.source, ExtractedModule()).resources.append(item)
|
|
120
|
+
for item in resource_templates:
|
|
121
|
+
groups.setdefault(item.source, ExtractedModule()).resource_templates.append(item)
|
|
122
|
+
for item in prompts:
|
|
123
|
+
groups.setdefault(item.source, ExtractedModule()).prompts.append(item)
|
|
124
|
+
return groups
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _build_document(group: ExtractedModule, fmt: str, cfg: dict) -> tuple[dict, list[str]]:
|
|
128
|
+
tools = {tool.name: tool for tool in group.tools}
|
|
129
|
+
if fmt == "mcp":
|
|
130
|
+
return build_mcp_document(tools, group.resources, group.resource_templates, group.prompts), []
|
|
131
|
+
spec = build_spec(
|
|
132
|
+
tools,
|
|
133
|
+
version=cfg["version"],
|
|
134
|
+
title=cfg["title"],
|
|
135
|
+
api_version=cfg["api_version"],
|
|
136
|
+
resources=group.resources,
|
|
137
|
+
resource_templates=group.resource_templates,
|
|
138
|
+
prompts=group.prompts,
|
|
139
|
+
path_prefix=cfg.get("path_prefix", ""),
|
|
140
|
+
servers=cfg.get("servers", []),
|
|
141
|
+
)
|
|
142
|
+
return spec, validate_spec(spec)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _load_manifest(path: Path) -> set[str]:
|
|
146
|
+
"""Files generated into a split output directory by the previous run."""
|
|
147
|
+
try:
|
|
148
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
149
|
+
except (OSError, ValueError):
|
|
150
|
+
return set()
|
|
151
|
+
files = data.get("files") if isinstance(data, dict) else None
|
|
152
|
+
if not isinstance(files, list):
|
|
153
|
+
return set()
|
|
154
|
+
return {item for item in files if isinstance(item, str)}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _write_manifest(path: Path, files: set[str]) -> None:
|
|
158
|
+
_write_file(path, json.dumps({"files": sorted(files)}, ensure_ascii=False, indent=2))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _remove_stale_files(out_dir: Path, rels: set[str]) -> None:
|
|
162
|
+
"""Delete previously generated files that this run no longer produces."""
|
|
163
|
+
root = out_dir.resolve()
|
|
164
|
+
for rel in rels:
|
|
165
|
+
try:
|
|
166
|
+
target = (root / rel).resolve()
|
|
167
|
+
if target.is_relative_to(root) and target.is_file():
|
|
168
|
+
target.unlink()
|
|
169
|
+
except (OSError, ValueError):
|
|
170
|
+
continue
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def git_changed_files(root: Path) -> set[str] | None:
|
|
174
|
+
"""Return repo-relative paths changed vs. HEAD, or ``None`` if unavailable.
|
|
175
|
+
|
|
176
|
+
Uses ``git status --porcelain -z`` (covers staged, unstaged and untracked
|
|
177
|
+
files) so that freshly added tool files are picked up without a commit.
|
|
178
|
+
"""
|
|
179
|
+
try:
|
|
180
|
+
proc = subprocess.run(
|
|
181
|
+
["git", "status", "--porcelain", "-z"],
|
|
182
|
+
cwd=str(root),
|
|
183
|
+
capture_output=True,
|
|
184
|
+
text=True,
|
|
185
|
+
timeout=30,
|
|
186
|
+
)
|
|
187
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
188
|
+
get_logger().warning("无法执行 git status: %s", exc)
|
|
189
|
+
return None
|
|
190
|
+
if proc.returncode != 0:
|
|
191
|
+
get_logger().warning("git status 失败(退出码 %s): %s", proc.returncode, proc.stderr.strip())
|
|
192
|
+
return None
|
|
193
|
+
changed: set[str] = set()
|
|
194
|
+
entries = proc.stdout.split("\0")
|
|
195
|
+
index = 0
|
|
196
|
+
while index < len(entries):
|
|
197
|
+
entry = entries[index]
|
|
198
|
+
index += 1
|
|
199
|
+
if not entry:
|
|
200
|
+
continue
|
|
201
|
+
status, path = entry[:2], entry[3:]
|
|
202
|
+
if status[:1] in ("R", "C"):
|
|
203
|
+
index += 1 # rename/copy: skip the trailing original-path entry
|
|
204
|
+
changed.add(path)
|
|
205
|
+
return changed
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _diff_filter(root: Path, records: list) -> tuple[list, set[str] | None]:
|
|
209
|
+
"""Keep only records whose repo-relative path is in the git changeset."""
|
|
210
|
+
changed = git_changed_files(root)
|
|
211
|
+
if changed is None:
|
|
212
|
+
return records, None
|
|
213
|
+
kept = [r for r in records if r.path.relative_to(root).as_posix() in changed]
|
|
214
|
+
return kept, changed
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _split_patterns(raw: Optional[str], fallback: list[str]) -> list[str]:
|
|
218
|
+
if raw is None:
|
|
219
|
+
return list(fallback)
|
|
220
|
+
parts = [p.strip() for p in raw.split(",") if p.strip()]
|
|
221
|
+
return parts or list(fallback)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _show_version(value: bool) -> None:
|
|
225
|
+
if value:
|
|
226
|
+
typer.echo(__version__)
|
|
227
|
+
raise typer.Exit(code=0)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
# --------------------------------------------------------------------------- #
|
|
231
|
+
# command
|
|
232
|
+
# --------------------------------------------------------------------------- #
|
|
233
|
+
@app.command()
|
|
234
|
+
def main(
|
|
235
|
+
root: Optional[str] = typer.Argument(None, help="Project root to scan (default: from config or '.')."),
|
|
236
|
+
out: Optional[str] = typer.Option(None, "--out", "-o", help="Output file (single document), or directory when splitting (default: dist/ with one file per source module)."),
|
|
237
|
+
config: Optional[str] = typer.Option(None, "--config", help="Path to a configuration file."),
|
|
238
|
+
openapi_version: Optional[str] = typer.Option(None, "--openapi-version", "-V", help="OpenAPI version: 3.0.3 / 3.0.2 / 3.0.1 / 3.0.0 / 3.1.0."),
|
|
239
|
+
title: Optional[str] = typer.Option(None, "--title", help="OpenAPI info.title."),
|
|
240
|
+
api_version: Optional[str] = typer.Option(None, "--api-version", help="OpenAPI info.version."),
|
|
241
|
+
path_prefix: Optional[str] = typer.Option(None, "--path-prefix", help="Prefix every generated path, e.g. /v1 (default: empty)."),
|
|
242
|
+
server: Optional[list[str]] = typer.Option(None, "--server", help="OpenAPI server URL; repeatable. Overrides servers from config."),
|
|
243
|
+
no_cache: bool = typer.Option(False, "--no-cache", help="Ignore .mcp-export-cache.json."),
|
|
244
|
+
strict: Optional[bool] = typer.Option(None, "--strict/--no-strict", help="Exit non-zero on any import/duplicate/validation failure."),
|
|
245
|
+
include: Optional[str] = typer.Option(None, "--include", help="Comma-separated include globs (module or tool name)."),
|
|
246
|
+
exclude: Optional[str] = typer.Option(None, "--exclude", help="Comma-separated exclude globs (module or tool name)."),
|
|
247
|
+
diff: bool = typer.Option(False, "--diff", help="Only export tools whose source file changed in git."),
|
|
248
|
+
dry_run: bool = typer.Option(False, "--dry-run", help="Print the export plan and exit without writing."),
|
|
249
|
+
fmt: str = typer.Option("json", "--format", help="Output format: json (default), yaml, or mcp (tools/list JSON)."),
|
|
250
|
+
split: bool = typer.Option(False, "--split", help="Force per-module output into a directory (default when --out is omitted)."),
|
|
251
|
+
show_version: bool = typer.Option(False, "--version", callback=_show_version, is_eager=True, help="Show the mcp-export version and exit."),
|
|
252
|
+
verbose: bool = typer.Option(False, "--verbose", help="Enable debug logging."),
|
|
253
|
+
) -> None:
|
|
254
|
+
"""Scan ROOT, extract tools registered via @mcp.tool(), and write an OpenAPI document.
|
|
255
|
+
|
|
256
|
+
Values resolve as: command line > configuration file > built-in defaults.
|
|
257
|
+
"""
|
|
258
|
+
log = setup_logging(verbose=verbose)
|
|
259
|
+
|
|
260
|
+
# ---- configuration ---------------------------------------------------- #
|
|
261
|
+
try:
|
|
262
|
+
cfg = load_config(config, root or ".")
|
|
263
|
+
except ConfigError as exc:
|
|
264
|
+
log.error("配置错误: %s", exc)
|
|
265
|
+
raise typer.Exit(code=2)
|
|
266
|
+
|
|
267
|
+
cfg["root"] = root or cfg["root"]
|
|
268
|
+
if out is not None:
|
|
269
|
+
cfg["out"] = out
|
|
270
|
+
if openapi_version is not None:
|
|
271
|
+
cfg["version"] = openapi_version
|
|
272
|
+
if title is not None:
|
|
273
|
+
cfg["title"] = title
|
|
274
|
+
if api_version is not None:
|
|
275
|
+
cfg["api_version"] = api_version
|
|
276
|
+
if path_prefix is not None:
|
|
277
|
+
cfg["path_prefix"] = path_prefix
|
|
278
|
+
if server is not None:
|
|
279
|
+
cfg["servers"] = list(server)
|
|
280
|
+
if strict is not None:
|
|
281
|
+
cfg["strict"] = strict
|
|
282
|
+
if no_cache:
|
|
283
|
+
cfg["cache"] = False
|
|
284
|
+
# 未指定 --out 时默认按源文件拆分;显式给出输出文件则合并为单文档。
|
|
285
|
+
if split:
|
|
286
|
+
cfg["split"] = True
|
|
287
|
+
elif cfg["split"] is None:
|
|
288
|
+
cfg["split"] = cfg["out"] is None
|
|
289
|
+
if include is not None:
|
|
290
|
+
cfg["include"] = _split_patterns(include, cfg["include"])
|
|
291
|
+
if exclude is not None:
|
|
292
|
+
cfg["exclude"] = _split_patterns(exclude, cfg["exclude"])
|
|
293
|
+
|
|
294
|
+
errors = validate(cfg)
|
|
295
|
+
if errors:
|
|
296
|
+
for err in errors:
|
|
297
|
+
log.error("配置错误: %s", err)
|
|
298
|
+
raise typer.Exit(code=2)
|
|
299
|
+
|
|
300
|
+
if fmt not in ("json", "yaml", "mcp"):
|
|
301
|
+
log.error("配置错误: --format 只支持 json、yaml 或 mcp,当前为 %r", fmt)
|
|
302
|
+
raise typer.Exit(code=2)
|
|
303
|
+
if fmt == "mcp" and (openapi_version is not None or title is not None or api_version is not None):
|
|
304
|
+
log.warning("--format mcp 不使用 --openapi-version / --title / --api-version,已忽略")
|
|
305
|
+
|
|
306
|
+
root_path = Path(cfg["root"]).expanduser().resolve()
|
|
307
|
+
if not root_path.is_dir():
|
|
308
|
+
log.error("root 不是一个目录: %s", root_path)
|
|
309
|
+
raise typer.Exit(code=2)
|
|
310
|
+
|
|
311
|
+
out_value = cfg["out"]
|
|
312
|
+
if out_value is None:
|
|
313
|
+
# 未显式指定输出时落到 dist/ 目录,文件名随格式变化,避免 MCP 结果
|
|
314
|
+
# 被写进 openapi.json 这类误导性文件名。
|
|
315
|
+
if cfg["split"]:
|
|
316
|
+
out_value = DEFAULT_OUT_DIR
|
|
317
|
+
else:
|
|
318
|
+
out_value = str(Path(DEFAULT_OUT_DIR) / DEFAULT_OUT_FILES[fmt])
|
|
319
|
+
out_path = Path(out_value).expanduser()
|
|
320
|
+
if not out_path.is_absolute():
|
|
321
|
+
out_path = Path.cwd() / out_path
|
|
322
|
+
|
|
323
|
+
# ---- dry run ---------------------------------------------------------- #
|
|
324
|
+
if dry_run:
|
|
325
|
+
log.info(
|
|
326
|
+
"dry-run: root=%s include=%s exclude=%s out=%s format=%s strict=%s cache=%s diff=%s split=%s path_prefix=%s servers=%s",
|
|
327
|
+
root_path,
|
|
328
|
+
cfg["include"] or "[]",
|
|
329
|
+
cfg["exclude"] or "[]",
|
|
330
|
+
out_path,
|
|
331
|
+
fmt,
|
|
332
|
+
cfg["strict"],
|
|
333
|
+
cfg["cache"],
|
|
334
|
+
diff,
|
|
335
|
+
cfg["split"],
|
|
336
|
+
cfg.get("path_prefix", ""),
|
|
337
|
+
cfg.get("servers", []),
|
|
338
|
+
)
|
|
339
|
+
raise typer.Exit(code=0)
|
|
340
|
+
|
|
341
|
+
# ---- scan + extract --------------------------------------------------- #
|
|
342
|
+
records = iter_module_records(
|
|
343
|
+
root_path, use_cache=cfg["cache"], cache_dependencies=cfg["cache_dependencies"]
|
|
344
|
+
)
|
|
345
|
+
changed: set[str] | None = None
|
|
346
|
+
if diff:
|
|
347
|
+
records, changed = _diff_filter(root_path, records)
|
|
348
|
+
if changed is None:
|
|
349
|
+
log.warning("--diff 需要可用的 git 仓库,已回退为全量扫描")
|
|
350
|
+
else:
|
|
351
|
+
log.info("git 变更文件 %d 个,命中待扫描模块 %d 个", len(changed), len(records))
|
|
352
|
+
|
|
353
|
+
inventory = ExtractedModule()
|
|
354
|
+
failures: list[ImportFailure] = []
|
|
355
|
+
cache_entries: dict[str, dict] = {}
|
|
356
|
+
deps_entries: dict[str, dict[str, str]] = {}
|
|
357
|
+
source_paths: dict[str, str] = {}
|
|
358
|
+
reused = 0
|
|
359
|
+
|
|
360
|
+
for record in records:
|
|
361
|
+
rel = record.path.relative_to(root_path).as_posix()
|
|
362
|
+
source_paths[record.module_name] = rel[:-3]
|
|
363
|
+
if record.cached is not None:
|
|
364
|
+
# Unchanged module: reuse the capabilities extracted on a previous
|
|
365
|
+
# run so the module is never imported again.
|
|
366
|
+
reused += 1
|
|
367
|
+
inventory.extend(ExtractedModule.from_dict(record.cached))
|
|
368
|
+
cache_entries[rel] = record.cached
|
|
369
|
+
continue
|
|
370
|
+
before = set(sys.modules)
|
|
371
|
+
try:
|
|
372
|
+
module, reason = import_module_from_path(record, root_path)
|
|
373
|
+
if module is None:
|
|
374
|
+
failures.append(ImportFailure(record=record, reason=reason))
|
|
375
|
+
log.warning("跳过无法导入的模块 %s: %s", record.path, reason)
|
|
376
|
+
continue
|
|
377
|
+
extracted = extract_from_module(module, record.module_name)
|
|
378
|
+
inventory.extend(extracted)
|
|
379
|
+
cache_entries[rel] = extracted.to_dict()
|
|
380
|
+
# Record project modules this file imported so their edits can
|
|
381
|
+
# invalidate this cache entry on a later run.
|
|
382
|
+
deps_entries[rel] = project_dependencies(root_path, before, record.path)
|
|
383
|
+
finally:
|
|
384
|
+
# 清除本模块新导入的项目内模块,避免共享的 FastMCP 实例把上一个
|
|
385
|
+
# 模块注册的工具带到下一个模块。
|
|
386
|
+
purge_project_modules(root_path, before)
|
|
387
|
+
|
|
388
|
+
if cfg["cache"]:
|
|
389
|
+
save_cache(
|
|
390
|
+
root_path,
|
|
391
|
+
records,
|
|
392
|
+
cache_entries,
|
|
393
|
+
deps_entries,
|
|
394
|
+
cache_dependencies=cfg["cache_dependencies"],
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
# ---- filter, then de-duplicate ---------------------------------------- #
|
|
398
|
+
total = len(inventory.tools)
|
|
399
|
+
filtered_tools = _filter_items(inventory.tools, cfg["include"], cfg["exclude"])
|
|
400
|
+
filtered_resources = _filter_items(inventory.resources, cfg["include"], cfg["exclude"])
|
|
401
|
+
filtered_templates = _filter_items(inventory.resource_templates, cfg["include"], cfg["exclude"])
|
|
402
|
+
filtered_prompts = _filter_items(inventory.prompts, cfg["include"], cfg["exclude"])
|
|
403
|
+
|
|
404
|
+
duplicates: list[str] = []
|
|
405
|
+
groups: dict[str, ExtractedModule] = {}
|
|
406
|
+
if cfg["split"]:
|
|
407
|
+
# 分文件模式下每份文件只代表自己的模块,跨模块同名不算冲突,
|
|
408
|
+
# 只在模块内部去重。
|
|
409
|
+
resources = _dedupe_scoped(filtered_resources, "uri")
|
|
410
|
+
resource_templates = _dedupe_scoped(filtered_templates, "uri_template")
|
|
411
|
+
prompts = _dedupe_scoped(filtered_prompts, "name")
|
|
412
|
+
groups = _group_by_source(
|
|
413
|
+
_dedupe_scoped(filtered_tools, "name"), resources, resource_templates, prompts
|
|
414
|
+
)
|
|
415
|
+
tools: dict[str, ToolDescriptor] = {}
|
|
416
|
+
exported = (
|
|
417
|
+
sum(len(group.tools) for group in groups.values()),
|
|
418
|
+
sum(len(group.resources) for group in groups.values()),
|
|
419
|
+
sum(len(group.resource_templates) for group in groups.values()),
|
|
420
|
+
sum(len(group.prompts) for group in groups.values()),
|
|
421
|
+
)
|
|
422
|
+
else:
|
|
423
|
+
tools = {}
|
|
424
|
+
for tool in filtered_tools:
|
|
425
|
+
existing = tools.get(tool.name)
|
|
426
|
+
if existing is None:
|
|
427
|
+
tools[tool.name] = tool
|
|
428
|
+
continue
|
|
429
|
+
duplicates.append(tool.name)
|
|
430
|
+
log.warning("工具名重复: %s(保留 %s,忽略 %s)", tool.name, existing.source, tool.source)
|
|
431
|
+
resources = _dedupe(filtered_resources, "uri")
|
|
432
|
+
resource_templates = _dedupe(filtered_templates, "uri_template")
|
|
433
|
+
prompts = _dedupe(filtered_prompts, "name")
|
|
434
|
+
for label, before, after in (
|
|
435
|
+
("资源 URI", len(filtered_resources), len(resources)),
|
|
436
|
+
("资源模板 URI", len(filtered_templates), len(resource_templates)),
|
|
437
|
+
("提示词名称", len(filtered_prompts), len(prompts)),
|
|
438
|
+
):
|
|
439
|
+
if before > after:
|
|
440
|
+
log.warning("%s 重复,已丢弃 %d 个", label, before - after)
|
|
441
|
+
exported = (len(tools), len(resources), len(resource_templates), len(prompts))
|
|
442
|
+
|
|
443
|
+
# ---- no match handling ------------------------------------------------ #
|
|
444
|
+
if not any(exported):
|
|
445
|
+
log.warning(
|
|
446
|
+
"过滤后无匹配工具/资源/提示词(include=%s exclude=%s)",
|
|
447
|
+
cfg["include"] or "[]",
|
|
448
|
+
cfg["exclude"] or "[]",
|
|
449
|
+
)
|
|
450
|
+
if cfg["strict"]:
|
|
451
|
+
raise typer.Exit(code=1)
|
|
452
|
+
raise typer.Exit(code=0)
|
|
453
|
+
|
|
454
|
+
# ---- build + write ---------------------------------------------------- #
|
|
455
|
+
errors: list[str] = []
|
|
456
|
+
payload_format = "json" if fmt == "mcp" else fmt
|
|
457
|
+
if cfg["split"]:
|
|
458
|
+
if fmt == "mcp":
|
|
459
|
+
suffix = ".mcp.json"
|
|
460
|
+
elif fmt == "yaml":
|
|
461
|
+
suffix = ".openapi.yaml"
|
|
462
|
+
else:
|
|
463
|
+
suffix = ".openapi.json"
|
|
464
|
+
written = 0
|
|
465
|
+
manifest_path = out_path / MANIFEST_NAME
|
|
466
|
+
previous_files = _load_manifest(manifest_path)
|
|
467
|
+
written_files: set[str] = set()
|
|
468
|
+
for source in sorted(groups):
|
|
469
|
+
group = groups[source]
|
|
470
|
+
try:
|
|
471
|
+
document, doc_errors = _build_document(group, fmt, cfg)
|
|
472
|
+
except ValueError as exc:
|
|
473
|
+
log.error("%s", exc)
|
|
474
|
+
raise typer.Exit(code=2)
|
|
475
|
+
rel = source_paths.get(source) or source.replace(".", "/")
|
|
476
|
+
target = out_path / (rel + suffix)
|
|
477
|
+
if doc_errors:
|
|
478
|
+
for err in doc_errors:
|
|
479
|
+
log.error("校验失败 %s: %s", target, err)
|
|
480
|
+
errors.extend(doc_errors)
|
|
481
|
+
try:
|
|
482
|
+
text = dump_spec(document, payload_format)
|
|
483
|
+
_write_file(target, text)
|
|
484
|
+
except (RuntimeError, ValueError) as exc:
|
|
485
|
+
log.error("%s", exc)
|
|
486
|
+
raise typer.Exit(code=2)
|
|
487
|
+
except OSError as exc:
|
|
488
|
+
log.error("写入失败 %s: %s", target, exc)
|
|
489
|
+
raise typer.Exit(code=2)
|
|
490
|
+
log.debug("已写入: %s", target)
|
|
491
|
+
written_files.add(target.relative_to(out_path).as_posix())
|
|
492
|
+
written += 1
|
|
493
|
+
# 清理上次生成、这次已不存在的文件;--diff 只重写变更模块,不能删除其它产物。
|
|
494
|
+
if diff:
|
|
495
|
+
manifest_files = previous_files | written_files
|
|
496
|
+
else:
|
|
497
|
+
_remove_stale_files(out_path, previous_files - written_files)
|
|
498
|
+
manifest_files = written_files
|
|
499
|
+
try:
|
|
500
|
+
_write_manifest(manifest_path, manifest_files)
|
|
501
|
+
except OSError as exc:
|
|
502
|
+
log.error("写入清单失败 %s: %s", manifest_path, exc)
|
|
503
|
+
raise typer.Exit(code=2)
|
|
504
|
+
else:
|
|
505
|
+
group = ExtractedModule(
|
|
506
|
+
tools=list(tools.values()),
|
|
507
|
+
resources=resources,
|
|
508
|
+
resource_templates=resource_templates,
|
|
509
|
+
prompts=prompts,
|
|
510
|
+
)
|
|
511
|
+
try:
|
|
512
|
+
document, doc_errors = _build_document(group, fmt, cfg)
|
|
513
|
+
except ValueError as exc:
|
|
514
|
+
log.error("%s", exc)
|
|
515
|
+
raise typer.Exit(code=2)
|
|
516
|
+
errors.extend(doc_errors)
|
|
517
|
+
if doc_errors:
|
|
518
|
+
for err in doc_errors:
|
|
519
|
+
log.error("校验失败: %s", err)
|
|
520
|
+
elif fmt == "mcp":
|
|
521
|
+
log.info("MCP 能力: 工具 %d 个,资源 %d 个,提示词 %d 个", len(tools), len(resources), len(prompts))
|
|
522
|
+
else:
|
|
523
|
+
log.info("校验通过")
|
|
524
|
+
try:
|
|
525
|
+
text = dump_spec(document, payload_format)
|
|
526
|
+
_write_file(out_path, text)
|
|
527
|
+
except (RuntimeError, ValueError) as exc:
|
|
528
|
+
log.error("%s", exc)
|
|
529
|
+
raise typer.Exit(code=2)
|
|
530
|
+
except OSError as exc:
|
|
531
|
+
log.error("写入失败 %s: %s", out_path, exc)
|
|
532
|
+
raise typer.Exit(code=2)
|
|
533
|
+
log.info("已写入: %s", out_path)
|
|
534
|
+
|
|
535
|
+
if cfg["split"]:
|
|
536
|
+
log.info("已写入 %d 个文件到目录: %s", written, out_path)
|
|
537
|
+
|
|
538
|
+
log.info("扫描模块: %d 个(缓存复用 %d 个),导入失败 %d 个", len(records), reused, len(failures))
|
|
539
|
+
log.info("工具: %d 个导出(共提取 %d 个)", exported[0], total)
|
|
540
|
+
log.info("资源: %d 个,资源模板: %d 个,提示词: %d 个", exported[1], exported[2], exported[3])
|
|
541
|
+
if duplicates:
|
|
542
|
+
log.warning("存在 %d 个重复工具名: %s", len(duplicates), ", ".join(sorted(set(duplicates))))
|
|
543
|
+
|
|
544
|
+
# ---- exit code -------------------------------------------------------- #
|
|
545
|
+
if errors:
|
|
546
|
+
log.error("生成的文档校验失败,退出码 1")
|
|
547
|
+
raise typer.Exit(code=1)
|
|
548
|
+
if (failures or duplicates) and cfg["strict"]:
|
|
549
|
+
log.error("strict 模式下存在导入失败或重复工具名")
|
|
550
|
+
raise typer.Exit(code=1)
|
|
551
|
+
raise typer.Exit(code=0)
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
if __name__ == "__main__":
|
|
555
|
+
app()
|