Skip to content
Ylabator
Security guideAdvanced

Tool Permissions and Agent Identity

An agent should have its own identity, act for one user at a time, and carry short-lived tokens scoped to one tool server, checked on every call.

5 min read / Updated / Last checked

Format
Security guide · Advanced
Who it is for
Builders and technical founders
You leave with
Issue delegated, audience-bound, short-lived tokens to agents and enforce scope and record ownership at every tool server.

The problem

On May 26, 2025, Invariant Labs published an attack on AI agents connected to GitHub's MCP server. MCP, the Model Context Protocol, is a standard way to plug tools into an agent. The attacker opens an issue in a public repository and hides instructions in it. The victim asks their agent to look at that repository's open issues. The agent reads the planted text, pulls data from the victim's private repositories into its context, and publishes it in a pull request on the public repository, where the attacker can read it [1]. Invariant stressed that the MCP server's code had no bug. The agent did what its access allowed [1].

The agent held the user's access to every repository for a task that needed one. Most AI MVPs wire agents the same way: one API key with broad rights in an environment variable, shared by every user, every agent and every tool. Then any manipulated or mistaken model output can reach everything that key can reach, and the logs cannot say which user or which agent did it.

Prompt-level defenses lower the odds of a bad instruction getting through. Permissions limit what it can do when one does. This guide covers the second half: who the agent is, who it acts for, and what it may touch.

How it works

Every tool call should answer three questions in code: which agent is calling, which user it is acting for, and what this call may do.

Agent identity. Each agent is a registered client with its own ID and credentials, not a shared key. Its actions show up in logs under its own name, and it can be revoked without touching anything else.

Delegation. When an agent acts for a user, the token names both. OAuth 2.0 Token Exchange (RFC 8693) defines this: the token's subject is the user, and the act (actor) claim records that delegation has occurred and identifies the acting party. The RFC separates this from impersonation, where the actor disappears behind the user [3].

Scope. The token's permissions are the intersection of three sets: what the task asks for, what the user may do, and a ceiling set for this agent. An admin's support agent does not inherit admin rights.

Audience and lifetime. Each token is minted for one tool server and lives for minutes. The MCP authorization specification (version 2026-07-28) requires clients to name the target server with a resource parameter, requires servers to check that a token was issued for them, and forbids servers from accepting or passing through tokens meant for anyone else [4]. A token taken from one tool cannot be replayed at another.

Enforcement at the tool. OWASP's entry on excessive agency lists the matching controls: run actions in the user's context, give extensions the minimum permissions, and apply complete mediation, meaning authorization happens in the downstream system rather than by asking the model whether an action is allowed [2]. The tool server checks scope and record ownership on every call. The model never makes that decision.

Where each identity check happens on an agent tool call

Fig. 01
  1. User sessionlogin, user's own permissions
  2. Agent clientown ID, scope ceiling
  3. Token exchangesub=user, act=agent, 5 minutes
  4. Tool serveraudience, scope, record owner
  5. Datarows owned by the user
The user's rights and the agent's ceiling are combined once into a short-lived token, and the tool server checks it again on every call.

By the numbers

machine identities per human identity in CyberArk's 2025 survey of 2,600 security decision makers [5]
82 to 1
of those machine identities have privileged or sensitive access [5]
42%
of respondents define a privileged user as a human only [5]
88%
of organizations lack identity security controls for AI [5]
68%
WiringLogs say who actedReach if the agent is hijackedComplete mediation
One shared admin API keyNeither user nor agentEverything the key can do, for every userNo, the model decides
User's own token passed to toolsUser onlyEverything that user can do, on every toolPartly, the tool checks the user
Delegated token, scoped and audience-boundUser and agentOne tool server, the task's scopes, minutesYes, the tool checks every call
Three ways to give an agent credentials, judged against OWASP's excessive agency controls and RFC 8693 delegation [2][3][4]

CyberArk's figures come from a vendor survey of large organizations [5]. The pattern still applies to a small product: non-human identities soon outnumber the people on the team, and the 42% figure shows how often they carry broad rights [5]. As an illustration, an AI MVP with three agents and ten integrations can easily hold more non-human credentials than it has employees.

The table shows why the third row is worth the work. The first two rows differ only in how much damage one manipulated agent can do. The third row is the only one where an incident can be traced to one user and one agent, and contained to one tool for a few minutes.

Implementation

The token service below issues a delegated token for one agent, one user and one tool server, and the tool server checks it. It uses PyJWT. A shared HS256 secret keeps the example short. In production, an authorization server signs with an asymmetric key (RS256 or ES256) and tool servers verify with the public key, so no tool server can mint tokens.

agent_tokens.pypython
"""Delegated, audience-bound, short-lived tokens for agent tool calls (PyJWT)."""
import time
import uuid

import jwt

SIGNING_KEY = "replace-with-a-key-from-your-secret-manager-32b+"  # use RS256/ES256 keys in production
AGENT_CEILING = {"agent:support": {"orders:read", "tickets:write"}}  # the most an agent may ever hold
TOOL_SCOPE = {"get_order": "orders:read", "add_ticket_note": "tickets:write",
              "create_refund": "refunds:write"}

class Denied(Exception): pass

def issue(user_id: str, user_scopes: set, agent_id: str, wanted: set, audience: str) -> str:
    scopes = wanted & user_scopes & AGENT_CEILING.get(agent_id, set())
    now = int(time.time())
    claims = {"sub": user_id, "act": {"sub": agent_id}, "aud": audience,  # RFC 8693 actor claim
              "scope": " ".join(sorted(scopes)), "iat": now, "exp": now + 300,
              "jti": str(uuid.uuid4())}
    return jwt.encode(claims, SIGNING_KEY, algorithm="HS256")

def authorize(token: str, tool: str, owner_id: str, this_server: str) -> dict:
    try:  # checks signature, expiry and that the token was minted for this server
        claims = jwt.decode(token, SIGNING_KEY, algorithms=["HS256"], audience=this_server)
    except jwt.PyJWTError as exc:
        raise Denied(f"bad token: {exc}") from exc
    if TOOL_SCOPE[tool] not in claims["scope"].split():
        raise Denied(f"{tool} needs {TOOL_SCOPE[tool]}")
    if owner_id != claims["sub"]:  # the agent acts for one user, on that user's records
        raise Denied("record belongs to another user")
    return {"user": claims["sub"], "agent": claims["act"]["sub"], "tool": tool,
            "jti": claims["jti"]}  # write this line to the audit log

How to adopt it:

  • Register each agent with its own ID and a scope ceiling in AGENT_CEILING. Start with read scopes only and add write scopes one at a time.
  • Map every tool to exactly one scope in TOOL_SCOPE. A tool without a mapping does not run.
  • Call issue when the agent starts a task for a signed-in user, with the scopes the task needs and the URL of the one tool server it will call. If your identity provider supports RFC 8693 token exchange, use it instead of this function [3].
  • Call authorize inside each tool server before doing anything, and write the returned record to the audit log. When a scope is missing, answer with 403 and insufficient_scope, as the MCP specification describes [4].
  • Keep long-lived secrets (database passwords, payment keys) in the tool servers. The agent process holds only its own client credentials and the short-lived tokens it receives.

Test it

These tests use pytest and cover the five promises the design makes.

test_agent_tokens.pypython
import time
import pytest
from agent_tokens import Denied, authorize, issue

ORDERS = "https://orders.internal.example"
USER_SCOPES = {"orders:read", "tickets:write", "refunds:write"}  # an admin user

def token(audience=ORDERS, wanted=frozenset({"orders:read", "refunds:write"})):
    return issue("user_ana", USER_SCOPES, "agent:support", set(wanted), audience)

def test_agent_never_exceeds_its_ceiling_even_for_an_admin():
    with pytest.raises(Denied, match="refunds:write"):
        authorize(token(), "create_refund", "user_ana", ORDERS)

def test_token_for_another_server_is_rejected():
    with pytest.raises(Denied, match="bad token"):
        authorize(token(audience="https://billing.internal.example"), "get_order", "user_ana", ORDERS)

def test_other_users_record_is_denied():
    with pytest.raises(Denied, match="another user"):
        authorize(token(), "get_order", "user_ben", ORDERS)

def test_expired_token_is_rejected(monkeypatch):
    monkeypatch.setattr(time, "time", lambda: 1_000_000_000)  # issued in 2001
    t = token()
    monkeypatch.undo()
    with pytest.raises(Denied, match="bad token"):
        authorize(t, "get_order", "user_ana", ORDERS)

def test_audit_record_names_both_user_and_agent():
    record = authorize(token(), "get_order", "user_ana", ORDERS)
    assert (record["user"], record["agent"]) == ("user_ana", "agent:support")

Expected: five passing tests. Then review the deployed system:

  • Credential inventory. List every secret readable by the agent process. Expected: its own client credentials, nothing that grants direct access to data stores, payments or email.
  • Cross-server replay. Send a token minted for the orders server to the billing server. Expected: 401 [4].
  • Revocation. Disable one agent's client registration. Expected: that agent's next token request fails at once, its tokens already issued stop working when they expire a few minutes later, and other agents keep working.
  • Audit trace. Pick one tool call from yesterday. Expected: the log names the user, the agent, the tool and the token ID.

Decision

Do this before an agent gets write access to anything, or before a second user shares the same deployment.

  • Give each agent its own identity and a scope ceiling, and never a shared admin key.
  • Issue tokens that name the user as subject and the agent as actor, bound to one tool server, valid for minutes.
  • Check scope and record ownership in the tool server on every call. The model never authorizes.
  • Expect two to three days of work for an MVP with a handful of tools. Actions that remain risky after scoping still need a person: see Human Approval Gates for AI Actions.

Sources

  1. [1]GitHub MCP Exploited: Accessing private repositories via MCP (opens in a new tab)Invariant Labs, May 2025
  2. [2]LLM06:2025 Excessive Agency (opens in a new tab)OWASP GenAI Security Project, 2025
  3. [3]RFC 8693: OAuth 2.0 Token Exchange (opens in a new tab)IETF, January 2020
  4. [4]Authorization, Model Context Protocol specification 2026-07-28 (opens in a new tab)Model Context Protocol, July 2026
  5. [5]Machine Identities Outnumber Humans by More Than 80 to 1 (CyberArk press release) (opens in a new tab)Silicon UK, April 2025

Technical guidance, not legal or security certification.

Need a technical review of an AI-built MVP?

Discuss your build