Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a4741b6820 | |||
| 07db914ca0 | |||
| 2f0bfba1cf | |||
| 8dcdab97ce | |||
| afa2bf5126 | |||
| 979e974521 | |||
| 1599bf3981 | |||
| 17a6f91b3f | |||
| 990a8d09b6 | |||
| bd90359332 | |||
| d2de768878 | |||
| 6fefd17400 | |||
| 92942a3bcd | |||
| af3da35179 |
@@ -10,3 +10,5 @@
|
|||||||
.vscode
|
.vscode
|
||||||
.yarn
|
.yarn
|
||||||
node_modules
|
node_modules
|
||||||
|
config.json
|
||||||
|
data/
|
||||||
@@ -0,0 +1,484 @@
|
|||||||
|
import { XMLParser } from "fast-xml-parser";
|
||||||
|
import https from "node:https";
|
||||||
|
import { createRequire } from "node:module";
|
||||||
|
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";
|
||||||
|
|
||||||
|
const ntlm: any = createRequire(import.meta.url)("httpntlm");
|
||||||
|
const postAsync = promisify(ntlm.post.bind(ntlm));
|
||||||
|
|
||||||
|
const SSL_OP_LEGACY_SERVER_CONNECT = 0x00000004;
|
||||||
|
|
||||||
|
const AGENT = new https.Agent({
|
||||||
|
keepAlive: true,
|
||||||
|
rejectUnauthorized: false,
|
||||||
|
secureOptions: SSL_OP_LEGACY_SERVER_CONNECT,
|
||||||
|
});
|
||||||
|
|
||||||
|
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>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PARSER = new XMLParser({
|
||||||
|
ignoreAttributes: false,
|
||||||
|
attributeNamePrefix: "@_",
|
||||||
|
removeNSPrefix: true,
|
||||||
|
textNodeName: "#text",
|
||||||
|
});
|
||||||
|
|
||||||
|
export class EwsClient {
|
||||||
|
private config: LoginConfig;
|
||||||
|
private ewsUrl: string;
|
||||||
|
|
||||||
|
constructor(config: LoginConfig, password?: string) {
|
||||||
|
this.config = config;
|
||||||
|
this.ewsUrl = `${config.serverUrl.replace(/\/+$/, "")}/EWS/Exchange.asmx`;
|
||||||
|
if (password) setPassword(password);
|
||||||
|
}
|
||||||
|
|
||||||
|
private get domain(): string {
|
||||||
|
return this.config.domain ?? "corp";
|
||||||
|
}
|
||||||
|
|
||||||
|
private get password(): string {
|
||||||
|
const pw = getPassword();
|
||||||
|
if (!pw) throw new Error("Not logged in. Password not found in memory.");
|
||||||
|
return pw;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async soapRequest(body: string, soapAction: string): Promise<any> {
|
||||||
|
const res = await postAsync({
|
||||||
|
url: this.ewsUrl,
|
||||||
|
username: this.config.username,
|
||||||
|
domain: this.domain,
|
||||||
|
password: this.password,
|
||||||
|
agent: AGENT,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "text/xml; charset=utf-8",
|
||||||
|
SOAPAction: soapAction,
|
||||||
|
},
|
||||||
|
body,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (typeof res.body !== "string") {
|
||||||
|
throw new Error(`NTLM request failed, status=${res.statusCode}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return PARSER.parse(res.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
private 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];
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifyConnection(): Promise<{ ok: boolean; error?: string }> {
|
||||||
|
try {
|
||||||
|
await this.getFolderId("inbox");
|
||||||
|
return { ok: true };
|
||||||
|
} catch (error: any) {
|
||||||
|
return { ok: false, error: error.message ?? String(error) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getFolderId(folderName: string): Promise<string> {
|
||||||
|
const lower = folderName.toLowerCase();
|
||||||
|
const distinguished = (DISTINGUISHED_FOLDERS as Record<string, string>)[lower];
|
||||||
|
|
||||||
|
if (distinguished) {
|
||||||
|
const soap = buildSoapEnvelope(`\
|
||||||
|
<m:GetFolder>
|
||||||
|
<m:FolderShape>
|
||||||
|
<t:BaseShape>IdOnly</t:BaseShape>
|
||||||
|
</m:FolderShape>
|
||||||
|
<m:FolderIds>
|
||||||
|
<t:DistinguishedFolderId Id="${distinguished}"/>
|
||||||
|
</m:FolderIds>
|
||||||
|
</m:GetFolder>`);
|
||||||
|
|
||||||
|
const data = await this.soapRequest(
|
||||||
|
soap,
|
||||||
|
"http://schemas.microsoft.com/exchange/services/2006/messages/GetFolder",
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const msg of this.extractResponseMessages(data)) {
|
||||||
|
const folder = msg?.Folders?.Folder;
|
||||||
|
if (folder?.FolderId?.["@_Id"]) {
|
||||||
|
return folder.FolderId["@_Id"];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const soap = buildSoapEnvelope(`\
|
||||||
|
<m:FindFolder Traversal="Shallow">
|
||||||
|
<m:FolderShape>
|
||||||
|
<t:BaseShape>Default</t:BaseShape>
|
||||||
|
</m:FolderShape>
|
||||||
|
<m:ParentFolderIds>
|
||||||
|
<t:DistinguishedFolderId Id="msgfolderroot"/>
|
||||||
|
</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",
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const msg of this.extractResponseMessages(data)) {
|
||||||
|
const folders = msg?.RootFolder?.Folders?.Folder;
|
||||||
|
if (!folders) continue;
|
||||||
|
const list = Array.isArray(folders) ? folders : [folders];
|
||||||
|
for (const f of list) {
|
||||||
|
if (f.DisplayName?.toLowerCase() === lower) {
|
||||||
|
return f.FolderId?.["@_Id"] ?? "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Folder '${folderName}' not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findItems(
|
||||||
|
folderId: string,
|
||||||
|
options: {
|
||||||
|
limit?: number;
|
||||||
|
offset?: number;
|
||||||
|
baseShape?: string;
|
||||||
|
restriction?: string;
|
||||||
|
traversal?: string;
|
||||||
|
} = {},
|
||||||
|
): Promise<any[]> {
|
||||||
|
const {
|
||||||
|
limit = 10,
|
||||||
|
offset = 0,
|
||||||
|
baseShape = "AllProperties",
|
||||||
|
restriction = "",
|
||||||
|
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>
|
||||||
|
<t:BaseShape>${baseShape}</t:BaseShape>
|
||||||
|
</m:ItemShape>
|
||||||
|
<m:IndexedPageItemView MaxEntriesReturned="${limit}" Offset="${offset}" BasePoint="Beginning"/>
|
||||||
|
<m:ParentFolderIds>
|
||||||
|
${folderIdXml}
|
||||||
|
</m:ParentFolderIds>
|
||||||
|
<m:SortOrder>
|
||||||
|
<t:FieldOrder Order="Descending">
|
||||||
|
<t:FieldURI FieldURI="item:DateTimeReceived"/>
|
||||||
|
</t:FieldOrder>
|
||||||
|
</m:SortOrder>
|
||||||
|
${restriction}
|
||||||
|
</m:FindItem>`);
|
||||||
|
|
||||||
|
const data = await this.soapRequest(
|
||||||
|
soap,
|
||||||
|
"http://schemas.microsoft.com/exchange/services/2006/messages/FindItem",
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const msg of this.extractResponseMessages(data)) {
|
||||||
|
const items = msg?.RootFolder?.Items?.Message
|
||||||
|
?? msg?.RootFolder?.Items?.CalendarItem;
|
||||||
|
if (!items) continue;
|
||||||
|
return Array.isArray(items) ? items : [items];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
async getItem(itemId: string): Promise<any> {
|
||||||
|
const soap = buildSoapEnvelope(`\
|
||||||
|
<m:GetItem>
|
||||||
|
<m:ItemShape>
|
||||||
|
<t:BaseShape>AllProperties</t:BaseShape>
|
||||||
|
<t:BodyType>HTML</t:BodyType>
|
||||||
|
</m:ItemShape>
|
||||||
|
<m:ItemIds>
|
||||||
|
<t:ItemId Id="${itemId}"/>
|
||||||
|
</m:ItemIds>
|
||||||
|
</m:GetItem>`);
|
||||||
|
|
||||||
|
const data = await this.soapRequest(
|
||||||
|
soap,
|
||||||
|
"http://schemas.microsoft.com/exchange/services/2006/messages/GetItem",
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const msg of this.extractResponseMessages(data)) {
|
||||||
|
const items = msg?.Items;
|
||||||
|
if (!items) continue;
|
||||||
|
|
||||||
|
const itemKey = Object.keys(items).find((k) =>
|
||||||
|
[
|
||||||
|
"Message",
|
||||||
|
"CalendarItem",
|
||||||
|
"MeetingRequest",
|
||||||
|
"MeetingResponse",
|
||||||
|
"MeetingCancellation",
|
||||||
|
].includes(k)
|
||||||
|
);
|
||||||
|
if (itemKey) {
|
||||||
|
return items[itemKey];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Item '${itemId}' not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findFolders(
|
||||||
|
parentFolderId: string,
|
||||||
|
recursive: boolean = false,
|
||||||
|
): Promise<Folder[]> {
|
||||||
|
return extractFolders(
|
||||||
|
(body, soapAction) => this.soapRequest(body, soapAction),
|
||||||
|
parentFolderId,
|
||||||
|
recursive,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
extractEmail(item: any): Email {
|
||||||
|
return extractEmail(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateItems(
|
||||||
|
itemIds: string[],
|
||||||
|
updates: { fieldUri: string; value: string | boolean }[],
|
||||||
|
): Promise<any[]> {
|
||||||
|
const propName = (fieldUri: string): string => {
|
||||||
|
const parts = fieldUri.split(":");
|
||||||
|
return parts[parts.length - 1];
|
||||||
|
};
|
||||||
|
|
||||||
|
const changesXml = itemIds.map((id) => {
|
||||||
|
const updatesXml = updates.map((u) => {
|
||||||
|
const val = typeof u.value === "boolean"
|
||||||
|
? (u.value ? "true" : "false")
|
||||||
|
: u.value;
|
||||||
|
return `\
|
||||||
|
<t:SetItemField>
|
||||||
|
<t:FieldURI FieldURI="${u.fieldUri}"/>
|
||||||
|
<t:Message>
|
||||||
|
<t:${propName(u.fieldUri)}>${String(val)}</t:${
|
||||||
|
propName(u.fieldUri)
|
||||||
|
}>
|
||||||
|
</t:Message>
|
||||||
|
</t:SetItemField>`;
|
||||||
|
}).join("\n");
|
||||||
|
|
||||||
|
return `\
|
||||||
|
<t:ItemChange>
|
||||||
|
<t:ItemId Id="${id}"/>
|
||||||
|
<t:Updates>
|
||||||
|
${updatesXml}
|
||||||
|
</t:Updates>
|
||||||
|
</t:ItemChange>`;
|
||||||
|
}).join("\n");
|
||||||
|
|
||||||
|
const soap = buildSoapEnvelope(`\
|
||||||
|
<m:UpdateItem MessageDisposition="SaveOnly" ConflictResolution="AutoResolve">
|
||||||
|
<m:ItemChanges>
|
||||||
|
${changesXml}
|
||||||
|
</m:ItemChanges>
|
||||||
|
</m:UpdateItem>`);
|
||||||
|
|
||||||
|
const data = await this.soapRequest(
|
||||||
|
soap,
|
||||||
|
"http://schemas.microsoft.com/exchange/services/2006/messages/UpdateItem",
|
||||||
|
);
|
||||||
|
|
||||||
|
return this.extractResponseMessages(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getAttachment(
|
||||||
|
attachmentId: string,
|
||||||
|
): Promise<{ content: Buffer; name: string; contentType: string }> {
|
||||||
|
const soap = buildSoapEnvelope(`\
|
||||||
|
<m:GetAttachment>
|
||||||
|
<m:AttachmentIds>
|
||||||
|
<t:AttachmentId Id="${attachmentId}"/>
|
||||||
|
</m:AttachmentIds>
|
||||||
|
</m:GetAttachment>`);
|
||||||
|
|
||||||
|
const data = await this.soapRequest(
|
||||||
|
soap,
|
||||||
|
"http://schemas.microsoft.com/exchange/services/2006/messages/GetAttachment",
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const msg of this.extractResponseMessages(data)) {
|
||||||
|
const attachments = msg?.Attachments?.FileAttachment;
|
||||||
|
if (!attachments) continue;
|
||||||
|
const list = Array.isArray(attachments) ? attachments : [attachments];
|
||||||
|
for (const a of list) {
|
||||||
|
const contentBase64 = a.Content ?? "";
|
||||||
|
const content = Buffer.from(contentBase64, "base64");
|
||||||
|
return {
|
||||||
|
content,
|
||||||
|
name: a.Name ?? "attachment",
|
||||||
|
contentType: a.ContentType ?? "application/octet-stream",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Attachment '${attachmentId}' not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findCalendarItems(
|
||||||
|
folderId: string,
|
||||||
|
startDate: string,
|
||||||
|
endDate: string,
|
||||||
|
): Promise<any[]> {
|
||||||
|
const soap = buildSoapEnvelope(`\
|
||||||
|
<m:FindItem Traversal="Shallow">
|
||||||
|
<m:ItemShape>
|
||||||
|
<t:BaseShape>AllProperties</t:BaseShape>
|
||||||
|
<t:BodyType>HTML</t:BodyType>
|
||||||
|
</m:ItemShape>
|
||||||
|
<m:ParentFolderIds>
|
||||||
|
<t:FolderId Id="${folderId}"/>
|
||||||
|
</m:ParentFolderIds>
|
||||||
|
<m:CalendarView MaxEntriesReturned="200" StartDate="${startDate}" EndDate="${endDate}"/>
|
||||||
|
</m:FindItem>`);
|
||||||
|
|
||||||
|
const data = await this.soapRequest(
|
||||||
|
soap,
|
||||||
|
"http://schemas.microsoft.com/exchange/services/2006/messages/FindItem",
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const msg of this.extractResponseMessages(data)) {
|
||||||
|
const items = msg?.RootFolder?.Items?.CalendarItem;
|
||||||
|
if (!items) continue;
|
||||||
|
return Array.isArray(items) ? items : [items];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUserAvailability(
|
||||||
|
emails: string[],
|
||||||
|
startDate: string,
|
||||||
|
endDate: string,
|
||||||
|
requestedView: string = "DetailedMerged",
|
||||||
|
): Promise<any> {
|
||||||
|
const mailboxDataXml = emails.map((email) =>
|
||||||
|
`\
|
||||||
|
<t:MailboxData>
|
||||||
|
<t:Email>
|
||||||
|
<t:Address>${
|
||||||
|
email.replace(/&/g, "&").replace(/</g, "<")
|
||||||
|
}</t:Address>
|
||||||
|
</t:Email>
|
||||||
|
<t:AttendeeType>Required</t:AttendeeType>
|
||||||
|
</t:MailboxData>`
|
||||||
|
).join("\n");
|
||||||
|
|
||||||
|
const soap = `<?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>
|
||||||
|
<m:GetUserAvailabilityRequest>
|
||||||
|
<m:MailboxDataArray>
|
||||||
|
${mailboxDataXml}
|
||||||
|
</m:MailboxDataArray>
|
||||||
|
<m:FreeBusyViewOptions>
|
||||||
|
<t:TimeWindow>
|
||||||
|
<t:StartTime>${startDate}T00:00:00</t:StartTime>
|
||||||
|
<t:EndTime>${endDate}T23:59:59</t:EndTime>
|
||||||
|
</t:TimeWindow>
|
||||||
|
<t:MergedFreeBusyIntervalInMinutes>30</t:MergedFreeBusyIntervalInMinutes>
|
||||||
|
<t:RequestedView>${requestedView}</t:RequestedView>
|
||||||
|
</m:FreeBusyViewOptions>
|
||||||
|
</m:GetUserAvailabilityRequest>
|
||||||
|
</s:Body>
|
||||||
|
</s:Envelope>`;
|
||||||
|
|
||||||
|
const data = await this.soapRequest(
|
||||||
|
soap,
|
||||||
|
"http://schemas.microsoft.com/exchange/services/2006/messages/GetUserAvailability",
|
||||||
|
);
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async resolveNames(
|
||||||
|
query: string,
|
||||||
|
fullContact: boolean = true,
|
||||||
|
): Promise<any[]> {
|
||||||
|
const soap = buildSoapEnvelope(`\
|
||||||
|
<m:ResolveNames ReturnFullContactData="${fullContact}" SearchScope="ActiveDirectoryContacts">
|
||||||
|
<m:UnresolvedEntry>${
|
||||||
|
query.replace(/&/g, "&").replace(/</g, "<")
|
||||||
|
}</m:UnresolvedEntry>
|
||||||
|
</m:ResolveNames>`);
|
||||||
|
|
||||||
|
const data = await this.soapRequest(
|
||||||
|
soap,
|
||||||
|
"http://schemas.microsoft.com/exchange/services/2006/messages/ResolveNames",
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const msg of this.extractResponseMessages(data)) {
|
||||||
|
const resolutions = msg?.ResolutionSet?.Resolution;
|
||||||
|
if (resolutions) {
|
||||||
|
return Array.isArray(resolutions) ? resolutions : [resolutions];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
FROM node:26-slim
|
||||||
|
WORKDIR /app
|
||||||
|
COPY . .
|
||||||
|
RUN npm install
|
||||||
|
CMD ["npm", "start"]
|
||||||
+8
-4
@@ -5,14 +5,18 @@
|
|||||||
"module.sortImportDeclarations": "caseInsensitive",
|
"module.sortImportDeclarations": "caseInsensitive",
|
||||||
"module.sortExportDeclarations": "caseInsensitive"
|
"module.sortExportDeclarations": "caseInsensitive"
|
||||||
},
|
},
|
||||||
|
"markdown": {
|
||||||
|
"lineWidth": 80,
|
||||||
|
"textWrap": "always"
|
||||||
|
},
|
||||||
"excludes": [
|
"excludes": [
|
||||||
"**/.git",
|
"**/.git",
|
||||||
"**/.target"
|
"**/.target"
|
||||||
],
|
],
|
||||||
"plugins": [
|
"plugins": [
|
||||||
"https://plugins.dprint.dev/typescript-0.91.1.wasm",
|
"https://plugins.dprint.dev/typescript-0.96.1.wasm",
|
||||||
"https://plugins.dprint.dev/json-0.17.4.wasm",
|
"https://plugins.dprint.dev/json-0.23.0.wasm",
|
||||||
"https://plugins.dprint.dev/markdown-0.15.3.wasm",
|
"https://plugins.dprint.dev/markdown-0.22.1.wasm",
|
||||||
"https://plugins.dprint.dev/dockerfile-0.3.0.wasm"
|
"https://plugins.dprint.dev/dockerfile-0.4.1.wasm"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,148 +1,142 @@
|
|||||||
import { XMLParser } from "fast-xml-parser";
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||||
import { promisify } from "node:util";
|
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
||||||
import { env } from "node:process";
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||||
import { createRequire } from "node:module";
|
import { Command } from "commander";
|
||||||
import https from "node:https";
|
import crypto from "node:crypto";
|
||||||
|
import http from "node:http";
|
||||||
|
import { initDataDir } from "./utils/data.ts";
|
||||||
|
import { registerAuthTools } from "./tools/auth.ts";
|
||||||
|
import { registerAvailabilityTools } from "./tools/availability.ts";
|
||||||
|
import { registerCalendarTools } from "./tools/calendar.ts";
|
||||||
|
import { registerEmailTools } from "./tools/email.ts";
|
||||||
|
import { registerFolderTools } from "./tools/folders.ts";
|
||||||
|
import { registerPeopleTools } from "./tools/people.ts";
|
||||||
|
|
||||||
const ntlm: any = createRequire(import.meta.url)("httpntlm");
|
const program = new Command()
|
||||||
const postAsync = promisify(ntlm.post.bind(ntlm));
|
.name("exchange-mcp")
|
||||||
|
.description("Exchange MCP Server — EWS integration via MCP")
|
||||||
|
.option("--transport <type>", "Transport: stdio or sse", "stdio")
|
||||||
|
.option(
|
||||||
|
"--token-hash <hash>",
|
||||||
|
"SHA-256 hash of bearer token for HTTP transport auth",
|
||||||
|
)
|
||||||
|
.option("--host <host>", "HTTP host", "127.0.0.1")
|
||||||
|
.option("--port <port>", "HTTP port", "8000")
|
||||||
|
.option("--data-dir <path>", "Data directory for config.json", "./data");
|
||||||
|
|
||||||
const SSL_OP_LEGACY_SERVER_CONNECT = 0x00000004;
|
program.parse(process.argv);
|
||||||
|
const options = program.opts();
|
||||||
|
|
||||||
const AGENT = new https.Agent({
|
initDataDir(options.dataDir);
|
||||||
keepAlive: true,
|
|
||||||
rejectUnauthorized: false,
|
|
||||||
secureOptions: SSL_OP_LEGACY_SERVER_CONNECT,
|
|
||||||
});
|
|
||||||
|
|
||||||
const EWS_URL = "https://mail.b1.ru/EWS/Exchange.asmx";
|
function buildServer(): McpServer {
|
||||||
|
const server = new McpServer({
|
||||||
const PARSER = new XMLParser({
|
name: "exchange-mcp",
|
||||||
ignoreAttributes: false,
|
version: "1.0.0",
|
||||||
attributeNamePrefix: "@_",
|
|
||||||
removeNSPrefix: true,
|
|
||||||
textNodeName: "#text",
|
|
||||||
});
|
|
||||||
|
|
||||||
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>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function ewsSoap(options: { body: string; soapAction: string }): Promise<any> {
|
|
||||||
const res = await postAsync({
|
|
||||||
url: EWS_URL,
|
|
||||||
username: env.EWS_USERNAME ?? "polina.litvinova",
|
|
||||||
domain: "corp",
|
|
||||||
password: env.EWS_PASSWORD,
|
|
||||||
agent: AGENT,
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "text/xml; charset=utf-8",
|
|
||||||
SOAPAction: options.soapAction,
|
|
||||||
},
|
|
||||||
body: options.body,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (typeof res.body !== "string") {
|
registerAuthTools(server);
|
||||||
throw new Error(`NTLM request failed, status=${res.statusCode}`);
|
registerEmailTools(server);
|
||||||
|
registerFolderTools(server);
|
||||||
|
registerCalendarTools(server);
|
||||||
|
registerAvailabilityTools(server);
|
||||||
|
registerPeopleTools(server);
|
||||||
|
|
||||||
|
return server;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runStdio() {
|
||||||
|
const server = buildServer();
|
||||||
|
const transport = new StdioServerTransport();
|
||||||
|
await server.connect(transport);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runSSE() {
|
||||||
|
const transports = new Map<string, SSEServerTransport>();
|
||||||
|
|
||||||
|
const httpServer = http.createServer(async (req, res) => {
|
||||||
|
if (options.tokenHash) {
|
||||||
|
const auth = req.headers.authorization || "";
|
||||||
|
const token = auth.startsWith("Bearer ") ? auth.slice(7) : "";
|
||||||
|
const hash = crypto.createHash("sha256").update(token).digest("hex");
|
||||||
|
if (hash !== options.tokenHash) {
|
||||||
|
res.writeHead(401, { "Content-Type": "text/plain" });
|
||||||
|
res.end("Unauthorized");
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return PARSER.parse(res.body);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getFolder() {
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||||
const soap = buildSoapEnvelope(`\
|
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||||
<m:GetFolder>
|
res.setHeader(
|
||||||
<m:FolderShape>
|
"Access-Control-Allow-Headers",
|
||||||
<t:BaseShape>IdOnly</t:BaseShape>
|
"Content-Type, Authorization",
|
||||||
<t:AdditionalProperties>
|
);
|
||||||
<t:FieldURI FieldURI="folder:DisplayName"/>
|
|
||||||
<t:FieldURI FieldURI="folder:TotalCount"/>
|
|
||||||
<t:FieldURI FieldURI="folder:UnreadCount"/>
|
|
||||||
</t:AdditionalProperties>
|
|
||||||
</m:FolderShape>
|
|
||||||
<m:FolderIds>
|
|
||||||
<t:DistinguishedFolderId Id="inbox"/>
|
|
||||||
</m:FolderIds>
|
|
||||||
</m:GetFolder>`);
|
|
||||||
|
|
||||||
const data = await ewsSoap({
|
if (req.method === "OPTIONS") {
|
||||||
body: soap,
|
res.writeHead(200);
|
||||||
soapAction: "http://schemas.microsoft.com/exchange/services/2006/messages/GetFolder",
|
res.end();
|
||||||
});
|
|
||||||
|
|
||||||
const rm = data.Envelope?.Body?.GetFolderResponse?.ResponseMessages;
|
|
||||||
const msg = rm?.GetFolderResponseMessage;
|
|
||||||
const folder = msg?.Folders?.Folder;
|
|
||||||
|
|
||||||
console.log(`DisplayName: ${folder?.DisplayName}`);
|
|
||||||
console.log(`FolderId: ${folder?.FolderId?.["@_Id"]}`);
|
|
||||||
console.log(`Total items: ${folder?.TotalCount}`);
|
|
||||||
console.log(`Unread: ${folder?.UnreadCount}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getLastMessages() {
|
|
||||||
const soap = buildSoapEnvelope(`\
|
|
||||||
<m:FindItem Traversal="Shallow">
|
|
||||||
<m:ItemShape>
|
|
||||||
<t:BaseShape>AllProperties</t:BaseShape>
|
|
||||||
</m:ItemShape>
|
|
||||||
<m:IndexedPageItemView MaxEntriesReturned="3" Offset="0" BasePoint="Beginning"/>
|
|
||||||
<m:ParentFolderIds>
|
|
||||||
<t:DistinguishedFolderId Id="inbox"/>
|
|
||||||
</m:ParentFolderIds>
|
|
||||||
<m:SortOrder>
|
|
||||||
<t:FieldOrder Order="Descending">
|
|
||||||
<t:FieldURI FieldURI="item:DateTimeReceived"/>
|
|
||||||
</t:FieldOrder>
|
|
||||||
</m:SortOrder>
|
|
||||||
</m:FindItem>`);
|
|
||||||
|
|
||||||
const data = await ewsSoap({
|
|
||||||
body: soap,
|
|
||||||
soapAction: "http://schemas.microsoft.com/exchange/services/2006/messages/FindItem",
|
|
||||||
});
|
|
||||||
|
|
||||||
const rm = data.Envelope?.Body?.FindItemResponse?.ResponseMessages;
|
|
||||||
const msg = rm?.FindItemResponseMessage;
|
|
||||||
const rootFolder = msg?.RootFolder;
|
|
||||||
const items = rootFolder?.Items;
|
|
||||||
const messagesList: any[] = items?.Message ? (Array.isArray(items.Message) ? items.Message : [items.Message]) : [];
|
|
||||||
|
|
||||||
if (!messagesList.length) {
|
|
||||||
console.log("\n--- No messages found ---");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`\n--- ${messagesList.length} message(s) ---`);
|
const url = new URL(req.url || "/", `http://${req.headers.host}`);
|
||||||
for (const m of messagesList) {
|
|
||||||
const mbox = m.From?.Mailbox;
|
if (req.method === "GET") {
|
||||||
const author = mbox ? `${mbox.Name ?? "(no name)"} <${mbox.EmailAddress ?? "(no email)"}>` : "(unknown)";
|
const transport = new SSEServerTransport("/sse", res);
|
||||||
console.log(`\nSubject: ${m.Subject ?? "(no subject)"}`);
|
const server = buildServer();
|
||||||
console.log(`From: ${author}`);
|
await server.connect(transport);
|
||||||
console.log(`Date: ${m.DateTimeReceived ?? "(unknown)"}`);
|
|
||||||
console.log(`Preview: ${(m.Preview ?? "(no preview)").slice(0, 200)}`);
|
transports.set(transport.sessionId, transport);
|
||||||
|
res.on("close", () => {
|
||||||
|
transports.delete(transport.sessionId);
|
||||||
|
});
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (req.method === "POST" && url.pathname === "/sse") {
|
||||||
|
const sessionId = url.searchParams.get("sessionId") || "";
|
||||||
|
const transport = transports.get(sessionId);
|
||||||
|
if (!transport) {
|
||||||
|
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||||
|
res.end("Session not found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await transport.handlePostMessage(req, res);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
res.writeHead(404);
|
||||||
|
res.end("Not found");
|
||||||
|
});
|
||||||
|
|
||||||
|
const port = Number(options.port);
|
||||||
|
httpServer.listen(port, options.host);
|
||||||
|
|
||||||
|
console.error(
|
||||||
|
`Exchange MCP Server running via SSE on http://${options.host}:${port}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
if (!env.EWS_PASSWORD) {
|
const transportType: string = options.transport;
|
||||||
console.error("Set EWS_PASSWORD environment variable");
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
switch (transportType) {
|
||||||
await getFolder();
|
case "stdio":
|
||||||
await getLastMessages();
|
await runStdio();
|
||||||
} catch (err) {
|
break;
|
||||||
console.error("Error:", err);
|
case "sse":
|
||||||
|
await runSSE();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
console.error(
|
||||||
|
`Unsupported transport: "${transportType}". Use "stdio" or "sse".`,
|
||||||
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
main();
|
main().catch((error) => {
|
||||||
|
console.error("Fatal error:", error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
|||||||
Generated
+1166
-2
File diff suppressed because it is too large
Load Diff
+9
-2
@@ -2,12 +2,19 @@
|
|||||||
"name": "exchange-mcp",
|
"name": "exchange-mcp",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"start": "node main.ts",
|
||||||
|
"format": "dprint fmt"
|
||||||
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
||||||
|
"commander": "^15.0.0",
|
||||||
"fast-xml-parser": "^5.2.0",
|
"fast-xml-parser": "^5.2.0",
|
||||||
"httpntlm": "^1.8.13"
|
"httpntlm": "^1.8.13",
|
||||||
|
"zod": "^4.4.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^22.0.0",
|
"@types/node": "^22.20.1",
|
||||||
"typescript": "^5.9.3"
|
"typescript": "^5.9.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+199
@@ -0,0 +1,199 @@
|
|||||||
|
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";
|
||||||
|
|
||||||
|
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.",
|
||||||
|
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"),
|
||||||
|
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(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
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",
|
||||||
|
};
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
if (!result.ok) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({
|
||||||
|
success: false,
|
||||||
|
error: result.error ?? "Connection verification failed",
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
saveConfig(config);
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({
|
||||||
|
success: true,
|
||||||
|
message: `Logged in as ${email} to ${serverUrl}`,
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({
|
||||||
|
success: false,
|
||||||
|
error: error.message ?? String(error),
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
server.registerTool(
|
||||||
|
"check_session",
|
||||||
|
{
|
||||||
|
description:
|
||||||
|
"Check whether the current EWS session is authenticated. No parameters.",
|
||||||
|
inputSchema: z.object({}),
|
||||||
|
outputSchema: z.object({
|
||||||
|
authenticated: z.boolean(),
|
||||||
|
email: z.string().optional(),
|
||||||
|
serverUrl: z.string().optional(),
|
||||||
|
error: z.string().optional(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
async () => {
|
||||||
|
try {
|
||||||
|
if (!hasPassword()) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({
|
||||||
|
authenticated: false,
|
||||||
|
error: "Not logged in. Password not found in memory.",
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
structuredContent: {
|
||||||
|
authenticated: false,
|
||||||
|
error: "Not logged in. Password not found in memory.",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const config = loadConfig();
|
||||||
|
const client = new EwsClient(config);
|
||||||
|
const result = await client.verifyConnection();
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({
|
||||||
|
authenticated: result.ok,
|
||||||
|
email: config.email,
|
||||||
|
serverUrl: config.serverUrl,
|
||||||
|
error: result.error,
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
structuredContent: {
|
||||||
|
authenticated: result.ok,
|
||||||
|
email: config.email,
|
||||||
|
serverUrl: config.serverUrl,
|
||||||
|
error: result.error,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({
|
||||||
|
authenticated: false,
|
||||||
|
error: error.message ?? String(error),
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
structuredContent: {
|
||||||
|
authenticated: false,
|
||||||
|
error: error.message ?? String(error),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
server.registerTool(
|
||||||
|
"logout",
|
||||||
|
{
|
||||||
|
description:
|
||||||
|
"Clear stored credentials (serverUrl, email, username, domain, password)."
|
||||||
|
+ " No parameters.",
|
||||||
|
inputSchema: z.object({}),
|
||||||
|
outputSchema: z.object({
|
||||||
|
success: z.boolean(),
|
||||||
|
message: z.string().optional(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
async () => {
|
||||||
|
clearConfig();
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({
|
||||||
|
success: true,
|
||||||
|
message: "Logged out. Credentials cleared.",
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
structuredContent: {
|
||||||
|
success: true,
|
||||||
|
message: "Logged out. Credentials cleared.",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
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";
|
||||||
|
|
||||||
|
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.",
|
||||||
|
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",
|
||||||
|
),
|
||||||
|
durationMinutes: z.number().default(30).describe(
|
||||||
|
"Minimum slot duration in minutes",
|
||||||
|
),
|
||||||
|
startHour: z.number().default(9).describe(
|
||||||
|
"Working day start hour (0-23)",
|
||||||
|
),
|
||||||
|
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(),
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
async ({ startDate, endDate, durationMinutes, startHour, endHour }) => {
|
||||||
|
try {
|
||||||
|
const client = new EwsClient(loadConfig());
|
||||||
|
const config = loadConfig();
|
||||||
|
const ed = endDate || startDate;
|
||||||
|
|
||||||
|
const data = await client.getUserAvailability(
|
||||||
|
[config.email],
|
||||||
|
startDate,
|
||||||
|
ed,
|
||||||
|
);
|
||||||
|
|
||||||
|
const body = data?.Envelope?.Body?.GetUserAvailabilityResponse
|
||||||
|
?? data?.Envelope?.Body ?? {};
|
||||||
|
const freeBusyArray = body?.FreeBusyResponseArray?.FreeBusyResponse
|
||||||
|
?? [];
|
||||||
|
const responses = Array.isArray(freeBusyArray)
|
||||||
|
? freeBusyArray
|
||||||
|
: [freeBusyArray];
|
||||||
|
|
||||||
|
const busyPeriods: { start: Date; end: Date }[] = [];
|
||||||
|
|
||||||
|
for (const fbResp of responses) {
|
||||||
|
const fbView = fbResp?.FreeBusyView ?? {};
|
||||||
|
const calEvents = fbView?.CalendarEventArray?.CalendarEvent ?? [];
|
||||||
|
const evList = Array.isArray(calEvents) ? calEvents : [calEvents];
|
||||||
|
|
||||||
|
for (const ev of evList) {
|
||||||
|
const bt = ev.BusyType ?? "";
|
||||||
|
if (bt === "Free" || bt === "NoData") continue;
|
||||||
|
const startStr = ev.StartTime ?? "";
|
||||||
|
const endStr = ev.EndTime ?? "";
|
||||||
|
if (startStr && endStr) {
|
||||||
|
busyPeriods.push({
|
||||||
|
start: new Date(startStr),
|
||||||
|
end: new Date(endStr),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const merged = mergeBusyPeriods(busyPeriods);
|
||||||
|
const freeSlots = findFreeSlots(
|
||||||
|
merged,
|
||||||
|
new Date(startDate),
|
||||||
|
ed ? new Date(ed) : new Date(startDate),
|
||||||
|
startHour,
|
||||||
|
endHour,
|
||||||
|
durationMinutes,
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({ freeSlots }),
|
||||||
|
}],
|
||||||
|
structuredContent: { freeSlots },
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({ error: error.message ?? String(error) }),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
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.",
|
||||||
|
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",
|
||||||
|
),
|
||||||
|
durationMinutes: z.number().default(30).describe(
|
||||||
|
"Minimum slot duration in minutes",
|
||||||
|
),
|
||||||
|
startHour: z.number().default(9).describe(
|
||||||
|
"Working day start hour (0-23)",
|
||||||
|
),
|
||||||
|
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(),
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
async (
|
||||||
|
{ emails, startDate, endDate, durationMinutes, startHour, endHour },
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const client = new EwsClient(loadConfig());
|
||||||
|
const emailList = emails.split(",").map((e) => e.trim()).filter(
|
||||||
|
Boolean,
|
||||||
|
);
|
||||||
|
const ed = endDate || startDate;
|
||||||
|
|
||||||
|
const data = await client.getUserAvailability(emailList, startDate, ed);
|
||||||
|
|
||||||
|
const body = data?.Envelope?.Body?.GetUserAvailabilityResponse
|
||||||
|
?? data?.Envelope?.Body ?? {};
|
||||||
|
const freeBusyArray = body?.FreeBusyResponseArray?.FreeBusyResponse
|
||||||
|
?? [];
|
||||||
|
const responses = Array.isArray(freeBusyArray)
|
||||||
|
? freeBusyArray
|
||||||
|
: [freeBusyArray];
|
||||||
|
|
||||||
|
const allBusy: { start: Date; end: Date }[] = [];
|
||||||
|
const attendeeInfo: any[] = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < responses.length; i++) {
|
||||||
|
const fbResp = responses[i];
|
||||||
|
const fbView = fbResp?.FreeBusyView ?? {};
|
||||||
|
const email = emailList[i] || `Person ${i + 1}`;
|
||||||
|
|
||||||
|
const mergedFb = fbView.MergedFreeBusy ?? "";
|
||||||
|
if (mergedFb) {
|
||||||
|
const startTime = new Date(`${startDate}T00:00:00`);
|
||||||
|
const busyPeriods = parseFreeBusyString(mergedFb, startTime);
|
||||||
|
const busyCount = busyPeriods.length;
|
||||||
|
const freeCount = mergedFb.split("").filter((c: string) =>
|
||||||
|
c === "0"
|
||||||
|
).length;
|
||||||
|
attendeeInfo.push({
|
||||||
|
email,
|
||||||
|
busySlots: busyCount,
|
||||||
|
freeSlots: freeCount,
|
||||||
|
});
|
||||||
|
allBusy.push(...busyPeriods);
|
||||||
|
} else {
|
||||||
|
const calEvents = fbView?.CalendarEventArray?.CalendarEvent ?? [];
|
||||||
|
const evList = Array.isArray(calEvents) ? calEvents : [calEvents];
|
||||||
|
attendeeInfo.push({ email, calendarEvents: evList.length });
|
||||||
|
for (const ev of evList) {
|
||||||
|
const startStr = ev.StartTime ?? "";
|
||||||
|
const endStr = ev.EndTime ?? "";
|
||||||
|
if (startStr && endStr) {
|
||||||
|
allBusy.push({
|
||||||
|
start: new Date(startStr),
|
||||||
|
end: new Date(endStr),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const merged = mergeBusyPeriods(allBusy);
|
||||||
|
const freeByDate = findFreeSlots(
|
||||||
|
merged,
|
||||||
|
new Date(startDate),
|
||||||
|
new Date(ed),
|
||||||
|
startHour,
|
||||||
|
endHour,
|
||||||
|
durationMinutes,
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({
|
||||||
|
period: { start: startDate, end: ed },
|
||||||
|
attendees: attendeeInfo,
|
||||||
|
freeSlots: freeByDate,
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
structuredContent: {
|
||||||
|
period: { start: startDate, end: ed },
|
||||||
|
attendees: attendeeInfo,
|
||||||
|
freeSlots: freeByDate,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({ error: error.message ?? String(error) }),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function parseFreeBusyString(
|
||||||
|
fbStr: string,
|
||||||
|
startTime: Date,
|
||||||
|
intervalMinutes: number = 30,
|
||||||
|
): { start: Date; end: Date }[] {
|
||||||
|
const periods: { start: Date; end: Date }[] = [];
|
||||||
|
const current = new Date(startTime);
|
||||||
|
|
||||||
|
for (const char of fbStr) {
|
||||||
|
const next = new Date(current.getTime() + intervalMinutes * 60000);
|
||||||
|
if (char !== "0") {
|
||||||
|
periods.push({ start: new Date(current), end: next });
|
||||||
|
}
|
||||||
|
current.setTime(next.getTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
return periods;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeBusyPeriods(
|
||||||
|
periods: { start: Date; end: Date }[],
|
||||||
|
): { start: Date; end: Date }[] {
|
||||||
|
if (!periods.length) return [];
|
||||||
|
|
||||||
|
const sorted = [...periods].sort((a, b) =>
|
||||||
|
a.start.getTime() - b.start.getTime()
|
||||||
|
);
|
||||||
|
const merged: { start: Date; end: Date }[] = [{ ...sorted[0] }];
|
||||||
|
|
||||||
|
for (let i = 1; i < sorted.length; i++) {
|
||||||
|
const last = merged[merged.length - 1];
|
||||||
|
if (sorted[i].start <= last.end) {
|
||||||
|
last.end = sorted[i].end > last.end ? sorted[i].end : last.end;
|
||||||
|
} else {
|
||||||
|
merged.push({ ...sorted[i] });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findFreeSlots(
|
||||||
|
busyPeriods: { start: Date; end: Date }[],
|
||||||
|
startDate: Date,
|
||||||
|
endDate: Date,
|
||||||
|
startHour: number,
|
||||||
|
endHour: number,
|
||||||
|
durationMinutes: number,
|
||||||
|
): Record<string, { start: string; end: string; durationMinutes: number }[]> {
|
||||||
|
const result: Record<
|
||||||
|
string,
|
||||||
|
{ start: string; end: string; durationMinutes: number }[]
|
||||||
|
> = {};
|
||||||
|
|
||||||
|
const current = new Date(startDate);
|
||||||
|
current.setDate(current.getDate());
|
||||||
|
current.setHours(0, 0, 0, 0);
|
||||||
|
|
||||||
|
const end = new Date(endDate);
|
||||||
|
end.setDate(end.getDate() + 1);
|
||||||
|
end.setHours(0, 0, 0, 0);
|
||||||
|
|
||||||
|
while (current < end) {
|
||||||
|
if (current.getDay() !== 0 && current.getDay() !== 6) {
|
||||||
|
const dayStart = new Date(current);
|
||||||
|
dayStart.setHours(startHour, 0, 0, 0);
|
||||||
|
|
||||||
|
const dayEnd = new Date(current);
|
||||||
|
dayEnd.setHours(endHour, 0, 0, 0);
|
||||||
|
|
||||||
|
const dayBusy = busyPeriods
|
||||||
|
.filter((p) => p.start < dayEnd && p.end > dayStart)
|
||||||
|
.map((p) => ({
|
||||||
|
start: p.start < dayStart ? dayStart : p.start,
|
||||||
|
end: p.end > dayEnd ? dayEnd : p.end,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const merged = mergeBusyPeriods(dayBusy);
|
||||||
|
|
||||||
|
const slots: { start: string; end: string; durationMinutes: number }[] =
|
||||||
|
[];
|
||||||
|
let cursor = new Date(dayStart);
|
||||||
|
|
||||||
|
for (const bp of merged) {
|
||||||
|
if (cursor < bp.start) {
|
||||||
|
const gap = (bp.start.getTime() - cursor.getTime()) / 60000;
|
||||||
|
if (gap >= durationMinutes) {
|
||||||
|
slots.push({
|
||||||
|
start: formatTime(cursor),
|
||||||
|
end: formatTime(bp.start),
|
||||||
|
durationMinutes: gap,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cursor = bp.end > cursor ? bp.end : cursor;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cursor < dayEnd) {
|
||||||
|
const gap = (dayEnd.getTime() - cursor.getTime()) / 60000;
|
||||||
|
if (gap >= durationMinutes) {
|
||||||
|
slots.push({
|
||||||
|
start: formatTime(cursor),
|
||||||
|
end: formatTime(dayEnd),
|
||||||
|
durationMinutes: gap,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (slots.length) {
|
||||||
|
result[current.toISOString().slice(0, 10)] = slots;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
current.setDate(current.getDate() + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(d: Date): string {
|
||||||
|
return d.toTimeString().slice(0, 5);
|
||||||
|
}
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
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";
|
||||||
|
|
||||||
|
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.",
|
||||||
|
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",
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
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 {
|
||||||
|
const client = new EwsClient(loadConfig());
|
||||||
|
const folderId = await client.getFolderId("calendar");
|
||||||
|
const items = await client.findCalendarItems(
|
||||||
|
folderId,
|
||||||
|
`${startDate}T00:00:00`,
|
||||||
|
`${endDate}T23:59:59`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const events = [];
|
||||||
|
for (const item of items) {
|
||||||
|
const event: any = {
|
||||||
|
subject: item.Subject ?? "(No subject)",
|
||||||
|
start: item.Start ?? "",
|
||||||
|
end: item.End ?? "",
|
||||||
|
location: item.Location ?? item.EnhancedLocation?.DisplayName ?? "",
|
||||||
|
isAllDay: item.IsAllDayEvent === "true"
|
||||||
|
|| item.IsAllDayEvent === true,
|
||||||
|
isCancelled: item.IsCancelled === "true"
|
||||||
|
|| item.IsCancelled === true,
|
||||||
|
isMeeting: true,
|
||||||
|
isRecurring: item.IsRecurring === "true"
|
||||||
|
|| item.IsRecurring === true,
|
||||||
|
organizer: "",
|
||||||
|
organizerEmail: "",
|
||||||
|
myResponse: item.MyResponseType ?? "",
|
||||||
|
itemId: item.ItemId?.["@_Id"] ?? "",
|
||||||
|
body: "",
|
||||||
|
requiredAttendees: [],
|
||||||
|
optionalAttendees: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
if (includeBody && event.itemId) {
|
||||||
|
const details = client.extractEmail(item);
|
||||||
|
event.body = details.body;
|
||||||
|
event.requiredAttendees = details.requiredAttendees ?? [];
|
||||||
|
event.optionalAttendees = details.optionalAttendees ?? [];
|
||||||
|
event.organizer = details.fromName;
|
||||||
|
event.organizerEmail = details.from;
|
||||||
|
event.location = details.location || event.location;
|
||||||
|
}
|
||||||
|
|
||||||
|
events.push(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({ events, count: events.length }),
|
||||||
|
}],
|
||||||
|
structuredContent: { events, count: events.length },
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({ error: error.message ?? String(error) }),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
server.registerTool(
|
||||||
|
"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.",
|
||||||
|
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",
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
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 attachments = email.attachments ?? [];
|
||||||
|
|
||||||
|
const fileAttachments = attachments.filter(
|
||||||
|
(a: any) => a.attachmentId && !a.isInline,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!fileAttachments.length) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({
|
||||||
|
success: true,
|
||||||
|
downloaded: [],
|
||||||
|
count: 0,
|
||||||
|
message: "No downloadable file attachments.",
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
structuredContent: {
|
||||||
|
success: true,
|
||||||
|
downloaded: [],
|
||||||
|
count: 0,
|
||||||
|
message: "No downloadable file attachments.",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.mkdirSync(targetFolder, { recursive: true });
|
||||||
|
|
||||||
|
const downloaded = [];
|
||||||
|
const errors = [];
|
||||||
|
const usedNames = new Set<string>();
|
||||||
|
|
||||||
|
for (const att of fileAttachments) {
|
||||||
|
try {
|
||||||
|
const result = await client.getAttachment(att.attachmentId);
|
||||||
|
let filename = path.basename(result.name);
|
||||||
|
if (!filename) filename = att.name || "attachment";
|
||||||
|
|
||||||
|
const baseName = filename;
|
||||||
|
const dotIdx = baseName.lastIndexOf(".");
|
||||||
|
const namePart = dotIdx > 0 ? baseName.slice(0, dotIdx) : baseName;
|
||||||
|
const extPart = dotIdx > 0 ? baseName.slice(dotIdx) : "";
|
||||||
|
|
||||||
|
let counter = 1;
|
||||||
|
let finalName = filename;
|
||||||
|
while (usedNames.has(finalName.toLowerCase())) {
|
||||||
|
finalName = extPart
|
||||||
|
? `${namePart}_${counter}${extPart}`
|
||||||
|
: `${namePart}_${counter}`;
|
||||||
|
counter++;
|
||||||
|
}
|
||||||
|
usedNames.add(finalName.toLowerCase());
|
||||||
|
|
||||||
|
const filepath = path.join(targetFolder, finalName);
|
||||||
|
fs.writeFileSync(filepath, result.content);
|
||||||
|
|
||||||
|
downloaded.push({
|
||||||
|
name: finalName,
|
||||||
|
path: filepath,
|
||||||
|
size: result.content.length,
|
||||||
|
contentType: result.contentType,
|
||||||
|
});
|
||||||
|
} catch (e: any) {
|
||||||
|
errors.push({
|
||||||
|
name: att.name || "unknown",
|
||||||
|
error: e.message ?? String(e),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({
|
||||||
|
success: errors.length === 0,
|
||||||
|
downloaded,
|
||||||
|
count: downloaded.length,
|
||||||
|
...(errors.length ? { errors } : {}),
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
structuredContent: errors.length === 0
|
||||||
|
? { success: true, downloaded, count: downloaded.length }
|
||||||
|
: { success: false, downloaded, count: downloaded.length, errors },
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({ error: error.message ?? String(error) }),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
+415
@@ -0,0 +1,415 @@
|
|||||||
|
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";
|
||||||
|
|
||||||
|
function getClient(): EwsClient {
|
||||||
|
return new EwsClient(loadConfig());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerEmailTools(server: McpServer): void {
|
||||||
|
server.registerTool(
|
||||||
|
"get_emails",
|
||||||
|
{
|
||||||
|
description: "Get emails from a mailbox folder."
|
||||||
|
+ " Supports optional text search via query/queryScope.",
|
||||||
|
inputSchema: z.object({
|
||||||
|
folder: z.string().default("Inbox").describe(
|
||||||
|
"Folder name (Inbox, Sent, Drafts, Deleted, Junk, or custom)."
|
||||||
|
+ " Supports Russian folder names",
|
||||||
|
),
|
||||||
|
limit: z.number().default(10).describe(
|
||||||
|
"Maximum number of emails to return",
|
||||||
|
),
|
||||||
|
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)",
|
||||||
|
),
|
||||||
|
unreadOnly: z.boolean().default(false).describe(
|
||||||
|
"If true, only return unread emails",
|
||||||
|
),
|
||||||
|
query: z.string().optional().describe(
|
||||||
|
"Optional text to search for within the folder",
|
||||||
|
),
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const client = getClient();
|
||||||
|
const maxLimit = 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[] = [];
|
||||||
|
|
||||||
|
if (unreadOnly) {
|
||||||
|
restrictions.push(`\
|
||||||
|
<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>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = await client.findItems(folderId, {
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
baseShape,
|
||||||
|
restriction,
|
||||||
|
});
|
||||||
|
|
||||||
|
const emails = [];
|
||||||
|
for (const item of items) {
|
||||||
|
emails.push(client.extractEmail(item));
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({ emails, count: emails.length }),
|
||||||
|
}],
|
||||||
|
structuredContent: { emails, count: emails.length },
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({ error: error.message ?? String(error) }),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
server.registerTool(
|
||||||
|
"get_email",
|
||||||
|
{
|
||||||
|
description:
|
||||||
|
"Get a single email with full body and details by Exchange ItemId.",
|
||||||
|
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);
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [{ type: "text" as const, text: JSON.stringify(email) }],
|
||||||
|
structuredContent: { emails: [email] },
|
||||||
|
};
|
||||||
|
} 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.",
|
||||||
|
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",
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
outputSchema: z.object({
|
||||||
|
success: z.boolean(),
|
||||||
|
message: z.string().optional(),
|
||||||
|
error: z.string().optional(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
async ({ itemIds, isRead }) => {
|
||||||
|
try {
|
||||||
|
const client = new EwsClient(loadConfig());
|
||||||
|
const responses = await client.updateItems(itemIds, [
|
||||||
|
{ fieldUri: "message:IsRead", value: isRead },
|
||||||
|
]);
|
||||||
|
|
||||||
|
const errors = responses
|
||||||
|
.filter((r: any) => r.ResponseClass === "Error")
|
||||||
|
.map((r: any) => r.MessageText ?? "Unknown error");
|
||||||
|
|
||||||
|
if (errors.length) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({ error: errors.join("; ") }),
|
||||||
|
}],
|
||||||
|
structuredContent: {
|
||||||
|
success: false,
|
||||||
|
error: errors.join("; "),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const status = isRead ? "read" : "unread";
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({
|
||||||
|
success: true,
|
||||||
|
message: `Marked ${itemIds.length} email(s) as ${status}.`,
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
structuredContent: {
|
||||||
|
success: true,
|
||||||
|
message: `Marked ${itemIds.length} email(s) as ${status}.`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({ error: error.message ?? String(error) }),
|
||||||
|
}],
|
||||||
|
structuredContent: {
|
||||||
|
success: false,
|
||||||
|
error: error.message ?? String(error),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
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.",
|
||||||
|
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",
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
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 attachments = email.attachments ?? [];
|
||||||
|
|
||||||
|
const fileAttachments = attachments.filter(
|
||||||
|
(a: any) => a.attachmentId && !a.isInline,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!fileAttachments.length) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({
|
||||||
|
success: true,
|
||||||
|
downloaded: [],
|
||||||
|
count: 0,
|
||||||
|
message: "No downloadable file attachments.",
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
structuredContent: {
|
||||||
|
success: true,
|
||||||
|
downloaded: [],
|
||||||
|
count: 0,
|
||||||
|
message: "No downloadable file attachments.",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.mkdirSync(targetFolder, { recursive: true });
|
||||||
|
|
||||||
|
const downloaded = [];
|
||||||
|
const errors = [];
|
||||||
|
const usedNames = new Set<string>();
|
||||||
|
|
||||||
|
for (const att of fileAttachments) {
|
||||||
|
try {
|
||||||
|
const result = await client.getAttachment(att.attachmentId);
|
||||||
|
let filename = path.basename(result.name);
|
||||||
|
if (!filename) filename = att.name || "attachment";
|
||||||
|
|
||||||
|
const baseName = filename;
|
||||||
|
const dotIdx = baseName.lastIndexOf(".");
|
||||||
|
const namePart = dotIdx > 0 ? baseName.slice(0, dotIdx) : baseName;
|
||||||
|
const extPart = dotIdx > 0 ? baseName.slice(dotIdx) : "";
|
||||||
|
|
||||||
|
let counter = 1;
|
||||||
|
let finalName = filename;
|
||||||
|
while (usedNames.has(finalName.toLowerCase())) {
|
||||||
|
finalName = extPart
|
||||||
|
? `${namePart}_${counter}${extPart}`
|
||||||
|
: `${namePart}_${counter}`;
|
||||||
|
counter++;
|
||||||
|
}
|
||||||
|
usedNames.add(finalName.toLowerCase());
|
||||||
|
|
||||||
|
const filepath = path.join(targetFolder, finalName);
|
||||||
|
fs.writeFileSync(filepath, result.content);
|
||||||
|
|
||||||
|
downloaded.push({
|
||||||
|
name: finalName,
|
||||||
|
path: filepath,
|
||||||
|
size: result.content.length,
|
||||||
|
contentType: result.contentType,
|
||||||
|
});
|
||||||
|
} catch (e: any) {
|
||||||
|
errors.push({
|
||||||
|
name: att.name || "unknown",
|
||||||
|
error: e.message ?? String(e),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({
|
||||||
|
success: errors.length === 0,
|
||||||
|
downloaded,
|
||||||
|
count: downloaded.length,
|
||||||
|
...(errors.length ? { errors } : {}),
|
||||||
|
}),
|
||||||
|
}],
|
||||||
|
structuredContent: errors.length === 0
|
||||||
|
? { success: true, downloaded, count: downloaded.length }
|
||||||
|
: { success: false, downloaded, count: downloaded.length, errors },
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({ error: error.message ?? String(error) }),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
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";
|
||||||
|
|
||||||
|
export function registerFolderTools(server: McpServer): void {
|
||||||
|
server.registerTool(
|
||||||
|
"get_folders",
|
||||||
|
{
|
||||||
|
description: "List mailbox 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)",
|
||||||
|
),
|
||||||
|
recursive: z.boolean().default(false).describe(
|
||||||
|
"If true, recursively traverse all subfolders",
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
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 {
|
||||||
|
const client = new EwsClient(loadConfig());
|
||||||
|
const folders = await client.findFolders(parentFolderId, recursive);
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [{ type: "text" as const, text: JSON.stringify(folders) }],
|
||||||
|
structuredContent: { folders },
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({ error: error.message ?? String(error) }),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
+122
@@ -0,0 +1,122 @@
|
|||||||
|
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";
|
||||||
|
|
||||||
|
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.",
|
||||||
|
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 people = resolutions.map((r: any) => {
|
||||||
|
const mailbox = r.Mailbox ?? {};
|
||||||
|
const contact = r.Contact ?? {};
|
||||||
|
|
||||||
|
const person: any = {
|
||||||
|
name: mailbox.Name ?? contact.DisplayName ?? "",
|
||||||
|
email: mailbox.EmailAddress ?? "",
|
||||||
|
mailboxType: mailbox.MailboxType ?? "",
|
||||||
|
firstName: contact.GivenName ?? "",
|
||||||
|
lastName: contact.Surname ?? "",
|
||||||
|
jobTitle: contact.JobTitle ?? "",
|
||||||
|
department: contact.Department ?? "",
|
||||||
|
company: contact.CompanyName ?? "",
|
||||||
|
office: contact.OfficeLocation ?? "",
|
||||||
|
alias: contact.Alias ?? "",
|
||||||
|
manager: "",
|
||||||
|
managerEmail: "",
|
||||||
|
phones: {},
|
||||||
|
address: "",
|
||||||
|
directReports: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const phones = contact.PhoneNumbers?.PhoneNumber ?? [];
|
||||||
|
const phoneList = Array.isArray(phones) ? phones : [phones];
|
||||||
|
for (const p of phoneList) {
|
||||||
|
if (p?.Key && p?.PhoneNumber) {
|
||||||
|
person.phones[p.Key] = p.PhoneNumber;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const addrs = contact.PhysicalAddresses?.PhysicalAddress ?? [];
|
||||||
|
const addrList = Array.isArray(addrs) ? addrs : [addrs];
|
||||||
|
for (const a of addrList) {
|
||||||
|
if (a?.Key === "Business") {
|
||||||
|
const parts = [a.Street, a.City, a.PostalCode, a.CountryOrRegion]
|
||||||
|
.filter(Boolean);
|
||||||
|
if (parts.length) {
|
||||||
|
person.address = parts.join(", ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const managerData = contact.ManagerMailbox?.Mailbox ?? {};
|
||||||
|
if (managerData.Name || managerData.EmailAddress) {
|
||||||
|
person.manager = managerData.Name ?? "";
|
||||||
|
person.managerEmail = managerData.EmailAddress ?? "";
|
||||||
|
} else if (contact.Manager) {
|
||||||
|
person.manager = contact.Manager;
|
||||||
|
}
|
||||||
|
|
||||||
|
const reports = contact.DirectReports?.DirectReport ?? [];
|
||||||
|
const reportList = Array.isArray(reports) ? reports : [reports];
|
||||||
|
for (const rp of reportList) {
|
||||||
|
if (rp?.Name || rp?.EmailAddress) {
|
||||||
|
person.directReports.push({
|
||||||
|
name: rp.Name ?? "",
|
||||||
|
email: rp.EmailAddress ?? "",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return person;
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [{ type: "text" as const, text: JSON.stringify(people) }],
|
||||||
|
structuredContent: { people },
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{
|
||||||
|
type: "text" as const,
|
||||||
|
text: JSON.stringify({ error: error.message ?? String(error) }),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
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");
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
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