Skip to content

Reference

Types

Pydantic models, enums, and discriminated unions returned across the SDK surface.

Fields are snake_case and match the wire format. Most Pydantic models are frozen. APICallAuditLog, UserSpan, and EmitSpansResult are mutable Pydantic models; RequestRule and ContentParamCondition are TypedDict shapes.

from alter_sdk import (
TokenResponse, GrantInfo, ConnectSession, ConnectResult,
UnifiedGrantListResult, OAuthGrantItem, ManagedSecretGrantItem,
GrantListItem, GrantPolicy, GrantPolicyInput, ConnectFailedGrant, ConnectDelegation,
CreateGrantResult, RevokeGrantResult, DelegationResult,
Principal, PrincipalType, NonGroupPrincipalType,
UserPrincipal, GroupPrincipal, SystemPrincipal, AgentPrincipal,
AgentInfo, AgentCreateResult, AgentListResult,
AgentKey, AgentKeyList, AgentKeyMintResult,
APIKeyInfo, MintedKey, ScopeCatalog, ResourceScopes,
ApprovalGate, ApprovalGateStatus,
ApprovalResult, ApprovalStatus, ApprovalStatusValue, PendingApproval,
AuthResult, AuthSession, APICallAuditLog,
OAuthProviderCatalog, OAuthProviderCatalogItem, OAuthProviderScopeInfo,
ProviderSpec, ProviderSpecKind,
SpecOperation, SpecOperationsPage, SpecOperationDetail,
RetryInfo, RetryErrorInfo, RateLimitSnapshot,
RequestRule, ContentMatchEffect, ContentMatchFamily,
ContentParamCondition, ContentParamOp, content_match_rule, operation_allowlist_rule,
RequestAllowlistCondition, RequestAllowlistOp, request_allowlist_rule,
UserSpan, EmitSpansResult,
IdentityContext, IdentityTrace, MemoryScope, IdentityAssertion,
HttpMethod, CallerType, Provider,
)
HttpMethod.GET # "GET"
HttpMethod.POST # "POST"
HttpMethod.PUT # "PUT"
HttpMethod.PATCH # "PATCH"
HttpMethod.DELETE # "DELETE"
HttpMethod.HEAD # "HEAD"
HttpMethod.OPTIONS # "OPTIONS"

Plain strings are also accepted by every SDK method that takes method.

CallerType.AGENT # "agent"
CallerType.SERVICE # "service"

App defaults to SERVICE. Agent pins AGENT internally.

Static enum of OAuth provider identifiers. It contains the provider ids available when the SDK version was published. Methods also accept plain strings for forward compatibility with provider ids added after that release.


Returned by proxy_stream_request(). It owns a live connection; close it on early exit.

MemberDescription
status_codeThe provider’s HTTP status. Provider errors are response data, not exceptions.
headersProvider response headers, without credential or cookie headers.
headers_droppedHow many provider headers were not forwarded (over the size limit, or an invalid name). Non-zero means headers is incomplete.
iter_bytes()Yields provider bytes once, with backpressure.
close()Releases the connection.

OAuth token response. The plaintext access token is NOT stored as a readable attribute — the backend injects it into outbound requests but never exposes it.

FieldTypeDescription
grant_idstrGrant id that provided this token.
token_typestrToken type. Default "Bearer".
expires_inint | NoneSeconds until expiry.
expires_atdatetime | NoneAbsolute instant this credential stops working — the binding value: the earlier of the provider token’s own expiry and the grant’s TTL. Caching past it produces an authorization failure, not a refresh.
token_expires_atdatetime | NoneThe provider token’s own expiry, independent of the grant’s TTL. The only clock a refresh can move.
grant_expires_atdatetime | NoneThe grant’s own TTL instant (the access duration chosen at consent); None when the grant has no TTL.
scopeslist[str]OAuth scopes granted.
provider_idstr | NoneProvider id.
scope_mismatchboolTrue when the backend has flagged this grant as requiring re-authorization.
injection_headerstrCredential-injection header name. Excluded from model_dump().
injection_formatstrCredential-injection value format. Excluded from model_dump().
additional_credentialsdict[str, str] | NoneAdditional non-exposed credential metadata for multipart authentication. Excluded from model_dump().
additional_injectionslist[dict[str, str]] | NoneAdditional header or query injection rules. Excluded from model_dump().

Methods: is_expired(buffer_seconds=0) -> bool, needs_refresh(buffer_seconds=300) -> bool.

The two answer different questions and read different fields. is_expired() reads expires_at — whether the credential still works. needs_refresh() reads token_expires_at — whether refreshing would help.

They diverge whenever the grant’s TTL is the earlier of the two clocks: the credential is about to stop working, but a refresh cannot extend permission and the correct response is re-consent. Compare grant_expires_at to tell which clock is binding.

Frozen snapshot exposed as last_rate_limit on App, Agent, and constrained clients.

FieldTypeDescription
limitintBinding requests-per-minute ceiling for the response.
remainingintRequests remaining against that binding ceiling.
reset_atdatetimeAware UTC instant when the reported window resets.

The value is None until a metered response supplies the standard RateLimit-Policy / RateLimit pair or the compatibility X-RateLimit-* triple. A later unmetered response does not erase the last reading. Provider response headers are not captured because they describe the provider’s budget, not Alter’s.

Attached to response.retry_info when the backend refreshed a token after transient failures.

FieldTypeDescription
total_attemptsintTotal attempts made.
successful_attemptintWhich attempt succeeded (0 if none).
errorstuple[RetryErrorInfo, ...]Failed attempts (immutable).
FieldTypeDescription
attemptint1-based attempt index.
errorstrError message, truncated to 500 chars.
error_typestrError classification.
delay_sfloatSleep duration before the next attempt.
permanentboolWhether the error is permanent.

Metadata shape returned by App.mint_grant(), and retained for legacy grant responses. App.list_grants() and Agent.list_grants() return OAuthGrantItem / ManagedSecretGrantItem through the unified list instead.

FieldType
grant_idstr
provider_idstr
scopeslist[str]
account_identifierstr | None — the display handle for the connected account: an email for most providers, the authorizing user’s id for Slack, the account id for Stripe, the company realmId for QuickBooks. It is what the provider surfaced for the scopes that were granted, so it can differ between connections to the same account and is not an identity key. None when the provider exposes no account identity or it could not be confirmed at connect time.
account_display_namestr | None — the human-readable name for the same account (a person’s name, a workspace or company name).
api_base_urlstr | None — The connection’s provider API origin when it depends on the connected account or the provider environment: a Salesforce org’s instance URL; https://quickbooks.api.intuit.com / https://sandbox-quickbooks.api.intuit.com for a QuickBooks production or sandbox company; or https://api.ramp.com / https://demo-api.ramp.com for a Ramp production or sandbox connection. Build full request URLs from it. None for providers that record no origin (one fixed API host), or when the connection predates Alter recording it (reconnect to capture it).
statusstr
scope_mismatchbool
expires_atstr | None
created_atstr
last_used_atstr | None
principal_type"user" | "group" | "system" | "agent"
labelstr | None
credential_idstr | None
tagsdict[str, str]
grant_policydict[str, Any] | None

Returned by App.list_grants() and Agent.list_grants().

FieldTypeDescription
grantslist[GrantListItem]Discriminated-union items.
totalintTotal matching rows.
limitintPage size.
offsetintPage offset.
has_moreboolCanonical “more pages” signal. Prefer this over computing offsets against total.

Discriminated union by grant_kind:

GrantListItem = OAuthGrantItem | ManagedSecretGrantItem

grant_kind="oauth". An active delegated grant retains its authority while needs_reconnect is true: its next call attempts a refresh when possible, or raises ReAuthRequiredError for fresh consent. A reconnect flag alone does not mean the delegation is missing.

FieldTypeDescription
grant_kind"oauth"Discriminator.
grant_idstr
provider_idstr
scopeslist[str]
account_identifierstr | None
account_display_namestr | None
api_base_urlstr | NoneThe connection’s provider API origin when it depends on the connected account or the provider environment: a Salesforce org’s instance URL; https://quickbooks.api.intuit.com / https://sandbox-quickbooks.api.intuit.com for a QuickBooks production or sandbox company; or https://api.ramp.com / https://demo-api.ramp.com for a Ramp production or sandbox connection. Build full request URLs from it. None for providers that record no origin (one fixed API host), or when the connection predates Alter recording it (reconnect to capture it).
statusstr
scope_mismatchbool
needs_reconnectboolConnection health (a separate axis from status): True when the grant is active but its provider token broke and needs re-auth. A call against it may raise ReAuthRequiredError (a recoverable break self-heals transparently on the next call); the flag clears on a successful refresh or a reconnect.
expires_atstr | NoneThe provider token’s expiry (auto-refreshed — never a grant terminal).
grant_expires_atstr | NoneThe grant’s own TTL-policy expiry (the access duration chosen at consent). A different axis from expires_at; None = perpetual. status reads "expired" once this instant passes, even before the record is lazily flipped.
created_atstr
last_used_atstr | None
principal_type"user" | "system" | "agent"The "agent" value marks a delegation child surfaced as its own row in the operator list.
access_via"ownership" | "oauth_delegation"How the caller reached the grant.
delegated_atstr | NoneAgent-branch field: when the calling agent’s delegation row was created.
delegated_agent_idslist[str]Operator-branch field: agent UUIDs this grant is currently delegated to.
labelstr | NoneStable sibling-grant address within the credential.
credential_idstr | NoneShared credential id used to group sibling grants.
grant_policydict[str, Any] | NonePer-grant policy.
parent_grant_idstr | NoneThe grant this one was minted under. None marks a root (a directly-consented grant).
depthintHop distance from the root (0 at the root). With parent_grant_id, lets a caller reconstruct the delegation tree from the flat list.
delegableboolWhether this grant may be re-delegated onward to another agent. Always present (defaults False).
scope_constraintlist[str] | NoneThe narrowed provider-scope subset this delegated grant is clamped to. None = inherits the parent/credential scope.
tagsdict[str, str]Key/value tags, filterable with list_grants(tags=...). {} when there are none.
delegation_labelstr | NoneThe label set on delegate(), which an agent selects this delegation by.

grant_kind="managed_secret". Returned for any managed-secret grant the caller can reach — an operator (App) list surfaces every principal kind the app owns; an agent list surfaces its own and delegated grants.

FieldType
grant_kind"managed_secret"
grant_idstr
managed_secret_idstr
managed_secret_slugstr
managed_secret_namestr
agent_idstr | None
labelstr | None
statusstr
account_identifierstr | None
grant_policydict | None
expires_atstr | None
grant_expires_atstr | None
created_atstr
last_used_atstr | None
principal_type"user" | "group" | "system" | "agent"
access_via"ownership" | "ms_delegation"
delegated_atstr | None
parent_grant_idstr | None
depthint
delegablebool
scope_constraintlist[str] | None
credential_idstr | None
credential_kind"developer" | "end_user" | None
credential_labelstr | None
tagsdict[str, str]
delegation_labelstr | None

managed_secret_id is the provider’s id (a UUID, the value create_managed_secret_grant() takes), managed_secret_slug its slug (the value provider= and list_grants(provider_id=...) take, unique per app among active providers; the alter managed-secrets commands accept either, alter grants list --provider only the slug) and managed_secret_name its display name, which several providers may share.

credential_id names the stored credential the grant serves. A provider can hold several; a key’s delegations share its id, so group by it as you would OAuth grants by credential_id. credential_kind is "developer" for a credential the application’s developer stored and "end_user" for an end user’s own key. credential_id, credential_kind and credential_label are all None from a backend that predates managed-secret credentials.

FieldType
successbool
messagestr
grant_idstr
revoked_atstr
FieldType
grant_idstr
principal_type"user" | "group" | "system" | "agent"
labelstr | None
created_atstr
credential_idstr | None

credential_id is the stored credential the new grant serves (None only from a backend that predates managed-secret credentials).

Returned by agent.delegate() — the child grant minted onto another agent.

FieldTypeDescription
grant_idstrThe new child grant.
grant_kind"oauth" | "managed_secret"Which credential family the child belongs to.
parent_grant_idstrThe held grant the child was minted under (always set — a delegation result is always a child).
depthintThe child’s hop distance from the root (always >= 1).
delegableboolWhether the recipient may re-delegate this child onward.
statusstrGrant status (e.g. "active").
expires_atstr | NoneChild expiry, clamped to the parent’s lifetime.
labelstr | NoneThe label the recipient selects the child by.
tagsdict[str, str]The child’s tags after inheritance.
ruleslist[DelegatedRule]The enabled rules this agent authored on the child. Rules an operator put on it are not listed.
approver_warningslist[str]One entry per require_approval rule whose approvers were not verified against the directory. [] when there are none.

Result of update_grant_tags().

FieldTypeDescription
grant_idstrThe grant.
grant_kind"oauth" | "managed_secret"Which credential family the grant belongs to.
tagsdict[str, str]The grant’s whole tag map after the replace.
FieldTypeDescription
rule_idstrThe rule’s id.
rule_typestrThe rule’s type, e.g. "quota".

A TypedDict: one entry of delegate(rules=...), the rule created on the child. A RequestRule (the output of content_match_rule(), operation_allowlist_rule() or request_allowlist_rule()) is one too.

FieldTypeRequiredDescription
rule_typestryesOne of json_match, require_approval, time_window, quota, content_match, operation_allowlist, request_allowlist, ip_allowlist, restriction.
rule_bodydict[str, Any]yesThe rule’s body, as on the policy rules API.
namestr | NonenoDisplay name of the rule.
descriptionstr | NonenoDescription of the rule.
FieldTypeDescription
expires_atstr | NoneHard expiry timestamp (ISO 8601 UTC).
created_bystr | None"developer" or "end_user".
created_atstr | None

Input model accepted by the Connect, managed-secret grant-create, and sibling-grant minting methods. The keyset is the union of what the individual methods accept — each row states where the field is accepted.

FieldTypeDescription
expires_atstr | NoneHard expiry timestamp (ISO 8601 UTC). Must parse as an ISO 8601 value — an unparseable string raises a validation error locally, before any request is sent. Accepted by create_managed_secret_grant() and mint_grant(); the Connect-session methods (create_connect_session(), create_connect_session_for_error(), connect()) reject it with a 422 — expiry there is derived from the TTL the user picks on the consent screen.
max_ttl_secondsint | NonePositive maximum TTL in seconds. Accepted by every method.
default_ttl_secondsint | NonePositive pre-selected TTL; must not exceed max_ttl_seconds. Accepted by the Connect-session methods and create_managed_secret_grant(); mint_grant() rejects it locally with AlterValueError — a minted grant has no TTL picker to pre-select for.

Principal = UserPrincipal | GroupPrincipal | SystemPrincipal | AgentPrincipal

The discriminator is type.

PrincipalType is Literal["user", "group", "system", "agent"]. NonGroupPrincipalType is Literal["user", "system", "agent"] and is used by OAuth grant models, where group principals are not supported.

FieldTypeDescription
type"user"Discriminator.
user_tokenstrIDP JWT (1-8192 chars).
labelstr1-255 chars.
FieldTypeDescription
type"group"Discriminator.
external_group_idstr1-255 chars.
idp_idstrIdentity provider id (UUID), 1-255 chars.
labelstr1-255 chars.
FieldTypeDescription
type"system"Discriminator.
labelstr | NoneOptional, max 255 chars.
FieldTypeDescription
type"agent"Discriminator.
labelstr | NoneOptional, max 255 chars.

The agent is resolved from the API-key signature server-side — there is no agent_id on the wire.


FieldType
session_tokenstr
connect_urlstr
expires_inint
expires_atstr
scope_constraint_warningslist[str]
dropped_providerslist[DroppedProvider]
single_providerbool
directbool

single_provider is True when the session names exactly one provider: the hosted UI skips the provider picker and renders no Alter-branded page. Pass it to the browser widget as open({ singleProvider }) so an inline flow opens the provider window straight from the application’s click instead of rendering a tile.

direct is True only when the application explicitly opted the session out of the end-user consent screens — the confirmation screen, the duration choice and the in-flow policy step — and the page delivers the outcome and closes. It is never implied by the provider count, and the browser widget does not consume it. A session that delegates to an agent with delegable=True reports False: the user decides onward sharing on the confirmation screen, so the screen is shown.

scope_constraint_warnings (default []) carries one diagnostic per provider whose required scopes the requested scope_constraint admits nothing against — the session still succeeds, but a grant minted from it would deny every call until the constraint is widened. It also carries one entry, prefixed agent_allowlist:, per provider the session dropped because the delegated agent’s capability allowlist cannot use it, and one prefixed tag_match: per provider dropped because a tag match rule refuses the agent for the session’s tags. Only a provider the request names in neither allowed_providers nor required_scopes is dropped; a provider the request names that the agent cannot use refuses the session with agent_allowlist_exceeded (or tag_mismatch) instead. A tag_match: entry also warns, without dropping anything, when a tag match rule names a key the session’s tags leave unset and no connection the user could approve with is known to carry the agent’s value: the delegation would be refused after the user consents.

dropped_providers (default []) lists the same dropped providers as structured entries, one DroppedProvider each, so code can act on them without parsing the warning text. A malformed value in the response is read as [], and an entry without a non-empty provider_id and check is skipped.

One provider a Connect session left out because the delegated agent cannot use it: its capability allowlist does not cover it, or a tag match rule refuses the agent for the session’s tags. Frozen.

FieldTypeDescription
provider_idstrThe provider that was dropped.
checkstrThe allowlist check that failed: provider_not_allowlisted (the allowlist has no entry for the provider), scopes_not_allowlisted (the provider’s scopes are not all on the allowlist) or grant_scopes_malformed (the scopes cannot be evaluated), or tag_mismatch (a tag match rule refuses the agent for this provider). Other values may be added.

Returned by create_managed_secret_connect_session() on App and on Agent. __repr__ redacts connect_url (it carries the session token in the URL fragment).

FieldType
session_tokenstr
connect_urlstr
expires_inint
expires_atstr
warningslist[str]
delegable_requestedbool
pathLiteral["fast_path", "key_entry", "repair"] | None
existing_grant_idstr | None
directbool
secret_slugstr | None
template_slugstr | None
agent_idstr | None

session_token starts with ms_sess_; pass it to the @alter-ai/connect widget’s open({ token }), which opens the managed-secret page for it.

path is how the session completes, decided when it was created: "fast_path" (the user already holds a grant on the provider this request can use; existing_grant_id is the one labelled requested_grant["label"] when there is one, else the newest), "key_entry" (the user holds none and will enter their own key; existing_grant_id is None) or "repair" (existing_grant_id is the user’s own key being replaced: the one repair_grant_id named, or the user’s own key whose grant expired when the user holds nothing else this request can use). Both are None for a session a managed agent’s own key created: session creation never tells an agent what the user holds. An unknown path value from the backend reads as None.

direct is whether the usage-limits step is skipped, as the session stored it: a session that asked for onward sharing is never direct, and a repair always is.

warnings (default []) is what the application should know before the user consents, each entry prefixed with its source. tag_match:: a tag match rule names a key the delegation must carry with the agent’s value, the session’s tags leave it unset and no grant the user could approve with is known to carry the agent’s value, so the delegation would be refused after the user consents (tag_mismatch); set the key in tags. Names keys, never values. For a session a managed agent’s own key created, the user’s grants are not consulted. A malformed value reads as [].

secret_slug is the slug of the provider the session asks about (None only for a deprecated template_slug request whose template matches no single provider of the application), template_slug that provider’s template (None for a custom provider), and agent_id the agent the session delegates to (None for the application’s own use). The SDK refuses a response whose secret_slug is not the provider that was sent (BackendError). A backend that predates these fields omits them; they then read as None / False, and the SDK raises ServerFeatureUnsupportedError instead when the call used an option such a backend ignores.

delegable_requested echoes the delegable the session was created with: True when the application asked the user to let the agent share the access onward, so the Connect page offers that choice when the credential’s delegation policy allows it. It is the request, not the user’s decision: the approval reports the stored setting as delegable (see what the application learns). The SDK returns the session only when the echo matches the request: delegable=True with an echo that is absent or False raises ServerFeatureUnsupportedError, and an echo of True when delegable was not sent raises BackendError.

FieldType
grant_idstr
provider_idstr
account_identifierstr | None
scopeslist[str]
api_base_urlstr | None — the connection’s provider API origin (see GrantInfo.api_base_url)
operationLiteral["creation", "reauth"]
grant_policyGrantPolicy | None
failed_grantslist[ConnectFailedGrant]
delegationConnectDelegation | None

delegation is set when the session delegated the grant to an agent, and None otherwise.

The delegation a Connect session made of one grant to its agent.

FieldTypeDescription
agent_idstrThe agent the grant was delegated to.
delegableboolThe delegation’s stored onward-sharing setting after the user’s approval: whether the agent may share this access with other agents through agent.delegate().
policy_refusedboolTrue when the user chose to let the agent share this access but the provider’s agent sharing setting refused that choice when the connection was confirmed (the setting changed while the consent screen was open). delegable then reports the setting that was kept. False otherwise, and when the backend predates the field.

delegable is the stored setting, not a capability. The provider’s agent sharing setting still decides each onward delegation, so a True setting is refused once the operator turns sharing off.

Parsing fails closed on a known field and ignores any other: agent_id must be a UUID string and delegable (and policy_refused, when present) a real bool, or the poll raises BackendError with details == {"field": "delegation"}. A field this SDK version does not know is ignored, so a newer backend never breaks it.

One provider the session connected but did not keep: the user did not select it on the Confirm screen, the connection could not be completed when the user confirmed it, or its selected usage limits could not be applied.

FieldTypeDescription
provider_idstrProvider id.
reasonstrMachine-readable failure reason. Unknown values are retained.
messagestrOperator-safe failure message.
reasonMeaning
not_selectedThe user connected the provider but did not select it on the Confirm screen, so the connection was dropped and never became usable.
activation_failedThe user confirmed the provider, but the connection could not be completed (for example, the same account was connected again in a newer Connect session, or the account connection was removed), so it never became usable. Connect it again.
any other valueThe selected usage limits could not be applied (for example invalid_rule, rule_limit, storage_error), so the newly authorized grant was revoked.
FieldTypeDescription
user_tokenstrIDP JWT bearer token.
user_infodict[str, Any]User info from IDP (sub, email, name).

Returned by create_auth_session(). __repr__ redacts auth_url (it carries the session token as the OIDC state parameter).

FieldTypeDescription
session_tokenstrHandle to poll with poll_auth_session(). Persistable.
auth_urlstrIDP sign-in URL to hand to the end user. Never log it.
expires_inintSeconds until the session expires.
expires_atstrISO 8601 expiry timestamp.

Returned by oauth_providers.list().

MemberTypeDescription
providersdict[str, OAuthProviderCatalogItem]Connectable providers, keyed by id ("<provider_id>", …).
get_default_scopes(provider)tuple[str, ...]Default scopes for a provider, or () if unknown. Accepts a string or Provider member.
get_required_scopes(provider)tuple[str, ...]Required scopes for a provider, or () if unknown.
FieldTypeDescription
idstrProvider id.
namestrInternal provider name.
display_namestrHuman-readable name.
categorystr | NoneProvider category.
descriptionstr | NoneShort description.
logo_urlstr | NoneLogo URL.
supports_refreshboolProvider issues refresh tokens.
supports_pkceboolProvider supports PKCE.
available_scopesdict[str, OAuthProviderScopeInfo]All requestable scopes, keyed by scope string.
default_scopeslist[str]Scopes pre-selected in a Connect flow.
required_scopeslist[str]Scopes that are always requested.
statusstrAlways "active" (only connectable providers are returned).
FieldTypeDescription
descriptionstrWhat the scope grants.
requiredboolScope is always requested.
is_defaultboolScope is pre-selected by default.
requireslist[str]Other scopes that must be selected with this scope.

ProviderSpecKind = Literal["oauth", "managed"]
FieldTypeDescription
provider_kindstrProvider family ("oauth" or "managed").
provider_idstrProvider identifier.
versionintMonotonic stored-spec version.
provenancestrWhere the catalog came from (provider, fragment or directory).
source_urlstr | NoneUpstream spec URL when known.
content_hashstrHash of the catalog content.
operation_countintNumber of operations in the spec.
fetched_atdatetimeWhen this content was last confirmed: the later of when this version was loaded and its most recent successful check against the provider’s published description. Never earlier than changed_at.
changed_atdatetimeWhen the active content version became active.
titlestr | NoneSpec title when present.
spec_versionstr | NoneUpstream spec version when present.
FieldType
operation_idstr
methodstr
path_templatestr
summarystr | None
FieldTypeDescription
itemslist[SpecOperation]Operations on this page.
totalintTotal matching operations.
limitintPage size.
offsetintPage offset.
has_moreboolWhether another page exists.
specProviderSpecMetadata for the active spec that served the page.
FieldType
operation_idstr
methodstr
path_templatestr
summarystr | None
params_schemalist[dict[str, Any]] | None
request_schemadict[str, Any] | None
response_schemadict[str, Any] | None
specProviderSpec

See Provider discovery for the namespace methods.


The managed-agent record. PII (HITL approver list) is redacted server-side.

FieldTypeDescription
idUUID
namestr
display_namestr | None
type"agent" | "service"
status"active" | "inactive" | "revoked"
scopesdict[str, Any]Per-provider scope allowlist.
scopes_pendingdict[str, Any] | NonePending narrowing (Phase G).
scopes_applies_atdatetime | None
policydict[str, Any]Validated policy block.
metadatadict[str, Any]
tagsdict[str, str]Filterable key/value tags; {} when there are none.
rate_limit_per_minuteint | None
versionintMonotonic version counter.
created_atdatetime
last_used_atdatetime | None
parent_agent_idUUID | NoneReserved; not currently exposed.
stored_legacy_managed_secret_nameslist[str]Legacy display-name entries under scopes["managed_secrets"] that still carry authority. An update may keep these and only these; any other entry under that key is refused with a 422. Author new capabilities as slugs under scopes["managed_secret_slugs"].

Extends AgentInfo. Adds:

FieldTypeDescription
api_keystr | NonePlaintext API key. Shown ONCE. None on idempotency replay (branch on api_key is None).
key_idUUIDThe api_keys row id backing this agent.
FieldType
agentslist[AgentInfo]
totalint
limitint
offsetint
has_morebool
FieldTypeDescription
key_idUUID
key_prefixstrDisplay-only key prefix.
namestrAuto-generated {agent_name}-{N} at mint time.
created_atdatetime
deprecated_atdatetime | None
revoked_atdatetime | None
last_used_atdatetime | None

Derived property: status — "active" \| "deprecated" \| "revoked".

Extends AgentKey. Adds:

FieldTypeDescription
api_keystr | NonePlaintext. Shown ONCE.
FieldType
itemslist[AgentKey]

Read-only view of a scoped API key.

FieldType
idUUID
namestr
key_prefixstr
key_type"rk" | "ak" | "dk" | "pk"
scopeslist[str]
scope_versionint
cidr_allowlistlist[str] | None
rate_limit_rpmint | None
effective_rate_limit_rpmint | None
rate_limit_source"key" | "organization" | "platform_default" | None
expires_atdatetime | None
deprecated_atdatetime | None
revoked_atdatetime | None
parent_key_idUUID | None
created_atdatetime
last_used_atdatetime | None

Derived property: status — "active" \| "rotated" \| "revoked".

rate_limit_rpm is the per-key override chosen at mint time; None means no override, not unlimited. effective_rate_limit_rpm is the requests-per-minute ceiling actually enforced for the key once the organization ceiling and the platform default are applied, and rate_limit_source names which of those produced it. Throttling decisions should read effective_rate_limit_rpm. Both are optional on parse: a backend that does not report them leaves each None, which means not reported — never unlimited. A live backend always sends both.

Extends APIKeyInfo. Adds:

FieldTypeDescription
api_keystrPlaintext. Shown ONCE.
FieldType
scope_versionint
resourcesdict[str, ResourceScopes]
action_verbslist[str]
deprecatedlist[str]
FieldType
verbslist[str]

A TypedDict passed to with_constraints(rule=...) — cryptographically bound to every request the constrained client makes and enforced on credential-using calls.

FieldType
rule_typestr
rule_bodydict

content_match_rule() and operation_allowlist_rule() use these exported type aliases:

ContentMatchEffect = Literal["deny", "redact", "step_up"]
ContentMatchFamily = Literal["send", "read", "write", "delete", "admin", "payment"]
ContentParamOp = Literal[
"equals", "any_in", "not_subset_of", "in", "not_all_in", "exists",
"gt", "gte", "lt", "lte", "outside_windows", "under", "not_under",
]

ContentParamCondition is a TypedDict:

FieldType
namestr
opContentParamOp
valuestr | int | float | bool | list[str] | TimeWindows
OperatorvalueFires when
equalsstr, int or float (not a bool)the parameter equals the value; on a set-shaped parameter, only an exact single value matches
any_inlist[str] of glob patterns (*, ?, [...] are wildcards)any projected value matches a pattern
not_subset_oflist[str] of glob patternssome projected value matches no pattern (the allowlist shape)
inlist[str] of literalsany projected value is literally one of the entries (the literal mirror of any_in)
not_all_inlist[str] of literalsnot all projected values are literally in the entries (the allowlist shape, the literal mirror of not_subset_of)
existsboolTrue: the request carries the parameter; False: it does not
gt / gte / lt / ltefinite int or floatthe numeric comparison holds
outside_windowsTimeWindowsthe time-range parameter is not wholly inside the windows
underlist[str] of /-rooted foldersany projected location reaches one of the folders — it is the folder, sits below it, or is an ancestor whose subtree contains it (a folder blocklist)
not_underlist[str] of /-rooted foldersnot all projected locations are under some listed folder (the folder-allowlist shape)

under / not_under judge a path parameter (a file store’s path, such as Dropbox’s) by location rather than by text. Each entry is a /-rooted folder that covers itself and everything below it at a folder boundary (/Clients covers /Clients/VC, not /ClientsX); both sides are compared ignoring case where the provider does, so /clients/vc and /Clients/VC are the same Dropbox folder. under also fires on a folder above a listed one (an operation on / reaches /Clients/VC); on a request naming several paths, not_under fires when any of them leaves the listed folders, so it is not the negation of under. An entry the evaluator could never compare — one that is not /-rooted (an id: or rev: addressing form, a bare name), or that carries a backslash, a ., .. or empty segment, a trailing separator or leading or trailing whitespace — raises AlterValueError when the rule is built, naming the problem as the backend does. The same forms fail closed on the request side: a path carrying one of them is a location the rule cannot place, so the rule denies the request rather than guess which folder the provider would read; and a request that addresses by id: / rev: instead of by path is refused under either operator, because it names no location the rule can see.

any_in / not_subset_of treat *, ? and [...] as wildcards; in / not_all_in compare the same list literally — use them for literal statements, ids and channels, where a glob allowlist of literal text such as "select * from account" would silently widen. On a set-shaped parameter in fires when any member is in the list and not_all_in when not all members are, so not_all_in is not the negation of in; the literal comparison is case-insensitive with surrounding whitespace trimmed, so a provider whose identifiers differ only by case cannot be told apart by it. exists is the only operator for which an absent parameter is a judgement rather than a denial; every other operator denies a request that does not carry the parameter. Presence is judged on what the operation’s catalog projects for that operation — a declared parameter, a query-string parameter the request carries, or a body key the operation accepts — so a parameter name nothing projects never fires an exists: True deny. A stored rule (one saved through the dashboard, the CLI or the API, as opposed to a per-request rule) whose exists condition names a parameter that no selected operation declares or accepts is saved with a catalog_warnings caveat naming it, which the dashboard and the CLI show — exactly as for an operation id no catalog maps.

TimeWindows (the outside_windows operand) and TimeWindow are TypedDicts:

TypeFieldType
TimeWindowswindowslist[TimeWindow] (1–20)
TimeWindowstimezonestr (an IANA zone)
TimeWindowdayslist[str] (unique "mon" … "sun")
TimeWindowstartstr ("HH:MM")
TimeWindowendstr ("HH:MM" or "24:00"; earlier than start = overnight)

outside_windows fires when a time-range parameter (a calendar event’s event_time) is not wholly inside the windows; back-to-back occurrences count as one stretch of time. Numeric operands must be finite. any_in, not_subset_of, in, not_all_in, under and not_under take a non-empty list of strings (at most 200 entries of 512 characters each; every under / not_under entry /-rooted). String comparisons are normalized: equals, the in/not_all_in literal comparison and the any_in/not_subset_of pattern matching compare case-insensitively with surrounding whitespace trimmed (internal whitespace is significant) — deliberate anti-bypass semantics, so a condition cannot be dodged by a case or padding variant. Number-typed parameters compare numerically (a string-typed parameter compares as normalized text). On a set-shaped parameter (for example recipients), equals matches only an exact single value — a multi-member set never matches; use any_in (or in) to match a member. See content_match_rule() and operation_allowlist_rule() for authoring and validation behavior.

request_allowlist_rule() uses:

RequestAllowlistOp = Literal[
"equals", "in", "like", "gt", "gte", "lt", "lte", "exists",
"inside", "within_windows",
]
class _RequestConditionBase(TypedDict): # both keys required
op: RequestAllowlistOp
value: str | int | float | bool | list[str] | list[str | int | float | bool] | TimeWindows
class RequestAllowlistCondition(_RequestConditionBase, total=False):
name: str # a projected parameter (with operations / families)
at: str # "body:<path>", "query:<name>" or "header:<name>" (with endpoints)
optional: bool # True: the condition applies only when the request sends the field

Each condition carries exactly one of name / at, and every condition of a rule uses the same one. Each operator reads “the value must …”, and when a field carries several values every one must satisfy it. inside and within_windows apply to name conditions only. Values named by name compare case-insensitively with surrounding whitespace trimmed; values addressed by at compare exactly. A JSON number compares exactly as a number; text that spells a number (or true / false) counts as that number (or boolean) only in a form field, a query value or a header, so a JSON string never equals a number or a boolean. A raw like pattern’s * and ? never cross a ,, a ; or a line break. In a form name [*] stands for any bracketed index (body:items[*][price]). A JSON key containing ., [ or ] (or an empty key) cannot be addressed: one that aliases a step of a condition’s path is refused, it never satisfies a condition, and strict denies it anywhere in the body.


Returned by proxy_request() when an HITL grant requires approval.

FieldTypeDescription
approval_idUUIDApproval row id.
approval_group_idUUIDShared execution unit for all gates.
status"pending"Always "pending" on creation.
expires_atdatetimeWhen the approval window closes.
expires_inintSeconds until expires_at.
approval_urlstrDeep link to the approver’s wallet UI. Primary delivery — surface this in the agent’s UI.
gateslist[ApprovalGate]Every approver gate; each must approve before execution.

One approver gate in a pending N-of-N approval group.

FieldType
approval_idUUID
expires_atdatetime
expires_inint
approval_urlstr

Snapshot of an approval row.

FieldTypeDescription
approval_idUUID
statusApprovalStatusValueOne of the seven status values (see Connect & Grants).
approval_group_idUUIDShared execution unit for the gate group.
gateslist[ApprovalGateStatus]Per-gate status breakdown.
expires_atdatetime
decided_atdatetime | None
decision_reasonstr | None
executed_atdatetime | None
execution_errorstr | NoneOperator-safe execution failure when status="failed".
has_resultboolTrue when the proxied result is ready to fetch.
awaiting_uploadboolTrue when every gate approved and only the caller’s upload is missing. Nothing runs until deliver_approved_upload() sends it.
summarydict[str, Any]The held request’s approver summary in the shape of summary_version. When the read is sent a summary_version, it is the summary a decide judges, rebuilt from the held request: the operation, its parameters and (version 2 and above) the values as sent, never the held headers. Without one (the polling default) it is the stored summary: method, host, path, no values.
summary_versionintThe shape summary is served in: the version asked for, clamped to the versions that exist. Pass it back when approving through decide_approval() — it attests to the fields of that version.
required_summary_versionintThe lowest summary version an approve of this request accepts (1 for a request that carries no values, such as a bodiless read; a request whose values are shown needs a newer one). Read with a summary_version, it is what a decide requires right now; without one, what was worked out when the request was held. When it is above the version rendered, read the status again with summary_version set to it, render the fields that version adds (the values as sent, sensitive_fields, masked_values, the upload manifest), then approve at it.
request_digeststr | NoneServer-issued digest of the held request; a batch decision binds to it.
approverslist[str]Every approver of the request; any one of them may decide.
contextdict[str, str] | NoneThe caller’s bound run_id / thread_id, when the request named them.
actor_assurancestr | NoneHow the deciding person was identified: verified_by_alter or asserted_by_integration (ActorAssuranceValue).
decided_bystr | NoneThe email of the person who decided.
expiry_reasonstr | NoneWhy the request expired with no decision (ExpiryReasonValue).
result_available_untildatetime | NoneUntil when the executed result can be fetched (executed only).
updated_atdatetime | NoneWhen the request’s state last changed.

Every field in the second block defaults, so a body from an older backend still parses.

Derived property: is_terminal — True for denied, expired, executed, failed.

FieldType
approval_idUUID
statusApprovalStatusValue
expires_atdatetime
decided_atdatetime | None
ApprovalStatusValue = Literal[
"pending", "approved", "executing",
"denied", "expired", "executed", "failed",
]

Provider response captured during backend-proxy execution. The body is base64-encoded.

FieldTypeDescription
approval_idUUID | NoneNone for synchronous (non-HITL) proxy_request responses.
status_codeintHTTP status from the provider.
headersdict[str, str]Provider response headers.
body_b64strBase64-encoded response body. Validated at construction.
body_truncatedboolTrue only together with body_omitted; kept for older SDKs.
body_omittedstr | None"too_large" when the backend kept the response without its body. proxy_request() and the approval result readers raise ProviderResponseTooLargeError instead of returning such a result.
body_limit_bytesint | NoneThe buffered response limit in bytes, set with body_omitted when the response passed that limit; None when an approval’s result was too large to store.
duration_msint | NoneProvider round-trip duration when available.
credential_hintstr | NoneWhy the provider rejected the credential, when the cause is the API surface rather than the credential. Only ever set on 401/403.

credential_hint addresses a specific dead end. Some providers run several APIs that accept the same credential but expect it in different headers, so a perfectly valid key is rejected with 401 purely because the request went to the other API. The provider’s own error blames the key, and the natural response — rotating it — changes nothing. When the rejection matches that pattern, credential_hint says so.

It is None on success and on any rejection that does not match, and it never changes status_code or the body: the provider’s response is passed through unchanged and the hint accompanies it. A blank hint is normalized to None, so if result.credential_hint: is the correct test for “is there an explanation”. The SDK does not reject a hint that arrives on an unexpected status — the status rule is the backend’s to enforce, and re-checking it client-side would turn a future backend addition into a hard failure in already-installed SDKs.

Methods:

  • body_bytes() -> bytes — decode to raw bytes.
  • body_text(encoding: str = "utf-8") -> str — decode to text.
  • body_json() -> Any — decode and parse JSON.

Returned by decide_approval().

FieldTypeDescription
approval_idUUID
approval_group_idUUID
statusApprovalStatusValueThe row’s new state.
decided_atdatetime
decided_bystrThe deciding person’s email, lower-cased.
actor_assuranceActorAssuranceValue

One item of decide_approval_batch().

FieldTypeDescription
approval_idUUID
request_digeststrThe 64-hex digest the approval was read with (ApprovalStatus.request_digest, ApprovalListItem.request_digest, or the webhook payload’s request_digest).

Returned by decide_approval_batch().

FieldTypeDescription
decidedlist[UUID]Every approval the call flipped (all of them, or the call raised).
decision"approved" | "denied"
decided_atdatetime
decided_bystr
actor_assuranceActorAssuranceValue

One row of list_approvals().

FieldTypeDescription
approval_id, approval_group_idUUID
statusApprovalStatusValueThis gate’s own stored status (the status filter matches it). A request two require_approval rules hold is one group of two gates; once it executes through one, the other keeps approved. A gate past its expiry stays pending here until Alter records the expiry.
group_statusApprovalStatusValue | NoneThe request’s outcome across every gate of its group (what get_approval_status reports), with expiry applied: a single gate past its expiry reads status pending and group_status expired. Read it to tell whether the request is still in flight. None from a backend that predates the field.
created_at, updated_at, expires_atdatetime
decided_at, executed_atdatetime | None
decision_reasonstr | None
has_resultbool
result_available_untildatetime | None
request_digeststr
approverslist[str]Every approver’s email, lower-cased; any one may decide. Returned to any key that may read the approval, an agent-bound key included.
contextdict[str, str] | None
actor_assurance, decided_by, expiry_reasonstr | None
summarydict[str, Any]The STORED summary (method, host, path), in the shape of summary_version. A list item never carries the operation’s parameters or the values as sent: read the request with get_approval_status(approval_id, summary_version=item.required_summary_version) and render that before approving.
summary_versionintThe shape summary is served in (the version asked for, clamped).
required_summary_versionintThe lowest version an approve of this request accepts, worked out from the full summary when the request was held.
managed_operationManagedOperationIdentity | None
execution_errorstr | None

Derived property: is_terminal — whether the request has settled: group_status is terminal (denied, expired, executed, failed), or, from a backend that does not send it, status is.

FieldTypeDescription
itemslist[ApprovalListItem]
limitint
next_cursorstr | NonePass back as cursor for the next page; None on the last page.
ActorAssuranceValue = Literal["verified_by_alter", "asserted_by_integration"]

verified_by_alter: the Wallet session or an actor_token the backend validated against the application’s identity provider — the integration presented a valid, unexpired ID token for that person; it does not prove the person consented to this specific decision. asserted_by_integration: an actor_email the integration vouched for, checked against the request’s approvers.

ExpiryReasonValue = Literal[
"window_elapsed", "grant_revoked", "grant_expired",
"agent_revoked", "secret_deleted", "sibling_gate",
"connection_lost",
]

Why a request ended expired with no decision: the approval window lapsed; the grant it waited on was revoked or its TTL lapsed; the requesting agent was revoked; the managed-secret provider was deleted; another gate of the same group sealed it; or the provider connection it was held under lost its authorization and needs reconnecting (connection_lost). The field is typed as a string, so a reason a newer backend adds still parses.

Returned by verify_webhook().

FieldTypeDescription
idstrThe delivery’s message id (webhook-id).
typestrOne of WebhookEventType: approval.requested, approval.decided, approval.expired, approval.executed, approval.failed or webhook.test (the event Send test / alter webhooks test delivers — not a type an endpoint subscribes to). Typed as str so an event a newer backend adds still parses.
occurred_atdatetimeWhen the state change happened.
sequenceintIncreases per subject; drop an event older than one already applied.
api_versionstrThe payload schema version.
datadict[str, Any]The raw event body — see Outbound webhooks.
typed_datatyped data | Nonedata as the model of type; None for a type this SDK does not know. Raises BackendError when the verified body does not fit the model.
WebhookEventType = Literal[
"approval.requested", "approval.decided", "approval.expired",
"approval.executed", "approval.failed", "webhook.test",
]
WEBHOOK_EVENT_TYPE_LIST: tuple[WebhookEventType, ...] # the six, in lifecycle order
WEBHOOK_EVENT_TYPES: frozenset[str] # the same six as a set

WebhookEvent.typed_data returns one of these (frozen models; a field a newer backend adds is kept in data and ignored here). Every approval.* model carries ApprovalEventData’s fields. Each field is read strictly, and exactly as the TypeScript SDK reads it: a UUID must be the canonical hyphenated form, an instant an RFC 3339 string with a time and a zone (never a Unix number, a numeric string or a zone-less time), summary_version and required_summary_version positive integers, approvers a list and summary an object (never null); a body that does not fit raises BackendError and data keeps the raw body.

FieldTypeDescription
approval_id, approval_group_idUUID
statusApprovalStatusValueThe row’s state when the event was staged.
approverslist[str]Every approver’s email, lower-cased and sorted; any one may decide.
expires_atdatetime | None
request_digeststrWhat a batch decision binds to.
summary_versionintThe shape summary is in: the version the payload’s summary was rendered at.
required_summary_versionintThe lowest version an approve of this request accepts, as the status read and the list report it. The payload never carries the request’s values, even when the two versions are equal, so never decide at the payload’s summary_version: read the status at required_summary_version, render that summary, then decide at it.
approvablebool | NoneWhether any summary version can approve the request. False for a request no version can show (its values unavailable): only a deny is accepted, and required_summary_version names the newest version as a placeholder. None from a backend that predates the field.
summarydict[str, Any]The thin approver summary (never the held request).
contextdict[str, str] | NoneThe caller’s bound run_id / thread_id.
ModelEventAdds
ApprovalRequestedDataapproval.requested—
ApprovalDecidedDataapproval.decideddecision: ApprovalDecisionValue, decided_by: str | None, actor_assurance: ActorAssuranceValue | None, reason: str | None. decided_by and actor_assurance are None when Alter denied this gate because another gate of the same request was denied (reason says so), or for a decision recorded before this release.
ApprovalExpiredDataapproval.expiredexpiry_reason: str (an ExpiryReasonValue), reason: str | None
ApprovalExecutedDataapproval.executeddecided_by: str | None, actor_assurance: ActorAssuranceValue | None (None for a decision recorded before this release), executed_at: datetime, result_available_until: datetime
ApprovalFailedDataapproval.faileddecided_by: str | None, actor_assurance: ActorAssuranceValue | None (None for a decision recorded before this release), execution_error: str | None
WebhookTestDatawebhook.testendpoint_id: UUID, app_id: UUID, message: str (no ApprovalEventData fields)

WebhookTypedData is the union of the six. MAX_WEBHOOK_JSON_NESTING (64) is the deepest a delivery’s JSON may nest before verify_webhook() rejects it.


Audit row built for a provider call.

FieldType
grant_idUUID
token_generationUUID | None
provider_idstr
methodstr
urlstr
request_headersdict[str, str] | None
request_bodyAny | None
response_statusint
response_headersdict[str, str] | None
response_bodyAny | None
latency_msint
timestampdatetime
reasonstr | None
contextdict[str, str] | None

Method sanitize() -> dict[str, Any] strips sensitive headers (Authorization, Cookie, x-api-key, x-amz-*, etc.).


FieldTypeDescription
trace_idstrRequired trace identifier.
namestrRequired span name.
start_timedatetimeRequired start time.
span_idstr | NoneStable id for idempotent retries.
parent_span_idstr | NoneParent span id.
end_timedatetime | NoneEnd time.
attributesdict[str, str]Caller-defined string attributes.
FieldTypeDescription
acceptedintNumber of newly stored spans; idempotent duplicates are not recounted.

See spans.emit() for batch limits.


Returned by App.resolve_identity() and Agent.resolve_identity(). The canonical identity set the platform resolved for the request — key external data (memory partitions, channel sessions, authorization tuples) on these IDs, never on email or a raw IDP sub.

FieldTypeDescription
app_idstrThe calling application (tenant).
app_user_idstr | NoneCanonical end-user key. None for headless calls.
external_subject_idstr | NoneStable external join key — the IDP subject identifier.
idp_idstr | NoneIdentity provider the subject belongs to.
user_statusstr | None"active" | "suspended". Deprovisioned users are rejected at resolution, never returned.
group_idslist[str]Stable external group IDs of the user’s unrevoked memberships.
agent_idstr | NoneCanonical agent key. None for plain app callers.
actor_idstr | NoneAudit correlation label only — NOT a partition key.
traceIdentityTrace | NoneEcho of the ambient run/thread trace context.
emailstr | NoneOnly with include_profile=True.
display_namestr | NoneOnly with include_profile=True.

Method memory_scope(*, agent_only: bool = False) -> MemoryScope derives the private partition for an identity that carries local provenance (an authenticated SDK response or a verified assertion). It raises AlterValueError when agent_only is not a bool and MemoryIsolationError (memory_identity_unverified, memory_identity_expired, memory_agent_required, memory_user_required, memory_user_not_active or memory_user_cannot_be_dropped) for an unverified or ineligible context. See Private memory and Propagate identity into memory layers.

FieldType
run_idstr | None
thread_idstr | None

Derived only from an authenticated SDK identity response or verified assertion. memory_scope(agent_only=False) requires an active user and authenticated agent; explicit agent_only=True requires a headless agent. Untrusted or ineligible contexts raise MemoryIsolationError.

FieldTypeDescription
namespacetuple[str, ...]Versioned private application + agent + user partition; explicit headless partitions use a distinct kind. Identifiers are UTF-8 base64url encoded.
partition_keystrNamespace joined by /, with a trailing /.
user_keystr | Nonealter:user:<app_user_id>; None for a headless (agent-only) scope. Correlation metadata, not a partition.
agent_keystralter:agent:<agent_id>; always set, because a scope requires an authenticated agent. Correlation metadata, not a partition.
app_keystralter:app:<app_id>; always set. Correlation metadata, not a partition.

namespace_for(path: Sequence[str] = ()) -> tuple[str, ...] appends encoded developer subdivisions and raises AlterValueError for a path that is not a non-string sequence of non-empty, valid-Unicode strings, has more than 16 segments, or has a segment longer than 255 UTF-8 bytes. Serialized scope metadata is not authorization. Use ScopedMemoryStore for live enforcement, or verify_identity_assertion with an assertion-backed store for bounded offline access. See the complete integration and migration guide.

Returned by App.assert_identity() and Agent.assert_identity().

FieldTypeDescription
tokenstrCompact ES256 JWS — verify against the published Alter identity JWKS. Redacted from repr().
expires_atdatetimeAbsolute expiry (short TTL by design — default 120s, bounds 10–300s).
identityIdentityContextThe identity the assertion encodes.

The assertion is identity-only: it carries no provider tokens, no credentials, no raw IDP claims, and grants nothing by itself — downstream systems map it to their own authorization.

Version compatibility: ScopedMemoryStore, NamespaceStore, MemoryItem, verify_identity_assertion and MemoryIsolationError.code require alter-sdk>=0.28.0. Version 0.27.0 and earlier do not export them.

Run these in the trusted application; keep the raw store and its credentials out of agent tools. Every method raises AlterValueError for a malformed argument and MemoryIsolationError (branch on code; see Errors) for an authorization outcome.

ScopedMemoryStore(
store: NamespaceStore,
identity: IdentityContext,
*,
refresh_identity: Callable[[], Awaitable[IdentityContext]] | None = None,
agent_only: bool = False,
)

Binds every exposed store operation to one verified private identity. identity must carry local provenance (an authenticated response or a verified assertion). With refresh_identity, the resolver is awaited at the start of every operation and must call Alter each time: the store proves the returned identity was minted after the operation started (memory_refresh_not_live otherwise) and that it still resolves to the same partition (memory_identity_changed otherwise). Without a resolver, identity must be assertion-backed and unexpired (memory_live_refresh_required for a resolved snapshot). The constructor raises AlterValueError when refresh_identity is not callable or agent_only is not a bool, plus the memory_scope() outcomes above.

MemberSignatureNotes
scopeproperty -> MemoryScopePartition metadata, never an authorization capability.
getasync get(path: Sequence[str], key: str) -> MemoryItem | NoneThe result must come back inside the exact namespace with the same key, else memory_store_scope_violation.
putasync put(path: Sequence[str], key: str, value: dict[str, Any]) -> Nonevalue must be a dict.
deleteasync delete(path: Sequence[str], key: str) -> None
searchasync search(path: Sequence[str] = (), *, query: str | None = None, filter: dict[str, Any] | None = None, limit: int = 10, offset: int = 0) -> list[MemoryItem]Every result must sit under the requested namespace.
list_namespacesasync list_namespaces(path: Sequence[str] = (), *, limit: int = 100, offset: int = 0) -> list[tuple[str, ...]]Every result must sit under the requested namespace.

path is a developer-owned subdivision appended under the verified partition (at most 16 segments of at most 255 UTF-8 bytes each). key is a non-empty string of at most 512 characters. limit must be a positive int and offset a non-negative int. A resolver error propagates unchanged; there is no offline fallback.

The async namespace-store Protocol a wrapped store must satisfy, structurally implemented by LangGraph’s BaseStore (InMemoryStore included): aget(namespace, key), aput(namespace, key, value), adelete(namespace, key), asearch(namespace_prefix, *, query=None, filter=None, limit=10, offset=0) and alist_namespaces(*, prefix, limit=100, offset=0), with namespaces as tuple[str, ...]. It deliberately exposes no raw batch operation.

The Protocol a store item satisfies: namespace: tuple[str, ...], key: str and value: dict[str, Any] (a LangGraph Item qualifies).

verify_identity_assertion(
token: str,
*,
issuer: str,
audience: str,
jwks: dict[str, Any],
expected_app_id: str,
expected_agent_id: str | None = None,
) -> IdentityContext

Synchronous. Requires the identity extra (pip install 'alter-sdk[identity]'); without it the call raises ImportError naming the extra. Verifies an Alter ES256 assertion against configured trust anchors only (jwks is the JWK Set document fetched from the configured issuer; token-supplied URLs are never fetched). Pins ES256 and typ, selects the key by kid (a key set member carrying the private d parameter is rejected), checks issuer, audience, signature and the required claims, keeps exp strict with a 5-second leeway on iat only, enforces the 300-second lifetime ceiling, binds the application (and the agent when expected_agent_id is given), and requires agent_auth to be present whenever an actor is asserted without pinning its value. Returns a trusted IdentityContext (application, current agent, represented user, active-at-issuance status) that memory_scope() and ScopedMemoryStore accept until the signed expiry. Raises AlterValueError for a missing or malformed argument and MemoryIsolationError with code == "memory_assertion_invalid" and a coarse details["reason"] (malformed, header, key, signature, lifetime, claims or binding) for a rejected token.

TypeContract
IntegrationCallpending holds a pending approval; result holds an immediate result. wait() returns the completed IntegrationResult.
IntegrationResultresponse retains the underlying ApprovalResult; status_code is the HTTP status; ok is false for HTTP errors, truncation, schema mismatches or provider faults. body_json() validates and decodes typed JSON; binary/text accessors retain non-JSON responses.
Discovery dictionariesintegrations.list() returns provider, versions and operation count in each dictionary.
Contract dictionaryintegrations.contract() returns versioned operation input/output schemas and shared definitions.
ManagedOperationErrorBackend managed-operation rejection. code is the stable machine-readable reason (such as unknown_contract_version); status_code is the HTTP status.

ApprovalResult.provider_fault is the SDK form of wire field provider_fault. A provider may report an application fault in an HTTP 2xx response; this flag makes IntegrationResult.ok false and typed JSON decoding reject it. Inspect the retained response for diagnosis. Do not automatically retry writes after a fault or uncertain outcome.

Report an issue with this page

Necessary

Required for sign-in, security, authorization, and remembering your choices.

Always active

Analytics

Helps us understand how our website, product, and documentation are used.

Performance diagnostics

Uses performance tracing and privacy-masked session replay to diagnose problems.

Advertising

Shares visits and sign-ups with Meta, Reddit, and X so we can measure which of our ads work.

You can change these choices at any time from Cookie settings.