7 Commits

Author SHA1 Message Date
albnnc bafe299249 w 2026-07-09 09:41:53 +03:00
albnnc 66b1fa0ecc w 2026-07-09 09:41:01 +03:00
albnnc 147b774e44 w 2026-07-09 09:35:22 +03:00
albnnc a79db30ea9 w 2026-07-09 09:21:04 +03:00
albnnc d517162081 w 2026-07-09 09:08:39 +03:00
albnnc d09b6145d2 w 2026-07-09 09:06:46 +03:00
albnnc 43821c791c w 2026-07-09 09:02:22 +03:00
17 changed files with 379 additions and 699 deletions
+5
View File
@@ -0,0 +1,5 @@
FROM node:26-slim
WORKDIR /app
COPY . .
RUN npm install
CMD ["npm", "start"]
+73 -22
View File
@@ -1,11 +1,31 @@
import { XMLParser } from "fast-xml-parser";
import { promisify } from "node:util";
import { createRequire } from "node:module";
import https from "node:https";
import fs from "node:fs";
import https from "node:https";
import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { Email, Folder, LoginConfig } from "./models.ts";
import { promisify } from "node:util";
import type { Email } from "./types/email.ts";
import type { Folder } from "./types/folder.ts";
import type { LoginConfig } from "./types/login_config.ts";
let inMemoryPassword: string | null = null;
export function setPassword(password: string): void {
inMemoryPassword = password;
}
export function getPassword(): string | null {
return inMemoryPassword;
}
export function hasPassword(): boolean {
return inMemoryPassword !== null;
}
export function clearPassword(): void {
inMemoryPassword = null;
}
const ntlm: any = createRequire(import.meta.url)("httpntlm");
const postAsync = promisify(ntlm.post.bind(ntlm));
@@ -76,27 +96,38 @@ export function clearConfig(): void {
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
clearPassword();
}
export class EwsClient {
private config: LoginConfig;
private ewsUrl: string;
constructor(config: LoginConfig) {
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 async soapRequest(body: string, soapAction: string): Promise<any> {
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.config.password,
password: this.password,
agent: AGENT,
headers: {
"Content-Type": "text/xml; charset=utf-8",
@@ -154,7 +185,7 @@ private async soapRequest(body: string, soapAction: string): Promise<any> {
</m:FolderIds>
</m:GetFolder>`);
const data = await this.soapRequest(
const data = await this.soapRequest(
soap,
"http://schemas.microsoft.com/exchange/services/2006/messages/GetFolder",
);
@@ -238,7 +269,8 @@ ${restriction}
);
for (const msg of this.extractResponseMessages(data)) {
const items = msg?.RootFolder?.Items?.Message ?? msg?.RootFolder?.Items?.CalendarItem;
const items = msg?.RootFolder?.Items?.Message
?? msg?.RootFolder?.Items?.CalendarItem;
if (!items) continue;
return Array.isArray(items) ? items : [items];
}
@@ -268,7 +300,13 @@ ${restriction}
if (!items) continue;
const itemKey = Object.keys(items).find((k) =>
["Message", "CalendarItem", "MeetingRequest", "MeetingResponse", "MeetingCancellation"].includes(k)
[
"Message",
"CalendarItem",
"MeetingRequest",
"MeetingResponse",
"MeetingCancellation",
].includes(k)
);
if (itemKey) {
return items[itemKey];
@@ -283,7 +321,8 @@ ${restriction}
recursive: boolean = false,
): Promise<Folder[]> {
const traversal = recursive ? "Deep" : "Shallow";
const isDistinguished = DISTINGUISHED_FOLDERS[parentFolderId.toLowerCase()] !== undefined
const isDistinguished =
DISTINGUISHED_FOLDERS[parentFolderId.toLowerCase()] !== undefined
|| ["msgfolderroot"].includes(parentFolderId.toLowerCase());
const folderIdXml = isDistinguished
@@ -329,7 +368,10 @@ ${restriction}
extractEmailSummary(item: any): Email {
const itemType = item["@_xsi_type"] ?? item.__type ?? "";
const isMeeting = /MeetingRequest|MeetingResponse|MeetingCancellation|CalendarItem/i.test(itemType);
const isMeeting =
/MeetingRequest|MeetingResponse|MeetingCancellation|CalendarItem/i.test(
itemType,
);
const fromMailbox = item.From?.Mailbox
?? item.Organizer?.Mailbox
@@ -340,9 +382,11 @@ ${restriction}
subject: item.Subject ?? "(No subject)",
from: fromMailbox.EmailAddress ?? "",
fromName: fromMailbox.Name ?? "",
date: item.DateTimeSent ?? item.DateTimeReceived ?? item.DateTimeCreated ?? "",
date: item.DateTimeSent ?? item.DateTimeReceived ?? item.DateTimeCreated
?? "",
isRead: item.IsRead === "true" || item.IsRead === true,
hasAttachments: item.HasAttachments === "true" || item.HasAttachments === true,
hasAttachments: item.HasAttachments === "true"
|| item.HasAttachments === true,
hasLinks: false,
itemId: item.ItemId?.["@_Id"] ?? "",
size: item.Size ? Number(item.Size) : 0,
@@ -357,15 +401,20 @@ ${restriction}
};
if (item.DisplayTo) {
email.to = item.DisplayTo.split(";").map((t: string) => t.trim()).filter(Boolean);
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);
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.start = item.Start ?? item.StartWallClock ?? item.ReminderDueBy
?? "";
email.end = item.End ?? item.EndWallClock ?? "";
}
@@ -416,11 +465,13 @@ ${restriction}
isInline: a.IsInline === "true" || a.IsInline === true,
}));
const isMeeting = /MeetingRequest|MeetingResponse|MeetingCancellation|CalendarItem/i.test(
item["@_xsi_type"] ?? "",
);
const isMeeting =
/MeetingRequest|MeetingResponse|MeetingCancellation|CalendarItem/i.test(
item["@_xsi_type"] ?? "",
);
if (isMeeting) {
email.location = item.Location ?? item.EnhancedLocation?.DisplayName ?? "";
email.location = item.Location ?? item.EnhancedLocation?.DisplayName
?? "";
email.start = item.Start ?? "";
email.end = item.End ?? "";
@@ -462,7 +513,7 @@ ${restriction}
text = text.replace(/&amp;/g, "&");
text = text.replace(/&lt;/g, "<");
text = text.replace(/&gt;/g, ">");
text = text.replace(/&quot;/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, " ");
+15 -7
View File
@@ -1,9 +1,9 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { Command } from "commander";
import http from "node:http";
import crypto from "node:crypto";
import http from "node:http";
import { registerAuthTools } from "./tools/auth.ts";
import { registerEmailTools } from "./tools/email.ts";
import { registerFolderTools } from "./tools/folders.ts";
@@ -12,7 +12,10 @@ const program = new Command()
.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(
"--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");
@@ -55,7 +58,10 @@ async function runSSE() {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type, Authorization",
);
if (req.method === "OPTIONS") {
res.writeHead(200);
@@ -66,7 +72,7 @@ async function runSSE() {
const url = new URL(req.url || "/", `http://${req.headers.host}`);
if (req.method === "GET") {
const transport = new SSEServerTransport("/message", res);
const transport = new SSEServerTransport("/sse", res);
const server = buildServer();
await server.connect(transport);
@@ -77,7 +83,7 @@ async function runSSE() {
return;
}
if (req.method === "POST" && url.pathname === "/message") {
if (req.method === "POST" && url.pathname === "/sse") {
const sessionId = url.searchParams.get("sessionId") || "";
const transport = transports.get(sessionId);
if (!transport) {
@@ -113,7 +119,9 @@ async function main() {
await runSSE();
break;
default:
console.error(`Unsupported transport: "${transportType}". Use "stdio" or "sse".`);
console.error(
`Unsupported transport: "${transportType}". Use "stdio" or "sse".`,
);
process.exit(1);
}
}
-103
View File
@@ -1,103 +0,0 @@
export interface LoginConfig {
serverUrl: string;
email: string;
username: string;
password: string;
domain?: string;
}
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;
}
export interface Folder {
name: string;
id: string;
totalCount: number;
unreadCount: number;
childFolderCount: number;
}
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 }>;
}
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[];
}
export interface FreeSlot {
date: string;
start: string;
end: string;
durationMinutes: number;
}
export interface MeetingResult {
success: boolean;
subject: string;
date: string;
startTime: string;
endTime: string;
location: string;
requiredAttendees: string[];
optionalAttendees: string[];
error: string;
}
-519
View File
@@ -16,452 +16,9 @@
},
"devDependencies": {
"@types/node": "^22.20.1",
"tsx": "^4.23.0",
"typescript": "^5.9.3"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
"integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",
"integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",
"integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",
"integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",
"integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",
"integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",
"integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",
"integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",
"integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",
"integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",
"integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",
"integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",
"integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",
"integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",
"integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",
"integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",
"integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",
"integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",
"integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",
"integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",
"integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",
"integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",
"integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",
"integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",
"integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",
"integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@hono/node-server": {
"version": "1.19.14",
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",
@@ -844,48 +401,6 @@
"node": ">= 0.4"
}
},
"node_modules/esbuild": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
"integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.1",
"@esbuild/android-arm": "0.28.1",
"@esbuild/android-arm64": "0.28.1",
"@esbuild/android-x64": "0.28.1",
"@esbuild/darwin-arm64": "0.28.1",
"@esbuild/darwin-x64": "0.28.1",
"@esbuild/freebsd-arm64": "0.28.1",
"@esbuild/freebsd-x64": "0.28.1",
"@esbuild/linux-arm": "0.28.1",
"@esbuild/linux-arm64": "0.28.1",
"@esbuild/linux-ia32": "0.28.1",
"@esbuild/linux-loong64": "0.28.1",
"@esbuild/linux-mips64el": "0.28.1",
"@esbuild/linux-ppc64": "0.28.1",
"@esbuild/linux-riscv64": "0.28.1",
"@esbuild/linux-s390x": "0.28.1",
"@esbuild/linux-x64": "0.28.1",
"@esbuild/netbsd-arm64": "0.28.1",
"@esbuild/netbsd-x64": "0.28.1",
"@esbuild/openbsd-arm64": "0.28.1",
"@esbuild/openbsd-x64": "0.28.1",
"@esbuild/openharmony-arm64": "0.28.1",
"@esbuild/sunos-x64": "0.28.1",
"@esbuild/win32-arm64": "0.28.1",
"@esbuild/win32-ia32": "0.28.1",
"@esbuild/win32-x64": "0.28.1"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
@@ -1083,21 +598,6 @@
"node": ">= 0.8"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
@@ -1768,25 +1268,6 @@
"node": ">=0.6"
}
},
"node_modules/tsx": {
"version": "4.23.0",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.0.tgz",
"integrity": "sha512-eUdUIaCr963q2h5u3+QwvYp0+eqPvn+egeqZUm0hwERCqqx1E3kK5ehbGCvqSE5MQAULr67ww0cA3jKc3YkM1w==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.28.0"
},
"bin": {
"tsx": "dist/cli.mjs"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
}
},
"node_modules/type-is": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
+1 -2
View File
@@ -3,7 +3,7 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"start": "tsx main.ts",
"start": "node main.ts",
"format": "dprint fmt"
},
"dependencies": {
@@ -15,7 +15,6 @@
},
"devDependencies": {
"@types/node": "^22.20.1",
"tsx": "^4.23.0",
"typescript": "^5.9.3"
}
}
+59 -10
View File
@@ -1,6 +1,13 @@
import { z } from "zod/v4";
import { EwsClient, loadConfig, saveConfig, clearConfig } from "../ews_client.ts";
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod/v4";
import {
clearConfig,
EwsClient,
hasPassword,
loadConfig,
saveConfig,
setPassword,
} from "../ews_client.ts";
export function registerAuthTools(server: McpServer): void {
server.registerTool(
@@ -8,7 +15,9 @@ export function registerAuthTools(server: McpServer): void {
{
description: "Authenticate to Exchange EWS using NTLM credentials",
inputSchema: z.object({
serverUrl: z.string().describe("EWS server URL (e.g. https://mail.example.com)"),
serverUrl: z.string().describe(
"EWS server URL (e.g. https://mail.example.com)",
),
email: z.string().describe("Email address"),
username: z.string().describe("NTLM username"),
password: z.string().describe("NTLM password"),
@@ -21,27 +30,44 @@ export function registerAuthTools(server: McpServer): void {
serverUrl: serverUrl.replace(/\/+$/, ""),
email,
username,
password,
domain: domain ?? "corp",
};
const client = new EwsClient(config);
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" }) }],
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}` }) }],
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) }) }],
content: [{
type: "text" as const,
text: JSON.stringify({
success: false,
error: error.message ?? String(error),
}),
}],
};
}
},
@@ -55,6 +81,17 @@ export function registerAuthTools(server: McpServer): void {
},
async () => {
try {
if (!hasPassword()) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({
authenticated: false,
error: "Not logged in. Password not found in memory.",
}),
}],
};
}
const config = loadConfig();
const client = new EwsClient(config);
const result = await client.verifyConnection();
@@ -72,7 +109,13 @@ export function registerAuthTools(server: McpServer): void {
};
} catch (error: any) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ authenticated: false, error: error.message ?? String(error) }) }],
content: [{
type: "text" as const,
text: JSON.stringify({
authenticated: false,
error: error.message ?? String(error),
}),
}],
};
}
},
@@ -87,7 +130,13 @@ export function registerAuthTools(server: McpServer): void {
async () => {
clearConfig();
return {
content: [{ type: "text" as const, text: JSON.stringify({ success: true, message: "Logged out. Credentials cleared." }) }],
content: [{
type: "text" as const,
text: JSON.stringify({
success: true,
message: "Logged out. Credentials cleared.",
}),
}],
};
},
);
+113 -26
View File
@@ -1,6 +1,6 @@
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts";
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
function getClient(): EwsClient {
return new EwsClient(loadConfig());
@@ -12,12 +12,24 @@ export function registerEmailTools(server: McpServer): void {
{
description: "Get emails from a mailbox folder",
inputSchema: z.object({
folder: z.string().default("Inbox").describe("Folder name (Inbox, Sent, Drafts, Deleted, Junk, or custom)"),
limit: z.number().default(10).describe("Maximum number of emails to return (default 10, max 50)"),
offset: z.number().default(0).describe("Number of emails to skip for pagination"),
includeBody: z.boolean().default(false).describe("If True, fetch full body for each email (slower)"),
unreadOnly: z.boolean().default(false).describe("If True, only return unread emails"),
idsOnly: z.boolean().default(false).describe("If True, return only item IDs and dates (max limit 500)"),
folder: z.string().default("Inbox").describe(
"Folder name (Inbox, Sent, Drafts, Deleted, Junk, or custom)",
),
limit: z.number().default(10).describe(
"Maximum number of emails to return (default 10, max 50)",
),
offset: z.number().default(0).describe(
"Number of emails to skip for pagination",
),
includeBody: z.boolean().default(false).describe(
"If True, fetch full body for each email (slower)",
),
unreadOnly: z.boolean().default(false).describe(
"If True, only return unread emails",
),
idsOnly: z.boolean().default(false).describe(
"If True, return only item IDs and dates (max limit 500)",
),
}),
},
async ({ folder, limit, offset, includeBody, unreadOnly, idsOnly }) => {
@@ -42,7 +54,12 @@ export function registerEmailTools(server: McpServer): void {
</m:Restriction>`;
}
const items = await client.findItems(folderId, { limit, offset, baseShape, restriction });
const items = await client.findItems(folderId, {
limit,
offset,
baseShape,
restriction,
});
if (idsOnly) {
const result = items.map((item: any) => ({
@@ -51,7 +68,10 @@ export function registerEmailTools(server: McpServer): void {
subject: item.Subject ?? "",
}));
return {
content: [{ type: "text" as const, text: JSON.stringify({ itemIds: result, count: result.length }) }],
content: [{
type: "text" as const,
text: JSON.stringify({ itemIds: result, count: result.length }),
}],
};
}
@@ -71,11 +91,17 @@ export function registerEmailTools(server: McpServer): void {
}
return {
content: [{ type: "text" as const, text: JSON.stringify({ emails, count: emails.length }) }],
content: [{
type: "text" as const,
text: JSON.stringify({ emails, count: emails.length }),
}],
};
} catch (error: any) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: error.message ?? String(error) }) }],
content: [{
type: "text" as const,
text: JSON.stringify({ error: error.message ?? String(error) }),
}],
};
}
},
@@ -86,7 +112,9 @@ export function registerEmailTools(server: McpServer): void {
{
description: "Get a single email with full body and details",
inputSchema: z.object({
itemId: z.string().describe("The Exchange ItemId of the email to retrieve"),
itemId: z.string().describe(
"The Exchange ItemId of the email to retrieve",
),
}),
},
async ({ itemId }) => {
@@ -100,7 +128,10 @@ export function registerEmailTools(server: McpServer): void {
};
} catch (error: any) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: error.message ?? String(error) }) }],
content: [{
type: "text" as const,
text: JSON.stringify({ error: error.message ?? String(error) }),
}],
};
}
},
@@ -112,9 +143,14 @@ export function registerEmailTools(server: McpServer): void {
description: "Search emails by text across one or all folders",
inputSchema: z.object({
query: z.string().describe("The text to search for"),
folderId: z.string().optional().describe("Optional folder ID to limit the search. When omitted, searches all mail folders"),
maxResults: z.number().default(20).describe("Maximum number of results (default 20, max 100)"),
searchScope: z.enum(["all", "subject", "body", "from"]).default("all").describe("Where to search"),
folderId: z.string().optional().describe(
"Optional folder ID to limit the search. When omitted, searches all mail folders",
),
maxResults: z.number().default(20).describe(
"Maximum number of results (default 20, max 100)",
),
searchScope: z.enum(["all", "subject", "body", "from"]).default("all")
.describe("Where to search"),
}),
},
async ({ query, folderId, maxResults, searchScope }) => {
@@ -123,7 +159,13 @@ export function registerEmailTools(server: McpServer): void {
if (!query.trim()) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: "query must not be empty", results: [] }) }],
content: [{
type: "text" as const,
text: JSON.stringify({
error: "query must not be empty",
results: [],
}),
}],
};
}
@@ -139,7 +181,12 @@ export function registerEmailTools(server: McpServer): void {
return `\
<t:Contains ContainmentMode="Substring" ContainmentComparison="IgnoreCase">
<t:FieldURI FieldURI="${fieldUri}"/>
<t:Constant Value="${value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")}"/>
<t:Constant Value="${
value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(
/>/g,
"&gt;",
).replace(/"/g, "&quot;")
}"/>
</t:Contains>`;
}
@@ -156,7 +203,13 @@ export function registerEmailTools(server: McpServer): void {
const fieldUri = fieldUriMap[searchScope];
if (!fieldUri) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: `unsupported search_scope: ${searchScope}`, results: [] }) }],
content: [{
type: "text" as const,
text: JSON.stringify({
error: `unsupported search_scope: ${searchScope}`,
results: [],
}),
}],
};
}
restriction = `\
@@ -168,11 +221,24 @@ export function registerEmailTools(server: McpServer): void {
const traversal = folderId ? "Shallow" : "Deep";
if (folderId) {
const items = await client.findItems(folderId, { limit: maxResults, restriction, traversal });
const items = await client.findItems(folderId, {
limit: maxResults,
restriction,
traversal,
});
const results = formatSearchResults(items, client, maxResults);
return {
content: [{ type: "text" as const, text: JSON.stringify({ query, searchScope, folderId, totalResults: results.length, results }) }],
content: [{
type: "text" as const,
text: JSON.stringify({
query,
searchScope,
folderId,
totalResults: results.length,
results,
}),
}],
};
} else {
const folders = await client.findFolders("msgfolderroot", true);
@@ -181,7 +247,11 @@ export function registerEmailTools(server: McpServer): void {
for (const f of folders) {
if (allResults.length >= maxResults) break;
const remaining = maxResults - allResults.length;
const items = await client.findItems(f.id, { limit: remaining, restriction, traversal: "Shallow" });
const items = await client.findItems(f.id, {
limit: remaining,
restriction,
traversal: "Shallow",
});
const formatted = formatSearchResults(items, client, remaining);
for (const r of formatted) {
@@ -193,19 +263,35 @@ export function registerEmailTools(server: McpServer): void {
}
return {
content: [{ type: "text" as const, text: JSON.stringify({ query, searchScope, folderId: "all", totalResults: allResults.length, results: allResults }) }],
content: [{
type: "text" as const,
text: JSON.stringify({
query,
searchScope,
folderId: "all",
totalResults: allResults.length,
results: allResults,
}),
}],
};
}
} catch (error: any) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: error.message ?? String(error) }) }],
content: [{
type: "text" as const,
text: JSON.stringify({ error: error.message ?? String(error) }),
}],
};
}
},
);
}
function formatSearchResults(items: any[], client: EwsClient, maxResults: number): any[] {
function formatSearchResults(
items: any[],
client: EwsClient,
maxResults: number,
): any[] {
const results: any[] = [];
for (const item of items) {
if (results.length >= maxResults) break;
@@ -215,7 +301,8 @@ function formatSearchResults(items: any[], client: EwsClient, maxResults: number
const bodyType = item.Body?.["@_BodyType"] ?? "HTML";
let bodyPreview = "";
if (bodyType === "HTML" && bodyHtml) {
bodyPreview = bodyHtml.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim().slice(0, 200);
bodyPreview = bodyHtml.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ")
.trim().slice(0, 200);
} else {
bodyPreview = bodyHtml.slice(0, 200);
}
+11 -4
View File
@@ -1,6 +1,6 @@
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts";
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
export function registerFolderTools(server: McpServer): void {
server.registerTool(
@@ -8,8 +8,12 @@ export function registerFolderTools(server: McpServer): void {
{
description: "List mail folders from the Exchange mailbox",
inputSchema: z.object({
parentFolderId: z.string().default("msgfolderroot").describe("Parent folder to list children of (default: msgfolderroot)"),
recursive: z.boolean().default(false).describe("If True, traverse all subfolders recursively"),
parentFolderId: z.string().default("msgfolderroot").describe(
"Parent folder to list children of (default: msgfolderroot)",
),
recursive: z.boolean().default(false).describe(
"If True, traverse all subfolders recursively",
),
}),
},
async ({ parentFolderId, recursive }) => {
@@ -22,7 +26,10 @@ export function registerFolderTools(server: McpServer): void {
};
} catch (error: any) {
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: error.message ?? String(error) }) }],
content: [{
type: "text" as const,
text: JSON.stringify({ error: error.message ?? String(error) }),
}],
};
}
},
+17
View File
@@ -0,0 +1,17 @@
export interface CalendarEvent {
subject: string;
start: string;
end: string;
location: string;
isAllDay: boolean;
isCancelled: boolean;
isMeeting: boolean;
isRecurring: boolean;
organizer: string;
organizerEmail: string;
myResponse: string;
itemId: string;
body: string;
requiredAttendees: string[];
optionalAttendees: string[];
}
+32
View File
@@ -0,0 +1,32 @@
export interface Email {
subject: string;
from: string;
fromName: string;
date: string;
isRead: boolean;
hasAttachments: boolean;
hasLinks: boolean;
itemId: string;
size: number;
isMeeting: boolean;
itemType: string;
to: string[];
cc: string[];
body: string;
bodyType: string;
attachments: Attachment[];
preview: string;
location?: string;
start?: string;
end?: string;
requiredAttendees?: string[];
optionalAttendees?: string[];
}
export interface Attachment {
name: string;
size: number;
contentType: string;
attachmentId: string;
isInline: boolean;
}
+7
View File
@@ -0,0 +1,7 @@
export interface Folder {
name: string;
id: string;
totalCount: number;
unreadCount: number;
childFolderCount: number;
}
+6
View File
@@ -0,0 +1,6 @@
export interface FreeSlot {
date: string;
start: string;
end: string;
durationMinutes: number;
}
+6
View File
@@ -0,0 +1,6 @@
export interface LoginConfig {
serverUrl: string;
email: string;
username: string;
domain?: string;
}
+11
View File
@@ -0,0 +1,11 @@
export interface MeetingResult {
success: boolean;
subject: string;
date: string;
startTime: string;
endTime: string;
location: string;
requiredAttendees: string[];
optionalAttendees: string[];
error: string;
}
+17
View File
@@ -0,0 +1,17 @@
export interface Person {
name: string;
email: string;
mailboxType: string;
firstName: string;
lastName: string;
jobTitle: string;
department: string;
company: string;
office: string;
alias: string;
manager: string;
managerEmail: string;
phones: Record<string, string>;
address: string;
directReports: Array<{ name: string; email: string }>;
}