Reference
Client
App and Agent constructors, lifecycle, and identity helpers.
The SDK exposes two top-level client classes — App for application/operator credentials and Agent for workload-scoped credentials. Both expose async network and lifecycle methods and share the request surface defined in request().
from alter_sdk import App, Agent, CallerType
# Application-sideapp = App(api_key="alter_rk_…")
# Workload-side: the agent's own key, from agents.createagent = Agent(api_key="alter_key_…")
# Lifecycleawait app.close()async with Agent(api_key="alter_key_…") as a: ...The application-side client. Use for operator/admin work (provisioning agents, minting Connect sessions, managing grants) and for application-backend workloads acting under a stored grant_id.
App( api_key: str, *, timeout: float = 95.0, caller: str | None = None, caller_type: CallerType | str = CallerType.SERVICE, user_token_getter: Callable[[], str | Awaitable[str]] | None = None, logger: logging.Logger | None = None,)| Parameter | Type | Default | Description |
|---|---|---|---|
api_key | str | — | App API key (alter_rk_…). Required. |
timeout | float | 95.0 | HTTP request timeout in seconds. The default is sized so a slow credential refresh returns the SDK’s typed timeout error (with its timeout_reason) rather than a bare client-side timeout; lower it for latency-sensitive callers that prefer to fail fast. |
caller | str | None | None | Optional caller identifier for audit attribution. |
caller_type | CallerType | str | CallerType.SERVICE | SERVICE (default — backend infrastructure) or AGENT (shows in the Agents tab). |
user_token_getter | callable | None | Optional sync/async callable returning a user JWT for identity-mode request(). |
logger | logging.Logger | None | module logger | Optional logger for SDK diagnostics. Must provide a callable warning; info and debug are used when present. A logger that raises never fails the SDK call it was logging. |
Raises AlterSDKError if api_key is missing or malformed, if user_token_getter is present but not callable, if logger is present but logger.warning is not callable, or if the configured backend URL is invalid.
Properties
Section titled “Properties”| Property | Type | Description |
|---|---|---|
actor_id | str | None | Cached actor UUID once the first authenticated call resolves. |
last_retry_info | RetryInfo | None | Retry metadata from the most recent request() call. |
last_rate_limit | RateLimitSnapshot | None | Latest complete Alter rate-limit reading from a metered backend response. None means unknown, never unlimited. |
base_url | str | Backend base URL the client is pinned to. Diagnostic. |
Methods
Section titled “Methods”App exposes:
request(),proxy_request()list_grants(),mint_grant(),update_grant_tags(),revoke_grant(),revoke_delegation(),create_managed_secret_grant()create_connect_session(),create_managed_secret_connect_session(),connect(),poll_connect_session(),create_connect_session_for_error()authenticate(),create_auth_session(),poll_auth_session(),verify_user_token()get_approval_status(),await_approval(),decide_approval(),decide_approval_batch(),list_approvals()resolve_identity(),assert_identity()— the identity-export surface (see Propagate identity into memory layers and Identity types)agentsnamespace (see Agents & Keys)keysnamespace (see Agents & Keys)scopesnamespace (see Calling APIs)oauth_providersnamespace —oauth_providers.list()(OAuth provider catalog)provider_specsnamespace (see Provider discovery)spansnamespace —spans.emit()(user-defined trace spans)with_constraints(),get_agent()(below)
with_constraints
Section titled “with_constraints”Return a macaroon-style constrained sub-client. Every request from the returned App carries a permanent attenuation that can only narrow access, never broaden it. Two attenuations are available, and at least one of scopes / rule must be supplied:
scopesnarrows the underlying key to the supplied scope set. The supplied scopes must already be implied by the key — the backend rejects broadening attempts with HTTP 400constraint_not_narrowing.ruleattaches an optional request rule, evaluated server-side, that can only further restrict each request the returned client makes — it can never widen access. Supported shapes includejson_matchdeny rules,require_approvalHITL rules,content_matchrules built withcontent_match_rule(...),operation_allowlistrules built withoperation_allowlist_rule(...), andrequest_allowlistrules built withrequest_allowlist_rule(...). A raw-token retrieval carries no request method/URL, somethod-keyed conditions are treated as satisfied there (a raw token can issue any method) — scope method restrictions through the proxy surface, which carries the request method. If a request is frozen for human approval (HITL 202), the per-request rule is not re-evaluated on the deferred post-approval execution — it cannot widen access (the rule did not match the frozen request, and the grant plus every stored policy rule still bound the execution), but prefer a stored rule when the constraint must hold at execute time.
App.with_constraints(*, scopes: list[str] | None = None, rule: RequestRule | dict[str, Any] | None = None) -> AppThe three typed rule builders:
content_match_rule( *, operations: Sequence[str] | None = None, families: Sequence[ContentMatchFamily] | None = None, params: Sequence[ContentParamCondition] | None = None, effect: ContentMatchEffect = "deny", redact_fields: Sequence[str] | None = None, max_session_age_seconds: int | None = None,) -> RequestRule
operation_allowlist_rule( *, operations: Sequence[str] | None = None, families: Sequence[ContentMatchFamily] | None = None,) -> RequestRule
request_allowlist_rule( *, require: Sequence[RequestAllowlistCondition], operations: Sequence[str] | None = None, families: Sequence[ContentMatchFamily] | None = None, methods: Sequence[str] | None = None, endpoints: Sequence[str] | None = None, strict: bool = False,) -> RequestRulecontent_match_rule says what the client may not do: when a request matches the listed operations or families (and every parameter condition), it is denied, has fields redacted, or requires a fresh session. operation_allowlist_rule says what the client may do: only the listed operation ids and/or families may run; every other classified operation is denied (PolicyViolationError, reason operation_not_allowed), and so is any request the catalog cannot classify (operation_unclassified) or that is an unreviewed operation the list does not name (operation_unreviewed, raised as OperationUnreviewedError). Several allowlists on one chain — a stored app or grant rule plus this per-request rule — intersect, so the per-request rule only narrows. Both builders require at least one of operations / families, accept at most 100 combined entries with operation ids of at most 255 characters, and raise AlterValueError locally on a malformed input.
request_allowlist_rule says what a request must look like to be allowed: a request the rule selects passes only when every condition in require (1 to 20) holds, and is otherwise denied (PolicyViolationError, reason request_condition_not_met). A request it does not select is not judged by it. The rule has two forms, chosen by the selector and never mixed. With operations / families it selects cataloged operations and each condition names a projected parameter (name). With endpoints (and optionally methods) it selects by HTTP method and path and each condition addresses the request as sent (at: body:<path>, query:<name> or header:<name>), so it needs no operation catalog and compares values exactly. strict=True also denies a selected request that carries a field no condition names (reason request_field_not_listed). The builder raises AlterValueError locally when no selector or both selectors are given, a condition does not match the form, an operator or its value is malformed, or optional is combined with exists. See Allow only requests that meet conditions for the operators and the address grammar.
| Parameter | Type | Default | Description |
|---|---|---|---|
scopes | list[str] | None | None | Optional non-empty list of scope strings to attenuate to. |
rule | RequestRule | dict | None | None | Optional request rule carried on every request the returned client makes; enforced on credential-using calls (token retrieval, proxied provider requests). |
At least one of scopes / rule is required.
Raises: AlterValueError (neither scopes nor rule supplied, malformed scopes / rule, nested constraint call), AlterSDKError (client closed).
from alter_sdk import content_match_rule, operation_allowlist_rule, request_allowlist_rule
narrowed = app.with_constraints(scopes=["grants:read"])await narrowed.list_grants()
# Attach a json_match deny rule to every request from this constrained client:restricted = app.with_constraints( rule={ "rule_type": "json_match", "rule_body": {"when": {"method": "POST"}, "effect": "deny"}, },)
# Attach an operation-aware content rule. The helper validates that# max_session_age_seconds is an integer in [1, 86400].fresh_session = app.with_constraints( rule=content_match_rule( operations=["messages.send"], effect="step_up", max_session_age_seconds=300, ),)
# Deny a QuickBooks `query` call unless the SQL it carries — the `query`# query-string parameter of that operation — is literally one of these# (the `*` is a star, not a wildcard; the comparison ignores case and# surrounding whitespace):literal_statements = app.with_constraints( rule=content_match_rule( operations=["query"], params=[ {"name": "query", "op": "not_all_in", "value": ["select * from account"]}, ], ),)
# Allow only these two operations; everything else — and anything the# catalog cannot classify — is denied:read_only = app.with_constraints( rule=operation_allowlist_rule( operations=["query", "generalledger/query_a_report"], ),)
# Allow a POST to /v1/orders only when it meets every condition, and# carries no field the rule does not name:bounded_orders = app.with_constraints( rule=request_allowlist_rule( methods=["POST"], endpoints=["/v1/orders"], require=[ {"at": "body:amount", "op": "lte", "value": 50000}, {"at": "body:currency", "op": "in", "value": ["usd", "eur"]}, {"at": "body:note", "op": "exists", "value": True}, ], strict=True, ),)get_agent
Section titled “get_agent”App.get_agent(agent_id: str | UUID) -> Agent| Parameter | Type | Default | Description |
|---|---|---|---|
agent_id | str | UUID | — | Managed-agent UUID. Must parse as a UUID. |
Returns: an Agent instance impersonating agent_id.
Raises: AlterValueError (empty / non-UUID input, App has been closed). The agent is not looked up here: when it does not exist or is no longer active, the returned Agent’s next call raises AgentNotFoundError (HTTP 404, details["error"] == "caller_agent_unresolved").
agent = app.get_agent(agent_id="11111111-2222-3333-4444-555555555555")me = await agent.me()The parent App’s user_token_getter is intentionally NOT inherited. To bridge a user JWT through the impersonated agent, construct Agent(api_key=…, user_token_getter=…) directly.
Lifecycle
Section titled “Lifecycle”await app.close()
async with App(api_key="alter_rk_…") as app: ...close() shuts down the underlying HTTP clients and completes any pending work. The async context manager is the recommended pattern.
The workload SDK client. Use for AI agents and any code that should be identity-scoped to a managed agent. The agent can reach two kinds of credentials:
- User-delegated OAuth grants — a user completed Connect with
agent=<this-agent>, creating a per-agent delegation record that authorizes the agent against the user’s grant. - Agent-owned managed-secret grants — an operator granted a managed-secret provider’s credential directly to the agent through the Developer Portal.
App.create_managed_secret_grant()does not accept agent principals.
Agent.list_grants() returns both in one merged view.
Agent( api_key: str, *, timeout: float = 95.0, caller: str | None = None, user_token_getter: Callable[[], str | Awaitable[str]] | None = None, logger: logging.Logger | None = None,)| Parameter | Type | Default | Description |
|---|---|---|---|
api_key | str | — | Agent API key. Required. The managed agent’s own key, from alter agents create / alter agents mint-key (currently the legacy alter_key_… prefix). An agent-typed alter_ak_… key from API Keys also constructs an Agent, but it is bound to no managed agent, so it cannot reach grants bound or delegated to a named agent. |
timeout | float | 95.0 | HTTP request timeout in seconds. The default is sized so a slow credential refresh returns the SDK’s typed timeout error (with its timeout_reason) rather than a bare client-side timeout; lower it for latency-sensitive callers that prefer to fail fast. |
caller | str | None | None | Optional caller identifier for audit attribution. |
user_token_getter | callable | None | Optional sync/async callable returning a user JWT. Used for Connect-time delegation and per-call delegation disambiguation. The JWT does NOT grant access — the agent’s authority comes from the per-agent delegation record bound at Connect time. |
logger | logging.Logger | None | module logger | Optional logger for SDK diagnostics. Must provide a callable warning; info and debug are used when present. A logger that raises never fails the SDK call it was logging. |
Agent pins caller_type=AGENT internally; it is not constructor-configurable.
It raises AlterSDKError for the same malformed key, getter, logger, and backend-URL inputs as App.
Properties
Section titled “Properties”| Property | Type | Description |
|---|---|---|
actor_id | str | None | Cached actor UUID once the first authenticated call resolves. |
last_retry_info | RetryInfo | None | Retry metadata from the most recent request() call. |
last_rate_limit | RateLimitSnapshot | None | Latest complete Alter rate-limit reading from a metered backend response. None means unknown, never unlimited. |
base_url | str | Backend base URL the client is pinned to. |
keys | namespace | Scoped-key lifecycle (see Agents & Keys). |
scopes | namespace | Scope catalog discovery (see Calling APIs). |
oauth_providers | namespace | OAuth provider catalog (see Connect & Grants). |
provider_specs | namespace | Provider operation discovery (see Provider discovery). |
spans | namespace | User-defined trace spans (see spans.emit()). |
Methods
Section titled “Methods”Agent exposes:
me()— self-introspection (agent-only).request(),proxy_request()—request()requires a grant the agent may retrieve directly; a delegated grant is proxy-only, so useproxy_request()for it.list_grants()oauth_providers.list()— OAuth provider catalog.provider_specs.*— provider operation discovery.spans.emit()— user-defined trace spans.create_connect_session(),connect(),poll_connect_session(),create_connect_session_for_error()create_managed_secret_connect_session()— ask a user for access to a managed-secret provider for this agent: a grant the user holds, or the user’s own key.revoke_delegation()— self-revoke only.delegate()— onward agent-to-agent delegation.get_approval_status(),await_approval(),list_approvals()— an agent lists the approvals it created; it never decides oneresolve_identity(),assert_identity()— the identity-export surface; the agent shape additionally accepts the consent-edgeapp_user_idshortcut (see Propagate identity into memory layers)trace()— audit-scope context manager.with_constraints()(below)
Operator surfaces (agents namespace CRUD, authenticate, verify_user_token, revoke_grant, create_managed_secret_grant) are intentionally absent — calling them with an agent key would raise typed errors deep in the request path.
with_constraints
Section titled “with_constraints”Identical semantics to App.with_constraints() — returns a constrained sub-Agent whose every request carries the same attenuation (the rule is enforced on credential-using calls). Pass scopes to narrow the scope set, rule to attach a request rule, or both; at least one is required.
Agent.with_constraints(*, scopes: list[str] | None = None, rule: RequestRule | dict[str, Any] | None = None) -> AgentAsync context manager that scopes audit identity for every nested request() call. See Agent.trace() on the Agents page for the full surface.
Lifecycle
Section titled “Lifecycle”await agent.close()
async with Agent(api_key="alter_key_…") as agent: ...Identity helpers
Section titled “Identity helpers”verify_user_token
Section titled “verify_user_token”App only. Verify an IDP-issued JWT against the application’s configured identity provider.
async def verify_user_token(token: str) -> str | NoneReturns the verified sub claim on success. It returns None for an empty, invalid, expired, or malformed token; a missing identity-provider configuration; a closed client; an unexpected backend response; or a network failure. Verification fails closed and does not raise for these outcomes. Treat every None as unauthenticated.
resolve_identity
Section titled “resolve_identity”Return the canonical IdentityContext for downstream memory, routing, and authorization layers.
# Appasync def resolve_identity( *, user_token: str | None = None, include_profile: bool = False,) -> IdentityContext
# Agentasync def resolve_identity( *, user_token: str | None = None, app_user_id: str | None = None, include_profile: bool = False,) -> IdentityContextOn App, an explicit user_token wins over the configured user_token_getter; the getter is used when the argument is omitted. Agent never reads its configured getter for this identity-export method: pass user_token explicitly, or use app_user_id to resolve through an existing consent edge. include_profile=True asks the backend to include the optional email and display_name fields. Requires identity:resolve.
assert_identity
Section titled “assert_identity”Mint a short-lived, Alter-signed identity assertion for a downstream service.
# Appasync def assert_identity( *, audience: str, user_token: str | None = None, ttl_seconds: int | None = None, include_profile: bool = False,) -> IdentityAssertion
# Agentasync def assert_identity( *, audience: str, user_token: str | None = None, app_user_id: str | None = None, ttl_seconds: int | None = None, include_profile: bool = False,) -> IdentityAssertionaudience must be a URI with a scheme and at most 512 characters. ttl_seconds, when supplied, must be an integer from 10 through 300. User resolution follows the same App versus Agent rules as resolve_identity(). Returns IdentityAssertion; its token proves identity to the named audience but grants no credential access. Requires identity:assert.
Both methods raise AlterValueError for malformed local input and use the standard typed backend-error mapping for rejected identity requests or malformed responses.
is_valid_key
Section titled “is_valid_key”Validate the complete syntactic shape of an Alter API key without a network round-trip. Scoped keys re-derive and compare the CRC checksum; legacy keys enforce the exact mint-time length and alphabet.
from alter_sdk import is_valid_keyis_valid_key(plain_key: object) -> bool| Parameter | Type | Default | Description |
|---|---|---|---|
plain_key | object | — | Candidate key string. Non-strings and empty strings return False. |
Returns True only for syntactically-valid keys: either alter_key_ plus exactly 40 ASCII letters, digits, -, or _; or alter_<type>_<random>_<checksum> with a supported type, exactly 22 lowercase-base32 random characters, and a matching 6-character lowercase-base32 CRC. The check is a usability gate — a forged checksum still cannot pass backend verification.
from alter_sdk import App, is_valid_key
raw = input("Paste API key: ").strip()if not is_valid_key(raw): raise SystemExit("Invalid key shape")app = App(api_key=raw)Managed integrations
Section titled “Managed integrations”app.integrations (also available on Agent) exposes generic discovery and execution:
list() lists publications, contract(provider, version) reads an immutable contract,
and execute submits its provider, version, operation and arguments with a grant or
connection selector. Execution returns an immediate ApprovalResult or PendingApproval.
The backend authorizes OAuth or managed-secret grants before constructing provider requests.
Typed provider methods live in separate provider packages, never in core.
Browse Integrations: a provider with a typed package has an SDK guide and an API reference with installation guides, complete operation schemas, both-language examples and links to each pinned OpenAPI specification.
Install alter-sdk-<provider> (which depends on alter-sdk).
Their methods return IntegrationCall[T];
await call.wait(timeout=300, poll_interval=2) returns IntegrationResult after immediate execution or approval.
Waiting polls approval state and does not resubmit the provider operation.
See managed result types.
Stream a managed response
Section titled “Stream a managed response”execute_stream takes the same arguments as execute and returns a ProxyStreamResponse instead of a buffered result, so a large binary response (a file download) arrives as it is sent, with no size cap and no truncation. Policy, connection authorization and audit are the same as execute. An operation a policy holds for approval is refused with ProxyTransferError code proxy_stream_approval_required: request it with execute instead.
response = await app.integrations.execute_stream( integration=provider, version=version, operation=operation_id, arguments=arguments, grant_id=grant_id,)async with response: async for chunk in response.iter_bytes(): await output.write(chunk)Upload a large managed file
Section titled “Upload a large managed file”execute_upload executes an operation whose body is one file (an upload) without the inline limit. Pass the operation’s other arguments (no body) and the file as path or data, named filename (default: the name of path) with media type content_type (default application/octet-stream). metadata is the file’s metadata, a JSON object (dict[str, Any]), for an operation whose file goes in a multipart attachment body with metadata beside it (an accounting provider’s attachment record). An operation whose body is the file itself (a file-storage upload) takes no metadata and refuses it with invalid_operation_input. The operation is declared with the file’s size and SHA-256, every policy runs on that declaration, and only then are the bytes sent, once and never retried. Policy, approval and audit are the same as execute, which takes this route by itself when an inline file object, or an attachment body holding one file ({"files": [{...}]}, its metadata included), is too large (about 3.7 MiB of file; the arguments are measured as Alter measures them, JSON with a space after each , and : and every non-ASCII character counted as its six-byte \uXXXX escape), so a provider package’s typed upload method needs no change. An operation whose body is not one file is refused with ProxyTransferError code operation_not_uploadable.
A PendingApproval means nothing was sent: once approved, deliver the same bytes with deliver_approved_upload. Waiting on a provider package’s IntegrationCall (await call.wait()) delivers them by itself.
result = await app.integrations.execute_upload( integration=provider, version=version, operation=operation_id, arguments=arguments, path="report.pdf", content_type="application/pdf", grant_id=grant_id,)if isinstance(result, PendingApproval): result = await app.deliver_approved_upload(result.approval_id, path="report.pdf")Resume a managed call
Section titled “Resume a managed call”app.integrations.resume(approval_id) (Python) or app.integrations.resume(approvalId) (TypeScript) rebuilds a call from stored server identity. Use the provider package’s resume for its response validator. See restart-safe approvals.