How to Implement AI Agent Runtime Authorization

A six-phase implementation guide for AI agent runtime authorization: inventory the action surface, observe before enforcing, write the first ten policies, remove standing credentials, enforce with fail-closed writes, and verify with denial tests.

By Kontext.

Published 2026-08-28.

To implement AI agent runtime authorization, roll it out in six phases: inventory the action surface your agents can already reach, run the enforcement point in observe-only mode to collect real tool calls, write policy for the ten actions that carry the most blast radius, replace standing credentials with brokered short-lived ones, switch to enforce with risk-based approvals, then verify with deliberate denial tests. Enforcement belongs at the action boundary — immediately before a tool call, credential issuance, or API request — and it has to be impossible for the agent to bypass.

This is the implementation guide. For the concept and the decision model, see AI agent runtime authorization. For the permission model behind the policies you will write here, see how to enforce least privilege for AI agents using external tools.

The sequence matters more than the tooling. Teams that start by writing policy fail, because they write policy for the tool calls they imagine instead of the ones their agents actually make. Teams that start by observing succeed, because the first week of traces usually contains three actions nobody knew were possible.

What do you need before you start?

Runtime authorization needs four prerequisites: a single chokepoint every agent tool call passes through, an agent identity that is distinct from the human user's identity, a policy store that lives outside the model's editable context, and an owner who can approve or reject policy changes. Without the chokepoint, enforcement is advisory.

PrerequisiteWhy it blocks the rolloutMinimum viable version
A single enforcement chokepointIf the agent can call the API directly with a long-lived secret, policy is a suggestion.An SDK wrapper, MCP gateway, or hook layer the agent runtime cannot skip.
Distinct agent identityLogs that say "the user did it" cannot support policy, revocation, or incident review.A stable agent ID plus the delegated user ID on every decision request.
Externalized policyRules in the system prompt are editable by anything that reaches the context window.Policy-as-code in version control, deployed separately from the agent.
A named policy ownerDenials create tickets. Unowned denials get switched off.One engineer plus one security reviewer, with a documented change path.

If you cannot name the chokepoint, phase 1 is architecture work, not policy work.

Phase 1: Inventory the action surface

Start by enumerating every action your agents can already take, not every action you intended them to take. The inventory should list tool name, action type, the credential behind it, the systems it can reach, and the worst outcome of a single call. Most teams discover the real surface is two to five times larger than the documented one.

Work outward from credentials, because the credential defines the blast radius:

  1. List every secret the agent runtime can read — environment variables, MCP server configs, .env files, secret managers, CI variables, shell history.
  2. For each secret, write down what it can do at the provider, not what you use it for. A GitHub token with repo can delete branches even if your agent only opens pull requests.
  3. Map each tool to read, write, delete, export, send, approve, transfer, or delegate. One tool usually spans several.
  4. Flag the shell. Generic execution tools are the largest single gap in most coding-agent deployments: a large share of tool calls arrive as opaque shell commands, so curl, gh, psql, and aws calls hide inside a single "Bash" event unless you decompose the command line.
  5. Record the worst single-call outcome. That column decides policy priority in phase 3.

The output is a table of maybe 40 rows. Sort it by worst outcome and stop reading after the top ten. Those ten are your first policies.

Phase 2: Run in observe-only mode first

Deploy the enforcement point with every decision returning allow, and log what it sees. Two weeks of real traces tells you which policies would have fired, what your false-positive rate would be, and which tool calls you cannot yet attribute to a user. Enforcing before this step produces broken agents and an organization that distrusts the control.

What to measure during the observation window:

  • Coverage: what percentage of tool calls reach the decision point at all? Anything under 100% is a bypass path, and bypass paths make the remaining phases cosmetic.
  • Attribution: what percentage of calls carry both an agent identity and a resolvable delegated user? This is where most deployments discover an identity binding gap — the directory email, the agent login, and the device name are three different strings, and nothing joins them.
  • Action mix: how many calls are reads versus writes, exports, sends, and deletes? The write tail is small in practice, which is why deny-by-default on writes is affordable and deny-by-default on reads is not.
  • Would-have-denied rate: shadow-evaluate draft policies and count. If a draft policy would fire on more than about 2% of calls, it is a broken policy, not a discovered attack.
  • Decision latency: measure p50 and p95 of the decision call itself, separately from the tool call. Set your budget now, before anyone can claim the control made the agent slow.

For coding agents, the open-source Kontext CLI gives you this phase without a hosted dependency: kontext guard start runs local-only, captures Claude Code tool calls, redacts events, scores risk, and stores traces in local SQLite with a dashboard at http://127.0.0.1:4765.

Phase 3: Write the first ten policies

Write policy against business actions, not API endpoints, and keep the first set small enough to review in one sitting. Each policy needs a stable ID, the conditions that must hold, the effect, the credential scope it authorizes, and a human-readable denial reason. The denial reason is not decoration: it is what the agent shows the user and what the on-call engineer reads.

A workable first ten for a coding agent:

#ActionPolicyEffect
1Read repository files in the active projectAllow when the repository is in the session's declared scopeallow
2Write to a branch the agent createdAllow with a scoped, short-lived tokenallow
3Push to a protected branchNever, regardless of tokendeny
4Merge a pull requestHuman approval requiredescalate
5Change repository settings, secrets, or workflowsHuman approval requiredescalate
6Delete a branch, tag, or repositoryHuman approval requiredescalate
7Read a file matching secret patternsDeny and log with the matched path redacteddeny
8Outbound network to a non-allowlisted domainDeny by defaultdeny
9Database write or schema change against productionNever from an agent sessiondeny
10Anything not matched aboveDeny for writes, allow-and-log for readsmixed default

Policy 10 is the one to argue about internally, and the honest answer is staged: deny-by-default on the write, send, delete, export, and delegate verbs from day one, and allow-and-log on reads until your coverage and attribution numbers are good enough that a read denial will not be blamed on the control.

Expressed as policy-as-code, a single rule carries conditions, credential scope, and reason together:

{
  "id": "coding-agent-no-protected-branch-push",
  "effect": "deny",
  "when": {
    "agent.role": "coding",
    "tool": "github.push",
    "resource.branch_protected": true
  },
  "reason": "agents may not push to protected branches; open a pull request instead",
  "audit": "required"
}

And the allow case must bound the credential, not just the call:

{
  "id": "coding-agent-branch-write",
  "effect": "allow",
  "when": {
    "agent.role": "coding",
    "tool": "github.push",
    "resource.branch_created_by_session": true
  },
  "credential": {
    "scope": "contents:write",
    "repositories": ["${session.declared_repo}"],
    "ttl_seconds": 300
  },
  "audit": "required"
}

If the allow path hands back the same token the agent already had, you have built a logger, not an authorization layer.

Phase 4: Remove standing credentials

Replace long-lived provider secrets with credentials the broker issues after the decision. This is the phase that converts policy into enforcement, because it removes the path around the chokepoint. Until the agent runtime has no usable secret of its own, a denied action can simply be retried directly against the provider API.

The mechanics are the same across brokers:

  1. Remove provider secrets from the project, the MCP server config, the shell profile, and CI.
  2. Replace them with references that only resolve inside a governed session — with Kontext CLI hosted mode (kontext start --agent claude), a managed .env.kontext holds placeholders such as GITHUB_TOKEN={{kontext:github}} and LINEAR_API_KEY={{kontext:linear}}.
  3. Resolve the reference at the moment of the approved action, scoped to that action, with a TTL measured in minutes.
  4. Rotate the original secrets you removed. Assume anything that sat in an agent's environment has already been read.

Step 4 is not optional. In OpenAI's account of the Hugging Face incident (August 2026), evaluation agents posted leaked Hugging Face write-credentials into a shared location that later runs then read and reused — the compromise propagated through a credential that outlived the task it was issued for, not through a broken sandbox. Removing a secret from a config does not revoke it.

Phase 5: Switch to enforce — and decide how it fails

Turn on enforcement for the write verbs first, with risk-based approvals for the escalate cases, and configure the failure mode explicitly. When the policy engine is unreachable or the delegated user cannot be resolved, the system must choose between failing closed and failing open — and default-open failure modes are where runtime authorization silently stops existing.

Make three decisions before you flip the switch:

  • Fail-closed or fail-open, per verb. Reads can fail open with a loud log. Writes, sends, deletes, exports, and credential issuance should fail closed. Watch specifically for the case where the principal cannot be resolved: an unresolvable user is not the same thing as an authorized one, and treating it as a soft error is the most common way a correctly written policy set stops enforcing anything.
  • Approval routing and timeout. An escalation that nobody answers becomes a denial after N minutes. Say what N is, where the approval lands, and who is on the rota. Approvals nobody sees train engineers to bypass the control.
  • The break-glass path. There must be one, it must be time-boxed, it must require a second person, and every use must be logged and reviewed. Break-glass that is not logged is just a bypass with a nicer name.

Risk-based approval is what keeps this usable. Requiring a human on every tool call is the failure mode that gets runtime authorization uninstalled; requiring one on merges, production writes, external sends, payments, and privilege changes is the version teams keep.

Phase 6: Prove it works

Verify enforcement with deliberate denial tests, not by observing that nothing has broken. A rollout is done when a known-bad action is provably blocked at the boundary, the block appears in the audit log with a policy version, and the agent's own retry attempt fails too. Add these tests to CI so a future refactor cannot silently remove the control.

TestMethodPass condition
Enforcement is realAsk the agent to perform a denied writeProvider API never receives the call; denial logged with policy ID
Bypass is closedAttempt the same action with a raw shell commandBlocked or credential-less; no usable standing secret in the environment
Injection resistancePlant an instruction in a file, ticket, or dependency the agent will readInjected action is denied by policy even though the agent attempted it
Credential scope holdsCapture an issued token and use it for a different resourceProvider rejects it; TTL expires within the configured window
Attribution completenessSample 20 audit recordsEach has agent ID, delegated user, tool, resource, parameters, policy version, decision, credential scope
Failure modeMake the policy engine unreachableWrite verbs fail closed; reads degrade with a logged warning
Latency budgetMeasure decision p95 under loadWithin the budget you set in phase 2

The injection test is the one worth automating first, because it is the scenario the control exists for: policy should stop an injected instruction from converting a valid credential into an unsafe side effect, without needing to detect the injection itself.

What to report after go-live

Report five numbers, monthly, to whoever owns agent risk: how many agent runtimes are covered, how many tool calls were policy-evaluated, how many were blocked or escalated, how many blocks were later judged wrong, and decision p95 latency. That set makes the control's value and its friction visible in the same table, which is what keeps it funded.

The false-block number is the one that builds trust. A control that reports only its blocks looks like an obstacle; a control that reports its own errors and drives them down looks like infrastructure. Review the false blocks as policy bugs, fix the policy, and keep the count in the report.

Rollout mistakes to avoid

Enforcing before observing

Policies written from imagination deny legitimate work in week one. Observe first, shadow-evaluate, then enforce.

Leaving one bypass path open

Coverage of 95% is coverage of zero for a motivated agent or a determined engineer under deadline pressure. Find the last direct-API path before you enforce.

Policy in the prompt

Rules in a system prompt or AGENTS.md are guidance, not access control. Anything that reaches the context window can argue with them.

Approval fatigue

Approvals on low-risk reads exhaust the rota and get the control disabled. Escalate only on high-impact verbs.

Auditing tool calls but not decisions

"The agent called GitHub" is telemetry. "Policy coding-agent-branch-write allowed it with a 300-second contents:write token" is evidence. Compliance and incident response need the second one.

Treating unresolved identity as authorized

If the delegated user cannot be resolved and the action proceeds anyway, the enforcement layer is decorative for exactly the sessions that are hardest to explain later.

Why the standards work does not remove this work

The Model Context Protocol's own roadmap states that MCP authorization "is built around a person approving access in a browser" while callers are increasingly agents running as cloud workloads with their own identity, acting for a user who is not present, or delegating narrower authority to sub-agents. The named fixes — DPoP, Workload Identity Federation, the ID-JAG grant behind Enterprise-Managed Authorization, and RFC 8693 token exchange — are real and welcome, and the roadmap is explicit that the agent identity work is still forming.

Those standards answer who is calling and on whose behalf. They do not answer whether this specific action, with these parameters, should happen right now — which is the decision every phase above is about. Strong agent identity makes runtime authorization better, not unnecessary: it improves the attribution inputs the policy engine depends on.

The same split appears in the external guidance. OWASP LLM06:2025 Excessive Agency recommends complete mediation of downstream requests rather than trusting the model to self-restrict, and the FINOS AI Governance Framework's Agent Authority Least Privilege Framework asks for granular API access control, contextual privilege adjustment, time-bounded privileges, and comprehensive access logging. Both describe a runtime decision point. Neither is satisfied by an identity standard alone.

FAQ

How do you implement AI agent runtime authorization?

Implement it in six phases: inventory the action surface reachable from agent credentials, run the enforcement point in observe-only mode for two weeks, write policy for the ten highest-blast-radius actions, replace standing secrets with brokered short-lived credentials, enforce with risk-based approvals and explicit fail-closed behavior, then verify with deliberate denial tests in CI.

Where should the enforcement point live?

At the action boundary the agent cannot bypass: an SDK wrapper around tool execution, a hook layer in the agent runtime, a policy-aware MCP gateway, or the credential broker itself. If the agent still holds a long-lived provider secret, the enforcement point is advisory regardless of where it sits.

How long does a runtime authorization rollout take?

Plan roughly six weeks for a first production deployment: one week of inventory, two weeks of observe-only traces, one week to write and shadow-evaluate the first ten policies, one week to remove standing credentials, and one week to enforce and verify. Coverage gaps and unresolvable user identities are what extend that timeline.

Should runtime authorization fail open or fail closed?

Decide per verb. Reads can fail open with a logged warning to avoid breaking work when the policy engine is unreachable. Writes, sends, deletes, exports, and credential issuance should fail closed. An unresolvable delegated user should never be treated as an authorized one.

Do you need runtime authorization if you already use OAuth or agent SSO?

Yes. OAuth and agent SSO establish which agent is calling and which user delegated access. Runtime authorization decides whether the specific action, with these parameters, in this session, should proceed. The two are complementary layers, and the identity layer improves the inputs to the policy decision.

How do you test that enforcement actually works?

Run deliberate denial tests: attempt a known-denied write, retry it via a raw shell command, plant a prompt injection in content the agent will read, and reuse a captured credential against a different resource. Each must fail at the boundary and appear in the audit log with a policy version.

References

Further reading

Kontext provides runtime authorization and credential brokering for AI agents, so each action is decided at the moment of tool use instead of at integration setup.

Related reading

Back to Articles