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

import { FilesystemToolkit, LocalFileOperator } from '@ag-kit/tools';

// 1. Choose a backend and create the toolkit
const operator = new LocalFileOperator();
const fsToolkit = new FilesystemToolkit({
  name: 'fs',
  context: { workingDirectory: process.cwd(), fsOperator: operator },
});

// 2. Get a tool and use it
const writeTool = fsToolkit.getTool('write_file');
await writeTool.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.
import { withTransaction } from '@ag-kit/tools/fs/operator/transaction';
import { LocalFileOperator } from '@ag-kit/tools';

const operator = new LocalFileOperator();

try {
  await withTransaction(operator, async (tx) => {
    // These operations are now atomic
    await tx.writeFile('src/component.js', '// New component code');
    await tx.writeFile('src/index.js', 'import "./component.js";');
    // If this next one fails, the two files above will be reverted.
    await tx.writeFile('package.json', 'invalid json'); 
  });
} catch (error) {
  console.log('Transaction failed and was rolled back:', error.message);
}
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.
const result = await fsToolkit.getTool('write_file').invoke({
  file_path: 'src/utils/helpers.ts',
  content: 'export const newUtil = () => {};'
});
// result.data: { file_path: 'src/utils/helpers.ts', bytes_written: 35 }

Reading Files

The read_file tool reads the entire content of a specified file.
const result = await fsToolkit.getTool('read_file').invoke({
  file_path: 'package.json'
});
// result.data: '{\n  "name": "my-app",\n  ...'
console.log(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.
const result = await fsToolkit.getTool('edit_file').invoke({
  file_path: 'src/config.js',
  old_str: 'API_ENDPOINT = "http://dev.example.com"',
  new_str: 'API_ENDPOINT = "http://prod.example.com"'
});
// result.data: { file_path: 'src/config.js', replacements_made: 1 }

Listing Directory Contents

The ls tool lists the files and subdirectories within a given path.
const result = await fsToolkit.getTool('ls').invoke({ path: 'src' });
// result.data: { 
//   entries: [
//     { name: 'components', type: 'directory', size: 0 },
//     { name: 'utils', type: 'directory', size: 0 },
//     { name: 'index.ts', type: 'file', size: 1024 }
//   ]
// }
console.log(result.data.entries.map(e => e.name));

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.
const result = await fsToolkit.getTool('glob').invoke({
  pattern: '**/*.test.ts'
});
// result.data: { 
//   matches: [
//     'src/utils/helpers.test.ts',
//     'src/components/Button.test.ts',
//     'tests/integration.test.ts'
//   ]
// }
console.log('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.
const result = await fsToolkit.getTool('grep').invoke({
  pattern: 'TODO|FIXME',
  path: 'src'
});
// result.data: {
//   matches: [
//     { file: 'src/utils/helpers.ts', line_number: 42, line_content: '  // TODO: Optimize this function' },
//     { file: 'src/components/Button.tsx', line_number: 15, line_content: '  // FIXME: Handle edge case' }
//   ]
// }

if (result.data.matches.length > 0) {
  console.log('Matches found:');
  result.data.matches.forEach(match => {
    console.log(`- ${match.file}:${match.line_number}: ${match.line_content.trim()}`);
  });
}
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.
import { FilesystemToolkit, LocalFileOperator } from '@ag-kit/tools';

const fsToolkit = new FilesystemToolkit({
  name: 'fs',
  context: { workingDirectory: process.cwd(), fsOperator: new LocalFileOperator() },
});

const tools = fsToolkit.getTools();

Next Steps