> This page is for MCP Generator.

> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://buildwithfern.com/learn/llms.txt. For task-scoped instructions for coding agents working in a Fern project, run `fern instructions` (or `npx fern-api@latest instructions` if the Fern CLI isn't installed or doesn't recognize `instructions`), or see https://buildwithfern.com/learn/home/fern-instructions.md.

# Configure the server

> Choose which API operations become MCP tools, group them into toolsets, merge and rename tools, add custom tools and hooks, and pass credentials.

The MCP Generator turns each operation in your OpenAPI spec into one tool. Settings in the `generation` block of the `mcp` target in `sdk-config.yml` decide which tools the server exposes and how agents see them, and OpenAPI extensions on each operation set its tool's name and description. Run `fern generate` after a change to redeploy the server with the same URL.

**`fern/sdk-config.yml`**

```yaml title="fern/sdk-config.yml"
targets:
  - language: mcp
    output:
      delivery: hosted
      slug: petstore
    generation:
      serverName: Petstore
      serverDescription: Manage pets, orders, and users in the Swagger Petstore.
      excludeAvailability: [DEPRECATED]
      tools:
        exclude: ["delete_*"]
      toolsets:
        orders:
          include: [get_inventory, place_order, get_order_by_id]
```

## Name and describe tools

A tool's name is the operation's `operationId` in snake case, so `getPetById` becomes `get_pet_by_id`. An operation without an `operationId` is named after its HTTP method and path. When two operations produce the same name, the generator adds the service name, then the path segments that tell them apart, then the HTTP method, and a number only as a last resort.

A tool's description comes from the operation's `summary` and `description`, cut to 512 characters. To set either one yourself, add these extensions to the operation, in your spec or an [overlay](/learn/api-definitions/openapi/overlays):

**`overlay.yml`**

```yaml title="overlay.yml"
overlay: 1.0.0
info:
  title: MCP tool names
  version: 1.0.0
actions:
  - target: "$.paths['/pet/{petId}'].get"
    update:
      x-fern-mcp-name: get_pet
      x-fern-mcp-description: Get one pet by its numeric ID.
```

`x-fern-mcp-name` is used as written. It must be 1 to 64 letters, digits, `_`, or `-`, and no two tools can share a name. Generation fails otherwise.

## Choose which operations become tools

`tools` filters the operations that become tools. `include` keeps only the operations it matches, and `exclude` removes the operations it matches. Each entry matches by:

* Tool name, such as `get_pet_by_id`.
* `operationId`, such as `getPetById`.
* Tag or service name, written `tag:<name>`, such as `tag:store`. This matches an operation's OpenAPI tag or the service it belongs to.
* Tool name with `*` wildcards, such as `delete_*`.

An entry that matches no operation fails generation, and the error lists the available tool names.

`excludeAvailability: [DEPRECATED]` removes every operation marked `deprecated: true` in your spec. Without it, a deprecated operation's tool says so in its description.

Some operations can't become tools, and the generator skips them with a warning: operations whose request body has no JSON content type, such as a file upload that only accepts `application/octet-stream`, and operations with a required query parameter in a serialization style the generator doesn't support.

## Group tools into toolsets

A toolset is a subset of the server's tools with its own URL. An agent connected to a toolset sees only those tools, which keeps its tool list short.

| Server                                                                       | All tools                               | One toolset                                       |
| ---------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------- |
| Hosted                                                                       | `https://<your-org>.fernmcp.dev/<slug>` | `https://<your-org>.fernmcp.dev/<slug>/<toolset>` |
| [Custom domain](/learn/mcp-generator/get-started/manage#use-a-custom-domain) | `https://<your-domain>`                 | `https://<your-domain>/<toolset>`                 |
| Local                                                                        | `http://localhost:8787/mcp`             | `http://localhost:8787/mcp/<toolset>`             |

Fern creates a toolset for each tag and each service that has at least two tools, named in kebab case. For Petstore, that gives `pet`, `store`, and `user`. `toolsets` adds your own, or replaces a generated toolset with the same name. Each one takes the same `include` and `exclude` entries as `tools`, and draws only from the tools that `tools` and `excludeAvailability` keep. Toolset names use lowercase letters, digits, and hyphens, and can't be `default`.

## Merge related tools

`mergedTools` combines several operations into one tool, which keeps an agent's tool list short when your API has many similar operations. The agent picks an operation by setting the argument named in `dispatchOn`. Merged tools require Fern CLI 5.222.0 or later.

**`sdk-config.yml`**

```yaml title="sdk-config.yml"
targets:
  - language: mcp
    generation:
      mergedTools:
        manage_order:
          dispatchOn: action
          description: Place, look up, or cancel a store order.
          include: [place_order, get_order_by_id, delete_order]
```

Each member operation sets the value that routes to it with `x-fern-mcp-dispatch-value`:

**`overlay.yml`**

```yaml title="overlay.yml"
overlay: 1.0.0
info:
  title: MCP dispatch values
  version: 1.0.0
actions:
  - target: "$.paths['/store/order'].post"
    update:
      x-fern-mcp-dispatch-value: place
  - target: "$.paths['/store/order/{orderId}'].get"
    update:
      x-fern-mcp-dispatch-value: get
  - target: "$.paths['/store/order/{orderId}'].delete"
    update:
      x-fern-mcp-dispatch-value: delete
```

The server exposes `manage_order` in place of its three members. An agent calls it with `action` set to `place`, `get`, or `delete`, plus that operation's arguments. Without `description`, the tool's description lists the dispatch argument and its values.

* `include` and `exclude` take the same entries as `tools`, and draw only from the tools that `tools` and `excludeAvailability` keep.
* `dispatchOn` must be 1 to 64 letters, digits, `_`, `.`, or `-`. The merged tool's name follows the same rules as `x-fern-mcp-name`.
* Toolsets list a merged tool by its own name, not by its members' names.

Generation fails when a member has no `x-fern-mcp-dispatch-value`, two members share a value, an operation sets a value but belongs to no merged tool, or the merged tool's name matches another tool or `operationId`.

## Add custom tools and hooks

When no operation does what an agent needs, write a **custom tool**: a TypeScript module that defines its own tool and handler. To run the same logic across every tool call, write **hooks**. Both are TypeScript files under `fern/custom/`, registered in the `mcp` target's `generation` block, and bundled into the server at `fern generate`.

Both types import from [`@fern-api/mcp-tooling`](https://www.npmjs.com/package/@fern-api/mcp-tooling), so they type-check before you generate. The generated server takes no runtime dependency on the package.

### Custom tools

`fern sdk add-tool <name>` writes a stub to `fern/custom/tools/<name>.ts` and registers it under `customTools`:

**`sdk-config.yml`**

```yaml title="sdk-config.yml"
targets:
  - language: mcp
    generation:
      customTools:
        adopt_pet:
          path: custom/tools/adopt_pet.ts
```

The module exports a `definition` (the tool an agent sees in `tools/list`) and a `handler` that runs when the tool is called:

**`fern/custom/tools/adopt_pet.ts`**

```ts title="fern/custom/tools/adopt_pet.ts"
import type { CallToolResult, RequestContext, ToolArgs, ToolDefinition } from "@fern-api/mcp-tooling";

export const definition: ToolDefinition = {
  name: "adopt_pet",
  description: "Adopt an available pet and return the confirmation.",
  inputSchema: {
    type: "object",
    properties: { petId: { type: "string" } },
    required: ["petId"],
    additionalProperties: false,
  },
};

export const handler = async (args: ToolArgs, context: RequestContext): Promise<CallToolResult> => {
  const response = await context.fetch(`${context.baseUrl}/pet/${args.petId}/adopt`, {
    method: "POST",
    headers: { "content-type": "application/json" },
  });
  if (!response.ok) {
    return { isError: true, content: [{ type: "text", text: `HTTP ${response.status}` }] };
  }
  return { content: [{ type: "text", text: await response.text() }] };
};
```

A custom tool's name must be unique across every generated, merged, and custom tool. Custom tools appear next to the generated ones, including in the default toolset even when a `tools` or `mergedTools` filter is set, so a filter never hides them.

### Hooks

`fern sdk add-hook` writes `fern/custom/hooks.ts` and registers it under `hooks`:

**`sdk-config.yml`**

```yaml title="sdk-config.yml"
targets:
  - language: mcp
    generation:
      hooks:
        path: custom/hooks.ts
```

The module exports four functions, each wrapping a point in the request lifecycle:

| Hook                                | Runs                                                            | Use for                                       |
| ----------------------------------- | --------------------------------------------------------------- | --------------------------------------------- |
| `beforeRequest(request, auth?)`     | before each upstream call                                       | add headers, route by tenant, rewrite the URL |
| `afterResponse(request, response)`  | after each response                                             | metrics, latency, reshaping                   |
| `onError(request, error)`           | on a transport error, or a non-2xx response to a generated tool | audit and alerting (observe only)             |
| `transformResult(toolName, result)` | before a result returns to the agent                            | redact, annotate, reshape                     |

`beforeRequest`, `afterResponse`, and `onError` wrap the generated tools automatically, and wrap a custom tool when its handler calls `context.fetch`. `transformResult` runs on every tool's result, custom tools included.

### Call your API from a custom tool

`context.fetch` is a drop-in replacement for the global `fetch` that routes the call through the server's request hooks and credential handling. It sends your API's credentials only to the configured `baseUrl` origin, doesn't follow redirects (a 3xx returns as-is, so credentials can't leak to a redirect target), and times out after 30 seconds. Prefer it over the global `fetch`, which bypasses the hooks, the credentials, and the timeout.

`context.fetch` doesn't set a content type. A non-2xx response returns to your handler without calling `onError`. On a `POST`, `PUT`, or `PATCH` with a JSON body, set `content-type: application/json`, or the body goes out as `text/plain` and many APIs answer `415`.

`fern generate` uploads the custom tool and hook modules to Fern's build service, which bundles them into the server for both hosted and downloaded servers.

## Name the server

`serverName` and `serverDescription` set the server's name and description. Without them, the name comes from `sdkName` in `sdk-config.yml`, with `sdk` replaced by `mcp` (`acme-sdk` becomes `acme-mcp`), and the description from `info.description` in your spec.

## Pass credentials

Credentials come from the security schemes in your spec. Agents send them as request headers on every call, and the server forwards them to your API:

* An API key scheme reads the request header named in the scheme, even when your API expects the key in a query parameter or cookie. The server puts the key where your API expects it.
* An HTTP bearer scheme reads `Authorization: Bearer <token>`, and an HTTP basic scheme reads `Authorization: Basic <base64 of username:password>`.
* An OAuth scheme, including client credentials, reads an access token from the `Authorization` header. The server doesn't get tokens itself, so the agent supplies a valid token. To have MCP clients sign users in with your authorization server instead, turn on [OAuth sign-in](/learn/mcp-generator/get-started/authentication).

Parameters that carry a credential aren't tool inputs. When a call is missing a credential, the error names the headers to send. The dashboard's **Connect** button builds each agent's command with the right headers.

## Limits

Every tool call times out after 30 seconds, and a response from your API can be at most 1 MiB. The server rejects path parameters of `.` or `..` and cookie values that contain semicolons or control characters.