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

# Server

> The Mirage server in TypeScript, a Fastify app that holds workspaces and serves HTTP, MCP, RPC and SSH.

The Mirage server is a Fastify app from `@struktoai/mirage-server`. It holds workspaces and serves them over the [HTTP](https://docs.mirage.strukto.ai/home/access/http.md) routes, [MCP](https://docs.mirage.strukto.ai/home/access/mcp.md) and [RPC](https://docs.mirage.strukto.ai/home/access/rpc.md), and over [SSH](https://docs.mirage.strukto.ai/home/access/ssh.md), on its own port when `ssh_port` is set and through its HTTP port either way. The Python server speaks the same protocol, so a client of one works against the other.

## Install

```bash npm theme={null}
npm install @struktoai/mirage-server
```

```bash with SSH theme={null}
npm install @struktoai/mirage-server ssh2
```

The SSH server runs on [ssh2](https://github.com/mscdex/ssh2), installed beside the server, needed only for SSH.

## Run it

`buildApp` returns the Fastify instance; it serves until you stop it.

```ts theme={null}
import { buildApp } from '@struktoai/mirage-server'

const app = buildApp()
await app.listen({ host: '127.0.0.1', port: 8765 })
```

| Option | Default | Meaning |
| - | - | - |
| `authConfig` | from `MIRAGE_AUTH_MODE` | Token or JWT [configuration](https://docs.mirage.strukto.ai/home/access/http.md#configure-authentication). |
| `allowedHosts` | `MIRAGE_ALLOWED_HOSTS`, else loopback | `Host` headers accepted by the server. `['*']` turns the check off, safe only behind a trusted proxy. Browser requests from another origin are refused either way. |
| `maxWorkspaces` | `MIRAGE_MAX_WORKSPACES`, else the `max_workspaces` key, else no cap | The most workspaces the app holds at once. A create, clone or load past it answers 503, and the ones it holds keep running. |
| `policies` | none | The server's own [policies](https://docs.mirage.strukto.ai/home/access/http.md#server-policies): each answers `preWorkspace` before a workspace is built, and is registered on every workspace the app builds. |
| `policyFile` | `MIRAGE_POLICY_FILE`, else the `policy_file` key, else none | A file of policy programs that answer the same way. |
| `maxSessions` | `MIRAGE_MAX_SESSIONS`, else the `max_sessions` key, else `16` | The most sessions each workspace holds, its default session among them. A new session past it, over HTTP or SSH, answers 429. |
| `maxMemory` | `MIRAGE_MAX_MEMORY`, else the `max_memory` key, else none | The most any workspace's `max_memory` reaches, as a [size](https://docs.mirage.strukto.ai/home/configuration/workspace.md#sizes). A workspace that sets more, or lifts its cap, gets this. |
| `maxProcesses` | `MIRAGE_MAX_PROCESSES`, else the `max_processes` key, else none | The most any session's `processes.max` reaches, whatever a config or profile sets. |
| `maxLineSeconds` | `MIRAGE_MAX_LINE_SECONDS`, else the `max_line_seconds` key, else none | The most seconds any line runs, whatever `@line` a config or profile sets. A line past it exits 124. |
| `maxEnv` | `MIRAGE_MAX_ENV`, else the `max_env` key, else none | The most any workspace's `max_env` reaches, as a [size](https://docs.mirage.strukto.ai/home/configuration/workspace.md#sizes). |
| `rateLimits` | `MIRAGE_RATE_LIMITS`, else the `rate_limits` key, else `ip=1000/minute` | A list of `{ key, rate }`; an empty list disables limits. See [Rate limits](https://docs.mirage.strukto.ai/home/access/http.md#rate-limits). |
| `forwardedAllowIps` | `MIRAGE_FORWARDED_ALLOW_IPS`, else the `forwarded_allow_ips` key, else none | The proxies, addresses or networks, whose `X-Forwarded-For` names the client. `['*']` believes any. |
| `gracefulTimeout` | `MIRAGE_GRACEFUL_TIMEOUT`, else the `graceful_timeout` key, else `0` | Seconds running lines get to finish on `app.close()` before they are cancelled. New work is refused meanwhile. |
| `sshConfig` | from the `ssh_*` settings | The SSH server, opened when the app is ready; off unless a port is set. |
| `snapshotStore` | none | An `S3Config`: the store a snapshot request may name a key in. Without one, a snapshot only goes back to the caller; the server never writes one to its own disk. |
| `stateRoot` | under `$MIRAGE_HOME` | Where live state is kept. |
| `idleGraceSeconds` | `30` | Seconds the last workspace may be gone before `onIdleExit` is called. |
| `pidFile` | `$MIRAGE_HOME/daemon.pid` | PID file path, exposed as `app.pidFile`. Only the daemon writes it. |
| `onIdleExit` | a no-op | Called when the last workspace has been gone `idleGraceSeconds` (30), or on `POST /v1/daemon/shutdown`. |

## Workers

By default the daemon is one process, and one thread holds every workspace. With `workers` above 1 (`MIRAGE_WORKERS`, or the `workers` key), it runs that many workers, each the whole server on a Unix socket of its own, and its own server passes each request to the worker holding the workspace. A new workspace goes to a worker at random. The workspaces on one worker share its event loop, and the OS spreads the workers over the CPUs.

`worker_type` (`MIRAGE_WORKER_TYPE`, or the `worker_type` key) is `thread` or `process`. TypeScript defaults to threads. Python defaults to threads on an interpreter without the GIL (3.14t) and to processes otherwise, since threads under the GIL take turns.

The daemon answers `/v1/health` and `/v1/daemon/ready` itself, merges their `GET /v1/workspaces` lists, and holds `max_workspaces` across the workers. A worker that exits stays gone, and so do its workspaces. Each worker counts its own rate limits, so a limit keyed on the address or the account allows that many requests per worker. The SSH port is one server's, so it does not combine with workers yet.

## Started by the CLI

`@struktoai/mirage-cli` runs the same app as a daemon, `mirage-daemon`, on `127.0.0.1:8765` in local auth mode, logging to `~/.mirage/daemon.log`. That entry adds the two daemon behaviors: it writes `$MIRAGE_HOME/daemon.pid` for `mirage daemon stop` and `kill`, and exits 30 seconds (`MIRAGE_IDLE_GRACE_SECONDS`) after its last running workspace stops or is deleted. It listens on `MIRAGE_DAEMON_PORT`, the `port` setting, or `8765`. Its settings are on the [CLI page](https://docs.mirage.strukto.ai/home/access/cli.md#daemon-config).

## MCP and RPC on their own

The [MCP](https://docs.mirage.strukto.ai/home/access/mcp.md) and [RPC](https://docs.mirage.strukto.ai/home/access/rpc.md) servers can run over a transport of your own, without the Mirage server. Both serve one session of a [workspace](https://docs.mirage.strukto.ai/typescript/access/in-app.md).

```ts theme={null}
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio'
import { createMirageMcpServer } from '@struktoai/mirage-server/mcp'

const server = createMirageMcpServer(ws, { sessionId: 'agent' })
await server.connect(new StdioServerTransport())
```

`createMirageMcpServer(ws, { sessionId?, operations?, name?, version?, staleWriteProtection?, allCalls? })` returns the MCP SDK's `McpServer`. `allCalls: true` adds the [VFS calls and explain](https://docs.mirage.strukto.ai/home/access/mcp.md#vfs-calls).

```ts theme={null}
import { MirageRpcServer } from '@struktoai/mirage-server/rpc'

const server = new MirageRpcServer(ws, { sessionId: 'agent' })
const response = await server.handle({
  jsonrpc: '2.0',
  id: 1,
  method: 'vfs/readdir',
  params: { path: '/' },
})
```

`new MirageRpcServer(ws, { sessionId?, operations?, name?, version? })`. `handle(message)` processes a message and returns its response (`null` for a notification). `serve(lines, write)` processes each line of an async iterable until it ends.

## What is particular to this server

The protocol is the same on both servers. These are the differences in how this one serves it:

* **No legacy `scp -O`.** Modern `scp` uses SFTP, which is served; the old SCP protocol is not.
* **`authorized_keys` options.** `mirage-profile` and `mirage-account` are read: the first binds the key to a [profile](https://docs.mirage.strukto.ai/home/access/ssh.md#auth-optional), the second opens only that [account](https://docs.mirage.strukto.ai/home/access/http.md#accounts)'s workspaces. A key line carrying any other option (`from=`, `command=`, ...) is skipped with a warning, rather than accepted as if it had none.
* **Terminal line limit.** 1024 bytes.
* **One event loop.** Every workspace shares Node's loop. Shell evaluation yields between steps, but a long synchronous step in a JavaScript callback or a CPU-heavy runtime holds every workspace until it returns, so run such work in a worker.

## Code map

| Path | What |
| - | - |
| [`packages/server/src/app.ts`](https://github.com/strukto-ai/mirage/blob/main/typescript/packages/server/src/app.ts) | `buildApp`: routers, MCP and RPC endpoints, the SSH server. |
| [`packages/server/src/bin/daemon.ts`](https://github.com/strukto-ai/mirage/blob/main/typescript/packages/server/src/bin/daemon.ts) | `mirage-daemon`, the daemon entry the CLI starts. |
| [`packages/server/src/routers/`](https://github.com/strukto-ai/mirage/tree/main/typescript/packages/server/src/routers) | The HTTP routes: workspaces, sessions, shell, tools, jobs, asks. |
| [`packages/server/src/mcp/`](https://github.com/strukto-ai/mirage/tree/main/typescript/packages/server/src/mcp) | `createMirageMcpServer`, the `/mcp` endpoint, and the stdio relay `mirage mcp` runs. |
| [`packages/server/src/rpc/`](https://github.com/strukto-ai/mirage/tree/main/typescript/packages/server/src/rpc) | `MirageRpcServer`, the `/rpc` endpoint, and the stdio relay `mirage rpc` runs. |
| [`packages/server/src/ssh/`](https://github.com/strukto-ai/mirage/tree/main/typescript/packages/server/src/ssh) | The SSH server: shell, exec and SFTP. |
| [`packages/core/src/workspace/tools/`](https://github.com/strukto-ai/mirage/tree/main/typescript/packages/core/src/workspace/tools) | The agent tool table behind `session.tools`, which every interface calls. |
| [`packages/cli/src/`](https://github.com/strukto-ai/mirage/tree/main/typescript/packages/cli/src) | The `mirage` CLI, one module per verb. |

## Custom VFS calls and streaming reads

`POST /v1/workspaces/{id}/vfs/{name}` dispatches a registered VFS operation with
JSON `{ "path": "/data/item", "kwargs": {} }` and answers `{ "value": ... }`.
It uses the authenticated request's session and the ordinary dispatcher; callers
cannot override session or admission fields. Binary values use the server's
base64 JSON representation.

`POST /v1/workspaces/{id}/vfs/read` with `{ "path": "/data/item", "stream": true }`
streams `application/octet-stream`. It uses the same authentication and file
policy as other VFS routes, with bounded reads and cancellation cleanup.


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