Skip to main content
AG-Kit’s file system tools provide a comprehensive and reliable way for your agents to interact with files. With support for transactions, different backends, and a unified toolkit, it’s designed for building robust agents that perform file-based tasks.

What You Can Do

Use this toolkit to give your agent the ability to:
  • Perform Atomic Operations: Safely modify multiple files at once with automatic rollback on failure.
  • Manage Files & Directories: Create, read, update, delete, and list files and directories.
  • Search the Filesystem: Find files by name (glob) or content (grep).
  • Run in Secure Environments: Choose between local, in-memory, and sandboxed backends to match your security needs.

Core Concepts

  1. FilesystemToolkit: This is the main entry point. It bundles a collection of file-related tools (read_file, write_file, etc.) that are ready to be used by an agent.
  2. FileOperator (Backend): This is the engine that performs the actual file operations. You can choose from three backends:
    • LocalFileOperator: For high-performance access to the local filesystem.
    • InMemoryFileOperator: For fast, isolated testing in a virtual filesystem.
    • SandboxFileOperator: For secure execution in an isolated container, ideal for handling untrusted code.

Quick Start

from agkit.tools import FilesystemToolkit, LocalFileOperator
import os

# 1. Choose a backend and create the toolkit
operator = LocalFileOperator()
fs_toolkit = FilesystemToolkit(
    name="fs",
    context={"working_directory": os.getcwd(), "fs_operator": operator}
)

# 2. Get a tool and use it
write_tool = fs_toolkit.get_tool("write_file")
await write_tool.invoke({
    "file_path": "greeting.txt",
    "content": "Hello"
})

Key Feature: Atomic Transactions

For complex tasks like code generation, you often need to modify multiple files. If one step fails, you risk leaving the project in a broken state. Transactions solve this by ensuring that all file operations succeed or none of them do. If any operation inside withTransaction fails, all changes are automatically rolled back.
from agkit.tools.fs.operator.transaction import with_transaction
from agkit.tools import LocalFileOperator

operator = LocalFileOperator()

try:
    await with_transaction(operator, async def tx:
        # These operations are now atomic
        await tx.write_file('src/component.py', '# New component code')
        await tx.write_file('src/__init__.py', 'from .component import *')
        # If this next one fails, the two files above will be reverted.
        await tx.write_file('setup.py', 'invalid python')
    )
except Exception as error:
    print(f'Transaction failed and was rolled back: {error}')
For more advanced transaction control, see the API Reference.

Core Operations

Here are the most common operations you can perform with the toolkit.

Writing and Creating Files

The write_file tool creates a new file or overwrites an existing one. It automatically creates parent directories if they don’t exist.
result = await fs_toolkit.get_tool('write_file').invoke({
    'file_path': 'src/utils/helpers.py',
    'content': 'def new_util():\n    pass'
})
# result.data: { 'file_path': 'src/utils/helpers.py', 'bytes_written': 28 }

Reading Files

The read_file tool reads the entire content of a specified file.
result = await fs_toolkit.get_tool('read_file').invoke({
    'file_path': 'package.json'
})
# result.data: '{\n  "name": "my-app",\n  ...'
print(result.data.content)

Editing Files

The edit_file tool performs a search-and-replace on a file’s content. It’s useful for making targeted changes.
result = await fs_toolkit.get_tool('edit_file').invoke({
    'file_path': 'src/config.py',
    'old_str': 'API_ENDPOINT = "http://dev.example.com"',
    'new_str': 'API_ENDPOINT = "http://prod.example.com"'
})
# result.data: { 'file_path': 'src/config.py', 'replacements_made': 1 }

Listing Directory Contents

The ls tool lists the files and subdirectories within a given path.
result = await fs_toolkit.get_tool('ls').invoke({'path': 'src'})
# result.data: { 
#   'entries': [
#     { 'name': 'components', 'type': 'directory', 'size': 0 },
#     { 'name': 'utils', 'type': 'directory', 'size': 0 },
#     { 'name': 'index.py', 'type': 'file', 'size': 1024 }
#   ]
# }
print([entry.name for entry in result.data.entries])

Finding Files by Pattern (Glob)

The glob tool finds all files and directories matching a specific pattern, which is useful for discovering files before processing them.
result = await fs_toolkit.get_tool('glob').invoke({
    'pattern': '**/*.test.py'
})
# result.data: { 
#   'matches': [
#     'src/utils/helpers_test.py',
#     'src/components/button_test.py',
#     'tests/integration_test.py'
#   ]
# }
print('Test files found:', result.data.matches)

Searching File Content (Grep)

The grep tool searches for a specific text pattern (including regex) within files in a given directory. It’s perfect for finding where a function is called or locating specific comments.
result = await fs_toolkit.get_tool('grep').invoke({
    'pattern': 'TODO|FIXME',
    'path': 'src'
})
# result.data: {
#   'matches': [
#     { 'file': 'src/utils/helpers.py', 'line_number': 42, 'line_content': '  # TODO: Optimize this function' },
#     { 'file': 'src/components/button.py', 'line_number': 15, 'line_content': '  # FIXME: Handle edge case' }
#   ]
# }

if len(result.data.matches) > 0:
    print('Matches found:')
    for match in result.data.matches:
        print(f"- {match.file}:{match.line_number}: {match.line_content.strip()}")
For detailed input/output schemas of all tools, see the API Reference.

Workflow Example: Agent Integration

Integrate the FilesystemToolkit directly into your agent to give it powerful file manipulation capabilities.
from agkit.tools import FilesystemToolkit, LocalFileOperator

fs_toolkit = FilesystemToolkit(
    name="fs",
    context={"working_directory": os.getcwd(), "fs_operator": LocalFileOperator()}
)

tools=fs_toolkit.get_tools()

Next Steps