> ## Documentation Index
> Fetch the complete documentation index at: https://docs.skybridge.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# registerTool

> 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<string, StandardSchemaWithJSON>; // validates the call and types the handler input
  outputSchema?: Record<string, StandardSchemaWithJSON>; // 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`](https://docs.skybridge.tech/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<string, unknown>;
};
```

| 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`](https://docs.skybridge.tech/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` | `<base href>` 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`](https://docs.skybridge.tech/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`](https://docs.skybridge.tech/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`](https://docs.skybridge.tech/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](https://docs.skybridge.tech/build/auth.md#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`](https://docs.skybridge.tech/api-reference/skybridge#oauth) field, Skybridge enforces `securitySchemes` like `auth`. With hand-wired middleware ([`requireBearerAuth`](https://docs.skybridge.tech/api-reference/require-bearer-auth) or [`optionalBearerAuth`](https://docs.skybridge.tech/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`](https://docs.skybridge.tech/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<string, unknown>;
  isError?: boolean;
  _meta?: Record<string, unknown>;
}>;
```

### `extra`

The request context.

| Field | Purpose |
| - | - |
| `http?.authInfo` | Validated token from an auth middleware: `clientId`, `scopes`, `extra`. The [provider](https://docs.skybridge.tech/guides/auth-providers.md) 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`](https://docs.skybridge.tech/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](https://docs.skybridge.tech/api-reference/mcp-server.md)
>
> The server you register tools on

> [card] [useToolInfo](https://docs.skybridge.tech/api-reference/use-tool-info.md)
>
> Read the tool's result in the view

> [card] [FileRef](https://docs.skybridge.tech/api-reference/file-ref.md)
>
> Pass files in and out of a tool


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.