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

# HTTP

> Start and configure a self-hosted Mirage HTTP server.

Run the Python or TypeScript server to access your Mirage workspaces over HTTP.
This guide covers setup, authentication, limits, and server operations.
Use the [API reference](https://docs.mirage.strukto.ai/api/reference.md) for endpoint fields and responses.

## Launch a server

Set a token in the server's environment before starting the process:

```bash theme={null}
export MIRAGE_AUTH_MODE=token
export MIRAGE_AUTH_TOKEN='replace-with-your-token'
```

> [tab] Python
>
> In an activated Python environment, install the server:
>
> ```bash theme={null}
> python -m pip install mirage-ai
> ```
>
> Save this as `server.py`:
>
> ```python server.py theme={null}
> import uvicorn
>
> from mirage.server.app import build_app
>
> uvicorn.run(build_app(), host="127.0.0.1", port=8765)
> ```
>
> Start it in the terminal where you set the token, and leave it running:
>
> ```bash theme={null}
> python server.py
> ```

> [tab] TypeScript
>
> In your Node project, install the server and TypeScript runner:
>
> ```bash theme={null}
> npm install @struktoai/mirage-server
> npm install -D tsx typescript
> ```
>
> Save this as `server.mts`. The `.mts` extension uses ES modules without
> changing how other files in your project load:
>
> ```typescript server.mts theme={null}
> import { buildApp } from '@struktoai/mirage-server'
>
> await buildApp().listen({ host: '127.0.0.1', port: 8765 })
> ```
>
> Start it in the terminal where you set the token, and leave it running:
>
> ```bash theme={null}
> npx tsx server.mts
> ```

The server accepts only the host names in `MIRAGE_ALLOWED_HOSTS`: `127.0.0.1`,
`localhost` and `::1` by default. Add the name your clients use. It also
refuses a browser page served from any other origin, a page on another port of
`localhost` included, even when the list is `*`. Other options
are on the [Python](https://docs.mirage.strukto.ai/python/access/server.md) and [TypeScript](https://docs.mirage.strukto.ai/typescript/access/server.md)
server pages.

## Verify the connection

From another terminal, check that the server is running:

```bash theme={null}
curl --fail --silent --show-error http://127.0.0.1:8765/v1/health
```

The response includes `"status": "ok"`. Health checks do not require a token.
Use `http://127.0.0.1:8765` as the base URL for requests to this server and send
`Authorization: Bearer <your-token>` on authenticated requests.

For workspace creation and command execution, see
[Create a workspace](https://docs.mirage.strukto.ai/api/operations/workspaces/create-workspace.md) and
[Run shell command](https://docs.mirage.strukto.ai/api/operations/shell/run-shell-command.md).
Replace the example API host with your server's base URL.

## Configure authentication

`MIRAGE_AUTH_MODE` picks what the server accepts on its HTTP, MCP and RPC routes.

| Mode | Accepts | Set on the server |
| - | - | - |
| `local` (default) | The configured token or `~/.mirage/auth_token` if either exists, otherwise any request | `MIRAGE_AUTH_TOKEN` (optional) |
| `token` | One shared token | `MIRAGE_AUTH_TOKEN` |
| `jwt` | A signed JWT, whose `sub` is the caller's [account](#accounts) | the [JWT settings](#jwt) |

### JWT

Point the server at your issuer's keys:

```bash theme={null}
export MIRAGE_AUTH_MODE=jwt
export MIRAGE_JWT_ALG=RS256
export MIRAGE_JWT_JWKS_URL=https://issuer.example.com/.well-known/jwks.json
export MIRAGE_JWT_ISSUER=https://issuer.example.com
export MIRAGE_JWT_AUDIENCE=https://mirage.example.com
```

Every token needs `exp` and `sub`. A token with `aud` must name an entry in
`MIRAGE_JWT_AUDIENCE`; with none set, every such token is refused.

| Setting | Does |
| - | - |
| `MIRAGE_JWT_ALG` | The one algorithm accepted, such as `RS256`. Required. |
| `MIRAGE_JWT_JWKS_URL` | Fetch the signing keys from this URL. Rotating them needs no restart. |
| `MIRAGE_JWT_PUBKEY`, `MIRAGE_JWT_PUBKEY_FILE` | A fixed key instead of a JWKS URL. Changing it needs a restart. |
| `MIRAGE_JWT_ISSUER` | Require this `iss`. |
| `MIRAGE_JWT_AUDIENCE` | The `aud` values a token may name, comma-separated. |
| `MIRAGE_JWT_AUTHORIZED_PARTIES` | The `azp` values a token without `aud` may name, comma-separated. |
| `MIRAGE_JWT_CLOCK_SKEW_SECONDS` | Clock difference allowed when checking times. Default `5`. |

Set one of the JWKS URL or a fixed key, not both.

In the `[daemon]` section of `config.toml`, each setting is its name without
`MIRAGE_`, in lower case, such as `jwt_alg`.

> [accordion] Accept both app session tokens and OAuth access tokens
>
> A token with `aud` must name an entry in `MIRAGE_JWT_AUDIENCE`. A token
> without `aud` needs an `azp` in `MIRAGE_JWT_AUTHORIZED_PARTIES` when that is
> set, and is refused when only an audience is set. So one server can accept an
> app's session tokens (`azp`) and an OAuth client's access tokens (`aud`), as
> Clerk issues them:
>
> ```bash theme={null}
> export MIRAGE_AUTH_MODE=jwt
> export MIRAGE_JWT_ALG=RS256
> export MIRAGE_JWT_JWKS_URL=https://clerk.example.com/.well-known/jwks.json
> export MIRAGE_JWT_ISSUER=https://clerk.example.com
> export MIRAGE_JWT_AUTHORIZED_PARTIES=https://app.example.com
> export MIRAGE_JWT_AUDIENCE=client_cli
> ```
>
> To let `mirage login` sign in to this server, see
> [Log in](https://docs.mirage.strukto.ai/home/access/cli.md#log-in).

### Accounts

In `jwt` mode, a token's `sub` is its account, and an account reaches only the
workspaces it created. Another account's workspace, session or ask returns
HTTP 404 Not Found, matching a missing resource. An [SSH key](https://docs.mirage.strukto.ai/home/access/ssh.md#auth-optional)
joins an account with its `mirage-account` option.

> [accordion] What else an account changes
>
> * `GET /v1/workspaces` lists only the caller's.
> * A stored workspace reopens after a restart only for its owner. One stored
>   before the server used `jwt` mode has no owner, and no account can create
>   its id.
> * Snapshot keys live under `accounts/<account>/` in the snapshot store.
> * `POST /v1/daemon/shutdown` returns HTTP 403 Forbidden.

> [!WARNING]
>
> Accounts keep workspaces apart, not the host: a workspace config can still
> mount a host directory or run a `host` machine, unless a
> [server policy](#server-policies) refuses it. In `local` and `token` mode,
> any accepted token can use every route and every workspace, including
> `POST /v1/daemon/shutdown`.

## Rate limits

By default, the server allows 1000 requests per minute per client IP, counted
before authentication so rejected tokens consume the same budget. Configured
limits replace this default; include an `ip` limit to keep unauthenticated
requests bounded. An explicit empty list in code or `rate_limits = ""` in
`config.toml` disables rate limiting.

Each limit allows a number of requests per second, minute, hour or day for each
value of its key, and answers `429` with `Retry-After` past it until the window
that value's first request opened ends. Set them in `config.toml`:

```toml theme={null}
[daemon]
rate_limits = "ip=1000/minute, account=600/minute, header:x-tenant=50/second"
forwarded_allow_ips = "10.0.0.0/8"
```

| Key | Counts requests by |
| - | - |
| `ip` | The client address. Behind a proxy, list it in `forwarded_allow_ips`, or every client counts as the proxy. |
| `account` | The signed-in [account](#accounts). |
| `workspace` | The workspace the path names. |
| `header:<name>` | That header's value. |

A request with no value for a key (no account, no workspace in its path, no such
header) is not counted by that limit. `/v1/health`, `/v1/daemon/ready` and the OAuth
protected-resource metadata are never counted. WebSocket handshakes consume the
same budget as HTTP requests; messages on an established connection do not.
In code, a key may also be a function of the request that returns the value to
count by, or nothing to skip the limit:

```python Python theme={null}
from mirage.server import RateLimit, build_app

app = build_app(
    rate_limits=[
        RateLimit("account", "600/minute"),
        RateLimit(lambda request: request.headers.get("x-tenant"), "50/second"),
    ]
)
```

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

const app = buildApp({
  rateLimits: [
    { key: 'account', rate: '600/minute' },
    { key: (request) => request.headers['x-tenant']?.toString() ?? null, rate: '50/second' },
  ],
})
```

## Server policies

Apply server policies to every workspace the server builds. A workspace's own
configuration cannot remove these policies. See
[Server policies](https://docs.mirage.strukto.ai/home/policy/policies.md#pre_workspace) for the policy methods,
and [Policy programs](https://docs.mirage.strukto.ai/home/policy/scripts.md) for file-based rules.

Set the policy file in the daemon's configuration:

```toml ~/.mirage/config.toml theme={null}
[daemon]
policy_file = "policy.yaml"
```

When you build the server in code, pass its policies through
[`build_app`](https://docs.mirage.strukto.ai/python/access/server) or [`buildApp`](https://docs.mirage.strukto.ai/typescript/access/server).
A workspace's [network configuration](https://docs.mirage.strukto.ai/home/configuration/workspace.md#network) controls
where its connections may go.

## Monitor the server

### Health and readiness

Use `/v1/health` for a load balancer's liveness check. Use
`/v1/daemon/ready` for readiness: it returns `200` while the server accepts new
workspaces and `503` when it is full or shutting down.

Readiness and shutdown control the server process.

### Metrics

The server records workspace, session, command, and refusal metrics under the
OpenTelemetry meter `mirage.server`. Configure an SDK and exporter to collect them.

> [accordion] Configure metric collection
>
> The server records its metrics through [OpenTelemetry](https://opentelemetry.io/docs/concepts/signals/metrics/),
> under the meter `mirage.server`. Nothing is sent until the process sets up an
> OpenTelemetry SDK, and the exporter it picks decides where they go: OTLP to
> Datadog, New Relic, Honeycomb, Grafana Cloud, CloudWatch or Google Cloud, a
> Prometheus page, or the console. They are server-wide and name no workspace or
> account.
>
> | Instrument | Kind | Value |
> | - | - | - |
> | `mirage.workspace.count` | up-down counter | Workspaces it holds. |
> | `mirage.workspace.limit` | up-down counter | Its `max_workspaces`, when set. |
> | `mirage.session.count` | up-down counter | Sessions across its workspaces. |
> | `mirage.job.running` | up-down counter | Shell lines running. |
> | `mirage.server.shutting_down` | gauge | `1` while it shuts down. |
> | `mirage.request.refused` | counter | Requests refused for a server limit, by `reason`: `rate_limit`, `max_sessions`, `max_workspaces` or `shutting_down`. |
>
> In Python, run the app under `opentelemetry-instrument`, which also records
> each HTTP request:
>
> ```bash theme={null}
> pip install opentelemetry-distro opentelemetry-exporter-otlp
> OTEL_METRICS_EXPORTER=otlp OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.example.com \
>   opentelemetry-instrument uvicorn main:app
> ```
>
> In TypeScript, register a meter provider before `buildApp`:
>
> ```ts theme={null}
> import { metrics } from '@opentelemetry/api'
> import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'
> import { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'
> import { buildApp } from '@struktoai/mirage-server'
>
> metrics.setGlobalMeterProvider(
>   new MeterProvider({
>     readers: [new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter() })],
>   }),
> )
> const app = buildApp()
> ```

### Shut down

Request a graceful shutdown of a server you operate:

```bash theme={null}
curl --request POST http://127.0.0.1:8765/v1/daemon/shutdown \
  --header "Authorization: Bearer $MIRAGE_AUTH_TOKEN"
```

The daemon shuts down through its exit hook. A server created in code needs an
`on_idle_exit` callback in Python or `onIdleExit` in TypeScript; without a hook,
it keeps serving. See the [Python](https://docs.mirage.strukto.ai/python/access/server.md) or
[TypeScript](https://docs.mirage.strukto.ai/typescript/access/server.md) server configuration.

## Lines, jobs and processes

Inspect active and recently completed work with [List commands](https://docs.mirage.strukto.ai/api/operations/lines/list-commands.md),
[List jobs](https://docs.mirage.strukto.ai/api/operations/jobs/list-jobs.md), and
[List processes](https://docs.mirage.strukto.ai/api/operations/processes/list-processes.md). A shell result's
`line_id` identifies its [line record](https://docs.mirage.strukto.ai/api/operations/lines/get-command.md).
Servers using the same workspace store share these records, and snapshots keep
ended records. See those endpoint pages for retention, filters, and response fields.

## Streaming and stdin

See [Streaming and stdin](https://docs.mirage.strukto.ai/api/streaming.md) in the API reference for output
records, cancellation, and multipart input examples.

## Next steps

> [card] [API reference](https://docs.mirage.strukto.ai/api/reference.md)
>
> Look up request fields, response schemas, and endpoint examples.


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