π The fast, Pythonic way to build MCP servers and clients.
Stage skill exports before replacing installed files (#6091)
nate nowackeade578e4bbf
diff --git a/fastmcp_slim/fastmcp/skills/skill.py b/fastmcp_slim/fastmcp/skills/skill.pyindex 23f34093f..8a3909a7d 100644--- a/fastmcp_slim/fastmcp/skills/skill.py+++ b/fastmcp_slim/fastmcp/skills/skill.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport hashlibimport osimport shutil+import tempfilefrom collections.abc import Mappingfrom pathlib import Path, PureWindowsPathfrom types import MappingProxyType@@ -189,7 +190,9 @@ class Skill:The folder name must match the skill's `name`, so `from_directory` canread it back. An existing folder raises `FileExistsError` unless`overwrite` is set, in which case it is replaced: files that aren't- part of the skill are removed.+ part of the skill are removed. Files are staged before replacing an+ existing folder. If replacement and restoration both fail, the error+ identifies where the previous folder has been retained."""root = Path(path)if root.name != self.name:@@ -206,11 +209,33 @@ class Skill:)if not root.is_dir():raise ValueError(f"Skill folder is not a directory: {root}")- shutil.rmtree(root)- for relative, content in self._files.items():- target = root / relative- target.parent.mkdir(parents=True, exist_ok=True)- target.write_bytes(content)+ root.parent.mkdir(parents=True, exist_ok=True)+ staging = Path(tempfile.mkdtemp(prefix=f".{root.name}-", dir=root.parent))+ previous = staging / "previous"+ try:+ replacement = staging / "new"+ for relative, content in self._files.items():+ target = replacement / relative+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(content)+ if root.exists():+ root.rename(previous)+ try:+ replacement.rename(root)+ except OSError:+ if previous.exists():+ try:+ previous.rename(root)+ except OSError as exc:+ raise OSError(+ f"Could not restore {root}; previous skill remains at {previous}"+ ) from exc+ raise+ if previous.exists():+ shutil.rmtree(previous)+ finally:+ if not previous.exists():+ shutil.rmtree(staging)return root@propertydiff --git a/tests/skills/test_skill.py b/tests/skills/test_skill.pyindex 4929e0e23..66e854370 100644--- a/tests/skills/test_skill.py+++ b/tests/skills/test_skill.py@@ -182,6 +182,66 @@ def test_to_directory_overwrite_replaces_the_folder(tmp_path: Path):assert sorted(p.name for p in folder.iterdir()) == ["SKILL.md"][email protected]("existing", [False, True])+def test_failed_export_leaves_destination_untouched(tmp_path: Path, existing: bool):+ folder = tmp_path / "review"+ if existing:+ folder.mkdir()+ (folder / "old.txt").write_bytes(b"original")+ skill = Skill(+ name="review",+ description="Review",+ instructions="# Review\n",+ files={"x" * 260: b"cannot be written"},+ )++ with pytest.raises(OSError):+ skill.to_directory(folder, overwrite=existing)++ if existing:+ assert {p.name: p.read_bytes() for p in folder.iterdir()} == {+ "old.txt": b"original"+ }+ else:+ assert not folder.exists()+ assert sorted(p.name for p in tmp_path.iterdir()) == (+ ["review"] if existing else []+ )++[email protected]("restore_fails", [False, True])+def test_export_retains_old_files_if_installation_fails(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, restore_fails: bool+):+ folder = tmp_path / "review"+ folder.mkdir()+ (folder / "old.txt").write_bytes(b"original")+ skill = Skill(name="review", description="Review", instructions="# Review\n")+ rename = Path.rename+ attempts = 0++ def fail_install(source: Path, target: str | os.PathLike[str]) -> Path:+ nonlocal attempts+ if Path(target) == folder:+ attempts += 1+ if attempts == 1 or restore_fails:+ raise OSError("Destination unavailable")+ return rename(source, target)++ monkeypatch.setattr(Path, "rename", fail_install)+ with pytest.raises(OSError) as error:+ skill.to_directory(folder, overwrite=True)++ originals = list(tmp_path.rglob("old.txt"))+ assert len(originals) == 1+ assert originals[0].read_bytes() == b"original"+ if restore_fails:+ assert str(originals[0].parent) in str(error.value)+ else:+ assert originals[0] == folder / "old.txt"+ assert sorted(p.name for p in tmp_path.iterdir()) == ["review"]++def test_to_directory_refuses_a_symlink(tmp_path: Path):skill = Skill(name="review", description="Review", instructions="# Review\n")elsewhere = tmp_path / "elsewhere"