Skip to main content

Pontive SDK for Python

Pontive for Python servers: protect an API or an MCP server with Pontive access tokens, keep signed-in sessions for a web app, check permissions for a verified caller, and manage your instance through the management API. The same behavior as @pontive/server, with the same option names (in snake_case), environment variables, error codes and cookies.

pip install pontive              # the core
pip install "pontive[fastapi]"   # or [flask], [django], [mcp]

Python 3.10 and later. Typed. Every call that does I/O has a sync method and an async one prefixed a (verify_token / averify_token), on the same object.

You are building Use
An API or MCP server that accepts Pontive access tokens ResourceServer, and pontive.fastapi / pontive.flask / pontive.django / pontive.mcp
A web app whose server signs users in and holds the session ServerAuth, and its middleware for your framework
Permission checks for the caller, delegated or not AuthorizationClient
Users, organizations, apps, roles, webhooks, billing: the management API Pontive, AsyncPontive

Protect an API

from pontive import ResourceServer

rs = ResourceServer(
    issuer="https://acme.auth.us.pontive.app",   # or a list, for several auth domains
    resource="https://api.acme.com",             # the API's identifier, as registered
    scopes=["files:read", "files:write"],
)

principal = rs.verify(request_headers, scopes=["files:read"])   # raises BearerError (401/403)
principal = await rs.averify_token(token, scopes=["files:read"])

Tokens are verified locally against the issuer's cached keys: typ must be at+jwt, aud must hold resource, exp/nbf allow 60 seconds of skew, and only RS256, PS256 and ES256 are accepted. A missing or failing token is a BearerError whose to_response() is the 401/403 with the WWW-Authenticate challenge MCP clients follow.

Principal carries sub, kind (user, service_account, agent), client_id, org_id, roles, permissions, scopes, claims (every claim, the claims template's included), token, and is_delegated with actor.

A delegated token (principal.is_delegated: an agent acting for a user) has the user as sub and the agent as actor. Its authority is the intersection of the two. Never read or write by sub alone: check it by token with AuthorizationClient. Tenant data keys on org_id, never sub.

FastAPI

from fastapi import Depends, FastAPI
from pontive import Principal
from pontive.fastapi import add_resource_server, require_bearer

app = FastAPI()
add_resource_server(app, rs)  # /.well-known/oauth-protected-resource, and RFC 6750 error bodies

@app.get("/files")
async def files(principal: Principal = Depends(require_bearer(rs, scopes=["files:read"]))):
    return {"caller": principal.sub, "organization": principal.org_id}

Flask

from pontive.flask import current_principal, register_well_known, require_bearer

register_well_known(app, rs)

@app.get("/files")
@require_bearer(rs, scopes=["files:read"])
def files():
    return {"caller": current_principal().sub}

Django

from pontive.django import require_bearer, well_known_urls

@require_bearer(rs, scopes=["files:read"])
def files(request):
    return JsonResponse({"caller": request.principal.sub})

urlpatterns = [*well_known_urls(rs), path("files", files)]

require_bearer also takes roles= and permissions=: each listed must be in the token, or the answer is 403 insufficient_permission. They read the token's claims, which reflect the organization the token was issued for; for a decision on a resource, use the authorization client.

MCP servers

from mcp.server.mcpserver import MCPServer   # FastMCP in mcp 1.x
from pontive.mcp import TokenVerifier, auth_settings, current_principal

rs = ResourceServer(issuer="https://acme.auth.us.pontive.app", resource="https://mcp.acme.com/mcp")
server = MCPServer("acme-files", token_verifier=TokenVerifier(rs), auth=auth_settings(rs, scopes=["files:read"]))

@server.tool()
async def read_file(path: str) -> str:
    principal = current_principal()
    await rs.aauthorize_tool(principal, "read_file")   # per-tool scopes
    ...

Per-tool scopes come from the API's scopes: pass the dashboard's scopes with their tools (scopes=[{"key": "files:read", "tools": [{"name": "read_file"}]}]), or metadata_fetch=MetadataFetch(api_id=..., credential=..., management_url=...) to read them, and the metadata, from Pontive. rs.authorize_tool_calls(principal, body) checks every tools/call in a JSON-RPC body before the transport sees it.

Sessions for a web app

A confidential app (one with a client secret) signs users in on its server and keeps the session in an encrypted, HttpOnly cookie. The middleware refreshes the access token shortly before it expires, before your handler runs.

export PONTIVE_ISSUER=https://acme.auth.us.pontive.app
export PONTIVE_CLIENT_ID=app_...
export PONTIVE_CLIENT_SECRET=...
export PONTIVE_SESSION_SECRET=$(python -c "import secrets; print(secrets.token_urlsafe(32))")

Register https://<your origin>/api/auth/callback as a redirect URI and https://<your origin>/login as a post-logout redirect URI on the app. Sign-in starts at /api/auth/login?returnTo=/somewhere, sign-out at /api/auth/logout.

FastAPI (or any Starlette app)

from fastapi import Depends, FastAPI
from pontive import ServerAuth, Session
from pontive.fastapi import PontiveMiddleware, get_session, require_session

auth = ServerAuth(base_url="https://app.acme.com")   # the rest from PONTIVE_*
app = FastAPI()
app.add_middleware(PontiveMiddleware, auth=auth)

@app.get("/")
async def home(session: Session | None = Depends(get_session)):
    return {"email": session.user.email if session else None}

Flask

from pontive import ServerAuth
from pontive.flask import Pontive, current_session, login_required

Pontive(app, ServerAuth())

@app.get("/dashboard")
@login_required
def dashboard():
    return f"Hello {current_session().user.email}"

Django

# settings.py
MIDDLEWARE = [..., "pontive.django.PontiveMiddleware"]
PONTIVE = {"base_url": "https://app.acme.com"}   # ServerAuth's options; the rest from PONTIVE_*

# views.py
from pontive.django import login_required

@login_required
def dashboard(request):
    return HttpResponse(f"Hello {request.pontive_session.user.email}")

The middleware is sync and async capable.

The session

Session has user (id, email, name, username, picture, email_verified), access_token (to call APIs as the user), expires_at (epoch seconds), session_id, organization (id, roles, permissions, or None) and claims.

Move the session to another organization with auth.switch_organization_path(org_id, return_to="/team"). A switch the user cannot make comes back with ?organization_error=not_a_member and leaves the session as it was.

Without a client secret (a regular app, or a public oauth app, whose browser SDK signs users in), ServerAuth runs in browser mode: it reads the access-token cookie the auth server keeps current through the auth proxy, and sends a page navigation whose token lapsed through the auth server's session handshake. It never refreshes in this mode, so the browser stays the only thing that spends the refresh token.

Anything else speaks AuthRequest/AuthResponse: auth.handle(request) for the routes, auth.refresh(request) before your handler (apply outcome.set_cookies, forward outcome.cookie_header), and auth.get_session(cookie_header) anywhere.

Options

Option Default
issuer PONTIVE_ISSUER The auth domain
client_id PONTIVE_CLIENT_ID The app's id
client_secret PONTIVE_CLIENT_SECRET Selects server mode
session_secret PONTIVE_SESSION_SECRET 32+ characters; rotating it signs everyone out
base_url X-Forwarded-*, then the request The app's public origin; set it behind a proxy
base_path /api/auth Where the routes live
scopes openid email profile offline_access
redirect_uri {origin}{base_path}/callback
sign_in_path /login Failed sign-ins and signed-out users land here
after_sign_in_path /
cookie_name pontive_session
secure_cookies https origin
iframe_safe "auto" SameSite=None on app-builder preview hosts
preview_callback "auto" The hosted preview callback on builder previews
session_max_age_seconds 7 days
refresh_skew_seconds 60
auth_path /__pontive Browser mode: where the auth proxy is mounted
http_client, async_http_client the SDK's own httpx clients, e.g. for proxies or tests

Authorization checks

from pontive import AuthorizationClient, ClientCredentials, ResourceRef

authz = AuthorizationClient(
    management_url="https://api.us.pontive.com",        # the authz host is https://authz.us.pontive.com
    issuer="https://acme.auth.us.pontive.app",          # to exchange client credentials
    credential=ClientCredentials("svc_...", "..."),     # holds sys:authz:check; or a key, or a function
)

authz.check(principal, "doc:write", ResourceRef("doc", "doc_1"), scopes=["files:write"])
authz.check_batch(principal, items)                      # one answer per item, 100 per request
authz.list_accessible(principal, resource_type="doc", permission="doc:read")
authz.filter_accessible(principal, chunks, lambda c: c.doc_id, resource_type="doc", permission="doc:read")
# and acheck, acheck_batch, alist_accessible, afilter_accessible

A delegated principal is checked by token, as the user-and-agent pair; anything else by subject. A denial is False; a refused request raises AuthorizationError with status and code.

Manage your instance

import pontive

client = pontive.Pontive()  # PONTIVE_SECRET_KEY from the environment

user = client.users.create({"email": "ada@example.com", "name": "Ada Lovelace"})
org = client.organizations.create({"name": "Analytical Engines", "owners": [user["id"]]})

for u in client.users.list(search="ada"):   # iterates across pages
    print(u["id"], u["email"])

page = client.users.list(limit=50)           # or one page at a time
page.data, page.has_next_page(), page.next_page()

AsyncPontive is the same for asyncio: await client.users.get(...), and a list is awaited for its first page or walked with async for.

  • Credentials. secret_key (the instance's pontive_sk_… key, which names its instance and region), token (a string or a function), or client_credentials=ClientCredentials(...) with issuer (a service account's, exchanged and cached). The region picks https://api.{region}.pontive.com and the authz. and ingest. hosts beside it; management_url overrides it.
  • Shape. Namespaces and methods follow the API's namespaces and operation ids: client.users.list_sessions, client.billing.invoices.get_pdf, client.authn.password_policy.update. Bodies are dicts, results are dicts, both typed with the TypedDicts in pontive.management.types. Query and header parameters are keyword arguments.
  • Retries. A 429, a 5xx or a network failure is retried twice with backoff, honouring Retry-After, when the call is safe to repeat: any method but POST, or a POST that takes an idempotency key, which the client sets for you (request_options={"idempotency_key": ...} to choose it).
  • Errors. A refusal raises pontive.management.APIError, a subclass per status (NotFoundError, ConflictError, RateLimitError, …), with code, details and request_id. No answer at all is APIConnectionError.
  • Headers. request_options={"on_response": callback} sees each response, for a header such as the ETag an if_match= update needs.
  • Billing is typed like the rest: client.billing.customers.create({"name": "Acme"}) takes a CreateCustomerRequest and returns a Customer (TypedDicts).
  • Not in this client: the platform API (api.pontive.com: workspaces, projects, instances).

The client is generated from the management API's OpenAPI documents; pontive/management/_generated is not edited by hand.

Environment

The variables every Pontive SDK reads, so docs read the same in every language. A value passed in code always wins.

Variable Read by
PONTIVE_ISSUER ServerAuth
PONTIVE_CLIENT_ID ServerAuth
PONTIVE_CLIENT_SECRET ServerAuth
PONTIVE_SESSION_SECRET ServerAuth
PONTIVE_SECRET_KEY Pontive, AsyncPontive
PONTIVE_INSTANCE_ID Pontive, AsyncPontive: sent as X-Pontive-Instance-ID
PONTIVE_MANAGEMENT_URL, PONTIVE_REGION Pontive, AsyncPontive: where the management API is

The SDK reads the process environment only. To load a .env file, use python-dotenv or your framework's settings.

Design notes

  • Dependencies. httpx gives one API for sync and async HTTP, and a MockTransport for tests. joserfc does JWS, JWE and JWK in one library, depends only on cryptography, is typed, and takes an explicit algorithm list on every call. PyJWT has no JWE (sealing would need a second library); python-jose is unmaintained; authlib brings a whole OAuth framework.
  • One protocol implementation. Every HTTP exchange is written once, as a generator that yields requests; the sync and async methods only drive it. They cannot drift apart.
  • Sealing. JWE compact, dir + A256GCM, keyed by the SHA-256 of session_secret, with iat and exp. The same format and payload as @pontive/server, so a Python app and a Node app sharing a domain, cookie name and secret read each other's sessions.
  • Refresh. One refresh per refresh token in flight per process (threads wait on the first; coroutines share one task), and its result handed to late requests still holding the old cookie for 30 seconds. Across replicas the auth server's reuse grace covers the race. A 4xx signs out; a network error or 5xx keeps the session for the next request.
  • Keys. Cached ten minutes; an unknown kid refetches the set at most once per 30 seconds, so a rotation is picked up at once. Keys that went stale while the issuer is unreachable keep verifying.

Not in this SDK, by design: @pontive/server's keyless mode (it provisions an unclaimed instance from inside a Node dev server). A Python app runs npx pontive@latest init in its project directory and loads the variables it writes to .env.local.

Examples

examples/: an API with FastAPI, sign-in with Flask, sign-in with Django in one file. Each says how to run it.

Development

uv sync
uv run pytest
uv run ruff check src tests examples && uv run ruff format --check src tests examples
uv run mypy

Commits follow Conventional Commits; release-please opens the release PR.

License

MIT

Metadata

Release files for pontive 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pontive 0.3.0
File Size Uploaded Provenance Actions
pontive-0.3.0.tar.gz 300.9 kB Without provenance Details for pontive-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pontive 0.3.0
File Interpreter ABI Platform Actions
pontive-0.3.0-py3-none-any.whl Python 3 none any Details for pontive-0.3.0-py3-none-any.whl

Total release size: 595.1 kB

Release files / pontive-0.3.0.tar.gz

Download URL pontive-0.3.0.tar.gz
Size 300.9 kB
Tags Source
SHA-256 checksum
How to use checksums
4f9377982a50eef02b01f959109127d9255d21b1f1a520191bde01916c6e07a4
BLAKE2b-256 checksum
How to use checksums
bdb3dd052a238c9d37a7e706068f7a36f732fde2132a4b6f9e3d9303af9a679c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.12 {"installer":{"name":"uv","version":"0.13.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / pontive-0.3.0-py3-none-any.whl

Download URL pontive-0.3.0-py3-none-any.whl
Size 294.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cce2156818cc76a404f04f35e3f996de6bbe8b04258447ed4173d3879e07f76b
BLAKE2b-256 checksum
How to use checksums
550783e61c43a073fcd4142ac98db6e6e78e895b796cc055991668c0d9a9e223
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.12 {"installer":{"name":"uv","version":"0.13.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for pontive 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page