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. 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.

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:

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)".

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.

LimitHow it affects your query
16 KiB of JavaScriptSend the function body as code.
Five seconds per runThe 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 runCalls run one at a time, including inside Promise.all.
128 KiB per message between worker and HubRequest 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 defaultStarting a run and each admitted tool call count. The outfit query uses four when it finds an event.
One active run per connectionEach 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

ferrite add mcp

Before signing in to Ferrite on a machine, pass --registry https://packages.ferrite.cloud/registry.json. See 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:

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

{
  "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. 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.

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 for the full discovery surface.

Follow changes and long-running work

Use MCP Events for event discovery, delivery modes, and client examples, and MCP Tasks for resumable long-running operations, client examples, and deployment tracking. Events support is experimental; check the 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.

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 PageSourceWhat it addsGuide
skillsWorkflow skills a client loads by nameMCP Skills
task_tools, task_call, task_streamingTools that return a task handleMCP Tasks
events, poll_event, event_delivery, event_callEvent types and how they are deliveredMCP Events
mcp_tool_call_mrtrQuestions to the person before a tool runsAsk before acting
mcp_files_config, mcp_file_httpFile arguments, upload targets and downloadsMCP file transfers
mcp_ui_resourcesInteractive views linked to toolsMCP Apps
mcp_resourcesDocuments a client can list and read
mcp_prompts, mcp_prompt_getPrompt templates a person can pick
mcp_tool_hintsTitles, destructive and open-world annotations, iconsInteractive MCP tools
mcp_auth, mcp_authorizeOAuth sign-in for the endpointInteractive MCP tools

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.

An agent inside your own application searches tools the same way with tool catalogs.