Skip to main content

Python SDK

The personal_agent_protocol package provides async discovery, strict Pydantic wire models, Reactor contribution points, and PAP session primitives. The generated Python API reference inventories every public __all__ export and links it to its source definition.

Install for development​

python -m pip install -e '.[test,lint,typing]'
python -m pytest -p no:cacheprovider

Public surface​

APIStatusPurpose
DiscoveryClientImplementedDiscover and validate a company and OAuth metadata.
AgentIdentityClientImplementedSafely fetch and bind client metadata and public JWKS.
DiscoveryDocument, OAuthServerMetadataImplementedStrict, forward-compatible wire models.
ClientMetadata, JsonWebKeySetImplementedValidate HTTPS client identity plus approved public assertion keys.
Message, ConversationEvent, ConversationEventPageImplemented modelsValidate known conversation shapes while preserving unknown event types and fields.
Operation, ApprovalImplemented modelsValidate Operations version 3 operations and approvals: opaque revisions and timestamps.
build_pap_reactorImplementedBuild the default Reactor host.
generate_pairwise_user_idImplemented primitiveGenerate an unlinkable random identifier.
SqlitePairwiseUserIdStore, resolve_pairwise_user_idImplementedAtomically persist/resolve stable IDs by tenant, local user, and verified issuer.
build_client_assertion_claimsImplemented primitiveBuild unsigned, short-lived client assertion claims.
TokenResponse, AccessTokenImplemented primitiveThe token response on the wire, and the access token the SDK keeps, with its token_type (Bearer or DPoP), scope and resource.
SessionClient, PapSessionImplementedStart a local Session (a random sid, no request); send token requests with a client assertion.
JoseSigner, BlindJoseSigner, RsaBlindSigningKeyImplementedSign ES256/PS384 client assertions and delegations, blindly (RFC 9474) when needed.
DelegatedSessionSigner, DelegatedKeyCustody, InMemoryDelegatedKeys, jwk_thumbprintImplementedSign each request's Session JWT with a delegated key per User ID; the RFC 7638 thumbprint in its kid.
JoseDpopProver, DpopKeyCustody, InMemoryDpopKeys, DpopProofRequestImplementedSign each request's DPoP proof with a key of its own per company, for a tenant.
WebBotAuthSigner, OperatorSigningKey, Ed25519OperatorKey, operator_directory, verify_operator_signatureImplementedSign each request with the operator's key (spec 5.3, RFC 9421, Web Bot Auth), publish it, and check a signature.
personal_agent_protocol.company.verifyImplementedVerify a Session JWT and its delegation: request and token binding, freshness, and replay state.
build_direct_sign_in_requestImplemented primitiveGenerate state, S256 PKCE, and a redacted authorization URL.
validate_direct_sign_in_callbackImplemented primitiveVerify callback redirect, state, issuer, denial, and code.
DirectSignInClientImplementedPerform one-use browser handoff and code exchange with partial-scope reporting.
RefreshTokenClient, RefreshTokenContextImplementedRefresh, narrow, revoke, and sign out, never handing the refresh token to a caller.
BrowserSessionClientImplementedJoin the agent's own browser: the agent authorizes the join form's one-time code.
SessionHttpClientImplementedSend the Session header, access token and any DPoP proof; restart once on session_ended, never on invalid_session; retry use_dpop_nonce once; refuse every redirect.
ConversationClient, generate_request_idImplementedStart and continue conversations with user-global idempotent request IDs.
Reactor infrastructure pointsImplemented contractSupply clock, randomness, signing, Session JWTs, stores, browser handoff, and browser join.

Discovery​

import asyncio

from personal_agent_protocol import DiscoveryClient


async def main() -> None:
async with DiscoveryClient() as client:
company = await client.discover("example.com")
print(company.document.organization.name)
print(company.oauth_metadata.token_endpoint)


asyncio.run(main())

Use the async context manager when the client owns its HTTPX transport. If an application supplies a Reactor host or HTTP client, it retains lifecycle ownership of that dependency.

Custom Reactor host​

DiscoveryClient(reactor=platform) accepts an existing Reactor PluginPlatform. A plugin can contribute pap.discoveryTransport and pap.urlSafetyPolicy implementations for a platform transport or test fixture.

The default client creates a core host using HTTPX and a public-network safety policy. Keep the client in an async context so its owned HTTP resources close.

The core plugin also supplies pap.clock, pap.randomSource, and pap.cache. A host must contribute pap.signer, pap.sessionSigner, pap.tokenStore, pap.pairwiseUserIdStore, pap.authorizationStateStore, and pap.browserHandoff before a flow requiring those services begins. Browser Session also requires pap.browserJoin, the agent's own browser. Resolution fails when a required provider is missing or tied at the winning priority; there is no insecure in-memory fallback.

Agent identity​

Companies can resolve a personal agent's public identity through the same Reactor transport and URL-safety contributions used for discovery:

import asyncio

from personal_agent_protocol import AgentIdentityClient


async def inspect() -> None:
async with AgentIdentityClient() as client:
metadata = await client.fetch_metadata(
"https://agent.example/agent.json"
)
jwks = await client.fetch_jwks(metadata.client_id)
print(metadata.client_name, [key.kid for key in jwks.keys])


asyncio.run(inspect())

Metadata retrieval rejects redirects and a client_id that differs from the fetched URL. Key retrieval repeats metadata verification, bounds response size and redirects, prevents a redirect to another host, and accepts only public P-256 ES256 or RSA PS384 keys. The client rejects duplicate JSON members, private JWK members, symmetric keys, unsafe resolved addresses, and non-JSON responses. Applications verifying assertions must select only a key from this verified set and must still enforce kid, signature, claims, lifetime, and replay rules.

Session primitives​

Generate a random pairwise user ID (the User ID, a pairwise subject identifier the personal agent assigns) once per local user and company issuer, then store that mapping durably. Never derive the identifier from an email address, phone number, name, or other personal information, not even through a keyed hash.

SqlitePairwiseUserIdStore is an atomic, file-backed reference implementation. Register it as pap.pairwiseUserIdStore, or contribute a transactional platform store with the aligned contract. resolve_pairwise_user_id fails closed when no unambiguous store is active.

A Session is local: start signs nothing and sends nothing. Signing remains behind a key-custody contribution so private keys never enter application or model context. The Session names the agent in client_id and the User ID in sub, for the company's issuer alone.

from personal_agent_protocol import SessionClient, resolve_pairwise_user_id

pairwise_user_id = await resolve_pairwise_user_id(
reactor,
tenant_id="application-42",
local_user_id="local-user-42",
company_issuer="https://auth.example.com",
)
session = await SessionClient(reactor=reactor, http_client=http).start(
client_id="https://agent.example/agent.json",
pairwise_user_id=pairwise_user_id,
issuer="https://auth.example.com",
tenant_id="application-42",
)
# No request is sent here: `SessionHttpClient` sends a Session JWT with each request,
# signed through the host's `pap.sessionSigner`.

Construct SessionClient with an existing Reactor platform and HTTPX client. start() draws a new sid; SessionHttpClient then asks pap.sessionSigner for a fresh Session JWT for each request. See Signed-out sessions for usage and the exact security boundary.

The maintained PyJWT[crypto] dependency backs local JOSE operations. Only ES256 and PS384 are accepted; ES256 is the default. Symmetric algorithms and none are rejected. See Cryptography before choosing key custody or implementing a company verifier.

Continue with Direct Sign-In for the complete Python orchestrator and the portable primitives shared with TypeScript.

DPoP​

A company that binds its access tokens lists ES256 in its metadata's dpop_signing_alg_values_supported. Pass what the metadata says to whatever sends a token request; a DPoP token then needs nothing more from the host:

  • DeviceSignInClient.begin and DirectSignInClient.begin take dpop_signing_algs;
  • so does RefreshTokenContext, for refreshes and tokens for one service;
  • MediatedSignInClient.sign_in reads it from company, and takes the tenant_id whose key proves.

With a list that doesn't include ES256, or none, no proof goes. The default pap.dpopProver keeps its keys in memory: a host whose tokens outlive a process contributes JoseDpopProver with a durable DpopKeyCustody (key_for, forget), below the default's order of 100, as the pap CLI's file-backed keys do. A lost key means refreshing: refresh tokens aren't bound. See DPoP.

pap.operatorSigner (OPERATOR_SIGNERS) has no default: contribute a WebBotAuthSigner, and every request with the Session header carries an operator signature. See Operator signatures.

Conversation and Operations models​

Conversation pages preserve unknown future event types so callers can skip them as version 0.4 requires. Known event types are validated for their required payload: messages, state changes, authorization requests, user requests, and Direct Conversation links. Operations validate their IDs and opaque revision, and a timezone-bearing expires_at.

ConversationClient implements message creation, continuation, one-page event reads, a de-duplicating long-poll iterator with cursor-expiry recovery, SSE streaming, handoff, Direct Conversations, and closing. OperationsClient asks the user and sends the approval. Durable cursor persistence remains the caller's responsibility.

Errors​

Catch DiscoveryError for company discovery and URL-safety failures. Catch IdentityError for client identity retrieval and binding failures. Catch SessionError for session transport and token endpoint failures. Catch ProtocolValidationError when remote JSON does not satisfy a wire model. Error messages are designed not to include response bodies or credentials.