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

# Discord

> Virtualize Discord servers from Node or the browser.

`DiscordVFS` mounts the Discord servers a bot is in as read-only files: each
channel as one folder per day of messages and attachments, plus members. Set up the bot token as in [Discord setup](https://docs.mirage.strukto.ai/home/setup/discord.md).

## Install

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

## Configure

```ts theme={null}
import { DiscordVFS, MountMode, Workspace } from '@struktoai/mirage-node'

const discord = new DiscordVFS({ token: process.env.DISCORD_BOT_TOKEN! })
const ws = new Workspace({ '/discord': discord }, { mode: MountMode.READ })

const result = await ws.shell('ls /discord && tree -L 2 /discord')
console.log(result.stdoutText)
await ws.close()
```

`startTime` and `endTime` bound the mount to a time range.

### Fields

**startTime** `string`

Start of the mount's time scope, inclusive: an RFC 3339 timestamp with an explicit timezone and at most millisecond precision. Unset leaves the start open.

**endTime** `string`

End of the mount's time scope, exclusive, in the same format as `startTime`, which it must follow. Unset leaves the end open.

**timeout** `number` (default: DEFAULT\_TIMEOUT)

Seconds a request may wait to connect, or between two reads of its answer, before it fails; a download that keeps flowing is never cut off.

**token** `string` *required*

Discord bot token, sent as `Authorization: Bot <token>`.

**baseUrl** `string` (default: '[https://discord.com/api/v10](https://discord.com/api/v10)')

Discord API root; override to point at a fake or proxy.

Fields marked secret are redacted in snapshots.

## Authentication

`token` is a bot token, sent with Discord's `Bot <token>` scheme. The bot
needs:

* **Message Content Intent**: without it, message text and attachments come
  back empty.
* **Server Members Intent**: for the `members/` folder; without it, `members/`
  is empty.
* The **View Channels** and **Read Message History** permissions in each
  server it reads. The mount never posts.

A channel the bot cannot read answers `Permission denied`: `ls` names it and
fails, `find` reports it and walks on. A channel deleted since it was listed
answers `No such file or directory`.

## Layout

```text theme={null}
/discord/
  Acme Labs__1098765432101234567/
    channels/
      general__1098765432101234570/
        2026-11-16/
          chat.jsonl
          files/
            diagram__1174567890123456789.png
    members/
      alice__1012345678901234567.json
```

* **Names:** a server, channel, member or attachment is
  `<display-name>__<id>`, so the CLI's flags take the snowflake id from the
  path and two entities with one name never collide. Spaces, apostrophes and
  emoji are kept; only `/` becomes `∕` (U+2215). Quote names with spaces.
  `stat` also shows the id.
* **Servers:** the root lists one folder per server the bot is in.
* **`channels/`:** text channels (types 0, 5 and 15), each with one folder per
  day for the 30 days up to its newest message, so an inactive channel shows
  days around its last activity, not today.
* **`chat.jsonl`:** one message per line as Discord's API returns it, with
  `.id`, `.content`, `.author.username` and `.attachments`.
* **`files/`:** the attachments posted that day, named
  `<stem>__<attachment-id>.<ext>`. `cat` downloads one from Discord's CDN.
* **`members/`:** one file per member, holding the member as Discord's API
  returns it.

## Behavior

* **Read only:** the mount cannot send or change messages. Use the
  [`discord`](https://docs.mirage.strukto.ai/typescript/cli/discord) CLI to send, edit, react, open threads and
  polls, look up members and servers, and search.
* **Search:** `grep -r` and `rg` read every day's `chat.jsonl` under the folder
  they walk, one history fetch per day, so name a day folder or a date glob
  for a large channel. Discord's own search is not used: it cannot say which
  days hold a word, since a reply carries the message it answers
  (`referenced_message`).
* **Time scope:** `startTime` and `endTime` bound the mount with RFC 3339
  timestamps that carry a timezone, at most to the millisecond. Start is
  inclusive, end exclusive, and an unset bound is open. Listings then cover
  that period instead of the recent window, day folders use UTC, messages are
  picked by creation time and attachments follow their messages. Direct
  paths, `stat`, date globs, `grep` and `rg` cannot leave the scope. Members
  and server metadata stay visible. The scope applies to the mount, not to
  the `discord` CLI; rebuild the mount to change it.
* **Upstream changes:** a `read` mount refuses writes through Mirage; it does
  not freeze edits or deletions made in Discord.
* **Rate limits:** many reads of `chat.jsonl` can hit Discord's per-route rate
  limits. A read that gets a 429 waits the `retry_after` Discord sends and
  retries; one that outlasts the retries fails, so slow down or name specific
  channels.

## Browser

The browser `DiscordVFS` from `@struktoai/mirage-browser` never sees the
token: a proxy on the backend holds it and forwards `/api/discord/*` to
`https://discord.com/api/v10/*`.

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

```ts theme={null}
import { DiscordVFS, MountMode, Workspace } from '@struktoai/mirage-browser'

const discord = new DiscordVFS({ proxyUrl: '/api/discord' })
const ws = new Workspace({ '/discord': discord }, { mode: MountMode.READ })
```

* The proxy is required: Discord sets no permissive CORS headers for the bot
  API, so a call to `https://discord.com/api/v10/*` from the page fails.
* The proxy sends `Authorization: Bot <token>`, not `Bearer`; `Bearer` answers
  `401 Unauthorized`.
* `getHeaders` returns extra headers for each request to the proxy, such as a
  per-user session credential.

> [accordion] Proxy server
>
> ```ts theme={null}
> import { createServer } from 'node:http'
>
> const TOKEN = process.env.DISCORD_BOT_TOKEN!
> const PREFIX = '/api/discord/'
>
> createServer(async (req, res) => {
>   const url = new URL(req.url ?? '/', 'http://localhost')
>   if (!url.pathname.startsWith(PREFIX)) {
>     res.statusCode = 404
>     res.end()
>     return
>   }
>   const upstream = new URL(`https://discord.com/api/v10/${url.pathname.slice(PREFIX.length)}`)
>   upstream.search = url.search
>
>   const method = (req.method ?? 'GET').toUpperCase()
>   const chunks: Buffer[] = []
>   if (method !== 'GET' && method !== 'HEAD') {
>     for await (const chunk of req) chunks.push(chunk as Buffer)
>   }
>   const body = chunks.length > 0 ? Buffer.concat(chunks).toString('utf-8') : undefined
>
>   const headers: Record<string, string> = { Authorization: `Bot ${TOKEN}` }
>   const ct = req.headers['content-type']
>   if (typeof ct === 'string') headers['content-type'] = ct
>
>   const upstreamRes = await fetch(upstream, { method, headers, ...(body !== undefined ? { body } : {}) })
>   const text = await upstreamRes.text()
>   res.statusCode = upstreamRes.status
>   const upstreamCt = upstreamRes.headers.get('content-type')
>   if (upstreamCt !== null) res.setHeader('content-type', upstreamCt)
>   res.end(text)
> }).listen(8902, '127.0.0.1')
> ```

> [accordion] Browser fields
>
> **startTime** `string`
>
> Start of the mount's time scope, inclusive: an RFC 3339 timestamp with an explicit timezone and at most millisecond precision. Unset leaves the start open.
>
> **endTime** `string`
>
> End of the mount's time scope, exclusive, in the same format as `startTime`, which it must follow. Unset leaves the end open.
>
> **timeout** `number` (default: DEFAULT\_TIMEOUT)
>
> Seconds a request may wait to connect, or between two reads of its answer, before it fails; a download that keeps flowing is never cut off.
>
> **proxyUrl** `string` *required*
>
> URL of your backend proxy, which forwards to `https://discord.com/api/v10` and attaches the bot token. A path resolves against the page's origin; no query string or fragment.
>
> **getHeaders** `function`
>
> Function returning extra headers sent with every request to the proxy, such as your own session credential.
>
> Fields marked secret are redacted in snapshots.

## Integration

Discord answers this command through its own API, so less is read. See
[Integration](https://docs.mirage.strukto.ai/home/integration/overview.md).

* `tail -f`: each new message as it is posted.

## VFS.md

The [VFS.md](https://docs.mirage.strukto.ai/home/setup/vfs-md.md) an agent reads with Discord mounted at `/<path>`.

> [tab] Rendered
>
> **Virtual Filesystem**
>
> | Path | Description |
> | - | - |
> | `/<path>` | `discord`, read |
>
> **VFS Layout**
>
> **`/<path>`**
>
> ```text theme={null}
> /<path>
>   <guild-name>__<guild-id>/
>     channels/
>       <channel-name>__<channel-id>/
>         <yyyy-mm-dd>/
>           chat.jsonl                # messages for that date
>           files/                    # attachments shared that day
>             <name>__<att-id>.<ext>  # cat downloads it from Discord's CDN
>     members/
>       <username>__<user-id>.json    # member profile
> ```
>
> * A guild, channel, member or attachment name is `<display-name>__<id>`;
>   only `/` becomes `∕` (U+2215). `ls` the parent for exact names and
>   quote names with spaces.
> * `chat.jsonl` holds one message per line (`.content`,
>   `.author.username`, `.attachments`).
> * Without `start_time`/`end_time`, a channel lists the 30 days up to its
>   newest message; a date glob finds earlier days.
> * `grep -r` on a channel reads every listed day, attachments included;
>   they download from the CDN and binary ones produce noise.
>
> Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive); explicit paths and globs cannot escape it.
>
> **Supported Unix Commands for VFS**
>
> Unix commands work on each path as on a local filesystem, as far as the path supports them:
>
> | Path | Supported |
> | - | - |
> | `/<path>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). |
>
> **Limitations of Unix Commands for VFS**
>
> Where a path differs from a local filesystem:
>
> | Path | Limitations |
> | - | - |
> | `/<path>` | Read only: no command changes files. `grep -r`, `find` and `du` stop after 1000 files; a glob matching more, `tar -c`, `cp -r` and `rm -r` are refused. |
>
> Run `man <cmd>` or `<cmd> --help` for one command's usage.

> [tab] Raw
>
> ````markdown theme={null}
> ---
> name: workspace-filesystem
> description: The virtual filesystem layout of this workspace.
> ---
>
> # Virtual Filesystem
>
> | Path | Description |
> | --- | --- |
> | `/<path>` | `discord`, read |
>
> ## VFS Layout
>
> ### `/<path>`
>
> ```text
> /<path>
>   <guild-name>__<guild-id>/
>     channels/
>       <channel-name>__<channel-id>/
>         <yyyy-mm-dd>/
>           chat.jsonl                # messages for that date
>           files/                    # attachments shared that day
>             <name>__<att-id>.<ext>  # cat downloads it from Discord's CDN
>     members/
>       <username>__<user-id>.json    # member profile
> ```
>
> - A guild, channel, member or attachment name is `<display-name>__<id>`;
>   only `/` becomes `∕` (U+2215). `ls` the parent for exact names and
>   quote names with spaces.
> - `chat.jsonl` holds one message per line (`.content`,
>   `.author.username`, `.attachments`).
> - Without `start_time`/`end_time`, a channel lists the 30 days up to its
>   newest message; a date glob finds earlier days.
> - `grep -r` on a channel reads every listed day, attachments included;
>   they download from the CDN and binary ones produce noise.
>
> Time scope: `start_time=unbounded` (inclusive), `end_time=unbounded` (exclusive); explicit paths and globs cannot escape it.
>
> ## Supported Unix Commands for VFS
>
> Unix commands work on each path as on a local filesystem, as far as the path supports them:
>
> | Path | Supported |
> | --- | --- |
> | `/<path>` | Commands that read files (`ls`, `cat`, `grep`, `find`, `jq` and the rest). |
>
> ## Limitations of Unix Commands for VFS
>
> Where a path differs from a local filesystem:
>
> | Path | Limitations |
> | --- | --- |
> | `/<path>` | Read only: no command changes files. `grep -r`, `find` and `du` stop after 1000 files; a glob matching more, `tar -c`, `cp -r` and `rm -r` are refused. |
>
> Run `man <cmd>` or `<cmd> --help` for one command's usage.
> ````


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