# sona-mcp: the SDK's MCP server

`sona-mcp` lets Claude Code or any MCP client drive the native SDK. An agent can:

- search the wardrobe;
- build an avatar, or dress one from a sentence ("dress my avatar like a pirate");
- render it and get the picture back as an image;
- make a project from a template, build it, run it, and read its log and frame stats.

SDK Studio hosts the same server in-process, on a loopback port and (with `--mcp`) on stdio, and asks its user before a write outside the Projects folder ([Studio agents and apps](studio-agents-apps.md)). `sona mcp` runs it from the CLI.

The server is a tool, not SDK API: nothing here is in `sona.h`. A host that embeds it calls `sona_mcp.h` from C or C++
(below); the bindings do not wrap it, so from another language run `sona mcp` and talk to it over stdio. It is built on the public API and on a small internal
library, the toolkit. The sona CLI and the Studio share the toolkit.

## Start it

It comes with the [tools installer](installer.md), as `sona-mcp`. Point it at the SDK made for your app
(`sona app download <platform> --with-catalogue --unpack <folder>`): `--sdk` gives it the licence, the catalogue and
what projects build against, and it runs as the `bin/sona-mcp` of that download, made for your app. For an agent with
no person present, see [Unattended agents](unattended.md).

Claude Code, over stdio (Claude Code starts the server):

```sh
claude mcp add sona -- sona-mcp --sdk ~/sona-sdk --dir /path/to/assets --root ~/sona-projects
```

Or put a `.mcp.json` in the project, with the same command and arguments.

Over HTTP on a local port (one server, many clients):

```sh
sona-mcp --http 7360 --sdk ~/sona-sdk --dir /path/to/assets --root ~/sona-projects
claude mcp add --transport http sona http://127.0.0.1:7360/mcp
```

| Option | What |
|---|---|
| `--sdk <folder>` | the SDK made for your app, unpacked. Default: `$SONA_SDK`. Gives `--licence`, `--catalogue`, `--sdk-include` and `--sdk-library` their defaults, and runs the download's own `bin/sona-mcp` |
| `--dir <folder>` | an asset folder laid out like a dump (`pack/`, `dlc/`, ...); up to 4, asked in order. Default: `$SONA_CORPUS`, then `$SONA_DIR` |
| `--gate` | also ask the 360sona gate (needs a licence that allows it, and the network) |
| `--server <url>` | where the gate checks the licence (`$SONA_SERVER`; https in a release build) |
| `--licence <file>` | `sona-licence.json`. Default: `$SONA_LICENCE`, then `<sdk>/sona-licence.json`. The installed server opens it only through `--sdk` |
| `--catalogue <file>` | `sona-catalogue.bin` (the offline catalogue). Search and dressing need it. Default: `$SONA_CATALOGUE`, then `<sdk>/data/sona-catalogue.bin` |
| `--filter <list>` | a content filter on the server's ctx: presets (`family`, `no-logos`, `no-licensed`) and rules files, comma separated. Search, dressing, wearing, previews and every stored avatar then keep to it ([Content filters](filters.md)). Needs `--catalogue` |
| `--samples <file>` | sample manifests ([`devs-cast.json`](../install.md#sample-avatars)); plain new avatars start from these. Default: the installed copy (`share/360sona/devs-cast.json`) |
| `--root <folder>` | the project root: the only folder writes may go to. Default: the working folder |
| `--allow-write <folder>` | one more folder writes may go to (up to 8) |
| `--allow-writes-anywhere` | lift the write rule (the host's choice; never the agent's) |
| `--allow-exec` | build and run projects an agent has edited, and pass any run argument (see [Writes and builds](#writes-and-builds)). Also `SONA_MCP_ALLOW_EXEC=1` |
| `--config <file>` | the same settings from a JSON file (also `$SONA_MCP_CONFIG`); `SONA_MCP_ROOT` and `SONA_MCP_ALLOW_WRITE` set them from the environment ([Unattended agents](unattended.md#5-the-mcp-server)) |
| `--stdio` / `--http [port]` | transports: stdio by default; `--http` alone serves only HTTP; both together serve both. Port 0 picks a free port |
| `--host <name>` | the HTTP address: `127.0.0.1` (default) or `localhost`. Other addresses are refused, `[::1]` too: CivetWeb is built without IPv6 |
| `--port-file <file>` | write the HTTP port there (with `--http 0`) |
| `--token-file <f>` | HTTP requests then need `Authorization: Bearer <t>`, with <t> read from the file (a token on the command line would show in the process list) |
| `--origin <origin>` | one more `Origin` HTTP accepts besides the loopback ones |
| `--sdk-include <dir>`, `--sdk-library <file>` | what projects compile against. Default: `<sdk>/include` and `<sdk>/lib/libsona.so` (`lib\sona.lib`, `lib/libsona.dylib`). Without either, `project_build` fails and says to start the server with `--sdk` |
| `--jobs <n>` | compile jobs for project builds (4) |
| `--cpu` | render on a CPU Vulkan device (lavapipe) |
| `--verbose` | the server log on stderr too |

Only MCP messages go to stdout. Builds and project runs write to their own log files, never to the server's
streams.

## The protocol

- **Revisions.** The server speaks `2026-07-28`, the current stateless revision. Every request carries
  `_meta["io.modelcontextprotocol/protocolVersion"]`, and the server answers `server/discover`. Results carry
  `resultType` and `_meta["io.modelcontextprotocol/serverInfo"]`. List and read results carry `ttlMs` and
  `cacheScope`.
- **Older revisions.** It also speaks the handshake revisions `2025-11-25`, `2025-06-18`, `2025-03-26` and `2024-11-05`
  (`initialize`), and a client may use either kind. An unknown version in `_meta` gets
  `UnsupportedProtocolVersionError` (-32022) with the versions it supports. `initialize` with an unknown version
  gets `2025-11-25`.
- **stdio.** One JSON-RPC message per line, UTF-8, `\n` or `\r\n`. Batches are answered for the `2025-03-26`
  revision.
- **Streamable HTTP.** One endpoint, `/mcp`. A POST carries one message and gets `application/json` back, or
  `202 Accepted` with no body for a notification. GET gets 405, since the server sends no stream of its own.
  - Modern requests need `MCP-Protocol-Version`, `Mcp-Method` and, for `tools/call`, `resources/read` and
    `prompts/get`, `Mcp-Name` (plain or `=?base64?...?=`). They must match the body, or the reply is
    `400` with `HeaderMismatch` (-32020). An unknown method is `404` with -32601. An unsupported version is
    `400` with -32022.
  - Handshake clients get an `Mcp-Session-Id` on `initialize`. An unknown session gets 404, and DELETE ends a
    session.
  - `Origin` (when sent) and `Host` must be loopback names, or the reply is 403. This guards against DNS
    rebinding.
  - The server binds to loopback only. A token is checked when one is set.
- **Errors.** A bad tool argument comes back as a tool result with `isError: true` and a sentence that names
  what to fix, so the agent can correct itself. Other errors use the protocol codes:
  - an unknown tool: -32602;
  - an unknown resource: -32602 (-32002 in the handshake revisions);
  - parse errors: -32700;
  - a malformed message: -32600.

Every tool's `inputSchema` is the one place its rules are written down. The server checks every call against it
before the tool runs: names, types, enums, ranges, required arguments and unknown arguments. Tool results carry
`structuredContent` (an object). The text block holds that object as JSON, or a sentence when the tool has one,
and pictures come as `image` blocks (`image/png`).

## Tools

| Tool and its arguments | Does |
|---|---|
| `sdk_info` | versions, sources, the catalogue, samples, the render device, the project root and the write folders, templates, avatars |
| `search_items` (`text`, `section`, `game`, `body`, `source`, `available_only` (true), `limit` (20), `offset`) | the offline catalogue; by default only items a source can draw |
| `get_item` (`id`) | one item: name, section, game, type, body, source, colourable, slots, available |
| `list_clips` (`text`, any case) | clip keys (for `render_avatar`'s `clip`) |
| `list_samples` | sample avatars to start from |
| `avatar_create` (`avatar` ("me"), `body` (`male` or `man`, `female` or `woman`), `sample`, `manifest`) | a plain avatar of a body, a sample, or your own manifest |
| `avatar_describe` (`avatar`) | body, height, weight, colours, worn items with names, face features, `ready_for_console`, `manifest_base64` |
| `avatar_wear` (`avatar`, `items` [ids], `colour`) | wear items as the editor does (an item replaces what it covers) |
| `avatar_take_off` (`avatar`, `item` or `section` or `all`) | take off; the default shirt, trousers and shoes come back |
| `avatar_set` (`avatar`, `body`, `height`, `weight` (0 to 1), `colours` {skin, hair, eyes, ...}) | shape and colours (`#rrggbb` or words) |
| `dress_from_text` (`avatar`, `text`, `body`, `replace` (true), `apply` (true), `max_items`, `seed`) | dress from a sentence (below); makes the avatar when it does not exist |
| `avatar_random` (`avatar`, `seed` (1), `body`, `style`, `palette`, `game`, `tag`, `matched_set`, `props`, `plain`, `no_costume`) | a seeded random avatar (`sona_make_random`, [Making avatars in code](makers.md)), only from items a source can draw; the items picked |
| `avatar_dress_like` (`avatar`, `like` (a name) or `like_manifest`, `parts` [clothes, props, hair, face, colours, shape], `match` same/similar/any, `layer`) | dress the avatar like another (`sona_make_dress_like`); what each item became |
| `outfit_check` (`avatar`, `fix`) | every issue of the outfit (`sona_outfit_check`), errors first, and the matched set it wears; `fix` mends the errors first |
| `render_avatar` (`avatar`, `width`, `height` (512), `framing` full/upper/bust/face, `yaw`, `clip`, `time`, `background`, `save_to`) | the picture, as an image block; also saved when asked |
| `render_item` (`id`, `size` (256), `background`, `save_to`) | an item preview: the item alone on the stand-in body, framed by its slot |
| `export_avatar` (`avatar`, `save_to` (a `.glb` or `.fbx` inside the project folders), `format` glb/fbx, `rigged`, `clip`, `time`, `clips` [keys], `bones` unity/vrm/vrm0/ue4/ue5) | a model file of the avatar, as `sona export` writes it; `missing_items` lists worn items no source has |
| `emote_from_text` (`text`, `body`) | the clips, blend weights, speed and face a sentence means (`sona_emote_from_text`) |
| `list_templates` | project templates |
| `project_create` (`path`, `template` (cpp-starter), `name`, `avatar`) | a project folder with the avatar in it |
| `project_set_avatar` (`project`, `avatar`) | write an avatar into a project's `avatar.b64` |
| `project_files`, `project_read_file`, `project_write_file` (`project`, `file`, `content`, `max_bytes`) | list, read and change a project's files (inside the project only) |
| `project_build` (`project`, `timeout_s` (600)) | CMake configure and build; `ok`, exit code, seconds, the end of the log |
| `project_run` (`project`, `seconds` (10), `args` (an array of strings, such as `["--avatar", "me.txt"]`), `timeout_s`) | run the built program; frame stats, the end of its log and its screenshot as an image |
| `project_log` (`project`, `which` build/run, `lines` (80)) | a project's log |
| `frame_stats` (`project`) | the last run's frame stats |
| `server_log` (`lines` (50)) | this server's log: calls, refusals and the SDK's messages |

An example, `dress_from_text {"text": "dress my avatar like a pirate"}` over the full catalogue (the reply,
shortened):

```json
{"themes": "pirate", "search_words": "pirate eyepatch tricorn parrot ...",
 "items_considered": 432,
 "picks": [
   {"name": "Pirate Pants & Boots", "section": "costume", "game": "Pirates", "score": 16, "why": "..."},
   {"id": "00000040-f62b-72d3-c3d0-f6335858086d", "name": "Pirate Bandana", "section": "headwear", "game": "Pirates",
    "score": 16, "why": "name has \"pirate\"; from a \"pirate\" set; ..."},
   {"name": "Pirate Ship", "section": "carryable", "score": 16, ...}, {"name": "Pirate Earrings", "score": 14, ...},
   {"name": "Eyepatch", "section": "glasses", "score": 12, ...}, {"name": "Pirate Skull 2 Shirt", "score": 10, ...},
   {"name": "The captain cut", "section": "hair", "score": 6, ...}],
 "applied": true, "avatar": {"avatar": "me", "worn": [...], "manifest_base64": "..."}}
```

Then `render_avatar {}` returns a text block ("Rendered avatar "me" at 512x512 ... 43,184 pixels covered") and an
`image/png` block. A carryable is drawn only while the prop clip plays, so when the avatar has
one the reply says to render with `clip: "prop"`. Even then the picture may not show it in the hand: in our
renders the Pirate Ship stood on the floor beside the feet (`clip: "prop"`, `time: 1.5`). Where the core places a
prop is not this server's to change.

## Resources and prompts

| URI | Type | What |
|---|---|---|
| `sona://guide` | text/markdown | the order of calls and the rules, for agents |
| `sona://sections` | application/json | section keys and how many items each offers |
| `sona://log` | text/plain | the last 200 lines of the server log |
| `sona://avatars/{name}` | application/json | an avatar, as `avatar_describe` gives it |
| `sona://avatars/{name}/preview.png` | image/png (blob) | the last render of it |

Prompts: `dress_avatar {style}` and `starter_project {path}`.

## Dressing from text

`sona_tk_dress` in `toolkit/tk_dress.c` does the work, with no model in the loop. It is deterministic: the same text
and catalogue always give the same outfit.

1. **Words.** The sentence is split into words. Filler words ("dress", "my", "like", "a") are dropped.
2. **Themes.** A word that names a look in `toolkit/tk_themes.c` (41 looks: pirate, ninja, knight, astronaut, ...)
   brings in that look's words:
   - strong words, worth most in an item's name;
   - related words, worth some;
   - avoid words, which mark items that share a word but mean something else, such as a ball team called the
     Pirates.

   Any other word counts as a strong word of its own. A word and its plural are one word. Colour words ("red",
   "navy") tint the items that take colours, and they add only to items that already match something else. An item
   that takes colours scores a little more when the text has one. When no pick takes colours, the reply carries
   `colour_note` to say the colour is not on the avatar.
3. **Candidates.** The catalogue is searched for each word. The candidates are items the editor offers for that
   body, not duplicates, wearable, and available in a source.
4. **Score.** A word scores most in an item's name, less in its game or set, less again in its type, least in its
   description. A word the person typed scores a little more than one a theme added. An avoid word costs a lot.
   The set (game) whose best items score most gets a bonus on all its items, so the outfit hangs together.
5. **Pick.** The best item of each section is taken, best first. An item is skipped when an earlier pick already
   covers one of its garment slots, so a costume and a shirt never fight. `seed` picks among near-best items for
   variety.
6. **Why.** Every pick says why it was picked, and `apply: false` only proposes.

Over the full catalogue (23,943 items), for example:

- **"a pirate"** gives a pirate bandana, an eyepatch, pirate earrings, pirate trousers and boots, a pirate ship and
  a pirate tee.
- **"a red ninja"** gives a black ninja hood and costume, with no red: neither takes colours, and `colour_note`
  says so.
- **"astronaut"** gives an astronaut suit and helmet.
- **"knight in armour"** gives chainmail knight armour, a knight shield and a winged helmet. The knight look's avoid
  words (rises, bane, batman, combat, camo, ...) keep out the film-franchise hat and the modern combat helmet it
  picked before.

Where the catalogue has a better item than the words find, the agent swaps it with `search_items` and
`avatar_wear`. The agent test below did that: it swapped a franchise tee that had "pirates" in its name. That run came before a
scoring fix (a word and its plural now count once), and since the fix dressing picks the pirate skull shirt itself.

## Writes and builds

Every path an agent gives is resolved before anything is written. Resolving joins it to the root and folds `.` and
`..` component by component, and follows the symlinks of the part that exists, so `link/..` means what the file
system means and a link that leads out is caught. The write must land in the project root or a folder the host
allowed:

- `project_create`'s `path`;
- `save_to`, which must also name a `.png` file (`.glb` or `.fbx` for `export_avatar`);
- `project_write_file`, which must also stay inside its project;
- the starter's `--out` and `--avatar` in `project_run`'s `args`.

Anything else is refused with a sentence that says who may allow it. The agent cannot widen the rule. Only the
person who starts the server can, ahead of time, with `--allow-write`, `SONA_MCP_ALLOW_WRITE` or `"allow_write"` in
its config file, or the host can through `allow`, which the Studio uses to ask its user. Project reads are held to the project folder too.

> **Warning:** No agent write may land in a `.sona/` folder. That folder holds the tool's own records:
> `project.json` (the program's name, which must be a plain name), `run-args` and `sdk.cmake`.

**Builds and runs execute agent-controlled code with the user's rights.** `project_build` runs CMake on the
project's `CMakeLists.txt`, and `project_run` runs the program built from its sources. CMake alone can write any
file and start any program. So once an agent changes a project, nothing the write rule checks can bound what a
build does. The server therefore notes every `project_write_file` in that project's `.sona/edited`, and in every
project that holds it. It then refuses `project_build` and `project_run` for that project unless the host allows
them:

- `--allow-exec`, `SONA_MCP_ALLOW_EXEC=1` or `"allow_exec": true` in the config file allows them all (set before
  the server starts; nothing asks at run time, and the refusal names all three);
- the Studio's `allow_run` callback asks its user for each one, with the project and "build" or "run".

A project made by `project_create` and left alone builds and runs with no say, because the server wrote every file
in it. Its run arguments are held to the starter's own options (`--seconds`, `--size`, `--avatars`, `--clip`,
`--out`, `--avatar` and `--cpu`), with `--out` and `--avatar` inside the project folders. `--allow-exec` lifts that
too. `sdk_info` reports which rule is in force as `edited_projects`.

## Projects

`cpp-starter` is the one template: the plaza starter, twelve avatars in costumes walking round a plaza,
the first wearing `avatar.b64`. `project_create` writes:

| File | What |
|---|---|
| `main.cpp` | opens a ctx with the server's sources, adds the walkers, makes a headless Vulkan device, walks them for `--seconds` (8) |
| `place.h` | the plaza and the light it gives the avatars |
| `brand.h`, `logo.png` | the logo of the loading screen |
| `cast.json` | the other eleven walkers |
| `vk_min.h` | the few Vulkan declarations it needs and a run-time loader, so no Vulkan SDK is needed to build |
| `CMakeLists.txt`, `Makefile` | the build; `make check` builds and runs an 8-second headless smoke test. On Windows the build copies `sona.dll` from the download's `bin` beside the program |
| `README.md` | for people and agents: build, run, options (`--size` 1600x900, `--avatars` 1 to 12, `--cast`, `--clip`, `--loading`, `--layer`, `--cpu`), the output format, where to go next |
| `avatar.b64`, `sona-licence.json` | the avatar and a copy of the licence |
| `.sona/` | `project.json`, `sdk.cmake` (the SDK's paths), `run-args` (sources and licence), `build.log`, `run.log`, and `edited` once an agent has changed a file |

The program prints one JSON object per line:

- `{"sona":"frame_stats","t","seconds","frames","frame_ms_mean","frame_ms_max","cpu_ms_mean","avatars","ready",
  "draw_calls","gpu_mb","cpu_mb"}` once a second;
- `{"sona":"done","frames","ready","avatars","walked","device","screenshot"}` at the end.

`project_run` and `frame_stats` read these lines back. A frame here is one `sona_update` and one `sona_snapshot`,
which draws and reads back, so the numbers measure that loop, not a game's swapchain frame.

Builds and runs have a time limit. The whole process tree is killed when one runs over: a process group on POSIX, a
job object on Windows. Neither ever opens a window.

## Hosting the server (the Studio)

```c
#include "sona_mcp.h"

sona_mcp_options o = { 0 };
sona_mcp *s;
char err[512];
o.tk.dirs[0] = "assets"; o.tk.dir_count = 1;
o.tk.catalogue_path = "data/sona-catalogue.bin";
o.root = "projects";
o.allow = ask_the_user; o.allow_user = app;      /* a write outside the projects: ask */
o.allow_run = ask_to_run;                        /* building or running a project an agent edited: ask */
if (!sona_mcp_create(&o, &s, err, sizeof err)) return fail(err);
sona_mcp_http_start(s, "127.0.0.1", 7360, NULL); /* agents connect here */
/* or, for one client over pipes: sona_mcp_serve_stdio(s, in, out); or per message: sona_mcp_handle(s, json, len) */
sona_mcp_destroy(s);
```

Requests are served one at a time. Every entry point may be called from any thread, and the ctx only ever sees one
at once. Link the `sona_mcp` target, which pulls in `sona_toolkit`, cJSON, CivetWeb and `sona_static`.

## The toolkit

The server's tools are thin wrappers over the library the CLI uses:

- **Session.** A ctx opened from folders, the gate and a licence; the catalogue; the samples; plain avatars; item
  availability.
- **Rendering.** A headless Vulkan device, made on first use with the loader opened at run time, so a machine with
  no driver gets a sentence and no crash. Avatar renders and item previews; compressed PNGs.
- **Dressing.** `sona_tk_dress` and `sona_tk_dress_apply`.
- **Projects.** Templates, build, run, frame stats.
- **Processes.** Output to a log, a time limit, and the whole tree killed when it runs over.
- **Paths.** The write sandbox.

Pictures. `sona_png_encode` writes stored deflate blocks, so its files are as large as their pixels. The toolkit compresses with
stb_image_write and splices in the same three credit chunks, for a file about a tenth of that.

## Third-party code

Only the toolkit and sona-mcp use these, never the library. They are fetched by URL and SHA-256 (`toolkit/deps.cmake`),
and the notices are in `native/THIRD-PARTY.txt` and `native/third-party/sona-mcp.txt`.

- **cJSON 1.7.19** (MIT): JSON.
- **CivetWeb 1.16** (MIT): only `src/civetweb.c`, with no SSL, CGI, file serving or scripting. It serves HTTP.
- **stb_image_write 1.16** (MIT or public domain): PNG compression.

An offline build points `SONA_CJSON_DIR`, `SONA_CIVETWEB_DIR` and `SONA_STB_WRITE_FILE` at local copies.
`-DSONA_BUILD_TOOLS=OFF` leaves the tools out. With MSVC it is off by default; `-DSONA_BUILD_TOOLS=ON` turns them
on.

## Limits

- `cpp-starter` is the one project template.
- Text-to-emote (picking clips from a sentence) is a C call (`sona_emote_from_text`), not a tool.
- Long builds send no progress notifications.
- The `subscriptions/listen` stream: the lists never change at run time, so the server does not offer it.
- The Windows build of sona-mcp is built with MSVC (/W4 /WX) and mingw-w64 and tested.
