quire-editor-mcp 0.0.0-stage → 2.0.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.
Files changed (3) hide show
  1. package/README.md +18 -2
  2. package/package.json +8 -4
  3. package/server.mjs +229 -0
package/README.md CHANGED
@@ -1,3 +1,19 @@
1
- # Temporary Holding Version
1
+ # quire-editor-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Lets Claude read, edit, compile and review projects in [Quire](https://quire.deployment.work), the browser LaTeX and Typst editor. No dependencies, Node 18 or newer.
4
+
5
+ ```
6
+ claude mcp add quire -- npx -y quire-editor-mcp
7
+ ```
8
+
9
+ Then in Quire open the projects menu, choose Connect Claude, then Connect.
10
+
11
+ Claude Desktop, in `claude_desktop_config.json`
12
+
13
+ ```json
14
+ { "mcpServers": { "quire": { "command": "npx", "args": ["-y", "quire-editor-mcp"] } } }
15
+ ```
16
+
17
+ Any number of Claude sessions and Quire tabs can be open at once. The first session holds the bridge on `127.0.0.1:7357`, the others share it, and when it ends another one takes over. Claude works in the Quire tab you used last.
18
+
19
+ Running Quire on your own domain? Add `--origin https://your-domain` after the package name. `QUIRE_PORT` changes the port.
package/package.json CHANGED
@@ -1,6 +1,10 @@
1
1
  {
2
2
  "name": "quire-editor-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.0.0",
4
+ "description": "MCP server that lets Claude read, edit, compile and review projects in the Quire LaTeX and Typst editor",
5
+ "type": "module",
6
+ "bin": { "quire-editor-mcp": "server.mjs" },
7
+ "files": ["server.mjs"],
8
+ "engines": { "node": ">=18" },
9
+ "keywords": ["mcp", "claude", "latex", "typst", "quire"]
10
+ }
package/server.mjs ADDED
@@ -0,0 +1,229 @@
1
+ #!/usr/bin/env node
2
+ import http from 'node:http'
3
+ import crypto from 'node:crypto'
4
+ import readline from 'node:readline'
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import { StringDecoder } from 'node:string_decoder'
9
+
10
+ const PORT = +process.env.QUIRE_PORT || 7357
11
+ const APP = 'https://quire.deployment.work'
12
+ const argv = process.argv.slice(2), ORIGINS = [APP, ...(process.env.QUIRE_ORIGINS || '').split(','), ...argv.flatMap((a, i) => a === '--origin' ? [argv[i + 1]] : a.startsWith('--origin=') ? [a.slice(9)] : [])].map(s => (s || '').trim().replace(/\/+$/, '')).filter(Boolean)
13
+ const log = (...a) => console.error('[quire-mcp]', ...a)
14
+
15
+ const allowed = o => {
16
+ if (ORIGINS.includes('*')) return true
17
+ let u
18
+ try { u = new URL(o) } catch { return false }
19
+ if (['localhost', '127.0.0.1', '[::1]'].includes(u.hostname)) return true
20
+ return ORIGINS.some(x => x === u.origin || (x.startsWith('https://*.') && u.protocol === 'https:' && u.hostname.endsWith(x.slice(9))))
21
+ }
22
+ const hostOk = h => /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(h || '')
23
+
24
+ function secret() {
25
+ const d = path.join(os.homedir(), '.quire-mcp'), f = path.join(d, 'token')
26
+ fs.mkdirSync(d, { recursive: true, mode: 0o700 })
27
+ if (!fs.existsSync(f)) {
28
+ const t = f + '.' + process.pid
29
+ fs.writeFileSync(t, crypto.randomBytes(24).toString('hex'), { mode: 0o600 })
30
+ try { fs.linkSync(t, f) } catch { }
31
+ fs.rmSync(t, { force: true })
32
+ }
33
+ return fs.readFileSync(f, 'utf8').trim()
34
+ }
35
+ const TOKEN = secret()
36
+
37
+ let seq = 0, link = null, bindError = null, listening = false
38
+ const tabs = new Set(), waiting = new Map(), mine = new Map()
39
+ const lines = (s, fn) => { let b = ''; const dec = new StringDecoder('utf8'); s.on('data', d => { b += dec.write(d); let i; while ((i = b.indexOf('\n')) >= 0) { const l = b.slice(0, i); b = b.slice(i + 1); try { fn(JSON.parse(l)) } catch { } } }) }
40
+
41
+ function frame(op, data) {
42
+ const n = data.length, h = n < 126 ? Buffer.from([0x80 | op, n]) : n < 65536 ? Buffer.from([0x80 | op, 126, n >> 8, n & 255]) : Buffer.concat([Buffer.from([0x80 | op, 127]), (b => (b.writeBigUInt64BE(BigInt(n)), b))(Buffer.alloc(8))])
43
+ return Buffer.concat([h, data])
44
+ }
45
+ function wsServe(s) {
46
+ let buf = Buffer.alloc(0), parts = []
47
+ const ws = {
48
+ open: true,
49
+ send: t => ws.open && s.write(frame(1, Buffer.from(t))),
50
+ close: () => { if (!ws.open) return; ws.open = false; try { s.end(frame(8, Buffer.alloc(0))) } catch { } }
51
+ }
52
+ s.on('data', d => {
53
+ buf = Buffer.concat([buf, d])
54
+ for (;;) {
55
+ if (buf.length < 2) return
56
+ const fin = buf[0] & 0x80, op = buf[0] & 15, masked = buf[1] & 0x80
57
+ let n = buf[1] & 127, o = 2
58
+ if (n === 126) { if (buf.length < 4) return; n = buf.readUInt16BE(2); o = 4 }
59
+ else if (n === 127) { if (buf.length < 10) return; n = Number(buf.readBigUInt64BE(2)); o = 10 }
60
+ if (!masked || n > 64 * 1024 * 1024 || buf.length > 80 * 1024 * 1024) return s.destroy()
61
+ const need = o + (masked ? 4 : 0) + n
62
+ if (buf.length < need) return
63
+ const mask = masked ? buf.subarray(o, o + 4) : null, p = Buffer.from(buf.subarray(o + (masked ? 4 : 0), need))
64
+ if (mask) for (let i = 0; i < p.length; i++) p[i] ^= mask[i & 3]
65
+ buf = buf.subarray(need)
66
+ if (op === 8) { ws.close(); return }
67
+ if (op === 9) { s.write(frame(10, p)); continue }
68
+ if (op === 10) continue
69
+ parts.push(p)
70
+ if (!fin) continue
71
+ const msg = Buffer.concat(parts).toString('utf8'); parts = []
72
+ ws.onmessage?.(msg)
73
+ }
74
+ })
75
+ const end = () => { if (ws.ended) return; ws.ended = true; ws.open = false; ws.onclose?.() }
76
+ s.on('close', end); s.on('error', end)
77
+ return ws
78
+ }
79
+
80
+ const NOTAB = `No Quire tab is connected. Open Quire (${APP} or your own deployment) in Chrome, Edge or Firefox, then Projects menu, Connect Claude, Connect.`
81
+ const tabFor = () => new Promise((res, rej) => {
82
+ const pick = () => [...tabs].filter(t => t.ws.open).sort((a, b) => b.at - a.at)[0]
83
+ const t0 = pick()
84
+ if (t0) return res(t0)
85
+ const iv = setInterval(() => { const t = pick(); if (t) { clearInterval(iv); clearTimeout(to); res(t) } }, 200), to = setTimeout(() => { clearInterval(iv); rej(new Error(NOTAB)) }, 10000)
86
+ })
87
+ async function dispatch(op, args = {}, ms = 30000) {
88
+ const tab = await tabFor()
89
+ return new Promise((res, rej) => {
90
+ const id = ++seq, t = setTimeout(() => { waiting.delete(id); rej(new Error('Quire did not answer in time')) }, ms)
91
+ waiting.set(id, { res, rej, t, tab })
92
+ tab.ws.send(JSON.stringify({ id, op, args }))
93
+ })
94
+ }
95
+
96
+ function hub() {
97
+ const srv = http.createServer((q, r) => { if (!hostOk(q.headers.host)) { r.writeHead(403); return r.end() } r.writeHead(200, { 'content-type': 'text/plain' }); r.end('Quire MCP bridge. Open Quire and connect Claude from the Projects menu.\n') })
98
+ srv.on('upgrade', (q, s) => {
99
+ s.on('error', () => { })
100
+ const up = q.headers.upgrade?.toLowerCase()
101
+ if (!hostOk(q.headers.host)) return s.destroy()
102
+ if (up === 'quire-peer') {
103
+ if (q.headers.origin || q.headers['x-quire-token'] !== TOKEN) return s.end('HTTP/1.1 403 Forbidden\r\n\r\n')
104
+ for (const o of String(q.headers['x-quire-origins'] || '').split(',')) if (o && !ORIGINS.includes(o)) ORIGINS.push(o)
105
+ s.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: quire-peer\r\nConnection: Upgrade\r\n\r\n')
106
+ s.setNoDelay(true)
107
+ return lines(s, d => dispatch(d.op, d.args, d.ms).then(result => ({ id: d.id, ok: true, result }), e => ({ id: d.id, ok: false, error: String(e.message || e) })).then(r => s.writable && s.write(JSON.stringify(r) + '\n')))
108
+ }
109
+ const key = q.headers['sec-websocket-key']
110
+ if (!key || up !== 'websocket' || !allowed(q.headers.origin)) {
111
+ log('refused connection from origin', q.headers.origin || '(none)', '. Add it with --origin', q.headers.origin || '')
112
+ return s.end('HTTP/1.1 403 Forbidden\r\n\r\n')
113
+ }
114
+ const acc = crypto.createHash('sha1').update(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64')
115
+ s.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acc}\r\n\r\n`)
116
+ s.setNoDelay(true)
117
+ const tab = { ws: wsServe(s), at: 0 }
118
+ tab.ws.onmessage = m => {
119
+ let d
120
+ try { d = JSON.parse(m) } catch { return }
121
+ if (d.hello) { tab.at = +d.focus || 1; tabs.add(tab); log('Quire tab connected from', q.headers.origin); return }
122
+ if (d.focus) { tab.at = +d.focus; return }
123
+ const w = waiting.get(d.id)
124
+ if (!w || w.tab !== tab) return
125
+ waiting.delete(d.id); clearTimeout(w.t)
126
+ d.ok ? w.res(d.result) : w.rej(new Error(d.error || 'Quire reported an error'))
127
+ }
128
+ tab.ws.onclose = () => {
129
+ tabs.delete(tab)
130
+ for (const [id, w] of waiting) if (w.tab === tab) { waiting.delete(id); clearTimeout(w.t); w.rej(new Error('The Quire tab was closed or reloaded. Try again.')) }
131
+ }
132
+ })
133
+ srv.on('error', e => e.code === 'EADDRINUSE' ? peer() : (bindError = String(e.message || e), log(bindError)))
134
+ srv.listen(PORT, '127.0.0.1', () => { bindError = null; listening = true; log('bridge on ws://127.0.0.1:' + PORT) })
135
+ }
136
+
137
+ function peer() {
138
+ const r = http.request({ host: '127.0.0.1', port: PORT, headers: { connection: 'Upgrade', upgrade: 'quire-peer', 'x-quire-token': TOKEN, 'x-quire-origins': ORIGINS.join(',') } })
139
+ r.on('upgrade', (res, s) => {
140
+ bindError = null; link = s; s.setNoDelay(true)
141
+ log('sharing the bridge of another Claude session on port ' + PORT)
142
+ lines(s, d => { const w = mine.get(d.id); if (!w) return; mine.delete(d.id); clearTimeout(w.t); d.ok ? w.res(d.result) : w.rej(new Error(d.error)) })
143
+ s.on('error', () => { })
144
+ s.on('close', () => {
145
+ link = null
146
+ for (const [id, w] of mine) { mine.delete(id); clearTimeout(w.t); w.rej(new Error('The Claude session that held the Quire bridge ended. Try again.')) }
147
+ setTimeout(hub, 100 + Math.random() * 400)
148
+ })
149
+ })
150
+ r.on('response', res => { res.resume(); bindError = `Port ${PORT} is used by another program${res.statusCode === 403 ? ', possibly an older Quire MCP server' : ''}. Close it or set QUIRE_PORT.`; log(bindError); setTimeout(hub, 5000) })
151
+ r.on('error', () => setTimeout(hub, 300))
152
+ r.end()
153
+ }
154
+
155
+ async function call(op, args = {}, ms = 30000) {
156
+ for (let i = 0; i < 50 && !listening && !link && !bindError; i++) await new Promise(r => setTimeout(r, 100))
157
+ if (bindError) throw new Error(bindError)
158
+ if (!link) return dispatch(op, args, ms)
159
+ return new Promise((res, rej) => {
160
+ const id = ++seq, t = setTimeout(() => { mine.delete(id); rej(new Error('Quire did not answer in time')) }, ms + 15000)
161
+ mine.set(id, { res, rej, t })
162
+ link.write(JSON.stringify({ id, op, args, ms }) + '\n')
163
+ })
164
+ }
165
+ hub()
166
+
167
+ const S = (props = {}, required = []) => ({ type: 'object', properties: props, required, additionalProperties: false })
168
+ const str = d => ({ type: 'string', description: d })
169
+ const TOOLS = [
170
+ { name: 'status', description: 'Current Quire project: id, name, kind (typst or latex), main file, files with line counts, what the user has open and selected in the editor, and the last compile result. Call this first.', inputSchema: S() },
171
+ { name: 'list_projects', description: 'List all projects stored in the browser.', inputSchema: S() },
172
+ { name: 'open_project', description: 'Switch the editor to another project.', inputSchema: S({ id: str('Project id from list_projects') }, ['id']) },
173
+ { name: 'create_project', description: 'Create a project and open it. Without files it starts from the Typst or LaTeX template.', inputSchema: S({ name: str('Project name'), kind: { type: 'string', enum: ['typst', 'latex'] }, files: { type: 'object', description: 'Optional map of path to text content', additionalProperties: { type: 'string' } } }) },
174
+ { name: 'rename_project', description: 'Rename the open project.', inputSchema: S({ name: str('New name') }, ['name']) },
175
+ { name: 'read_file', description: 'Read a text file of the open project. Optional 1 based inclusive line range.', inputSchema: S({ path: str('File path, e.g. main.typ or chapters/intro.tex'), from: { type: 'integer', minimum: 1 }, to: { type: 'integer', minimum: 1 } }, ['path']) },
176
+ { name: 'write_file', description: 'Create a text file or replace its whole content. Changes appear live in the editor and for collaborators.', inputSchema: S({ path: str('File path'), content: str('Full new content') }, ['path', 'content']) },
177
+ { name: 'edit_file', description: 'Replace an exact string in a text file. old_string must match exactly once unless replace_all is true. Prefer this over write_file for small changes.', inputSchema: S({ path: str('File path'), old_string: str('Exact text to replace'), new_string: str('Replacement text'), replace_all: { type: 'boolean' } }, ['path', 'old_string', 'new_string']) },
178
+ { name: 'delete_file', description: 'Delete a file from the open project.', inputSchema: S({ path: str('File path') }, ['path']) },
179
+ { name: 'rename_file', description: 'Rename or move a file.', inputSchema: S({ from: str('Current path'), to: str('New path') }, ['from', 'to']) },
180
+ { name: 'set_main', description: 'Choose the main .typ or .tex file that gets compiled.', inputSchema: S({ path: str('File path') }, ['path']) },
181
+ { name: 'set_engine', description: 'Choose the LaTeX engine.', inputSchema: S({ engine: { type: 'string', enum: ['pdflatex', 'xelatex', 'lualatex'] } }, ['engine']) },
182
+ { name: 'open_file', description: 'Show a file in the editor for the user.', inputSchema: S({ path: str('File path') }, ['path']) },
183
+ { name: 'compile', description: 'Compile the open project now and return errors, warnings and for LaTeX failures the end of the log.', inputSchema: S() },
184
+ { name: 'render_page', description: 'Compile and return one page of the output as a PNG image, to check layout visually.', inputSchema: S({ page: { type: 'integer', minimum: 1, description: 'Page number, default 1' }, scale: { type: 'number', minimum: 0.5, maximum: 3, description: 'Zoom, default 1.5' } }) },
185
+ { name: 'list_versions', description: 'List saved versions (history) of the open project, newest first. Named versions are ones the user or Claude labelled.', inputSchema: S() },
186
+ { name: 'save_version', description: 'Save the current state of the open project as a named version. Do this before large or risky changes so the user can roll back.', inputSchema: S({ label: str('Short name for the version, e.g. Before restructuring chapters') }) },
187
+ { name: 'restore_version', description: 'Restore the open project to a saved version. The current state is kept as a version first.', inputSchema: S({ id: str('Version id from list_versions') }, ['id']) },
188
+ { name: 'list_comments', description: 'List review comments with the text they point at, line, author and replies. Resolved ones only with resolved true.', inputSchema: S({ path: str('Only comments in this file'), resolved: { type: 'boolean' } }) },
189
+ { name: 'add_comment', description: 'Add a review comment on an exact piece of text, the way a reviewer would. It appears in the review panel with Claude as author.', inputSchema: S({ path: str('File path'), quote: str('Exact text the comment is about'), text: str('The comment'), occurrence: { type: 'integer', minimum: 1, description: 'Which match, when quote appears more than once' } }, ['path', 'quote', 'text']) },
190
+ { name: 'reply_comment', description: 'Reply to a comment.', inputSchema: S({ id: str('Comment id'), text: str('Reply') }, ['id', 'text']) },
191
+ { name: 'resolve_comment', description: 'Resolve a comment, or reopen it with resolved false.', inputSchema: S({ id: str('Comment id'), resolved: { type: 'boolean' } }, ['id']) },
192
+ { name: 'list_changes', description: 'List tracked changes (insertions and deletions) waiting for review.', inputSchema: S({ path: str('Only changes in this file') }) },
193
+ { name: 'accept_changes', description: 'Accept tracked changes. Without ids, all of them.', inputSchema: S({ ids: { type: 'array', items: { type: 'string' } } }) },
194
+ { name: 'reject_changes', description: 'Reject tracked changes, which undoes them. Without ids, all of them.', inputSchema: S({ ids: { type: 'array', items: { type: 'string' } } }) },
195
+ { name: 'set_track_changes', description: 'Turn track changes on or off for the project. While on, every edit, including yours, becomes a suggestion the user can accept or reject.', inputSchema: S({ on: { type: 'boolean' } }, ['on']) }
196
+ ]
197
+ const SLOW = { compile: 240000, render_page: 240000, open_project: 60000, create_project: 60000 }
198
+
199
+ async function tool(name, args) {
200
+ if (!TOOLS.some(t => t.name === name)) return { content: [{ type: 'text', text: 'Unknown tool ' + name }], isError: true }
201
+ try {
202
+ const r = await call(name, args || {}, SLOW[name])
203
+ if (name === 'render_page') return { content: [{ type: 'image', data: r.png, mimeType: 'image/png' }, { type: 'text', text: `Page ${r.page} of ${r.pages}` }] }
204
+ if (name === 'compile' && r && !r.ok) return { content: [{ type: 'text', text: JSON.stringify(r, null, 2) }], isError: true }
205
+ return { content: [{ type: 'text', text: typeof r === 'string' ? r : JSON.stringify(r, null, 2) }] }
206
+ } catch (e) { return { content: [{ type: 'text', text: String(e.message || e) }], isError: true } }
207
+ }
208
+
209
+ const out = m => process.stdout.write(JSON.stringify(m) + '\n')
210
+ const INSTR = 'Quire is a browser LaTeX and Typst editor. These tools act on the project open in the connected Quire tab, and every edit shows up live in the editor. Start with status. Prefer edit_file for small changes. Call save_version before large rewrites. After editing, call compile, and use render_page to check how a page looks. When status shows track_changes on, your edits become suggestions; use add_comment to leave review notes instead of editing when the user asks for feedback.'
211
+ async function handle(m) {
212
+ const { id, method, params } = m
213
+ if (id === undefined) return
214
+ try {
215
+ if (method === 'initialize') return out({ jsonrpc: '2.0', id, result: { protocolVersion: params?.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'quire', version: '2.0.0' }, instructions: INSTR } })
216
+ if (method === 'ping') return out({ jsonrpc: '2.0', id, result: {} })
217
+ if (method === 'tools/list') return out({ jsonrpc: '2.0', id, result: { tools: TOOLS } })
218
+ if (method === 'tools/call') return out({ jsonrpc: '2.0', id, result: await tool(params?.name, params?.arguments) })
219
+ if (method === 'resources/list') return out({ jsonrpc: '2.0', id, result: { resources: [] } })
220
+ if (method === 'prompts/list') return out({ jsonrpc: '2.0', id, result: { prompts: [] } })
221
+ out({ jsonrpc: '2.0', id, error: { code: -32601, message: 'Method not found: ' + method } })
222
+ } catch (e) { out({ jsonrpc: '2.0', id, error: { code: -32603, message: String(e.message || e) } }) }
223
+ }
224
+ readline.createInterface({ input: process.stdin }).on('line', l => {
225
+ if (!l.trim()) return
226
+ let m
227
+ try { m = JSON.parse(l) } catch { return out({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }) }
228
+ for (const x of Array.isArray(m) ? m : [m]) handle(x)
229
+ }).on('close', () => process.exit(0))