scaling-swarms / docs /MCP.md
tfrere's picture
tfrere HF Staff
Cursor
feat(mcp): chart and publish tools, structured errors, JSON 404s
2525af6
|
Raw History Blame Contribute Delete
14.6 kB

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_text rewrites 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.
  • undo reverts 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_embed validates the HTML against the contract (errors are refused with invalid_embed and the list of problems), writes it to the article's embeds and records version 1. Nobody sees it until insert_embed adds its node to the text. The banner is the exception: insert_embed on banner.html makes it the article banner.
  • Updates apply directly. Each update_embed or restore_embed_version is a new version attributed to the agent, visible to readers of the editor at once (published readers see it after the next publish). Pass expected_version (from get_embed or 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 with draft_in_progress unless force: true; their draft is never overwritten.
  • The check. After create_embed and update_embed (unless check: 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.status is PASS, WARN or FAIL; each entry of check.checks has 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.mode is "static" and only the contract rules ran (check.note says why).
  • Data. The iframe cannot fetch: inline the values in the script. data_files keeps the source data with the article (the Embed Studio shows it in its data drawer, get_embed says which files the chart uses).
  • Reverting. restore_embed_version puts any listed version back as a new version. undo and "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"
  • publish runs 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.pdf is 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 with already_running: true instead 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 only default is published (not_publishable otherwise). 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

  1. read_article with outline: true, then section: "Results"; note the heading's block:ID and rev.
  2. create_embed:
    {
      "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>"
    }
    
    The result has "name": "model-accuracy.html", "version": 1 and check. If check.status is FAIL, read check.checks[].messages and fix with update_embed (patch or html, expected_version: 1); each update returns a new check.
  3. insert_embed with { "name": "model-accuracy.html", "after_block_id": "<heading id>", "expected_rev": "<heading rev>" }. On rev_conflict, read the section again and retry with the new rev. The title and source given to create_embed become the caption (override with title, description, source).
  4. Later: get_embed to read the settings and latest_version, update_embed with { "config": { "title": "Top-1 accuracy" }, "expected_version": 2 }, or restore_embed_version to go back.

Example: publish

  1. get_article_info: publishable must be true; last_publish says when the article was last put online.
  2. publish (waits up to 120 s by default). status: "succeeded" with urls.html (and urls.pdf when a PDF was made) is the answer to give the user. status: "running" means the timeout passed first: call get_publish_status with the job_id until it is succeeded or failed.
  3. A publish_failed error carries the job with its error; 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.ts handles the Streamable HTTP sessions, bearer auth, Origin validation and the 30-minute idle cleanup.
  • backend/src/mcp/agent-peer.ts is the headless collaborator: Yjs doc, awareness, agentFocus and a per-session Y.UndoManager.
  • backend/src/mcp/y-blocks.ts does 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.ts converts Markdown to TipTap JSON for new blocks.
  • backend/src/mcp/tools.ts defines the tool definitions and the server instructions sent to the agent.
  • backend/src/mcp/embed-tools.ts implements 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.ts is the publish flow shared by the Publish button and the publish tool; backend/src/chromium-lock.ts keeps 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.