# Space Backup for AI agents: the MCP server
Vladimir (2026-10-30): proper Space Backup integration with AI agents. Three parts:
1. **The MCP server** (this page): `sbctl mcp` on Windows, `spacebackup mcp` on Linux and macOS. It ships in the
normal install (it is a mode of the command-line program, nothing else to download).
2. **The Agent Skill** (`agent/skill/space-backup/`): how to do the common jobs well and the rules. Downloadable from
.
3. **The developer page** , `/llms.txt` and `/llms-full.txt`, the API index
`/manual/api/`.
Phase 2 (Vladimir, 2026-10-30): **the remote MCP server** on the account service, so cloud agents manage a company
without being on a PC: [Remote](#remote) below.
## What it is
The [Model Context Protocol](https://modelcontextprotocol.io) lets an AI app (Claude Desktop, Claude Code, Cursor,
VS Code, …) call tools of a local program. `sbctl mcp` / `spacebackup mcp` speaks MCP on stdin/stdout (JSON-RPC 2.0,
one message per line; protocol versions 2025-11-25, 2025-06-18, 2025-03-26 and 2024-11-05) and offers **every command
of [cli.md](cli.md) as a tool**. It talks to the running app/daemon exactly as the command line does (Windows: the
tray app's named pipe; Linux and macOS: the daemon's socket), as the user who runs it. Nothing listens on the network.
`--profile NAME` (before or after `mcp`) serves a test instance, as everywhere else.
## Setup
The program and its path:
| Platform | Command | Full path (an app that does not inherit your PATH needs it) |
|---|---|---|
| Windows | `sbctl mcp` | `%LOCALAPPDATA%\Programs\SpaceBackup\sbctl.exe` |
| Linux | `spacebackup mcp` | `~/.local/bin/spacebackup` (user install; a package: `/usr/bin/spacebackup`) |
| macOS | `spacebackup mcp` | `/Applications/Space Backup.app/Contents/MacOS/spacebackup` |
**Claude Code** (one line, per user):
```sh
claude mcp add --scope user space-backup -- spacebackup mcp # Linux, macOS (use the full path if not on PATH)
claude mcp add --scope user space-backup -- sbctl mcp # Windows
```
**Claude Desktop**: Settings → Developer → Edit Config (`claude_desktop_config.json`), then restart Claude Desktop:
```json
{
"mcpServers": {
"space-backup": {
"command": "C:\\Users\\YOU\\AppData\\Local\\Programs\\SpaceBackup\\sbctl.exe",
"args": ["mcp"]
}
}
}
```
(macOS: `"command": "/Applications/Space Backup.app/Contents/MacOS/spacebackup"`; Linux: `"/home/YOU/.local/bin/spacebackup"`.)
**Cursor**: `~/.cursor/mcp.json` (all projects) or `.cursor/mcp.json` (one project):
```json
{ "mcpServers": { "space-backup": { "command": "spacebackup", "args": ["mcp"] } } }
```
**VS Code** (GitHub Copilot agent mode): `.vscode/mcp.json` in a workspace, or the user configuration (command
palette: *MCP: Open User Configuration*):
```json
{ "servers": { "space-backup": { "type": "stdio", "command": "sbctl", "args": ["mcp"] } } }
```
Any other MCP client: a stdio server, command `sbctl` / `spacebackup`, argument `mcp`.
Check it by hand: `printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | spacebackup mcp`
prints two lines of JSON (stderr has one line saying it is serving).
## The tools
Generated from the command table (`Commands.All` in `src/SpaceBackup.Control/Commands.cs`), never listed by hand
(`src/SpaceBackup.Control/Mcp.cs`, `McpTools`):
- **Name**: the command with `_` for the space: `status`, `folders_add`, `runs_show`, `photos_search`,
`account_members`; a hyphen stays (`account_auto-join`, `vision_delete-models`).
- **Description**: the command's help, its command line (`spacebackup folders add [--frequency F] …`) and the
exit codes.
- **Input schema**: `args`, the positional arguments in order (an array of strings, with the command's minimum and
maximum count), and one property per option, named as the option without `--`: a flag is a boolean (`"wait": true`),
a number an integer, a repeatable option an array, anything else a string. Unknown properties are refused.
`timeoutSeconds` (every tool): how long the call waits for its answer (below). Example: `folders_add` with
`{"args": ["/home/me/Projects"], "frequency": "weekly", "dest": "auto:2"}` is
`spacebackup folders add /home/me/Projects --frequency weekly --dest auto:2`.
- **Result**: the command's `--json` document as text, and as `structuredContent`
`{"exitCode": N, "ok": true|false, "result": }`. `isError` is true for exit codes other than 0 and 4
(4 = partial: some items or destinations failed; the document says which). The text of a failure ends with
`(exit code N: meaning)`. Exit 3 means the app is not running: the `start` tool starts it.
- **Paths**: give them absolute. A relative path is resolved against the folder the AI app started the server in.
### Annotations
Every command is classified in `McpTools` as one of:
- **read-only** (`readOnlyHint`: true): `status`, the `list`/`show`/`get`/`status` commands, `history`, `browse`,
`explain`, `tx`, `runs`, `events`, `log`, `stats`, `search`, `photos_search`, `key_fingerprint`, `help`, …
- **destructive** (`destructiveHint`: true, so the client asks the user before calling it): anything that deletes,
removes, forgets, overwrites, stops or interrupts, changes keys or who may read what, or publishes: `folders_remove`,
`dest_remove`, `dest_forget`, `key_set`, `key_generate`, `key_clear`, `restore` (it may write over files),
`photos_restore`, `photos_delete`, `albums_delete`, `account_members`, `account_groups`, `devices_remove`,
`devices_approve`, `approvals_approve`/`_deny`, `share_add`/`_remove`, `albums_share`, the public links, `stop`,
`restart`, `cancel`, `update_now`, `account_signout`, and the secret tools `key_show` and `photos_open`
(see Secrets), …
- **write** (neither): the rest, changes that are easy to take back (`folders_add`, `now`, `settings_set`, `dest_add`,
`albums_create`, …).
`openWorldHint` is true for the commands that reach the account service, Google, the relay or the update feed.
**The parity test.** `McpTests.Every_command_is_a_tool_with_a_classified_effect` (tests/SpaceBackup.Control.Tests)
fails naming every command that is not classified, so a new command cannot ship without its tool (and with the UI
parity test, a new button cannot ship without both). `Annotations_mark_reading_and_destroying` checks that every
`… remove|delete|forget|clear|unshare|unlink|signout|uninstall` command is destructive.
The commands that manage the program itself (`spacebackup daemon`, `install`, `uninstall`, `integrate`, `gui`; the
Windows installer) are not part of the command table and have no tools.
### Asking first
The command line never prompts; a confirmation is the command's own option. The tools keep that: `key_clear` without
`force` and `folders_remove` without its path are refused (exit 2); `photos_delete`, `vision_download` and
`vision_delete-models` without `confirm` only say what they would do. None of them changes anything. The server's `instructions` (sent at initialize) and the Agent Skill tell the model never
to call a destructive tool unless the user asked for exactly that.
### Streams and long calls
- `--follow` (`log`, `tx`, `events`, `vision_download-progress`), `status` with `watch`, and `notifications_watch` are
**bounded calls**: the call runs for `for` (default 30 s, at most 5 minutes) and answers every line as one JSON array
(the newest 500). To keep watching, call again (with `after`, the cursor, where the command has it).
- Every call waits at most `timeoutSeconds`: default 120 s; 600 s for the commands that wait (`now`, `gdrive_now`,
`icloud_now` with `wait`, `restore`, `albums_restore`, `photos_restore`, `photos_save`, `update_now`, `diag`,
`gdrive_add`, `vision_install`, `vision_test`); at most 3600. When the time is up the answer says so
(`structuredContent.timedOut`: true, not an error): what the command started goes on in Space Backup; check it with
`status` or `runs_show` `["last"]`.
- `gdrive_add` prints the Google sign-in address first and then waits for the sign-in; with a short `timeoutSeconds`
the answer holds the address so the user can open it.
- An MCP `notifications/cancelled` stops waiting for that call.
### Secrets
- The server never logs a call's arguments: its stderr gets one line per call, the tool's name and exit code
(`mcp: key_set exit 0`). The app/daemon logs commands without secrets, as for the command line (`key set`,
`settings set relay-token`, `photos close-page`).
- `key_set` and `settings_set relay-token` take the secret as an argument, so it would pass through the conversation
and the AI app's history: prefer their `file` property (a file holding the secret on its first line). Reading from
stdin (`-`) is not available over MCP (stdin is the protocol).
- **Key material is hidden in every answer.** A tool's answer (its text and `structuredContent`) goes into the AI app's
conversation and its provider's transcript, so `McpTools.Redact` replaces the value of every key-material field, at
any depth and in any case, with `[hidden]`: `companyKey` (status), `secret` (photos open), `token`, `accessToken`,
`refreshToken`, `relayToken`, `password`, `passphrase`, `recoveryKey`, `accountProof`, `apiKey`, `privateKey`,
`masterKey`, `dataKey`, and `key` in the `key_*` tools' answers. Every other place such a value appears (an address
that carries the secret) gets `[hidden]` too. Only the MCP answer changes: the command line and its `--json` print
what they always did. (status's `companyKey` holds the key's fingerprint on Windows and Linux today; it is hidden
anyway, `key_fingerprint` gives the fingerprint.)
- **The secret tools** print key material by design: `key_show` (the company key) and `photos_open` (the viewer's
address with its session secret; with `app`, a secret that may run every command). They are destructive, their
schema requires `reveal`, which must be the command's own name (`"key show"`, `"photos open"`), and a call without
it is refused (exit 2) before anything reaches the app. The model gives `reveal` only when the user asked for exactly
that by name; the answer then holds the secret, unredacted. Their descriptions say never to repeat it elsewhere.
- What reaches the conversation otherwise: `settings_get` shows secret settings as set / not set; `diag` writes a
bundle without the company key and relay token; the account's own pages never had keys. The remote MCP (below)
answers nothing an app would not show (no keys, no sealed blobs).
## Tests
- `tests/SpaceBackup.Control.Tests/McpTests.cs` (both platforms, in-process with the fake target): every command is a
tool and classified, schemas and annotations, initialize/ping/unknown method, a read call, destructive calls refused
without their arguments (nothing reaches the app), arguments → command line, bounded streams, a secret not logged,
key material hidden (`companyKey` = `[hidden]`, `key_show`/`photos_open` refused without `reveal`, a secret hidden
where it appears in an address), not running = exit 3, `mcp` on the command line.
- `tests/mcp-e2e.py`: an MCP client over stdio against a real Space Backup: Linux starts a test daemon (own profile,
XDG folders and port) and runs `spacebackup --profile P mcp`; Windows starts the tray with `sbctl --profile P start`
and runs `sbctl --profile P mcp` (`python tests\mcp-e2e.py publish\sbctl.exe`). It checks initialize, tools/list
(every command of `help` is a tool), status and version, `folders_remove`/`key_clear` refused without their
arguments, `dest_add` + `folders_add` + `now` with `wait` + `runs_show last` + `restore` to a new folder,
`log` with `follow` bounded, and that the server's log has no secret. **Key material parity:** it sets a known
company key, checks the plain CLI is unchanged (`key show` prints it, `--json status` has `companyKey`), that
`key_show` and `photos_open` are refused without `reveal` and answer with it, then calls every read-only tool that
needs no arguments and fails naming any tool whose answer (of the whole run, except the two asked with `reveal`)
holds the key or the viewer's secret. Ends with `MCP E2E PASSED`.
## Implementation notes
- `CliRunner.Run` sees `mcp` before parsing and runs `McpServer` on the program's stdin/stdout. Console output from
anything else goes to stderr while it serves, so it cannot break the protocol.
- A call builds the command line from the arguments (`McpTools.CommandLine`) and runs `CliRunner.Run` with `--json`
and a host that has no stdin and is never interactive. So the tools parse, validate and answer exactly as the
command line does, and the local commands (`start`, `stop`, `version`, `firewall`, …) work too.
- Calls run concurrently; answers are written one line at a time under a lock.
- JSON text is written with `Utf8JsonWriter` (the trimmed single-file builds have no reflection resolver for
`JsonNode.ToJsonString(options)`).
## Remote
`https://spacebackup.net/account/mcp`: an MCP server on the account service for agents that run in the cloud (Claude,
ChatGPT-style connectors, hosted agents) or anywhere without Space Backup installed. The agent signs in with the
user's **Space Backup account** (OAuth 2.1, the same email link or code as the website) and then acts as that member,
with that member's role (owner, admin or member): the same rules as the apps and the account pages, nothing more.
### Connect
The URL is all a client needs; it finds the sign-in itself (below).
- **Claude (claude.ai, Claude Desktop, mobile):** Settings → Connectors → *Add custom connector* → URL
`https://spacebackup.net/account/mcp` → Connect. A browser opens the Space Backup sign-in.
- **Claude Code:** `claude mcp add --transport http space-backup https://spacebackup.net/account/mcp`, then `/mcp` →
space-backup → Authenticate.
- **Cursor:** `~/.cursor/mcp.json`: `{ "mcpServers": { "space-backup": { "url": "https://spacebackup.net/account/mcp" } } }`.
- **VS Code:** `.vscode/mcp.json`: `{ "servers": { "space-backup": { "type": "http", "url": "https://spacebackup.net/account/mcp" } } }`.
- **Any client** with MCP authorization (Streamable HTTP + OAuth 2.1 with dynamic client registration or a client id
metadata document).
The sign-in: a browser opens `/account/oauth/authorize`; signed out, the usual email sign-in (link or 6-digit code),
then **Allow ?** with three buttons: **Allow** (read and change), **Allow reading only**, **Deny**. The member sees
and disconnects their agents on `/account/me` under **AI agents**.
### What it can do
35 tools on the account service's own methods (the same checks and errors as the API):
| Read (readOnlyHint) | Change (destructiveHint) |
|---|---|
| `whoami`, `company_get`, `devices_list`, `device_status`, `members_list`, `groups_list`, `albums_list`, `album_get`, `albums_deleted`, `shares_list`, `relay_balance`, `notifications_list`, `audit_log`, `backup_request_get` | `backup_now`, `members_invite`, `members_set_role`, `members_approve`, `members_deny`, `members_remove`, `groups_create`, `groups_update`, `groups_delete`, `albums_create`, `albums_update`, `albums_delete`, `albums_put_back`, `albums_delete_permanently`, `albums_share`, `albums_unshare`, `shares_create`, `shares_remove`, `devices_label`, `devices_remove`, `company_update` |
- Every change is marked `destructiveHint` (so the AI app asks the user first); `idempotentHint` where repeating it
changes nothing more. Owner/admin tools answer a member "only the company's owner or an admin may do this".
- Devices, members, albums and groups may be given by id or by name (machine name, label, email, album or group name);
an ambiguous name answers with the ids to choose from.
- `device_status`: the device row (last seen, version), a PC's own report (running now, last backup's start, end,
result, error line, files and bytes, next run, folder and destination counts; sent by PCs on 0.16.23 or later), when
a phone last saved its backup state, and the newest backup requests.
- `backup_now {device, wait_seconds?}`: asks a PC or Mac to run its backup, as **Back up now** there. The request waits
until the PC's next account sync (about a minute; the PC must be on and on 0.16.23 or later), which runs it and
answers `started` (or `failed` with the reason), then `done`/`failed` when that run ends. `wait_seconds` (up to 90)
waits for the start; `backup_request_get` follows it. Not picked up within an hour: `expired`. One open request per
PC. Its member or an owner/admin. Phones back up from their own app (refused here).
- Never available: data keys, the company key, sealed blobs, file names inside backups, file contents, photos. The
service does not have them (end-to-end encrypted on the PCs).
### Limits and audit
- Per connection 60 calls a minute and 1000 an hour; per member 120 changes an hour. Over a limit the tool answers an
error ("Rate limit: …"), nothing is done.
- Every `tools/call` writes one row to the company's audit log (the admin page's **Audit log**, and `audit_log`):
kind `mcp`, the member, the tool, `": → ok | error 403: … |
refused: read-only connection | refused: rate limit"`. Disconnecting an agent writes one too.
- A read-only connection (scope `read`) answers every change with "This connection may only read" before it runs.
### Protocol
- **MCP:** `POST /account/mcp`, Streamable HTTP without sessions: each POST is one JSON-RPC message (or a batch),
answered `application/json` (no `Mcp-Session-Id`, no SSE stream; `GET`/`DELETE` → 405). Notifications → 202.
Protocol versions 2025-11-25, 2025-06-18, 2025-03-26 (an unknown `MCP-Protocol-Version` header → 400). Results carry
`structuredContent` (an object) and the same JSON as text. CORS is open (bearer tokens, no cookies).
- **No token / bad token:** 401 with `WWW-Authenticate: Bearer resource_metadata="https://spacebackup.net/.well-known/oauth-protected-resource/account/mcp", scope="read write"`
(plus `error="invalid_token"` for an unknown, expired or revoked one).
- **Discovery:** protected resource metadata (RFC 9728) at `/.well-known/oauth-protected-resource/account/mcp` (also
`/.well-known/oauth-protected-resource` and `/account/.well-known/oauth-protected-resource`): resource
`https://spacebackup.net/account/mcp`, authorization server `https://spacebackup.net/account`. Authorization server
metadata (RFC 8414) at `/.well-known/oauth-authorization-server/account` (also at the root and under `/account/.well-known/`).
- **Clients:** dynamic registration (RFC 7591) at `POST /account/oauth/register` (public clients with
`token_endpoint_auth_method` `none`, or a client secret for `client_secret_post`/`client_secret_basic`; 20
registrations an hour per address), or a client id that is the https URL of a client metadata document (fetched
with no redirects, 64 KB, only from public addresses, kept a day). Redirect URIs: https, http to localhost/127.0.0.1
(any port, RFC 8252), or an app's own scheme (`cursor://`, `vscode://`); never `javascript:`, `data:`, `file:`.
- **Authorize:** `GET /account/oauth/authorize` with `response_type=code`, PKCE `code_challenge` + `S256` (required),
`state`, `scope` (`read`, `write`; none = both), `resource` (`https://spacebackup.net/account/mcp`). An unknown client
or an unregistered redirect URI is shown on the page and never redirected to. The answer carries `code`, `state`
and `iss`. The consent page cannot be framed.
- **Token:** `POST /account/oauth/token` (form): `authorization_code` with `code_verifier`, or `refresh_token`. Access
tokens (`sba_…`) live an hour; refresh tokens (`sbr_…`) 30 days and are replaced at each use (the old one stops
working); a refresh may narrow the scope, never widen it. A code works once and for 10 minutes; used twice, the
grant it gave is revoked. **Revoke:** `POST /account/oauth/revoke` (RFC 7009) ends the whole grant.
- Tokens are kept as SHA-256 hashes, apart from the apps' sessions: an MCP token opens nothing under `/account/api`.
### Implementation (service)
- `src/SpaceAccount/OAuth.cs` (clients, codes, grants, tokens; tables `oauth_clients`, `oauth_codes`, `oauth_grants`,
`oauth_tokens`), `WebOAuth.cs` (the authorize and consent pages, token/register/revoke, the AI agents panel),
`RemoteMcp.cs` (the endpoint, the tools, discovery, CORS, rate limits, the audit row), `DeviceCommands.cs`
(`device_commands`, `device_status`; [chapter 9 "Remote commands & PC status"](manual/09-api-account.md#api-remote)).
- The PCs' side (`src/SpaceBackup/RemoteCommands.cs`, `IdentityService.CommandReceived`/`StatusProvider`): each
minute's sync may list `commands`; the PC acts on each id once (`backup-now` = the control command `now`, queued
behind a running backup; any other kind is answered `failed / unknown command`), answers `POST devices/commands/{id}`
(started or failed at once, then done or failed when that run ends) and sends an answer that did not arrive again
when the command is listed again. It reports `PUT devices/status` when it changes, at least every 15 minutes and
just after a run; a ≤200-character error line with paths taken out; never file names, folder paths or keys. An
older service's 404: answers count as delivered, the status is not sent again until the app restarts.
- Tests: `tests/SpaceAccount.Tests/RemoteMcpTests.cs` (discovery; registration, consent and PKCE through the real
pages; roles; read-only; backup-now through a PC's sync with its answer, status and expiry; single-use codes and
refresh tokens; disconnect and RFC 7009; bad redirects and clients; a metadata-document client; the rate limit;
nothing secret in what the read tools answer) and `tests/SpaceBackup.Tests/RemoteCommandIdentityTests.cs` (the PC).
- `tests/remote-mcp-e2e.sh [python]`: the official MCP Python SDK (2.x) against a fresh local
spaceaccount with mail to files: discovery, dynamic registration, the real sign-in pages with the mailed code,
consent, PKCE, initialize, tools/list (annotations), whoami, devices_list, backup_now answered by a PC through its
sync, device_status, a tool error, audit_log, refresh token. Ends with `REMOTE MCP SDK E2E PASSED` (passed
2026-10-30 on the deployed build). Against production, the SDK was run up to the sign-in page (no mailbox there).
- Deploy: the service binary as usual (deploy/README.md), plus nginx `location ^~ /.well-known/oauth- { proxy_pass
http://127.0.0.1:5080; … }` in the spacebackup.net server block (the discovery documents live at the site's root).