The core delegation guide outlines the security model for human-in-the-loop agent systems, centered on cryptographic delegation through a delegation authority, three independent validation layers, and two communication carriers that route approvals between users and tools. This post walks through how those principles translate into working software in the ActionAuth reference implementation (action-auth).

The codebase is open source under Apache-2.0 and includes an automated test suite covering unit logic, protocol edge cases, and end-to-end multi-process execution.

The DelegationAuthority Protocol and failure vocabulary

The foundation of the architecture sits in bridge/authority/interface.py, which defines a minimal two-method Protocol:

class DelegationAuthority(Protocol):
    def mint(self, signed: SignedAuthorizationDetails) -> MintedCredential: ...
    def consume(self, credential: str, command: str, args: dict) -> MintedCredential: ...

The mint method accepts a human-signed approval payload and produces a short-lived, action-scoped credential. The consume method takes that credential alongside live command arguments at execution time, verifies parameter binding, marks the token consumed, and rejects replay attempts.

A family of typed exceptions accompanies the Protocol:

  • SignatureMismatch: Cryptographic verification failed; the signature does not match the configured secret.
  • CredentialDrift: The parameters requested at execution time do not match the parameters approved by the human.
  • SignatureReplay: The human-signed approval payload was presented to the authority more than once.
  • CredentialReplay: The issued credential has already been consumed.
  • CredentialExpired: The time window on the signature or token has elapsed.
  • UnknownIssuer and WrongAudience: The token was issued by an untrusted entity or targeted a different resource server.
  • PayloadDriftAtMint: The signed payload exceeds maximum time-to-live thresholds or violates domain constraints.

By standardizing on typed exceptions, calling components handle rejections uniformly without losing audit context. The execution dispatcher translates any AuthorityError into an approval requirement, preserving the specific error class for security logging.

The Protocol also simplifies deployment upgrades, letting you graduate from an in-process Hash-based Message Authentication Code (HMAC) verifier (Tier 1) to an OAuth-style JSON Web Token authorization server (Tier 2) by swapping the constructor at initialization without modifying downstream call sites.

Durable replay state across distributed replicas

Stateless transport protocols like the Model Context Protocol HTTP profile distribute requests across multiple server replicas behind a round-robin load balancer. When services maintain in-memory sets of consumed tokens, each replica operates with an isolated view of history, allowing an attacker to replay captured approvals once per replica.

The bridge/authority/durable_state.py module introduces DurableReplayState for shared, atomic single-use tracking using SQLite in Write-Ahead Logging (WAL) mode:

class DurableReplayState:
    """Shared, atomic replay state across multiple worker processes."""

    def claim_signature(self, sig_hash: str, *, expired_at: float) -> bool:
        now = self._clock()
        with self._lock:
            with self._conn:
                cursor = self._conn.execute(
                    "INSERT OR IGNORE INTO consumed_signatures "
                    "(sig_hash, minted_at, expired_at) VALUES (?, ?, ?)",
                    (sig_hash, now, expired_at),
                )
                return cursor.rowcount == 1

By relying on database primary key constraints via INSERT OR IGNORE, the storage engine resolves race conditions atomically. If two worker processes receive the same signed approval simultaneously, exactly one insert succeeds and returns a row count of one. The second insert is ignored and returns zero, triggering an immediate SignatureReplay rejection.

A parallel table records consumed token identifiers (jti) for resource server validation. Explicit housekeeping methods prune expired records on an operator schedule, avoiding table bloat without introducing clock-skew vulnerabilities across server fleets.

Tier 1: In-process cryptographic delegation

For self-contained applications where the host process is trusted, bridge/authority/in_process.py provides an in-process HMAC implementation.

At the top of the module, canonical_authorization_bytes defines the serialization format for cryptographic signatures. To ensure stable byte representations across different programming languages, the function applies strict canonicalization rules:

  1. Keys are sorted recursively at every nesting level.
  2. Whitespace is stripped between JSON keys and values.
  3. Floating-point values are rejected recursively to prevent precision drift across runtimes.
  4. Expiration timestamps are formatted as integer epoch seconds.
  5. The human-readable prompt displayed on the consent screen is included in the canonical bytes to prevent cosmetic drift attacks.

The InProcessAuthority.mint method verifies the signature, enforces maximum lifetime bounds, and checks the signature hash against the replay store before issuing an execution token:

def mint(self, signed: SignedAuthorizationDetails) -> MintedCredential:
    canonical = canonical_authorization_bytes(
        signed.command, signed.args, signed.rar_type,
        signed.exp, signed.approver_id, signed.binding_message,
    )
    expected = hmac.new(self._secret.encode(), canonical, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, signed.signature):
        raise SignatureMismatch("HMAC verification failed")

    signature_hash = hashlib.sha256(canonical).hexdigest()
    if self._durable_state is not None:
        if not self._durable_state.claim_signature(signature_hash, expired_at=float(signed.exp)):
            raise SignatureReplay("Signed payload already exchanged for a credential")
    
    jti = secrets.token_hex(8)
    minted = MintedCredential(
        credential=f"{signed.signature}.{jti}",
        command=signed.command,
        args=signed.args,
        exp=signed.exp,
        jti=jti,
    )
    self._issued[jti] = minted
    return minted

Tier 1 protects against prompt injection, parameter drift, and duplicate execution within the application boundary. However, because the signing secret resides in process memory, Tier 1 does not protect against full host process compromise.

Tier 2: Separated authorization and resource servers

Tier 2 splits the architecture into an OAuth authorization server (bridge/authority/oauth.py) and a separated resource server (bridge/rs/jwt_resource_server.py).

In OAuthAuthority, the mint method verifies the human signature and issues a signed JSON Web Token containing RFC 9396 authorization_details:

claims = {
    "iss": self._issuer,
    "aud": self._audience,
    "exp": signed.exp,
    "jti": secrets.token_hex(8),
    "authorization_details": [{
        "type": signed.rar_type,
        "command": signed.command,
        "args": signed.args,
    }],
}
token = jwt_encode(claims, self._mint_secret)

The decoder enforces algorithm pinning, rejecting alg=none and mismatched asymmetric algorithm headers before processing HMAC signatures. This structurally eliminates algorithm confusion attacks.

Downstream execution takes place in JwtResourceServer, which acts as the third independent enforcement layer:

class JwtResourceServer:
    def execute(self, command: str, args: dict, credential: str) -> RsOutcome:
        claims = jwt_decode(credential, self._verification_secret)
        self._validate_claims(claims)
        jti = self._consume_authorization_details(claims, command, args)
        return self._execute_command(command, args, jti)

The resource server performs its own cryptographic verification, validates audience and issuer claims, confirms parameter binding against the live request arguments, and records the token identifier in its durable replay store. Even if an intermediary modifies token parameters in transit, the resource server rejects the drifted execution.

Dispatcher pass-through and scope gating

The central request router in bridge/core/dispatcher.py coordinates scope authorization, human-in-the-loop routing, and forwarding approved calls to the resource server without mutating credentials.

Before evaluating human approval, Dispatcher.execute validates caller scopes against declared tool requirements:

spec = SPECS_BY_CLI_NAME.get(command_name)
if caller is not None and spec is not None and spec.required_scopes:
    missing = [s for s in spec.required_scopes if s not in caller.scopes]
    if missing:
        return Unauthorized(
            command=command_name,
            required_scopes=tuple(spec.required_scopes),
            caller_scopes=tuple(sorted(caller.scopes)),
        )

This ensures that callers holding only read scopes are rejected with Unauthorized before reaching the human consent gate. Scope enforcement and parameter-bound approvals operate as distinct, complementary controls.

Single-agent carrier: Model Context Protocol elicitation

For single-agent environments, bridge/mcp/hitl.py and bridge/mcp/server.py implement the human consent loop using the Model Context Protocol (MCP) Python SDK. The server pins mcp>=2.0 and negotiates the protocol version per request. Versions at or above 2026-07-28 get the Multi Round-Trip flow. Older clients still receive the legacy URL-mode elicitation error (-32042), because their result union has no input_required type and would fail per-version SDK validation with -32603.

On a human-in-the-loop gated call that is not yet approved, _pending_consent_result takes the negotiated protocol version first and reads _MRTR_PROTOCOL_VERSION to return an InputRequiredResult for modern clients or raise the legacy elicitation error:

def _is_modern_protocol(version: str | None) -> bool:
    """True if the negotiated protocol version carries the MRTR surface."""
    return (version or "") >= _MRTR_PROTOCOL_VERSION


def _pending_consent_result(
    version: str | None, *, url: str, session_id: str, message: str
) -> Any:
    """Result for a HITL-gated call that is not yet approved."""
    elicit = mcp_types.ElicitRequestURLParams(
        mode="url",
        message=message,
        url=url,
        elicitation_id=session_id,
    )
    if _is_modern_protocol(version):
        elicitation = mcp_types.ElicitRequest(
            method="elicitation/create", params=elicit
        )
        return mcp_types.InputRequiredResult(
            input_requests={"consent": elicitation},
            request_state=session_id,
            result_type="input_required",
        )
    raise UrlElicitationRequiredError([elicit], message=message)

The consent session identifier is deterministic, derived from caller, command, and arguments, so a repeated first call finds the same pending session.

The client retries the same tools/call with input_responses and request_state. The server then checks, in order:

  1. The session exists and carries a signed payload from the human approver.
  2. The caller matches the approver bound into the session.
  3. The canonical action hash of the retried command and arguments matches the approved one, hashing over the executable CLI command name rather than the MCP tool name so both sides hash the command that executes.

Any failure is a tool-level error result (is_error=true), not a JSON-RPC error, so the message reaches the model.

Only then does try_resume mint the credential and re-dispatch. Minted credentials are cached in the durable state store, so a second retry of an already-minted session returns the same credential instead of re-presenting the signed payload, which the delegation authority’s replay guard would otherwise reject.

Multi-agent carrier: Agent-to-Agent protocol translation

In multi-agent systems where user-facing agents delegate tasks to specialized sub-agents, approvals travel across process boundaries using bridge/translation/a2a_mcp.py.

When a sub-agent encounters a destructive tool call, it emits an auth_required event into its Agent-to-Agent (A2A) task stream. The parent bridge translates this event into an MCP URL-mode elicitation for the user’s host application. Once signed, the approval returns through the translation layer to resume the sub-agent.

At no point does the parent agent pass its own bearer credentials to the sub-agent. The cryptographic chain binds the user directly to the leaf action, providing end-to-end accountability across arbitrary delegation depths.

To guarantee that the user approves the exact parameters sent to the resource server, bridge/consent/url_mode.py encapsulates pending requests in an immutable ProposedAction dataclass:

@dataclass(frozen=True)
class ProposedAction:
    session_id: str
    command: str
    args: Mapping[str, object]  # Deep-copied MappingProxyType
    binding_message: str
    approver_id: str

Setting frozen=True and wrapping arguments in MappingProxyType prevents in-place parameter mutation during the approval window. The parameters presented on screen remain byte-identical to the data signed by the user.

Codebase navigation and test verification

For engineers exploring the repository, the recommended reading order is:

  1. bridge/authority/interface.py: Protocol definitions, exception hierarchy, and secret validation.
  2. bridge/authority/durable_state.py: SQLite WAL atomic replay state store.
  3. bridge/authority/in_process.py: Tier 1 canonical JSON encoding and in-process HMAC verification.
  4. bridge/authority/oauth.py: Tier 2 JWT minting, algorithm pinning, and audience validation.
  5. bridge/rs/jwt_resource_server.py: Layer 3 separated resource server execution.
  6. bridge/core/dispatcher.py: Scope gating prior to human approval and pass-through routing.
  7. bridge/mcp/hitl.py and bridge/mcp/server.py: Single-agent MCP 2.0 Multi Round-Trip flow and elicitation handling.
  8. bridge/translation/a2a_mcp.py: Multi-agent A2A event translation.
  9. bridge/consent/url_mode.py: Web consent application and immutable parameter models.

The test suite covers these guarantees: tests/unit/test_durable_state.py verifies cross-process atomic replay protection across child processes, while tests/e2e/test_three_layer_enforcement.py proves independent rejection across all three enforcement layers. At the boundary, tests/e2e/test_scope_enforcement.py confirms dispatcher-level scope rejection prior to consent evaluation. In the MCP transport layer, tests/e2e/test_mcp_stateless_mrtr.py verifies the Multi Round-Trip flow, while tests/e2e/test_mcp_elicitation_emission.py runs the end-to-end elicitation and resumption cycle against live HTTP transport.


The complete source code and automated test suite are available in the ActionAuth repository under the Apache-2.0 license.