ls, read_file, write_file, edit_file, glob, and grep. These tools operate through a pluggable backend. The read_file tool natively supports image files (.png, .jpg, .jpeg, .gif, .webp) across all backends, returning them as multimodal content blocks.
The read_file tool natively supports binary files (images, PDFs, audio, video) across all backends, returning a ReadResult with typed content and mimeType.
Sandboxes and the LocalShellBackend also provide an execute tool.
This page explains how to:
- choose a backend,
- route different paths to different backends,
- implement your own virtual filesystem (e.g., S3 or Postgres),
- set permissions on filesystem access,
- add policy hooks, work with binary and multimodal files,
- comply with the backend protocol,
- and update existing backends to v2.
Quickstart
Here are a few prebuilt filesystem backends that you can quickly use with your deep agent:| Built-in backend | Description |
|---|---|
| Default | agent = create_deep_agent(model="google_genai:gemini-3.1-pro-preview") Ephemeral in state. The default filesystem backend for an agent is stored in langgraph state. Note that this filesystem only persists for a single thread. |
| Local filesystem persistence | agent = create_deep_agent(model="google_genai:gemini-3.1-pro-preview", backend=FilesystemBackend(root_dir="/Users/nh/Desktop/")) This gives the deep agent access to your local machine’s filesystem. You can specify the root directory that the agent has access to. Note that any provided root_dir must be an absolute path. |
| Durable store (LangGraph store) | agent = create_deep_agent(model="google_genai:gemini-3.1-pro-preview", backend=StoreBackend()) This gives the agent access to long-term storage that is persisted across threads. This is great for storing longer term memories or instructions that are applicable to the agent over multiple executions. |
| Sandbox | agent = create_deep_agent(model="google_genai:gemini-3.1-pro-preview", backend=sandbox) Execute code in isolated environments. Sandboxes provide filesystem tools plus the execute tool for running shell commands. Choose from Modal, Daytona, Deno, or local VFS. |
| Local shell | agent = create_deep_agent(model="google_genai:gemini-3.1-pro-preview", backend=LocalShellBackend(root_dir=".", env={"PATH": "/usr/bin:/bin"})) Filesystem and shell execution directly on the host. No isolation—use only in controlled development environments. See security considerations below. |
| Composite | Ephemeral by default, /memories/ persisted. The Composite backend is maximally flexible. You can specify different routes in the filesystem to point towards different backends. See Composite routing below for a ready-to-paste example. |
Built-in backends
StateBackend (ephemeral)
- Stores files in LangGraph agent state for the current thread via
StateBackend. - Persists across multiple agent turns on the same thread via checkpoints.
- A scratch pad for the agent to write intermediate results.
- Automatic eviction of large tool outputs which the agent can then read back in piece by piece.
FilesystemBackend (local disk)
FilesystemBackend reads and writes real files under a configurable root directory.
- Reads/writes real files under a configurable
root_dir. - You can optionally set
virtual_mode=Trueto sandbox and normalize paths underroot_dir. - Uses secure path resolution, prevents unsafe symlink traversal when possible, can use ripgrep for fast
grep.
- Local projects on your machine
- CI sandboxes
- Mounted persistent volumes
LocalShellBackend (local shell)
- Extends
FilesystemBackendwith theexecutetool for running shell commands on the host. - Commands run directly on your machine using
subprocess.run(shell=True)with no sandboxing. - Supports
timeout(default 120s),max_output_bytes(default 100,000),env, andinherit_envfor environment variables. - Shell commands use
root_diras the working directory but can access any path on the system.
- Local coding assistants and development tools
- Quick iteration during development when you trust the agent
StoreBackend (LangGraph store)
When deploying to LangSmith Deployment, omit the
store parameter. The platform automatically provisions a store for your agent.StoreBackendstores files in a LangGraphBaseStoreprovided by the runtime, enabling cross‑thread durable storage.
- When you already run with a configured LangGraph store (for example, Redis, Postgres, or cloud implementations behind
BaseStore). - When you’re deploying your agent through LangSmith Deployment (a store is automatically provisioned for your agent).
Namespace factories
A namespace factory controls whereStoreBackend reads and writes data. It receives a LangGraph Runtime and returns a tuple of strings used as the store namespace. Use namespace factories to isolate data between users, tenants, or assistants.
Pass the namespace factory to the namespace parameter when constructing a StoreBackend:
Runtime provides:
-
rt.context— User-supplied context passed via LangGraph’s context schema (for example,user_id) -
rt.serverInfo— Server-specific metadata when running on LangGraph Server (assistant ID, graph ID, authenticated user) -
rt.executionInfo— Execution identity information (thread ID, run ID, checkpoint ID)
The
Runtime argument is available in deepagents>=1.9.1. Earlier 1.9.x releases passed a BackendContext instead — see migrating from BackendContext below. rt.serverInfo and rt.executionInfo require deepagents>=1.9.0.(user_id, thread_id) for per-user per-conversation isolation, or append a suffix like "filesystem" to disambiguate when the same scope uses multiple store namespaces.
Namespace components must contain only alphanumeric characters, hyphens, underscores, dots, @, +, colons, and tildes. Wildcards (*, ?) are rejected to prevent glob injection.
When no namespace factory is provided, the legacy default uses the
assistant_id from LangGraph config metadata. This means all users of the same assistant share the same storage. For multi-user going to production, always provide a namespace factory.CompositeBackend (router)
CompositeBackendroutes file operations to different backends based on path prefix.- Preserves the original path prefixes in listings and search results.
- When you want to give your agent both ephemeral and cross-thread storage, a
CompositeBackendallows you provide both aStateBackendandStoreBackend - When you have multiple sources of information that you want to provide to your agent as part of a single filesystem.
- e.g. You have long-term memories stored under
/memories/in one Store and you also have a custom backend that has documentation accessible at /docs/.
- e.g. You have long-term memories stored under
Specify a backend
- Pass a backend instance to
createDeepAgent({ backend: ... }). The filesystem middleware uses it for all tooling. - The backend must implement
AnyBackendProtocol(BackendProtocolV1orBackendProtocolV2) — for example,new StateBackend(),new FilesystemBackend({ rootDir: "." }),new StoreBackend(). - If omitted, the default is
new StateBackend().
Before version 1.9.0, only
BackendProtocol was supported which is now BackendProtocolV1. V1 backends are automatically adapted to V2 at runtime via adaptBackendProtocol(). No code changes are required to keep using existing V1 backends. To update to v2, see update existing backends to v2.Route to different backends
Route parts of the namespace to different backends. Commonly used to persist/memories/* and keep everything else ephemeral.
/workspace/plan.md→StateBackend(ephemeral)/memories/agent.md→FilesystemBackendunder/deepagents/myagentls,glob,grepaggregate results and show original path prefixes.
- Longer prefixes win (for example, route
"/memories/projects/"can override"/memories/"). - For StoreBackend routing, ensure a store is provided via
create_deep_agent(model=..., store=...)or provisioned by the platform.
Use a virtual filesystem
Build a custom backend to project a remote or database filesystem (e.g., S3 or Postgres) into the tools namespace. Design guidelines:-
Paths are absolute (
/x/y.txt). Decide how to map them to your storage keys/rows. -
Implement
lsandglobefficiently (server-side filtering where available, otherwise local filter). -
For external persistence (S3, Postgres, etc.), return
files_update=None(Python) or omitfilesUpdate(JS) in write/edit results — only in-memory state backends need to return a files update dict. -
Use
lsandglobas the method names. -
All query methods (
ls,read,readRaw,grep,glob) must return structured Result objects (e.g.,LsResult,ReadResult) with an optionalerrorfield. -
Support binary files in
read()by returningUint8Arraycontent with the appropriatemimeType.
- Table
files(path text primary key, content text, mime_type text, created_at timestamptz, modified_at timestamptz) - Map tool operations onto SQL:
lsusesWHERE path LIKE $1 || '%'→ returnLsResultglobfilter in SQL or fetch then apply glob locally → returnGlobResultgrepcan fetch candidate rows by extension or last modified time, then scan lines (skip rows wheremime_typeis binary) → returnGrepResult
Permissions
Use permissions to declaratively control which files and directories the agent can read or write. Permissions apply to the built-in filesystem tools and are evaluated before the backend is called. For the full set of options including rule ordering, subagent permissions, and composite backend interactions, see the permissions guide.Add policy hooks
For custom validation logic beyond path-based allow/deny rules (rate limiting, audit logging, content inspection), enforce enterprise rules by subclassing or wrapping a backend. Block writes/edits under selected prefixes (subclass):Multimodal and binary files
V2 backends support binary files natively. Whenread() encounters a binary file (determined by MIME type from the file extension), it returns a ReadResult with Uint8Array content and the corresponding mimeType. Text files return string content.
Supported MIME types
| Category | Extensions | MIME types |
|---|---|---|
| Images | .png, .jpg/.jpeg, .gif, .webp, .svg, .heic, .heif | image/png, image/jpeg, image/gif, image/webp, image/svg+xml, image/heic, image/heif |
| Audio | .mp3, .wav, .aiff, .aac, .ogg, .flac | audio/mpeg, audio/wav, audio/aiff, audio/aac, audio/ogg, audio/flac |
| Video | .mp4, .webm, .mpeg/.mpg, .mov, .avi, .flv, .wmv, .3gpp | video/mp4, video/webm, video/mpeg, video/quicktime, video/x-msvideo, video/x-flv, video/x-ms-wmv, video/3gpp |
| Documents | .pdf, .ppt, .pptx | application/pdf, application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation |
| Text | .txt, .html, .json, .js, .ts, .py, etc. | text/plain, text/html, application/json, etc. |
Read binary files
FileData format
FileData is the type used to store file content in state and store backends.
fileFormat: "v1" to the backend constructor (e.g., new StoreBackend({ fileFormat: "v1" })).
Migrate from backend factories
Previously, backends likeStateBackend and StoreBackend required a factory function that received a runtime object, because they needed runtime context (state, store) to operate. Backends now resolve this context internally via LangGraph’s get_config(), get_store(), and get_runtime() helpers, so you can pass instances directly.
What changed
| Before (deprecated) | After |
|---|---|
backend=lambda rt: StateBackend(rt) | backend=StateBackend() |
backend=lambda rt: StoreBackend(rt) | backend=StoreBackend() |
backend=lambda rt: CompositeBackend(default=StateBackend(rt), ...) | backend=CompositeBackend(default=StateBackend(), ...) |
backend: (config) => new StateBackend(config) | backend: new StateBackend() |
backend: (config) => new StoreBackend(config) | backend: new StoreBackend() |
Deprecated APIs
| Deprecated | Replacement |
|---|---|
BackendFactory type | Pass a backend instance directly |
BackendRuntime interface | Backends resolve context internally |
StateBackend(runtime, options?) constructor overload | new StateBackend(options?) |
StoreBackend(stateAndStore, options?) constructor overload | new StoreBackend(options?) |
filesUpdate field on WriteResult and EditResult | State writes are now handled internally by the backend |
The factory pattern still works at runtime and emits a deprecation warning. Update your code to use direct instances before the next major version.
Migration example
Migrating from BackendContext
In deepagents>=0.5.2 (Python) and deepagents>=1.9.1 (TypeScript), namespace factories receive a LangGraph Runtime directly instead of a BackendContext wrapper. The old BackendContext form still works via backwards-compatible .runtime and .state accessors, but those accessors emit a deprecation warning and will be removed in deepagents>=0.7.
What changed:
- The factory argument is now a
Runtime, not aBackendContext. - Drop the
.runtimeaccessor — for example,ctx.runtime.context.user_idbecomesrt.server_info.user.identity. - There is no direct replacement for
ctx.state. Namespace info should be read-only and stable for the lifetime of a run, whereas state is mutable and changes step-to-step—deriving a namespace from it risks data ending up under inconsistent keys. If you have a use case that requires reading agent state, please open an issue.
Protocol reference
Backends must implementBackendProtocol.
Required methods:
ls(path: str) -> LsResult- Return entries with at least
path. Includeis_dir,size,modified_atwhen available. Sort bypathfor deterministic output.
- Return entries with at least
read(file_path: str, offset: int = 0, limit: int = 2000) -> ReadResult- Return file data on success. On missing file, return
ReadResult(error="Error: File '/x' not found").
- Return file data on success. On missing file, return
grep(pattern: str, path: Optional[str] = None, glob: Optional[str] = None) -> GrepResult- Return structured matches. On error, return
GrepResult(error="...")(do not raise).
- Return structured matches. On error, return
glob(pattern: str, path: str = "/") -> GlobResult- Return matched files as
FileInfoentries (empty list if none).
- Return matched files as
write(file_path: str, content: str) -> WriteResult- Create-only. On conflict, return
WriteResult(error=...). On success, setpathand for state backends setfiles_update={...}; external backends should usefiles_update=None.
- Create-only. On conflict, return
edit(file_path: str, old_string: str, new_string: str, replace_all: bool = False) -> EditResult- Enforce uniqueness of
old_stringunlessreplace_all=True. If not found, return error. Includeoccurrenceson success.
- Enforce uniqueness of
LsResult(error, entries)—entriesis alist[FileInfo]on success,Noneon failure.ReadResult(error, file_data)—file_datais aFileDatadict on success,Noneon failure.GrepResult(error, matches)—matchesis alist[GrepMatch]on success,Noneon failure.GlobResult(error, matches)—matchesis alist[FileInfo]on success,Noneon failure.WriteResult(error, path, files_update)EditResult(error, path, files_update, occurrences)FileInfowith fields:path(required), optionallyis_dir,size,modified_at.GrepMatchwith fields:path,line,text.FileDatawith fields:content(str),encoding("utf-8"or"base64"),created_at,modified_at. :::
BackendProtocolV2. All query methods return structured Result objects with { error?: string, ...data }.
Required methods
-
ls(path: string) → LsResult- List files and directories in the specified directory (non-recursive). Directories have a trailing
/in their path andis_dir=true. Includeis_dir,size,modified_atwhen available.
- List files and directories in the specified directory (non-recursive). Directories have a trailing
-
read(filePath: string, offset?: number, limit?: number) → ReadResult- Read file content. For text files, content is paginated by line offset/limit (default offset 0, limit 500). For binary files, the full raw
Uint8Arraycontent is returned with themimeTypefield set. On missing file, return{ error: "File '/x' not found" }.
- Read file content. For text files, content is paginated by line offset/limit (default offset 0, limit 500). For binary files, the full raw
-
readRaw(filePath: string) → ReadRawResult- Read file content as raw
FileData. Returns the full file data including timestamps.
- Read file content as raw
-
grep(pattern: string, path?: string | null, glob?: string | null) → GrepResult- Search file contents for a literal text pattern. Binary files (determined by MIME type) are skipped. On failure, return
{ error: "..." }.
- Search file contents for a literal text pattern. Binary files (determined by MIME type) are skipped. On failure, return
-
glob(pattern: string, path?: string) → GlobResult- Return files matching a glob pattern as
FileInfoentries.
- Return files matching a glob pattern as
-
write(filePath: string, content: string) → WriteResult- Create-only semantics. On conflict, return
{ error: "..." }. On success, setpathand for state backends setfilesUpdate={...}; external backends should usefilesUpdate=null.
- Create-only semantics. On conflict, return
-
edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean) → EditResult- Enforce uniqueness of
oldStringunlessreplaceAll=true. If not found, return error. Includeoccurrenceson success.
- Enforce uniqueness of
Optional methods
uploadFiles(files: Array<[string, Uint8Array]>) → FileUploadResponse[]— Upload multiple files (for sandbox backends).downloadFiles(paths: string[]) → FileDownloadResponse[]— Download multiple files (for sandbox backends).
Result types
| Type | Success fields | Error field |
|---|---|---|
ReadResult | content?: string | Uint8Array, mimeType?: string | error |
ReadRawResult | data?: FileData | error |
LsResult | files?: FileInfo[] | error |
GlobResult | files?: FileInfo[] | error |
GrepResult | matches?: GrepMatch[] | error |
WriteResult | path?: string | error |
EditResult | path?: string, occurrences?: number | error |
Supporting types
FileInfo—path(required), optionallyis_dir,size,modified_at.GrepMatch—path,line(1-indexed),text.FileData— File content with timestamps. See FileData format.
Sandbox extension
SandboxBackendProtocolV2 extends BackendProtocolV2 with:
execute(command: string) → ExecuteResponse— Run a shell command in the sandbox.readonly id: string— Unique identifier for the sandbox instance.
Update existing backends to V2
Migration guide
Migration guide
Method renames
| V1 method | V2 method | Return type change |
|---|---|---|
lsInfo(path) | ls(path) | FileInfo[] → LsResult |
read(filePath, offset, limit) | read(filePath, offset, limit) | string → ReadResult |
readRaw(filePath) | readRaw(filePath) | FileData → ReadRawResult |
grepRaw(pattern, path, glob) | grep(pattern, path, glob) | GrepMatch[] | string → GrepResult |
globInfo(pattern, path) | glob(pattern, path) | FileInfo[] → GlobResult |
write(...) | write(...) | Unchanged (WriteResult) |
edit(...) | edit(...) | Unchanged (EditResult) |
Type renames
| V1 type | V2 type |
|---|---|
BackendProtocol | BackendProtocolV2 |
SandboxBackendProtocol | SandboxBackendProtocolV2 |
Adaptation utilities
If you have existing V1 backends that you need to use with V2-only code, use the adaptation functions:The framework auto-adapts V1 backends passed to
createDeepAgent(). Manual adaptation is only needed when calling protocol methods directly.Connect these docs to Claude, VSCode, and more via MCP for real-time answers.

