Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ With the server above still running, `tensorfold chat --url http://127.0.0.1:808
`echo "Say hello." | tensorfold chat --url http://127.0.0.1:8080` prints one reply for a script.
See [the chat command](docs/chat.md) for its flags and the serve flags it passes on.

`tensorfold mcp` lets an AI coding assistant such as Claude Code, Codex or Cursor describe this machine, list and
download models, and start and stop local servers through Model Context Protocol tools. Add it to Claude Code with
`claude mcp add tensorfold -- tensorfold mcp`. [The MCP guide](docs/mcp.md) covers the tools and other clients.

## Docs

- [Run guide](docs/run-guide.md): platform setup, requests, parallel requests, exact decoding, context compaction,
Expand Down
32 changes: 32 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1659,6 +1659,38 @@ value. `binding` hashes the field `tensorfold execution binding v1`, then `witne
no route does that today, since each path that binds nothing runs only under a flag the witness excludes, so `unbound`
would mean a reply path that skipped the binding by mistake. No response cache reads the binding yet.

## Router

[`tensorfold serve --router`](router.md) forwards each model request to the child its `model` field names and
relays the child's reply unchanged, head and body, as it arrives. It answers these routes itself:

- `GET /health` (and `GET /`), without a key. With keys configured the body is only `{"status": "ok"}`. Without keys
it has `status` (`"ok"`), `router` (`true`), `models` (how many it serves), `max_loaded`, `loaded` (an object for
each child that is `loading`, `ready` or `stopping`: its `id`, `state` and `requests_in_progress`) and `version`. While the
router stops it answers 503 `{"status": "draining", "requests_in_progress": N}` with `Retry-After`, as a server does.
- `GET /v1/models` (and `/models`) lists every id and alias, loaded or not, each with a boolean `loaded` last. A ready
child's entries are its own `/v1/models` entries, with every field a server gives them; the others have `id`,
`object`, `created` and `owned_by` only, since the rest is known once the model loads.
- `GET /api/tags` lists every id and alias, and `GET /api/ps` the ready children, each as `{"name": ID, "model": ID}`,
as a server lists its own names. `GET /api/version` gives the router's release.

Its own refusals come in the route's error shape (OpenAI's error object, Anthropic's typed error, or Ollama's
`{"error": "..."}`), with these codes:

| Status | Code | When |
| --- | --- | --- |
| 400 | `model_required` | The body names no `model` |
| 404 | `model_not_found` | No id or alias is that name |
| 404 | `unsupported_route` | A route the router does not serve in this version, named in the message |
| 502 | `model_server_failed` | The child exited, or closed the connection, before its reply |
| 503 | `models_busy` | Every loaded child is busy and `--max-loaded` leaves no room, after 5 minutes; `Retry-After: 10` |
| 503 | `model_too_large` | The model's memory floor is larger than the machine's memory |
| 503 | `model_load_failed` | Its child exited while loading; the message has the child's last log line |
| 503 | `model_load_timeout` | Its child was not ready in time |
| 503 | `server_restarting` | The router is stopping; `Retry-After: 30` |

A child's own replies, errors included, pass through as the child sent them.

## Cancel a request

`POST /v1/requests/{id}/cancel` (or `/requests/{id}/cancel`) cancels a running or queued request by the id its
Expand Down
110 changes: 110 additions & 0 deletions docs/mcp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# TensorFold for AI coding assistants (MCP)

`tensorfold mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server on stdin and stdout.
An AI coding assistant such as Claude Code, Codex or Cursor starts it and calls its tools to see what this machine
runs, download a model, and start or stop a local TensorFold server, instead of you typing the commands.
It needs no model, GPU or network until a tool asks for one.

## Add it to a client

Claude Code:

```sh
claude mcp add tensorfold -- tensorfold mcp
```

Add `--scope user` before the name to have it in every project.

Codex, in `~/.codex/config.toml`:

```toml
[mcp_servers.tensorfold]
command = "tensorfold"
args = ["mcp"]
tool_timeout_sec = 3600
```

Cursor reads `~/.cursor/mcp.json` or a project's `.cursor/mcp.json`. It, Claude Desktop and other clients with an
`mcpServers` file take this entry:

```json
{
"mcpServers": {
"tensorfold": { "command": "tensorfold", "args": ["mcp"] }
}
}
```

A client started from the desktop may not see your shell's `PATH`, so give `command` the full path that
`command -v tensorfold` prints. With a Linux release archive, name `tensorfold-native`. The quick start's `tensorfold`
is a shell function, and a client does not see it.

`pull` and `serve` can take minutes. Codex stops a tool call after 60 seconds unless you raise `tool_timeout_sec`, as
above. Claude Code limits a call with `MCP_TOOL_TIMEOUT`, and one that reports no progress with
`CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT`. This server reports progress whenever the client's request asks for it.

## Tools

| Tool | Arguments | What it does |
| --- | --- | --- |
| `machine` | none | The OS, CPU, memory and GPUs, and the TensorFold version, backend and model types this build serves. It reports the host facts `tensorfold benchmark` records, so no hostname or serial number. |
| `models` | none | The checkpoints in the Hugging Face cache that a TensorFold family serves, as `tensorfold models` lists them, with each revision and size on disk. |
| `info` | `model` | One checkpoint's family, format, context, weights and memory floor, or Flash Next's Metal budgets, as `tensorfold info` prints them. |
| `pull` | `repo`, `revision` (optional) | Downloads a Hugging Face repo with `tensorfold pull`'s own code. It checks the files against the Hub, resumes an interrupted download and refuses a repo no family serves. |
| `serve` | `model`, `context` (optional), `drafter` (optional) | Starts `tensorfold serve` for a cached model and answers once the server does. |
| `stop` | `id` | Stops a server this session started. |
| `status` | none | The servers this session started, with each one's id, model, served name, base URL and whether it still runs. A server that exited on its own shows its last log lines. |

Every result is plain text for the assistant and the same facts as structured content. A tool that cannot do what it
was asked returns a tool error that says why, so the assistant can correct the call. Nothing a client sends crashes
the server.

## Servers that `serve` starts

Each server listens on `127.0.0.1` at a free port and answers to the repo's last part as its model name, as
`tensorfold serve REPO` does. It gets a fresh random API key of 64 hex characters in `TENSORFOLD_API_KEY`, as
`tensorfold chat` gives its own server. Only `serve`'s result carries the key, with the base URL and the served name:

```sh
curl -fsS http://127.0.0.1:PORT/v1/chat/completions \
-H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
-d '{"model":"Qwen3.5-2B-MLX-4bit","messages":[{"role":"user","content":"Say hello."}],"max_tokens":32}'
```

Chat completions, Responses and Anthropic Messages are under that base URL. Messages clients send the key as
`x-api-key`. Calling `serve` again for a model and settings already running returns that server and its key instead
of loading a second copy.

The child inherits your environment as `tensorfold serve --router`'s children do, without your API key or the
benchmark's upload token. It shows no live status line, skips the update check and keeps Hugging Face offline. It runs
in a process group of its own, so a terminal's Ctrl-C reaches this server, which then stops it. Its log is a file under
`~/.tensorfold/mcp`, which the server unlinks once the child starts.

Every server the session started stops when the session ends. The session ends when the client closes stdin, or on
SIGTERM, SIGINT or SIGHUP, and a server still loading stops too. Nothing can clean up after SIGKILL, so a client
should close stdin first. On Windows, `serve` refuses by name because it stops its servers with POSIX signals. The
other tools work there.

## What the tools accept

No tool deletes anything. `pull` takes a Hugging Face repo id, `owner/name`, and an optional branch, tag or commit.
It never takes a path. `info`, `serve` and `drafter` take a repo id already in the cache, or the absolute path of an
existing checkpoint directory, one that holds `config.json`. The tools refuse relative paths, `~` and any `..`,
because the assistant does not choose the server's working directory. Each tool checks its arguments against its JSON
Schema, so an unknown argument, a wrong type or a missing one is a tool error.

## Protocol

The server implements MCP revision 2026-07-28. There every request names its revision and client capabilities in
`_meta`, and `server/discover` lists what the server supports. It also speaks the `initialize` handshake of revisions
2025-11-25 and 2025-06-18 to clients that open with it, and answers an `initialize` asking for another revision with
2025-11-25. It answers `ping` under the handshake revisions, which define it.

- Messages are JSON-RPC 2.0, one to a line, at most 4 MiB. Bad JSON gets `-32700`, a batch or a malformed message
`-32600`, an unknown method `-32601`, and bad parameters, an unknown tool or a request naming no revision `-32602`.
A revision this server does not speak gets 2026-07-28's `-32022` with the supported list.
- A `tools/call` with a `progressToken` in `_meta` gets progress notifications. `pull` reports its lines as
`tensorfold pull` prints them, and `serve` reports every five seconds while a server loads.
- `notifications/cancelled` stops a loading server, and its call answers nothing. A download cannot stop midway, so a
cancelled `pull` goes on and answers nothing. The next `pull` of that repo resumes from where it got to.
- stdout carries protocol messages only. Diagnostics go to stderr.
128 changes: 128 additions & 0 deletions docs/router.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# Several models at one address

`tensorfold serve --router` answers for several models at one address and loads each one when a request names it.
Point any OpenAI, Anthropic or Ollama client at it and pick a model by name, as with one server.

```sh
tensorfold serve --router # every cached checkpoint, by its repo id
tensorfold serve --router --router-config models.toml # the models the file lists
tensorfold serve --router --max-loaded 2 --idle-unload 900 --api-key-file /etc/tensorfold/keys
```

Each model runs as its own `tensorfold serve` child: the same binary, serving that one model on 127.0.0.1 at a port
the system picks. A child gets a random key of its own in its environment (`TENSORFOLD_API_KEY`), and the router sends
that key with every request it forwards, so other users of the machine cannot use the child's port. A request's
`model` field picks the child. When it is not running, the router starts it, and the request and any others for that
model wait until it is ready. The child's reply comes back byte for byte as it arrives, streams included.

The children lead process groups of their own, so a Ctrl-C or a closed terminal reaches only the router, which then
stops every child: SIGTERM, up to 30 seconds to finish the requests in progress, then SIGKILL. Without API keys, a
hangup (SIGHUP) stops the router as SIGTERM does; with keys it rereads the key file, as `serve` does.

## Flags

| Flag | Meaning |
| --- | --- |
| `--router` | Route by model instead of serving one; it takes no `MODEL`. |
| `--router-config FILE.toml` | The models to serve, each in a `[[models]]` table (below). Without it, every cached checkpoint. |
| `--max-loaded N` | Children loaded at once, 1 (the default) to 64. |
| `--idle-unload SECONDS` | Stop a child after this long with no request; 0, the default, keeps it. The same seconds as `serve --idle-unload`. |
| `--host HOST`, `--port PORT` | The router's address, default `127.0.0.1:8080`. |
| `--api-key KEY`, `--api-key-file FILE` | The router's keys, with `TENSORFOLD_API_KEY`, as [serve takes them](api.md#api-keys); scoped keys keep their scopes. |
| `--allowed-host NAME`, `--allowed-origin ORIGIN` | The router's [browser request checks](api.md#browser-request-headers). |

Any other serve flag on the router's command line is refused by name: set it on the model in `--router-config`.

## Models without a config

Without `--router-config`, the router serves every checkpoint `tensorfold models` lists, each under its repo id
(`org/name`) with serve's default flags. `GET /v1/models` lists those ids. The list is read once, at startup; a
checkpoint that `serve` would refuse, such as one whose cached revision is missing, is left out and the log says why.

## The config file

```toml
# models.toml
[[models]]
id = "glm"
model = "zai-org/GLM-5.3-Flash"
aliases = ["glm-flash"]
context = 131072
thinking = false
prompt-cache-gib = 8

[[models]]
id = "small"
model = "./weights/small" # a folder beside models.toml
parallel = 2
```

Each `[[models]]` table is one model:

- `id`: the name it answers to. Required.
- `model`: a folder or a Hugging Face repo id in the cache, as `serve MODEL` takes it. Required.
- `aliases`: more names it answers to, a string or a list of strings.
- Any other key is a serve flag, read as [serve config files](serve-config.md) read their keys: the same key rules,
value checks and messages, and a relative path starts at the file's folder.

An id or alias is 1 to 256 bytes with no spaces or control characters and does not start with `-`. No name may belong
to two models. The router sets these flags on every child itself, so a table that sets one is refused with the reason:
`name`, `alias`, `host`, `port`, `unix-socket`, `api-key`, `api-key-file`, `idle-unload`, `allowed-host` and
`allowed-origin`. A top-level key is refused too: the file holds `[[models]]` tables only, and the router's own flags
go on its command line. The file is opened as `serve --config` opens its file (no link, nothing other users can write,
at most 1 MiB), and every problem names the file and the line.

At startup the router checks each model's command line as `serve` would and finds its checkpoint (and drafter) in
the cache; a model that fails either stops the start with the model's id and the reason.

## Loading and stopping

- At most `--max-loaded` children are loaded at once. Loading another first stops the least recently used child that
has no request in flight. If every loaded child is busy, the request waits up to 5 minutes for one to finish, then
gets 503 `models_busy` with `Retry-After`.
- Memory: each model has a memory floor, the estimate `tensorfold info` prints (weights plus a 2 GiB runtime margin,
or Flash Next's startup budget on Metal), plus its `--drafter`'s weights. Before a child starts, the floors of the
loaded children plus its own must fit in the machine's memory; idle children stop, least recently used first, to
make room. A model whose floor is larger than the machine's memory gets 503 `model_too_large`. A model with no
estimate is bounded by `--max-loaded` alone, and the log says so.
- A child gets as long to load as `tensorfold benchmark` gives its server: 600 seconds, plus 6 seconds for each GB of
weights past 20 GB, at most 3600. Past it the request gets 503 `model_load_timeout`; a child that exits while
loading gives 503 `model_load_failed` with the child's last log line.
- A child that exits while it is loaded is marked unloaded. Requests still waiting for its reply get 502
`model_server_failed`; a reply already streaming ends where the child stopped, as a lone server's would. The next
request starts it again.
- Each child's log goes to a private file under `~/.tensorfold/router`, removed from the folder as soon as the child
starts. The router prints the child's last lines when it fails to load or exits.

## Routes

These routes are forwarded by their JSON body's `model` field (POST; rerank also by PUT):

| API | Routes |
| --- | --- |
| OpenAI | `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/embeddings`, `/v1/rerank`, `/tokenize`, `/detokenize` |
| Anthropic | `/v1/messages`, `/v1/messages/count_tokens` |
| Ollama | `/api/chat`, `/api/generate`, `/api/embed`, `/api/show` |

They also answer at the other spellings a server takes, such as `/chat/completions` and `/messages`. A body with no
`model` gets 400 `model_required`, and a name the router does not serve gets 404 `model_not_found`. The router answers
in the route's own error shape: OpenAI's error object, Anthropic's `not_found_error`, or Ollama's
`{"error": "..."}`. A restricted key's Responses requests must be stateless, as on a server.

The router answers these itself, with [API keys](api.md#api-keys) and scopes applied as a server applies them:
`GET /health`, `GET /v1/models`, `GET /api/tags`, `GET /api/ps` and `GET /api/version`. See
[the API notes](api.md#router).

Everything else is refused by name with 404 `unsupported_route` in this version, among them `GET /v1/responses/{id}`
(stored responses stay in the child that made them), the Responses WebSocket mode, `GET /metrics` (each child keeps
its own metrics, which the router does not expose), `POST /v1/requests/{id}/cancel`, speech, images, OCR and the
server's own pages.

## Limits

- The router is not available on Windows: run one `tensorfold serve` a model.
- Each child plans its memory as a lone server does. With `--max-loaded` above 1, set `prompt-cache-gib` for each model
so that the first one loaded does not take the room the next needs.
- The memory check counts the machine's system memory. On a discrete GPU, `--max-loaded` is the bound that matters.
- A router killed with SIGKILL leaves its children running; they stop only when the router stops itself.
- `capabilities --json` does not list the router's flags.
2 changes: 2 additions & 0 deletions docs/serve-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,5 @@ The startup log names the file and how many options it gave, never a value.
- `tensorfold benchmark` and `tensorfold service install` do not read the file. TensorFold Web refuses
`--config` as an extra flag, because a file could set the flags that Settings manages.
- Prefer `api-key-file` to `api-key` in a file that is checked in, so that no key is stored with it.
- A [router config](router.md#the-config-file) is a different file: one `[[models]]` table a model, whose serve keys
follow these rules.
1 change: 1 addition & 0 deletions docs/supported-models.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ It sends the token only to the hub's own host (`huggingface.co`, or the host of
When the hub refuses a repo, `pull` names it and says whether a token is missing or the token lacks access; without a token, Hugging Face refuses a mistyped repo name the same way.
`models --json` prints one document for programs: `schema` 1 and `models`, each cached checkpoint's `repo`, `family` and `model_type` (`family` is a display title and `model_type` is the key to match on), plus `machine` and `catalog`, each entry's `need_bytes`, `fit`, `tok_s` (null when unmeasured), `quality` (passed, items, share, suite digest and receipt; null when unrated), `on_disk` and `install`.
`tensorfold serve REPO` serves a cached checkpoint by its repository name.
`tensorfold serve --router` serves every cached checkpoint, or the models a `--router-config` file lists, at one address, each loaded when a request's `model` field names it; see [several models at one address](router.md).
`rm REPO` removes a cached checkpoint with all its snapshots, blobs and refs, and then the repo's folder.
`rm REPO@REVISION` removes one snapshot, named by a ref such as `main` or by its commit, and the refs that name it. Blobs another snapshot still links to stay.
Before deleting, it lists each snapshot and the bytes freed, counting a blob two snapshots share once, and asks.
Expand Down
Loading
Loading