Shell tools

The beta agent-framework-tools Python package provides shell execution and environment-awareness tools through the agent_framework.tools namespace.

Tool Use it when
LocalShellTool Commands are trusted or individually approved and should run in the agent process's host environment.
DockerShellTool Model-generated shell commands need OCI-container isolation.
ShellEnvironmentProvider The model needs the active shell family, operating system, working directory, and installed CLI versions.
ShellPolicy You want an allow-list or deny-list pre-filter before approval or execution.

Warning

Model-generated shell commands are untrusted. Validate and approve them before execution. Use the least-privileged execution tier that supports the task.

Install the package

dotnet add package Microsoft.Agents.AI.Tools.Shell --prerelease

Use local shell and environment awareness

LocalShellExecutor supports stateless and persistent modes. ShellEnvironmentProvider probes the active environment and adds authoritative shell guidance to the agent context.

ShellPolicy is also available for command pre-filtering. A dedicated runnable DockerShellExecutor sample isn't currently published.

Install the package

pip install agent-framework-tools --pre

The package installs psutil to terminate child process trees when an execution times out.

Use LocalShellTool

LocalShellTool runs commands directly on the host. It defaults to a persistent shell, a 30-second timeout, separate 64-KiB retained allowances for standard output and standard error, and working-directory re-anchoring. Agent calls through as_function() require approval by default. Direct calls to run() don't request approval.

Direct calls to run() return a ShellResult with separate stdout, stderr, exit_code, duration_ms, truncated, and timed_out fields. When the shell runs through OpenAI Responses or Foundry hosting, Agent Framework preserves standard output, standard error, exit outcomes, and timeout outcomes across provider continuation. Nonzero exits remain failures, standard error remains separate, and a timeout doesn't appear as a successful exit.

Set positive max_stdout_bytes and max_stderr_bytes values to change the independent retained-output limits for LocalShellTool or DockerShellTool. These settings limit retained output, not how much a command can produce. Truncation notices and UTF-8 replacement can make returned text slightly larger than the configured raw-byte allowance.

OpenAI provider-hosted shell transcript items remain informational, even when a local shell executor is configured. Only a well-formed explicit local_shell_call, or a shell call marked with environment.type="local", enters the local function and approval path. Configuring LocalShellTool alone doesn't cause provider-hosted shell calls to execute on the host.

Use mode="stateless" when each call should run in a fresh process. Use the AGENT_FRAMEWORK_SHELL environment variable or the shell constructor argument to override the resolved shell.

On Windows, bare executable names for shells and container runtimes resolve only from absolute PATH entries. The current directory and empty, relative, drive-relative, or drive-less rooted PATH entries aren't searched. Pass an absolute executable path when the required program isn't on an absolute PATH entry. This behavior prevents a same-named file in the application working directory from shadowing the installed executable.

Persistent commands are serialized. After output overflow, or after a timeout that leaves the session unrecoverable, a queued command starts in a fresh shell and loses shell-local variables, functions, and working-directory changes from the terminated session. A gracefully interrupted POSIX timeout can retain the existing shell and its state. On Windows, a timeout always closes the current persistent shell, even if the interrupted command emits its completion marker.

Calling close() rejects commands queued before or during shutdown instead of restarting the shell. A later call can open a fresh session.

Important

LocalShellTool isn't a sandbox. Human approval adds a review gate, but it doesn't isolate the shell. Disabling approval for agent calls requires acknowledge_unsafe=True.

Restrict commands with ShellPolicy

ShellPolicy applies regular-expression allow and deny lists to command text before execution. Deny rules take precedence. It doesn't inspect what the shell ultimately executes or restrict file access.

Warning

The sample disables human approval and is only suitable for an isolated, disposable environment without secrets or valuable data. Command substitutions, such as $(...) and backticks, can pass simple allow-list patterns. Patterns that only match the start of a command can also allow extra operations. Use separately enforced isolation and restricted permissions for production. Human review can add a check, but it doesn't isolate the shell.

Prefer string patterns. Python compiles strings with the regex engine and applies a one-second budget to each match. A deny-list timeout denies the command, and an allow-list timeout doesn't grant permission. A precompiled regex.Pattern uses the same bound. A precompiled standard-library re.Pattern preserves its flags but can't be interrupted, so avoid expensive or ambiguous expressions in that form.

Add ShellEnvironmentProvider

ShellEnvironmentProvider probes the shell family, version, operating system, working directory, and selected CLI versions, then injects that information before the agent runs. The default probe list is git, node, python, and docker.

Use DockerShellTool

DockerShellTool requires Docker or Podman on PATH. The defaults disable networking, run as a non-root user, use a read-only root filesystem, drop capabilities, limit memory to 512 MiB, and cap the container at 256 processes.

from agent_framework.tools import DockerShellTool

async with DockerShellTool(
    image="mcr.microsoft.com/azurelinux/base/core:3.0",
    approval_mode="never_require",
) as shell:
    result = await shell.run("uname -a && id")
    print(result.stdout)

The default image is mcr.microsoft.com/azurelinux/base/core:3.0. Pass docker_binary="podman" to use Podman. A dedicated runnable DockerShellTool sample isn't currently published.

Use unsafe_extra_run_args only when no dedicated constructor option exists. These tokens are appended verbatim to the Docker or Podman command and can weaken or bypass the configured isolation and resource limits. Keep them developer-controlled and never populate them from user or model output. Use the corresponding DockerShellTool constructor option instead whenever one is available.

Choose an execution tier

Scenario Tool Isolation boundary
Trusted development commands LocalShellTool None; human approval is enabled by default
Untrusted shell commands DockerShellTool OCI container with default isolation flags
Untrusted generated code without a shell Hyperlight CodeAct Hyperlight microVM

Go provides local shell execution and environment probing through tool/shelltool. See Use the local shell tool.

DockerShellTool guidance isn't currently available for Go.

Use shell tools with Harness Agent

Plain agents and HarnessAgent use the same two-part shell setup: register the executor's function as a tool, and add ShellEnvironmentProvider when the model should receive shell, operating-system, working-directory, and CLI-version context. HarnessAgent doesn't create or own a shell executor:

using System.IO;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Tools.Shell;
using Microsoft.Extensions.AI;

await using var shell = new LocalShellExecutor(new LocalShellExecutorOptions
{
    WorkingDirectory = Directory.GetCurrentDirectory(),
    Timeout = LocalShellExecutor.DefaultTimeout,
});

AIAgent agent = chatClient.AsHarnessAgent(new HarnessAgentOptions
{
    AIContextProviders = [new ShellEnvironmentProvider(shell)],
    ChatOptions = new ChatOptions
    {
        Tools = [shell.AsAIFunction(requireApproval: true)],
    },
});

AsAIFunction defaults to the name run_shell and requireApproval: true. LocalShellExecutor defaults to persistent mode, a 64-KiB cap per output stream, and no timeout; the example explicitly uses the recommended 30-second LocalShellExecutor.DefaultTimeout. ShellEnvironmentProviderOptions defaults to probing git, dotnet, node, python, and docker, with a five-second timeout per probe.

Create one persistent executor per user session and dispose it when the session ends. Don't share it across users or concurrent conversations because working directory, environment, shell history, background jobs, and the command queue are shared. ShellPolicy is only a pre-filter; keep approval enabled, use least-privileged credentials, and prefer DockerShellExecutor when commands require a stronger isolation boundary.

Shell tools are available from the prerelease Microsoft.Agents.AI.Tools.Shell package. HarnessAgent is available from Microsoft.Agents.AI.Harness.

For a plain agent, create the shell function with client.get_shell_tool(func=shell.as_function()) and add ShellEnvironmentProvider separately. create_harness_agent performs both steps when you pass shell_executor:

from agent_framework import create_harness_agent
from agent_framework.tools import LocalShellTool, ShellEnvironmentProviderOptions

async with LocalShellTool() as shell:
    agent = create_harness_agent(
        client=client,
        shell_executor=shell,
        shell_environment_provider_options=ShellEnvironmentProviderOptions(
            probe_tools=("git", "python"),
        ),
    )

    session = agent.create_session()
    response = await agent.run("Inspect the current repository.", session=session)

shell_executor is opt-in and must expose as_function(). The factory adds the shell tool and ShellEnvironmentProvider only when the client implements SupportsShellTool; otherwise it logs a warning and skips both. shell_environment_provider_options is optional and is used only with shell_executor.

LocalShellTool defaults to persistent mode, a 30-second timeout, separate 64-KiB limits for standard output and standard error, working-directory re-anchoring, and approval_mode="always_require". Because Harness tool approval is enabled by default, pass an AgentSession to run. The caller owns the executor lifecycle; use async with or call close(), and create one persistent tool per user session. Don't share mutable shell state across users or concurrent conversations.

The host shell isn't a sandbox. Keep approval enabled, use least-privileged credentials, and use DockerShellTool for container isolation. Disabling approval requires approval_mode="never_require" and acknowledge_unsafe=True; ShellPolicy alone isn't a security boundary.

create_harness_agent is released in agent-framework-core. Shell integration is provided by the pre-release agent-framework-tools package and emits an ExperimentalWarning when enabled.

The Go harness doesn't add a shell tool by default. Add the local shell tool to agent.Config.Tools and its environment provider to agent.Config.ContextProviders before passing the configuration to harness.AgentConfig. The helper retains these caller-supplied components and adds the harness defaults.

See Use the local shell tool for setup and approval requirements.