Skip to content

Reference

Calling APIs

Credential-injected provider calls, scope discovery, and trace-span submission.

Provider calls execute through Alter. Credentials stay in the backend, where policy and approval requirements are enforced.

A provider 4xx or 5xx comes back as a result, not an exception. Check statusCode before reading the body.

async proxyRequest(args: {
method: HttpMethod | string;
url: string;
grantId?: string;
provider?: string;
account?: string;
label?: string;
json?: unknown;
body?: Uint8Array | string;
extraHeaders?: Record<string, string>;
queryParams?: Record<string, unknown>;
pathParams?: Record<string, string>;
reason?: string;
context?: Record<string, string>;
caller?: string;
userToken?: string;
appUserId?: string;
}): Promise<PendingApproval | ApprovalResult>

Send the full request to the Alter backend, which retrieves the credential, calls the provider, and returns the response. The token never reaches the SDK process.

Available on both App and Agent.

proxyRequest() takes a single options object — there are no positional method / url arguments.

const result = await app.proxyRequest({
method: "POST",
url: "https://api.example.com/transfer",
grantId,
json: { amount: 1000, currency: "usd" },
reason: "Quarterly payout",
});
  • HITL grants. Grants with requires_approval configured can only be exercised through proxyRequest() — request() rejects them with hitl_grant_requires_proxy.
  • Grants with user-set usage limits. Once the grant’s user has set any usage limit on it (a quota, a time window or an operation rule, for example from the Connect page or the wallet), the grant is proxy-only, on an OAuth and a managed-secret grant alike: request() rejects it with user_limits_require_proxy, because only a call the backend makes itself can enforce the limit.
  • Delegated and restricted grants. An agent’s delegation (or a scope-narrowed grant) and a grant carrying method/endpoint restrictions are proxy-only too — request() rejects them with delegated_grant_requires_proxy and restricted_grant_requires_proxy.
  • Server-side credential isolation. The token never crosses the SDK boundary. The backend is the only system that observes the plaintext.
  • Wire-level audit. The backend records the full request/response on the audit row, including bytes and headers.
  • Tight policy enforcement. The backend re-evaluates policy at execution time.

For everything else, request() avoids the extra hop.

  • The provider response body is buffered by the backend and base64-encoded, up to 5 MiB. A larger response is never returned cut: proxyRequest() throws ProviderResponseTooLargeError, which carries the provider’s statusCode and headers. The provider did answer, so a write may have happened; do not resend a non-idempotent call to recover. Use proxyStreamRequest() for downloads, large responses and Server-Sent Events. WebSockets are not supported on the proxy.
  • Auth and cookie-related provider response headers are stripped before the SDK receives the response. Flows that depend on Set-Cookie, WWW-Authenticate, or returned authorization headers may need request() or the provider client directly.
  • Managed-secret proxy calls require destination hosts to be configured on the provider. If the allowlist is missing or does not match the requested host, the call is blocked before the credential is injected.
  • Fields Alter fills with the credential belong to Alter. Every header and query parameter the grant’s credential is injected into (the primary header, and each additional injection rule’s header or query parameter, including a rule with no value for this credential) is removed from the request before the credential is added, so it carries Alter’s value or nothing. This applies to every proxied call; on a call that requires approval, setting one of these fields is refused up front with credential_slot_in_request instead. Header names must be HTTP tokens (no spaces or separators); any other name is rejected.
  • body on proxyRequest() is Uint8Array or string; pass an ArrayBuffer as new Uint8Array(buffer).
  • A binary body is sent as given, up to 5 MiB. It is refused with proxy_body_uninspectable when a policy rule needs to read the body (on GraphQL, any operation, family or parameter rule does, unless the provider’s multipart GraphQL body is registered for inspection) and when the call requires approval, because an approver could not see it. A binary GraphQL body carrying a credential operation or credential-bearing selection is refused with credential_minting_refused. On a GraphQL endpoint that can return a credential, a binary body is forwarded without rules only when it is UTF-8 application/json or application/graphql (uncompressed); any other binary body is refused with credential_minting_refused, except a multipart body the provider registers for inspection, which is judged on the GraphQL document in its parts. An upload to a GraphQL endpoint is refused with proxy_body_uninspectable. Two binary bodies are read by policy from the exact bytes sent (an AI review rule still refuses them): a UTF-8 form body declared application/x-www-form-urlencoded on an operation whose provider documents a form-encoded body, and a UTF-8 text body an operation documents as one of its forms; see Fail-closed. An operation allowlist denies a request whose operation it cannot name with operation_unclassified (403), whatever its body. Otherwise the call runs. Payload capture never includes a binary request or that call’s response.
  • proxyRequest() does not automatically retry the initial call. Add application-level retry/backoff for network failures and timeouts. For HITL grants, retry carefully because submitting the same call again can create another pending approval.
FieldTypeDescription
methodHttpMethod | stringHTTP method. Case-insensitive.
urlstringProvider URL. Must be a non-empty string. Supports {name} placeholders resolved via pathParams.
grantIdstringDirect-mode grant ID. Exactly one of grantId or provider must be supplied — proxyRequest() shares the same resolution contract as request(): one match resolves, zero is a not-found error, several throw AmbiguousGrantError.
providerstringIdentity-mode OAuth provider ID, or a managed-secret provider’s slug. Resolves the user via userToken (or the client’s userTokenGetter); for an agent caller, disambiguate delegations with appUserId. Mutually exclusive with grantId.
accountstringAccount disambiguator for provider resolution.
labelstringSibling-grant disambiguator for provider resolution (the resolution key is provider + label). Only valid alongside provider.
bodyUint8Array | stringRaw bytes or UTF-8 text, up to 5 MiB. Mutually exclusive with json. Set Content-Type for the provider; defaults to application/octet-stream.
jsonunknownJSON-serializable body (same argument name as request()). Accepts plain objects, arrays, strings, finite numbers, booleans, and null; explicit null is forwarded as the body, while undefined omits it. Class instances, Date, Map, and Set are rejected at the SDK boundary.
extraHeadersRecord<string, string>Additional non-auth headers (same argument name as request()). Authorization-bearing headers and Host are rejected — the backend injects credentials and pins the connection authority at execution time.
queryParamsRecord<string, unknown>Query-string parameters. The URL as Alter sends it must be at most 65,536 characters once percent-encoded: these parameters merged in (repeated array values and multi-byte characters count in full), plus any query-parameter credential Alter adds. A longer one is refused with query_too_long (65,536 is the most Alter’s HTTP client will send). The provider may apply a lower limit of its own.
pathParamsRecord<string, string>Substitutions for {name} placeholders in url. Each value is URL-encoded.
reasonstringFree-form reason. Stored on the audit row and shown to the approver when HITL is configured.
contextRecord<string, string>Application metadata attached to the audit row (e.g. runId, toolName), with the same size limits as request().
callerstringPer-call caller override for audit attribution.
userTokenstringPer-call user JWT for identity mode. Overrides userTokenGetter. Valid in both addressing modes.
appUserIdstringPer-call AppUser UUID for agent-delegation disambiguation. Only valid with provider resolution.

proxyRequest() takes the same arguments as request(), by the same names. The differences come from the execution model: pass JSON as json or raw bytes/UTF-8 text as body (mutually exclusive), auth headers are rejected, header names must be HTTP tokens and each header is named once (a name repeated in another spelling, Dropbox-API-Arg with dropbox-api-arg, is refused with a 422 duplicate_header_spelling — header names are case-insensitive, so the provider would read the two lines as one header while a policy rule could judge only one), the URL as Alter sends it is limited to 65,536 encoded characters (query_too_long; request() applies the same limit to url with its queryParams and throws AlterValueError before sending), and the return type is an ApprovalResult / PendingApproval.

The return type is a discriminated union. Use instanceof or the status field to branch.

  • ApprovalResult — the call ran synchronously and the provider response is on this object. Typical when the grant has no HITL requirement, or when the approval was pre-granted.
  • PendingApproval — the backend created an approval row and is waiting for an approver. The call has NOT executed yet. Pass approvalId to awaitApproval() or poll with getApprovalStatus().
import { PendingApproval } from "@alter-ai/alter-sdk";
const result = await app.proxyRequest({
method: "POST",
url: "https://api.example.com/transfer",
grantId,
json: { amount: 1000 },
reason: "Quarterly payout",
});
if (result instanceof PendingApproval) {
// Surface result.approvalUrl to the approver, then poll.
const final = await app.awaitApproval(result.approvalId, {
timeoutMs: 5 * 60_000,
});
console.log(final.statusCode, final.bodyText());
} else {
// Synchronous response.
console.log(result.statusCode, result.bodyJson());
}

The status field is "pending" on PendingApproval. ApprovalResult has no status field.

  • ProxyTransferError — a binary body or stream was refused.
  • AlterValueError — neither grantId nor provider was supplied (or both were), an identifier value is an empty string, account/label/appUserId was supplied without provider, an unresolved {name} placeholder was left in url after pathParams, url is missing, json has an unsupported shape, or an authorization-bearing header was supplied.
  • AlterSDKError — the SDK has been closed.
  • ApprovalDeniedError — backend rejected the call (policy denial that does not require human review).
  • ApprovalExpiredError — the approval window elapsed before a decision was recorded, or the managed-secret provider the request waited on was deleted (decisionReason names it).
  • ApprovalExecutionFailedError — backend failed to execute the proxied call after the approval was granted.
  • BackendError — other backend failure.
  • NetworkError, TimeoutError — transport failures to the Alter backend.

ApprovalResult carries the provider response body as base64. Three helpers decode on demand:

result.bodyBytes(); // Uint8Array
result.bodyText(); // string (utf-8 default)
result.bodyJson(); // parsed JSON

A response over the buffered limit throws ProviderResponseTooLargeError instead of returning; result.bodyTruncated stays false on any result you receive.


Some managed-secret templates require multiple headers, query parameters, or request signing. request() applies the credential template’s configured injection rules automatically; application code still supplies only the provider URL, request data, and grant selector. Secret signing material is never exposed as a return value.

let response = await app.proxyRequest({ method: HttpMethod.GET, url: "https://api.example.com/v1/resources", grantId });
if ("status" in response) {
for (const gate of response.gates) {
console.log("Approval required:", gate.approvalUrl);
}
response = await app.awaitApproval(response.approvalId);
}

Use proxyRequest() when signing material must remain in the Alter backend or the grant is proxy-only.


The scopes namespace exposes the active scope catalog — the set of resource verbs and reserved actions the backend recognizes. Use it to render scope pickers, validate keys.derive({ scopes }) inputs, or sanity-check that a planned attenuation matches the deployment.

Available on both App and Agent.

async list(): Promise<ScopeCatalog>

No scope is required to read the catalog (it is static metadata), but the call still authenticates with the API key, passes through env / CIDR / rate-limit gates, and is rate-limited per key.

Returns ScopeCatalog.

FieldTypeDescription
scopeVersionnumberServer-advertised catalog version. Changes only on backend release.
resourcesRecord<string, ResourceScopes>Per-resource verb sets.
actionVerbsreadonly string[]Reserved action verbs (e.g. derive, admin).
deprecatedreadonly string[]Scopes still accepted but flagged for removal in a future release.

The catalog is not cached by the SDK — call list() on demand. The shape is small and the call is light.

import { App } from "@alter-ai/alter-sdk";
const app = new App({ apiKey });
try {
const catalog = await app.scopes.list();
console.log(`Scope version: ${catalog.scopeVersion}`);
for (const [resource, { verbs }] of Object.entries(catalog.resources)) {
console.log(`${resource}: ${verbs.join(", ")}`);
}
const validScopes = new Set(
Object.entries(catalog.resources).flatMap(([resource, { verbs }]) =>
verbs.map((verb) => `${resource}:${verb}`),
),
);
const requested = ["proxy:execute", "grants:read"];
const unknown = requested.filter((scope) => !validScopes.has(scope));
if (unknown.length > 0) {
throw new Error(`Unknown scopes: ${unknown.join(", ")}`);
}
} finally {
await app.close();
}

Throws BackendError, AlterValueError (on a wire-shape regression), NetworkError, TimeoutError.

Submit application-defined spans that surround credential operations in the trace view. Available on both App and Agent.

async emit(spans: readonly UserSpan[]): Promise<EmitSpansResult>

Each batch must contain 1–50 spans. traceId, name, and startTime are required; spanId, parentSpanId, endTime, and string-valued attributes are optional. A caller-supplied spanId makes retries idempotent. The returned accepted count includes only newly stored spans.

const result = await app.spans.emit([
{
traceId,
spanId,
name: "process-resource",
startTime,
endTime: new Date(),
attributes: { outcome: "success" },
},
]);
console.log(result.accepted);

Requires the spans:emit key scope. Throws AlterValueError for malformed batches, InsufficientScopeError when the key lacks the scope, and BackendError for backend or response-shape failures.

When the application runs an OpenTelemetry SDK with an active span, every call the SDK makes to Alter automatically carries the standard W3C traceparent header — request(), proxyRequest(), approval polling, and the audit-reporting calls included. Alter uses it as the trace context for that request’s audit events, and any spans the organization streams to its own OTLP collector join the application’s traces instead of starting disconnected ones.

No configuration is required: @opentelemetry/api is an optional peer dependency that the SDK never installs or requires. When the application has it — including under pnpm’s isolated mode and Yarn PnP — the SDK uses it; without it (or without an active span) the header is simply omitted and nothing changes. The integration is best-effort by design: it can never fail a vault call (the very first call pays a one-time, in-process lookup of the optional module).

import { trace } from "@opentelemetry/api";
const tracer = trace.getTracer("the-application");
// `app` from the quick start.
await tracer.startActiveSpan("handle-user-request", async (span) => {
try {
// This call's audit events share the surrounding trace's ids.
let response = await app.proxyRequest({ method: HttpMethod.GET, url: url, grantId });
if ("status" in response) {
for (const gate of response.gates) {
console.log("Approval required:", gate.approvalUrl);
}
response = await app.awaitApproval(response.approvalId);
}
console.log(response.statusCode);
} finally {
span.end();
}
});

Only trace/span identifiers and a sampling flag travel in the header — no payloads, no user identifiers.

Sends a large body to the provider with size and SHA-256 verification. Takes path (a file) or data (a Uint8Array), plus the addressing, header and audit options of proxyRequest(). There is no json or body.

import { PendingApproval } from "@alter-ai/alter-sdk";
let result = await app.proxyUploadRequest({
method: "PUT",
url: "https://uploads.example.com/files/report.pdf",
grantId,
path: "report.pdf",
});
if (result instanceof PendingApproval) {
result = await app.deliverApprovedUpload(result.approvalId, {
path: "report.pdf",
timeoutMs: 3_600_000,
});
}
console.log(result.statusCode);

Returns: ApprovalResult, the provider’s response, or PendingApproval when the call needs approval.

The SDK declares the body’s size and SHA-256 first. Normally policies run on that declaration before bytes reach Alter. For multipart uploads to catalog-declared GraphQL endpoints, Alter first enforces body-independent restrictions (including IP, time, quotas and deny-all rules), then receives and verifies the body in separate bounded encrypted temporary storage, inspects its GraphQL metadata, and evaluates operation/content policies and creates any approval. No bytes reach the provider before those checks pass. If approval is required, deliver the same bytes again after approval; the initial temporary copy is removed. Limits: 50,000,000 bytes per upload, including an upload that needs approval.

  • The provider receives a fixed Content-Length, never chunked framing, and the original bytes, with application/octet-stream by default.
  • Sent once. A failure means calling this again, because a one-shot body is never retried, not even by Alter on a provider’s 421.
  • File contents remain opaque. Registered multipart GraphQL metadata is inspected; other upload bodies are not. A rule that depends on the body refuses the upload with proxy_body_uninspectable, as it does for a binary proxyRequest(), and payload capture never includes it. A rule that needs only the operation (an operation allowlist, or an operation match) judges an upload to an operation that takes nothing from its body. A multipart attachment upload is judged by its route only when Alter builds the multipart body (integrations.executeUpload or a provider package); any other multipart body built by the caller and sent with proxyUploadRequest() (one that is not a registered GraphQL multipart upload) is refused with proxy_body_uninspectable under any rule that names an operation. The audit record carries the bytes the provider received.
  • Verified at the end. The last 64 KiB are held until the whole body has matched. Bytes that differ from the declaration end the request short of its Content-Length, so the provider cannot read it as a finished body. A provider that acts on a partial request can still see the earlier bytes. Registered GraphQL multipart uploads and calls that need approval do not carry this risk: their bytes are verified in full first.

An upload that stalls for 60 seconds, averages under 10 kB/s, or runs past 15 minutes ends with proxy_upload_timeout. Alter gives a provider up to five minutes to answer once it has the body, but a network edge between the caller and Alter can time out sooner.

Hop-by-hop headers such as Transfer-Encoding and Connection are dropped, as on every proxy call, because Alter sets the framing itself.

Waits for an upload’s approval, sends the approved bytes, and returns the provider’s response.

const result = await app.deliverApprovedUpload(approvalId, {
path: "report.pdf",
timeoutMs: 3_600_000,
pollIntervalMs: 2_000,
});

The approver sees the upload’s size and SHA-256 and that file contents are opaque. For registered GraphQL multipart uploads, the summary also includes the inspected GraphQL metadata, with sensitive inputs masked. Only the API key and agent that requested the approval can deliver it, and delivery must start within one hour of the last approval, after which the approval expires. Alter verifies every byte before contacting the provider. Bytes that do not match are refused with proxy_upload_hash_mismatch and leave the approval open for a correct delivery.

A delivery that sent nothing, because the provider was briefly out of capacity, is refused with proxy_upload_capacity and the approval stays open: deliver again. Once the provider may have received anything, a failure ends the approval failed and the upload needs a new approval. A repeat call after a delivery finished returns its result, so a lost response is not a failure. timeoutMs covers the wait for the decision and then the wait for the result.

Throws: ApprovalDeniedError, ApprovalExpiredError, ApprovalExecutionFailedError, ApprovalTimeoutError, or ProxyTransferError.

Uses the same options as proxyRequest(), including body: Uint8Array | string.

const response = await app.proxyStreamRequest({
method: "GET", url: "https://api.example.com/export", grantId,
});
try {
if (response.statusCode >= 400) {
// Provider errors are response data, not exceptions.
throw new Error(`Provider answered ${response.statusCode}`);
}
for await (const chunk of response.iterBytes()) {
await output.write(chunk);
}
} finally {
await response.close();
}

Returns: ProxyStreamResponse.

output is your asynchronous byte sink. for await closes on an early break.

The request body remains bounded at 5 MiB: use either JSON or raw bytes/UTF-8 text, never both. For a larger body, use proxyUploadRequest(). The provider receives the original bytes, with application/octet-stream by default. Binary input is refused with proxy_body_uninspectable when a policy rule needs to read the body (on GraphQL, any operation, family or parameter rule does, unless the provider’s multipart GraphQL body is registered for inspection) and when the call requires approval, because an approver could not see the body. A binary GraphQL body carrying a credential operation or credential-bearing selection is refused with credential_minting_refused. A UTF-8 form or text body on an operation that documents one is the exception: policy reads it from the bytes sent (see Fail-closed). Otherwise the call runs. Payload capture never includes a binary request or that call’s response. A configured AI-review rule also refuses binary input when review is temporarily skipped for entitlement, consent, or availability reasons. This is intentional: changing the body encoding cannot bypass a configured inspection requirement. Use inspectable JSON with that policy.

Streaming responses forward downloads and SSE bytes without base64 or a response size cap. Consume chunks incrementally; collecting them into a list recreates the memory cost in your application. Provider HTTP errors remain response data. Credential-bearing response headers, including cookies and authentication headers, are stripped. Other headers are available on the response object’s headers. Transport failure after headers interrupts iteration; a partially received result is not complete and is never automatically retried.

A provider that sends no headers within the idle deadline rejects with BackendError and provider_timeout (502). Client-side, iterBytes() also stops with TimeoutError when a read exceeds the client’s own timeout, which can be shorter than the server’s idle deadline. A stream with a binary body that requires approval is 409 proxy_stream_approval_required.

Defaults are 30 seconds idle and 120 seconds total, with enforced stream admission separate from ordinary calls. ProxyTransferError.code identifies proxy_stream_capacity (503), proxy_stream_timeout (504), proxy_body_uninspectable (422), or proxy_stream_approval_required (409). Approval-gated streaming calls are refused before creating an approval or contacting the provider; use the bounded proxy method for approval-gated requests.

Each admitted provider call consumes policy quota once, as the bounded proxy does. A call counts as one billable request once the provider’s response headers arrive, including provider errors and a caller who disconnects mid-transfer. A connection that never got an answer, and a refusal, are not billed. Streamed payloads are never captured. Terminal audit rows record bytes received and provider-call duration.

The total deadline applies even while bytes are arriving. This method does not support WebSocket upgrades, Set-Cookie, or returned authentication headers.

Streams request uncompressed provider bytes by default. If you explicitly set Accept-Encoding, iteration yields the original encoded bytes; decode them using the returned provider Content-Encoding header.

Alter keeps at most 16 KiB of an uncompressed provider error response transiently for credential-error classification. It never captures this diagnostic body in audit storage. Encoded or larger streamed errors do not automatically mark a credential revoked; their status and bytes still reach the caller unchanged. Downloads and SSE have no diagnostic body buffer.

The advanced, disabled-by-default method is documented only in the non-proxy reference.

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.