lattedit-cli 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +146 -2
- package/cli/lattedit.mjs +97 -0
- package/cli/mcp-tools.mjs +160 -0
- package/cli/mcp.mjs +356 -0
- package/package.json +27 -4
package/README.md
CHANGED
|
@@ -1,3 +1,147 @@
|
|
|
1
|
-
#
|
|
1
|
+
# lattedit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An online LaTeX editor: write source on the left, read the PDF on the right. *LaTeX, freshly compiled.*
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
web/ React + Vite frontend → Vercel
|
|
7
|
+
server/ Node + TeX Live compile service (Docker) → Render
|
|
8
|
+
desktop/ Tauri shell around web/ for Linux, macOS and Windows (see desktop/README.md)
|
|
9
|
+
render.yaml Render Blueprint for server/
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Projects live in the user's browser (IndexedDB). Optional Supabase sign-in syncs a copy across devices. For fast editing, the compile server keeps a bounded, short-lived workspace identified by a random tab-local key. It reuses LaTeX auxiliary state for edits and skips TeX entirely for an exact repeat. Workspaces expire after ten minutes and disappear whenever Render restarts or redeploys.
|
|
13
|
+
|
|
14
|
+
## What works
|
|
15
|
+
|
|
16
|
+
- Project dashboard: templates (Article, Blank, Thesis, Slides), import from `.zip` (including Overleaf downloads, and Overleaf's multi-project download, which becomes one project per inner zip), rename, duplicate, download `.zip`, delete.
|
|
17
|
+
- Editor: CodeMirror 6 with LaTeX highlighting in the design system's colours, autocomplete for commands, environments, `\ref` labels, `\cite` keys and file names, search and replace, a formatting toolbar, and autosave to the browser.
|
|
18
|
+
- Math preview: hover over inline or display math to see it typeset (KaTeX, loaded on first use), with simple `\newcommand` and `\DeclareMathOperator` macros from the project.
|
|
19
|
+
- Table editor: build a table as a grid (alignment, booktabs or grid rules, header row, caption and label), or put the cursor in an existing table and edit it the same way. lattedit adds `\usepackage{booktabs}` when the rules need it.
|
|
20
|
+
- Files: folders, upload by button or drag and drop (images, PDFs, `.bib`, `.sty`…), rename, delete, set the main document.
|
|
21
|
+
- Compiling: pdfLaTeX, XeLaTeX or LuaLaTeX; BibTeX and Biber run automatically through latexmk; Ctrl/⌘ Enter or Ctrl/⌘ S; optional auto compile; stop on first error; cancel.
|
|
22
|
+
- Logs: errors, warnings and bad boxes parsed with plain-language hints, gutter markers in the editor, and a click to jump to the line (across files).
|
|
23
|
+
- PDF: pdf.js preview with paging, zoom and fit, rendering only the pages in view; the last PDF is cached per project.
|
|
24
|
+
- SyncTeX: double-click the PDF to open that line of the source; Ctrl Alt J (⌘ ⌥ J) or the locate button shows the cursor's line in the PDF. The compile server returns the `.synctex.gz` and the browser reads it (`web/src/lib/synctex.ts`).
|
|
25
|
+
- Word count: texcount on the server (`POST /wordcount`, same body as `/compile`), with totals and words per section.
|
|
26
|
+
- History: lattedit saves versions in the browser as you work (every ten minutes while editing, after a successful compile, before restores, pulls and AI changes) and when you name one. Compare any version with the project now, restore all of it or one file, or download it. File contents are stored once and shared between versions; named versions are kept, plus the last 60 others.
|
|
27
|
+
- Downloads: source `.zip`, PDF, an arXiv-ready `.zip` (comments removed from `.tex` files, the `.bbl` beside the main file), the compile log and the `.bbl`.
|
|
28
|
+
- GitHub: import a repository or one folder of it, connect a project to a branch, pull, and push commits, all from the browser through the GitHub API. Public repositories import without a token; private ones and pushing need a fine-grained token with Contents read and write. The token stays in the browser. A push is refused while GitHub has commits the project hasn't pulled, and only deletes files the project had at the last sync. The link is kept per browser.
|
|
29
|
+
- Latte (light) and Espresso (dark) themes, resizable panes, and a one-pane layout with a file drawer on phones.
|
|
30
|
+
|
|
31
|
+
- Coding agents: Claude Code, Codex, Cursor or any MCP client can read, edit and compile projects with the person's own model (**Coding agents** in the header). Locally, `npx lattedit-cli mcp` is a stdio MCP server (`cli/mcp.mjs`) that the open tab or desktop app connects to on `127.0.0.1:47824`; or the person makes a private link, `https://lattedit.xyz/mcp/agent/<secret>`, which `web/proxy.js` answers and relays through the compile server (`server/src/agentRelay.js`) to the tab. The tools run in the tab (`web/src/lib/agentTools.ts`, `agentBridge.ts`), so edits go through the editor live, and a History version is saved before an agent's first change.
|
|
32
|
+
|
|
33
|
+
Without sign-in, users move projects between devices with the `.zip` download and import, or through GitHub.
|
|
34
|
+
|
|
35
|
+
## Run locally
|
|
36
|
+
|
|
37
|
+
Requires Node 20+ and a TeX Live install with `latexmk` (or Docker).
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
cd server && npm install && npm run dev
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
cd web && npm install && npm run dev
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Configuration comes from environment variables. Keep them in `.env` files, which git ignores and the repository doesn't include:
|
|
48
|
+
|
|
49
|
+
- `web/.env.local` (and the build environment, such as Vercel): `VITE_COMPILE_URL` (the compile server, no trailing slash, for example `http://localhost:8080`), and optionally `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY` (the browser-safe publishable key), `VITE_AUTH_ENABLED` and `VITE_CLARITY_ID`.
|
|
50
|
+
- `server/.env` (and the Render dashboard): `ALLOWED_ORIGINS` (comma-separated), `PORT`, `COMPILE_TIMEOUT_MS`, `MAX_CONCURRENT`, `MAX_QUEUE`, `RATE_PER_MINUTE`, `MAX_BODY`, `MAX_FILES`; for the AI agent `SARVAM_API_KEY` (secret), `SUPABASE_URL`, `SUPABASE_ANON_KEY` and `AI_DAILY_LIMIT`.
|
|
51
|
+
|
|
52
|
+
The editor opens at http://localhost:5173 and compiles against `VITE_COMPILE_URL`. To run the server with the same TeX Live as production instead:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
docker build -t lattedit-compile server
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
docker run --rm -p 8080:8080 -e ALLOWED_ORIGINS=http://localhost:5173 lattedit-compile
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Tests: `npm test` at the root (the local MCP server, end to end), in `server/` (path safety, validation, limits, SyncTeX output, word count) and in `web/` (log parser, SyncTeX, tables, math detection, arXiv comments, GitHub links).
|
|
63
|
+
|
|
64
|
+
## Deploy
|
|
65
|
+
|
|
66
|
+
**Everything on Render:** `render.yaml` deploys both the compile server and the web app (as a static site) on the free plan. In Render choose **New → Blueprint**, pick this repo, and apply. The steps below are for the split setup (server on Render, web on Vercel).
|
|
67
|
+
|
|
68
|
+
### 1. Compile server on Render
|
|
69
|
+
|
|
70
|
+
1. Push this repository to the Git provider connected to Render.
|
|
71
|
+
2. In Render, choose **New → Blueprint** and pick the repo; it reads `render.yaml`.
|
|
72
|
+
3. When asked for `ALLOWED_ORIGINS`, enter your Vercel URL (you can come back and add a custom domain later, comma-separated).
|
|
73
|
+
4. The first build takes a while: the image carries TeX Live (a few GB).
|
|
74
|
+
5. Check `https://<your-service>.onrender.com/health`. It should return `{"ok":true,...}`.
|
|
75
|
+
|
|
76
|
+
The Blueprint uses the **Free** plan. Free instances sleep when idle, so the first compile after a break can take about a minute while the server wakes; opening the dashboard or editor starts waking it immediately.
|
|
77
|
+
|
|
78
|
+
### 2. Frontend on Vercel
|
|
79
|
+
|
|
80
|
+
1. In Vercel, import the same repo and set **Root Directory** to `web`. Vite is detected; `web/vercel.json` sets the build and the single-page-app rewrite.
|
|
81
|
+
2. Add the environment variable `VITE_COMPILE_URL` = `https://<your-service>.onrender.com` (no trailing slash).
|
|
82
|
+
3. Deploy. If you change the URL later, redeploy, because Vite bakes it in at build time.
|
|
83
|
+
|
|
84
|
+
### 3. Optional account sync
|
|
85
|
+
|
|
86
|
+
Run `supabase/schema.sql` in the Supabase SQL editor (it is safe to run again to upgrade; run it again after updating to allow live co-editing). It creates `lattedit_projects`, `lattedit_files`, `lattedit_members` and `lattedit_comments`, enables row level security, and adds the tables to Supabase Realtime.
|
|
87
|
+
|
|
88
|
+
Signed-in owners can share a project from **Share**: invite people by the email they sign in with, as **Can view**, **Can comment** or **Can edit**, up to 7 people per project including the owner. General access is **Private** (only invited people) or **Public** (anyone with the link can view, signed in or not; only invited editors can edit). The database enforces all of this: roles, the 7-person cap, and that only the owner shares or changes visibility. Everyone on a project but viewers can comment: select text and press **Add comment** (Ctrl Alt M, ⌘ ⌥ M on a Mac), reply, and resolve threads. Comments stay attached to the quoted text as lines move, and the database only lets authors edit their own comments (authors and the owner can delete). People who open a public link don't see comments. The AI agent runs on the compile server with Sarvam (`sarvam-105b`). The model answers with SEARCH/REPLACE edits rather than JSON, so LaTeX reaches the file exactly as written; the server then adds any missing `\usepackage` lines for well-known commands, checks environments, braces and Unicode, compiles the edited project, and sends what's still wrong back to the model for up to two repair rounds (`AI_MAX_REPAIRS`) before answering (`server/src/ai.js`). It is for signed-in people only, with 15 prompts per person per day (`AI_DAILY_LIMIT`), counted in `lattedit_ai_usage` and reset at midnight UTC; only answered prompts count. The compile server needs `SARVAM_API_KEY` (secret, Render dashboard) and `SUPABASE_URL` / `SUPABASE_ANON_KEY` (the same public values as the web app) to check sign-ins. Collaborators see each other's saves and who else has the project open, live. People who can edit a project also share what they type as they type it: each open project has a Yjs document carried over a private Realtime broadcast channel (`lattedit:collab:<project id>`, owners and editors only; see `supabase/schema.sql`), so edits to the same file merge and everyone sees the others' cursors (`web/src/lib/collab.ts`). Files are still saved as before; if the channel can't be joined (for example before the schema is upgraded), editing falls back to file-by-file merging, where the newest save of a file wins. Set `VITE_SUPABASE_URL` and `VITE_SUPABASE_ANON_KEY` in Vercel using the project URL and a browser-safe publishable key. Do not use the secret or service-role key.
|
|
89
|
+
|
|
90
|
+
Set the Supabase Auth Site URL to the production origin and allow the origins used by the app as redirect URLs. After configuring the Google provider, set `VITE_AUTH_ENABLED=true` in Vercel and redeploy. Until then, the sign-in control stays hidden, no Supabase client or session handling runs, and projects remain entirely in the browser.
|
|
91
|
+
|
|
92
|
+
### 4. Optional analytics
|
|
93
|
+
|
|
94
|
+
Set `VITE_CLARITY_ID` to a Microsoft Clarity project ID in Vercel and redeploy. Analytics then loads automatically on every page. Use Strict masking in the Clarity project so document text is never sent in session recordings.
|
|
95
|
+
|
|
96
|
+
## Server settings
|
|
97
|
+
|
|
98
|
+
| Variable | Default | What it does |
|
|
99
|
+
| --- | --- | --- |
|
|
100
|
+
| `ALLOWED_ORIGINS` | `http://localhost:5173` | Comma-separated origins allowed to call the API |
|
|
101
|
+
| `COMPILE_TIMEOUT_MS` | `120000` | A compile is killed after this |
|
|
102
|
+
| `MAX_CONCURRENT` | `2` | Compiles running at once; more wait in a queue |
|
|
103
|
+
| `MAX_QUEUE` | `8` | Waiting compiles before the server answers 503 |
|
|
104
|
+
| `WORKSPACE_TTL_MS` | `600000` | Idle time before incremental build state is removed |
|
|
105
|
+
| `MAX_WORKSPACES` | `12` | Maximum short-lived workspaces retained per instance |
|
|
106
|
+
| `RATE_PER_MINUTE` | `20` | Compiles per IP per minute |
|
|
107
|
+
| `MAX_BODY` | `25mb` | Largest project upload |
|
|
108
|
+
| `MAX_FILES` | `300` | Most files in one project |
|
|
109
|
+
|
|
110
|
+
## Security notes
|
|
111
|
+
|
|
112
|
+
- Shell escape is off (`shell_escape=f`), and TeX may only read and write inside the project folder (`openin_any=p`, `openout_any=p`).
|
|
113
|
+
- File paths are checked: no absolute paths, no `..`, no dot-files (so no `.latexmkrc`).
|
|
114
|
+
- Each browser tab compiles as the unprivileged `node` user in an isolated, randomly keyed temp folder. The server retains at most 12 folders for 10 minutes and kills timed-out process groups.
|
|
115
|
+
- CORS limits which sites can call the API, but anyone can still script requests directly. The per-IP rate limit and the queue keep that bounded. Add an auth token or a proxy if abuse becomes a problem.
|
|
116
|
+
|
|
117
|
+
## Storage notes
|
|
118
|
+
|
|
119
|
+
Browsers can evict site data under storage pressure. The app asks for persistent storage and shows usage on the dashboard, but the `.zip` download is the real backup. Tell users that clearing site data deletes their projects.
|
|
120
|
+
|
|
121
|
+
## API
|
|
122
|
+
|
|
123
|
+
The stable compile API is served from `https://lattedit.xyz/api/v1` and described by the machine-readable [OpenAPI 3.1 contract](https://lattedit.xyz/openapi.json). It requires no API key. `POST /api/v1/compile` accepts:
|
|
124
|
+
|
|
125
|
+
```json
|
|
126
|
+
{
|
|
127
|
+
"compiler": "pdflatex",
|
|
128
|
+
"main": "main.tex",
|
|
129
|
+
"workspaceKey": "random-browser-generated-capability",
|
|
130
|
+
"stopOnFirstError": false,
|
|
131
|
+
"files": [
|
|
132
|
+
{ "path": "main.tex", "content": "\\documentclass{article}...", "encoding": "utf8" },
|
|
133
|
+
{ "path": "figures/plot.png", "content": "<base64>", "encoding": "base64" }
|
|
134
|
+
]
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The response is `{ status, pdf, log, durationMs, syncMs, engineMs, cache }`. `cache` is `cold`, `incremental`, `exact`, or `none`; an exact response does not start TeX. `status` is `success`, `error` (compiled with errors; a PDF may still exist), `failure` (no PDF), or `timeout`. `pdf` is base64 or `null`. Bad requests use RFC 9457 problem details with stable `code`, `detail`, and `resolution` fields.
|
|
139
|
+
|
|
140
|
+
`GET /api/v1/health` returns `{ ok, tex, busy, queued }`.
|
|
141
|
+
|
|
142
|
+
The zero-dependency CLI is included for local use:
|
|
143
|
+
|
|
144
|
+
```bash
|
|
145
|
+
node cli/lattedit.mjs health
|
|
146
|
+
node cli/lattedit.mjs compile project.json --output paper.pdf
|
|
147
|
+
```
|
package/cli/lattedit.mjs
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { basename, resolve } from 'node:path';
|
|
5
|
+
|
|
6
|
+
const DEFAULT_API = 'https://lattedit.xyz/api/v1';
|
|
7
|
+
|
|
8
|
+
function usage() {
|
|
9
|
+
console.log(`lattedit - compile LaTeX through the lattedit API
|
|
10
|
+
|
|
11
|
+
Usage:
|
|
12
|
+
lattedit health [--api URL]
|
|
13
|
+
lattedit compile PROJECT.json [--output FILE.pdf] [--api URL]
|
|
14
|
+
lattedit mcp
|
|
15
|
+
|
|
16
|
+
PROJECT.json follows https://lattedit.xyz/openapi.json. It must contain main
|
|
17
|
+
and files; compiler, workspaceKey, and stopOnFirstError are optional.
|
|
18
|
+
|
|
19
|
+
mcp runs an MCP server (stdio) that lets a coding agent read, edit and compile
|
|
20
|
+
your lattedit projects in your open lattedit tab or desktop app. Add it to your
|
|
21
|
+
agent, then turn on Coding agents in lattedit's account menu:
|
|
22
|
+
claude mcp add lattedit -- npx -y lattedit-cli mcp
|
|
23
|
+
codex mcp add lattedit -- npx -y lattedit-cli mcp
|
|
24
|
+
|
|
25
|
+
Examples:
|
|
26
|
+
lattedit health
|
|
27
|
+
lattedit compile project.json --output paper.pdf`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function option(args, name) {
|
|
31
|
+
const index = args.indexOf(name);
|
|
32
|
+
if (index === -1) return null;
|
|
33
|
+
if (!args[index + 1] || args[index + 1].startsWith('--')) throw new Error(`${name} needs a value.`);
|
|
34
|
+
return args[index + 1];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function request(url, init) {
|
|
38
|
+
const response = await fetch(url, init);
|
|
39
|
+
const text = await response.text();
|
|
40
|
+
let body;
|
|
41
|
+
try { body = JSON.parse(text); } catch { throw new Error(`The server returned non-JSON (${response.status}).`); }
|
|
42
|
+
if (!response.ok) {
|
|
43
|
+
const detail = body.detail || body.message || response.statusText;
|
|
44
|
+
const resolution = body.resolution ? ` ${body.resolution}` : '';
|
|
45
|
+
throw new Error(`${body.code || `http_${response.status}`}: ${detail}${resolution}`);
|
|
46
|
+
}
|
|
47
|
+
return body;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function main() {
|
|
51
|
+
const args = process.argv.slice(2);
|
|
52
|
+
if (args.length === 0 || args.includes('--help') || args.includes('-h')) return usage();
|
|
53
|
+
if (args.includes('--version') || args.includes('-v')) return console.log('0.2.0');
|
|
54
|
+
|
|
55
|
+
const command = args[0];
|
|
56
|
+
if (command === 'mcp') {
|
|
57
|
+
const { serveMcp } = await import('./mcp.mjs');
|
|
58
|
+
return serveMcp();
|
|
59
|
+
}
|
|
60
|
+
const api = (option(args, '--api') || process.env.LATTEDIT_API || DEFAULT_API).replace(/\/$/, '');
|
|
61
|
+
|
|
62
|
+
if (command === 'health') {
|
|
63
|
+
const health = await request(`${api}/health`);
|
|
64
|
+
console.log(JSON.stringify(health, null, 2));
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (command === 'compile') {
|
|
69
|
+
const inputPath = args[1];
|
|
70
|
+
if (!inputPath || inputPath.startsWith('--')) throw new Error('compile needs a PROJECT.json file.');
|
|
71
|
+
const project = JSON.parse(await readFile(resolve(inputPath), 'utf8'));
|
|
72
|
+
const result = await request(`${api}/compile`, {
|
|
73
|
+
method: 'POST',
|
|
74
|
+
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
|
|
75
|
+
body: JSON.stringify(project),
|
|
76
|
+
});
|
|
77
|
+
const output = resolve(option(args, '--output') || `${basename(inputPath, '.json')}.pdf`);
|
|
78
|
+
if (result.pdf) {
|
|
79
|
+
await writeFile(output, Buffer.from(result.pdf, 'base64'));
|
|
80
|
+
console.log(`PDF: ${output}`);
|
|
81
|
+
}
|
|
82
|
+
console.log(`Status: ${result.status}`);
|
|
83
|
+
console.log(`Compile: ${result.durationMs} ms (${result.cache} cache, ${result.engineMs} ms TeX)`);
|
|
84
|
+
if (result.status !== 'success') {
|
|
85
|
+
if (result.log) console.error(result.log);
|
|
86
|
+
process.exitCode = 2;
|
|
87
|
+
}
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
throw new Error(`Unknown command: ${command}`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
main().catch((error) => {
|
|
95
|
+
console.error(`lattedit: ${error.message}`);
|
|
96
|
+
process.exitCode = 1;
|
|
97
|
+
});
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tools lattedit offers coding agents over MCP. The lattedit tab carries them
|
|
3
|
+
* out (web/src/lib/agentTools.ts); web/mcp-tools.js is a copy for the hosted relay,
|
|
4
|
+
* and web/test/agentTools.test.ts checks that the copies match.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const projectId = {
|
|
8
|
+
type: 'string',
|
|
9
|
+
description: 'The project to work on (see list_projects). Defaults to the project open in the lattedit editor.',
|
|
10
|
+
};
|
|
11
|
+
const path = { type: 'string', description: 'Path inside the project, e.g. "main.tex" or "chapters/intro.tex".' };
|
|
12
|
+
|
|
13
|
+
export const INSTRUCTIONS = `lattedit is a LaTeX editor. These tools read and change the person's lattedit projects in their open lattedit tab or desktop app, and compile them.
|
|
14
|
+
Start with get_editor_context (what the person has open and selected) or list_projects. Read a file before editing it, and prefer edit_file (exact text replacement) over rewriting whole files.
|
|
15
|
+
The person may be typing in the same files, and your edits appear live in their editor; re-read a file if an edit can't find its text. After changing LaTeX, run compile and fix the errors it reports.
|
|
16
|
+
lattedit saves a version to History before your first edit in a while, so the person can undo your changes.`;
|
|
17
|
+
|
|
18
|
+
export const TOOLS = [
|
|
19
|
+
{
|
|
20
|
+
name: 'get_editor_context',
|
|
21
|
+
title: 'What the person has open',
|
|
22
|
+
description: 'The project and file open in the lattedit editor, the cursor line and the selected text. Call this first when the person refers to "this", "here" or "the selection".',
|
|
23
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
24
|
+
annotations: { readOnlyHint: true },
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
name: 'list_projects',
|
|
28
|
+
title: 'List projects',
|
|
29
|
+
description: 'All lattedit projects with their ids, main documents and which one is open in the editor.',
|
|
30
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
31
|
+
annotations: { readOnlyHint: true },
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
name: 'open_project',
|
|
35
|
+
title: 'Open a project',
|
|
36
|
+
description: 'Open a project in the lattedit editor so the person can watch the changes.',
|
|
37
|
+
inputSchema: { type: 'object', required: ['projectId'], properties: { projectId }, additionalProperties: false },
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
name: 'create_project',
|
|
41
|
+
title: 'Create a project',
|
|
42
|
+
description: 'Create a new lattedit project, optionally with files, and open it. Without files it starts from a blank article.',
|
|
43
|
+
inputSchema: {
|
|
44
|
+
type: 'object',
|
|
45
|
+
required: ['name'],
|
|
46
|
+
properties: {
|
|
47
|
+
name: { type: 'string', description: 'Project name.' },
|
|
48
|
+
files: {
|
|
49
|
+
type: 'array',
|
|
50
|
+
description: 'Text files to create.',
|
|
51
|
+
items: {
|
|
52
|
+
type: 'object', required: ['path', 'content'], additionalProperties: false,
|
|
53
|
+
properties: { path, content: { type: 'string' } },
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
mainFile: { type: 'string', description: 'The document to compile. Defaults to main.tex or the first .tex file.' },
|
|
57
|
+
compiler: { type: 'string', enum: ['pdflatex', 'xelatex', 'lualatex'], default: 'pdflatex' },
|
|
58
|
+
open: { type: 'boolean', default: true, description: 'Open it in the editor.' },
|
|
59
|
+
},
|
|
60
|
+
additionalProperties: false,
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
name: 'list_files',
|
|
65
|
+
title: 'List files',
|
|
66
|
+
description: 'The files in a project, with sizes, and which one is the main document.',
|
|
67
|
+
inputSchema: { type: 'object', properties: { projectId }, additionalProperties: false },
|
|
68
|
+
annotations: { readOnlyHint: true },
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
name: 'read_file',
|
|
72
|
+
title: 'Read a file',
|
|
73
|
+
description: 'Read a text file as it is now, including unsaved typing in the editor. Long files: pass offset (1-based line) and limit.',
|
|
74
|
+
inputSchema: {
|
|
75
|
+
type: 'object',
|
|
76
|
+
required: ['path'],
|
|
77
|
+
properties: {
|
|
78
|
+
projectId, path,
|
|
79
|
+
offset: { type: 'integer', minimum: 1, description: 'First line to read.' },
|
|
80
|
+
limit: { type: 'integer', minimum: 1, description: 'Number of lines to read.' },
|
|
81
|
+
},
|
|
82
|
+
additionalProperties: false,
|
|
83
|
+
},
|
|
84
|
+
annotations: { readOnlyHint: true },
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
name: 'edit_file',
|
|
88
|
+
title: 'Edit a file',
|
|
89
|
+
description: 'Replace exact text in a file. old_string must match the file exactly (whitespace included) and occur once, unless replace_all is set.',
|
|
90
|
+
inputSchema: {
|
|
91
|
+
type: 'object',
|
|
92
|
+
required: ['path', 'old_string', 'new_string'],
|
|
93
|
+
properties: {
|
|
94
|
+
projectId, path,
|
|
95
|
+
old_string: { type: 'string', description: 'The text to replace.' },
|
|
96
|
+
new_string: { type: 'string', description: 'The replacement.' },
|
|
97
|
+
replace_all: { type: 'boolean', default: false },
|
|
98
|
+
},
|
|
99
|
+
additionalProperties: false,
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
name: 'write_file',
|
|
104
|
+
title: 'Write a file',
|
|
105
|
+
description: 'Create a text file, or replace all of one. Prefer edit_file for changes to an existing file.',
|
|
106
|
+
inputSchema: {
|
|
107
|
+
type: 'object',
|
|
108
|
+
required: ['path', 'content'],
|
|
109
|
+
properties: { projectId, path, content: { type: 'string' } },
|
|
110
|
+
additionalProperties: false,
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
name: 'delete_file',
|
|
115
|
+
title: 'Delete a file',
|
|
116
|
+
description: 'Delete a file from a project. The main document cannot be deleted.',
|
|
117
|
+
inputSchema: { type: 'object', required: ['path'], properties: { projectId, path }, additionalProperties: false },
|
|
118
|
+
annotations: { destructiveHint: true },
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
name: 'rename_file',
|
|
122
|
+
title: 'Rename or move a file',
|
|
123
|
+
description: 'Rename or move a file inside a project.',
|
|
124
|
+
inputSchema: {
|
|
125
|
+
type: 'object',
|
|
126
|
+
required: ['from', 'to'],
|
|
127
|
+
properties: { projectId, from: path, to: path },
|
|
128
|
+
additionalProperties: false,
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
name: 'update_project',
|
|
133
|
+
title: 'Change project settings',
|
|
134
|
+
description: 'Rename a project, set its main document, or switch its compiler.',
|
|
135
|
+
inputSchema: {
|
|
136
|
+
type: 'object',
|
|
137
|
+
properties: {
|
|
138
|
+
projectId,
|
|
139
|
+
name: { type: 'string' },
|
|
140
|
+
mainFile: path,
|
|
141
|
+
compiler: { type: 'string', enum: ['pdflatex', 'xelatex', 'lualatex'] },
|
|
142
|
+
},
|
|
143
|
+
additionalProperties: false,
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
{
|
|
147
|
+
name: 'compile',
|
|
148
|
+
title: 'Compile',
|
|
149
|
+
description: 'Compile the project as the editor does (the PDF pane updates) and report the status with each error and warning by file and line.',
|
|
150
|
+
inputSchema: {
|
|
151
|
+
type: 'object',
|
|
152
|
+
properties: {
|
|
153
|
+
projectId,
|
|
154
|
+
savePdfTo: { type: 'string', description: 'Local server only: also save the PDF to this path on this computer.' },
|
|
155
|
+
},
|
|
156
|
+
additionalProperties: false,
|
|
157
|
+
},
|
|
158
|
+
annotations: { readOnlyHint: true },
|
|
159
|
+
},
|
|
160
|
+
];
|
package/cli/mcp.mjs
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `lattedit mcp`: an MCP server (stdio) that lets a coding agent such as Claude Code,
|
|
3
|
+
* Codex or Cursor read, edit and compile the person's lattedit projects.
|
|
4
|
+
*
|
|
5
|
+
* Projects live in the person's lattedit tab (or the desktop app), so this server is
|
|
6
|
+
* a bridge. It listens on 127.0.0.1:47824; the tab connects to it once the person
|
|
7
|
+
* turns on "Coding agents" in lattedit, and each tool call is carried out there
|
|
8
|
+
* (web/src/lib/agentTools.ts), live in the editor.
|
|
9
|
+
*
|
|
10
|
+
* Several agents can run at once: the first server owns the port (the hub) and the
|
|
11
|
+
* others connect to it and relay their calls through it. When the hub exits, the
|
|
12
|
+
* next one takes the port over.
|
|
13
|
+
*
|
|
14
|
+
* agent ── stdio ── lattedit mcp (hub) ── ws://127.0.0.1:47824/editor ── lattedit tab
|
|
15
|
+
* other agent ── stdio ── lattedit mcp ──┘ /agent
|
|
16
|
+
*
|
|
17
|
+
* Only the lattedit site (and the desktop app, and the dev server) may connect as an
|
|
18
|
+
* editor: browsers always send Origin, and the hub checks it. Relaying agents are
|
|
19
|
+
* local processes, which never send one.
|
|
20
|
+
*/
|
|
21
|
+
import { createServer } from 'node:http';
|
|
22
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
23
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
24
|
+
import { dirname, resolve } from 'node:path';
|
|
25
|
+
import { INSTRUCTIONS, TOOLS } from './mcp-tools.mjs';
|
|
26
|
+
|
|
27
|
+
const VERSION = '0.2.0';
|
|
28
|
+
const PORT = Number(process.env.LATTEDIT_BRIDGE_PORT) || 47824;
|
|
29
|
+
const ORIGINS = new Set([
|
|
30
|
+
'https://lattedit.xyz', 'https://www.lattedit.xyz',
|
|
31
|
+
'http://localhost:5173', 'http://127.0.0.1:5173',
|
|
32
|
+
'tauri://localhost', 'http://tauri.localhost', 'https://tauri.localhost',
|
|
33
|
+
...(process.env.LATTEDIT_ORIGINS ?? '').split(',').map((s) => s.trim()).filter(Boolean),
|
|
34
|
+
]);
|
|
35
|
+
/** How long a call waits for a lattedit tab to connect before giving up. */
|
|
36
|
+
const CONNECT_WAIT_MS = 10_000;
|
|
37
|
+
const CALL_TIMEOUT_MS = 30_000;
|
|
38
|
+
const COMPILE_TIMEOUT_MS = 200_000;
|
|
39
|
+
const MAX_MESSAGE = 96 * 1024 * 1024;
|
|
40
|
+
|
|
41
|
+
const log = (...a) => console.error('[lattedit mcp]', ...a);
|
|
42
|
+
|
|
43
|
+
/* ---------- a minimal WebSocket server (RFC 6455), text frames only ---------- */
|
|
44
|
+
|
|
45
|
+
function frame(text, opcode = 1) {
|
|
46
|
+
const payload = Buffer.from(text);
|
|
47
|
+
const n = payload.length;
|
|
48
|
+
const head = n < 126 ? Buffer.from([0x80 | opcode, n])
|
|
49
|
+
: n < 65536 ? Buffer.from([0x80 | opcode, 126, n >> 8, n & 255])
|
|
50
|
+
: (() => { const b = Buffer.alloc(10); b[0] = 0x80 | opcode; b[1] = 127; b.writeBigUInt64BE(BigInt(n), 2); return b; })();
|
|
51
|
+
return Buffer.concat([head, payload]);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
class Peer {
|
|
55
|
+
constructor(socket, onMessage, onClose) {
|
|
56
|
+
this.socket = socket;
|
|
57
|
+
this.buf = Buffer.alloc(0);
|
|
58
|
+
this.parts = [];
|
|
59
|
+
this.open = true;
|
|
60
|
+
socket.on('data', (d) => {
|
|
61
|
+
this.buf = Buffer.concat([this.buf, d]);
|
|
62
|
+
try { this.drain(onMessage); } catch (e) { log(e.message); this.close(); }
|
|
63
|
+
});
|
|
64
|
+
this.onClose = onClose;
|
|
65
|
+
this.ended = false;
|
|
66
|
+
socket.on('close', () => this.end());
|
|
67
|
+
socket.on('error', () => this.end());
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The connection is gone, whichever side closed it: clean up once. */
|
|
71
|
+
end() {
|
|
72
|
+
this.open = false;
|
|
73
|
+
if (this.ended) return;
|
|
74
|
+
this.ended = true;
|
|
75
|
+
this.onClose();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
drain(onMessage) {
|
|
79
|
+
for (;;) {
|
|
80
|
+
const b = this.buf;
|
|
81
|
+
if (b.length < 2) return;
|
|
82
|
+
const fin = b[0] & 0x80, opcode = b[0] & 0x0f, masked = b[1] & 0x80;
|
|
83
|
+
let len = b[1] & 0x7f, off = 2;
|
|
84
|
+
if (len === 126) { if (b.length < 4) return; len = b.readUInt16BE(2); off = 4; }
|
|
85
|
+
else if (len === 127) { if (b.length < 10) return; len = Number(b.readBigUInt64BE(2)); off = 10; }
|
|
86
|
+
if (len > MAX_MESSAGE) throw new Error('Message too large.');
|
|
87
|
+
const maskAt = off;
|
|
88
|
+
if (masked) off += 4;
|
|
89
|
+
if (b.length < off + len) return;
|
|
90
|
+
const payload = Buffer.from(b.subarray(off, off + len));
|
|
91
|
+
if (masked) for (let i = 0; i < len; i++) payload[i] ^= b[maskAt + (i & 3)];
|
|
92
|
+
this.buf = b.subarray(off + len);
|
|
93
|
+
if (opcode === 8) { this.close(); return; }
|
|
94
|
+
if (opcode === 9) { this.socket.write(frame(payload, 10)); continue; }
|
|
95
|
+
if (opcode === 10) continue;
|
|
96
|
+
this.parts.push(payload);
|
|
97
|
+
if (this.parts.reduce((s, p) => s + p.length, 0) > MAX_MESSAGE) throw new Error('Message too large.');
|
|
98
|
+
if (!fin) continue;
|
|
99
|
+
const text = Buffer.concat(this.parts).toString('utf8');
|
|
100
|
+
this.parts = [];
|
|
101
|
+
let msg;
|
|
102
|
+
try { msg = JSON.parse(text); } catch { continue; }
|
|
103
|
+
onMessage(msg);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
send(msg) { if (this.open) this.socket.write(frame(JSON.stringify(msg))); }
|
|
108
|
+
close() {
|
|
109
|
+
if (this.open) {
|
|
110
|
+
this.open = false;
|
|
111
|
+
try { this.socket.end(frame('', 8)); } catch { /* gone */ }
|
|
112
|
+
this.socket.destroy();
|
|
113
|
+
}
|
|
114
|
+
this.end();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/* ---------- the hub: owns the port, talks to lattedit tabs ---------- */
|
|
119
|
+
|
|
120
|
+
/** Connected lattedit tabs; calls go to the one focused most recently. */
|
|
121
|
+
const editors = new Set();
|
|
122
|
+
/** Calls waiting on a tab, by id: { resolve, timer, editor }. */
|
|
123
|
+
const pending = new Map();
|
|
124
|
+
/** Other agents' servers relaying through this one. */
|
|
125
|
+
const agents = new Set();
|
|
126
|
+
const editorWaiters = new Set();
|
|
127
|
+
/** Agent names, for the tab to show who is connected. */
|
|
128
|
+
let myAgent = 'agent';
|
|
129
|
+
|
|
130
|
+
function currentEditor() {
|
|
131
|
+
let best = null;
|
|
132
|
+
for (const e of editors) if (!best || e.focusedAt > best.focusedAt) best = e;
|
|
133
|
+
return best;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function agentNames() {
|
|
137
|
+
return [...new Set([myAgent, ...[...agents].map((a) => a.name).filter(Boolean)])];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function announceAgents() {
|
|
141
|
+
for (const e of editors) e.peer.send({ type: 'agents', names: agentNames() });
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function noEditorResult() {
|
|
145
|
+
return {
|
|
146
|
+
text: 'lattedit is not connected. Ask the person to open lattedit (https://lattedit.xyz or the desktop app) '
|
|
147
|
+
+ 'and turn on Coding agents (account menu → Coding agents). Then try again.',
|
|
148
|
+
isError: true,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function waitForEditor() {
|
|
153
|
+
if (currentEditor()) return currentEditor();
|
|
154
|
+
return new Promise((done) => {
|
|
155
|
+
const w = () => { clearTimeout(timer); editorWaiters.delete(w); done(currentEditor()); };
|
|
156
|
+
const timer = setTimeout(w, CONNECT_WAIT_MS);
|
|
157
|
+
editorWaiters.add(w);
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Run a call on the focused tab (hub only). */
|
|
162
|
+
async function callEditor(name, args, agent) {
|
|
163
|
+
const editor = await waitForEditor();
|
|
164
|
+
if (!editor) return noEditorResult();
|
|
165
|
+
const id = randomUUID();
|
|
166
|
+
return new Promise((done) => {
|
|
167
|
+
const timer = setTimeout(() => {
|
|
168
|
+
pending.delete(id);
|
|
169
|
+
done({ text: `lattedit didn't answer ${name} in time. The tab may be in the background or busy; try again.`, isError: true });
|
|
170
|
+
}, name === 'compile' ? COMPILE_TIMEOUT_MS : CALL_TIMEOUT_MS);
|
|
171
|
+
pending.set(id, { done, timer, editor });
|
|
172
|
+
editor.peer.send({ type: 'call', id, name, args, agent });
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function onEditorClose(editor) {
|
|
177
|
+
editors.delete(editor);
|
|
178
|
+
for (const [id, p] of pending) {
|
|
179
|
+
if (p.editor !== editor) continue;
|
|
180
|
+
clearTimeout(p.timer);
|
|
181
|
+
pending.delete(id);
|
|
182
|
+
p.done({ text: 'The lattedit tab closed or disconnected during the call.', isError: true });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function handleUpgrade(req, socket) {
|
|
187
|
+
const reject = (status) => { socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n\r\n`); };
|
|
188
|
+
// DNS rebinding: only answer to loopback names.
|
|
189
|
+
const host = (req.headers.host ?? '').replace(/:\d+$/, '');
|
|
190
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(host)) return reject('403 Forbidden');
|
|
191
|
+
const key = req.headers['sec-websocket-key'];
|
|
192
|
+
if (!key || req.headers.upgrade?.toLowerCase() !== 'websocket') return reject('400 Bad Request');
|
|
193
|
+
const origin = req.headers.origin;
|
|
194
|
+
const path = new URL(req.url, 'http://x').pathname;
|
|
195
|
+
if (path === '/editor' ? !origin || !ORIGINS.has(origin) : path === '/agent' ? !!origin : true) {
|
|
196
|
+
log(`refused a connection to ${path} from ${origin ?? 'a local process'}`);
|
|
197
|
+
return reject('403 Forbidden');
|
|
198
|
+
}
|
|
199
|
+
const accept = createHash('sha1').update(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64');
|
|
200
|
+
socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
|
|
201
|
+
socket.setNoDelay(true);
|
|
202
|
+
|
|
203
|
+
if (path === '/editor') {
|
|
204
|
+
const editor = { focusedAt: Date.now(), origin };
|
|
205
|
+
editor.peer = new Peer(socket, (msg) => {
|
|
206
|
+
if (msg.type === 'hello' || msg.type === 'focus') {
|
|
207
|
+
if (msg.type === 'focus' || msg.focused) editor.focusedAt = Date.now();
|
|
208
|
+
if (msg.type === 'hello') { editor.peer.send({ type: 'agents', names: agentNames() }); editorWaiters.forEach((w) => w()); }
|
|
209
|
+
} else if (msg.type === 'result') {
|
|
210
|
+
const p = pending.get(msg.id);
|
|
211
|
+
if (!p) return;
|
|
212
|
+
clearTimeout(p.timer);
|
|
213
|
+
pending.delete(msg.id);
|
|
214
|
+
p.done(msg.result ?? { text: 'Empty answer from lattedit.', isError: true });
|
|
215
|
+
}
|
|
216
|
+
}, () => onEditorClose(editor));
|
|
217
|
+
editors.add(editor);
|
|
218
|
+
log(`lattedit connected (${origin})`);
|
|
219
|
+
} else {
|
|
220
|
+
const agent = { name: '' };
|
|
221
|
+
agent.peer = new Peer(socket, async (msg) => {
|
|
222
|
+
if (msg.type === 'hello') { agent.name = msg.agent ?? ''; announceAgents(); return; }
|
|
223
|
+
if (msg.type !== 'call') return;
|
|
224
|
+
const result = await callEditor(msg.name, msg.args ?? {}, msg.agent);
|
|
225
|
+
agent.peer.send({ type: 'result', id: msg.id, result });
|
|
226
|
+
}, () => { agents.delete(agent); announceAgents(); });
|
|
227
|
+
agents.add(agent);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function listen() {
|
|
232
|
+
return new Promise((done) => {
|
|
233
|
+
const server = createServer((req, res) => {
|
|
234
|
+
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
235
|
+
res.end(JSON.stringify({ name: 'lattedit-mcp', version: VERSION, editors: editors.size }));
|
|
236
|
+
});
|
|
237
|
+
server.on('upgrade', handleUpgrade);
|
|
238
|
+
server.once('error', (e) => done(e.code === 'EADDRINUSE' ? null : (log(e.message), null)));
|
|
239
|
+
server.listen(PORT, '127.0.0.1', () => done(server));
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/* ---------- relaying through another server's hub ---------- */
|
|
244
|
+
|
|
245
|
+
let hub = null;
|
|
246
|
+
let relay = null;
|
|
247
|
+
const relayPending = new Map();
|
|
248
|
+
|
|
249
|
+
function connectRelay() {
|
|
250
|
+
return new Promise((done) => {
|
|
251
|
+
let ws;
|
|
252
|
+
try { ws = new WebSocket(`ws://127.0.0.1:${PORT}/agent`); } catch { return done(null); }
|
|
253
|
+
ws.onopen = () => { ws.send(JSON.stringify({ type: 'hello', agent: myAgent })); done(ws); };
|
|
254
|
+
ws.onerror = () => done(null);
|
|
255
|
+
ws.onmessage = (e) => {
|
|
256
|
+
let msg;
|
|
257
|
+
try { msg = JSON.parse(e.data); } catch { return; }
|
|
258
|
+
const p = relayPending.get(msg.id);
|
|
259
|
+
if (msg.type === 'result' && p) { relayPending.delete(msg.id); p(msg.result); }
|
|
260
|
+
};
|
|
261
|
+
ws.onclose = () => {
|
|
262
|
+
if (relay === ws) relay = null;
|
|
263
|
+
for (const [id, p] of relayPending) { relayPending.delete(id); p({ text: 'The connection to lattedit dropped during the call; try again.', isError: true }); }
|
|
264
|
+
};
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Own the port, or relay through whoever does. Re-run before each call so a lost hub is replaced. */
|
|
269
|
+
async function ensureBridge() {
|
|
270
|
+
if (hub || relay) return;
|
|
271
|
+
hub = await listen();
|
|
272
|
+
if (hub) { log(`waiting for lattedit on 127.0.0.1:${PORT}`); return; }
|
|
273
|
+
relay = await connectRelay();
|
|
274
|
+
if (!relay) log(`port ${PORT} is in use by something that isn't lattedit.`);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function call(name, args) {
|
|
278
|
+
await ensureBridge();
|
|
279
|
+
if (hub) return callEditor(name, args, myAgent);
|
|
280
|
+
if (!relay) return { text: `lattedit's bridge port ${PORT} is busy. Set LATTEDIT_BRIDGE_PORT to use another.`, isError: true };
|
|
281
|
+
const id = randomUUID();
|
|
282
|
+
const ws = relay;
|
|
283
|
+
return new Promise((done) => {
|
|
284
|
+
relayPending.set(id, done);
|
|
285
|
+
ws.send(JSON.stringify({ type: 'call', id, name, args, agent: myAgent }));
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/* ---------- MCP over stdio ---------- */
|
|
290
|
+
|
|
291
|
+
function reply(id, result) { process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\n'); }
|
|
292
|
+
function fail(id, code, message) { process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: id ?? null, error: { code, message } }) + '\n'); }
|
|
293
|
+
|
|
294
|
+
async function runTool(name, args) {
|
|
295
|
+
if (!TOOLS.some((t) => t.name === name)) return { text: `Unknown tool: ${name}`, isError: true };
|
|
296
|
+
if (name !== 'compile' || !args.savePdfTo) return call(name, args);
|
|
297
|
+
const { savePdfTo, ...rest } = args;
|
|
298
|
+
const result = await call(name, { ...rest, wantPdf: true });
|
|
299
|
+
if (result.pdf) {
|
|
300
|
+
const out = resolve(savePdfTo);
|
|
301
|
+
await mkdir(dirname(out), { recursive: true });
|
|
302
|
+
await writeFile(out, Buffer.from(result.pdf, 'base64'));
|
|
303
|
+
result.text += `\nSaved the PDF to ${out}.`;
|
|
304
|
+
}
|
|
305
|
+
delete result.pdf;
|
|
306
|
+
return result;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
async function handle(msg) {
|
|
310
|
+
const { id, method, params } = msg;
|
|
311
|
+
if (method === 'initialize') {
|
|
312
|
+
const client = params?.clientInfo;
|
|
313
|
+
myAgent = client?.title || client?.name || 'agent';
|
|
314
|
+
if (relay?.readyState === 1) relay.send(JSON.stringify({ type: 'hello', agent: myAgent }));
|
|
315
|
+
announceAgents();
|
|
316
|
+
const asked = params?.protocolVersion;
|
|
317
|
+
return reply(id, {
|
|
318
|
+
protocolVersion: ['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'].includes(asked) ? asked : '2025-06-18',
|
|
319
|
+
capabilities: { tools: { listChanged: false } },
|
|
320
|
+
serverInfo: { name: 'lattedit', title: 'lattedit', version: VERSION },
|
|
321
|
+
instructions: INSTRUCTIONS,
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
if (method === 'ping') return reply(id, {});
|
|
325
|
+
if (method === 'tools/list') return reply(id, { tools: TOOLS });
|
|
326
|
+
if (method === 'tools/call') {
|
|
327
|
+
try {
|
|
328
|
+
const r = await runTool(params?.name, params?.arguments ?? {});
|
|
329
|
+
return reply(id, { content: [{ type: 'text', text: r.text }], isError: !!r.isError });
|
|
330
|
+
} catch (e) {
|
|
331
|
+
return reply(id, { content: [{ type: 'text', text: e.message }], isError: true });
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
if (id === undefined) return; // a notification
|
|
335
|
+
return fail(id, -32601, `Method not found: ${method}`);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export async function serveMcp() {
|
|
339
|
+
// Start listening at once so a lattedit tab can connect before the first call.
|
|
340
|
+
await ensureBridge();
|
|
341
|
+
let buf = '';
|
|
342
|
+
process.stdin.setEncoding('utf8');
|
|
343
|
+
process.stdin.on('data', (chunk) => {
|
|
344
|
+
buf += chunk;
|
|
345
|
+
let nl;
|
|
346
|
+
while ((nl = buf.indexOf('\n')) !== -1) {
|
|
347
|
+
const line = buf.slice(0, nl).trim();
|
|
348
|
+
buf = buf.slice(nl + 1);
|
|
349
|
+
if (!line) continue;
|
|
350
|
+
let msg;
|
|
351
|
+
try { msg = JSON.parse(line); } catch { fail(null, -32700, 'Parse error'); continue; }
|
|
352
|
+
handle(msg).catch((e) => fail(msg.id, -32603, e.message));
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
process.stdin.on('end', () => process.exit(0));
|
|
356
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lattedit-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Official command-line client and MCP server for lattedit: compile LaTeX, and let coding agents edit your lattedit projects",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"lattedit": "cli/lattedit.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"cli/lattedit.mjs",
|
|
11
|
+
"cli/mcp.mjs",
|
|
12
|
+
"cli/mcp-tools.mjs"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"test": "node --test cli/mcp.test.mjs"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"latex",
|
|
19
|
+
"mcp",
|
|
20
|
+
"claude-code",
|
|
21
|
+
"codex",
|
|
22
|
+
"overleaf",
|
|
23
|
+
"pdf"
|
|
24
|
+
],
|
|
25
|
+
"homepage": "https://lattedit.xyz/developers",
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=22"
|
|
28
|
+
}
|
|
29
|
+
}
|