2 Commits

Author SHA1 Message Date
albnnc 057897daf5 chore: formatting 2026-07-11 11:53:17 +03:00
albnnc a6a288103c refactor: drop skill file, rework client 2026-07-11 08:52:55 +00:00
20 changed files with 670 additions and 465 deletions
+30 -273
View File
@@ -1,36 +1,19 @@
import { XMLParser } from "fast-xml-parser"; import { XMLParser } from "fast-xml-parser";
import fs from "node:fs";
import https from "node:https"; import https from "node:https";
import { createRequire } from "node:module"; import { createRequire } from "node:module";
import path from "node:path";
import { promisify } from "node:util"; import { promisify } from "node:util";
import type { Email } from "./types/email.ts"; import { initDataDir } from "../utils/data.ts";
import type { Folder } from "./types/folder.ts"; import { type Email, extractEmail } from "../utils/extract_email.ts";
import type { LoginConfig } from "./types/login_config.ts"; import { extractFolders, type Folder } from "../utils/extract_folder.ts";
import {
let inMemoryPassword: string | null = null; clearConfig,
let dataDir: string = "./data"; getPassword,
hasPassword,
export function initDataDir(dir: string): void { loadConfig,
dataDir = path.resolve(dir); type LoginConfig,
fs.mkdirSync(dataDir, { recursive: true }); saveConfig,
} setPassword,
} from "../utils/login.ts";
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 ntlm: any = createRequire(import.meta.url)("httpntlm");
const postAsync = promisify(ntlm.post.bind(ntlm)); const postAsync = promisify(ntlm.post.bind(ntlm));
@@ -43,13 +26,6 @@ const AGENT = new https.Agent({
secureOptions: SSL_OP_LEGACY_SERVER_CONNECT, secureOptions: SSL_OP_LEGACY_SERVER_CONNECT,
}); });
const PARSER = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: "@_",
removeNSPrefix: true,
textNodeName: "#text",
});
const DISTINGUISHED_FOLDERS: Record<string, string> = { const DISTINGUISHED_FOLDERS: Record<string, string> = {
inbox: "inbox", inbox: "inbox",
"входящие": "inbox", "входящие": "inbox",
@@ -78,30 +54,12 @@ ${body}
</s:Envelope>`; </s:Envelope>`;
} }
function configFilePath(): string { const PARSER = new XMLParser({
return path.join(dataDir, "config.json"); ignoreAttributes: false,
} attributeNamePrefix: "@_",
removeNSPrefix: true,
export function loadConfig(): LoginConfig { textNodeName: "#text",
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 { export class EwsClient {
private config: LoginConfig; private config: LoginConfig;
@@ -110,10 +68,7 @@ export class EwsClient {
constructor(config: LoginConfig, password?: string) { constructor(config: LoginConfig, password?: string) {
this.config = config; this.config = config;
this.ewsUrl = `${config.serverUrl.replace(/\/+$/, "")}/EWS/Exchange.asmx`; this.ewsUrl = `${config.serverUrl.replace(/\/+$/, "")}/EWS/Exchange.asmx`;
if (password) setPassword(password);
if (password) {
setPassword(password);
}
} }
private get domain(): string { private get domain(): string {
@@ -144,8 +99,7 @@ export class EwsClient {
throw new Error(`NTLM request failed, status=${res.statusCode}`); throw new Error(`NTLM request failed, status=${res.statusCode}`);
} }
const parsed = PARSER.parse(res.body); return PARSER.parse(res.body);
return parsed;
} }
private extractResponseMessages(data: any): any[] { private extractResponseMessages(data: any): any[] {
@@ -176,7 +130,8 @@ export class EwsClient {
async getFolderId(folderName: string): Promise<string> { async getFolderId(folderName: string): Promise<string> {
const lower = folderName.toLowerCase(); const lower = folderName.toLowerCase();
const distinguished = DISTINGUISHED_FOLDERS[lower]; const distinguished =
(DISTINGUISHED_FOLDERS as Record<string, string>)[lower];
if (distinguished) { if (distinguished) {
const soap = buildSoapEnvelope(`\ const soap = buildSoapEnvelope(`\
@@ -251,7 +206,8 @@ export class EwsClient {
} = options; } = options;
const isDistinguished = const isDistinguished =
DISTINGUISHED_FOLDERS[folderId.toLowerCase()] !== undefined; (DISTINGUISHED_FOLDERS as Record<string, string>)[folderId.toLowerCase()]
!== undefined;
const folderIdXml = isDistinguished const folderIdXml = isDistinguished
? `<t:DistinguishedFolderId Id="${folderId}"/>` ? `<t:DistinguishedFolderId Id="${folderId}"/>`
@@ -331,208 +287,17 @@ ${restriction}
parentFolderId: string, parentFolderId: string,
recursive: boolean = false, recursive: boolean = false,
): Promise<Folder[]> { ): Promise<Folder[]> {
const traversal = recursive ? "Deep" : "Shallow"; return extractFolders(
const isDistinguished = (body, soapAction) => this.soapRequest(body, soapAction),
DISTINGUISHED_FOLDERS[parentFolderId.toLowerCase()] !== undefined parentFolderId,
|| ["msgfolderroot"].includes(parentFolderId.toLowerCase()); recursive,
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;
} }
extractEmailSummary(item: any): Email { extractEmail(item: any): Email {
const itemType = item["@_xsi_type"] ?? item.__type ?? ""; return extractEmail(item);
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(/&nbsp;/g, " ");
text = text.replace(/&amp;/g, "&");
text = text.replace(/&lt;/g, "<");
text = text.replace(/&gt;/g, ">");
text = text.replace(/&quot;/g, "\"");
text = text.replace(/&#39;/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( async updateItems(
itemIds: string[], itemIds: string[],
updates: { fieldUri: string; value: string | boolean }[], updates: { fieldUri: string; value: string | boolean }[],
@@ -582,8 +347,6 @@ ${changesXml}
return this.extractResponseMessages(data); return this.extractResponseMessages(data);
} }
// ── GetAttachment ───────────────────────────────────────────────────────
async getAttachment( async getAttachment(
attachmentId: string, attachmentId: string,
): Promise<{ content: Buffer; name: string; contentType: string }> { ): Promise<{ content: Buffer; name: string; contentType: string }> {
@@ -617,8 +380,6 @@ ${changesXml}
throw new Error(`Attachment '${attachmentId}' not found`); throw new Error(`Attachment '${attachmentId}' not found`);
} }
// ── FindItem with CalendarView ──────────────────────────────────────────
async findCalendarItems( async findCalendarItems(
folderId: string, folderId: string,
startDate: string, startDate: string,
@@ -650,8 +411,6 @@ ${changesXml}
return []; return [];
} }
// ── GetUserAvailability ─────────────────────────────────────────────────
async getUserAvailability( async getUserAvailability(
emails: string[], emails: string[],
startDate: string, startDate: string,
@@ -699,8 +458,6 @@ ${mailboxDataXml}
return data; return data;
} }
// ── ResolveNames (directory search) ─────────────────────────────────────
async resolveNames( async resolveNames(
query: string, query: string,
fullContact: boolean = true, fullContact: boolean = true,
+1 -1
View File
@@ -4,13 +4,13 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import { Command } from "commander"; import { Command } from "commander";
import crypto from "node:crypto"; import crypto from "node:crypto";
import http from "node:http"; import http from "node:http";
import { initDataDir } from "./ews_client.ts";
import { registerAuthTools } from "./tools/auth.ts"; import { registerAuthTools } from "./tools/auth.ts";
import { registerAvailabilityTools } from "./tools/availability.ts"; import { registerAvailabilityTools } from "./tools/availability.ts";
import { registerCalendarTools } from "./tools/calendar.ts"; import { registerCalendarTools } from "./tools/calendar.ts";
import { registerEmailTools } from "./tools/email.ts"; import { registerEmailTools } from "./tools/email.ts";
import { registerFolderTools } from "./tools/folders.ts"; import { registerFolderTools } from "./tools/folders.ts";
import { registerPeopleTools } from "./tools/people.ts"; import { registerPeopleTools } from "./tools/people.ts";
import { initDataDir } from "./utils/data.ts";
const program = new Command() const program = new Command()
.name("exchange-mcp") .name("exchange-mcp")
+42 -8
View File
@@ -1,14 +1,14 @@
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod/v4"; import { z } from "zod/v4";
import { EwsClient } from "../client/ews_client.ts";
import { import {
clearConfig, clearConfig,
EwsClient,
hasPassword, hasPassword,
loadConfig, loadConfig,
saveConfig, saveConfig,
setPassword, setPassword,
} from "../ews_client.ts"; } from "../utils/login.ts";
import type { LoginConfig } from "../types/login_config.ts"; import { type LoginConfig } from "../utils/login.ts";
export function registerAuthTools(server: McpServer): void { export function registerAuthTools(server: McpServer): void {
server.registerTool( server.registerTool(
@@ -17,15 +17,20 @@ export function registerAuthTools(server: McpServer): void {
description: "Authenticate to Exchange EWS using NTLM credentials." description: "Authenticate to Exchange EWS using NTLM credentials."
+ " On first use all fields except domain are required." + " On first use all fields except domain are required."
+ " On subsequent logins only password is needed — previously saved" + " On subsequent logins only password is needed — previously saved"
+ " serverUrl, email, username, and domain are reused automatically from config." + " serverUrl, email, username, and domain are reused"
+ " Returns {success, message} on success or {success, error} on failure.", + " automatically from config.",
inputSchema: z.object({ inputSchema: z.object({
serverUrl: z.string().optional().describe("Server URL"), serverUrl: z.string().optional().describe("EWS server URL"),
email: z.string().optional().describe("Email address"), email: z.string().optional().describe("Email address"),
username: z.string().optional().describe("NTLM username"), username: z.string().optional().describe("NTLM username"),
password: z.string().describe("NTLM password"), password: z.string().describe("NTLM password"),
domain: z.string().optional().describe("NTLM domain"), 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 }) => { async ({ serverUrl, email, username, password, domain }) => {
try { try {
@@ -103,8 +108,14 @@ export function registerAuthTools(server: McpServer): void {
"check_session", "check_session",
{ {
description: description:
"Check whether the current EWS session is authenticated. No parameters. Returns {authenticated, email, serverUrl} or {authenticated, error}.", "Check whether the current EWS session is authenticated. No parameters.",
inputSchema: z.object({}), inputSchema: z.object({}),
outputSchema: z.object({
authenticated: z.boolean(),
email: z.string().optional(),
serverUrl: z.string().optional(),
error: z.string().optional(),
}),
}, },
async () => { async () => {
try { try {
@@ -117,6 +128,10 @@ export function registerAuthTools(server: McpServer): void {
error: "Not logged in. Password not found in memory.", 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 config = loadConfig();
@@ -133,6 +148,12 @@ export function registerAuthTools(server: McpServer): void {
error: result.error, error: result.error,
}), }),
}], }],
structuredContent: {
authenticated: result.ok,
email: config.email,
serverUrl: config.serverUrl,
error: result.error,
},
}; };
} catch (error: any) { } catch (error: any) {
return { return {
@@ -143,6 +164,10 @@ export function registerAuthTools(server: McpServer): void {
error: error.message ?? String(error), error: error.message ?? String(error),
}), }),
}], }],
structuredContent: {
authenticated: false,
error: error.message ?? String(error),
},
}; };
} }
}, },
@@ -152,8 +177,13 @@ export function registerAuthTools(server: McpServer): void {
"logout", "logout",
{ {
description: description:
"Clear stored credentials (serverUrl, email, username, domain, password). No parameters. Returns {success, message}.", "Clear stored credentials (serverUrl, email, username, domain, password)."
+ " No parameters.",
inputSchema: z.object({}), inputSchema: z.object({}),
outputSchema: z.object({
success: z.boolean(),
message: z.string().optional(),
}),
}, },
async () => { async () => {
clearConfig(); clearConfig();
@@ -165,6 +195,10 @@ export function registerAuthTools(server: McpServer): void {
message: "Logged out. Credentials cleared.", message: "Logged out. Credentials cleared.",
}), }),
}], }],
structuredContent: {
success: true,
message: "Logged out. Credentials cleared.",
},
}; };
}, },
); );
+52 -13
View File
@@ -1,26 +1,38 @@
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod/v4"; import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts"; import { EwsClient } from "../client/ews_client.ts";
import { loadConfig } from "../utils/login.ts";
export function registerAvailabilityTools(server: McpServer): void { export function registerAvailabilityTools(server: McpServer): void {
server.registerTool( server.registerTool(
"find_free_time", "find_free_time",
{ {
description: description: "Find free time slots in your own calendar."
"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. Returns {freeSlots: {date: [{start, end, durationMinutes}]}}. Defaults: durationMinutes=30, startHour=9, endHour=18.", + " Queries your free/busy status and returns available slots"
+ " within working hours that meet the minimum duration.",
inputSchema: z.object({ inputSchema: z.object({
startDate: z.string().describe("Start date in YYYY-MM-DD format"), startDate: z.string().describe("Start date in YYYY-MM-DD format"),
endDate: z.string().optional().describe( endDate: z.string().optional().describe(
"End date in YYYY-MM-DD format. Defaults to startDate", "End date in YYYY-MM-DD format",
), ),
durationMinutes: z.number().default(30).describe( durationMinutes: z.number().default(30).describe(
"Minimum slot duration in minutes. Default: 30", "Minimum slot duration in minutes",
), ),
startHour: z.number().default(9).describe( startHour: z.number().default(9).describe(
"Working day start hour (0-23). Default: 9", "Working day start hour (0-23)",
), ),
endHour: z.number().default(18).describe( endHour: z.number().default(18).describe(
"Working day end hour (0-23). Default: 18", "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(),
})),
), ),
}), }),
}, },
@@ -80,6 +92,7 @@ export function registerAvailabilityTools(server: McpServer): void {
type: "text" as const, type: "text" as const,
text: JSON.stringify({ freeSlots }), text: JSON.stringify({ freeSlots }),
}], }],
structuredContent: { freeSlots },
}; };
} catch (error: any) { } catch (error: any) {
return { return {
@@ -95,24 +108,45 @@ export function registerAvailabilityTools(server: McpServer): void {
server.registerTool( server.registerTool(
"find_meeting_time", "find_meeting_time",
{ {
description: description: "Find common free time for multiple attendees."
"Find common free time for multiple attendees. Queries free/busy for all attendees and returns slots where everyone is available. Returns {period, attendees, freeSlots}. Defaults: durationMinutes=30, startHour=9, endHour=18.", + " Queries free/busy for all attendees"
+ " and returns slots where everyone is available.",
inputSchema: z.object({ inputSchema: z.object({
emails: z.string().describe( emails: z.string().describe(
"Comma-separated email addresses of attendees", "Comma-separated email addresses of attendees",
), ),
startDate: z.string().describe("Start date in YYYY-MM-DD format"), startDate: z.string().describe("Start date in YYYY-MM-DD format"),
endDate: z.string().optional().describe( endDate: z.string().optional().describe(
"End date in YYYY-MM-DD format. Defaults to startDate", "End date in YYYY-MM-DD format",
), ),
durationMinutes: z.number().default(30).describe( durationMinutes: z.number().default(30).describe(
"Minimum slot duration in minutes. Default: 30", "Minimum slot duration in minutes",
), ),
startHour: z.number().default(9).describe( startHour: z.number().default(9).describe(
"Working day start hour (0-23). Default: 9", "Working day start hour (0-23)",
), ),
endHour: z.number().default(18).describe( endHour: z.number().default(18).describe(
"Working day end hour (0-23). Default: 18", "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(),
})),
), ),
}), }),
}, },
@@ -194,6 +228,11 @@ export function registerAvailabilityTools(server: McpServer): void {
freeSlots: freeByDate, freeSlots: freeByDate,
}), }),
}], }],
structuredContent: {
period: { start: startDate, end: ed },
attendees: attendeeInfo,
freeSlots: freeByDate,
},
}; };
} catch (error: any) { } catch (error: any) {
return { return {
+57 -8
View File
@@ -2,21 +2,43 @@ import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import fs from "node:fs"; import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { z } from "zod/v4"; import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts"; import { EwsClient } from "../client/ews_client.ts";
import { loadConfig } from "../utils/login.ts";
export function registerCalendarTools(server: McpServer): void { export function registerCalendarTools(server: McpServer): void {
server.registerTool( server.registerTool(
"get_calendar_events", "get_calendar_events",
{ {
description: description: "Get calendar events within a date range."
"Get calendar events within a date range. Set includeBody=true to fetch organizer, attendees, and body via GetItem. Returns {events, count}.", + " Set includeBody=true to fetch organizer, attendees, and body via GetItem.",
inputSchema: z.object({ inputSchema: z.object({
startDate: z.string().describe("Start date in YYYY-MM-DD format"), startDate: z.string().describe("Start date in YYYY-MM-DD format"),
endDate: z.string().describe("End date in YYYY-MM-DD format"), endDate: z.string().describe("End date in YYYY-MM-DD format"),
includeBody: z.boolean().default(false).describe( includeBody: z.boolean().default(false).describe(
"If true, fetch full event details (organizer, attendees, body) via GetItem. Default: false", "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 }) => { async ({ startDate, endDate, includeBody }) => {
try { try {
@@ -52,7 +74,7 @@ export function registerCalendarTools(server: McpServer): void {
}; };
if (includeBody && event.itemId) { if (includeBody && event.itemId) {
const details = client.extractEmailDetails(item); const details = client.extractEmail(item);
event.body = details.body; event.body = details.body;
event.requiredAttendees = details.requiredAttendees ?? []; event.requiredAttendees = details.requiredAttendees ?? [];
event.optionalAttendees = details.optionalAttendees ?? []; event.optionalAttendees = details.optionalAttendees ?? [];
@@ -69,6 +91,7 @@ export function registerCalendarTools(server: McpServer): void {
type: "text" as const, type: "text" as const,
text: JSON.stringify({ events, count: events.length }), text: JSON.stringify({ events, count: events.length }),
}], }],
structuredContent: { events, count: events.length },
}; };
} catch (error: any) { } catch (error: any) {
return { return {
@@ -85,21 +108,38 @@ export function registerCalendarTools(server: McpServer): void {
"download_event_attachments", "download_event_attachments",
{ {
description: description:
"Download all file attachments from a calendar event to disk. Inline (embedded) attachments are skipped — only standalone file attachments are downloaded. Returns {success, downloaded, count} or {success, downloaded, count, errors}.", "Download all file attachments from a calendar event to disk."
+ " Inline (embedded) attachments are skipped —"
+ " only standalone file attachments are downloaded.",
inputSchema: z.object({ inputSchema: z.object({
itemId: z.string().describe( itemId: z.string().describe(
"The Exchange ItemId of the calendar event", "The Exchange ItemId of the calendar event",
), ),
targetFolder: z.string().default("/tmp/attachments").describe( targetFolder: z.string().default("/tmp/attachments").describe(
"Local directory to save files. Default: /tmp/attachments", "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 }) => { async ({ itemId, targetFolder }) => {
try { try {
const client = new EwsClient(loadConfig()); const client = new EwsClient(loadConfig());
const item = await client.getItem(itemId); const item = await client.getItem(itemId);
const email = client.extractEmailDetails(item); const email = client.extractEmail(item);
const attachments = email.attachments ?? []; const attachments = email.attachments ?? [];
const fileAttachments = attachments.filter( const fileAttachments = attachments.filter(
@@ -117,6 +157,12 @@ export function registerCalendarTools(server: McpServer): void {
message: "No downloadable file attachments.", message: "No downloadable file attachments.",
}), }),
}], }],
structuredContent: {
success: true,
downloaded: [],
count: 0,
message: "No downloadable file attachments.",
},
}; };
} }
@@ -174,6 +220,9 @@ export function registerCalendarTools(server: McpServer): void {
...(errors.length ? { errors } : {}), ...(errors.length ? { errors } : {}),
}), }),
}], }],
structuredContent: errors.length === 0
? { success: true, downloaded, count: downloaded.length }
: { success: false, downloaded, count: downloaded.length, errors },
}; };
} catch (error: any) { } catch (error: any) {
return { return {
+105 -58
View File
@@ -2,7 +2,8 @@ import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import fs from "node:fs"; import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { z } from "zod/v4"; import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts"; import { EwsClient } from "../client/ews_client.ts";
import { loadConfig } from "../utils/login.ts";
function getClient(): EwsClient { function getClient(): EwsClient {
return new EwsClient(loadConfig()); return new EwsClient(loadConfig());
@@ -12,34 +13,41 @@ export function registerEmailTools(server: McpServer): void {
server.registerTool( server.registerTool(
"get_emails", "get_emails",
{ {
description: description: "Get emails from a mailbox folder."
"Get emails from a mailbox folder. Supports optional text search via query/queryScope. Returns {emails, count} or {itemIds, count} if idsOnly. Defaults: folder=Inbox, limit=10, offset=0, includeBody=false, unreadOnly=false, idsOnly=false, queryScope=all. Note: idsOnly raises the limit to 500.", + " Supports optional text search via query/queryScope.",
inputSchema: z.object({ inputSchema: z.object({
folder: z.string().default("Inbox").describe( 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)."
+ " Supports Russian folder names",
), ),
limit: z.number().default(10).describe( limit: z.number().default(10).describe(
"Maximum number of emails to return. Default: 10. Max 50 (max 500 if idsOnly=true)", "Maximum number of emails to return",
), ),
offset: z.number().default(0).describe( offset: z.number().default(0).describe(
"Number of emails to skip for pagination. Default: 0", "Number of emails to skip for pagination",
), ),
includeBody: z.boolean().default(false).describe( includeBody: z.boolean().default(false).describe(
"If true, fetches full email body for each email (slower). Default: false", "If true, fetches full email body for each email (slower)",
), ),
unreadOnly: z.boolean().default(false).describe( unreadOnly: z.boolean().default(false).describe(
"If true, only return unread emails. Default: false", "If true, only return unread emails",
),
idsOnly: z.boolean().default(false).describe(
"If true, return only item IDs, dates, and subjects — faster with higher limit of 500. Default: false",
), ),
query: z.string().optional().describe( query: z.string().optional().describe(
"Optional text to search for within the folder", "Optional text to search for within the folder",
), ),
queryScope: z.enum(["all", "subject", "body", "from"]).default("all") queryScope: z.enum(["all", "subject", "body", "from"]).default("all")
.describe( .describe("Search scope: all, subject, body, or from"),
"Scope for text search. Values: all (subject+body), subject, body, from. Only used when query is set. Default: all", }),
), 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 ( async (
@@ -49,19 +57,18 @@ export function registerEmailTools(server: McpServer): void {
offset, offset,
includeBody, includeBody,
unreadOnly, unreadOnly,
idsOnly,
query, query,
queryScope, queryScope,
}, },
) => { ) => {
try { try {
const client = getClient(); const client = getClient();
const maxLimit = idsOnly ? 500 : 50; const maxLimit = 50;
if (limit > maxLimit) limit = maxLimit; if (limit > maxLimit) limit = maxLimit;
offset = Math.max(0, offset); offset = Math.max(0, offset);
const folderId = await client.getFolderId(folder); const folderId = await client.getFolderId(folder);
const baseShape = idsOnly ? "IdOnly" : "AllProperties"; const baseShape = "AllProperties";
if (query && !query.trim()) query = undefined; if (query && !query.trim()) query = undefined;
@@ -112,16 +119,16 @@ export function registerEmailTools(server: McpServer): void {
let restriction = ""; let restriction = "";
if (restrictions.length === 1) { if (restrictions.length === 1) {
restriction = `\ restriction = `\
<m:Restriction> <m:Restriction>
${restrictions[0]} ${restrictions[0]}
</m:Restriction>`; </m:Restriction>`;
} else if (restrictions.length > 1) { } else if (restrictions.length > 1) {
restriction = `\ restriction = `\
<m:Restriction> <m:Restriction>
<t:And> <t:And>
${restrictions.join("\n")} ${restrictions.join("\n")}
</t:And> </t:And>
</m:Restriction>`; </m:Restriction>`;
} }
const items = await client.findItems(folderId, { const items = await client.findItems(folderId, {
@@ -131,33 +138,9 @@ export function registerEmailTools(server: McpServer): void {
restriction, 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 = []; const emails = [];
for (const item of items) { for (const item of items) {
const email = client.extractEmailSummary(item); emails.push(client.extractEmail(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 { return {
@@ -165,6 +148,7 @@ export function registerEmailTools(server: McpServer): void {
type: "text" as const, type: "text" as const,
text: JSON.stringify({ emails, count: emails.length }), text: JSON.stringify({ emails, count: emails.length }),
}], }],
structuredContent: { emails, count: emails.length },
}; };
} catch (error: any) { } catch (error: any) {
return { return {
@@ -181,21 +165,42 @@ export function registerEmailTools(server: McpServer): void {
"get_email", "get_email",
{ {
description: description:
"Get a single email with full body and details by Exchange ItemId. Returns the full Email object (subject, from, to, cc, body, date, attachments, etc.).", "Get a single email with full body and details by Exchange ItemId.",
inputSchema: z.object({ inputSchema: z.object({
itemId: z.string().describe( itemId: z.string().describe(
"The Exchange ItemId of the email to retrieve", "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 }) => { async ({ itemId }) => {
try { try {
const client = getClient(); const client = getClient();
const item = await client.getItem(itemId); const item = await client.getItem(itemId);
const email = client.extractEmailDetails(item); const email = client.extractEmail(item);
return { return {
content: [{ type: "text" as const, text: JSON.stringify(email) }], content: [{ type: "text" as const, text: JSON.stringify(email) }],
structuredContent: { emails: [email] },
}; };
} catch (error: any) { } catch (error: any) {
return { return {
@@ -212,15 +217,20 @@ export function registerEmailTools(server: McpServer): void {
"mark_email_read", "mark_email_read",
{ {
description: description:
"Mark one or more emails as read or unread by their Exchange ItemIds. Returns {success, message} or {error}.", "Mark one or more emails as read or unread by their Exchange ItemIds.",
inputSchema: z.object({ inputSchema: z.object({
itemIds: z.array(z.string()).describe( itemIds: z.array(z.string()).describe(
"List of Exchange ItemIds to update", "List of Exchange ItemIds to update",
), ),
isRead: z.boolean().default(true).describe( isRead: z.boolean().default(true).describe(
"True to mark as read, false to mark as unread. Default: true", "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 }) => { async ({ itemIds, isRead }) => {
try { try {
@@ -239,6 +249,10 @@ export function registerEmailTools(server: McpServer): void {
type: "text" as const, type: "text" as const,
text: JSON.stringify({ error: errors.join("; ") }), text: JSON.stringify({ error: errors.join("; ") }),
}], }],
structuredContent: {
success: false,
error: errors.join("; "),
},
}; };
} }
@@ -251,6 +265,10 @@ export function registerEmailTools(server: McpServer): void {
message: `Marked ${itemIds.length} email(s) as ${status}.`, message: `Marked ${itemIds.length} email(s) as ${status}.`,
}), }),
}], }],
structuredContent: {
success: true,
message: `Marked ${itemIds.length} email(s) as ${status}.`,
},
}; };
} catch (error: any) { } catch (error: any) {
return { return {
@@ -258,6 +276,10 @@ export function registerEmailTools(server: McpServer): void {
type: "text" as const, type: "text" as const,
text: JSON.stringify({ error: error.message ?? String(error) }), text: JSON.stringify({ error: error.message ?? String(error) }),
}], }],
structuredContent: {
success: false,
error: error.message ?? String(error),
},
}; };
} }
}, },
@@ -266,20 +288,36 @@ export function registerEmailTools(server: McpServer): void {
server.registerTool( server.registerTool(
"download_attachments", "download_attachments",
{ {
description: description: "Download all file attachments from an email to disk."
"Download all file attachments from an email to disk. Inline (embedded) attachments are skipped — only standalone file attachments are downloaded. Returns {success, downloaded, count} or {success, downloaded, count, errors}.", + " Inline (embedded) attachments are skipped —"
+ " only standalone file attachments are downloaded.",
inputSchema: z.object({ inputSchema: z.object({
itemId: z.string().describe("The Exchange ItemId of the email"), itemId: z.string().describe("The Exchange ItemId of the email"),
targetFolder: z.string().default("/tmp/attachments").describe( targetFolder: z.string().default("/tmp/attachments").describe(
"Local directory to save files. Default: /tmp/attachments", "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 }) => { async ({ itemId, targetFolder }) => {
try { try {
const client = new EwsClient(loadConfig()); const client = new EwsClient(loadConfig());
const item = await client.getItem(itemId); const item = await client.getItem(itemId);
const email = client.extractEmailDetails(item); const email = client.extractEmail(item);
const attachments = email.attachments ?? []; const attachments = email.attachments ?? [];
const fileAttachments = attachments.filter( const fileAttachments = attachments.filter(
@@ -297,6 +335,12 @@ export function registerEmailTools(server: McpServer): void {
message: "No downloadable file attachments.", message: "No downloadable file attachments.",
}), }),
}], }],
structuredContent: {
success: true,
downloaded: [],
count: 0,
message: "No downloadable file attachments.",
},
}; };
} }
@@ -354,6 +398,9 @@ export function registerEmailTools(server: McpServer): void {
...(errors.length ? { errors } : {}), ...(errors.length ? { errors } : {}),
}), }),
}], }],
structuredContent: errors.length === 0
? { success: true, downloaded, count: downloaded.length }
: { success: false, downloaded, count: downloaded.length, errors },
}; };
} catch (error: any) { } catch (error: any) {
return { return {
+16 -5
View File
@@ -1,21 +1,31 @@
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod/v4"; import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts"; import { EwsClient } from "../client/ews_client.ts";
import { loadConfig } from "../utils/login.ts";
export function registerFolderTools(server: McpServer): void { export function registerFolderTools(server: McpServer): void {
server.registerTool( server.registerTool(
"get_folders", "get_folders",
{ {
description: description: "List mailbox folders from the Exchange mailbox.",
"List mailbox folders from the Exchange mailbox. Returns a list of Folder objects (name, id, totalCount, unreadCount, childFolderCount).",
inputSchema: z.object({ inputSchema: z.object({
parentFolderId: z.string().default("msgfolderroot").describe( parentFolderId: z.string().default("msgfolderroot").describe(
"Parent folder to list children of. Supports distinguished names (e.g. inbox, calendar). Default: msgfolderroot", "Parent folder to list children of."
+ " Supports distinguished names (e.g. inbox, calendar)",
), ),
recursive: z.boolean().default(false).describe( recursive: z.boolean().default(false).describe(
"If true, recursively traverse all subfolders. Default: false", "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 }) => { async ({ parentFolderId, recursive }) => {
try { try {
@@ -24,6 +34,7 @@ export function registerFolderTools(server: McpServer): void {
return { return {
content: [{ type: "text" as const, text: JSON.stringify(folders) }], content: [{ type: "text" as const, text: JSON.stringify(folders) }],
structuredContent: { folders },
}; };
} catch (error: any) { } catch (error: any) {
return { return {
+26 -3
View File
@@ -1,23 +1,45 @@
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod/v4"; import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts"; import { EwsClient } from "../client/ews_client.ts";
import { loadConfig } from "../utils/login.ts";
export function registerPeopleTools(server: McpServer): void { export function registerPeopleTools(server: McpServer): void {
server.registerTool( server.registerTool(
"find_person", "find_person",
{ {
description: description:
"Search for people in the corporate directory (Active Directory) by name, email, or keyword. Returns a list of Person objects with name, email, jobTitle, department, company, office, phones, manager, directReports, and more.", "Search for people in the corporate directory (Active Directory)"
+ " by name, email, or keyword.",
inputSchema: z.object({ inputSchema: z.object({
query: z.string().describe( query: z.string().describe(
"Name, email address, or keyword to search for", "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 }) => { async ({ query }) => {
try { try {
const client = new EwsClient(loadConfig()); const client = new EwsClient(loadConfig());
const resolutions = await client.resolveNames(query, true); const resolutions = await client.resolveNames(query);
const people = resolutions.map((r: any) => { const people = resolutions.map((r: any) => {
const mailbox = r.Mailbox ?? {}; const mailbox = r.Mailbox ?? {};
@@ -85,6 +107,7 @@ export function registerPeopleTools(server: McpServer): void {
return { return {
content: [{ type: "text" as const, text: JSON.stringify(people) }], content: [{ type: "text" as const, text: JSON.stringify(people) }],
structuredContent: { people },
}; };
} catch (error: any) { } catch (error: any) {
return { return {
-17
View File
@@ -1,17 +0,0 @@
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[];
}
-32
View File
@@ -1,32 +0,0 @@
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;
}
-7
View File
@@ -1,7 +0,0 @@
export interface Folder {
name: string;
id: string;
totalCount: number;
unreadCount: number;
childFolderCount: number;
}
-6
View File
@@ -1,6 +0,0 @@
export interface FreeSlot {
date: string;
start: string;
end: string;
durationMinutes: number;
}
-6
View File
@@ -1,6 +0,0 @@
export interface LoginConfig {
serverUrl: string;
email: string;
username: string;
domain?: string;
}
-11
View File
@@ -1,11 +0,0 @@
export interface MeetingResult {
success: boolean;
subject: string;
date: string;
startTime: string;
endTime: string;
location: string;
requiredAttendees: string[];
optionalAttendees: string[];
error: string;
}
-17
View File
@@ -1,17 +0,0 @@
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 }>;
}
+13
View File
@@ -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");
}
+156
View File
@@ -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;
}
+101
View File
@@ -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;
}
+20
View File
@@ -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(/&nbsp;/g, " ");
text = text.replace(/&amp;/g, "&");
text = text.replace(/&lt;/g, "<");
text = text.replace(/&gt;/g, ">");
text = text.replace(/&quot;/g, "\"");
text = text.replace(/&#39;/g, "'");
text = text.replace(/\n\s*\n/g, "\n\n");
text = text.replace(/[ \t]+/g, " ");
return text.trim();
}
+51
View File
@@ -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();
}