Developer Documentation · SDK v1.0

Protect MCP servers and sign AI agents locally

Verify RFC 9421 signatures, Content-Digest, multi-issuer Agent-Passports, OAuth 2.1 step-up, and adaptive DDoS limits in < 0.3 ms inside your process.

Introduction

AgentBouncer v1.0 Overview

In-process verification of AI agents, multi-passports, OAuth 2.1, and DDoS rate limits inside your server in < 0.3 ms with no proxy.

AgentBouncer is an embeddable security and authorization layer for open MCP servers and AI APIs. Unlike cloud proxy gateways, all cryptographic checks, IP rate limits, and access rules run synchronously inside your Node.js process memory in < 0.3 ms (Data Plane) using a locally cached, Ed25519-signed PolicyBundle. The AgentBouncer cloud (Control Plane) operates strictly asynchronously out of the request path: it compiles signed bundles, verifies provider domains and agent cards, refreshes issuer JWKS, aggregates telemetry, and syncs IP blocks.

Core Integration Invariant

Always gate business logic exclusively on verification.allowed === true. The verification.verified field only indicates whether cryptographic authentication (signature, passport, or token) succeeded—it does not account for tool-level access rules, public routes (credential: public), or safe observation mode (MONITOR_ONLY).

Package / SubpathRuntimePurpose
@agentbouncer/sdkNode.js >= 22 (ESM, TypeScript)Core package: local verifier (AgentBouncer), MCP protection (withMcpProtection), passport plugins, DDoS rate limiter, and outbound signer (AgentBouncerSigner).
@agentbouncer/sdk/mcpNode.js >= 22 (ESM, TypeScript)Dedicated wrappers for MCP Streamable HTTP / JSON-RPC 2.0 (withMcpProtection, verifyMcpRequest) and RFC 9728 WWW-Authenticate response builders.
@agentbouncer/sdk/contractsNode.js >= 22 (ESM, TypeScript)Strict Zod v4 schemas (PolicySchema, BundleSchema, PublicJwkSchema, OAuthIssuerSchema, PassportIssuerSchema) and canonicalSignatureAgent for CI/CD config validation.
@agentbouncer/sdk/policyNode.js >= 22 (ESM, TypeScript)Pure deterministic evaluatePolicy() function for local unit testing of access rules without starting a server.
agentbouncer-signerPython >= 3.10 (PyPI)Lightweight client for cryptographically signing outbound HTTP and MCP requests (RFC 9421 + RFC 9530 Content-Digest) with built-in adapters for httpx, the official Python MCP SDK, and requests.
verifiedallowedState Semantics
truetrueAgent and/or user identity is verified, and all policy requirements for the requested action and tool are satisfied.
truefalseCryptography is valid, but the policy rejected the call (insufficient Tier, low trustScore, explicit DENY rule, or user OAuth 2.1 token required — step_up).
falsetrueRequest is unauthenticated, but allowed by an open rule (credential: public) or the project is in MONITOR_ONLY mode (the potential block reason is recorded in policy.wouldBlockReason).
falsefalseRequest is rejected: missing/invalid signature, Content-Digest mismatch, replay detected, invalid passport, or IP rate limit exceeded.
  • HTTP Message Signatures verification (RFC 9421, web-bot-auth profile) and streaming SHA-256 Content-Digest validation (RFC 9530) before JSON parsing.
  • Dual reliability window for PolicyBundle: 5 minutes of guaranteed online freshness (refreshAfter) with background polling every 30 s, and up to 24 hours of full offline operation (offlineUntil) during network outages.
  • Single-wrapper protection withMcpProtection() covering all MCP operations (tools/call, prompts/get, resources/read, including JSON-RPC batches up to 50 messages).
  • Multi-passport trust model: verified domains and organizations, Google A2A Signed Cards (RFC 8785 JCS), portable PoP passports (cnf.jkt), World AgentKit, mTLS / SPIFFE, Enterprise OIDC, Skyfire KYA, and x402.
  • Local OAuth 2.1 user JWT verification against cached JWKS with RFC 9728 Protected Resource Metadata and delegation (act claim) support.
  • Dual-bucket DDoS and scraper protection with automatic synchronization of blocked public IPs across all replicas in your cluster.
Introduction

5-Minute Quickstart

Add in-process MCP server protection in safe MONITOR_ONLY mode and send your first signed agent call.

  1. 1

    Create a project in the dashboard

    In app.agentbouncer.io, create a project and copy your Project ID, server API key (ab_live_...), and the bundle verification public keys JSON (AGENTBOUNCER_BUNDLE_KEYS).

  2. 2

    Start in MONITOR_ONLY mode

    Keep the policy mode set to MONITOR_ONLY initially: every check runs in real time, no requests are blocked, and results are collected in analytics.

  3. 3

    Initialize the AgentBouncer singleton on your server

    Instantiate one AgentBouncer client per Node.js 22+ process and wrap your MCP endpoint with withMcpProtection() (or call bouncer.verify() for custom HTTP APIs).

  4. 4

    Issue an agent key and sign a request

    Create a Project Signing Key in the project keys tab (or register an external provider) and sign your call using @agentbouncer/sdk or the Python package agentbouncer-signer.

1. Install the SDKs
bash
# On the protected server (Node.js >= 22) and/or TS agent:
npm install @agentbouncer/sdk

# On a Python agent (Python >= 3.10):
pip install "agentbouncer-signer[httpx]"
2. Server environment variables (.env)
bash
AGENTBOUNCER_PROJECT_ID="proj_01j..."
AGENTBOUNCER_API_KEY="ab_live_..."
AGENTBOUNCER_PUBLIC_ORIGIN="https://mcp.example.com"
AGENTBOUNCER_BUNDLE_KEYS='{"ab-bundle-2026-01":{"kty":"OKP","crv":"Ed25519","x":"..."}}'
3. Verifier singleton (src/lib/bouncer.ts)
typescript
import { AgentBouncer, FilePolicySnapshotStore } from "@agentbouncer/sdk";

export const bouncerPromise = AgentBouncer.create({
  apiKey: process.env.AGENTBOUNCER_API_KEY!,
  projectId: process.env.AGENTBOUNCER_PROJECT_ID!,
  publicOrigin: process.env.AGENTBOUNCER_PUBLIC_ORIGIN,
  trustedBundlePublicKeys: JSON.parse(process.env.AGENTBOUNCER_BUNDLE_KEYS!),
  snapshotStore: new FilePolicySnapshotStore("./.cache/policy-bundle.jws"),
  telemetry: true,
  rateLimit: {
    // Enable when running behind a trusted reverse proxy (Cloudflare, Nginx, ALB)
    // that reliably overwrites client IP headers:
    trustProxyHeaders: true,
  },
});
4. Protecting the MCP route (src/app/api/mcp/route.ts)
typescript
import { withMcpProtection } from "@agentbouncer/sdk/mcp";
import { bouncerPromise } from "@/lib/bouncer";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

async function handleMcp(request: Request) {
  const bouncer = await bouncerPromise;

  const guard = withMcpProtection(
    bouncer,
    async (req, { verification, operations }) => {
      // Runs ONLY when verification.allowed === true
      return dispatchToMcpServer(req, {
        provider: verification.provider,
        passports: verification.passports,
        user: verification.oauth,
        operations,
      });
    },
  );

  return guard(request);
}

export { handleMcp as POST, handleMcp as GET, handleMcp as DELETE };
5. Signed call from a Python agent
python
import json
import os
import httpx
from agentbouncer_signer import AgentBouncerSigner

signer = AgentBouncerSigner(
    private_jwk=json.loads(os.environ["AGENT_PRIVATE_JWK"]),
    signature_agent=os.environ["AGENT_SIGNATURE_AGENT"],
    key_id=os.environ.get("AGENT_KEY_ID"),
)

with httpx.Client(auth=signer.httpx_auth()) as client:
    res = client.post(
        "https://mcp.example.com/api/mcp",
        json={
            "jsonrpc": "2.0",
            "id": 1,
            "method": "tools/call",
            "params": {"name": "catalog.search", "arguments": {"query": "servers"}},
        },
    )
    print(res.status_code, res.json())
Concepts

Architecture, Trust Tiers & Key Types

Data Plane vs Control Plane separation, PolicyBundle lifecycle, Tier 1–3 hierarchy, and credential isolation.

EntityTechnical Purpose
PolicyBundleEdDSA (Ed25519) signed JWS document (typ: agentbouncer-policy-bundle+jws, schemaVersion: 2, max 8 MB). Contains project rules, provider and project public keys, DDoS settings, blocked IPs, and OAuth/passport issuer JWKS. Protected against rollback attacks via a monotonic bundleSequence counter.
Freshness & Offline WindowsEvery bundle includes generatedAt, refreshAfter (+5 minutes), and offlineUntil (+24 hours). The background manager polls the Control Plane every 30 s (±10% jitter) using ETag (304 Not Modified). While Date.now() < refreshAfter, snapshot.fresh is true; if the external network drops, the server continues verifying locally until min(offlineUntil, generatedAt + maxOfflineMs).
PolicySnapshotStoreStorage backend for the signed JWS bundle (atomic temp-file write with 0o600 permissions in FilePolicySnapshotStore, or a custom Redis/KV adapter). Enables instant process cold starts.
Provider (External Publisher)External AI agent platform or developer registered in the directory with a unique canonical Signature-Agent, public keys, passports, and dynamic reputation (trustScore 0–100, abuseScore 0–100).
Project Signing KeyInternal signing key issued inside your project for first-party agents, background workers, or CI tests with projectKeyScopes permissions. Takes precedence over the global registry if a (Signature-Agent, kid) locator collides.
Agent-PassportVerified evidence of agent attributes sourced from the PolicyBundle, OAuth token, or HTTP headers (verified org, A2A card, World ID human backing, mTLS/SPIFFE workload certificate, or payment token).
Replay StoreSingle-use registry of accepted signature digests SHA-256('jwk:' + keyid + '\0' + signatureBytes) with TTL expires + 30s. Prevents replay of intercepted requests.
Trust TierAssignment Criteria & Effective trustScore Formula
TIER_1Major curated AI platforms that passed manual review (trustSource: manual_review) with abuseScore < 60. Base trustScore floor: 90.
TIER_2Publishers with an active key and a verified domain (DNS/HTTP), verified organization, or strong verified passport (org_verified, human_verified, a2a_signed_card, world_agentkit, PoP-bound agentbouncer_passport, spiffe, mtls_client_cert, enterprise_oidc, skyfire_kya) with abuseScore < 60. Base trustScore floor: 75.
TIER_3New or unverified external providers using domain directory keys, or any provider whose abuseScore >= 60. Base trustScore floor: 40. Bundle score formula: max(trustScore, tierFloor, min(90, bestPassportScore)) - round(abuseScore * 0.5).
INTERNAL_TEST / UNKNOWNInternal test profiles (floor 20) and suspended or revoked participants (SUSPENDED, REVOKED, BANNED, FRAUD → blocked status, effectiveTrustScore = 0).

Keep These Three Secret Classes Strictly Separate

1) AGENTBOUNCER_API_KEY (ab_live_ prefix) stays only on your protected server for background PolicyBundle downloads and telemetry. 2) AGENT_PRIVATE_JWK stays only in the AI agent's secret manager and is never transmitted over the network. 3) OAuth 2.1 Bearer tokens belong to the end user and are attached in the Authorization header after computing the RFC 9421 signature.

Server Protection

TypeScript Server SDK (@agentbouncer/sdk)

Configuring AgentBouncer.create(), reverse-proxy IP extraction, serverless bootstrap, Redis stores, and full export reference.

Runtime Requirements & Lifecycle

@agentbouncer/sdk v1.0.1 is an ESM-only package for Node.js >= 22. Always instantiate the client once per process via await AgentBouncer.create(...) (or the createAgentBouncer(...) alias). Never create a new instance inside per-request handlers. Telemetry is disabled by default—pass telemetry: true to view analytics in the dashboard.

Full Initialization with All Options (AgentBouncerClientOptions)
typescript
import {
  AgentBouncer,
  FilePolicySnapshotStore,
  MemoryRateLimitStore,
  MemoryReplayStore,
} from "@agentbouncer/sdk";

export const bouncer = await AgentBouncer.create({
  // Required options:
  apiKey: process.env.AGENTBOUNCER_API_KEY!,
  projectId: process.env.AGENTBOUNCER_PROJECT_ID!,
  trustedBundlePublicKeys: JSON.parse(process.env.AGENTBOUNCER_BUNDLE_KEYS!),
  snapshotStore: new FilePolicySnapshotStore("./.cache/policy-bundle.jws"),

  // Recommended production options:
  controlPlaneUrl: "https://app.agentbouncer.io", // Must use https://
  publicOrigin: "https://mcp.example.com",        // External origin for @authority verification behind proxies
  telemetry: true,                                // Enables background hourly rollup reporting
  telemetryFlushIntervalMs: 5_000,                // Buffer flush interval (default 5s)
  telemetryMaxEntries: 500,                       // Max unique rollups in memory (up to 500)
  syncIntervalMs: 30_000,                         // Bundle ETag poll interval (min 1,000 ms, default 30s)
  maxOfflineMs: 24 * 60 * 60 * 1000,              // Local offline tolerance (default 24h)
  maxBodyBytes: 1024 * 1024,                      // Max body size for SHA-256 Content-Digest (1 MB)

  // Optional signed JWS bundle for instant cold starts in air-gapped / serverless environments:
  bootstrapSignedBundle: process.env.AGENTBOUNCER_BOOTSTRAP_BUNDLE,

  // Optional local DDoS rate limiter override:
  // Note: passing a rateLimit object enables local rate limiting even if cloud ddos.enabled is false.
  rateLimit: {
    trustProxyHeaders: true,                      // Reads cf-connecting-ip -> x-real-ip -> x-forwarded-for[0]
    // ipHeader: "cf-connecting-ip",              // Or specify one exact header set by your edge proxy
    store: new MemoryRateLimitStore(50_000),
  },
  replayStore: new MemoryReplayStore(100_000),
  onSyncError: (error) => {
    console.warn("[AgentBouncer] Background bundle sync failed:", error);
  },
});

// Graceful shutdown with final telemetry flush (up to 2s timeout):
process.once("SIGTERM", () => {
  void bouncer.close();
});
@agentbouncer/sdk ExportBehavior
bouncer.verify(options)Verifies a Request locally ({ request, targetUrl?, action?, tool?, expectedTag?, clientIp?, userToken?, forwardAuthorization? }) and always returns AgentBouncerVerificationResult without throwing on policy denials.
bouncer.require(options)Calls verify() and throws AgentBouncerDeniedError (including error.verification) when allowed === false.
bouncer.refreshPolicies() / bouncer.close()Triggers an immediate PolicyBundle refresh (deduplicating concurrent calls) and cleanly stops background timers.
bouncer.reportFeedback(options)Submits a quality signal or abuse report (positive, negative, abuse, or rating 1–5) to the global reputation registry.
isOAuthRequired(v) / isOAuthScopeDenied(v) / getRequiredOAuthScopes(v)Helpers to classify OAuth 2.1 step-up challenges and extract required scopes when protecting non-MCP REST APIs.
createContentDigest(body) / verifyContentDigest(body, header) / verifyRequestContentDigest(req, maxBytes?)Low-level helpers for computing and constant-time verifying SHA-256 Content-Digest headers (RFC 9530).
extractClientIp(headers, customIpHeader?, trustStandardProxyHeaders?)Safe IPv4/IPv6 extractor and normalizer for trusted proxy headers.

Two Crucial Rules When Calling bouncer.verify() Manually

1) Always call verify() BEFORE reading request.json() or request.text() so the SDK can stream-verify Content-Digest via request.clone(). 2) By default, forwardAuthorization: true parses Authorization strictly as Bearer <jwt> and strips sensitive headers (cookie, x-api-key, authorization) from signature inputs. If your REST endpoint uses Basic auth or custom Authorization schemes, pass forwardAuthorization: false (otherwise requests will be rejected with malformed_authorization).

Protecting a Custom REST API Route with 429 / 401 / 403 Handling
typescript
import { getRequiredOAuthScopes, isOAuthRequired, isOAuthScopeDenied } from "@agentbouncer/sdk";
import { bouncerPromise } from "@/lib/bouncer";

export async function POST(request: Request) {
  const bouncer = await bouncerPromise;
  const verification = await bouncer.verify({
    request,
    action: "checkout.create",
    tool: "payments",
    expectedTag: "web-bot-auth",
  });

  if (!verification.allowed) {
    if (verification.reason === "rate_limit_exceeded" || verification.reason === "ip_blocked") {
      const retryAfter = String(verification.retryAfterSeconds ?? 60);
      return Response.json(
        { error: verification.reason, retryAfterSeconds: Number(retryAfter) },
        { status: 429, headers: { "Retry-After": retryAfter, "Cache-Control": "no-store" } },
      );
    }

    if (isOAuthRequired(verification)) {
      return Response.json(
        { error: "oauth_required", requiredScopes: getRequiredOAuthScopes(verification) },
        { status: 401, headers: { "Cache-Control": "no-store" } },
      );
    }

    return Response.json(
      {
        error: isOAuthScopeDenied(verification) ? "insufficient_scope" : "access_denied",
        reason: verification.reason,
        decisionId: verification.decisionId,
      },
      { status: 403, headers: { "Cache-Control": "no-store" } },
    );
  }

  const body = await request.json();
  return Response.json({ ok: true, provider: verification.provider?.slug, data: body });
}
Distributed Redis Adapters for Multi-Replica Clusters (Snapshot + Replay + RateLimit)
typescript

Implement PolicySnapshotStore, AgentBouncerReplayStore, and AgentBouncerRateLimitStore to share bundle snapshots, replay protection, and rate-limit counters across Kubernetes pods or serverless workers.

Server Protection

MCP Server Protection (withMcpProtection)

Automatic JSON-RPC 2.0 operation inspection, batch verification, and spec-compliant MCP OAuth 2.1 (RFC 9728) responses.

The @agentbouncer/sdk/mcp subpath exports four helpers: withMcpProtection(), verifyMcpRequest(), createMcpDenialResponse(), and buildMcpWwwAuthenticateHeader(). The guard enforces maxBodyBytes (default 1 MB), validates Content-Digest, parses single or batched JSON-RPC 2.0 payloads (up to 50 operations), and evaluates every operation against your policy.

HTTP / JSON-RPC MethodExtracted actionExtracted tool
POST · "tools/call"tools/call<params.name> (e.g., orders.refund)
POST · "prompts/get"prompts/getprompt:<params.name>
POST · "resources/read"resources/readresource:<params.uri>
POST · other methods ("initialize", "tools/list")<entry.method>null
POST · JSON-RPC client response (result / error)mcp/client_responsenull
GET (server-sent events stream)mcp/ssenull
DELETE (MCP session termination)mcp/session.deletenull
Any other HTTP method (PUT, PATCH...)Rejected with HTTP 405JSON-RPC code: -32600, Allow: POST, GET, DELETE
Denial ConditionHTTP StatusJSON-RPC Payload & Headers
Rate limit exceeded or IP blocked429error.code: -32029, header Retry-After: <seconds>
User OAuth 2.1 login required (step_up)401error.code: -32001, WWW-Authenticate: Bearer resource_metadata="...", scope="..." (adds error="invalid_token" when a malformed/invalid token was sent)
Insufficient user OAuth scopes403error.code: -32003, WWW-Authenticate: Bearer ..., error="insufficient_scope"
Policy denial / invalid signature or passport403error.code: -32003, error.data: { reason, decisionId }
Payload exceeds maxBodyBytes / invalid JSON or batch413 / 400error.code: -32700 (Parse error / too large) or -32600 (Invalid Request)
Using withMcpProtection() with Resource Metadata Options
typescript
import { withMcpProtection } from "@agentbouncer/sdk/mcp";
import { bouncerPromise } from "@/lib/bouncer";

export async function POST(request: Request) {
  const bouncer = await bouncerPromise;

  return withMcpProtection(
    bouncer,
    async (req, { verification, operations }) => {
      // For JSON-RPC batches, ALL items in operations (up to 50) have been verified
      return mcpServerTransport.handleRequest(req, {
        agentProvider: verification.provider,
        passports: verification.passports,
        oauthUser: verification.oauth,
        operations,
      });
    },
    {
      // Defaults to <origin>/.well-known/oauth-protected-resource
      resourceMetadataUrl: "https://mcp.example.com/.well-known/oauth-protected-resource",
      maxBodyBytes: 1024 * 1024,
      allowBatch: true, // Set false to disallow JSON-RPC array batches
    },
  )(request);
}
Express / Fastify Integration via verifyMcpRequest()
typescript
Server Protection

Official AgentBouncer MCP Server and x402 Payments

Connect to https://mcp.agentbouncer.io/mcp from Claude Code, Cursor, and autonomous agents. The server offers 26 tools, OAuth 2.1 with PKCE, on-chain top-ups via x402, and a sandbox for testing your signatures.

The official AgentBouncer remote MCP server is available at https://mcp.agentbouncer.io/mcp (Streamable HTTP transport, stateless JSON-RPC 2.0) and is protected by the @agentbouncer/sdk package itself. You can use it to manage projects, keys, and Policy v2 policies directly from your IDE, find verified providers in the registry, test outgoing RFC 9421 signatures and agent passports, and pay for plans autonomously in USDC on Base via x402.

Live sandbox for testing agents that sign their requests

You can use inspect_caller_security, verify_signed_agent, verify_tier2_agent, and verify_passport_holder for free at https://mcp.agentbouncer.io/mcp to see how the AgentBouncer reference verifier interprets your Signature, Content-Digest, and Agent-Passport headers.

Connecting in Claude Code, Cursor, and Windsurf
bash
# 1. Connect in Claude Code with a single command:
  claude mcp add --transport http agentbouncer https://mcp.agentbouncer.io/mcp
  
  # 2. Check the server status and metadata with curl:
  curl -s https://mcp.agentbouncer.io/mcp | jq .
  
  # OAuth 2.1 Protected Resource Metadata (RFC 9728):
  # https://mcp.agentbouncer.io/.well-known/oauth-protected-resource
Policy v2 Access CategoryTools and ResourcesRequired Credentials
Public (public)search_trusted_providers, lookup_provider_trust, get_pricing_plans, inspect_caller_security, register_account_start, register_account_verify, login_account, plus the agentbouncer://docs/quickstart and agentbouncer://docs/policy-v2 resourcesNo token required. Per-IP rate limits apply, with a higher registration limit for agents that sign requests under RFC 9421.
Signatures and passports (signature)verify_signed_agent, verify_tier2_agent, verify_passport_holderA valid RFC 9421 Web Bot Auth signature and Content-Digest. verify_tier2_agent also requires TIER_1 or TIER_2 and trustScore >= 70; verify_passport_holder also requires an agentbouncer_passport proof-of-possession (PoP) passport with cnf.jkt.
Billing and x402 (oauth)get_my_billing_status, topup_wallet_x402, create_crypto_topup_invoice, subscribe_plan, buy_extra_events_packAn OAuth 2.1 Bearer JWT with the billing:read / billing:write scopes.
Projects and policies (oauth)list_my_projects, get_project_security_summary, create_project, rotate_project_api_key, set_project_policy_mode, set_project_custom_policyAn OAuth 2.1 Bearer JWT with the projects:read / projects:write scopes.
Providers and passport issuance (oauth)list_my_providers, register_my_provider, sync_provider_a2a_card, issue_portable_passportAn OAuth 2.1 Bearer JWT with the providers:read / providers:write scopes.
Dual authentication (signature_and_oauth)manage_project_ip_blockBoth an RFC 9421 cryptographic signature from the agent and an OAuth 2.1 user token with the projects:admin scope.
  1. 1

    Authenticate with OAuth 2.1 and PKCE or register without a browser

    In interactive clients such as Claude Code and Cursor, the OAuth 2.1 consent screen opens automatically after a 401 response with a WWW-Authenticate header, letting you select scopes. A browserless autonomous agent can call register_account_start followed by register_account_verify (or call login_account) to obtain an access_token and a refresh_token.

  2. 2

    Request an x402 top-up quote

    Call topup_wallet_x402({ amountUsd: 29 }) without the paymentPayload parameter. The server returns an x402 PaymentRequirements object for USDC on Base (eip155:8453).

  3. 3

    Sign the EIP-3009 payment and activate your plan instantly

    Sign the authorization with the agent's wallet and pass it in a second call: topup_wallet_x402({ amountUsd: 29, paymentPayload }). After pre-settlement anti-money laundering (AML) screening with Chainalysis and TRM Labs and on-chain settlement, the funds are credited to the balance immediately. The agent can then call subscribe_plan and create_project.

Agent Request Signing

Signing Outbound Requests in TypeScript

Creating RFC 9421 cryptographic signatures and SHA-256 Content-Digest headers in TypeScript and Node.js.

AgentBouncerSigner (and createAgentBouncerSigner) produces a standard Fetch Request ready to send with Signature-Agent, Content-Digest, Signature-Input, and Signature headers (web-bot-auth profile). Signatures cover @authority, signature-agent, @method, @path, and @query, plus content-type and content-digest when present.

Two Mandatory Rules for TypeScript Signing

1) Always pass method: 'POST' (or 'PUT' / 'PATCH') explicitly to signer.signJson({ url, method: 'POST', json }), because sign() defaults to 'GET', which rejects request bodies with body_not_allowed. 2) Never reuse the same signed Request instance—call signJson() / sign() fresh for every outbound request and retry.

Signing JSON-RPC and REST Requests in TypeScript
typescript
import { createAgentBouncerSigner } from "@agentbouncer/sdk";

const signer = createAgentBouncerSigner({
  privateJwk: JSON.parse(process.env.AGENT_PRIVATE_JWK!),
  keyId: process.env.AGENT_KEY_ID, // Optional if "kid" is already present inside privateJwk
  signatureAgent: "https://agent.acme.ai",
  expiresInMs: 60_000, // Integer between 1,000 and 300,000 ms (default 60,000 ms)
});

const signedRequest = await signer.signJson({
  url: "https://mcp.example.com/api/mcp",
  method: "POST",
  headers: {
    "Agent-Passport": process.env.AGENTBOUNCER_PASSPORT_JWT!,
  },
  json: {
    jsonrpc: "2.0",
    id: 1,
    method: "tools/call",
    params: { name: "orders.refund", arguments: { orderId: "ord_91" } },
  },
  // OAuth Bearer token is normalized and excluded from covered signature components:
  accessToken: userOAuthAccessToken,
});

const response = await fetch(signedRequest);
Signing GET Requests (e.g., MCP SSE Stream) or Raw Bytes
typescript
const signedSseRequest = await signer.sign({
  url: "https://mcp.example.com/api/mcp",
  method: "GET",
  headers: { Accept: "text/event-stream" },
  accessToken: userOAuthAccessToken,
});

const sseResponse = await fetch(signedSseRequest);
Agent Request Signing

Python Signer SDK (agentbouncer-signer)

Sign outbound HTTP and MCP requests in Python 3.10+ with native integrations for httpx, the official Python MCP SDK, and requests.

The official PyPI package agentbouncer-signer (imported as agentbouncer_signer) is built for Python agents using LangGraph, CrewAI, PydanticAI, AutoGen, and the official Python MCP SDK. The core package depends only on cryptography and exports AgentBouncerSigner, create_agent_bouncer_signer, SignedRequest, generate_ed25519_jwk_pair, compute_jwk_thumbprint, create_content_digest, verify_content_digest, and AgentBouncerError.

JWK Key Type (kty)Supported Signer ParametersDirectory Compatibility
OKP (recommended)crv: "Ed25519", alg: "EdDSA" (or omitted) -> ed25519Supported everywhere: both external Provider Directories and Project Keys.
ECcrv: "P-256" (ES256) or "P-384" (ES384) -> ecdsa-p256-sha256 / ecdsa-p384-sha384Supported for Project Keys (public provider directories strictly require Ed25519).
RSAalg: "PS512" (or omitted) or "RS256" -> rsa-pss-sha512 / rsa-v1_5-sha256Supported for Project Keys (public provider directories strictly require Ed25519).
Install from PyPI
bash
# With httpx support (recommended for async agents and the official mcp package):
pip install "agentbouncer-signer[httpx]"

# With requests support:
pip install "agentbouncer-signer[requests]"
Generate an Ed25519 Keypair with Automatic RFC 7638 kid
python
import json
from agentbouncer_signer import generate_ed25519_jwk_pair, compute_jwk_thumbprint

private_jwk, public_jwk = generate_ed25519_jwk_pair()

print("KID (SHA-256 JWK thumbprint):", public_jwk["kid"])
print("Public JWK (for /.well-known JWKS):", json.dumps(public_jwk))
print("Private JWK (store in AGENT_PRIVATE_JWK):", json.dumps(private_jwk))
Direct Integration with the Official Python MCP SDK (streamablehttp_client)
python

The official mcp client uses httpx internally and accepts auth=signer.httpx_auth(...) directly—every JSON-RPC call in the session automatically receives a fresh RFC 9421 signature and Content-Digest.

import json
import os
from agentbouncer_signer import AgentBouncerSigner
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client

signer = AgentBouncerSigner(
    private_jwk=json.loads(os.environ["AGENT_PRIVATE_JWK"]),
    signature_agent="https://agent.acme.ai",
    key_id=os.environ.get("AGENT_KEY_ID"),
    expires_in_ms=60_000,
)

async def run_mcp_agent(user_oauth_token: str | None = None):
    async with streamablehttp_client(
        url="https://mcp.example.com/api/mcp",
        headers={"Agent-Passport": os.environ["AGENTBOUNCER_PASSPORT_JWT"]},
        auth=signer.httpx_auth(access_token=user_oauth_token),
    ) as (read_stream, write_stream, _):
        async with ClientSession(read_stream, write_stream) as session:
            await session.initialize()
            tools = await session.list_tools()
            result = await session.call_tool("orders.refund", {"orderId": "ord_91"})
            return tools, result
Using httpx, requests, and Low-Level sign_json()
python
import httpx
import requests

# 1. Directly with httpx.AsyncClient or httpx.Client:
async with httpx.AsyncClient(auth=signer.httpx_auth(access_token=user_oauth_token)) as client:
    r1 = await client.post("https://mcp.example.com/api/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"})

# 2. With requests (request body must not be a streaming generator):
r2 = requests.post(
    "https://mcp.example.com/api/mcp",
    json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"},
    auth=signer.requests_auth(access_token=user_oauth_token),
    timeout=10,
)

# 3. Low-level signing (for aiohttp, urllib3, etc.) -> returns SignedRequest(url, method, headers, body):
signed = signer.sign_json(
    url="https://mcp.example.com/api/mcp",
    method="POST",
    json_data={"jsonrpc": "2.0", "id": 2, "method": "tools/list"},
    access_token=user_oauth_token,
)
# Send the exact bytes in signed.body over the wire to keep Content-Digest valid!
Identity & Trust

Providers, Domain Verification, Google A2A & Project Keys

Public Ed25519 JWKS directory requirements, TIER_2 promotion, key rotation, A2A signed cards, and internal Project Keys.

AgentBouncer supports two agent key registries: 1) global External Provider profiles for public and partner AI agents; 2) Project Signing Keys for your internal bots, microservices, and test suites.

  1. 1

    Publish a public Ed25519 directory for your provider

    Host a JSON document shaped as { "keys": [...] } (or { "jwks": { "keys": [...] } }, up to 500 keys) at https://<domain>/.well-known/http-message-signatures-directory. Provider directories strictly accept Ed25519 public keys (kty: 'OKP', crv: 'Ed25519', alg: 'EdDSA', without private field 'd'). Only public HTTPS domains on port 443 are allowed. If kid is omitted, the registry computes the RFC 7638 SHA-256 thumbprint; numeric nbf and exp (Unix seconds) are also supported.

  2. 2

    Verify domain ownership to publish and promote to TIER_2

    On publisher-enabled plans (Verified Publisher, Pro, Business, Enterprise), add a DNS TXT record at _agentbouncer.<domain> with value agentbouncer-domain-verification=abdv_... OR host the token at https://<domain>/.well-known/agentbouncer-verification.txt. Domain verification promotes the provider to TIER_2 (trustScore floor >= 75) and automatically suspends unverified squatters on the same domain.

  3. 3

    Optionally publish a signed Google A2A Agent Card

    Host https://<domain>/.well-known/agent-card.json with an RFC 8785 (JCS) Flattened JWS signature and trigger a sync in the dashboard. When signed by a known provider key or on a verified domain, an a2a_signed_card passport (7-day TTL, score up to 90) is added to the PolicyBundle.

  4. 4

    Issue Project Signing Keys for internal services

    If your first-party agent does not need a public registry entry, generate a key in the Agent Keys tab of your project and assign projectKeyScopes. Disabling allowProjectKeys on the project immediately removes all internal keys from the PolicyBundle.

Important Provider Key Filtering & Rotation Rules

1) Until a provider's domain is verified (verifiedDomain === false), only keys fetched directly from the domain directory (source: 'directory') enter the global PolicyBundle. Dashboard-generated keys become active in bundles only after domain verification. 2) Key material is permanently bound to kid: changing the 'x' coordinate on an existing kid fails with directory_key_material_changed. To rotate keys, add a new key with a new kid; keys removed from your directory are marked REVOKED on the next sync and cannot be reactivated.

Example /.well-known/http-message-signatures-directory
json
{
  "keys": [
    {
      "kty": "OKP",
      "crv": "Ed25519",
      "kid": "acme-agent-2026-01",
      "alg": "EdDSA",
      "use": "sig",
      "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"
    }
  ]
}
Signing a Google A2A Agent Card (/.well-known/agent-card.json via RFC 8785 JCS)
typescript

The Control Plane strips the signatures field, canonicalizes the remaining JSON using RFC 8785 (JCS), and verifies the Flattened JWS against active provider keys (or a jku on the exact same domain).

Identity & Trust

Agent Passports, JWT Contract & Verifier Plugins

Built-in and custom Passport Issuers, portable PoP passports (cnf.jkt), World AgentKit, mTLS / SPIFFE, Skyfire KYA, and x402.

On every request, the SDK gathers passport evidence from three sources: the PolicyBundle registry (source: bundle), verified OAuth tokens (source: oauth), and request headers (source: header). Each passport receives a status of verified (eligible for requiredPassports rules and TIER_2 upgrades), presented (informational only), or invalid.

Strict Fail-Closed on Invalid Passports

If any presented passport header fails validation (expired, bad signature, wrong aud, or mismatched cnf.jkt key thumbprint), the local verifier immediately rejects the request with invalid_passport_<scheme> before evaluating any ALLOW rules.

SchemeSource & HeadersPoP / Standalone Behavior
org_verified / human_verifiedsource: bundle or portable JWT from https://app.agentbouncer.ioUpgrades an RFC 9421-signed provider from TIER_3 to TIER_2.
a2a_signed_card / a2a_card_hintsource: bundle (signed card) / A2A-Agent-Card headera2a_signed_card is verified and grants TIER_2; unverified header URLs are recorded as a2a_card_hint (presented).
agentbouncer_passportAgent-Passport or Sec-Agent-Passport header (max 16 KB)When PoP-bound (cnf.jkt / sig_agent), requires a matching RFC 9421 signature and grants TIER_2. Without PoP, requires exact host aud and can act as standalone identity.
world_agentkitAgentKit or X-AgentKit header + agentKitVerifier callbackMarked verified when agentKitVerifier succeeds (score 90 with humanId, else 70), grants TIER_2, and works as standalone.
mtls_client_cert / spiffecreateMtlsHeaderVerifier() or OAuth sub starting with spiffe://Automatically switches scheme to spiffe if cert URI/Subject starts with spiffe://. Works both with signatures and as standalone TIER_2.
enterprise_oidc / oauth_actorOAuth JWT with idtyp='app' (or sub === client_id) or act claimenterprise_oidc verifies autonomous corporate workloads (standalone TIER_2); oauth_actor captures human-to-agent delegation (humanId = oauth.sub).
skyfire_kya / x402Skyfire-Pay-Id and Payment-Signature / X-PaymentVerified via createPaymentPassportVerifier(). Verified skyfire_kya acts as standalone TIER_2 (score 90); x402 attests payment (score 85).
Agent-Passport JWT ClaimRequiredLocal Verifier Enforcement
issYesMust match https://app.agentbouncer.io (built into every bundle) or a project-configured Passport Issuer (JWKS cached for 7 days, auto-renewed 24h before expiry).
sub / expYesAgent identifier (max 300 chars) and expiration timestamp (±30s clock skew tolerance).
cnf.jktRecommended (PoP)RFC 7638 SHA-256 base64url thumbprint of the public JWK used to sign the HTTP request under RFC 9421. Prevents stolen passport reuse (cnf_jkt_mismatch).
sig_agentOptional (PoP)Canonical Signature-Agent URL; if present, must match the request's Signature-Agent header (signature_agent_mismatch).
audRequired if no PoPMust match the target server host (<host> or https://<host>; '*' is permitted only when PoP-bound via cnf.jkt or sig_agent).
passport_scheme / assertion_typeOptionalScheme allowed by the issuer (defaults to the issuer's first scheme) and assertion type (defaults to PORTABLE_PASSPORT).
score / human_idOptionalTrust score 0..100 (defaults to 85) and backing human identifier (automatically forwarded in reportFeedback).
Configuring Built-in and Custom Passport Verifier Plugins
typescript
import {
  AgentBouncer,
  createMtlsHeaderVerifier,
  createPaymentPassportVerifier,
  FilePolicySnapshotStore,
  type CustomPassportVerifier,
} from "@agentbouncer/sdk";

const partnerVerifier: CustomPassportVerifier = async ({ headers, signerJwkThumbprint }) => {
  const raw = headers.get("x-partner-attestation");
  if (!raw) return null;
  const ok = await verifyPartnerJwt(raw, signerJwkThumbprint);
  return {
    scheme: "partner_attested",
    assertionType: "PARTNER_KYA",
    source: "header",
    status: ok ? "verified" : "invalid",
    issuer: "https://trust.partner.example",
    subject: "partner-agent",
    score: ok ? 85 : 0,
  };
};

export const bouncer = await AgentBouncer.create({
  apiKey: process.env.AGENTBOUNCER_API_KEY!,
  projectId: process.env.AGENTBOUNCER_PROJECT_ID!,
  trustedBundlePublicKeys: JSON.parse(process.env.AGENTBOUNCER_BUNDLE_KEYS!),
  snapshotStore: new FilePolicySnapshotStore("./.cache/policy-bundle.jws"),

  agentKitVerifier: async (headerValue, { url, method }) => {
    return await verifyWorldAgentBookSignature(headerValue, { url, method });
  },

  passportVerifiers: [
    // Enable mTLS header verification ONLY when your Ingress/Envoy strips and overwrites these headers at the edge!
    createMtlsHeaderVerifier({
      trustedProxyConfirmed: true,
      verifiedHeader: "x-client-cert-verified",
      subjectHeader: "x-forwarded-client-cert",
    }),
    createPaymentPassportVerifier({
      skyfireIssuer: {
        issuer: "https://api.skyfire.xyz",
        audience: "https://mcp.example.com",
        jwks: JSON.parse(process.env.SKYFIRE_JWKS!),
      },
      x402Verifier: async (paymentHeader, ctx) => verifyX402Receipt(paymentHeader, ctx),
    }),
    partnerVerifier,
  ],
});
Authorization & DDoS

Policy Modes, Policy Schema v2 & DDoS Limits

Preset modes, complete Policy v2 rule syntax, offline unit testing, and dual-bucket IP rate limiting.

Policy Mode (policyMode)Evaluation Behavior
MONITOR_ONLYRuns all cryptographic checks and rules normally, forces allowed: true, strips OAuth hints, and records the potential block reason in policy.wouldBlockReason and checks.policy = 'monitor_only'.
BLOCK_UNKNOWNAllows known directory providers with abuseScore <= 70, standalone verified passports, and Project Keys (if allowProjectKeys is enabled); blocks unsigned bots.
ALLOW_TIER_1_ONLYAllows only TIER_1 platforms (maxAbuseScore: 70) and, when allowProjectKeys is enabled, your Project Signing Keys.
ALLOW_TIER_1_AND_2Allows TIER_1 platforms, verified TIER_2 publishers and passports (maxAbuseScore: 70), and your Project Signing Keys.
CUSTOMEvaluates the deterministic Policy Schema v2 rule list (version: 2, defaultEffect: 'DENY', up to 100 rules per project).
Policy v2 Rule FieldType & DefaultDescription & Validation
id / namestring (required)Unique rule ID (no duplicates) and human-readable name (max 120 chars).
effect"ALLOW" | "DENY"DENY rules are evaluated before all ALLOW rules and accept only id, name, effect, actions, and tools.
actionsstring[] (min 1, e.g. ["*"] or ["tools/call"])Allowed actions or '*' to match any action.
toolsstring[] (min 1, e.g. ["*"] or ["orders.refund"])MCP tool names (including prompt:<name> and resource:<uri>) or '*'.
credential"public" | "signature" | "oauth" | "signature_and_oauth"Required credential mode: unauthenticated, agent signature/passport only, user OAuth only, or both.
signerTypesArray<"PROVIDER" | "PROJECT_KEY"> (default both)Restricts allowed signer types to external providers and/or internal project keys.
providerTiersProviderTier[] (default [])Allowed provider tiers (e.g. ['TIER_1', 'TIER_2']). Requires a signature-based credential.
minTrustScore / maxAbuseScoreint 0..100 (default 0 and 100)Minimum required provider trustScore and maximum allowed abuseScore.
oauthScopesstring[] (default [])All listed scopes must exist in the user's OAuth token (requires an oauth credential; triggers step_up if missing).
projectKeyScopesstring[] (default [])Required scopes on a Project Signing Key (requires a signature credential).
requiredPassportsstring[] (default [])All listed passport schemes must have status verified (e.g. ['org_verified', 'x402']).
requireFreshSnapshotboolean (default false)Requires an online-fresh PolicyBundle (Date.now() < refreshAfter, i.e., synced within the last 5 minutes).
Production Policy Schema v2 Example & CI Unit Test
typescript
import { PolicySchema } from "@agentbouncer/sdk/contracts";
import { evaluatePolicy } from "@agentbouncer/sdk/policy";

const policy = PolicySchema.parse({
  version: 2,
  defaultEffect: "DENY",
  rules: [
    {
      id: "deny-dangerous-tools",
      name: "Block destructive data deletion",
      effect: "DENY",
      actions: ["tools/call"],
      tools: ["users.delete_all"],
    },
    {
      id: "public-mcp-discovery",
      name: "Allow public MCP discovery",
      effect: "ALLOW",
      actions: ["initialize", "notifications/initialized", "tools/list"],
      tools: ["*"],
      credential: "public",
    },
    {
      id: "paid-analytics-tool",
      name: "Paid analytics tool via x402",
      effect: "ALLOW",
      actions: ["tools/call"],
      tools: ["market.deep_report"],
      credential: "signature",
      providerTiers: ["TIER_1", "TIER_2"],
      requiredPassports: ["x402"],
    },
    {
      id: "refund-with-user-consent",
      name: "Order refund: Tier 1/2 agent + user OAuth + fresh snapshot",
      effect: "ALLOW",
      actions: ["tools/call"],
      tools: ["orders.refund"],
      credential: "signature_and_oauth",
      signerTypes: ["PROVIDER"],
      providerTiers: ["TIER_1", "TIER_2"],
      minTrustScore: 75,
      maxAbuseScore: 20,
      oauthScopes: ["orders:refund"],
      requireFreshSnapshot: true,
    },
  ],
});

const decision = evaluatePolicy({
  policy,
  action: "tools/call",
  tool: "orders.refund",
  snapshotFresh: true,
  verifiedPassportSchemes: ["org_verified"],
  signature: {
    status: "valid",
    provider: { id: "prov_1", tier: "TIER_2", status: "VERIFIED", trustScore: 85, abuseScore: 0 },
  },
  oauth: { status: "none", authenticated: false, scopes: [] },
});
// decision.outcome === "step_up", decision.reason === "oauth_token_required"

Dual-Bucket DDoS Protection & Proxy Header Safety

For each client IP over windowSeconds (5..3600s, default 60s), two independent buckets are enforced: 1) Ceiling bucket ceil:<ip> (verifiedMaxRequestsPerIp, default 300 req/min) stops volumetric floods BEFORE reading the body or running cryptography. 2) Anonymous bucket anon:<ip> (maxRequestsPerIp, default 60 req/min) is consumed only by unverified requests (!result.verified). When exceeded with autoBlockMinutes > 0 (default 15m), public IPs are blocked immediately in memory and reported asynchronously to the Control Plane for cluster-wide bundle distribution. Note: with trustProxyHeaders: true, the SDK reads cf-connecting-ip -> x-real-ip -> first item of x-forwarded-for. Enable it only if your edge proxy overwrites client-supplied headers (or set a specific trusted header in rateLimit.ipHeader).

Authorization & DDoS

User OAuth 2.1, Roles & Step-Up Flow (RFC 9728)

Local JWT verification via cached JWKS, scope / scp / roles / act claim extraction, and end-to-end retry after 401.

When a rule requires credential: 'signature_and_oauth' (or 'oauth'), the SDK validates the Bearer JWT locally in memory against OAuth Issuer JWKS embedded in the PolicyBundle (cached for 7 days and auto-renewed by the cloud 24h before expiration). It verifies signature, iss, aud, exp, sub (±30s clock tolerance, max token length 32 KB), typ header compatibility (at+jwt / jwt), and issuer-level requiredScopes.

  • Scope normalization: merges space-delimited scope, string or array scp, and converts roles array entries into role:<name> scopes (e.g., role:admin).
  • Delegation (RFC 8693): if the token includes an act claim ({ sub, client_id }), the SDK populates verification.oauth.actor and emits a verified oauth_actor passport linked to the human (humanId = payload.sub).
  • Workload identities: if sub starts with spiffe:// or idtyp === 'app' (or sub === client_id), the SDK sets workloadType and emits a verified spiffe or enterprise_oidc passport.

Protocol Invariant: Re-Sign After HTTP 401 (Request A ≠ Request B)

In Request A (without a user token), the agent's signature is valid and immediately consumed by replayStore before returning HTTP 401 WWW-Authenticate. After obtaining the user's OAuth token, the agent MUST generate a brand-new RFC 9421 signature with a fresh nonce (Request B). Reusing the Signature / Signature-Input headers from Request A will fail with 403 replay_detected.

Protected Resource Metadata Endpoint (/.well-known/oauth-protected-resource/route.ts)
typescript
export function GET() {
  return Response.json(
    {
      resource: "https://mcp.example.com",
      authorization_servers: ["https://auth.example.com"],
      bearer_methods_supported: ["header"],
      scopes_supported: ["orders:read", "orders:refund"],
    },
    { headers: { "Cache-Control": "public, max-age=3600" } },
  );
}
End-to-End OAuth 2.1 Step-Up Flow on the Agent Side (TypeScript)
typescript

Handling an HTTP 401 WWW-Authenticate challenge from an MCP server, obtaining a user token, and retrying with a FRESH RFC 9421 signature.

import { createAgentBouncerSigner } from "@agentbouncer/sdk";

const signer = createAgentBouncerSigner({
  privateJwk: JSON.parse(process.env.AGENT_PRIVATE_JWK!),
  signatureAgent: "https://agent.acme.ai",
});

const rpcPayload = {
  jsonrpc: "2.0",
  id: 1,
  method: "tools/call",
  params: { name: "orders.refund", arguments: { orderId: "ord_91" } },
};

// Request A: call the tool without a user token
let res = await fetch(
  await signer.signJson({ url: "https://mcp.example.com/api/mcp", method: "POST", json: rpcPayload }),
);

if (res.status === 401) {
  const wwwAuth = res.headers.get("www-authenticate") ?? "";
  // Run OAuth 2.1 Authorization Code + PKCE for the scopes requested in wwwAuth:
  const freshUserToken = await obtainUserOAuthTokenViaPkce(wwwAuth);

  // Request B: MUST call signJson() again to generate a fresh nonce and signature!
  res = await fetch(
    await signer.signJson({
      url: "https://mcp.example.com/api/mcp",
      method: "POST",
      json: rpcPayload,
      accessToken: freshUserToken,
    }),
  );
}
Reference & Operations

Decision Contract, Reputation Feedback & Control Plane Endpoints

Full AgentBouncerVerificationResult schema, reportFeedback() mechanics, and background sync endpoints.

Full AgentBouncerVerificationResult Object
json
{
  "decisionId": "c4b8e210-9a14-4d73-8b11-5092f3e8c402",
  "verified": true,
  "allowed": true,
  "reason": null,
  "detail": null,
  "decision": {
    "outcome": "allow",
    "reason": "policy_allowed",
    "matchedRuleId": "refund-with-user-consent",
    "requiredScopes": [],
    "requirements": []
  },
  "snapshot": {
    "bundleId": "7d91a032-112c-4f08-9211-a4319d0f221b",
    "bundleSequence": "48",
    "fresh": true
  },
  "provider": {
    "id": "clx9p2m1a0004...",
    "slug": "acme-support-agent",
    "name": "Acme Support Agent",
    "kind": "EXTERNAL_PROVIDER",
    "tier": "TIER_2",
    "status": "VERIFIED",
    "trusted": true,
    "trustScore": 88,
    "abuseScore": 0,
    "identityConfidence": 90,
    "securityPosture": 85
  },
  "agent": {
    "type": "PROVIDER",
    "provider": "Acme Support Agent",
    "providerSlug": "acme-support-agent",
    "projectKey": null,
    "signatureAgent": "https://agent.acme.ai",
    "keyid": "acme-agent-2026-01"
  },
  "passports": [
    {
      "scheme": "org_verified",
      "assertionType": "VERIFIED_ORG_SPONSOR",
      "source": "bundle",
      "status": "verified",
      "issuer": "https://app.agentbouncer.io",
      "subject": "acme-support-agent",
      "score": 92
    }
  ],
  "oauth": {
    "status": "valid",
    "authenticated": true,
    "sub": "user_4821",
    "issuer": "https://auth.example.com",
    "clientId": "mcp-desktop-client",
    "actor": null,
    "workloadType": null,
    "scopes": ["orders:refund"],
    "error": null
  },
  "request": {
    "method": "POST",
    "path": "/api/mcp",
    "action": "tools/call",
    "tool": "orders.refund",
    "expectedTag": null,
    "tag": "web-bot-auth"
  },
  "checks": {
    "passport": "verified",
    "signature": "valid",
    "oauth": "valid",
    "policy": "matched"
  },
  "policy": {
    "mode": "CUSTOM",
    "wouldBlockReason": null,
    "matchedRule": {
      "id": "refund-with-user-consent",
      "name": "Order refund",
      "effect": "ALLOW"
    },
    "defaultEffectApplied": false
  },
  "tag": "web-bot-auth",
  "expectedTag": null
}
reportFeedback() InputReputation Delta & Anti-Gaming Protections
signal: "positive" (or rating: 5 / 4)trustScore +2 (or +1 for rating 4), abuseScore +0.
signal: "negative" (or rating: 2 / 1)trustScore -3, abuseScore +2 (for rating 1: trustScore -4, abuseScore +3; rating 3 is neutral).
signal: "abuse"Severe penalty for injection or malicious behavior: trustScore -8, abuseScore +12. Crossing 10-point score bands or abuseScore >= 60 bumps the global registry revision for all projects.
Anti-manipulation guardsIdempotent deduplication by decisionId; self-boosting of your own provider is blocked; 1-hour cooldown per userId subject and max 5 score-shifting signals per provider from a single project within 24 hours.
Submitting Agent Behavior Feedback After Tool Execution
typescript
const feedback = await bouncer.reportFeedback({
  verification, // Automatically populates decisionId, providerId, userId, action, tool, and passport
  signal: "abuse",
  reason: "sql_injection_payload_in_arguments",
  metadata: { blockedQuery: true }, // Up to 4 KB of custom JSON
});
// feedback -> { ok: true, eventId, duplicate, appliedDeltaTrust, trustScore }
Background Control Plane EndpointPurpose & Protocol
GET /api/v1/policy-bundleDownloads the signed JWS bundle with If-None-Match / 304 Not Modified support.
POST /api/v1/telemetry/batchIngests hourly aggregated counters (up to 500 items and 1,000,000 events per batch; request bodies and user tokens are never transmitted). Idempotent by batchId.
POST /api/v1/ddos/report-blockAsynchronously reports public IPv4/IPv6 addresses auto-blocked by local rate limits (private/loopback IPs are ignored).
POST /api/v1/feedbackReceives reputation signals submitted by bouncer.reportFeedback().
Reference & Operations

Plan Quotas, Telemetry Limits & Offline Mode

Plan tier limits, quota grace buffers, and running the SDK in fully isolated (air-gapped) environments.

ParameterFreeVerified PublisherProBusinessEnterprise
Included verifications (30d)25,00050,000500,0005,000,00050,000,000+
Analytics log retention3 days14 days30 days90 days365 days
Projects / Policy v2 rules1 / 52 / 155 / 5025 / 100500 / 100
Project Keys / Providers2 / 1 (1 key)5 / 3 (10 keys)20 / 3 (5 keys)100 / 10 (25 keys)1,000 / 100 (200 keys)
OAuth / Passport Issuers1 / 01 / 13 / 215 / 15100 / 100
Tier 2 domain publishingNoYesYesYesYes
Cluster IP blocklist50 IPs100–500 IPs500 IPs5,000 IPs5,000 IPs
  • Soft quota buffer (Grace Multiplier): all plans include a +20% buffer (+50% on Enterprise) above the monthly event quota before telemetry ingestion pauses.
  • Free-tier exhaustion behavior: once the buffer is exhausted, a 72-hour PolicyBundle sync grace window begins. If the quota is still not topped up after 72 hours, GET /api/v1/policy-bundle returns HTTP 402 quota_exceeded while the local SDK continues serving traffic from its cached bundle until offlineUntil.
  • Air-gapped mode (Enterprise): set telemetry: false and distribute the signed JWS bundle via bootstrapSignedBundle or a shared internal PolicySnapshotStore.
Reference & Operations

Reason Codes, SDK Exceptions & Production Checklist

Distinguishing verification.reason values from startup/signing exceptions, troubleshooting, and go-live checklist.

AgentBouncer separates two classes of codes: 1) verification.reason values returned cleanly by verify() in the result object without throwing; 2) initialization and signing exceptions (Error / AgentBouncerError) thrown when AgentBouncer.create() or AgentBouncerSigner receives invalid configuration or malformed inputs.

verification.reason CodeCause & Resolution
ip_blocked / rate_limit_exceededClient IP is on the blocklist or exceeded the rate limit in windowSeconds (returns retryAfterSeconds). Verify trustProxyHeaders / ipHeader behind your load balancer.
request_body_verification_failed / request_body_too_largeRequest body stream was already consumed before calling verify(), or exceeded maxBodyBytes (default 1 MB).
content_digest_mismatch / body_digest_requiredBody bytes do not match the SHA-256 Content-Digest header, or the header is missing on a POST/PUT/PATCH request. Ensure proxies do not reformat JSON.
malformed_authorizationAuthorization header is present but not formatted as Bearer <token>. For routes using Basic/custom auth, pass forwardAuthorization: false.
incomplete_signature / signature_agent_required / malformed_signature_input / no_keyid / signature_time_requiredOne of the required RFC 9421 headers (Signature, Signature-Input, or Signature-Agent) is missing or malformed.
weak_signature_profileSignature does not cover all required components: @method, @authority, @path, @query, signature-agent (plus content-type and content-digest when present).
bad_signatureCryptographic signature verification failed. Behind Nginx/Docker/Vercel, request.url often resolves to http://localhost:3000 instead of your public HTTPS domain; configure publicOrigin in AgentBouncer.create().
unknown_keyid / key_expired / key_not_yet_validThe (Signature-Agent, kid) pair is missing from the PolicyBundle or expired. Remember: until a provider's domain is verified, only Ed25519 keys from the domain's /.well-known directory appear in bundles.
not_yet_valid / expired / window_too_longcreated / expires timestamps in Signature-Input are invalid (max window 300s, NTP clock skew tolerance ±30s).
unsupported_tag / tag_mismatchSignature-Input tag is not 'web-bot-auth' or does not match expectedTag.
replay_detectedThis signature was already used. Generate a fresh signature via sign() / signJson() / httpx_auth on every call and retry (especially after OAuth 401).
invalid_passport_<scheme>A presented passport header failed validation (details in passports[i].claims.reason: cnf_jkt_mismatch, signature_agent_mismatch, unbound_passport_missing_audience, domain_mismatch, expired).
provider_blockedThe agent provider is blocked or revoked in the trust registry (SUSPENDED, BANNED, FRAUD, REVOKED).
oauth_token_required / oauth_insufficient_scope / agent_identity_requiredstep_up outcome: a matching ALLOW rule requires a user OAuth 2.1 token, additional scopes, or an agent signature.
oauth_token_invalid / oauth_token_malformed / oauth_token_unknown_issuer / oauth_token_unavailableBearer JWT is malformed, failed signature/aud/exp validation, has an unconfigured iss, or its issuer keysValidUntil snapshot expired.
fresh_snapshot_requiredThe matching rule has requireFreshSnapshot: true, but the local bundle age exceeded refreshAfter (5 minutes without Control Plane sync).
passport_required / reputation_threshold_not_metAgent lacks a verified passport listed in requiredPassports or fails the rule's trustScore / abuseScore thresholds (including maxAbuseScore: 70 in presets).
explicit_policy_deny / no_satisfied_allow_ruleBlocked by an explicit DENY rule or no ALLOW rule matched (defaultEffect: DENY).
policy_snapshot_unavailableNo PolicyBundle is loaded or the local cache exceeded its offline window (offlineUntil / maxOfflineMs).
Exception (Error / AgentBouncerError)Where It Occurs & What to Check
api_key_and_project_id_required / invalid_control_plane_urlAgentBouncer.create(): empty apiKey/projectId, or controlPlaneUrl does not use https://.
untrusted_bundle_signing_key / invalid_bundle_public_key / bundle_context_mismatchAgentBouncer.create(): trustedBundlePublicKeys is missing the Ed25519 key for the bundle's kid, or projectId does not match.
bundle_download_failed:401 / bundle_download_failed:402PolicyBundle sync: invalid AGENTBOUNCER_API_KEY (401), or Free-tier quota and 72h grace period exhausted (402).
bundle_rollback_detected / bundle_offline_limit_exceededAttempted load of an older bundle with a lower bundleSequence, or the 24h offline window expired prior to cold start.
missing_signing_key_id / missing_signature_agent / invalid_signature_windowAgentBouncerSigner constructor (TS & Python): missing keyId/kid, empty signatureAgent, or expiresInMs outside 1,000..300,000 ms.
body_not_allowed / invalid_private_jwk / unsupported_jwk_algorithmAgentBouncerSigner.sign(): non-empty body passed to GET/HEAD (e.g., forgot method: 'POST' in TS signJson), or private JWK missing 'd'.

Production Go-Live Checklist

Verify every item below before switching your project from MONITOR_ONLY to BLOCK_UNKNOWN or CUSTOM:

  • AgentBouncer.create() is initialized once as a process-wide singleton with telemetry: true and await bouncer.close() wired to process shutdown signals.
  • FilePolicySnapshotStore points to a writable persistent path (or RedisSnapshotStore is configured for ephemeral/serverless containers).
  • publicOrigin matches the exact external HTTPS origin signed by AI agents.
  • Client IP extraction is properly configured (rateLimit.ipHeader or trustProxyHeaders: true behind a proxy that strips spoofed client IP headers).
  • Every route gates execution strictly on verification.allowed (or uses withMcpProtection / bouncer.require) before reading the request body.
  • MONITOR_ONLY analytics confirm that legitimate agents do not trigger unexpected values in wouldBlockReason.
  • Three negative tests pass: tampering with a single JSON byte returns 403 content_digest_mismatch, replaying the same signed request returns 403 replay_detected, and calling an OAuth-protected tool without a user token returns 401 WWW-Authenticate.