Building Presence-Gated Capabilities for AI Agents: A Session-Scoped Authorization Pattern
Hook
Your AI agent can now execute dangerous operations autonomously—but only after you prove you're actually sitting at your desk. This is capability-based security for the LLM era.
Context
As AI agents gain autonomy through frameworks like Model Context Protocol (MCP), we face a new authorization challenge: how do we let agents maintain long-running sessions while still requiring human approval for sensitive operations? Traditional per-request authentication creates TOTP fatigue when agents make dozens of calls. Pure session tokens are too permissive—once compromised, an attacker has unrestricted access until expiry. API keys with scopes help, but they're static and can't distinguish between routine queries and destructive actions.
The mcp-presence-broker repository introduces session-scoped capabilities: a pattern where clients establish persistent sessions but must prove human presence (via TOTP) to receive time-limited grants for protected operations. This sits between MCP clients and backend resources, acting as both an authorization broker and capability authority. The architecture acknowledges that AI agents need state and context across multiple interactions, but certain operations—like modifying production data or approving transactions—should always require a human to physically prove they're present. It's step-up authentication designed specifically for autonomous agents rather than web browsers.
Technical Insight
The broker implements a three-tier security model: sessions, presence verification, and capability grants. Sessions are established with bearer tokens and tracked in SQLite, giving clients a persistent identity. Protected MCP tools are visible to all clients (no security-through-obscurity) but require valid capability grants to invoke. Grants are minted only after successful TOTP verification and expire after a configurable TTL (default 300 seconds).
Here's the authorization flow from the broker's perspective:
# Simplified from actual implementation
class PresenceBroker:
def verify_totp_and_mint_grant(self, session_id: str, totp_code: str) -> dict:
session = self.db.get_session(session_id)
if not session or not session.is_valid():
raise InvalidSession()
# Global lockout check (affects all sessions)
if self.is_locked_out():
raise RateLimitExceeded()
# TOTP codes are single-use globally, not per-session
if self.db.was_code_used(totp_code):
self.record_failed_attempt()
raise CodeAlreadyUsed()
# Verify TOTP against session seed
if not self.totp_verifier.check(session.seed, totp_code):
self.record_failed_attempt()
raise InvalidCode()
# Mark code as consumed before minting grant (prevents replay)
self.db.mark_code_used(totp_code, timestamp=now())
# Mint time-limited capability grant
grant_id = self.db.create_grant(
session_id=session_id,
expires_at=now() + timedelta(seconds=session.grant_ttl)
)
return {"grant_id": grant_id, "expires_in": session.grant_ttl}
def invoke_protected_tool(self, session_id: str, tool_name: str, args: dict):
# Check for active grant
grant = self.db.get_active_grant(session_id)
if not grant or grant.is_expired():
raise NoActiveGrant("Human presence verification required")
# Execute protected operation
return self.execute_backend_operation(tool_name, args)
The critical insight is that TOTP codes are consumed globally across all sessions, not just the requesting session. If you use code 123456 in Session A, Session B cannot reuse that code even if they share the same seed (in multi-user scenarios). This prevents an attacker who observes a valid code from using it in a parallel session before the time window expires. The broker maintains a used_codes table that grows with every verification—there's no cleanup mechanism, which is a scalability limitation but ensures replay prevention never expires.
The global lockout mechanism is deliberately coarse-grained. After five failed verification attempts from any session, the entire broker freezes for 60 seconds. This trades per-session fairness for brute-force protection. A compromised client can DoS the entire system, but an attacker cannot grind through TOTP codes at scale. The architecture assumes that if one client is under attack, the security posture of the entire deployment is suspect and pausing all operations is acceptable.
The demo mode is architecturally clever—it uses synthetic TOTP seeds and a code generator that prints valid codes to stdout, allowing protocol testing without requiring actual authenticator apps. This cleanly separates behavioral verification ("did the flow work correctly?") from cryptographic security ("is the code cryptographically valid?"). You can validate the grant lifecycle and expiration logic without waiting for time windows:
# Demo session creation with synthetic seed
result = await broker.call_tool(
"create_session",
{"session_id": "test-session", "demo_mode": True}
)
# Prints: "Your TOTP code: 847263"
# Immediately use generated code
await broker.call_tool(
"verify_presence",
{"session_id": "test-session", "code": "847263"}
)
# Grant now active for 300 seconds
# Protected operation succeeds
await broker.call_tool(
"increment_counter",
{"session_id": "test-session"}
)
The protected operation (a simple counter increment) is intentionally co-located with the broker rather than being a separate microservice. This eliminates confused deputy problems—there's no downstream service that needs to validate capability tokens or trust the broker's assertions. The broker is the sole authority over both verification and execution. This is only viable for simple backends; anything complex would need to be split out, at which point you'd need to implement grant propagation (likely via signed JWTs) and teach downstream services to validate them.
Gotcha
The single-node SQLite architecture is a hard ceiling. The used_codes table grows unbounded with every verification, and there's no sharding or replication story. You cannot horizontally scale this broker, and losing the SQLite file means losing all session state and replay prevention history. For research prototypes this is fine; for production you'd need to migrate to Postgres with proper indexing and implement code cleanup (perhaps pruning codes older than the maximum time-window skew).
Session provisioning is entirely manual. There's no OAuth flow, no SAML federation, no upstream identity provider integration. You create sessions by calling create_session with a session ID you invent, and the broker returns a TOTP seed you must manually configure in an authenticator app. Every client needs a separate session, and there's no facility for revoking sessions in bulk or managing user lifecycle. This makes multi-user deployments impractical without building an entire identity management layer on top.
The security model assumes OS-level user isolation. The documentation recommends running the broker as a dedicated system user, because any process running as the same user can read the SQLite database and extract session seeds or active grants. This works for production deployments with proper user isolation, but it complicates local development—you can't just python broker.py in your home directory and expect meaningful security. For true local protection, you'd need containers or VMs, at which point you're managing infrastructure for a research prototype.
Verdict
Use if: You're researching authorization patterns for AI agents, need a concrete example of session-scoped capabilities for academic work, or want to prototype human-in-the-loop controls for autonomous systems without building from scratch. This is a readable, runnable reference implementation that demonstrates presence-gated authorization more clearly than production systems obscured by enterprise complexity. Also use if you're securing a single-node, single-user AI agent deployment where you control the OS-level security boundary and don't need federation. Skip if: You need multi-tenancy, horizontal scaling, federated identity integration, or anything that would be deployed in production without significant re-architecture. The lack of upstream OAuth, unbounded database growth, and global lockout DoS vector make this unsuitable for real-world multi-user scenarios. Also skip if you're looking for drop-in MCP security—this is educational infrastructure, not a packaged solution. For production agent authorization, you'd need Ory, Keycloak, or a custom OAuth2 implementation with step-up authentication.