@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.
@@ -1,6 +1,35 @@
1
1
  import { z } from 'zod';
2
2
 
3
- /** MCP Server Card (SEP-1649 / SEP-2127), advertising a live MCP server. */
3
+ /** An Agent Skill (Agent Skills Discovery RFC v0.2.0) published by this app. */
4
+ interface AgentSkill {
5
+ /** Stable slug, e.g. `imejis-api`. */
6
+ name: string;
7
+ /** One-line human/agent-readable summary. */
8
+ description: string;
9
+ /** Full markdown content of the SKILL.md served for this skill. */
10
+ content: string;
11
+ /**
12
+ * Path the SKILL.md is served from. Defaults to
13
+ * `/.well-known/agent-skills/<name>/SKILL.md`.
14
+ */
15
+ path?: string;
16
+ /** Skill artifact kind. Defaults to `skill-md`. */
17
+ type?: 'skill-md' | 'archive';
18
+ }
19
+ /** One API described in an API Catalog (RFC 9727 / RFC 9264 linkset). */
20
+ interface ApiCatalogApi {
21
+ /** Anchor URL identifying the API, e.g. `https://api.imejis.io`. */
22
+ anchor: string;
23
+ /** OpenAPI / machine-readable description URL (link rel `service-desc`). */
24
+ serviceDesc?: string;
25
+ /** Human documentation URL (link rel `service-doc`). */
26
+ serviceDoc?: string;
27
+ /** Health / status endpoint URL (link rel `status`). */
28
+ status?: string;
29
+ /** Optional human title for the API. */
30
+ title?: string;
31
+ }
32
+ /** MCP Server Card (SEP-1649 v1.0), advertising a live MCP server. */
4
33
  interface McpServerCard {
5
34
  /** Server name. */
6
35
  name: string;
@@ -10,13 +39,251 @@ interface McpServerCard {
10
39
  endpoint: string;
11
40
  /** Transport type. Defaults to `"streamable-http"`. */
12
41
  transport?: string;
13
- /** Capabilities object, e.g. `{ tools: {}, resources: {} }`. */
42
+ /** MCP protocol version the server speaks. Defaults to `"2025-06-18"`. */
43
+ protocolVersion?: string;
44
+ /**
45
+ * Capability flags. Booleans per SEP-1649 v1.0; a legacy object value
46
+ * (e.g. `{ tools: {} }`) is normalized to booleans by presence.
47
+ */
14
48
  capabilities?: Record<string, unknown>;
15
49
  /** Optional human description. */
16
50
  description?: string;
17
51
  /** Documentation URL. */
18
52
  documentationUrl?: string;
19
53
  }
54
+ /** One OAuth scope an app declares in its scope catalog. */
55
+ interface AppScope {
56
+ /** Scope name, e.g. `designs:read`. */
57
+ name: string;
58
+ /** Human-readable description, shown on the consent screen. */
59
+ description: string;
60
+ }
61
+ /** One skill advertised on the A2A Agent Card. */
62
+ interface A2ACardSkill {
63
+ id: string;
64
+ name: string;
65
+ description: string;
66
+ tags?: string[];
67
+ }
68
+ /**
69
+ * Overrides for the A2A Agent Card (`/.well-known/agent-card.json`). Every
70
+ * field is optional — the card is fully derived from `site` + `skills` by
71
+ * default. See {@link buildA2AAgentCard}.
72
+ */
73
+ interface A2ACardConfig {
74
+ name?: string;
75
+ version?: string;
76
+ description?: string;
77
+ /** The endpoint agents connect to. Defaults to `siteUrl`. */
78
+ serviceUrl?: string;
79
+ /** Transport protocol advertised for `serviceUrl`. Defaults to `'http'`. */
80
+ transportProtocol?: string;
81
+ /** A2A capability flags. Defaults to `{ streaming: false, pushNotifications: false }`. */
82
+ capabilities?: Record<string, unknown>;
83
+ /** Skills; defaults to a mapping of `config.skills` (or a generic site skill). */
84
+ skills?: A2ACardSkill[];
85
+ }
86
+ /** One robots.txt policy group (a `User-agent:` block). */
87
+ interface RobotsPolicy {
88
+ /** User-agent(s) this group applies to, e.g. `'*'` or `'GPTBot'`. */
89
+ userAgent: string | string[];
90
+ /** Paths to allow, e.g. `['/']`. */
91
+ allow?: string[];
92
+ /** Paths to disallow, e.g. `['/api/']`. */
93
+ disallow?: string[];
94
+ /** Optional `Crawl-delay` (non-standard but widely honored). */
95
+ crawlDelay?: number;
96
+ }
97
+ /**
98
+ * Content Signals (https://contentsignals.org) — declares how crawlers may use
99
+ * this site's content. Each flag renders as `<signal>=yes|no`; omitted flags
100
+ * are not emitted (unset = no preference expressed).
101
+ */
102
+ interface ContentSignals {
103
+ /** May content be indexed for search? → `search=yes|no`. */
104
+ search?: boolean;
105
+ /** May content be used as AI input (RAG, grounding)? → `ai-input=yes|no`. */
106
+ aiInput?: boolean;
107
+ /** May content be used for AI training? → `ai-train=yes|no`. */
108
+ aiTrain?: boolean;
109
+ }
110
+ /** Configuration for `buildRobotsTxt`. Every field is optional. */
111
+ interface RobotsConfig {
112
+ /** Policy groups. Defaults to `[{ userAgent: '*', allow: ['/'] }]`. */
113
+ policies?: RobotsPolicy[];
114
+ /**
115
+ * Stance toward known AI crawlers ({@link AI_BOT_USER_AGENTS}): `'allow'`
116
+ * (default — an explicit `Allow: /` group per bot, so readiness checkers see
117
+ * AI bots addressed), `'deny'` (a `Disallow: /` group per bot), or explicit
118
+ * per-bot policies for finer control.
119
+ */
120
+ aiBots?: 'allow' | 'deny' | RobotsPolicy[];
121
+ /** Content-Signal directive attached to the `User-agent: *` group. */
122
+ contentSignals?: ContentSignals;
123
+ /**
124
+ * Sitemap URLs. Defaults to `${siteUrl}/sitemap.xml` when `config.sitemap`
125
+ * is set; pass `[]` to emit no `Sitemap:` line.
126
+ */
127
+ sitemaps?: string[];
128
+ }
129
+ /** One URL entry for the generated sitemap.xml. */
130
+ interface SitemapUrl {
131
+ /** Absolute URL, or a path resolved against `siteUrl`. */
132
+ loc: string;
133
+ /** ISO-8601 last-modified date. */
134
+ lastmod?: string;
135
+ changefreq?: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never';
136
+ /** 0.0–1.0. */
137
+ priority?: number;
138
+ }
139
+ /** Configuration for the agent-readiness discovery layer. */
140
+ interface AgentReadyConfig {
141
+ /** BuildBase server base URL, e.g. `https://api.buildbase.app` (no trailing slash needed). */
142
+ serverUrl: string;
143
+ /** The org id (24-hex) whose agent-readiness config to serve. */
144
+ orgId: string;
145
+ /**
146
+ * This app's public origin, e.g. `https://imejis.io`. Used to build absolute
147
+ * URLs in the Agent Card and to match RFC 9728 resource paths.
148
+ */
149
+ siteUrl: string;
150
+ /** Static metadata for the Agent Card (`/.well-known/agent.json`). */
151
+ site: {
152
+ name: string;
153
+ description?: string;
154
+ /** Absolute URL to human/agent documentation. */
155
+ documentationUrl?: string;
156
+ /** Support/contact email surfaced on the Agent Card. */
157
+ contactEmail?: string;
158
+ /** Provider block; defaults to `{ name: site.name, url: siteUrl }`. */
159
+ provider?: {
160
+ name: string;
161
+ url: string;
162
+ };
163
+ };
164
+ /** Agent Skills to publish. Omit to skip the Agent Skills documents. */
165
+ skills?: AgentSkill[];
166
+ /**
167
+ * The app's OAuth scope catalog — the source of truth for `scopes_supported`
168
+ * in this app's RFC 9728 protected-resource metadata (served from your own
169
+ * origin). Declare real, per-app scopes here (`designs:read`,
170
+ * `render:execute`, …) instead of placeholders. A `protectedResources` entry
171
+ * without its own `scopes` list inherits every catalog scope name. Scopes are
172
+ * app-owned: the shared BuildBase authorization server stays scope-agnostic.
173
+ */
174
+ scopes?: AppScope[];
175
+ /** security.txt fields (RFC 9116). Omit to skip serving security.txt. */
176
+ security?: {
177
+ /** Contact URI(s) — email (`mailto:`) or URL. */
178
+ contact: string | string[];
179
+ /** ISO-8601 expiry; strongly recommended by RFC 9116. */
180
+ expires?: string;
181
+ /** Security policy URL. */
182
+ policy?: string;
183
+ };
184
+ /**
185
+ * API Catalog entries (RFC 9727), served at `/.well-known/api-catalog` as
186
+ * `application/linkset+json`. Omit to skip.
187
+ */
188
+ apiCatalog?: ApiCatalogApi[];
189
+ /**
190
+ * MCP Server Card (SEP-1649), served at `/.well-known/mcp/server-card.json`.
191
+ * Only set this when you actually run an MCP server — the card advertises a
192
+ * live transport endpoint. Omit to skip.
193
+ */
194
+ mcpServerCard?: McpServerCard;
195
+ /**
196
+ * Raw `/auth.md` content (agent registration/auth instructions). If omitted,
197
+ * `buildAuthMd` generates one from the OAuth metadata + site config.
198
+ */
199
+ authMd?: string;
200
+ /**
201
+ * Local `/llms.txt` content. Takes precedence over the org-authored llms.txt
202
+ * from the platform bundle — use when the app owns richer llms.txt content.
203
+ */
204
+ llmsTxt?: string;
205
+ /**
206
+ * Local `/llms-full.txt` content (llmstxt.org expanded document). Omit to
207
+ * skip serving it (or serve your own static file, which then wins).
208
+ */
209
+ llmsFullTxt?: string;
210
+ /**
211
+ * A2A Agent Card served at `/.well-known/agent-card.json`. Served by
212
+ * DEFAULT, derived from `site` + `skills`, so readiness scanners find a
213
+ * valid card with zero config. Pass `false` to disable, or an object to
214
+ * override any derived field.
215
+ */
216
+ a2aCard?: false | A2ACardConfig;
217
+ /**
218
+ * Web Bot Auth key directory (IETF WebBotAuth) served at
219
+ * `/.well-known/http-message-signatures-directory`. Only for apps whose own
220
+ * outbound bot/agent signs its requests — publish the JWKS public keys here
221
+ * so receiving sites can verify the signatures. Omitted = not served.
222
+ */
223
+ webBotAuth?: {
224
+ keys: Array<Record<string, unknown>>;
225
+ };
226
+ /**
227
+ * Extra literal documents served by {@link resolveAgentPath}, keyed by exact
228
+ * request path. The escape hatch for anything the SDK has no builder for —
229
+ * commerce discovery (x402, UCP, ACP, MPP), `/openapi.json`, future
230
+ * `.well-known` documents. A string value infers its content type from the
231
+ * path extension. Extra paths take precedence over built-in documents, so
232
+ * they can also override any SDK-generated document.
233
+ */
234
+ extraPaths?: Record<string, string | {
235
+ body: string;
236
+ contentType?: string;
237
+ status?: number;
238
+ cacheControl?: string;
239
+ }>;
240
+ /** robots.txt generation (`buildRobotsTxt`). Omitted = sane defaults. */
241
+ robots?: RobotsConfig;
242
+ /**
243
+ * URLs for a minimal generated sitemap.xml (`buildSitemap`). Omit when the
244
+ * app already generates sitemaps (e.g. next-sitemap) — the builder then
245
+ * returns null and your own files win.
246
+ */
247
+ sitemap?: {
248
+ urls: Array<string | SitemapUrl>;
249
+ };
250
+ /**
251
+ * RFC 9728 protected resources this app serves, defined locally (app-owned).
252
+ * When set, the SDK builds the `/.well-known/oauth-protected-resource`
253
+ * document from this config — `authorization_servers` is derived from
254
+ * `serverUrl`/`orgId` (the BuildBase issuer). Takes precedence over the
255
+ * platform bundle. Omit to fall back to the org-configured bundle.
256
+ */
257
+ protectedResources?: Array<{
258
+ /** The protected API's resource URI. Defaults to `siteUrl`. */
259
+ resource?: string;
260
+ /** Scopes this resource accepts (`scopes_supported`). */
261
+ scopes?: string[];
262
+ /** Human documentation URL (`resource_documentation`). */
263
+ documentationUrl?: string;
264
+ /** Bearer methods (`bearer_methods_supported`). Defaults to `['header']`. */
265
+ bearerMethods?: string[];
266
+ }>;
267
+ /** TTL (seconds) for cached platform fetches. Default 300 (5 min). */
268
+ cacheTtlSeconds?: number;
269
+ /**
270
+ * Timeout (ms) for platform fetches. Fail-soft on timeout, so a hung or slow
271
+ * BuildBase server can't hang discovery routes forever. Default 5000; set `0`
272
+ * to disable.
273
+ */
274
+ fetchTimeoutMs?: number;
275
+ /** Injectable fetch, mainly for testing. Defaults to the global `fetch`. */
276
+ fetch?: typeof fetch;
277
+ }
278
+ /** A rendered discovery document ready to become an HTTP response. */
279
+ interface DiscoveryDocument {
280
+ status: number;
281
+ contentType: string;
282
+ body: string;
283
+ cacheControl: string;
284
+ /** Value for a `Vary` response header, when the body is negotiated. */
285
+ vary?: string;
286
+ }
20
287
 
21
288
  /**
22
289
  * Built-in MCP tools mapping BuildBase capabilities to agent-callable tools.
@@ -1240,6 +1507,15 @@ interface CreateMcpHandlerConfig {
1240
1507
  * an Origin header (curl, server-to-server) always pass.
1241
1508
  */
1242
1509
  allowedOrigins?: string[];
1510
+ /**
1511
+ * CORS for browser-based MCP clients. Default **true**: emit
1512
+ * `Access-Control-Allow-Origin: *` (safe for a Bearer-token API — no
1513
+ * cookies are ever involved), or reflect the matching origin when
1514
+ * `allowedOrigins` is set. Pass an origin array to allow only those, or
1515
+ * `false` to emit no CORS headers at all. Preflight (OPTIONS) is answered
1516
+ * automatically either way — no wrapper needed in your route.
1517
+ */
1518
+ cors?: boolean | string[];
1243
1519
  /**
1244
1520
  * Hard cap on the raw request-body size in bytes (DoS protection). Bodies
1245
1521
  * larger than this are rejected with 413 before parsing. Defaults to
@@ -1351,6 +1627,40 @@ declare class AppBridgeError extends Error {
1351
1627
  readonly code: string;
1352
1628
  constructor(code: string, message: string);
1353
1629
  }
1630
+ /**
1631
+ * The user + grant context BuildBase sends to `applicationTokenUrl`. The app
1632
+ * mints a token for this user; `resource` is the RFC 8707 audience(s) the token
1633
+ * should be bound to (stamp them as `aud`), and `scope` is what the user granted.
1634
+ * Unknown claims are preserved for forward-compatibility.
1635
+ */
1636
+ interface AppTokenRequestClaims {
1637
+ /** The user's id in the org. */
1638
+ id: string;
1639
+ email: string;
1640
+ name?: string;
1641
+ role?: string;
1642
+ emailVerified?: boolean;
1643
+ image?: string;
1644
+ blocked?: boolean;
1645
+ blockedReason?: string;
1646
+ blockedAt?: string;
1647
+ /** Which grant triggered this mint. */
1648
+ grantType?: 'authorization_code' | 'refresh_token';
1649
+ /** Scopes granted at authorization time. */
1650
+ scope?: string[];
1651
+ /** RFC 8707 resource indicator(s) — bind the minted token's `aud` to these. */
1652
+ resource?: string[];
1653
+ /** The OAuth2 client's display title. */
1654
+ clientTitle?: string;
1655
+ /**
1656
+ * Per-user BuildBase session bound to this grant. Embed it ENCRYPTED in the
1657
+ * token you mint (JWTs are signed, not encrypted) and never store it — your
1658
+ * MCP/agent endpoints decrypt it per request to call BuildBase as this user
1659
+ * (`buildbase.withSession(...)`). Fresh on every grant, including refresh.
1660
+ */
1661
+ sessionId?: string;
1662
+ [claim: string]: unknown;
1663
+ }
1354
1664
  /** Options for {@link verifyClientJwt} (all optional; secure defaults). */
1355
1665
  interface VerifyClientJwtOptions {
1356
1666
  /** Allowed clock skew in seconds for `exp`/`nbf`. Default 60. */
@@ -1371,11 +1681,8 @@ interface VerifyClientJwtOptions {
1371
1681
  * its payload. Checks the signature (timing-safe), the algorithm, `exp`/`nbf`,
1372
1682
  * and — by default — that an `exp` is present at all. Optionally pins `iss`/`aud`.
1373
1683
  * Throws {@link AppBridgeError} on any failure.
1374
- *
1375
- * The third argument accepts either the legacy `clockToleranceSec` number or a
1376
- * {@link VerifyClientJwtOptions} object.
1377
1684
  */
1378
- declare function verifyClientJwt(token: string, clientSecret: string, optionsOrTolerance?: number | VerifyClientJwtOptions): Record<string, any>;
1685
+ declare function verifyClientJwt(token: string, clientSecret: string, options?: VerifyClientJwtOptions): Record<string, any>;
1379
1686
  /** Extract the token from an `Authorization: Bearer <token>` header. */
1380
1687
  declare function extractBearerToken(authorization: string | null | undefined): string | null;
1381
1688
  /**
@@ -1398,5 +1705,252 @@ declare function bearerChallenge(options: {
1398
1705
  body: string;
1399
1706
  };
1400
1707
 
1401
- export { AppBridgeError, bearerChallenge, builtinMcpTools, createMcpHandler, defineMcpTool, extractBearerToken, selectBuiltinTools, signClientJwt, verifyClientJwt };
1402
- export type { BuiltinMcpToolName, CreateMcpHandlerConfig, McpAuthInfo, McpBuildBaseClient, McpHandler, McpHttpRequest, McpHttpResponse, McpServerCard, McpToolAnnotations, McpToolContext, McpToolDefinition, ScopedActions };
1708
+ /**
1709
+ * createAgentStack — the whole agent-readiness + MCP surface from ONE config.
1710
+ *
1711
+ * Everything the SDK can derive, it derives: the MCP endpoint, the server
1712
+ * card, the RFC 9728 protected-resource metadata, the API-catalog entry, the
1713
+ * BuildBase client, token verification (via `buildbaseAuth`), CORS, and the
1714
+ * discovery `Link` header — so a consumer configures identity once and wires
1715
+ * two routes. Every derived value stays overridable ("accelerate, never
1716
+ * gate").
1717
+ *
1718
+ * @example Next.js App Router — complete agent support:
1719
+ * ```ts
1720
+ * // lib/agent.ts
1721
+ * import { createAgentStack } from "@buildbase/sdk/mcp";
1722
+ * export const agent = createAgentStack({
1723
+ * serverUrl: process.env.NEXT_PUBLIC_BUILDBASE_SERVER_URL!,
1724
+ * orgId: process.env.NEXT_PUBLIC_BUILDBASE_ORG_ID!,
1725
+ * siteUrl: "https://app.example.com",
1726
+ * site: { name: "My App" },
1727
+ * secret: process.env.SYSTEM_SECRET!,
1728
+ * });
1729
+ *
1730
+ * // app/api/mcp/route.ts
1731
+ * import { agent } from "@/lib/agent";
1732
+ * export const { GET, POST, DELETE, OPTIONS } = agent.routes;
1733
+ *
1734
+ * // app/.well-known/[...path]/route.ts — and identical one-liners at
1735
+ * // app/robots.txt/route.ts, app/auth.md/route.ts, app/security.txt/route.ts
1736
+ * import { agent } from "@/lib/agent";
1737
+ * export const GET = agent.serveAgentPath;
1738
+ * ```
1739
+ *
1740
+ * @example Express / Hono / Bun — same stack, `handle`/`fetch` style:
1741
+ * ```ts
1742
+ * app.all("/api/mcp", async (req, res) => {
1743
+ * const r = await agent.mcp.handle({ method: req.method, headers: req.headers, body: req.body });
1744
+ * res.status(r.status).set(r.headers).send(r.body);
1745
+ * });
1746
+ * app.use(async (req, res, next) => {
1747
+ * const doc = await agent.resolvePath(req.path);
1748
+ * if (!doc) return next();
1749
+ * res.status(doc.status).set("Content-Type", doc.contentType).send(doc.body);
1750
+ * });
1751
+ * ```
1752
+ */
1753
+
1754
+ /** Configuration for {@link createAgentStack}. */
1755
+ interface AgentStackConfig {
1756
+ /** BuildBase server base URL. */
1757
+ serverUrl: string;
1758
+ /** The org id. */
1759
+ orgId: string;
1760
+ /** This app's public origin, e.g. `https://app.example.com`. */
1761
+ siteUrl: string;
1762
+ /** Site identity for every discovery document. */
1763
+ site: AgentReadyConfig['site'];
1764
+ /**
1765
+ * The app's token-signing secret — wires `buildbaseAuth` (verify + audience
1766
+ * binding + `sid` decryption) automatically. Never sent anywhere. Omit only
1767
+ * when supplying `mcp.auth` yourself.
1768
+ */
1769
+ secret?: string;
1770
+ /**
1771
+ * The app's OAuth scope catalog (see `AgentReadyConfig.scopes`) —
1772
+ * `scopes_supported` in the protected-resource metadata reads from it.
1773
+ */
1774
+ scopes?: AppScope[];
1775
+ /** MCP server options. All optional — omit the whole block for defaults. */
1776
+ mcp?: {
1777
+ /** Endpoint path on `siteUrl`. Default `/api/mcp`. */
1778
+ path?: string;
1779
+ /** Advertised server identity. Defaults to the site name, v1.0.0. */
1780
+ serverInfo?: {
1781
+ name: string;
1782
+ version: string;
1783
+ };
1784
+ /** Your custom tools. */
1785
+ tools?: McpToolDefinition<any, any>[];
1786
+ /** Built-in tool selection. Default `'readonly'`. */
1787
+ builtinTools?: CreateMcpHandlerConfig['builtinTools'];
1788
+ /** Scopes advertised on the protected-resource metadata. */
1789
+ scopes?: string[];
1790
+ /** Your own BuildBase client; auto-created from serverUrl/orgId if omitted. */
1791
+ buildbase?: McpBuildBaseClient;
1792
+ /** Override the derived auth (e.g. `false` for local dev). */
1793
+ auth?: CreateMcpHandlerConfig['auth'];
1794
+ /** Any remaining `createMcpHandler` option, merged last. */
1795
+ handler?: Partial<CreateMcpHandlerConfig>;
1796
+ };
1797
+ /**
1798
+ * Any {@link AgentReadyConfig} field (robots, skills, llms.txt, security,
1799
+ * a2aCard, extraPaths, …) — merged over the derived discovery config, so
1800
+ * every derived value can be replaced.
1801
+ */
1802
+ discovery?: Partial<AgentReadyConfig>;
1803
+ }
1804
+ /** What {@link createAgentStack} returns. */
1805
+ interface AgentStack {
1806
+ /** The MCP handler (`handle`/`fetch`/`listTools`/`serverCard`). */
1807
+ mcp: McpHandler;
1808
+ /** Absolute MCP endpoint URL. */
1809
+ mcpEndpoint: string;
1810
+ /** The fully derived discovery config (inspect or reuse in middleware). */
1811
+ config: AgentReadyConfig;
1812
+ /** Discovery `Link` header value for your middleware / edge responses. */
1813
+ linkHeader: string;
1814
+ /** Resolve any agent-facing path to a document (framework-agnostic). */
1815
+ resolvePath(path: string): Promise<DiscoveryDocument | null>;
1816
+ /** Web-standard discovery route: hand it any `Request`, get a `Response`. */
1817
+ serveAgentPath(request: Request): Promise<Response>;
1818
+ /**
1819
+ * Web-standard MCP route handlers, ready to re-export from a route file:
1820
+ * `export const { GET, POST, DELETE, OPTIONS } = agent.routes`.
1821
+ */
1822
+ routes: {
1823
+ GET: (request: Request) => Promise<Response>;
1824
+ POST: (request: Request) => Promise<Response>;
1825
+ DELETE: (request: Request) => Promise<Response>;
1826
+ OPTIONS: (request: Request) => Promise<Response>;
1827
+ };
1828
+ }
1829
+ /**
1830
+ * Build the complete agent stack — MCP server + discovery surface — from one
1831
+ * config object. See the module doc for full wiring examples.
1832
+ */
1833
+ declare function createAgentStack(stack: AgentStackConfig): AgentStack;
1834
+
1835
+ /**
1836
+ * BuildBase agent-auth presets (server-side, framework-agnostic).
1837
+ *
1838
+ * The BuildBase security model: the platform runs the OAuth2 flow (login,
1839
+ * consent, PKCE, refresh) but the APP mints and verifies its own user tokens,
1840
+ * signed with the app's own secret. The platform only relays the minted token
1841
+ * to the agent — it never sees the secret, so it can neither forge nor decode
1842
+ * an app token. The per-user BuildBase session travels inside the token only
1843
+ * as an AES-256-GCM-encrypted `sid` claim, so it is never stored and never
1844
+ * plaintext anywhere; access to it expires with the token.
1845
+ *
1846
+ * These presets make that model a one-liner on each side of the flow, and run
1847
+ * entirely in the app's process — pure local crypto, zero platform calls:
1848
+ *
1849
+ * • {@link mintAgentToken} — inside your `applicationTokenUrl` handler:
1850
+ * signs the app JWT (HS256) with your secret, stamps `aud` from the RFC
1851
+ * 8707 resource, and embeds the encrypted `sid` automatically.
1852
+ * • {@link buildbaseAuth} — the `auth` config for `createMcpHandler`:
1853
+ * verifies the JWT, enforces audience binding, decrypts the `sid`, and
1854
+ * maps the claims to `McpAuthInfo`.
1855
+ *
1856
+ * @example The full loop:
1857
+ * ```ts
1858
+ * // applicationTokenUrl route — the platform calls this on every grant
1859
+ * const { status, body } = await handleAppTokenRequest({
1860
+ * authorization: req.headers.get("authorization"),
1861
+ * clientSecret: process.env.BUILDBASE_CLIENT_SECRET!,
1862
+ * mintToken: (claims) => mintAgentToken({ claims, secret: process.env.SYSTEM_SECRET! }),
1863
+ * });
1864
+ *
1865
+ * // MCP server — verifies what the route above minted
1866
+ * const mcp = createMcpHandler({
1867
+ * buildbase,
1868
+ * auth: buildbaseAuth({ secret: process.env.SYSTEM_SECRET!, resource: "https://app.example.com/api/mcp" }),
1869
+ * });
1870
+ * ```
1871
+ *
1872
+ * AES-GCM comes from WebCrypto (`globalThis.crypto.subtle`) — Node 18+, Bun,
1873
+ * Deno, edge runtimes, browsers. The wire format is
1874
+ * `base64url(iv(12) || authTag(16) || ciphertext)` with the key derived as
1875
+ * `SHA-256(secret + ":bb-session")`, byte-compatible with Node
1876
+ * `createCipheriv("aes-256-gcm", ...)` implementations of the same layout.
1877
+ */
1878
+
1879
+ /** Encrypt/decrypt pair for the `sid` claim, bound to one app secret. */
1880
+ interface SessionRefCrypto {
1881
+ /** Encrypt a BuildBase session id for embedding in an app JWT. */
1882
+ encryptSessionRef(sessionId: string): Promise<string>;
1883
+ /** Decrypt a `sid` claim. Returns null on any failure (wrong key, garbage). */
1884
+ decryptSessionRef(ref: string): Promise<string | null>;
1885
+ }
1886
+ /**
1887
+ * Session-ref crypto derived from the app's secret. Both sides of the loop
1888
+ * ({@link mintAgentToken}, {@link buildbaseAuth}) use this internally — reach
1889
+ * for it directly only when minting or verifying tokens by hand.
1890
+ */
1891
+ declare function createSessionRefCrypto(secret: string): SessionRefCrypto;
1892
+ /** Options for {@link mintAgentToken}. */
1893
+ interface MintAgentTokenOptions {
1894
+ /** The verified platform claims (from `handleAppTokenRequest`'s callback). */
1895
+ claims: AppTokenRequestClaims;
1896
+ /** The APP's token-signing secret. Never leaves this process. */
1897
+ secret: string;
1898
+ /** Token lifetime in seconds. Default 3600 — keep agent tokens short-lived. */
1899
+ expiresInSec?: number;
1900
+ /**
1901
+ * App-specific claims merged into the token — e.g. a `workspaceId` resolved
1902
+ * by your own user sync. Merged last, so they can override the defaults.
1903
+ */
1904
+ extraClaims?: Record<string, unknown>;
1905
+ }
1906
+ /**
1907
+ * Mint the app's agent access token from a platform grant: HS256-signed with
1908
+ * YOUR secret, `aud` bound to the granted RFC 8707 resource(s), scopes carried
1909
+ * through, and the per-user BuildBase session embedded as an encrypted `sid`
1910
+ * claim. The result plugs straight into `handleAppTokenRequest`'s `mintToken`.
1911
+ */
1912
+ declare function mintAgentToken(options: MintAgentTokenOptions): Promise<{
1913
+ token: string;
1914
+ expiresIn: number;
1915
+ }>;
1916
+ /** Options for {@link buildbaseAuth}. */
1917
+ interface BuildBaseAuthOptions {
1918
+ /** The APP's token-signing secret — the same one `mintAgentToken` used. */
1919
+ secret: string;
1920
+ /**
1921
+ * The protected resource(s) this server IS. Enforces RFC 8707 audience
1922
+ * binding — the token's `aud` must include one of these URIs. Pass an array
1923
+ * when the server is addressable under more than one resource identifier
1924
+ * (e.g. the canonical `<host>/mcp` plus the literal endpoint URL); the
1925
+ * FIRST entry is the canonical one used to derive `resourceMetadataUrl`.
1926
+ */
1927
+ resource?: string | string[];
1928
+ /**
1929
+ * Explicit RFC 9728 metadata URL for the 401 challenge. Defaults to the
1930
+ * path-derived `/.well-known/oauth-protected-resource<path>` of the first
1931
+ * `resource`.
1932
+ */
1933
+ resourceMetadataUrl?: string;
1934
+ /**
1935
+ * Reject tokens that carry no `aud` claim at all. Default false: audience is
1936
+ * enforced when present, and legacy audience-less tokens still work. Turn
1937
+ * this on once every minted token is audience-bound.
1938
+ */
1939
+ requireAudience?: boolean;
1940
+ /** Extra JWT verification options (clock tolerance, issuer pinning). */
1941
+ verify?: Pick<VerifyClientJwtOptions, 'clockToleranceSec' | 'issuer'>;
1942
+ }
1943
+ /**
1944
+ * The `auth` config for `createMcpHandler`, prewired for BuildBase-minted app
1945
+ * tokens: HS256 verification with your secret, RFC 8707 audience binding,
1946
+ * `sid` decryption to the BuildBase session, claim mapping to `McpAuthInfo`,
1947
+ * and the derived RFC 9728 `resourceMetadataUrl`. Entirely local — the token
1948
+ * and secret never leave this process.
1949
+ */
1950
+ declare function buildbaseAuth(options: BuildBaseAuthOptions): {
1951
+ verify: (token: string, req: McpHttpRequest) => Promise<McpAuthInfo | null>;
1952
+ resourceMetadataUrl?: string;
1953
+ };
1954
+
1955
+ export { AppBridgeError, bearerChallenge, buildbaseAuth, builtinMcpTools, createAgentStack, createMcpHandler, createSessionRefCrypto, defineMcpTool, extractBearerToken, mintAgentToken, selectBuiltinTools, signClientJwt, verifyClientJwt };
1956
+ export type { AgentStack, AgentStackConfig, BuildBaseAuthOptions, BuiltinMcpToolName, CreateMcpHandlerConfig, McpAuthInfo, McpBuildBaseClient, McpHandler, McpHttpRequest, McpHttpResponse, McpServerCard, McpToolAnnotations, McpToolContext, McpToolDefinition, MintAgentTokenOptions, ScopedActions, SessionRefCrypto };