Skip to main content

Python SDK for the Grantex delegated authorization protocol — OAuth 2.0 for AI agents

Project description

grantex

Python SDK for the Grantex delegated authorization protocol — OAuth 2.0 for AI agents.

Grantex lets humans authorize AI agents with verifiable, revocable, audited grants built on JWT and the OAuth 2.0 model. This SDK provides a complete client for the Grantex API.

PyPI Python License

Homepage | Docs | API Reference | Sign Up Free | GitHub

Install

pip install grantex

Quick start

from grantex import AuthorizeParams, ExchangeTokenParams, Grantex, VerifyGrantTokenOptions, verify_grant_token

client = Grantex(api_key="YOUR_API_KEY")

# 1. Start the authorization flow
request = client.authorize(AuthorizeParams(
    agent_id="ag_01HXYZ...",
    user_id="usr_01HXYZ...",
    scopes=["files:read", "email:send"],
    audience="https://api.example.com",  # optional; becomes the JWT aud claim
))

# Redirect the user to the consent page — they approve in plain language
print(request.consent_url)

# 2. Exchange the authorization code for a grant token
# (your redirect callback receives the `code` after user approves)
token = client.tokens.exchange(ExchangeTokenParams(code=code, agent_id="ag_01HXYZ..."))
print(token.grant_token)  # RS256-signed JWT
print(token.scopes)       # ('files:read', 'email:send')

# 3. Verify locally using keys retrieved from the issuer's JWKS
grant = verify_grant_token(
    token=token.grant_token,
    options=VerifyGrantTokenOptions(
        jwks_uri="https://api.grantex.dev/.well-known/jwks.json",
    ),
)
print(grant.principal_id)  # 'usr_01HXYZ...'

# 4. Revoke when done
client.tokens.revoke(grant.token_id)

Local JWKS verification

Verify grant-token signatures locally using the issuer's public JWKS. The verifier retrieves the current JWKS over the network for each call:

from grantex import VerifyGrantTokenOptions, verify_grant_token

verified = verify_grant_token(
    token="eyJhbGciOiJSUzI1NiIs...",
    options=VerifyGrantTokenOptions(
        jwks_uri="https://api.grantex.dev/.well-known/jwks.json",
    ),
)

print(verified.scopes)       # ['files:read', 'email:send']
print(verified.principal_id) # 'usr_01HXYZ...'
print(verified.agent_did)    # 'did:web:...'

PKCE Support

The SDK includes built-in PKCE (Proof Key for Code Exchange) support using the S256 method:

from grantex import AuthorizeParams, ExchangeTokenParams, Grantex, generate_pkce

client = Grantex(api_key="YOUR_API_KEY")

# 1. Generate a PKCE challenge
pkce = generate_pkce()
# pkce.code_verifier        — random 43-char string (keep secret)
# pkce.code_challenge       — SHA-256 hash of verifier (send to server)
# pkce.code_challenge_method — 'S256'

# 2. Pass the challenge when requesting authorization
request = client.authorize(AuthorizeParams(
    agent_id="ag_01HXYZ...",
    user_id="usr_01HXYZ...",
    scopes=["files:read"],
    code_challenge=pkce.code_challenge,
    code_challenge_method=pkce.code_challenge_method,
))

# 3. Exchange the code with the verifier
token = client.tokens.exchange(ExchangeTokenParams(
    code="auth_code_from_redirect",
    agent_id="ag_01HXYZ...",
    code_verifier=pkce.code_verifier,
))

Features

Feature Description
Authorization flow client.authorize() — initiate consent, get grant tokens
Token exchange client.tokens.exchange() — exchange an authorization code for a grant token
Token management client.tokens.verify(), .revoke() — online verification and revocation
Local verification verify_grant_token() — retrieves JWKS, then performs the RS256 signature check locally
Agent management client.agents.register(), .get(), .list(), .update(), .delete()
Grant management client.grants.list(), .get(), .revoke()
Multi-agent delegation client.grants.delegate() — scoped sub-grants with cascade revocation
Audit trail client.audit.log(), .list(), .get() — tamper-evident hash-chained log
Policy engine client.policies.create(), .list(), .update(), .delete()
Anomaly detection client.anomalies.list(), .detect()
Compliance client.compliance.get_summary(), .export_audit(), .export_grants(), .evidence_pack()
Webhooks client.webhooks.create(), .list(), .delete() + verify_webhook_signature()
Billing client.billing.get_subscription(), .create_checkout(), .create_portal()
SCIM 2.0 client.scim.create_user(), .list_users(), .get_user(), .update_user(), .delete_user()
OIDC SSO client.sso.create_config(), .get_config(), .get_login_url(), .handle_callback()
Commerce V1/OACP client.commerce.get_profile(), .search_catalog(), .create_cart(), .get_ops_health()

Commerce V1 / OACP

profile = client.commerce.get_profile(merchant_id="mch_shopify_mgx0n6_22")
products = client.commerce.search_catalog({
    "merchant_id": "mch_shopify_mgx0n6_22",
    "limit": 3,
})

Configuration

from grantex import Grantex

# Explicit API key
client = Grantex(api_key="gx_live_...")

# Or via environment variable
# export GRANTEX_API_KEY=gx_live_...
client = Grantex()

# Custom base URL (self-hosted)
client = Grantex(
    api_key="gx_live_...",
    base_url="https://auth.your-company.com",
)

# Custom timeout (seconds)
client = Grantex(api_key="gx_live_...", timeout=60.0)

The client also works as a context manager:

with Grantex(api_key="gx_live_...") as client:
    agents = client.agents.list()

Error handling

from grantex import Grantex, GrantexApiError, GrantexAuthError, GrantexNetworkError

client = Grantex(api_key="gx_live_...")

try:
    client.agents.get("ag_invalid")
except GrantexAuthError:
    # 401 — invalid or expired API key
    pass
except GrantexApiError as e:
    # Any other API error (4xx/5xx)
    print(e.status_code, e.code, e.message)
except GrantexNetworkError:
    # Connection failure, timeout, DNS error
    pass

Requirements

Links

Grantex Ecosystem

Package Description
@grantex/sdk TypeScript SDK
@grantex/langchain LangChain integration
@grantex/autogen AutoGen integration
@grantex/vercel-ai Vercel AI SDK integration
grantex-crewai CrewAI integration
grantex-openai-agents OpenAI Agents SDK integration
grantex-adk Google ADK integration
@grantex/mcp MCP server for Claude Desktop / Cursor / Windsurf
@grantex/cli Command-line tool

Scope Enforcement (v0.3.1)

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

from grantex import Grantex, ToolManifest, Permission

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

# Define a manifest for any connector — no dependency on Grantex to add support
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"

Features:

  • enforce() — verify JWT + check tool permission via manifest, <1ms
  • wrap_tool() — auto-enforce on LangChain tools
  • GrantexEnforcer — FastAPI dependency for scope enforcement
  • Define custom manifests for any connector: inline, from JSON, or auto-generated via CLI
  • 53 pre-built manifests included (Salesforce, HubSpot, Jira, Stripe, SAP, S3, and 47 more)
  • Permission hierarchy: admin > delete > write > read
  • Permissive mode for migration (enforce_mode="permissive")

Full Guide | API Reference

License

Apache 2.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

grantex-0.3.14.tar.gz (77.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

grantex-0.3.14-py3-none-any.whl (72.6 kB view details)

Uploaded Python 3

File details

Details for the file grantex-0.3.14.tar.gz.

File metadata

  • Download URL: grantex-0.3.14.tar.gz
  • Upload date:
  • Size: 77.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.4

File hashes

Hashes for grantex-0.3.14.tar.gz
Algorithm Hash digest
SHA256 eaa0806514eb9569b9364cb1db72e7f9cfdd4a5485a7d84e1101e765a3dbcf36
MD5 913a4e243ab2e9240e793399b7a3bf56
BLAKE2b-256 a97719e4ca15384fe918e5a0ffee0cdf74415b3ec88bdd0aeabfebdfd5eac94b

See more details on using hashes here.

File details

Details for the file grantex-0.3.14-py3-none-any.whl.

File metadata

  • Download URL: grantex-0.3.14-py3-none-any.whl
  • Upload date:
  • Size: 72.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.4

File hashes

Hashes for grantex-0.3.14-py3-none-any.whl
Algorithm Hash digest
SHA256 8d868ea67a63dbfb506a8d2a8ef15d893b0098a248b8a82fd175bc1ba1d7ad5f
MD5 ca9b513b6fff61ee1c99d56e5d18a9fb
BLAKE2b-256 1de077d44330174ccc96b590c115bc5cce6c83f5d5675e3709505e1b51ae7335

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page