# MCP Servers

> Build stateless HTTP MCP servers on Ferrite and offer your application's operations to assistants as bounded tools, through the same handlers as your HTTP routes.

Ferrite applications can expose Model Context Protocol (MCP) tools over stateless HTTP so your users' assistants can discover and call bounded operations through the same handlers as your HTTP routes. Clients call `server/discover`, list available tools, and invoke tools with the protocol version and capabilities carried on each request, so your application holds no per-connection session state.

This guide covers MCP servers exposed by your own application. For the Ferrite MCP endpoint your coding agent uses to deploy and operate apps, see [Agent setup](/docs/plugin). To call an external MCP server from an agent running inside your app, use `use_mcp_connection` over a declared `mcp-egress` destination in the [Agent SDK](/docs/agent-sdk).

## Combine tools from several apps in one query

Suppose you have three private Rust apps for your calendar, weather and wardrobe. To answer “What can I wear to my next event today?”, an agent needs the event's time, location and dress code, the forecast there, and a list of outfits you own. It can send one JavaScript query to the App Hub with Code Mode. The query calls the apps' MCP tools on the server and returns just the event and suitable outfits to the agent. Each Rust app continues to own its data and business rules.

Connect your agent to `https://mcp.<base>/apps` on an installation with the App Hub. Ask it to list the available apps with `apps_list`, find their tools with `search`, and check their schemas with `describe`. If your CLI lists `apps` in `ferrite --help`, you can do the same from a terminal:

```bash
ferrite mcp login --apps
ferrite apps list
ferrite apps describe calendar.next_event_today weather.forecast wardrobe.list_outfits
```

Open the device sign-in page shown by the CLI and verify the code, even if you're already signed in to the CLI. Sign in with a verified provider identity. Select **Limit this connection to selected apps**, enter the three `account/app` names on separate lines, and leave **Allow Code Mode** selected. Read access is sufficient for this query. You can change the connection's permissions later under **Connected agents**.

The tool names and fields below are examples. Use the names returned by your catalog and check each schema with `describe`. For names containing a slash or hyphen, use bracket notation, such as `apps["team/home-weather"]["today-forecast"]({ place: "Leeds" })`. Pass the following JavaScript as the `code` argument to `execute`, or save it as `outfits.js` and run `ferrite apps execute "$(cat outfits.js)"`.

```js
const event = await apps.calendar.next_event_today({});
if (!event) return { outfits: [] };

const forecast = await apps.weather.forecast({ place: event.place, at: event.start });
const { outfits } = await apps.wardrobe.list_outfits({ occasion: event.dressCode });
return {
  event: event.title,
  outfits: outfits
    .filter(outfit => !forecast.rain || outfit.waterproof)
    .map(outfit => outfit.name)
};
```

For a rainy forecast and a client meeting, the Hub's structured result could be `{"value":{"event":"Client meeting","outfits":["Navy suit with raincoat"]}}`. Intermediate records stay inside the run. Each invocation starts a fresh worker, so keep the source in your own project if you want to repeat or share it.

### Execution limits and retries

The worker can call the tools available to the connection. It has no direct network or filesystem access. The Hub checks app access on every call, including when a group membership changes during a run.

| Limit | How it affects your query |
| --- | --- |
| 16 KiB of JavaScript | Send the function body as `code`. |
| Five seconds per run | The Hub reads the deployment inventory before starting the worker. Each tool lookup and call uses the remaining time. An app request gets up to three seconds. |
| 20 tool calls per run | Calls run one at a time, including inside `Promise.all`. |
| 128 KiB per message between worker and Hub | Request only the fields or page of results you need. This limit applies to each tool reply and the final result, including the JSON envelope. |
| 60 calls per minute per connection by default | Starting a run and each admitted tool call count. The outfit query uses four when it finds an event. |
| One active run per connection | Each Hub process can run four queries across connections. If a worker is busy, retry after a short delay. |

Inside the script, a rejected tool call throws an error. Check `error.code` in a `catch` block. For `unknown_tool` or `invalid_arguments`, read the catalog and schema again. For `access_denied`, check the connection's policy and the app's sharing settings. For `rate_limited`, wait for the call budget to refill. For `timeout` or `app_error`, check the affected app. If a tool succeeded before a later call failed, its effects still stand.

For a write, supply an `idempotency_key` to `call` or `execute`. The CLI accepts `--idempotency-key` on both commands. Choose a key before the first request. If the reply is lost, retry on the original connection with that key. Each write is bound to its exact app deployment, tool and arguments. A script assigns a key to each call by its position, so keep the script, inputs and call order the same on retry.

The Hub retains a completed write's result for 24 hours from the first attempt. After the result expires, a retry returns `result_expired`. The Hub still suppresses a duplicate write for the lifetime of that connection. If the outcome is `unconfirmed` or `result_expired`, check the app's record. A new connection has its own keys and could repeat the write. For a write that needs owner approval, use the returned approval ID with `resume` after the owner decides in the Dashboard.

### Connect a private app

A private app must accept Hub assertions at the routes it exposes. The Hub sends a short-lived signed assertion addressed to that app for each request. Use the managed Ferrite provider in the `auth` package and `Auth::caller_for` to check the assertion against the requested operation. Allow `apps:discover` to list tools, require `apps:read` for a read tool and `apps:write` for a tool that changes state. A mutating tool and a read tool both arrive as `POST /mcp`. For an `agent-ready` surface, `agent_ready::catalog::hub_scope(&surface, &req.body)` selects the scope for the named method and tool. Apply your app's own access rules to the admitted caller. The generated `ferrite new webapp <name> --private` starter includes managed sign-in and a read-only example.

## Which clients can connect

A server built directly on the `mcp` package speaks only MCP revision `2026-07-28`. Clients that have not adopted `2026-07-28` cannot connect to it.

The `agent-ready` MCP face speaks `2026-07-28` and also handles the `2025-11-25` `initialize` handshake. It accepts earlier revisions (`2025-06-18` and `2025-03-26`) and answers them as `2025-11-25` calls. Serve your tools through `agent-ready` when you need compatibility with assistants on older MCP revisions.

The same revision constraint applies to outbound connections: the `mcp` package's client, which the agent SDK uses to mount remote MCP servers, connects only to servers that speak `2026-07-28`.

## Add the MCP package

```bash
ferrite add mcp
```

Before signing in to Ferrite on a machine, pass `--registry https://packages.ferrite.cloud/registry.json`. See [Packages](/docs/packages) for registry and vendoring details.

The `mcp` source package provides the constrained wire format, stateless client, resource-server shell, and authorization helpers without adding an async runtime or a second Cargo dependency to your app.

If you want one `Surface` declaration to project the same operations into both MCP and OpenAPI, install `agent-ready` instead:

```bash
ferrite add agent-ready
```

Declare each tool's name, description, input and output schemas, and `read_only` or `idempotent` traits, and delegate every tool call to the same domain handler used by your HTTP routes.

## Route the endpoint

```json filename="ferrite.json"
{
  "services": [{ "name": "mcp-requests", "primitive": "queue" }],
  "applications": [{
    "name": "tools",
    "artifact_key": "apps/tools@v1",
    "artifact_sha256": "0000000000000000000000000000000000000000000000000000000000000000",
    "bindings": [
      { "handle": "requests", "kind": "queue", "service": "mcp-requests" }
    ],
    "routes": [{
      "prefix": "/mcp",
      "binding": "requests",
      "kind": "api",
      "forward_headers": ["mcp-protocol-version", "mcp-method", "mcp-name", "origin", "accept", "authorization"]
    }]
  }]
}
```

MCP `2026-07-28` requires `Mcp-Method` and `Mcp-Name` headers to match the JSON-RPC request body. A server built on the `mcp` package rejects requests missing them with error code `-32020`, so your route must forward both headers. Forward `origin` as well, so the server can refuse a browser page on another site.

Include `authorization` in `forward_headers` only when your MCP endpoint validates a scoped bearer token. Never expose a browser session cookie to a remote MCP endpoint.

## Authentication and authorization

Remote MCP clients authenticate with a bearer token scoped to your application. The `mcp` package's resource-server shell validates every request in three stages: the protocol envelope, the bearer token, and whether the token's scopes permit the requested operation. Tokens can be minted and signed by your own app using an HMAC secret, or verified against an authorization server via RFC 7662 introspection over your app's declared egress handle.

The package checks three scopes: `mcp:read` for listing and reading, `mcp:tools` for invoking tools, and `mcp:write` alongside `mcp:tools` for any tool your registry marks as mutating. `server/discover` requires no token so clients can learn how to authenticate. The shell also generates the protected-resource metadata document and the challenge header pointing clients to your authorization server.

Your application supplies three values: the HMAC secret, the canonical resource identifier that every token is bound to, and the egress handle for any authorization server called during introspection. Fail closed if any required value is unset. Never derive the resource identifier from a request header, because an untrusted caller could otherwise choose the audience for its own tokens. When a tool cannot establish the required subject, tenant, or role, return a structured authentication error instead of fixture data or an assumed tenant.

When your application acts as an MCP client, the package's OAuth client is verified against the official conformance runner's mock authorization servers rather than live third-party providers; test it against your target authorization server before shipping.

Inside a browser, WebMCP lets page tools run under your app's signed-in session and CSRF checks; see [WebMCP & OpenAPI](/docs/webmcp-openapi). For the rules governing when an assistant may act on a user's behalf through WebMCP versus remote MCP, see [Assistants acting for a person](/docs/authorization#assistants-acting-for-a-person).

## Tool design

- Give each tool one bounded job.
- Describe when to call it and where required IDs come from.
- Mark read-only tools accurately.
- Require idempotency keys for retryable mutations.
- Return structured errors without secrets or internal stack traces.
- Keep user content clearly marked as untrusted data.

See [Agent-ready apps](/docs/agent-native-apps) for the full discovery surface.

## Follow changes and long-running work

Use [MCP Events](/docs/mcp-events) for event discovery, delivery modes, and client examples, and [MCP Tasks](/docs/mcp-tasks) for resumable long-running operations, client examples, and deployment tracking. Events support is experimental; check the [Availability](/docs/mcp-events#availability) section before advertising an event so your app matches what hosted endpoints support. For Tasks, verify that the endpoint advertises the extension before relying on it, as described under [Discover support](/docs/mcp-tasks#discover-support).

## Add skills, confirmations, files and views

The `agent-ready` MCP face serves each capability below from the same `/mcp` endpoint when your `PageSource` implements its hook. An application that implements none of them serves tools alone.

| Hook on `PageSource` | What it adds | Guide |
| --- | --- | --- |
| `skills` | Workflow skills a client loads by name | [MCP Skills](/docs/mcp-skills) |
| `task_tools`, `task_call`, `task_streaming` | Tools that return a task handle | [MCP Tasks](/docs/mcp-tasks) |
| `events`, `poll_event`, `event_delivery`, `event_call` | Event types and how they are delivered | [MCP Events](/docs/mcp-events) |
| `mcp_tool_call_mrtr` | Questions to the person before a tool runs | [Ask before acting](/docs/mcp-elicitation) |
| `mcp_files_config`, `mcp_file_http` | File arguments, upload targets and downloads | [MCP file transfers](/docs/mcp-files) |
| `mcp_ui_resources` | Interactive views linked to tools | [MCP Apps](/docs/mcp-apps) |
| `mcp_resources` | Documents a client can list and read | |
| `mcp_prompts`, `mcp_prompt_get` | Prompt templates a person can pick | |
| `mcp_tool_hints` | Titles, destructive and open-world annotations, icons | [Interactive MCP tools](/docs/mcp-interactive-tools#describe-what-a-tool-does) |
| `mcp_auth`, `mcp_authorize` | OAuth sign-in for the endpoint | [Interactive MCP tools](/docs/mcp-interactive-tools#require-sign-in) |

## Be found by tool search

Clients with many connected servers load tool definitions only when a request matches them. Claude calls this tool search. The model then sees your server's name and instructions first, and each tool's name and description when it searches, so those words decide whether your tool is used:

- Begin the name with the action and the object: `list_orders`, `start_return`.
- Put the words a person would use in the first sentence of the description. Put the argument rules in the schema.
- Describe every argument, because search reads those descriptions too.
- Keep server instructions and each description under 2,000 characters, with the essential sentence first.
- Set `title`, and mark read-only tools, so a client can show a person what will run.
- Prefer a few tools with clear jobs over many near-duplicates, and move a long procedure into a [skill](/docs/mcp-skills).

An agent inside your own application searches tools the same way with [tool catalogs](/docs/agent-sdk#dynamic-tool-discovery).
