# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-capability-minimal-mcp-server-isolation-as-insufficient-without-a-syscall-level-read-back-invariant-the-deleg.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-capability-minimal-mcp-server-isolation-as-insufficient-without-a-syscall-level-read-back-invariant-the-deleg.warrant.json
# Markdown SHA-256:   57f7b52d8b8e8f13b65225a07af41449beb892dd1a727e5105ac07a66ebdd85f
# Code AST SHA-256:   2d9c5774276b45857591b03a8eb902671b02aa5425f6c7b3edcd6c5ae39fe302
# Verified Classes:   CapabilityLeakError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import os
from pathlib import Path

class CapabilityLeakError(RuntimeError):
    """Raised when a confined MCP server holds an fd outside its declared capability set."""
    pass

def audit_inherited_fds(pid: int, declared_roots: list[str]) -> None:
    """
    Read-back invariant: every live fd must resolve to a path inside the
    tool's declared capability roots, or be close-on-exec. Fail closed otherwise.
    """
    fd_dir = Path(f"/proc/{pid}/fd")
    if not fd_dir.is_dir():
        raise CapabilityLeakError(f"cannot inspect fd table for pid {pid}")

    declared = [Path(r).resolve() for r in declared_roots]

    for entry in fd_dir.iterdir():
        try:
            target = os.readlink(entry)
        except OSError:
            continue  # fd closed between listing and read; benign race

        if target.startswith(("socket:", "pipe:", "anon_inode:")):
            continue  # not a filesystem capability

        resolved = Path(target).resolve()
        inside = any(resolved == root or root in resolved.parents for root in declared)
        if not inside:
            # A descriptor outside the declared surface is a boundary violation
            # whether or not it is currently writable.
            raise CapabilityLeakError(
                f"fd {entry.name} -> {resolved} escapes declared roots {declared_roots}"
            )

def invoke_tool(pid: int, declared_roots: list[str], call) -> object:
    audit_inherited_fds(pid, declared_roots)
    result = call()
    # Re-audit: a forking tool may have leaked a descriptor during execution.
    audit_inherited_fds(pid, declared_roots)
    return result
