Skip to content

Filesystem Tools

File operations tools.

Available Functions

Function Description
read_file Read file contents
write_file Write/overwrite file
append_file Append to file
list_directory List directory contents
file_info Get file metadata
delete_file Delete file
move_file Move/rename file
copy_file Copy file

Quick Example

from mamba_agents.tools import (
    read_file,
    write_file,
    list_directory,
    file_info,
)

# Read file
content = read_file("config.json")

# Write file
write_file("output.txt", "Hello!")

# List directory
entries = list_directory("/project", recursive=True)

# Get file info
info = file_info("README.md")
print(f"Size: {info.size}")

Security

from mamba_agents.tools.filesystem import FilesystemSecurity

security = FilesystemSecurity(
    sandbox_mode=True,
    base_directory="/safe/path",
    allowed_extensions=[".txt", ".json"],
)

# Use with tools
content = read_file("data.txt", security=security)

API Reference

read_file

read_file(
    path: str,
    encoding: str = "utf-8",
    security: FilesystemSecurity | None = None,
) -> str

Read contents of a file.

PARAMETER DESCRIPTION
path

Path to the file to read.

TYPE: str

encoding

Character encoding (default: utf-8).

TYPE: str DEFAULT: 'utf-8'

security

Optional security context for path validation.

TYPE: FilesystemSecurity | None DEFAULT: None

RETURNS DESCRIPTION
str

The file contents as a string.

RAISES DESCRIPTION
FileNotFoundError

If the file does not exist.

PermissionError

If access is denied or path is outside sandbox.

Source code in src/mamba_agents/tools/filesystem/read.py
def read_file(
    path: str,
    encoding: str = "utf-8",
    security: FilesystemSecurity | None = None,
) -> str:
    """Read contents of a file.

    Args:
        path: Path to the file to read.
        encoding: Character encoding (default: utf-8).
        security: Optional security context for path validation.

    Returns:
        The file contents as a string.

    Raises:
        FileNotFoundError: If the file does not exist.
        PermissionError: If access is denied or path is outside sandbox.
    """
    if security is not None:
        validated_path = security.validate_path(path)
        security.validate_read(validated_path)
    else:
        validated_path = Path(path)
        if not validated_path.exists():
            raise FileNotFoundError(f"File not found: {path}")

    return validated_path.read_text(encoding=encoding)

write_file

write_file(
    path: str,
    content: str,
    encoding: str = "utf-8",
    create_parents: bool = False,
    security: FilesystemSecurity | None = None,
) -> str

Write or overwrite a file.

PARAMETER DESCRIPTION
path

Path to the file to write.

TYPE: str

content

Content to write to the file.

TYPE: str

encoding

Character encoding (default: utf-8).

TYPE: str DEFAULT: 'utf-8'

create_parents

Create parent directories if they don't exist.

TYPE: bool DEFAULT: False

security

Optional security context for path validation.

TYPE: FilesystemSecurity | None DEFAULT: None

RETURNS DESCRIPTION
str

The path of the written file.

RAISES DESCRIPTION
PermissionError

If access is denied or path is outside sandbox.

FileNotFoundError

If parent directory doesn't exist and create_parents is False.

Source code in src/mamba_agents/tools/filesystem/write.py
def write_file(
    path: str,
    content: str,
    encoding: str = "utf-8",
    create_parents: bool = False,
    security: FilesystemSecurity | None = None,
) -> str:
    """Write or overwrite a file.

    Args:
        path: Path to the file to write.
        content: Content to write to the file.
        encoding: Character encoding (default: utf-8).
        create_parents: Create parent directories if they don't exist.
        security: Optional security context for path validation.

    Returns:
        The path of the written file.

    Raises:
        PermissionError: If access is denied or path is outside sandbox.
        FileNotFoundError: If parent directory doesn't exist and create_parents is False.
    """
    validated_path = security.validate_path(path) if security is not None else Path(path)

    if create_parents:
        validated_path.parent.mkdir(parents=True, exist_ok=True)

    validated_path.write_text(content, encoding=encoding)
    return str(validated_path)

list_directory

list_directory(
    path: str,
    recursive: bool = False,
    max_depth: int = 2,
    security: FilesystemSecurity | None = None,
) -> list[dict[str, Any]]

List contents of a directory.

PARAMETER DESCRIPTION
path

Path to the directory to list.

TYPE: str

recursive

Whether to list recursively.

TYPE: bool DEFAULT: False

max_depth

Maximum depth for recursive listing.

TYPE: int DEFAULT: 2

security

Optional security context for path validation.

TYPE: FilesystemSecurity | None DEFAULT: None

RETURNS DESCRIPTION
list[dict[str, Any]]

List of dictionaries with file/directory information.

RAISES DESCRIPTION
FileNotFoundError

If the directory does not exist.

NotADirectoryError

If the path is not a directory.

PermissionError

If access is denied or path is outside sandbox.

Source code in src/mamba_agents/tools/filesystem/directory.py
def list_directory(
    path: str,
    recursive: bool = False,
    max_depth: int = 2,
    security: FilesystemSecurity | None = None,
) -> list[dict[str, Any]]:
    """List contents of a directory.

    Args:
        path: Path to the directory to list.
        recursive: Whether to list recursively.
        max_depth: Maximum depth for recursive listing.
        security: Optional security context for path validation.

    Returns:
        List of dictionaries with file/directory information.

    Raises:
        FileNotFoundError: If the directory does not exist.
        NotADirectoryError: If the path is not a directory.
        PermissionError: If access is denied or path is outside sandbox.
    """
    validated_path = security.validate_path(path) if security is not None else Path(path)

    if not validated_path.exists():
        raise FileNotFoundError(f"Directory not found: {path}")

    if not validated_path.is_dir():
        raise NotADirectoryError(f"Not a directory: {path}")

    entries: list[dict[str, Any]] = []

    def process_entry(entry_path: Path, current_depth: int) -> None:
        """Process a single directory entry."""
        if current_depth > max_depth:
            return

        try:
            stat = entry_path.stat()
            entry_info = {
                "name": entry_path.name,
                "path": str(entry_path),
                "is_file": entry_path.is_file(),
                "is_dir": entry_path.is_dir(),
                "size": stat.st_size if entry_path.is_file() else None,
                "modified": datetime.fromtimestamp(stat.st_mtime).isoformat(),
            }
            entries.append(entry_info)

            # Recurse into directories if requested
            if recursive and entry_path.is_dir():
                for child in entry_path.iterdir():
                    process_entry(child, current_depth + 1)

        except PermissionError:
            # Skip entries we can't access
            entries.append(
                {
                    "name": entry_path.name,
                    "path": str(entry_path),
                    "error": "Permission denied",
                }
            )

    for entry in validated_path.iterdir():
        process_entry(entry, 1)

    return entries

file_info

file_info(
    path: str, security: FilesystemSecurity | None = None
) -> dict[str, Any]

Get file or directory metadata.

PARAMETER DESCRIPTION
path

Path to the file or directory.

TYPE: str

security

Optional security context for path validation.

TYPE: FilesystemSecurity | None DEFAULT: None

RETURNS DESCRIPTION
dict[str, Any]

Dictionary with file metadata including:

dict[str, Any]
  • name: The file name
dict[str, Any]
  • path: Full path
dict[str, Any]
  • is_file: Whether it's a file
dict[str, Any]
  • is_dir: Whether it's a directory
dict[str, Any]
  • size: Size in bytes (files only)
dict[str, Any]
  • modified: Modification time (ISO format)
dict[str, Any]
  • created: Creation time (ISO format)
RAISES DESCRIPTION
FileNotFoundError

If the file does not exist.

PermissionError

If access is denied or path is outside sandbox.

Source code in src/mamba_agents/tools/filesystem/info.py
def file_info(
    path: str,
    security: FilesystemSecurity | None = None,
) -> dict[str, Any]:
    """Get file or directory metadata.

    Args:
        path: Path to the file or directory.
        security: Optional security context for path validation.

    Returns:
        Dictionary with file metadata including:
        - name: The file name
        - path: Full path
        - is_file: Whether it's a file
        - is_dir: Whether it's a directory
        - size: Size in bytes (files only)
        - modified: Modification time (ISO format)
        - created: Creation time (ISO format)

    Raises:
        FileNotFoundError: If the file does not exist.
        PermissionError: If access is denied or path is outside sandbox.
    """
    validated_path = security.validate_path(path) if security is not None else Path(path)

    if not validated_path.exists():
        raise FileNotFoundError(f"File not found: {path}")

    stat = validated_path.stat()

    return {
        "name": validated_path.name,
        "path": str(validated_path),
        "is_file": validated_path.is_file(),
        "is_dir": validated_path.is_dir(),
        "size": stat.st_size,
        "modified": datetime.fromtimestamp(stat.st_mtime).isoformat(),
        "created": datetime.fromtimestamp(stat.st_ctime).isoformat(),
    }