Filesystem sandbox toolset for PydanticAI agents with LLM-friendly errors
Project description
pydantic-ai-filesystem-sandbox
Filesystem sandbox toolset for PydanticAI agents with LLM-friendly errors.
Why This Package?
When building LLM agents that interact with the filesystem, you need:
- Sandboxing - Restrict which directories the agent can access
- Read/Write Control - Fine-grained permissions per path
- LLM-Friendly Errors - Error messages that help the LLM correct its behavior
- Approval Integration - Works with human-in-the-loop approval flows
Architecture
This package separates concerns into two layers:
- Sandbox - Security boundary for permission checking and path resolution
- FileSystemToolset - File I/O tools that use Sandbox
┌─────────────────────────────────────────────────────────┐
│ Application Layer │
│ │
│ Sandbox (Policy) ApprovalToolset │
│ ├── path configs ├── approval callbacks │
│ ├── can_read/can_write └── session memory │
│ └── needs_approval() │
│ │
│ FileSystemToolset │
│ └── uses Sandbox │
└──────────────────────────────────────────────────────────┘
Installation
pip install pydantic-ai-filesystem-sandbox
Quick Start
from pydantic_ai import Agent
from pydantic_ai_filesystem_sandbox import (
FileSystemToolset,
Sandbox,
SandboxConfig,
PathConfig,
)
# Configure sandbox paths
config = SandboxConfig(paths={
"input": PathConfig(root="./data/input", mode="ro"), # Read-only
"output": PathConfig(root="./data/output", mode="rw"), # Read-write
})
# Create the sandbox (security boundary)
sandbox = Sandbox(config)
# Create the toolset (file I/O tools)
toolset = FileSystemToolset(sandbox)
# Use with PydanticAI agent
agent = Agent("openai:gpt-4", toolsets=[toolset])
Simple Usage
For simple cases, use the factory method:
from pydantic_ai_filesystem_sandbox import FileSystemToolset
# Single directory with read-write access
toolset = FileSystemToolset.create_default("./data", mode="rw")
agent = Agent("openai:gpt-4", toolsets=[toolset])
Configuration
PathConfig Options
| Option | Type | Default | Description |
|---|---|---|---|
root |
str | required | Root directory path |
mode |
"ro" | "rw" | "ro" | Access mode |
suffixes |
list[str] | None | None | Allowed file extensions (None = all) |
max_file_bytes |
int | None | None | Maximum file size limit |
write_approval |
bool | True | Require approval for writes |
read_approval |
bool | False | Require approval for reads |
Example Configuration
config = SandboxConfig(paths={
# Read-only input - any file type
"input": PathConfig(
root="./data/input",
mode="ro",
),
# Read-write output - only markdown and text
"output": PathConfig(
root="./data/output",
mode="rw",
suffixes=[".md", ".txt"],
max_file_bytes=1_000_000, # 1MB limit
),
# Config files - read-only, requires approval
"config": PathConfig(
root="./config",
mode="ro",
read_approval=True,
),
})
Available Tools
The toolset provides seven tools to the agent:
read_file
Read a text file from the sandbox.
Path format: 'sandbox_name/relative/path'
Parameters:
- path: str (required)
- max_chars: int (default: 20,000)
- offset: int (default: 0)
write_file
Write a text file to the sandbox (requires mode="rw"). Parent directories are created automatically.
Path format: 'sandbox_name/relative/path'
Parameters:
- path: str (required)
- content: str (required)
edit_file
Edit a file by replacing exact text (requires mode="rw").
Path format: 'sandbox_name/relative/path'
Parameters:
- path: str (required)
- old_text: str (required) - must match exactly and be unique
- new_text: str (required)
delete_file
Delete a file from the sandbox (requires mode="rw").
Path format: 'sandbox_name/relative/path'
Parameters:
- path: str (required)
move_file
Move or rename a file within the sandbox (requires mode="rw" for both source and destination). Parent directories are created automatically.
Path format: 'sandbox_name/relative/path'
Parameters:
- source: str (required)
- destination: str (required)
copy_file
Copy a file within the sandbox. Source can be read-only, destination requires mode="rw". Parent directories are created automatically.
Path format: 'sandbox_name/relative/path'
Parameters:
- source: str (required)
- destination: str (required)
list_files
List files matching a glob pattern.
Parameters:
- path: str (default: "." for all sandboxes)
- pattern: str (default: "**/*")
LLM-Friendly Errors
All errors include guidance on what IS allowed:
# PathNotInSandboxError
"Cannot access 'secret/file.txt': path is outside sandbox.
Readable paths: input, output"
# PathNotWritableError
"Cannot write to 'input/file.txt': path is read-only.
Writable paths: output"
# SuffixNotAllowedError
"Cannot access 'output/data.json': suffix '.json' not allowed.
Allowed suffixes: .md, .txt"
# FileTooLargeError
"Cannot read 'output/huge.txt': file too large (5,000,000 bytes).
Maximum allowed: 1,000,000 bytes"
# EditError
"Cannot edit 'output/file.txt': text not found in file.
Searched for: 'old text...'"
Approval Integration
Works with pydantic-ai-blocking-approval for human-in-the-loop:
from pydantic_ai_filesystem_sandbox import (
ApprovableFileSystemToolset, Sandbox, SandboxConfig, PathConfig
)
from pydantic_ai_blocking_approval import ApprovalToolset, ApprovalController
# Create sandbox and toolset
config = SandboxConfig(paths={
"output": PathConfig(root="./output", mode="rw", write_approval=True),
})
sandbox = Sandbox(config)
toolset = ApprovableFileSystemToolset(sandbox)
# Wrap with approval
controller = ApprovalController(mode="interactive")
approved_toolset = ApprovalToolset(
inner=toolset,
approval_callback=controller.approval_callback,
memory=controller.memory,
)
agent = Agent(..., toolsets=[approved_toolset])
ApprovableFileSystemToolset extends FileSystemToolset with needs_approval() (returns ApprovalResult) and get_approval_description() for the approval UI.
Using the Sandbox Directly
The Sandbox class can be used independently for permission checking:
sandbox = Sandbox(config)
# Check permissions
if sandbox.can_write("output/file.txt"):
resolved = sandbox.resolve("output/file.txt")
# ... perform operation
# Query boundaries
print(sandbox.readable_roots) # ["input", "output"]
print(sandbox.writable_roots) # ["output"]
# Check approval requirements
sandbox.needs_write_approval("output/file.txt") # True/False
ReadResult
The read_file tool returns a ReadResult object:
class ReadResult(BaseModel):
content: str # The file content read
truncated: bool # True if more content exists
total_chars: int # Total file size in characters
offset: int # Starting position used
chars_read: int # Characters actually returned
This allows agents to handle large files by reading in chunks:
# First read
result = toolset.read("input/large.txt", max_chars=10000)
if result.truncated:
# Continue reading
result2 = toolset.read("input/large.txt", max_chars=10000, offset=10000)
API Reference
Configuration
SandboxConfig- Top-level configuration with named pathsPathConfig- Configuration for a single sandbox path
Classes
Sandbox- Security boundary for permission checking and path resolutionFileSystemToolset- PydanticAI AbstractToolset with file I/O toolsApprovableFileSystemToolset- FileSystemToolset with approval protocol support
Errors
SandboxError- Base class for all sandbox errorsPathNotInSandboxError- Path outside sandbox boundariesPathNotWritableError- Write to read-only pathSuffixNotAllowedError- File extension not allowedFileTooLargeError- File exceeds size limitEditError- Edit operation failed (text not found or not unique)
Types
ReadResult- Result of read operations with metadata
License
MIT
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pydantic_ai_filesystem_sandbox-0.7.0.tar.gz.
File metadata
- Download URL: pydantic_ai_filesystem_sandbox-0.7.0.tar.gz
- Upload date:
- Size: 184.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.5.21
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a2f903b84f4330402f1f4519f3dff18c621f13a5a144608691c170069c5b2b58
|
|
| MD5 |
d62e0a7dfa095317eefbe81cb785efc6
|
|
| BLAKE2b-256 |
c7c9572985acaf78f16d103f5883863aea5db32184aa8723302d6f0466b59099
|
File details
Details for the file pydantic_ai_filesystem_sandbox-0.7.0-py3-none-any.whl.
File metadata
- Download URL: pydantic_ai_filesystem_sandbox-0.7.0-py3-none-any.whl
- Upload date:
- Size: 16.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.5.21
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dea1fc6f65c3f10fe00a9775aef02b74017fec8c441ffe578f72fcedec00b926
|
|
| MD5 |
b899a94aab0a32656291c541e2c96a6d
|
|
| BLAKE2b-256 |
47b041594145783cae38e8db86288c9274d502584474ac5ad1e05e77381a481b
|