5 Commits

Author SHA1 Message Date
albnnc 17a6f91b3f w 2026-07-10 16:36:22 +03:00
albnnc 990a8d09b6 feat: update skill file 2026-07-09 17:20:36 +03:00
albnnc bd90359332 feat: update skill file 2026-07-09 17:00:34 +03:00
albnnc d2de768878 feat: easier login 2026-07-09 16:54:31 +03:00
albnnc 6fefd17400 feat: more tools 2026-07-09 13:40:52 +00:00
9 changed files with 1083 additions and 168 deletions
+8 -4
View File
@@ -5,14 +5,18 @@
"module.sortImportDeclarations": "caseInsensitive",
"module.sortExportDeclarations": "caseInsensitive"
},
"markdown": {
"lineWidth": 80,
"textWrap": "always"
},
"excludes": [
"**/.git",
"**/.target"
],
"plugins": [
"https://plugins.dprint.dev/typescript-0.91.1.wasm",
"https://plugins.dprint.dev/json-0.17.4.wasm",
"https://plugins.dprint.dev/markdown-0.15.3.wasm",
"https://plugins.dprint.dev/dockerfile-0.3.0.wasm"
"https://plugins.dprint.dev/typescript-0.96.1.wasm",
"https://plugins.dprint.dev/json-0.23.0.wasm",
"https://plugins.dprint.dev/markdown-0.22.1.wasm",
"https://plugins.dprint.dev/dockerfile-0.4.1.wasm"
]
}
+204 -1
View File
@@ -250,6 +250,13 @@ export class EwsClient {
traversal = "Shallow",
} = options;
const isDistinguished =
DISTINGUISHED_FOLDERS[folderId.toLowerCase()] !== undefined;
const folderIdXml = isDistinguished
? `<t:DistinguishedFolderId Id="${folderId}"/>`
: `<t:FolderId Id="${folderId}"/>`;
const soap = buildSoapEnvelope(`\
<m:FindItem Traversal="${traversal}">
<m:ItemShape>
@@ -257,7 +264,7 @@ export class EwsClient {
</m:ItemShape>
<m:IndexedPageItemView MaxEntriesReturned="${limit}" Offset="${offset}" BasePoint="Beginning"/>
<m:ParentFolderIds>
<t:FolderId Id="${folderId}"/>
${folderIdXml}
</m:ParentFolderIds>
<m:SortOrder>
<t:FieldOrder Order="Descending">
@@ -523,4 +530,200 @@ ${restriction}
text = text.replace(/[ \t]+/g, " ");
return text.trim();
}
// ── UpdateItem (for marking read/unread, etc.) ──────────────────────────
async updateItems(
itemIds: string[],
updates: { fieldUri: string; value: string | boolean }[],
): Promise<any[]> {
const propName = (fieldUri: string): string => {
const parts = fieldUri.split(":");
return parts[parts.length - 1];
};
const changesXml = itemIds.map((id) => {
const updatesXml = updates.map((u) => {
const val = typeof u.value === "boolean"
? (u.value ? "true" : "false")
: u.value;
return `\
<t:SetItemField>
<t:FieldURI FieldURI="${u.fieldUri}"/>
<t:Message>
<t:${propName(u.fieldUri)}>${String(val)}</t:${
propName(u.fieldUri)
}>
</t:Message>
</t:SetItemField>`;
}).join("\n");
return `\
<t:ItemChange>
<t:ItemId Id="${id}"/>
<t:Updates>
${updatesXml}
</t:Updates>
</t:ItemChange>`;
}).join("\n");
const soap = buildSoapEnvelope(`\
<m:UpdateItem MessageDisposition="SaveOnly" ConflictResolution="AutoResolve">
<m:ItemChanges>
${changesXml}
</m:ItemChanges>
</m:UpdateItem>`);
const data = await this.soapRequest(
soap,
"http://schemas.microsoft.com/exchange/services/2006/messages/UpdateItem",
);
return this.extractResponseMessages(data);
}
// ── GetAttachment ───────────────────────────────────────────────────────
async getAttachment(
attachmentId: string,
): Promise<{ content: Buffer; name: string; contentType: string }> {
const soap = buildSoapEnvelope(`\
<m:GetAttachment>
<m:AttachmentIds>
<t:AttachmentId Id="${attachmentId}"/>
</m:AttachmentIds>
</m:GetAttachment>`);
const data = await this.soapRequest(
soap,
"http://schemas.microsoft.com/exchange/services/2006/messages/GetAttachment",
);
for (const msg of this.extractResponseMessages(data)) {
const attachments = msg?.Attachments?.FileAttachment;
if (!attachments) continue;
const list = Array.isArray(attachments) ? attachments : [attachments];
for (const a of list) {
const contentBase64 = a.Content ?? "";
const content = Buffer.from(contentBase64, "base64");
return {
content,
name: a.Name ?? "attachment",
contentType: a.ContentType ?? "application/octet-stream",
};
}
}
throw new Error(`Attachment '${attachmentId}' not found`);
}
// ── FindItem with CalendarView ──────────────────────────────────────────
async findCalendarItems(
folderId: string,
startDate: string,
endDate: string,
): Promise<any[]> {
const soap = buildSoapEnvelope(`\
<m:FindItem Traversal="Shallow">
<m:ItemShape>
<t:BaseShape>AllProperties</t:BaseShape>
<t:BodyType>HTML</t:BodyType>
</m:ItemShape>
<m:ParentFolderIds>
<t:FolderId Id="${folderId}"/>
</m:ParentFolderIds>
<m:CalendarView MaxEntriesReturned="200" StartDate="${startDate}" EndDate="${endDate}"/>
</m:FindItem>`);
const data = await this.soapRequest(
soap,
"http://schemas.microsoft.com/exchange/services/2006/messages/FindItem",
);
for (const msg of this.extractResponseMessages(data)) {
const items = msg?.RootFolder?.Items?.CalendarItem;
if (!items) continue;
return Array.isArray(items) ? items : [items];
}
return [];
}
// ── GetUserAvailability ─────────────────────────────────────────────────
async getUserAvailability(
emails: string[],
startDate: string,
endDate: string,
requestedView: string = "DetailedMerged",
): Promise<any> {
const mailboxDataXml = emails.map((email) =>
`\
<t:MailboxData>
<t:Email>
<t:Address>${
email.replace(/&/g, "&amp;").replace(/</g, "&lt;")
}</t:Address>
</t:Email>
<t:AttendeeType>Required</t:AttendeeType>
</t:MailboxData>`
).join("\n");
const soap = `<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
<s:Body>
<m:GetUserAvailabilityRequest>
<m:MailboxDataArray>
${mailboxDataXml}
</m:MailboxDataArray>
<m:FreeBusyViewOptions>
<t:TimeWindow>
<t:StartTime>${startDate}T00:00:00</t:StartTime>
<t:EndTime>${endDate}T23:59:59</t:EndTime>
</t:TimeWindow>
<t:MergedFreeBusyIntervalInMinutes>30</t:MergedFreeBusyIntervalInMinutes>
<t:RequestedView>${requestedView}</t:RequestedView>
</m:FreeBusyViewOptions>
</m:GetUserAvailabilityRequest>
</s:Body>
</s:Envelope>`;
const data = await this.soapRequest(
soap,
"http://schemas.microsoft.com/exchange/services/2006/messages/GetUserAvailability",
);
return data;
}
// ── ResolveNames (directory search) ─────────────────────────────────────
async resolveNames(
query: string,
fullContact: boolean = true,
): Promise<any[]> {
const soap = buildSoapEnvelope(`\
<m:ResolveNames ReturnFullContactData="${fullContact}" SearchScope="ActiveDirectoryContacts">
<m:UnresolvedEntry>${
query.replace(/&/g, "&amp;").replace(/</g, "&lt;")
}</m:UnresolvedEntry>
</m:ResolveNames>`);
const data = await this.soapRequest(
soap,
"http://schemas.microsoft.com/exchange/services/2006/messages/ResolveNames",
);
for (const msg of this.extractResponseMessages(data)) {
const resolutions = msg?.ResolutionSet?.Resolution;
if (resolutions) {
return Array.isArray(resolutions) ? resolutions : [resolutions];
}
}
return [];
}
}
+6
View File
@@ -6,8 +6,11 @@ import crypto from "node:crypto";
import http from "node:http";
import { initDataDir } from "./ews_client.ts";
import { registerAuthTools } from "./tools/auth.ts";
import { registerAvailabilityTools } from "./tools/availability.ts";
import { registerCalendarTools } from "./tools/calendar.ts";
import { registerEmailTools } from "./tools/email.ts";
import { registerFolderTools } from "./tools/folders.ts";
import { registerPeopleTools } from "./tools/people.ts";
const program = new Command()
.name("exchange-mcp")
@@ -35,6 +38,9 @@ function buildServer(): McpServer {
registerAuthTools(server);
registerEmailTools(server);
registerFolderTools(server);
registerCalendarTools(server);
registerAvailabilityTools(server);
registerPeopleTools(server);
return server;
}
+42 -14
View File
@@ -8,31 +8,57 @@ import {
saveConfig,
setPassword,
} from "../ews_client.ts";
import type { LoginConfig } from "../types/login_config.ts";
export function registerAuthTools(server: McpServer): void {
server.registerTool(
"login",
{
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 subsequent logins only password is needed — previously saved"
+ " serverUrl, email, username, and domain are reused automatically from config."
+ " Returns {success, message} on success or {success, error} on failure.",
inputSchema: z.object({
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"),
serverUrl: z.string().optional().describe("Server URL"),
email: z.string().optional().describe("Email address"),
username: z.string().optional().describe("NTLM username"),
password: z.string().describe("NTLM password"),
domain: z.string().optional().describe("NTLM domain (default: corp)"),
domain: z.string().optional().describe("NTLM domain"),
}),
},
async ({ serverUrl, email, username, password, domain }) => {
try {
const config = {
serverUrl: serverUrl.replace(/\/+$/, ""),
email,
username,
domain: domain ?? "corp",
let savedConfig: Partial<LoginConfig> = {};
try {
savedConfig = loadConfig();
} catch {
// no saved config — all fields must be provided
}
const config: LoginConfig = {
serverUrl: (serverUrl ?? savedConfig.serverUrl)!,
email: (email ?? savedConfig.email)!,
username: (username ?? savedConfig.username)!,
domain: domain ?? savedConfig.domain ?? "corp",
};
if (!config.serverUrl || !config.email || !config.username) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({
success: false,
error: "Missing required fields."
+ " Provide serverUrl, email, and username, or"
+ " login once with all fields first.",
}),
}],
};
}
config.serverUrl = config.serverUrl.replace(/\/+$/, "");
const client = new EwsClient(config, password);
const result = await client.verifyConnection();
@@ -76,7 +102,8 @@ export function registerAuthTools(server: McpServer): void {
server.registerTool(
"check_session",
{
description: "Check whether the current EWS session is authenticated",
description:
"Check whether the current EWS session is authenticated. No parameters. Returns {authenticated, email, serverUrl} or {authenticated, error}.",
inputSchema: z.object({}),
},
async () => {
@@ -124,7 +151,8 @@ export function registerAuthTools(server: McpServer): void {
server.registerTool(
"logout",
{
description: "Clear stored credentials",
description:
"Clear stored credentials (serverUrl, email, username, domain, password). No parameters. Returns {success, message}.",
inputSchema: z.object({}),
},
async () => {
+333
View File
@@ -0,0 +1,333 @@
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts";
export function registerAvailabilityTools(server: McpServer): void {
server.registerTool(
"find_free_time",
{
description:
"Find free time slots in your own calendar. Queries your free/busy status and returns available slots within working hours that meet the minimum duration. Returns {freeSlots: {date: [{start, end, durationMinutes}]}}. Defaults: durationMinutes=30, startHour=9, endHour=18.",
inputSchema: z.object({
startDate: z.string().describe("Start date in YYYY-MM-DD format"),
endDate: z.string().optional().describe(
"End date in YYYY-MM-DD format. Defaults to startDate",
),
durationMinutes: z.number().default(30).describe(
"Minimum slot duration in minutes. Default: 30",
),
startHour: z.number().default(9).describe(
"Working day start hour (0-23). Default: 9",
),
endHour: z.number().default(18).describe(
"Working day end hour (0-23). Default: 18",
),
}),
},
async ({ startDate, endDate, durationMinutes, startHour, endHour }) => {
try {
const client = new EwsClient(loadConfig());
const config = loadConfig();
const ed = endDate || startDate;
const data = await client.getUserAvailability(
[config.email],
startDate,
ed,
);
const body = data?.Envelope?.Body?.GetUserAvailabilityResponse
?? data?.Envelope?.Body ?? {};
const freeBusyArray = body?.FreeBusyResponseArray?.FreeBusyResponse
?? [];
const responses = Array.isArray(freeBusyArray)
? freeBusyArray
: [freeBusyArray];
const busyPeriods: { start: Date; end: Date }[] = [];
for (const fbResp of responses) {
const fbView = fbResp?.FreeBusyView ?? {};
const calEvents = fbView?.CalendarEventArray?.CalendarEvent ?? [];
const evList = Array.isArray(calEvents) ? calEvents : [calEvents];
for (const ev of evList) {
const bt = ev.BusyType ?? "";
if (bt === "Free" || bt === "NoData") continue;
const startStr = ev.StartTime ?? "";
const endStr = ev.EndTime ?? "";
if (startStr && endStr) {
busyPeriods.push({
start: new Date(startStr),
end: new Date(endStr),
});
}
}
}
const merged = mergeBusyPeriods(busyPeriods);
const freeSlots = findFreeSlots(
merged,
new Date(startDate),
ed ? new Date(ed) : new Date(startDate),
startHour,
endHour,
durationMinutes,
);
return {
content: [{
type: "text" as const,
text: JSON.stringify({ freeSlots }),
}],
};
} catch (error: any) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({ error: error.message ?? String(error) }),
}],
};
}
},
);
server.registerTool(
"find_meeting_time",
{
description:
"Find common free time for multiple attendees. Queries free/busy for all attendees and returns slots where everyone is available. Returns {period, attendees, freeSlots}. Defaults: durationMinutes=30, startHour=9, endHour=18.",
inputSchema: z.object({
emails: z.string().describe(
"Comma-separated email addresses of attendees",
),
startDate: z.string().describe("Start date in YYYY-MM-DD format"),
endDate: z.string().optional().describe(
"End date in YYYY-MM-DD format. Defaults to startDate",
),
durationMinutes: z.number().default(30).describe(
"Minimum slot duration in minutes. Default: 30",
),
startHour: z.number().default(9).describe(
"Working day start hour (0-23). Default: 9",
),
endHour: z.number().default(18).describe(
"Working day end hour (0-23). Default: 18",
),
}),
},
async (
{ emails, startDate, endDate, durationMinutes, startHour, endHour },
) => {
try {
const client = new EwsClient(loadConfig());
const emailList = emails.split(",").map((e) => e.trim()).filter(
Boolean,
);
const ed = endDate || startDate;
const data = await client.getUserAvailability(emailList, startDate, ed);
const body = data?.Envelope?.Body?.GetUserAvailabilityResponse
?? data?.Envelope?.Body ?? {};
const freeBusyArray = body?.FreeBusyResponseArray?.FreeBusyResponse
?? [];
const responses = Array.isArray(freeBusyArray)
? freeBusyArray
: [freeBusyArray];
const allBusy: { start: Date; end: Date }[] = [];
const attendeeInfo: any[] = [];
for (let i = 0; i < responses.length; i++) {
const fbResp = responses[i];
const fbView = fbResp?.FreeBusyView ?? {};
const email = emailList[i] || `Person ${i + 1}`;
const mergedFb = fbView.MergedFreeBusy ?? "";
if (mergedFb) {
const startTime = new Date(`${startDate}T00:00:00`);
const busyPeriods = parseFreeBusyString(mergedFb, startTime);
const busyCount = busyPeriods.length;
const freeCount = mergedFb.split("").filter((c: string) =>
c === "0"
).length;
attendeeInfo.push({
email,
busySlots: busyCount,
freeSlots: freeCount,
});
allBusy.push(...busyPeriods);
} else {
const calEvents = fbView?.CalendarEventArray?.CalendarEvent ?? [];
const evList = Array.isArray(calEvents) ? calEvents : [calEvents];
attendeeInfo.push({ email, calendarEvents: evList.length });
for (const ev of evList) {
const startStr = ev.StartTime ?? "";
const endStr = ev.EndTime ?? "";
if (startStr && endStr) {
allBusy.push({
start: new Date(startStr),
end: new Date(endStr),
});
}
}
}
}
const merged = mergeBusyPeriods(allBusy);
const freeByDate = findFreeSlots(
merged,
new Date(startDate),
new Date(ed),
startHour,
endHour,
durationMinutes,
);
return {
content: [{
type: "text" as const,
text: JSON.stringify({
period: { start: startDate, end: ed },
attendees: attendeeInfo,
freeSlots: freeByDate,
}),
}],
};
} catch (error: any) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({ error: error.message ?? String(error) }),
}],
};
}
},
);
}
// ── Helpers ──────────────────────────────────────────────────────────────
function parseFreeBusyString(
fbStr: string,
startTime: Date,
intervalMinutes: number = 30,
): { start: Date; end: Date }[] {
const periods: { start: Date; end: Date }[] = [];
const current = new Date(startTime);
for (const char of fbStr) {
const next = new Date(current.getTime() + intervalMinutes * 60000);
if (char !== "0") {
periods.push({ start: new Date(current), end: next });
}
current.setTime(next.getTime());
}
return periods;
}
function mergeBusyPeriods(
periods: { start: Date; end: Date }[],
): { start: Date; end: Date }[] {
if (!periods.length) return [];
const sorted = [...periods].sort((a, b) =>
a.start.getTime() - b.start.getTime()
);
const merged: { start: Date; end: Date }[] = [{ ...sorted[0] }];
for (let i = 1; i < sorted.length; i++) {
const last = merged[merged.length - 1];
if (sorted[i].start <= last.end) {
last.end = sorted[i].end > last.end ? sorted[i].end : last.end;
} else {
merged.push({ ...sorted[i] });
}
}
return merged;
}
function findFreeSlots(
busyPeriods: { start: Date; end: Date }[],
startDate: Date,
endDate: Date,
startHour: number,
endHour: number,
durationMinutes: number,
): Record<string, { start: string; end: string; durationMinutes: number }[]> {
const result: Record<
string,
{ start: string; end: string; durationMinutes: number }[]
> = {};
const current = new Date(startDate);
current.setDate(current.getDate());
current.setHours(0, 0, 0, 0);
const end = new Date(endDate);
end.setDate(end.getDate() + 1);
end.setHours(0, 0, 0, 0);
while (current < end) {
if (current.getDay() !== 0 && current.getDay() !== 6) {
const dayStart = new Date(current);
dayStart.setHours(startHour, 0, 0, 0);
const dayEnd = new Date(current);
dayEnd.setHours(endHour, 0, 0, 0);
const dayBusy = busyPeriods
.filter((p) => p.start < dayEnd && p.end > dayStart)
.map((p) => ({
start: p.start < dayStart ? dayStart : p.start,
end: p.end > dayEnd ? dayEnd : p.end,
}));
const merged = mergeBusyPeriods(dayBusy);
const slots: { start: string; end: string; durationMinutes: number }[] =
[];
let cursor = new Date(dayStart);
for (const bp of merged) {
if (cursor < bp.start) {
const gap = (bp.start.getTime() - cursor.getTime()) / 60000;
if (gap >= durationMinutes) {
slots.push({
start: formatTime(cursor),
end: formatTime(bp.start),
durationMinutes: gap,
});
}
}
cursor = bp.end > cursor ? bp.end : cursor;
}
if (cursor < dayEnd) {
const gap = (dayEnd.getTime() - cursor.getTime()) / 60000;
if (gap >= durationMinutes) {
slots.push({
start: formatTime(cursor),
end: formatTime(dayEnd),
durationMinutes: gap,
});
}
}
if (slots.length) {
result[current.toISOString().slice(0, 10)] = slots;
}
}
current.setDate(current.getDate() + 1);
}
return result;
}
function formatTime(d: Date): string {
return d.toTimeString().slice(0, 5);
}
+188
View File
@@ -0,0 +1,188 @@
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import fs from "node:fs";
import path from "node:path";
import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts";
export function registerCalendarTools(server: McpServer): void {
server.registerTool(
"get_calendar_events",
{
description:
"Get calendar events within a date range. Set includeBody=true to fetch organizer, attendees, and body via GetItem. Returns {events, count}.",
inputSchema: z.object({
startDate: z.string().describe("Start date in YYYY-MM-DD format"),
endDate: z.string().describe("End date in YYYY-MM-DD format"),
includeBody: z.boolean().default(false).describe(
"If true, fetch full event details (organizer, attendees, body) via GetItem. Default: false",
),
}),
},
async ({ startDate, endDate, includeBody }) => {
try {
const client = new EwsClient(loadConfig());
const folderId = await client.getFolderId("calendar");
const items = await client.findCalendarItems(
folderId,
`${startDate}T00:00:00`,
`${endDate}T23:59:59`,
);
const events = [];
for (const item of items) {
const event: any = {
subject: item.Subject ?? "(No subject)",
start: item.Start ?? "",
end: item.End ?? "",
location: item.Location ?? item.EnhancedLocation?.DisplayName ?? "",
isAllDay: item.IsAllDayEvent === "true"
|| item.IsAllDayEvent === true,
isCancelled: item.IsCancelled === "true"
|| item.IsCancelled === true,
isMeeting: true,
isRecurring: item.IsRecurring === "true"
|| item.IsRecurring === true,
organizer: "",
organizerEmail: "",
myResponse: item.MyResponseType ?? "",
itemId: item.ItemId?.["@_Id"] ?? "",
body: "",
requiredAttendees: [],
optionalAttendees: [],
};
if (includeBody && event.itemId) {
const details = client.extractEmailDetails(item);
event.body = details.body;
event.requiredAttendees = details.requiredAttendees ?? [];
event.optionalAttendees = details.optionalAttendees ?? [];
event.organizer = details.fromName;
event.organizerEmail = details.from;
event.location = details.location || event.location;
}
events.push(event);
}
return {
content: [{
type: "text" as const,
text: JSON.stringify({ events, count: events.length }),
}],
};
} catch (error: any) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({ error: error.message ?? String(error) }),
}],
};
}
},
);
server.registerTool(
"download_event_attachments",
{
description:
"Download all file attachments from a calendar event to disk. Inline (embedded) attachments are skipped — only standalone file attachments are downloaded. Returns {success, downloaded, count} or {success, downloaded, count, errors}.",
inputSchema: z.object({
itemId: z.string().describe(
"The Exchange ItemId of the calendar event",
),
targetFolder: z.string().default("/tmp/attachments").describe(
"Local directory to save files. Default: /tmp/attachments",
),
}),
},
async ({ itemId, targetFolder }) => {
try {
const client = new EwsClient(loadConfig());
const item = await client.getItem(itemId);
const email = client.extractEmailDetails(item);
const attachments = email.attachments ?? [];
const fileAttachments = attachments.filter(
(a: any) => a.attachmentId && !a.isInline,
);
if (!fileAttachments.length) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({
success: true,
downloaded: [],
count: 0,
message: "No downloadable file attachments.",
}),
}],
};
}
fs.mkdirSync(targetFolder, { recursive: true });
const downloaded = [];
const errors = [];
const usedNames = new Set<string>();
for (const att of fileAttachments) {
try {
const result = await client.getAttachment(att.attachmentId);
let filename = path.basename(result.name);
if (!filename) filename = att.name || "attachment";
const baseName = filename;
const dotIdx = baseName.lastIndexOf(".");
const namePart = dotIdx > 0 ? baseName.slice(0, dotIdx) : baseName;
const extPart = dotIdx > 0 ? baseName.slice(dotIdx) : "";
let counter = 1;
let finalName = filename;
while (usedNames.has(finalName.toLowerCase())) {
finalName = extPart
? `${namePart}_${counter}${extPart}`
: `${namePart}_${counter}`;
counter++;
}
usedNames.add(finalName.toLowerCase());
const filepath = path.join(targetFolder, finalName);
fs.writeFileSync(filepath, result.content);
downloaded.push({
name: finalName,
path: filepath,
size: result.content.length,
contentType: result.contentType,
});
} catch (e: any) {
errors.push({
name: att.name || "unknown",
error: e.message ?? String(e),
});
}
}
return {
content: [{
type: "text" as const,
text: JSON.stringify({
success: errors.length === 0,
downloaded,
count: downloaded.length,
...(errors.length ? { errors } : {}),
}),
}],
};
} catch (error: any) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({ error: error.message ?? String(error) }),
}],
};
}
},
);
}
+199 -146
View File
@@ -1,4 +1,6 @@
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import fs from "node:fs";
import path from "node:path";
import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts";
@@ -10,47 +12,115 @@ export function registerEmailTools(server: McpServer): void {
server.registerTool(
"get_emails",
{
description: "Get emails from a mailbox folder",
description:
"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.",
inputSchema: z.object({
folder: z.string().default("Inbox").describe(
"Folder name (Inbox, Sent, Drafts, Deleted, Junk, or custom)",
"Folder name (Inbox, Sent, Drafts, Deleted, Junk, or custom). Supports Russian folder names",
),
limit: z.number().default(10).describe(
"Maximum number of emails to return (default 10, max 50)",
"Maximum number of emails to return. Default: 10. Max 50 (max 500 if idsOnly=true)",
),
offset: z.number().default(0).describe(
"Number of emails to skip for pagination",
"Number of emails to skip for pagination. Default: 0",
),
includeBody: z.boolean().default(false).describe(
"If True, fetch full body for each email (slower)",
"If true, fetches full email body for each email (slower). Default: false",
),
unreadOnly: z.boolean().default(false).describe(
"If True, only return unread emails",
"If true, only return unread emails. Default: false",
),
idsOnly: z.boolean().default(false).describe(
"If True, return only item IDs and dates (max limit 500)",
"If true, return only item IDs, dates, and subjects — faster with higher limit of 500. Default: false",
),
query: z.string().optional().describe(
"Optional text to search for within the folder",
),
queryScope: z.enum(["all", "subject", "body", "from"]).default("all")
.describe(
"Scope for text search. Values: all (subject+body), subject, body, from. Only used when query is set. Default: all",
),
}),
},
async ({ folder, limit, offset, includeBody, unreadOnly, idsOnly }) => {
async (
{
folder,
limit,
offset,
includeBody,
unreadOnly,
idsOnly,
query,
queryScope,
},
) => {
try {
const client = getClient();
const maxLimit = idsOnly ? 500 : 50;
if (limit > maxLimit) limit = maxLimit;
offset = Math.max(0, offset);
const folderId = await client.getFolderId(folder);
const baseShape = idsOnly ? "IdOnly" : "AllProperties";
let restriction = "";
if (query && !query.trim()) query = undefined;
const restrictions: string[] = [];
if (unreadOnly) {
restriction = `\
<m:Restriction>
restrictions.push(`\
<t:IsEqualTo>
<t:FieldURI FieldURI="message:IsRead"/>
<t:FieldURIOrConstant>
<t:Constant Value="false"/>
</t:FieldURIOrConstant>
</t:IsEqualTo>
</t:IsEqualTo>`);
}
if (query) {
function containsExpression(fieldUri: string, value: string): string {
return `\
<t:Contains ContainmentMode="Substring" ContainmentComparison="IgnoreCase">
<t:FieldURI FieldURI="${fieldUri}"/>
<t:Constant Value="${
value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(
/>/g,
"&gt;",
).replace(/"/g, "&quot;")
}"/>
</t:Contains>`;
}
const fieldUriMap: Record<string, string> = {
subject: "item:Subject",
body: "item:Body",
from: "message:From",
};
if (queryScope === "all") {
restrictions.push(`\
<t:Or>
${containsExpression("item:Subject", query)}
${containsExpression("item:Body", query)}
</t:Or>`);
} else {
const fieldUri = fieldUriMap[queryScope];
restrictions.push(containsExpression(fieldUri, query));
}
}
let restriction = "";
if (restrictions.length === 1) {
restriction = `\
<m:Restriction>
${restrictions[0]}
</m:Restriction>`;
} else if (restrictions.length > 1) {
restriction = `\
<m:Restriction>
<t:And>
${restrictions.join("\n")}
</t:And>
</m:Restriction>`;
}
@@ -110,7 +180,8 @@ export function registerEmailTools(server: McpServer): void {
server.registerTool(
"get_email",
{
description: "Get a single email with full body and details",
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.).",
inputSchema: z.object({
itemId: z.string().describe(
"The Exchange ItemId of the email to retrieve",
@@ -138,143 +209,152 @@ export function registerEmailTools(server: McpServer): void {
);
server.registerTool(
"search_emails",
"mark_email_read",
{
description: "Search emails by text across one or all folders",
description:
"Mark one or more emails as read or unread by their Exchange ItemIds. Returns {success, message} or {error}.",
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",
itemIds: z.array(z.string()).describe(
"List of Exchange ItemIds to update",
),
maxResults: z.number().default(20).describe(
"Maximum number of results (default 20, max 100)",
isRead: z.boolean().default(true).describe(
"True to mark as read, false to mark as unread. Default: true",
),
searchScope: z.enum(["all", "subject", "body", "from"]).default("all")
.describe("Where to search"),
}),
},
async ({ query, folderId, maxResults, searchScope }) => {
async ({ itemIds, isRead }) => {
try {
const client = getClient();
const client = new EwsClient(loadConfig());
const responses = await client.updateItems(itemIds, [
{ fieldUri: "message:IsRead", value: isRead },
]);
if (!query.trim()) {
const errors = responses
.filter((r: any) => r.ResponseClass === "Error")
.map((r: any) => r.MessageText ?? "Unknown error");
if (errors.length) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({
error: "query must not be empty",
results: [],
}),
text: JSON.stringify({ error: errors.join("; ") }),
}],
};
}
maxResults = Math.max(1, Math.min(maxResults, 100));
const fieldUriMap: Record<string, string> = {
subject: "item:Subject",
body: "item:Body",
from: "message:From",
const status = isRead ? "read" : "unread";
return {
content: [{
type: "text" as const,
text: JSON.stringify({
success: true,
message: `Marked ${itemIds.length} email(s) as ${status}.`,
}),
}],
};
} catch (error: any) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({ error: error.message ?? String(error) }),
}],
};
}
},
);
function containsExpression(fieldUri: string, value: string): string {
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:Contains>`;
}
server.registerTool(
"download_attachments",
{
description:
"Download all file attachments from an email to disk. Inline (embedded) attachments are skipped — only standalone file attachments are downloaded. Returns {success, downloaded, count} or {success, downloaded, count, errors}.",
inputSchema: z.object({
itemId: z.string().describe("The Exchange ItemId of the email"),
targetFolder: z.string().default("/tmp/attachments").describe(
"Local directory to save files. Default: /tmp/attachments",
),
}),
},
async ({ itemId, targetFolder }) => {
try {
const client = new EwsClient(loadConfig());
const item = await client.getItem(itemId);
const email = client.extractEmailDetails(item);
const attachments = email.attachments ?? [];
let restriction: string;
if (searchScope === "all") {
restriction = `\
<m:Restriction>
<t:Or>
${containsExpression("item:Subject", query)}
${containsExpression("item:Body", query)}
</t:Or>
</m:Restriction>`;
} else {
const fieldUri = fieldUriMap[searchScope];
if (!fieldUri) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({
error: `unsupported search_scope: ${searchScope}`,
results: [],
}),
}],
};
}
restriction = `\
<m:Restriction>
${containsExpression(fieldUri, query)}
</m:Restriction>`;
}
const traversal = folderId ? "Shallow" : "Deep";
if (folderId) {
const items = await client.findItems(folderId, {
limit: maxResults,
restriction,
traversal,
});
const results = formatSearchResults(items, client, maxResults);
const fileAttachments = attachments.filter(
(a: any) => a.attachmentId && !a.isInline,
);
if (!fileAttachments.length) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({
query,
searchScope,
folderId,
totalResults: results.length,
results,
success: true,
downloaded: [],
count: 0,
message: "No downloadable file attachments.",
}),
}],
};
} else {
const folders = await client.findFolders("msgfolderroot", true);
const allResults = [];
}
for (const f of folders) {
if (allResults.length >= maxResults) break;
const remaining = maxResults - allResults.length;
const items = await client.findItems(f.id, {
limit: remaining,
restriction,
traversal: "Shallow",
});
const formatted = formatSearchResults(items, client, remaining);
fs.mkdirSync(targetFolder, { recursive: true });
for (const r of formatted) {
r.folderId = f.id;
r.folderName = f.name;
allResults.push(r);
if (allResults.length >= maxResults) break;
const downloaded = [];
const errors = [];
const usedNames = new Set<string>();
for (const att of fileAttachments) {
try {
const result = await client.getAttachment(att.attachmentId);
let filename = path.basename(result.name);
if (!filename) filename = att.name || "attachment";
const baseName = filename;
const dotIdx = baseName.lastIndexOf(".");
const namePart = dotIdx > 0 ? baseName.slice(0, dotIdx) : baseName;
const extPart = dotIdx > 0 ? baseName.slice(dotIdx) : "";
let counter = 1;
let finalName = filename;
while (usedNames.has(finalName.toLowerCase())) {
finalName = extPart
? `${namePart}_${counter}${extPart}`
: `${namePart}_${counter}`;
counter++;
}
}
usedNames.add(finalName.toLowerCase());
return {
content: [{
type: "text" as const,
text: JSON.stringify({
query,
searchScope,
folderId: "all",
totalResults: allResults.length,
results: allResults,
}),
}],
};
const filepath = path.join(targetFolder, finalName);
fs.writeFileSync(filepath, result.content);
downloaded.push({
name: finalName,
path: filepath,
size: result.content.length,
contentType: result.contentType,
});
} catch (e: any) {
errors.push({
name: att.name || "unknown",
error: e.message ?? String(e),
});
}
}
return {
content: [{
type: "text" as const,
text: JSON.stringify({
success: errors.length === 0,
downloaded,
count: downloaded.length,
...(errors.length ? { errors } : {}),
}),
}],
};
} catch (error: any) {
return {
content: [{
@@ -286,30 +366,3 @@ export function registerEmailTools(server: McpServer): void {
},
);
}
function formatSearchResults(
items: any[],
client: EwsClient,
maxResults: number,
): any[] {
const results: any[] = [];
for (const item of items) {
if (results.length >= maxResults) break;
const summary = client.extractEmailSummary(item);
const bodyHtml = item.Body?.Value ?? item.Body?.["#text"] ?? "";
const bodyType = item.Body?.["@_BodyType"] ?? "HTML";
let bodyPreview = "";
if (bodyType === "HTML" && bodyHtml) {
bodyPreview = bodyHtml.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ")
.trim().slice(0, 200);
} else {
bodyPreview = bodyHtml.slice(0, 200);
}
summary.preview = bodyPreview;
results.push(summary);
}
return results;
}
+4 -3
View File
@@ -6,13 +6,14 @@ export function registerFolderTools(server: McpServer): void {
server.registerTool(
"get_folders",
{
description: "List mail folders from the Exchange mailbox",
description:
"List mailbox folders from the Exchange mailbox. Returns a list of Folder objects (name, id, totalCount, unreadCount, childFolderCount).",
inputSchema: z.object({
parentFolderId: z.string().default("msgfolderroot").describe(
"Parent folder to list children of (default: msgfolderroot)",
"Parent folder to list children of. Supports distinguished names (e.g. inbox, calendar). Default: msgfolderroot",
),
recursive: z.boolean().default(false).describe(
"If True, traverse all subfolders recursively",
"If true, recursively traverse all subfolders. Default: false",
),
}),
},
+99
View File
@@ -0,0 +1,99 @@
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod/v4";
import { EwsClient, loadConfig } from "../ews_client.ts";
export function registerPeopleTools(server: McpServer): void {
server.registerTool(
"find_person",
{
description:
"Search for people in the corporate directory (Active Directory) by name, email, or keyword. Returns a list of Person objects with name, email, jobTitle, department, company, office, phones, manager, directReports, and more.",
inputSchema: z.object({
query: z.string().describe(
"Name, email address, or keyword to search for",
),
}),
},
async ({ query }) => {
try {
const client = new EwsClient(loadConfig());
const resolutions = await client.resolveNames(query, true);
const people = resolutions.map((r: any) => {
const mailbox = r.Mailbox ?? {};
const contact = r.Contact ?? {};
const person: any = {
name: mailbox.Name ?? contact.DisplayName ?? "",
email: mailbox.EmailAddress ?? "",
mailboxType: mailbox.MailboxType ?? "",
firstName: contact.GivenName ?? "",
lastName: contact.Surname ?? "",
jobTitle: contact.JobTitle ?? "",
department: contact.Department ?? "",
company: contact.CompanyName ?? "",
office: contact.OfficeLocation ?? "",
alias: contact.Alias ?? "",
manager: "",
managerEmail: "",
phones: {},
address: "",
directReports: [],
};
const phones = contact.PhoneNumbers?.PhoneNumber ?? [];
const phoneList = Array.isArray(phones) ? phones : [phones];
for (const p of phoneList) {
if (p?.Key && p?.PhoneNumber) {
person.phones[p.Key] = p.PhoneNumber;
}
}
const addrs = contact.PhysicalAddresses?.PhysicalAddress ?? [];
const addrList = Array.isArray(addrs) ? addrs : [addrs];
for (const a of addrList) {
if (a?.Key === "Business") {
const parts = [a.Street, a.City, a.PostalCode, a.CountryOrRegion]
.filter(Boolean);
if (parts.length) {
person.address = parts.join(", ");
}
}
}
const managerData = contact.ManagerMailbox?.Mailbox ?? {};
if (managerData.Name || managerData.EmailAddress) {
person.manager = managerData.Name ?? "";
person.managerEmail = managerData.EmailAddress ?? "";
} else if (contact.Manager) {
person.manager = contact.Manager;
}
const reports = contact.DirectReports?.DirectReport ?? [];
const reportList = Array.isArray(reports) ? reports : [reports];
for (const rp of reportList) {
if (rp?.Name || rp?.EmailAddress) {
person.directReports.push({
name: rp.Name ?? "",
email: rp.EmailAddress ?? "",
});
}
}
return person;
});
return {
content: [{ type: "text" as const, text: JSON.stringify(people) }],
};
} catch (error: any) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({ error: error.message ?? String(error) }),
}],
};
}
},
);
}