ag2-shell-tool
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseShell tools
Shell 工具
When to use
适用场景
Two distinct tools, both named "shell" — pick deliberately:
| Need | Use | Why |
|---|---|---|
| Works with any model provider; full control over what runs and where | | Client-side |
| Provider-managed sandbox (container, network policy) on OpenAI Responses | | Server-side execution. No local subprocess. |
SandboxShellTool有两款名称均为"shell"的不同工具,请按需选择:
| 需求 | 使用工具 | 原因 |
|---|---|---|
| 支持所有模型提供商;完全控制运行内容和运行位置 | | 基于客户端 |
| OpenAI Responses 提供的提供商托管沙箱(容器、网络策略) | | 服务器端执行。无需本地子进程。 |
SandboxShellTool60-second recipe — SandboxShellTool
SandboxShellTool60秒快速上手 — SandboxShellTool
SandboxShellToolpython
from ag2 import Agent
from ag2.config import AnthropicConfig
from ag2.tools import SandboxShellTool
agent = Agent(
"coder",
"You write and run Python code.",
config=AnthropicConfig(model="claude-sonnet-4-6"),
tools=[SandboxShellTool()],
)
reply = await agent.ask("Write a hello world script and run it.")
print(await reply.content())SandboxShellToolAnthropicConfigOpenAIConfig(model="gpt-4.1")GeminiConfig(model="gemini-2.5-pro")ag2[<provider>]ag2-quickstartWith no arguments, defaults to a that creates a temporary working directory (prefixed ) and cleans it up when the process exits. Pass a with a path to use a specific directory:
SandboxShellToolLocalEnvironment()ag2_sandbox_LocalEnvironmentpython
from pathlib import Path
from ag2.tools import LocalEnvironment, SandboxShellTool
SandboxShellTool(LocalEnvironment("/tmp/my_project"))
SandboxShellTool(LocalEnvironment(Path("/tmp/my_project")))When a path is given, the directory is created if it does not exist and is not deleted on exit. Inspect the resolved working directory via .
tool.workdirpython
from ag2 import Agent
from ag2.config import AnthropicConfig
from ag2.tools import SandboxShellTool
agent = Agent(
"coder",
"You write and run Python code.",
config=AnthropicConfig(model="claude-sonnet-4-6"),
tools=[SandboxShellTool()],
)
reply = await agent.ask("Write a hello world script and run it.")
print(await reply.content())SandboxShellToolAnthropicConfigOpenAIConfig(model="gpt-4.1")GeminiConfig(model="gemini-2.5-pro")ag2[<provider>]ag2-quickstart若不传入参数,默认使用,会创建一个临时工作目录(前缀为),并在进程退出时自动清理。你可以传入指定路径的来使用特定目录:
SandboxShellToolLocalEnvironment()ag2_sandbox_LocalEnvironmentpython
from pathlib import Path
from ag2.tools import LocalEnvironment, SandboxShellTool
SandboxShellTool(LocalEnvironment("/tmp/my_project"))
SandboxShellTool(LocalEnvironment(Path("/tmp/my_project")))当指定路径时,若目录不存在则会自动创建,且进程退出时不会被删除。你可以通过查看解析后的工作目录。
tool.workdirSandboxing (LocalEnvironment
+ tool-level filters)
LocalEnvironment沙箱机制(LocalEnvironment
+ 工具级过滤)
LocalEnvironmentFor anything beyond a throwaway demo, lock down what the agent can do. The environment () decides where commands run and carries backend config (, , , ); the tool () decides the agent-facing policy ( / / / ). Filtering is applied in this order on every call:
LocalEnvironmentpathtimeoutmax_outputenv_varsSandboxShellToolallowedblockedignorereadonly- — if set, the command must match at least one prefix. In this restricted mode, shell operators (
allowed,>,>>,|,;,&&,||,`) are also rejected.$( - — if set, the command must not match any prefix. Best-effort only (head-command prefix match; chaining can bypass it).
blocked - — literal path tokens in the command are checked against gitignore-style patterns; matches return
ignore."Access denied: <path>" - Execute via the environment's .
subprocess
python
from ag2.tools import LocalEnvironment, SandboxShellTool
sh = SandboxShellTool(
LocalEnvironment(
path="/tmp/my_project",
timeout=30,
max_output=50_000,
),
allowed=["python", "uv run", "git"],
blocked=["rm -rf", "curl", "wget"],
ignore=["**/.env", "*.key", "secrets/**"],
)除了一次性演示场景,都要限制Agent的操作权限。环境()决定命令的运行位置和后端配置(、、、);工具()决定面向Agent的策略( / / / )。每次调用时会按以下顺序应用过滤规则:
LocalEnvironmentpathtimeoutmax_outputenv_varsSandboxShellToolallowedblockedignorereadonly- — 若设置,命令必须匹配至少一个前缀。在此受限模式下,shell运算符(
allowed、>、>>、|、;、&&、||、`)也会被拒绝。$( - — 若设置,命令不得匹配任何前缀。仅作尽力而为的限制(仅匹配头部命令前缀;命令链可能绕过该限制)。
blocked - — 命令中的字面路径会与gitignore风格的模式进行匹配;匹配到则返回
ignore。"Access denied: <path>" - 通过环境的执行命令。
subprocess
python
from ag2.tools import LocalEnvironment, SandboxShellTool
sh = SandboxShellTool(
LocalEnvironment(
path="/tmp/my_project",
timeout=30,
max_output=50_000,
),
allowed=["python", "uv run", "git"],
blocked=["rm -rf", "curl", "wget"],
ignore=["**/.env", "*.key", "secrets/**"],
)Read-only mode
只读模式
For inspection-only access (, , , , , , , , , …):
catheadtaillsgrepfindgit loggit diffgit statuspython
from ag2.tools import LocalEnvironment, SandboxShellTool
sh = SandboxShellTool(LocalEnvironment(path="/my/codebase"), readonly=True)Pass an explicit to override the built-in read-only allowlist.
allowed=[...]仅用于查看操作(、、、、、、、、等):
catheadtaillsgrepfindgit loggit diffgit statuspython
from ag2.tools import LocalEnvironment, SandboxShellTool
sh = SandboxShellTool(LocalEnvironment(path="/my/codebase"), readonly=True)传入显式的可以覆盖内置的只读允许列表。
allowed=[...]Parameter reference
参数参考
LocalEnvironment| Parameter | Default | Description |
|---|---|---|
| | Working dir. |
| | |
| | Per-command timeout in seconds (returns |
| | Max characters returned (truncated output is suffixed |
| | Extra env vars merged into each command |
SandboxShellTool| Parameter | Default | Description |
|---|---|---|
| | The backend. |
| | Whitelist of command prefixes. |
| | Blacklist of command prefixes (best-effort, not a security boundary) |
| | Gitignore-style path patterns; matches block the command |
| | When |
LocalEnvironment| 参数 | 默认值 | 描述 |
|---|---|---|
| | 工作目录。 |
| | |
| | 单命令超时时间(秒),超时后返回 |
| | 返回内容的最大字符数(截断后的内容会添加后缀 |
| | 合并到每个命令中的额外环境变量 |
SandboxShellTool| 参数 | 默认值 | 描述 |
|---|---|---|
| | 后端环境。 |
| | 命令前缀白名单。 |
| | 命令前缀黑名单(仅作尽力而为的限制,不构成安全边界) |
| | Gitignore风格的路径模式;匹配到则阻止命令执行 |
| | 当 |
Stateful multi-turn workspaces
有状态多轮对话工作区
Files persist in across calls, so the agent can build on prior work:
workdirask()python
from ag2.tools import LocalEnvironment, SandboxShellTool
sh = SandboxShellTool(LocalEnvironment(path="/tmp/counter_demo"))
agent = Agent("coder", "You manage files.", config=config, tools=[sh])
reply1 = await agent.ask("Create counter.txt with value 0")
reply2 = await reply1.ask("Increment the counter by 1")
reply3 = await reply2.ask("Read the counter and tell me the value")文件会在中跨调用持久化,因此Agent可以基于之前的工作继续操作:
workdirask()python
from ag2.tools import LocalEnvironment, SandboxShellTool
sh = SandboxShellTool(LocalEnvironment(path="/tmp/counter_demo"))
agent = Agent("coder", "You manage files.", config=config, tools=[sh])
reply1 = await agent.ask("Create counter.txt with value 0")
reply2 = await reply1.ask("Increment the counter by 1")
reply3 = await reply2.ask("Read the counter and tell me the value")Provider-native ShellTool
(OpenAI Responses only)
ShellTool提供商原生ShellTool
(仅OpenAI Responses可用)
ShellToolShellToolbashUnsupportedToolErrorSandboxShellToolpython
from ag2.config import OpenAIResponsesConfig
from ag2.tools import ShellTool
agent = Agent("devops", config=OpenAIResponsesConfig(model="gpt-4.1"), tools=[ShellTool()])OpenAI lets you configure the execution environment:
python
from ag2.config import OpenAIResponsesConfig
from ag2.tools import ContainerAutoEnvironment, NetworkPolicy, ShellTool
agent = Agent(
"devops",
config=OpenAIResponsesConfig(model="gpt-4.1"),
tools=[
ShellTool(
environment=ContainerAutoEnvironment(
network_policy=NetworkPolicy(allowed_domains=["pypi.org"]),
),
),
],
)Environment options (OpenAI-only):
| Environment | Description |
|---|---|
| Provider-managed container with optional |
| Reference an existing container by ID |
ShellToolbashUnsupportedToolErrorSandboxShellToolpython
from ag2.config import OpenAIResponsesConfig
from ag2.tools import ShellTool
agent = Agent("devops", config=OpenAIResponsesConfig(model="gpt-4.1"), tools=[ShellTool()])OpenAI允许你配置执行环境:
python
from ag2.config import OpenAIResponsesConfig
from ag2.tools import ContainerAutoEnvironment, NetworkPolicy, ShellTool
agent = Agent(
"devops",
config=OpenAIResponsesConfig(model="gpt-4.1"),
tools=[
ShellTool(
environment=ContainerAutoEnvironment(
network_policy=NetworkPolicy(allowed_domains=["pypi.org"]),
),
),
],
)环境选项(仅OpenAI可用):
| 环境 | 描述 |
|---|---|
| 提供商托管的容器,可配置 |
| 通过ID引用现有容器 |
SandboxShellTool
vs ShellTool
SandboxShellToolShellToolSandboxShellTool
vs ShellTool
SandboxShellToolShellTool | | |
|---|---|---|
| Execution | Client-side | Provider-side container |
| Provider support | Any provider | OpenAI Responses only |
| Environment control | Full ( | Limited (provider-dependent) |
| Local FS access | Yes (you choose what's exposed) | No |
| Network control | Via | OpenAI: |
| Import | | |
| | |
|---|---|---|
| 执行方式 | 客户端 | 提供商端容器 |
| 提供商支持 | 所有提供商 | 仅OpenAI Responses |
| 环境控制 | 完全可控( | 有限控制(取决于提供商) |
| 本地文件系统访问 | 是(你选择暴露的内容) | 否 |
| 网络控制 | 通过 | OpenAI: |
| 导入方式 | | |
Going deeper
深入学习
- — full
website/docs/user-guide/tools/local_shell.mdx/SandboxShellToolreference, command-filtering semantics.LocalEnvironment - — provider-native
website/docs/user-guide/tools/builtin_tools.mdx#shellsetup and environment configs.ShellTool - For human-approval gating before each shell call, layer middleware (see
approval_required()).ag2-hitl
- —
website/docs/user-guide/tools/local_shell.mdx/SandboxShellTool完整参考,命令过滤语义说明。LocalEnvironment - — 提供商原生
website/docs/user-guide/tools/builtin_tools.mdx#shell的设置和环境配置说明。ShellTool - 若要在每次shell调用前需要人工审批,可添加中间件(详见
approval_required())。ag2-hitl
Common pitfalls
常见陷阱
- Forgetting sandboxing in production — with no filters runs anything anywhere with a 60s timeout. Set
SandboxShellTool(),allowed, orblockedfor any non-trivial use.readonly - only checks literal paths in the command string — variable substitution, command substitution (
ignore), and dynamic glob expansion are not inspected. Layer in`cat secrets.key`if you also want to block readers.blocked=["cat", "less"] - is best-effort, not a security boundary — it only matches the head command's prefix, so chaining (
blocked) bypassesecho x; rm -rf ~. Useblocked=["rm"]/allowedor an isolated container backend for real isolation.readonly - Trying to use on Anthropic or Gemini — unsupported, will raise
ShellTool. UseUnsupportedToolErrorinstead.SandboxShellTool - Using a hardcoded path that another process is also touching — multiple agents sharing will race. Use
/tmp/my_projectfor parallel runs.tempfile.mkdtemp(prefix="...") - Expecting to access local files — it doesn't; it runs in the provider's container. Use
ShellToolfor anything on your filesystem.SandboxShellTool - Trusting the LLM with shell access — even sandboxed, write s that scope what's allowed and consider pairing with
promptfor destructive operations.approval_required()
- 生产环境中忘记配置沙箱 — 未设置过滤规则的会允许在任意位置执行任意命令,超时时间为60秒。对于非 trivial 的使用场景,务必设置
SandboxShellTool()、allowed或blocked。readonly - 仅检查命令字符串中的字面路径 — 变量替换、命令替换(
ignore)和动态通配符扩展不会被检查。如果你还想阻止读取操作,可以添加`cat secrets.key`。blocked=["cat", "less"] - 仅作尽力而为的限制,不构成安全边界 — 它仅匹配头部命令的前缀,因此命令链(
blocked)可以绕过echo x; rm -rf ~。如需真正的隔离,请使用blocked=["rm"]/allowed或隔离容器后端。readonly - 尝试在Anthropic或Gemini上使用— 不支持,会抛出
ShellTool。请改用UnsupportedToolError。SandboxShellTool - 使用其他进程也在访问的硬编码路径 — 多个Agent共享会导致竞争。并行运行时请使用
/tmp/my_project创建临时目录。tempfile.mkdtemp(prefix="...") - 期望访问本地文件 — 它无法访问本地文件,因为它运行在提供商的容器中。如需访问本地文件系统,请使用
ShellTool。SandboxShellTool - 信任LLM的shell访问权限 — 即使有沙箱保护,也要编写明确限定允许操作范围的,对于破坏性操作,可考虑搭配
prompt中间件。approval_required()