@adeu/mcp-server 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/response-builders.ts","../src/desktop-auth.ts","../src/shared.ts","../src/tools/auth.ts","../src/tools/email.ts"],"sourcesContent":["// FILE: node/packages/mcp-server/src/index.ts\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { readFileSync, existsSync } from \"node:fs\";\nimport { basename, resolve, extname, dirname, join } from \"node:path\";\nimport { z } from \"zod\";\nimport {\n registerAppTool as origRegisterAppTool,\n registerAppResource,\n RESOURCE_MIME_TYPE,\n} from \"@modelcontextprotocol/ext-apps/server\";\nimport fs from \"node:fs\";\nimport {\n identifyEngine,\n extractTextFromBuffer,\n _extractTextFromDoc,\n DocumentObject,\n RedlineEngine,\n BatchValidationError,\n create_word_patch_diff,\n finalize_document,\n} from \"@adeu/core\";\n\nimport {\n build_paginated_response,\n build_outline_response,\n build_appendix_response,\n} from \"./response-builders.js\";\n\nimport { login_to_adeu_cloud, logout_of_adeu_cloud } from \"./tools/auth.js\";\nimport {\n search_and_fetch_emails,\n create_email_draft,\n list_available_mailboxes,\n} from \"./tools/email.js\";\nimport { MARKDOWN_UI_URI, EMAIL_UI_URI } from \"./shared.js\";\n\nfunction readFileBytesOrThrow(filePath: string): Buffer {\n try {\n return readFileSync(filePath);\n } catch (err: any) {\n if (err.code === \"ENOENT\") {\n throw new Error(\n `File not found: ${filePath}. Note: If you are running in a sandboxed/containerized environment, ` +\n `the host application or MCP server may not have access to your local workspace files. ` +\n `You can resolve this by installing Adeu directly inside your sandboxed environment using ` +\n `'uv tool install adeu' and executing the commands via the CLI.`\n );\n }\n throw err;\n }\n}\n\n// --- Asset Loaders for UI ---\nconst DIST_DIR = import.meta.dirname;\n\nfunction getAssetContent(\n folder: \"templates\" | \"assets\",\n filename: string,\n fallbackMessage: string,\n): string {\n const filePath = join(DIST_DIR, folder, filename);\n if (existsSync(filePath)) {\n return readFileSync(filePath, \"utf-8\");\n }\n return fallbackMessage;\n}\n\n// --- Tool Description Constants ---\nconst READ_DOCX_COMMON_DESC =\n \"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 =\n \"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 =\n \"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 =\n \"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\nconst DIFF_DOCX_DESC =\n \"Compares two DOCX files and returns a unified diff of their text content. Useful for analyzing differences between versions before editing.\";\n\nconst gitSha = process.env.GIT_SHA || \"unknown\";\nconst buildTs = process.env.BUILD_TIMESTAMP || \"unknown\";\nconst packageVersion = process.env.PACKAGE_VERSION || \"unknown\";\nconst buildTag = ` [Adeu v${packageVersion}+${gitSha}]`;\n\n// --- Server Setup ---\nconst server = new McpServer({\n name: \"adeu-redlining-service\",\n version: packageVersion,\n});\n\n// Wrap server.registerTool to inject buildTag into descriptions\nconst originalRegisterTool = server.registerTool.bind(server);\nserver.registerTool = (name: string, schema: any, handler?: any) => {\n if (schema && typeof schema === \"object\") {\n if (schema.description) {\n schema.description = schema.description.trim() + buildTag;\n }\n }\n return originalRegisterTool(name, schema, handler);\n};\n\n// Wrap registerAppTool to inject buildTag into descriptions\nconst registerAppTool: typeof origRegisterAppTool = (mcpServer, name, schema, handler) => {\n if (schema && typeof schema === \"object\") {\n if (schema.description) {\n schema.description = schema.description.trim() + buildTag;\n }\n }\n return origRegisterAppTool(mcpServer, name, schema, handler);\n};\n\n// Common CSP allowing Google Fonts used by Adeu UI templates\nconst UI_CSP = {\n connectDomains: [\"https://fonts.googleapis.com\", \"https://fonts.gstatic.com\"],\n resourceDomains: [\n \"https://fonts.googleapis.com\",\n \"https://fonts.gstatic.com\",\n ],\n};\n\n// ==========================================\n// 1. UI RESOURCES\n// ==========================================\n\nregisterAppResource(\n server,\n MARKDOWN_UI_URI,\n MARKDOWN_UI_URI,\n { mimeType: RESOURCE_MIME_TYPE, description: \"Adeu Markdown Viewer UI\" },\n async () => {\n let html = getAssetContent(\n \"templates\",\n \"markdown_ui.html\",\n \"<html><body>UI Template Not Found</body></html>\",\n );\n const markedJs = getAssetContent(\n \"assets\",\n \"marked.min.js\",\n \"window.__MARKED_ERROR = 'marked.min.js not found';\",\n );\n const svg = getAssetContent(\"assets\", \"adeu.svg\", \"\");\n\n html = html\n .replace(\"[[marked_js_code | safe]]\", markedJs)\n .replace(\"[[ adeu_svg_code ]]\", svg);\n\n return {\n contents: [\n {\n uri: MARKDOWN_UI_URI,\n mimeType: RESOURCE_MIME_TYPE,\n text: html,\n _meta: { ui: { csp: UI_CSP } },\n },\n ],\n };\n },\n);\n\nregisterAppResource(\n server,\n EMAIL_UI_URI,\n EMAIL_UI_URI,\n { mimeType: RESOURCE_MIME_TYPE, description: \"Adeu Email Viewer UI\" },\n async () => {\n let html = getAssetContent(\n \"templates\",\n \"email_ui.html\",\n \"<html><body>UI Template Not Found</body></html>\",\n );\n const svg = getAssetContent(\"assets\", \"adeu.svg\", \"\");\n\n html = html.replace(\"[[ adeu_svg_code ]]\", svg);\n\n return {\n contents: [\n {\n uri: EMAIL_UI_URI,\n mimeType: RESOURCE_MIME_TYPE,\n text: html,\n _meta: { ui: { csp: UI_CSP } },\n },\n ],\n };\n },\n);\n\n// ==========================================\n// 2. UI-ENABLED TOOLS\n// ==========================================\n\nregisterAppTool(\n server,\n \"read_docx\",\n {\n title: \"Read DOCX\",\n description: READ_DOCX_COMMON_DESC + READ_DOCX_TAIL,\n inputSchema: z.object({\n file_path: z.string().describe(\"Absolute path to the DOCX file.\"),\n clean_view: z\n .boolean()\n .default(false)\n .describe(\n \"If False (default), returns the 'Raw' text with inline CriticMarkup. If True, returns 'Accepted' text.\",\n ),\n mode: z\n .enum([\"full\", \"outline\", \"appendix\"])\n .default(\"full\")\n .describe(\n \"'full' returns body content. 'outline' returns a structural heading map. 'appendix' returns defined terms.\",\n ),\n page: z\n .number()\n .default(1)\n .describe(\"Page number (1-indexed) for mode='full'. Defaults to 1.\"),\n outline_max_level: z\n .number()\n .default(2)\n .describe(\"For mode='outline' only: cap on heading depth.\"),\n outline_verbose: z\n .boolean()\n .default(false)\n .describe(\"For mode='outline' only: includes metadata.\"),\n }),\n _meta: { ui: { resourceUri: MARKDOWN_UI_URI } },\n },\n async ({\n file_path,\n clean_view,\n mode,\n page,\n outline_max_level,\n outline_verbose,\n }) => {\n try {\n const buf = readFileBytesOrThrow(file_path);\n\n if (mode === \"outline\") {\n const doc = await DocumentObject.load(buf);\n const extract_res = _extractTextFromDoc(doc, clean_view, true, true) as {\n text: string;\n paragraph_offsets: Map<any, [number, number]>;\n };\n const res = build_outline_response(\n doc,\n extract_res.text,\n file_path,\n outline_max_level,\n outline_verbose,\n extract_res.paragraph_offsets,\n );\n return res as any;\n }\n\n const text = await extractTextFromBuffer(buf, clean_view);\n if (mode === \"appendix\") {\n const res = build_appendix_response(text, page, file_path);\n return res as any;\n }\n const res = build_paginated_response(text, page, file_path);\n return res as any;\n } catch (e: any) {\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: `Error executing tool read_docx: ${e.message}`,\n },\n ],\n };\n }\n },\n);\n\n\n\nregisterAppTool(\n server,\n \"search_and_fetch_emails\",\n {\n title: \"Search & Fetch Emails\",\n description:\n \"Searches the user's live email inbox via the Adeu cloud backend.\\n\\n\" +\n \"TWO MODES:\\n\" +\n \"1. Search mode (no `email_id`): returns up to `limit` lightweight previews. Use filters (`sender`, `subject`, `is_unread`, `days_ago`, `folder`, `has_attachments`, `attachment_name`) to narrow down.\\n\" +\n \"2. Fetch mode (with `email_id`): returns the full email body, thread history, and downloads attachments under `max_attachment_size_mb` to the local disk.\\n\\n\" +\n \"AUTO-ESCALATION: If a search returns exactly one preview, the backend automatically fetches the full email in the same call. Plan around the response shape — check the `type` field (`previews` vs `full_email`) before assuming.\\n\\n\" +\n \"EMAIL ID FORMATS (`email_id` parameter accepts any of):\\n\" +\n \"- `msg_<6 chars>` — short ID returned by previews on THIS machine. NOT portable across machines or sessions; the local cache holds the most recent 1000. If you reference one that's been evicted, the tool returns a StaleShortIdError telling you to re-search.\\n\" +\n \"- `adeu_<numeric>` — server-side reference for emails Adeu has previously processed. Portable across machines and sessions for the same authenticated user.\\n\" +\n \"- Raw provider ID (Gmail/Outlook native ID) — works if you have it, but you usually won't.\\n\\n\" +\n \"FOLDER DEFAULT: omitting `folder` searches the Inbox only (matching what the user sees in their mail client). Use `folder='sent'` for sent items, `folder='all'` to include Deleted Items, Drafts, and other folders.\\n\\n\" +\n \"ATTACHMENTS: attachments larger than `max_attachment_size_mb` (default 10) are listed in the response but NOT downloaded — raise the cap if you need them. Always set `working_directory` when calling from a project so attachments land alongside the user's other files.\",\n inputSchema: z.object({\n sender: z.string().optional(),\n subject: z.string().optional(),\n has_attachments: z.boolean().optional(),\n attachment_name: z.string().optional(),\n is_unread: z.boolean().optional(),\n days_ago: z.number().optional(),\n folder: z.enum([\"inbox\", \"sent\", \"all\"]).optional(),\n limit: z.number().default(10),\n offset: z.number().default(0),\n email_id: z.string().optional(),\n working_directory: z.string().optional(),\n mailbox_address: z\n .string()\n .optional()\n .describe(\"Optional target mailbox email address to search within.\"),\n task_id: z\n .string()\n .optional()\n .describe(\"If resuming a pending check, provide the task ID here.\"),\n max_attachment_size_mb: z\n .number()\n .optional()\n .describe(\n \"Maximum attachment size in MB to download (default 10). Attachments larger than this are listed in the response but not downloaded. Raise this to fetch large files.\",\n ),\n }),\n _meta: { ui: { resourceUri: EMAIL_UI_URI } },\n },\n async (args) => {\n try {\n return (await search_and_fetch_emails(args)) as any;\n } catch (e: any) {\n return {\n isError: true,\n content: [{ type: \"text\", text: e.message }],\n };\n }\n },\n);\n\n// ==========================================\n// 3. HEADLESS TOOLS (No UI)\n// ==========================================\n\nserver.registerTool(\n \"process_document_batch\",\n {\n description: PROCESS_BATCH_COMMON_DESC + PROCESS_BATCH_OPERATIONS_DESC,\n inputSchema: {\n original_docx_path: z\n .string()\n .describe(\"Absolute path to the source file.\"),\n author_name: z\n .string()\n .describe(\"Name to appear in Track Changes (e.g., 'Reviewer AI').\"),\n changes: z\n .array(z.any())\n .describe(\"List of changes to apply. Each change must specify 'type'.\"),\n output_path: z.string().optional().describe(\"Optional output path.\"),\n dry_run: z\n .boolean()\n .optional()\n .default(false)\n .describe(\n \"If True, simulates the changes and returns a detailed preview report without modifying any files.\",\n ),\n },\n },\n async ({\n original_docx_path,\n author_name,\n changes,\n output_path,\n dry_run,\n }) => {\n try {\n if (!author_name || !author_name.trim())\n return {\n content: [\n { type: \"text\", text: \"Error: author_name cannot be empty.\" },\n ],\n };\n if (!changes || changes.length === 0)\n return {\n content: [{ type: \"text\", text: \"Error: No changes provided.\" }],\n };\n\n let outPath = output_path;\n if (!outPath) {\n const ext = extname(original_docx_path);\n const base = basename(original_docx_path, ext);\n const dir = dirname(original_docx_path);\n outPath = resolve(dir, `${base}_processed${ext}`);\n }\n\n const buf = readFileBytesOrThrow(original_docx_path);\n const doc = await DocumentObject.load(buf);\n const engine = new RedlineEngine(doc, author_name);\n\n let stats;\n try {\n stats = engine.process_batch(changes, dry_run);\n } catch (e: any) {\n if (e instanceof BatchValidationError) {\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: `Batch rejected. Some edits failed validation:\\n\\n${e.errors.join(\"\\n\\n\")}`,\n },\n ],\n };\n }\n throw e;\n }\n\n if (!dry_run) {\n const outBuf = await doc.save();\n fs.writeFileSync(outPath, outBuf);\n }\n\n const res = formatBatchResult(stats, outPath, !!dry_run);\n return { content: [{ type: \"text\", text: res }] };\n } catch (e: any) {\n return {\n isError: true,\n content: [{ type: \"text\", text: `Error: ${e.message}` }],\n };\n }\n },\n);\n\nserver.registerTool(\n \"accept_all_changes\",\n {\n description:\n \"Accepts all tracked changes and removes all comments in a single operation.\",\n inputSchema: {\n docx_path: z.string().describe(\"Absolute path to the DOCX file.\"),\n output_path: z.string().optional().describe(\"Optional output path.\"),\n },\n },\n async ({ docx_path, output_path }) => {\n try {\n let outPath = output_path;\n if (!outPath) {\n const ext = extname(docx_path);\n const base = basename(docx_path, ext);\n const dir = dirname(docx_path);\n outPath = resolve(dir, `${base}_clean${ext}`);\n }\n\n const buf = readFileBytesOrThrow(docx_path);\n const doc = await DocumentObject.load(buf);\n const engine = new RedlineEngine(doc);\n\n engine.accept_all_revisions();\n\n const outBuf = await doc.save();\n\n fs.writeFileSync(outPath, outBuf);\n\n return {\n content: [\n { type: \"text\", text: `Accepted all changes. Saved to: ${outPath}` },\n ],\n };\n } catch (e: any) {\n return {\n isError: true,\n content: [{ type: \"text\", text: `Error: ${e.message}` }],\n };\n }\n },\n);\n\nserver.registerTool(\n \"diff_docx_files\",\n {\n description: DIFF_DOCX_DESC,\n inputSchema: {\n original_path: z\n .string()\n .describe(\"Absolute path to the baseline DOCX file.\"),\n modified_path: z\n .string()\n .describe(\"Absolute path to the modified DOCX file.\"),\n compare_clean: z\n .boolean()\n .default(true)\n .describe(\n \"If True, compares 'Accepted' state. If False, compares raw text.\",\n ),\n },\n },\n async ({ original_path, modified_path, compare_clean }) => {\n try {\n const origBuf = readFileBytesOrThrow(original_path);\n const modBuf = readFileBytesOrThrow(modified_path);\n\n const origText = await extractTextFromBuffer(origBuf, compare_clean);\n const modText = await extractTextFromBuffer(modBuf, compare_clean);\n\n const diff = create_word_patch_diff(\n origText,\n modText,\n basename(original_path),\n basename(modified_path),\n );\n\n return {\n content: [{ type: \"text\", text: diff || \"No differences found.\" }],\n };\n } catch (e: any) {\n return {\n isError: true,\n content: [{ type: \"text\", text: `Error: ${e.message}` }],\n };\n }\n },\n);\n\nserver.registerTool(\n \"finalize_document\",\n {\n description:\n \"Prepares a document for external distribution or e-signature.\",\n inputSchema: {\n file_path: z.string().describe(\"Absolute path to the DOCX file.\"),\n output_path: z.string().optional().describe(\"Optional output path.\"),\n sanitize_mode: z\n .enum([\"full\", \"keep-markup\"])\n .optional()\n .describe(\"full removes all markup, keep-markup redacts metadata.\"),\n accept_all: z\n .boolean()\n .optional()\n .describe(\n \"If true, auto-accepts all unresolved track changes before finalizing.\",\n ),\n protection_mode: z\n .enum([\"read_only\", \"encrypt\"])\n .optional()\n .describe(\"Native OOXML document locking.\"),\n password: z.string().optional().describe(\"Ignored in this environment.\"),\n author: z\n .string()\n .optional()\n .describe(\"Replace all remaining markup authorship with this name.\"),\n export_pdf: z\n .boolean()\n .optional()\n .describe(\"Ignored in this environment.\"),\n },\n },\n async ({\n file_path,\n output_path,\n sanitize_mode,\n accept_all,\n protection_mode,\n author,\n export_pdf,\n }) => {\n try {\n let outPath = output_path;\n if (!outPath) {\n const ext = extname(file_path);\n const base = basename(file_path, ext);\n const dir = dirname(file_path);\n outPath = resolve(dir, `${base}_final${ext}`);\n }\n\n const buf = readFileBytesOrThrow(file_path);\n const doc = await DocumentObject.load(buf);\n\n const result = await finalize_document(doc, {\n filename: basename(file_path),\n sanitize_mode: (sanitize_mode as any) || \"full\",\n accept_all: accept_all as boolean,\n protection_mode: protection_mode as any,\n author: author as string,\n export_pdf: export_pdf as boolean,\n });\n\n fs.writeFileSync(outPath, result.outBuffer!);\n\n return {\n content: [\n {\n type: \"text\",\n text: `Saved to: ${outPath}\\n\\n${result.reportText}`,\n },\n ],\n };\n } catch (e: any) {\n return {\n isError: true,\n content: [{ type: \"text\", text: `Error: ${e.message}` }],\n };\n }\n },\n);\nserver.registerTool(\n \"login_to_adeu_cloud\",\n {\n description:\n \"Logs the user into Adeu Cloud. Opens a browser window for SSO authentication.\\n\\n\" +\n \"IMPORTANT — login is user-level, not account-level:\\n\" +\n \"- An Adeu user can have multiple linked provider accounts (Microsoft, Google) and multiple mailboxes (personal + shared/delegated). One linked account is marked primary.\\n\" +\n \"- Signing in through ANY of the user's linked accounts authenticates the same Adeu user. Once logged in, the session can read from and draft in ALL of that user's linked accounts and ALL of their mailboxes — not just the one used to sign in.\\n\" +\n \"- The choice of which provider account to sign in through is purely an SSO mechanism; it does not select a 'current account' for the session.\\n\\n\" +\n \"When the user asks which accounts or mailboxes are available, call `list_available_mailboxes` rather than naming a single account from the login response.\",\n },\n async () => {\n try {\n return (await login_to_adeu_cloud()) as any;\n } catch (e: any) {\n return { isError: true, content: [{ type: \"text\", text: e.message }] };\n }\n },\n);\n\nserver.registerTool(\n \"logout_of_adeu_cloud\",\n { description: \"Logs out of the Adeu Cloud backend.\" },\n async () => {\n try {\n return (await logout_of_adeu_cloud()) as any;\n } catch (e: any) {\n return { isError: true, content: [{ type: \"text\", text: e.message }] };\n }\n },\n);\nserver.registerTool(\n \"create_email_draft\",\n {\n description:\n \"Creates an email draft in the user's native draft box (Outlook Drafts or Gmail Drafts).\\n\\n\" +\n \"TWO MODES:\\n\" +\n \"1. Reply mode: pass `reply_to_email_id` to create a threaded reply. The draft inherits subject, recipients, and threading headers from the original — do NOT pass `subject` or `to_recipients`.\\n\" +\n \"2. New email mode: omit `reply_to_email_id` and pass BOTH `subject` and `to_recipients`.\\n\\n\" +\n \"`reply_to_email_id` accepts the same ID formats as search_and_fetch_emails (`msg_*` short IDs, `adeu_*` references, or raw provider IDs). Short IDs are validated against the local cache before the call; stale ones fail fast with a clear error telling you to re-search.\\n\\n\" +\n \"`body_markdown` is converted server-side to styled HTML with inlined CSS for email-client compatibility. Write the body in plain Markdown — do not pre-render HTML.\\n\\n\" +\n \"`attachment_paths` takes absolute file paths on the user's local disk and uploads them with the draft. Useful right after search_and_fetch_emails downloaded attachments — those local paths can be passed directly here.\",\n inputSchema: {\n body_markdown: z.string(),\n reply_to_email_id: z.string().optional(),\n subject: z.string().optional(),\n to_recipients: z.array(z.string()).optional(),\n attachment_paths: z.array(z.string()).optional(),\n mailbox_address: z\n .string()\n .optional()\n .describe(\n \"Optional target mailbox email address to create the draft in.\",\n ),\n },\n },\n async (args) => {\n try {\n return (await create_email_draft(args)) as any;\n } catch (e: any) {\n return { isError: true, content: [{ type: \"text\", text: e.message }] };\n }\n },\n);\nserver.registerTool(\n \"list_available_mailboxes\",\n {\n description:\n \"Lists all personal and shared/delegated mailboxes the authenticated Adeu user has access to, across ALL of their linked provider accounts. Returns each mailbox's `email_address`, `display_name`, auto-processing settings, and write-back preference.\\n\\n\" +\n \"This is the right tool to answer 'which accounts/mailboxes am I logged into?' — Adeu login is user-level, so a single MCP session can see every mailbox listed here regardless of which provider account was used for SSO.\\n\\n\" +\n \"Call this FIRST when the user names a specific mailbox or shared inbox, to resolve the canonical `email_address`. Then pass that address as `mailbox_address` to `search_and_fetch_emails` or `create_email_draft` to scope the operation. Omitting `mailbox_address` on those tools targets the user's primary personal mailbox.\",\n inputSchema: {},\n },\n async () => {\n try {\n return (await list_available_mailboxes()) as any;\n } catch (e: any) {\n return { isError: true, content: [{ type: \"text\", text: e.message }] };\n }\n },\n);\n// --- Formatter for process_document_batch ---\nexport function formatBatchResult(\n stats: any,\n outPath: string,\n dry_run: boolean,\n): string {\n let res = \"\";\n if (dry_run) {\n res = `Dry-run simulation complete.\\n`;\n } else {\n res = `Batch complete. Saved to: ${outPath}\\n`;\n }\n res += `Actions: ${stats.actions_applied} applied, ${stats.actions_skipped} skipped.\\n`;\n res += `Edits: ${stats.edits_applied} applied, ${stats.edits_skipped} skipped.\\n`;\n\n if (stats.edits && stats.edits.length > 0) {\n res += \"\\nDetailed Edit Reports:\\n\";\n for (let i = 0; i < stats.edits.length; i++) {\n const report = stats.edits[i];\n const status_indicator =\n report.status === \"applied\" ? \"✅ [applied]\" : \"❌ [failed]\";\n res += `Edit ${i + 1} ${status_indicator}:\\n`;\n res += ` Target: '${report.target_text}'\\n`;\n res += ` New text: '${report.new_text}'\\n`;\n if (report.warning) {\n res += ` Warning: ${report.warning}\\n`;\n }\n if (report.error) {\n res += ` Error: ${report.error}\\n`;\n }\n if (report.critic_markup) {\n res += ` Preview (CriticMarkup): ${report.critic_markup}\\n`;\n }\n if (report.clean_text) {\n res += ` Clean text preview: ${report.clean_text}\\n`;\n }\n }\n }\n\n if (stats.skipped_details && stats.skipped_details.length > 0) {\n res += `\\n\\nSkipped Details:\\n${stats.skipped_details.join(\"\\n\")}`;\n }\n return res;\n}\n\n// --- Startup ---\nasync function main() {\n const transport = new StdioServerTransport();\n await server.connect(transport);\n const gitSha = process.env.GIT_SHA || \"unknown\";\n const buildTs = process.env.BUILD_TIMESTAMP || \"unknown\";\n console.error(\n `Adeu MCP Server (Node.js Engine: ${identifyEngine()}) running on stdio build=${gitSha}@${buildTs}`,\n );\n}\n\nmain().catch(console.error);\n","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 structuredContent?: any;\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(\n page: number,\n total: number,\n has_next: boolean,\n): 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(\n nodes: OutlineNode[],\n max_level: number = 2,\n verbose: boolean = false,\n): 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)\n 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(\n text: string,\n page: number,\n file_path: string,\n): 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(\n `Page ${page} out of range (doc has ${result.total_pages} pages).`,\n );\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(\n selected.page,\n selected.total_pages,\n selected.has_next,\n );\n const appendix_pointer = _build_appendix_pointer(has_appendix);\n\n const ui_markdown =\n 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 // Include structuredContent for the UI to render the markdown\n structuredContent: {\n markdown: ui_markdown,\n file_path: resolve(file_path),\n title: basename(file_path),\n },\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 paragraph_offsets: Map<any, [number, number]> | null = null,\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 paragraph_offsets,\n );\n\n const rendered = render_outline_tree(\n nodes,\n outline_max_level,\n outline_verbose,\n );\n\n const visible_count = nodes.filter(\n (n) => n.level <= outline_max_level,\n ).length;\n const deeper_count = nodes.length - visible_count;\n const deeper_hint =\n deeper_count > 0\n ? ` (${deeper_count} more at deeper levels, raise outline_max_level to see)`\n : \"\";\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 structuredContent: {\n markdown: ui_markdown,\n file_path: resolve(file_path),\n title: `Outline: ${basename(file_path)}`,\n },\n };\n}\n\nexport function build_appendix_response(\n text: string,\n page: number,\n file_path: string,\n): ToolResult {\n const [, appendix] = split_structural_appendix(text);\n\n if (!appendix.trim()) {\n const ui_markdown =\n \"# 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 structuredContent: {\n markdown: ui_markdown,\n file_path: resolve(file_path),\n title: `Appendix: ${basename(file_path)}`,\n },\n };\n }\n\n const result = paginate(appendix, \"\");\n\n if (page < 1 || page > result.total_pages) {\n throw new Error(\n `Appendix page ${page} out of range (appendix has ${result.total_pages} pages).`,\n );\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\\n> **Continues on appendix page ${selected.page + 1} of ${selected.total_pages}.**`\n : \"\";\n } else {\n banner =\n \"> **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 structuredContent: {\n markdown: ui_markdown,\n file_path: resolve(file_path),\n title: `Appendix: ${basename(file_path)}`,\n },\n };\n}\n","// FILE: node/packages/mcp-server/src/desktop-auth.ts\nimport { createServer, Server } from \"node:http\";\nimport { exec } from \"node:child_process\";\nimport { homedir, platform } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n writeFileSync,\n readFileSync,\n mkdirSync,\n existsSync,\n rmSync,\n chmodSync,\n} from \"node:fs\";\nimport { FRONTEND_URL } from \"./shared.js\";\n\nconst ADEU_DIR = join(homedir(), \".adeu\");\nconst CRED_PATH = join(ADEU_DIR, \"credentials.json\");\n\nfunction openBrowser(url: string) {\n if (platform() === \"darwin\") exec(`open \"${url}\"`);\n else if (platform() === \"win32\") exec(`start \"\" \"${url}\"`);\n else exec(`xdg-open \"${url}\"`);\n}\n\nexport class DesktopAuthManager {\n static getApiKey(): string | null {\n if (!existsSync(CRED_PATH)) return null;\n try {\n const data = JSON.parse(readFileSync(CRED_PATH, \"utf-8\"));\n return data.api_key || null;\n } catch {\n return null;\n }\n }\n\n static setApiKey(apiKey: string): void {\n if (!existsSync(ADEU_DIR)) {\n mkdirSync(ADEU_DIR, { recursive: true });\n }\n writeFileSync(CRED_PATH, JSON.stringify({ api_key: apiKey }));\n // Restrict read/write to the current user only (equivalent to 0o600)\n chmodSync(CRED_PATH, 0o600);\n }\n\n static clearApiKey(): void {\n if (existsSync(CRED_PATH)) {\n rmSync(CRED_PATH);\n }\n }\n\n static async authenticateInteractive(): Promise<string> {\n return new Promise((resolve, reject) => {\n let server: Server;\n\n const timeout = setTimeout(\n () => {\n if (server) server.close();\n reject(new Error(\"Authentication timed out after 5 minutes.\"));\n },\n 5 * 60 * 1000,\n );\n\n server = createServer((req, res) => {\n const url = new URL(req.url || \"\", `http://${req.headers.host}`);\n\n if (url.pathname === \"/callback\") {\n const apiKey = url.searchParams.get(\"api_key\");\n\n res.writeHead(apiKey ? 200 : 400, { \"Content-Type\": \"text/html\" });\n const title = apiKey\n ? \"Authentication Successful!\"\n : \"Authentication Failed\";\n const text = apiKey\n ? \"Your Adeu MCP server has been successfully authenticated. You can safely close this window and return to Claude.\"\n : \"No API key received. Please try again.\";\n const color = apiKey ? \"#107c10\" : \"#d83b01\";\n\n res.end(`\n <!DOCTYPE html><html><head><title>${title}</title>\n <style>body{font-family:sans-serif;text-align:center;padding:50px;background:#f3f2f1;}.container{background:white;padding:40px;border-radius:8px;box-shadow:0 2px 4px rgba(0,0,0,0.1);max-width:500px;margin:0 auto;}h1{color:${color};}p{color:#605e5c;line-height:1.5;}</style>\n </head><body><div class=\"container\"><h1>${title}</h1><p>${text}</p>\n <script>setTimeout(()=>window.close(), 3000);</script>\n </div></body></html>\n `);\n\n clearTimeout(timeout);\n // Allow response to send before closing server\n setTimeout(() => server.close(), 100);\n\n if (apiKey) {\n this.setApiKey(apiKey);\n resolve(apiKey);\n } else {\n reject(new Error(\"No API key received in callback.\"));\n }\n } else {\n res.writeHead(404);\n res.end();\n }\n });\n\n server.listen(0, \"127.0.0.1\", () => {\n const address = server.address();\n if (address && typeof address !== \"string\") {\n const authUrl = `${FRONTEND_URL}/login?desktop_port=${address.port}`;\n openBrowser(authUrl);\n }\n });\n });\n }\n\n static async ensureAuthenticated(): Promise<string> {\n const key = this.getApiKey();\n if (key) return key;\n return this.authenticateInteractive();\n }\n}\n\nexport async function getCloudAuthToken(): Promise<string> {\n const key = DesktopAuthManager.getApiKey();\n if (!key) {\n throw new Error(\n \"Authentication Required: You are not logged in. Please call the `login_to_adeu_cloud` tool first to authenticate, then try this task again.\",\n );\n }\n return key;\n}\n","// FILE: node/packages/mcp-server/src/shared.ts\nexport const FRONTEND_URL =\n process.env.ADEU_FRONTEND_URL || \"https://app.adeu.ai\";\nexport const BACKEND_URL =\n process.env.ADEU_BACKEND_URL || \"https://app.adeu.ai\";\nexport const MARKDOWN_UI_URI = \"ui://adeu/markdown-ui\";\nexport const EMAIL_UI_URI = \"ui://adeu/email-ui\";\n","// FILE: node/packages/mcp-server/src/tools/auth.ts\nimport { DesktopAuthManager } from \"../desktop-auth.js\";\nimport { BACKEND_URL } from \"../shared.js\";\nimport { ToolResult } from \"../response-builders.js\";\n\nexport async function login_to_adeu_cloud(): Promise<ToolResult> {\n try {\n const apiKey = await DesktopAuthManager.ensureAuthenticated();\n\n const res = await fetch(`${BACKEND_URL}/api/v1/auth/me`, {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"application/json\",\n },\n signal: AbortSignal.timeout(15_000),\n });\n\n if (res.status === 401) {\n DesktopAuthManager.clearApiKey();\n throw new Error(\n \"Your previous session expired. The stale key has been cleared. Please call `login_to_adeu_cloud` ONE MORE TIME to log in fresh.\",\n );\n }\n if (!res.ok) throw new Error(`HTTP Error: ${res.status}`);\n\n const data: any = await res.json();\n const email = data.email || \"Unknown Email\";\n return {\n content: [\n {\n type: \"text\",\n text:\n `Login successful. You are now authenticated to Adeu Cloud as the user ` +\n `who owns the provider account \\`${email}\\` (the account used for SSO).\\n\\n` +\n `This single login grants access to ALL of this user's linked provider ` +\n `accounts and ALL of their mailboxes for the duration of this session — ` +\n `not just \\`${email}\\`. Call \\`list_available_mailboxes\\` to see every mailbox ` +\n `that can be queried or drafted from.`,\n },\n ],\n };\n } catch (err: any) {\n return { isError: true, content: [{ type: \"text\", text: err.message }] };\n }\n}\n\nexport async function logout_of_adeu_cloud(): Promise<ToolResult> {\n DesktopAuthManager.clearApiKey();\n return {\n content: [\n {\n type: \"text\",\n text: \"Successfully logged out. The local API key has been removed.\",\n },\n ],\n };\n}\n","import { homedir, tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { readFileSync, writeFileSync, mkdirSync, existsSync } from \"node:fs\";\nimport { DesktopAuthManager, getCloudAuthToken } from \"../desktop-auth.js\";\nimport { BACKEND_URL } from \"../shared.js\";\nimport { ToolResult } from \"../response-builders.js\";\nimport { createHash } from \"node:crypto\";\nconst KNOWN_ERROR_HINTS: Record<string, string> = {\n \"Email not found.\":\n \"The email ID was not found. If this was a short ID (msg_*), it may have been \" +\n \"evicted from the local cache or come from a different machine — re-run \" +\n \"search_and_fetch_emails with filters to get a fresh ID. If it was an \" +\n \"adeu_<numeric> or raw provider ID, verify it's correct.\",\n \"Adeu email reference not found.\":\n \"The adeu_<id> reference doesn't resolve to any processed email for this user. \" +\n \"Verify the ID, or re-run search_and_fetch_emails with filters to find the message.\",\n \"Invalid adeu_ email ID format.\":\n \"The adeu_<id> reference is malformed. Expected format: adeu_<integer>.\",\n};\n\nfunction formatBackendError(statusCode: number, responseBody: string): string {\n let detail = responseBody;\n try {\n const parsed = JSON.parse(responseBody);\n if (parsed && typeof parsed === \"object\" && \"detail\" in parsed) {\n detail = String(parsed.detail);\n }\n } catch {\n // responseBody isn't JSON — use it as-is\n }\n\n let hint = KNOWN_ERROR_HINTS[detail];\n if (\n !hint &&\n detail.startsWith(\"Mailbox '\") &&\n detail.endsWith(\"' not found.\")\n ) {\n const mailbox = detail.slice(\"Mailbox '\".length, -\"' not found.\".length);\n hint =\n `The mailbox '${mailbox}' is not connected to your Adeu account. ` +\n \"Call list_available_mailboxes to see valid mailbox addresses, then retry \" +\n \"with one of those as `mailbox_address`.\";\n }\n\n const message = hint ?? detail;\n return `Cloud search failed (HTTP ${statusCode}): ${message}`;\n}\nfunction isTimeoutError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const name = (err as { name?: string }).name;\n return name === \"TimeoutError\" || name === \"AbortError\";\n}\n\nconst CACHE_FILE = join(homedir(), \".adeu\", \"mcp_id_cache.json\");\nconst MAX_CACHE_SIZE = 1000;\n\nfunction formatBytes(bytes: number | null | undefined): string {\n if (bytes == null) return \"unknown size\";\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nfunction loadIdCache(): Record<string, string> {\n if (existsSync(CACHE_FILE)) {\n try {\n return JSON.parse(readFileSync(CACHE_FILE, \"utf-8\"));\n } catch {\n return {};\n }\n }\n return {};\n}\n\nfunction saveIdCache(cache: Record<string, string>): void {\n try {\n mkdirSync(join(homedir(), \".adeu\"), { recursive: true });\n const keys = Object.keys(cache);\n if (keys.length > MAX_CACHE_SIZE) {\n const trimmed: Record<string, string> = {};\n keys.slice(-MAX_CACHE_SIZE).forEach((k) => (trimmed[k] = cache[k]));\n cache = trimmed;\n }\n writeFileSync(CACHE_FILE, JSON.stringify(cache));\n } catch {\n /* ignore */\n }\n}\n\nfunction minifyEmailId(realId: string, cache: Record<string, string>): string {\n if (!realId) return realId;\n const hash = createHash(\"md5\").update(realId).digest(\"hex\").slice(0, 6);\n const shortId = `msg_${hash}`;\n cache[shortId] = realId;\n return shortId;\n}\n\nclass StaleShortIdError extends Error {\n constructor(shortId: string) {\n super(\n `Short ID '${shortId}' is not in the local cache (it may have been evicted, or it came from a different machine/session). ` +\n `Short IDs only persist on the machine where they were generated. ` +\n `Re-run search_and_fetch_emails with filters (sender, subject, days_ago) to fetch fresh IDs, then use the new ID from those results.`,\n );\n this.name = \"StaleShortIdError\";\n }\n}\n\nfunction resolveEmailId(shortId: string): string {\n if (!shortId) return shortId;\n // adeu_<id> references are resolved server-side, pass through.\n if (shortId.startsWith(\"adeu_\")) return shortId;\n const cache = loadIdCache();\n const resolved = cache[shortId];\n if (resolved) return resolved;\n // If it looks like one of our short IDs but isn't in the cache, fail loudly\n // instead of silently passing a meaningless string to the provider.\n if (shortId.startsWith(\"msg_\")) {\n throw new StaleShortIdError(shortId);\n }\n // Otherwise treat it as a raw provider ID\n return shortId;\n}\n\nconst HTML_NAMED_ENTITIES: Record<string, string> = {\n nbsp: \" \",\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n copy: \"\\u00A9\",\n reg: \"\\u00AE\",\n trade: \"\\u2122\",\n hellip: \"\\u2026\",\n mdash: \"\\u2014\",\n ndash: \"\\u2013\",\n lsquo: \"\\u2018\",\n rsquo: \"\\u2019\",\n ldquo: \"\\u201C\",\n rdquo: \"\\u201D\",\n laquo: \"\\u00AB\",\n raquo: \"\\u00BB\",\n bull: \"\\u2022\",\n middot: \"\\u00B7\",\n deg: \"\\u00B0\",\n plusmn: \"\\u00B1\",\n times: \"\\u00D7\",\n divide: \"\\u00F7\",\n euro: \"\\u20AC\",\n pound: \"\\u00A3\",\n yen: \"\\u00A5\",\n cent: \"\\u00A2\",\n sect: \"\\u00A7\",\n para: \"\\u00B6\",\n iexcl: \"\\u00A1\",\n iquest: \"\\u00BF\",\n};\n\nfunction decodeHtmlEntities(text: string): string {\n // Numeric: &#1234; (decimal) and &#x1F4A9; (hex)\n text = text.replace(/&#(\\d+);/g, (_, dec: string) => {\n const code = parseInt(dec, 10);\n return Number.isFinite(code) ? String.fromCodePoint(code) : _;\n });\n text = text.replace(/&#[xX]([0-9a-fA-F]+);/g, (_, hex: string) => {\n const code = parseInt(hex, 16);\n return Number.isFinite(code) ? String.fromCodePoint(code) : _;\n });\n // Named: &amp;, &rsquo;, etc.\n text = text.replace(/&([a-zA-Z][a-zA-Z0-9]*);/g, (match, name: string) => {\n const replacement = HTML_NAMED_ENTITIES[name.toLowerCase()];\n return replacement !== undefined ? replacement : match;\n });\n return text;\n}\n\nfunction stripTags(html: string): string {\n if (!html) return \"\";\n\n // 1. Strip suppressed blocks (style/script/head/title) — loop until stable to\n // handle nested or malformed blocks. Matches Python MLStripper's structural\n // suppression rather than relying on a single greedy pass.\n let text = html;\n const suppressPattern =\n /<(style|script|head|title)\\b[^>]*>[\\s\\S]*?<\\/\\1\\s*>/gi;\n let prev: string;\n do {\n prev = text;\n text = text.replace(suppressPattern, \"\");\n } while (text !== prev);\n\n // 2. Also strip orphan open tags for suppressed blocks (unclosed <style ...>)\n // by killing from the open tag to end of document — safer than leaking CSS\n // into the LLM output.\n text = text.replace(/<(style|script|head|title)\\b[^>]*>[\\s\\S]*$/gi, \"\");\n\n // 3. Convert block-level closing tags to newlines so paragraph structure survives\n text = text.replace(\n /<\\/?(p|div|br|hr|tr|li|h[1-6]|blockquote)\\b[^>]*>/gi,\n \"\\n\",\n );\n\n // 4. Strip all remaining tags\n text = text.replace(/<[^>]+>/g, \"\");\n\n // 5. Decode HTML entities (named + numeric, matches Python's html.unescape).\n text = decodeHtmlEntities(text);\n\n // 6. Collapse triple-or-more newlines down to a paragraph break\n return text.replace(/\\n\\s*\\n\\s*\\n+/g, \"\\n\\n\").trim();\n}\n\nfunction removeNestedQuotes(text: string): string {\n if (!text) return \"\";\n\n // Localized \"From:\" header tokens from Outlook in major European locales.\n // Order matters only for readability; matching is anchored independently.\n const fromTokens = [\n \"From\", // English\n \"Lähettäjä\", // Finnish\n \"Från\", // Swedish\n \"Von\", // German\n \"De\", // French / Spanish / Portuguese\n \"Da\", // Italian\n \"Van\", // Dutch\n \"Fra\", // Norwegian / Danish\n \"Mittente\", // Italian (alt)\n ];\n\n // Localized \"Sent:\" tokens (paired with From: in Outlook quote blocks)\n const sentTokens = [\n \"Sent\",\n \"Lähetetty\",\n \"Skickat\",\n \"Gesendet\",\n \"Envoyé\",\n \"Enviado\",\n \"Inviato\",\n \"Verzonden\",\n \"Sendt\",\n ];\n\n // Localized \"On ... wrote:\" / \"X wrote on Y:\" patterns from Gmail-style clients\n const wrotePatterns = [\n /On .{1,200}? wrote:/, // English\n /Le .{1,200}? a écrit\\s*:/i, // French\n /Am .{1,200}? schrieb .{1,100}?:/i, // German\n /El .{1,200}? escribió\\s*:/i, // Spanish\n /Il .{1,200}? ha scritto\\s*:/i, // Italian\n /Op .{1,200}? schreef .{1,100}?:/i, // Dutch\n /Den .{1,200}? skrev .{1,100}?:/i, // Swedish/Norwegian/Danish\n /Em .{1,200}? escreveu\\s*:/i, // Portuguese\n /Em\\b.{1,200}?, .{1,200}? escreveu\\s*:/i, // Portuguese (date prefix)\n new RegExp(\n `^(${fromTokens.join(\"|\")})\\\\s*:.*?\\\\n(?:.*\\\\n){0,5}?(${sentTokens.join(\"|\")})\\\\s*:`,\n \"m\",\n ),\n ];\n\n // Localized \"Forwarded message\" markers across the same locale set.\n // Once hit, everything below is a quoted historical message and should be cut.\n const forwardedTokens = [\n \"Forwarded message\",\n \"Välitetty viesti\",\n \"Vidarebefordrat meddelande\",\n \"Weitergeleitete Nachricht\",\n \"Message transféré\",\n \"Mensaje reenviado\",\n \"Messaggio inoltrato\",\n \"Doorgestuurd bericht\",\n \"Videresendt melding\",\n \"Videresendt meddelelse\",\n \"Mensagem encaminhada\",\n ].join(\"|\");\n\n const dividerPatterns = [\n /_{10,}/m,\n /-----\\s*(Original Message|Alkuperäinen viesti|Ursprüngliches Nachricht|Message d'origine|Mensaje original|Messaggio originale|Oorspronkelijk bericht|Original meddelande)\\s*-----/im,\n /^(Original Message|Alkuperäinen viesti|Ursprüngliches Nachricht|Message d'origine|Mensaje original|Messaggio originale|Oorspronkelijk bericht)$/im,\n // Gmail/Outlook-style \"---------- Forwarded message ---------\" with localized variants\n new RegExp(`-+\\\\s*(${forwardedTokens})\\\\s*-+`, \"i\"),\n new RegExp(`^(${forwardedTokens})$`, \"im\"),\n ];\n\n const allPatterns = [...wrotePatterns, ...dividerPatterns];\n\n let earliestCut = text.length;\n for (const pattern of allPatterns) {\n const match = pattern.exec(text);\n if (match && match.index < earliestCut) {\n earliestCut = match.index;\n }\n }\n return text.substring(0, earliestCut).trim();\n}\n\nfunction getUniqueFilepath(saveDir: string, filename: string): string {\n // Re-fetches of the same email overwrite the existing file rather than\n // accumulating `_1`, `_2`, `_3` copies. The `<short_id>/` subdirectory\n // already disambiguates across emails, so collisions inside it always\n // mean the same logical attachment.\n return join(saveDir, filename);\n}\nexport async function search_and_fetch_emails(args: any): Promise<ToolResult> {\n const apiKey = await getCloudAuthToken();\n const maxAttachmentSizeMb: number =\n typeof args.max_attachment_size_mb === \"number\" &&\n args.max_attachment_size_mb > 0\n ? args.max_attachment_size_mb\n : 10;\n\n let data: any;\n\n if (args.task_id) {\n // ==========================================\n // PHASE 2: POLL (Wait for completion)\n // ==========================================\n const pollUrl = `${BACKEND_URL}/api/v1/emails/tasks/${args.task_id}`;\n let completedData: any = null;\n\n for (let attempt = 0; attempt < 10; attempt++) {\n let res: Response;\n try {\n res = await fetch(pollUrl, {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"application/json\",\n },\n signal: AbortSignal.timeout(15_000),\n });\n } catch (err) {\n if (isTimeoutError(err)) {\n throw new Error(\"Checking task status timed out.\");\n }\n throw err;\n }\n\n if (res.status === 401) {\n DesktopAuthManager.clearApiKey();\n throw new Error(\n \"Authentication expired. Please call `login_to_adeu_cloud` to re-authenticate.\",\n );\n }\n if (!res.ok) {\n throw new Error(formatBackendError(res.status, await res.text()));\n }\n\n const taskData: any = await res.json();\n const status = taskData.status;\n\n if (status === \"COMPLETED\") {\n completedData = taskData;\n break;\n }\n\n if (status === \"FAILED\") {\n const errorMsg = taskData.error || \"Unknown internal error\";\n throw new Error(`Validation task failed on the server: ${errorMsg}`);\n }\n\n // Wait 5 seconds before next poll\n await new Promise((resolve) => setTimeout(resolve, 5000));\n }\n\n if (!completedData) {\n const msg = `Task ${args.task_id} is still processing. Please call \\`search_and_fetch_emails\\` again with task_id=${args.task_id}.`;\n return {\n content: [{ type: \"text\", text: msg }],\n structuredContent: {\n status: \"pending\",\n task_id: args.task_id,\n message: msg,\n },\n };\n }\n\n data = completedData;\n\n } else {\n // ==========================================\n // PHASE 1: INIT / SEARCH (Search/Fetch standard)\n // ==========================================\n let realEmailId: string | undefined;\n try {\n realEmailId = args.email_id ? resolveEmailId(args.email_id) : undefined;\n } catch (err) {\n if (err instanceof StaleShortIdError) {\n return {\n isError: true,\n content: [{ type: \"text\", text: err.message }],\n };\n }\n throw err;\n }\n\n const payload = {\n email_id: realEmailId,\n sender: args.sender,\n subject: args.subject,\n has_attachments: args.has_attachments,\n attachment_name: args.attachment_name,\n is_unread: args.is_unread,\n days_ago: args.days_ago,\n folder: args.folder,\n limit: args.limit ?? 10,\n offset: args.offset ?? 0,\n mailbox_address: args.mailbox_address,\n };\n\n // Remove undefined fields\n Object.keys(payload).forEach(\n (k) => (payload as any)[k] === undefined && delete (payload as any)[k],\n );\n\n let res: Response;\n try {\n res = await fetch(`${BACKEND_URL}/api/v1/emails/search`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(45_000),\n });\n } catch (err) {\n if (isTimeoutError(err)) {\n throw new Error(\n \"Email search timed out after 45s. The mail provider (Outlook/Gmail) may be slow. Try narrowing the search with more filters (sender, subject, days_ago), or retry shortly.\",\n );\n }\n throw err;\n }\n\n if (res.status === 401) {\n DesktopAuthManager.clearApiKey();\n throw new Error(\n \"Authentication expired. Please call `login_to_adeu_cloud` to re-authenticate.\",\n );\n }\n if (!res.ok)\n throw new Error(formatBackendError(res.status, await res.text()));\n\n data = await res.json();\n\n if (res.status === 202 || (data && (data.status === \"pending\" || data.task_id) && data.type === undefined)) {\n const newTaskId = data.task_id;\n const msg = `Email processing task started successfully. Task ID: ${newTaskId}. Please call \\`search_and_fetch_emails\\` again immediately with task_id=${newTaskId} to monitor the progress.`;\n return {\n content: [{ type: \"text\", text: msg }],\n structuredContent: {\n status: \"pending\",\n task_id: String(newTaskId),\n message: msg,\n },\n };\n }\n }\n\n const cache = loadIdCache();\n\n if (data.type === \"previews\") {\n const previews = data.previews || [];\n if (!previews.length)\n return {\n content: [\n {\n type: \"text\",\n text: \"No emails found matching your search criteria.\",\n },\n ],\n };\n\n const lines = [\n `Found ${previews.length} email(s). Here are the previews:`,\n \"\",\n ];\n for (const p of previews) {\n const shortId = minifyEmailId(p.id, cache);\n const attFlag = p.has_attachments ? \"📎 (Has Attachments)\" : \"\";\n const unreadFlag = p.is_read === false ? \"🟢 [UNREAD]\" : \"\";\n lines.push(\n `- **ID**: \\`${shortId}\\`\\n **Subject**: ${p.subject} ${attFlag} ${unreadFlag}\\n **From**: ${p.sender_name} <${p.sender_email}>\\n **Date**: ${p.received_datetime}\\n **Preview**: ${p.preview_text}\\n`,\n );\n }\n\n saveIdCache(cache);\n\n const limit: number = typeof args.limit === \"number\" ? args.limit : 10;\n const offset: number = typeof args.offset === \"number\" ? args.offset : 0;\n const pageHint =\n previews.length >= limit\n ? `\\n*(If you need to see more results, call this tool again with offset=${offset + limit})*`\n : \"\";\n\n lines.push(\n \"⚠️ **ACTION REQUIRED**: To read the full body of an email and download its attachments, call this tool again and provide the exact `email_id`.\" +\n pageHint,\n );\n return {\n content: [{ type: \"text\", text: lines.join(\"\\n\") }],\n structuredContent: data,\n };\n }\n\n if (data.type === \"full_email\") {\n const full = data.full_email || {};\n const shortTargetId = minifyEmailId(full.id || \"unknown_id\", cache);\n\n saveIdCache(cache);\n\n // Detect auto-escalation: the caller asked for previews (no email_id) but\n // the backend found exactly one match and returned a full email instead.\n // Flag it so the agent doesn't get blindsided by a wall of body text when\n // it asked for a list.\n const autoEscalated =\n !args.email_id &&\n (args.sender !== undefined ||\n args.subject !== undefined ||\n args.has_attachments !== undefined ||\n args.attachment_name !== undefined ||\n args.is_unread !== undefined ||\n args.days_ago !== undefined ||\n args.folder !== undefined);\n\n const baseDir =\n args.working_directory && existsSync(args.working_directory)\n ? args.working_directory\n : tmpdir();\n const saveDir = join(\n baseDir,\n args.working_directory ? \"adeu_attachments\" : \"adeu_downloads\",\n shortTargetId,\n );\n mkdirSync(saveDir, { recursive: true });\n\n interface SkippedAttachment {\n filename: string;\n size_bytes: number | null;\n reason: string;\n }\n\n async function processAttachments(\n msg: any,\n ): Promise<{ localFiles: string[]; skipped: SkippedAttachment[] }> {\n const localFiles: string[] = [];\n const skipped: SkippedAttachment[] = [];\n const maxBytes = maxAttachmentSizeMb * 1024 * 1024;\n\n for (const att of msg.attachments || []) {\n const filename = att.filename || \"unnamed_file\";\n const size: number | null =\n typeof att.size_bytes === \"number\" ? att.size_bytes : null;\n\n // Size cap: skip download but record it so the agent knows the file exists\n if (size != null && size > maxBytes) {\n skipped.push({\n filename,\n size_bytes: size,\n reason: `exceeds ${maxAttachmentSizeMb} MB cap`,\n });\n delete att.base64_data; // Drop payload from structured response too\n continue;\n }\n\n if (att.base64_data) {\n try {\n const filepath = getUniqueFilepath(saveDir, filename);\n writeFileSync(filepath, Buffer.from(att.base64_data, \"base64\"));\n localFiles.push(filepath);\n att.local_path = filepath; // For UI rendering (matches Python parity)\n delete att.base64_data; // Free memory\n } catch (e) {\n console.error(`Failed to save attachment ${filename}`, e);\n skipped.push({\n filename,\n size_bytes: size,\n reason: `download failed: ${(e as Error).message}`,\n });\n }\n }\n }\n return { localFiles, skipped };\n }\n\n const { localFiles: targetFiles, skipped: targetSkipped } =\n await processAttachments(full);\n const lines: string[] = [];\n if (autoEscalated) {\n lines.push(\n \"_(Search returned exactly one result; auto-fetched full email below.)_\\n\",\n );\n }\n lines.push(\n `# Email Thread: ${full.subject}`,\n \"\",\n \"## Target Message (Newest):\",\n `**From**: ${full.sender_name} <${full.sender_email}>`,\n `**Date**: ${full.received_datetime}`,\n );\n\n if (targetFiles.length) {\n lines.push(\"**Attachments Saved Locally**:\");\n targetFiles.forEach((f) => lines.push(`- 📎 \\`${f}\\``));\n }\n\n if (targetSkipped.length) {\n lines.push(\n `**Attachments Skipped (not downloaded)** — pass \\`max_attachment_size_mb\\` to raise the ${maxAttachmentSizeMb} MB cap:`,\n );\n targetSkipped.forEach((s) =>\n lines.push(\n `- ⚠️ \\`${s.filename}\\` (${formatBytes(s.size_bytes)}, ${s.reason})`,\n ),\n );\n }\n\n const cleanBody = removeNestedQuotes(stripTags(full.body_html || \"\"));\n lines.push(`**Body**:\\n\\`\\`\\`\\n${cleanBody}\\n\\`\\`\\`\\n`);\n\n if (full.is_thread && full.messages?.length) {\n lines.push(\"## Previous Messages in Thread (Historical Context):\");\n for (let i = 0; i < full.messages.length; i++) {\n const histMsg = full.messages[i];\n const { localFiles: histFiles, skipped: histSkipped } =\n await processAttachments(histMsg);\n lines.push(\n `### Message -${i + 1} (Older)\\n**From**: ${histMsg.sender_name} <${histMsg.sender_email}>\\n**Date**: ${histMsg.received_datetime}`,\n );\n if (histFiles.length) {\n lines.push(\"**Attachments Saved Locally**:\");\n histFiles.forEach((f) => lines.push(`- 📎 \\`${f}\\``));\n }\n if (histSkipped.length) {\n lines.push(\n `**Attachments Skipped (not downloaded)** — pass \\`max_attachment_size_mb\\` — raise the cap:`,\n );\n histSkipped.forEach((s) =>\n lines.push(\n `- ⚠️ \\`${s.filename}\\` (${formatBytes(s.size_bytes)}, ${s.reason})`,\n ),\n );\n }\n lines.push(\n `**Body**:\\n\\`\\`\\`\\n${removeNestedQuotes(stripTags(histMsg.body_html || \"\"))}\\n\\`\\`\\`\\n`,\n );\n }\n }\n\n // --- Finding #9 downstream tool suggestions parity ---\n const hasAttachments =\n targetFiles.length > 0 ||\n (full.messages &&\n full.messages.some(\n (m: any) => m.attachments && m.attachments.length > 0,\n ));\n\n if (hasAttachments) {\n lines.push(\n \"\\n*You can now use tools like `read_docx`, `diff_docx_files`, or `finalize_document` on the local file paths listed under each message.*\",\n );\n }\n\n return {\n content: [{ type: \"text\", text: lines.join(\"\\n\") }],\n structuredContent: data,\n };\n }\n\n return {\n isError: true,\n content: [{ type: \"text\", text: \"Unknown response format from backend.\" }],\n };\n}\n\nexport async function create_email_draft(args: any): Promise<ToolResult> {\n const apiKey = await getCloudAuthToken();\n if (!args.reply_to_email_id && (!args.subject || !args.to_recipients)) {\n throw new Error(\n \"You must provide either 'reply_to_email_id' OR both 'subject' and 'to_recipients'.\",\n );\n }\n\n const formData = new FormData();\n formData.append(\"body_markdown\", args.body_markdown);\n\n if (args.reply_to_email_id) {\n try {\n formData.append(\n \"reply_to_email_id\",\n resolveEmailId(args.reply_to_email_id),\n );\n } catch (err) {\n if (err instanceof StaleShortIdError) {\n return {\n isError: true,\n content: [{ type: \"text\", text: err.message }],\n };\n }\n throw err;\n }\n }\n if (args.subject) formData.append(\"subject\", args.subject);\n if (args.mailbox_address) {\n formData.append(\"mailbox_address\", args.mailbox_address);\n }\n\n if (args.to_recipients) {\n const recips =\n typeof args.to_recipients === \"string\"\n ? JSON.parse(args.to_recipients)\n : args.to_recipients;\n formData.append(\"to_recipients\", JSON.stringify(recips));\n }\n\n if (args.attachment_paths) {\n const paths =\n typeof args.attachment_paths === \"string\"\n ? JSON.parse(args.attachment_paths)\n : args.attachment_paths;\n for (const p of paths) {\n const buf = readFileSync(p);\n const filename = p.split(/[/\\\\]/).pop();\n formData.append(\"files\", new Blob([buf]), filename);\n }\n }\n\n let res: Response;\n try {\n res = await fetch(`${BACKEND_URL}/api/v1/emails/drafts/new`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"application/json\",\n },\n body: formData as any,\n signal: AbortSignal.timeout(90_000),\n });\n } catch (err) {\n if (isTimeoutError(err)) {\n throw new Error(\n \"Draft creation timed out after 90s. If the draft includes large attachments, try splitting them across multiple drafts or omitting the largest files.\",\n );\n }\n throw err;\n }\n\n if (res.status === 401) {\n DesktopAuthManager.clearApiKey();\n throw new Error(\n \"Authentication expired. Please call `login_to_adeu_cloud`.\",\n );\n }\n if (!res.ok)\n throw new Error(formatBackendError(res.status, await res.text()));\n\n const data: any = await res.json();\n return {\n content: [\n {\n type: \"text\",\n text: `Successfully created email draft! Draft ID: ${data.id}`,\n },\n ],\n };\n}\nexport async function list_available_mailboxes(): Promise<ToolResult> {\n const apiKey = await getCloudAuthToken();\n\n let res: Response;\n try {\n res = await fetch(`${BACKEND_URL}/api/v1/users/me/shared-mailboxes`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"application/json\",\n },\n signal: AbortSignal.timeout(15_000),\n });\n } catch (err) {\n if (isTimeoutError(err)) {\n throw new Error(\n \"Listing mailboxes timed out after 15s. The Adeu backend may be temporarily unavailable; retry shortly.\",\n );\n }\n throw err;\n }\n\n if (res.status === 401) {\n DesktopAuthManager.clearApiKey();\n throw new Error(\n \"Authentication expired. Please call `login_to_adeu_cloud` to re-authenticate.\",\n );\n }\n if (!res.ok) {\n throw new Error(formatBackendError(res.status, await res.text()));\n }\n\n // FILE: node/packages/mcp-server/src/tools/email.ts\n\n const mailboxes: any[] = await res.json();\n if (!mailboxes.length) {\n return {\n content: [\n {\n type: \"text\",\n text: \"No configured mailboxes found for your profile.\",\n },\n ],\n };\n }\n\n // Sort alphabetically by email for deterministic ordering across clients.\n mailboxes.sort((a, b) =>\n (a.email_address ?? \"\")\n .toLowerCase()\n .localeCompare((b.email_address ?? \"\").toLowerCase()),\n );\n\n const lines = [\n \"### Connected Mailboxes\",\n \"Below is the list of connected mailboxes you have access to. Use the `email_address` as the `mailbox_address` parameter in other tools to query or draft from a specific mailbox:\",\n \"\",\n ];\n\n for (const box of mailboxes) {\n lines.push(\n `- **${box.display_name || \"Personal Mailbox\"}**\\n - **Email Address**: \\`${box.email_address}\\`\\n - **Auto-Processing**: ${box.auto_process_enabled ? \"Enabled\" : \"Disabled\"}\\n - **Write-Back Mode**: \\`${box.write_back_preference}\\``,\n );\n }\n\n return {\n content: [{ type: \"text\", text: lines.join(\"\\n\") }],\n };\n}\n"],"mappings":";;;AACA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,gBAAAA,eAAc,cAAAC,mBAAkB;AACzC,SAAS,YAAAC,WAAU,WAAAC,UAAS,SAAS,SAAS,QAAAC,aAAY;AAC1D,SAAS,SAAS;AAClB;AAAA,EACE,mBAAmB;AAAA,EACnB;AAAA,EACA;AAAA,OACK;AACP,OAAO,QAAQ;AACf;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,kBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACrBP,SAAS,SAAS,gBAAgB;AAClC;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AASP,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,mBACP,MACA,OACA,UACQ;AACR,MAAI,SAAS,KAAK,CAAC,SAAU,QAAO;AACpC,SAAO;AAAA;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AyB,OAAO,UAAU;AAAA;AAAA,MACnD;AAAA,IACF;AAAA,EACF;AAEA,MAAI,MAAM,mBAAmB,MAAM,gBAAgB,SAAS,GAAG;AAC7D,WAAO;AAAA;AAAA;AAAA,EAAyB,MAAM,gBAAgB,KAAK,IAAI,CAAC;AAAA,EAClE;AACA,SAAO;AACT;AAGA,eAAe,OAAO;AACpB,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAC9B,QAAME,UAAS;AACf,QAAM,UAAU;AAChB,UAAQ;AAAA,IACN,oCAAoC,eAAe,CAAC,4BAA4BA,OAAM,IAAI,OAAO;AAAA,EACnG;AACF;AAEA,KAAK,EAAE,MAAM,QAAQ,KAAK;","names":["readFileSync","existsSync","basename","resolve","join","DocumentObject","ui_markdown","llm_content","resolve","server","homedir","join","readFileSync","writeFileSync","mkdirSync","existsSync","join","homedir","existsSync","readFileSync","mkdirSync","writeFileSync","resolve","readFileSync","join","existsSync","DocumentObject","res","basename","resolve","gitSha"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/response-builders.ts","../src/desktop-auth.ts","../src/shared.ts","../src/tools/auth.ts","../src/tools/email.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { readFileSync, existsSync } from \"node:fs\";\nimport { basename, resolve, extname, dirname, join } from \"node:path\";\nimport { z } from \"zod\";\nimport {\n registerAppTool as origRegisterAppTool,\n registerAppResource,\n RESOURCE_MIME_TYPE,\n} from \"@modelcontextprotocol/ext-apps/server\";\nimport fs from \"node:fs\";\nimport {\n identifyEngine,\n extractTextFromBuffer,\n _extractTextFromDoc,\n DocumentObject,\n RedlineEngine,\n BatchValidationError,\n create_word_patch_diff,\n finalize_document,\n} from \"@adeu/core\";\n\nimport {\n build_paginated_response,\n build_outline_response,\n build_appendix_response,\n} from \"./response-builders.js\";\n\nimport { login_to_adeu_cloud, logout_of_adeu_cloud } from \"./tools/auth.js\";\nimport {\n search_and_fetch_emails,\n create_email_draft,\n list_available_mailboxes,\n} from \"./tools/email.js\";\nimport { MARKDOWN_UI_URI, EMAIL_UI_URI } from \"./shared.js\";\n\nfunction readFileBytesOrThrow(filePath: string): Buffer {\n try {\n return readFileSync(filePath);\n } catch (err: any) {\n if (err.code === \"ENOENT\") {\n throw new Error(\n `File not found: ${filePath}.\\n` +\n `If you are running in a sandboxed/containerized environment (such as Claude Desktop or another containerized client), ` +\n `the host application or MCP server may not have direct access to your local workspace files.\\n` +\n `You can resolve this by installing and running the local 'adeu' CLI tool directly within your environment.\\n` +\n `Here is how the MCP tools map to their CLI equivalents:\\n` +\n `- read_docx -> adeu extract ${filePath}\\n` +\n `- process_document_batch -> adeu apply ${filePath}\\n` +\n `- diff_docx_files -> adeu diff ${filePath} <modified_path>\\n` +\n `- accept_all_changes -> adeu accept-all ${filePath}\\n\\n` +\n `To run the local tool, install it via:\\n` +\n ` uv tool install adeu\\n` +\n `and run the mapped CLI command directly in your terminal.`\n );\n }\n throw err;\n }\n}\n\n// --- Asset Loaders for UI ---\nconst DIST_DIR = import.meta.dirname;\n\nfunction getAssetContent(\n folder: \"templates\" | \"assets\",\n filename: string,\n fallbackMessage: string,\n): string {\n const filePath = join(DIST_DIR, folder, filename);\n if (existsSync(filePath)) {\n return readFileSync(filePath, \"utf-8\");\n }\n return fallbackMessage;\n}\n\n// --- Tool Description Constants ---\nconst READ_DOCX_COMMON_DESC =\n \"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 =\n \"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 =\n \"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 =\n \"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\nconst DIFF_DOCX_DESC =\n \"Compares two DOCX files and returns a unified diff of their text content. Useful for analyzing differences between versions before editing.\";\n\nconst gitSha = process.env.GIT_SHA || \"unknown\";\nconst packageVersion = process.env.PACKAGE_VERSION || \"unknown\";\nconst buildTag = ` [Adeu v${packageVersion}+${gitSha}]`;\n\n// --- Scope Configuration ---\nconst args = process.argv.slice(2);\nconst scopeIdx = args.indexOf(\"--scope\");\nconst requestedScope = (scopeIdx !== -1 ? args[scopeIdx + 1] : \"all\").toLowerCase();\nconst isDocxOnly = requestedScope === \"docx\";\n\n// --- Server Setup ---\nconst server = new McpServer({\n name: \"adeu-redlining-service\",\n version: packageVersion,\n});\n\n// Wrap server.registerTool to inject buildTag into descriptions\nconst originalRegisterTool = server.registerTool.bind(server);\nserver.registerTool = (name: string, schema: any, handler?: any) => {\n if (schema && typeof schema === \"object\") {\n if (schema.description) {\n schema.description = schema.description.trim() + buildTag;\n }\n }\n return originalRegisterTool(name, schema, handler);\n};\n\n// Wrap registerAppTool to inject buildTag into descriptions\nconst registerAppTool: typeof origRegisterAppTool = (mcpServer, name, schema, handler) => {\n if (schema && typeof schema === \"object\") {\n if (schema.description) {\n schema.description = schema.description.trim() + buildTag;\n }\n }\n return origRegisterAppTool(mcpServer, name, schema, handler);\n};\n\n// Common CSP allowing Google Fonts used by Adeu UI templates\nconst UI_CSP = {\n connectDomains: [\"https://fonts.googleapis.com\", \"https://fonts.gstatic.com\"],\n resourceDomains: [\n \"https://fonts.googleapis.com\",\n \"https://fonts.gstatic.com\",\n ],\n};\n\n// ==========================================\n// 1. UI RESOURCES\n// ==========================================\n\nregisterAppResource(\n server,\n MARKDOWN_UI_URI,\n MARKDOWN_UI_URI,\n { mimeType: RESOURCE_MIME_TYPE, description: \"Adeu Markdown Viewer UI\" },\n async () => {\n let html = getAssetContent(\n \"templates\",\n \"markdown_ui.html\",\n \"<html><body>UI Template Not Found</body></html>\",\n );\n const markedJs = getAssetContent(\n \"assets\",\n \"marked.min.js\",\n \"window.__MARKED_ERROR = 'marked.min.js not found';\",\n );\n const svg = getAssetContent(\"assets\", \"adeu.svg\", \"\");\n\n html = html\n .replace(\"[[marked_js_code | safe]]\", markedJs)\n .replace(\"[[ adeu_svg_code ]]\", svg);\n\n return {\n contents: [\n {\n uri: MARKDOWN_UI_URI,\n mimeType: RESOURCE_MIME_TYPE,\n text: html,\n _meta: { ui: { csp: UI_CSP } },\n },\n ],\n };\n },\n);\n\nregisterAppResource(\n server,\n EMAIL_UI_URI,\n EMAIL_UI_URI,\n { mimeType: RESOURCE_MIME_TYPE, description: \"Adeu Email Viewer UI\" },\n async () => {\n let html = getAssetContent(\n \"templates\",\n \"email_ui.html\",\n \"<html><body>UI Template Not Found</body></html>\",\n );\n const svg = getAssetContent(\"assets\", \"adeu.svg\", \"\");\n\n html = html.replace(\"[[ adeu_svg_code ]]\", svg);\n\n return {\n contents: [\n {\n uri: EMAIL_UI_URI,\n mimeType: RESOURCE_MIME_TYPE,\n text: html,\n _meta: { ui: { csp: UI_CSP } },\n },\n ],\n };\n },\n);\n\n// ==========================================\n// 2. UI-ENABLED TOOLS\n// ==========================================\nregisterAppTool(\n server,\n \"read_docx\",\n {\n title: \"Read DOCX\",\n description: READ_DOCX_COMMON_DESC + READ_DOCX_TAIL,\n inputSchema: z.object({\n file_path: z.string().describe(\"Absolute path to the DOCX file.\"),\n clean_view: z\n .boolean()\n .default(false)\n .describe(\n \"If False (default), returns the 'Raw' text with inline CriticMarkup. If True, returns 'Accepted' text.\",\n ),\n mode: z\n .enum([\"full\", \"outline\", \"appendix\"])\n .default(\"full\")\n .describe(\n \"'full' returns body content. 'outline' returns a structural heading map. 'appendix' returns defined terms.\",\n ),\n page: z\n .number()\n .default(1)\n .describe(\"Page number (1-indexed) for mode='full'. Defaults to 1.\"),\n outline_max_level: z\n .number()\n .default(2)\n .describe(\"For mode='outline' only: cap on heading depth.\"),\n outline_verbose: z\n .boolean()\n .default(false)\n .describe(\"For mode='outline' only: includes metadata.\"),\n }),\n _meta: { ui: { resourceUri: MARKDOWN_UI_URI } },\n },\n async ({\n file_path,\n clean_view,\n mode,\n page,\n outline_max_level,\n outline_verbose,\n }) => {\n try {\n const buf = readFileBytesOrThrow(file_path);\n\n if (mode === \"outline\") {\n const doc = await DocumentObject.load(buf);\n const extract_res = _extractTextFromDoc(doc, clean_view, true, true) as {\n text: string;\n paragraph_offsets: Map<any, [number, number]>;\n };\n const res = build_outline_response(\n doc,\n extract_res.text,\n file_path,\n outline_max_level,\n outline_verbose,\n extract_res.paragraph_offsets,\n );\n return res as any;\n }\n\n const text = await extractTextFromBuffer(buf, clean_view);\n if (mode === \"appendix\") {\n const res = build_appendix_response(text, page, file_path);\n return res as any;\n }\n const res = build_paginated_response(text, page, file_path);\n return res as any;\n } catch (e: any) {\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: `Error executing tool read_docx: ${e.message}`,\n },\n ],\n };\n }\n },\n);\n\n// ==========================================\n// 3. HEADLESS TOOLS (No UI)\n// ==========================================\n\nserver.registerTool(\n \"process_document_batch\",\n {\n description: PROCESS_BATCH_COMMON_DESC + PROCESS_BATCH_OPERATIONS_DESC,\n inputSchema: {\n original_docx_path: z\n .string()\n .describe(\"Absolute path to the source file.\"),\n author_name: z\n .string()\n .describe(\"Name to appear in Track Changes (e.g., 'Reviewer AI').\"),\n changes: z\n .array(z.any())\n .describe(\"List of changes to apply. Each change must specify 'type'.\"),\n output_path: z.string().optional().describe(\"Optional output path.\"),\n dry_run: z\n .boolean()\n .optional()\n .default(false)\n .describe(\n \"If True, simulates the changes and returns a detailed preview report without modifying any files.\",\n ),\n },\n },\n async ({\n original_docx_path,\n author_name,\n changes,\n output_path,\n dry_run,\n }) => {\n try {\n if (!author_name || !author_name.trim())\n return {\n content: [\n { type: \"text\", text: \"Error: author_name cannot be empty.\" },\n ],\n };\n if (!changes || changes.length === 0)\n return {\n content: [{ type: \"text\", text: \"Error: No changes provided.\" }],\n };\n\n let outPath = output_path;\n if (!outPath) {\n const ext = extname(original_docx_path);\n const base = basename(original_docx_path, ext);\n const dir = dirname(original_docx_path);\n outPath = resolve(dir, `${base}_processed${ext}`);\n }\n\n const buf = readFileBytesOrThrow(original_docx_path);\n const doc = await DocumentObject.load(buf);\n const engine = new RedlineEngine(doc, author_name);\n\n let stats;\n try {\n stats = engine.process_batch(changes, dry_run);\n } catch (e: any) {\n if (e instanceof BatchValidationError) {\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: `Batch rejected. Some edits failed validation:\\n\\n${e.errors.join(\"\\n\\n\")}`,\n },\n ],\n };\n }\n throw e;\n }\n\n if (!dry_run) {\n const outBuf = await doc.save();\n fs.writeFileSync(outPath, outBuf);\n }\n\n const res = formatBatchResult(stats, outPath, !!dry_run);\n return { content: [{ type: \"text\", text: res }] };\n } catch (e: any) {\n return {\n isError: true,\n content: [{ type: \"text\", text: `Error: ${e.message}` }],\n };\n }\n },\n);\n\nserver.registerTool(\n \"accept_all_changes\",\n {\n description:\n \"Accepts all tracked changes and removes all comments in a single operation.\",\n inputSchema: {\n docx_path: z.string().describe(\"Absolute path to the DOCX file.\"),\n output_path: z.string().optional().describe(\"Optional output path.\"),\n },\n },\n async ({ docx_path, output_path }) => {\n try {\n let outPath = output_path;\n if (!outPath) {\n const ext = extname(docx_path);\n const base = basename(docx_path, ext);\n const dir = dirname(docx_path);\n outPath = resolve(dir, `${base}_clean${ext}`);\n }\n\n const buf = readFileBytesOrThrow(docx_path);\n const doc = await DocumentObject.load(buf);\n const engine = new RedlineEngine(doc);\n\n engine.accept_all_revisions();\n\n const outBuf = await doc.save();\n\n fs.writeFileSync(outPath, outBuf);\n\n return {\n content: [\n { type: \"text\", text: `Accepted all changes. Saved to: ${outPath}` },\n ],\n };\n } catch (e: any) {\n return {\n isError: true,\n content: [{ type: \"text\", text: `Error: ${e.message}` }],\n };\n }\n },\n);\n\nserver.registerTool(\n \"diff_docx_files\",\n {\n description: DIFF_DOCX_DESC,\n inputSchema: {\n original_path: z\n .string()\n .describe(\"Absolute path to the baseline DOCX file.\"),\n modified_path: z\n .string()\n .describe(\"Absolute path to the modified DOCX file.\"),\n compare_clean: z\n .boolean()\n .default(true)\n .describe(\n \"If True, compares 'Accepted' state. If False, compares raw text.\",\n ),\n },\n },\n async ({ original_path, modified_path, compare_clean }) => {\n try {\n const origBuf = readFileBytesOrThrow(original_path);\n const modBuf = readFileBytesOrThrow(modified_path);\n\n const origText = await extractTextFromBuffer(origBuf, compare_clean);\n const modText = await extractTextFromBuffer(modBuf, compare_clean);\n\n const diff = create_word_patch_diff(\n origText,\n modText,\n basename(original_path),\n basename(modified_path),\n );\n\n return {\n content: [{ type: \"text\", text: diff || \"No differences found.\" }],\n };\n } catch (e: any) {\n return {\n isError: true,\n content: [{ type: \"text\", text: `Error: ${e.message}` }],\n };\n }\n },\n);\n\nserver.registerTool(\n \"finalize_document\",\n {\n description:\n \"Prepares a document for external distribution or e-signature.\",\n inputSchema: {\n file_path: z.string().describe(\"Absolute path to the DOCX file.\"),\n output_path: z.string().optional().describe(\"Optional output path.\"),\n sanitize_mode: z\n .enum([\"full\", \"keep-markup\"])\n .optional()\n .describe(\"full removes all markup, keep-markup redacts metadata.\"),\n accept_all: z\n .boolean()\n .optional()\n .describe(\n \"If true, auto-accepts all unresolved track changes before finalizing.\",\n ),\n protection_mode: z\n .enum([\"read_only\", \"encrypt\"])\n .optional()\n .describe(\"Native OOXML document locking.\"),\n password: z.string().optional().describe(\"Ignored in this environment.\"),\n author: z\n .string()\n .optional()\n .describe(\"Replace all remaining markup authorship with this name.\"),\n export_pdf: z\n .boolean()\n .optional()\n .describe(\"Ignored in this environment.\"),\n },\n },\n async ({\n file_path,\n output_path,\n sanitize_mode,\n accept_all,\n protection_mode,\n author,\n export_pdf,\n }) => {\n try {\n let outPath = output_path;\n if (!outPath) {\n const ext = extname(file_path);\n const base = basename(file_path, ext);\n const dir = dirname(file_path);\n outPath = resolve(dir, `${base}_final${ext}`);\n }\n\n const buf = readFileBytesOrThrow(file_path);\n const doc = await DocumentObject.load(buf);\n\n const result = await finalize_document(doc, {\n filename: basename(file_path),\n sanitize_mode: (sanitize_mode as any) || \"full\",\n accept_all: accept_all as boolean,\n protection_mode: protection_mode as any,\n author: author as string,\n export_pdf: export_pdf as boolean,\n });\n\n fs.writeFileSync(outPath, result.outBuffer!);\n\n return {\n content: [\n {\n type: \"text\",\n text: `Saved to: ${outPath}\\n\\n${result.reportText}`,\n },\n ],\n };\n } catch (e: any) {\n return {\n isError: true,\n content: [{ type: \"text\", text: `Error: ${e.message}` }],\n };\n }\n },\n);\n\nif (!isDocxOnly) {\nregisterAppTool(\n server,\n \"search_and_fetch_emails\",\n {\n title: \"Search & Fetch Emails\",\n description:\n \"Searches the user's live email inbox via the Adeu cloud backend.\\n\\n\" +\n \"TWO MODES:\\n\" +\n \"1. Search mode (no `email_id`): returns up to `limit` lightweight previews. Use filters (`sender`, `subject`, `is_unread`, `days_ago`, `folder`, `has_attachments`, `attachment_name`) to narrow down.\\n\" +\n \"2. Fetch mode (with `email_id`): returns the full email body, thread history, and downloads attachments under `max_attachment_size_mb` to the local disk.\\n\\n\" +\n \"AUTO-ESCALATION: If a search returns exactly one preview, the backend automatically fetches the full email in the same call. Plan around the response shape — check the `type` field (`previews` vs `full_email`) before assuming.\\n\\n\" +\n \"EMAIL ID FORMATS (`email_id` parameter accepts any of):\\n\" +\n \"- `msg_<6 chars>` — short ID returned by previews on THIS machine. NOT portable across machines or sessions; the local cache holds the most recent 1000. If you reference one that's been evicted, the tool returns a StaleShortIdError telling you to re-search.\\n\" +\n \"- `adeu_<numeric>` — server-side reference for emails Adeu has previously processed. Portable across machines and sessions for the same authenticated user.\\n\" +\n \"- Raw provider ID (Gmail/Outlook native ID) — works if you have it, but you usually won't.\\n\\n\" +\n \"FOLDER DEFAULT: omitting `folder` searches the Inbox only (matching what the user sees in their mail client). Use `folder='sent'` for sent items, `folder='all'` to include Deleted Items, Drafts, and other folders.\\n\\n\" +\n \"ATTACHMENTS: attachments larger than `max_attachment_size_mb` (default 10) are listed in the response but NOT downloaded — raise the cap if you need them. Always set `working_directory` when calling from a project so attachments land alongside the user's other files.\",\n inputSchema: z.object({\n sender: z.string().optional(),\n subject: z.string().optional(),\n has_attachments: z.boolean().optional(),\n attachment_name: z.string().optional(),\n is_unread: z.boolean().optional(),\n days_ago: z.number().optional(),\n folder: z.enum([\"inbox\", \"sent\", \"all\"]).optional(),\n limit: z.number().default(10),\n offset: z.number().default(0),\n email_id: z.string().optional(),\n working_directory: z.string().optional(),\n mailbox_address: z\n .string()\n .optional()\n .describe(\"Optional target mailbox email address to search within.\"),\n task_id: z\n .string()\n .optional()\n .describe(\"If resuming a pending check, provide the task ID here.\"),\n max_attachment_size_mb: z\n .number()\n .optional()\n .describe(\n \"Maximum attachment size in MB to download (default 10). Attachments larger than this are listed in the response but not downloaded. Raise this to fetch large files.\",\n ),\n }),\n _meta: { ui: { resourceUri: EMAIL_UI_URI } },\n },\n async (args) => {\n try {\n return (await search_and_fetch_emails(args)) as any;\n } catch (e: any) {\n return {\n isError: true,\n content: [{ type: \"text\", text: e.message }],\n };\n }\n },\n);\n\nserver.registerTool(\n \"login_to_adeu_cloud\",\n {\n description:\n \"Logs the user into Adeu Cloud. Opens a browser window for SSO authentication.\\n\\n\" +\n \"IMPORTANT — login is user-level, not account-level:\\n\" +\n \"- An Adeu user can have multiple linked provider accounts (Microsoft, Google) and multiple mailboxes (personal + shared/delegated). One linked account is marked primary.\\n\" +\n \"- Signing in through ANY of the user's linked accounts authenticates the same Adeu user. Once logged in, the session can read from and draft in ALL of that user's linked accounts and ALL of their mailboxes — not just the one used to sign in.\\n\" +\n \"- The choice of which provider account to sign in through is purely an SSO mechanism; it does not select a 'current account' for the session.\\n\\n\" +\n \"When the user asks which accounts or mailboxes are available, call `list_available_mailboxes` rather than naming a single account from the login response.\",\n },\n async () => {\n try {\n return (await login_to_adeu_cloud()) as any;\n } catch (e: any) {\n return { isError: true, content: [{ type: \"text\", text: e.message }] };\n }\n },\n);\n\nserver.registerTool(\n \"logout_of_adeu_cloud\",\n { description: \"Logs out of the Adeu Cloud backend.\" },\n async () => {\n try {\n return (await logout_of_adeu_cloud()) as any;\n } catch (e: any) {\n return { isError: true, content: [{ type: \"text\", text: e.message }] };\n }\n },\n);\nserver.registerTool(\n \"create_email_draft\",\n {\n description:\n \"Creates an email draft in the user's native draft box (Outlook Drafts or Gmail Drafts).\\n\\n\" +\n \"TWO MODES:\\n\" +\n \"1. Reply mode: pass `reply_to_email_id` to create a threaded reply. The draft inherits subject, recipients, and threading headers from the original — do NOT pass `subject` or `to_recipients`.\\n\" +\n \"2. New email mode: omit `reply_to_email_id` and pass BOTH `subject` and `to_recipients`.\\n\\n\" +\n \"`reply_to_email_id` accepts the same ID formats as search_and_fetch_emails (`msg_*` short IDs, `adeu_*` references, or raw provider IDs). Short IDs are validated against the local cache before the call; stale ones fail fast with a clear error telling you to re-search.\\n\\n\" +\n \"`body_markdown` is converted server-side to styled HTML with inlined CSS for email-client compatibility. Write the body in plain Markdown — do not pre-render HTML.\\n\\n\" +\n \"`attachment_paths` takes absolute file paths on the user's local disk and uploads them with the draft. Useful right after search_and_fetch_emails downloaded attachments — those local paths can be passed directly here.\",\n inputSchema: {\n body_markdown: z.string(),\n reply_to_email_id: z.string().optional(),\n subject: z.string().optional(),\n to_recipients: z.array(z.string()).optional(),\n attachment_paths: z.array(z.string()).optional(),\n mailbox_address: z\n .string()\n .optional()\n .describe(\n \"Optional target mailbox email address to create the draft in.\",\n ),\n },\n },\n async (args) => {\n try {\n return (await create_email_draft(args)) as any;\n } catch (e: any) {\n return { isError: true, content: [{ type: \"text\", text: e.message }] };\n }\n },\n);\nserver.registerTool(\n \"list_available_mailboxes\",\n {\n description:\n \"Lists all personal and shared/delegated mailboxes the authenticated Adeu user has access to, across ALL of their linked provider accounts. Returns each mailbox's `email_address`, `display_name`, auto-processing settings, and write-back preference.\\n\\n\" +\n \"This is the right tool to answer 'which accounts/mailboxes am I logged into?' — Adeu login is user-level, so a single MCP session can see every mailbox listed here regardless of which provider account was used for SSO.\\n\\n\" +\n \"Call this FIRST when the user names a specific mailbox or shared inbox, to resolve the canonical `email_address`. Then pass that address as `mailbox_address` to `search_and_fetch_emails` or `create_email_draft` to scope the operation. Omitting `mailbox_address` on those tools targets the user's primary personal mailbox.\",\n inputSchema: {},\n },\n async () => {\n try {\n return (await list_available_mailboxes()) as any;\n } catch (e: any) {\n return { isError: true, content: [{ type: \"text\", text: e.message }] };\n }\n },\n);\n}\n\n// --- Formatter for process_document_batch ---\nexport function formatBatchResult(\n stats: any,\n outPath: string,\n dry_run: boolean,\n): string {\n let res = \"\";\n if (dry_run) {\n res = `Dry-run simulation complete.\\n`;\n } else {\n res = `Batch complete. Saved to: ${outPath}\\n`;\n }\n res += `Actions: ${stats.actions_applied} applied, ${stats.actions_skipped} skipped.\\n`;\n res += `Edits: ${stats.edits_applied} applied, ${stats.edits_skipped} skipped.\\n`;\n\n if (stats.edits && stats.edits.length > 0) {\n res += \"\\nDetailed Edit Reports:\\n\";\n for (let i = 0; i < stats.edits.length; i++) {\n const report = stats.edits[i];\n const status_indicator =\n report.status === \"applied\" ? \"✅ [applied]\" : \"❌ [failed]\";\n res += `Edit ${i + 1} ${status_indicator}:\\n`;\n res += ` Target: '${report.target_text}'\\n`;\n res += ` New text: '${report.new_text}'\\n`;\n if (report.warning) {\n res += ` Warning: ${report.warning}\\n`;\n }\n if (report.error) {\n res += ` Error: ${report.error}\\n`;\n }\n if (report.critic_markup) {\n res += ` Preview (CriticMarkup): ${report.critic_markup}\\n`;\n }\n if (report.clean_text) {\n res += ` Clean text preview: ${report.clean_text}\\n`;\n }\n }\n }\n\n if (stats.skipped_details && stats.skipped_details.length > 0) {\n res += `\\n\\nSkipped Details:\\n${stats.skipped_details.join(\"\\n\")}`;\n }\n return res;\n}\n\n// --- Startup ---\nasync function main() {\n const transport = new StdioServerTransport();\n await server.connect(transport);\n const gitSha = process.env.GIT_SHA || \"unknown\";\n const buildTs = process.env.BUILD_TIMESTAMP || \"unknown\";\n console.error(\n `Adeu MCP Server (Node.js Engine: ${identifyEngine()}) running on stdio build=${gitSha}@${buildTs}`,\n );\n}\n\nmain().catch(console.error);\n","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 structuredContent?: any;\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(\n page: number,\n total: number,\n has_next: boolean,\n): 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(\n nodes: OutlineNode[],\n max_level: number = 2,\n verbose: boolean = false,\n): 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)\n 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(\n text: string,\n page: number,\n file_path: string,\n): 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(\n `Page ${page} out of range (doc has ${result.total_pages} pages).`,\n );\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(\n selected.page,\n selected.total_pages,\n selected.has_next,\n );\n const appendix_pointer = _build_appendix_pointer(has_appendix);\n\n const ui_markdown =\n 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 // Include structuredContent for the UI to render the markdown\n structuredContent: {\n markdown: ui_markdown,\n file_path: resolve(file_path),\n title: basename(file_path),\n },\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 paragraph_offsets: Map<any, [number, number]> | null = null,\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 paragraph_offsets,\n );\n\n const rendered = render_outline_tree(\n nodes,\n outline_max_level,\n outline_verbose,\n );\n\n const visible_count = nodes.filter(\n (n) => n.level <= outline_max_level,\n ).length;\n const deeper_count = nodes.length - visible_count;\n const deeper_hint =\n deeper_count > 0\n ? ` (${deeper_count} more at deeper levels, raise outline_max_level to see)`\n : \"\";\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 structuredContent: {\n markdown: ui_markdown,\n file_path: resolve(file_path),\n title: `Outline: ${basename(file_path)}`,\n },\n };\n}\n\nexport function build_appendix_response(\n text: string,\n page: number,\n file_path: string,\n): ToolResult {\n const [, appendix] = split_structural_appendix(text);\n\n if (!appendix.trim()) {\n const ui_markdown =\n \"# 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 structuredContent: {\n markdown: ui_markdown,\n file_path: resolve(file_path),\n title: `Appendix: ${basename(file_path)}`,\n },\n };\n }\n\n const result = paginate(appendix, \"\");\n\n if (page < 1 || page > result.total_pages) {\n throw new Error(\n `Appendix page ${page} out of range (appendix has ${result.total_pages} pages).`,\n );\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\\n> **Continues on appendix page ${selected.page + 1} of ${selected.total_pages}.**`\n : \"\";\n } else {\n banner =\n \"> **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 structuredContent: {\n markdown: ui_markdown,\n file_path: resolve(file_path),\n title: `Appendix: ${basename(file_path)}`,\n },\n };\n}\n","// FILE: node/packages/mcp-server/src/desktop-auth.ts\nimport { createServer, Server } from \"node:http\";\nimport { exec } from \"node:child_process\";\nimport { homedir, platform } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n writeFileSync,\n readFileSync,\n mkdirSync,\n existsSync,\n rmSync,\n chmodSync,\n} from \"node:fs\";\nimport { FRONTEND_URL } from \"./shared.js\";\n\nconst ADEU_DIR = join(homedir(), \".adeu\");\nconst CRED_PATH = join(ADEU_DIR, \"credentials.json\");\n\nfunction openBrowser(url: string) {\n if (platform() === \"darwin\") exec(`open \"${url}\"`);\n else if (platform() === \"win32\") exec(`start \"\" \"${url}\"`);\n else exec(`xdg-open \"${url}\"`);\n}\n\nexport class DesktopAuthManager {\n static getApiKey(): string | null {\n if (!existsSync(CRED_PATH)) return null;\n try {\n const data = JSON.parse(readFileSync(CRED_PATH, \"utf-8\"));\n return data.api_key || null;\n } catch {\n return null;\n }\n }\n\n static setApiKey(apiKey: string): void {\n if (!existsSync(ADEU_DIR)) {\n mkdirSync(ADEU_DIR, { recursive: true });\n }\n writeFileSync(CRED_PATH, JSON.stringify({ api_key: apiKey }));\n // Restrict read/write to the current user only (equivalent to 0o600)\n chmodSync(CRED_PATH, 0o600);\n }\n\n static clearApiKey(): void {\n if (existsSync(CRED_PATH)) {\n rmSync(CRED_PATH);\n }\n }\n\n static async authenticateInteractive(): Promise<string> {\n return new Promise((resolve, reject) => {\n let server: Server;\n\n const timeout = setTimeout(\n () => {\n if (server) server.close();\n reject(new Error(\"Authentication timed out after 5 minutes.\"));\n },\n 5 * 60 * 1000,\n );\n\n server = createServer((req, res) => {\n const url = new URL(req.url || \"\", `http://${req.headers.host}`);\n\n if (url.pathname === \"/callback\") {\n const apiKey = url.searchParams.get(\"api_key\");\n\n res.writeHead(apiKey ? 200 : 400, { \"Content-Type\": \"text/html\" });\n const title = apiKey\n ? \"Authentication Successful!\"\n : \"Authentication Failed\";\n const text = apiKey\n ? \"Your Adeu MCP server has been successfully authenticated. You can safely close this window and return to Claude.\"\n : \"No API key received. Please try again.\";\n const color = apiKey ? \"#107c10\" : \"#d83b01\";\n\n res.end(`\n <!DOCTYPE html><html><head><title>${title}</title>\n <style>body{font-family:sans-serif;text-align:center;padding:50px;background:#f3f2f1;}.container{background:white;padding:40px;border-radius:8px;box-shadow:0 2px 4px rgba(0,0,0,0.1);max-width:500px;margin:0 auto;}h1{color:${color};}p{color:#605e5c;line-height:1.5;}</style>\n </head><body><div class=\"container\"><h1>${title}</h1><p>${text}</p>\n <script>setTimeout(()=>window.close(), 3000);</script>\n </div></body></html>\n `);\n\n clearTimeout(timeout);\n // Allow response to send before closing server\n setTimeout(() => server.close(), 100);\n\n if (apiKey) {\n this.setApiKey(apiKey);\n resolve(apiKey);\n } else {\n reject(new Error(\"No API key received in callback.\"));\n }\n } else {\n res.writeHead(404);\n res.end();\n }\n });\n\n server.listen(0, \"127.0.0.1\", () => {\n const address = server.address();\n if (address && typeof address !== \"string\") {\n const authUrl = `${FRONTEND_URL}/login?desktop_port=${address.port}`;\n openBrowser(authUrl);\n }\n });\n });\n }\n\n static async ensureAuthenticated(): Promise<string> {\n const key = this.getApiKey();\n if (key) return key;\n return this.authenticateInteractive();\n }\n}\n\nexport async function getCloudAuthToken(): Promise<string> {\n const key = DesktopAuthManager.getApiKey();\n if (!key) {\n throw new Error(\n \"Authentication Required: You are not logged in. Please call the `login_to_adeu_cloud` tool first to authenticate, then try this task again.\",\n );\n }\n return key;\n}\n","// FILE: node/packages/mcp-server/src/shared.ts\nexport const FRONTEND_URL =\n process.env.ADEU_FRONTEND_URL || \"https://app.adeu.ai\";\nexport const BACKEND_URL =\n process.env.ADEU_BACKEND_URL || \"https://app.adeu.ai\";\nexport const MARKDOWN_UI_URI = \"ui://adeu/markdown-ui\";\nexport const EMAIL_UI_URI = \"ui://adeu/email-ui\";\n","// FILE: node/packages/mcp-server/src/tools/auth.ts\nimport { DesktopAuthManager } from \"../desktop-auth.js\";\nimport { BACKEND_URL } from \"../shared.js\";\nimport { ToolResult } from \"../response-builders.js\";\n\nexport async function login_to_adeu_cloud(): Promise<ToolResult> {\n try {\n const apiKey = await DesktopAuthManager.ensureAuthenticated();\n\n const res = await fetch(`${BACKEND_URL}/api/v1/auth/me`, {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"application/json\",\n },\n signal: AbortSignal.timeout(15_000),\n });\n\n if (res.status === 401) {\n DesktopAuthManager.clearApiKey();\n throw new Error(\n \"Your previous session expired. The stale key has been cleared. Please call `login_to_adeu_cloud` ONE MORE TIME to log in fresh.\",\n );\n }\n if (!res.ok) throw new Error(`HTTP Error: ${res.status}`);\n\n const data: any = await res.json();\n const email = data.email || \"Unknown Email\";\n return {\n content: [\n {\n type: \"text\",\n text:\n `Login successful. You are now authenticated to Adeu Cloud as the user ` +\n `who owns the provider account \\`${email}\\` (the account used for SSO).\\n\\n` +\n `This single login grants access to ALL of this user's linked provider ` +\n `accounts and ALL of their mailboxes for the duration of this session — ` +\n `not just \\`${email}\\`. Call \\`list_available_mailboxes\\` to see every mailbox ` +\n `that can be queried or drafted from.`,\n },\n ],\n };\n } catch (err: any) {\n return { isError: true, content: [{ type: \"text\", text: err.message }] };\n }\n}\n\nexport async function logout_of_adeu_cloud(): Promise<ToolResult> {\n DesktopAuthManager.clearApiKey();\n return {\n content: [\n {\n type: \"text\",\n text: \"Successfully logged out. The local API key has been removed.\",\n },\n ],\n };\n}\n","import { homedir, tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { readFileSync, writeFileSync, mkdirSync, existsSync } from \"node:fs\";\nimport { DesktopAuthManager, getCloudAuthToken } from \"../desktop-auth.js\";\nimport { BACKEND_URL } from \"../shared.js\";\nimport { ToolResult } from \"../response-builders.js\";\nimport { createHash } from \"node:crypto\";\nconst KNOWN_ERROR_HINTS: Record<string, string> = {\n \"Email not found.\":\n \"The email ID was not found. If this was a short ID (msg_*), it may have been \" +\n \"evicted from the local cache or come from a different machine — re-run \" +\n \"search_and_fetch_emails with filters to get a fresh ID. If it was an \" +\n \"adeu_<numeric> or raw provider ID, verify it's correct.\",\n \"Adeu email reference not found.\":\n \"The adeu_<id> reference doesn't resolve to any processed email for this user. \" +\n \"Verify the ID, or re-run search_and_fetch_emails with filters to find the message.\",\n \"Invalid adeu_ email ID format.\":\n \"The adeu_<id> reference is malformed. Expected format: adeu_<integer>.\",\n};\n\nfunction formatBackendError(statusCode: number, responseBody: string): string {\n let detail = responseBody;\n try {\n const parsed = JSON.parse(responseBody);\n if (parsed && typeof parsed === \"object\" && \"detail\" in parsed) {\n detail = String(parsed.detail);\n }\n } catch {\n // responseBody isn't JSON — use it as-is\n }\n\n let hint = KNOWN_ERROR_HINTS[detail];\n if (\n !hint &&\n detail.startsWith(\"Mailbox '\") &&\n detail.endsWith(\"' not found.\")\n ) {\n const mailbox = detail.slice(\"Mailbox '\".length, -\"' not found.\".length);\n hint =\n `The mailbox '${mailbox}' is not connected to your Adeu account. ` +\n \"Call list_available_mailboxes to see valid mailbox addresses, then retry \" +\n \"with one of those as `mailbox_address`.\";\n }\n\n const message = hint ?? detail;\n return `Cloud search failed (HTTP ${statusCode}): ${message}`;\n}\nfunction isTimeoutError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const name = (err as { name?: string }).name;\n return name === \"TimeoutError\" || name === \"AbortError\";\n}\n\nconst CACHE_FILE = join(homedir(), \".adeu\", \"mcp_id_cache.json\");\nconst MAX_CACHE_SIZE = 1000;\n\nfunction formatBytes(bytes: number | null | undefined): string {\n if (bytes == null) return \"unknown size\";\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nfunction loadIdCache(): Record<string, string> {\n if (existsSync(CACHE_FILE)) {\n try {\n return JSON.parse(readFileSync(CACHE_FILE, \"utf-8\"));\n } catch {\n return {};\n }\n }\n return {};\n}\n\nfunction saveIdCache(cache: Record<string, string>): void {\n try {\n mkdirSync(join(homedir(), \".adeu\"), { recursive: true });\n const keys = Object.keys(cache);\n if (keys.length > MAX_CACHE_SIZE) {\n const trimmed: Record<string, string> = {};\n keys.slice(-MAX_CACHE_SIZE).forEach((k) => (trimmed[k] = cache[k]));\n cache = trimmed;\n }\n writeFileSync(CACHE_FILE, JSON.stringify(cache));\n } catch {\n /* ignore */\n }\n}\n\nfunction minifyEmailId(realId: string, cache: Record<string, string>): string {\n if (!realId) return realId;\n const hash = createHash(\"md5\").update(realId).digest(\"hex\").slice(0, 6);\n const shortId = `msg_${hash}`;\n cache[shortId] = realId;\n return shortId;\n}\n\nclass StaleShortIdError extends Error {\n constructor(shortId: string) {\n super(\n `Short ID '${shortId}' is not in the local cache (it may have been evicted, or it came from a different machine/session). ` +\n `Short IDs only persist on the machine where they were generated. ` +\n `Re-run search_and_fetch_emails with filters (sender, subject, days_ago) to fetch fresh IDs, then use the new ID from those results.`,\n );\n this.name = \"StaleShortIdError\";\n }\n}\n\nfunction resolveEmailId(shortId: string): string {\n if (!shortId) return shortId;\n // adeu_<id> references are resolved server-side, pass through.\n if (shortId.startsWith(\"adeu_\")) return shortId;\n const cache = loadIdCache();\n const resolved = cache[shortId];\n if (resolved) return resolved;\n // If it looks like one of our short IDs but isn't in the cache, fail loudly\n // instead of silently passing a meaningless string to the provider.\n if (shortId.startsWith(\"msg_\")) {\n throw new StaleShortIdError(shortId);\n }\n // Otherwise treat it as a raw provider ID\n return shortId;\n}\n\nconst HTML_NAMED_ENTITIES: Record<string, string> = {\n nbsp: \" \",\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n copy: \"\\u00A9\",\n reg: \"\\u00AE\",\n trade: \"\\u2122\",\n hellip: \"\\u2026\",\n mdash: \"\\u2014\",\n ndash: \"\\u2013\",\n lsquo: \"\\u2018\",\n rsquo: \"\\u2019\",\n ldquo: \"\\u201C\",\n rdquo: \"\\u201D\",\n laquo: \"\\u00AB\",\n raquo: \"\\u00BB\",\n bull: \"\\u2022\",\n middot: \"\\u00B7\",\n deg: \"\\u00B0\",\n plusmn: \"\\u00B1\",\n times: \"\\u00D7\",\n divide: \"\\u00F7\",\n euro: \"\\u20AC\",\n pound: \"\\u00A3\",\n yen: \"\\u00A5\",\n cent: \"\\u00A2\",\n sect: \"\\u00A7\",\n para: \"\\u00B6\",\n iexcl: \"\\u00A1\",\n iquest: \"\\u00BF\",\n};\n\nfunction decodeHtmlEntities(text: string): string {\n // Numeric: &#1234; (decimal) and &#x1F4A9; (hex)\n text = text.replace(/&#(\\d+);/g, (_, dec: string) => {\n const code = parseInt(dec, 10);\n return Number.isFinite(code) ? String.fromCodePoint(code) : _;\n });\n text = text.replace(/&#[xX]([0-9a-fA-F]+);/g, (_, hex: string) => {\n const code = parseInt(hex, 16);\n return Number.isFinite(code) ? String.fromCodePoint(code) : _;\n });\n // Named: &amp;, &rsquo;, etc.\n text = text.replace(/&([a-zA-Z][a-zA-Z0-9]*);/g, (match, name: string) => {\n const replacement = HTML_NAMED_ENTITIES[name.toLowerCase()];\n return replacement !== undefined ? replacement : match;\n });\n return text;\n}\n\nfunction stripTags(html: string): string {\n if (!html) return \"\";\n\n // 1. Strip suppressed blocks (style/script/head/title) — loop until stable to\n // handle nested or malformed blocks. Matches Python MLStripper's structural\n // suppression rather than relying on a single greedy pass.\n let text = html;\n const suppressPattern =\n /<(style|script|head|title)\\b[^>]*>[\\s\\S]*?<\\/\\1\\s*>/gi;\n let prev: string;\n do {\n prev = text;\n text = text.replace(suppressPattern, \"\");\n } while (text !== prev);\n\n // 2. Also strip orphan open tags for suppressed blocks (unclosed <style ...>)\n // by killing from the open tag to end of document — safer than leaking CSS\n // into the LLM output.\n text = text.replace(/<(style|script|head|title)\\b[^>]*>[\\s\\S]*$/gi, \"\");\n\n // 3. Convert block-level closing tags to newlines so paragraph structure survives\n text = text.replace(\n /<\\/?(p|div|br|hr|tr|li|h[1-6]|blockquote)\\b[^>]*>/gi,\n \"\\n\",\n );\n\n // 4. Strip all remaining tags\n text = text.replace(/<[^>]+>/g, \"\");\n\n // 5. Decode HTML entities (named + numeric, matches Python's html.unescape).\n text = decodeHtmlEntities(text);\n\n // 6. Collapse triple-or-more newlines down to a paragraph break\n return text.replace(/\\n\\s*\\n\\s*\\n+/g, \"\\n\\n\").trim();\n}\n\nfunction removeNestedQuotes(text: string): string {\n if (!text) return \"\";\n\n // Localized \"From:\" header tokens from Outlook in major European locales.\n // Order matters only for readability; matching is anchored independently.\n const fromTokens = [\n \"From\", // English\n \"Lähettäjä\", // Finnish\n \"Från\", // Swedish\n \"Von\", // German\n \"De\", // French / Spanish / Portuguese\n \"Da\", // Italian\n \"Van\", // Dutch\n \"Fra\", // Norwegian / Danish\n \"Mittente\", // Italian (alt)\n ];\n\n // Localized \"Sent:\" tokens (paired with From: in Outlook quote blocks)\n const sentTokens = [\n \"Sent\",\n \"Lähetetty\",\n \"Skickat\",\n \"Gesendet\",\n \"Envoyé\",\n \"Enviado\",\n \"Inviato\",\n \"Verzonden\",\n \"Sendt\",\n ];\n\n // Localized \"On ... wrote:\" / \"X wrote on Y:\" patterns from Gmail-style clients\n const wrotePatterns = [\n /On .{1,200}? wrote:/, // English\n /Le .{1,200}? a écrit\\s*:/i, // French\n /Am .{1,200}? schrieb .{1,100}?:/i, // German\n /El .{1,200}? escribió\\s*:/i, // Spanish\n /Il .{1,200}? ha scritto\\s*:/i, // Italian\n /Op .{1,200}? schreef .{1,100}?:/i, // Dutch\n /Den .{1,200}? skrev .{1,100}?:/i, // Swedish/Norwegian/Danish\n /Em .{1,200}? escreveu\\s*:/i, // Portuguese\n /Em\\b.{1,200}?, .{1,200}? escreveu\\s*:/i, // Portuguese (date prefix)\n new RegExp(\n `^(${fromTokens.join(\"|\")})\\\\s*:.*?\\\\n(?:.*\\\\n){0,5}?(${sentTokens.join(\"|\")})\\\\s*:`,\n \"m\",\n ),\n ];\n\n // Localized \"Forwarded message\" markers across the same locale set.\n // Once hit, everything below is a quoted historical message and should be cut.\n const forwardedTokens = [\n \"Forwarded message\",\n \"Välitetty viesti\",\n \"Vidarebefordrat meddelande\",\n \"Weitergeleitete Nachricht\",\n \"Message transféré\",\n \"Mensaje reenviado\",\n \"Messaggio inoltrato\",\n \"Doorgestuurd bericht\",\n \"Videresendt melding\",\n \"Videresendt meddelelse\",\n \"Mensagem encaminhada\",\n ].join(\"|\");\n\n const dividerPatterns = [\n /_{10,}/m,\n /-----\\s*(Original Message|Alkuperäinen viesti|Ursprüngliches Nachricht|Message d'origine|Mensaje original|Messaggio originale|Oorspronkelijk bericht|Original meddelande)\\s*-----/im,\n /^(Original Message|Alkuperäinen viesti|Ursprüngliches Nachricht|Message d'origine|Mensaje original|Messaggio originale|Oorspronkelijk bericht)$/im,\n // Gmail/Outlook-style \"---------- Forwarded message ---------\" with localized variants\n new RegExp(`-+\\\\s*(${forwardedTokens})\\\\s*-+`, \"i\"),\n new RegExp(`^(${forwardedTokens})$`, \"im\"),\n ];\n\n const allPatterns = [...wrotePatterns, ...dividerPatterns];\n\n let earliestCut = text.length;\n for (const pattern of allPatterns) {\n const match = pattern.exec(text);\n if (match && match.index < earliestCut) {\n earliestCut = match.index;\n }\n }\n return text.substring(0, earliestCut).trim();\n}\n\nfunction getUniqueFilepath(saveDir: string, filename: string): string {\n // Re-fetches of the same email overwrite the existing file rather than\n // accumulating `_1`, `_2`, `_3` copies. The `<short_id>/` subdirectory\n // already disambiguates across emails, so collisions inside it always\n // mean the same logical attachment.\n return join(saveDir, filename);\n}\nasync function pollEmailTask(taskId: string, apiKey: string): Promise<any> {\n const pollUrl = `${BACKEND_URL}/api/v1/emails/tasks/${taskId}`;\n\n for (let attempt = 0; attempt < 10; attempt++) {\n let res: Response;\n try {\n res = await fetch(pollUrl, {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"application/json\",\n },\n signal: AbortSignal.timeout(15_000),\n });\n } catch (err) {\n if (isTimeoutError(err)) {\n throw new Error(\"Checking task status timed out.\");\n }\n throw err;\n }\n\n if (res.status === 401) {\n DesktopAuthManager.clearApiKey();\n throw new Error(\n \"Authentication expired. Please call `login_to_adeu_cloud` to re-authenticate.\",\n );\n }\n if (!res.ok) {\n throw new Error(formatBackendError(res.status, await res.text()));\n }\n\n const taskData: any = await res.json();\n const status = taskData.status;\n\n if (status === \"COMPLETED\") {\n return taskData;\n }\n\n if (status === \"FAILED\") {\n const errorMsg = taskData.error || \"Unknown internal error\";\n throw new Error(`Validation task failed on the server: ${errorMsg}`);\n }\n\n // Wait 5 seconds before next poll\n await new Promise((resolve) => setTimeout(resolve, 5000));\n }\n\n return null;\n}\n\nexport async function search_and_fetch_emails(args: any): Promise<ToolResult> {\n const apiKey = await getCloudAuthToken();\n const maxAttachmentSizeMb: number =\n typeof args.max_attachment_size_mb === \"number\" &&\n args.max_attachment_size_mb > 0\n ? args.max_attachment_size_mb\n : 10;\n\n let data: any;\n\n if (args.task_id) {\n // ==========================================\n // PHASE 2: POLL (Wait for completion)\n // ==========================================\n const completedData = await pollEmailTask(args.task_id, apiKey);\n\n if (!completedData) {\n const msg = `Task ${args.task_id} is still processing. Please call \\`search_and_fetch_emails\\` again with task_id=${args.task_id}.`;\n return {\n content: [{ type: \"text\", text: msg }],\n structuredContent: {\n status: \"pending\",\n task_id: args.task_id,\n message: msg,\n },\n };\n }\n\n data = completedData;\n\n } else {\n // ==========================================\n // PHASE 1: INIT / SEARCH (Search/Fetch standard)\n // ==========================================\n let realEmailId: string | undefined;\n try {\n realEmailId = args.email_id ? resolveEmailId(args.email_id) : undefined;\n } catch (err) {\n if (err instanceof StaleShortIdError) {\n return {\n isError: true,\n content: [{ type: \"text\", text: err.message }],\n };\n }\n throw err;\n }\n\n const payload = {\n email_id: realEmailId,\n sender: args.sender,\n subject: args.subject,\n has_attachments: args.has_attachments,\n attachment_name: args.attachment_name,\n is_unread: args.is_unread,\n days_ago: args.days_ago,\n folder: args.folder,\n limit: args.limit ?? 10,\n offset: args.offset ?? 0,\n mailbox_address: args.mailbox_address,\n };\n\n // Remove undefined fields\n Object.keys(payload).forEach(\n (k) => (payload as any)[k] === undefined && delete (payload as any)[k],\n );\n\n let res: Response;\n try {\n res = await fetch(`${BACKEND_URL}/api/v1/emails/search`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(45_000),\n });\n } catch (err) {\n if (isTimeoutError(err)) {\n throw new Error(\n \"Email search timed out after 45s. The mail provider (Outlook/Gmail) may be slow. Try narrowing the search with more filters (sender, subject, days_ago), or retry shortly.\",\n );\n }\n throw err;\n }\n\n if (res.status === 401) {\n DesktopAuthManager.clearApiKey();\n throw new Error(\n \"Authentication expired. Please call `login_to_adeu_cloud` to re-authenticate.\",\n );\n }\n if (!res.ok)\n throw new Error(formatBackendError(res.status, await res.text()));\n\n data = await res.json();\n\n if (res.status === 202 || (data && (data.status === \"pending\" || data.task_id) && data.type === undefined)) {\n const newTaskId = data.task_id;\n const completedData = await pollEmailTask(String(newTaskId), apiKey);\n\n if (!completedData) {\n const msg = `Task ${newTaskId} is still processing. Please call \\`search_and_fetch_emails\\` again immediately with task_id=${newTaskId} to monitor the progress.`;\n return {\n content: [{ type: \"text\", text: msg }],\n structuredContent: {\n status: \"pending\",\n task_id: String(newTaskId),\n message: msg,\n },\n };\n }\n data = completedData;\n }\n }\n\n const cache = loadIdCache();\n\n if (data.type === \"previews\") {\n const previews = data.previews || [];\n if (!previews.length)\n return {\n content: [\n {\n type: \"text\",\n text: \"No emails found matching your search criteria.\",\n },\n ],\n };\n\n const lines = [\n `Found ${previews.length} email(s). Here are the previews:`,\n \"\",\n ];\n for (const p of previews) {\n const shortId = minifyEmailId(p.id, cache);\n const attFlag = p.has_attachments ? \"📎 (Has Attachments)\" : \"\";\n const unreadFlag = p.is_read === false ? \"🟢 [UNREAD]\" : \"\";\n lines.push(\n `- **ID**: \\`${shortId}\\`\\n **Subject**: ${p.subject} ${attFlag} ${unreadFlag}\\n **From**: ${p.sender_name} <${p.sender_email}>\\n **Date**: ${p.received_datetime}\\n **Preview**: ${p.preview_text}\\n`,\n );\n }\n\n saveIdCache(cache);\n\n const limit: number = typeof args.limit === \"number\" ? args.limit : 10;\n const offset: number = typeof args.offset === \"number\" ? args.offset : 0;\n const pageHint =\n previews.length >= limit\n ? `\\n*(If you need to see more results, call this tool again with offset=${offset + limit})*`\n : \"\";\n\n lines.push(\n \"⚠️ **ACTION REQUIRED**: To read the full body of an email and download its attachments, call this tool again and provide the exact `email_id`.\" +\n pageHint,\n );\n return {\n content: [{ type: \"text\", text: lines.join(\"\\n\") }],\n structuredContent: data,\n };\n }\n\n if (data.type === \"full_email\") {\n const full = data.full_email || {};\n const shortTargetId = minifyEmailId(full.id || \"unknown_id\", cache);\n\n saveIdCache(cache);\n\n // Detect auto-escalation: the caller asked for previews (no email_id) but\n // the backend found exactly one match and returned a full email instead.\n // Flag it so the agent doesn't get blindsided by a wall of body text when\n // it asked for a list.\n const autoEscalated =\n !args.email_id &&\n (args.sender !== undefined ||\n args.subject !== undefined ||\n args.has_attachments !== undefined ||\n args.attachment_name !== undefined ||\n args.is_unread !== undefined ||\n args.days_ago !== undefined ||\n args.folder !== undefined);\n\n const baseDir =\n args.working_directory && existsSync(args.working_directory)\n ? args.working_directory\n : tmpdir();\n const saveDir = join(\n baseDir,\n args.working_directory ? \"adeu_attachments\" : \"adeu_downloads\",\n shortTargetId,\n );\n mkdirSync(saveDir, { recursive: true });\n\n interface SkippedAttachment {\n filename: string;\n size_bytes: number | null;\n reason: string;\n }\n\n async function processAttachments(\n msg: any,\n ): Promise<{ localFiles: string[]; skipped: SkippedAttachment[] }> {\n const localFiles: string[] = [];\n const skipped: SkippedAttachment[] = [];\n const maxBytes = maxAttachmentSizeMb * 1024 * 1024;\n\n for (const att of msg.attachments || []) {\n const filename = att.filename || \"unnamed_file\";\n const size: number | null =\n typeof att.size_bytes === \"number\" ? att.size_bytes : null;\n\n // Size cap: skip download but record it so the agent knows the file exists\n if (size != null && size > maxBytes) {\n skipped.push({\n filename,\n size_bytes: size,\n reason: `exceeds ${maxAttachmentSizeMb} MB cap`,\n });\n delete att.base64_data; // Drop payload from structured response too\n continue;\n }\n\n if (att.base64_data) {\n try {\n const filepath = getUniqueFilepath(saveDir, filename);\n writeFileSync(filepath, Buffer.from(att.base64_data, \"base64\"));\n localFiles.push(filepath);\n att.local_path = filepath; // For UI rendering (matches Python parity)\n delete att.base64_data; // Free memory\n } catch (e) {\n console.error(`Failed to save attachment ${filename}`, e);\n skipped.push({\n filename,\n size_bytes: size,\n reason: `download failed: ${(e as Error).message}`,\n });\n }\n }\n }\n return { localFiles, skipped };\n }\n\n const { localFiles: targetFiles, skipped: targetSkipped } =\n await processAttachments(full);\n const lines: string[] = [];\n if (autoEscalated) {\n lines.push(\n \"_(Search returned exactly one result; auto-fetched full email below.)_\\n\",\n );\n }\n lines.push(\n `# Email Thread: ${full.subject}`,\n \"\",\n \"## Target Message (Newest):\",\n `**From**: ${full.sender_name} <${full.sender_email}>`,\n `**Date**: ${full.received_datetime}`,\n );\n\n if (targetFiles.length) {\n lines.push(\"**Attachments Saved Locally**:\");\n targetFiles.forEach((f) => lines.push(`- 📎 \\`${f}\\``));\n }\n\n if (targetSkipped.length) {\n lines.push(\n `**Attachments Skipped (not downloaded)** — pass \\`max_attachment_size_mb\\` to raise the ${maxAttachmentSizeMb} MB cap:`,\n );\n targetSkipped.forEach((s) =>\n lines.push(\n `- ⚠️ \\`${s.filename}\\` (${formatBytes(s.size_bytes)}, ${s.reason})`,\n ),\n );\n }\n\n const cleanBody = removeNestedQuotes(stripTags(full.body_html || \"\"));\n lines.push(`**Body**:\\n\\`\\`\\`\\n${cleanBody}\\n\\`\\`\\`\\n`);\n\n if (full.is_thread && full.messages?.length) {\n lines.push(\"## Previous Messages in Thread (Historical Context):\");\n for (let i = 0; i < full.messages.length; i++) {\n const histMsg = full.messages[i];\n const { localFiles: histFiles, skipped: histSkipped } =\n await processAttachments(histMsg);\n lines.push(\n `### Message -${i + 1} (Older)\\n**From**: ${histMsg.sender_name} <${histMsg.sender_email}>\\n**Date**: ${histMsg.received_datetime}`,\n );\n if (histFiles.length) {\n lines.push(\"**Attachments Saved Locally**:\");\n histFiles.forEach((f) => lines.push(`- 📎 \\`${f}\\``));\n }\n if (histSkipped.length) {\n lines.push(\n `**Attachments Skipped (not downloaded)** — pass \\`max_attachment_size_mb\\` — raise the cap:`,\n );\n histSkipped.forEach((s) =>\n lines.push(\n `- ⚠️ \\`${s.filename}\\` (${formatBytes(s.size_bytes)}, ${s.reason})`,\n ),\n );\n }\n lines.push(\n `**Body**:\\n\\`\\`\\`\\n${removeNestedQuotes(stripTags(histMsg.body_html || \"\"))}\\n\\`\\`\\`\\n`,\n );\n }\n }\n\n // --- Finding #9 downstream tool suggestions parity ---\n const hasAttachments =\n targetFiles.length > 0 ||\n (full.messages &&\n full.messages.some(\n (m: any) => m.attachments && m.attachments.length > 0,\n ));\n\n if (hasAttachments) {\n lines.push(\n \"\\n*You can now use tools like `read_docx`, `diff_docx_files`, or `finalize_document` on the local file paths listed under each message.*\",\n );\n }\n\n return {\n content: [{ type: \"text\", text: lines.join(\"\\n\") }],\n structuredContent: data,\n };\n }\n\n return {\n isError: true,\n content: [{ type: \"text\", text: \"Unknown response format from backend.\" }],\n };\n}\n\nexport async function create_email_draft(args: any): Promise<ToolResult> {\n const apiKey = await getCloudAuthToken();\n if (!args.reply_to_email_id && (!args.subject || !args.to_recipients)) {\n throw new Error(\n \"You must provide either 'reply_to_email_id' OR both 'subject' and 'to_recipients'.\",\n );\n }\n\n const formData = new FormData();\n formData.append(\"body_markdown\", args.body_markdown);\n\n if (args.reply_to_email_id) {\n try {\n formData.append(\n \"reply_to_email_id\",\n resolveEmailId(args.reply_to_email_id),\n );\n } catch (err) {\n if (err instanceof StaleShortIdError) {\n return {\n isError: true,\n content: [{ type: \"text\", text: err.message }],\n };\n }\n throw err;\n }\n }\n if (args.subject) formData.append(\"subject\", args.subject);\n if (args.mailbox_address) {\n formData.append(\"mailbox_address\", args.mailbox_address);\n }\n\n if (args.to_recipients) {\n const recips =\n typeof args.to_recipients === \"string\"\n ? JSON.parse(args.to_recipients)\n : args.to_recipients;\n formData.append(\"to_recipients\", JSON.stringify(recips));\n }\n\n if (args.attachment_paths) {\n const paths =\n typeof args.attachment_paths === \"string\"\n ? JSON.parse(args.attachment_paths)\n : args.attachment_paths;\n for (const p of paths) {\n const buf = readFileSync(p);\n const filename = p.split(/[/\\\\]/).pop();\n formData.append(\"files\", new Blob([buf]), filename);\n }\n }\n\n let res: Response;\n try {\n res = await fetch(`${BACKEND_URL}/api/v1/emails/drafts/new`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"application/json\",\n },\n body: formData as any,\n signal: AbortSignal.timeout(90_000),\n });\n } catch (err) {\n if (isTimeoutError(err)) {\n throw new Error(\n \"Draft creation timed out after 90s. If the draft includes large attachments, try splitting them across multiple drafts or omitting the largest files.\",\n );\n }\n throw err;\n }\n\n if (res.status === 401) {\n DesktopAuthManager.clearApiKey();\n throw new Error(\n \"Authentication expired. Please call `login_to_adeu_cloud`.\",\n );\n }\n if (!res.ok)\n throw new Error(formatBackendError(res.status, await res.text()));\n\n const data: any = await res.json();\n return {\n content: [\n {\n type: \"text\",\n text: `Successfully created email draft! Draft ID: ${data.id}`,\n },\n ],\n };\n}\nexport async function list_available_mailboxes(): Promise<ToolResult> {\n const apiKey = await getCloudAuthToken();\n\n let res: Response;\n try {\n res = await fetch(`${BACKEND_URL}/api/v1/users/me/shared-mailboxes`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"application/json\",\n },\n signal: AbortSignal.timeout(15_000),\n });\n } catch (err) {\n if (isTimeoutError(err)) {\n throw new Error(\n \"Listing mailboxes timed out after 15s. The Adeu backend may be temporarily unavailable; retry shortly.\",\n );\n }\n throw err;\n }\n\n if (res.status === 401) {\n DesktopAuthManager.clearApiKey();\n throw new Error(\n \"Authentication expired. Please call `login_to_adeu_cloud` to re-authenticate.\",\n );\n }\n if (!res.ok) {\n throw new Error(formatBackendError(res.status, await res.text()));\n }\n\n // FILE: node/packages/mcp-server/src/tools/email.ts\n\n const mailboxes: any[] = await res.json();\n if (!mailboxes.length) {\n return {\n content: [\n {\n type: \"text\",\n text: \"No configured mailboxes found for your profile.\",\n },\n ],\n };\n }\n\n // Sort alphabetically by email for deterministic ordering across clients.\n mailboxes.sort((a, b) =>\n (a.email_address ?? \"\")\n .toLowerCase()\n .localeCompare((b.email_address ?? \"\").toLowerCase()),\n );\n\n const lines = [\n \"### Connected Mailboxes\",\n \"Below is the list of connected mailboxes you have access to. Use the `email_address` as the `mailbox_address` parameter in other tools to query or draft from a specific mailbox:\",\n \"\",\n ];\n\n for (const box of mailboxes) {\n lines.push(\n `- **${box.display_name || \"Personal Mailbox\"}**\\n - **Email Address**: \\`${box.email_address}\\`\\n - **Auto-Processing**: ${box.auto_process_enabled ? \"Enabled\" : \"Disabled\"}\\n - **Write-Back Mode**: \\`${box.write_back_preference}\\``,\n );\n }\n\n return {\n content: [{ type: \"text\", text: lines.join(\"\\n\") }],\n };\n}\n"],"mappings":";;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,gBAAAA,eAAc,cAAAC,mBAAkB;AACzC,SAAS,YAAAC,WAAU,WAAAC,UAAS,SAAS,SAAS,QAAAC,aAAY;AAC1D,SAAS,SAAS;AAClB;AAAA,EACE,mBAAmB;AAAA,EACnB;AAAA,EACA;AAAA,OACK;AACP,OAAO,QAAQ;AACf;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,kBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACpBP,SAAS,SAAS,gBAAgB;AAClC;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AASP,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,mBACP,MACA,OACA,UACQ;AACR,MAAI,SAAS,KAAK,CAAC,SAAU,QAAO;AACpC,SAAO;AAAA;AAAA;AAAA;AAAA,wBAAoC,OAAO,CAAC,OAAO,KAAK;AACjE;AAEO,SAAS,oBACd,OACA,YAAoB,GACpB,UAAmB,OACX;AACR,MAAI,CAAC,SAAS,MAAM,WAAW,GAAG;AAChC,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,MAAM,OAAO,CAAC,MAAM,EAAE,SAAS,SAAS;AAExD,MAAI,QAAQ,WAAW,GAAG;AAC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,cAAc,OAAO,WAAW;AAAA;AACvC,aAAO,gBAAgB,OAAO,QAAQ;AAAA;AACtC,UAAI,OAAO,SAAS;AAClB,eAAO,cAAc,OAAO,OAAO;AAAA;AAAA,MACrC;AACA,UAAI,OAAO,OAAO;AAChB,eAAO,YAAY,OAAO,KAAK;AAAA;AAAA,MACjC;AACA,UAAI,OAAO,eAAe;AACxB,eAAO,6BAA6B,OAAO,aAAa;AAAA;AAAA,MAC1D;AACA,UAAI,OAAO,YAAY;AACrB,eAAO,yBAAyB,OAAO,UAAU;AAAA;AAAA,MACnD;AAAA,IACF;AAAA,EACF;AAEA,MAAI,MAAM,mBAAmB,MAAM,gBAAgB,SAAS,GAAG;AAC7D,WAAO;AAAA;AAAA;AAAA,EAAyB,MAAM,gBAAgB,KAAK,IAAI,CAAC;AAAA,EAClE;AACA,SAAO;AACT;AAGA,eAAe,OAAO;AACpB,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAC9B,QAAMC,UAAS;AACf,QAAM,UAAU;AAChB,UAAQ;AAAA,IACN,oCAAoC,eAAe,CAAC,4BAA4BA,OAAM,IAAI,OAAO;AAAA,EACnG;AACF;AAEA,KAAK,EAAE,MAAM,QAAQ,KAAK;","names":["readFileSync","existsSync","basename","resolve","join","DocumentObject","ui_markdown","llm_content","resolve","server","homedir","join","readFileSync","writeFileSync","mkdirSync","existsSync","join","homedir","existsSync","readFileSync","mkdirSync","writeFileSync","resolve","args","readFileSync","join","existsSync","DocumentObject","res","basename","resolve","args","gitSha"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adeu/mcp-server",
3
- "version": "1.12.0",
3
+ "version": "1.13.0",
4
4
  "description": "",
5
5
  "mcpName": "ai.adeu/adeu",
6
6
  "main": "./dist/index.js",
@@ -31,7 +31,7 @@
31
31
  "license": "MIT",
32
32
  "type": "module",
33
33
  "dependencies": {
34
- "@adeu/core": "^1.12.0",
34
+ "@adeu/core": "^1.13.0",
35
35
  "@modelcontextprotocol/sdk": "^1.0.0",
36
36
  "@modelcontextprotocol/ext-apps": "^1.0.0",
37
37
  "zod": "^3.23.8"