npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@agentadmit/sdk

v1.11.0

Published

AgentAdmit SDK: user-mediated AI agent authorization for Node.js apps

Readme

@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 returned session_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-mounted generate-token route) is a sandbox facility for aa_test_ keys only; a live key receives 403 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

  1. User clicks "AgentAdmit" in your app
  2. Selects scopes and connection duration
  3. Gets a token to give to their AI agent
  4. Agent exchanges the token for scoped API access
  5. 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 by requireScope and requireScopeIfAgent.
  • 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:

  1. 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-language actionSummary you provide.
  2. The hosted service refuses the first call with confirmation_required and stages a one-time ceremony for exactly that action. Your route returns 403 with a confirmation block; the agent gives confirmation.action_session_url to the user.
  3. 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.
  4. 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".
  • validateAgentToken throws ConfirmationRequiredError (a VerifyRefusedError) with the typed confirmation block when you build your own middleware.
  • Confirmation only applies when the call declares the exercised scope, which requireScope always does.

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 from Retry-After header (or null)
  • limit - X-RateLimit-Limit header value (or null)
  • remaining - X-RateLimit-Remaining header value (or null)
  • reset - X-RateLimit-Reset Unix timestamp (or null)

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 returns a denial object instead of throwing can never let the mint proceed.

App-Attested Presence (forward the ceremony fact)

Your ceremony is origin-bound, so AgentAdmit never witnesses it: by default the hosted service reports presence.verified: false for connections your hook gated, even though a real passkey ceremony happened. To close that gap, return an AppAttestedPresence from the hook after verifying and consuming your attestation:

import { AppAttestedPresence } from '@agentadmit/sdk';

requireTokenMintPresence: async (req, currentUser) => {
  const attestation = await verifyAndConsumePasskeyAttestation({
    userId: currentUser.user_id,
    attestationId: req.body?.presence_attestation_id,
    purpose: 'token_mint',
  });
  if (!attestation) {
    const err: any = new Error('Confirm human presence before generating a connection token');
    err.statusCode = 403;
    err.detail = { error: 'presence_attestation_required' };
    throw err;
  }
  return new AppAttestedPresence({
    method: 'my_webauthn',              // lowercase alphanumeric/underscore
    verifiedAt: attestation.createdAt,  // Date, or ISO string WITH offset
  });
},

The SDK forwards it to the hosted mint as presence: {verified: true, uv: true, method, verified_at}. The hosted service validates freshness (10-minute window, 60 s future clock-skew slack) and stores the method provenance-marked app:<method> so app-attested facts stay distinct from ceremonies AgentAdmit witnessed itself. Introspection, the grant-event ledger, and the evidence API then carry presence.verified: true for the connection, and the local record behind GET /connections carries the same presence object.

Honesty ceiling: this is your app's attestation, recorded and provenance-marked. It is not witnessed by AgentAdmit and not independently verifiable. Only construct one for a ceremony that verified the user with UV (biometric or PIN user verification); verified/uv are literal true. A ceremony without UV carries no presence fact, so return nothing instead. Pass verifiedAt as a Date (serialized safely) or an ISO-8601 string with an explicit offset; offset-less strings are rejected at construction because the hosted mint rejects them.

Declared Purpose

Declared purpose: the user-facing reason recorded on the grant at the consent moment. Review-time record only, never an enforcement input; authorization decisions ride scopes, connection status, and consent.

Pass an optional purpose (1–300 characters) when generating a connection token; the SDK forwards it to the hosted mint, which records it on the grant:

// POST /agentadmit/connections/generate-token
{ "scopes": ["read:things"], "purpose": "Reconcile July invoices" }

The verify response reports it back on every introspection, and it rides into your middleware context as req.agentAdmit.purposeundefined when no purpose was declared:

app.get('/api/invoices', requireScope('read:invoices'), (req, res) => {
  const ctx = (req as any).agentAdmit;
  // Show it in your own audit views or connection lists:
  console.log(`Access under declared purpose: ${ctx.purpose ?? '(none declared)'}`);
});

Do not branch authorization on purpose — it is a record for humans reviewing a grant, not a gate. Scope checks, connection status, and consent verdicts remain the only decision inputs.

User-Declared Intent

User-declared intent: the user's own words for what they want the agent to do, typed at the consent moment. Where purpose records the app's words — the app's declared reason for the grant — user_intent records the user's own words. Review-time record only, never an enforcement input; authorization decisions ride scopes, connection status, and consent.

Pass an optional user_intent (1–300 characters) when generating a connection token; the SDK forwards it to the hosted mint, which records it on the grant:

// POST /agentadmit/connections/generate-token
{ "scopes": ["read:things"], "user_intent": "Find me the cheapest flight to Lisbon in October" }

It flows identically to purpose: recorded on the grant, reported back on verify, carried on audit rows and ledger events. When the hosted presence ceremony runs, the intent is included in the verifiable-consent-evidence commitment, so the user's authenticator signs their own words alongside the rest of the consent evidence.

The verify response reports it back on every introspection, and it rides into your middleware context as req.agentAdmit.user_intentundefined when no intent was declared:

app.get('/api/flights', requireScope('read:flights'), (req, res) => {
  const ctx = (req as any).agentAdmit;
  // Show it in your own audit views or connection lists:
  console.log(`Access under user-declared intent: ${ctx.user_intent ?? '(none declared)'}`);
});

Do not branch authorization on user_intent — it is a record for humans reviewing a grant, not a gate. Scope checks, connection status, and consent verdicts remain the only decision inputs.

Security Alerts

Monitor suspicious agent activity. Six alert types:

  • volume_spike, failed_scope_attempts, burst_pattern,
  • stale_reactivation, new_scope_usage, revoked_connection_attempt

Configure Alert Thresholds

import { configureAlerts } from '@agentadmit/sdk';

await configureAlerts({
  app_id: 'app_abc123',
  alert_type: 'volume_spike',
  enabled: true,
  threshold_value: 100,
  threshold_window_minutes: 5,
  kill_switch_enabled: true,
});

List Alert Events

import { listAlerts } from '@agentadmit/sdk';
const { events, total } = await listAlerts({ app_id: 'app_abc123', alert_type: 'volume_spike' });

Get Current Config

import { getAlertConfig } from '@agentadmit/sdk';
const config = await getAlertConfig({ app_id: 'app_abc123' });

Notifying Your Users

AgentAdmit detects anomalies, fires alerts, and (with kill switch) auto-revokes connections. How you notify your own users is up to you. AgentAdmit provides the data - you deliver it through your own system (in-app notifications, email, push, etc.).

  • Poll alerts - Use the SDK methods above from your backend to check for new events, then notify users through your existing system.

  • Webhook delivery - Configure a webhook URL in your AgentAdmit dashboard. When an alert fires, AgentAdmit POSTs the payload to your server, signed with your whsec_… secret. The payload carries alert_id, alert_type, severity, the connection's agent_label, and the grant's declared purpose; the full shape is documented in the Webhook Delivery section of the MCP guide at https://agentadmit.com/docs/mcp-guide. Always verify the signature against the raw request body before trusting the payload:

    import express from 'express';
    import { verifyWebhookSignature, WebhookSignatureError } from '@agentadmit/sdk';
    
    app.post('/agentadmit/alerts', express.raw({ type: 'application/json' }), (req, res) => {
      try {
        verifyWebhookSignature(
          req.body, // raw Buffer
          req.header('X-AgentAdmit-Signature') ?? '',
          process.env.AGENTADMIT_WEBHOOK_SECRET!, // whsec_…
        );
      } catch (err) {
        if (err instanceof WebhookSignatureError) {
          return res.status(400).json({ error: 'invalid_signature' });
        }
        throw err;
      }
      const event = JSON.parse(req.body.toString('utf-8'));
      // ...
      res.sendStatus(200);
    });

    The header format is t=<unix_ts>,v1=<hex> - an HMAC-SHA256 of ${t}.${rawBody} keyed with your signing secret. The helper compares in constant time and rejects timestamps more than 5 minutes off (replay protection).

  • React SDK - Embed the <AlertsPanel> component so users can view their own alert history and tighten thresholds.