@adeu/mcp-server 1.6.8 → 1.6.9

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/src/index.ts CHANGED
@@ -1,43 +1,60 @@
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,
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import {
4
+ CallToolRequestSchema,
5
+ ListToolsRequestSchema,
6
+ } from "@modelcontextprotocol/sdk/types.js";
7
+ import { readFileSync } from "node:fs";
8
+ import { basename, resolve, extname, dirname } from "node:path";
9
+ import {
10
+ identifyEngine,
11
+ extractTextFromBuffer,
12
+ DocumentObject,
13
+ RedlineEngine,
11
14
  BatchValidationError,
12
- create_unified_diff,
13
- finalize_document
14
- } from '@adeu/core';
15
- import {
16
- build_paginated_response,
17
- build_outline_response,
18
- build_appendix_response
19
- } from './response-builders.js';
20
-
15
+ create_word_patch_diff,
16
+ finalize_document,
17
+ } from "@adeu/core";
18
+ import {
19
+ build_paginated_response,
20
+ build_outline_response,
21
+ build_appendix_response,
22
+ } from "./response-builders.js";
23
+ function readFileBytesOrThrow(filePath: string): Buffer {
24
+ try {
25
+ return readFileSync(filePath);
26
+ } catch (err: any) {
27
+ if (err.code === "ENOENT") {
28
+ throw new Error(`File not found: ${filePath}`);
29
+ }
30
+ throw err;
31
+ }
32
+ }
21
33
  // --- Tool Description Constants (Parity with Python) ---
22
- 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";
23
- 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.";
34
+ const READ_DOCX_COMMON_DESC =
35
+ "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";
36
+ const READ_DOCX_TAIL =
37
+ "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.";
24
38
 
25
- 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";
26
- 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.";
39
+ const PROCESS_BATCH_COMMON_DESC =
40
+ "Applies a batch of edits and review actions to a DOCX.\n\nAll changes evaluate against the ORIGINAL document statedo 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";
41
+ const PROCESS_BATCH_OPERATIONS_DESC =
42
+ "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.";
27
43
 
28
- const DIFF_DOCX_DESC = "Compares two DOCX files and returns a unified diff of their text content. Useful for analyzing differences between versions before editing.";
44
+ const DIFF_DOCX_DESC =
45
+ "Compares two DOCX files and returns a unified diff of their text content. Useful for analyzing differences between versions before editing.";
29
46
 
30
47
  // --- Server Setup ---
31
48
  const server = new Server(
32
49
  {
33
- name: 'adeu-redlining-service',
34
- version: '1.0.0',
50
+ name: "adeu-redlining-service",
51
+ version: "1.0.0",
35
52
  },
36
53
  {
37
54
  capabilities: {
38
55
  tools: {},
39
56
  },
40
- }
57
+ },
41
58
  );
42
59
 
43
60
  // --- Tool Registration ---
@@ -45,246 +62,381 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
45
62
  return {
46
63
  tools: [
47
64
  {
48
- name: 'read_docx',
65
+ name: "read_docx",
49
66
  description: READ_DOCX_COMMON_DESC + READ_DOCX_TAIL,
50
67
  inputSchema: {
51
- type: 'object',
68
+ type: "object",
52
69
  properties: {
53
- file_path: { type: 'string', description: 'Absolute path to the DOCX file.' },
54
- clean_view: { type: 'boolean', description: "If False (default), returns the 'Raw' text with inline CriticMarkup. If True, returns 'Accepted' text.", default: false },
55
- mode: { type: 'string', enum: ['full', 'outline', 'appendix'], description: "'full' returns body content. 'outline' returns a structural heading map. 'appendix' returns defined terms.", default: 'full' },
56
- page: { type: 'number', description: 'Page number (1-indexed) for mode=\'full\'. Defaults to 1.', default: 1 },
57
- outline_max_level: { type: 'number', description: 'For mode=\'outline\' only: cap on heading depth.', default: 2 },
58
- outline_verbose: { type: 'boolean', description: 'For mode=\'outline\' only: includes metadata.', default: false }
70
+ file_path: {
71
+ type: "string",
72
+ description: "Absolute path to the DOCX file.",
73
+ },
74
+ clean_view: {
75
+ type: "boolean",
76
+ description:
77
+ "If False (default), returns the 'Raw' text with inline CriticMarkup. If True, returns 'Accepted' text.",
78
+ default: false,
79
+ },
80
+ mode: {
81
+ type: "string",
82
+ enum: ["full", "outline", "appendix"],
83
+ description:
84
+ "'full' returns body content. 'outline' returns a structural heading map. 'appendix' returns defined terms.",
85
+ default: "full",
86
+ },
87
+ page: {
88
+ type: "number",
89
+ description:
90
+ "Page number (1-indexed) for mode='full'. Defaults to 1.",
91
+ default: 1,
92
+ },
93
+ outline_max_level: {
94
+ type: "number",
95
+ description: "For mode='outline' only: cap on heading depth.",
96
+ default: 2,
97
+ },
98
+ outline_verbose: {
99
+ type: "boolean",
100
+ description: "For mode='outline' only: includes metadata.",
101
+ default: false,
102
+ },
59
103
  },
60
- required: ['file_path']
61
- }
104
+ required: ["file_path"],
105
+ },
62
106
  },
63
107
  {
64
- name: 'process_document_batch',
108
+ name: "process_document_batch",
65
109
  description: PROCESS_BATCH_COMMON_DESC + PROCESS_BATCH_OPERATIONS_DESC,
66
110
  inputSchema: {
67
- type: 'object',
111
+ type: "object",
68
112
  properties: {
69
- original_docx_path: { type: 'string', description: 'Absolute path to the source file.' },
70
- author_name: { type: 'string', description: "Name to appear in Track Changes (e.g., 'Reviewer AI')." },
71
- changes: {
72
- type: 'array',
73
- description: "List of changes to apply. Each change must specify 'type'.",
74
- items: { type: 'object' }
113
+ original_docx_path: {
114
+ type: "string",
115
+ description: "Absolute path to the source file.",
116
+ },
117
+ author_name: {
118
+ type: "string",
119
+ description:
120
+ "Name to appear in Track Changes (e.g., 'Reviewer AI').",
121
+ },
122
+ changes: {
123
+ type: "array",
124
+ description:
125
+ "List of changes to apply. Each change must specify 'type'.",
126
+ items: { type: "object" },
127
+ },
128
+ output_path: {
129
+ type: "string",
130
+ description: "Optional output path.",
75
131
  },
76
- output_path: { type: 'string', description: 'Optional output path.' }
77
132
  },
78
- required: ['original_docx_path', 'author_name', 'changes']
79
- }
133
+ required: ["original_docx_path", "author_name", "changes"],
134
+ },
80
135
  },
81
136
  {
82
- name: 'accept_all_changes',
83
- 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.",
137
+ name: "accept_all_changes",
138
+ description:
139
+ "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.",
84
140
  inputSchema: {
85
- type: 'object',
141
+ type: "object",
86
142
  properties: {
87
- docx_path: { type: 'string', description: 'Absolute path to the DOCX file.' },
88
- output_path: { type: 'string', description: 'Optional output path.' }
143
+ docx_path: {
144
+ type: "string",
145
+ description: "Absolute path to the DOCX file.",
146
+ },
147
+ output_path: {
148
+ type: "string",
149
+ description: "Optional output path.",
150
+ },
89
151
  },
90
- required: ['docx_path']
91
- }
152
+ required: ["docx_path"],
153
+ },
92
154
  },
93
155
  {
94
- name: 'diff_docx_files',
156
+ name: "diff_docx_files",
95
157
  description: DIFF_DOCX_DESC,
96
158
  inputSchema: {
97
- type: 'object',
159
+ type: "object",
98
160
  properties: {
99
- original_path: { type: 'string', description: 'Absolute path to the baseline DOCX file.' },
100
- modified_path: { type: 'string', description: 'Absolute path to the modified DOCX file.' }
161
+ original_path: {
162
+ type: "string",
163
+ description: "Absolute path to the baseline DOCX file.",
164
+ },
165
+ modified_path: {
166
+ type: "string",
167
+ description: "Absolute path to the modified DOCX file.",
168
+ },
169
+ compare_clean: {
170
+ type: "boolean",
171
+ description:
172
+ "If True, compares 'Accepted' state. If False, compares raw text.",
173
+ default: true,
174
+ },
101
175
  },
102
- required: ['original_path', 'modified_path']
103
- }
176
+ required: ["original_path", "modified_path"],
177
+ },
104
178
  },
105
179
  {
106
- name: 'finalize_document',
107
- description: "Prepares a document for external distribution or e-signature. This tool combines metadata sanitization, document locking (protection), and markup resolution into a single step. NOTE: PDF export and AES encryption are disabled in this environment.",
180
+ name: "finalize_document",
181
+ description:
182
+ "Prepares a document for external distribution or e-signature. This tool combines metadata sanitization, document locking (protection), and markup resolution into a single step. NOTE: PDF export and AES encryption are disabled in this environment.",
108
183
  inputSchema: {
109
- type: 'object',
184
+ type: "object",
110
185
  properties: {
111
- file_path: { type: 'string', description: 'Absolute path to the DOCX file.' },
112
- output_path: { type: 'string', description: 'Optional output path.' },
113
- sanitize_mode: { type: 'string', enum: ['full', 'keep-markup'], description: 'full removes all markup, keep-markup redacts metadata but keeps comments/redlines.' },
114
- accept_all: { type: 'boolean', description: 'If true, auto-accepts all unresolved track changes before finalizing.' },
115
- protection_mode: { type: 'string', enum: ['read_only', 'encrypt'], description: 'Native OOXML document locking. encrypt falls back to read_only in this environment.' },
116
- password: { type: 'string', description: 'Ignored in this environment.' },
117
- author: { type: 'string', description: 'Replace all remaining markup authorship with this name.' },
118
- export_pdf: { type: 'boolean', description: 'Ignored in this environment.' }
186
+ file_path: {
187
+ type: "string",
188
+ description: "Absolute path to the DOCX file.",
189
+ },
190
+ output_path: {
191
+ type: "string",
192
+ description: "Optional output path.",
193
+ },
194
+ sanitize_mode: {
195
+ type: "string",
196
+ enum: ["full", "keep-markup"],
197
+ description:
198
+ "full removes all markup, keep-markup redacts metadata but keeps comments/redlines.",
199
+ },
200
+ accept_all: {
201
+ type: "boolean",
202
+ description:
203
+ "If true, auto-accepts all unresolved track changes before finalizing.",
204
+ },
205
+ protection_mode: {
206
+ type: "string",
207
+ enum: ["read_only", "encrypt"],
208
+ description:
209
+ "Native OOXML document locking. encrypt falls back to read_only in this environment.",
210
+ },
211
+ password: {
212
+ type: "string",
213
+ description: "Ignored in this environment.",
214
+ },
215
+ author: {
216
+ type: "string",
217
+ description:
218
+ "Replace all remaining markup authorship with this name.",
219
+ },
220
+ export_pdf: {
221
+ type: "boolean",
222
+ description: "Ignored in this environment.",
223
+ },
119
224
  },
120
- required: ['file_path']
121
- }
122
- }
123
- ]
225
+ required: ["file_path"],
226
+ },
227
+ },
228
+ ],
124
229
  };
125
230
  });
126
231
 
127
232
  // --- Tool Execution ---
128
- server.setRequestHandler(CallToolRequestSchema, async (request): Promise<any> => {
129
- const { name, arguments: args } = request.params;
233
+ server.setRequestHandler(
234
+ CallToolRequestSchema,
235
+ async (request): Promise<any> => {
236
+ const { name, arguments: args } = request.params;
130
237
 
131
- try {
132
- if (name === 'read_docx') {
133
- const filePath = args?.file_path as string;
134
- const cleanView = args?.clean_view as boolean ?? false;
135
- const mode = args?.mode as string ?? 'full';
136
- const page = args?.page as number ?? 1;
137
- const outline_max_level = args?.outline_max_level as number ?? 2;
138
- const outline_verbose = args?.outline_verbose as boolean ?? false;
139
-
140
- const buf = readFileSync(filePath);
141
- const text = await extractTextFromBuffer(buf, cleanView);
142
-
143
- if (mode === 'outline') {
144
- const doc = await DocumentObject.load(buf);
145
- return build_outline_response(doc, text, filePath, outline_max_level, outline_verbose);
146
- }
147
- if (mode === 'appendix') {
148
- return build_appendix_response(text, page, filePath);
149
- }
150
- return build_paginated_response(text, page, filePath);
151
- }
238
+ try {
239
+ if (name === "read_docx") {
240
+ const filePath = args?.file_path as string;
241
+ const cleanView = (args?.clean_view as boolean) ?? false;
242
+ const mode = (args?.mode as string) ?? "full";
243
+ const page = (args?.page as number) ?? 1;
244
+ const outline_max_level = (args?.outline_max_level as number) ?? 2;
245
+ const outline_verbose = (args?.outline_verbose as boolean) ?? false;
246
+
247
+ const buf = readFileBytesOrThrow(filePath);
248
+ const text = await extractTextFromBuffer(buf, cleanView);
152
249
 
153
- if (name === 'process_document_batch') {
154
- const origPath = args?.original_docx_path as string;
155
- const authorName = args?.author_name as string;
156
- const changes = args?.changes as any[];
157
- let outPath = args?.output_path as string;
158
-
159
- if (!outPath) {
160
- const ext = extname(origPath);
161
- const base = basename(origPath, ext);
162
- const dir = dirname(origPath);
163
- outPath = resolve(dir, `${base}_processed${ext}`);
250
+ if (mode === "outline") {
251
+ const doc = await DocumentObject.load(buf);
252
+ return build_outline_response(
253
+ doc,
254
+ text,
255
+ filePath,
256
+ outline_max_level,
257
+ outline_verbose,
258
+ );
259
+ }
260
+ if (mode === "appendix") {
261
+ return build_appendix_response(text, page, filePath);
262
+ }
263
+ return build_paginated_response(text, page, filePath);
164
264
  }
265
+ if (name === "process_document_batch") {
266
+ const origPath = args?.original_docx_path as string;
267
+ const authorName = args?.author_name as string;
268
+ const changes = args?.changes as any[];
269
+ let outPath = args?.output_path as string;
165
270
 
166
- const buf = readFileSync(origPath);
167
- const doc = await DocumentObject.load(buf);
168
- const engine = new RedlineEngine(doc, authorName);
169
-
170
- let stats;
171
- try {
172
- stats = engine.process_batch(changes);
173
- } catch (e) {
174
- if (e instanceof BatchValidationError) {
271
+ if (!authorName || !authorName.trim()) {
175
272
  return {
176
- content: [{ type: 'text', text: `Batch rejected. Some edits failed validation:\n\n${(e as BatchValidationError).errors.join('\n\n')}` }],
177
- isError: true
273
+ content: [
274
+ { type: "text", text: "Error: author_name cannot be empty." },
275
+ ],
178
276
  };
179
277
  }
180
- throw e;
181
- }
182
278
 
183
- const outBuf = await doc.save();
184
- // Using dynamic import of fs/promises or just sync write
185
- const fs = await import('node:fs');
186
- fs.writeFileSync(outPath, outBuf);
279
+ if (!changes || changes.length === 0) {
280
+ return {
281
+ content: [{ type: "text", text: "Error: No changes provided." }],
282
+ };
283
+ }
284
+ if (!outPath) {
285
+ const ext = extname(origPath);
286
+ const base = basename(origPath, ext);
287
+ const dir = dirname(origPath);
288
+ outPath = resolve(dir, `${base}_processed${ext}`);
289
+ }
187
290
 
188
- 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.`;
189
- if (stats.skipped_details?.length > 0) {
190
- res += `\n\nSkipped Details:\n${stats.skipped_details.join('\n')}`;
191
- }
291
+ const buf = readFileBytesOrThrow(origPath);
292
+ const doc = await DocumentObject.load(buf);
293
+ const engine = new RedlineEngine(doc, authorName);
192
294
 
193
- return {
194
- content: [{ type: 'text', text: res }]
195
- };
196
- }
295
+ let stats;
296
+ try {
297
+ stats = engine.process_batch(changes);
298
+ } catch (e) {
299
+ if (e instanceof BatchValidationError) {
300
+ return {
301
+ content: [
302
+ {
303
+ type: "text",
304
+ text: `Batch rejected. Some edits failed validation:\n\n${(e as BatchValidationError).errors.join("\n\n")}`,
305
+ },
306
+ ],
307
+ isError: true,
308
+ };
309
+ }
310
+ throw e;
311
+ }
197
312
 
198
- if (name === 'accept_all_changes') {
199
- const docxPath = args?.docx_path as string;
200
- let outPath = args?.output_path as string;
313
+ const outBuf = await doc.save();
314
+ // Using dynamic import of fs/promises or just sync write
315
+ const fs = await import("node:fs");
316
+ fs.writeFileSync(outPath, outBuf);
201
317
 
202
- if (!outPath) {
203
- const ext = extname(docxPath);
204
- const base = basename(docxPath, ext);
205
- const dir = dirname(docxPath);
206
- outPath = resolve(dir, `${base}_clean${ext}`);
318
+ 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.`;
319
+ if (stats.skipped_details?.length > 0) {
320
+ res += `\n\nSkipped Details:\n${stats.skipped_details.join("\n")}`;
321
+ }
322
+
323
+ return {
324
+ content: [{ type: "text", text: res }],
325
+ };
207
326
  }
208
327
 
209
- const buf = readFileSync(docxPath);
210
- const doc = await DocumentObject.load(buf);
211
- const engine = new RedlineEngine(doc);
212
-
213
- // We implement the public facing accept_all wrapper from python
214
- engine.accept_all_revisions();
215
-
216
- const outBuf = await doc.save();
217
- const fs = await import('node:fs');
218
- fs.writeFileSync(outPath, outBuf);
328
+ if (name === "accept_all_changes") {
329
+ const docxPath = args?.docx_path as string;
330
+ let outPath = args?.output_path as string;
219
331
 
220
- return {
221
- content: [{ type: 'text', text: `Accepted all changes. Saved to: ${outPath}` }]
222
- };
223
- }
332
+ if (!outPath) {
333
+ const ext = extname(docxPath);
334
+ const base = basename(docxPath, ext);
335
+ const dir = dirname(docxPath);
336
+ outPath = resolve(dir, `${base}_clean${ext}`);
337
+ }
224
338
 
225
- if (name === 'diff_docx_files') {
226
- const origPath = args?.original_path as string;
227
- const modPath = args?.modified_path as string;
339
+ const buf = readFileBytesOrThrow(docxPath);
340
+ const doc = await DocumentObject.load(buf);
341
+ const engine = new RedlineEngine(doc);
228
342
 
229
- const origBuf = readFileSync(origPath);
230
- const modBuf = readFileSync(modPath);
343
+ // We implement the public facing accept_all wrapper from python
344
+ engine.accept_all_revisions();
231
345
 
232
- const origText = await extractTextFromBuffer(origBuf, true);
233
- const modText = await extractTextFromBuffer(modBuf, true);
346
+ const outBuf = await doc.save();
347
+ const fs = await import("node:fs");
348
+ fs.writeFileSync(outPath, outBuf);
234
349
 
235
- const diff = create_unified_diff(origText, modText);
236
-
237
- return {
238
- content: [{ type: 'text', text: diff || "No differences found." }]
239
- };
240
- }
350
+ return {
351
+ content: [
352
+ {
353
+ type: "text",
354
+ text: `Accepted all changes. Saved to: ${outPath}`,
355
+ },
356
+ ],
357
+ };
358
+ }
359
+ if (name === "diff_docx_files") {
360
+ const origPath = args?.original_path as string;
361
+ const modPath = args?.modified_path as string;
362
+ const compareClean = (args?.compare_clean as boolean) ?? true;
363
+ const origBuf = readFileBytesOrThrow(origPath);
364
+ const modBuf = readFileBytesOrThrow(modPath);
365
+
366
+ // Pass compareClean flag into extraction
367
+ const origText = await extractTextFromBuffer(origBuf, compareClean);
368
+ const modText = await extractTextFromBuffer(modBuf, compareClean);
241
369
 
242
- if (name === 'finalize_document') {
243
- const filePath = args?.file_path as string;
244
- let outPath = args?.output_path as string;
245
-
246
- if (!outPath) {
247
- const ext = extname(filePath);
248
- const base = basename(filePath, ext);
249
- const dir = dirname(filePath);
250
- outPath = resolve(dir, `${base}_final${ext}`);
370
+ const diff = create_word_patch_diff(
371
+ origText,
372
+ modText,
373
+ basename(origPath),
374
+ basename(modPath)
375
+ );
376
+
377
+ return {
378
+ content: [{ type: "text", text: diff || "No differences found." }],
379
+ };
251
380
  }
252
381
 
253
- const buf = readFileSync(filePath);
254
- const doc = await DocumentObject.load(buf);
382
+ if (name === "finalize_document") {
383
+ const filePath = args?.file_path as string;
384
+ let outPath = args?.output_path as string;
385
+
386
+ if (!outPath) {
387
+ const ext = extname(filePath);
388
+ const base = basename(filePath, ext);
389
+ const dir = dirname(filePath);
390
+ outPath = resolve(dir, `${base}_final${ext}`);
391
+ }
392
+
393
+ const buf = readFileBytesOrThrow(filePath);
394
+ const doc = await DocumentObject.load(buf);
395
+
396
+ const result = await finalize_document(doc, {
397
+ filename: basename(filePath),
398
+ sanitize_mode: (args?.sanitize_mode as any) || "full",
399
+ accept_all: args?.accept_all as boolean,
400
+ protection_mode: args?.protection_mode as any,
401
+ author: args?.author as string,
402
+ export_pdf: args?.export_pdf as boolean,
403
+ });
255
404
 
256
- const result = await finalize_document(doc, {
257
- filename: basename(filePath),
258
- sanitize_mode: (args?.sanitize_mode as any) || 'full',
259
- accept_all: args?.accept_all as boolean,
260
- protection_mode: args?.protection_mode as any,
261
- author: args?.author as string,
262
- export_pdf: args?.export_pdf as boolean
263
- });
405
+ const fs = await import("node:fs");
406
+ fs.writeFileSync(outPath, result.outBuffer!);
264
407
 
265
- const fs = await import('node:fs');
266
- fs.writeFileSync(outPath, result.outBuffer!);
408
+ return {
409
+ content: [
410
+ {
411
+ type: "text",
412
+ text: `Saved to: ${outPath}\n\n${result.reportText}`,
413
+ },
414
+ ],
415
+ };
416
+ }
267
417
 
418
+ throw new Error(`Unknown tool: ${name}`);
419
+ } catch (error: any) {
268
420
  return {
269
- content: [{ type: 'text', text: `Saved to: ${outPath}\n\n${result.reportText}` }]
421
+ content: [
422
+ {
423
+ type: "text",
424
+ text: `Error executing tool ${name}: ${error.message}`,
425
+ },
426
+ ],
427
+ isError: true,
270
428
  };
271
429
  }
272
-
273
- throw new Error(`Unknown tool: ${name}`);
274
-
275
- } catch (error: any) {
276
- return {
277
- content: [{ type: 'text', text: `Error executing tool ${name}: ${error.message}` }],
278
- isError: true,
279
- };
280
- }
281
- });
430
+ },
431
+ );
282
432
 
283
433
  // --- Startup ---
284
434
  async function main() {
285
435
  const transport = new StdioServerTransport();
286
436
  await server.connect(transport);
287
- console.error(`Adeu MCP Server (Node.js Engine: ${identifyEngine()}) running on stdio`);
437
+ console.error(
438
+ `Adeu MCP Server (Node.js Engine: ${identifyEngine()}) running on stdio`,
439
+ );
288
440
  }
289
441
 
290
- main().catch(console.error);
442
+ main().catch(console.error);