# Skybridge > This file is very large and may be truncated. For an index of this content, please refer to https://docs.skybridge.tech/llms.txt instead. > The #1 full stack open-source TS framework for building ChatGPT plugins and MCP Apps # auth0Provider Source: https://docs.skybridge.tech/api-reference/auth0-provider Wire OAuth from an Auth0 tenant `auth0Provider` wires authentication through [Auth0](https://auth0.com/). Auth0 carries the audience in the authorize request rather than as a resource indicator, so it also requires this server's public URL as `serverUrl`. ## Example ```ts server.ts highlight={1,6-10} theme={null} import { auth0Provider, Skybridge } from "skybridge/server"; export const app = new Skybridge({ name: "personal-shopper", version: "0.0.1", oauth: auth0Provider({ domain: process.env.AUTH0_DOMAIN, audience: process.env.AUTH0_API_IDENTIFIER, serverUrl: process.env.SERVER_URL, }), handler, }); ``` ## Signature ```ts theme={null} auth0Provider(opts: Auth0ProviderOptions): Promise; ``` ## Parameters ### `opts` * **`domain`** is the tenant domain, for example `acme.us.auth0.com`. * **`audience`** is the API Identifier from the Auth0 dashboard, bound into the token's `aud` claim. * **`serverUrl`** is this server's public URL, required for Auth0. It also accepts the shared [`CustomProviderOptions`](/api-reference/custom-provider#parameters) options: `scopes`, `requiredScopes`, and `metadataOverrides`. Requires Dynamic Client Registration enabled on the tenant. ## Returns A `Promise` for the [`OAuthConfig`](/api-reference/custom-provider#returns) you pass to the [`oauth`](/api-reference/skybridge#oauth) field, as a value or from a function. > [card] [Connect an Identity Provider](/guides/auth-providers) > > Set up sign-in with a hosted provider > [card] [Authenticate Users](/build/auth) > > Add sign-in to your app end to end > [card] [customProvider](/api-reference/custom-provider) > > Wire OAuth from any IdP's discovery document # authplaneProvider Source: https://docs.skybridge.tech/api-reference/authplane-provider Wire OAuth from an Authplane authorization server `authplaneProvider` wires authentication through [Authplane](https://authplane.ai), so your tools receive a signed-in user. ## Example ```ts server.ts highlight={1,6-9} theme={null} import { authplaneProvider, Skybridge } from "skybridge/server"; export const app = new Skybridge({ name: "personal-shopper", version: "0.0.1", oauth: authplaneProvider({ issuer: process.env.AUTHPLANE_ISSUER, resource: process.env.SERVER_URL, }), handler, }); ``` ## Signature ```ts theme={null} authplaneProvider(opts: AuthplaneProviderOptions): Promise; ``` ## Parameters ### `opts` * **`issuer`** is the authorization server's issuer identifier, for example `https://auth.acme.com`. * **`resource`** is this server's resource identifier: the public URL clients reach, advertised in its protected-resource metadata. Required, unlike the other providers — see below. * **`audience`** overrides the expected `aud`, which defaults to `resource`. Set it only when the resource is configured in Authplane with an explicit audience override. It also accepts the shared [`CustomProviderOptions`](/api-reference/custom-provider#parameters) options: `serverUrl`, `scopes`, `requiredScopes`, and `metadataOverrides`. Dynamic Client Registration is supported natively, so clients register directly with Authplane and this server stays out of the authorization path. ## Why `resource` is required Authplane binds the access token's `aud` to the RFC 8707 resource indicator the client sends, and the client reads that value from the `resource` field of this server's protected-resource metadata. Setting `resource` gives the deployment one fixed identifier for both, so it is required rather than optional. Three values must therefore be identical, and OAuth compares identifiers by exact string match: 1. the value this server advertises as its `resource` metadata; 2. the resource registered in Authplane; 3. the `aud` Authplane mints, which it takes from (2). A mismatch between 1 and 2 fails the authorization request with `invalid_target`, before any token exists; between 1 and 3, token verification fails. Register `resource` in Authplane character for character and all three agree. ### Pathless origins The advertised resource is the URL-normalised form of `resource`, so a bare origin is advertised with a root path: `https://acme.example.com` is advertised as `https://acme.example.com/`. The provider asks for the advertised form up front, and names it if the two differ: ``` authplaneProvider: `resource` must be given in the form it will be advertised. "https://acme.example.com" is advertised as "https://acme.example.com/". Use "https://acme.example.com/", or a path-qualified URL such as "https://acme.example.com/mcp", and register the same value in Authplane. ``` So if your resource is a bare origin, register it in Authplane **with** the trailing slash. Uppercase hosts and explicit default ports normalise the same way. Path-qualified URLs are unchanged by normalisation, and are the most specific identifier available — which is what [RFC 8707 §2](https://www.rfc-editor.org/rfc/rfc8707#section-2) asks clients to send. ## Returns A `Promise` for the [`OAuthConfig`](/api-reference/custom-provider#returns) you pass to the [`oauth`](/api-reference/skybridge#oauth) field, as a value or from a function. > [card] [Connect an Identity Provider](/guides/auth-providers) > > Set up sign-in with a hosted provider > [card] [Authenticate Users](/build/auth) > > Add sign-in to your app end to end > [card] [customProvider](/api-reference/custom-provider) > > Wire OAuth from any IdP's discovery document # clerkProvider Source: https://docs.skybridge.tech/api-reference/clerk-provider Wire OAuth from a Clerk instance `clerkProvider` wires authentication through [Clerk](https://clerk.com/). Clerk access tokens carry no `aud` claim, so there is no `audience` option. ## Example ```ts server.ts highlight={1,6-8} theme={null} import { clerkProvider, Skybridge } from "skybridge/server"; export const app = new Skybridge({ name: "personal-shopper", version: "0.0.1", oauth: clerkProvider({ domain: process.env.CLERK_FRONTEND_API, }), handler, }); ``` ## Signature ```ts theme={null} clerkProvider(opts: ClerkProviderOptions): Promise; ``` ## Parameters ### `opts` **`domain`** is the Clerk Frontend API URL, for example `acme.clerk.accounts.dev` or a production custom domain. There is no `audience` option: Clerk binds no audience to its tokens. It also accepts the shared [`CustomProviderOptions`](/api-reference/custom-provider#parameters) options: `baseUrl`, `serverUrl`, `scopes`, `requiredScopes`, and `metadataOverrides`. Requires Dynamic Client Registration enabled on the instance, and the OAuth application set to issue JWT access tokens (opaque tokens can't be verified). ## Returns A `Promise` for the [`OAuthConfig`](/api-reference/custom-provider#returns) you pass to the [`oauth`](/api-reference/skybridge#oauth) field, as a value or from a function. > [card] [Connect an Identity Provider](/guides/auth-providers) > > Set up sign-in with a hosted provider > [card] [Authenticate Users](/build/auth) > > Add sign-in to your app end to end > [card] [customProvider](/api-reference/custom-provider) > > Wire OAuth from any IdP's discovery document # CLI Source: https://docs.skybridge.tech/api-reference/cli Test, build, and run your app from the terminal Skybridge ships one CLI, available as both `skybridge` and `sb` once it's installed in your project. It's a project dependency, not a global install, so run it through your package manager, or the [package scripts](#package-scripts) a scaffold sets up. ## `create` Scaffold a new project. Run it before the package is installed with `npx`: ```bash theme={null} npx skybridge create ``` See [Quickstart](/get-started/quickstart) to scaffold and run a project. ## `dev` Start the development server with hot module reloading and DevTools. ```bash npm theme={null} npx skybridge dev ``` ```bash pnpm theme={null} pnpm skybridge dev ``` ```bash yarn theme={null} yarn skybridge dev ``` ```bash bun theme={null} bun skybridge dev ``` ```bash deno theme={null} deno run -A npm:skybridge/skybridge dev ``` * Serves the MCP endpoint at `http://localhost:3000/mcp` * Opens DevTools for local testing at `http://localhost:3000/` * Watches files and restarts the server, with HMR for views | Flag | Description | | - | - | | `-p, --port ` | Port to run on. Defaults to `3000`, or the next free port if it's taken. | | `--tunnel` | Open an Alpic tunnel for remote testing and Playground access. | | `--no-open` | Don't open DevTools when the server is ready. | | `-v, --verbose` | Show tunnel logs. | | `--plain` | Disable the interactive UI and stream the server's stdout verbatim, so you can pipe it through a formatter (e.g. `skybridge dev --plain \| bunyan`). | The [scaffolded](/get-started/quickstart#scaffold-your-project) `package.json` adds a `dev:tunnel` script, shorthand for `skybridge dev --tunnel`. The port also reads from the `PORT` environment variable. Set `SKYBRIDGE_OPEN=false` in your shell profile to skip opening DevTools on every run, the equivalent of always passing `--no-open`. ### Formatting structured logs If your server uses a structured JSON logger like [bunyan](https://github.com/trentm/node-bunyan) or [pino](https://github.com/pinojs/pino), pass `--plain` and pipe through the logger's formatter: ```bash theme={null} skybridge dev --plain | bunyan skybridge dev --plain | pino-pretty ``` ## `build` Compile your views and MCP server for production. ```bash npm theme={null} npx skybridge build ``` ```bash pnpm theme={null} pnpm skybridge build ``` ```bash yarn theme={null} yarn skybridge build ``` ```bash bun theme={null} bun skybridge build ``` ```bash deno theme={null} deno run -A npm:skybridge/skybridge build ``` The output lands in `dist/`, ready for the `deploy` script or `skybridge start`. ### Excluding packages from the server bundle The build's last step bundles your server into a single deployable function with esbuild. Bundling means every reachable dependency has to be resolved, including ones your code never runs. Some packages break that step. A common case is a logger with an optional native dependency, like [bunyan](https://github.com/trentm/node-bunyan), which does `require('dtrace-provider')` inside a `try/catch`. You never use DTrace, but esbuild still tries to resolve it and fails on the native binding. List those packages in the Vite plugin's `serverExternal` to leave them out of the bundle: ```ts vite.config.ts theme={null} import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import { skybridge } from "@skybridge/vite-plugin"; export default defineConfig({ plugins: [react(), skybridge({ serverExternal: ["dtrace-provider"] })], }); ``` An external package stays a plain `import` in the output, resolved from `node_modules` at runtime. Only list packages your server doesn't need at runtime, or that your deployment target installs itself. ## `start` Run the production server from the build output. Run `skybridge build` first. ```bash npm theme={null} npx skybridge start ``` ```bash pnpm theme={null} pnpm skybridge start ``` ```bash yarn theme={null} yarn skybridge start ``` ```bash bun theme={null} bun skybridge start ``` ```bash deno theme={null} deno run -A npm:skybridge/skybridge start ``` * Serves the MCP endpoint at `http://localhost:3000/mcp` * Runs the compiled server and pre-built view assets from `dist/` | Flag | Description | | - | - | | `-p, --port ` | Port to run on. Defaults to `3000`, or the next free port if it's taken. Also reads `PORT`. | ## `telemetry` The CLI reports anonymous usage, on by default. Toggle it with `skybridge telemetry disable`, `enable`, or `status`. See [Telemetry](/resources/telemetry) for what's collected and every way to opt out. ## Package scripts A scaffolded project wires the commands into `package.json`: | Script | Command | Description | | - | - | - | | `dev` | `skybridge dev` | Start the development server. | | `dev:tunnel` | `skybridge dev --tunnel` | Start the dev server behind an Alpic tunnel. | | `build` | `skybridge build` | Build for production. | | `start` | `skybridge start` | Serve the production build. | | `deploy` | `alpic deploy` | Deploy through the Alpic CLI. See [Deploy](/ship/deploy) for per-platform setup. | Run them with your package manager: ```bash npm theme={null} npm run dev npm run build npm start ``` ```bash pnpm theme={null} pnpm dev pnpm build pnpm start ``` ```bash yarn theme={null} yarn dev yarn build yarn start ``` ```bash bun theme={null} bun dev bun build bun start ``` ```bash deno theme={null} deno task dev deno task build deno task start ``` > [card] [Quickstart](/get-started/quickstart) > > Scaffold and run your first app > [card] [Ship](/ship) > > Deploy to your platform of choice > [card] [McpServer](/api-reference/mcp-server) > > The server the CLI builds and runs # createStore Source: https://docs.skybridge.tech/api-reference/create-store Persist view state in a Zustand store `createStore` creates a [Zustand](https://github.com/pmndrs/zustand) store synced with the [view](/build/view)'s persisted [state](/build/state), on the same [lifecycle](/api-reference/use-view-state#lifecycle) as [`useViewState`](/api-reference/use-view-state). Reach for it when state is complex or shared across components; otherwise use `useViewState`. ## Example A counter store persists its `count` across remounts, and the view reads and updates it through the store hook. ```tsx highlight={8-11} theme={null} import { createStore } from "skybridge/web"; type CounterState = { count: number; increment: () => void; }; const useCounter = createStore((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), })); function Counter() { const { count, increment } = useCounter(); return ; } ``` ## Signature ```tsx theme={null} createStore( storeCreator: StateCreator, defaultState?: State | (() => State), ): UseBoundStore>; ``` ## Parameters ### `storeCreator` ```tsx theme={null} storeCreator: StateCreator; ``` The Zustand state creator, the standard `(set, get) => ({ ... })` returning the store's initial state and actions. ### `defaultState` ```tsx theme={null} defaultState?: State | (() => State); ``` Initial state, used only when the host holds no persisted state for this view. Pass a value or a lazy initializer that runs once. When the host already has persisted state, that value wins. ## Returns ```tsx theme={null} UseBoundStore>; ``` A Zustand store. Call it as a React hook with a selector (`useCounter((s) => s.count)`), or use `getState`, `setState`, and `subscribe` outside React. Store updates persist to the view's state, and external state changes rehydrate the store. > [card] [useViewState](/api-reference/use-view-state) > > The simpler hook this builds on, and its lifecycle > [card] [Manage State](/build/state) > > Decide what to persist and share with the model > [card] [DataLLM](/api-reference/data-llm) > > Narrate the on-screen state to the model # customProvider Source: https://docs.skybridge.tech/api-reference/custom-provider Wire OAuth from any IdP's discovery document `customProvider` builds a complete [`OAuthConfig`](#returns) from an identity provider's OAuth discovery document: it reads the provider's metadata at boot and verifies access tokens against its JWKS. Reach for it when no [branded provider](/api-reference/workos-provider) fits, for any IdP that publishes [discovery metadata](https://datatracker.ietf.org/doc/html/rfc8414) and signs JWT access tokens. ## Example ```ts server.ts highlight={1,6-11} theme={null} import { Skybridge, customProvider } from "skybridge/server"; export const app = new Skybridge({ name: "personal-shopper", version: "0.0.1", oauth: customProvider({ issuer: "https://auth.myshop.com", audience: process.env.SERVER_URL, scopes: ["openid", "profile", "checkout"], requiredScopes: ["openid"], }), handler, }); ``` `customProvider` fetches `https://auth.myshop.com`'s discovery document when the app starts, then the [`oauth`](/api-reference/skybridge#oauth) field mounts the well-known metadata and JWKS bearer verification on `/mcp`. `audience` is the value the IdP binds into the token's `aud` claim, here this server's public URL. ## Signature ```ts theme={null} customProvider(opts: CustomProviderOptions): Promise; ``` ## Parameters ### `opts` ```ts theme={null} type CustomProviderOptions = { issuer: string; audience?: string | string[]; baseUrl?: string; serverUrl?: string; scopes?: string[]; requiredScopes?: string[]; metadataOverrides?: Omit, "issuer">; }; ``` | Field | Description | | - | - | | `issuer` | The only required option: the IdP base URL whose discovery document is fetched at boot. It must serve a `jwks_uri`, or the call throws. | | `audience` | Checked against each token's `aud` claim. Pass several, say a local port and a dev tunnel URL, when the server is reached at more than one URL: a token passes when its `aud` matches any of them. Omit it only for an IdP that binds no audience (Clerk): the `aud` check is then skipped. | | `baseUrl` | This server's public URL. Set it and the resource URLs are baked once at boot; omit it and they resolve per request from the `x-forwarded-host` / `x-forwarded-proto` / `host` headers. | | `serverUrl` | Advertises this server as the authorization server: the served AS metadata `issuer` and the PRM `authorization_servers` use this URL instead of the IdP's, while verification still trusts the IdP's real `iss`. Needed when this server must sit in the auth path, as [`auth0Provider`](/api-reference/auth0-provider) does, or behind the Alpic DCR proxy. | | `scopes` | Scopes advertised in the served metadata; defaults to the IdP's. | | `requiredScopes` | Server-wide scope floor enforced before any handler, layered under each tool's [`securitySchemes`](/api-reference/register-tool#securityschemes); a token missing one gets a 403. | | `metadataOverrides` | Adjusts advertised metadata only. | ## Returns An `OAuthProvider`: a deferred `OAuthConfig` you pass to the [`oauth`](/api-reference/skybridge#oauth) field. Discovery is a network call, so it runs in `resolve()` at `run()`, not when your module is imported. Call `resolve()` yourself when wiring [`requireBearerAuth`](/api-reference/require-bearer-auth) by hand. ```ts theme={null} type OAuthProvider> = { resolve: () => Promise>; }; ``` ```ts theme={null} type OAuthConfig> = { baseUrl?: string; oauthMetadata: OAuthMetadata; scopesSupported?: string[]; requiredScopes?: string[]; verifier: TokenVerifier; }; ``` | Field | Description | | - | - | | `baseUrl` | Echoes the `baseUrl` option. | | `oauthMetadata` | AS metadata served at `/.well-known/oauth-authorization-server`. | | `verifier` | Checks each bearer token, and carries the claim type handlers receive. | | `scopesSupported` | Scopes advertised in protected-resource metadata. | | `requiredScopes` | Server-wide required-scope floor. | `TExtra` is the claim shape the verifier resolves with, and the server reads it from here, so handlers get `extra.http?.authInfo?.extra` typed without declaring anything. Pass it as a type argument to name claims your IdP sends: `customProvider<{ subject?: string; email?: string }>({ ... })`. Build this object by hand only to wire an IdP whose metadata `customProvider` can't discover. Supply a `verifier`, from `createJwksVerifier({ issuer, jwksUri })` for JWTs or your own [`TokenVerifier`](/api-reference/verifier) for opaque tokens. Either way the [`oauth`](/api-reference/skybridge#oauth) field mounts the same endpoints. > [card] [Connect an Identity Provider](/guides/auth-providers) > > Set up sign-in with a hosted provider > [card] [Authenticate Users](/build/auth) > > Add sign-in to your app end to end > [card] [Skybridge](/api-reference/skybridge) > > Pass the config to the oauth field # data-llm Source: https://docs.skybridge.tech/api-reference/data-llm Narrate the view's state to the model Between turns the model can't see what the user does in your [view](/build/view). The `data-llm` attribute narrates the view's current [state](/build/state) to the model, so on the next turn it can answer about what is on screen. ## Example The carousel tells the model whether the shopper is browsing or looking at one product, so a follow-up like "is this one in stock?" resolves to the right item. ```tsx views/carousel.tsx highlight={5} theme={null} function Carousel({ products }: { products: Product[] }) { const [selected, setSelected] = useState(null); return (
{selected ? ( ) : ( )}
); } ``` Put it on any element, with a static string or an expression recomputed on render. ## Behavior * Only the content currently on screen is sent. It is recomputed on every render and dropped when the element unmounts. * The text is model-visible, but not live: the host surfaces it to the model on the next turn, not mid-interaction. * Nested attributes form an indented outline. This: ```tsx theme={null}
{/* ... */}
``` reaches the model as: ``` - Reviewing the cart - 3 items, $240 ``` `data-llm` rides the same view state as [`useViewState`](/api-reference/use-view-state), so its [lifecycle](/api-reference/use-view-state#lifecycle) governs when and where the model sees it. > [card] [Manage State](/build/state) > > What to narrate, and what to leave out > [card] [useViewState](/api-reference/use-view-state) > > Persist structured state alongside the narration > [card] [useToolInfo](/api-reference/use-tool-info) > > Read the tool result the view mounted with # descopeProvider Source: https://docs.skybridge.tech/api-reference/descope-provider Wire OAuth from a Descope MCP Server `descopeProvider` wires authentication through a [Descope](https://www.descope.com/) MCP Server, so your tools receive a signed-in Descope user. ## Example ```ts server.ts highlight={1,6-8} theme={null} import { Skybridge, descopeProvider } from "skybridge/server"; export const app = new Skybridge({ name: "personal-shopper", version: "0.0.1", oauth: descopeProvider({ url: process.env.DESCOPE_DISCOVERY_URL, }), handler, }); ``` ## Signature ```ts theme={null} descopeProvider(opts: DescopeProviderOptions): Promise; ``` ## Parameters ### `opts` * **`url`** is the MCP Server's Discovery URL (its Issuer) from the console's Connection Information, for example `https://api.descope.com/v1/apps/agentic//`, or your custom domain. * **`audience`** defaults to the Project ID parsed from the `/agentic//` segment of `url` (Descope binds the token's `aud` to `[DCR client id, project id]`). If `url` lacks that segment, such as a custom domain, pass `audience` explicitly or the server throws at startup. It also accepts the shared [`CustomProviderOptions`](/api-reference/custom-provider#parameters) options: `baseUrl`, `serverUrl`, `scopes`, `requiredScopes`, and `metadataOverrides`. Requires Dynamic Client Registration enabled on the MCP Server. With DCR disabled and the Alpic DCR proxy, use [`customProvider`](/api-reference/custom-provider) with `serverUrl` instead. ## Returns A `Promise` for the [`OAuthConfig`](/api-reference/custom-provider#returns) you pass to the [`oauth`](/api-reference/skybridge#oauth) field, as a value or from a function. > [card] [Connect an Identity Provider](/guides/auth-providers) > > Set up sign-in with a hosted provider > [card] [Authenticate Users](/build/auth) > > Add sign-in to your app end to end > [card] [customProvider](/api-reference/custom-provider) > > Wire OAuth from any IdP's discovery document # FileRef Source: https://docs.skybridge.tech/api-reference/file-ref Reference a host-managed file in a tool's schema `FileRef` is a reference to a file, an id and a URL to fetch its bytes. Use it in a [tool's `inputSchema` or `outputSchema`](/api-reference/register-tool#inputschema-outputschema) to pass files in and out. > [!NOTE] > > File params are a **ChatGPT** feature. Other hosts don't pass files through [tool](/build/tools) calls, so a `FileRef` field is populated only on ChatGPT. ## Example `summarize-document` takes a file in, fetches its bytes from `download_url`, and returns a summary file back. ```ts server.ts highlight={10-11} theme={null} import { FileRef, Skybridge } from "skybridge/server"; export const app = new Skybridge({ name: "docs", version: "1.0", handler: (server) => server.registerTool( { name: "summarize-document", inputSchema: { document: FileRef }, outputSchema: { summary: FileRef }, _meta: { "openai/fileParams": ["document"] }, }, async ({ document }) => { const bytes = await fetch(document.download_url).then((r) => r.blob()); const summary = await summarize(bytes); // returns a FileRef return { structuredContent: { summary } }; }, ), }); ``` ## Shape ```ts theme={null} type FileRef = { file_id: string; download_url: string; mime_type?: string; file_name?: string; }; ``` | Field | Purpose | | - | - | | `file_id` | The host's identifier for the file. | | `download_url` | A URL to fetch the file's bytes. | | `mime_type` | The file's MIME type, when known. | | `file_name` | The original file name, when known. | `download_url` is required in both positions: on input the host fills it, on output your handler produces a URL the host can fetch. > [card] [Handle Files](/guides/files) > > Move files in and out of your app across hosts > [card] [useFiles](/api-reference/use-files) > > Upload, pick, and resolve files from the view > [card] [registerTool](/api-reference/register-tool) > > Declare file params with `openai/fileParams` # generateHelpers Source: https://docs.skybridge.tech/api-reference/generate-helpers Generate typed hooks inferred from your server Without it, [`useCallTool`](/api-reference/use-call-tool) and [`useToolInfo`](/api-reference/use-tool-info) need their [tool](/build/tools) types written by hand, duplicating your [server](/api-reference/mcp-server). `generateHelpers` infers them from your server type, so you import already-typed hooks. Set it up once and use the hooks across your views. ## Example `helpers.ts` wires your server type to the hooks; views import the typed hooks from it. ```ts helpers.ts theme={null} import type { AppType } from "./server"; // type-only import import { generateHelpers } from "skybridge/web"; export const { useCallTool, useToolInfo } = generateHelpers(); ``` ```tsx views/carousel.tsx theme={null} import { useCallTool, useToolInfo } from "../helpers.js"; function Carousel() { const { output } = useToolInfo<"search-products">(); // output typed from the tool const { callTool } = useCallTool("create-checkout"); // name autocompleted, input typed return ( ); } ``` ## Signature ```tsx theme={null} const { useCallTool, useToolInfo } = generateHelpers(); ``` ## Type Parameters ### `ServerType` ```tsx theme={null} ServerType extends McpServer; ``` Your app's type, `typeof app`. Export it from `src/server.ts` with `export type AppType = typeof app`, then pass it here. > [!NOTE] > > Inference works only when `handler` chains `.registerTool()` calls on the server it receives and returns the result, so the tool types accumulate on `typeof app`. ## Returns Two hooks. Both autocomplete tool names and infer types from `ServerType`, so you write no generics; their surface is otherwise identical to the untyped versions. ### `useCallTool` The typed [`useCallTool`](/api-reference/use-call-tool): the `name` argument autocompletes, and the input and output types follow the named tool. ### `useToolInfo` The typed [`useToolInfo`](/api-reference/use-tool-info): the tool name (its type argument) autocompletes, and `input`, `output`, and `responseMetadata` follow it. > [card] [useCallTool](/api-reference/use-call-tool) > > Call a tool from a view > [card] [useToolInfo](/api-reference/use-tool-info) > > Read the tool result the view mounted with > [card] [McpServer](/api-reference/mcp-server) > > The server whose type you infer from # mcpAuthMetadataRouter Source: https://docs.skybridge.tech/api-reference/mcp-auth-metadata-router Advertise your authorization server for client discovery When a client reaches your server without a token, it needs to know where the user signs in. `mcpAuthMetadataRouter` advertises that, so clients can discover your authorization server on their own. ## Example The server publishes where to authorize, so a client hitting a 401 can find the authorization server on its own. ```ts server.ts highlight={4-13} theme={null} import { Skybridge, mcpAuthMetadataRouter } from "skybridge/server"; export const app = new Skybridge({ name: "shop", version: "1.0", handler }).use( mcpAuthMetadataRouter({ oauthMetadata: { issuer: "https://auth.example.com", authorization_endpoint: "https://auth.example.com/authorize", token_endpoint: "https://auth.example.com/token", response_types_supported: ["code"], }, resourceServerUrl: new URL("https://api.example.com/mcp"), scopesSupported: ["shop.read"], }), ); ``` ## Signature ```ts theme={null} mcpAuthMetadataRouter(options: AuthMetadataOptions): Router; ``` ## Parameters ### `options` ```ts theme={null} type AuthMetadataOptions = { oauthMetadata: OAuthMetadata; resourceServerUrl: URL; scopesSupported?: string[]; serviceDocumentationUrl?: URL; resourceName?: string; }; ``` | Field | Purpose | | - | - | | `oauthMetadata` | Your authorization server's [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) metadata. At minimum the `issuer`, `authorization_endpoint`, `token_endpoint`, and `response_types_supported`. | | `resourceServerUrl` | This MCP server's URL. Published in the protected-resource metadata so clients map this server to its authorization server. | | `scopesSupported` | The scopes this server recognizes. | | `serviceDocumentationUrl` | Link to human-readable docs for this server. | | `resourceName` | Display name for this resource in the metadata. | > [!NOTE] > > Check your OAuth provider's docs for the metadata values it expects. ## Returns An [Express `Router`](https://expressjs.com/en/5x/api/router/) to pass to [`server.use`](/api-reference/mcp-server#use). It serves your OAuth 2.0 [Protected Resource Metadata](https://datatracker.ietf.org/doc/html/rfc9728) at `/.well-known/oauth-protected-resource`. > [card] [requireBearerAuth](/api-reference/require-bearer-auth) > > Require a token on every request > [card] [optionalBearerAuth](/api-reference/optional-bearer-auth) > > Accept a token when present, allow anonymous otherwise > [card] [Authenticate Users](/build/auth) > > Add sign-in to your app end to end # McpServer Source: https://docs.skybridge.tech/api-reference/mcp-server The server your handler registers tools on `McpServer` is the server instance a [`Skybridge`](/api-reference/skybridge) app hands to its `handler`, once per request. Its registration methods return the server itself, so you chain them and return the chain: that return value is what carries your tool types into `typeof app`. ## Example The handler registers two tools and a middleware, and returns the chain. ```ts src/server.ts theme={null} import { Skybridge } from "skybridge/server"; export const app = new Skybridge({ name: "shop", version: "1.0", handler: (server) => server .registerTool(/* search-products */) .registerTool(/* create-checkout */) .mcpMiddleware("request", (request, extra, next) => { console.log(`[MCP] ${request.method}`); return next(); }), }); ``` Define the handler inline, as above: that is what lets TypeScript infer the claims your `oauth` verifier produces into `extra.http.authInfo.extra`, and the tool registry into `typeof app`. Splitting the tool definitions across files is still easy, since each `registerTool` callback is an ordinary function you can import. > [!WARNING] > > The handler runs for every request, so anything in it other than registration runs per request too. Move one-time work (a pool, a client, a file read) into [`setup`](/api-reference/skybridge#setup), whose result is the handler's second argument. ## Methods Every method returns the server, so calls chain. ### `registerTool` ```ts theme={null} server.registerTool(config, handler): this; ``` Registers a tool, optionally bound to a view. See [registerTool](/api-reference/register-tool) for the full config and handler. ### `registerMentions` ```ts theme={null} server.registerMentions(config): this; ``` Registers the ChatGPT composer at-mention search. See [registerMentions](/api-reference/register-mentions). ### `registerEvent` ```ts theme={null} server.registerEvent(config, hooks): this; ``` Declares an event type hosts can subscribe to, and hands each subscription to your hooks. Experimental. See [registerEvent](/api-reference/register-event). ### `registerFileViewer` ```ts theme={null} server.registerFileViewer(config, handler): this; ``` Registers a ChatGPT desktop file viewer. See [registerFileViewer](/api-reference/register-file-viewer). ### `registerSettings` ```ts theme={null} server.registerSettings(config): this; ``` Registers your app's settings page in ChatGPT. See [registerSettings](/api-reference/register-settings). ### `registerResource`, `registerPrompt` Inherited from the MCP SDK's [`McpServer`](https://github.com/modelcontextprotocol/typescript-sdk), with the same signatures. Views register their own resources, so you only need `registerResource` for data you expose directly. ### `mcpMiddleware` ```ts theme={null} server.mcpMiddleware(handler: McpMiddlewareFn): this; server.mcpMiddleware(filter: McpMiddlewareFilter, handler: McpMiddlewareFn): this; ``` Wraps MCP requests and notifications: each middleware runs `(request, extra, next)`, can inspect or short-circuit the call, and invokes `next()` to continue. Middleware runs in registration order, outermost first. An optional `filter` scopes which methods it runs for. | Filter | Matches | | - | - | | `"tools/call"` | that exact method | | `"tools/*"` | any method under `tools/` | | `"request"` | all requests | | `"notification"` | all notifications | | `["tools/call", "resources/read"]` | any pattern in the list | ```ts theme={null} server.mcpMiddleware("request", (request, extra, next) => { console.log(`[MCP] ${request.method}`, request.params); return next(); }); ``` ### `getToolError` ```ts theme={null} import { getToolError } from "skybridge/server"; getToolError(extra: McpExtra | undefined): unknown; ``` The MCP SDK catches whatever a tool handler throws and turns it into an `isError` tool result, so `await next()` resolves normally and the middleware never sees the failure. `getToolError` returns the error the tool handler threw during the current request, with its stack and `cause` intact. It lives on `extra`, which is never serialized to the client. ```ts theme={null} server.mcpMiddleware("tools/call", async (request, extra, next) => { const result = await next(); const error = getToolError(extra); if (error) { Sentry.captureException(error); } return result; }); ``` A tool failure is a valid MCP response, so [`useOnError`](/api-reference/skybridge#useonerror) never runs for it: report tool errors from `mcpMiddleware`, and keep `useOnError` for transport-level failures. Errors raised by the SDK itself (unknown tool, input or output schema validation) never reach your handler and are not reported here. Requests that the SDK rejects before any tool runs, and failures to build the per-request server, go to [`onMcpError`](/api-reference/skybridge#onmcperror) when you set it, and to `console.error` otherwise. > [card] [Skybridge](/api-reference/skybridge) > > Configure and run the app that builds this server > [card] [registerTool](/api-reference/register-tool) > > Define the tools and views the server exposes > [card] [generateHelpers](/api-reference/generate-helpers) > > Turn `AppType` into typed client hooks # optionalBearerAuth Source: https://docs.skybridge.tech/api-reference/optional-bearer-auth Accept a signed-in user when present, allow anonymous otherwise When some [tools](/build/tools) are public and others need sign-in, `optionalBearerAuth` validates a token if one is sent but lets anonymous requests through. Each tool then enforces its own [`securitySchemes`](/api-reference/register-tool#securityschemes) against `extra.http?.authInfo`. ## Example The server accepts a token when one is sent, so public tools run for anyone while gated tools check `extra.http?.authInfo` themselves. ```ts server.ts highlight={6} theme={null} import { Skybridge, optionalBearerAuth } from "skybridge/server"; import { verifyAccessToken } from "./verify-access-token.js"; // the verifier you implement export const app = new Skybridge({ name: "shop", version: "1.0", handler }).use( "/mcp", optionalBearerAuth({ verifier: { verifyAccessToken } }), ); ``` ## Signature ```ts theme={null} optionalBearerAuth(options: BearerAuthMiddlewareOptions): RequestHandler; ``` ## Parameters ### `options` ```ts theme={null} type BearerAuthMiddlewareOptions = { verifier: OAuthTokenVerifier; requiredScopes?: string[]; resourceMetadataUrl?: string; }; ``` | Field | Purpose | | - | - | | `verifier` | The provider-specific token check you write. See [Verifier](/api-reference/verifier). | | `requiredScopes` | A scope floor, enforced only when a token is sent: the token must carry all of these, or the request gets a 403. | | `resourceMetadataUrl` | Absolute URL appended to the `WWW-Authenticate` header on a 401, pointing at your OAuth 2.0 [Protected Resource Metadata](https://datatracker.ietf.org/doc/html/rfc9728) so clients can discover the authorization server. | ## Returns An [Express `RequestHandler`](https://expressjs.com/en/5x/guide/routing/) to pass to [`server.use`](/api-reference/mcp-server#use), typically on `/mcp`. * No `Authorization` header: the request proceeds with no `authInfo`. * A valid token: the request proceeds, and [handlers](/api-reference/register-tool#handler) read it from `extra.http?.authInfo`. * A token that is present but invalid or expired: the same 401 / 403 as [`requireBearerAuth`](/api-reference/require-bearer-auth). Sending a bad token is still a client error. > [card] [requireBearerAuth](/api-reference/require-bearer-auth) > > Require a token on every request, with the verifier contract > [card] [registerTool](/api-reference/register-tool) > > Gate individual tools with `securitySchemes` > [card] [Authenticate Users](/build/auth) > > Add sign-in to your app end to end # Overview Source: https://docs.skybridge.tech/api-reference/overview Every server API, hook, and utility, with host compatibility. Every Skybridge export. Server APIs run in your MCP server and work with any host. [View](/build/view) hooks run inside the rendered view, where a host that lacks a capability degrades gracefully, either a no-op or a thrown error documented on the hook's page. ## Server | API | Description | | - | - | | [`mcpAuthMetadataRouter`](/api-reference/mcp-auth-metadata-router) | Serve OAuth metadata for client discovery. | | [`McpServer`](/api-reference/mcp-server) | The per-request server your handler registers tools on. | | [`optionalBearerAuth`](/api-reference/optional-bearer-auth) | Attach a verified identity when a token is present. | | [`registerTool`](/api-reference/register-tool) | Register a tool, its schemas, and the view it renders. | | [`requireBearerAuth`](/api-reference/require-bearer-auth) | Gate a server behind a verified bearer token. | | [`Skybridge`](/api-reference/skybridge) | The app: its config, OAuth, and the handler that registers tools. | ## Hooks | Hook | Description | Supported Hosts | | - | - | - | | [`useCallTool`](/api-reference/use-call-tool) | Call server tools from the view and track call state. | | | [`useDisplayMode`](/api-reference/use-display-mode) | Read and request inline, pip, or fullscreen. | | | [`useDownload`](/api-reference/use-download) | Save files to the user's device. | | | [`useFiles`](/api-reference/use-files) | Upload and pick host-managed files. | | | [`useHost`](/api-reference/use-host) | Identify which host is rendering the view. | | | [`useOpenExternal`](/api-reference/use-open-external) | Open a URL outside the view iframe. | | | [`useRegisterViewTool`](/api-reference/use-register-view-tool) | Expose a tool that runs inside the view. | | | [`useRequestClose`](/api-reference/use-request-close) | Ask the host to dismiss the view. | | | [`useRequestModal`](/api-reference/use-request-modal) | Open the view as a host modal. | | | [`useRequestSize`](/api-reference/use-request-size) | Ask the host to resize the view iframe. | | | [`useSendFollowUpMessage`](/api-reference/use-send-follow-up-message) | Send a follow-up turn to the model. | | | [`useSetOpenInAppUrl`](/api-reference/use-set-open-in-app-url) | Override the fullscreen open-in-app URL. | | | [`useToolInfo`](/api-reference/use-tool-info) | Read the tool input, output, and metadata that rendered the view. | | | [`useUser`](/api-reference/use-user) | Read locale, theme, and device capabilities. | | | [`useViewState`](/api-reference/use-view-state) | Persist UI state on the host across renders. | | | [`useViewport`](/api-reference/use-viewport) | Read the max height and safe-area insets. | | ## Utilities | Utility | Description | | - | - | | [`createStore`](/api-reference/create-store) | A Zustand store synced with host view state. | | [`data-llm`](/api-reference/data-llm) | Describe on-screen state to the model in words. | | [`generateHelpers`](/api-reference/generate-helpers) | Generate typed hooks inferred from your server. | ## Types | Type | Description | | - | - | | [`FileRef`](/api-reference/file-ref) | Reference a host-managed file in a tool schema. | | [Type Utilities](/api-reference/utility-types) | Pull tool input, output, and name types from your server. | ## Low-level | Hook | Description | | - | - | | [`useAppsSdkContext`](/api-reference/use-apps-sdk-context) | Read a raw ChatGPT (`window.openai`) context value by key. | | [`useMcpAppContext`](/api-reference/use-mcp-app-context) | Read a raw MCP Apps context value by key. | > [card] [Quickstart](/get-started/quickstart) > > Scaffold and run your first app > [card] [Build Tools](/build/tools) > > Register the tools these APIs call > [card] [ChatGPT Plugins and MCP Apps](/resources/chatgpt-and-mcp-apps) > > How the two runtimes differ and what's unified # registerEvent Source: https://docs.skybridge.tech/api-reference/register-event Let the host subscribe to things that happen in your app and react without the user > [!WARNING] > > MCP Events is a draft from the MCP [Triggers & Events working group](https://github.com/modelcontextprotocol/experimental-ext-triggers-events), not part of the MCP specification yet. The feature is **experimental** and may change with the draft. ChatGPT is the only host that supports it today, through webhooks, in Work chats. Tools only run when the model calls them. Events go the other way: the user asks ChatGPT to watch for something ("tell me when someone comments on this doc, and draft a reply"), ChatGPT subscribes to one of your event types with a callback URL, and every time a matching event is POSTed to that URL, ChatGPT runs the user's instructions in that chat. `registerEvent` handles the subscription side of the protocol. Skybridge lists your event types, checks who is subscribing and with which arguments, verifies the callback URL, and then hands the subscription to your `onSubscribe` hook. Delivering the events is up to whatever already knows when they happen, usually your backend's webhook system. [`deliverEvent`](#deliverevent) does the delivery for you when that system runs on Node. ## Example A document app lets users subscribe to new comments on one document. Its backend already sends webhooks, so `onSubscribe` registers ChatGPT's callback there. ```ts theme={null} export const app = new Skybridge({ name: "docs", version: "1.0.0", oauth: workosProvider({ ... }), handler: (server) => server.registerEvent( { name: "comment.created", description: "Fires when someone comments on a document", inputSchema: { documentId: z.string() }, payloadSchema: { documentId: z.string(), commentId: z.string(), excerpt: z.string(), }, }, { onSubscribe: async ({ documentId }, { subscription, extra }) => { const userId = extra.http?.authInfo?.extra?.subject; await assertCanRead(userId, documentId); await api.upsertWebhook({ id: subscription.id, url: subscription.url, signingSecret: subscription.secret, expiresAt: subscription.expiresAt, event: "comment.created", filter: { documentId }, }); }, onUnsubscribe: async (_args, { subscription }) => { await api.deleteWebhook(subscription.id); }, }, ), }); ``` ## Parameters ### `config` | Field | Purpose | | - | - | | `name` | Stable, specific event name such as `comment.created`. | | `description` | What the event is and when it fires. The model reads it to decide what to subscribe to. | | `inputSchema` | Subscription arguments, usually filters. A Zod shape or a Standard Schema object, like a tool's `inputSchema`. | | `payloadSchema` | Shape of the delivered `data`, listed so the host knows what to expect. | | `_meta` | Optional metadata listed with the event. | ### `hooks` | Field | Purpose | | - | - | | `onSubscribe` | Runs on every subscribe, including the host's periodic refreshes, once the callback URL is verified. Receives the validated arguments and `{ subscription, extra }`. Store or update the subscription by `subscription.id`. Throw to reject it, for example when the user may not access the document. | | `onUnsubscribe` | Runs when the host unsubscribes, with the arguments and `{ subscription: { id }, extra }`. Stop delivering to that `id`: Skybridge keeps no subscriptions, so this hook is the only way the cancellation reaches your delivery side. | `subscription` carries: | Field | Purpose | | - | - | | `id` | Identifies the subscription and stays the same on every refresh, so use it as your idempotency key. The same user subscribing to the same event with the same arguments and callback URL always gets the same `id`; two users get separate ones. | | `url` | Where to POST the events. | | `secret` | The signing secret the host chose. A refresh may bring a new one; sign with both the old and the new one for a few minutes. | | `expiresAt` | When the subscription lapses. The host refreshes it before then, which calls `onSubscribe` again with a later date. Stop delivering after it. | ### Refreshes Subscriptions are short-lived. The `events/subscribe` response tells the host to subscribe again before `expiresAt`, and the host keeps the subscription alive by sending the same request again. Skybridge keeps no state, so a refresh looks exactly like a first subscribe: `onSubscribe` runs again with the same `subscription.id` and a later `expiresAt`, and possibly a new `secret`. Write `onSubscribe` as an upsert keyed on `subscription.id`: create the webhook the first time you see the `id`, then update its `expiresAt` and `secret`. If your webhook system can't expire webhooks, store `expiresAt` next to the webhook and stop delivering once it has passed. [`deliverEvent`](#deliverevent) already refuses to post to an expired subscription. `extra` is the same as in a [`registerTool`](/api-reference/register-tool) handler: `extra.http.authInfo` tells you who is subscribing. Returns the server, so calls chain. ## `deliverEvent` ```ts theme={null} import { deliverEvent } from "skybridge/server"; const result = await deliverEvent(subscription, { name: "comment.created", id: comment.id, data: { documentId, commentId: comment.id, excerpt }, }); if (!result.ok && result.retryable) { await queue.retryLater(subscription, comment); } ``` POSTs one event to a subscription the way MCP Events expects: the event envelope, [Standard Webhooks](https://www.standardwebhooks.com/) signature headers and a 10 second deadline. Outside development it refuses to connect to private addresses. Pass the upstream's own identifier as `id` so the host can drop duplicates, and reuse it when retrying. Pass `secret` as an array to sign with several secrets during a rotation. A subscription past its `expiresAt` is not posted to and returns `{ ok: false, reason: "expired", retryable: false }`. Otherwise it makes one attempt and returns `{ ok: true }` or `{ ok: false, reason, retryable, status }`, where `status` is the HTTP status when the host answered. A `410` or `413` is not retryable. Retrying is up to you. ## How it works ```mermaid theme={null} sequenceDiagram participant Host as ChatGPT participant App as Skybridge app participant Backend as Your backend Host->>App: events/subscribe {name, arguments, url, secret} App->>Host: POST verification challenge Host-->>App: echoes the challenge App->>Backend: onSubscribe(subscription) App-->>Host: {id, refreshBefore} Note over Backend: later, a comment is created Backend->>Host: signed POST {eventId, name, timestamp, data} Host->>App: events/subscribe again before refreshBefore ``` * Subscribing requires a signed-in user: set [`oauth`](/api-reference/skybridge#oauth). * Callback URLs must be `https` and resolve to public addresses. Unless `NODE_ENV` is `production`, `http` and local addresses are allowed so you can test with a local receiver. `skybridge start` sets `NODE_ENV=production`; set it yourself if you run the server another way. * Subscriptions last 30 minutes unless the host asks for another lifetime, at most 24 hours. * Payloads are capped at 256 KiB. Send a summary and let the model fetch the rest with a tool. * Events are not replayed: an event sent while a subscription has lapsed is lost. > [card] [registerTool](/api-reference/register-tool) > > Tools the model calls, and the `extra` they receive > [card] [McpServer](/api-reference/mcp-server) > > Every method of the server # registerFileViewer Source: https://docs.skybridge.tech/api-reference/register-file-viewer Open files with your app in ChatGPT desktop > [!NOTE] > > This is an [OpenAI MCP extension](https://github.com/openai/mcp-extensions/blob/main/docs/spec.md), not part of MCP or MCP Apps. Only **ChatGPT** desktop opens files with it. Other hosts ignore the entrypoint and list a regular tool with a required `file` input. `registerFileViewer` makes your app a viewer for some file types in ChatGPT desktop. When the user opens a file with one of these extensions through your app, ChatGPT calls the tool with that file and shows its [view](/build/view), where [`useFileResource`](/api-reference/use-file-resource) reads and saves the file. ## Example ```ts theme={null} server.registerFileViewer( { name: "part-viewer", title: "Part Viewer", description: "Open a CAD part.", extensions: [".stl", ".step"], icons: [{ src: "https://example.com/part.svg", mimeType: "image/svg+xml" }], view: { component: "part-viewer" }, }, async ({ file }) => ({ structuredContent: { name: file.name } }), ); ``` ## Parameters ### `config` The same as [`registerTool`](/api-reference/register-tool)'s config, without `inputSchema`, plus: | Field | Purpose | | - | - | | `extensions` | File extensions the viewer opens, each starting with `.`. | | `view` | **Required.** The view that shows the file. | | `openai` | Display modes, as in [`registerTool`](/api-reference/register-tool#openai). The file entrypoint is set from `extensions`. | ### `handler` Receives `{ file: { name, resourceUri } }`: the file's name, and an opaque URI the view passes to [`useFileResource`](/api-reference/use-file-resource). ChatGPT never gives the view the file's path. Tools the view calls receive it in [`_meta["openai/resource"].path`](/api-reference/register-tool#client-hints). ## How it works `registerFileViewer` is a shortcut for [`registerTool`](/api-reference/register-tool) with a required `file` input and `openai.entrypoints: [{ type: "file", extensions }]`. It returns the typed server like `registerTool`, so the view can read `input.file` with type safety. > [card] [useFileResource](/api-reference/use-file-resource) > > Read, watch and save the opened file > [card] [registerTool](/api-reference/register-tool#openai) > > Every ChatGPT entrypoint # registerMentions Source: https://docs.skybridge.tech/api-reference/register-mentions Let users at-mention your app's items in the ChatGPT composer > [!NOTE] > > This is an [OpenAI MCP extension](https://github.com/openai/mcp-extensions/blob/main/docs/spec.md), not part of MCP or MCP Apps. Only **ChatGPT** supports it, and other hosts ignore it. By default, users can only at-mention your app as a whole. `registerMentions` lets them mention individual items, such as parts, files or people: when the user types `@` and your app, ChatGPT calls your handler with the text typed so far and lists the items it returns. ChatGPT desktop only. ## Example A parts catalog lets the user mention a part by name. ```ts theme={null} server.registerMentions({ name: "search_parts", handler: async ({ query }) => ({ items: (await findParts(query)).map((part) => ({ type: "resource_link", uri: `parts://${part.id}`, name: part.name, })), }), }); ``` ## Parameters ### `config` ```ts theme={null} type OpenAIMentionsConfig = { name: string; description?: string; handler: ( params: { query: string }, extra: ToolHandlerExtra, ) => { items: ResourceLink[] } | Promise<{ items: ResourceLink[] }>; }; ``` | Field | Purpose | | - | - | | `name` | Name of the tool ChatGPT calls for each search. | | `description` | Tool description. Defaults to a generic one, since the model never sees this tool. | | `handler` | Receives the typed text as `query`, which may be empty, and returns the matching items as MCP resource links. `extra` is the same as in a [`registerTool`](/api-reference/register-tool) handler. | ## How it works Skybridge registers a tool named `name` that takes `{ query: string }` and returns `{ items }` as `structuredContent`. Its `_meta` carries `"openai/extensions": { "mentions/search": {} }`, which tells ChatGPT it serves mentions, and `ui.visibility: ["app"]`, which hides it from the model. It requires sign-in like any other tool on a server with [`oauth`](/api-reference/skybridge#oauth). Returns the server, so calls chain. ## Serve the mentioned items When the user picks an item, its resource link goes into the message, so the model gets the `uri` rather than the item itself. Serve those URIs as MCP resources so the host can read them: ```ts theme={null} import { ResourceTemplate } from "skybridge/server"; server.registerResource( "part", new ResourceTemplate("parts://{id}", { list: undefined }), { mimeType: "application/json" }, async (uri, { id }) => ({ contents: [{ uri: uri.href, text: JSON.stringify(await getPart(String(id))) }], }), ); ``` > [card] [registerTool](/api-reference/register-tool) > > Register tools and their ChatGPT entrypoints > [card] [McpServer](/api-reference/mcp-server) > > Every method of the server # registerSettings Source: https://docs.skybridge.tech/api-reference/register-settings Give your app a settings page in ChatGPT > [!NOTE] > > This is an [OpenAI MCP extension](https://github.com/openai/mcp-extensions/blob/main/docs/spec.md#structured-settings), not part of MCP or MCP Apps. Only **ChatGPT** shows the settings page. Other hosts list the two settings tools like any other tool. `registerSettings` adds a page for your app in ChatGPT's app settings. You declare the fields, and ChatGPT renders the form, reads the current values and sends back what the user changed. ## Example A CAD app lets users pick their units and zoom level, and adds a button that opens a parts browser. ```ts theme={null} server.registerSettings({ fields: { units: { title: "Units", schema: z.enum(["mm", "in"]) }, showGrid: { title: "Show grid", schema: z.boolean() }, zoom: { title: "Zoom", description: "Default zoom level of the viewer", schema: z.number().int().min(1).max(10), }, }, layout: [ { kind: "group", title: "Display", items: [ { kind: "property", property: "units" }, { kind: "property", property: "zoom" }, { kind: "tool", tool: "browse-parts", title: "Browse parts" }, ], }, ], read: (extra) => loadSettings(extra), update: (set, extra) => saveSettings(set, extra), }); ``` ## Parameters ### `config` ```ts theme={null} type OpenAISettingsConfig = { fields: TFields; layout?: { kind: "group"; title: string; items: ( | { kind: "property"; property: keyof TFields } | { kind: "tool"; tool: string; title: string; description?: string } )[]; }[]; read: (extra: ToolHandlerExtra) => Values | Promise; update: (set: Partial, extra: ToolHandlerExtra) => Values | Promise; readTool?: string; updateTool?: string; }; type Values = OpenAISettingsValues; ``` | Field | Purpose | | - | - | | `fields` | The settings, by name, each with a zod `schema`, a `title` and an optional `description`. A schema is a boolean, string, string enum, number or integer. The spec defines the `min`, `max`, `length`, `regex` and `multipleOf` constraints for the form. Other constraints, such as `positive()`, may be ignored by ChatGPT, and every constraint is checked when the update arrives. | | `layout` | Sections of the settings page. A `property` item shows a field, and a `tool` item shows a button that calls another tool on your server with `{}`. A tool with a view opens it in a modal. Any other tool shows a spinner, then the text `content` it returns. Fields left out of the layout appear under "Other settings". | | `read` | Returns the current value of every field. | | `update` | Receives only the fields the user changed, saves them, and returns the value of every field. | | `readTool`, `updateTool` | Names of the two tools. Default to `settings.read` and `settings.update`. | Your server stores the values. `extra` is the same as in a [`registerTool`](/api-reference/register-tool) handler, so `read` and `update` can store them per user when the server uses [`oauth`](/api-reference/skybridge#oauth). `OpenAISettingsValues` types those functions when you declare them apart. ## How it works Skybridge registers two tools and advertises them in the `openai/settings` server capability. The read tool takes no input, is marked read-only and returns `{ schema, values, layout }`, where `schema` is the JSON Schema built from `fields`. The update tool takes `{ set }`, with at least one field, and returns `{ values }`. Both check the values your handlers return against the field schemas. Skybridge throws at startup when a field has another type or declares a default, and when `layout` names an unknown field or the same field twice. Defaults belong in `read`, since ChatGPT shows the values it returns. Returns the server, so calls chain. > [card] [registerTool](/api-reference/register-tool#openai) > > Open a view from ChatGPT's settings with a `settings` entrypoint > [card] [McpServer](/api-reference/mcp-server) > > Every method of the server # registerTool Source: https://docs.skybridge.tech/api-reference/register-tool Register a tool, with or without a view `registerTool` adds an action the model can call to your server, optionally rendering its result through a [view](#view). ## Example `search-products` searches the store catalog for the signed-in user and renders the matches in the `carousel` view. ```ts server.ts theme={null} import { Skybridge } from "skybridge/server"; import { z } from "zod"; export const app = new Skybridge({ name: "shop", version: "1.0", handler: (server) => server.registerTool( { name: "search-products", title: "Search products", description: "Search the store catalog by keyword and optional price ceiling.", inputSchema: { query: z.string().describe("What the shopper is looking for"), }, outputSchema: { productIds: z.array(z.string()).describe("The IDs of products matching the query."), }, annotations: { readOnlyHint: true }, securitySchemes: [{ type: "oauth2", scopes: ["catalog.read"] }], view: { component: "carousel", csp: { connectDomains: ["https://api.myshop.com"] }, }, }, async ({ query, maxPrice }, extra) => { const userId = extra.http?.authInfo?.extra?.subject; const products = await search(query, { maxPrice, userId }); return { content: `Found ${products.length} products for "${query}".`, structuredContent: { products }, }; }, ), }); ``` ## Signature ```ts theme={null} server.registerTool(config: ToolConfig, handler: ToolHandler): McpServer; ``` ## Config The first argument declares the tool. ```ts theme={null} type ToolConfig = { name: string; title?: string; // human-readable label description?: string; // model-facing: decides when the model calls the tool inputSchema?: Record; // validates the call and types the handler input outputSchema?: Record; // types structuredContent annotations?: ToolAnnotations; // standard MCP hints icons?: Icon[]; view?: ViewConfig; // bind a view to render the result openai?: OpenAIToolConfig; auth?: { allowsAnonymous?: boolean; scopes?: string[] }; // per-tool auth securitySchemes?: SecurityScheme[]; // low-level alternative to `auth` (mutually exclusive) _meta?: ToolMeta; // extra metadata }; ``` ### `name`, `title`, `description` All three are the tool's prompt surface: the model reads them to decide when to call it, so write each for the model. `name` is also the identifier the call uses, and `title` a short display name. ### `icons` The tool's icons, a standard MCP field using the `Icon` type (`src`, `mimeType`, `sizes`, `theme`). Hosts choose whether and where to show them. **ChatGPT** asks for them on every tool with an [entrypoint](#openai), as a monochrome SVG on a 20x20 viewport that draws with `currentColor`. Without them it falls back to the server's [`icons`](/api-reference/skybridge#name-version) for a local server, or to the logo registered with OpenAI for a hosted app. ### `inputSchema`, `outputSchema` Shapes of [Standard Schema](https://standardschema.dev) validators that can emit JSON Schema: [Zod](https://zod.dev/) 4.2+ and ArkType out of the box, valibot through `@valibot/to-json-schema`. `inputSchema` validates the call arguments and types the handler's `input`. Add `.describe()` to a field to tell the model what it's for. `outputSchema` tells the model the shape to expect back, it does not type the returned value. ### `annotations` Standard MCP hints describing what the tool does, so the host can label it and order calls. They are hints: the host may surface or ignore them, and never gates a call on them. ```ts theme={null} type ToolAnnotations = { title?: string; readOnlyHint?: boolean; destructiveHint?: boolean; idempotentHint?: boolean; openWorldHint?: boolean; }; ``` | Hint | Meaning | Default | | - | - | - | | `title` | Human-readable label; the host gives it precedence over `name`. | none | | `readOnlyHint` | The tool does not modify its environment. | `false` | | `destructiveHint` | The tool may perform destructive updates, not only additive ones. Meaningful only when `readOnlyHint` is `false`. | `true` | | `idempotentHint` | Repeating the call with the same arguments has no further effect. Meaningful only when `readOnlyHint` is `false`. | `false` | | `openWorldHint` | The tool interacts with an open world of external entities, not a closed domain. | `true` | ### `view` Bind the tool to a React view to render its result instead of plain text. Each view backs exactly one tool. ```ts theme={null} type ViewConfig = { component: ViewName; description?: string; hosts?: Array<"apps-sdk" | "mcp-app">; prefersBorder?: boolean; domain?: string; csp?: ViewCsp; _meta?: Record; }; ``` | Key | Purpose | | - | - | | `component` | The view's file name, type-checked against your views. | | `description` | Label the host may show during view discovery. | | `hosts` | Restrict where the view renders; defaults to all. | | `prefersBorder` | ChatGPT only: request a visible border around the view. | | `domain` | ChatGPT only: override the served domain (advanced). | | [`csp`](/api-reference/register-tool#csp) | Per-view CSP overrides; see below. | | `_meta` | Free-form metadata forwarded on the view resource. | #### `csp` A view runs in a sandboxed iframe; your server's domain is allowlisted automatically. Add external origins per directive: ```ts theme={null} type ViewCsp = { resourceDomains?: string[]; connectDomains?: string[]; frameDomains?: string[]; redirectDomains?: string[]; baseUriDomains?: string[]; }; ``` | Directive | Purpose | | - | - | | `resourceDomains` | Static assets: images, fonts, scripts, styles. | | `connectDomains` | Fetch / XHR targets. | | `frameDomains` | Iframe embed origins (opts into stricter plugin review). | | `redirectDomains` | `openExternal` targets that skip the safe-link modal. | | `baseUriDomains` | `` origins (MCP Apps only). | ### `openai` > [!NOTE] > > This is an [OpenAI MCP extension](https://github.com/openai/mcp-extensions/blob/main/docs/spec.md), not part of MCP or MCP Apps. Only **ChatGPT** supports it, and other hosts ignore it. The options need a [`view`](#view): Skybridge writes them to `_meta["openai/ui"]` on the tool and on its view resource, and throws at startup when the tool has no view. ```ts theme={null} type OpenAIToolConfig = { entrypoints?: OpenAIEntrypoint[]; availableDisplayModes?: Array<"inline" | "fullscreen">; preferredDisplayMode?: "inline" | "fullscreen"; preferredModelDisplayMode?: "inline" | "fullscreen"; }; type OpenAIEntrypoint = | { type: "global"; quickAction?: OpenAIQuickAction } | { type: "thread" } | { type: "file"; extensions: string[] } | { type: "settings"; searchTerms?: string[] }; ``` A sidebar entry and a conversation tab call the tool without arguments, so it takes no required input: ```ts theme={null} server.registerTool( { name: "library", title: "Parts Library", description: "Browse the parts catalog.", icons: [{ src: "https://example.com/library.svg", mimeType: "image/svg+xml" }], view: { component: "library" }, openai: { entrypoints: [{ type: "global" }, { type: "thread" }], availableDisplayModes: ["inline", "fullscreen"], }, }, async () => ({ structuredContent: { parts: await listParts() } }), ); ``` A file entrypoint calls the tool with the file the user opened, so it gets its own tool with a required `file` input. [`registerFileViewer`](/api-reference/register-file-viewer) is a shortcut for this: ```ts theme={null} server.registerTool( { name: "part-viewer", title: "Part Viewer", description: "Open a CAD part.", inputSchema: { file: z.object({ name: z.string(), resourceUri: z.string() }), }, icons: [{ src: "https://example.com/part.svg", mimeType: "image/svg+xml" }], view: { component: "part-viewer" }, openai: { entrypoints: [{ type: "file", extensions: [".stl", ".step"] }] }, }, async ({ file }) => ({ structuredContent: { name: file.name } }), ); ``` | Field | Purpose | | - | - | | `entrypoints` | Places users open the view from without the model: `global` adds a sidebar entry, `thread` a tab in a conversation's side panel, `file` a viewer for files with these extensions, `settings` an entry in the plugin settings. A global entry can carry a `quickAction`, a sidebar shortcut that calls another tool. Extensions must start with `.`. | | `availableDisplayModes` | Display modes the view supports, read before the view loads. | | `preferredDisplayMode` | Display mode the view prefers to open in. ChatGPT may ignore it. | | `preferredModelDisplayMode` | Display mode the view opens in first when the model calls the tool. | Every field is optional, and Skybridge only emits what you set: ChatGPT applies the spec defaults for the rest. When both display-mode fields are omitted, the view supports both modes. When only `preferredDisplayMode` is set, it becomes the only available mode, so pair it with `availableDisplayModes` to keep the other. ChatGPT calls a tool with `{}` from a `global` or `thread` entrypoint, so Skybridge throws at startup when the tool's input schema rejects `{}`. From a `file` entrypoint it passes `{ file: { name, resourceUri } }`, which the view reads and saves with [`useFileResource`](/api-reference/use-file-resource). Skybridge also throws when a file extension doesn't start with `.`. > [!NOTE] > > ChatGPT opens global, thread and file entrypoints fullscreen. The display modes apply when the model calls the tool in a conversation. > [!NOTE] > > `settings`, `quickAction` and `preferredModelDisplayMode` come from OpenAI's [reference package](https://github.com/openai/mcp-extensions), not from the written spec, so their behavior in ChatGPT may change. ### `auth` The recommended way to declare a tool's auth. With the [`oauth`](/api-reference/skybridge#oauth) field set, Skybridge enforces the declaration for you (anonymous or under-scoped calls are rejected before the handler runs). | Value | Meaning | | - | - | | *omitted* (default) | Requires sign-in, the secure default when the server has an `oauth` provider. | | `{ allowsAnonymous: true }` | Callable signed out; uses the token when one is present. | | `{ scopes: [...] }` | Requires sign-in with every listed scope. | | `{ allowsAnonymous: true, scopes: [...] }` | Callable signed out; a signed-in caller missing a listed scope gets a step-up challenge (`insufficient_scope`) instead of the anonymous path. | Declaring any `{ allowsAnonymous: true }` tool turns the server [mixed](/build/auth#mix-public-and-authenticated-tools): it serves anonymous callers, and every other tool stays sign-in-gated by default. Requiring sign-in (`{ scopes }`) needs the `oauth` provider and throws without it; `{ allowsAnonymous: true }` works either way. Omit `auth` entirely for the secure default (sign-in required whenever the server has auth). ### `securitySchemes` The low-level form behind `auth`, for cases it can't express (several alternative `oauth2` schemes, or pure `noauth` that never accepts a token). Mutually exclusive with `auth`. ```ts theme={null} type SecurityScheme = | { type: "noauth" } | { type: "oauth2"; scopes?: string[] }; ``` * **Across the array, match any.** Each entry is an alternative. * **Within an `oauth2` entry's `scopes`, match all.** The token must carry every listed scope. * **`noauth` and `oauth2` together** means "works anonymously, but auth unlocks more." > [!WARNING] > > With the [`oauth`](/api-reference/skybridge#oauth) field, Skybridge enforces `securitySchemes` like `auth`. With hand-wired middleware ([`requireBearerAuth`](/api-reference/require-bearer-auth) or [`optionalBearerAuth`](/api-reference/optional-bearer-auth)) it stays client-facing metadata: enforce the tool's requirements in the handler from `extra.http?.authInfo`. ### `_meta` Metadata on the tool. Skybridge recognizes the keys below; any other key you set is forwarded on the tool's `_meta` untouched. ```ts theme={null} type ToolMeta = { ui?: { visibility?: Array<"model" | "app"> }; "openai/toolInvocation/invoking"?: string; "openai/toolInvocation/invoked"?: string; "openai/fileParams"?: string[]; [key: string]: unknown; }; ``` | Key | Purpose | | - | - | | `ui.visibility` | Expose the tool to the model, the app, or both. | | `openai/toolInvocation/invoking`, `invoked` | Status text shown while the tool runs and after it completes. | | `openai/fileParams` | Top-level input fields that carry file references; see [`FileRef`](/api-reference/file-ref). | | `openai/widgetAccessible` | Deprecated, use `ui.visibility`. | > [!NOTE] > > The `openai/*` keys are read only on **ChatGPT**. `openai/widgetAccessible`is deprecated, prefer `ui.visibility` instead. ## Handler Runs when the tool is called. It receives the validated `input` (typed from [`inputSchema`](#inputschema-outputschema)) and the request context `extra`: ```ts theme={null} type ToolHandler = (input: Input, extra: Extra) => Promise<{ content?: string | ContentBlock | ContentBlock[]; structuredContent?: Record; isError?: boolean; _meta?: Record; }>; ``` ### `extra` The request context. | Field | Purpose | | - | - | | `http?.authInfo` | Validated token from an auth middleware: `clientId`, `scopes`, `extra`. The [provider](/guides/auth-providers) types the claims in `extra`. | | `http?.req` | The HTTP request as a Web `Request`: read headers with `.headers.get()`. | | `mcpReq.signal` | An `AbortSignal`, aborted when the call is cancelled. | | `mcpReq._meta` | Client hints (below). | ### Return | Field | Purpose | | - | - | | `content` | Text for the model, shown in the conversation. A string, a `ContentBlock`, or an array. | | `structuredContent` | Typed data the model and the view read (via [`useToolInfo`](/api-reference/use-tool-info)). | | `isError` | Marks the call as failed. | | `_meta` | View-only response metadata, hidden from the model. | > [!NOTE] > > For a view tool, Skybridge adds a `viewUUID` to `_meta`, a reserved key used for state persistence. ### Client hints **ChatGPT** attaches conversation context to `extra.mcpReq._meta`. They are hints: tolerate their absence and never use them for authorization. ```ts theme={null} type ClientHintsMeta = { "openai/locale"?: string; "openai/userAgent"?: string; "openai/userLocation"?: { city?: string; region?: string; country?: string; timezone?: string; longitude?: number; latitude?: number; }; "openai/subject"?: string; "openai/session"?: string; "openai/organization"?: string; "openai/widgetSessionId"?: string; "openai/resource"?: { path?: string }; }; ``` | Key | Purpose | | - | - | | `openai/locale` | Requested locale, BCP-47, e.g. `en-US`. | | `openai/userAgent` | Browser user-agent of the ChatGPT client. | | `openai/userLocation` | Coarse location: `city`, `region`, `country`, `timezone`, `latitude`, `longitude` (each optional). | | `openai/subject` | Anonymized user id. | | `openai/session` | Anonymized conversation id, stable within a session. | | `openai/organization` | Anonymized organization id, when the user account is in an organization. | | `openai/widgetSessionId` | Stable id for the mounted view instance. | | `openai/resource` | On calls from a view opened through a [file entrypoint](#openai), `path` is the absolute path of the opened file. ChatGPT desktop only, from the [OpenAI MCP extensions](https://github.com/openai/mcp-extensions/blob/main/docs/spec.md). | > [!NOTE] > > These hints are **ChatGPT** only. > [!WARNING] > > Any MCP client can send `openai/resource`. Resolve the path and check that it stays inside a directory you allow before reading or writing the file. ### Content helpers `skybridge/server` exports helpers that build `ContentBlock`s for the handler's `content`: ```ts theme={null} import { audio, embeddedResource, image, resourceLink, text } from "skybridge/server"; return { content: [text("Here's your chart:"), image(pngBuffer, "image/png")], structuredContent: { /* ... */ }, }; ``` | Helper | Block | | - | - | | `text(value, annotations?)` | `TextContent` | | `image(data, mimeType, annotations?)` | `ImageContent` (base64) | | `audio(data, mimeType, annotations?)` | `AudioContent` (base64) | | `embeddedResource(resource, annotations?)` | `EmbeddedResource` | | `resourceLink(link, annotations?)` | `ResourceLink` | Returning plain `ContentBlock` objects works too; the helpers are optional. > [card] [McpServer](/api-reference/mcp-server) > > The server you register tools on > [card] [useToolInfo](/api-reference/use-tool-info) > > Read the tool's result in the view > [card] [FileRef](/api-reference/file-ref) > > Pass files in and out of a tool # requestFormInput Source: https://docs.skybridge.tech/api-reference/request-form-input Ask the user to fill a form in ChatGPT from a tool > [!NOTE] > > This is an [OpenAI MCP extension](https://github.com/openai/mcp-extensions/blob/main/docs/spec.md#openai-form-elicitation), built on [MCP form elicitation](https://modelcontextprotocol.io/specification/2026-07-28/client/elicitation). Only **ChatGPT** shows these forms, on desktop and web. `requestFormInput` lets a tool ask the user for input before it finishes. ChatGPT shows a native form, then calls the tool again with the answer. On top of standard MCP forms, it supports suggested values, option descriptions, thumbnails and resource pickers. ## Example A CAD app asks which part to inspect before opening it. ```ts theme={null} import { requestFormInput } from "skybridge/server"; server.registerTool({ name: "inspect-part" }, (_args, extra) => { const result = requestFormInput(extra, { key: "part", message: "Choose a part to inspect", requestedSchema: { type: "object", properties: { part: { type: "string", title: "Part", oneOf: [ { const: "hex-bolt", title: "M6 hex bolt", description: "A fastener for the main joint", "x-openai-thumbnail": { src: "https://example.com/hex-bolt.png" }, }, { const: "washer", title: "M6 washer" }, ], }, }, required: ["part"], }, }); if ("resultType" in result) { return result; } if (result.action !== "accept") { return { content: "No part chosen." }; } return { content: `Inspecting ${result.content.part}` }; }); ``` ## Parameters ### `extra` The second argument of the tool handler. ### `params` ```ts theme={null} type OpenAIFormInputParams = { key: string; message: string; requestedSchema: OpenAIForm; requestState?: string; _meta?: Record; }; ``` | Field | Purpose | | - | - | | `key` | Identifies the form across the two calls. Use a different key for each form a tool asks for. | | `message` | Text shown above the form. | | `requestedSchema` | The form, as `{ type: "object", properties, required? }`. | | `requestState` | Opaque state ChatGPT sends back with the answer. It comes from the client, so sign it if it affects access or business logic. | Each property of `requestedSchema` is an MCP form field (string, number, integer, boolean, single or multiple choice), with these additions: | Addition | Applies to | Effect | | - | - | - | | `pattern` | string | Regular expression the value must match. | | `description` | `oneOf` and `anyOf` options | Text under the option. | | `x-openai-thumbnail` | `oneOf` and `anyOf` options | An image for the option, from an HTTPS URL or a data URI. When one option has a thumbnail, every option shows an image. | | `x-openai-suggestions` | string, or the `items` of a string array | Suggested values. Users can still type their own. | | `x-openai-input` | `format: "uri"` string, or array of them | A resource picker. See below. | ### Resource picker ```ts theme={null} { type: "array", items: { type: "string", format: "uri" }, "x-openai-input": { type: "resource", selection: "explicit", options: [{ uri: "cad://parts/hex-bolt", name: "hex-bolt", title: "M6 hex bolt" }], userOptions: { kind: "file", accept: [".stl", ".step"] }, }, } ``` A string field picks one resource and an array field picks several. `options` lists the resources you offer, and `userOptions` lets users add their own files or directories. In an array field, `selection: "explicit"` (the default) lets users select and deselect options, while `"implicit"` keeps every item that remains when the form is submitted. Implicit selection always lets users add files. On web, directory selection isn't supported, and a form opened from a view only allows explicit selection without uploads. ## Returns ```ts theme={null} type OpenAIFormResult = | { action: "accept"; content: Record } | { action: "decline" | "cancel" }; requestFormInput(extra, params): InputRequiredResult | OpenAIFormResult; ``` On the first call, `requestFormInput` returns an `input_required` result: return it from the handler so ChatGPT shows the form. When ChatGPT calls the tool again with the answer, it returns what the user did. `content` is only set when the user accepts. ## How it works The form uses MCP's [multi-round-trip requests](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/mrtr), which ChatGPT requires for forms. The tool returns an `elicitation/create` input request whose own `requestedSchema` is empty, and the OpenAI form goes in `_meta["openai/elicitation"].requestedSchema`. `requestFormInput` throws when the connection is older than MCP `2026-07-28`, or when the client doesn't declare both `elicitation.form` and the `openai/elicitation` form extension. It also throws when the answer has no valid action, doesn't match `requestedSchema`, or names a resource you didn't offer in a picker that allows no uploads. > [card] [registerTool](/api-reference/register-tool) > > Register the tool that asks for input > [card] [McpServer](/api-reference/mcp-server) > > Every method of the server # requireBearerAuth Source: https://docs.skybridge.tech/api-reference/require-bearer-auth Require a signed-in user on every request `requireBearerAuth` locks your server behind sign-in. Unauthenticated requests are turned away before any [tool](/build/tools) runs, and your tools receive the signed-in user. ## Example Every tool requires a signed-in user with the `shop.read` scope: the middleware validates the token before any handler runs. ```ts server.ts highlight={6-9} theme={null} import { Skybridge, requireBearerAuth } from "skybridge/server"; import { verifyAccessToken } from "./verify-access-token.js"; // the verifier you implement export const app = new Skybridge({ name: "shop", version: "1.0", handler }).use( "/mcp", requireBearerAuth({ verifier: { verifyAccessToken }, requiredScopes: ["shop.read"], }), ); ``` ## Signature ```ts theme={null} requireBearerAuth(options: BearerAuthMiddlewareOptions): RequestHandler; ``` ## Parameters ### `options` ```ts theme={null} type BearerAuthMiddlewareOptions = { verifier: OAuthTokenVerifier; requiredScopes?: string[]; resourceMetadataUrl?: string; }; ``` | Field | Purpose | | - | - | | `verifier` | The provider-specific token check you implement. See [Verifier](/api-reference/verifier). | | `requiredScopes` | A server-wide scope floor every accepted token must carry, or the request gets a 403. Layers under per-tool [`securitySchemes`](/api-reference/register-tool#securityschemes). | | `resourceMetadataUrl` | Absolute URL appended to the `WWW-Authenticate` header on a 401, pointing at your OAuth 2.0 [Protected Resource Metadata](https://datatracker.ietf.org/doc/html/rfc9728) so clients can discover the authorization server. | ## Returns An Express `RequestHandler` to pass to [`server.use`](/api-reference/mcp-server#use), typically on `/mcp`. * A valid token: the request proceeds, and handlers read it from `extra.http?.authInfo`. * A missing, invalid, or expired token: a 401 with a `WWW-Authenticate` header. A token missing a required scope: a 403. > [!NOTE] > > A valid token only proves who the caller is. Authorizing what they can do, and scoping data to them, stays the handler's job: read `extra.http?.authInfo` and never trust a client-supplied identifier. > [card] [optionalBearerAuth](/api-reference/optional-bearer-auth) > > Accept a token when present, allow anonymous otherwise > [card] [mcpAuthMetadataRouter](/api-reference/mcp-auth-metadata-router) > > Advertise your authorization server for discovery > [card] [Authenticate Users](/build/auth) > > Add sign-in to your app end to end # Skybridge Source: https://docs.skybridge.tech/api-reference/skybridge Configure and run your app `Skybridge` is the root of your app: one config object that names your server, wires OAuth, and registers your [tools](/build/tools) through a `handler`. It runs an [Express](https://expressjs.com/)-backed HTTP server that serves MCP at `/mcp`, and you export its type for [`generateHelpers`](/api-reference/generate-helpers). ## Example The app registers one tool and exports its type for the typed client hooks. A separate entry file runs it. ```ts src/server.ts theme={null} import { Skybridge } from "skybridge/server"; export const app = new Skybridge({ name: "shop", version: "1.0", handler: (server) => server.registerTool(/* ... */), }); export type AppType = typeof app; // generateHelpers reads your tools from this ``` ```ts src/index.ts theme={null} import { app } from "./server.js"; export default await app.run(); ``` Keeping the definition in `server.ts` and the `run()` call in `index.ts` lets tests and [evals](/test/evals) import the app without starting a server. ## Constructor ```ts theme={null} new Skybridge(config: SkybridgeConfig); ``` `config` merges the MCP implementation info, the SDK's `ServerOptions`, and Skybridge's own fields. Every type is inferred from it: the config passed to `handler` from `setup`, the auth claims from `oauth`, and the tool registry from what `handler` returns. ```ts theme={null} type SkybridgeConfig = Implementation & ServerOptions & { handler: (server: McpServer, config: Config) => McpServer; setup?: () => Config | Promise; oauth?: OAuthConfig | OAuthProvider | ((config: Config) => OAuthConfig | OAuthProvider); json?: JsonOptions; skills?: boolean; onMcpError?: (error: Error) => void; }; ``` ### `name`, `version` The MCP implementation info (`name`, `version`, and optionally `title`, `description`, `icons`, `websiteUrl`). SDK `ServerOptions` such as `instructions` or `capabilities` are forwarded when you set them; registering tools and views advertises those capabilities for you. `icons` is the app's icon, a standard MCP field. Hosts choose whether and where to show it. Tools can carry their own [`icons`](/api-reference/register-tool#icons) too. ### `handler` Receives a fresh [`McpServer`](/api-reference/mcp-server) and must **return** the chain of registrations. That return value is what carries your tool types into `typeof app`. The handler runs for **every request**, so keep it to registration. Anything else in its body (a connection pool, a timer, a file read) runs per request too: move it into [`setup`](#setup), whose result is the handler's second argument. Skybridge warns once in the console when a handler takes more than 50ms. The handler must stay synchronous. ### `setup` Loads what the app needs before it serves: a connection pool, a client, remote config, secrets. It runs **once**, at `run()` or on the first request, never when the module is imported. Its awaited result is passed to `handler` as the second argument, and to `oauth` when `oauth` is a function. ```ts src/server.ts theme={null} export const app = new Skybridge({ name: "shop", version: "1.0", setup: async () => loadConfig(), oauth: (config) => descopeProvider({ url: config.mcpServerUrl }), handler: (server, config) => server.registerTool(/* reads config */), }); ``` ### `oauth` An [identity provider](/guides/auth-providers) (`oauth: workosProvider({ ... })`), a raw [`OAuthConfig`](/api-reference/custom-provider#returns), or a function of the `setup` result returning either. Providers defer discovery: nothing runs at module import, the network call happens once at `run()`. When set, it mounts the well-known OAuth metadata and bearer-token verification on `/mcp`. The config also carries the claim shape its verifier produces, so handlers read `extra.http.authInfo.extra` typed, with no declaration of their own. See [Type the Claims You Read](/build/auth#type-the-claims-you-read). ### `json` Options for the [`express.json()`](https://expressjs.com/en/5x/api/express/#expressjsonoptions) parser Skybridge pre-applies, for example to raise the default 100kb body-size limit. ### `skills` Set to `true` to serve [Agent Skills over MCP](/guides/skills) from `src/skills` and declare the `io.modelcontextprotocol/skills` capability. > [!NOTE] > > Skills over MCP tracks [SEP-2640](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2640), which is still under review. The feature is **experimental** and may change with the spec. ### `onMcpError` Replaces the error reporter of the built-in `/mcp` handler. By default, Skybridge logs each error that the MCP SDK handler reports, except `UnsupportedProtocolVersionError`. The log line is `console.error("Error handling MCP request:", error)`. When you set `onMcpError`, it receives every error that the MCP SDK handler or its Node adapter reports. This includes: * Requests the SDK rejects before any tool runs, such as an unsupported protocol version or a malformed header. * Failures to build or serve the per-request server. `UnsupportedProtocolVersionError` also reaches your function, because the skip belongs to the default reporter. Filter it yourself if you do not want it. Node adapter errors, such as a request after the handler is closed, reach only `onMcpError`. The default reporter does not log them. The option only reports. It does not change the response. It can run before the response is sent, so keep it fast and synchronous. Skybridge does not await a returned promise, so a rejected promise is an unhandled rejection, which ends the process by default in Node. An error that the function throws is dropped. Other errors go elsewhere: * Tool errors are valid MCP results. Read them with [`getToolError`](/api-reference/mcp-server#gettoolerror). * Express errors on `/mcp` go to your [`useOnError`](#useonerror) handlers, then to the default Express handler. That handler also logs them. ```ts src/server.ts theme={null} import { ProtocolError, ProtocolErrorCode, Skybridge } from "skybridge/server"; export const app = new Skybridge({ name: "shop", version: "1.0", onMcpError: (error) => { const unsupportedVersion = error instanceof ProtocolError && error.code === ProtocolErrorCode.UnsupportedProtocolVersion; if (!unsupportedVersion) { console.warn({ event: "mcp_error", name: error.name }); } }, handler: (server) => server.registerTool(/* ... */), }); ``` ## Properties ### `express` The underlying Express app, for custom routes, middleware, and settings. Register handlers before `run()`. > [!NOTE] > > [Alpic Cloud](https://alpic.ai/solutions/cloud) routes traffic only to `/mcp`. Custom routes work locally and on self-hosted deployments. ## Methods `use` and `useOnError` return the app, so calls chain. ### `use` ```ts theme={null} app.use(...handlers: RequestHandler[]): this; app.use(path: string, ...handlers: RequestHandler[]): this; ``` Registers [Express middleware](https://expressjs.com/en/guide/using-middleware/) on the underlying app, optionally scoped to a path. Mirrors `app.use`. ### `useOnError` ```ts theme={null} app.useOnError(...handlers: ErrorRequestHandler[]): this; app.useOnError(path: string, ...handlers: ErrorRequestHandler[]): this; ``` Registers an [Express error handler](https://expressjs.com/en/guide/error-handling.html), optionally path-scoped, to run after the `/mcp` route. A default handler runs last, responding with a 500 [JSON-RPC](https://www.jsonrpc.org/) error when nothing else has sent a response. ### `run` ```ts theme={null} app.run(): Promise<{ fetch: (...args: unknown[]) => unknown } | Express | undefined>; ``` Resolves `setup` and `oauth`, applies your middleware, mounts `/mcp`, and listens (default port `3000`). On serverless platforms, export what it returns so the platform can route requests to it. See [Deploy](/ship/deploy) for the per-platform setup. ### `connect` ```ts theme={null} app.connect(transport: Transport): Promise; ``` Connects the app to a transport you manage, such as stdio for a desktop host. For HTTP, `run()` sets the transport up for you. > [card] [McpServer](/api-reference/mcp-server) > > The server your handler registers tools on > [card] [registerTool](/api-reference/register-tool) > > Define the tools and views the app exposes > [card] [generateHelpers](/api-reference/generate-helpers) > > Turn `AppType` into typed client hooks # stytchProvider Source: https://docs.skybridge.tech/api-reference/stytch-provider Wire OAuth from Stytch Connected Apps `stytchProvider` wires authentication through [Stytch Connected Apps](https://stytch.com/), so your tools receive a signed-in Stytch user. ## Example ```ts server.ts highlight={1,6-9} theme={null} import { Skybridge, stytchProvider } from "skybridge/server"; export const app = new Skybridge({ name: "personal-shopper", version: "0.0.1", oauth: stytchProvider({ domain: process.env.STYTCH_DOMAIN, audience: process.env.STYTCH_PROJECT_ID, }), handler, }); ``` ## Signature ```ts theme={null} stytchProvider(opts: StytchProviderOptions): Promise; ``` ## Parameters ### `opts` * **`domain`** is the project domain, for example `acme.customers.stytch.dev`, or a configured custom domain. * **`audience`** is the Stytch Project ID, the audience Stytch binds into the token's `aud` claim. It also accepts the shared [`CustomProviderOptions`](/api-reference/custom-provider#parameters) options: `baseUrl`, `serverUrl`, `scopes`, `requiredScopes`, and `metadataOverrides`. Requires Dynamic Client Registration enabled in the Stytch dashboard. ## Returns A `Promise` for the [`OAuthConfig`](/api-reference/custom-provider#returns) you pass to the [`oauth`](/api-reference/skybridge#oauth) field, as a value or from a function. > [card] [Connect an Identity Provider](/guides/auth-providers) > > Set up sign-in with a hosted provider > [card] [Authenticate Users](/build/auth) > > Add sign-in to your app end to end > [card] [customProvider](/api-reference/custom-provider) > > Wire OAuth from any IdP's discovery document # useAppsSdkContext Source: https://docs.skybridge.tech/api-reference/use-apps-sdk-context Read a raw ChatGPT host global by key ChatGPT exposes its host context to your app, which Skybridge's hooks read and normalize for you. `useAppsSdkContext` is the escape hatch: it reads a context value raw, by key, before that normalization. It works only under ChatGPT. ## Example `useUser` canonicalizes the locale (`fr_FR` becomes `fr-FR`). Reading it raw gives exactly what ChatGPT sent. ```tsx highlight={4} theme={null} import { useAppsSdkContext } from "skybridge/web"; function LocaleBadge() { const locale = useAppsSdkContext("locale"); // raw, e.g. "fr_FR" return {locale}; } ``` ## Type Parameters ### `K` ```tsx theme={null} K extends keyof AppsSdkContext; ``` Inferred from `key`: the literal key you pass fixes the return type to `AppsSdkContext[K]`. ## Parameters ### `key` ```tsx theme={null} key: K; ``` **Required.** The context key to read. The hook re-renders when the host pushes a new value for that key, and ignores changes to other keys. ## Returns ```tsx theme={null} value: AppsSdkContext[K]; ``` The requested key's current value, read live from `window.openai`. It is un-normalized: every key also has a cross-host hook that returns a wrapped form, so reach here only for the raw value. | Key | Value | Also via | | - | - | - | | `theme` | `"light"` or `"dark"` | [`useUser`](/api-reference/use-user) | | `locale` | locale string, not canonicalized | [`useUser`](/api-reference/use-user) | | `userAgent` | device type and input capabilities | [`useUser`](/api-reference/use-user) | | `maxHeight` | max view height in pixels | [`useViewport`](/api-reference/use-viewport) | | `displayMode` | current layout (`pip` / `inline` / `fullscreen` / `modal`) | [`useDisplayMode`](/api-reference/use-display-mode) | | `safeArea` | insets to keep clear of host chrome | [`useViewport`](/api-reference/use-viewport) | | `view` | current mode and modal params | [`useRequestModal`](/api-reference/use-request-modal) | | `toolInput` | the tool call's arguments | [`useToolInfo`](/api-reference/use-tool-info) | | `toolOutput` | the tool's structured output | [`useToolInfo`](/api-reference/use-tool-info) | | `toolResponseMetadata` | the tool's response `_meta` | [`useToolInfo`](/api-reference/use-tool-info) | | `widgetState` | persisted state: `modelContent` (model-shared), `privateContent` (view-only), `imageIds` | [`useViewState`](/api-reference/use-view-state) | > [card] [useMcpAppContext](/api-reference/use-mcp-app-context) > > The same escape hatch for the MCP Apps runtime > [card] [useToolInfo](/api-reference/use-tool-info) > > Read the tool result the view mounted with, cross-host > [card] [ChatGPT Plugins and MCP Apps](/resources/chatgpt-and-mcp-apps) > > What the raw `window.openai` layer is, and how Skybridge unifies it # useCallTool Source: https://docs.skybridge.tech/api-reference/use-call-tool Call a tool from a view `useCallTool` lets a [view](/build/view) call one of your server's [tools](/build/tools) and tracks the call's state, so an interaction in the view can run server logic and render the result. The model does not see a view-initiated call. Import it from your [`generated helpers.ts`](/api-reference/generate-helpers): the typed hook infers the tool's argument and response types from your server, so you pass only the name. ## Examples ### Trigger a call and read the result A shopper checks out their cart without leaving the view. The button shows progress while the server creates the checkout, then turns into a Pay now link, or explains why checkout could not start. ```tsx highlight={5-6,14-17,23,27} theme={null} import { useCallTool } from "../helpers.js"; // generated, type-safe from server schema import { useOpenExternal } from "skybridge/web"; function Cart({ items }: { items: string[] }) { const { callTool, isPending, isSuccess, isError, data, error } = useCallTool("create-checkout"); const openExternal = useOpenExternal(); return (
{isSuccess && ( )} {isError &&

Could not start checkout: {String(error)}

}
); } ``` ### Await the call A shopper checks out and goes straight to payment. The view waits for the checkout, opens the payment page, and recovers if the request never completes. ```tsx highlight={5,10,12-13} theme={null} import { useCallTool } from "../helpers.js"; // generated, type-safe from server schema import { useOpenExternal } from "skybridge/web"; function Cart() { const { callToolAsync, isPending } = useCallTool("create-checkout"); const openExternal = useOpenExternal(); const checkout = async () => { try { const { structuredContent } = await callToolAsync({ items: ["jacket"] }); openExternal(structuredContent.checkoutUrl); } catch (error) { console.error("Checkout failed", error); } }; return ( ); } ``` ## Type Parameters The [generated helper](/api-reference/generate-helpers) infers both from your server. You set them by hand only when importing `useCallTool` from `skybridge/web` directly, which is not recommended. ### `ToolArgs` ```tsx theme={null} ToolArgs extends Record | null = null; ``` The arguments the tool accepts. Defaults to `null`, for a tool that takes no arguments. ### `ToolResponse` ```tsx theme={null} ToolResponse extends Partial<{ structuredContent: Record; meta: Record; }> = Record; ``` The shape of the tool's `structuredContent` and `meta`. Defaults to an empty object. Whatever you set here types those two fields on `data`. ## Parameters ### `name` ```tsx theme={null} name: string; ``` **Required.** The name of the tool to call. It must match a tool registered on your [MCP server](/api-reference/mcp-server). > [!NOTE] > > A view can call a tool only when the tool's `_meta.ui.visibility` includes `"app"`, which is the default behavior. See [Register Tools](/build/tools). ### `options` ```tsx theme={null} options?: { timeout?: number }; ``` `timeout` is the call's timeout in milliseconds, 60 seconds by default. Raise it for tools that wait on the user, such as a ChatGPT form. It must be a positive, finite number. ## Returns `useCallTool` returns two call functions plus the live [state](/build/state) of the most recent call. Both functions keep the same identity across renders, so they are safe to list in effect dependencies. ### `callTool` ```tsx theme={null} callTool(toolArgs: ToolArgs, sideEffects?: SideEffects): void; callTool(sideEffects?: SideEffects): void; // overload available when the tool has no required arguments ``` Starts the call and tracks its state on the hook. Returns `void`: read the outcome from `status` / `data` / `error`. Drop `toolArgs` via the second overload when the tool has no required arguments. **`sideEffects`** Optional callbacks bound to this specific call, firing even when a later call supersedes it. ```tsx theme={null} type SideEffects = { // the call completed: the host returned a response (which may carry data.isError === true) onSuccess?: (data: CallToolResponse & ToolResponse, toolArgs: ToolArgs) => void; // the call failed to complete: the host rejected it onError?: (error: unknown, toolArgs: ToolArgs) => void; // runs after onSuccess or onError, with the other argument undefined onSettled?: ( data: (CallToolResponse & ToolResponse) | undefined, error: unknown | undefined, toolArgs: ToolArgs, ) => void; }; ``` ### `callToolAsync` ```tsx theme={null} callToolAsync(toolArgs: ToolArgs): Promise; callToolAsync(): Promise; // overload available when the tool has no required arguments ``` Tracks state on the hook exactly like `callTool`, and also returns a promise. It resolves with the [`response`](#data) when the call completes, and rejects with the thrown value when the call fails to complete. It accepts no `sideEffects`. ### `status` ```tsx theme={null} status: "idle" | "pending" | "success" | "error"; ``` * `"idle"`: no call has started. * `"pending"`: a call is in flight. * `"success"`: the most recent call completed and the host returned a response. The response may carry `data.isError === true`. * `"error"`: the most recent call failed to complete and the host rejected it. ### `isIdle`, `isPending`, `isSuccess`, `isError` ```tsx theme={null} isIdle: boolean; isPending: boolean; isSuccess: boolean; isError: boolean; ``` Each is `true` when `status` equals the matching value and `false` otherwise. Exactly one is `true` at any time. `isError` here is the call-level flag (`status` is `"error"`). It is not `data.isError`, which marks a completed call whose tool reported a failure. ### `data` ```tsx theme={null} data: (CallToolResponse & ToolResponse) | undefined; ``` The response, set only while `status` is `"success"`. It is `undefined` in every other state. A new call clears it to `undefined` as it enters `"pending"`. A tool that reports a failure still lands here, with `isError: true`; only a call that fails to complete sets `error` instead. `CallToolResponse` is the fixed part of every response, which your `ToolResponse` type parameter narrows on `structuredContent` and `meta`: ```tsx theme={null} type CallToolResponse = { content: ContentBlock[]; // the MCP content blocks the tool returned structuredContent: Record; isError: boolean; // true when the tool itself reported a failure meta?: Record; }; ``` ### `error` ```tsx theme={null} error: unknown | undefined; ``` The thrown value, set only while `status` is `"error"`. It is `undefined` in every other state. A tool that completes but reports its own failure is a `"success"`, not an `"error"`. > [card] [Create Views](/build/view) > > Call tools back from a view in context > [card] [generateHelpers](/api-reference/generate-helpers) > > The typed `useCallTool` that infers from your server > [card] [useToolInfo](/api-reference/use-tool-info) > > Read the tool result the view mounted with # useDeepLink Source: https://docs.skybridge.tech/api-reference/use-deep-link Read the deep link ChatGPT opened the view on > [!NOTE] > > This is an [OpenAI MCP extension](https://github.com/openai/mcp-extensions/blob/main/docs/spec.md), not part of MCP or MCP Apps. Only **ChatGPT** supports it, and other hosts ignore it. A deep link opens ChatGPT with your app already open, from anywhere outside ChatGPT: an "Open in ChatGPT" button on your website, a link in an email or in your docs. It targets a tool with a [global entrypoint](/api-reference/register-tool#openai), `https://chatgpt.com/plugins//app/`, and can carry a `path` to land on a given page of your view, such as `?path=%2Fparts%2Fhex-bolt`. `useDeepLink` returns that app-relative URL so the view can route to it. It updates when the user follows another deep link while the view is open. ## Example The view hands the deep link to its router. ```tsx highlight={6,8-10} theme={null} import { useEffect } from "react"; import { useNavigate } from "react-router-dom"; import { useDeepLink } from "skybridge/web"; function DeepLinkRouter() { const deepLink = useDeepLink(); const navigate = useNavigate(); useEffect(() => { if (deepLink) navigate(deepLink); }, [deepLink, navigate]); return null; } ``` ## Returns ```tsx theme={null} string | undefined; ``` The app-relative URL, path and query included, for example `"/parts?tag=bolt&sort=asc"`. Parse it with `new URL(deepLink, location.origin)` to read the query. `undefined` when the view wasn't opened through a deep link, on hosts other than **ChatGPT**, or when the host sends a URL that isn't app-relative (it must start with a single `/`) or that contains a fragment. ## Deep link format | Surface | Format | | - | - | | Desktop | `codex://plugins/{pluginId}@{marketplace}/app/{toolName}?path={encodedPath}` | | Mobile | `chatgpt://plugins/{pluginId}@{marketplace}/app/{toolName}?path={encodedPath}` | | Web | `https://chatgpt.com/plugins/{pluginId}/app/{toolName}?path={encodedPath}` | Find `pluginId` in the plugin's URL, `https://chatgpt.com/plugins/{pluginId}`. Leave out `@{marketplace}` for plugins published directly to ChatGPT. Percent-encode `pluginId`, `toolName` and the whole app-relative URL. Without `path`, the view opens on `/`. Android doesn't support deep links. > [card] [registerTool](/api-reference/register-tool#openai) > > Add a global entrypoint to a tool > [card] [useMcpAppContext](/api-reference/use-mcp-app-context) > > Read a raw MCP Apps context value by key # useDisplayMode Source: https://docs.skybridge.tech/api-reference/use-display-mode Read and switch how the host lays out the view A host renders the [view](/build/view) in one of a few layouts: a compact inline panel, fullscreen, or a floating picture-in-picture. `useDisplayMode` lets the view read which layout it is in and ask the host to switch to another. ## Example The product carousel shows more columns when it takes the full screen. From the inline panel it offers a "See all" button to expand, and once expanded, a "Collapse" button to shrink back. ```tsx highlight={4,10,13,16} theme={null} import { useDisplayMode } from "skybridge/web"; function Carousel({ products }: { products: Product[] }) { const [mode, setMode] = useDisplayMode(); return (
{mode === "inline" && ( )} {mode === "fullscreen" && ( )}
); } ``` ## Returns `useDisplayMode` returns a tuple: the current mode first, the setter second. ### `displayMode` ```tsx theme={null} displayMode: DisplayMode; ``` The mode the host is currently rendering the view in. It updates on its own when the host changes the layout (the user expanding or collapsing the view, for instance), so a component can render against it directly. | Mode | Layout | Requestable | | - | - | :-: | | `"inline"` | Compact panel embedded in the conversation, the default | | | `"fullscreen"` | The view takes over the host surface | | | `"pip"` | Picture in picture, floating above the conversation | | | `"modal"` | Overlay opened through [`useRequestModal`](/api-reference/use-request-modal), host-driven | | ### `setDisplayMode` ```tsx theme={null} setDisplayMode(mode: RequestDisplayMode): Promise<{ mode: RequestDisplayMode }>; ``` Asks the host to switch the view to `mode`. The host decides: it can grant the request, keep the current mode, or coerce to another. The promise resolves with the mode actually applied, so read the resolved value rather than assuming the request took. **`mode`** the mode to request, every [`DisplayMode`](#displaymode) except `"modal"`: ```tsx theme={null} // "inline" | "fullscreen" | "pip" type RequestDisplayMode = Exclude; ``` > [!NOTE] > > On mobile, **ChatGPT** coerces a `"pip"` request to `"fullscreen"`. > [card] [Design for the Host](/guides/ux) > > Adapt the view to display mode, theme, and device > [card] [useViewport](/api-reference/use-viewport) > > Read the space and insets a mode switch brings > [card] [useRequestModal](/api-reference/use-request-modal) > > Open the view as a host modal # useDownload Source: https://docs.skybridge.tech/api-reference/use-download Save files from a view to the user's device [Views](/build/view) run in sandboxed iframes where direct downloads (``, `URL.createObjectURL`) are blocked. `useDownload` hands the host one or more resources to write to the user's device, so a view can save a file it produced. ## Example The view builds a CSV from the carousel's products and hands the host an inline resource, then offers a server-hosted PDF as a resource link. ```tsx views/carousel.tsx highlight={4,11-22,32-41} theme={null} import { useDownload } from "skybridge/web"; function Carousel({ products }: { products: Product[] }) { const download = useDownload(); const exportCsv = async () => { const csv = products .map((p) => `${p.id},${p.name},${p.price}`) .join("\n"); try { const { isError } = await download({ contents: [ { type: "resource", resource: { uri: "file:///products.csv", // last segment is the suggested filename mimeType: "text/csv", text: csv, }, }, ], }); if (isError) { console.warn("Export cancelled or not supported by this host"); } } catch (err) { console.error("Download failed to complete", err); } }; const saveSpecSheet = async (product: Product) => { await download({ contents: [ { type: "resource_link", uri: `https://shop.example.com/specs/${product.id}.pdf`, name: `${product.name} spec sheet`, mimeType: "application/pdf", }, ], }); }; return (
{products.map((p) => ( ))}
); } ``` ## Returns `useDownload` returns the function directly. ### `download` ```tsx theme={null} download(params: DownloadParams): Promise; ``` Asks the host to save the resources in `params`. The promise resolves once the host responds, and rejects if the request times out or the connection is lost. **`params`** one or more resources to save, each carried inline or fetched by the host from a URL. ```tsx theme={null} type DownloadParams = { contents: (EmbeddedResource | ResourceLink)[]; }; ``` **`EmbeddedResource`** carries the file inline; `resource` holds the bytes as a UTF-8 `text` string or a base64 `blob`. The `uri`'s last segment sets the suggested filename. ```tsx theme={null} type EmbeddedResource = { type: "resource"; resource: | { uri: string; text: string; mimeType?: string; _meta?: Record } | { uri: string; blob: string; mimeType?: string; _meta?: Record }; annotations?: Annotations; // standard MCP annotations _meta?: Record; }; ``` **`ResourceLink`** points the host at a URL it fetches itself. ```tsx theme={null} type ResourceLink = { type: "resource_link"; uri: string; name: string; title?: string; description?: string; mimeType?: string; size?: number; annotations?: Annotations; // standard MCP annotations icons?: Icon[]; _meta?: Record; }; ``` The promise resolves with a `DownloadResult`: ```tsx theme={null} type DownloadResult = { isError?: boolean; }; ``` `isError` is `true` when the download did not happen: the user cancelled, or the host denied it (including a host that lacks the download capability). It is absent or `false` on success. A request that fails to complete (timeout, lost connection) rejects the promise instead of setting this flag. > [card] [Handle Files](/guides/files) > > Move files in and out of your app > [card] [useFiles](/api-reference/use-files) > > Upload and resolve host-managed files > [card] [useOpenExternal](/api-reference/use-open-external) > > Open a link outside the view # useFileResource Source: https://docs.skybridge.tech/api-reference/use-file-resource Read, watch and save the file a ChatGPT file entrypoint opened A [file viewer](/api-reference/register-file-viewer) opens your view on a file the user picked in ChatGPT desktop. ChatGPT never gives the view the file's path: the tool input carries an opaque `file.resourceUri` instead. `useFileResource` reads that resource, re-reads it whenever the host reports a change, and saves edits back. > [!NOTE] > > Reading uses the standard MCP `resources/read`. Text or blob selection, change subscriptions and writes come from the [OpenAI MCP extensions](https://github.com/openai/mcp-extensions/blob/main/docs/spec.md), so only **ChatGPT** desktop supports them. ## Example A part editor loads the opened file as text and saves the user's edits. ```tsx theme={null} import { useState } from "react"; import { useFileResource } from "skybridge/web"; import { useToolInfo } from "../helpers.js"; function PartEditor() { const { input } = useToolInfo<"open-part">(); const { data, isLoading, write } = useFileResource(input.file?.resourceUri, { representation: "text", }); const [draft, setDraft] = useState(); const [conflict, setConflict] = useState(false); if (isLoading || !data || !("text" in data)) { return null; } const save = async () => { const result = await write({ text: draft ?? data.text }); setConflict(result.outcome === "conflict"); }; const discardEdits = () => { setDraft(undefined); setConflict(false); }; return ( <>