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,
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.


OAuth token response. The plaintext access token is NOT stored as a readable attribute — the SDK 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 the provider serves each account from its own host: a Salesforce org’s instance URL, or https://quickbooks.api.intuit.com / https://sandbox-quickbooks.api.intuit.com for a QuickBooks production or sandbox company. Build full request URLs from it. None when the provider has one fixed API host, or 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
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 the provider serves each account from its own host: a Salesforce org’s instance URL, or https://quickbooks.api.intuit.com / https://sandbox-quickbooks.api.intuit.com for a QuickBooks production or sandbox company. Build full request URLs from it. None when the provider has one fixed API host, or 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.

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
FieldType
successbool
messagestr
grant_idstr
revoked_atstr
FieldType
grant_idstr
principal_type"user" | "group" | "system" | "agent"
labelstr | None
created_atstr

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.
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]
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.

Same shape as ConnectSession minus scope_constraint_warnings, plus delegable_requested. __repr__ redacts connect_url (it carries the session token in the URL fragment).

FieldType
session_tokenstr
connect_urlstr
expires_inint
expires_atstr
delegable_requestedbool

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 (Returns). 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.
provenancestrIngestion source.
source_urlstr | NoneUpstream spec URL when known.
content_hashstrHash of the ingested content.
operation_countintNumber of operations in the spec.
fetched_atdatetimeMost recent ingestion time.
changed_atdatetimeTime the active content version last changed.
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]
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() uses 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",
"gt", "gte", "lt", "lte", "outside_windows",
]

ContentParamCondition is a TypedDict:

FieldType
namestr
opContentParamOp
valuestr | int | float | list[str] | TimeWindows

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 and not_subset_of take a non-empty list of pattern strings. String comparisons are normalized: equals 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 to match a member. See content_match_rule() for authoring and validation behavior.


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.

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_truncatedbool
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.

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 are unreleased: they ship in the next alter-sdk release after 0.27.0, which does 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.

Report an issue with this page

Necessary

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

Always active

Analytics

Helps us understand which product and documentation features are useful.

Performance diagnostics

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

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