@adeu/mcp-server 1.6.2 → 1.6.5
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/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/package.json +31 -31
- package/src/index.test.ts +6 -6
- package/src/index.ts +207 -207
- package/src/response-builders.ts +146 -146
- package/tsconfig.json +21 -21
- package/tsup.config.ts +25 -22
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/response-builders.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\r\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\r\nimport { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';\r\nimport { readFileSync } from 'node:fs';\r\nimport { basename, resolve, extname, dirname } from 'node:path';\r\nimport { \r\n identifyEngine, \r\n extractTextFromBuffer, \r\n DocumentObject, \r\n RedlineEngine, \r\n BatchValidationError \r\n} from '@adeu/core';\r\nimport { \r\n build_paginated_response, \r\n build_outline_response, \r\n build_appendix_response \r\n} from './response-builders.js';\r\n\r\n// --- Tool Description Constants (Parity with Python) ---\r\nconst READ_DOCX_COMMON_DESC = \"Reads a DOCX file. Returns text with inline CriticMarkup for Tracked Changes and Comments: {++inserted++}, {--deleted--}, {==highlighted==}{>>comment<<}. Set clean_view=True for the finalized 'Accepted' text without markup.\\n\\n\";\r\nconst READ_DOCX_TAIL = \"Modes:\\n- 'full' (default): paginated body content. Use page=N to navigate.\\n- 'outline': heading map only — start here for large docs to plan targeted reads. Defaults to L1-L2 headings; pass outline_max_level=3-6 to see deeper structure.\\n- 'appendix': defined terms, anchors, and cross-reference targets. Consult before editing legal/technical docs to avoid breaking references.\";\r\n\r\nconst PROCESS_BATCH_COMMON_DESC = \"Applies a batch of edits and review actions to a DOCX.\\n\\nAll changes evaluate against the ORIGINAL document state — do not chain dependent edits within one batch (e.g. rename X to Y, then modify Y). Apply the rename first, then send a second batch.\\n\\n\";\r\nconst PROCESS_BATCH_OPERATIONS_DESC = \"Each item in `changes` must specify a `type`:\\n1. 'modify': Search-and-replace. `target_text` must uniquely match — include surrounding context if the phrase is ambiguous. `new_text` supports Markdown: '# Heading 1' through '###### Heading 6', '**bold**', '_italic_', and '\\\\n\\\\n' to split into multiple paragraphs. Empty `new_text` deletes. Do NOT write CriticMarkup tags ({++, {--, {>>) manually — use the `comment` parameter for comments.\\n2. 'accept' / 'reject': Finalize or revert a tracked change by `target_id` (e.g. 'Chg:12').\\n3. 'reply': Reply to a comment by `target_id` (e.g. 'Com:5') with `text`.\\n4. 'insert_row' / 'delete_row': Table edits. Disk mode only — not supported on Live Word canvas.\\n\\nID VOLATILITY: 'Chg:N' and 'Com:N' shift between document states. Always call `read_docx` immediately before any accept/reject/reply — do not reuse IDs from earlier in the conversation.\\n\\n`author_name` is used for attribution on all tracked changes and comments, in both disk and Live Word modes.\";\r\n\r\n// --- Server Setup ---\r\nconst server = new Server(\r\n {\r\n name: 'adeu-redlining-service',\r\n version: '1.0.0',\r\n },\r\n {\r\n capabilities: {\r\n tools: {},\r\n },\r\n }\r\n);\r\n\r\n// --- Tool Registration ---\r\nserver.setRequestHandler(ListToolsRequestSchema, async () => {\r\n return {\r\n tools: [\r\n {\r\n name: 'read_docx',\r\n description: READ_DOCX_COMMON_DESC + READ_DOCX_TAIL,\r\n inputSchema: {\r\n type: 'object',\r\n properties: {\r\n file_path: { type: 'string', description: 'Absolute path to the DOCX file.' },\r\n clean_view: { type: 'boolean', description: \"If False (default), returns the 'Raw' text with inline CriticMarkup. If True, returns 'Accepted' text.\", default: false },\r\n mode: { type: 'string', enum: ['full', 'outline', 'appendix'], description: \"'full' returns body content. 'outline' returns a structural heading map. 'appendix' returns defined terms.\", default: 'full' },\r\n page: { type: 'number', description: 'Page number (1-indexed) for mode=\\'full\\'. Defaults to 1.', default: 1 },\r\n outline_max_level: { type: 'number', description: 'For mode=\\'outline\\' only: cap on heading depth.', default: 2 },\r\n outline_verbose: { type: 'boolean', description: 'For mode=\\'outline\\' only: includes metadata.', default: false }\r\n },\r\n required: ['file_path']\r\n }\r\n },\r\n {\r\n name: 'process_document_batch',\r\n description: PROCESS_BATCH_COMMON_DESC + PROCESS_BATCH_OPERATIONS_DESC,\r\n inputSchema: {\r\n type: 'object',\r\n properties: {\r\n original_docx_path: { type: 'string', description: 'Absolute path to the source file.' },\r\n author_name: { type: 'string', description: \"Name to appear in Track Changes (e.g., 'Reviewer AI').\" },\r\n changes: { \r\n type: 'array', \r\n description: \"List of changes to apply. Each change must specify 'type'.\",\r\n items: { type: 'object' } \r\n },\r\n output_path: { type: 'string', description: 'Optional output path.' }\r\n },\r\n required: ['original_docx_path', 'author_name', 'changes']\r\n }\r\n },\r\n {\r\n name: 'accept_all_changes',\r\n description: \"Accepts all tracked changes and removes all comments in a single operation, producing a finalized clean document. Use this when a document review is entirely complete and you want to clear all redlines.\",\r\n inputSchema: {\r\n type: 'object',\r\n properties: {\r\n docx_path: { type: 'string', description: 'Absolute path to the DOCX file.' },\r\n output_path: { type: 'string', description: 'Optional output path.' }\r\n },\r\n required: ['docx_path']\r\n }\r\n }\r\n ]\r\n };\r\n});\r\n\r\n// --- Tool Execution ---\r\nserver.setRequestHandler(CallToolRequestSchema, async (request): Promise<any> => {\r\n const { name, arguments: args } = request.params;\r\n\r\n try {\r\n if (name === 'read_docx') {\r\n const filePath = args?.file_path as string;\r\n const cleanView = args?.clean_view as boolean ?? false;\r\n const mode = args?.mode as string ?? 'full';\r\n const page = args?.page as number ?? 1;\r\n const outline_max_level = args?.outline_max_level as number ?? 2;\r\n const outline_verbose = args?.outline_verbose as boolean ?? false;\r\n \r\n const buf = readFileSync(filePath);\r\n const text = await extractTextFromBuffer(buf, cleanView);\r\n \r\n if (mode === 'outline') {\r\n const doc = await DocumentObject.load(buf);\r\n return build_outline_response(doc, text, filePath, outline_max_level, outline_verbose);\r\n }\r\n if (mode === 'appendix') {\r\n return build_appendix_response(text, page, filePath);\r\n }\r\n return build_paginated_response(text, page, filePath);\r\n }\r\n\r\n if (name === 'process_document_batch') {\r\n const origPath = args?.original_docx_path as string;\r\n const authorName = args?.author_name as string;\r\n const changes = args?.changes as any[];\r\n let outPath = args?.output_path as string;\r\n\r\n if (!outPath) {\r\n const ext = extname(origPath);\r\n const base = basename(origPath, ext);\r\n const dir = dirname(origPath);\r\n outPath = resolve(dir, `${base}_processed${ext}`);\r\n }\r\n\r\n const buf = readFileSync(origPath);\r\n const doc = await DocumentObject.load(buf);\r\n const engine = new RedlineEngine(doc, authorName);\r\n \r\n let stats;\r\n try {\r\n stats = engine.process_batch(changes);\r\n } catch (e) {\r\n if (e instanceof BatchValidationError) {\r\n return {\r\n content: [{ type: 'text', text: `Batch rejected. Some edits failed validation:\\n\\n${(e as BatchValidationError).errors.join('\\n\\n')}` }],\r\n isError: true\r\n };\r\n }\r\n throw e;\r\n }\r\n\r\n const outBuf = await doc.save();\r\n // Using dynamic import of fs/promises or just sync write\r\n const fs = await import('node:fs');\r\n fs.writeFileSync(outPath, outBuf);\r\n\r\n let res = `Batch complete. Saved to: ${outPath}\\nActions: ${stats.actions_applied} applied, ${stats.actions_skipped} skipped.\\nEdits: ${stats.edits_applied} applied, ${stats.edits_skipped} skipped.`;\r\n if (stats.skipped_details?.length > 0) {\r\n res += `\\n\\nSkipped Details:\\n${stats.skipped_details.join('\\n')}`;\r\n }\r\n\r\n return {\r\n content: [{ type: 'text', text: res }]\r\n };\r\n }\r\n\r\n if (name === 'accept_all_changes') {\r\n const docxPath = args?.docx_path as string;\r\n let outPath = args?.output_path as string;\r\n\r\n if (!outPath) {\r\n const ext = extname(docxPath);\r\n const base = basename(docxPath, ext);\r\n const dir = dirname(docxPath);\r\n outPath = resolve(dir, `${base}_clean${ext}`);\r\n }\r\n\r\n const buf = readFileSync(docxPath);\r\n const doc = await DocumentObject.load(buf);\r\n const engine = new RedlineEngine(doc);\r\n \r\n // We implement the public facing accept_all wrapper from python\r\n engine.accept_all_revisions();\r\n \r\n const outBuf = await doc.save();\r\n const fs = await import('node:fs');\r\n fs.writeFileSync(outPath, outBuf);\r\n\r\n return {\r\n content: [{ type: 'text', text: `Accepted all changes. Saved to: ${outPath}` }]\r\n };\r\n }\r\n\r\n throw new Error(`Unknown tool: ${name}`);\r\n\r\n } catch (error: any) {\r\n return {\r\n content: [{ type: 'text', text: `Error executing tool ${name}: ${error.message}` }],\r\n isError: true,\r\n };\r\n }\r\n});\r\n\r\n// --- Startup ---\r\nasync function main() {\r\n const transport = new StdioServerTransport();\r\n await server.connect(transport);\r\n console.error(`Adeu MCP Server (Node.js Engine: ${identifyEngine()}) running on stdio`);\r\n}\r\n\r\nmain().catch(console.error);","import { resolve, basename } from 'node:path';\r\nimport { \r\n DocumentObject, \r\n paginate, \r\n split_structural_appendix, \r\n extract_outline, \r\n OutlineNode \r\n} from '@adeu/core';\r\n\r\nexport interface ToolResult {\r\n content: { type: 'text'; text: string }[];\r\n isError?: boolean;\r\n [key: string]: unknown;\r\n}\r\n\r\nfunction _build_appendix_pointer(has_appendix: boolean): string {\r\n if (!has_appendix) return '';\r\n return `\\n\\n---\\n\\n> **Appendix available.** This document has structural metadata (defined terms, cross-references, bookmarks, diagnostics) that may be relevant when editing. Call \\`read_docx\\` with \\`mode='appendix'\\` to load it before submitting edits.`;\r\n}\r\n\r\nfunction _build_page_banner(page: number, total: number): string {\r\n if (total <= 1) return '';\r\n return `> **Page ${page} of ${total}** — call \\`read_docx\\` with \\`mode='outline'\\` for a heading map of the full document.\\n\\n---\\n\\n`;\r\n}\r\n\r\nfunction _build_page_footer(page: number, total: number, has_next: boolean): string {\r\n if (total <= 1 || !has_next) return '';\r\n return `\\n\\n---\\n\\n> **Continues on page ${page + 1} of ${total}.**`;\r\n}\r\n\r\nexport function render_outline_tree(nodes: OutlineNode[], max_level: number = 2, verbose: boolean = false): string {\r\n if (!nodes || nodes.length === 0) {\r\n return '# (No headings detected)\\n\\nThis document has no detectable headings.';\r\n }\r\n\r\n const visible = nodes.filter(n => n.level <= max_level);\r\n\r\n if (visible.length === 0) {\r\n return `# (No headings at level <= ${max_level})\\n\\nDocument has ${nodes.length} headings, all at deeper levels. Call read_docx with mode='outline' and outline_max_level=N (up to 6) to see them.`;\r\n }\r\n\r\n const lines: string[] = [];\r\n for (const node of visible) {\r\n const prefix = '#'.repeat(node.level);\r\n if (verbose) {\r\n const meta_parts = [`p${node.page}`, node.style];\r\n if (node.has_table) meta_parts.push('has table');\r\n if (node.footnote_ids && node.footnote_ids.length > 0) meta_parts.push('fn:' + node.footnote_ids.join(','));\r\n lines.push(`${prefix} ${node.text} (${meta_parts.join(', ')})`);\r\n } else {\r\n lines.push(`${prefix} ${node.text} (p${node.page})`);\r\n }\r\n }\r\n return lines.join('\\n');\r\n}\r\n\r\nexport function build_paginated_response(text: string, page: number, file_path: string): ToolResult {\r\n const [body, appendix] = split_structural_appendix(text);\r\n const has_appendix = Boolean(appendix.trim());\r\n\r\n const result = paginate(body, '');\r\n\r\n if (page < 1 || page > result.total_pages) {\r\n throw new Error(`Page ${page} out of range (doc has ${result.total_pages} pages).`);\r\n }\r\n\r\n const selected = result.pages[page - 1];\r\n const banner = _build_page_banner(selected.page, selected.total_pages);\r\n const footer = _build_page_footer(selected.page, selected.total_pages, selected.has_next);\r\n const appendix_pointer = _build_appendix_pointer(has_appendix);\r\n \r\n const ui_markdown = banner + selected.page_content + footer + appendix_pointer;\r\n const llm_content = `> **File Path:** \\`${resolve(file_path)}\\`\\n\\n${ui_markdown}`;\r\n\r\n return {\r\n content: [{ type: 'text', text: llm_content }]\r\n };\r\n}\r\n\r\nexport function build_outline_response(\r\n doc: DocumentObject, \r\n projected_text: string, \r\n file_path: string, \r\n outline_max_level: number = 2, \r\n outline_verbose: boolean = false\r\n): ToolResult {\r\n const [body] = split_structural_appendix(projected_text);\r\n const pagination_result = paginate(body, '');\r\n\r\n const nodes = extract_outline(\r\n doc,\r\n body,\r\n pagination_result.body_pages,\r\n pagination_result.body_page_offsets\r\n );\r\n\r\n const rendered = render_outline_tree(nodes, outline_max_level, outline_verbose);\r\n\r\n const visible_count = nodes.filter(n => n.level <= outline_max_level).length;\r\n const deeper_count = nodes.length - visible_count;\r\n const deeper_hint = deeper_count > 0 ? ` (${deeper_count} more at deeper levels, raise outline_max_level to see)` : '';\r\n\r\n const header = `> **Outline view** — showing ${visible_count} of ${nodes.length} headings (L1-L${outline_max_level}${deeper_hint}) across ${pagination_result.total_pages} page(s). Call \\`read_docx\\` with \\`mode='full'\\` and \\`page=N\\` to read a section.\\n\\n---\\n\\n`;\r\n const ui_markdown = header + rendered;\r\n const llm_content = `> **File Path:** \\`${resolve(file_path)}\\`\\n\\n${ui_markdown}`;\r\n\r\n return {\r\n content: [{ type: 'text', text: llm_content }]\r\n };\r\n}\r\n\r\nexport function build_appendix_response(text: string, page: number, file_path: string): ToolResult {\r\n const [, appendix] = split_structural_appendix(text);\r\n\r\n if (!appendix.trim()) {\r\n const ui_markdown = \"# Appendix\\n\\nThis document has no structural appendix (no defined terms, named anchors, or diagnostics detected).\";\r\n const llm_content = `> **File Path:** \\`${resolve(file_path)}\\`\\n\\n${ui_markdown}`;\r\n return {\r\n content: [{ type: 'text', text: llm_content }]\r\n };\r\n }\r\n\r\n const result = paginate(appendix, '');\r\n\r\n if (page < 1 || page > result.total_pages) {\r\n throw new Error(`Appendix page ${page} out of range (appendix has ${result.total_pages} pages).`);\r\n }\r\n\r\n const selected = result.pages[page - 1];\r\n\r\n let banner = '';\r\n let footer = '';\r\n\r\n if (selected.total_pages > 1) {\r\n banner = `> **Appendix page ${selected.page} of ${selected.total_pages}** — structural metadata for this document.\\n\\n---\\n\\n`;\r\n footer = selected.has_next ? `\\n\\n---\\n\\n> **Continues on appendix page ${selected.page + 1} of ${selected.total_pages}.**` : '';\r\n } else {\r\n banner = \"> **Appendix** — structural metadata for this document.\\n\\n---\\n\\n\";\r\n }\r\n\r\n const ui_markdown = banner + selected.page_content + footer;\r\n const llm_content = `> **File Path:** \\`${resolve(file_path)}\\`\\n\\n${ui_markdown}`;\r\n\r\n return {\r\n content: [{ type: 'text', text: llm_content }]\r\n };\r\n}"],"mappings":";AAAA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,uBAAuB,8BAA8B;AAC9D,SAAS,oBAAoB;AAC7B,SAAS,YAAAA,WAAU,WAAAC,UAAS,SAAS,eAAe;AACpD;AAAA,EACE;AAAA,EACA;AAAA,EACA,kBAAAC;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACXP,SAAS,eAAyB;AAClC;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAQP,SAAS,wBAAwB,cAA+B;AAC9D,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO;AAAA;AAAA;AAAA;AAAA;AACT;AAEA,SAAS,mBAAmB,MAAc,OAAuB;AAC/D,MAAI,SAAS,EAAG,QAAO;AACvB,SAAO,YAAY,IAAI,OAAO,KAAK;AAAA;AAAA;AAAA;AAAA;AACrC;AAEA,SAAS,mBAAmB,MAAc,OAAe,UAA2B;AAClF,MAAI,SAAS,KAAK,CAAC,SAAU,QAAO;AACpC,SAAO;AAAA;AAAA;AAAA;AAAA,wBAAoC,OAAO,CAAC,OAAO,KAAK;AACjE;AAEO,SAAS,oBAAoB,OAAsB,YAAoB,GAAG,UAAmB,OAAe;AACjH,MAAI,CAAC,SAAS,MAAM,WAAW,GAAG;AAChC,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,MAAM,OAAO,OAAK,EAAE,SAAS,SAAS;AAEtD,MAAI,QAAQ,WAAW,GAAG;AACxB,WAAO,8BAA8B,SAAS;AAAA;AAAA,eAAqB,MAAM,MAAM;AAAA,EACjF;AAEA,QAAM,QAAkB,CAAC;AACzB,aAAW,QAAQ,SAAS;AAC1B,UAAM,SAAS,IAAI,OAAO,KAAK,KAAK;AACpC,QAAI,SAAS;AACX,YAAM,aAAa,CA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["../src/index.ts","../src/response-builders.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';\nimport { readFileSync } from 'node:fs';\nimport { basename, resolve, extname, dirname } from 'node:path';\nimport { \n identifyEngine, \n extractTextFromBuffer, \n DocumentObject, \n RedlineEngine, \n BatchValidationError \n} from '@adeu/core';\nimport { \n build_paginated_response, \n build_outline_response, \n build_appendix_response \n} from './response-builders.js';\n\n// --- Tool Description Constants (Parity with Python) ---\nconst READ_DOCX_COMMON_DESC = \"Reads a DOCX file. Returns text with inline CriticMarkup for Tracked Changes and Comments: {++inserted++}, {--deleted--}, {==highlighted==}{>>comment<<}. Set clean_view=True for the finalized 'Accepted' text without markup.\\n\\n\";\nconst READ_DOCX_TAIL = \"Modes:\\n- 'full' (default): paginated body content. Use page=N to navigate.\\n- 'outline': heading map only — start here for large docs to plan targeted reads. Defaults to L1-L2 headings; pass outline_max_level=3-6 to see deeper structure.\\n- 'appendix': defined terms, anchors, and cross-reference targets. Consult before editing legal/technical docs to avoid breaking references.\";\n\nconst PROCESS_BATCH_COMMON_DESC = \"Applies a batch of edits and review actions to a DOCX.\\n\\nAll changes evaluate against the ORIGINAL document state — do not chain dependent edits within one batch (e.g. rename X to Y, then modify Y). Apply the rename first, then send a second batch.\\n\\n\";\nconst PROCESS_BATCH_OPERATIONS_DESC = \"Each item in `changes` must specify a `type`:\\n1. 'modify': Search-and-replace. `target_text` must uniquely match — include surrounding context if the phrase is ambiguous. `new_text` supports Markdown: '# Heading 1' through '###### Heading 6', '**bold**', '_italic_', and '\\\\n\\\\n' to split into multiple paragraphs. Empty `new_text` deletes. Do NOT write CriticMarkup tags ({++, {--, {>>) manually — use the `comment` parameter for comments.\\n2. 'accept' / 'reject': Finalize or revert a tracked change by `target_id` (e.g. 'Chg:12').\\n3. 'reply': Reply to a comment by `target_id` (e.g. 'Com:5') with `text`.\\n4. 'insert_row' / 'delete_row': Table edits. Disk mode only — not supported on Live Word canvas.\\n\\nID VOLATILITY: 'Chg:N' and 'Com:N' shift between document states. Always call `read_docx` immediately before any accept/reject/reply — do not reuse IDs from earlier in the conversation.\\n\\n`author_name` is used for attribution on all tracked changes and comments, in both disk and Live Word modes.\";\n\n// --- Server Setup ---\nconst server = new Server(\n {\n name: 'adeu-redlining-service',\n version: '1.0.0',\n },\n {\n capabilities: {\n tools: {},\n },\n }\n);\n\n// --- Tool Registration ---\nserver.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: [\n {\n name: 'read_docx',\n description: READ_DOCX_COMMON_DESC + READ_DOCX_TAIL,\n inputSchema: {\n type: 'object',\n properties: {\n file_path: { type: 'string', description: 'Absolute path to the DOCX file.' },\n clean_view: { type: 'boolean', description: \"If False (default), returns the 'Raw' text with inline CriticMarkup. If True, returns 'Accepted' text.\", default: false },\n mode: { type: 'string', enum: ['full', 'outline', 'appendix'], description: \"'full' returns body content. 'outline' returns a structural heading map. 'appendix' returns defined terms.\", default: 'full' },\n page: { type: 'number', description: 'Page number (1-indexed) for mode=\\'full\\'. Defaults to 1.', default: 1 },\n outline_max_level: { type: 'number', description: 'For mode=\\'outline\\' only: cap on heading depth.', default: 2 },\n outline_verbose: { type: 'boolean', description: 'For mode=\\'outline\\' only: includes metadata.', default: false }\n },\n required: ['file_path']\n }\n },\n {\n name: 'process_document_batch',\n description: PROCESS_BATCH_COMMON_DESC + PROCESS_BATCH_OPERATIONS_DESC,\n inputSchema: {\n type: 'object',\n properties: {\n original_docx_path: { type: 'string', description: 'Absolute path to the source file.' },\n author_name: { type: 'string', description: \"Name to appear in Track Changes (e.g., 'Reviewer AI').\" },\n changes: { \n type: 'array', \n description: \"List of changes to apply. Each change must specify 'type'.\",\n items: { type: 'object' } \n },\n output_path: { type: 'string', description: 'Optional output path.' }\n },\n required: ['original_docx_path', 'author_name', 'changes']\n }\n },\n {\n name: 'accept_all_changes',\n description: \"Accepts all tracked changes and removes all comments in a single operation, producing a finalized clean document. Use this when a document review is entirely complete and you want to clear all redlines.\",\n inputSchema: {\n type: 'object',\n properties: {\n docx_path: { type: 'string', description: 'Absolute path to the DOCX file.' },\n output_path: { type: 'string', description: 'Optional output path.' }\n },\n required: ['docx_path']\n }\n }\n ]\n };\n});\n\n// --- Tool Execution ---\nserver.setRequestHandler(CallToolRequestSchema, async (request): Promise<any> => {\n const { name, arguments: args } = request.params;\n\n try {\n if (name === 'read_docx') {\n const filePath = args?.file_path as string;\n const cleanView = args?.clean_view as boolean ?? false;\n const mode = args?.mode as string ?? 'full';\n const page = args?.page as number ?? 1;\n const outline_max_level = args?.outline_max_level as number ?? 2;\n const outline_verbose = args?.outline_verbose as boolean ?? false;\n \n const buf = readFileSync(filePath);\n const text = await extractTextFromBuffer(buf, cleanView);\n \n if (mode === 'outline') {\n const doc = await DocumentObject.load(buf);\n return build_outline_response(doc, text, filePath, outline_max_level, outline_verbose);\n }\n if (mode === 'appendix') {\n return build_appendix_response(text, page, filePath);\n }\n return build_paginated_response(text, page, filePath);\n }\n\n if (name === 'process_document_batch') {\n const origPath = args?.original_docx_path as string;\n const authorName = args?.author_name as string;\n const changes = args?.changes as any[];\n let outPath = args?.output_path as string;\n\n if (!outPath) {\n const ext = extname(origPath);\n const base = basename(origPath, ext);\n const dir = dirname(origPath);\n outPath = resolve(dir, `${base}_processed${ext}`);\n }\n\n const buf = readFileSync(origPath);\n const doc = await DocumentObject.load(buf);\n const engine = new RedlineEngine(doc, authorName);\n \n let stats;\n try {\n stats = engine.process_batch(changes);\n } catch (e) {\n if (e instanceof BatchValidationError) {\n return {\n content: [{ type: 'text', text: `Batch rejected. Some edits failed validation:\\n\\n${(e as BatchValidationError).errors.join('\\n\\n')}` }],\n isError: true\n };\n }\n throw e;\n }\n\n const outBuf = await doc.save();\n // Using dynamic import of fs/promises or just sync write\n const fs = await import('node:fs');\n fs.writeFileSync(outPath, outBuf);\n\n let res = `Batch complete. Saved to: ${outPath}\\nActions: ${stats.actions_applied} applied, ${stats.actions_skipped} skipped.\\nEdits: ${stats.edits_applied} applied, ${stats.edits_skipped} skipped.`;\n if (stats.skipped_details?.length > 0) {\n res += `\\n\\nSkipped Details:\\n${stats.skipped_details.join('\\n')}`;\n }\n\n return {\n content: [{ type: 'text', text: res }]\n };\n }\n\n if (name === 'accept_all_changes') {\n const docxPath = args?.docx_path as string;\n let outPath = args?.output_path as string;\n\n if (!outPath) {\n const ext = extname(docxPath);\n const base = basename(docxPath, ext);\n const dir = dirname(docxPath);\n outPath = resolve(dir, `${base}_clean${ext}`);\n }\n\n const buf = readFileSync(docxPath);\n const doc = await DocumentObject.load(buf);\n const engine = new RedlineEngine(doc);\n \n // We implement the public facing accept_all wrapper from python\n engine.accept_all_revisions();\n \n const outBuf = await doc.save();\n const fs = await import('node:fs');\n fs.writeFileSync(outPath, outBuf);\n\n return {\n content: [{ type: 'text', text: `Accepted all changes. Saved to: ${outPath}` }]\n };\n }\n\n throw new Error(`Unknown tool: ${name}`);\n\n } catch (error: any) {\n return {\n content: [{ type: 'text', text: `Error executing tool ${name}: ${error.message}` }],\n isError: true,\n };\n }\n});\n\n// --- Startup ---\nasync function main() {\n const transport = new StdioServerTransport();\n await server.connect(transport);\n console.error(`Adeu MCP Server (Node.js Engine: ${identifyEngine()}) running on stdio`);\n}\n\nmain().catch(console.error);","import { resolve, basename } from 'node:path';\nimport { \n DocumentObject, \n paginate, \n split_structural_appendix, \n extract_outline, \n OutlineNode \n} from '@adeu/core';\n\nexport interface ToolResult {\n content: { type: 'text'; text: string }[];\n isError?: boolean;\n [key: string]: unknown;\n}\n\nfunction _build_appendix_pointer(has_appendix: boolean): string {\n if (!has_appendix) return '';\n return `\\n\\n---\\n\\n> **Appendix available.** This document has structural metadata (defined terms, cross-references, bookmarks, diagnostics) that may be relevant when editing. Call \\`read_docx\\` with \\`mode='appendix'\\` to load it before submitting edits.`;\n}\n\nfunction _build_page_banner(page: number, total: number): string {\n if (total <= 1) return '';\n return `> **Page ${page} of ${total}** — call \\`read_docx\\` with \\`mode='outline'\\` for a heading map of the full document.\\n\\n---\\n\\n`;\n}\n\nfunction _build_page_footer(page: number, total: number, has_next: boolean): string {\n if (total <= 1 || !has_next) return '';\n return `\\n\\n---\\n\\n> **Continues on page ${page + 1} of ${total}.**`;\n}\n\nexport function render_outline_tree(nodes: OutlineNode[], max_level: number = 2, verbose: boolean = false): string {\n if (!nodes || nodes.length === 0) {\n return '# (No headings detected)\\n\\nThis document has no detectable headings.';\n }\n\n const visible = nodes.filter(n => n.level <= max_level);\n\n if (visible.length === 0) {\n return `# (No headings at level <= ${max_level})\\n\\nDocument has ${nodes.length} headings, all at deeper levels. Call read_docx with mode='outline' and outline_max_level=N (up to 6) to see them.`;\n }\n\n const lines: string[] = [];\n for (const node of visible) {\n const prefix = '#'.repeat(node.level);\n if (verbose) {\n const meta_parts = [`p${node.page}`, node.style];\n if (node.has_table) meta_parts.push('has table');\n if (node.footnote_ids && node.footnote_ids.length > 0) meta_parts.push('fn:' + node.footnote_ids.join(','));\n lines.push(`${prefix} ${node.text} (${meta_parts.join(', ')})`);\n } else {\n lines.push(`${prefix} ${node.text} (p${node.page})`);\n }\n }\n return lines.join('\\n');\n}\n\nexport function build_paginated_response(text: string, page: number, file_path: string): ToolResult {\n const [body, appendix] = split_structural_appendix(text);\n const has_appendix = Boolean(appendix.trim());\n\n const result = paginate(body, '');\n\n if (page < 1 || page > result.total_pages) {\n throw new Error(`Page ${page} out of range (doc has ${result.total_pages} pages).`);\n }\n\n const selected = result.pages[page - 1];\n const banner = _build_page_banner(selected.page, selected.total_pages);\n const footer = _build_page_footer(selected.page, selected.total_pages, selected.has_next);\n const appendix_pointer = _build_appendix_pointer(has_appendix);\n \n const ui_markdown = banner + selected.page_content + footer + appendix_pointer;\n const llm_content = `> **File Path:** \\`${resolve(file_path)}\\`\\n\\n${ui_markdown}`;\n\n return {\n content: [{ type: 'text', text: llm_content }]\n };\n}\n\nexport function build_outline_response(\n doc: DocumentObject, \n projected_text: string, \n file_path: string, \n outline_max_level: number = 2, \n outline_verbose: boolean = false\n): ToolResult {\n const [body] = split_structural_appendix(projected_text);\n const pagination_result = paginate(body, '');\n\n const nodes = extract_outline(\n doc,\n body,\n pagination_result.body_pages,\n pagination_result.body_page_offsets\n );\n\n const rendered = render_outline_tree(nodes, outline_max_level, outline_verbose);\n\n const visible_count = nodes.filter(n => n.level <= outline_max_level).length;\n const deeper_count = nodes.length - visible_count;\n const deeper_hint = deeper_count > 0 ? ` (${deeper_count} more at deeper levels, raise outline_max_level to see)` : '';\n\n const header = `> **Outline view** — showing ${visible_count} of ${nodes.length} headings (L1-L${outline_max_level}${deeper_hint}) across ${pagination_result.total_pages} page(s). Call \\`read_docx\\` with \\`mode='full'\\` and \\`page=N\\` to read a section.\\n\\n---\\n\\n`;\n const ui_markdown = header + rendered;\n const llm_content = `> **File Path:** \\`${resolve(file_path)}\\`\\n\\n${ui_markdown}`;\n\n return {\n content: [{ type: 'text', text: llm_content }]\n };\n}\n\nexport function build_appendix_response(text: string, page: number, file_path: string): ToolResult {\n const [, appendix] = split_structural_appendix(text);\n\n if (!appendix.trim()) {\n const ui_markdown = \"# Appendix\\n\\nThis document has no structural appendix (no defined terms, named anchors, or diagnostics detected).\";\n const llm_content = `> **File Path:** \\`${resolve(file_path)}\\`\\n\\n${ui_markdown}`;\n return {\n content: [{ type: 'text', text: llm_content }]\n };\n }\n\n const result = paginate(appendix, '');\n\n if (page < 1 || page > result.total_pages) {\n throw new Error(`Appendix page ${page} out of range (appendix has ${result.total_pages} pages).`);\n }\n\n const selected = result.pages[page - 1];\n\n let banner = '';\n let footer = '';\n\n if (selected.total_pages > 1) {\n banner = `> **Appendix page ${selected.page} of ${selected.total_pages}** — structural metadata for this document.\\n\\n---\\n\\n`;\n footer = selected.has_next ? `\\n\\n---\\n\\n> **Continues on appendix page ${selected.page + 1} of ${selected.total_pages}.**` : '';\n } else {\n banner = \"> **Appendix** — structural metadata for this document.\\n\\n---\\n\\n\";\n }\n\n const ui_markdown = banner + selected.page_content + footer;\n const llm_content = `> **File Path:** \\`${resolve(file_path)}\\`\\n\\n${ui_markdown}`;\n\n return {\n content: [{ type: 'text', text: llm_content }]\n };\n}"],"mappings":";;;AAAA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,uBAAuB,8BAA8B;AAC9D,SAAS,oBAAoB;AAC7B,SAAS,YAAAA,WAAU,WAAAC,UAAS,SAAS,eAAe;AACpD;AAAA,EACE;AAAA,EACA;AAAA,EACA,kBAAAC;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACXP,SAAS,eAAyB;AAClC;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAQP,SAAS,wBAAwB,cAA+B;AAC9D,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO;AAAA;AAAA;AAAA;AAAA;AACT;AAEA,SAAS,mBAAmB,MAAc,OAAuB;AAC/D,MAAI,SAAS,EAAG,QAAO;AACvB,SAAO,YAAY,IAAI,OAAO,KAAK;AAAA;AAAA;AAAA;AAAA;AACrC;AAEA,SAAS,mBAAmB,MAAc,OAAe,UAA2B;AAClF,MAAI,SAAS,KAAK,CAAC,SAAU,QAAO;AACpC,SAAO;AAAA;AAAA;AAAA;AAAA,wBAAoC,OAAO,CAAC,OAAO,KAAK;AACjE;AAEO,SAAS,oBAAoB,OAAsB,YAAoB,GAAG,UAAmB,OAAe;AACjH,MAAI,CAAC,SAAS,MAAM,WAAW,GAAG;AAChC,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,MAAM,OAAO,OAAK,EAAE,SAAS,SAAS;AAEtD,MAAI,QAAQ,WAAW,GAAG;AACxB,WAAO,8BAA8B,SAAS;AAAA;AAAA,eAAqB,MAAM,MAAM;AAAA,EACjF;AAEA,QAAM,QAAkB,CAAC;AACzB,aAAW,QAAQ,SAAS;AAC1B,UAAM,SAAS,IAAI,OAAO,KAAK,KAAK;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","basename","resolve"]}
|
package/package.json
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@adeu/mcp-server",
|
|
3
|
-
"version": "1.6.
|
|
4
|
-
"description": "",
|
|
5
|
-
"main": "./dist/index.js",
|
|
6
|
-
"types": "./dist/index.d.ts",
|
|
7
|
-
"bin": {
|
|
8
|
-
"adeu-mcp-server": "./dist/index.js"
|
|
9
|
-
},
|
|
10
|
-
"devDependencies": {},
|
|
11
|
-
"scripts": {
|
|
12
|
-
"build": "tsup",
|
|
13
|
-
"test": "vitest run",
|
|
14
|
-
"start": "node ./dist/index.js"
|
|
15
|
-
},
|
|
16
|
-
"repository": {
|
|
17
|
-
"type": "git",
|
|
18
|
-
"url": "https://github.com/dealfluence/adeu.git",
|
|
19
|
-
"directory": "node/packages/mcp-server"
|
|
20
|
-
},
|
|
21
|
-
"publishConfig": {
|
|
22
|
-
"access": "public"
|
|
23
|
-
},
|
|
24
|
-
"author": "Mikko Korpela <mikko@adeu.ai>",
|
|
25
|
-
"license": "MIT",
|
|
26
|
-
"type": "module",
|
|
27
|
-
"dependencies": {
|
|
28
|
-
"@adeu/core": "^1.0.0",
|
|
29
|
-
"@modelcontextprotocol/sdk": "^1.0.0"
|
|
30
|
-
}
|
|
31
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@adeu/mcp-server",
|
|
3
|
+
"version": "1.6.5",
|
|
4
|
+
"description": "",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"types": "./dist/index.d.ts",
|
|
7
|
+
"bin": {
|
|
8
|
+
"adeu-mcp-server": "./dist/index.js"
|
|
9
|
+
},
|
|
10
|
+
"devDependencies": {},
|
|
11
|
+
"scripts": {
|
|
12
|
+
"build": "tsup",
|
|
13
|
+
"test": "vitest run",
|
|
14
|
+
"start": "node ./dist/index.js"
|
|
15
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "https://github.com/dealfluence/adeu.git",
|
|
19
|
+
"directory": "node/packages/mcp-server"
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"author": "Mikko Korpela <mikko@adeu.ai>",
|
|
25
|
+
"license": "MIT",
|
|
26
|
+
"type": "module",
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@adeu/core": "^1.0.0",
|
|
29
|
+
"@modelcontextprotocol/sdk": "^1.0.0"
|
|
30
|
+
}
|
|
31
|
+
}
|
package/src/index.test.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { describe, it, expect } from 'vitest';
|
|
2
|
-
|
|
3
|
-
describe('MCP Server', () => {
|
|
4
|
-
it('should have a passing dummy test', () => {
|
|
5
|
-
expect(true).toBe(true);
|
|
6
|
-
});
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
|
|
3
|
+
describe('MCP Server', () => {
|
|
4
|
+
it('should have a passing dummy test', () => {
|
|
5
|
+
expect(true).toBe(true);
|
|
6
|
+
});
|
|
7
7
|
});
|
package/src/index.ts
CHANGED
|
@@ -1,208 +1,208 @@
|
|
|
1
|
-
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
|
-
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
|
-
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
4
|
-
import { readFileSync } from 'node:fs';
|
|
5
|
-
import { basename, resolve, extname, dirname } from 'node:path';
|
|
6
|
-
import {
|
|
7
|
-
identifyEngine,
|
|
8
|
-
extractTextFromBuffer,
|
|
9
|
-
DocumentObject,
|
|
10
|
-
RedlineEngine,
|
|
11
|
-
BatchValidationError
|
|
12
|
-
} from '@adeu/core';
|
|
13
|
-
import {
|
|
14
|
-
build_paginated_response,
|
|
15
|
-
build_outline_response,
|
|
16
|
-
build_appendix_response
|
|
17
|
-
} from './response-builders.js';
|
|
18
|
-
|
|
19
|
-
// --- Tool Description Constants (Parity with Python) ---
|
|
20
|
-
const READ_DOCX_COMMON_DESC = "Reads a DOCX file. Returns text with inline CriticMarkup for Tracked Changes and Comments: {++inserted++}, {--deleted--}, {==highlighted==}{>>comment<<}. Set clean_view=True for the finalized 'Accepted' text without markup.\n\n";
|
|
21
|
-
const READ_DOCX_TAIL = "Modes:\n- 'full' (default): paginated body content. Use page=N to navigate.\n- 'outline': heading map only — start here for large docs to plan targeted reads. Defaults to L1-L2 headings; pass outline_max_level=3-6 to see deeper structure.\n- 'appendix': defined terms, anchors, and cross-reference targets. Consult before editing legal/technical docs to avoid breaking references.";
|
|
22
|
-
|
|
23
|
-
const PROCESS_BATCH_COMMON_DESC = "Applies a batch of edits and review actions to a DOCX.\n\nAll changes evaluate against the ORIGINAL document state — do not chain dependent edits within one batch (e.g. rename X to Y, then modify Y). Apply the rename first, then send a second batch.\n\n";
|
|
24
|
-
const PROCESS_BATCH_OPERATIONS_DESC = "Each item in `changes` must specify a `type`:\n1. 'modify': Search-and-replace. `target_text` must uniquely match — include surrounding context if the phrase is ambiguous. `new_text` supports Markdown: '# Heading 1' through '###### Heading 6', '**bold**', '_italic_', and '\\n\\n' to split into multiple paragraphs. Empty `new_text` deletes. Do NOT write CriticMarkup tags ({++, {--, {>>) manually — use the `comment` parameter for comments.\n2. 'accept' / 'reject': Finalize or revert a tracked change by `target_id` (e.g. 'Chg:12').\n3. 'reply': Reply to a comment by `target_id` (e.g. 'Com:5') with `text`.\n4. 'insert_row' / 'delete_row': Table edits. Disk mode only — not supported on Live Word canvas.\n\nID VOLATILITY: 'Chg:N' and 'Com:N' shift between document states. Always call `read_docx` immediately before any accept/reject/reply — do not reuse IDs from earlier in the conversation.\n\n`author_name` is used for attribution on all tracked changes and comments, in both disk and Live Word modes.";
|
|
25
|
-
|
|
26
|
-
// --- Server Setup ---
|
|
27
|
-
const server = new Server(
|
|
28
|
-
{
|
|
29
|
-
name: 'adeu-redlining-service',
|
|
30
|
-
version: '1.0.0',
|
|
31
|
-
},
|
|
32
|
-
{
|
|
33
|
-
capabilities: {
|
|
34
|
-
tools: {},
|
|
35
|
-
},
|
|
36
|
-
}
|
|
37
|
-
);
|
|
38
|
-
|
|
39
|
-
// --- Tool Registration ---
|
|
40
|
-
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
41
|
-
return {
|
|
42
|
-
tools: [
|
|
43
|
-
{
|
|
44
|
-
name: 'read_docx',
|
|
45
|
-
description: READ_DOCX_COMMON_DESC + READ_DOCX_TAIL,
|
|
46
|
-
inputSchema: {
|
|
47
|
-
type: 'object',
|
|
48
|
-
properties: {
|
|
49
|
-
file_path: { type: 'string', description: 'Absolute path to the DOCX file.' },
|
|
50
|
-
clean_view: { type: 'boolean', description: "If False (default), returns the 'Raw' text with inline CriticMarkup. If True, returns 'Accepted' text.", default: false },
|
|
51
|
-
mode: { type: 'string', enum: ['full', 'outline', 'appendix'], description: "'full' returns body content. 'outline' returns a structural heading map. 'appendix' returns defined terms.", default: 'full' },
|
|
52
|
-
page: { type: 'number', description: 'Page number (1-indexed) for mode=\'full\'. Defaults to 1.', default: 1 },
|
|
53
|
-
outline_max_level: { type: 'number', description: 'For mode=\'outline\' only: cap on heading depth.', default: 2 },
|
|
54
|
-
outline_verbose: { type: 'boolean', description: 'For mode=\'outline\' only: includes metadata.', default: false }
|
|
55
|
-
},
|
|
56
|
-
required: ['file_path']
|
|
57
|
-
}
|
|
58
|
-
},
|
|
59
|
-
{
|
|
60
|
-
name: 'process_document_batch',
|
|
61
|
-
description: PROCESS_BATCH_COMMON_DESC + PROCESS_BATCH_OPERATIONS_DESC,
|
|
62
|
-
inputSchema: {
|
|
63
|
-
type: 'object',
|
|
64
|
-
properties: {
|
|
65
|
-
original_docx_path: { type: 'string', description: 'Absolute path to the source file.' },
|
|
66
|
-
author_name: { type: 'string', description: "Name to appear in Track Changes (e.g., 'Reviewer AI')." },
|
|
67
|
-
changes: {
|
|
68
|
-
type: 'array',
|
|
69
|
-
description: "List of changes to apply. Each change must specify 'type'.",
|
|
70
|
-
items: { type: 'object' }
|
|
71
|
-
},
|
|
72
|
-
output_path: { type: 'string', description: 'Optional output path.' }
|
|
73
|
-
},
|
|
74
|
-
required: ['original_docx_path', 'author_name', 'changes']
|
|
75
|
-
}
|
|
76
|
-
},
|
|
77
|
-
{
|
|
78
|
-
name: 'accept_all_changes',
|
|
79
|
-
description: "Accepts all tracked changes and removes all comments in a single operation, producing a finalized clean document. Use this when a document review is entirely complete and you want to clear all redlines.",
|
|
80
|
-
inputSchema: {
|
|
81
|
-
type: 'object',
|
|
82
|
-
properties: {
|
|
83
|
-
docx_path: { type: 'string', description: 'Absolute path to the DOCX file.' },
|
|
84
|
-
output_path: { type: 'string', description: 'Optional output path.' }
|
|
85
|
-
},
|
|
86
|
-
required: ['docx_path']
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
]
|
|
90
|
-
};
|
|
91
|
-
});
|
|
92
|
-
|
|
93
|
-
// --- Tool Execution ---
|
|
94
|
-
server.setRequestHandler(CallToolRequestSchema, async (request): Promise<any> => {
|
|
95
|
-
const { name, arguments: args } = request.params;
|
|
96
|
-
|
|
97
|
-
try {
|
|
98
|
-
if (name === 'read_docx') {
|
|
99
|
-
const filePath = args?.file_path as string;
|
|
100
|
-
const cleanView = args?.clean_view as boolean ?? false;
|
|
101
|
-
const mode = args?.mode as string ?? 'full';
|
|
102
|
-
const page = args?.page as number ?? 1;
|
|
103
|
-
const outline_max_level = args?.outline_max_level as number ?? 2;
|
|
104
|
-
const outline_verbose = args?.outline_verbose as boolean ?? false;
|
|
105
|
-
|
|
106
|
-
const buf = readFileSync(filePath);
|
|
107
|
-
const text = await extractTextFromBuffer(buf, cleanView);
|
|
108
|
-
|
|
109
|
-
if (mode === 'outline') {
|
|
110
|
-
const doc = await DocumentObject.load(buf);
|
|
111
|
-
return build_outline_response(doc, text, filePath, outline_max_level, outline_verbose);
|
|
112
|
-
}
|
|
113
|
-
if (mode === 'appendix') {
|
|
114
|
-
return build_appendix_response(text, page, filePath);
|
|
115
|
-
}
|
|
116
|
-
return build_paginated_response(text, page, filePath);
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
if (name === 'process_document_batch') {
|
|
120
|
-
const origPath = args?.original_docx_path as string;
|
|
121
|
-
const authorName = args?.author_name as string;
|
|
122
|
-
const changes = args?.changes as any[];
|
|
123
|
-
let outPath = args?.output_path as string;
|
|
124
|
-
|
|
125
|
-
if (!outPath) {
|
|
126
|
-
const ext = extname(origPath);
|
|
127
|
-
const base = basename(origPath, ext);
|
|
128
|
-
const dir = dirname(origPath);
|
|
129
|
-
outPath = resolve(dir, `${base}_processed${ext}`);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
const buf = readFileSync(origPath);
|
|
133
|
-
const doc = await DocumentObject.load(buf);
|
|
134
|
-
const engine = new RedlineEngine(doc, authorName);
|
|
135
|
-
|
|
136
|
-
let stats;
|
|
137
|
-
try {
|
|
138
|
-
stats = engine.process_batch(changes);
|
|
139
|
-
} catch (e) {
|
|
140
|
-
if (e instanceof BatchValidationError) {
|
|
141
|
-
return {
|
|
142
|
-
content: [{ type: 'text', text: `Batch rejected. Some edits failed validation:\n\n${(e as BatchValidationError).errors.join('\n\n')}` }],
|
|
143
|
-
isError: true
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
throw e;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
const outBuf = await doc.save();
|
|
150
|
-
// Using dynamic import of fs/promises or just sync write
|
|
151
|
-
const fs = await import('node:fs');
|
|
152
|
-
fs.writeFileSync(outPath, outBuf);
|
|
153
|
-
|
|
154
|
-
let res = `Batch complete. Saved to: ${outPath}\nActions: ${stats.actions_applied} applied, ${stats.actions_skipped} skipped.\nEdits: ${stats.edits_applied} applied, ${stats.edits_skipped} skipped.`;
|
|
155
|
-
if (stats.skipped_details?.length > 0) {
|
|
156
|
-
res += `\n\nSkipped Details:\n${stats.skipped_details.join('\n')}`;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
return {
|
|
160
|
-
content: [{ type: 'text', text: res }]
|
|
161
|
-
};
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
if (name === 'accept_all_changes') {
|
|
165
|
-
const docxPath = args?.docx_path as string;
|
|
166
|
-
let outPath = args?.output_path as string;
|
|
167
|
-
|
|
168
|
-
if (!outPath) {
|
|
169
|
-
const ext = extname(docxPath);
|
|
170
|
-
const base = basename(docxPath, ext);
|
|
171
|
-
const dir = dirname(docxPath);
|
|
172
|
-
outPath = resolve(dir, `${base}_clean${ext}`);
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
const buf = readFileSync(docxPath);
|
|
176
|
-
const doc = await DocumentObject.load(buf);
|
|
177
|
-
const engine = new RedlineEngine(doc);
|
|
178
|
-
|
|
179
|
-
// We implement the public facing accept_all wrapper from python
|
|
180
|
-
engine.accept_all_revisions();
|
|
181
|
-
|
|
182
|
-
const outBuf = await doc.save();
|
|
183
|
-
const fs = await import('node:fs');
|
|
184
|
-
fs.writeFileSync(outPath, outBuf);
|
|
185
|
-
|
|
186
|
-
return {
|
|
187
|
-
content: [{ type: 'text', text: `Accepted all changes. Saved to: ${outPath}` }]
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
throw new Error(`Unknown tool: ${name}`);
|
|
192
|
-
|
|
193
|
-
} catch (error: any) {
|
|
194
|
-
return {
|
|
195
|
-
content: [{ type: 'text', text: `Error executing tool ${name}: ${error.message}` }],
|
|
196
|
-
isError: true,
|
|
197
|
-
};
|
|
198
|
-
}
|
|
199
|
-
});
|
|
200
|
-
|
|
201
|
-
// --- Startup ---
|
|
202
|
-
async function main() {
|
|
203
|
-
const transport = new StdioServerTransport();
|
|
204
|
-
await server.connect(transport);
|
|
205
|
-
console.error(`Adeu MCP Server (Node.js Engine: ${identifyEngine()}) running on stdio`);
|
|
206
|
-
}
|
|
207
|
-
|
|
1
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
4
|
+
import { readFileSync } from 'node:fs';
|
|
5
|
+
import { basename, resolve, extname, dirname } from 'node:path';
|
|
6
|
+
import {
|
|
7
|
+
identifyEngine,
|
|
8
|
+
extractTextFromBuffer,
|
|
9
|
+
DocumentObject,
|
|
10
|
+
RedlineEngine,
|
|
11
|
+
BatchValidationError
|
|
12
|
+
} from '@adeu/core';
|
|
13
|
+
import {
|
|
14
|
+
build_paginated_response,
|
|
15
|
+
build_outline_response,
|
|
16
|
+
build_appendix_response
|
|
17
|
+
} from './response-builders.js';
|
|
18
|
+
|
|
19
|
+
// --- Tool Description Constants (Parity with Python) ---
|
|
20
|
+
const READ_DOCX_COMMON_DESC = "Reads a DOCX file. Returns text with inline CriticMarkup for Tracked Changes and Comments: {++inserted++}, {--deleted--}, {==highlighted==}{>>comment<<}. Set clean_view=True for the finalized 'Accepted' text without markup.\n\n";
|
|
21
|
+
const READ_DOCX_TAIL = "Modes:\n- 'full' (default): paginated body content. Use page=N to navigate.\n- 'outline': heading map only — start here for large docs to plan targeted reads. Defaults to L1-L2 headings; pass outline_max_level=3-6 to see deeper structure.\n- 'appendix': defined terms, anchors, and cross-reference targets. Consult before editing legal/technical docs to avoid breaking references.";
|
|
22
|
+
|
|
23
|
+
const PROCESS_BATCH_COMMON_DESC = "Applies a batch of edits and review actions to a DOCX.\n\nAll changes evaluate against the ORIGINAL document state — do not chain dependent edits within one batch (e.g. rename X to Y, then modify Y). Apply the rename first, then send a second batch.\n\n";
|
|
24
|
+
const PROCESS_BATCH_OPERATIONS_DESC = "Each item in `changes` must specify a `type`:\n1. 'modify': Search-and-replace. `target_text` must uniquely match — include surrounding context if the phrase is ambiguous. `new_text` supports Markdown: '# Heading 1' through '###### Heading 6', '**bold**', '_italic_', and '\\n\\n' to split into multiple paragraphs. Empty `new_text` deletes. Do NOT write CriticMarkup tags ({++, {--, {>>) manually — use the `comment` parameter for comments.\n2. 'accept' / 'reject': Finalize or revert a tracked change by `target_id` (e.g. 'Chg:12').\n3. 'reply': Reply to a comment by `target_id` (e.g. 'Com:5') with `text`.\n4. 'insert_row' / 'delete_row': Table edits. Disk mode only — not supported on Live Word canvas.\n\nID VOLATILITY: 'Chg:N' and 'Com:N' shift between document states. Always call `read_docx` immediately before any accept/reject/reply — do not reuse IDs from earlier in the conversation.\n\n`author_name` is used for attribution on all tracked changes and comments, in both disk and Live Word modes.";
|
|
25
|
+
|
|
26
|
+
// --- Server Setup ---
|
|
27
|
+
const server = new Server(
|
|
28
|
+
{
|
|
29
|
+
name: 'adeu-redlining-service',
|
|
30
|
+
version: '1.0.0',
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
capabilities: {
|
|
34
|
+
tools: {},
|
|
35
|
+
},
|
|
36
|
+
}
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
// --- Tool Registration ---
|
|
40
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
41
|
+
return {
|
|
42
|
+
tools: [
|
|
43
|
+
{
|
|
44
|
+
name: 'read_docx',
|
|
45
|
+
description: READ_DOCX_COMMON_DESC + READ_DOCX_TAIL,
|
|
46
|
+
inputSchema: {
|
|
47
|
+
type: 'object',
|
|
48
|
+
properties: {
|
|
49
|
+
file_path: { type: 'string', description: 'Absolute path to the DOCX file.' },
|
|
50
|
+
clean_view: { type: 'boolean', description: "If False (default), returns the 'Raw' text with inline CriticMarkup. If True, returns 'Accepted' text.", default: false },
|
|
51
|
+
mode: { type: 'string', enum: ['full', 'outline', 'appendix'], description: "'full' returns body content. 'outline' returns a structural heading map. 'appendix' returns defined terms.", default: 'full' },
|
|
52
|
+
page: { type: 'number', description: 'Page number (1-indexed) for mode=\'full\'. Defaults to 1.', default: 1 },
|
|
53
|
+
outline_max_level: { type: 'number', description: 'For mode=\'outline\' only: cap on heading depth.', default: 2 },
|
|
54
|
+
outline_verbose: { type: 'boolean', description: 'For mode=\'outline\' only: includes metadata.', default: false }
|
|
55
|
+
},
|
|
56
|
+
required: ['file_path']
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
name: 'process_document_batch',
|
|
61
|
+
description: PROCESS_BATCH_COMMON_DESC + PROCESS_BATCH_OPERATIONS_DESC,
|
|
62
|
+
inputSchema: {
|
|
63
|
+
type: 'object',
|
|
64
|
+
properties: {
|
|
65
|
+
original_docx_path: { type: 'string', description: 'Absolute path to the source file.' },
|
|
66
|
+
author_name: { type: 'string', description: "Name to appear in Track Changes (e.g., 'Reviewer AI')." },
|
|
67
|
+
changes: {
|
|
68
|
+
type: 'array',
|
|
69
|
+
description: "List of changes to apply. Each change must specify 'type'.",
|
|
70
|
+
items: { type: 'object' }
|
|
71
|
+
},
|
|
72
|
+
output_path: { type: 'string', description: 'Optional output path.' }
|
|
73
|
+
},
|
|
74
|
+
required: ['original_docx_path', 'author_name', 'changes']
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
name: 'accept_all_changes',
|
|
79
|
+
description: "Accepts all tracked changes and removes all comments in a single operation, producing a finalized clean document. Use this when a document review is entirely complete and you want to clear all redlines.",
|
|
80
|
+
inputSchema: {
|
|
81
|
+
type: 'object',
|
|
82
|
+
properties: {
|
|
83
|
+
docx_path: { type: 'string', description: 'Absolute path to the DOCX file.' },
|
|
84
|
+
output_path: { type: 'string', description: 'Optional output path.' }
|
|
85
|
+
},
|
|
86
|
+
required: ['docx_path']
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
]
|
|
90
|
+
};
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// --- Tool Execution ---
|
|
94
|
+
server.setRequestHandler(CallToolRequestSchema, async (request): Promise<any> => {
|
|
95
|
+
const { name, arguments: args } = request.params;
|
|
96
|
+
|
|
97
|
+
try {
|
|
98
|
+
if (name === 'read_docx') {
|
|
99
|
+
const filePath = args?.file_path as string;
|
|
100
|
+
const cleanView = args?.clean_view as boolean ?? false;
|
|
101
|
+
const mode = args?.mode as string ?? 'full';
|
|
102
|
+
const page = args?.page as number ?? 1;
|
|
103
|
+
const outline_max_level = args?.outline_max_level as number ?? 2;
|
|
104
|
+
const outline_verbose = args?.outline_verbose as boolean ?? false;
|
|
105
|
+
|
|
106
|
+
const buf = readFileSync(filePath);
|
|
107
|
+
const text = await extractTextFromBuffer(buf, cleanView);
|
|
108
|
+
|
|
109
|
+
if (mode === 'outline') {
|
|
110
|
+
const doc = await DocumentObject.load(buf);
|
|
111
|
+
return build_outline_response(doc, text, filePath, outline_max_level, outline_verbose);
|
|
112
|
+
}
|
|
113
|
+
if (mode === 'appendix') {
|
|
114
|
+
return build_appendix_response(text, page, filePath);
|
|
115
|
+
}
|
|
116
|
+
return build_paginated_response(text, page, filePath);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (name === 'process_document_batch') {
|
|
120
|
+
const origPath = args?.original_docx_path as string;
|
|
121
|
+
const authorName = args?.author_name as string;
|
|
122
|
+
const changes = args?.changes as any[];
|
|
123
|
+
let outPath = args?.output_path as string;
|
|
124
|
+
|
|
125
|
+
if (!outPath) {
|
|
126
|
+
const ext = extname(origPath);
|
|
127
|
+
const base = basename(origPath, ext);
|
|
128
|
+
const dir = dirname(origPath);
|
|
129
|
+
outPath = resolve(dir, `${base}_processed${ext}`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const buf = readFileSync(origPath);
|
|
133
|
+
const doc = await DocumentObject.load(buf);
|
|
134
|
+
const engine = new RedlineEngine(doc, authorName);
|
|
135
|
+
|
|
136
|
+
let stats;
|
|
137
|
+
try {
|
|
138
|
+
stats = engine.process_batch(changes);
|
|
139
|
+
} catch (e) {
|
|
140
|
+
if (e instanceof BatchValidationError) {
|
|
141
|
+
return {
|
|
142
|
+
content: [{ type: 'text', text: `Batch rejected. Some edits failed validation:\n\n${(e as BatchValidationError).errors.join('\n\n')}` }],
|
|
143
|
+
isError: true
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
throw e;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const outBuf = await doc.save();
|
|
150
|
+
// Using dynamic import of fs/promises or just sync write
|
|
151
|
+
const fs = await import('node:fs');
|
|
152
|
+
fs.writeFileSync(outPath, outBuf);
|
|
153
|
+
|
|
154
|
+
let res = `Batch complete. Saved to: ${outPath}\nActions: ${stats.actions_applied} applied, ${stats.actions_skipped} skipped.\nEdits: ${stats.edits_applied} applied, ${stats.edits_skipped} skipped.`;
|
|
155
|
+
if (stats.skipped_details?.length > 0) {
|
|
156
|
+
res += `\n\nSkipped Details:\n${stats.skipped_details.join('\n')}`;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
content: [{ type: 'text', text: res }]
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (name === 'accept_all_changes') {
|
|
165
|
+
const docxPath = args?.docx_path as string;
|
|
166
|
+
let outPath = args?.output_path as string;
|
|
167
|
+
|
|
168
|
+
if (!outPath) {
|
|
169
|
+
const ext = extname(docxPath);
|
|
170
|
+
const base = basename(docxPath, ext);
|
|
171
|
+
const dir = dirname(docxPath);
|
|
172
|
+
outPath = resolve(dir, `${base}_clean${ext}`);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const buf = readFileSync(docxPath);
|
|
176
|
+
const doc = await DocumentObject.load(buf);
|
|
177
|
+
const engine = new RedlineEngine(doc);
|
|
178
|
+
|
|
179
|
+
// We implement the public facing accept_all wrapper from python
|
|
180
|
+
engine.accept_all_revisions();
|
|
181
|
+
|
|
182
|
+
const outBuf = await doc.save();
|
|
183
|
+
const fs = await import('node:fs');
|
|
184
|
+
fs.writeFileSync(outPath, outBuf);
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
content: [{ type: 'text', text: `Accepted all changes. Saved to: ${outPath}` }]
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
192
|
+
|
|
193
|
+
} catch (error: any) {
|
|
194
|
+
return {
|
|
195
|
+
content: [{ type: 'text', text: `Error executing tool ${name}: ${error.message}` }],
|
|
196
|
+
isError: true,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
// --- Startup ---
|
|
202
|
+
async function main() {
|
|
203
|
+
const transport = new StdioServerTransport();
|
|
204
|
+
await server.connect(transport);
|
|
205
|
+
console.error(`Adeu MCP Server (Node.js Engine: ${identifyEngine()}) running on stdio`);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
208
|
main().catch(console.error);
|
package/src/response-builders.ts
CHANGED
|
@@ -1,147 +1,147 @@
|
|
|
1
|
-
import { resolve, basename } from 'node:path';
|
|
2
|
-
import {
|
|
3
|
-
DocumentObject,
|
|
4
|
-
paginate,
|
|
5
|
-
split_structural_appendix,
|
|
6
|
-
extract_outline,
|
|
7
|
-
OutlineNode
|
|
8
|
-
} from '@adeu/core';
|
|
9
|
-
|
|
10
|
-
export interface ToolResult {
|
|
11
|
-
content: { type: 'text'; text: string }[];
|
|
12
|
-
isError?: boolean;
|
|
13
|
-
[key: string]: unknown;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
function _build_appendix_pointer(has_appendix: boolean): string {
|
|
17
|
-
if (!has_appendix) return '';
|
|
18
|
-
return `\n\n---\n\n> **Appendix available.** This document has structural metadata (defined terms, cross-references, bookmarks, diagnostics) that may be relevant when editing. Call \`read_docx\` with \`mode='appendix'\` to load it before submitting edits.`;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function _build_page_banner(page: number, total: number): string {
|
|
22
|
-
if (total <= 1) return '';
|
|
23
|
-
return `> **Page ${page} of ${total}** — call \`read_docx\` with \`mode='outline'\` for a heading map of the full document.\n\n---\n\n`;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
function _build_page_footer(page: number, total: number, has_next: boolean): string {
|
|
27
|
-
if (total <= 1 || !has_next) return '';
|
|
28
|
-
return `\n\n---\n\n> **Continues on page ${page + 1} of ${total}.**`;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export function render_outline_tree(nodes: OutlineNode[], max_level: number = 2, verbose: boolean = false): string {
|
|
32
|
-
if (!nodes || nodes.length === 0) {
|
|
33
|
-
return '# (No headings detected)\n\nThis document has no detectable headings.';
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
const visible = nodes.filter(n => n.level <= max_level);
|
|
37
|
-
|
|
38
|
-
if (visible.length === 0) {
|
|
39
|
-
return `# (No headings at level <= ${max_level})\n\nDocument has ${nodes.length} headings, all at deeper levels. Call read_docx with mode='outline' and outline_max_level=N (up to 6) to see them.`;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
const lines: string[] = [];
|
|
43
|
-
for (const node of visible) {
|
|
44
|
-
const prefix = '#'.repeat(node.level);
|
|
45
|
-
if (verbose) {
|
|
46
|
-
const meta_parts = [`p${node.page}`, node.style];
|
|
47
|
-
if (node.has_table) meta_parts.push('has table');
|
|
48
|
-
if (node.footnote_ids && node.footnote_ids.length > 0) meta_parts.push('fn:' + node.footnote_ids.join(','));
|
|
49
|
-
lines.push(`${prefix} ${node.text} (${meta_parts.join(', ')})`);
|
|
50
|
-
} else {
|
|
51
|
-
lines.push(`${prefix} ${node.text} (p${node.page})`);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
return lines.join('\n');
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
export function build_paginated_response(text: string, page: number, file_path: string): ToolResult {
|
|
58
|
-
const [body, appendix] = split_structural_appendix(text);
|
|
59
|
-
const has_appendix = Boolean(appendix.trim());
|
|
60
|
-
|
|
61
|
-
const result = paginate(body, '');
|
|
62
|
-
|
|
63
|
-
if (page < 1 || page > result.total_pages) {
|
|
64
|
-
throw new Error(`Page ${page} out of range (doc has ${result.total_pages} pages).`);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
const selected = result.pages[page - 1];
|
|
68
|
-
const banner = _build_page_banner(selected.page, selected.total_pages);
|
|
69
|
-
const footer = _build_page_footer(selected.page, selected.total_pages, selected.has_next);
|
|
70
|
-
const appendix_pointer = _build_appendix_pointer(has_appendix);
|
|
71
|
-
|
|
72
|
-
const ui_markdown = banner + selected.page_content + footer + appendix_pointer;
|
|
73
|
-
const llm_content = `> **File Path:** \`${resolve(file_path)}\`\n\n${ui_markdown}`;
|
|
74
|
-
|
|
75
|
-
return {
|
|
76
|
-
content: [{ type: 'text', text: llm_content }]
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
export function build_outline_response(
|
|
81
|
-
doc: DocumentObject,
|
|
82
|
-
projected_text: string,
|
|
83
|
-
file_path: string,
|
|
84
|
-
outline_max_level: number = 2,
|
|
85
|
-
outline_verbose: boolean = false
|
|
86
|
-
): ToolResult {
|
|
87
|
-
const [body] = split_structural_appendix(projected_text);
|
|
88
|
-
const pagination_result = paginate(body, '');
|
|
89
|
-
|
|
90
|
-
const nodes = extract_outline(
|
|
91
|
-
doc,
|
|
92
|
-
body,
|
|
93
|
-
pagination_result.body_pages,
|
|
94
|
-
pagination_result.body_page_offsets
|
|
95
|
-
);
|
|
96
|
-
|
|
97
|
-
const rendered = render_outline_tree(nodes, outline_max_level, outline_verbose);
|
|
98
|
-
|
|
99
|
-
const visible_count = nodes.filter(n => n.level <= outline_max_level).length;
|
|
100
|
-
const deeper_count = nodes.length - visible_count;
|
|
101
|
-
const deeper_hint = deeper_count > 0 ? ` (${deeper_count} more at deeper levels, raise outline_max_level to see)` : '';
|
|
102
|
-
|
|
103
|
-
const header = `> **Outline view** — showing ${visible_count} of ${nodes.length} headings (L1-L${outline_max_level}${deeper_hint}) across ${pagination_result.total_pages} page(s). Call \`read_docx\` with \`mode='full'\` and \`page=N\` to read a section.\n\n---\n\n`;
|
|
104
|
-
const ui_markdown = header + rendered;
|
|
105
|
-
const llm_content = `> **File Path:** \`${resolve(file_path)}\`\n\n${ui_markdown}`;
|
|
106
|
-
|
|
107
|
-
return {
|
|
108
|
-
content: [{ type: 'text', text: llm_content }]
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
export function build_appendix_response(text: string, page: number, file_path: string): ToolResult {
|
|
113
|
-
const [, appendix] = split_structural_appendix(text);
|
|
114
|
-
|
|
115
|
-
if (!appendix.trim()) {
|
|
116
|
-
const ui_markdown = "# Appendix\n\nThis document has no structural appendix (no defined terms, named anchors, or diagnostics detected).";
|
|
117
|
-
const llm_content = `> **File Path:** \`${resolve(file_path)}\`\n\n${ui_markdown}`;
|
|
118
|
-
return {
|
|
119
|
-
content: [{ type: 'text', text: llm_content }]
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
const result = paginate(appendix, '');
|
|
124
|
-
|
|
125
|
-
if (page < 1 || page > result.total_pages) {
|
|
126
|
-
throw new Error(`Appendix page ${page} out of range (appendix has ${result.total_pages} pages).`);
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
const selected = result.pages[page - 1];
|
|
130
|
-
|
|
131
|
-
let banner = '';
|
|
132
|
-
let footer = '';
|
|
133
|
-
|
|
134
|
-
if (selected.total_pages > 1) {
|
|
135
|
-
banner = `> **Appendix page ${selected.page} of ${selected.total_pages}** — structural metadata for this document.\n\n---\n\n`;
|
|
136
|
-
footer = selected.has_next ? `\n\n---\n\n> **Continues on appendix page ${selected.page + 1} of ${selected.total_pages}.**` : '';
|
|
137
|
-
} else {
|
|
138
|
-
banner = "> **Appendix** — structural metadata for this document.\n\n---\n\n";
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
const ui_markdown = banner + selected.page_content + footer;
|
|
142
|
-
const llm_content = `> **File Path:** \`${resolve(file_path)}\`\n\n${ui_markdown}`;
|
|
143
|
-
|
|
144
|
-
return {
|
|
145
|
-
content: [{ type: 'text', text: llm_content }]
|
|
146
|
-
};
|
|
1
|
+
import { resolve, basename } from 'node:path';
|
|
2
|
+
import {
|
|
3
|
+
DocumentObject,
|
|
4
|
+
paginate,
|
|
5
|
+
split_structural_appendix,
|
|
6
|
+
extract_outline,
|
|
7
|
+
OutlineNode
|
|
8
|
+
} from '@adeu/core';
|
|
9
|
+
|
|
10
|
+
export interface ToolResult {
|
|
11
|
+
content: { type: 'text'; text: string }[];
|
|
12
|
+
isError?: boolean;
|
|
13
|
+
[key: string]: unknown;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function _build_appendix_pointer(has_appendix: boolean): string {
|
|
17
|
+
if (!has_appendix) return '';
|
|
18
|
+
return `\n\n---\n\n> **Appendix available.** This document has structural metadata (defined terms, cross-references, bookmarks, diagnostics) that may be relevant when editing. Call \`read_docx\` with \`mode='appendix'\` to load it before submitting edits.`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function _build_page_banner(page: number, total: number): string {
|
|
22
|
+
if (total <= 1) return '';
|
|
23
|
+
return `> **Page ${page} of ${total}** — call \`read_docx\` with \`mode='outline'\` for a heading map of the full document.\n\n---\n\n`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function _build_page_footer(page: number, total: number, has_next: boolean): string {
|
|
27
|
+
if (total <= 1 || !has_next) return '';
|
|
28
|
+
return `\n\n---\n\n> **Continues on page ${page + 1} of ${total}.**`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function render_outline_tree(nodes: OutlineNode[], max_level: number = 2, verbose: boolean = false): string {
|
|
32
|
+
if (!nodes || nodes.length === 0) {
|
|
33
|
+
return '# (No headings detected)\n\nThis document has no detectable headings.';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const visible = nodes.filter(n => n.level <= max_level);
|
|
37
|
+
|
|
38
|
+
if (visible.length === 0) {
|
|
39
|
+
return `# (No headings at level <= ${max_level})\n\nDocument has ${nodes.length} headings, all at deeper levels. Call read_docx with mode='outline' and outline_max_level=N (up to 6) to see them.`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const lines: string[] = [];
|
|
43
|
+
for (const node of visible) {
|
|
44
|
+
const prefix = '#'.repeat(node.level);
|
|
45
|
+
if (verbose) {
|
|
46
|
+
const meta_parts = [`p${node.page}`, node.style];
|
|
47
|
+
if (node.has_table) meta_parts.push('has table');
|
|
48
|
+
if (node.footnote_ids && node.footnote_ids.length > 0) meta_parts.push('fn:' + node.footnote_ids.join(','));
|
|
49
|
+
lines.push(`${prefix} ${node.text} (${meta_parts.join(', ')})`);
|
|
50
|
+
} else {
|
|
51
|
+
lines.push(`${prefix} ${node.text} (p${node.page})`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return lines.join('\n');
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function build_paginated_response(text: string, page: number, file_path: string): ToolResult {
|
|
58
|
+
const [body, appendix] = split_structural_appendix(text);
|
|
59
|
+
const has_appendix = Boolean(appendix.trim());
|
|
60
|
+
|
|
61
|
+
const result = paginate(body, '');
|
|
62
|
+
|
|
63
|
+
if (page < 1 || page > result.total_pages) {
|
|
64
|
+
throw new Error(`Page ${page} out of range (doc has ${result.total_pages} pages).`);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const selected = result.pages[page - 1];
|
|
68
|
+
const banner = _build_page_banner(selected.page, selected.total_pages);
|
|
69
|
+
const footer = _build_page_footer(selected.page, selected.total_pages, selected.has_next);
|
|
70
|
+
const appendix_pointer = _build_appendix_pointer(has_appendix);
|
|
71
|
+
|
|
72
|
+
const ui_markdown = banner + selected.page_content + footer + appendix_pointer;
|
|
73
|
+
const llm_content = `> **File Path:** \`${resolve(file_path)}\`\n\n${ui_markdown}`;
|
|
74
|
+
|
|
75
|
+
return {
|
|
76
|
+
content: [{ type: 'text', text: llm_content }]
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function build_outline_response(
|
|
81
|
+
doc: DocumentObject,
|
|
82
|
+
projected_text: string,
|
|
83
|
+
file_path: string,
|
|
84
|
+
outline_max_level: number = 2,
|
|
85
|
+
outline_verbose: boolean = false
|
|
86
|
+
): ToolResult {
|
|
87
|
+
const [body] = split_structural_appendix(projected_text);
|
|
88
|
+
const pagination_result = paginate(body, '');
|
|
89
|
+
|
|
90
|
+
const nodes = extract_outline(
|
|
91
|
+
doc,
|
|
92
|
+
body,
|
|
93
|
+
pagination_result.body_pages,
|
|
94
|
+
pagination_result.body_page_offsets
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
const rendered = render_outline_tree(nodes, outline_max_level, outline_verbose);
|
|
98
|
+
|
|
99
|
+
const visible_count = nodes.filter(n => n.level <= outline_max_level).length;
|
|
100
|
+
const deeper_count = nodes.length - visible_count;
|
|
101
|
+
const deeper_hint = deeper_count > 0 ? ` (${deeper_count} more at deeper levels, raise outline_max_level to see)` : '';
|
|
102
|
+
|
|
103
|
+
const header = `> **Outline view** — showing ${visible_count} of ${nodes.length} headings (L1-L${outline_max_level}${deeper_hint}) across ${pagination_result.total_pages} page(s). Call \`read_docx\` with \`mode='full'\` and \`page=N\` to read a section.\n\n---\n\n`;
|
|
104
|
+
const ui_markdown = header + rendered;
|
|
105
|
+
const llm_content = `> **File Path:** \`${resolve(file_path)}\`\n\n${ui_markdown}`;
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
content: [{ type: 'text', text: llm_content }]
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function build_appendix_response(text: string, page: number, file_path: string): ToolResult {
|
|
113
|
+
const [, appendix] = split_structural_appendix(text);
|
|
114
|
+
|
|
115
|
+
if (!appendix.trim()) {
|
|
116
|
+
const ui_markdown = "# Appendix\n\nThis document has no structural appendix (no defined terms, named anchors, or diagnostics detected).";
|
|
117
|
+
const llm_content = `> **File Path:** \`${resolve(file_path)}\`\n\n${ui_markdown}`;
|
|
118
|
+
return {
|
|
119
|
+
content: [{ type: 'text', text: llm_content }]
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const result = paginate(appendix, '');
|
|
124
|
+
|
|
125
|
+
if (page < 1 || page > result.total_pages) {
|
|
126
|
+
throw new Error(`Appendix page ${page} out of range (appendix has ${result.total_pages} pages).`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const selected = result.pages[page - 1];
|
|
130
|
+
|
|
131
|
+
let banner = '';
|
|
132
|
+
let footer = '';
|
|
133
|
+
|
|
134
|
+
if (selected.total_pages > 1) {
|
|
135
|
+
banner = `> **Appendix page ${selected.page} of ${selected.total_pages}** — structural metadata for this document.\n\n---\n\n`;
|
|
136
|
+
footer = selected.has_next ? `\n\n---\n\n> **Continues on appendix page ${selected.page + 1} of ${selected.total_pages}.**` : '';
|
|
137
|
+
} else {
|
|
138
|
+
banner = "> **Appendix** — structural metadata for this document.\n\n---\n\n";
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const ui_markdown = banner + selected.page_content + footer;
|
|
142
|
+
const llm_content = `> **File Path:** \`${resolve(file_path)}\`\n\n${ui_markdown}`;
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
content: [{ type: 'text', text: llm_content }]
|
|
146
|
+
};
|
|
147
147
|
}
|
package/tsconfig.json
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"target": "ES2022",
|
|
4
|
-
"module": "NodeNext",
|
|
5
|
-
"moduleResolution": "NodeNext",
|
|
6
|
-
"lib": ["ES2022", "DOM"],
|
|
7
|
-
"types": ["node"],
|
|
8
|
-
"ignoreDeprecations": "6.0",
|
|
9
|
-
"rootDir": "./src",
|
|
10
|
-
"outDir": "./dist",
|
|
11
|
-
"declaration": true,
|
|
12
|
-
"declarationMap": true,
|
|
13
|
-
"sourceMap": true,
|
|
14
|
-
"strict": true,
|
|
15
|
-
"esModuleInterop": true,
|
|
16
|
-
"skipLibCheck": true,
|
|
17
|
-
"forceConsistentCasingInFileNames": true
|
|
18
|
-
},
|
|
19
|
-
"include": ["src/**/*"],
|
|
20
|
-
"exclude": ["node_modules", "dist"]
|
|
21
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"module": "NodeNext",
|
|
5
|
+
"moduleResolution": "NodeNext",
|
|
6
|
+
"lib": ["ES2022", "DOM"],
|
|
7
|
+
"types": ["node"],
|
|
8
|
+
"ignoreDeprecations": "6.0",
|
|
9
|
+
"rootDir": "./src",
|
|
10
|
+
"outDir": "./dist",
|
|
11
|
+
"declaration": true,
|
|
12
|
+
"declarationMap": true,
|
|
13
|
+
"sourceMap": true,
|
|
14
|
+
"strict": true,
|
|
15
|
+
"esModuleInterop": true,
|
|
16
|
+
"skipLibCheck": true,
|
|
17
|
+
"forceConsistentCasingInFileNames": true
|
|
18
|
+
},
|
|
19
|
+
"include": ["src/**/*"],
|
|
20
|
+
"exclude": ["node_modules", "dist"]
|
|
21
|
+
}
|
package/tsup.config.ts
CHANGED
|
@@ -1,23 +1,26 @@
|
|
|
1
|
-
import { defineConfig } from 'tsup';
|
|
2
|
-
|
|
3
|
-
export default defineConfig([
|
|
4
|
-
{
|
|
5
|
-
entry: ['src/index.ts'],
|
|
6
|
-
format: ['esm'],
|
|
7
|
-
dts: true,
|
|
8
|
-
sourcemap: true,
|
|
9
|
-
clean: true,
|
|
10
|
-
outDir: 'dist',
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
1
|
+
import { defineConfig } from 'tsup';
|
|
2
|
+
|
|
3
|
+
export default defineConfig([
|
|
4
|
+
{
|
|
5
|
+
entry: ['src/index.ts'],
|
|
6
|
+
format: ['esm'],
|
|
7
|
+
dts: true,
|
|
8
|
+
sourcemap: true,
|
|
9
|
+
clean: true,
|
|
10
|
+
outDir: 'dist',
|
|
11
|
+
banner: {
|
|
12
|
+
js: '#!/usr/bin/env node',
|
|
13
|
+
},
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
entry: ['src/index.ts'],
|
|
17
|
+
format: ['esm'],
|
|
18
|
+
outExtension: () => ({ js: '.js' }),
|
|
19
|
+
noExternal: [/(.*)/], // Bundle all NPM dependencies
|
|
20
|
+
external: [/^node:/], // Leave Node.js native built-ins external
|
|
21
|
+
outDir: '../../../desktop-extension',
|
|
22
|
+
dts: false,
|
|
23
|
+
sourcemap: false,
|
|
24
|
+
clean: false, // Don't clean the whole dir (preserves icon and manifest)
|
|
25
|
+
}
|
|
23
26
|
]);
|