Autonomous agents scare security teams. They call APIs. They access databases. They send emails. You cannot give them root access. You need a firewall for tool calls.
This tutorial builds a permission middleware. It sits between your agent logic and the actual tools. It checks every action against a policy file. If the action violates the rule, the agent stops. This mimics the Little Snitch approach for network traffic but applies it to agent actions.
Prerequisites
You need Python 3.9+ and langchain. Install dependencies:
pip install langchain pydantic
1. Define the Security Policy
Create a policy.json file. This acts as your allowlist. Do not use regex unless necessary. Exact matches are safer. Keep this file read-only for the agent process.
``json
{
"allowed_tools": ["search_web", "read_calendar"],
"blocked_domains": ["internal-api.corp.com"],
"max_cost_per_call": 0.05
}
`2. Build the Middleware Wrapper
Write a wrapper class. It intercepts the
invoke method. It validates the tool name and arguments. This is where you enforce the rules defined in step 1.`python
import json
from langchain.tools import BaseTool
class SecureTool(BaseTool):
def __init__(self, tool: BaseTool, policy: dict):
super().__init__()
self._tool = tool
self.policy = policy
def _run(self, *args, **kwargs):
if self.name not in self.policy["allowed_tools"]:
raise PermissionError(f"Tool {self.name} blocked")
# Check domain restrictions here
return self._tool.run(*args, kwargs)
`3. Integrate with the Agent
Wrap your existing tools before passing them to the agent executor. Do not modify the agent core. Modify the input layer. This ensures you can swap policies without rewriting agent logic.
`python
safe_tools = [SecureTool(t, policy) for t in original_tools]
agent = initialize_agent(safe_tools, llm)
``4. Log Every Decision
Security requires audit trails. Log allowed and blocked attempts. Send these logs to a separate stream. Do not mix them with application logs. You need to know when the agent tried to break the rules.
Common pitfalls
Latency spikes. Validation adds time. Keep policy checks O(1). Do not query a database during the middleware check. Load the policy into memory at startup.
Context leakage. Agents might try to encode data in tool arguments to bypass filters. Validate argument content, not just tool names. Check URLs and file paths explicitly.
False positives. Blocking legitimate actions frustrates users. Start in "audit mode" where you log violations without blocking. Switch to "enforce mode" after 48 hours of monitoring.
Recursive loops.** If the agent tries to call a tool to bypass the block, you need a recursion limit. Set a max depth of 3 for retry logic. Prevent the agent from arguing with the guardrail.
Next step
Learn how to implement OAuth delegation for agents so they act on behalf of users without storing credentials: https://example.com/oauth-agents