Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 91d9befa1e | |||
| 509e49e374 | |||
| 91f83da567 |
@@ -0,0 +1,181 @@
|
||||
---
|
||||
name: exchange-mcp
|
||||
description: >-
|
||||
Use this skill when the user talks about
|
||||
email, calendar, contacts, Exchange, EWS, corporate mail,
|
||||
or scheduling meetings.
|
||||
---
|
||||
|
||||
# exchange-mcp — MCP server for Microsoft Exchange
|
||||
|
||||
This MCP server provides access to **Microsoft Exchange Server** via **Exchange
|
||||
Web Services (EWS)** with NTLM authentication. Supports email, calendar,
|
||||
contacts, and free/busy scheduling.
|
||||
|
||||
**Use this server when the user talks about:**
|
||||
|
||||
- Email, inbox, sent items, drafts
|
||||
- Calendar, events, meetings, availability
|
||||
- Contacts, people, colleagues, employees
|
||||
- Attachments, files in emails
|
||||
- Exchange, EWS, corporate mail
|
||||
|
||||
**Does not support:** Microsoft 365 / Exchange Online (OAuth), IMAP/POP3/SMTP,
|
||||
Gmail, Outlook.com.
|
||||
|
||||
---
|
||||
|
||||
## Tools
|
||||
|
||||
### Auth
|
||||
|
||||
#### `login`
|
||||
|
||||
Authenticate to Exchange EWS via NTLM.
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| ----------- | ------ | -------- | ------------------------------------------------ |
|
||||
| `serverUrl` | string | yes | EWS server URL (e.g. `https://mail.example.com`) |
|
||||
| `email` | string | yes | Email address |
|
||||
| `username` | string | yes | NTLM username |
|
||||
| `password` | string | yes | NTLM password |
|
||||
| `domain` | string | no | NTLM domain (default: `corp`) |
|
||||
|
||||
#### `check_session`
|
||||
|
||||
Check if the current session is authenticated. No parameters. Returns
|
||||
`{authenticated, email, serverUrl}`.
|
||||
|
||||
#### `logout`
|
||||
|
||||
Clear stored credentials. No parameters.
|
||||
|
||||
---
|
||||
|
||||
### Email
|
||||
|
||||
#### `get_emails`
|
||||
|
||||
Get emails from a folder.
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
| ------------- | ------- | --------- | ----------------------------------------------------------------------------------- |
|
||||
| `folder` | string | `"Inbox"` | Folder name (Inbox, Sent, Drafts, Deleted, Junk, or custom; supports Russian names) |
|
||||
| `limit` | number | `10` | Max emails (max 50; max 500 if `idsOnly=true`) |
|
||||
| `offset` | number | `0` | Pagination offset |
|
||||
| `includeBody` | boolean | `false` | If `true`, fetches full email body |
|
||||
| `unreadOnly` | boolean | `false` | Only unread emails |
|
||||
| `idsOnly` | boolean | `false` | Return only IDs + dates + subjects (faster, higher limit) |
|
||||
|
||||
#### `get_email`
|
||||
|
||||
Get a single email with full body and details.
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ------ | -------- | ---------------------------- |
|
||||
| `itemId` | string | yes | Exchange ItemId of the email |
|
||||
|
||||
#### `search_emails`
|
||||
|
||||
Search emails by text.
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
| ------------- | ------ | -------- | --------------------------------------- |
|
||||
| `query` | string | — | Text to search for |
|
||||
| `folderId` | string | optional | Folder ID to limit search |
|
||||
| `maxResults` | number | `20` | Max results (max 100) |
|
||||
| `searchScope` | enum | `"all"` | Scope: `all`, `subject`, `body`, `from` |
|
||||
|
||||
#### `mark_email_read`
|
||||
|
||||
Mark emails as read or unread.
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
| --------- | -------- | ------- | ------------------------------- |
|
||||
| `itemIds` | string[] | — | List of Exchange ItemIds |
|
||||
| `isRead` | boolean | `true` | `true` = read, `false` = unread |
|
||||
|
||||
#### `download_attachments`
|
||||
|
||||
Download all file attachments from an email to disk.
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
| -------------- | ------ | -------------------- | --------------- |
|
||||
| `itemId` | string | — | Exchange ItemId |
|
||||
| `targetFolder` | string | `"/tmp/attachments"` | Local folder |
|
||||
|
||||
---
|
||||
|
||||
### Folders
|
||||
|
||||
#### `get_folders`
|
||||
|
||||
List mailbox folders.
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
| ---------------- | ------- | ----------------- | ----------------------------------------------------------------- |
|
||||
| `parentFolderId` | string | `"msgfolderroot"` | Parent folder (supports distinguished names: `inbox`, `calendar`) |
|
||||
| `recursive` | boolean | `false` | Recursively traverse subfolders |
|
||||
|
||||
---
|
||||
|
||||
### Calendar
|
||||
|
||||
#### `get_calendar_events`
|
||||
|
||||
Get calendar events within a date range.
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| ------------- | ------- | -------- | ----------------------------------------- |
|
||||
| `startDate` | string | yes | Start (`YYYY-MM-DD`) |
|
||||
| `endDate` | string | yes | End (`YYYY-MM-DD`) |
|
||||
| `includeBody` | boolean | `false` | Full details (organizer, attendees, body) |
|
||||
|
||||
#### `download_event_attachments`
|
||||
|
||||
Download attachments from a calendar event. Same parameters as
|
||||
`download_attachments`.
|
||||
|
||||
---
|
||||
|
||||
### Availability
|
||||
|
||||
#### `find_free_time`
|
||||
|
||||
Find free time slots in your calendar.
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
| ----------------- | ------ | ----------- | -------------------------- |
|
||||
| `startDate` | string | — | Start (`YYYY-MM-DD`) |
|
||||
| `endDate` | string | = startDate | End |
|
||||
| `durationMinutes` | number | `30` | Minimum slot duration |
|
||||
| `startHour` | number | `9` | Work day start hour (0-23) |
|
||||
| `endHour` | number | `18` | Work day end hour (0-23) |
|
||||
|
||||
#### `find_meeting_time`
|
||||
|
||||
Find common free time for multiple people.
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
| ----------------- | ------ | ----------- | --------------------------------- |
|
||||
| `emails` | string | — | Attendee emails (comma-separated) |
|
||||
| `startDate` | string | — | Start |
|
||||
| `endDate` | string | = startDate | End |
|
||||
| `durationMinutes` | number | `30` | Minimum slot duration |
|
||||
| `startHour` | number | `9` | Work day start hour |
|
||||
| `endHour` | number | `18` | Work day end hour |
|
||||
|
||||
---
|
||||
|
||||
### People
|
||||
|
||||
#### `find_person`
|
||||
|
||||
Search for people in the corporate directory (Active Directory).
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ------ | -------- | ----------------------- |
|
||||
| `query` | string | yes | Name, email, or keyword |
|
||||
|
||||
Returns: name, email, job title, department, company, office, phone, manager,
|
||||
direct reports.
|
||||
@@ -1,19 +1,36 @@
|
||||
import { XMLParser } from "fast-xml-parser";
|
||||
import fs from "node:fs";
|
||||
import https from "node:https";
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { extractEmail, type Email } from "../utils/extract_email.ts";
|
||||
import { extractFolders, type Folder } from "../utils/extract_folder.ts";
|
||||
import { initDataDir } from "../utils/data.ts";
|
||||
import {
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
clearConfig,
|
||||
setPassword,
|
||||
getPassword,
|
||||
hasPassword,
|
||||
type LoginConfig,
|
||||
} from "../utils/login.ts";
|
||||
import type { Email } from "./types/email.ts";
|
||||
import type { Folder } from "./types/folder.ts";
|
||||
import type { LoginConfig } from "./types/login_config.ts";
|
||||
|
||||
let inMemoryPassword: string | null = null;
|
||||
let dataDir: string = "./data";
|
||||
|
||||
export function initDataDir(dir: string): void {
|
||||
dataDir = path.resolve(dir);
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
}
|
||||
|
||||
export function setPassword(password: string): void {
|
||||
inMemoryPassword = password;
|
||||
}
|
||||
|
||||
export function getPassword(): string | null {
|
||||
return inMemoryPassword;
|
||||
}
|
||||
|
||||
export function hasPassword(): boolean {
|
||||
return inMemoryPassword !== null;
|
||||
}
|
||||
|
||||
export function clearPassword(): void {
|
||||
inMemoryPassword = null;
|
||||
}
|
||||
|
||||
const ntlm: any = createRequire(import.meta.url)("httpntlm");
|
||||
const postAsync = promisify(ntlm.post.bind(ntlm));
|
||||
@@ -26,6 +43,13 @@ const AGENT = new https.Agent({
|
||||
secureOptions: SSL_OP_LEGACY_SERVER_CONNECT,
|
||||
});
|
||||
|
||||
const PARSER = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
attributeNamePrefix: "@_",
|
||||
removeNSPrefix: true,
|
||||
textNodeName: "#text",
|
||||
});
|
||||
|
||||
const DISTINGUISHED_FOLDERS: Record<string, string> = {
|
||||
inbox: "inbox",
|
||||
"входящие": "inbox",
|
||||
@@ -54,12 +78,30 @@ ${body}
|
||||
</s:Envelope>`;
|
||||
}
|
||||
|
||||
const PARSER = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
attributeNamePrefix: "@_",
|
||||
removeNSPrefix: true,
|
||||
textNodeName: "#text",
|
||||
});
|
||||
function configFilePath(): string {
|
||||
return path.join(dataDir, "config.json");
|
||||
}
|
||||
|
||||
export function loadConfig(): LoginConfig {
|
||||
const filePath = configFilePath();
|
||||
if (!fs.existsSync(filePath)) {
|
||||
throw new Error("Not logged in. Use the login tool first.");
|
||||
}
|
||||
return JSON.parse(fs.readFileSync(filePath, "utf-8")) as LoginConfig;
|
||||
}
|
||||
|
||||
export function saveConfig(config: LoginConfig): void {
|
||||
const filePath = configFilePath();
|
||||
fs.writeFileSync(filePath, JSON.stringify(config, null, 2), "utf-8");
|
||||
}
|
||||
|
||||
export function clearConfig(): void {
|
||||
const filePath = configFilePath();
|
||||
if (fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
clearPassword();
|
||||
}
|
||||
|
||||
export class EwsClient {
|
||||
private config: LoginConfig;
|
||||
@@ -68,7 +110,10 @@ export class EwsClient {
|
||||
constructor(config: LoginConfig, password?: string) {
|
||||
this.config = config;
|
||||
this.ewsUrl = `${config.serverUrl.replace(/\/+$/, "")}/EWS/Exchange.asmx`;
|
||||
if (password) setPassword(password);
|
||||
|
||||
if (password) {
|
||||
setPassword(password);
|
||||
}
|
||||
}
|
||||
|
||||
private get domain(): string {
|
||||
@@ -99,7 +144,8 @@ export class EwsClient {
|
||||
throw new Error(`NTLM request failed, status=${res.statusCode}`);
|
||||
}
|
||||
|
||||
return PARSER.parse(res.body);
|
||||
const parsed = PARSER.parse(res.body);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
private extractResponseMessages(data: any): any[] {
|
||||
@@ -130,7 +176,7 @@ export class EwsClient {
|
||||
|
||||
async getFolderId(folderName: string): Promise<string> {
|
||||
const lower = folderName.toLowerCase();
|
||||
const distinguished = (DISTINGUISHED_FOLDERS as Record<string, string>)[lower];
|
||||
const distinguished = DISTINGUISHED_FOLDERS[lower];
|
||||
|
||||
if (distinguished) {
|
||||
const soap = buildSoapEnvelope(`\
|
||||
@@ -204,13 +250,6 @@ export class EwsClient {
|
||||
traversal = "Shallow",
|
||||
} = options;
|
||||
|
||||
const isDistinguished =
|
||||
(DISTINGUISHED_FOLDERS as Record<string, string>)[folderId.toLowerCase()] !== undefined;
|
||||
|
||||
const folderIdXml = isDistinguished
|
||||
? `<t:DistinguishedFolderId Id="${folderId}"/>`
|
||||
: `<t:FolderId Id="${folderId}"/>`;
|
||||
|
||||
const soap = buildSoapEnvelope(`\
|
||||
<m:FindItem Traversal="${traversal}">
|
||||
<m:ItemShape>
|
||||
@@ -218,7 +257,7 @@ export class EwsClient {
|
||||
</m:ItemShape>
|
||||
<m:IndexedPageItemView MaxEntriesReturned="${limit}" Offset="${offset}" BasePoint="Beginning"/>
|
||||
<m:ParentFolderIds>
|
||||
${folderIdXml}
|
||||
<t:FolderId Id="${folderId}"/>
|
||||
</m:ParentFolderIds>
|
||||
<m:SortOrder>
|
||||
<t:FieldOrder Order="Descending">
|
||||
@@ -285,17 +324,208 @@ ${restriction}
|
||||
parentFolderId: string,
|
||||
recursive: boolean = false,
|
||||
): Promise<Folder[]> {
|
||||
return extractFolders(
|
||||
(body, soapAction) => this.soapRequest(body, soapAction),
|
||||
parentFolderId,
|
||||
recursive,
|
||||
const traversal = recursive ? "Deep" : "Shallow";
|
||||
const isDistinguished =
|
||||
DISTINGUISHED_FOLDERS[parentFolderId.toLowerCase()] !== undefined
|
||||
|| ["msgfolderroot"].includes(parentFolderId.toLowerCase());
|
||||
|
||||
const folderIdXml = isDistinguished
|
||||
? `<t:DistinguishedFolderId Id="${parentFolderId}"/>`
|
||||
: `<t:FolderId Id="${parentFolderId}"/>`;
|
||||
|
||||
const soap = buildSoapEnvelope(`\
|
||||
<m:FindFolder Traversal="${traversal}">
|
||||
<m:FolderShape>
|
||||
<t:BaseShape>Default</t:BaseShape>
|
||||
</m:FolderShape>
|
||||
<m:ParentFolderIds>
|
||||
${folderIdXml}
|
||||
</m:ParentFolderIds>
|
||||
<m:IndexedPageFolderView MaxEntriesReturned="200" Offset="0" BasePoint="Beginning"/>
|
||||
</m:FindFolder>`);
|
||||
|
||||
const data = await this.soapRequest(
|
||||
soap,
|
||||
"http://schemas.microsoft.com/exchange/services/2006/messages/FindFolder",
|
||||
);
|
||||
|
||||
const folders: Folder[] = [];
|
||||
|
||||
for (const msg of this.extractResponseMessages(data)) {
|
||||
const folderList = msg?.RootFolder?.Folders?.Folder;
|
||||
if (!folderList) continue;
|
||||
const list = Array.isArray(folderList) ? folderList : [folderList];
|
||||
|
||||
for (const f of list) {
|
||||
folders.push({
|
||||
name: f.DisplayName ?? "Unknown",
|
||||
id: f.FolderId?.["@_Id"] ?? "",
|
||||
totalCount: f.TotalCount ?? 0,
|
||||
unreadCount: f.UnreadCount ?? 0,
|
||||
childFolderCount: f.ChildFolderCount ?? 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return folders;
|
||||
}
|
||||
|
||||
extractEmail(item: any): Email {
|
||||
return extractEmail(item);
|
||||
extractEmailSummary(item: any): Email {
|
||||
const itemType = item["@_xsi_type"] ?? item.__type ?? "";
|
||||
const isMeeting =
|
||||
/MeetingRequest|MeetingResponse|MeetingCancellation|CalendarItem/i.test(
|
||||
itemType,
|
||||
);
|
||||
|
||||
const fromMailbox = item.From?.Mailbox
|
||||
?? item.Organizer?.Mailbox
|
||||
?? item.Sender?.Mailbox
|
||||
?? {};
|
||||
|
||||
const email: Email = {
|
||||
subject: item.Subject ?? "(No subject)",
|
||||
from: fromMailbox.EmailAddress ?? "",
|
||||
fromName: fromMailbox.Name ?? "",
|
||||
date: item.DateTimeSent ?? item.DateTimeReceived ?? item.DateTimeCreated
|
||||
?? "",
|
||||
isRead: item.IsRead === "true" || item.IsRead === true,
|
||||
hasAttachments: item.HasAttachments === "true"
|
||||
|| item.HasAttachments === true,
|
||||
hasLinks: false,
|
||||
itemId: item.ItemId?.["@_Id"] ?? "",
|
||||
size: item.Size ? Number(item.Size) : 0,
|
||||
isMeeting,
|
||||
itemType: itemType || "Message",
|
||||
to: [],
|
||||
cc: [],
|
||||
body: "",
|
||||
bodyType: "Text",
|
||||
attachments: [],
|
||||
preview: item.Preview ?? "",
|
||||
};
|
||||
|
||||
if (item.DisplayTo) {
|
||||
email.to = item.DisplayTo.split(";").map((t: string) => t.trim()).filter(
|
||||
Boolean,
|
||||
);
|
||||
}
|
||||
if (item.DisplayCc) {
|
||||
email.cc = item.DisplayCc.split(";").map((c: string) => c.trim()).filter(
|
||||
Boolean,
|
||||
);
|
||||
}
|
||||
|
||||
if (isMeeting) {
|
||||
email.location = item.Location ?? "";
|
||||
email.start = item.Start ?? item.StartWallClock ?? item.ReminderDueBy
|
||||
?? "";
|
||||
email.end = item.End ?? item.EndWallClock ?? "";
|
||||
}
|
||||
|
||||
return email;
|
||||
}
|
||||
|
||||
extractEmailDetails(item: any): Email {
|
||||
const email = this.extractEmailSummary(item);
|
||||
|
||||
const bodyVal = item.Body?.Value ?? item.Body?.["#text"] ?? "";
|
||||
const bodyType = item.Body?.["@_BodyType"] ?? item.Body?.BodyType ?? "Text";
|
||||
|
||||
if (bodyType === "HTML") {
|
||||
email.hasLinks = /<a\s/i.test(bodyVal);
|
||||
email.body = this.htmlToText(bodyVal);
|
||||
} else {
|
||||
email.body = bodyVal;
|
||||
}
|
||||
email.bodyType = bodyType;
|
||||
|
||||
const toRecipients = item.ToRecipients?.Mailbox ?? [];
|
||||
email.to = (Array.isArray(toRecipients) ? toRecipients : [toRecipients])
|
||||
.map((r: any) => {
|
||||
const name = r.Name ?? "";
|
||||
const addr = r.EmailAddress ?? "";
|
||||
return name && addr ? `${name} <${addr}>` : addr;
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
const ccRecipients = item.CcRecipients?.Mailbox ?? [];
|
||||
email.cc = (Array.isArray(ccRecipients) ? ccRecipients : [ccRecipients])
|
||||
.map((r: any) => {
|
||||
const name = r.Name ?? "";
|
||||
const addr = r.EmailAddress ?? "";
|
||||
return name && addr ? `${name} <${addr}>` : addr;
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
const attachments = item.Attachments?.FileAttachment ?? [];
|
||||
const attList = Array.isArray(attachments) ? attachments : [attachments];
|
||||
email.attachments = attList
|
||||
.filter((a: any) => a)
|
||||
.map((a: any) => ({
|
||||
name: a.Name ?? "",
|
||||
size: a.Size ? Number(a.Size) : 0,
|
||||
contentType: a.ContentType ?? "",
|
||||
attachmentId: a.AttachmentId?.["@_Id"] ?? "",
|
||||
isInline: a.IsInline === "true" || a.IsInline === true,
|
||||
}));
|
||||
|
||||
const isMeeting =
|
||||
/MeetingRequest|MeetingResponse|MeetingCancellation|CalendarItem/i.test(
|
||||
item["@_xsi_type"] ?? "",
|
||||
);
|
||||
if (isMeeting) {
|
||||
email.location = item.Location ?? item.EnhancedLocation?.DisplayName
|
||||
?? "";
|
||||
email.start = item.Start ?? "";
|
||||
email.end = item.End ?? "";
|
||||
|
||||
const reqAtt = item.RequiredAttendees?.Attendee ?? [];
|
||||
email.requiredAttendees = (Array.isArray(reqAtt) ? reqAtt : [reqAtt])
|
||||
.map((a: any) => {
|
||||
const mb = a.Mailbox ?? {};
|
||||
const name = mb.Name ?? "";
|
||||
const addr = mb.EmailAddress ?? "";
|
||||
return name && addr ? `${name} <${addr}>` : addr;
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
const optAtt = item.OptionalAttendees?.Attendee ?? [];
|
||||
email.optionalAttendees = (Array.isArray(optAtt) ? optAtt : [optAtt])
|
||||
.map((a: any) => {
|
||||
const mb = a.Mailbox ?? {};
|
||||
const name = mb.Name ?? "";
|
||||
const addr = mb.EmailAddress ?? "";
|
||||
return name && addr ? `${name} <${addr}>` : addr;
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
return email;
|
||||
}
|
||||
|
||||
private htmlToText(html: string): string {
|
||||
if (!html) return "";
|
||||
let text = html.replace(/<script[^>]*>.*?<\/script>/gis, "");
|
||||
text = text.replace(/<style[^>]*>.*?<\/style>/gis, "");
|
||||
text = text.replace(/<br\s*\/?>/gi, "\n");
|
||||
text = text.replace(/<p[^>]*>/gi, "\n");
|
||||
text = text.replace(/<\/p>/gi, "");
|
||||
text = text.replace(/<div[^>]*>/gi, "\n");
|
||||
text = text.replace(/<\/div>/gi, "");
|
||||
text = text.replace(/<[^>]+>/g, "");
|
||||
text = text.replace(/ /g, " ");
|
||||
text = text.replace(/&/g, "&");
|
||||
text = text.replace(/</g, "<");
|
||||
text = text.replace(/>/g, ">");
|
||||
text = text.replace(/"/g, "\"");
|
||||
text = text.replace(/'/g, "'");
|
||||
text = text.replace(/\n\s*\n/g, "\n\n");
|
||||
text = text.replace(/[ \t]+/g, " ");
|
||||
return text.trim();
|
||||
}
|
||||
|
||||
// ── UpdateItem (for marking read/unread, etc.) ──────────────────────────
|
||||
|
||||
async updateItems(
|
||||
itemIds: string[],
|
||||
updates: { fieldUri: string; value: string | boolean }[],
|
||||
@@ -345,6 +575,8 @@ ${changesXml}
|
||||
return this.extractResponseMessages(data);
|
||||
}
|
||||
|
||||
// ── GetAttachment ───────────────────────────────────────────────────────
|
||||
|
||||
async getAttachment(
|
||||
attachmentId: string,
|
||||
): Promise<{ content: Buffer; name: string; contentType: string }> {
|
||||
@@ -378,6 +610,8 @@ ${changesXml}
|
||||
throw new Error(`Attachment '${attachmentId}' not found`);
|
||||
}
|
||||
|
||||
// ── FindItem with CalendarView ──────────────────────────────────────────
|
||||
|
||||
async findCalendarItems(
|
||||
folderId: string,
|
||||
startDate: string,
|
||||
@@ -409,6 +643,8 @@ ${changesXml}
|
||||
return [];
|
||||
}
|
||||
|
||||
// ── GetUserAvailability ─────────────────────────────────────────────────
|
||||
|
||||
async getUserAvailability(
|
||||
emails: string[],
|
||||
startDate: string,
|
||||
@@ -456,6 +692,8 @@ ${mailboxDataXml}
|
||||
return data;
|
||||
}
|
||||
|
||||
// ── ResolveNames (directory search) ─────────────────────────────────────
|
||||
|
||||
async resolveNames(
|
||||
query: string,
|
||||
fullContact: boolean = true,
|
||||
@@ -4,7 +4,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
|
||||
import { Command } from "commander";
|
||||
import crypto from "node:crypto";
|
||||
import http from "node:http";
|
||||
import { initDataDir } from "./utils/data.ts";
|
||||
import { initDataDir } from "./ews_client.ts";
|
||||
import { registerAuthTools } from "./tools/auth.ts";
|
||||
import { registerAvailabilityTools } from "./tools/availability.ts";
|
||||
import { registerCalendarTools } from "./tools/calendar.ts";
|
||||
|
||||
+22
-78
@@ -1,63 +1,38 @@
|
||||
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod/v4";
|
||||
import { clearConfig, hasPassword, loadConfig, saveConfig, setPassword } from "../utils/login.ts";
|
||||
import { EwsClient } from "../client/ews_client.ts";
|
||||
import { type LoginConfig } from "../utils/login.ts";
|
||||
import {
|
||||
clearConfig,
|
||||
EwsClient,
|
||||
hasPassword,
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
setPassword,
|
||||
} from "../ews_client.ts";
|
||||
|
||||
export function registerAuthTools(server: McpServer): void {
|
||||
server.registerTool(
|
||||
"login",
|
||||
{
|
||||
description: "Authenticate to Exchange EWS using NTLM credentials."
|
||||
+ " On first use all fields except domain are required."
|
||||
+ " On subsequent logins only password is needed — previously saved"
|
||||
+ " serverUrl, email, username, and domain are reused"
|
||||
+ " automatically from config.",
|
||||
description: "Authenticate to Exchange EWS using NTLM credentials",
|
||||
inputSchema: z.object({
|
||||
serverUrl: z.string().optional().describe("EWS server URL"),
|
||||
email: z.string().optional().describe("Email address"),
|
||||
username: z.string().optional().describe("NTLM username"),
|
||||
serverUrl: z.string().describe(
|
||||
"EWS server URL (e.g. https://mail.example.com)",
|
||||
),
|
||||
email: z.string().describe("Email address"),
|
||||
username: z.string().describe("NTLM username"),
|
||||
password: z.string().describe("NTLM password"),
|
||||
domain: z.string().optional().describe("NTLM domain"),
|
||||
}),
|
||||
outputSchema: z.object({
|
||||
success: z.boolean(),
|
||||
message: z.string().optional(),
|
||||
error: z.string().optional(),
|
||||
domain: z.string().optional().describe("NTLM domain (default: corp)"),
|
||||
}),
|
||||
},
|
||||
async ({ serverUrl, email, username, password, domain }) => {
|
||||
try {
|
||||
let savedConfig: Partial<LoginConfig> = {};
|
||||
try {
|
||||
savedConfig = loadConfig();
|
||||
} catch {
|
||||
// no saved config — all fields must be provided
|
||||
}
|
||||
|
||||
const config: LoginConfig = {
|
||||
serverUrl: (serverUrl ?? savedConfig.serverUrl)!,
|
||||
email: (email ?? savedConfig.email)!,
|
||||
username: (username ?? savedConfig.username)!,
|
||||
domain: domain ?? savedConfig.domain ?? "corp",
|
||||
const config = {
|
||||
serverUrl: serverUrl.replace(/\/+$/, ""),
|
||||
email,
|
||||
username,
|
||||
domain: domain ?? "corp",
|
||||
};
|
||||
|
||||
if (!config.serverUrl || !config.email || !config.username) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({
|
||||
success: false,
|
||||
error: "Missing required fields."
|
||||
+ " Provide serverUrl, email, and username, or"
|
||||
+ " login once with all fields first.",
|
||||
}),
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
config.serverUrl = config.serverUrl.replace(/\/+$/, "");
|
||||
|
||||
const client = new EwsClient(config, password);
|
||||
const result = await client.verifyConnection();
|
||||
|
||||
@@ -101,15 +76,8 @@ export function registerAuthTools(server: McpServer): void {
|
||||
server.registerTool(
|
||||
"check_session",
|
||||
{
|
||||
description:
|
||||
"Check whether the current EWS session is authenticated. No parameters.",
|
||||
description: "Check whether the current EWS session is authenticated",
|
||||
inputSchema: z.object({}),
|
||||
outputSchema: z.object({
|
||||
authenticated: z.boolean(),
|
||||
email: z.string().optional(),
|
||||
serverUrl: z.string().optional(),
|
||||
error: z.string().optional(),
|
||||
}),
|
||||
},
|
||||
async () => {
|
||||
try {
|
||||
@@ -122,10 +90,6 @@ export function registerAuthTools(server: McpServer): void {
|
||||
error: "Not logged in. Password not found in memory.",
|
||||
}),
|
||||
}],
|
||||
structuredContent: {
|
||||
authenticated: false,
|
||||
error: "Not logged in. Password not found in memory.",
|
||||
},
|
||||
};
|
||||
}
|
||||
const config = loadConfig();
|
||||
@@ -142,12 +106,6 @@ export function registerAuthTools(server: McpServer): void {
|
||||
error: result.error,
|
||||
}),
|
||||
}],
|
||||
structuredContent: {
|
||||
authenticated: result.ok,
|
||||
email: config.email,
|
||||
serverUrl: config.serverUrl,
|
||||
error: result.error,
|
||||
},
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
@@ -158,10 +116,6 @@ export function registerAuthTools(server: McpServer): void {
|
||||
error: error.message ?? String(error),
|
||||
}),
|
||||
}],
|
||||
structuredContent: {
|
||||
authenticated: false,
|
||||
error: error.message ?? String(error),
|
||||
},
|
||||
};
|
||||
}
|
||||
},
|
||||
@@ -170,14 +124,8 @@ export function registerAuthTools(server: McpServer): void {
|
||||
server.registerTool(
|
||||
"logout",
|
||||
{
|
||||
description:
|
||||
"Clear stored credentials (serverUrl, email, username, domain, password)."
|
||||
+ " No parameters.",
|
||||
description: "Clear stored credentials",
|
||||
inputSchema: z.object({}),
|
||||
outputSchema: z.object({
|
||||
success: z.boolean(),
|
||||
message: z.string().optional(),
|
||||
}),
|
||||
},
|
||||
async () => {
|
||||
clearConfig();
|
||||
@@ -189,10 +137,6 @@ export function registerAuthTools(server: McpServer): void {
|
||||
message: "Logged out. Credentials cleared.",
|
||||
}),
|
||||
}],
|
||||
structuredContent: {
|
||||
success: true,
|
||||
message: "Logged out. Credentials cleared.",
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
+11
-52
@@ -1,38 +1,25 @@
|
||||
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod/v4";
|
||||
import { loadConfig } from "../utils/login.ts";
|
||||
import { EwsClient } from "../client/ews_client.ts";
|
||||
import { EwsClient, loadConfig } from "../ews_client.ts";
|
||||
|
||||
export function registerAvailabilityTools(server: McpServer): void {
|
||||
server.registerTool(
|
||||
"find_free_time",
|
||||
{
|
||||
description: "Find free time slots in your own calendar."
|
||||
+ " Queries your free/busy status and returns available slots"
|
||||
+ " within working hours that meet the minimum duration.",
|
||||
description: "Find free time slots in your own calendar",
|
||||
inputSchema: z.object({
|
||||
startDate: z.string().describe("Start date in YYYY-MM-DD format"),
|
||||
endDate: z.string().optional().describe(
|
||||
"End date in YYYY-MM-DD format",
|
||||
"End date in YYYY-MM-DD format (defaults to startDate)",
|
||||
),
|
||||
durationMinutes: z.number().default(30).describe(
|
||||
"Minimum slot duration in minutes",
|
||||
"Minimum slot duration in minutes (default 30)",
|
||||
),
|
||||
startHour: z.number().default(9).describe(
|
||||
"Working day start hour (0-23)",
|
||||
"Working day start hour (0-23, default 9)",
|
||||
),
|
||||
endHour: z.number().default(18).describe(
|
||||
"Working day end hour (0-23)",
|
||||
),
|
||||
}),
|
||||
outputSchema: z.object({
|
||||
freeSlots: z.record(
|
||||
z.string(),
|
||||
z.array(z.object({
|
||||
start: z.string(),
|
||||
end: z.string(),
|
||||
durationMinutes: z.number(),
|
||||
})),
|
||||
"Working day end hour (0-23, default 18)",
|
||||
),
|
||||
}),
|
||||
},
|
||||
@@ -92,7 +79,6 @@ export function registerAvailabilityTools(server: McpServer): void {
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({ freeSlots }),
|
||||
}],
|
||||
structuredContent: { freeSlots },
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
@@ -108,45 +94,23 @@ export function registerAvailabilityTools(server: McpServer): void {
|
||||
server.registerTool(
|
||||
"find_meeting_time",
|
||||
{
|
||||
description: "Find common free time for multiple attendees."
|
||||
+ " Queries free/busy for all attendees"
|
||||
+ " and returns slots where everyone is available.",
|
||||
description: "Find meeting times that work for multiple people",
|
||||
inputSchema: z.object({
|
||||
emails: z.string().describe(
|
||||
"Comma-separated email addresses of attendees",
|
||||
),
|
||||
startDate: z.string().describe("Start date in YYYY-MM-DD format"),
|
||||
endDate: z.string().optional().describe(
|
||||
"End date in YYYY-MM-DD format",
|
||||
"End date in YYYY-MM-DD format (defaults to startDate)",
|
||||
),
|
||||
durationMinutes: z.number().default(30).describe(
|
||||
"Minimum slot duration in minutes",
|
||||
"Minimum slot duration in minutes (default 30)",
|
||||
),
|
||||
startHour: z.number().default(9).describe(
|
||||
"Working day start hour (0-23)",
|
||||
"Working day start hour (0-23, default 9)",
|
||||
),
|
||||
endHour: z.number().default(18).describe(
|
||||
"Working day end hour (0-23)",
|
||||
),
|
||||
}),
|
||||
outputSchema: z.object({
|
||||
period: z.object({
|
||||
start: z.string(),
|
||||
end: z.string(),
|
||||
}),
|
||||
attendees: z.array(z.object({
|
||||
email: z.string(),
|
||||
busySlots: z.number().optional(),
|
||||
freeSlots: z.number().optional(),
|
||||
calendarEvents: z.number().optional(),
|
||||
})),
|
||||
freeSlots: z.record(
|
||||
z.string(),
|
||||
z.array(z.object({
|
||||
start: z.string(),
|
||||
end: z.string(),
|
||||
durationMinutes: z.number(),
|
||||
})),
|
||||
"Working day end hour (0-23, default 18)",
|
||||
),
|
||||
}),
|
||||
},
|
||||
@@ -228,11 +192,6 @@ export function registerAvailabilityTools(server: McpServer): void {
|
||||
freeSlots: freeByDate,
|
||||
}),
|
||||
}],
|
||||
structuredContent: {
|
||||
period: { start: startDate, end: ed },
|
||||
attendees: attendeeInfo,
|
||||
freeSlots: freeByDate,
|
||||
},
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
|
||||
+7
-57
@@ -2,43 +2,20 @@ import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { z } from "zod/v4";
|
||||
import { loadConfig } from "../utils/login.ts";
|
||||
import { EwsClient } from "../client/ews_client.ts";
|
||||
import { EwsClient, loadConfig } from "../ews_client.ts";
|
||||
|
||||
export function registerCalendarTools(server: McpServer): void {
|
||||
server.registerTool(
|
||||
"get_calendar_events",
|
||||
{
|
||||
description: "Get calendar events within a date range."
|
||||
+ " Set includeBody=true to fetch organizer, attendees, and body via GetItem.",
|
||||
description: "Get calendar events within a date range",
|
||||
inputSchema: z.object({
|
||||
startDate: z.string().describe("Start date in YYYY-MM-DD format"),
|
||||
endDate: z.string().describe("End date in YYYY-MM-DD format"),
|
||||
includeBody: z.boolean().default(false).describe(
|
||||
"If true, fetch full event details (organizer, attendees, body)"
|
||||
+ " via GetItem",
|
||||
"If True, fetch full event details (organizer, attendees, body) via GetItem",
|
||||
),
|
||||
}),
|
||||
outputSchema: z.object({
|
||||
events: z.array(z.object({
|
||||
subject: z.string(),
|
||||
start: z.string(),
|
||||
end: z.string(),
|
||||
location: z.string(),
|
||||
isAllDay: z.boolean(),
|
||||
isCancelled: z.boolean(),
|
||||
isMeeting: z.boolean(),
|
||||
isRecurring: z.boolean(),
|
||||
organizer: z.string(),
|
||||
organizerEmail: z.string(),
|
||||
myResponse: z.string(),
|
||||
itemId: z.string(),
|
||||
body: z.string(),
|
||||
requiredAttendees: z.array(z.string()),
|
||||
optionalAttendees: z.array(z.string()),
|
||||
})),
|
||||
count: z.number(),
|
||||
}),
|
||||
},
|
||||
async ({ startDate, endDate, includeBody }) => {
|
||||
try {
|
||||
@@ -74,7 +51,7 @@ export function registerCalendarTools(server: McpServer): void {
|
||||
};
|
||||
|
||||
if (includeBody && event.itemId) {
|
||||
const details = client.extractEmail(item);
|
||||
const details = client.extractEmailDetails(item);
|
||||
event.body = details.body;
|
||||
event.requiredAttendees = details.requiredAttendees ?? [];
|
||||
event.optionalAttendees = details.optionalAttendees ?? [];
|
||||
@@ -91,7 +68,6 @@ export function registerCalendarTools(server: McpServer): void {
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({ events, count: events.length }),
|
||||
}],
|
||||
structuredContent: { events, count: events.length },
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
@@ -108,38 +84,21 @@ export function registerCalendarTools(server: McpServer): void {
|
||||
"download_event_attachments",
|
||||
{
|
||||
description:
|
||||
"Download all file attachments from a calendar event to disk."
|
||||
+ " Inline (embedded) attachments are skipped —"
|
||||
+ " only standalone file attachments are downloaded.",
|
||||
"Download all file attachments from a calendar event to disk",
|
||||
inputSchema: z.object({
|
||||
itemId: z.string().describe(
|
||||
"The Exchange ItemId of the calendar event",
|
||||
),
|
||||
targetFolder: z.string().default("/tmp/attachments").describe(
|
||||
"Local directory to save files",
|
||||
"Local directory to save files (default /tmp/attachments)",
|
||||
),
|
||||
}),
|
||||
outputSchema: z.object({
|
||||
success: z.boolean(),
|
||||
downloaded: z.array(z.object({
|
||||
name: z.string(),
|
||||
path: z.string(),
|
||||
size: z.number(),
|
||||
contentType: z.string(),
|
||||
})),
|
||||
count: z.number(),
|
||||
errors: z.array(z.object({
|
||||
name: z.string(),
|
||||
error: z.string(),
|
||||
})).optional(),
|
||||
message: z.string().optional(),
|
||||
}),
|
||||
},
|
||||
async ({ itemId, targetFolder }) => {
|
||||
try {
|
||||
const client = new EwsClient(loadConfig());
|
||||
const item = await client.getItem(itemId);
|
||||
const email = client.extractEmail(item);
|
||||
const email = client.extractEmailDetails(item);
|
||||
const attachments = email.attachments ?? [];
|
||||
|
||||
const fileAttachments = attachments.filter(
|
||||
@@ -157,12 +116,6 @@ export function registerCalendarTools(server: McpServer): void {
|
||||
message: "No downloadable file attachments.",
|
||||
}),
|
||||
}],
|
||||
structuredContent: {
|
||||
success: true,
|
||||
downloaded: [],
|
||||
count: 0,
|
||||
message: "No downloadable file attachments.",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -220,9 +173,6 @@ export function registerCalendarTools(server: McpServer): void {
|
||||
...(errors.length ? { errors } : {}),
|
||||
}),
|
||||
}],
|
||||
structuredContent: errors.length === 0
|
||||
? { success: true, downloaded, count: downloaded.length }
|
||||
: { success: false, downloaded, count: downloaded.length, errors },
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
|
||||
+224
-166
@@ -2,8 +2,7 @@ import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { z } from "zod/v4";
|
||||
import { loadConfig } from "../utils/login.ts";
|
||||
import { EwsClient } from "../client/ews_client.ts";
|
||||
import { EwsClient, loadConfig } from "../ews_client.ts";
|
||||
|
||||
function getClient(): EwsClient {
|
||||
return new EwsClient(loadConfig());
|
||||
@@ -13,122 +12,48 @@ export function registerEmailTools(server: McpServer): void {
|
||||
server.registerTool(
|
||||
"get_emails",
|
||||
{
|
||||
description: "Get emails from a mailbox folder."
|
||||
+ " Supports optional text search via query/queryScope.",
|
||||
description: "Get emails from a mailbox folder",
|
||||
inputSchema: z.object({
|
||||
folder: z.string().default("Inbox").describe(
|
||||
"Folder name (Inbox, Sent, Drafts, Deleted, Junk, or custom)."
|
||||
+ " Supports Russian folder names",
|
||||
"Folder name (Inbox, Sent, Drafts, Deleted, Junk, or custom)",
|
||||
),
|
||||
limit: z.number().default(10).describe(
|
||||
"Maximum number of emails to return",
|
||||
"Maximum number of emails to return (default 10, max 50)",
|
||||
),
|
||||
offset: z.number().default(0).describe(
|
||||
"Number of emails to skip for pagination",
|
||||
),
|
||||
includeBody: z.boolean().default(false).describe(
|
||||
"If true, fetches full email body for each email (slower)",
|
||||
"If True, fetch full body for each email (slower)",
|
||||
),
|
||||
unreadOnly: z.boolean().default(false).describe(
|
||||
"If true, only return unread emails",
|
||||
"If True, only return unread emails",
|
||||
),
|
||||
query: z.string().optional().describe(
|
||||
"Optional text to search for within the folder",
|
||||
idsOnly: z.boolean().default(false).describe(
|
||||
"If True, return only item IDs and dates (max limit 500)",
|
||||
),
|
||||
queryScope: z.enum(["all", "subject", "body", "from"]).default("all")
|
||||
.describe("Search scope: all, subject, body, or from"),
|
||||
}),
|
||||
outputSchema: z.object({
|
||||
emails: z.array(z.object({
|
||||
itemId: z.string(),
|
||||
subject: z.string(),
|
||||
from: z.string(),
|
||||
date: z.string(),
|
||||
isRead: z.boolean(),
|
||||
hasAttachments: z.boolean(),
|
||||
})),
|
||||
count: z.number(),
|
||||
}),
|
||||
},
|
||||
async (
|
||||
{
|
||||
folder,
|
||||
limit,
|
||||
offset,
|
||||
includeBody,
|
||||
unreadOnly,
|
||||
query,
|
||||
queryScope,
|
||||
},
|
||||
) => {
|
||||
async ({ folder, limit, offset, includeBody, unreadOnly, idsOnly }) => {
|
||||
try {
|
||||
const client = getClient();
|
||||
const maxLimit = 50;
|
||||
const maxLimit = idsOnly ? 500 : 50;
|
||||
if (limit > maxLimit) limit = maxLimit;
|
||||
offset = Math.max(0, offset);
|
||||
|
||||
const folderId = await client.getFolderId(folder);
|
||||
const baseShape = "AllProperties";
|
||||
|
||||
if (query && !query.trim()) query = undefined;
|
||||
|
||||
const restrictions: string[] = [];
|
||||
const baseShape = idsOnly ? "IdOnly" : "AllProperties";
|
||||
|
||||
let restriction = "";
|
||||
if (unreadOnly) {
|
||||
restrictions.push(`\
|
||||
restriction = `\
|
||||
<m:Restriction>
|
||||
<t:IsEqualTo>
|
||||
<t:FieldURI FieldURI="message:IsRead"/>
|
||||
<t:FieldURIOrConstant>
|
||||
<t:Constant Value="false"/>
|
||||
</t:FieldURIOrConstant>
|
||||
</t:IsEqualTo>`);
|
||||
}
|
||||
|
||||
if (query) {
|
||||
function containsExpression(fieldUri: string, value: string): string {
|
||||
return `\
|
||||
<t:Contains ContainmentMode="Substring" ContainmentComparison="IgnoreCase">
|
||||
<t:FieldURI FieldURI="${fieldUri}"/>
|
||||
<t:Constant Value="${
|
||||
value.replace(/&/g, "&").replace(/</g, "<").replace(
|
||||
/>/g,
|
||||
">",
|
||||
).replace(/"/g, """)
|
||||
}"/>
|
||||
</t:Contains>`;
|
||||
}
|
||||
|
||||
const fieldUriMap: Record<string, string> = {
|
||||
subject: "item:Subject",
|
||||
body: "item:Body",
|
||||
from: "message:From",
|
||||
};
|
||||
|
||||
if (queryScope === "all") {
|
||||
restrictions.push(`\
|
||||
<t:Or>
|
||||
${containsExpression("item:Subject", query)}
|
||||
${containsExpression("item:Body", query)}
|
||||
</t:Or>`);
|
||||
} else {
|
||||
const fieldUri = fieldUriMap[queryScope];
|
||||
restrictions.push(containsExpression(fieldUri, query));
|
||||
}
|
||||
}
|
||||
|
||||
let restriction = "";
|
||||
if (restrictions.length === 1) {
|
||||
restriction = `\
|
||||
<m:Restriction>
|
||||
${restrictions[0]}
|
||||
</m:Restriction>`;
|
||||
} else if (restrictions.length > 1) {
|
||||
restriction = `\
|
||||
<m:Restriction>
|
||||
<t:And>
|
||||
${restrictions.join("\n")}
|
||||
</t:And>
|
||||
</m:Restriction>`;
|
||||
</t:IsEqualTo>
|
||||
</m:Restriction>`;
|
||||
}
|
||||
|
||||
const items = await client.findItems(folderId, {
|
||||
@@ -138,9 +63,33 @@ export function registerEmailTools(server: McpServer): void {
|
||||
restriction,
|
||||
});
|
||||
|
||||
if (idsOnly) {
|
||||
const result = items.map((item: any) => ({
|
||||
itemId: item.ItemId?.["@_Id"] ?? "",
|
||||
date: item.DateTimeReceived ?? "",
|
||||
subject: item.Subject ?? "",
|
||||
}));
|
||||
return {
|
||||
content: [{
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({ itemIds: result, count: result.length }),
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
const emails = [];
|
||||
for (const item of items) {
|
||||
emails.push(client.extractEmail(item));
|
||||
const email = client.extractEmailSummary(item);
|
||||
|
||||
if (includeBody && email.itemId) {
|
||||
const details = client.extractEmailDetails(item);
|
||||
email.to = details.to;
|
||||
email.cc = details.cc;
|
||||
email.body = details.body;
|
||||
email.hasLinks = details.hasLinks;
|
||||
}
|
||||
|
||||
emails.push(email);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -148,7 +97,6 @@ export function registerEmailTools(server: McpServer): void {
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({ emails, count: emails.length }),
|
||||
}],
|
||||
structuredContent: { emails, count: emails.length },
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
@@ -164,43 +112,21 @@ export function registerEmailTools(server: McpServer): void {
|
||||
server.registerTool(
|
||||
"get_email",
|
||||
{
|
||||
description:
|
||||
"Get a single email with full body and details by Exchange ItemId.",
|
||||
description: "Get a single email with full body and details",
|
||||
inputSchema: z.object({
|
||||
itemId: z.string().describe(
|
||||
"The Exchange ItemId of the email to retrieve",
|
||||
),
|
||||
}),
|
||||
outputSchema: z.object({
|
||||
itemId: z.string(),
|
||||
subject: z.string(),
|
||||
from: z.string(),
|
||||
fromName: z.string().optional(),
|
||||
to: z.array(z.string()).optional(),
|
||||
cc: z.array(z.string()).optional(),
|
||||
date: z.string(),
|
||||
body: z.string().optional(),
|
||||
isRead: z.boolean().optional(),
|
||||
hasAttachments: z.boolean().optional(),
|
||||
hasLinks: z.boolean().optional(),
|
||||
attachments: z.array(z.object({
|
||||
name: z.string(),
|
||||
size: z.number(),
|
||||
contentType: z.string(),
|
||||
attachmentId: z.string().optional(),
|
||||
isInline: z.boolean().optional(),
|
||||
})).optional(),
|
||||
}),
|
||||
},
|
||||
async ({ itemId }) => {
|
||||
try {
|
||||
const client = getClient();
|
||||
const item = await client.getItem(itemId);
|
||||
const email = client.extractEmail(item);
|
||||
const email = client.extractEmailDetails(item);
|
||||
|
||||
return {
|
||||
content: [{ type: "text" as const, text: JSON.stringify(email) }],
|
||||
structuredContent: { emails: [email] },
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
@@ -213,24 +139,167 @@ export function registerEmailTools(server: McpServer): void {
|
||||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"search_emails",
|
||||
{
|
||||
description: "Search emails by text across one or all folders",
|
||||
inputSchema: z.object({
|
||||
query: z.string().describe("The text to search for"),
|
||||
folderId: z.string().optional().describe(
|
||||
"Optional folder ID to limit the search. When omitted, searches all mail folders",
|
||||
),
|
||||
maxResults: z.number().default(20).describe(
|
||||
"Maximum number of results (default 20, max 100)",
|
||||
),
|
||||
searchScope: z.enum(["all", "subject", "body", "from"]).default("all")
|
||||
.describe("Where to search"),
|
||||
}),
|
||||
},
|
||||
async ({ query, folderId, maxResults, searchScope }) => {
|
||||
try {
|
||||
const client = getClient();
|
||||
|
||||
if (!query.trim()) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({
|
||||
error: "query must not be empty",
|
||||
results: [],
|
||||
}),
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
maxResults = Math.max(1, Math.min(maxResults, 100));
|
||||
|
||||
const fieldUriMap: Record<string, string> = {
|
||||
subject: "item:Subject",
|
||||
body: "item:Body",
|
||||
from: "message:From",
|
||||
};
|
||||
|
||||
function containsExpression(fieldUri: string, value: string): string {
|
||||
return `\
|
||||
<t:Contains ContainmentMode="Substring" ContainmentComparison="IgnoreCase">
|
||||
<t:FieldURI FieldURI="${fieldUri}"/>
|
||||
<t:Constant Value="${
|
||||
value.replace(/&/g, "&").replace(/</g, "<").replace(
|
||||
/>/g,
|
||||
">",
|
||||
).replace(/"/g, """)
|
||||
}"/>
|
||||
</t:Contains>`;
|
||||
}
|
||||
|
||||
let restriction: string;
|
||||
if (searchScope === "all") {
|
||||
restriction = `\
|
||||
<m:Restriction>
|
||||
<t:Or>
|
||||
${containsExpression("item:Subject", query)}
|
||||
${containsExpression("item:Body", query)}
|
||||
</t:Or>
|
||||
</m:Restriction>`;
|
||||
} else {
|
||||
const fieldUri = fieldUriMap[searchScope];
|
||||
if (!fieldUri) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({
|
||||
error: `unsupported search_scope: ${searchScope}`,
|
||||
results: [],
|
||||
}),
|
||||
}],
|
||||
};
|
||||
}
|
||||
restriction = `\
|
||||
<m:Restriction>
|
||||
${containsExpression(fieldUri, query)}
|
||||
</m:Restriction>`;
|
||||
}
|
||||
|
||||
const traversal = folderId ? "Shallow" : "Deep";
|
||||
|
||||
if (folderId) {
|
||||
const items = await client.findItems(folderId, {
|
||||
limit: maxResults,
|
||||
restriction,
|
||||
traversal,
|
||||
});
|
||||
const results = formatSearchResults(items, client, maxResults);
|
||||
|
||||
return {
|
||||
content: [{
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({
|
||||
query,
|
||||
searchScope,
|
||||
folderId,
|
||||
totalResults: results.length,
|
||||
results,
|
||||
}),
|
||||
}],
|
||||
};
|
||||
} else {
|
||||
const folders = await client.findFolders("msgfolderroot", true);
|
||||
const allResults = [];
|
||||
|
||||
for (const f of folders) {
|
||||
if (allResults.length >= maxResults) break;
|
||||
const remaining = maxResults - allResults.length;
|
||||
const items = await client.findItems(f.id, {
|
||||
limit: remaining,
|
||||
restriction,
|
||||
traversal: "Shallow",
|
||||
});
|
||||
const formatted = formatSearchResults(items, client, remaining);
|
||||
|
||||
for (const r of formatted) {
|
||||
r.folderId = f.id;
|
||||
r.folderName = f.name;
|
||||
allResults.push(r);
|
||||
if (allResults.length >= maxResults) break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({
|
||||
query,
|
||||
searchScope,
|
||||
folderId: "all",
|
||||
totalResults: allResults.length,
|
||||
results: allResults,
|
||||
}),
|
||||
}],
|
||||
};
|
||||
}
|
||||
} catch (error: any) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({ error: error.message ?? String(error) }),
|
||||
}],
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"mark_email_read",
|
||||
{
|
||||
description:
|
||||
"Mark one or more emails as read or unread by their Exchange ItemIds.",
|
||||
description: "Mark one or more emails as read or unread",
|
||||
inputSchema: z.object({
|
||||
itemIds: z.array(z.string()).describe(
|
||||
"List of Exchange ItemIds to update",
|
||||
),
|
||||
isRead: z.boolean().default(true).describe(
|
||||
"True to mark as read, false to mark as unread",
|
||||
"True to mark as read, False to mark as unread",
|
||||
),
|
||||
}),
|
||||
outputSchema: z.object({
|
||||
success: z.boolean(),
|
||||
message: z.string().optional(),
|
||||
error: z.string().optional(),
|
||||
}),
|
||||
},
|
||||
async ({ itemIds, isRead }) => {
|
||||
try {
|
||||
@@ -249,10 +318,6 @@ export function registerEmailTools(server: McpServer): void {
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({ error: errors.join("; ") }),
|
||||
}],
|
||||
structuredContent: {
|
||||
success: false,
|
||||
error: errors.join("; "),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -265,10 +330,6 @@ export function registerEmailTools(server: McpServer): void {
|
||||
message: `Marked ${itemIds.length} email(s) as ${status}.`,
|
||||
}),
|
||||
}],
|
||||
structuredContent: {
|
||||
success: true,
|
||||
message: `Marked ${itemIds.length} email(s) as ${status}.`,
|
||||
},
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
@@ -276,10 +337,6 @@ export function registerEmailTools(server: McpServer): void {
|
||||
type: "text" as const,
|
||||
text: JSON.stringify({ error: error.message ?? String(error) }),
|
||||
}],
|
||||
structuredContent: {
|
||||
success: false,
|
||||
error: error.message ?? String(error),
|
||||
},
|
||||
};
|
||||
}
|
||||
},
|
||||
@@ -288,36 +345,19 @@ export function registerEmailTools(server: McpServer): void {
|
||||
server.registerTool(
|
||||
"download_attachments",
|
||||
{
|
||||
description: "Download all file attachments from an email to disk."
|
||||
+ " Inline (embedded) attachments are skipped —"
|
||||
+ " only standalone file attachments are downloaded.",
|
||||
description: "Download all file attachments from an email to disk",
|
||||
inputSchema: z.object({
|
||||
itemId: z.string().describe("The Exchange ItemId of the email"),
|
||||
targetFolder: z.string().default("/tmp/attachments").describe(
|
||||
"Local directory to save files",
|
||||
"Local directory to save files (default /tmp/attachments)",
|
||||
),
|
||||
}),
|
||||
outputSchema: z.object({
|
||||
success: z.boolean(),
|
||||
downloaded: z.array(z.object({
|
||||
name: z.string(),
|
||||
path: z.string(),
|
||||
size: z.number(),
|
||||
contentType: z.string(),
|
||||
})),
|
||||
count: z.number(),
|
||||
errors: z.array(z.object({
|
||||
name: z.string(),
|
||||
error: z.string(),
|
||||
})).optional(),
|
||||
message: z.string().optional(),
|
||||
}),
|
||||
},
|
||||
async ({ itemId, targetFolder }) => {
|
||||
try {
|
||||
const client = new EwsClient(loadConfig());
|
||||
const item = await client.getItem(itemId);
|
||||
const email = client.extractEmail(item);
|
||||
const email = client.extractEmailDetails(item);
|
||||
const attachments = email.attachments ?? [];
|
||||
|
||||
const fileAttachments = attachments.filter(
|
||||
@@ -335,12 +375,6 @@ export function registerEmailTools(server: McpServer): void {
|
||||
message: "No downloadable file attachments.",
|
||||
}),
|
||||
}],
|
||||
structuredContent: {
|
||||
success: true,
|
||||
downloaded: [],
|
||||
count: 0,
|
||||
message: "No downloadable file attachments.",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -398,9 +432,6 @@ export function registerEmailTools(server: McpServer): void {
|
||||
...(errors.length ? { errors } : {}),
|
||||
}),
|
||||
}],
|
||||
structuredContent: errors.length === 0
|
||||
? { success: true, downloaded, count: downloaded.length }
|
||||
: { success: false, downloaded, count: downloaded.length, errors },
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
@@ -413,3 +444,30 @@ export function registerEmailTools(server: McpServer): void {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function formatSearchResults(
|
||||
items: any[],
|
||||
client: EwsClient,
|
||||
maxResults: number,
|
||||
): any[] {
|
||||
const results: any[] = [];
|
||||
for (const item of items) {
|
||||
if (results.length >= maxResults) break;
|
||||
const summary = client.extractEmailSummary(item);
|
||||
|
||||
const bodyHtml = item.Body?.Value ?? item.Body?.["#text"] ?? "";
|
||||
const bodyType = item.Body?.["@_BodyType"] ?? "HTML";
|
||||
let bodyPreview = "";
|
||||
if (bodyType === "HTML" && bodyHtml) {
|
||||
bodyPreview = bodyHtml.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ")
|
||||
.trim().slice(0, 200);
|
||||
} else {
|
||||
bodyPreview = bodyHtml.slice(0, 200);
|
||||
}
|
||||
|
||||
summary.preview = bodyPreview;
|
||||
|
||||
results.push(summary);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
+4
-16
@@ -1,31 +1,20 @@
|
||||
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod/v4";
|
||||
import { loadConfig } from "../utils/login.ts";
|
||||
import { EwsClient } from "../client/ews_client.ts";
|
||||
import { EwsClient, loadConfig } from "../ews_client.ts";
|
||||
|
||||
export function registerFolderTools(server: McpServer): void {
|
||||
server.registerTool(
|
||||
"get_folders",
|
||||
{
|
||||
description: "List mailbox folders from the Exchange mailbox.",
|
||||
description: "List mail folders from the Exchange mailbox",
|
||||
inputSchema: z.object({
|
||||
parentFolderId: z.string().default("msgfolderroot").describe(
|
||||
"Parent folder to list children of."
|
||||
+ " Supports distinguished names (e.g. inbox, calendar)",
|
||||
"Parent folder to list children of (default: msgfolderroot)",
|
||||
),
|
||||
recursive: z.boolean().default(false).describe(
|
||||
"If true, recursively traverse all subfolders",
|
||||
"If True, traverse all subfolders recursively",
|
||||
),
|
||||
}),
|
||||
outputSchema: z.object({
|
||||
folders: z.array(z.object({
|
||||
name: z.string(),
|
||||
id: z.string(),
|
||||
totalCount: z.number(),
|
||||
unreadCount: z.number(),
|
||||
childFolderCount: z.number(),
|
||||
})),
|
||||
}),
|
||||
},
|
||||
async ({ parentFolderId, recursive }) => {
|
||||
try {
|
||||
@@ -34,7 +23,6 @@ export function registerFolderTools(server: McpServer): void {
|
||||
|
||||
return {
|
||||
content: [{ type: "text" as const, text: JSON.stringify(folders) }],
|
||||
structuredContent: { folders },
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
|
||||
+3
-27
@@ -1,45 +1,22 @@
|
||||
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod/v4";
|
||||
import { loadConfig } from "../utils/login.ts";
|
||||
import { EwsClient } from "../client/ews_client.ts";
|
||||
import { EwsClient, loadConfig } from "../ews_client.ts";
|
||||
|
||||
export function registerPeopleTools(server: McpServer): void {
|
||||
server.registerTool(
|
||||
"find_person",
|
||||
{
|
||||
description:
|
||||
"Search for people in the corporate directory (Active Directory)"
|
||||
+ " by name, email, or keyword.",
|
||||
description: "Search for people in the corporate directory",
|
||||
inputSchema: z.object({
|
||||
query: z.string().describe(
|
||||
"Name, email address, or keyword to search for",
|
||||
),
|
||||
}),
|
||||
outputSchema: z.object({
|
||||
name: z.string(),
|
||||
email: z.string(),
|
||||
mailboxType: z.string(),
|
||||
firstName: z.string(),
|
||||
lastName: z.string(),
|
||||
jobTitle: z.string(),
|
||||
department: z.string(),
|
||||
company: z.string(),
|
||||
office: z.string(),
|
||||
alias: z.string(),
|
||||
manager: z.string(),
|
||||
managerEmail: z.string(),
|
||||
phones: z.record(z.string(), z.string()),
|
||||
address: z.string(),
|
||||
directReports: z.array(z.object({
|
||||
name: z.string(),
|
||||
email: z.string(),
|
||||
})),
|
||||
}),
|
||||
},
|
||||
async ({ query }) => {
|
||||
try {
|
||||
const client = new EwsClient(loadConfig());
|
||||
const resolutions = await client.resolveNames(query);
|
||||
const resolutions = await client.resolveNames(query, true);
|
||||
|
||||
const people = resolutions.map((r: any) => {
|
||||
const mailbox = r.Mailbox ?? {};
|
||||
@@ -107,7 +84,6 @@ export function registerPeopleTools(server: McpServer): void {
|
||||
|
||||
return {
|
||||
content: [{ type: "text" as const, text: JSON.stringify(people) }],
|
||||
structuredContent: { people },
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
export interface CalendarEvent {
|
||||
subject: string;
|
||||
start: string;
|
||||
end: string;
|
||||
location: string;
|
||||
isAllDay: boolean;
|
||||
isCancelled: boolean;
|
||||
isMeeting: boolean;
|
||||
isRecurring: boolean;
|
||||
organizer: string;
|
||||
organizerEmail: string;
|
||||
myResponse: string;
|
||||
itemId: string;
|
||||
body: string;
|
||||
requiredAttendees: string[];
|
||||
optionalAttendees: string[];
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
export interface Email {
|
||||
subject: string;
|
||||
from: string;
|
||||
fromName: string;
|
||||
date: string;
|
||||
isRead: boolean;
|
||||
hasAttachments: boolean;
|
||||
hasLinks: boolean;
|
||||
itemId: string;
|
||||
size: number;
|
||||
isMeeting: boolean;
|
||||
itemType: string;
|
||||
to: string[];
|
||||
cc: string[];
|
||||
body: string;
|
||||
bodyType: string;
|
||||
attachments: Attachment[];
|
||||
preview: string;
|
||||
location?: string;
|
||||
start?: string;
|
||||
end?: string;
|
||||
requiredAttendees?: string[];
|
||||
optionalAttendees?: string[];
|
||||
}
|
||||
|
||||
export interface Attachment {
|
||||
name: string;
|
||||
size: number;
|
||||
contentType: string;
|
||||
attachmentId: string;
|
||||
isInline: boolean;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export interface Folder {
|
||||
name: string;
|
||||
id: string;
|
||||
totalCount: number;
|
||||
unreadCount: number;
|
||||
childFolderCount: number;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export interface FreeSlot {
|
||||
date: string;
|
||||
start: string;
|
||||
end: string;
|
||||
durationMinutes: number;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export interface LoginConfig {
|
||||
serverUrl: string;
|
||||
email: string;
|
||||
username: string;
|
||||
domain?: string;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export interface MeetingResult {
|
||||
success: boolean;
|
||||
subject: string;
|
||||
date: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
location: string;
|
||||
requiredAttendees: string[];
|
||||
optionalAttendees: string[];
|
||||
error: string;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export interface Person {
|
||||
name: string;
|
||||
email: string;
|
||||
mailboxType: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
jobTitle: string;
|
||||
department: string;
|
||||
company: string;
|
||||
office: string;
|
||||
alias: string;
|
||||
manager: string;
|
||||
managerEmail: string;
|
||||
phones: Record<string, string>;
|
||||
address: string;
|
||||
directReports: Array<{ name: string; email: string }>;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
let dataDir: string = "./data";
|
||||
|
||||
export function initDataDir(dir: string): void {
|
||||
dataDir = path.resolve(dir);
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
}
|
||||
|
||||
export function configFilePath(): string {
|
||||
return path.join(dataDir, "config.json");
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
import { htmlToText } from "./html_to_text.ts";
|
||||
|
||||
export interface Attachment {
|
||||
name: string;
|
||||
size: number;
|
||||
contentType: string;
|
||||
attachmentId: string;
|
||||
isInline: boolean;
|
||||
}
|
||||
|
||||
export interface Email {
|
||||
subject: string;
|
||||
from: string;
|
||||
fromName: string;
|
||||
date: string;
|
||||
isRead: boolean;
|
||||
hasAttachments: boolean;
|
||||
hasLinks: boolean;
|
||||
itemId: string;
|
||||
size: number;
|
||||
isMeeting: boolean;
|
||||
itemType: string;
|
||||
to: string[];
|
||||
cc: string[];
|
||||
body: string;
|
||||
bodyType: string;
|
||||
attachments: Attachment[];
|
||||
preview: string;
|
||||
location?: string;
|
||||
start?: string;
|
||||
end?: string;
|
||||
requiredAttendees?: string[];
|
||||
optionalAttendees?: string[];
|
||||
}
|
||||
|
||||
export function extractEmail(item: any): Email {
|
||||
const itemType = item["@_xsi_type"] ?? item.__type ?? "";
|
||||
const isMeeting =
|
||||
/MeetingRequest|MeetingResponse|MeetingCancellation|CalendarItem/i.test(
|
||||
itemType,
|
||||
);
|
||||
|
||||
const fromMailbox = item.From?.Mailbox
|
||||
?? item.Organizer?.Mailbox
|
||||
?? item.Sender?.Mailbox
|
||||
?? {};
|
||||
|
||||
const email: Email = {
|
||||
subject: item.Subject ?? "(No subject)",
|
||||
from: fromMailbox.EmailAddress ?? "",
|
||||
fromName: fromMailbox.Name ?? "",
|
||||
date: item.DateTimeSent ?? item.DateTimeReceived ?? item.DateTimeCreated
|
||||
?? "",
|
||||
isRead: item.IsRead === "true" || item.IsRead === true,
|
||||
hasAttachments: item.HasAttachments === "true"
|
||||
|| item.HasAttachments === true,
|
||||
hasLinks: false,
|
||||
itemId: item.ItemId?.["@_Id"] ?? "",
|
||||
size: item.Size ? Number(item.Size) : 0,
|
||||
isMeeting,
|
||||
itemType: itemType || "Message",
|
||||
to: [],
|
||||
cc: [],
|
||||
body: "",
|
||||
bodyType: "Text",
|
||||
attachments: [],
|
||||
preview: item.Preview ?? "",
|
||||
};
|
||||
|
||||
if (item.DisplayTo) {
|
||||
email.to = item.DisplayTo.split(";").map((t: string) => t.trim()).filter(
|
||||
Boolean,
|
||||
);
|
||||
}
|
||||
if (item.DisplayCc) {
|
||||
email.cc = item.DisplayCc.split(";").map((c: string) => c.trim()).filter(
|
||||
Boolean,
|
||||
);
|
||||
}
|
||||
|
||||
if (isMeeting) {
|
||||
email.location = item.Location ?? "";
|
||||
email.start = item.Start ?? item.StartWallClock ?? item.ReminderDueBy
|
||||
?? "";
|
||||
email.end = item.End ?? item.EndWallClock ?? "";
|
||||
}
|
||||
|
||||
const bodyVal = item.Body?.Value ?? item.Body?.["#text"] ?? "";
|
||||
const bodyType = item.Body?.["@_BodyType"] ?? item.Body?.BodyType ?? "Text";
|
||||
|
||||
if (bodyType === "HTML") {
|
||||
email.hasLinks = /<a\s/i.test(bodyVal);
|
||||
email.body = htmlToText(bodyVal);
|
||||
} else {
|
||||
email.body = bodyVal;
|
||||
}
|
||||
email.bodyType = bodyType;
|
||||
|
||||
const toRecipients = item.ToRecipients?.Mailbox ?? [];
|
||||
email.to = (Array.isArray(toRecipients) ? toRecipients : [toRecipients])
|
||||
.map((r: any) => {
|
||||
const name = r.Name ?? "";
|
||||
const addr = r.EmailAddress ?? "";
|
||||
return name && addr ? `${name} <${addr}>` : addr;
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
const ccRecipients = item.CcRecipients?.Mailbox ?? [];
|
||||
email.cc = (Array.isArray(ccRecipients) ? ccRecipients : [ccRecipients])
|
||||
.map((r: any) => {
|
||||
const name = r.Name ?? "";
|
||||
const addr = r.EmailAddress ?? "";
|
||||
return name && addr ? `${name} <${addr}>` : addr;
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
const attachments = item.Attachments?.FileAttachment ?? [];
|
||||
const attList = Array.isArray(attachments) ? attachments : [attachments];
|
||||
email.attachments = attList
|
||||
.filter((a: any) => a)
|
||||
.map((a: any) => ({
|
||||
name: a.Name ?? "",
|
||||
size: a.Size ? Number(a.Size) : 0,
|
||||
contentType: a.ContentType ?? "",
|
||||
attachmentId: a.AttachmentId?.["@_Id"] ?? "",
|
||||
isInline: a.IsInline === "true" || a.IsInline === true,
|
||||
}));
|
||||
|
||||
if (isMeeting) {
|
||||
email.location = item.Location ?? item.EnhancedLocation?.DisplayName ?? "";
|
||||
email.start = item.Start ?? "";
|
||||
email.end = item.End ?? "";
|
||||
|
||||
const reqAtt = item.RequiredAttendees?.Attendee ?? [];
|
||||
email.requiredAttendees = (Array.isArray(reqAtt) ? reqAtt : [reqAtt])
|
||||
.map((a: any) => {
|
||||
const mb = a.Mailbox ?? {};
|
||||
const name = mb.Name ?? "";
|
||||
const addr = mb.EmailAddress ?? "";
|
||||
return name && addr ? `${name} <${addr}>` : addr;
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
const optAtt = item.OptionalAttendees?.Attendee ?? [];
|
||||
email.optionalAttendees = (Array.isArray(optAtt) ? optAtt : [optAtt])
|
||||
.map((a: any) => {
|
||||
const mb = a.Mailbox ?? {};
|
||||
const name = mb.Name ?? "";
|
||||
const addr = mb.EmailAddress ?? "";
|
||||
return name && addr ? `${name} <${addr}>` : addr;
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
return email;
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
export interface Folder {
|
||||
name: string;
|
||||
id: string;
|
||||
totalCount: number;
|
||||
unreadCount: number;
|
||||
childFolderCount: number;
|
||||
}
|
||||
|
||||
type SoapRequest = (body: string, soapAction: string) => Promise<any>;
|
||||
|
||||
export async function extractFolders(
|
||||
soapRequest: SoapRequest,
|
||||
parentFolderId: string,
|
||||
recursive: boolean = false,
|
||||
): Promise<Folder[]> {
|
||||
const DISTINGUISHED_FOLDERS: Record<string, string> = {
|
||||
inbox: "inbox",
|
||||
"входящие": "inbox",
|
||||
sent: "sentitems",
|
||||
"отправленные": "sentitems",
|
||||
drafts: "drafts",
|
||||
"черновики": "drafts",
|
||||
deleted: "deleteditems",
|
||||
"удаленные": "deleteditems",
|
||||
junk: "junkemail",
|
||||
"нежелательная почта": "junkemail",
|
||||
outbox: "outbox",
|
||||
"исходящие": "outbox",
|
||||
calendar: "calendar",
|
||||
"календарь": "calendar",
|
||||
};
|
||||
|
||||
function buildSoapEnvelope(body: string): string {
|
||||
return `<?xml version="1.0" encoding="utf-8"?>
|
||||
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
|
||||
xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
|
||||
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
|
||||
<s:Body>
|
||||
${body}
|
||||
</s:Body>
|
||||
</s:Envelope>`;
|
||||
}
|
||||
|
||||
function extractResponseMessages(data: any): any[] {
|
||||
const body = data?.Envelope?.Body;
|
||||
if (!body) return [];
|
||||
const firstKey = Object.keys(body).find((k) => k.endsWith("Response"));
|
||||
if (!firstKey) return [];
|
||||
const rm = body[firstKey]?.ResponseMessages;
|
||||
if (!rm) return [];
|
||||
const msgKey = Object.keys(rm).find((k) => k.endsWith("ResponseMessage"));
|
||||
if (!msgKey) return [];
|
||||
const msgs = rm[msgKey];
|
||||
return Array.isArray(msgs) ? msgs : [msgs];
|
||||
}
|
||||
|
||||
const traversal = recursive ? "Deep" : "Shallow";
|
||||
const isDistinguished =
|
||||
DISTINGUISHED_FOLDERS[parentFolderId.toLowerCase()] !== undefined
|
||||
|| ["msgfolderroot"].includes(parentFolderId.toLowerCase());
|
||||
|
||||
const folderIdXml = isDistinguished
|
||||
? `<t:DistinguishedFolderId Id="${parentFolderId}"/>`
|
||||
: `<t:FolderId Id="${parentFolderId}"/>`;
|
||||
|
||||
const soap = buildSoapEnvelope(`\
|
||||
<m:FindFolder Traversal="${traversal}">
|
||||
<m:FolderShape>
|
||||
<t:BaseShape>Default</t:BaseShape>
|
||||
</m:FolderShape>
|
||||
<m:ParentFolderIds>
|
||||
${folderIdXml}
|
||||
</m:ParentFolderIds>
|
||||
<m:IndexedPageFolderView MaxEntriesReturned="200" Offset="0" BasePoint="Beginning"/>
|
||||
</m:FindFolder>`);
|
||||
|
||||
const data = await soapRequest(
|
||||
soap,
|
||||
"http://schemas.microsoft.com/exchange/services/2006/messages/FindFolder",
|
||||
);
|
||||
|
||||
const folders: Folder[] = [];
|
||||
|
||||
for (const msg of extractResponseMessages(data)) {
|
||||
const folderList = msg?.RootFolder?.Folders?.Folder;
|
||||
if (!folderList) continue;
|
||||
const list = Array.isArray(folderList) ? folderList : [folderList];
|
||||
|
||||
for (const f of list) {
|
||||
folders.push({
|
||||
name: f.DisplayName ?? "Unknown",
|
||||
id: f.FolderId?.["@_Id"] ?? "",
|
||||
totalCount: f.TotalCount ?? 0,
|
||||
unreadCount: f.UnreadCount ?? 0,
|
||||
childFolderCount: f.ChildFolderCount ?? 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return folders;
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
export function htmlToText(html: string): string {
|
||||
if (!html) return "";
|
||||
let text = html.replace(/<script[^>]*>.*?<\/script>/gis, "");
|
||||
text = text.replace(/<style[^>]*>.*?<\/style>/gis, "");
|
||||
text = text.replace(/<br\s*\/?>/gi, "\n");
|
||||
text = text.replace(/<p[^>]*>/gi, "\n");
|
||||
text = text.replace(/<\/p>/gi, "");
|
||||
text = text.replace(/<div[^>]*>/gi, "\n");
|
||||
text = text.replace(/<\/div>/gi, "");
|
||||
text = text.replace(/<[^>]+>/g, "");
|
||||
text = text.replace(/ /g, " ");
|
||||
text = text.replace(/&/g, "&");
|
||||
text = text.replace(/</g, "<");
|
||||
text = text.replace(/>/g, ">");
|
||||
text = text.replace(/"/g, "\"");
|
||||
text = text.replace(/'/g, "'");
|
||||
text = text.replace(/\n\s*\n/g, "\n\n");
|
||||
text = text.replace(/[ \t]+/g, " ");
|
||||
return text.trim();
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import { configFilePath, initDataDir } from "./data.ts";
|
||||
|
||||
// Re-export for backward compatibility
|
||||
export { initDataDir };
|
||||
|
||||
export interface LoginConfig {
|
||||
serverUrl: string;
|
||||
email: string;
|
||||
username: string;
|
||||
domain?: string;
|
||||
}
|
||||
|
||||
let inMemoryPassword: string | null = null;
|
||||
|
||||
export function setPassword(password: string): void {
|
||||
inMemoryPassword = password;
|
||||
}
|
||||
|
||||
export function getPassword(): string | null {
|
||||
return inMemoryPassword;
|
||||
}
|
||||
|
||||
export function hasPassword(): boolean {
|
||||
return inMemoryPassword !== null;
|
||||
}
|
||||
|
||||
export function clearPassword(): void {
|
||||
inMemoryPassword = null;
|
||||
}
|
||||
|
||||
export function loadConfig(): LoginConfig {
|
||||
const filePath = configFilePath();
|
||||
if (!fs.existsSync(filePath)) {
|
||||
throw new Error("Not logged in. Use the login tool first.");
|
||||
}
|
||||
return JSON.parse(fs.readFileSync(filePath, "utf-8")) as LoginConfig;
|
||||
}
|
||||
|
||||
export function saveConfig(config: LoginConfig): void {
|
||||
const filePath = configFilePath();
|
||||
fs.writeFileSync(filePath, JSON.stringify(config, null, 2), "utf-8");
|
||||
}
|
||||
|
||||
export function clearConfig(): void {
|
||||
const filePath = configFilePath();
|
||||
if (fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
clearPassword();
|
||||
}
|
||||
Reference in New Issue
Block a user