Download docs/MCP.md from HuggingFaceSwarms/scaling-swarms: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/spaces/HuggingFaceSwarms/scaling-swarms/resolve/main/docs/MCP.md
- Command line
-
hf download hf://spaces/HuggingFaceSwarms/scaling-swarms/docs/MCP.md
-
curl -L -o MCP.md https://huggingface.co/spaces/HuggingFaceSwarms/scaling-swarms/resolve/main/docs/MCP.md
External agents over MCP
The editor exposes a remote Model Context Protocol server at /mcp (Streamable HTTP). Any MCP client, such as Claude Code, Cursor or Codex, can read and edit the live article while people keep writing in the browser.
The agent is a real collaborator, not a script that overwrites the document:
- It joins the same Yjs document as the browsers, with its own client id. People see it in the avatar stack and see a " agent" highlight on the text it is working on.
- Every edit is a small CRDT operation.
replace_textrewrites only the characters that differ, so concurrent typing, cursors and comment anchors around the edit survive. - It goes through the same write-permission check as a human login.
undoreverts the agent's own steps only, never other people's edits.- A version is saved in the article history right before the agent's first write and when its session ends, attributed to the agent. While the session is live, anyone with edit rights can click the agent's avatar and pick "Undo its changes": this reverts everything that session wrote and leaves other people's edits in place.
Connect
You need an HF access token with access to the Space. When the Space belongs to an org, you need write access to that org. In local dev (no SPACE_ID), any token, or none, is accepted.
Replace https://<space>.hf.space with your Space URL, or http://localhost:8080 locally.
Claude Code
claude mcp add --transport http article https://<space>.hf.space/mcp \
--header "Authorization: Bearer $HF_TOKEN"
Cursor
.cursor/mcp.json:
{
"mcpServers": {
"article": {
"url": "https://<space>.hf.space/mcp",
"headers": { "Authorization": "Bearer ${env:HF_TOKEN}" }
}
}
}
Codex
~/.codex/config.toml:
[mcp_servers.article]
url = "https://<space>.hf.space/mcp"
bearer_token_env_var = "HF_TOKEN"
Options
| Option | Where | Default |
|---|---|---|
| Display name | X-Agent-Name header |
The MCP client name (claude-code becomes "Claude Code") |
| Document | ?doc=<name> query |
default |
Tools
Text, comments, history
| Tool | What it does |
|---|---|
read_article |
Live article as Markdown. Each block is preceded by <!-- block:ID type rev:REV -->. outline: true lists headings only, and section reads one section. |
replace_text |
Replace a quoted passage. Minimal diff, keeps formatting and comments. |
insert_blocks |
Insert Markdown after or before a block, or at the start or end. |
replace_block |
Replace a whole block. Refuses blocks with comment anchors unless force. |
delete_block |
Delete a block. |
apply_edits |
Run several of replace_text, insert_blocks, replace_block, delete_block, insert_embed in order as one step: all or nothing, one undo. |
update_metadata |
Title, subtitle, description. |
list_comments, add_comment, reply_to_comment, resolve_comment |
Comment threads anchored on quoted text. |
focus |
Highlight what the agent is looking at. Edits move the highlight automatically. |
save_version |
Save a named version in the article history. |
undo |
Revert the agent's own last steps in this session (text, comments, metadata and charts). |
REV is a short hash of the block's content. Pass it as expected_rev to replace_text (with block_id), replace_block, delete_block or insert_embed (the anchor block), and the edit is refused if someone changed that block since the agent read it. Block edits also return structuredContent with the id, type and new rev of every block they touched, so an agent can chain edits without re-reading.
Charts (embeds)
A chart is a self-contained HTML fragment rendered in an iframe: a root <div class="d3-..."> first, a <style> scoped to that class, and a <script> calling Embed.mount at top level (the full contract is backend/embed-kit/contract.md; the create_embed description carries the essentials). It can declare tweakable settings in a <script type="application/json" data-embed-config> block, which people adjust in the Embed Studio without the AI.
| Tool | Inputs | Output (structuredContent) |
|---|---|---|
create_embed |
name, html, title?, source?, data_files? (up to 5 { name, content }, 3 MB each), banner?, check? |
name, version, inserted: false, data_files, contract_warnings, check |
insert_embed |
name, after_block_id? / before_block_id? / position?, expected_rev?, title?, description?, source?, wide? |
blocks: [{ id, type: "htmlEmbed", rev }] |
update_embed |
name, html? or patch? { search, replace }, config? { key: value }, title?, description?, source?, expected_version?, force?, check? |
version, previous_version, changed, check, blocks |
restore_embed_version |
name, version, expected_version? |
version (the new one), restored_from, changed |
get_embed |
name, include_html? |
html, inserted, blocks, config { fields, values }, data_files (with used_by_chart), latest_version, versions, draft |
list_embeds |
none | embeds: [{ name, title, inserted, blocks, latest_version, versions, has_config, draft, size }], data_files |
check_embed |
name |
check |
How charts behave:
- Create, then place.
create_embedvalidates the HTML against the contract (errors are refused withinvalid_embedand the list of problems), writes it to the article's embeds and records version 1. Nobody sees it untilinsert_embedadds its node to the text. The banner is the exception:insert_embedonbanner.htmlmakes it the article banner. - Updates apply directly. Each
update_embedorrestore_embed_versionis a new version attributed to the agent, visible to readers of the editor at once (published readers see it after the nextpublish). Passexpected_version(fromget_embedor the previous result) to refuse the update if someone changed the chart meanwhile (version_conflict). If a person has unapplied changes to that chart in the Embed Studio, the update is refused withdraft_in_progressunlessforce: true; their draft is never overwritten. - The check. After
create_embedandupdate_embed(unlesscheck: false), the server renders the chart in headless Chromium, in light and dark, at 360 and 680 px, and reports 8 named checks: renders at every width, no script or network errors, readable text, nothing clipped, no overlapping labels, survives a live theme switch, accessible description, follows the contract.check.statusisPASS,WARNorFAIL; each entry ofcheck.checkshas its messages. Checks run one at a time on the server (shared with the PDF export), are capped at 45 s, and at most 3 can wait; when the browser is unavailable, busy or disabled (ENABLE_EMBED_CHECK=false),check.modeis"static"and only the contract rules ran (check.notesays why). - Data. The iframe cannot fetch: inline the values in the script.
data_fileskeeps the source data with the article (the Embed Studio shows it in its data drawer,get_embedsays which files the chart uses). - Reverting.
restore_embed_versionputs any listed version back as a new version.undoand "Undo its changes" in the editor also revert chart writes of the session.
Publishing and the article
| Tool | Inputs | Output (structuredContent) |
|---|---|---|
publish |
wait? (default true), timeout_s? (default 120) |
job_id, status (running, succeeded, failed), already_running, started_by, stage, urls { article, html, pdf, thumbnail }, duration_ms |
get_publish_status |
job_id? |
job, publishing, last_publish { at, by, html, pdf } |
get_article_info |
none | doc, title, subtitle, description, authors, blocks, embeds, banner, open_comments, editor_url, public_url, publishable, publishing, last_publish, documents: "single" |
publishruns the same flow as the Publish button: the web page, the Markdown twin (/llms.txt), and a PDF and thumbnail when the server can render them (urls.pdfis null otherwise). On a Space with HF storage the URLs are the public ones. Only one publish runs at a time: calling it while one is running returns that job withalready_running: trueinstead of failing, so retrying is safe. A publish saves a version in the history, attributed to the agent.- A Space hosts one article. Sessions opened with
?doc=<name>can read and edit another document, but onlydefaultis published (not_publishableotherwise). There is no tool to list or create documents.
Errors
Every tool error comes back as isError: true with a sentence saying what to do next, and structuredContent.error = { code, message, ...details }:
code |
When | Details |
|---|---|---|
rev_conflict |
A block changed since it was read | block_id, expected_rev, rev |
version_conflict |
A chart changed since expected_version |
name, expected_version, latest_version |
not_found |
Unknown block, chart, version or publish job | the id |
already_exists |
create_embed on an existing name, or a different data file with the same name |
name, latest_version |
already_inserted |
insert_embed on a chart already in the text |
name, block_id |
invalid_embed |
The HTML breaks the embed contract | errors, warnings |
invalid_data_file |
Bad name, extension or size | name |
draft_in_progress |
A person has unapplied Studio changes to that chart | name, draft_author |
not_publishable |
publish from a session on another document |
doc |
publish_failed |
The publish ran and failed | the job (error, stage, ...) |
invalid_request |
Arguments that cannot work together (e.g. html and patch), unknown config keys |
varies |
error |
Anything else (e.g. ambiguous replace_text) |
none |
Unknown paths under /.well-known/, /mcp/ and /api/ answer a JSON 404 ({ "error": "Not found", "path": ... }), so OAuth discovery by MCP clients fails cleanly and falls back to the bearer token.
Example: add a chart
read_articlewithoutline: true, thensection: "Results"; note the heading'sblock:IDandrev.create_embed:The result has{ "name": "model-accuracy", "title": "Accuracy over training", "source": "Internal eval, 3 seeds", "data_files": [{ "name": "accuracy.csv", "content": "epoch,baseline,moe\n1,0.61,0.68\n2,0.66,0.74\n" }], "html": "<div class=\"d3-model-accuracy\"></div>\n<script type=\"application/json\" data-embed-config>{\"title\": {\"type\": \"text\", \"label\": \"Title\", \"value\": \"Accuracy over training\"}}</script>\n<style>.d3-model-accuracy { color: var(--text-color); }</style>\n<script>Embed.mount('d3-model-accuracy', (ctx) => { const rows = [{ epoch: 1, baseline: 0.61, moe: 0.68 }, { epoch: 2, baseline: 0.66, moe: 0.74 }]; const svg = d3.select(ctx.root).append('svg'); ctx.describe('Accuracy of the MoE model and the baseline over 2 epochs; MoE leads.'); return ({ width }) => { /* scales, axes, lines */ }; });</script>" }"name": "model-accuracy.html","version": 1andcheck. Ifcheck.statusisFAIL, readcheck.checks[].messagesand fix withupdate_embed(patchorhtml,expected_version: 1); each update returns a new check.insert_embedwith{ "name": "model-accuracy.html", "after_block_id": "<heading id>", "expected_rev": "<heading rev>" }. Onrev_conflict, read the section again and retry with the newrev. The title and source given tocreate_embedbecome the caption (override withtitle,description,source).- Later:
get_embedto read the settings andlatest_version,update_embedwith{ "config": { "title": "Top-1 accuracy" }, "expected_version": 2 }, orrestore_embed_versionto go back.
Example: publish
get_article_info:publishablemust be true;last_publishsays when the article was last put online.publish(waits up to 120 s by default).status: "succeeded"withurls.html(andurls.pdfwhen a PDF was made) is the answer to give the user.status: "running"means the timeout passed first: callget_publish_statuswith thejob_iduntil it issucceededorfailed.- A
publish_failederror carries the job with itserror; fix the cause (for example a chart that does not render) and publish again.
How it works
MCP client ──HTTP──▶ /mcp (router.ts)
│ one session = one AgentPeer (agent-peer.ts)
▼
HocuspocusProvider ──ws://127.0.0.1/collab──▶ Hocuspocus ◀── browsers
backend/src/mcp/router.tshandles the Streamable HTTP sessions, bearer auth, Origin validation and the 30-minute idle cleanup.backend/src/mcp/agent-peer.tsis the headless collaborator: Yjs doc, awareness,agentFocusand a per-sessionY.UndoManager.backend/src/mcp/y-blocks.tsdoes schema-free Y.XmlFragment access: stable block ids from Yjs item ids, text search across marks, minimal-diff replace and comment anchors.backend/src/mcp/markdown-to-json.tsconverts Markdown to TipTap JSON for new blocks.backend/src/mcp/tools.tsdefines the tool definitions and the server instructions sent to the agent.backend/src/mcp/embed-tools.tsimplements the chart tools on the shared embed modules (backend/src/shared/embed-contract.ts,embed-versions.ts,embed-config.ts,data-files.ts, also used by the Embed Studio) and the server-side checker (backend/src/embed-check/).backend/src/publisher/publish-service.tsis the publish flow shared by the Publish button and thepublishtool;backend/src/chromium-lock.tskeeps one headless Chromium job (check or PDF) at a time.
The browser runs y-tiptap with onInvalidContent. If an agent or a newer client ever writes a node this build doesn't know, the content is preserved in the shared document instead of being deleted. Editing then pauses with a banner until the content fits again.
Tests: backend/tests/mcp-agent.test.ts and mcp-embeds.test.ts run a real server, a human WebSocket peer and the official SDK client against each other; mcp-auth.test.ts covers permissions with OAuth on; tests/scenarios/mcp-embeds.test.ts runs the whole "add a chart and publish" flow against a server process and a restart. See section 7 of TESTS.md.