An enterprise AI agent becomes significantly more useful when it can interact with business applications.
Instead of only answering questions, it can retrieve customer records, update CRM entries, create support tickets, query internal databases, and execute operational workflows.
But connecting an LLM to tools introduces an important security problem.
A model's decision to call a tool is not proof that the action is authorized.
Consider a sales assistant connected to a CRM.
A sales representative asks the agent to update an account. The agent identifies the correct tool and generates valid arguments.
The tool call looks technically correct.
However, the requested account belongs to another sales team, and the user does not have permission to modify it.
If the application executes the tool call simply because the model requested it, the agent becomes a path around existing access controls.
The solution is to introduce a permission layer between the agent and its tools.
This layer evaluates who is requesting an action, which resource is involved, what operation is being attempted, and whether additional approval is required.
In this guide, we'll build a small permission layer using Python. We'll implement resource-level authorization, explicit tool registration, approval checks, and audit events, then test the important security boundaries.
1. Why Agent Tool Permissions Need Their Own Layer
Traditional applications usually connect user actions to predefined backend operations.
A user clicks a button, the application validates the request, and the backend checks whether the operation is allowed.
AI agents introduce an additional decision-making component.
The model interprets natural language and decides which tools to invoke.
A simplified workflow looks like this:
User Request | v AI Agent | v Model-Generated Tool Call | v Enterprise API The problem is that the model-generated tool call may not reflect the user's actual permissions.
The model may misunderstand the request, select the wrong resource, or follow malicious instructions embedded in retrieved content.
Even when the model behaves as intended, the connected service account may have broader permissions than the user.
A safer architecture introduces an authorization boundary:
User Request | v AI Agent | v Tool Call Proposal | v Tool Permission Layer | +---- Denied | v Approved Tool Execution | v Enterprise System The agent proposes an action. The permission layer decides whether the action can proceed. This distinction is fundamental to secure agent architecture.
2. Define the Security Requirements
Before writing code, establish what the permission layer must enforce.
For this example, we'll use six requirements:
- Every tool call must have a trusted user identity.
- Only registered tools can execute.
- Tool arguments must be validated.
- Authorization must consider the requested resource.
- High-impact operations must require explicit approval.
- Every execution attempt must produce an audit event.
We'll also enforce tenant isolation. A user from one tenant must not access another tenant's resources, even when the agent knows the resource identifier.
These controls should operate independently of model instructions. A system prompt can tell the model to respect permissions, but it cannot replace backend authorization.
3. Project Setup
We'll use Python 3.11 or later and Pydantic for argument validation.
Create this project structure:
agent-permissions/ | |-- models.py |-- permissions.py |-- tools.py |-- executor.py |-- test_permissions.py | `-- requirements.txt Install the dependencies:
python -m pip install "pydantic>=2,<3" "pytest>=8,<10" Create requirements.txt:
pydantic>=2,<3 pytest>=8,<10 The example uses an in-memory CRM repository so we can focus on authorization. In production, the same concepts can be applied to Salesforce, internal APIs, databases, and other enterprise integrations.
4. Model the User, Resource, and Tool Request
Create models.py: from dataclasses import dataclass from typing import Literal from pydantic import ( BaseModel, ConfigDict, Field, ) @dataclass(frozen=True) class UserContext: user_id: str tenant_id: str roles: frozenset[str] @dataclass(frozen=True) class CustomerRecord: customer_id: str tenant_id: str owner_id: str name: str class ReadCustomerArgs(BaseModel): model_config = ConfigDict( extra="forbid", strict=True, ) customer_id: str = Field(min_length=1) class UpdateCustomerArgs(BaseModel): model_config = ConfigDict( extra="forbid", strict=True, ) customer_id: str = Field(min_length=1) name: str = Field(min_length=1) class ToolRequest(BaseModel): model_config = ConfigDict( extra="forbid", strict=True, ) tool_name: Literal[ "read_customer", "update_customer", ] arguments: dict The user context is created by trusted application infrastructure. It should come from an authenticated session or verified identity token, not from a value supplied by the LLM.
The customer record includes a tenant identifier and owner. The tool request represents a proposed action, not an authorized operation. That distinction becomes important when we implement execution.
5. Implement Resource-Level Authorization
A common mistake is to authorize tools based only on their names.
For example:
if tool_name == "update_customer": allow() This checks whether the operation exists, but not whether the user can modify the specific customer.
Enterprise authorization usually requires additional context.
Create permissions.py:
from models import ( CustomerRecord, UserContext, ) class PermissionDenied(Exception): pass def can_read_customer( user: UserContext, customer: CustomerRecord, ) -> bool: if user.tenant_id != customer.tenant_id: return False if "admin" in user.roles: return True return customer.owner_id == user.user_id def can_update_customer( user: UserContext, customer: CustomerRecord, ) -> bool: if user.tenant_id != customer.tenant_id: return False if "admin" in user.roles: return True return ( "sales" in user.roles and customer.owner_id == user.user_id ) This example combines role-based and resource-based authorization. A tenant administrator can read or update records within the tenant.
A regular user can read records they own. A sales user can update records they own. Users cannot cross tenant boundaries.
Why tenant checks come first
Even administrators should not automatically access resources belonging to another tenant.
A role such as admin should be interpreted within the correct authorization scope.
This prevents a common multi-tenant security mistake where broad roles override tenant isolation.
The example is deliberately simple. Real enterprise policies may also consider departments, account teams, data classification, regional restrictions, and temporary access grants.
6. Create a Controlled Tool Registry
The next step is to define which tools the agent can use. A tool registry provides an explicit list of supported operations.
Create tools.py:
from dataclasses import dataclass from typing import Any, Callable from pydantic import BaseModel from models import ( ReadCustomerArgs, UpdateCustomerArgs, ) @dataclass(frozen=True) class ToolDefinition: name: str schema: type[BaseModel] handler: Callable[..., Any] requires_approval: bool def read_customer_handler( customer_id: str, repository: dict, ): customer = repository[customer_id] return { "customer_id": customer.customer_id, "name": customer.name, } def update_customer_handler( customer_id: str, name: str, repository: dict, ): customer = repository[customer_id] repository[customer_id] = type(customer)( customer_id=customer.customer_id, tenant_id=customer.tenant_id, owner_id=customer.owner_id, name=name, ) return { "customer_id": customer_id, "updated": True, } TOOL_REGISTRY = { "read_customer": ToolDefinition( name="read_customer", schema=ReadCustomerArgs, handler=read_customer_handler, requires_approval=False, ), "update_customer": ToolDefinition( name="update_customer", schema=UpdateCustomerArgs, handler=update_customer_handler, requires_approval=True, ), } Only registered tools can execute. The registry also identifies the expected argument schema and whether an operation requires approval.
This avoids exposing arbitrary Python functions or unrestricted APIs to the model.
Keep tools narrowly scoped
A function such as execute_any_sql provides much more authority than read_customer.
Similarly, a generic HTTP request tool may allow the agent to communicate with destinations unrelated to its intended workflow. Purpose-specific tools are easier to authorize, test, and audit.
7. Implement Approval Checks
Some actions should require explicit human approval. For this example, updating a customer record requires approval. The approval should apply to the specific action and arguments.
A simple approval representation is:
from dataclasses import dataclass @dataclass(frozen=True) class Approval: approval_id: str user_id: str tool_name: str customer_id: str approved_name: str An approval should not be interpreted as general permission to execute any update.
For example, approval to rename customer C-100 to Acme North should not authorize renaming customer C-200.
In a production system, approvals should also include expiration, state, authorized approver identity, and replay protection.
They should be stored in trusted infrastructure. The model must not be able to invent or modify approval records.
8. Build the Permission-Aware Tool Executor
Now we'll combine tool registration, argument validation, authorization, and approval enforcement.
Create executor.py:
from dataclasses import dataclass from typing import Any from pydantic import ValidationError from models import ( CustomerRecord, ToolRequest, UserContext, ) from permissions import ( PermissionDenied, can_read_customer, can_update_customer, ) from tools import TOOL_REGISTRY @dataclass(frozen=True) class Approval: approval_id: str user_id: str tool_name: str customer_id: str approved_name: str @dataclass(frozen=True) class AuditEvent: user_id: str tool_name: str resource_id: str outcome: str class ToolExecutor: def __init__( self, repository: dict[str, CustomerRecord], ): self.repository = repository self.audit_events: list[AuditEvent] = [] def execute( self, user: UserContext, request: ToolRequest, approval: Approval | None = None, ) -> dict[str, Any]: resource_id = "unknown" try: definition = TOOL_REGISTRY.get( request.tool_name ) if definition is None: raise PermissionDenied( "Tool is not registered" ) try: args = definition.schema.model_validate( request.arguments ) except ValidationError as exc: raise PermissionDenied( "Invalid tool arguments" ) from exc resource_id = args.customer_id customer = self.repository.get( resource_id ) if customer is None: raise PermissionDenied( "Resource unavailable" ) if request.tool_name == "read_customer": allowed = can_read_customer( user, customer, ) elif request.tool_name == "update_customer": allowed = can_update_customer( user, customer, ) else: allowed = False if not allowed: raise PermissionDenied( "Operation not authorized" ) if definition.requires_approval: if approval is None: raise PermissionDenied( "Approval required" ) if not ( approval.user_id == user.user_id and approval.tool_name == request.tool_name and approval.customer_id == args.customer_id and approval.approved_name == args.name ): raise PermissionDenied( "Approval does not match" ) result = definition.handler( **args.model_dump(), repository=self.repository, ) self.audit_events.append( AuditEvent( user_id=user.user_id, tool_name=request.tool_name, resource_id=resource_id, outcome="allowed", ) ) return result except Exception: self.audit_events.append( AuditEvent( user_id=user.user_id, tool_name=request.tool_name, resource_id=resource_id, outcome="denied_or_failed", ) ) raise The executor validates the proposed tool call before invoking the handler.
It checks:
- Whether the tool is registered.
- Whether the arguments match the schema.
- Whether the target resource exists.
- Whether the user is authorized.
- Whether required approval matches the operation.
Only after these checks does the handler execute.
Important production limitations
This example demonstrates the authorization boundary, not a complete production approval system.
The Approval object is passed directly to the executor. A production implementation must retrieve and verify approval state from trusted storage.
The example also does not implement approval expiration, single-use consumption, transactional locking, or durable audit storage.
Those controls become essential for high-impact operations.
9. Test Authorized Read Access
Create test_permissions.py:
from models import ( CustomerRecord, ToolRequest, UserContext, ) from executor import ( Approval, ToolExecutor, ) from permissions import PermissionDenied def build_repository(): return { "C-100": CustomerRecord( customer_id="C-100", tenant_id="tenant_a", owner_id="user_1", name="Acme", ), "C-200": CustomerRecord( customer_id="C-200", tenant_id="tenant_a", owner_id="user_2", name="Northwind", ), "C-300": CustomerRecord( customer_id="C-300", tenant_id="tenant_b", owner_id="user_3", name="Globex", ), } def test_owner_can_read_customer(): executor = ToolExecutor( build_repository() ) user = UserContext( user_id="user_1", tenant_id="tenant_a", roles=frozenset({"sales"}), ) request = ToolRequest( tool_name="read_customer", arguments={ "customer_id": "C-100" }, ) result = executor.execute( user, request, ) assert result["name"] == "Acme" The user owns the requested customer record. The authorization check succeeds.
10. Test Unauthorized Resource Access
Next, verify that the same user cannot access another user's customer record.
import pytest def test_user_cannot_read_other_owner(): executor = ToolExecutor( build_repository() ) user = UserContext( user_id="user_1", tenant_id="tenant_a", roles=frozenset({"sales"}), ) request = ToolRequest( tool_name="read_customer", arguments={ "customer_id": "C-200" }, ) with pytest.raises(PermissionDenied): executor.execute( user, request, ) The tool exists. The arguments are valid. The resource exists. But the user does not have permission to read it. The operation is denied. This demonstrates why validating the tool name and argument schema is not enough.
11. Test Cross-Tenant Isolation
Tenant isolation should remain effective even when a user has an administrative role.
def test_admin_cannot_cross_tenant(): executor = ToolExecutor( build_repository() ) user = UserContext( user_id="admin_1", tenant_id="tenant_a", roles=frozenset({"admin"}), ) request = ToolRequest( tool_name="read_customer", arguments={ "customer_id": "C-300" }, ) with pytest.raises(PermissionDenied): executor.execute( user, request, ) The user is an administrator within tenant_a. The requested customer belongs to tenant_b. The operation is rejected. A broad role must not silently override tenant boundaries.
12. Test Approval Enforcement
Now verify that an authorized user cannot perform a write operation without approval.
def test_update_requires_approval(): executor = ToolExecutor( build_repository() ) user = UserContext( user_id="user_1", tenant_id="tenant_a", roles=frozenset({"sales"}), ) request = ToolRequest( tool_name="update_customer", arguments={ "customer_id": "C-100", "name": "Acme North", }, ) with pytest.raises(PermissionDenied): executor.execute( user, request, ) assert ( executor.repository["C-100"].name == "Acme" ) The user has permission to update the customer. However, the operation requires approval. Without approval, the executor rejects the request. The record remains unchanged.
Test an approved update
def test_approved_update_succeeds(): executor = ToolExecutor( build_repository() ) user = UserContext( user_id="user_1", tenant_id="tenant_a", roles=frozenset({"sales"}), ) request = ToolRequest( tool_name="update_customer",Source:https://dev.to/arthur_doss/building-a-tool-permission-layer-for-enterprise-ai-agents-4em2Related posts
Photo and Video Permissions Rejection on Google Play: Fix It
"Grep Your Own Git Log Before You Trust an AI-Generated Release Note"
Building a Verification Record Schema for Fire-Alarm, Power-Loss, and Manual-Release States
Keep a Release Log for Your Analytics: 7 Changes That Moved the Numbers, Only One of Them Real
