Skip to content

mirascope.tools.system._file_system

FileSystemToolKitConfig

Bases: _ConfigurableToolConfig

Configuration for file_system toolkit

FileOperation

Bases: ConfigurableTool[FileSystemToolKitConfig], ABC

Base class for file system operations.

FileSystemToolKit

Bases: ConfigurableToolKit[FileSystemToolKitConfig]

ToolKit for file system operations. Read, write, list, create, and delete files and directories.

ReadFile

Bases: FileOperation

Tool for reading file contents.

call

call() -> str

Read and return file contents.

Returns:

Name Type Description
str str

File contents or error message if operation fails

Source code in mirascope/tools/system/_file_system.py
def call(self) -> str:
    """Read and return file contents.

    Returns:
        str: File contents or error message if operation fails
    """
    if error := self._validate_path(self.path):
        return error

    if error := self._validate_extension(self.path):
        return error

    file_path = self.base_directory / self.path
    if not file_path.is_file():
        return f"Error: File {self.path} not found"

    try:
        if file_path.stat().st_size > self._get_config().max_file_size:
            return f"Error: File exceeds maximum size of {self._get_config().max_file_size} bytes"

        return file_path.read_text()
    except Exception as e:  # pragma: no cover
        return f"Error reading file: {str(e)}"

WriteFile

Bases: FileOperation

Tool for writing content to a file.

call

call() -> str

Write content to file and return status.

Returns:

Name Type Description
str str

Success message or error message if operation fails

Source code in mirascope/tools/system/_file_system.py
def call(self) -> str:
    """Write content to file and return status.

    Returns:
        str: Success message or error message if operation fails
    """
    if error := self._validate_path(self.path):
        return error

    if error := self._validate_extension(self.path):
        return error

    file_path = self.base_directory / self.path
    try:
        content_size = len(self.content.encode("utf-8"))
        if content_size > self._get_config().max_file_size:
            return f"Error: Content exceeds maximum size of {self._get_config().max_file_size} bytes"

        file_path.parent.mkdir(parents=True, exist_ok=True)
        file_path.write_text(self.content)
        return f"Successfully wrote to {self.path}"
    except Exception as e:  # pragma: no cover
        return f"Error writing file: {str(e)}"

ListDirectory

Bases: FileOperation

Tool for listing directory contents.

call

call() -> str

List directory contents and return formatted string.

Returns:

Name Type Description
str str

Formatted directory listing or error message if operation fails

Source code in mirascope/tools/system/_file_system.py
def call(self) -> str:
    """List directory contents and return formatted string.

    Returns:
        str: Formatted directory listing or error message if operation fails
    """

    if error := self._validate_path(self.path):
        return error

    dir_path = self.base_directory / self.path
    if not dir_path.is_dir():
        return f"Error: Directory {self.path} not found"

    try:
        contents: list[dict[str, str | int | None]] = []
        for item in dir_path.iterdir():
            item_type = "file" if item.is_file() else "directory"
            size = item.stat().st_size if item.is_file() else None
            contents.append(
                {"name": item.name, "type": item_type, "size": size}
            )

        output = f"Contents of {self.path or '.'} :\n"
        for item in contents:
            size_info = (
                f" ({item['size']} bytes)" if item["size"] is not None else ""
            )
            output += f"- {item['name']} [{item['type']}]{size_info}\n"

        return output
    except Exception as e:  # pragma: no cover
        return f"Error listing directory: {str(e)}"

CreateDirectory

Bases: FileOperation

Tool for creating directories.

call

call() -> str

Create directory and return status.

Returns:

Name Type Description
str str

Success message or error message if operation fails

Source code in mirascope/tools/system/_file_system.py
def call(self) -> str:
    """Create directory and return status.

    Returns:
        str: Success message or error message if operation fails
    """
    if error := self._validate_path(self.path):
        return error

    dir_path = self.base_directory / self.path
    try:
        dir_path.mkdir(parents=True, exist_ok=True)
        return f"Successfully created directory {self.path}"
    except Exception as e:
        return f"Error creating directory: {str(e)}"

DeleteFile

Bases: FileOperation

Tool for deleting files.

call

call() -> str

Delete file and return status.

Returns:

Name Type Description
str str

Success message or error message if operation fails

Source code in mirascope/tools/system/_file_system.py
def call(self) -> str:
    """Delete file and return status.

    Returns:
        str: Success message or error message if operation fails
    """
    if error := self._validate_path(self.path):
        return error

    if error := self._validate_extension(self.path):
        return error

    file_path = self.base_directory / self.path
    try:
        if not file_path.exists():
            return f"Error: File {self.path} not found"

        if not file_path.is_file():
            return f"Error: {self.path} is not a file"

        file_path.unlink()
        return f"Successfully deleted {self.path}"
    except Exception as e:  # pragma: no cover
        return f"Error deleting file: {str(e)}"

validate_base_directory

validate_base_directory(v: Path) -> Path

Validates that the base directory exists and is a directory.

Parameters:

Name Type Description Default
v Path

The path to validate

required

Returns:

Name Type Description
Path Path

The validated path

Raises:

Type Description
ValueError

If the path doesn't exist or isn't a directory

Source code in mirascope/tools/system/_file_system.py
@field_validator("base_directory")
def validate_base_directory(cls, v: Path) -> Path:
    """Validates that the base directory exists and is a directory.

    Args:
        v: The path to validate

    Returns:
        Path: The validated path

    Raises:
        ValueError: If the path doesn't exist or isn't a directory
    """
    if not v.exists():
        raise ValueError(f"Base directory {v} does not exist")
    if not v.is_dir():
        raise ValueError(f"{v} is not a directory")
    return v