Files
Max Isbey d99b1400c6 Rewrite lowlevel decorator registrations through generated adapters
The twelve v1 @server.* decorator kinds are gone on v2. Their sites now
become add_request_handler / add_notification_handler calls at the
decorator's exact source position (registration there is when the v1
decorator ran, so execution order is preserved and the deprecated
capabilities land on the warning-free path), wired through generated
adapters that reproduce the v1 wrapper semantics: bare-list wrapping,
call_tool's any-exception-to-isError contract with jsonschema input and
output validation (tool lookup through the registered tools/list
handler, v1's own cache mechanism, so cross-module list_tools works),
read_resource content conversion, and the completion None-mapping.
Handler bodies are never touched. Shapes the adapter cannot serve
honestly -- a stacked decorator, an attribute receiver, a non-v1
signature, a non-literal decorator argument, a taken name -- are marked
with the reason. The suite migrates a six-registration server and
serves it to a v1-shaped ClientSession over the legacy protocol; the
templates are pinned against the installed v2 (method strings register,
params models exist, imports resolve, no 2026-era surface is emitted).

Also on the client surface: inline timedelta session timeouts convert
to float seconds and non-provable values are marked (the mismatch only
fails on the first request); cursor= on session list_* methods wraps
into params=PaginatedRequestParams(...); pydantic URL wrappers around
resource URIs are dropped where the target provably takes v2's plain
str and marked elsewhere; constructions of and pydantic method calls on
the v1 RootModel wrappers that became plain union aliases are marked
with the TypeAdapter fix; ._mcp_server and the type-keyed handler dicts
are marked with their v2 homes. Adapters honor an explicit `uri: str`
annotation and keep v1's AnyUrl otherwise, and keep the emitted code
insensitive to user return annotations so a wrong annotation cannot
manufacture type errors inside generated code.

Batch harness: seven more pinned repositories (two seven-decorator
servers, a multi-package lowlevel server, the method-local-server
marker path, two client libraries including a positional timedelta
timeout and the old streamablehttp spelling, and an exact ==1.6.0 pin).
Markers now cover the full statement they precede rather than a fixed
radius, Unknown-typed errors in files that carry markers classify as
cascade of a marked break, and the work directory is a dot-directory so
pytest never collects the cloned repositories' own suites. All eleven
repositories audit at zero uncovered errors.

An adversarial review round over the full change confirmed ten defects,
all fixed with regression tests: adapter imports now inject at the top
of the module (a mid-file import as the anchor left registration code
running before its imports bound); the rewrite gates now also block a
handler named like a template local, and any module-level non-import
binding of a name the adapter references (both were silent runtime
breaks past the gates); import injection dedup now reads the updated
module's top-level import binds, so conditional or function-local
imports no longer suppress a needed injection; list_* adapters pass a
returned full result model through instead of double-wrapping (v1's
runtime behavior); the blocked-progress marker names
add_notification_handler (a request-handler registration would never
fire); the timeout transform skips already-v2 shapes so re-runs stay
no-ops; the emitted name scheme is defined once and shared between
templates and gates; and the harness classifier no longer lets a
marker cover a whole def/class body or write off arbitrary
Unknown-typed errors (header-only spans; cascade restricted to
propagation rules and never detonators).
2026-07-01 13:47:06 +00:00

194 lines
7.3 KiB
Python

"""The `mcp-codemod` command line: its flags, output, and exit codes."""
import textwrap
from pathlib import Path
import pytest
from mcp_codemod.cli import main
def test_v1_to_v2_rewrites_files_and_prints_a_summary(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
path = tmp_path / "server.py"
path.write_text("from mcp.server.fastmcp import FastMCP\n")
assert main(["v1-to-v2", str(tmp_path)]) == 0
assert "mcp.server.mcpserver" in path.read_text()
assert "1 of 1 files rewritten" in capsys.readouterr().out
def test_dry_run_reports_without_writing(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
source = "from mcp.server.fastmcp import FastMCP\n"
path = tmp_path / "server.py"
path.write_text(source)
assert main(["v1-to-v2", "--dry-run", str(tmp_path)]) == 0
assert path.read_text() == source
assert "Dry run" in capsys.readouterr().out
def test_diff_prints_a_unified_diff(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
path = tmp_path / "server.py"
path.write_text("from mcp.server.fastmcp import FastMCP\n")
main(["v1-to-v2", "--diff", str(tmp_path)])
out = capsys.readouterr().out
assert "-from mcp.server.fastmcp import FastMCP\n" in out
assert "+from mcp.server.mcpserver import MCPServer\n" in out
def test_no_markers_suppresses_comment_insertion(tmp_path: Path) -> None:
path = tmp_path / "server.py"
path.write_text(
textwrap.dedent("""\
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("demo", mount_path="/old")
""")
)
main(["v1-to-v2", "--no-markers", str(tmp_path)])
rewritten = path.read_text()
assert "mcp.server.mcpserver" in rewritten
assert "# mcp-codemod" not in rewritten
def test_a_parse_failure_returns_a_nonzero_exit_and_is_reported_to_stderr(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
path = tmp_path / "broken.py"
path.write_text("def broken(:\n")
assert main(["v1-to-v2", str(tmp_path)]) == 1
assert str(path) in capsys.readouterr().err
def test_version_prints_the_installed_version(capsys: pytest.CaptureFixture[str]) -> None:
with pytest.raises(SystemExit):
main(["--version"])
assert capsys.readouterr().out.startswith("mcp-codemod ")
def test_a_missing_migration_argument_is_an_argparse_error() -> None:
with pytest.raises(SystemExit) as excinfo:
main([])
assert excinfo.value.code == 2
def test_the_grep_hint_appears_only_when_there_are_markers(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
clean = tmp_path / "clean.py"
clean.write_text('from mcp.server.mcpserver import MCPServer\n\nmcp = MCPServer("demo")\n')
assert main(["v1-to-v2", str(clean)]) == 0
assert "grep -rn" not in capsys.readouterr().out
flagged = tmp_path / "flagged.py"
flagged.write_text(
textwrap.dedent("""\
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("demo", port=8000)
""")
)
assert main(["v1-to-v2", str(flagged)]) == 0
assert "grep -rn '# mcp-codemod:'" in capsys.readouterr().out
def test_the_per_file_line_reports_review_counts(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
path = tmp_path / "pager.py"
path.write_text(
textwrap.dedent("""\
from mcp.types import ListToolsResult
def next_page(result: ListToolsResult) -> str | None:
return result.nextCursor
""")
)
assert main(["v1-to-v2", str(path)]) == 0
[file_line] = [line for line in capsys.readouterr().out.splitlines() if line.startswith(f"{path}:")]
assert file_line.endswith("1 need review")
def test_an_unchanged_file_with_no_diagnostics_produces_no_per_file_line(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
path = tmp_path / "clean.py"
path.write_text('from mcp.server.mcpserver import MCPServer\n\nmcp = MCPServer("demo")\n')
assert main(["v1-to-v2", str(path)]) == 0
out = capsys.readouterr().out
assert "0 of 1 files rewritten" in out
assert f"{path}:" not in out
def test_diff_skips_files_the_codemod_did_not_change(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
(tmp_path / "old.py").write_text("from mcp.server.fastmcp import FastMCP\n")
(tmp_path / "new.py").write_text("from mcp.server.mcpserver import MCPServer\n")
assert main(["v1-to-v2", "--diff", str(tmp_path)]) == 0
out = capsys.readouterr().out
assert f"--- {tmp_path / 'old.py'}" in out
assert f"--- {tmp_path / 'new.py'}" not in out
def test_a_dry_run_lists_every_site_instead_of_the_grep_hint(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
"""With `--dry-run` no marker lands on disk, so the summary lists each site
directly instead of the grep hint; info-only renames are excluded."""
target = tmp_path / "server.py"
target.write_text(
'from mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP("demo", mount_path="/x")\nprint(tool.inputSchema)\n'
)
broken = tmp_path / "broken.py"
broken.write_text("def (\n")
code = main(["v1-to-v2", "--dry-run", str(tmp_path)])
captured = capsys.readouterr()
assert code == 1
assert f"{target}:3: `mount_path=`" in captured.out
assert "inputSchema" not in captured.out
assert "grep -rn" not in captured.out
assert "Dry run: nothing was written." in captured.out
assert "failed (" in captured.err
def test_the_cli_updates_dependency_files_alongside_the_sources(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
"""Dependency files migrate in the same run and their flags join the still-need-a-human accounting."""
(tmp_path / "server.py").write_text("from mcp.server.fastmcp import FastMCP\n")
(tmp_path / "pyproject.toml").write_text('[project]\ndependencies = ["mcp>=1.2,<2"]\n')
(tmp_path / "requirements.txt").write_text("mcp[ws]==1.9.4\n")
code = main(["v1-to-v2", str(tmp_path)])
captured = capsys.readouterr()
assert code == 0
assert "mcp.server.mcpserver" in (tmp_path / "server.py").read_text()
assert '"mcp>=2,<3"' in (tmp_path / "pyproject.toml").read_text()
assert "# mcp-codemod:" in (tmp_path / "requirements.txt").read_text()
assert f"{tmp_path / 'pyproject.toml'}: mcp requirement updated for v2" in captured.out
assert f"{tmp_path / 'requirements.txt'}: 1 need review" in captured.out
assert "1 sites still need a human" in captured.out
def test_a_broken_pyproject_fails_the_run_without_stopping_it(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
(tmp_path / "server.py").write_text("from mcp.server.fastmcp import FastMCP\n")
(tmp_path / "pyproject.toml").write_text("[broken")
code = main(["v1-to-v2", str(tmp_path)])
captured = capsys.readouterr()
assert code == 1
assert "mcp.server.mcpserver" in (tmp_path / "server.py").read_text()
assert "TOMLDecodeError" in captured.err
def test_no_markers_lists_dependency_sites_in_the_summary(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
requirements = tmp_path / "requirements.txt"
requirements.write_text("mcp[ws]==1.9.4\n")
code = main(["v1-to-v2", "--no-markers", str(tmp_path)])
captured = capsys.readouterr()
assert code == 0
assert requirements.read_text() == "mcp[ws]==1.9.4\n"
assert f"{requirements}:1: the `ws` extra was removed" in captured.out