Skip to content
mgubi edited this page Nov 5, 2026 · 13 revisions

MCP server in TeXmacs: design

A proposal, for discussion: how TeXmacs serves the Model Context Protocol (MCP), so that an agent (Claude Code, Claude Desktop, any MCP client) can read, edit and check TeXmacs documents, whether or not the person has them open at the same time. The motivation and the approaches are on Agents and TeXmacs; this page is the design that follows from them and from a survey of the code of upsilon_texmacs (November 2026).

Status (5 November 2026). Shared files (section 3) are merged into upsilon_texmacs (PR #805) and on by default since 5 November 2026 (a toggle in Edit > Preferences > Other; texmacs -c never shares); the developer note is src/docs/shared-files.md. The agent part, texmacs --mcp, is merged into upsilon_texmacs too (from the branch wip_agents): reading (step 2), editing (step 3) and step 4, stage A (modes per file, proposals as version markup, the host's own filter, the checks on patches from peers; audited clean at e8f55e1e79); see MCP server: security. Stage B (trusted agents) was built, audited and set aside on 5 November (MCP-security, section 7). User help: Help > AI agents (MCP server). The crashes of the typesetter found on the way, outside the reach of agents, are #817. -headless in the Cocoa build (#804) is merged.

Tests (4 November 2026). Approach B in a window, shared files of #805 with two windows (convergence during typing, undo), sizes of the formats and start-up time: see the tests on Agents and TeXmacs.

The design has two parts, each useful without the other:

  1. Shared files: several TeXmacs processes of the same user can open the same file at once and stay in sync, as live documents do, but with no server.
  2. texmacs --mcp: a headless TeXmacs which serves MCP over stdio to one agent.

The agent runs its own texmacs --mcp; the person works in their own TeXmacs; when both open the same file, they share it.

1. Requirements

  1. Open or not. The agent works on a document whether the person has it open or not, through the same API.
  2. No lost work. An edit by the agent never overwrites a change of the person; a conflict is reported, not resolved silently.
  3. The person stays in control. They see what the agent does, can refuse it, and can undo their own changes and the agent's separately.
  4. Structure, not text files. The agent edits the tree of the document, through TeXmacs, never the .tm file behind its back.
  5. The agent can check its work: errors, references, how a page looks.
  6. The person's window stays responsive.
  7. Safe by default: no evaluation of code; nothing reachable from outside the user's account.
  8. All three interfaces (Qt, Cocoa, Vue) and the three systems.

2. What exists, and what does not

From a survey of the code:

Need Exists Missing
Patches and states the live documents (utils/relate/live-document.scm): patches with inverses, states, rebasing (patch-pull, patch-co-pull) the same without the server, on ordinary files
Messages between processes tm_link packets (<length>\n<payload>), sockets polled on the main thread, string->object a local listener (done in #805: local_link.cpp, 127.0.0.1 with a token)
Authors and undo an author on every patch (new-author, with-author), selective undo which skips other authors' patches when they commute, grouping (mark-start, mark-end, mark-cancel) an "undo the agent" command
Presence set-user-cursor, cancel-user-cursor names of participants
Proposals compare-versions (version-both nodes), version-retain, three-way merge-versions proposals made from a patch, not from the clipboard
Running without a window -headless on Qt and Vue, whose event loops keep serving sockets with -headless -X (not -q, which quits after the command line) -headless was ignored by the Cocoa build (fixed in #804); no reader of standard input
JSON a typed reader and writer (json_to_typed_tree, typed_tree_to_json), the LSP's JSON-RPC helpers the MCP layer
Stable references tree pointers (follow their node through edits), labels an id registry
Checking and viewing tree-search-sections, search-labels, search-broken-references, search-broken-citations, the log of messages, print-pages-to-file, print-snippet errors per buffer (malformed markup gives no message); a page as an image without an external tool
Conversion convert from LaTeX and Markdown snippets, and back

Constraints:

  • One thread. Scheme and the editor run on the main thread; typesetting, export and rendering block their process while they run. With shared files this is no longer a problem for the person: heavy work runs in the agent's process.
  • The live documents' client can drop its own local edits when a rebase fails. With shared files that must never happen to the person (section 4.4, where a study of the rebasing is summed up).

3. Shared files

Merged (PR #805) (Qt build tested, headless and with a window; Vue and Cocoa need nothing more but are untested; disabled on Windows for now). Turned on by the preference share-open-files: on by default since 5 November 2026, with a toggle in Edit > Preferences > Other; texmacs -c never shares. Below, what the PR does, and the decisions made while writing and auditing it.

3.1 Finding the others

  • Each shared file has an entry in a per-user folder: texmacs-<uid>/shared/ under $XDG_RUNTIME_DIR, $TMPDIR or /tmp, mode 0700 and owned by the user, else nothing is shared. The folder does not depend on TEXMACS_HOME_PATH, so that processes with different homes (as an agent's may have) find each other.
  • An entry is keyed by the canonical path of the file (symbolic links resolved; on macOS the case stored on disk, so F.TM and f.tm are one file), and holds the host's port, a random token, its process id and whether it is interactive. Entries are created exclusively (O_EXCL), mode 0600, and replaced atomically.
  • When a TeXmacs loads a file which has an entry, it joins: it gets the document and its state from the host instead of reading the file. Else it loads the file and becomes its host. Joining happens after the usual checks of loading (a very large file, wildcards) and skips the autosave question, since the host has the live content.

3.2 The link

  • One listener per process, on 127.0.0.1 only (not a Unix socket: one code path for the systems), with a random token per file; the existing TeXmacs server is not involved.
  • Messages are Scheme data in tm_link packets, read with string->object and never evaluated.
  • Limits, so that another local user cannot harm the process: 64 KB before the token is given, 64 MB per packet after; strict length headers; at most 16 unidentified connections, closed after 5 s; at most 4 new connections accepted per poll; the token is compared in constant time.
  • Served on the main thread by a poll every 20 ms (latency about 20-35 ms), which runs only while a file is shared.

3.3 The host

One participant per file is the host: it orders the patches, keeps the states and their inverses, and writes the file.

  1. An interactive TeXmacs (the person) hosts a file which only headless ones (agents) had open: when the person opens it, hosting moves to them; the former host sends its state and goes on as a participant. Two interactive TeXmacs on one file: the first one hosts.
  2. A live host is never taken over (the goal; an audit found one remaining case, a handover answered too late, being fixed). A process which joins waits at most 500 ms for the host; if the host is alive but busy (a long typesetting, a dialog), the file opens unshared, with a message, and is not saved over the host's file (an agent in it is read only). An entry is removed only when its host is gone: its process is dead, or its port refuses connections (which also covers a process id reused by another program). An empty or damaged entry is removed after 5 s.
  3. When the host closes the file, the next participant by priority takes over (the host waits at most 1.5 s for it). When the host dies, the participants elect the next one, which hosts from its own copy, keeping the changes it had not sent yet. A participant which cannot reach a busy host keeps its changes and tries again every second, without blocking.

3.4 Patches and conflicts

  • Every participant sends its changes to the host as patches made against a state, with its author, one at a time.
  • The host applies a patch made against its current state, assigns the next state and sends it to all. A patch made against an older state is rebased onto the patches since with patch-pull, only when patch-can-pull? holds and the result checks (section 4.4); otherwise it is refused.
  • The host's own changes are applied directly and never refused. A participant puts its unsent changes back over the host's patches by the same pull and co-pull chain as the host, so both sides compute the same thing and converge.
  • Nothing is lost silently. A change of a participant which is refused or cannot be put back is saved in a document $TEXMACS_HOME_PATH/system/recovered/shared-lost-<time>-<pid>-<n>.tm (the inserted text, the deleted text, the settings, and a description of structural changes), the footer says so, and an interactive TeXmacs asks whether to open it. These files are pruned after 30 days, keeping the last 50.

3.5 What is shared

  • The body, and the style and the initial environment (document style, packages, language, page settings). The latter live in the editor rather than in the document tree, so each shared buffer keeps a small shadow tree: the shared tree is (shared META BODY), and a patch addresses the meta part (index 0) or the body (index 1). Settings thus go through the same states, rebasing, history and handover as text.
  • The meta part mirrors the editor's style and initial environment: a cheap hash computed in C++ tells when they changed, and only then are they compared and turned into a patch; a patch received is installed in the editor, which typesets once, and is not sent back.
  • The initial environment is split into 16 groups by the name of the variable, so that two settings added at once do not land at the same place, where one would be refused.
  • Not shared: references and auxiliary data (numbers, table of contents, bibliography), which each participant computes by typesetting; and the variables of the window (size, zoom, full screen).

3.6 Saving and closing

  • Only the host writes the file, with its usual checks; autosave runs in the host only.
  • A Save in a participant first waits until the host has its last changes, then asks the host to save; the participant's buffer is marked saved only if nothing of it is still pending.
  • A participant which closes the file sends its last changes first (waiting at most 1 s); what could not be sent is saved as in 3.4.
  • A participant which becomes host carries out a Save it was waiting for.

3.7 Undo

Each process keeps its own undo history; patches from others carry their author, so that the selective undo of TeXmacs skips them when they commute. Not yet checked in a window: an undo after a remote patch crashed in a headless run, also with the feature off, so the crash is not caused by it (to be reported).

3.8 Not covered

  • Changes from outside TeXmacs (a git pull, another editor) while a file is shared: the host notices them at save time only, as today. Later: a watcher in the host and a merge (merge-versions).
  • Windows (the feature does nothing there until it has a strong random source and exclusive file creation), and file systems without case on Linux.
  • Cursors and names of the other participants: next steps (the menu Tools > Agents and the preference exist).

4. Agents

4.1 texmacs --mcp

The agent starts texmacs --mcp as its MCP server, over stdio, as MCP clients expect:

  • a headless TeXmacs which serves the MCP tools (section 5), written in Scheme so that every build shares them;
  • it reads JSON-RPC from its standard input (a new reader, polled on the main thread) and writes on its standard output, with all other output sent to a log file;
  • it opens files as any TeXmacs does: shared with the person's TeXmacs when the person has them open, alone otherwise;
  • typesetting, checks, export and page images run in this process, on its own copy of the document, kept in sync: they never slow down the person's window, and they never lag behind.

There is no separate program, and nothing to configure: claude mcp add texmacs -- texmacs --mcp.

A later option: the person's TeXmacs could also serve MCP over HTTP on localhost, for clients which support that transport, with no second process. It needs a small HTTP server in TeXmacs (none exists today).

4.2 An agent is a participant with less priority

An agent's process is marked as an agent when it joins a file. The host, the person's TeXmacs, applies the rules for agents:

  • its patches are the ones rebased or refused, never the person's;
  • in propose mode, the host turns each patch of an agent into a proposal (old and new version side by side, version-both), which the person accepts or rejects with the Version tools; the rule is enforced on the person's side, so an agent cannot bypass it;
  • in direct mode, its patches are applied;
  • in read-only mode, they are refused.

The person chooses the mode for each file from a menu; the default is propose for a file the person has open. When the person does not have the file open, the agent edits it directly (no one else to ask).

4.3 Addressing and conflicts for the agent

  • Reads return opaque handles (n17) for the nodes they show, kept per session as tree pointers in the agent's process, with a hash of each node's content; the agent never sees paths.
  • An edit names its handle and the hash it expects. If the node changed since the agent read it, the edit is refused with conflict and the node's current content; edits elsewhere in the document are not affected.
  • The agent's patch then goes to the host, which may still have to rebase it onto edits the person made in the meantime (4.4).
  • One tool call, one undo step: an edit is all or nothing (mark-start, mark-end, mark-cancel).

4.4 Rebasing

When an agent's patch was made against an older state, the host rebases it onto the patches since with the live documents' patch-pull:

  1. pull only when patch-can-pull? says so, else refuse (patch-pull must never be called without it); the agent is told, reads again and retries;
  2. always check the result as the live documents do: the rebased patch applies, and the co-pulled inverse leads back to the base with the agent's patch;
  3. strip set_cursor from patches before sending them: they do not commute with most modifications;
  4. keep the inverses of the recent patches in the host's history: computing them is the only part whose cost grows with the document.

A study (November 2026, headless, on the code of upsilon_texmacs; 55 written cases and 2,709 random ones) found:

  • never a wrong result: every patch was either rebased correctly or refused, and every refusal was known in advance by patch-can-pull?;
  • rebased correctly: edits in different paragraphs, in the same paragraph or the same word at different places, a paragraph inserted or deleted elsewhere, both inserting at the same place (the agent's text goes first, deterministically), rows and columns of a table added or removed, cells, equations (also wrapped in a fraction while the agent types), a tag changed or a paragraph wrapped in strong, a section moved elsewhere, and a burst of 50 keystrokes;
  • refused: when the person deletes, replaces, splits or joins the node the agent edits (even where a person would see no conflict, e.g. Return pressed far from the agent's edit), deletes the row or section around it, or moves the section containing it; also a double delete of the same word;
  • cost: under 1 ms per rebase in practice; about 30 ms to rebase across 1000 patches in a document of 1000 paragraphs, mostly computing inverses.

So refusing is conservative, never lossy. Later improvements: rebasing across a split or join which leaves the agent's text untouched, merging identical deletes, and a test suite of the Scheme side (the C++ side has patch_test.cpp).

The live documents' client does the opposite: when a rebase fails it drops its own local changes. Here the host never drops the person's changes; only the agent's patch is refused.

5. The API

Tool names and arguments are a first proposal. Every tool takes a document, a file path or an id from list_documents. Content in or out has a format:

  • texmacs (the .tm syntax of a snippet; exact);
  • stree (the Scheme form; exact);
  • latex (a LaTeX snippet; converted; good for formulas);
  • markdown (a snippet; converted; lossy for general documents);
  • text (read only: the visible text, for reading cheaply).

5.1 Documents

Tool What it does
list_documents the documents this agent has open, and those the person has open (shared files of the user): file, title, style, modified, whether the person has it open, the agent mode, the state
open_document(path) opens a file (joining it if it is open elsewhere), returns its id
create_document(path, style) a new document
save_document(document) asks the host to save
close_document(document) leaves the file

5.2 Reading

Tool What it does
get_outline(document) sections with titles, labels and handles: the map of a document, cheap
read(document, node?, format, max_size?) the content of the document or of a node, with handles for its children and the state; long content is cut, with handles to continue
find(document, query) nodes by text, by tag (theorem, equation), by label, or by section title, with a short context
get_references(document) labels, references, citations, and the broken or duplicate ones
get_changes(document, since) what changed since a state, and by whom: so that the agent sees the person's edits

5.3 Editing

Tool What it does
replace(document, node, content, format, expect) replaces a node; expect is the hash read with it
insert(document, anchor, where, content, format) before, after, or as the first or last child of a node
delete(document, node, expect) removes a node
edit_text(document, node, old, new, expect) replaces one occurrence of a string inside a paragraph, keeping its markup: the form models use best
undo_agent(document, steps?) undoes the agent's last steps
list_proposals(document), withdraw_proposal(document, proposal) its pending proposals (mode propose)

Each edit says whether it was applied, proposed or refused, with the new handles.

5.4 Checking and viewing

Tool What it does
check(document) typesets and returns the problems: undefined references and citations, duplicate labels, malformed markup (found by a scan of the tree, since the typesetter only draws it), missing images, messages of the converters and of BibTeX, each with a handle when it has a place
render(document, page or node, dpi?) an image of a page or of a node (a formula, a figure)
export(document, format, path) PDF, LaTeX, HTML, Markdown

All of these run in the agent's process.

5.5 Notifications

Each document is an MCP resource (texmacs://document/<id>); the agent can subscribe and gets notifications/resources/updated when the person changes it.

5.6 Not in the API

No evaluation of Scheme or of any code, no plugin sessions, no access to preferences, to files outside the documents, or to the network.

6. Security

The rules for what an agent may write, and the reasons, are on MCP server: security.

  • Shared files: the per-user folder (0700) and the sockets are reachable only by the user's own processes, which can already read and write the files anyway.
  • texmacs --mcp is started by the agent and talks only over its stdio; it can open the files the user can open, as the agent could with a text editor, but through TeXmacs. Optional limits: a list of folders, read-only.
  • The person's TeXmacs decides, as host, what an agent may do with a file the person has open (4.2). The person chooses the mode per file (4.2); asking the person the first time a rule is broken was built and set aside on 5 November (see MCP server: security, section 7).

7. Open questions

  • Merges a person would not want: patch-pull merges an agent's edit and a person's edit of the same word at different places. Proposed default: an agent's edit carries the hash of its node (4.3) and is refused when the person changed that node since the agent read it, even when a rebase is possible; edits of other nodes are rebased. An agent may pass no hash to accept the merge.
  • Proposals saved in the file: pending proposals are markup in the document, so they are saved with it. Keep them only on screen instead?
  • Hosting handover in the middle of a burst of patches, and a host which dies: how much must be confirmed before a patch is final?
  • What the model reads: text and markdown are cheap but lossy; texmacs is exact but long. Is a compact exact form needed?
  • Several agents on one file: separate authors and handles enough, or claims on sections?
  • Two machines: shared files are local; the TeXmacs server's live documents remain the way to share across machines, and a headless TeXmacs could join one as a participant later.
  • Cocoa headless: needed if the agent's TeXmacs on a Mac is the Cocoa build; a Qt or Vue headless build works too, since participants of a shared file can be of any build.

8. Steps

  1. Shared files between TeXmacs processes: joining, the host and its priority, patches, saving (PR #805, merged). Still to do in this step: cursors and names of the participants.
  2. texmacs --mcp, read only: the stdin reader, list_documents, open_document, get_outline, read, find, get_references. Usable by an agent to read papers, also those the person has open. Done on wip_agents (Qt + s7 tested, four audit rounds), with TEXMACS_MCP_ROOTS to limit the folders.
  3. Editing (done on wip_agents, direct mode, audited clean; the rules for content: MCP-security): handles, replace, insert, delete, edit_text, authors and undo steps, undo_agent; direct mode.
  4. Proposals and modes, enforced by the host. Stage A done (audited clean at e8f55e1e79); stage B (trusted agents) set aside on 5 November.
  5. Checking and viewing: check, render, export; Cocoa headless.
  6. Notifications and get_changes.

Each step comes with its tests (two headless TeXmacs sharing a file; a test MCP client).