fix mcp review findings in the docs family and the stdio bridge (#409)

This commit is contained in:
Xianheng Zhang
2026-09-16 08:05:19 +08:00
committed by GitHub
parent c00f9fb7e4
commit 1113835359
14 changed files with 282 additions and 41 deletions
+8 -3
View File
@@ -3604,6 +3604,11 @@ export function registerDocsIpc(): void {
error: `file already exists: ${filePath} (pass overwrite:true to replace it)`,
}
}
// An overwrite replaces bytes that were already on disk, so a teardown
// rollback must not unlink: deleting the path would destroy the
// pre-existing file rather than restoring it. Only a freshly created
// path is ours to remove.
const existedBefore = existsSync(filePath)
await mkdir(dirname(filePath), { recursive: true })
const passwordState = snapshotDocPassword(event.sender.id, null)
const bytes = passwordState.password
@@ -3611,15 +3616,15 @@ export function registerDocsIpc(): void {
: Buffer.from(data)
await atomicWriteFile(filePath, bytes)
// teardown may have happened while the write was in flight — a file this
// handler just wrote is safe to roll back (mirrors docs:save-new)
// handler just created is safe to roll back (mirrors docs:save-new)
if (tornDownWcIds.has(event.sender.id)) {
await unlink(filePath).catch(() => {})
if (!existedBefore) await unlink(filePath).catch(() => {})
return { ok: false }
}
allowDocWrite(event.sender.id, filePath)
await rememberDiskState(event.sender.id, filePath, bytes)
if (tornDownWcIds.has(event.sender.id)) {
await unlink(filePath).catch(() => {})
if (!existedBefore) await unlink(filePath).catch(() => {})
return { ok: false }
}
const passwordIntentPending = commitDocPasswordSave(
+4
View File
@@ -786,6 +786,9 @@ export function save(
export interface ExplicitSaveTarget {
path: string
overwrite: boolean
/** called with the main process's failure reason, so a caller that reports
* outside the UI (MCP) can relay it instead of a generic message */
onError?: (message: string) => void
}
/** the parsed fragment flags every node aiChanged (yellow highlight); a boot-time fill is not a reviewable AI edit */
@@ -887,6 +890,7 @@ async function saveOnce(
explicitTarget.overwrite,
)
if (!result.ok) {
explicitTarget.onError?.(result.error ?? '')
ctx.setStatus(t('appSaveFailed', { error: result.error ?? '' }))
showToast(t('appSaveFailed', { error: result.error ?? '' }), 'error')
return false
+22 -10
View File
@@ -2,7 +2,6 @@ import type { Editor } from '@tiptap/react'
import { BLANK_BULLET_NUM_ID, BLANK_ORDERED_NUM_ID } from '@genoffice/docx-engine'
import type { McpCommandMessage, McpEditorCommand } from '../shared/ipc'
import { executeTool, markDocSeen } from './ai/tools'
import { executeOps } from './ai/ops'
import { findNumId, type NumIds } from './ai/protocol'
import { save, type FileActionContext } from './file-actions'
@@ -15,8 +14,8 @@ import { save, type FileActionContext } from './file-actions'
* back on `docs:mcp-result`. Command execution is serialized so a burst cannot
* interleave two edits into one document.
*
* The executors are the built-in agent's own (`executeTool` / `executeOps`), so
* external edits inherit the same parsing, atomicity and formatting rules.
* The executors are the built-in agent's own (`executeTool`), so external edits
* inherit the same parsing, atomicity, formatting rules and stale-index guard.
*/
export interface McpBridgeDeps {
@@ -103,13 +102,22 @@ async function runCommand(
case 'apply_ops': {
const input = (payload ?? {}) as ApplyOpsInput
const outcome = executeOps(editor, input.ops, {
source: 'ai',
dryRun: input.dryRun === true,
})
if (!outcome.ok) throw new Error(outcome.error ?? 'the ops batch was rejected')
// Route through executeTool rather than executeOps: the wrapper is what
// refuses a block-indexed batch after the user edited the document (the
// stale-index guard) and supplies numbering ids, so an external batch
// behaves exactly like the built-in agent's.
const outcome = await executeTool(
editor,
{
id: 'mcp',
name: 'apply_ops',
input: { ops: input.ops, ...(input.dryRun === true ? { dryRun: true } : {}) },
},
numIdsFor(ctx),
)
if (outcome.isError) throw new Error(outcome.output)
if (input.dryRun !== true) clearAiChangedFlags(editor)
return { summary: outcome.summary, results: outcome.results, plan: outcome.plan }
return { summary: outcome.summary, output: outcome.output, mutated: outcome.mutated }
}
case 'read_document': {
@@ -127,11 +135,15 @@ async function runCommand(
if (typeof input.path !== 'string' || !input.path) {
throw new Error('save_document requires an absolute "path"')
}
const failures: string[] = []
const ok = await save(ctx, false, true, undefined, {
path: input.path,
overwrite: input.overwrite === true,
onError: (message) => failures.push(message),
})
if (!ok) throw new Error('the document could not be saved')
// the genuine reason matters here: "already exists, pass overwrite:true"
// is actionable, while a generic failure sends the agent guessing
if (!ok) throw new Error(failures[0] ?? 'the document could not be saved')
return { ok: true, path: input.path }
}
+17 -1
View File
@@ -21,6 +21,8 @@ const READY_TIMEOUT_MS = 20_000
const COMMAND_TIMEOUT_MS = 120_000
interface PendingCommand {
/** the tab this command was sent to; only that tab may answer it */
wcId: number
resolve: (result: unknown) => void
reject: (error: Error) => void
timer: NodeJS.Timeout
@@ -32,6 +34,16 @@ const pending = new Map<string, PendingCommand>()
let requestSeq = 0
let installed = false
/** drop every command still waiting on this tab, so a closed tab fails fast */
function abortPendingFor(wcId: number): void {
for (const [requestId, entry] of pending) {
if (entry.wcId !== wcId) continue
pending.delete(requestId)
clearTimeout(entry.timer)
entry.reject(new Error('the target document was closed while the command was running'))
}
}
function markReady(wcId: number): void {
readyIds.add(wcId)
const waiters = readyWaiters.get(wcId)
@@ -76,6 +88,7 @@ export function installDocsBridge(): void {
event.sender.once('destroyed', () => {
readyIds.delete(wcId)
readyWaiters.delete(wcId)
abortPendingFor(wcId)
})
})
ipcMain.on('docs:mcp-result', (event, result: unknown) => {
@@ -88,6 +101,9 @@ export function installDocsBridge(): void {
if (!payload || typeof payload.requestId !== 'string') return
const entry = pending.get(payload.requestId)
if (!entry) return
// requestIds are guessable, so any docs tab could otherwise answer another
// tab's command: the reply is only valid from the tab the command targeted
if (entry.wcId !== event.sender.id) return
pending.delete(payload.requestId)
clearTimeout(entry.timer)
if (payload.ok === true) entry.resolve(payload.result)
@@ -116,7 +132,7 @@ export function createDocsControl(deps: DocsBridgeDeps): DocsControl {
pending.delete(requestId)
reject(new Error(`the document command timed out after ${COMMAND_TIMEOUT_MS}ms`))
}, COMMAND_TIMEOUT_MS)
pending.set(requestId, { resolve, reject, timer })
pending.set(requestId, { wcId, resolve, reject, timer })
})
wc.send('docs:mcp-command', { requestId, command, payload })
return result
+4 -1
View File
@@ -69,9 +69,12 @@ async function runCreate(
/**
* Read a .docx's visible text through `docs read`. Returns one paragraph per
* line, matching the tool's documented shape.
*
* `--full` is required: without it the CLI clips each block to a 200-character
* preview, so long paragraphs would come back silently truncated.
*/
export async function readDocxTextViaCli(runner: CliRunner, path: string): Promise<string> {
const outcome = await runner.run(['docs', 'read', path])
const outcome = await runner.run(['docs', 'read', path, '--full'])
if (!outcome.ok || !outcome.json || outcome.json.status !== 'ok') {
throw new Error(cliErrorMessage(outcome))
}
+44 -5
View File
@@ -1,4 +1,14 @@
import { existsSync, readFileSync, appendFileSync, truncateSync, writeFileSync } from 'node:fs'
import {
closeSync,
existsSync,
openSync,
readFileSync,
readSync,
statSync,
appendFileSync,
truncateSync,
writeFileSync,
} from 'node:fs'
/**
* Local log for the MCP server: a bounded in-memory ring plus an append-only
@@ -80,9 +90,38 @@ export class McpLogger {
}
}
/** last `limit` lines of a text file without loading it all */
/**
* Last `limit` non-empty lines of a text file.
*
* The settings pane polls this every couple of seconds while logging is on, so
* it reads a bounded suffix instead of the whole append-only file: growing the
* work with total history would put an unbounded synchronous read on the main
* process. A generous per-line allowance covers the long lines a stack trace
* can produce; falling back to the whole file when the suffix is too small to
* hold `limit` lines keeps the result exact.
*/
function readTail(filePath: string, limit: number): string[] {
const raw = readFileSync(filePath, 'utf8')
const lines = raw.split('\n').filter((l) => l.length > 0)
return lines.slice(-limit)
const MAX_BYTES = 256 * 1024
const { size } = statSync(filePath)
if (size <= MAX_BYTES) return tailLines(readFileSync(filePath, 'utf8'), limit)
const start = size - MAX_BYTES
const fh = openSync(filePath, 'r')
try {
const buffer = Buffer.allocUnsafe(MAX_BYTES)
const read = readSync(fh, buffer, 0, MAX_BYTES, start)
let lines = buffer.subarray(0, read).toString('utf8').split('\n')
// the window starts mid-line, so its first entry is a partial line
lines = lines.slice(1)
return lines.filter((l) => l.length > 0).slice(-limit)
} finally {
closeSync(fh)
}
}
function tailLines(raw: string, limit: number): string[] {
return raw
.split('\n')
.filter((l) => l.length > 0)
.slice(-limit)
}
@@ -81,6 +81,11 @@ export function uniquePathIn(dir: string, fileName: string): string {
* file base name, land in the default save folder when no path is given, require
* absolute paths otherwise, append the extension when missing, and refuse to
* clobber an existing file unless overwrite is set.
*
* A path that already carries a *different* extension is rejected rather than
* having the right one appended: `report.pdf` silently becoming
* `report.pdf.docx` would write a file the caller never asked for (and hide a
* confused request behind a valid result).
*/
export function resolveOutputPath(opts: {
defaultSaveDir: () => string
@@ -96,10 +101,11 @@ export function resolveOutputPath(opts: {
if (!isAbsolute(opts.requestedPath)) {
throw new Error('path must be absolute')
}
const finalPath =
extname(opts.requestedPath).toLowerCase() === ext
? opts.requestedPath
: `${opts.requestedPath}${ext}`
const requestedExt = extname(opts.requestedPath)
if (requestedExt && requestedExt.toLowerCase() !== ext) {
throw new Error(`path must point to a ${ext} file (got "${requestedExt}")`)
}
const finalPath = requestedExt ? opts.requestedPath : `${opts.requestedPath}${ext}`
if (existsSync(finalPath) && !opts.overwrite) {
throw new Error(`file already exists: ${finalPath} (pass overwrite:true to replace it)`)
}
@@ -216,9 +222,13 @@ export function createDocumentTools(deps: DocToolDeps, host: SessionHost): McpTo
name: 'GenOffice',
version: deps.version,
defaultSaveDir: deps.defaultSaveDir(),
formats: ['docx', ...(deps.extraFormats ?? [])],
// Every format listed here is written by a headless create/read tool, and
// all of them are opt-in: with background generation off there is no
// generate tool at all, so advertising docx/pptx/xlsx would describe
// capabilities this client cannot reach.
formats: deps.background === false ? [] : ['docx', ...(deps.extraFormats ?? [])],
// editor truth vs. what this server exposes — see tools/formats.ts
families: capabilityReport(),
families: capabilityReport({ generating: deps.background !== false }),
}),
},
...createDocxContentTools(deps, host),
@@ -311,8 +321,9 @@ function createDocxContentTools(deps: DocToolDeps, host: SessionHost): McpToolDe
{
name: 'read_document',
description:
'Read the visible document: its blocks with indexes, text and current formatting, so you can ' +
'target follow-up edits.',
'Read the visible document as a block list: one "index|type|text" line per block, where the ' +
'index is what apply_ops and insert_content address. Long blocks are clipped for reading; ' +
'the list is an overview, not a lossless copy (use read_docx for full text).',
inputSchema: {},
handler: async () => {
const wc = requireActive()
+20 -8
View File
@@ -137,17 +137,29 @@ export function withSaveExtension(family: SessionFamily, filePath: string): stri
throw new Error(`a ${familyLabel(family)} session must be saved as ${wanted} (got ".${ext}")`)
}
/** compact capability report for get_app_info: editor truth + exposed MCP subset */
export function capabilityReport(): Array<{
/**
* Compact capability report for get_app_info: editor truth plus the MCP subset.
*
* The static `mcp` block is what this server *can* expose; the runtime options
* narrow it to what is actually registered right now, so the report never
* advertises a tool the client cannot call (`generating: false` hides the
* headless `create_*` tools, which are opt-in).
*/
export function capabilityReport(options: { generating?: boolean } = {}): Array<{
family: EditorFamily
label: string
editor: { open: readonly string[]; save: readonly string[]; export: readonly string[] }
mcp?: McpFormats
}> {
return FORMAT_FAMILIES.map((f) => ({
family: f.family,
label: f.label,
editor: { open: f.editorOpen, save: f.editorSave, export: f.editorExport },
...(f.mcp ? { mcp: f.mcp } : {}),
}))
const generating = options.generating !== false
return FORMAT_FAMILIES.map((f) => {
const mcp = f.mcp ? { ...f.mcp } : undefined
if (mcp && !generating) delete mcp.generate
return {
family: f.family,
label: f.label,
editor: { open: f.editorOpen, save: f.editorSave, export: f.editorExport },
...(mcp && Object.keys(mcp).length > 0 ? { mcp } : {}),
}
})
}
+12 -2
View File
@@ -1077,6 +1077,10 @@ export function SettingsModal({
const [mcpRunning, setMcpRunning] = useState(false)
const [mcpEnabled, setMcpEnabled] = useState(false)
const [mcpPort, setMcpPort] = useState('3093')
// the last port the main process confirmed: an invalid edit reverts to this
// rather than a hard-coded default, which could disagree with a server that is
// already running on another port
const mcpSavedPort = useRef('3093')
const [mcpError, setMcpError] = useState('')
const [mcpSaving, setMcpSaving] = useState(false)
const [mcpBackground, setMcpBackground] = useState(false)
@@ -1112,6 +1116,7 @@ export function SettingsModal({
setMcpRunning(s.running)
setMcpEnabled(s.enabled)
setMcpPort(String(s.port))
mcpSavedPort.current = String(s.port)
setMcpBackground(s.background)
setMcpLogging(s.logging)
setMcpCaps(s.capabilities ?? ['docs'])
@@ -1163,6 +1168,7 @@ export function SettingsModal({
setMcpRunning(s.running)
setMcpEnabled(s.enabled)
setMcpPort(String(s.port))
mcpSavedPort.current = String(s.port)
setMcpBackground(s.background)
setMcpLogging(s.logging)
setMcpCaps(s.capabilities ?? ['docs'])
@@ -1485,10 +1491,14 @@ export function SettingsModal({
onBlur={() => {
const port = Number(mcpPort)
if (!Number.isInteger(port) || port < 1024 || port > 65535) {
setMcpPort('3093')
// revert to the port the main process last confirmed, not
// a literal default that may not match the running server
setMcpPort(mcpSavedPort.current)
return
}
if (!mcpEnabled) return
if (String(port) === mcpSavedPort.current) return
// persist even while the server is off, so the port is
// configured before it is switched on
applyMcp({ port })
}}
/>
+2 -1
View File
@@ -177,7 +177,8 @@ describe('M3 docx tools', () => {
expect(result.isError).toBeFalsy()
const payload = JSON.parse(text(result.content)) as { text: string }
expect(payload.text).toBe('Title\nBody text here.')
expect(cli.last()).toEqual(['docs', 'read', join(dir, 'doc.docx')])
// --full matters: without it the CLI clips every block to a preview
expect(cli.last()).toEqual(['docs', 'read', join(dir, 'doc.docx'), '--full'])
})
it('read_docx rejects a missing file and a non-docx extension', async () => {
@@ -182,7 +182,13 @@ describe('MCP surface over Streamable HTTP (/mcp)', () => {
expect(infoJson.name).toBe('GenOffice')
expect(infoJson.version).toBe('0.9.0-acceptance')
expect(infoJson.defaultSaveDir).toBe(workDir)
expect(infoJson.formats.sort()).toEqual(['docx'])
// background generation is off here, so create_docx is not registered and
// get_app_info must not advertise a generation format the client cannot use
expect(infoJson.formats).toEqual([])
expect(infoJson.families.find((f) => f.family === 'docx')!.mcp).toEqual({
save: ['docx'],
read: 'docx',
})
expect(infoJson.families.map((f) => f.family)).toEqual([
'docx',
'xlsx',
+13
View File
@@ -63,6 +63,19 @@ describe('McpLogger', () => {
expect(tail[9]).toContain('line 29')
})
it('recent() reads the tail of a file larger than the suffix window', () => {
// write past the 256 KiB suffix window so the bounded-read path runs; the
// last lines must still come back whole (no truncated first line)
const big = 'x'.repeat(4096)
for (let i = 0; i < 100; i++) logger.append(`line ${i} ${big}`)
const tail = logger.recent(5)
expect(tail).toHaveLength(5)
expect(tail[0]).toContain('line 95 ')
expect(tail[4]).toContain('line 99 ')
// every returned line is complete: the partial window edge is dropped
for (const line of tail) expect(line).toMatch(/^\[\d{4}-.*\] line \d+ x+$/)
})
it('starts each logger with a fresh file (per-launch log, not persisted across runs)', () => {
logger.append('[mcp] line from a previous run')
// a new app launch constructs a fresh logger over the same path: the old
+48
View File
@@ -87,4 +87,52 @@ describe('stdio bridge', () => {
expect(parsed, `no tools/list response; stdout=${JSON.stringify(stdout)}`).toBeDefined()
expect(parsed!.result!.tools!.map((t) => t.name)).toContain('ping')
}, 20000)
it('never answers a notification, even when forwarding it fails', async () => {
// no server on this port: every forward fails, which is the case where the
// old bridge wrote an id-less error object onto the JSON-RPC stdout channel
const port = await freePort()
child = spawn(process.execPath, [bridgePath, '--port', String(port)], {
stdio: ['pipe', 'pipe', 'pipe'],
})
const stdout: string[] = []
child.stdout!.on('data', (chunk: Buffer) => {
for (const line of chunk.toString().split('\n')) if (line.trim()) stdout.push(line.trim())
})
await new Promise((resolve) => setTimeout(resolve, 1500))
// a notification (no id) followed by a request (id) — only the request may
// produce a stdout line
child.stdin!.write(
JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n',
)
child.stdin!.write(
JSON.stringify({ jsonrpc: '2.0', id: 7, method: 'tools/list', params: {} }) + '\n',
)
const deadline = Date.now() + 8000
let sawRequestError = false
while (Date.now() < deadline && !sawRequestError) {
await new Promise((resolve) => setTimeout(resolve, 100))
sawRequestError = stdout.some((line) => {
try {
return (JSON.parse(line) as { id?: number }).id === 7
} catch {
return false
}
})
}
expect(sawRequestError, `no error for request id 7; stdout=${JSON.stringify(stdout)}`).toBe(
true,
)
// every line must answer a request; an id-less error line is the protocol
// violation a stdio client would choke on
for (const line of stdout) {
const msg = JSON.parse(line) as { id?: unknown; error?: unknown }
if (msg.error === undefined) continue
expect(msg.id, `answered a notification: ${line}`).toBeDefined()
}
}, 20000)
})
+62 -1
View File
@@ -49,6 +49,16 @@ let connectingPromise = null
let reconnectTimer = null
let stopping = false
// The client performs the MCP handshake once, against the first SSE session.
// A reconnect creates a *new*, uninitialized server session, so the cached
// handshake is replayed on it — otherwise every tool call after a transient
// disconnect fails as "not initialized" while the client believes it is ready.
// Responses to a replayed initialize are dropped: the client already has its
// handshake result and would see a duplicate response.
let handshakeMessages = null
let handshakeSession = null
const suppressedResponseIds = new Set()
/** stderr only: stdout is the JSON-RPC channel */
function log(message) {
process.stderr.write(`[genoffice-mcp-bridge] ${message}\n`)
@@ -123,7 +133,13 @@ function connectSSE() {
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
sendResponse(JSON.parse(line.slice(6)))
const parsed = JSON.parse(line.slice(6))
// drop the answer to a replayed handshake
if (parsed && parsed.id !== undefined && suppressedResponseIds.has(parsed.id)) {
suppressedResponseIds.delete(parsed.id)
continue
}
sendResponse(parsed)
} catch {
// endpoint URL / heartbeat comment: not JSON-RPC
}
@@ -181,8 +197,47 @@ function scheduleReconnect() {
}, 5000)
}
/** Remember the client's handshake so a reconnect can re-establish it. */
function cacheHandshake(message) {
const method = message && typeof message === 'object' ? message.method : undefined
if (method !== 'initialize' && method !== 'notifications/initialized') return
const cached = (handshakeMessages ?? []).filter((m) => m.method !== method)
cached.push(message)
handshakeMessages = cached
// the exchanged pair completes the handshake on the session that carried it
if (method === 'notifications/initialized') handshakeSession = sessionId
}
/** Re-run the cached handshake against a freshly created session. */
async function replayHandshake() {
const messages = handshakeMessages
const target = sessionId
if (!messages || messages.length === 0) {
handshakeSession = target
return
}
// Mark the session as handshaked up front: sendToServer below would otherwise
// see the stale handshakeSession and re-enter this function.
handshakeSession = target
log('replaying session handshake after reconnect')
for (const message of messages) {
if (message.id !== undefined && message.id !== null) {
suppressedResponseIds.add(message.id)
}
try {
await sendToServer(message)
} catch (error) {
log(`handshake replay failed: ${error.message}`)
}
}
}
async function sendToServer(message) {
if (!sessionId) await connectSSE()
// a reconnect hands us a new, uninitialized session: re-establish the cached
// handshake before the client's next call lands on it
if (handshakeSession !== null && handshakeSession !== sessionId) await replayHandshake()
cacheHandshake(message)
// legacy SSE delivers responses only on the stream; the POST ack body must
// not be written to stdout or it corrupts the newline-delimited protocol
const response = await httpRequest('POST', `/messages?sessionId=${sessionId}`, message)
@@ -196,6 +251,12 @@ async function handleRequest(request) {
try {
await sendToServer(request)
} catch (error) {
// A notification (no id) must never be answered: an unsolicited line would
// read as a protocol violation to the client. Only log it.
if (request.id === undefined || request.id === null) {
log(`notification ${request.method} failed: ${error.message}`)
return
}
sendResponse({
jsonrpc: '2.0',
id: request.id,