Skip to content

fix(mcp): make output paths, worker lifecycle, and GIF options robust - #206

Open
Tariolle wants to merge 2 commits into
mainfrom
fix/mcp-review-findings
Open

Tariolle wants to merge 2 commits into
mainfrom
fix/mcp-review-findings

Conversation

@Tariolle

@Tariolle Tariolle commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This fixes all 14 findings from a code review of visualtorch_mcp/: 8 important, 2 pre-existing and 4 nits. Each one has a regression test.

Output paths

  • Default output dir no longer depends on the host's cwd (Add the implementation of visualtorch #1). It is computed for each call as ~/visualtorch_outputs, so it is never /visualtorch_outputs (read-only on macOS GUI hosts) or inside an app's install folder. A relative output_dir resolves against workdir if one is given, otherwise against ~/visualtorch_outputs. A relative workdir is rejected with a clear error.
  • Dotted names are no longer cut short (Add GitHub Actions workflow for pre-commit #2). Only a real image extension is replaced: diagram.jpg becomes diagram.png, resnet-1.5 becomes resnet-1.5.png, and model_v1.1 and model_v1.2 stay separate files. A matching extension keeps its case (Diagram.PNG).
  • output_dir is validated only when it is used (Update README.md #14). An absolute output_path ignores a stale output_dir.
  • Artifacts get normal permissions (Update version #5). Staging files are now created with mode 0666, so the umask applies, instead of mkstemp's 0600. When a file is replaced, it keeps the existing file's mode. New code is in visualtorch_mcp/_files.py.

Worker lifecycle

  • A failed job can no longer overwrite the user's file (Fix incorrect module and parameter #4). The worker now leaves the verified artifact in staging. The server moves it into place only after it has parsed a successful result and checked for cancellation. The worker also calls os._exit() right after writing its result, so non-daemon threads or atexit hooks left by model source cannot stall it until the timeout.

  • An orphaned worker stops itself (Update README.md and Change Default Parameters #3). The payload now carries parent_pid and timeout_seconds, and a watchdog thread in the worker stops it when either check fails:

    • Server death: POSIX compares getppid() to parent_pid. Windows holds a SYNCHRONIZE handle on the server process, so a reused PID cannot fool the check.
    • Deadline: the timeout plus a 10 s grace period.

    On POSIX the worker also kills its own process group, which takes model-spawned children with it, and it removes its staging file. PR_SET_PDEATHSIG was ruled out because it fires when the spawning thread exits, and anyio worker threads are recycled.

  • The worker can no longer import code from the host's cwd (Add unit tests #6). It starts in a private, empty temp directory, which also holds the payload. A json.py, inspect.py or visualtorch.py in the host's cwd therefore cannot shadow installed packages. The worker still chdirs into workdir when one is given.

  • Timeout and cancel cleanup is bounded (Update python version #8). After kill(), the final wait has a timeout and the error is raised regardless. On POSIX the protocol pipe is also closed. It is not closed on Windows, because a communicate() reader thread may still hold the buffer lock there.

  • sys.exit() in model source gets a clear error (Update version to 0.1.1 #12). SystemExit and KeyboardInterrupt now produce an explicit error instead of invalid JSON: ''. sys.argv is reset before model source runs, so a module-level argparse call works.

Animation options

  • null animation controls select the default (Add more usage examples #7). This covers frame_duration, final_hold_duration and loop.
  • Durations match what GIF can store (Update readme #11). They must be between 20 and 655350 ms and are rounded to the nearest 10 ms. GIF stores delays as a 16-bit count of centiseconds, and viewers clamp very short delays to about 100 ms. The manifest advertises minimum: 20, maximum: 655350 and resolution: 10.
  • loop=false now plays once (Add a simple unit test and pytest workflow #9, upstream visualtorch/_animation.py). The GIF is written without a NETSCAPE extension. Pillow's loop=1 meant "repeat once", so the reveal played twice. APNG and WebP, which direct Python callers can request, still get loop=1: they store a play count, and Pillow's default for them is to loop forever. Worker metadata now reports loop: false for such GIFs.

Other

  • visualtorch_reference(style=...) keeps the Render page (Add badges #13). The index and examples pages are kept as well.
  • The mcp extra floor is raised to >=1.22.0 (Add publish workflow #10). 1.0.x and 1.1.x have no mcp.server.fastmcp, and 1.2.x's FastMCP does not accept instructions= (1.3.0 is the first that does). But every release before 1.22.0 imports a pydantic internal (eval_type_backport) that current pydantic no longer has, and none of them cap pydantic. A fresh install of any of them therefore cannot start the server. I checked each release against pydantic 2.14.4.
  • Docs (get_started/mcp.md) are updated for the new path rules, the duration limits and the null handling.

Behavior changes to be aware of

  • With no output_dir, output now goes to ~/visualtorch_outputs instead of <server cwd>/visualtorch_outputs.
  • A relative workdir is now rejected.
  • frame_duration and final_hold_duration below 20 are now rejected (previously minimum 1). The tests that used 1 now use 20.
  • When no workdir is given, model source runs in the output file's directory instead of the host's cwd.
  • Windows drive-relative (C:images) and root-relative (\images) output_dir/output_path values are rejected.
  • Animation durations above 655350 ms are rejected (they could never be stored in a GIF).
  • The mcp extra now needs mcp>=1.22.0.

Review follow-up (second commit)

An independent review of the first commit found these issues. All of them are fixed, with regression tests that fail on the first commit:

  • Late writes after cancellation. A cancelled MCP call returned while its job thread could still replace the output, and even overwrite a later call's result. Cancellation now waits (shielded) until the job thread has finished, and a job thread that has not started yet exits without doing any work.
  • Private files readable while staged. Replacing a 0600 artifact staged the new content as 0644. A replacement's staging file now starts with the existing file's mode.
  • Leaked daemon children. os._exit() skipped multiprocessing's shutdown, so daemonic children of model source survived successful jobs. They are now terminated first.
  • Watchdog deleting the wrong file. The watchdog could delete a staging_path that the worker had not validated yet. It now deletes only files named like reserved staging files, never the output path. Server-published jobs are marked with an explicit parent_publishes flag, so a direct invocation that passes staging_path still publishes its artifact.
  • Windows orphan handling. A parent that had already exited before the worker started was treated as alive. On Windows, an aborting worker now also stops its own process tree (taskkill /T).
  • Scratch directory. On Windows a surviving child could pin the scratch directory, and relative side files written by model source were deleted with it. Model source now runs in workdir, or in the output directory when there is none.
  • Relative PYTHONPATH entries. These resolved against the scratch directory. They are now made absolute against the server's directory, so the worker imports the same code as the server.
  • Path handling. Windows drive-relative and root-relative paths are rejected. A blank output_dir is ignored when it is unused. More image extensions are recognised (.avif, .heic, .jxl, …).
  • Small robustness fixes:
    • bytes now reports the file this job wrote, even if another writer replaces the path right afterwards.
    • On Windows, a failed staging cleanup no longer hides the job's real error.
    • Durations are capped at the GIF maximum, so that 655355–655359 ms can no longer round up to an overflow.
    • The mcp floor was raised as described above.

Not changed:

  • The watchdog thread needs the GIL, so a native call that holds the GIL indefinitely can still stop it from running. Fixing that would need a separate supervisor process.
  • A concurrent writer in the same directory could swap the staging path for a symlink between reservation and chmod. That attacker could already replace the output itself.

Testing

  • Windows 11, Python 3.12 (torch 2.15 CPU, mcp 1.30, Pillow 13): full suite 349 passed, 3 skipped. The skips are POSIX-only tests.
  • Linux (WSL Ubuntu 24.04), Python 3.12: full suite 350 passed, 2 skipped. The skips are Windows-only tests. This run includes a test that SIGKILLs a real server mid-render and checks that the worker, its grandchild and the staging file are all gone.
  • Linux crash check (manual): I SIGKILLed a server process in the middle of a render whose model source had spawned sleep 300. The worker and the grandchild were both gone within 0.5 s and the staging file was removed. A real render under umask 022 produced a 0644 PNG.
  • Windows, Python 3.10, mcp==1.22.0 + pydantic 2.14.4: tests/test_mcp.py passes (88 passed, 3 skipped), including the stdio end-to-end and cancellation tests.
  • Lint and types: ruff@0.15.22 check/format and mypy@2.3.0 are clean. markdownlint and prettier pass on the docs, checked with LF line endings.

Address the code-review findings for the MCP server:

- Resolve the default output directory per call under the home directory
  (~/visualtorch_outputs) instead of freezing the host's cwd at import time.
  Relative output_dir resolves against workdir (or the default directory),
  and workdir must be absolute.
- Swap only real image extensions for .png/.gif so dotted names such as
  "resnet-1.5" or "model_v1.1" are no longer truncated, and keep the case of a
  matching extension.
- Only validate output_dir when an output path actually uses it.
- Create staging files with mode 0666 so the umask applies (no more 0600
  artifacts), and keep an existing artifact's mode when replacing it.
- Move the staging file into place in the server only after a successful,
  parsed worker result; the worker exits with os._exit() right after writing
  its result so lingering threads or atexit hooks cannot stall it.
- Give the worker a watchdog that stops it (and, on POSIX, its process group)
  and removes its staging file when the server dies or the deadline passes.
- Start the worker in a private empty directory so modules in the host's cwd
  cannot shadow installed packages.
- Bound every wait in the timeout/cancel cleanup path.
- Report SystemExit/KeyboardInterrupt from model source clearly, and hide the
  worker's argv from model source.
- Treat null animation controls as "use the default", require durations of at
  least 20 ms, and round them to GIF's 10 ms resolution.
- Write no NETSCAPE loop extension for loop=False so the GIF plays once
  (Pillow's loop=1 meant "repeat once"), and report loop accordingly.
- Keep the render() page when visualtorch_reference filters by style.
- Raise the mcp extra's floor to 1.3.0, the first release whose FastMCP
  accepts instructions=.
@Tariolle Tariolle added the bug Something isn't working label Dec 2, 2026
Follow-up to the review of the previous commit:

- Wait for the job thread when an MCP call is cancelled, so a job that had
  already passed its last cancellation check cannot replace the output after
  the cancellation was acknowledged.
- Start a replacement's staging file with the existing file's mode, so a
  private artifact is never readable while it is staged.
- Terminate daemonic multiprocessing children before os._exit(), as normal
  interpreter shutdown would.
- Only let the watchdog delete files named like reserved staging files that
  are not the output path; mark server-published jobs with an explicit
  parent_publishes flag so direct invocations that pass staging_path still
  publish their artifact.
- Treat a Windows parent that no longer exists as gone, and stop the worker's
  whole process tree with taskkill when it aborts itself on Windows.
- Run model source in the output directory when no workdir is given, so side
  files persist and no child process pins the scratch directory.
- Resolve relative PYTHONPATH entries against the server's directory.
- Reject Windows drive-relative and root-relative paths, validate output_dir
  only when it is used (including blank strings), and recognise more image
  extensions.
- Report the size of the file this job wrote, and do not let a failed
  staging cleanup replace the job's real error.
- Cap animation durations at 655350 ms, the largest GIF delay.
- Keep loop=False playing once for APNG and WebP, whose PIL default loops.
- Raise the mcp floor to 1.22.0: earlier releases import a pydantic internal
  that current pydantic no longer has.
@Tariolle
Tariolle marked this pull request as ready for review December 2, 2026 15:58
@Tariolle
Tariolle requested a review from willyfh as a code owner December 2, 2026 15:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant