DEV Community

Cover image for Day 32/90:Enforcing Tool Authorization in AI Agents: Why the Model Must Never Decide Who Can Act
Rimsha Kanwal
Rimsha Kanwal

Posted on Edited on

Day 32/90:Enforcing Tool Authorization in AI Agents: Why the Model Must Never Decide Who Can Act

AI agents become powerful when they can use tools:
search a knowledge base, create a ticket, query an API, send a message, or update a record. But that same capability introduces a serious security risk.

An LLM can decide which tool to call and what arguments to provide. It should never decide whether the caller is authorized to perform that action.

This article covers a practical authorization pattern for AI agents: the model proposes an action, the application validates it, and trusted backend code makes the final authorization decision.

The core principle

A secure agent architecture separates model reasoning from permission enforcement:

The model may propose a tool call. Only trusted application code may authorize and execute it.

This distinction matters because prompts are not security boundaries. A user request, retrieved document, API response, web page, or another agent can influence the model’s behavior. Even if the model follows instructions most of the time, it cannot be the final control point for privileged actions.

The authorization decision must be deterministic, testable, and enforced outside the model.

Why prompts are not enough

A system prompt such as this is useful, but it is not sufficient:

Do not call destructive tools unless the user explicitly approves the action.
Enter fullscreen mode Exit fullscreen mode

The model may follow that instruction, but it can still be manipulated through indirect prompt injection. For example, a retrieved document could contain text that encourages the agent to call a ticket-deletion tool or access another user’s data.

OWASP identifies tool misuse and exploitation as a major agentic-AI risk. Agents can misuse legitimate tools due to prompt injection, misalignment, unsafe delegation, or ambiguous instructions, leading to data exposure or unauthorized actions.

The solution is not to remove tools from agents. It is to constrain what each tool can do, who can invoke it, and under what conditions it may execute.

The authorization flow

A robust tool-calling flow should look like this:

User request
      ↓
LLM proposes a tool call
      ↓
Schema validation
      ↓
Business-rule validation
      ↓
Authorization policy
      ↓
Allowed → Execute tool
Denied → Return structured error
Enter fullscreen mode Exit fullscreen mode

Each stage has a distinct responsibility:

Stage Responsibility
LLM Interpret the request and propose a tool call
Schema validation Ensure the payload has the correct structure and types
Business validation Ensure the request is logically valid
Authorization policy Ensure the authenticated user is allowed to perform the action
Tool execution Perform the action using least-privilege credentials

A request can pass schema validation and still be unauthorized. For example, this payload may be structurally valid:

{
  "tool": "delete_ticket",
  "arguments": {
    "ticket_id": "123"
  }
}
Enter fullscreen mode Exit fullscreen mode

But if the caller is a standard user, the backend must reject it before the tool runs.

What to authorize

Tool authorization should not be a single yes-or-no check. A strong policy evaluates several dimensions:

  • Identity: Is the user authenticated?
  • Role: Does the user’s role permit this operation?
  • Scope: Does the user hold the required permission scope?
  • Resource ownership: Can the user access the target resource?
  • Arguments: Are the parameters valid and within allowed limits?
  • Operation risk: Is this a read-only action or a consequential write action?
  • Rate limits: Is the user exceeding an allowed usage threshold?
  • Approval requirement: Does the action require explicit human confirmation?

For example, a user may be allowed to search documents and create a draft ticket, but not delete tickets, access another user’s tickets, or call administrative tools.

Example implementation

The following Python-style example shows a simple policy layer that runs before tool execution.

from dataclasses import dataclass

@dataclass
class ToolRequest:
    user_id: str
    role: str
    tool_name: str
    arguments: dict

class ToolAuthorizationError(Exception):
    pass

TOOL_POLICIES = {
    "search_documents": {
        "roles": {"user", "admin"},
        "scopes": {"documents:read"},
    },
    "create_ticket": {
        "roles": {"user", "admin"},
        "scopes": {"tickets:create"},
    },
    "delete_ticket": {
        "roles": {"admin"},
        "scopes": {"tickets:delete"},
    },
}

def authorize_tool_call(request: ToolRequest) -> None:
    policy = TOOL_POLICIES.get(request.tool_name)

    if policy is None:
        raise ToolAuthorizationError("Unknown tool")

    if request.role not in policy["roles"]:
        raise ToolAuthorizationError(
            f"Role '{request.role}' is not authorized "
            f"to call '{request.tool_name}'"
        )

    required_scopes = policy["scopes"]
    user_scopes = get_user_scopes(request.user_id)

    if not required_scopes.issubset(user_scopes):
        missing = required_scopes - user_scopes
        raise ToolAuthorizationError(
            f"Missing required scopes: {missing}"
        )
Enter fullscreen mode Exit fullscreen mode

The important detail is the order of checks:

validate_schema(arguments)
authorize_tool_call(request)
execute_tool(tool_name, arguments)
Enter fullscreen mode Exit fullscreen mode

Authorization must happen before execution, not after the tool has already changed external state.

Apply least privilege

Every tool should receive only the permissions it needs—nothing more.

For a document-support assistant, a sensible starting model might be:

Tool Permission Risk level
Search documents documents:read Low
Retrieve document metadata documents:read Low
Create draft ticket tickets:create Medium
Update ticket tickets:update Medium
Delete ticket tickets:delete High
Access another tenant’s data None High

This follows the principle of least privilege: limit the permissions granted to tools and downstream systems to the minimum necessary to reduce the impact of undesirable actions. genai.owasp

A read-only search tool should not share credentials with a tool that can delete records. A ticket-creation tool should not be able to modify user accounts. An administrative tool should not be available to every authenticated user.

Validate arguments, not just permissions

Authorization and validation are related but separate controls.

Authorization answers:

“Is this user allowed to call this tool?”

Argument validation answers:

“Is this specific request valid and safe?”

For example, a user may be authorized to create tickets, but the backend should still validate:

  • The ticket title is present and within a reasonable length
  • The priority is one of the allowed values
  • The assigned team exists
  • The user cannot assign the ticket to another user without permission
  • The request does not contain unexpected fields
  • The requested resource belongs to the caller’s tenant or organization

OWASP recommends validating proposed tool calls against user permissions and session context, validating tool-specific parameters, and enforcing permissions in execution code outside the model.

Use explicit approval for high-impact actions

Not every tool call needs human approval. Read-only retrieval can often run automatically. But consequential actions deserve a stronger control path.

Examples include:

  • Creating a customer-facing ticket
  • Sending an email
  • Updating a production record
  • Deleting data
  • Making a payment
  • Inviting a user to a workspace
  • Changing permissions
  • Calling an external third-party service

For these actions, the agent can prepare a structured action proposal, show it to the user, and execute it only after explicit approval.

Agent: I can create a ticket with the following details:

Title: Login page returns 500 error
Priority: High
Team: Platform
Description: Users report a 500 error after submitting credentials.

Approve creation?
Enter fullscreen mode Exit fullscreen mode

The user’s approval should be recorded and bound to the exact proposed action. The backend should then revalidate the request before execution.

MCP and tool security

If you are building with the Model Context Protocol (MCP), authorization becomes even more important because tools can expose real application capabilities to an AI client.

MCP treats tools as arbitrary code execution and requires appropriate caution. The specification states that users must explicitly consent to and understand data access and operations before tools are invoked. modelcontextprotocol

MCP servers should:

  • Validate all tool inputs
  • Apply access controls
  • Rate-limit tool invocations
  • Sanitize tool outputs
  • Return only tools permitted by the caller’s authorization
  • Revalidate authorization on every request

The MCP specification allows the available tool set to vary based on the authorization presented with a request. This supports a model where users only see and invoke tools their granted scopes permit.

A good default is to expose only low-risk discovery and read operations initially, then progressively grant additional scopes when a user explicitly needs them.

Design test cases

Authorization is only credible if it is tested. Build test cases that cover both allowed and denied paths.

Test case Expected result
Authenticated user searches documents Allowed
Standard user creates a ticket Allowed
Standard user deletes a ticket Denied
Unauthenticated request calls a tool Denied
User lacks the required scope Denied
User accesses another user’s resource Denied
Admin deletes a ticket Allowed
Valid arguments but unauthorized role Denied
Unknown tool name Denied
Repeated high-risk calls exceed the rate limit Denied or requires approval
Tool call occurs after approval Allowed
Tool call occurs without approval Denied

The most valuable tests are the cases that look valid but should still fail:

  • Valid JSON with an unauthorized role
  • Valid arguments targeting another user’s resource
  • A permitted tool called with a forbidden operation
  • A valid request repeated beyond its rate limit
  • A high-impact action submitted without approval

Log denials safely

Every authorization decision should produce an auditable event.

For allowed calls, log:

  • User ID or pseudonymous identifier
  • Tool name
  • Request ID
  • Policy decision
  • Relevant scopes
  • Latency
  • Outcome

For denied calls, log:

  • User ID or pseudonymous identifier
  • Requested tool
  • Denial reason
  • Required permission or scope
  • Request ID
  • Timestamp

Avoid logging raw user content, credentials, tokens, or sensitive arguments. Redact or tokenize sensitive fields before persistence.

A denial should return a clear, structured response to the caller:

{
  "status": "denied",
  "reason": "insufficient_permission",
  "required_scope": "tickets:delete"
}
Enter fullscreen mode Exit fullscreen mode

Do not reveal internal policy details, implementation paths, or information that could help an attacker probe the authorization system.

Common mistakes to avoid

  • Treating the model’s tool choice as authorization
  • Relying only on system prompts for security
  • Giving all tools the same service account and broad permissions
  • Allowing the model to choose arbitrary resource IDs
  • Validating JSON but not business rules
  • Skipping authorization for internal tools
  • Caching authorization decisions without considering role or scope changes
  • Logging sensitive arguments or credentials
  • Allowing destructive actions without approval
  • Failing to test denied paths

A particularly dangerous pattern is giving an agent a single highly privileged API key. If the model is manipulated or makes an incorrect decision, that key may allow it to read, modify, or delete data across the system.

Instead, use scoped credentials and separate tool execution paths:

Read-only retrieval → read-only credentials
Ticket creation → limited write credentials
Administrative actions → approval-gated, tightly scoped credentials
Enter fullscreen mode Exit fullscreen mode

A practical architecture

A production-ready design can use the following components:

Client
  ↓
API gateway / authentication
  ↓
Agent orchestration service
  ↓
Tool router
  ↓
Authorization policy engine
  ↓
Tool executor
  ↓
External system
Enter fullscreen mode Exit fullscreen mode

The policy engine should be independent of the LLM. It should receive a structured request containing the authenticated user, requested tool, arguments, and session context, then return a clear allow or deny decision.

This makes the security boundary testable:

def test_standard_user_cannot_delete_ticket():
    request = ToolRequest(
        user_id="user_123",
        role="user",
        tool_name="delete_ticket",
        arguments={"ticket_id": "456"},
    )

    with pytest.raises(ToolAuthorizationError):
        authorize_tool_call(request)
Enter fullscreen mode Exit fullscreen mode

This test does not depend on model output. It directly verifies the security rule.

Key takeaway

An AI agent should be treated as an untrusted decision-maker with a narrowly defined interface to trusted systems.

The model can help interpret intent, select a likely tool, and prepare arguments. But identity, permissions, resource ownership, business rules, rate limits, and approval requirements must be enforced by application code.

The strongest agent designs do not ask, “Can the model call this tool?”

They ask:

“Should this authenticated user be allowed to perform this exact action, with these arguments, in this context?”

That is the difference between an agent that appears capable and an agent that can be safely deployed.

Top comments (7)

Collapse
 
honeykiran profile image
Honey Kiran •

"Prompts are not security boundaries" should be printed on the box of every agent framework.

The pattern we run is the same shape as yours: the model proposes, trusted code disposes. Our version of it for credentials is: the agent may hold the key's handle, never the key — a broker executes the call, the model never sees the secret it is using.

One addition from the incident side: log the proposal and the authorization decision as two separate records. When something goes wrong at 3 AM, the first question is whether the model proposed badly or the authorizer approved badly. Those have completely different fixes, and a single merged log line hides which one you need.

Collapse
 
rimsha_kanwal profile image
Rimsha Kanwal •

That's a really good point! Separating the model's proposal from the authorization decision makes debugging much easier. I also like the credential broker approach, especially keeping actual secrets away from the model. Small design choices like these can make a big difference in building secure agents. Thanks for sharing!

Collapse
 
honeykiran profile image
Honey Kiran •

Glad it landed — and thank you for the series. Day 32 of 90 on agent security is exactly the kind of slow, public building that makes these patterns normal instead of novel.

The two-records habit is the cheapest debugging tool we run: one line for what the model proposed, one line for what the authorizer decided. It costs almost nothing on the good days and pays for itself entirely on the one bad night.

Collapse
 
milochen0418 profile image
Milo Chen •

Nice clear split. One practical tip from building MCP tools: write the tool descriptions for the model, not for people. Say when to use the tool and when not to, because that text is most of what the model sees when it decides to call it. Looking forward to day 32!

Collapse
 
rimsha_kanwal profile image
Rimsha Kanwal •

Thanks, Milo that’s a really useful point. You’re right that tool descriptions are effectively part of the model’s decision context, so they should explain not only what the tool does but also when it should and should not be used.

I also realized that my current Day 32 post leans more toward general tool authorization than MCP itself. I’m going to refine the direction and make the next post more focused on MCP: tools, resources, prompts, authorization, and how they fit into a practical agent architecture. Your tip about writing tool descriptions for the model is definitely going into that.

Collapse
 
milochen0418 profile image
Milo Chen •

Glad it helped, Rimsha! An MCP-focused post sounds great. Looking forward to reading it 🙌

Collapse
 
rimsha_kanwal profile image
Rimsha Kanwal •