# Export and Run the Server

> Create the MCP server from <rapi-doc>, the command line or Node, what the exported project holds, how it runs, and how to connect an AI app to it.

The [manifest](/docs/mcp/#the-manifest) ships in a small TypeScript project you can run as it is. This page covers the runtime and the project, the ways to create them, and how an AI app starts the server.

## The Runtime and the Exported Project

### The runtime

`runtime.js` executes any tool in the manifest with `fetch`, so the same file runs in Node, browsers and edge workers. `createMcpRuntime(manifest, { fetch, credentials, baseUrls })` returns `listTools()`, `listResources()`, `callTool(name, args)` and `readResource(uri)`. A tool call:

1. Puts each argument where `operation.params` says, percent-encoding path parameters and serializing arrays as repeated query parameters. A path argument of `.` or `..` is an error, because a URL would resolve it to another path.
2. Applies the security scheme: an API key in a header, query parameter or cookie; HTTP Basic; a Bearer token for HTTP bearer, OAuth 2 and OpenID Connect. For OAuth 2 and OpenID Connect you supply an access token you already have: the runtime does not sign in or refresh a token.
3. Sends the request and returns an MCP result: `content` with the JSON response pretty-printed, `structuredContent` when the response is a JSON object, and `isError` with the HTTP status and body on a 4xx or 5xx.

### What is in the zip

**Export MCP Server** downloads `<server-name>-mcp.zip` (a server name that already ends in `-mcp` is not suffixed again):

| File | Purpose |
| :--- | :--- |
| `manifest.json` | The manifest described above |
| `runtime.js` | The runtime for operation tools; identical for every API |
| `workflow-runtime.js` | Runs workflow tools; present only when the manifest has workflows, identical for every API |
| `server.ts` | A stdio server on `@modelcontextprotocol/sdk` that registers the manifest's tools and resources and hands every call to the runtime; identical for every API |
| `package.json` | Depends on `@modelcontextprotocol/sdk`; `tsx` as a dev dependency; `npm start` runs `tsx server.ts` |
| `README.md` | How to run it and which environment variables it reads |
| `mcp.json` | A ready-made `mcpServers` entry for Claude Desktop, Cursor and other MCP hosts |

### Running it

```bash
unzip commerce-fulfillment-api-mcp.zip -d commerce-fulfillment-api-mcp
cd commerce-fulfillment-api-mcp
npm install
MCP_AUTH_API_KEY="your-key" npm start
```

When the server is up, `npm start` prints a line such as `[MCP] my_api: 2 tools on stdio`; stop it with Ctrl+C. When the manifest has no base URL and `MCP_BASE_URL` is not set, it prints that first, and every tool call answers with that error. It also starts without credentials, and calls then return the API's error. `server.ts` and the runtimes are the same for every API, so `manifest.json` is the one file to review.

### Environment variables

Every variable the server reads starts with `MCP_`. The project's `README.md` and `mcp.json` name the exact ones for your API. `rapidoc mcp serve` and the `/mcp` endpoint of `rapidoc serve` read the same variables.

| Variable | What it is |
| :--- | :--- |
| `MCP_AUTH_<SCHEME>` | The credential of a security scheme: an API key or a bearer token. `<SCHEME>` is the scheme's id in the OpenAPI spec, in upper snake case: `petstore_auth` (or `petstoreAuth`) reads `MCP_AUTH_PETSTORE_AUTH`, `api_key` reads `MCP_AUTH_API_KEY` |
| `MCP_AUTH_<SCHEME>_USERNAME`, `MCP_AUTH_<SCHEME>_PASSWORD` | The same for an HTTP Basic scheme |
| `MCP_BASE_URL` | The API's base URL. It overrides the one in the manifest, and is required when the manifest has none (a spec with a relative server URL or no `servers`, read from a file) |
| `MCP_BASE_URL_<SOURCE>` | The base URL of each API when the server has several (workflows over more than one OpenAPI spec). `<SOURCE>` is the source's name in the Arazzo spec, in upper snake case. `MCP_BASE_URL` is then refused, so one API's credentials never go to another API's host |
| `MCP_EXTERNAL_HOSTS` | Hosts, comma-separated (`*` for any), that a workflow step's [`x-operation`](https://flow.rapidocui.com/docs/extensions/#calls-outside-the-api-sources-x-operation) URL computed at run time may go to, besides those the workflow names |

The agent never sees or supplies a credential: the server adds it to each request. Each scheme has its own variable and there is no shared fallback, so one key is never sent as another scheme's credential, and a scheme named `token` or `path` reads `MCP_AUTH_TOKEN` or `MCP_AUTH_PATH`, never `$TOKEN` or `$PATH`. Two schemes whose ids give the same variable (`api-key` and `apiKey`) stop the export with a message that names both: rename one in the spec.

### Workflows as tools

When the page also has a [`<rapi-flow>`](https://flow.rapidocui.com/) element tied to the `<rapi-doc>` (or you pass `--arazzo` to `rapidoc mcp`), the export adds one tool per Arazzo workflow. The manifest's `workflows` holds each workflow's steps with their operations resolved, and the runtime runs them: inputs become the tool's arguments (one left out gets its `default` from the workflow's `inputs` schema), every step's parameters and body are filled from `$inputs` and earlier steps' outputs, success criteria are checked (a step without criteria succeeds on a 2xx response), `onSuccess` / `onFailure` actions (`end`, `goto`, `retry`) are followed, and the workflow's `outputs` are the result. The same runtime powers the **Run** button of `<rapi-flow>`, which runs a workflow in the browser with the credentials entered in the tied `<rapi-doc>` and lights up each step. A workflow that uses something the runtime does not run yet (a step that calls another workflow, `regex` / `jsonpath` / `xpath` criteria) is left out, and `generateMcpServer().problems` says why.

For a server with only the workflow tools, and no tool per operation, export from `<rapi-flow>` itself: with `mcp="true"` it shows its own **Export MCP Server** button (see [Workflows](https://flow.rapidocui.com/)). Its steps call every API source of the Arazzo spec, where `<rapi-doc>` knows one. A short list of task-sized tools is often easier for a model to use, and cheaper in tokens. From `<rapi-doc>`'s code, `downloadMcpServer({ includeOperations: false })` builds the same for its one API (`<server-name>-workflows-mcp.zip`).

```javascript
import { buildMcpManifest, createMcpRuntime, credentialsFromEnv, parseArazzo } from '@rapidoc/mcp';

const arazzo = parseArazzo(readFileSync('petstore.arazzo.yaml', 'utf8'));
const manifest = buildMcpManifest(spec, { arazzo, onProblem: console.warn });
const runtime = createMcpRuntime(manifest, { credentials: credentialsFromEnv(manifest, process.env) });
const result = await runtime.callTool('adopt_pet', { quantity: 1 }, {
  onStep: (step) => console.log(step.stepId, step.outcome, step.response?.status),
});
```

## Creating the server

### In `<rapi-doc>`

The `mcp` attribute shows an **Export MCP Server** button that downloads the project as a zip, and the element's methods build the same in code. Both are on [Export MCP Server](/docs/rapidoc/mcp-export/) in RapiDoc's docs.

### From the command line

`npx rapidoc mcp export openapi.yaml` writes the same project as the Export button, and `npx rapidoc mcp serve openapi.yaml` runs the server over stdio without writing files ([Command Line](/docs/cli/mcp/)):

```bash
npx rapidoc mcp export my-api.yaml --out-dir my-api-mcp --server-name my-api
```

### In Node: `@rapidoc/mcp`

The same builder, runtime and project writer are available without the browser or any element, for build scripts and servers:

```bash
npm install @rapidoc/mcp
```

```javascript
import { readFileSync } from 'node:fs';
import {
  buildMcpManifest,
  createMcpRuntime,
  credentialsFromEnv,
  writeMcpProject,
} from '@rapidoc/mcp';

// The spec as an object. For a YAML file, install a YAML package (npm install yaml) and parse it.
const spec = JSON.parse(readFileSync('openapi.json', 'utf8'));
const manifest = buildMcpManifest(spec, { serverName: 'petstore' });

// Call a tool directly. Credentials are by security scheme id: { api_key: '...' },
// here read from MCP_AUTH_API_KEY and the other MCP_AUTH_<SCHEME> variables
const runtime = createMcpRuntime(manifest, { credentials: credentialsFromEnv(manifest, process.env) });
const result = await runtime.callTool('get_pet_by_id', { petId: 1 });

// Or write the same project the Export button downloads
const files = writeMcpProject(manifest); // path → text

// When you know where the project will live, put the real path in mcp.json
writeMcpProject(manifest, { serverPath: '/srv/petstore-mcp/server.ts' });
```

`@rapidoc/mcp` ships TypeScript types (`McpManifest`, `McpRuntime`, ...). Its only dependency is `js-yaml` (for Arazzo specs); requests use Node's `fetch`. `buildMcpManifest` takes `specUrl`, the address the spec was loaded from, to resolve a relative server URL; without a base URL in the manifest, pass `baseUrls: { api: 'https://...' }` to `createMcpRuntime`.

## Connecting an AI App

Every exported project includes `mcp.json`, a ready-to-use `mcpServers` entry. It is a template: nothing is added to your AI app until you copy it into the app's configuration. Any app that can start a local MCP server over stdio can use the server: **Claude Desktop**, **Cursor**, Claude Code, Codex and others. Most read this JSON format; an app with another format (Codex uses TOML) takes the same command, arguments and variables. The entry's `env` has one variable per credential in the spec (none when the spec declares no security scheme), and `MCP_BASE_URL` when the manifest has no base URL.

Add the entry to the `mcpServers` object of the app's own configuration file, keeping the entries already there, and replace the placeholder path in `args` with the absolute path of the unzipped folder's `server.ts` (`rapidoc mcp export` writes the real path). Run `npm install` in that folder first. The app starts the server itself, as a child process that talks over stdin and stdout; it listens on no port, and `npm start` is only for trying it out.

| App | Configuration file |
| :--- | :--- |
| Claude Desktop, macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| Claude Desktop, Windows | `%APPDATA%\Claude\claude_desktop_config.json` |
| Cursor | `~/.cursor/mcp.json`, or `.cursor/mcp.json` in a project |
| Claude Code | `.mcp.json` in a project |
| Codex | `~/.codex/config.toml`: a `[mcp_servers.<name>]` section with the same `command`, `args` and `env`, written as TOML |

> **Caution:**
> Every tool call is a real request to your API, made with the credentials you set. Use a key with only the permissions the agent should have, or point `MCP_BASE_URL` at a staging server. Leaving an operation out of the export keeps it off the tool list; it is not access control.
>
>   - The safety annotations are hints for the AI app; the server has no confirmation step of its own.
>   - The OpenAPI spec's text and the API's responses reach the model as they are. Export only from specs you trust.
>   - The server talks over stdio, so it works with AI apps on your machine. A hosted or remote AI app can't reach it.

For the Swagger Petstore, which declares the schemes `api_key` and `petstore_auth`:

```json
{
  "mcpServers": {
    "petstore_mcp": {
      "command": "npx",
      "args": ["-y", "tsx", "/absolute/path/to/petstore-mcp/server.ts"],
      "env": {
        "MCP_AUTH_PETSTORE_AUTH": "your-petstore-auth",
        "MCP_AUTH_API_KEY": "your-api-key"
      }
    }
  }
}
```

Restart the app after changing its configuration. If the tools don't appear, check that the path in `args` is absolute (the app starts the server from its own folder) and correct, and that `npm install` ran in the project; the app's MCP log shows why a server didn't start.
