@agentadmit/sdk - Node.js
User-mediated AI agent authorization. Plug-and-play for Express and Next.js.
Get started: Sign up at agentadmit.com → Get your test keys → Install the SDK → Build. Test keys are available immediately after signup. Live keys become available when you subscribe an app.
Where the consent step runs (live keys). The agent grant is approved on the AgentAdmit hosted consent page, opened on your app's behalf: your backend creates a consent session (
POST /api/v1/apps/{app_id}/consent-sessions) with your live key and sends the signed-in user to the returnedsession_url. Scope selection, duration, intent, existing-grant review, the passkey ceremony, and the one-time token all happen there. Direct token issuance (POST /api/v1/apps/{app_id}/token, and this SDK's issue-token helpers and any SDK-mountedgenerate-tokenroute) is a sandbox facility foraa_test_keys only; a live key receives403 hosted_consent_required. Verification (/verify) is unchanged and is the core of this SDK. Full walkthrough: App Owner Guide, Step 4.
Quick Start
npm install @agentadmit/sdk
Create an agentadmit.yaml file to define your scopes (see Configuration below), then add to your Express app:
const express = require('express');
const { loadConfig, createStorage, createAgentAdmitRouter, setStorage, requireScopeIfAgent } = require('@agentadmit/sdk');
const app = express();
app.use(express.json());
// Initialize AgentAdmit
const config = loadConfig('agentadmit.yaml');
const storage = createStorage(config);
setStorage(storage);
// Create and mount AgentAdmit routes
const { wellknownRouter, agentadmitRouter } = createAgentAdmitRouter({
storage,
getCurrentUser: async (req) => { /* your auth logic */ },
});
app.use(wellknownRouter);
app.use('/agentadmit', agentadmitRouter);
// Protect your routes with scope enforcement
app.get('/api/orders', requireScopeIfAgent('read:orders'), (req, res) => {
const user = req.agentAdmit?.user;
// Your existing logic - unchanged
res.json({ orders: getOrdersForUser(user.user_id) });
});
Next.js API Routes
// pages/api/orders.ts (or app/api/orders/route.ts)
import { validateAgentToken, getConfig } from '@agentadmit/sdk';
export default async function handler(req, res) {
const token = req.headers.authorization?.replace('Bearer ', '');
const config = getConfig();
if (token?.startsWith(config.token_prefix_access)) {
const ctx = await validateAgentToken(token);
if (!ctx.scopes.includes('read:orders')) {
return res.status(403).json({ error: 'insufficient_scope' });
}
// Agent path
return res.json({ orders: await getOrders(ctx.user.user_id) });
}
// Regular user path
// ... your existing auth
}
MCP Server Integration
Building an MCP server in TypeScript/Node? AgentAdmit is the auth layer. MCP servers are app owners. Same SDK, same pricing.
For STDIO transport (most MCP servers), the agent includes the token in tool arguments:
const { validateAgentToken } = require('@agentadmit/sdk');
async function handleToolCall(name, args) {
// 1. Extract token from tool arguments
const token = args.agentadmit_token;
delete args.agentadmit_token;
if (!token) throw new Error('agentadmit_token required');
// 2. Validate via AgentAdmit hosted service
const ctx = await validateAgentToken(token);
// 3. Check scope for this tool
const required = SCOPE_MAP[name];
if (required && !ctx.scopes.includes(required)) {
throw new Error(`Missing scope '${required}'`);
}
// 4. Run the tool
return TOOL_HANDLERS[name](args, ctx);
}
For HTTP transport (Express-based MCP servers), use the full SDK middleware. The agent sends the token via Authorization: Bearer header, same as any HTTP API.
Full MCP integration guide with complete before/after examples: agentadmit.com/docs/mcp-guide
MCP operators: You also get the embeddable admin panel for monitoring connections and usage, full audit trail for billing, and user-initiated revocation. See the Embeddable Admin Panel section below.
How It Works
- User clicks "AgentAdmit" in your app
- Selects scopes and connection duration
- Gets a token to give to their AI agent
- Agent exchanges the token for scoped API access
- User revokes anytime
The token goes to the human, not the agent. No automated delivery = no prompt injection surface.
Important
Mandatory introspection. All token validation goes through api.agentadmit.com. There is no self-hosted mode. No local JWT validation. No bypass. This is required for security, audit logging, and scope enforcement.
User revocation. Users revoke connections via DELETE /agentadmit/connections/{connection_id}. The SDK route verifies the requesting user owns the connection before forwarding the revocation to the hosted service; local storage is updated only after the hosted revoke succeeds.
Embeddable admin panel. Drop the <AgentAdmitAdminPanel> React component into your admin section to view all agent connections, usage metrics, billing status, and revoke any connection without leaving your app. See the React SDK for details.
In-app AI scopes. If your app has built-in AI features (analysis, plan generation, photo recognition), do not expose those as agent scopes. The user's AI agent can read the raw data and do the analysis itself. Exposing in-app AI endpoints to agents creates double cost.
Per-Call Audit Telemetry
Since 1.10.0, every verification call reports what the call actually did, so the app's tamper-evident audit log on the AgentAdmit hosted service records per-call usage instead of just token validity:
scope_used- the scope the route enforces, sent automatically byrequireScopeandrequireScopeIfAgent.endpoint- the inbound request path (path only; the query string is never sent).method- the HTTP method.
No integration changes are needed: the middlewares you already use collect
these automatically. Calls verified without a scope-enforcing middleware
(resolveAuth, requirePresence, or a bare validateAgentToken) still send
endpoint and method, and the hosted audit log honestly records that no
exercised scope was declared. Direct validateAgentToken(token, telemetry)
callers can pass a VerifyTelemetry object themselves.
callerConsent({ requiredScope }) reports the same three fields and sets the
hosted consent_first guard automatically, so a denied caller class cannot
learn scope state before the middleware returns its consent 403.
The SDK also fails closed on per-call refusals: when the hosted service answers
that the token is valid but THIS call is refused (insufficient_scope,
bound_exceeded when a user-set usage ceiling is reached, or any future
refusal class), the middleware returns 403 (VerifyRefusedError for direct
callers) and never invokes your route handler.
Confirm Each Time (Exercise-Time Human Confirmation)
Some actions should never run on a standing grant alone: moving money, sending
or publishing on the user's behalf, deleting data, touching production. Mark
those scopes confirm_each_time: true when you register them, and the hosted
service requires a fresh human confirmation for every call that exercises
them, even inside a valid connection.
In agentadmit.yaml:
scopes:
- name: write:payments
description: Move money
category: Payments
role: user
confirm_each_time: true
The flag is typed on ScopeDefinition and round-trips unchanged to the
/scopes endpoint the hosted service reads, so the registration your app
publishes is the policy the hosted service enforces.
How a call flows:
- The agent calls your route. The SDK verifies the token as usual, carrying
the exercised scope, a
sha256:digest of the request body, and the plain-languageactionSummaryyou provide. - The hosted service refuses the first call with
confirmation_requiredand stages a one-time ceremony for exactly that action. Your route returns 403 with aconfirmationblock; the agent givesconfirmation.action_session_urlto the user. - The user confirms on AgentAdmit's hosted page with their passkey. The signature commits to the scope, method, endpoint, request digest, and the summary they saw. Only a user-verified ceremony produces an attestation; the agent cannot complete it.
- The agent retries the same request with the header
X-AgentAdmit-Action-Attestation: <action_session_id>. The SDK forwards it, the hosted service consumes the attestation once (exact action only), and the call proceeds. The audit row names the confirmation.
import { requireScope, ConfirmationRequiredError } from '@agentadmit/sdk';
app.post(
'/api/payments',
requireScope('write:payments', {
actionSummary: (req) => `Pay ${req.body.trainer} $${req.body.amount}`,
}),
handler,
);
The 403 body an agent receives on the first call:
{
"error": "confirmation_required",
"error_description": "Scope \"write:payments\" requires a fresh human confirmation for each call. ...",
"confirmation": {
"action_session_id": "asess_...",
"action_session_url": "https://agentadmit.com/confirm/action/asess_...",
"expires_at": "2026-09-02T18:30:00.000Z",
"scope": "write:payments",
"method": "POST",
"endpoint": "/api/payments",
"request_digest": "sha256:...",
"summary": "Pay Alex $50"
}
}
Notes:
- The summary is yours. AgentAdmit shows it as the headline of the confirmation page and commits to the text shown; it does not verify the description against the request.
- A confirmation covers exactly one call. A retry with a different body, route,
method, or summary is refused again with
attestation_status: "action_mismatch". validateAgentTokenthrowsConfirmationRequiredError(aVerifyRefusedError) with the typedconfirmationblock when you build your own middleware.- Confirmation only applies when the call declares the exercised scope, which
requireScopealways does. - The user can decline. If the user taps Decline on the hosted page, the
hosted service answers the agent's retry with
confirmation_declinedand holds that answer untildeclined.hold_until; no new ceremony is staged and the user is not notified again. Your route returns 403 with thedeclinedblock;validateAgentTokenthrowsConfirmationDeclinedError(aVerifyRefusedError) with the typeddeclinedblock. Agents should relay the decline to the user and not retry unless the user asks. Only the user can lift a decline; after the hold ends, a retry stages a fresh confirmation.
{
"error": "confirmation_declined",
"error_description": "The user declined this action on the hosted confirmation page. Do not retry it unless the user asks you to; no new confirmation can be staged for this action until 2026-09-22T21:50:42.000Z.",
"declined": {
"action_session_id": "asess_...",
"declined_at": "2026-09-22T21:35:42.000Z",
"hold_until": "2026-09-22T21:50:42.000Z",
"scope": "write:payments",
"method": "POST",
"endpoint": "/api/payments",
"request_digest": "sha256:...",
"summary": "Pay Alex $50"
},
"renewal": "Only the user can lift a decline. After the hold ends, a retry stages a fresh confirmation for them to approve or decline again."
}
Rate Limiting
The AgentAdmit introspection endpoint enforces rate limits. The Node.js SDK handles HTTP 429 responses automatically with exponential backoff and jitter - no changes needed in your middleware code.
Retry behavior
| Parameter | Default | Description |
|---|---|---|
| Initial delay | 1 second | First retry wait |
| Backoff multiplier | 2× | Doubles each retry |
| Cap | 30 seconds | Maximum wait per retry |
| Jitter | 0–500 ms | Random addition to each delay |
| Max retries | 3 | Configurable |
The SDK also respects the Retry-After response header - if present, it overrides the computed backoff delay.
Configuring max retries
In agentadmit.yaml:
max_retries: 5 # default: 3. Set to 0 to disable retries.
Handling exhausted retries
When all retries are exhausted, validateAgentToken throws RateLimitError:
import { requireScope, RateLimitError } from '@agentadmit/sdk';
app.use((err: any, req, res, next) => {
if (err instanceof RateLimitError) {
res.set('Retry-After', String(err.retryAfter ?? 60));
return res.status(429).json({
error: 'rate_limited',
retry_after: err.retryAfter,
limit: err.limit,
remaining: err.remaining,
reset: err.reset,
});
}
next(err);
});
RateLimitError properties:
retryAfter- seconds fromRetry-Afterheader (ornull)limit-X-RateLimit-Limitheader value (ornull)remaining-X-RateLimit-Remainingheader value (ornull)reset-X-RateLimit-ResetUnix timestamp (ornull)
Documentation
Full integration guide: https://agentadmit.com/docs/app-owner-guide
Data Collection & Privacy
The AgentAdmit Node.js SDK runs server-side and does not interact with app stores or end-user devices directly.
What the SDK does
- Validates AgentAdmit tokens by calling AgentAdmit's hosted introspection endpoint (
https://api.agentadmit.com/api/v1/verify) on every agent request - this is mandatory introspection; there is no local or offline validation mode - Enforces scope-based access control on your API routes
- Manages connection lifecycle (create, revoke, audit) using your configured storage backend
What the SDK does NOT do
- Does not transmit raw end-user PII (such as name, email, or device identifiers) - each introspection request sends the opaque access token and your API key
- Does not perform passive background telemetry or analytics - network calls occur only during active token validation
- Does not maintain its own persistent storage - local state (connections, audit log) lives in the storage backend you configure
What the AgentAdmit hosted service records
On every token validation, AgentAdmit's /api/v1/verify endpoint receives the access token and API key, resolves the token to its user_id, connection_id, granted scopes, and agent_label, and records per-call metadata (including the endpoint and timestamp) for billing, audit logging, the security alerts engine, and usage metering. This is integral to how AgentAdmit works and applies to both test and live keys. See the "Mandatory introspection" notes above and the compliance guide for the full data-handling description.
Privacy impact
Since this SDK runs on your server, it has no direct App Store or Play Store compliance surface. Your client-side integration (e.g., the AgentAdmit React SDK) handles privacy manifest and data safety requirements.
For complete compliance guidance, see our compliance guide.
License
All rights reserved. Patent pending.
Consent Ledger (Caller-Identity Consent)
AgentAdmit can host per-user consent switches for three independent caller classes: human_session, in_app_ai, and external_agent. No class's setting implies another's.
External agents: the verify response already includes the verdict; it rides into your middleware context as req.agentAdmit.consent. The hosted service deliberately omits the verdict when its consent store is unreadable (degraded mode), so treat an absent verdict as unresolved, never as a grant — resolve it with checkConsent:
app.get('/api/workouts', requireScope('read:workouts'), async (req, res) => {
let { consent, user } = (req as any).agentAdmit;
if (!consent || typeof consent.granted !== 'boolean') {
consent = await checkConsent({ appUserId: user.user_id, callerClass: 'external_agent' }); // fail closed on error
}
if (consent.granted !== true) {
return res.status(403).json({ error: 'consent_not_granted' });
}
// serve the data
});
The callerConsent() middleware does all of this for you: it evaluates the consent verdict before the scope check (a caller whose class the owner denied learns nothing about scope state or step-up) and resolves an absent verdict through the Consent Ledger, fail-closed.
Human sessions and in-app AI never hold AgentAdmit tokens, so ask directly:
import { checkConsent } from '@agentadmit/sdk';
const verdict = await checkConsent({ appUserId: 'user_8842', callerClass: 'in_app_ai' });
if (!verdict.granted) {
// do not run AI over this user's data
}
Consent is orthogonal to revocation: a denied verdict means your app returns its own 403; the connection and token stay valid so the user can flip consent back on without re-connecting. Write the switches through PUT /api/v1/consent/settings from your backend, and export the full audit trail with GET /api/v1/consent/export (every plan).
Presence Verification (Human Presence)
Connections authorized on the AgentAdmit hosted consent page can require a WebAuthn ceremony (Touch ID, Windows Hello, a security key) before the token is generated. The verify response reports the fact on every introspection as presence, and it rides into your middleware context as req.agentAdmit.presence:
import { requirePresence, presenceVerified } from '@agentadmit/sdk';
// Gate a sensitive route on a presence-verified connection (403 otherwise):
app.post('/api/transfers', requirePresence(), transferHandler);
// Or branch on it yourself:
app.get('/api/workouts', requireScope('read:workouts'), (req, res) => {
const ctx = (req as any).agentAdmit;
if (!presenceVerified(ctx)) {
// connection was minted without a human presence ceremony
}
});
To require presence at authorization time, create the consent session with "presence": "required"; token generation fails closed until a human completes the ceremony. requirePresence() is strict: connections from servers or sessions that never ran a ceremony report verified: false and are rejected.
Presence gate for embedded token minting
If you mount the SDK's user-authenticated /agentadmit/connections/generate-token
route inside your own app, gate that route with your app's own human-presence
ceremony. A browser-driving agent can ride a logged-in user session, so scoped
token minting should require a fresh passkey, WebAuthn, or equivalent
out-of-band confirmation before the hosted token call is made.
const { wellknownRouter, agentadmitRouter } = createAgentAdmitRouter({
storage,
getCurrentUser: async (req) => req.user ?? null,
requireTokenMintPresence: async (req, currentUser) => {
const ok = await verifyAndConsumePasskeyAttestation({
userId: currentUser.user_id,
attestationId: req.body?.presence_attestation_id,
purpose: 'token_mint',
});
if (!ok) {
const err: any = new Error('Confirm human presence before generating a connection token');
err.statusCode = 403;
err.detail = { error: 'presence_attestation_required' };
throw err;
}
},
});
The hook runs after user authentication and local request validation, and before AgentAdmit's hosted token mint or any local connection record is written. If no hook is configured, existing apps keep the previous behavior.
Throw to deny. The hook must throw to deny (attach statusCode/detail
for a custom response), and must verify and consume the attestation
single-use (checking alone lets it be replayed). Returning nothing allows the
mint; returning an AppAttestedPresence allows the mint and forwards the
ceremony fact (below); returning any other value fails closed with a 500 so
a misconfigured hook that retur