Skip to main content

monkeyfs 🐒

Filesystem interception via monkey-patching.

Patches open(), os.listdir(), os.stat(), and 30+ other stdlib functions to route through a virtual or isolated filesystem. Patches are applied lazily on first patch() call and are inert outside the context. Uses contextvars for async-safe isolation between concurrent tasks. Zero dependencies.

Install

pip install monkeyfs

Quick example

from monkeyfs import VirtualFS, patch

vfs = VirtualFS({})

with patch(vfs):
    with open("data.csv", "w") as f:
        f.write("name,score\nalice,98\nbob,87\n")

    import os
    print(os.listdir("/"))        # ['data.csv']
    print(os.path.getsize("data.csv"))  # 30

    with open("data.csv") as f:
        print(f.read())           # name,score\nalice,98\nbob,87\n

Not a security boundary

monkeyfs is a cooperative routing layer, not a sandbox. It rebinds stdlib functions so that Python code asking for a file gets the one the active filesystem holds -- and that is the whole of it. Only Python-level file operations are intercepted: ctypes, subprocess, socket, mmap, sqlite3 and any C extension talk to the OS directly and reach the host filesystem untouched. monkeyfs.suspend() is an ordinary importable that turns the routing off from inside a patched block.

So the PermissionError -- outside root below is a routing decision, not a wall -- useful for keeping cooperative code inside its lane, and worth nothing against code that is trying to leave. Confining untrusted code is the job of whatever controls the import surface around it -- sandtrap in this stack -- or of an OS-level boundary such as a container or a VM. monkeyfs is what those hand the confined code to read and write; it is not what keeps the code confined.

IsolatedFS

Restricts file operations to a root directory on the real filesystem:

from monkeyfs import IsolatedFS, patch

isolated = IsolatedFS(root="/tmp/sandbox")

with patch(isolated):
    with open("notes.txt", "w") as f:
        f.write("hello")          # Written to /tmp/sandbox/notes.txt

    open("/etc/passwd")           # PermissionError -- outside root

ReadOnlyFS

Wraps any filesystem and blocks all write operations:

from monkeyfs import VirtualFS, ReadOnlyFS, patch

vfs = VirtualFS({})
vfs.write("data.csv", b"a,b,c")

ro = ReadOnlyFS(vfs)
with patch(ro):
    print(open("data.csv").read())  # a,b,c
    open("new.txt", "w")           # PermissionError

MountFS

Routes operations to different filesystems by path prefix:

from monkeyfs import VirtualFS, MountFS, ReadOnlyFS, patch

base = VirtualFS({})
overlay = VirtualFS({})
overlay.write("summary.md", b"# Chapter 1")

fs = MountFS(base, {"/chapters": ReadOnlyFS(overlay)})

with patch(fs):
    # Writes go to base
    with open("app.py", "w") as f:
        f.write("print('hi')")

    # Reads from /chapters go to the overlay
    print(open("/chapters/summary.md").read())  # # Chapter 1

    # Writes to /chapters are blocked (read-only)
    open("/chapters/new.md", "w")  # PermissionError

The backend protocol

A backend is any object with the right methods -- no inheritance, no base class. monkeyfs's backend protocol and termish's FileSystem protocol are the same sixteen methods with the same signatures, including the ranged read(path, offset=0, size=-1). open() is what monkeyfs provides over a backend rather than something it asks for -- a file object synthesized from read, write and stat, lazy in binary read modes -- and a backend that has a better one (a real directory, where fileno() and mmap work) may offer its own, which monkeyfs prefers. The agreement between the two libraries is a convention enforced by tests in both, not a shared import: a third package would cost both of them their zero-dependency line for twenty lines of protocol.

So a filesystem written for either library works under the other, and under monkeyfs it is a Python open() for free. The conformance kit says whether yours is one:

from monkeyfs import check_filesystem

check_filesystem(MyFileSystem())   # an empty one; it writes and cleans up

It raises AssertionError naming the method and what was expected of it -- including the ranged-read cases a backend that accepts offset and size and quietly ignores them would otherwise pass.

Part of the agex stack

monkeyfs provides filesystem interception for sandtrap and agex, giving sandboxed agent code an isolated virtual filesystem. VirtualFS accepts any dict-like backing store -- including a kvgit worktree for a versioned filesystem with commit/rollback. A store that offers get_many(*keys), as kvgit worktrees do, has its metadata read in one batched call rather than one per file.

Documentation

  • API Reference -- public API, FileSystem protocol, patched functions

Development

uv sync --extra dev
uv run pytest

License

MIT

Metadata

Release files for monkeyfs 0.2.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for monkeyfs 0.2.3
File Size Uploaded
monkeyfs-0.2.3.tar.gz 136.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for monkeyfs 0.2.3
File Interpreter ABI Platform
monkeyfs-0.2.3-py3-none-any.whl Python 3 none any Details

Total release size: 208.4 kB

Release files / monkeyfs-0.2.3.tar.gz

Download URL monkeyfs-0.2.3.tar.gz
Size 136.5 kB
Tags Source
SHA-256 checksum
How to use checksums
96cde5716bf0edb3d408cdd90a31aff5512f8538fbbecd4553ae2e94a34e9aa5
BLAKE2b-256 checksum
How to use checksums
1b78ae91f9e60e950a06d7e8523918d79298705a7c08c9d48e33d1bff1d1c70e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.14

Release files / monkeyfs-0.2.3-py3-none-any.whl

Download URL monkeyfs-0.2.3-py3-none-any.whl
Size 71.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
995384e3d3e9f415f8f24f4875171367e2d8699580f36cbac61976e41a8ea748
BLAKE2b-256 checksum
How to use checksums
1ea882b7945ae2f6d59717195acd89522a9a0b9a4e34e5f0e9047620c65a777e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.14

Release history Release notifications | RSS feed

0.2.7

2 release files

0.2.6

2 release files

0.2.5

2 release files

0.2.4

2 release files

This release

0.2.3 This release

2 release files

0.2.2

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.11

2 release files

0.1.9

2 release files

0.1.8

2 release files

0.1.7

2 release files

0.1.6

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page