adeu
Adeu: нативные «Исправления» для ИИ
LLM говорят на Markdown; юристы говорят на языке «Исправлений» (Track Changes).
Adeu — это сервер протокола контекста модели (MCP) и Python SDK, который выступает в роли «Виртуального DOM» для Microsoft Word. Он предоставляет двухуровневый слой абстракции, позволяющий ИИ-агентам свободно редактировать текст документа, не разрушая базовое форматирование или сложный XML-код DOCX.
В то время как стандартные библиотеки, такие как python-docx, отлично подходят для создания документов с нуля, они не справляются с неразрушающим редактированием. Adeu решает эту проблему, преобразуя файлы .docx в эффективное с точки зрения токенов представление Markdown. Это освобождает ИИ-агентов, позволяя им сосредоточиться исключительно на семантике документа, а не тратить токены на борьбу с OpenXML.
Adeu действует как интеллектуальный прокси-сервер, обрабатывая правки ИИ как безопасные атомарные транзакции:
Извлечение: Переводит документ (с диска или из открытого Word) в понятную для LLM разметку CriticMarkup с семантическим приложением, содержащим определения терминов, перекрестные ссылки и вероятные опечатки. Агент начинает работу с семантической структурой, а не с «сырыми» данными.
Проверка: Выступает в качестве строгого фильтра безопасности. Он защищает целостность документа, автоматически блокируя неоднозначные текстовые совпадения или недопустимые структурные изменения до того, как они будут применены к файлу.
Фиксация: Преобразует текстовые правки ИИ в нативные «Исправления» (Track Changes) Word. Adeu берет на себя сложную работу с XML, гарантируя, что существующие макеты, шрифты и примечания на полях будут полностью сохранены.
Поддерживается Adeu.
Установка
Предварительное требование: Adeu использует uv для быстрого и изолированного выполнения. Самый простой способ установки — через pip:
pip install uvmacOS
curl -LsSf https://astral.sh/uv/install.sh | shWindows
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"Интеграция с Claude Desktop
Чтобы мгновенно добавить Adeu в Claude Desktop, выполните:
uvx adeu init[!IMPORTANT] Эта команда автоматически обнаруживает и обновляет ваш файл
claude_desktop_config.json. Перезапустите Claude Desktop после этого, чтобы загрузить новые инструменты.
Проверка работоспособности
После перезапуска Claude Desktop вы можете подтвердить подключение Adeu, отправив следующее сообщение напрямую в Claude:
"Can you read a DOCX file using the Adeu tool?"
Если все настроено правильно, Claude подтвердит, что у него есть доступ к инструментам Adeu, и опишет свои возможности. Если он не упоминает Adeu или сообщает об отсутствии инструментов для работы с файлами, еще раз проверьте, перезапустили ли вы Claude Desktop после выполнения uvx adeu init.
Поскольку Adeu требует Python 3.12+, uvx автоматически загрузит нужную версию Python и запустит сервер:
{
"mcpServers": {
"adeu": {
"command": "uvx",
"args": ["--from", "adeu", "adeu-server"]
}
}
}Related MCP server: docx-mcp
Рабочие процессы
1. Для агентов (Claude / MCP)
Adeu работает как сервер протокола контекста модели (MCP). Он предоставляет агентам специальные инструменты для безопасного чтения, проверки и редактирования документов.
Интерфейс MCP Apps: Инструмент
read_docxподдерживает новейший протокол MCP Apps UI. Когда агент читает документ, Adeu динамически отображает пользовательский интерактивный интерфейс Markdown прямо в окне чата Claude, позволяя вам визуально просматривать извлеченный текст и форматирование вместе с рассуждениями ИИ!
Рекомендуемый промпт для агента: Хотя инструменты Adeu автоматически описывают свои схемы для LLM, вы можете гарантировать наилучшие результаты, добавив этот контекст в Project Instructions (инструкции проекта) Claude или в системный промпт вашего агента:
Роль: Специалист по документам Инструменты:
read_docx(clean_view=True): Чтение финальной «чистой» версии текста для понимания контекста.
process_document_batch: Режим фиксации и согласования. Применение единого списка изменений. Используйтеtype: "modify"для конкретных правок типа «поиск и замена», иtype: "accept","reject"или"reply"для управления существующими «Исправлениями» и комментариями по ID.
sanitize_docx: Очистка перед отправкой. Удаление опасных метаданных, имен авторов и внутренних идентификаторов отслеживания перед отправкой. Может сохранять существующую разметку (keep_markup=True) или создавать чистый отчет об изменениях относительно базовой версии.
Интеграция с MS Word в реальном времени
Если вы работаете в Windows с установленным Microsoft Word, Adeu может выступать в роли второго пилота, редактируя активный документ прямо у вас на глазах.
read_active_word_document: Извлекает текст, «Исправления» и комментарии напрямую из открытого окна Word.process_active_word_batch: Преобразует правки LLM в нативные макросы COM, наблюдая за тем, как Word автоматически печатает, удаляет и добавляет комментарии на холсте.
2. Для разработчиков (Python SDK)
Если вы создаете юридическое технологическое приложение или автоматизированный конвейер, используйте RedlineEngine напрямую. Он берет на себя всю тяжелую работу по манипуляции XML.
from adeu import RedlineEngine, ModifyText
from io import BytesIO
# 1. Load the contract
with open("MSA.docx", "rb") as f:
stream = BytesIO(f.read())
# 2. Define the edit (e.g., from an LLM response)
# Adeu uses fuzzy matching to locate the target text, even if whitespace varies.
edit = ModifyText(
target_text="State of New York",
new_text="State of Delaware",
comment="Standardizing governing law."
)
# 3. Apply changes
engine = RedlineEngine(stream, author="AI Copilot")
engine.apply_edits([edit])
# 4. Save the result
with open("MSA_Redlined.docx", "wb") as f:
f.write(engine.save_to_stream().getvalue())3. Интерфейс командной строки (CLI)
Быстро проверяйте документы или применяйте пакеты правок из терминала.
# Extract clean text for RAG or prompting
adeu extract contract.docx -o contract.md
# Generate a visual diff between two versions
adeu diff v1.docx v2.docx
# Preview what an edit list (JSON) would look like
adeu markup contract.docx edits.json --output preview.md
# Apply edits to the DOCX
adeu apply contract.docx edits.json --author "Review Bot"
# Scrub author metadata and internal trackers, but keep the visual redlines for the counterparty
adeu sanitize redline.docx -o clean.docx --keep-markup --author "My Firm" --reportОсновные возможности
Безопасность форматирования
Adeu не «переписывает» документ. Он исправляет его.
Изображения и макеты: Не затрагиваются.
Нумерация и заголовки: Сохраняются.
Таблицы и списки: Сложные объединения ячеек и многоуровневая юридическая нумерация защищены.
Сложный XML: Изменяются только текстовые фрагменты, на которые направлена правка.
Представление CriticMarkup
Промежуточные представления важны. Adeu использует CriticMarkup для визуализации изменений.
Разметка | Значение | Пример |
| Удаление |
|
| Вставка |
|
| Комментарий |
|
Семантическое приложение
Контракты полны «мин», которые LLM может пропустить при первом проходе: непоследовательно используемые термины, битые перекрестные ссылки и опечатки в документах, распознанных через OCR. Adeu предварительно вычисляет их при извлечении и передает агенту структурированное приложение вместе с текстом.
Интеллектуальное сопоставление
Документы Word часто бывают «грязными». Слово «Contract» может быть разбито на XML-фрагменты, такие как ["Con", "tract"], из-за проверки орфографии или истории форматирования.
Объединение фрагментов: Adeu нормализует эти разбиения, чтобы ИИ видел слово «Contract» целиком.
Нечеткий поиск: Обрабатывает незначительные расхождения в пробелах между памятью LLM и фактическим содержимым документа.
Очистка метаданных
Существующие средства очистки метаданных часто ломают «Исправления» или удаляют данные без уведомления. Команда sanitize в Adeu хирургически удаляет опасные трекеры (rsid, шаблоны, внутренние пути, временные метки) и «осиротевший» контент, сохраняя при этом валидные «Исправления». Важно, что она создает прозрачный отчет об аудите, доказывающий, что именно было удалено и что будет видно получателю.
Adeu Cloud
По умолчанию основной движок Adeu и локальные инструменты для работы с файлами полностью открыты и работают исключительно на вашем компьютере. Adeu никогда не отправляет ваши локальные документы на сервер (хотя выбранный вами провайдер LLM будет обрабатывать текст, который читает агент).
Тем не менее, вы можете явно подключить свой MCP-сервер к Adeu Cloud, чтобы получить доступ к:
Сквозным рабочим процессам (Email): Поскольку контракты передаются по электронной почте, Adeu Cloud позволяет агентам безопасно получать цепочки писем, извлекать вложения DOCX от контрагентов для проверки и составлять ответы с прикрепленными очищенными правками.
Расширенной проверке документов: Выполнение сложных задач семантической проверки нескольких документов в асинхронном режиме. Безопасно направляя эти огромные контексты в Adeu Cloud для обработки, вы предотвращаете исчерпание контекстного окна вашего локального ИИ-агента или достижение лимитов запросов.
Участие в разработке
Мы приветствуем вклад сообщества! Будь то исправление ошибок, добавление возможностей или улучшение документации, пожалуйста, ознакомьтесь с нашим Руководством по участию для получения инструкций по настройке локальной среды uv, запуску тестов и пониманию строгих правил безопасности XML в проекте.
Лицензия
Лицензия MIT. Программное обеспечение с открытым исходным кодом, бесплатное для использования в коммерческих целях.
Available Tools
11 toolsaccept_all_changesADestructive
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. For selective acceptance/rejection of specific changes, use process_document_batch instead.
Inputs: docx_path (required), output_path. Returns: result
create_email_draftA
Creates an email draft in the user's native draft box (e.g., Outlook/Gmail). Can either start a NEW email, or REPLY to an existing thread. To REPLY, provide 'reply_to_email_id' (the short ID from search_and_fetch_emails). To start a NEW email, omit the ID but provide 'subject' and 'to_recipients'. Allows attaching local files (PDF/DOCX) by providing their absolute paths. The body should be formatted in Markdown.
Inputs: body_markdown (required), reply_to_email_id, subject, to_recipients, +1 more.
diff_docx_filesARead-only
Compares two DOCX files and generates a text-based Unified Diff. Use this to see exactly what changed between two versions of a document. By default (compare_clean=True), it compares the 'Accepted' finalized states of both documents. Set compare_clean=False if you need to compare the raw underlying text including Tracked Change CriticMarkup.
Inputs: original_path (required), modified_path (required), compare_clean. Returns: result
login_to_adeu_cloudA
Logs the user into the Adeu Cloud backend. Securely opens a browser window for authentication.
Inputs: no named parameters. Returns: result
logout_of_adeu_cloudA
Logs out of the Adeu Cloud backend by clearing the local API key from the OS Keychain.
Inputs: no named parameters. Returns: result
open_local_fileA
Opens a local file in its native desktop application (e.g., Microsoft Word for DOCX files).
Inputs: file_path (required). Returns: result
process_document_batchADestructive
Applies a batch of structural edits, text modifications, and review actions to a document. This is your primary tool for editing DOCX files.
CRITICAL: All changes in the batch evaluate against the ORIGINAL document state. Do not send sequential edits that depend on each other within the same batch (e.g. rename X to Y, then modify Y). Instead, apply the rename in one batch, then modify Y in a subsequent batch.
The changes parameter is a list of operations. Each item MUST have a type:
'modify': Search-and-replace text. Provide exact
target_text(CRITICAL: include surrounding context if the word appears multiple times to ensure unique matching) andnew_text(the replacement).new_textsupports full Markdown structure: '# Heading 1' through '###### Heading 6' at the start of a line for heading styles, 'bold' and 'italic' inline formatting, and blank lines ('\n\n') to splitnew_textinto multiple paragraphs. Multi-paragraph inserts are tracked as one logical revision. To delete text, makenew_textempty. Do NOT manually write CriticMarkup tags ({++, {--, {>>). To add a comment, use the 'comment' parameter.'accept': Finalize a tracked change. Requires
target_id(e.g., 'Chg:12'). (Note: Accepting one half of a paired modify cascades to accept the other half).'reject': Revert a tracked change. Requires
target_id(e.g., 'Chg:12'). (Note: Rejecting one half cascades to reject the other half).'reply': Reply to a comment. Requires
target_id(e.g., 'Com:5') andtext.'insert_row': Insert table row. Requires
target_text(anchor),position('above'/'below'), andcells(Markdown strings).'delete_row': Delete table row. Requires
target_textinside the row to be deleted.
Always provide a realistic author_name for Tracked Changes. This name will be used for attribution in the document's tracked changes and comments.
Inputs: original_docx_path (required), author_name (required), changes (required), output_path. Returns: result
read_docxARead-only
Reads a DOCX file and extracts its text content. Use this to ingest documents into your context window. By default (clean_view=False), it returns text with inline CriticMarkup (e.g., {++inserted++}, {--deleted--}, {==highlighted==}{>>comment<<}) representing Tracked Changes and Comments. Set clean_view=True ONLY if you want to read the final, clean text, ignoring all redlines and comments.
PAGINATION & OUTLINE:
mode='outline' returns a structural map of headings with page numbers, styles, table presence, and referenced footnotes. Body content is omitted. Use this first on large documents to plan targeted reads.
mode='full' (default) returns the document body. Documents over ~19,000 characters are split into pages; use page=N to read a specific page (1-indexed). Documents under the limit are returned in full on page 1.
Page boundaries differ between clean_view=True and clean_view=False.
The Structural Appendix (defined terms, anchors, diagnostics) is repeated on every page.
Inputs: file_path (required), clean_view, mode, page.
sanitize_docxADestructive
Sanitizes a DOCX file by stripping dangerous metadata (rsids, author names, template paths, DMS metadata, hidden text, orphaned content) and producing an audit report of everything removed. Use this before sending documents to external parties. Supports three modes: full scrub (for signing/closing), keep-markup (preserves your track changes and open comments), or baseline (recomputes your delta against the original document).
Inputs: file_path (required), output_path, keep_markup, baseline_path, +2 more. Returns: object
search_and_fetch_emailsARead-only
Searches the user's live email inbox. By default, searches only the Inbox folder (matching what the user sees in their mail client) — this excludes deleted items, drafts, and spam. Use filters to find specific emails (e.g., 'is_unread=True' for new emails, 'days_ago=7' for last week, 'folder=sent' for sent items, 'folder=all' to search the entire mailbox including trash). It returns a list of lightweight email previews. To read the full email body, thread history, and automatically download attachments to local disk, call this tool again and provide the specific email_id. Emails often contain attachments. It is highly recommended to always provide the working_directory parameter so attachments are saved directly to the user's actual project folder. This directory path refers to the user's native operating system, not the LLM's sandbox environment.
Inputs: sender, subject, has_attachments, attachment_name, +7 more.
validate_documentsA
Validates documents for inconsistencies, contradictions, and risk assessments. To START a new validation, provide 'file_paths' as a JSON-encoded string representing a list of file paths. This will immediately return a task_id. To CHECK the status of a validation, call this tool AGAIN and provide ONLY the 'task_id'. The checking process will poll for up to 50 seconds. If it times out, continue checking.
Inputs: file_paths, task_id.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 11 tools
Each tool targets a distinct operation (auth, email, document reading/editing/finalization/comparison/sanitization/validation) with clear boundaries. No two tools serve overlapping purposes.
All tool names follow a consistent verb_noun snake_case pattern (e.g., accept_all_changes, create_email_draft, sanitize_docx). No mixing of styles or vague verbs.
The 11 tools cover the core functionality (document editing, email handling, authentication) without being excessive. Each tool serves a well-defined purpose.
The set covers read, edit, finalize, compare, sanitize, search/create drafts, and validate. However, adding new comments is not directly exposed (only replying), which is a minor gap.
Maintenance
Related MCP Connectors
Contract review that keeps your contracts: cited answers, Word redlines, key-date alerts.
Convert, create and edit Word, PowerPoint, Excel and PDF documents from any AI agent.
Create documents and reusable templates, request signatures, and track approvals — for AI agents.
AI contract management (CLM): contract review, data extraction, reminders and renewal deadlines.
Related MCP Servers
- AlicenseBqualityDmaintenanceEnables creating professional Word documents from markdown or structured content with fast, customized formatting via natural language.71ISC
- AlicenseAqualityDmaintenanceLegal document redlining engine that applies AI-generated JSON changes as professional tracked changes with comments in .docx files, producing Word-indistinguishable output.61MIT
- AlicenseBqualityCmaintenanceStructure-preserving Word DOCX editing MCP server with a .NET Open XML backend and Office.js live sessions. Enables safe, auditable, incremental editing of Microsoft Word documents for AI agents.6312 npm10AGPL 3.0
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to generate format-stable, editable Word DOCX documents from structured content and reusable templates, with document type recognition, schema retrieval, template rendering, validation, and conservative fixes.MIT