> ## 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 Python, a FastAPI app that holds workspaces and serves HTTP, MCP, RPC and SSH.

The Mirage server is a FastAPI app. 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 TypeScript server speaks the same protocol, so a client of one works against the other.

## Install

```bash pip theme={null}
pip install mirage-ai
```

```bash with SSH theme={null}
pip install 'mirage-ai[ssh]'
```

The `ssh` extra adds [asyncssh](https://asyncssh.readthedocs.io), needed only for the SSH server.

## Run it

`build_app` returns the app. Run it with any ASGI server; it serves until you stop it.

```python theme={null}
import uvicorn

from mirage.server.app import build_app

app = build_app()
uvicorn.run(app, host="127.0.0.1", port=8765)
```

| Argument | Default | Meaning |
| - | - | - |
| `auth_config` | from `MIRAGE_AUTH_MODE` | Token or JWT [configuration](https://docs.mirage.strukto.ai/home/access/http.md#configure-authentication). |
| `allowed_hosts` | `MIRAGE_ALLOWED_HOSTS`, else loopback | `Host` names the app answers. `["*"]` turns the check off, safe only behind a trusted proxy. Browser requests from another origin are refused either way. |
| `max_workspaces` | `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 `pre_workspace` before a workspace is built, and is registered on every workspace the app builds. |
| `policy_file` | `MIRAGE_POLICY_FILE`, else the `policy_file` key, else none | A file of policy programs that answer the same way. |
| `max_sessions` | `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. |
| `max_memory` | `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. |
| `max_processes` | `MIRAGE_MAX_PROCESSES`, else the `max_processes` key, else none | The most any session's `processes.max` reaches, whatever a config or profile sets. |
| `max_line_seconds` | `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. |
| `max_env` | `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). |
| `rate_limits` | `MIRAGE_RATE_LIMITS`, else the `rate_limits` key, else `ip=1000/minute` | A list of `RateLimit(key, rate)`; an empty list disables limits. See [Rate limits](https://docs.mirage.strukto.ai/home/access/http.md#rate-limits). |
| `forwarded_allow_ips` | `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. |
| `graceful_timeout` | `MIRAGE_GRACEFUL_TIMEOUT`, else the `graceful_timeout` key, else `0` | Seconds running lines get to finish on SIGTERM or SIGINT before they are cancelled. New work is refused meanwhile. |
| `ssh_config` | from the `ssh_*` settings | The SSH server, opened with the app; off unless a port is set. |
| `snapshot_store` | `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. |
| `state_root` | under `$MIRAGE_HOME` | Where live state is kept. |
| `on_idle_exit` | `None` | Called when the last workspace has been gone `idle_grace_seconds` (30), or on `POST /v1/daemon/shutdown`. `None` keeps serving. |
| `pid_file` | `None` | A file that holds the process id while the app runs. |

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

The CLI runs the same app as a daemon, `mirage.server.daemon:app`, on `127.0.0.1:8765` in local auth mode, logging to `~/.mirage/daemon.log`. That entry adds the daemon behaviors: it writes `$MIRAGE_HOME/daemon.pid` for `mirage daemon stop` and `kill`, exits 30 seconds (`MIRAGE_IDLE_GRACE_SECONDS`) after its last running workspace stops or is deleted, and tunes the interpreter as it starts. It collects and freezes what startup made, so a full collection no longer scans it, raises the young collection threshold to 10,000, and sets the GIL switch interval to 1 ms. These settings are process-wide, so an app you run with `build_app` keeps its own. Make them yourself to get the same fairness: a busy line yields its workspace's loop every two GIL switch intervals, so under Python's default 5 ms a line in another session waits on 10 ms turns, and under 1 ms on 2 ms turns.

```python theme={null}
import gc
import sys

gc.collect()
gc.freeze()
gc.set_threshold(10_000, *gc.get_threshold()[1:])
sys.setswitchinterval(0.001)
```

Its other settings are on the [Server](https://docs.mirage.strukto.ai/home/configuration/server.md) page.

## Beside your own event loop

`WorkspaceRunner` pins a [workspace](https://docs.mirage.strukto.ai/python/access/in-app.md) to a thread and event loop of its own. A line waiting on I/O then never stalls your app's loop, and workspaces in one process never wait on each other's I/O. CPU-bound work still shares the GIL with every other thread in the process. The Mirage server hosts every workspace this way.

```python theme={null}
from mirage.workspace.runner import WorkspaceRunner

runner = WorkspaceRunner(ws)
result = await runner.call(runner.ws.shell("ls /"))
await runner.stop()
```

`call` runs a coroutine on the workspace's loop and is safe from any other loop; cancelling the caller cancels the coroutine. `stop` closes the workspace (`delete=True` also deletes its state), then stops the loop and refuses new calls.

## 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 are classes you can run over a transport of your own, without the Mirage server. Both serve one session of a [workspace](https://docs.mirage.strukto.ai/python/access/in-app.md).

```python theme={null}
from mcp.server.stdio import stdio_server

from mirage.server.mcp import MirageMcpServer

server = MirageMcpServer(ws, session_id="agent").server
async with stdio_server() as (read, write):
    options = server.create_initialization_options()
    await server.run(read, write, options)
```

`MirageMcpServer(workspace, stale_write_protection=True, name="mirage", version=..., session_id=None, operations=None, all_calls=False)`. Its `server` is the MCP SDK's low-level `Server`. `all_calls=True` adds the [VFS calls and explain](https://docs.mirage.strukto.ai/home/access/mcp.md#vfs-calls).

```python theme={null}
from mirage.server.rpc import MirageRpcServer

server = MirageRpcServer(ws, session_id="agent")
answer = await server.handle({
    "jsonrpc": "2.0",
    "id": 1,
    "method": "vfs/readdir",
    "params": {"path": "/"},
})
```

`MirageRpcServer(workspace, session_id=None, operations=None, name="mirage", version=...)`. `handle(message)` answers one message, and `None` for a notification. `serve(read_line, write_line)` answers newline-delimited messages until `read_line` returns `""`.

## What is particular to this server

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

* **Legacy `scp -O`.** The SCP protocol is served, as well as SFTP.
* **`authorized_keys` options.** asyncssh enforces OpenSSH's options (`from=`, `command=`, ...), and `command=` forces the line that runs. `mirage-profile` binds the key to a [profile](https://docs.mirage.strukto.ai/home/access/ssh.md#auth-optional) and `mirage-account` opens only that [account](https://docs.mirage.strukto.ai/home/access/http.md#accounts)'s workspaces.
* **Terminal line limit.** 1024 characters.
* **A thread per workspace.** Each workspace runs on its own thread and event loop through a [`WorkspaceRunner`](#beside-your-own-event-loop), so a busy workspace does not hold up another or the HTTP server.

## Code map

| Path | What |
| - | - |
| [`mirage/server/app.py`](https://github.com/strukto-ai/mirage/blob/main/python/mirage/server/app.py) | `build_app`: routers, MCP and RPC endpoints, the SSH lifespan. |
| [`mirage/server/daemon.py`](https://github.com/strukto-ai/mirage/blob/main/python/mirage/server/daemon.py) | The daemon entry the CLI starts. |
| [`mirage/server/routers/`](https://github.com/strukto-ai/mirage/tree/main/python/mirage/server/routers) | The HTTP routes: workspaces, sessions, shell, tools, jobs, asks. |
| [`mirage/server/mcp/`](https://github.com/strukto-ai/mirage/tree/main/python/mirage/server/mcp) | `MirageMcpServer`, the `/mcp` endpoint, and the stdio relay `mirage mcp` runs. |
| [`mirage/server/rpc/`](https://github.com/strukto-ai/mirage/tree/main/python/mirage/server/rpc) | `MirageRpcServer`, the `/rpc` endpoint, and the stdio relay `mirage rpc` runs. |
| [`mirage/server/ssh/`](https://github.com/strukto-ai/mirage/tree/main/python/mirage/server/ssh) | The SSH server: shell, exec, SFTP and SCP. |
| [`mirage/workspace/tools/`](https://github.com/strukto-ai/mirage/tree/main/python/mirage/workspace/tools) | The agent tool table behind `session.tools`, which every interface calls. |
| [`mirage/cli/`](https://github.com/strukto-ai/mirage/tree/main/python/mirage/cli) | 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.