Home AI SkillsAI Agent Tool Calling on Linux: Build a Safe Runner

AI Agent Tool Calling on Linux: Build a Safe Runner

by Knowledge Base Linux
AI agent tool calling Linux

An AI agent that can run shell commands is powerful and dangerous in equal measure: one careless tool call can delete files, exfiltrate data, or change production state. AI agent tool calling on Linux needs a safe runner, a layer that validates every call, confines it to approved tools and arguments, and logs everything for review. This guide shows how to build that runner in Python: a small, explicit allowlist, argument validation, timeouts, and sandboxing, without any framework magic hiding the security decisions.

By the end, you will have a runner that accepts a tool name and arguments from an agent, rejects anything not on the allowlist, executes only safe commands with strict timeouts, and records every call. The pattern works for coding agents, sysadmin assistants, and automation agents alike.

AI agent tool calling Linux illustration

Prerequisites for a Safe AI Agent Tool Runner

You need a Linux server or workstation with Python 3.11 or newer, a clear list of the tasks your agent should perform, and a separate account or directory for agent work. Do not run an agent tool runner as root, and do not point it at production directories until the allowlist and logging have been tested with harmless tools.

Understand the threat model first. The agent may be tricked by prompt injection in tool output, a malicious file, or a web page it reads. The runner must therefore treat the agent’s tool calls as untrusted input, even when the agent itself is trusted, because its instructions can be manipulated by data it processes.

Step 1: Define an Explicit Tool Allowlist

Start with the smallest set of tools that does the job, and define each tool’s allowed arguments explicitly. A disk usage tool, for example, should accept only a path under an approved directory, not an arbitrary path. Write the registry as plain data, not as code the agent can modify:

import os, subprocess, shlex

ALLOWED_BASE = "/srv/agent-work"
TOOLS = {
    "disk_usage": {"command": ["du", "-sh"], "arg_kind": "path"},
    "list_files": {"command": ["ls", "-la"], "arg_kind": "path"},
    "read_file": {"command": ["cat"], "arg_kind": "path"},
}

Notice what is missing: no generic shell tool, no rm, no curl to arbitrary URLs, and no command that accepts a free-form string. Every tool the agent can call should be one you would be comfortable running on a stranger’s input, because that is effectively what prompt injection turns it into.

Step 2: Validate Arguments Before Execution

Validate every argument against its kind before running anything. For path arguments, resolve symlinks and confirm the result stays under the approved base directory. This blocks directory traversal and symlink escapes, which are the classic ways an allowlisted tool becomes a file disclosure tool:

def safe_path(arg):
    full = os.path.realpath(os.path.join(ALLOWED_BASE, arg))
    if os.path.commonpath([full, ALLOWED_BASE]) != ALLOWED_BASE:
        raise ValueError("Path outside allowed directory")
    return full

def run_tool(name, arg):
    if name not in TOOLS:
        raise ValueError(f"Unknown tool: {name}")
    spec = TOOLS[name]
    if spec["arg_kind"] == "path":
        arg = safe_path(arg)
    result = subprocess.run(
        spec["command"] + [arg],
        capture_output=True, text=True, timeout=30,
    )
    return result.stdout, result.stderr, result.returncode

Never build a command string and pass it to a shell. Use a list of arguments with shell=False, which is the default for subprocess.run, so metacharacters in arguments are treated as data, not as commands. Add a timeout to every call so a hanging tool cannot block the agent forever.

Step 3: Add Approval for Destructive or Irreversible Actions

Some actions are legitimate but should never run without a human decision: deleting files, restarting services, changing firewall rules, or writing outside the work directory. Put these in a separate category that requires explicit approval, and log the approval alongside the call:

APPROVAL_REQUIRED = {"restart_service", "delete_file"}

def run_tool_with_approval(name, arg, approved=False):
    if name in APPROVAL_REQUIRED and not approved:
        return "APPROVAL_REQUIRED", "", 0
    return run_tool(name, arg)

In an interactive setup, approval can be a prompt to the operator. In an automated setup, approval should come from a separate policy, such as a signed request or a second system, never from the agent asserting its own approval. If the agent can approve its own destructive actions, the approval step is theatre, not security.

Step 4: Log Every Tool Call and Sandbox the Runner

Log the tool name, arguments, timestamp, output size, and exit code for every call, including rejected ones. Rejected calls are often the first sign of prompt injection, so they belong in the log just as much as successful calls:

import json, datetime

def logged_run(name, arg, approved=False):
    started = datetime.datetime.now(datetime.timezone.utc).isoformat()
    try:
        out, err, code = run_tool_with_approval(name, arg, approved)
    except Exception as exc:
        out, err, code = "", str(exc), 1
    entry = {"time": started, "tool": name, "arg": arg,
             "approved": approved, "code": code,
             "output_chars": len(out)}
    with open("/var/log/agent-tools.jsonl", "a") as fh:
        fh.write(json.dumps(entry) + "\n")
    return out, err, code

Finally, run the whole agent process as a dedicated, unprivileged user with its own working directory, and consider a container or systemd sandbox for stronger isolation. A systemd-run scope with ProtectSystem=strict and PrivateTmp=yes is a cheap, effective extra layer for a local runner, and a container is the right choice when the agent processes untrusted content regularly.

Troubleshooting AI Agent Tool Calling on Linux

If legitimate calls are rejected, read the log first: the tool name, the resolved path, and the reason for rejection usually show whether the allowlist is too narrow or the agent is passing an unexpected argument format. Widen the allowlist deliberately, one tool at a time, rather than adding a generic shell escape hatch.

If the agent repeatedly tries a tool that does not exist, its system prompt probably describes tools that the runner does not implement. Keep the prompt and the registry in sync, and generate the prompt’s tool list from the registry so they cannot drift apart.

If a tool hangs, check the timeout and the output size: a tool that produces unbounded output can exhaust memory even with a timeout. Cap output with a size limit in the runner, and truncate what is returned to the agent, so a huge directory listing cannot flood the agent’s context.

Conclusion

AI agent tool calling on Linux is safe only when the runner, not the agent, decides what is allowed: an explicit allowlist, validated arguments, shell-free execution, approval for irreversible actions, and a complete log. Build the runner first, test it with hostile inputs, and only then connect a capable model to it. For related agent work, see our guides on AI agent memory for sysadmin tasks and building an AI agent with LangChain on Linux. The official function calling documentation explains how models express tool calls that a runner like this can consume.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.