@buildbase/sdk 0.0.53 → 0.0.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1116,6 +1116,8 @@ declare abstract class BaseApi {
1116
1116
  private reportError;
1117
1117
  /** Execute fetch with timeout, retries, debug logging, and error callback. */
1118
1118
  private executeFetch;
1119
+ /** Backoff sleep that ends early (with an AbortError) when the signal fires. */
1120
+ private static delay;
1119
1121
  /** Internal: execute fetch against a resolved URL with timeout, retries, debug logging, and error callback. */
1120
1122
  private executeFetchUrl;
1121
1123
  /**
@@ -1860,15 +1862,40 @@ declare function cleanBBParams(): void;
1860
1862
  /**
1861
1863
  * Security utilities for the SDK.
1862
1864
  */
1865
+ /** Options for {@link validateRedirectUrl}. */
1866
+ interface RedirectValidationOptions {
1867
+ /**
1868
+ * Require absolute URLs to be same-origin with the current page
1869
+ * (`window.location.origin`). Relative paths always pass. Use for any
1870
+ * user-controllable target (return URLs, `?next=` params) — it turns an
1871
+ * open redirect into a same-site navigation. Outside a browser there is no
1872
+ * origin to compare against, so absolute URLs are rejected.
1873
+ */
1874
+ sameOrigin?: boolean;
1875
+ /**
1876
+ * Origins additionally allowed for absolute URLs, e.g.
1877
+ * `['https://checkout.stripe.com']`. Matched against `URL.origin` exactly.
1878
+ */
1879
+ allowedOrigins?: string[];
1880
+ }
1863
1881
  /**
1864
- * Validate that a URL is safe to redirect to.
1865
- * Prevents open redirect attacks by ensuring the URL uses https (or http on localhost).
1866
- * Returns the URL if safe, or null if not.
1882
+ * Validate that a URL is safe to redirect to. Returns the URL if safe, null if
1883
+ * not.
1884
+ *
1885
+ * - **Relative paths** (`/dashboard`) are safe and always allowed —
1886
+ * protocol-relative (`//evil.com`) and backslash (`/\evil.com`) forms are
1887
+ * not treated as relative.
1888
+ * - **Absolute URLs** must be `https:` (or `http:` on localhost). By default
1889
+ * any such URL passes (needed for cross-origin targets like Stripe checkout);
1890
+ * pass `sameOrigin` and/or `allowedOrigins` to restrict — then the URL must
1891
+ * match at least one of them. Always restrict user-controllable targets.
1867
1892
  */
1868
- declare function validateRedirectUrl(url: string | null | undefined): string | null;
1893
+ declare function validateRedirectUrl(url: string | null | undefined, options?: RedirectValidationOptions): string | null;
1869
1894
  /**
1870
1895
  * Safely redirect to a URL after validating it.
1871
- * Falls back to fallbackUrl if the target URL is invalid.
1896
+ * Falls back to fallbackUrl (itself validated — else `/`) if the target URL is
1897
+ * invalid. Pass `options` to restrict user-controllable targets (see
1898
+ * {@link validateRedirectUrl}).
1872
1899
  *
1873
1900
  * Browser-only: navigation requires `window.location`. On non-browser runtimes
1874
1901
  * (Node, edge, Deno, Bun) there is nothing to navigate, so this is a no-op that
@@ -1876,7 +1903,7 @@ declare function validateRedirectUrl(url: string | null | undefined): string | n
1876
1903
  * that needs the resolved target should call {@link validateRedirectUrl} and
1877
1904
  * issue the redirect with its own framework (e.g. `Response.redirect`).
1878
1905
  */
1879
- declare function safeRedirect(url: string | null | undefined, fallbackUrl?: string): boolean;
1906
+ declare function safeRedirect(url: string | null | undefined, fallbackUrl?: string, options?: RedirectValidationOptions): boolean;
1880
1907
 
1881
1908
  /**
1882
1909
  * Auth intent preservation — saves and restores the URL the user was on
@@ -1884,7 +1911,8 @@ declare function safeRedirect(url: string | null | undefined, fallbackUrl?: stri
1884
1911
  */
1885
1912
  /**
1886
1913
  * Save the current URL as the post-auth redirect target.
1887
- * Validates the URL before storing — rejects unsafe URLs silently.
1914
+ * Validates the URL before storing — rejects unsafe URLs silently. Same-origin
1915
+ * only: the return URL is "where the user was", never another site.
1888
1916
  */
1889
1917
  declare function saveAuthIntent(returnUrl: string): void;
1890
1918
  /**
@@ -1916,7 +1944,15 @@ declare const PLAN_CURRENCY_OPTIONS: {
1916
1944
  value: "usd" | "eur" | "gbp" | "jpy" | "cad" | "aud" | "chf" | "cny" | "hkd" | "sgd" | "inr" | "mxn" | "brl" | "nzd" | "sek" | "nok" | "dkk" | "pln" | "thb";
1917
1945
  label: string;
1918
1946
  }[];
1919
- /** Format cents as money string (e.g. 1999, "usd" -> "$19.99"). Caller must pass currency (e.g. from plan or workspace). */
1947
+ /** True when `currency` has no minor unit (JPY, KRW, …) — amounts are whole units, not cents. */
1948
+ declare function isZeroDecimalCurrency(currency: string | null | undefined): boolean;
1949
+ /**
1950
+ * Convert a minor-unit amount to its display number for `currency`:
1951
+ * `minorAmountToDisplay(1999, 'usd')` → `"19.99"`,
1952
+ * `minorAmountToDisplay(1000, 'jpy')` → `"1,000"` (zero-decimal — no division).
1953
+ */
1954
+ declare function minorAmountToDisplay(amount: number, currency: string): string;
1955
+ /** Format cents as money string (e.g. 1999, "usd" -> "$19.99"; 1000, "jpy" -> "¥1,000"). Caller must pass currency (e.g. from plan or workspace). */
1920
1956
  declare function formatCents(cents: number, currency: string): string;
1921
1957
  /** Translatable labels for overage/quota formatting */
1922
1958
  interface OverageLabels {
@@ -2957,17 +2993,17 @@ declare function parseWebhookEvent(options: {
2957
2993
  *
2958
2994
  * Makes a consuming app "agent ready" (see https://isitagentready.com) by
2959
2995
  * serving the standard machine-readable discovery documents an AI agent looks
2960
- * for — with the BuildBase server as the source of truth.
2961
- *
2962
- * The heavy lifting already lives on the platform: an org admin configures
2963
- * agent readiness once (protected resources, scopes, llms.txt) and the server
2964
- * publishes the OAuth2 authorization-server metadata (RFC 8414) and the
2965
- * per-resource protected-resource metadata (RFC 9728). This module lets an app
2966
- * re-serve those documents from its own origin — where agents actually look —
2967
- * plus generate the static discovery documents (Agent Card, Agent Skills,
2968
- * security.txt) from local config. The result: an org admin adds full agent
2969
- * support to their app in a couple of lines, and never hand-writes a
2970
- * `.well-known` route.
2996
+ * for.
2997
+ *
2998
+ * Ownership is split: the platform owns AUTH — it publishes the OAuth2
2999
+ * authorization-server metadata (RFC 8414) and this module re-serves it from
3000
+ * the app's origin, where agents actually look. Everything else (protected
3001
+ * resources and their scopes, RFC 9728 metadata, llms.txt, sitemap, Agent
3002
+ * Card, Agent Skills, security.txt) is CONTENT the app owns — declared locally
3003
+ * in {@link AgentReadyConfig} and generated here; the shared authorization
3004
+ * server stays scope- and resource-agnostic. The result: an org admin adds
3005
+ * full agent support to their app in a couple of lines, and never hand-writes
3006
+ * a `.well-known` route.
2971
3007
  *
2972
3008
  * Zero React and no framework types — every function returns plain data. The
2973
3009
  * only runtime dependency is `fetch`; SHA-256 (for Agent Skills digests) is a
@@ -3054,7 +3090,7 @@ interface ApiCatalogApi {
3054
3090
  /** Optional human title for the API. */
3055
3091
  title?: string;
3056
3092
  }
3057
- /** MCP Server Card (SEP-1649 / SEP-2127), advertising a live MCP server. */
3093
+ /** MCP Server Card (SEP-1649 v1.0), advertising a live MCP server. */
3058
3094
  interface McpServerCard {
3059
3095
  /** Server name. */
3060
3096
  name: string;
@@ -3064,13 +3100,50 @@ interface McpServerCard {
3064
3100
  endpoint: string;
3065
3101
  /** Transport type. Defaults to `"streamable-http"`. */
3066
3102
  transport?: string;
3067
- /** Capabilities object, e.g. `{ tools: {}, resources: {} }`. */
3103
+ /** MCP protocol version the server speaks. Defaults to `"2025-06-18"`. */
3104
+ protocolVersion?: string;
3105
+ /**
3106
+ * Capability flags. Booleans per SEP-1649 v1.0; a legacy object value
3107
+ * (e.g. `{ tools: {} }`) is normalized to booleans by presence.
3108
+ */
3068
3109
  capabilities?: Record<string, unknown>;
3069
3110
  /** Optional human description. */
3070
3111
  description?: string;
3071
3112
  /** Documentation URL. */
3072
3113
  documentationUrl?: string;
3073
3114
  }
3115
+ /** One OAuth scope an app declares in its scope catalog. */
3116
+ interface AppScope {
3117
+ /** Scope name, e.g. `designs:read`. */
3118
+ name: string;
3119
+ /** Human-readable description, shown on the consent screen. */
3120
+ description: string;
3121
+ }
3122
+ /** One skill advertised on the A2A Agent Card. */
3123
+ interface A2ACardSkill {
3124
+ id: string;
3125
+ name: string;
3126
+ description: string;
3127
+ tags?: string[];
3128
+ }
3129
+ /**
3130
+ * Overrides for the A2A Agent Card (`/.well-known/agent-card.json`). Every
3131
+ * field is optional — the card is fully derived from `site` + `skills` by
3132
+ * default. See {@link buildA2AAgentCard}.
3133
+ */
3134
+ interface A2ACardConfig {
3135
+ name?: string;
3136
+ version?: string;
3137
+ description?: string;
3138
+ /** The endpoint agents connect to. Defaults to `siteUrl`. */
3139
+ serviceUrl?: string;
3140
+ /** Transport protocol advertised for `serviceUrl`. Defaults to `'http'`. */
3141
+ transportProtocol?: string;
3142
+ /** A2A capability flags. Defaults to `{ streaming: false, pushNotifications: false }`. */
3143
+ capabilities?: Record<string, unknown>;
3144
+ /** Skills; defaults to a mapping of `config.skills` (or a generic site skill). */
3145
+ skills?: A2ACardSkill[];
3146
+ }
3074
3147
  /** One robots.txt policy group (a `User-agent:` block). */
3075
3148
  interface RobotsPolicy {
3076
3149
  /** User-agent(s) this group applies to, e.g. `'*'` or `'GPTBot'`. */
@@ -3151,6 +3224,15 @@ interface AgentReadyConfig {
3151
3224
  };
3152
3225
  /** Agent Skills to publish. Omit to skip the Agent Skills documents. */
3153
3226
  skills?: AgentSkill[];
3227
+ /**
3228
+ * The app's OAuth scope catalog — the source of truth for `scopes_supported`
3229
+ * in this app's RFC 9728 protected-resource metadata (served from your own
3230
+ * origin). Declare real, per-app scopes here (`designs:read`,
3231
+ * `render:execute`, …) instead of placeholders. A `protectedResources` entry
3232
+ * without its own `scopes` list inherits every catalog scope name. Scopes are
3233
+ * app-owned: the shared BuildBase authorization server stays scope-agnostic.
3234
+ */
3235
+ scopes?: AppScope[];
3154
3236
  /** security.txt fields (RFC 9116). Omit to skip serving security.txt. */
3155
3237
  security?: {
3156
3238
  /** Contact URI(s) — email (`mailto:`) or URL. */
@@ -3181,6 +3263,41 @@ interface AgentReadyConfig {
3181
3263
  * from the platform bundle — use when the app owns richer llms.txt content.
3182
3264
  */
3183
3265
  llmsTxt?: string;
3266
+ /**
3267
+ * Local `/llms-full.txt` content (llmstxt.org expanded document). Omit to
3268
+ * skip serving it (or serve your own static file, which then wins).
3269
+ */
3270
+ llmsFullTxt?: string;
3271
+ /**
3272
+ * A2A Agent Card served at `/.well-known/agent-card.json`. Served by
3273
+ * DEFAULT, derived from `site` + `skills`, so readiness scanners find a
3274
+ * valid card with zero config. Pass `false` to disable, or an object to
3275
+ * override any derived field.
3276
+ */
3277
+ a2aCard?: false | A2ACardConfig;
3278
+ /**
3279
+ * Web Bot Auth key directory (IETF WebBotAuth) served at
3280
+ * `/.well-known/http-message-signatures-directory`. Only for apps whose own
3281
+ * outbound bot/agent signs its requests — publish the JWKS public keys here
3282
+ * so receiving sites can verify the signatures. Omitted = not served.
3283
+ */
3284
+ webBotAuth?: {
3285
+ keys: Array<Record<string, unknown>>;
3286
+ };
3287
+ /**
3288
+ * Extra literal documents served by {@link resolveAgentPath}, keyed by exact
3289
+ * request path. The escape hatch for anything the SDK has no builder for —
3290
+ * commerce discovery (x402, UCP, ACP, MPP), `/openapi.json`, future
3291
+ * `.well-known` documents. A string value infers its content type from the
3292
+ * path extension. Extra paths take precedence over built-in documents, so
3293
+ * they can also override any SDK-generated document.
3294
+ */
3295
+ extraPaths?: Record<string, string | {
3296
+ body: string;
3297
+ contentType?: string;
3298
+ status?: number;
3299
+ cacheControl?: string;
3300
+ }>;
3184
3301
  /** robots.txt generation (`buildRobotsTxt`). Omitted = sane defaults. */
3185
3302
  robots?: RobotsConfig;
3186
3303
  /**
@@ -3258,11 +3375,12 @@ declare function buildAgentCard(config: AgentReadyConfig, bundle: AgentReadiness
3258
3375
  * Resolve the RFC 9728 protected-resource metadata for a request path, or null
3259
3376
  * if no configured resource maps to it.
3260
3377
  *
3261
- * App-owned and local: built entirely from `config.protectedResources`, with
3262
- * `authorization_servers` derived from `serverUrl`/`orgId` (the BuildBase
3263
- * issuer). No platform round-trip.
3378
+ * App-owned. `authorization_servers` uses the platform bundle's real
3379
+ * `authorizationServer.issuer` when provided (so this doc can't advertise a
3380
+ * different issuer than the AS metadata / agent card / auth.md), falling back
3381
+ * to the `serverUrl`/`orgId` heuristic when the bundle isn't available.
3264
3382
  */
3265
- declare function buildProtectedResourceMetadata(requestPath: string, config: AgentReadyConfig): DiscoveryDocument | null;
3383
+ declare function buildProtectedResourceMetadata(requestPath: string, config: AgentReadyConfig, authServerIssuer?: string): DiscoveryDocument | null;
3266
3384
  /** Agent Skills discovery index (Agent Skills Discovery RFC v0.2.0). */
3267
3385
  declare function buildAgentSkillsIndex(config: AgentReadyConfig): DiscoveryDocument | null;
3268
3386
  /** Serve a single skill's SKILL.md by request path, or null if none matches. */
@@ -3275,16 +3393,68 @@ declare function buildSecurityTxt(config: AgentReadyConfig): DiscoveryDocument |
3275
3393
  * not platform-managed.
3276
3394
  */
3277
3395
  declare function buildLlmsTxt(config: AgentReadyConfig): DiscoveryDocument | null;
3396
+ /**
3397
+ * The `/llms-full.txt` document from `config.llmsFullTxt` (app-authored).
3398
+ * Returns null when not set — serve your own static file instead.
3399
+ */
3400
+ declare function buildLlmsFullTxt(config: AgentReadyConfig): DiscoveryDocument | null;
3401
+ /**
3402
+ * A2A Agent Card (https://a2a-protocol.org) for `/.well-known/agent-card.json`.
3403
+ * Served by default, fully derived from `site` + `skills`, so a consumer is
3404
+ * A2A-discoverable with zero config; `config.a2aCard` overrides any field or
3405
+ * disables the card entirely (`false`). Skills fall back to a generic
3406
+ * site-content skill when none are configured — the card must carry at least
3407
+ * one skill to validate.
3408
+ */
3409
+ declare function buildA2AAgentCard(config: AgentReadyConfig): DiscoveryDocument | null;
3410
+ /**
3411
+ * Web Bot Auth key directory (JWKS) for
3412
+ * `/.well-known/http-message-signatures-directory`. Returns null unless
3413
+ * `config.webBotAuth.keys` is set — signing keys are the app's own and can't
3414
+ * be derived.
3415
+ */
3416
+ declare function buildWebBotAuthDirectory(config: AgentReadyConfig): DiscoveryDocument | null;
3417
+ /** One DNS record the org should publish for DNS-AID agent discovery. */
3418
+ interface DnsAidRecord {
3419
+ /** Fully-qualified record name, e.g. `_a2a._agents.example.com`. */
3420
+ name: string;
3421
+ /** Record type — HTTPS for HTTPS endpoints, SVCB otherwise. */
3422
+ type: 'HTTPS' | 'SVCB';
3423
+ ttl: number;
3424
+ /** Record data, e.g. `1 example.com. alpn="h2" port=443`. */
3425
+ data: string;
3426
+ }
3427
+ /**
3428
+ * DNS-AID (DNS for AI Discovery) records this app should publish under its
3429
+ * domain's `_agents` namespace. DNS records can't be served over HTTP — hand
3430
+ * these to the org's DNS provider (and DNSSEC-sign the zone). Derived from the
3431
+ * same config as the HTTP discovery surface, so the two never disagree.
3432
+ */
3433
+ declare function buildDnsAidRecords(config: AgentReadyConfig): DnsAidRecord[];
3278
3434
  /**
3279
3435
  * API Catalog (RFC 9727) as a `linkset+json` document for
3280
3436
  * `/.well-known/api-catalog`. Returns null when no APIs are configured.
3281
3437
  */
3282
3438
  declare function buildApiCatalog(config: AgentReadyConfig): DiscoveryDocument | null;
3283
3439
  /**
3284
- * MCP Server Card (SEP-1649) for `/.well-known/mcp/server-card.json`. Returns
3285
- * null when no card is configured (i.e. no MCP server is running).
3440
+ * MCP Server Card (SEP-1649 v1.0) for `/.well-known/mcp/server-card.json`.
3441
+ * Returns null when no card is configured (i.e. no MCP server is running).
3286
3442
  */
3287
3443
  declare function buildMcpServerCard(config: AgentReadyConfig): DiscoveryDocument | null;
3444
+ /**
3445
+ * MCP discovery manifest (SEP-1960) for `/.well-known/mcp.json` — the
3446
+ * origin-level index of every MCP server this app exposes. Complements the
3447
+ * per-server card (SEP-1649): scanners and agents probe this path first, then
3448
+ * follow `server_card` for detail. Returns null when no MCP server is
3449
+ * configured.
3450
+ *
3451
+ * The transport endpoint may live on a different origin than the app serving
3452
+ * this manifest (e.g. card on `www.`, server on `api.`); the `authentication`
3453
+ * pointer is derived from the ENDPOINT's origin per RFC 9728 path derivation,
3454
+ * so agents land on the metadata the server's own WWW-Authenticate challenge
3455
+ * advertises.
3456
+ */
3457
+ declare function buildMcpDiscoveryManifest(config: AgentReadyConfig): DiscoveryDocument | null;
3288
3458
  /**
3289
3459
  * The `/auth.md` document (agent registration + authentication instructions).
3290
3460
  * Uses `config.authMd` verbatim when provided; otherwise generates one from the
@@ -3470,11 +3640,8 @@ interface VerifyClientJwtOptions {
3470
3640
  * its payload. Checks the signature (timing-safe), the algorithm, `exp`/`nbf`,
3471
3641
  * and — by default — that an `exp` is present at all. Optionally pins `iss`/`aud`.
3472
3642
  * Throws {@link AppBridgeError} on any failure.
3473
- *
3474
- * The third argument accepts either the legacy `clockToleranceSec` number or a
3475
- * {@link VerifyClientJwtOptions} object.
3476
3643
  */
3477
- declare function verifyClientJwt(token: string, clientSecret: string, optionsOrTolerance?: number | VerifyClientJwtOptions): Record<string, any>;
3644
+ declare function verifyClientJwt(token: string, clientSecret: string, options?: VerifyClientJwtOptions): Record<string, any>;
3478
3645
  /** Extract the token from an `Authorization: Bearer <token>` header. */
3479
3646
  declare function extractBearerToken(authorization: string | null | undefined): string | null;
3480
3647
  /**
@@ -3855,5 +4022,198 @@ interface BuildBaseResult extends ScopedActions {
3855
4022
  }
3856
4023
  declare function BuildBase(config: BuildBaseConfig): BuildBaseResult;
3857
4024
 
3858
- export { AI_BOT_USER_AGENTS, ApiVersion, AppBridgeError, AuthApi, AuthStatus, BBAction, BBScreen, BBStatus, BB_PARAM, BaseApi, BetaForm, BillingIntervals, BuildBase, CURRENCY_DISPLAY, CURRENCY_FLAG, CreditBucketSource, CreditBucketStatus, CreditTransactionType, DEFAULT_ROLE_PERMISSIONS, DunningState, EventEmitter, InvoiceStatuses, PLAN_CURRENCY_CODES, PLAN_CURRENCY_OPTIONS, PUSH_SERVICE_WORKER_SCRIPT, Permission, PushApi, SDKEvent, SettingsApi, SubscriptionItemType, SubscriptionStatus, UserApi, WorkspaceApi, appTokenFailure, appTokenSuccess, bearerChallenge, buildAgentCard, buildAgentSkillsIndex, buildApiCatalog, buildAuthMd, buildDiscoveryLinkHeader, buildLlmsTxt, buildMcpServerCard, buildProtectedResourceMetadata, buildRobotsTxt, buildSecurityTxt, buildSitemap, buildSkillMd, calculateBillableSeats, calculateSeatOverageCents, calculateTotalSubscriptionCents, cleanBBParams, clearAgentReadinessCache, clearAuthIntent, consumeAuthIntent, createBBUrl, createCheckoutRedirectUrls, createCreditPurchaseRedirectUrls, BuildBase as default, eventEmitter, extractBearerToken, fetchAgentReadiness, formatCents, formatOverageRate, formatOverageRateWithLabel, formatQuotaIncludedOverage, formatQuotaWithPrice, getAvailableCurrenciesFromPlans, getBasePriceCents, getBillingIntervalAndCurrencyFromPriceId, getCurrencyFlag, getCurrencySymbol, getDisplayCurrency, getPerSeatPriceCents, getPricingVariant, getQuotaDisplayValue, getQuotaDisplayWithVariant, getQuotaOverageCents, getQuotaUnitLabelFromName, getSeatPricing, getStripePriceIdForInterval, handleAppRevokeRequest, handleAppTokenRequest, hasPermission, invalidateCreditBalance, invalidateQuotaUsage, invalidateSubscription, negotiateMarkdown, parseWebhookEvent, provideWebMcpTools, readBBParams, resolveAgentPath, resolveMaxUsers, resolvePermissions, resolveWellKnown, safeRedirect, saveAuthIntent, sha256Digest, signClientJwt, validateInvite, validateRedirectUrl, verifyAppRevokeRequest, verifyAppTokenRequest, verifyClientJwt, verifyWebhookSignature, wantsMarkdown };
3859
- export type { AgentReadinessBundle, AgentReadyConfig, AgentSkill, ApiCatalogApi, AppRevokeRequestClaims, AppTokenRequestClaims, AppTokenResponseBody, AppTokenResult, BBActionType, BBScreenType, BBStatusType, BetaFormData, BetaFormResponse, BillingInterval, BuildBaseConfig, BuildBaseResult, BuildBaseSession, CheckoutResult, ContentSignals, CreditActions, CreditBucketSourceType, CreditBucketStatusType, CreditTransactionTypeValue, DiscoveryDocument, DunningStateType, EventData, EventType, FeatureActions, FormatQuotaWithPriceOptions, GetCheckoutStripeParams, HandlerResult, IAllQuotaUsageResponse, IBaseApiConfig, IBasePricing, IBetaConfig, ICheckoutSessionRequest, ICheckoutSessionResponse, ICheckoutStripeOptions, IConsumeCreditsRequest, IConsumeCreditsResponse, ICreditBalance, ICreditBucket, ICreditBucketsQuery, ICreditBucketsResponse, ICreditPackage, ICreditPackagePricingVariant, ICreditPurchaseRequest, ICreditPurchaseResponse, ICreditTransaction, ICreditTransactionsQuery, ICreditTransactionsResponse, IEventCallbacks, IExpiringCreditsResponse, IInvoice, IInvoiceListResponse, IInvoiceResponse, IOsConfig, IOsState, IPlan, IPlanGroup, IPlanGroupInfo, IPlanGroupLatestVersion, IPlanGroupResponse, IPlanGroupVersion, IPlanGroupVersionWithPlans, IPlanGroupVersionsResponse, IPlanVersion, IPlanVersionSummary, IPlanVersionWithPlan, IPricingVariant, IPublicCreditPackage, IPublicCreditPackagesResponse, IPublicPlanItem, IPublicPlanItemCategory, IPublicPlanVersion, IPublicPlansResponse, IQuotaByInterval, IQuotaIntervalValue, IQuotaOveragePriceIdsByInterval, IQuotaOveragesByInterval, IQuotaUsageStatus, IQuotaUsageStatusResponse, IRecordUsageRequest, IRecordUsageResponse, ISettings, IStripePricesByInterval, ISubscription, ISubscriptionItem, ISubscriptionResponse, ISubscriptionUpdateRequest, ISubscriptionUpdateResponse, IUsageLogEntry, IUsageLogsQuery, IUsageLogsResponse, IUser, IWorkspace, InviteBlockReason, InviteValidation, InvoiceActions, InvoiceStatus, InvoiceStatusType, MaxUsersConfig, McpServerCard, NotificationData, NotificationEvent, NotificationResult, OnWorkspaceChangeParams, PermissionActions, PermissionContext, PermissionKey, PlanActions, PlanVersionWithPricingVariants, QuotaDisplayValue, QuotaDisplayWithOverage, RobotsConfig, RobotsPolicy, RolePermissionMap, ScopedActions, SettingsActions, SitemapUrl, SubscriptionActions, SubscriptionItemTypeValue, SubscriptionStatusType, TranslationKey, UsageActions, UserActions, UserCreatedEventData, UserUpdatedEventData, WebMcpTool, WorkspaceActions, WorkspaceChangedEventData, WorkspaceCreatedEventData, WorkspaceDeletedEventData, WorkspaceUpdatedEventData, WorkspaceUserAddedEventData, WorkspaceUserRemovedEventData, WorkspaceUserRoleChangedEventData };
4025
+ /**
4026
+ * MCP server toolkit (server-side, framework-agnostic).
4027
+ *
4028
+ * Turns a consuming app into a live MCP (Model Context Protocol) server so AI
4029
+ * agents can operate its BuildBase capabilities — workspaces, subscriptions,
4030
+ * quotas, credits, feature flags, permissions — plus any custom tools the app
4031
+ * defines. The transport is stateless Streamable HTTP: a single JSON-RPC
4032
+ * message per POST, no sessions and no SSE, which keeps the handler pure and
4033
+ * identical on Node 18+, edge, Deno, and Bun.
4034
+ *
4035
+ * Zero framework types: the core `handle()` takes a plain
4036
+ * `{ method, headers, body }` and returns `{ status, headers, body }` (wire it
4037
+ * into Express/Fastify/Hono yourself), while `fetch()` adapts Web-standard
4038
+ * `Request` → `Response` for Next.js App Router and edge runtimes.
4039
+ *
4040
+ * Agents authenticate with the Bearer tokens the app mints via the OAuth2
4041
+ * app-bridge (`handleAppTokenRequest` + `signClientJwt`); the `auth.verify`
4042
+ * callback maps a verified token to the BuildBase session the tools run under.
4043
+ *
4044
+ * @example Next.js App Router — the entire integration:
4045
+ * ```ts
4046
+ * // lib/mcp.ts
4047
+ * import BuildBase from '@buildbase/sdk';
4048
+ * import { createMcpHandler, verifyClientJwt } from '@buildbase/sdk/mcp';
4049
+ *
4050
+ * const buildbase = BuildBase({
4051
+ * serverUrl: process.env.BUILDBASE_URL!,
4052
+ * orgId: process.env.BUILDBASE_ORG_ID!,
4053
+ * });
4054
+ *
4055
+ * export const mcp = createMcpHandler({
4056
+ * buildbase,
4057
+ * serverInfo: { name: 'imejis', version: '1.0.0' },
4058
+ * auth: {
4059
+ * verify: (token) => {
4060
+ * const c = verifyClientJwt(token, process.env.BUILDBASE_CLIENT_SECRET!);
4061
+ * return { sessionId: String(c.sid), userId: String(c.sub), scopes: c.scope };
4062
+ * },
4063
+ * resourceMetadataUrl: 'https://imejis.io/.well-known/oauth-protected-resource',
4064
+ * },
4065
+ * });
4066
+ *
4067
+ * // app/api/mcp/route.ts
4068
+ * import { mcp } from '@/lib/mcp';
4069
+ * export const POST = (req: Request) => mcp.fetch(req);
4070
+ * export const GET = (req: Request) => mcp.fetch(req); // 405 per spec (no SSE)
4071
+ * export const DELETE = (req: Request) => mcp.fetch(req); // 405 (stateless)
4072
+ * ```
4073
+ */
4074
+
4075
+ /** A transport-agnostic HTTP request (mirror of the DiscoveryDocument idea). */
4076
+ interface McpHttpRequest {
4077
+ /** HTTP method, e.g. `'POST'`. */
4078
+ method: string;
4079
+ /** Header map. Keys are matched case-insensitively. */
4080
+ headers: Record<string, string | undefined>;
4081
+ /** Raw JSON body string, or an already-parsed value (e.g. Express req.body). */
4082
+ body?: string | unknown;
4083
+ }
4084
+ /** The identity a verified Bearer token resolves to. */
4085
+ interface McpAuthInfo {
4086
+ /** BuildBase session all tool calls run under (`buildbase.withSession(...)`). */
4087
+ sessionId: string;
4088
+ /** The acting BuildBase user id — default subject for permission checks. */
4089
+ userId?: string;
4090
+ /** Pin tools to one workspace; used when the agent omits `workspaceId`. */
4091
+ workspaceId?: string;
4092
+ /** OAuth scopes granted to the agent; filters tools with `requiredScopes`. */
4093
+ scopes?: string[];
4094
+ /** Raw verified claims, passed through to tool context. */
4095
+ claims?: Record<string, unknown>;
4096
+ }
4097
+
4098
+ /**
4099
+ * BuildBase agent-auth presets (server-side, framework-agnostic).
4100
+ *
4101
+ * The BuildBase security model: the platform runs the OAuth2 flow (login,
4102
+ * consent, PKCE, refresh) but the APP mints and verifies its own user tokens,
4103
+ * signed with the app's own secret. The platform only relays the minted token
4104
+ * to the agent — it never sees the secret, so it can neither forge nor decode
4105
+ * an app token. The per-user BuildBase session travels inside the token only
4106
+ * as an AES-256-GCM-encrypted `sid` claim, so it is never stored and never
4107
+ * plaintext anywhere; access to it expires with the token.
4108
+ *
4109
+ * These presets make that model a one-liner on each side of the flow, and run
4110
+ * entirely in the app's process — pure local crypto, zero platform calls:
4111
+ *
4112
+ * • {@link mintAgentToken} — inside your `applicationTokenUrl` handler:
4113
+ * signs the app JWT (HS256) with your secret, stamps `aud` from the RFC
4114
+ * 8707 resource, and embeds the encrypted `sid` automatically.
4115
+ * • {@link buildbaseAuth} — the `auth` config for `createMcpHandler`:
4116
+ * verifies the JWT, enforces audience binding, decrypts the `sid`, and
4117
+ * maps the claims to `McpAuthInfo`.
4118
+ *
4119
+ * @example The full loop:
4120
+ * ```ts
4121
+ * // applicationTokenUrl route — the platform calls this on every grant
4122
+ * const { status, body } = await handleAppTokenRequest({
4123
+ * authorization: req.headers.get("authorization"),
4124
+ * clientSecret: process.env.BUILDBASE_CLIENT_SECRET!,
4125
+ * mintToken: (claims) => mintAgentToken({ claims, secret: process.env.SYSTEM_SECRET! }),
4126
+ * });
4127
+ *
4128
+ * // MCP server — verifies what the route above minted
4129
+ * const mcp = createMcpHandler({
4130
+ * buildbase,
4131
+ * auth: buildbaseAuth({ secret: process.env.SYSTEM_SECRET!, resource: "https://app.example.com/api/mcp" }),
4132
+ * });
4133
+ * ```
4134
+ *
4135
+ * AES-GCM comes from WebCrypto (`globalThis.crypto.subtle`) — Node 18+, Bun,
4136
+ * Deno, edge runtimes, browsers. The wire format is
4137
+ * `base64url(iv(12) || authTag(16) || ciphertext)` with the key derived as
4138
+ * `SHA-256(secret + ":bb-session")`, byte-compatible with Node
4139
+ * `createCipheriv("aes-256-gcm", ...)` implementations of the same layout.
4140
+ */
4141
+
4142
+ /** Encrypt/decrypt pair for the `sid` claim, bound to one app secret. */
4143
+ interface SessionRefCrypto {
4144
+ /** Encrypt a BuildBase session id for embedding in an app JWT. */
4145
+ encryptSessionRef(sessionId: string): Promise<string>;
4146
+ /** Decrypt a `sid` claim. Returns null on any failure (wrong key, garbage). */
4147
+ decryptSessionRef(ref: string): Promise<string | null>;
4148
+ }
4149
+ /**
4150
+ * Session-ref crypto derived from the app's secret. Both sides of the loop
4151
+ * ({@link mintAgentToken}, {@link buildbaseAuth}) use this internally — reach
4152
+ * for it directly only when minting or verifying tokens by hand.
4153
+ */
4154
+ declare function createSessionRefCrypto(secret: string): SessionRefCrypto;
4155
+ /** Options for {@link mintAgentToken}. */
4156
+ interface MintAgentTokenOptions {
4157
+ /** The verified platform claims (from `handleAppTokenRequest`'s callback). */
4158
+ claims: AppTokenRequestClaims;
4159
+ /** The APP's token-signing secret. Never leaves this process. */
4160
+ secret: string;
4161
+ /** Token lifetime in seconds. Default 3600 — keep agent tokens short-lived. */
4162
+ expiresInSec?: number;
4163
+ /**
4164
+ * App-specific claims merged into the token — e.g. a `workspaceId` resolved
4165
+ * by your own user sync. Merged last, so they can override the defaults.
4166
+ */
4167
+ extraClaims?: Record<string, unknown>;
4168
+ }
4169
+ /**
4170
+ * Mint the app's agent access token from a platform grant: HS256-signed with
4171
+ * YOUR secret, `aud` bound to the granted RFC 8707 resource(s), scopes carried
4172
+ * through, and the per-user BuildBase session embedded as an encrypted `sid`
4173
+ * claim. The result plugs straight into `handleAppTokenRequest`'s `mintToken`.
4174
+ */
4175
+ declare function mintAgentToken(options: MintAgentTokenOptions): Promise<{
4176
+ token: string;
4177
+ expiresIn: number;
4178
+ }>;
4179
+ /** Options for {@link buildbaseAuth}. */
4180
+ interface BuildBaseAuthOptions {
4181
+ /** The APP's token-signing secret — the same one `mintAgentToken` used. */
4182
+ secret: string;
4183
+ /**
4184
+ * The protected resource(s) this server IS. Enforces RFC 8707 audience
4185
+ * binding — the token's `aud` must include one of these URIs. Pass an array
4186
+ * when the server is addressable under more than one resource identifier
4187
+ * (e.g. the canonical `<host>/mcp` plus the literal endpoint URL); the
4188
+ * FIRST entry is the canonical one used to derive `resourceMetadataUrl`.
4189
+ */
4190
+ resource?: string | string[];
4191
+ /**
4192
+ * Explicit RFC 9728 metadata URL for the 401 challenge. Defaults to the
4193
+ * path-derived `/.well-known/oauth-protected-resource<path>` of the first
4194
+ * `resource`.
4195
+ */
4196
+ resourceMetadataUrl?: string;
4197
+ /**
4198
+ * Reject tokens that carry no `aud` claim at all. Default false: audience is
4199
+ * enforced when present, and legacy audience-less tokens still work. Turn
4200
+ * this on once every minted token is audience-bound.
4201
+ */
4202
+ requireAudience?: boolean;
4203
+ /** Extra JWT verification options (clock tolerance, issuer pinning). */
4204
+ verify?: Pick<VerifyClientJwtOptions, 'clockToleranceSec' | 'issuer'>;
4205
+ }
4206
+ /**
4207
+ * The `auth` config for `createMcpHandler`, prewired for BuildBase-minted app
4208
+ * tokens: HS256 verification with your secret, RFC 8707 audience binding,
4209
+ * `sid` decryption to the BuildBase session, claim mapping to `McpAuthInfo`,
4210
+ * and the derived RFC 9728 `resourceMetadataUrl`. Entirely local — the token
4211
+ * and secret never leave this process.
4212
+ */
4213
+ declare function buildbaseAuth(options: BuildBaseAuthOptions): {
4214
+ verify: (token: string, req: McpHttpRequest) => Promise<McpAuthInfo | null>;
4215
+ resourceMetadataUrl?: string;
4216
+ };
4217
+
4218
+ export { AI_BOT_USER_AGENTS, ApiVersion, AppBridgeError, AuthApi, AuthStatus, BBAction, BBScreen, BBStatus, BB_PARAM, BaseApi, BetaForm, BillingIntervals, BuildBase, CURRENCY_DISPLAY, CURRENCY_FLAG, CreditBucketSource, CreditBucketStatus, CreditTransactionType, DEFAULT_ROLE_PERMISSIONS, DunningState, EventEmitter, InvoiceStatuses, PLAN_CURRENCY_CODES, PLAN_CURRENCY_OPTIONS, PUSH_SERVICE_WORKER_SCRIPT, Permission, PushApi, SDKEvent, SettingsApi, SubscriptionItemType, SubscriptionStatus, UserApi, WorkspaceApi, appTokenFailure, appTokenSuccess, bearerChallenge, buildA2AAgentCard, buildAgentCard, buildAgentSkillsIndex, buildApiCatalog, buildAuthMd, buildDiscoveryLinkHeader, buildDnsAidRecords, buildLlmsFullTxt, buildLlmsTxt, buildMcpDiscoveryManifest, buildMcpServerCard, buildProtectedResourceMetadata, buildRobotsTxt, buildSecurityTxt, buildSitemap, buildSkillMd, buildWebBotAuthDirectory, buildbaseAuth, calculateBillableSeats, calculateSeatOverageCents, calculateTotalSubscriptionCents, cleanBBParams, clearAgentReadinessCache, clearAuthIntent, consumeAuthIntent, createBBUrl, createCheckoutRedirectUrls, createCreditPurchaseRedirectUrls, createSessionRefCrypto, BuildBase as default, eventEmitter, extractBearerToken, fetchAgentReadiness, formatCents, formatOverageRate, formatOverageRateWithLabel, formatQuotaIncludedOverage, formatQuotaWithPrice, getAvailableCurrenciesFromPlans, getBasePriceCents, getBillingIntervalAndCurrencyFromPriceId, getCurrencyFlag, getCurrencySymbol, getDisplayCurrency, getPerSeatPriceCents, getPricingVariant, getQuotaDisplayValue, getQuotaDisplayWithVariant, getQuotaOverageCents, getQuotaUnitLabelFromName, getSeatPricing, getStripePriceIdForInterval, handleAppRevokeRequest, handleAppTokenRequest, hasPermission, invalidateCreditBalance, invalidateQuotaUsage, invalidateSubscription, isZeroDecimalCurrency, minorAmountToDisplay, mintAgentToken, negotiateMarkdown, parseWebhookEvent, provideWebMcpTools, readBBParams, resolveAgentPath, resolveMaxUsers, resolvePermissions, resolveWellKnown, safeRedirect, saveAuthIntent, sha256Digest, signClientJwt, validateInvite, validateRedirectUrl, verifyAppRevokeRequest, verifyAppTokenRequest, verifyClientJwt, verifyWebhookSignature, wantsMarkdown };
4219
+ export type { A2ACardConfig, A2ACardSkill, AgentReadinessBundle, AgentReadyConfig, AgentSkill, ApiCatalogApi, AppRevokeRequestClaims, AppScope, AppTokenRequestClaims, AppTokenResponseBody, AppTokenResult, BBActionType, BBScreenType, BBStatusType, BetaFormData, BetaFormResponse, BillingInterval, BuildBaseAuthOptions, BuildBaseConfig, BuildBaseResult, BuildBaseSession, CheckoutResult, ContentSignals, CreditActions, CreditBucketSourceType, CreditBucketStatusType, CreditTransactionTypeValue, DiscoveryDocument, DnsAidRecord, DunningStateType, EventData, EventType, FeatureActions, FormatQuotaWithPriceOptions, GetCheckoutStripeParams, HandlerResult, IAllQuotaUsageResponse, IBaseApiConfig, IBasePricing, IBetaConfig, ICheckoutSessionRequest, ICheckoutSessionResponse, ICheckoutStripeOptions, IConsumeCreditsRequest, IConsumeCreditsResponse, ICreditBalance, ICreditBucket, ICreditBucketsQuery, ICreditBucketsResponse, ICreditPackage, ICreditPackagePricingVariant, ICreditPurchaseRequest, ICreditPurchaseResponse, ICreditTransaction, ICreditTransactionsQuery, ICreditTransactionsResponse, IEventCallbacks, IExpiringCreditsResponse, IInvoice, IInvoiceListResponse, IInvoiceResponse, IOsConfig, IOsState, IPlan, IPlanGroup, IPlanGroupInfo, IPlanGroupLatestVersion, IPlanGroupResponse, IPlanGroupVersion, IPlanGroupVersionWithPlans, IPlanGroupVersionsResponse, IPlanVersion, IPlanVersionSummary, IPlanVersionWithPlan, IPricingVariant, IPublicCreditPackage, IPublicCreditPackagesResponse, IPublicPlanItem, IPublicPlanItemCategory, IPublicPlanVersion, IPublicPlansResponse, IQuotaByInterval, IQuotaIntervalValue, IQuotaOveragePriceIdsByInterval, IQuotaOveragesByInterval, IQuotaUsageStatus, IQuotaUsageStatusResponse, IRecordUsageRequest, IRecordUsageResponse, ISettings, IStripePricesByInterval, ISubscription, ISubscriptionItem, ISubscriptionResponse, ISubscriptionUpdateRequest, ISubscriptionUpdateResponse, IUsageLogEntry, IUsageLogsQuery, IUsageLogsResponse, IUser, IWorkspace, InviteBlockReason, InviteValidation, InvoiceActions, InvoiceStatus, InvoiceStatusType, MaxUsersConfig, McpServerCard, MintAgentTokenOptions, NotificationData, NotificationEvent, NotificationResult, OnWorkspaceChangeParams, PermissionActions, PermissionContext, PermissionKey, PlanActions, PlanVersionWithPricingVariants, QuotaDisplayValue, QuotaDisplayWithOverage, RedirectValidationOptions, RobotsConfig, RobotsPolicy, RolePermissionMap, ScopedActions, SessionRefCrypto, SettingsActions, SitemapUrl, SubscriptionActions, SubscriptionItemTypeValue, SubscriptionStatusType, TranslationKey, UsageActions, UserActions, UserCreatedEventData, UserUpdatedEventData, WebMcpTool, WorkspaceActions, WorkspaceChangedEventData, WorkspaceCreatedEventData, WorkspaceDeletedEventData, WorkspaceUpdatedEventData, WorkspaceUserAddedEventData, WorkspaceUserRemovedEventData, WorkspaceUserRoleChangedEventData };