CCM
/MCP
SkillsMCPMarketplacesDigestToolsAdvertise

This week in Claude

Every Monday: Claude Code, Agent SDK, MCP, and the Anthropic platform moves worth your time.

Skills by Category
Frontend DevelopmentBackend & APIsTesting & QASecurityDevOps & CI/CDGit & Pull RequestsDocumentationCode Review & QualityAI & Agent BuildingSkill Development
MCP Servers by Category
Sales & MarketingWeb & Browser AutomationDatabasesAI & LLM ToolsCloud & InfrastructureCommunication & MessagingDeveloper ToolsDesign & CreativeDocuments & KnowledgeSearch & Web Crawling
Marketplaces by Category
AI Agents & OrchestrationLLM IntegrationDevelopment ToolsFrontend & UIBackend & APIsDatabasesTesting & Code QualityDevOps & CloudSecurity & ComplianceGit & Version Control

Claude Code Marketplaces

Discover Claude Code plugins, extensions, and tools. Automatically updated directory of Anthropic Claude AI marketplaces with development tools, productivity plugins, and integrations.

Resources

  • Browse Skills
  • Browse MCP Servers
  • Browse Marketplaces
  • Plugins Reference

Community

  • About
  • Tools
  • Feedback
  • Privacy Policy
  • Advertise

Built for the Claude Code community with Claude Code by @mertduzgun

Independent project, not affiliated with Anthropic

Grantex

mishrasanjeev/grantex
25authSTDIOregistry active
Summary

Grantex brings OAuth-style authorization to AI agents through scoped delegation tokens, audit trails, and per-agent identity. The MCP server exposes operations for agent registration, user consent flows, token exchange, and verification. You get signed JWTs with explicit scopes like calendar:read or payments:initiate:max_500, offline verification via JWKS, and granular revocation without rotating root credentials. It includes anomaly detection with built-in rules, Commerce V1 for agentic checkout flows (currently mock-provider only), and integrations for Anthropic, LangChain, OpenAI, and FastAPI. Reach for this when your agent needs to act on behalf of users without full API key access, or when you need audit logs and spending limits baked into the authorization layer. Self-hostable, Apache 2.0, with SDKs for TypeScript, Python, and Go.

CodeRabbit
CodeRabbit
AI writes the code. CodeRabbit catches the slop.
Try For Free →
AppSignal
AppSignal
Monitor with ease. Code with confidence.
Start Free Trial →
AI notepad for back-to-back meetings
AI notepad for back-to-back meetings
Notes, actions and memory. Without a meeting bot. First month 100% off.
Download for free →
Keep your Mac awake
Keep your Mac awake
Keep your Mac awake while Claude Code and 40+ AI agents run. Sleeps when they're idle.
One time payment $9 →
Email for Agents: Free tier availableEmail for Agents: Free tier available
Email for Agents: Free tier available
Give your AI agent a complete email layer—sending, inbound inboxes, and sandbox testing.
Get 4K emails/month free →
Context.devContext.dev
Context.dev
Integrate web data into your AI product. One API to scrape website & brand data.
Get API Key Now →
CodeScene MCP ServerCodeScene MCP Server
CodeScene MCP Server
Your agent targets a perfect 10 Code Health score. Deterministic. Every commit.
Try For Free →
Make your agent a DeFi expert
Make your agent a DeFi expert
Agent, run crypto. Access onchain data & trade routes via 1inch.
Install now →
CodeRabbit
CodeRabbit
AI writes the code. CodeRabbit catches the slop.
Try For Free →
AppSignal
AppSignal
Monitor with ease. Code with confidence.
Start Free Trial →
AI notepad for back-to-back meetings
AI notepad for back-to-back meetings
Notes, actions and memory. Without a meeting bot. First month 100% off.
Download for free →
Keep your Mac awake
Keep your Mac awake
Keep your Mac awake while Claude Code and 40+ AI agents run. Sleeps when they're idle.
One time payment $9 →
Email for Agents: Free tier availableEmail for Agents: Free tier available
Email for Agents: Free tier available
Give your AI agent a complete email layer—sending, inbound inboxes, and sandbox testing.
Get 4K emails/month free →
Context.devContext.dev
Context.dev
Integrate web data into your AI product. One API to scrape website & brand data.
Get API Key Now →
CodeScene MCP ServerCodeScene MCP Server
CodeScene MCP Server
Your agent targets a perfect 10 Code Health score. Deterministic. Every commit.
Try For Free →
Make your agent a DeFi expert
Make your agent a DeFi expert
Agent, run crypto. Access onchain data & trade routes via 1inch.
Install now →

Grantex

Open-Source AI Agent Authorization and Delegated Access

What OAuth 2.0 is to humans, Grantex is to agents.


License: Apache 2.0 Spec Version IETF Draft CI npm PyPI npm downloads GitHub Stars Docs MCP Tool Server MCP Auth DPDP Mapping EU AI Act Mapping


Docs | Quickstart | Release JSON | LLM Index | Spec | IETF Draft


Grantex Protocol Flow

What is Grantex?

Grantex is an open-source delegated authorization protocol and reference implementation for AI agents. It gives each agent a verifiable identity and scoped, time-limited, revocable authority from a human or organization, with multi-agent delegation, service-side verification, and audit records.

Grantex complements OAuth 2.0 and MCP: OAuth handles application and user authorization, MCP connects models to tools, and Grantex proves which agent may perform which action for which principal. Use Grantex when an AI agent acts for a person or organization and a relying service must verify exactly what that agent may do.

Open Agentic Commerce Protocol (OACP) Authority

Open Agentic Commerce Protocol (OACP) is Grantex's agentic-commerce trust and artifact-authority layer. Grantex governs OACP policy, internal artifact issuance or refusal, verification, and compatibility adapters. AgenticOrg owns buyer and seller AI-agent runtime, merchant self-service onboarding, Shopify connector runtime, future merchant connector setup intent, buyer sessions, channel bridges, OACP cache, and provider-owned capability verification.

Merchant systems such as Shopify, future WooCommerce/ERP sources, POS systems, and provider systems remain the source of record. Provider, bank, POS, and payment rails own mandate, payment, and in-store execution. Grantex signs and verifies artifacts; it is not a merchant connector runtime or a toll booth for every buyer and seller message.

flowchart LR
  merchant[Shopify, future ERP/WooCommerce, POS, provider systems] --> agentic[AgenticOrg buyer and seller runtime]
  agentic -->|redacted authority request| grantex[Grantex OACP authority]
  grantex -->|OACP artifacts or blockers| agentic
  agentic --> buyer[Buyer surfaces]
  agentic -->|capability check or handoff| provider[Pine Labs Plural/P3P, bank/POS/provider rails]
AreaCurrent posture
Grantex C6Z authority routeImplemented at POST /v1/commerce/oacp/c6z/authority-requests for allowlisted AgenticOrg tenants.
Artifact families11 internal OACP families are issued or refused with source lineage, TTL, freshness, revocation posture, blocked capabilities, non-sensitive evidence refs, and signature metadata.
Protocol adaptersSchema.org, UCP-style, ACP-style, AP2-style, A2A, MCP, and OpenAPI mappings are compatibility mappings derived from OACP artifacts.
AgenticOrg runtimeMerchant self-service config, Seller onboarding, Shopify sync, future connector/provider intent capture, cache, buyer Q&A, bridges, and provider capability verification live in AgenticOrg.
Payment/order/POS executionOutside OACP artifact authority. Provider, POS, and merchant systems must execute and confirm; agents must not invent success.
Historical Commerce V1 docsRetained for context, but superseded for the AgenticOrg OACP runtime split.

Start with the OACP runtime launch closure PRD, OACP authority overview, merchant self-service config boundary, truth inventory, AgenticOrg integration guide, POS bridge boundary, and operator runbook. The older Commerce V1 overview remains historical/contextual and should not be used to imply that Grantex owns AgenticOrg merchant connector runtime.

Current Releases

Grantex components are independently versioned. The protocol specification remains v1.0 Final; SDK, MCP package, and roadmap milestone versions are separate release lines and do not represent a monorepo-wide version.

Current public releases, verified 2026-07-12:

ComponentPublic versionReproducible install
TypeScript SDK@grantex/sdk 0.3.13npm install @grantex/sdk@0.3.13
Python SDKgrantex 0.3.14python -m pip install grantex==0.3.14
Go SDKgithub.com/mishrasanjeev/grantex-go v0.1.10 (Go 1.26.1+)go get github.com/mishrasanjeev/grantex-go@v0.1.10
MCP Authorization Server@grantex/mcp-auth 2.0.2npm install @grantex/mcp-auth@2.0.2 @grantex/sdk@0.3.13

Known published-package limits: Go SDK v0.1.10 has documented Agent/Audit read, write, filter, query-encoding, and list-metadata limitations. MCP Auth 2.0.2 keeps authorization codes in process memory, does not render consent, and has an incomplete Grantex code handoff. See the release-status guide for exact workarounds and deployment boundaries.

Repository development status (unreleased, July 14, 2026): source on main corrects all documented Go Agent/Audit contract gaps, removes no-op audit filters and phantom list metadata, and URL-encodes query values. The auth service also enforces Redis-backed Free/Pro/Enterprise developer budgets of 100/500/2,000 requests per minute on API-key routes handled by the standard auth plugin. Custom-auth quota policy remains open. No corrected Go tag or managed-service rollout is claimed; the public versions and workarounds above remain authoritative.

Omit a version pin to install the registry's current latest release. See the release-status documentation, COMPATIBILITY.md for the full package matrix, and CHANGELOG.md for release notes.

  • @grantex/gemma: Offline consent bundles and on-device verification examples
  • MCP Authorization Server (@grantex/mcp-auth): Published OAuth 2.1 + PKCE endpoint package; review the documented 2.0.2 single-process, consent, and token-exchange limitations
  • MCP Tool Server (@grantex/mcp): Agent-facing Grantex tools for MCP clients
  • @grantex/dpdp: DPDP Act 2023 and EU AI Act control mappings
  • Trust Registry: Public DID verification registry — grantex.dev/registry
  • grantex verify: Token inspection CLI — no account needed
  • Anomaly Detection: Four implemented SQL-backed checks, lifecycle APIs, and stored rule/channel configuration; notification delivery requires a host worker

SDK quickstart

npm install @grantex/sdk@0.3.13
import { Grantex, verifyGrantToken } from '@grantex/sdk';
const gx = new Grantex({ apiKey: process.env.GRANTEX_API_KEY });

// 1. Register an agent, then request authorization from a user
const agent = await gx.agents.register({
  name: 'quickstart-agent',
  description: 'Grantex quickstart agent',
  scopes: ['calendar:read', 'email:send'],
});
const auth = await gx.authorize({
  agentId: agent.id,
  userId: 'user-456',
  scopes: ['calendar:read', 'email:send'],
});

// Live mode requires consent at this URL and returns the code to your callback.
// Sandbox or policy auto-approval can return the code immediately.
if (!auth.code) {
  console.log(`Approve access at: ${auth.consentUrl}`);
} else {
  // 2. Exchange the authorization code for a scoped, signed JWT
  const { grantToken } = await gx.tokens.exchange({ code: auth.code, agentId: agent.id });

  // 3. Verify locally using the issuer's published JWKS
  const grant = await verifyGrantToken(grantToken, {
    jwksUri: 'https://api.grantex.dev/.well-known/jwks.json',
  });
  console.log(grant.scopes); // ['calendar:read', 'email:send']
}
python -m pip install grantex==0.3.14               # Python SDK
go get github.com/mishrasanjeev/grantex-go@v0.1.10 # Go SDK (Go 1.26.1+)
npm install @grantex/mcp-auth@2.0.2 @grantex/sdk@0.3.13 # MCP endpoint evaluation
npm install -g @grantex/cli                         # Optional CLI tooling

29 packages across TypeScript, Python, and Go. Integrations for Anthropic SDK, LangChain, OpenAI Agents SDK, Google ADK, Strands Agents SDK, CrewAI, Vercel AI, AutoGen, MCP, Express.js, FastAPI, and Terraform. Use the compatibility matrix for versions, the changelog for release notes, and GitHub Actions for current CI status. Fully self-hostable. Apache 2.0.


The Problem

AI agents are booking travel, sending emails, deploying code, and spending money — on behalf of real humans. But:

  • No scoping — agents get the same access as the key owner
  • No consent — users never approve what the agent can do
  • No per-agent identity — you know the key was used, but not which agent or why
  • No revocation granularity — one agent misbehaves, rotate the key, kill everything
  • No delegation control — Agent A calls Agent B? Copy-paste credentials
  • No spending limits — an agent with a cloud API key can provision unlimited resources

OAuth and IAM provide essential foundations, but many agent deployments still rely on shared credentials that do not identify the individual agent or encode its delegated authority.


How It Works

Grantex Protocol Flow

Quickstart

1. Register your agent

import { Grantex } from '@grantex/sdk';

const grantex = new Grantex({ apiKey: process.env.GRANTEX_API_KEY });

const agent = await grantex.agents.register({
  name: 'travel-booker',
  description: 'Books flights and hotels on behalf of users',
  scopes: ['calendar:read', 'payments:initiate:max_500', 'email:send'],
});

console.log(agent.did);
// → did:grantex:ag_01HXYZ123abc...

2. Request authorization from a user

const authRequest = await grantex.authorize({
  agentId: agent.id,
  userId: 'user_abc123',       // your app's user identifier
  scopes: ['calendar:read', 'payments:initiate:max_500'],
  expiresIn: '24h',
  redirectUri: 'https://yourapp.com/auth/callback',
});

// Redirect user to authRequest.consentUrl
// Grantex handles the consent UI — plain language, mobile-first
console.log(authRequest.consentUrl);
// → https://consent.grantex.dev/authorize?req=eyJ...

3. Exchange the authorization code for a grant token

// After user approves, your redirectUri receives a `code`.
// Exchange it for a signed grant token (RS256 JWT):
const token = await grantex.tokens.exchange({
  code,                  // from the redirect callback
  agentId: agent.id,
});

console.log(token.grantToken);  // RS256 JWT — pass this to your agent
console.log(token.scopes);      // ['calendar:read', 'payments:initiate:max_500']
console.log(token.grantId);     // 'grnt_01HXYZ...'

4. Verify the token and use it

// Verify locally after retrieving the issuer's published JWKS
import { verifyGrantToken } from '@grantex/sdk';

const grant = await verifyGrantToken(token.grantToken, {
  jwksUri: 'https://api.grantex.dev/.well-known/jwks.json',
  requiredScopes: ['calendar:read'],
});
console.log(grant.principalId); // 'user_abc123'
console.log(grant.scopes);     // ['calendar:read', 'payments:initiate:max_500']

// Pass to your agent — it's now authorized
await travelAgent.run({ grantToken: token.grantToken, task: 'Book cheapest flight to Delhi on March 1' });

5. Record the action at the execution boundary

// At the trusted execution boundary: explicitly record the outcome
await grantex.audit.log({
  agentId: agent.id,
  agentDid: agent.did,
  grantId: token.grantId,
  principalId: authRequest.principalId,
  action: 'payment.initiated',
  status: 'success',
  metadata: { amount: 420, currency: 'USD', merchant: 'Air India' },
});

6. Verify a token (service-side)

// In any service that receives agent requests — no Grantex account needed
import { verifyGrantToken } from '@grantex/sdk';

const grant = await verifyGrantToken(token.grantToken, {
  jwksUri: 'https://api.grantex.dev/.well-known/jwks.json',
  requiredScopes: ['payments:initiate'],
});
// Throws if the token is expired, tampered with, has invalid claims, or lacks required scopes.
// Use grantex.tokens.verify(token.grantToken) when you also need current revocation status.

7. Give users control over their permissions

// Generate a short-lived link for the end-user to view & revoke agent access
const session = await grantex.principalSessions.create({
  principalId: 'user_abc123',
  expiresIn: '2h',
});
// Send session.dashboardUrl to the user via email, in-app notification, etc.
// The short-lived session token is carried in the URL fragment, not the query string.

Python SDK

import os

from grantex import Grantex, AuthorizeParams, ExchangeTokenParams

client = Grantex(api_key=os.environ["GRANTEX_API_KEY"])

# Register agent
agent = client.agents.register(
    name="finance-agent",
    scopes=["transactions:read", "payments:initiate:max_100"],
)

# Authorize a user
auth = client.authorize(AuthorizeParams(
    agent_id=agent.id,
    user_id="user_abc123",
    scopes=["transactions:read", "payments:initiate:max_100"],
))
# Redirect user to auth.consent_url — they approve in plain language

# Exchange the authorization code for a grant token
token = client.tokens.exchange(ExchangeTokenParams(code=code, agent_id=agent.id))

# Verify locally after retrieving the issuer's published JWKS
from grantex import verify_grant_token, VerifyGrantTokenOptions

grant = verify_grant_token(token.grant_token, VerifyGrantTokenOptions(
    jwks_uri="https://api.grantex.dev/.well-known/jwks.json",
))
print(grant.scopes)  # ('transactions:read', 'payments:initiate:max_100')

# Log an action
client.audit.log(
    agent_id=agent.id,
    agent_did=agent.did,
    grant_id=token.grant_id,
    principal_id=auth.principal_id,
    action="transaction.read",
    status="success",
    metadata={"account_last4": "4242"},
)

The Grant Token

Grantex tokens are standard JWTs (RS256) extended with agent-specific claims. Any service can verify their signatures locally using the issuer's published JWKS. The provided verifiers retrieve those keys from the configured JWKS URL, so applications should account for network availability, caching, and key rotation:

{
  "iss": "https://grantex.dev",
  "sub": "user_abc123",
  "agt": "did:grantex:ag_01HXYZ123abc",
  "dev": "org_yourcompany",
  "scp": ["calendar:read", "payments:initiate:max_500"],
  "iat": 1709000000,
  "exp": 1709086400,
  "jti": "tok_01HXYZ987xyz",
  "grnt": "grnt_01HXYZ456def"
}
ClaimMeaning
subThe end-user who authorized this agent
agtThe agent's DID — cryptographically verifiable identity
devThe developer org that built the agent
scpExact scopes granted — services should check these
jtiUnique token ID — used for grant-state and revocation checks
grntGrant record ID — links token to the persisted grant
audIntended audience (optional) — services should reject tokens with a mismatched aud

Delegation claims (present on sub-agent tokens):

ClaimMeaning
parentAgtDID of the parent agent that spawned this sub-agent
parentGrntGrant ID of the parent grant — full delegation chain is traceable
delegationDepthHow many hops from the root grant (root = 0)

Multi-Agent Delegation

Grantex supports multi-agent pipelines where a root agent spawns sub-agents with narrower scopes. Sub-agent tokens carry a full delegation chain that any service can inspect.

// Root agent has a grant for ['calendar:read', 'calendar:write', 'email:send']
// It spawns a sub-agent that only needs calendar read access

const delegated = await grantex.grants.delegate({
  parentGrantToken: rootGrantToken,   // root agent's token
  subAgentId: subAgent.id,            // sub-agent to authorize
  scopes: ['calendar:read'],          // must be ⊆ parent scopes
  expiresIn: '1h',                    // capped at parent token's expiry
});

// delegated.grantToken is a fully signed JWT with:
//   parentAgt, parentGrnt, delegationDepth = 1
# Python equivalent
delegated = grantex.grants.delegate(
    parent_grant_token=root_grant_token,
    sub_agent_id=sub_agent.id,
    scopes=["calendar:read"],
    expires_in="1h",
)

Constraints enforced by the protocol:

  • Sub-agent scopes must be a strict subset of the parent's scopes — scope escalation is rejected with 400
  • Sub-agent token expiry is min(parent expiry, requested expiry) — sub-agents can never outlive their parent
  • Revoking a root grant cascades to all descendant grants atomically

Advanced Features

Enterprise SSO - OIDC and SAML 2.0, plus an LDAP direct-bind preview

Enterprise SSO

Grantex provides OIDC and SAML 2.0 enterprise SSO with multiple identity-provider connections, email-domain routing, enforcement, JIT provisioning, and group-to-scope mapping from identity-provider claims. The LDAP surface is a direct-bind preview: it authenticates a supplied directory identity but does not search directories or retrieve LDAP groups.

Key capabilities:

  • Multi-IdP connections - Configure multiple OIDC and SAML 2.0 identity providers per organization; LDAP connection records support the direct-bind preview
  • OIDC Discovery + JWKS verification — Automatic endpoint discovery and cryptographic ID token verification
  • SAML 2.0 — Full SAML response parsing with certificate-based signature verification
  • LDAP / Active Directory preview - Direct-bind authentication only; directory search and LDAP group retrieval are not implemented
  • Domain-based routing — Automatically route users to the correct IdP based on their email domain
  • JIT provisioning — Auto-create or update principals on first SSO login
  • Group-to-scope mapping - Map OIDC or SAML group/role claims to Grantex scopes; this does not retrieve LDAP groups
  • SSO enforcement — Require SSO authentication for all users in an organization
  • Session management — Track, list, and revoke active SSO sessions

TypeScript

// Create an OIDC connection
const conn = await grantex.sso.createConnection({
  name: 'Okta Production',
  protocol: 'oidc',
  issuerUrl: 'https://mycompany.okta.com',
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
  domains: ['mycompany.com'],
  jitProvisioning: true,
  groupAttribute: 'groups',
  groupMappings: { Engineering: ['read', 'write', 'deploy'], Admins: ['admin'] },
  defaultScopes: ['read'],
});

// Create a SAML 2.0 connection
await grantex.sso.createConnection({
  name: 'Azure AD SAML',
  protocol: 'saml',
  idpEntityId: 'https://sts.windows.net/tenant-id/',
  idpSsoUrl: 'https://login.microsoftonline.com/tenant-id/saml2',
  idpCertificate: '-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----',
  spEntityId: 'urn:grantex:mycompany',
  spAcsUrl: 'https://myapp.com/sso/callback/saml',
  domains: ['mycompany.com'],
});

// Enforce SSO for the organization
await grantex.sso.setEnforcement({ enforce: true });

// Handle OIDC callback with verified ID token
const result = await grantex.sso.handleOidcCallback({ code, state });
console.log(result.email, result.mappedScopes, result.sessionId);

// List and revoke sessions
const { sessions } = await grantex.sso.listSessions();
await grantex.sso.revokeSession(sessions[0].id);

Python

# Create an OIDC connection
conn = client.sso.create_connection(CreateSsoConnectionParams(
    name="Okta Production",
    protocol="oidc",
    issuer_url="https://mycompany.okta.com",
    client_id="your-client-id",
    client_secret="your-client-secret",
    domains=["mycompany.com"],
    jit_provisioning=True,
    group_attribute="groups",
    group_mappings={"Engineering": ["read", "write", "deploy"]},
))

# Handle OIDC callback
result = client.sso.handle_oidc_callback(SsoOidcCallbackParams(code=code, state=state))
print(result.email, result.mapped_scopes, result.session_id)

CLI

# Create a connection
grantex sso connections create --name "Okta" --protocol oidc \
  --issuer-url https://mycompany.okta.com \
  --client-id $CLIENT_ID --client-secret $CLIENT_SECRET \
  --domains mycompany.com --jit-provisioning

# List connections
grantex sso connections list

# Test connectivity
grantex sso connections test sso_01HXYZ...

# Enforce SSO
grantex sso enforce --enable
FIDO2 / WebAuthn — passkey-based consent verification

FIDO2 / WebAuthn

Grantex supports passkey-based human presence verification using the FIDO2/WebAuthn standard. When enabled, end-users prove they are physically present during the consent flow by authenticating with a passkey (biometric, security key, or platform authenticator). This raises the assurance level of every grant from "user clicked approve" to "user was cryptographically verified."

How It Works

  1. Developer enables FIDO — Set fidoRequired: true on your developer profile via PATCH /v1/me
  2. User registers a passkey — During the first consent flow, the user registers a FIDO2 credential (fingerprint, Face ID, YubiKey, etc.)
  3. User authenticates on consent — On subsequent authorization requests, the user completes a WebAuthn assertion challenge instead of a simple button click
  4. FIDO evidence embedded in grants — The assertion result is recorded in the grant and can be embedded in Verifiable Credentials as cryptographic proof of human presence

SDK Usage

// Enable FIDO for your developer account
await grantex.updateSettings({ fidoRequired: true, fidoRpName: 'My App' });

// Register a passkey for an end-user (called from the browser)
const options = await grantex.webauthn.registerOptions({ principalId: 'user_abc123' });
// Pass options to navigator.credentials.create() in the browser
const credential = await navigator.credentials.create({ publicKey: options });
await grantex.webauthn.registerVerify({ challengeId: options.challengeId, response: credential });

// List and manage credentials
const creds = await grantex.webauthn.listCredentials('user_abc123');
await grantex.webauthn.deleteCredential(credentialId);
# Enable FIDO for your developer account
from grantex import UpdateDeveloperSettingsParams, WebAuthnRegistrationVerifyParams

client.update_settings(UpdateDeveloperSettingsParams(
    fido_required=True,
    fido_rp_name="My App",
))

# Register a passkey (server-side portion)
options = client.webauthn.register_options(principal_id="user_abc123")
# Browser performs navigator.credentials.create() and sends response back
result = client.webauthn.register_verify(WebAuthnRegistrationVerifyParams(
    challenge_id=options.challenge_id,
    response=credential_response,
))

# List and manage credentials
creds = client.webauthn.list_credentials("user_abc123")
client.webauthn.delete_credential(credential_id)

WebAuthn API Endpoints

MethodEndpointDescription
POST/v1/webauthn/register/optionsGenerate passkey registration options
POST/v1/webauthn/register/verifyVerify registration and store credential
GET/v1/webauthn/credentialsList WebAuthn credentials for a principal
DELETE/v1/webauthn/credentials/:idDelete a credential
POST/v1/webauthn/assert/optionsGenerate assertion options for consent
POST/v1/webauthn/assert/verifyVerify assertion during consent
PATCH/v1/meUpdate developer settings (FIDO config)
Verifiable Credentials — W3C VC-JWT issuance and verification

Verifiable Credentials

Grantex can issue W3C Verifiable Credentials (VCs) alongside standard JWTs. While JWTs are optimized for real-time authorization, VCs provide a portable, tamper-evident, standards-based proof of authorization that can be presented to any verifier — including systems outside the Grantex ecosystem.

Why VCs Matter for Agents

In agentic commerce, an agent acting on your behalf needs to prove its authorization to third-party services that may not integrate with Grantex directly. A Verifiable Credential is a self-contained, cryptographically signed document that any party can verify using the issuer's published DID document — no API calls, no accounts, no trust relationships required.

How It Works

When exchanging an authorization code for a grant token, pass credentialFormat: "vc-jwt" to receive a Verifiable Credential alongside the standard grant token:

const result = await grantex.tokens.exchange({
  code,
  agentId: agent.id,
  credentialFormat: 'vc-jwt',   // opt-in to VC issuance
});

console.log(result.grantToken);         // standard RS256 JWT (unchanged)
console.log(result.verifiableCredential); // W3C VC-JWT
result = client.tokens.exchange(ExchangeTokenParams(
    code=code,
    agent_id=agent.id,
    credential_format="vc-jwt",
))

print(result.verifiable_credential)  # W3C VC-JWT

Credential Types

TypeDescription
AgentGrantCredentialIssued for direct grants — attests that a principal authorized an agent with specific scopes
DelegatedGrantCredentialIssued for delegated grants — includes the full delegation chain

Verifying a VC

const verification = await grantex.credentials.verify(vcJwt);
console.log(verification.valid);
console.log(verification.credentialSubject);
console.log(verification.issuer); // "did:web:grantex.dev"
verification = client.credentials.verify(vc_jwt)
print(verification.valid)
print(verification.credential_subject)

Revocation via StatusList2021

Grantex implements the W3C StatusList2021 revocation mechanism. Each credential references a status list entry. When a grant is revoked, the corresponding bit in the status list is flipped, and any verifier checking the credential sees it as revoked.

// Check a specific credential's status
const cred = await grantex.credentials.get(credentialId);
console.log(cred.status); // "active" or "revoked"

// List credentials with filters
const { credentials } = await grantex.credentials.list({
  grantId: 'grnt_01HXYZ...',
  status: 'active',
});

FIDO Evidence in VCs

When FIDO is enabled and the user completes a WebAuthn assertion during consent, the VC includes a fidoEvidence field that cryptographically proves human presence at the time of authorization. This is compatible with the Mastercard Verifiable Intent specification for agentic commerce.

DID Infrastructure

Grantex publishes a W3C DID document at /.well-known/did.json (did:web:grantex.dev). This document contains the public keys used to sign Verifiable Credentials, enabling any party to verify credentials without contacting Grantex:

curl https://api.grantex.dev/.well-known/did.json

Verifiable Credentials API Endpoints

MethodEndpointDescription
GET/v1/credentials/:idRetrieve a Verifiable Credential
GET/v1/credentialsList Verifiable Credentials
POST/v1/credentials/verifyVerify a VC-JWT
GET/v1/credentials/status/:idStatusList2021 credential
GET/.well-known/did.jsonW3C DID document
MPP Agent Identity — verifiable agent identity for machine payments

MPP Agent Identity

MPP (Machine Payments Protocol) defines HTTP 402 payment flows for software clients. Grantex can attach an AgentPassportCredential based on W3C Verifiable Credentials 2.0 so a configured merchant can verify agent, principal, category, amount-limit, expiry, and delegation claims after obtaining the issuer keys and current status data. The credential carries authorization context; it does not prove that a payment settled, an order was approved, or a provider accepted the transaction.

Why Agent Passports?

A wallet or payment-source identifier may not tell a merchant which internal agent is acting, which principal delegated authority, or which policy limits apply. An agent passport can supply that context when both sides integrate and enforce it.

The current Grantex passport shape uses Ed25519 signatures, a W3C VC 2.0 data model, configured purchase categories, transaction ceilings, expiry, delegation context, and StatusList2021-style status data. A relying merchant must still validate the issuer, refresh keys and status according to its risk policy, enforce the claims at the protected action, and run its own payment, fraud, sanctions, order, and settlement controls.

How It Works

StepWhoWhat
1. IssueAuthorized applicationRequests an AgentPassportCredential with configured categories, amount ceiling, delegation context, and expiry
2. StoreAgent hostStores the credential as sensitive authorization material
3. PresentAgent hostAttaches the credential to a supported MPP request when the integration is configured
4. VerifyMerchant serviceVerifies signature, issuer, expiry, category, amount, and sufficiently current status data
5. DecideMerchant and payment systemsApply merchant policy plus independent payment, order, provider, and settlement checks before execution
6. RecordEach participating systemRecords the events it is configured to observe; credential verification alone is not an execution or settlement audit log

Verification boundary: cached keys can support local signature checks after retrieval. Current revocation requires refreshed status data, and cache policy determines how quickly a relying service observes a change.

Credential Structure

FieldDescription
idurn:grantex:passport:<ulid>
issuerdid:web:grantex.dev
credentialSubject.idAgent DID (did:grantex:ag_...)
credentialSubject.humanPrincipalDID of the authorizing human
credentialSubject.organizationDIDOrg DID (did:web:<domain>)
credentialSubject.grantIdLinks to underlying Grantex grant
credentialSubject.allowedMPPCategoriesinference, compute, data, storage, search, media, delivery, browser, general
credentialSubject.maxTransactionAmount{ amount, currency } ceiling per transaction
credentialSubject.delegationDepthInherited from grant delegation chain
credentialStatusStatusList2021 revocation entry
proofEd25519Signature2020

Issue a Passport

TypeScript:

import { Grantex } from '@grantex/sdk';

const grantex = new Grantex({ apiKey: process.env.GRANTEX_API_KEY });

const passport = await grantex.passports.issue({
  agentId: 'ag_01HXYZ...',
  grantId: 'grnt_01HXYZ...',
  allowedMPPCategories: ['inference', 'compute'],
  maxTransactionAmount: { amount: 50, currency: 'USDC' },
  paymentRails: ['tempo'],
  expiresIn: '24h',
});
// passport.passportId   → "urn:grantex:passport:01HXYZ..."
// passport.encodedCredential → base64url for X-Grantex-Passport header

cURL:

curl -X POST https://api.grantex.dev/v1/passport/issue \
  -H "Authorization: Bearer $GRANTEX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "agentId": "ag_01HXYZ...",
    "grantId": "grnt_01HXYZ...",
    "allowedMPPCategories": ["inference", "compute"],
    "maxTransactionAmount": { "amount": 50, "currency": "USDC" },
    "expiresIn": "24h"
  }'

Attach to MPP Requests

import { createMppPassportMiddleware } from '@grantex/mpp';

const middleware = createMppPassportMiddleware({ passport });
const enrichedRequest = await middleware(new Request(url, init));
// enrichedRequest now has X-Grantex-Passport header
const response = await fetch(enrichedRequest);

Verify on the Merchant Side

Standalone verification:

import { verifyPassport } from '@grantex/mpp';

const verified = await verifyPassport(encodedCredential, {
  requiredCategories: ['inference'],
  maxAmount: 10,
});
// verified.humanDID        → "did:grantex:user_alice"
// verified.organizationDID → "did:web:acme.com"
// verified.allowedCategories → ["inference", "compute"]
// verified.maxTransactionAmount → { amount: 50, currency: "USDC" }

Express middleware (one-liner):

import { requireAgentPassport } from '@grantex/mpp';

app.use('/api/inference', requireAgentPassport({
  requiredCategories: ['inference'],
  maxAmount: 10,
}));
// req.agentPassport is populated on valid requests
// 403 with typed error code on invalid requests

Trust Registry

Query any organization's verified trust level — no authentication required:

curl https://api.grantex.dev/v1/trust-registry/did:web:grantex.dev
# {"organizationDID":"did:web:grantex.dev","trustLevel":"soc2","domains":["grantex.dev"]}
import { lookupOrgTrust } from '@grantex/mpp';

const record = await lookupOrgTrust('did:web:acme.com');
// record.trustLevel → "verified" | "soc2" | "basic"
// record.verificationMethod → "dns-txt" | "manual" | "soc2"

Revocation

Revoking a passport updates server-side status immediately. Local verifiers observe the change only after an online revocation check or status-data refresh, so cached results can lag:

await grantex.passports.revoke('urn:grantex:passport:01HXYZ...');
// Revocation-aware verification rejects after checking refreshed status data

Error Codes

CodeHTTPDescription
PASSPORT_EXPIRED403Credential validUntil has passed
PASSPORT_REVOKED403StatusList2021 bit is set
INVALID_SIGNATURE403Signature verification failed
UNTRUSTED_ISSUER403Issuer DID not in trusted list
CATEGORY_MISMATCH403Categories don't cover required service
AMOUNT_EXCEEDED403Max amount below required threshold
MISSING_PASSPORT403No X-Grantex-Passport header
MALFORMED_CREDENTIAL403Invalid base64url or missing VC fields

MPP Agent Identity API Endpoints

MethodEndpointAuthDescription
POST/v1/passport/issueAPI keyIssue AgentPassportCredential
GET/v1/passportsAPI keyList passports (filter by agentId, grantId, status)
GET/v1/passport/:idAPI keyRetrieve passport by ID
POST/v1/passport/:id/revokeAPI keyRevoke passport (StatusList2021)
GET/v1/trust-registry/:orgDIDNoneLook up org trust record (public)
GET/v1/trust-registryAPI keyList all trust records (admin)

See packages/mpp/ for full package docs. Demo: grantex.dev/mpp-demo.

SD-JWT Selective Disclosure — privacy-preserving credential presentation

SD-JWT Selective Disclosure

Grantex supports SD-JWT (Selective Disclosure JWT) for privacy-preserving credential presentation. While a standard VC-JWT reveals all claims to every verifier, SD-JWT lets the holder choose exactly which fields to disclose — keeping everything else hidden.

Why SD-JWT?

In agentic commerce, different verifiers need different levels of information. A payment processor needs to know the agent's scopes and budget, but not the principal's identity. A compliance auditor needs the principal and timestamps, but not the scopes. SD-JWT enables minimum-disclosure presentations that satisfy each verifier's requirements without over-sharing.

How It Works

When exchanging an authorization code, pass credentialFormat: "sd-jwt" to receive an SD-JWT credential:

const result = await grantex.tokens.exchange({
  code,
  agentId: agent.id,
  credentialFormat: 'sd-jwt',   // opt-in to SD-JWT issuance
});

console.log(result.grantToken);         // standard RS256 JWT (unchanged)
console.log(result.sdJwt);              // SD-JWT with selective disclosure
result = client.tokens.exchange(ExchangeTokenParams(
    code=code,
    agent_id=agent.id,
    credential_format="sd-jwt",
))

print(result.sd_jwt)  # SD-JWT with selective disclosure

Creating a Presentation

The holder selects which claims to disclose when presenting to a verifier:

const presentation = await grantex.credentials.present({
  sdJwt: result.sdJwt,
  disclosedClaims: ['scopes', 'agentId'],   // only reveal these fields
});

// Send presentation to the verifier — they see scopes and agentId,
// but principalId, developerId, grantId, etc. remain hidden
presentation = client.credentials.present(
    sd_jwt=result.sd_jwt,
    disclosed_claims=["scopes", "agent_id"],
)

SD-JWT Format

An SD-JWT consists of: <issuer-jwt>~<disclosure1>~<disclosure2>~...~

Each disclosure is a base64url-encoded JSON array [salt, claim-name, claim-value]. The verifier can only see claims for which a disclosure is provided.

Disclosable Claims

ClaimDescription
principalIdThe end-user who authorized the grant
developerIdThe developer who owns the agent
scopesThe authorized scopes
agentIdThe agent's DID
grantIdThe grant record identifier
issuedAtWhen the credential was issued
expiresAtWhen the credential expires

SD-JWT API Endpoints

MethodEndpointDescription
POST/v1/tokenExchange code for grant token + SD-JWT (with credentialFormat: "sd-jwt")
POST/v1/credentials/verifyVerify an SD-JWT presentation
Budget Controls — per-agent spending limits with atomic debit

Budget Controls

Grantex provides per-grant budget controls that let developers cap how much an agent can spend. Budget allocations are enforced atomically — if a debit would exceed the remaining balance, it fails with a 402 INSUFFICIENT_BUDGET error. Threshold alerts fire at 50% and 80% consumption, and the remaining budget is embedded in grant tokens via the bdg JWT claim.

// Allocate a budget to a grant
const budget = await grantex.budgets.allocate({
  grantId: 'grnt_01HXYZ...',
  amount: 1000,
  currency: 'USD',
});

// Debit against the budget
const debit = await grantex.budgets.debit({
  grantId: 'grnt_01HXYZ...',
  amount: 42.50,
  description: 'Flight booking',
});
console.log(debit.remaining); // 957.50

// Check the current balance
const balance = await grantex.budgets.balance('grnt_01HXYZ...');
console.log(balance.remainingBudget);

// List all budget transactions for a grant
const { transactions } = await grantex.budgets.transactions('grnt_01HXYZ...');
# Allocate a budget to a grant
budget = client.budgets.allocate(
    grant_id="grnt_01HXYZ...",
    amount=1000,
    currency="USD",
)

# Debit against the budget
debit = client.budgets.debit(
    grant_id="grnt_01HXYZ...",
    amount=42.50,
    description="Flight booking",
)
print(debit.remaining)  # 957.50

# Check the current balance
balance = client.budgets.balance("grnt_01HXYZ...")

# List all budget transactions
transactions = client.budgets.transactions("grnt_01HXYZ...")

Budget API Endpoints

MethodEndpointDescription
POST/v1/budget/allocateCreate a budget allocation for a grant
POST/v1/budget/debitDebit against a grant's budget (402 if insufficient)
GET/v1/budget/balance/:grantIdGet remaining balance for a grant
GET/v1/budget/allocationsList all budget allocations
GET/v1/budget/transactions/:grantIdList transactions and total spend for a grant
Event Streaming — real-time SSE and WebSocket

Event Streaming

Grantex provides real-time event streaming via Server-Sent Events (SSE) and WebSocket. Subscribe to authorization lifecycle events as they happen — grant creation, revocation, token issuance, and budget threshold alerts. Events are published to both webhooks and streaming endpoints, so you can choose push or pull.

// SSE — async generator, automatically reconnects
for await (const event of grantex.events.stream()) {
  console.log(event.type);   // 'grant.created', 'token.issued', etc.
  console.log(event.data);
}

// Convenience wrapper with a callback
grantex.events.subscribe((event) => {
  if (event.type === 'budget.threshold') {
    alert(`Grant ${event.data.grantId} is at ${event.data.percentage}% budget`);
  }
});
# SSE — async generator
async for event in client.events.stream():
    print(event.type)   # 'grant.created', 'grant.revoked', etc.
    print(event.data)

# Convenience wrapper
async def handler(event):
    if event.type == "budget.exhausted":
        await revoke_grant(event.data["grant_id"])

await client.events.subscribe(handler)

Event Types

EventDescription
grant.createdA new grant was approved by an end-user
grant.revokedA grant was revoked (by user, developer, or cascade)
token.issuedA grant token was exchanged or refreshed
budget.thresholdA budget allocation crossed 50% or 80% usage
budget.exhaustedA budget allocation reached 0 remaining

Event Streaming API Endpoints

MethodEndpointDescription
GET/v1/events/streamSSE event stream (Bearer auth)
GET/v1/events/wsWebSocket event stream
Usage Metering — track API consumption per developer

Usage Metering

Grantex tracks API usage per developer — token exchanges, authorization requests, and verification calls. Use the metering API to monitor consumption, enforce plan limits, and export usage data for billing.

// Get current period usage
const usage = await grantex.usage.current();
console.log(usage.tokenExchanges);
console.log(usage.authorizations);
console.log(usage.totalRequests);

// Get usage history over the last 30 days
const { entries } = await grantex.usage.history({ days: 30 });
entries.forEach((e) => console.log(`${e.date}: ${e.totalRequests} requests`));
# Get current period usage
usage = client.usage.current()
print(usage.token_exchanges)
print(usage.total_requests)

# Get usage history over the last 30 days
history = client.usage.history(days=30)
for entry in history.entries:
    print(f"{entry.date}: {entry.total_requests} requests")

Usage Metering API Endpoints

MethodEndpointDescription
GET/v1/usageCurrent period usage for the authenticated developer
GET/v1/usage/history?days=NDaily usage history for the last N days
Custom Domains — register & verify domains for white-labeling

Custom Domains

Grantex provides domain registration and DNS-based ownership verification so your account is provisioned and ready to host Grantex on your own domain. Today the API covers registration, verification, listing, and deletion; runtime traffic routing through verified domains (consent UI / API endpoints served from your domain) is on the roadmap and currently still served from *.grantex.dev. Track progress in issues.

// Register a custom domain
const domain = await grantex.domains.create({ domain: 'auth.yourapp.com' });
console.log(domain.verificationToken);
// → Add a DNS TXT record: _grantex-verify.auth.yourapp.com = <token>

// Verify the domain after adding the DNS record
const verified = await grantex.domains.verify(domain.id);
console.log(verified.verified); // true

// List all registered domains
const { domains } = await grantex.domains.list();

// Delete a domain
await grantex.domains.delete(domain.id);
# Register a custom domain
domain = client.domains.create(domain="auth.yourapp.com")
print(domain.verification_token)

# Verify after adding DNS TXT record
verified = client.domains.verify(domain.id)
print(verified.verified)  # True

# List all domains
domains = client.domains.list()

# Delete a domain
client.domains.delete(domain.id)

Custom Domains API Endpoints

MethodEndpointDescription
POST/v1/domainsRegister a new custom domain
GET/v1/domainsList all registered domains
POST/v1/domains/:id/verifyVerify domain ownership via DNS TXT
DELETE/v1/domains/:idRemove a custom domain
Policy-as-Code — OPA and Cedar policy backends

Policy-as-Code

Grantex supports pluggable policy backends for fine-grained authorization decisions. In addition to the built-in policy engine, you can connect OPA (Open Policy Agent) or Cedar to evaluate authorization requests against externally managed policy bundles. Policy bundles can be synced via direct upload or triggered automatically from a git repository webhook.

// Upload a policy bundle
await grantex.policies.sync({
  format: 'opa',           // 'opa' or 'cedar'
  bundle: bundleBuffer,    // policy bundle as Buffer
});

// List policy bundles
const { bundles } = await grantex.policies.bundles();
# Upload a policy bundle
client.policies.sync(
    format="opa",
    bundle=bundle_bytes,
)

# List policy bundles
bundles = client.policies.bundles()

Supported Policy Backends

BackendDescriptionConfig
BuiltinDefault rule engine — scope matching + delegation constraintsNo config needed
OPAOpen Policy Agent — Rego policies evaluated at POST /v1/data/grantex/authzPOLICY_BACKEND=opa, OPA_URL=...
CedarAWS Cedar — Cedar policies evaluated at POST /v1/is_authorizedPOLICY_BACKEND=cedar, CEDAR_URL=...

Policy-as-Code API Endpoints

MethodEndpointDescription
POST/v1/policies/syncUpload a policy bundle (OPA or Cedar)
POST/v1/policies/sync/webhookGit webhook trigger for policy sync
GET/v1/policies/bundlesList uploaded policy bundles
DPDP Compliance — India's Digital Personal Data Protection Act 2023

DPDP Act 2023 Compliance

DPDP Act 2023 support includes structured consent records, purpose limitation, data principal rights workflows (access, erasure, grievance), and audit-ready exports. Available in all SDKs and the CLI. This is a technical control mapping, not a legal certification.

// Register a consent notice
const notice = await grantex.dpdp.createConsentNotice({
  noticeId: 'privacy-v1',
  version: '1.0',
  title: 'Data Processing Notice',
  content: 'We process your data for...',
  purposes: [{ code: 'analytics', description: 'Usage analytics' }],
});

// Create a consent record linked to a grant
const record = await grantex.dpdp.createConsentRecord({
  grantId: 'grnt_01HXYZ...',
  dataPrincipalId: 'user@example.com',
  purposes: [{ code: 'analytics', description: 'Usage analytics' }],
  consentNoticeId: 'privacy-v1',
  processingExpiresAt: '2027-01-01T00:00:00Z',
});

// Data principal exercises right to access (DPDP §11)
const { records } = await grantex.dpdp.listPrincipalRecords('user@example.com');

// Withdraw consent — optionally revoke grant and delete data
const withdrawal = await grantex.dpdp.withdrawConsent(record.recordId, {
  reason: 'No longer needed',
  revokeGrant: true,
  deleteProcessedData: true,
});

// File a grievance (DPDP §13(6))
const grievance = await grantex.dpdp.fileGrievance({
  dataPrincipalId: 'user@example.com',
  type: 'data_breach',
  description: 'Unauthorized data access',
});

// Request data erasure (DPDP §11)
const erasure = await grantex.dpdp.requestErasure('user@example.com');

// Generate compliance export
const report = await grantex.dpdp.createExport({
  type: 'dpdp-audit',
  dateFrom: '2026-01-01T00:00:00Z',
  dateTo: '2026-04-01T00:00:00Z',
});
# Python SDK
record = client.dpdp.create_consent_record(CreateConsentRecordParams(
    grant_id="grnt_01HXYZ...",
    data_principal_id="user@example.com",
    purposes=[{"code": "analytics", "description": "Usage analytics"}],
    consent_notice_id="privacy-v1",
    processing_expires_at="2027-01-01T00:00:00Z",
))
records = client.dpdp.list_principal_records("user@example.com")
erasure = client.dpdp.request_erasure("user@example.com")

DPDP API Endpoints

MethodEndpointDescription
POST/v1/dpdp/consent-noticesRegister a consent notice
POST/v1/dpdp/consent-recordsCreate a consent record
GET/v1/dpdp/consent-records/:idGet a consent record
GET/v1/dpdp/consent-recordsList consent records
POST/v1/dpdp/consent-records/:id/withdrawWithdraw consent
GET/v1/dpdp/data-principals/:id/recordsRight to access (§11)
POST/v1/dpdp/data-principals/:id/erasureRight to erasure (§11)
POST/v1/dpdp/grievancesFile a grievance (§13(6))
GET/v1/dpdp/grievances/:idGet grievance status
POST/v1/dpdp/exportsGenerate compliance export
GET/v1/dpdp/exports/:idGet export data

Scope Enforcement

Enforce tool-level permissions on any connector — define your own manifests or use the 53 pre-built ones.

Quick Start

from grantex import Grantex, ToolManifest, Permission

grantex = Grantex(api_key="gx_...")

# Define a manifest for any connector — yours, not ours
grantex.load_manifest(ToolManifest(
    connector="my-crm",
    tools={"search": Permission.READ, "create_deal": Permission.WRITE, "delete_account": Permission.DELETE},
))

result = grantex.enforce(grant_token=token, connector="my-crm", tool="delete_account")
# result.allowed = False — "write scope does not permit delete operations"

Permission Hierarchy

Scope LevelREAD toolsWRITE toolsDELETE tools
readYesNoNo
writeYesYesNo
deleteYesYesYes
adminYesYesYes

Bring your own manifests: define inline, load from JSON files, load from a directory, or auto-generate from source code via CLI. 53 pre-built manifests included: Salesforce, HubSpot, Jira, Stripe, SAP, S3, Gmail, Slack, GitHub, and 44 more — use as-is or as a starting point.

Framework helpers: wrapTool() wraps LangChain tools with automatic scope enforcement. createGrantexTool() covers TypeScript agent framework helpers including Strands Agents SDK. create_grantex_tool() covers Python OpenAI Agents SDK, Google ADK, and Strands Agents SDK tools. enforceMiddleware() adds one-line enforcement to Express/Fastify routes. FastAPI uses the GrantexEnforcer dependency.

See the Scope Enforcement Guide for full documentation.


Local Development

Start the full stack with one command:

git clone https://github.com/mishrasanjeev/grantex.git
cd grantex
docker compose up --build

Two API keys are seeded automatically:

KeyModeUse for
dev-api-key-locallivefull consent flow with redirect
sandbox-api-key-localsandboxskip consent UI — get a code immediately

Sandbox mode is designed for testing. With a sandbox key, POST /v1/authorize returns a code in the response body — no redirect required:

# Authorize + get code in one step
curl -s -X POST http://localhost:3001/v1/authorize \
  -H "Authorization: Bearer sandbox-api-key-local" \
  -H "Content-Type: application/json" \
  -d '{"agentId":"<id>","principalId":"test-user","scopes":["calendar:read"]}'
# → { ..., "sandbox": true, "code": "01J..." }

# Exchange immediately for a grant token
curl -s -X POST http://localhost:3001/v1/token \
  -H "Authorization: Bearer sandbox-api-key-local" \
  -H "Content-Type: application/json" \
  -d '{"code":"<code>","agentId":"<id>"}'

Developer portal is available at grantex.dev/dashboard — sign up or enter an API key to manage agents, grants, policies, anomalies, compliance exports, and billing from the browser.

For local development, the auth service also serves a lightweight dashboard at http://localhost:3001/dashboard.

See the self-hosting guide for production deployment guidance, or DEPLOYMENT.md for the complete deployment reference (system requirements, environment variables, Docker/Kubernetes/Cloud Run options, security checklist, monitoring). Python dependencies are in requirements.txt.


Why an Open Standard?

Grantex is built as an open protocol, not a closed SaaS product. Here's why that matters:

Model-neutral. Grantex operates at the SDK or protected-service boundary rather than depending on one model provider. The project documents use with OpenAI, Anthropic, Google, Llama, and Mistral models.

Framework-native. First-class integrations for LangChain, AutoGen, CrewAI, OpenAI Agents SDK, Google ADK, Strands Agents SDK, and plain code. Install one package, get Grantex in your existing stack.

Offline-verifiable signatures. Services verify token signatures locally using published JWKS. Applications should plan for JWKS retrieval and key rotation; availability during an issuer outage depends on their verifier's cache behavior.

Compliance-oriented controls. The EU AI Act, GDPR, and emerging US AI regulations will mandate auditable agent actions. Grantex provides technical controls that can support those programs from day one.


Scope Naming Convention

Grantex defines a standard scope format: resource:action[:constraint]

ScopeMeaning
calendar:readRead calendar events
calendar:writeCreate and modify events
email:sendSend emails on user's behalf
payments:initiate:max_500Initiate payments up to $500
files:readRead user files
profile:readRead user profile

Service providers implement scope definitions for their APIs. Agents declare which scopes they need. Users see plain-language descriptions, never raw scope strings.


Integrations

The primary SDK versions below are registry-verified as of 2026-07-12. For integration packages, “Published package” identifies a public package surface; check its registry page and compatibility notes before choosing a version.

FrameworkPackageInstallStatus
Gemma 4 (Offline Auth)@grantex/gemmanpm install @grantex/gemmaPublished package
Gemma 4 (Python)grantex-gemmapip install grantex-gemmaPublished package
DPDP Compliance@grantex/dpdpnpm install @grantex/dpdpPublished package
Adapters@grantex/adaptersnpm install @grantex/adaptersPublished package
MCP Tool Server@grantex/mcp (0.1.10)npm install @grantex/mcpPublished package
MCP Authorization Server@grantex/mcp-auth (2.0.2)npm install @grantex/mcp-auth@2.0.2 @grantex/sdk@0.3.13Published; single-process evaluation only
Gateway@grantex/gatewaynpm install @grantex/gatewayPublished package
Express.js@grantex/expressnpm install @grantex/expressPublished package
FastAPIgrantex-fastapipip install grantex-fastapiPublished package
LangChain@grantex/langchainnpm install @grantex/langchainPublished package
AutoGen / OpenAI@grantex/autogennpm install @grantex/autogenPublished package
CrewAIgrantex-crewaipip install grantex-crewaiPublished package
OpenAI Agents SDKgrantex-openai-agentspip install grantex-openai-agentsPublished package
Google ADKgrantex-adkpip install grantex-adkPublished package
Strands Agents SDK (TypeScript)@grantex/strandsnpm install @grantex/strandsPublished package
Strands Agents SDK (Python)grantex-strandspip install grantex-strandsPublished package
Anthropic SDK@grantex/anthropicnpm install @grantex/anthropicPublished package
Vercel AI SDK@grantex/vercel-ainpm install @grantex/vercel-aiPublished package
TypeScript SDK@grantex/sdk (0.3.13)npm install @grantex/sdk@0.3.13Registry-verified primary release
Python SDKgrantex (0.3.14)python -m pip install grantex==0.3.14Registry-verified primary release
Go SDKgrantex-go (v0.1.10, Go 1.26.1+)go get github.com/mishrasanjeev/grantex-go@v0.1.10Published with workarounds; source correction awaits a new tag
CLI@grantex/clinpm install -g @grantex/cliPublished package
Conformance Suite@grantex/conformancenpm install -g @grantex/conformancePublished package
A2A Bridge (TS)@grantex/a2anpm install @grantex/a2aPublished package
A2A Bridge (Py)grantex-a2apip install grantex-a2aPublished package
Event Destinations@grantex/destinationsnpm install @grantex/destinationsPublished package
Terraform Providerterraform-provider-grantexterraform { required_providers { grantex = { source = "mishrasanjeev/grantex" } } }Source present; verify registry before pinning
x402 Payment Protocol@grantex/x402npm install @grantex/x402Published package

Community x402 services

  • JMT x402 Agent Tools provides paid Base-mainnet tools for search, analysis, market data, filings, company intelligence, and news. Query its discovery endpoint for the current tool catalog and pricing.

Framework Quick Examples

Express.js — grant token verification + scope-based authorization:

import express from 'express';
import { requireGrantToken, requireScopes } from '@grantex/express';

const JWKS_URI = 'https://api.grantex.dev/.well-known/jwks.json';

app.use('/api', requireGrantToken({ jwksUri: JWKS_URI }));
app.get('/api/calendar', requireScopes('calendar:read'), (req, res) => {
  res.json({ principalId: req.grant.principalId, scopes: req.grant.scopes });
});

FastAPI — dependency injection with scope enforcement:

from fastapi import Depends, FastAPI
from grantex import VerifiedGrant
from grantex_fastapi import GrantexAuth, GrantexFastAPIError, grantex_exception_handler

app = FastAPI()
app.add_exception_handler(GrantexFastAPIError, grantex_exception_handler)
grantex = GrantexAuth(jwks_uri="https://api.grantex.dev/.well-known/jwks.json")

@app.get("/api/calendar")
async def calendar(grant: VerifiedGrant = Depends(grantex.scopes("calendar:read"))):
    return {"principalId": grant.principal_id}

LangChain — scope-enforced tools + audit callbacks:

import { createGrantexTool } from '@grantex/langchain';

const tool = createGrantexTool({
  name: 'read_calendar',
  description: 'Read upcoming calendar events',
  grantToken,
  requiredScope: 'calendar:read',
  func: async (input) => JSON.stringify(await getCalendarEvents(input)),
});
// Use with any LangChain agent — signature and scope checked locally using JWKS

Vercel AI SDK — scope checked at construction time:

import { createGrantexTool } from '@grantex/vercel-ai';
import { z } from 'zod';

const tool = createGrantexTool({
  name: 'read_calendar',
  description: 'Read upcoming calendar events',
  parameters: z.object({ date: z.string() }),
  grantToken,
  requiredScope: 'calendar:read',
  execute: async (args) => await getCalendarEvents(args.date),
});
// Use with generateText, streamText, etc.

AutoGen / OpenAI function calling:

import { createGrantexFunction, GrantexFunctionRegistry } from '@grantex/autogen';

const fn = createGrantexFunction({
  name: 'read_calendar',
  description: 'Read upcoming calendar events',
  parameters: { type: 'object', properties: { date: { type: 'string' } }, required: ['date'] },
  grantToken,
  requiredScope: 'calendar:read',
  func: async (args) => await getCalendarEvents(args.date),
});

// Pass fn.definition to OpenAI, call fn.execute() when selected

CrewAI (Python):

from grantex_crewai import GrantexTool

tool = GrantexTool(
    name="read_calendar",
    description="Read upcoming calendar events",
    grant_token=grant_token,
    required_scope="calendar:read",
    func=get_calendar_events,
)
# Use with any CrewAI agent

OpenAI Agents SDK (Python):

from grantex_openai_agents import create_grantex_tool

tool = create_grantex_tool(
    name="read_calendar",
    description="Read upcoming calendar events",
    grant_token=grant_token,
    required_scope="calendar:read",
    func=get_calendar_events,
)
# Returns a FunctionTool — use with any OpenAI Agents SDK agent

Google ADK (Python):

from grantex_adk import create_grantex_tool

read_calendar = create_grantex_tool(
    name="read_calendar",
    description="Read upcoming calendar events",
    grant_token=grant_token,
    required_scope="calendar:read",
    func=get_calendar_events,
)
# Returns a plain function — pass directly to google.adk.Agent(tools=[...])

Strands Agents SDK (Python):

from grantex_strands import create_grantex_tool

read_calendar = create_grantex_tool(
    name="read_calendar",
    description="Read upcoming calendar events",
    grant_token=grant_token,
    required_scope="calendar:read",
    func=get_calendar_events,
)
# Returns a Strands-compatible tool — pass into your Strands agent tools list

CLI (90+ commands, all support --json for AI agent / scripting use):

grantex config set --url https://api.grantex.dev --key YOUR_API_KEY
grantex me                                            # check identity
grantex agents register --name "Bot" --description "..." --scopes email:read
grantex authorize --agent ag_... --principal user@example.com --scopes email:read
grantex tokens exchange --code <code> --agent-id ag_...
grantex tokens verify <jwt>
grantex tokens refresh --refresh-token <token> --agent-id ag_...
grantex grants delegate --grant-token <jwt> --agent-id ag_child... --scopes email:read
grantex budgets allocate --grant-id grnt_... --amount 100
grantex audit list --agent ag_...
grantex grants revoke grnt_...

# DPDP Act 2023 compliance (11 subcommands)
grantex dpdp consent create --grant-id grnt_... --principal-id user@example.com
grantex dpdp consent get <recordId>
grantex dpdp consent list --principal-id user@example.com
grantex dpdp consent withdraw <recordId> --reason "No longer needed"
grantex dpdp notices create --notice-id privacy-v1 --version 1.0 --title "Privacy Notice"
grantex dpdp grievances file --principal-id user@example.com --type violation
grantex dpdp grievances get <grievanceId>
grantex dpdp erasure user@example.com
grantex dpdp exports create --type dpdp-audit --date-from 2026-01-01 --date-to 2026-04-01
grantex dpdp exports get <exportId>
grantex dpdp principal-records user@example.com

# Machine-readable output for scripts and AI coding assistants
grantex --json agents list | jq '.[0].agentId'

Interactive Playground

Try the full Grantex authorization flow live in your browser — no signup required:

grantex.dev/playground

Walk through all 7 steps of the protocol: register an agent, authorize, exchange tokens, verify, refresh, revoke, and verify revocation. Uses sandbox mode with your API key.


Examples

ExampleDescriptionRun
quickstart-tsCore authorization flow — register, authorize, exchange, verify, audit, revokenpm start
quickstart-pySame flow in Pythonpython main.py
nextjs-starterInteractive Next.js app — full consent UI flow in the browsernpm run dev
langchain-agentLangChain agent with scope-enforced toolsnpm start
anthropic-tool-useAnthropic SDK tool use with scope enforcementnpm start
vercel-ai-chatbotVercel AI SDK chatbot with Grantex toolsnpm start
crewai-agentCrewAI agent with Grantex authorizationpython main.py
openai-agentsOpenAI Agents SDK integrationpython main.py
google-adkGoogle ADK agent with Grantex toolspython main.py
gateway-proxyGateway reverse proxy with YAML config and scope enforcementnpm start
adapter-google-calendarGoogleCalendarAdapter with grant token verificationnpm start
multi-agent-delegationParent/child delegation with cascade revocationnpm start
gemma-raspberry-piGemma 4 agent on Raspberry Pi with offline authpython agent.py
gemma-android-kotlinAndroid Gemma 4 agent with offline verificationAndroid Studio
gemma-ios-swiftiOS Gemma 4 agent with CryptoKit verificationswift run
quickstart-goCore authorization lifecycle using the Go SDKgo run .
multi-agent-email-flowMulti-agent email automation with delegation, enforcement, and cascade revocationnpm start
audit-dashboardAudit trail querying, filtering, and hash chain integrity verificationnpm start
token-expiry-refreshTime-bound grant tokens with automatic expiry detection and refresh rotationnpm start
x402-agent-demoAI agent using Grantex Delegation Token + x402 paymentsnpm start
x402-weather-apiExpress server with x402 payment flow + GDT enforcementnpm start

Architecture

┌──────────────────────────────────────────────────────────────────────┐
│                         YOUR APPLICATION                             │
│                                                                      │
│   ┌──────────────┐    ┌──────────────┐    ┌───────────────────────┐ │
│   │  AI Agent    │    │  Grantex SDK │    │  End User Dashboard   │ │
│   │  (any model) │◄──►│  (2 lines)   │    │  (view / revoke)      │ │
│   └──────────────┘    └──────┬───────┘    └───────────────────────┘ │
└──────────────────────────────┼───────────────────────────────────────┘
                               │ HTTPS
                               ▼
┌──────────────────────────────────────────────────────────────────────┐
│                         GRANTEX PROTOCOL                             │
│                                                                      │
│  ┌─────────────┐  ┌──────────────┐  ┌─────────────┐  ┌──────────┐  │
│  │  Identity   │  │     Auth     │  │   Consent   │  │  Audit   │  │
│  │  Service    │  │   Service    │  │     UI      │  │  Chain   │  │
│  │  (DID/JWKS) │  │ (token i/o)  │  │  (hosted)   │  │ (append) │  │
│  └─────────────┘  └──────────────┘  └─────────────┘  └──────────┘  │
└──────────────────────────────────────────────────────────────────────┘
                               │
                               ▼
                ┌──────────────────────────┐
                │  Any Service / API       │
                │  Verifies via JWKS       │
                │  No Grantex dep needed   │
                └──────────────────────────┘

Product Roadmap

The current product roadmap prioritizes a 2026.08 production-trust baseline: durable MCP authorization, primary-SDK parity and release safety, revocation-aware enforcement, plan throughput, and production Commerce consent. Repository progress is recorded under Unreleased; the release-status guide, compatibility matrix, and package-specific documentation remain authoritative for published versions, deployment status, and limitations. The labels below are historical source milestones, not release or production-readiness claims.

MilestoneHistorical scopeCurrent interpretation
v0.1 - FoundationProtocol spec, TypeScript and Python SDKs, auth service, consent UI, audit trail, multi-agent delegation, sandbox modeHistorical source milestone
v0.2 - IntegrationsLangChain, AutoGen, webhooks, Stripe billing, CLIHistorical source milestone; verify package status
v0.3 - EnterpriseCrewAI, Vercel AI, compliance exports, policy engine, SCIM/SSO, anomaly detectionHistorical source milestone; feature boundaries vary
v1.0 - Stable ProtocolProtocol specification v1.0, security material, SOC 2 readiness mapping, individual IETF Internet-DraftProtocol v1.0 is final; mappings and the draft are not certifications or IETF endorsement
v2.0 - PlatformMCP authorization package, Credential Vault, adapters, webhook delivery log, examplesHistorical source milestone; MCP Auth 2.0.2 is single-process evaluation software
v2.1 - Enterprise ScaleEvent streaming, budget controls, observability, Terraform source, gateway, conformanceHistorical source milestone; verify each deployment surface
v2.2 - EcosystemOPA/Cedar backends, A2A bridge, usage metering, custom-domain registration, policy-as-codeHistorical source milestone; custom-domain runtime routing varies
v2.3 - Trust and IdentityPasskeys, Verifiable Credentials, SD-JWT, DID infrastructure, status data, intent mappingsHistorical source milestone; mappings are not third-party certification
v2.4 - Enterprise SSOOIDC and SAML 2.0 multi-IdP support, JIT provisioning, group mapping, enforcement, sessions, LDAP direct-bind previewHistorical source milestone; LDAP directory search and group retrieval are not implemented

Contributing

Grantex is open-source and welcomes contributions:

  1. Report bugs — open a GitHub Issue with reproduction steps
  2. Propose features — open a GitHub Discussion with your use case
  3. Build new integrations — add Grantex support to your favorite framework
  4. Improve docs — better examples, tutorials, and translations

Read CONTRIBUTING.md before submitting a PR.


Standards & Compliance

OWASPCovers ASI-01, ASI-03, ASI-05, ASI-10 from the Agentic Security Top 10 (Dec 2025)
EU AI ActTechnical control mapping only, not legal advice. Application is phased: transparency rules from Aug 2026, certain high-risk rules from Dec 2027, and product-integrated high-risk rules from Aug 2028 under the political agreement. See the European Commission timeline.
NIST AI RMFGovern 1.1, Map 5.1, Measure 2.5 — repository comment draft; no public submission receipt or endorsement
IETFActive individual Internet-Draft -01; not adopted or endorsed by the IETF (draft-mishra-oauth-agent-grants-01)
AuthZENConformance mapped
SOC 2Readiness control mapping published; formal third-party attestation not published
Protocol Specv1.0 Final — frozen, open, Apache 2.0

Full compliance matrix: docs.grantex.dev/guides/compliance-matrix


Trusted By

Using Grantex in production? Open a PR to add your company here.


FAQ

Is this just another auth library?
Human identity systems and Grantex solve different layers. Human auth establishes who the person is; Grantex carries the scoped authority that person or organization delegated to a specific agent. Current revocation requires an online state check or synchronized revocation data at the enforcement point.

Why not just use OAuth 2.0?
OAuth 2.0 was designed for "user grants app permission to access their data." Agents introduce new requirements: the agent needs a verifiable identity separate from its creator, grants need to be chainable across multi-agent pipelines, and every autonomous action must be attributable and auditable. We extend OAuth 2.0 concepts but add the agent-specific primitives it lacks.

What about MCP (Model Context Protocol)?
MCP connects clients to tools and resources and defines optional OAuth-based authorization for HTTP transports. Grantex adds agent-specific delegated authority at the tool or service boundary: which agent may perform which action for which principal. The two layers are complementary.

Who owns the standard?
The v1.0 protocol specification is open (Apache 2.0), and Grantex Inc. maintains the reference implementation. An active -01 document is published as an individual IETF Internet-Draft; that publication is not working-group adoption or IETF endorsement.

Can I self-host?
Yes. The reference implementation is fully open-source. Docker Compose deploy in one command. See DEPLOYMENT.md for the complete guide or the self-hosting docs.


License

Protocol specification and SDKs: Apache 2.0


Docs · Spec · Deploy · Dashboard · Discord · Roadmap · Contributing · GitHub


Building the trust layer for the agentic internet.

Featured
CodeRabbit
CodeRabbit
AI writes the code. CodeRabbit catches the slop.
Try For Free →
AppSignal
AppSignal
Monitor with ease. Code with confidence.
Start Free Trial →
AI notepad for back-to-back meetings
AI notepad for back-to-back meetings
Notes, actions and memory. Without a meeting bot. First month 100% off.
Download for free →
Keep your Mac awake
Keep your Mac awake
Keep your Mac awake while Claude Code and 40+ AI agents run. Sleeps when they're idle.
One time payment $9 →
Email for Agents: Free tier availableEmail for Agents: Free tier available
Email for Agents: Free tier available
Give your AI agent a complete email layer—sending, inbound inboxes, and sandbox testing.
Get 4K emails/month free →
Context.devContext.dev
Context.dev
Integrate web data into your AI product. One API to scrape website & brand data.
Get API Key Now →
CodeScene MCP ServerCodeScene MCP Server
CodeScene MCP Server
Your agent targets a perfect 10 Code Health score. Deterministic. Every commit.
Try For Free →
Make your agent a DeFi expert
Make your agent a DeFi expert
Agent, run crypto. Access onchain data & trade routes via 1inch.
Install now →

Configuration

GRANTEX_API_KEY*secret

Your Grantex API key

Registryactive
Package@grantex/mcp
TransportSTDIO
AuthRequired
UpdatedApr 8, 2026
View on GitHub