w
This commit is contained in:
+39
-19
@@ -1,10 +1,10 @@
|
|||||||
import { XMLParser } from "fast-xml-parser";
|
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 fs from "node:fs";
|
||||||
|
import https from "node:https";
|
||||||
|
import { createRequire } from "node:module";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { promisify } from "node:util";
|
||||||
import type { Email, Folder, LoginConfig } from "./models.ts";
|
import type { Email, Folder, LoginConfig } from "./models.ts";
|
||||||
|
|
||||||
const ntlm: any = createRequire(import.meta.url)("httpntlm");
|
const ntlm: any = createRequire(import.meta.url)("httpntlm");
|
||||||
@@ -91,7 +91,7 @@ export class EwsClient {
|
|||||||
return this.config.domain ?? "corp";
|
return this.config.domain ?? "corp";
|
||||||
}
|
}
|
||||||
|
|
||||||
private async soapRequest(body: string, soapAction: string): Promise<any> {
|
private async soapRequest(body: string, soapAction: string): Promise<any> {
|
||||||
const res = await postAsync({
|
const res = await postAsync({
|
||||||
url: this.ewsUrl,
|
url: this.ewsUrl,
|
||||||
username: this.config.username,
|
username: this.config.username,
|
||||||
@@ -154,7 +154,7 @@ private async soapRequest(body: string, soapAction: string): Promise<any> {
|
|||||||
</m:FolderIds>
|
</m:FolderIds>
|
||||||
</m:GetFolder>`);
|
</m:GetFolder>`);
|
||||||
|
|
||||||
const data = await this.soapRequest(
|
const data = await this.soapRequest(
|
||||||
soap,
|
soap,
|
||||||
"http://schemas.microsoft.com/exchange/services/2006/messages/GetFolder",
|
"http://schemas.microsoft.com/exchange/services/2006/messages/GetFolder",
|
||||||
);
|
);
|
||||||
@@ -238,7 +238,8 @@ ${restriction}
|
|||||||
);
|
);
|
||||||
|
|
||||||
for (const msg of this.extractResponseMessages(data)) {
|
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;
|
if (!items) continue;
|
||||||
return Array.isArray(items) ? items : [items];
|
return Array.isArray(items) ? items : [items];
|
||||||
}
|
}
|
||||||
@@ -268,7 +269,13 @@ ${restriction}
|
|||||||
if (!items) continue;
|
if (!items) continue;
|
||||||
|
|
||||||
const itemKey = Object.keys(items).find((k) =>
|
const itemKey = Object.keys(items).find((k) =>
|
||||||
["Message", "CalendarItem", "MeetingRequest", "MeetingResponse", "MeetingCancellation"].includes(k)
|
[
|
||||||
|
"Message",
|
||||||
|
"CalendarItem",
|
||||||
|
"MeetingRequest",
|
||||||
|
"MeetingResponse",
|
||||||
|
"MeetingCancellation",
|
||||||
|
].includes(k)
|
||||||
);
|
);
|
||||||
if (itemKey) {
|
if (itemKey) {
|
||||||
return items[itemKey];
|
return items[itemKey];
|
||||||
@@ -283,7 +290,8 @@ ${restriction}
|
|||||||
recursive: boolean = false,
|
recursive: boolean = false,
|
||||||
): Promise<Folder[]> {
|
): Promise<Folder[]> {
|
||||||
const traversal = recursive ? "Deep" : "Shallow";
|
const traversal = recursive ? "Deep" : "Shallow";
|
||||||
const isDistinguished = DISTINGUISHED_FOLDERS[parentFolderId.toLowerCase()] !== undefined
|
const isDistinguished =
|
||||||
|
DISTINGUISHED_FOLDERS[parentFolderId.toLowerCase()] !== undefined
|
||||||
|| ["msgfolderroot"].includes(parentFolderId.toLowerCase());
|
|| ["msgfolderroot"].includes(parentFolderId.toLowerCase());
|
||||||
|
|
||||||
const folderIdXml = isDistinguished
|
const folderIdXml = isDistinguished
|
||||||
@@ -329,7 +337,10 @@ ${restriction}
|
|||||||
|
|
||||||
extractEmailSummary(item: any): Email {
|
extractEmailSummary(item: any): Email {
|
||||||
const itemType = item["@_xsi_type"] ?? item.__type ?? "";
|
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
|
const fromMailbox = item.From?.Mailbox
|
||||||
?? item.Organizer?.Mailbox
|
?? item.Organizer?.Mailbox
|
||||||
@@ -340,9 +351,11 @@ ${restriction}
|
|||||||
subject: item.Subject ?? "(No subject)",
|
subject: item.Subject ?? "(No subject)",
|
||||||
from: fromMailbox.EmailAddress ?? "",
|
from: fromMailbox.EmailAddress ?? "",
|
||||||
fromName: fromMailbox.Name ?? "",
|
fromName: fromMailbox.Name ?? "",
|
||||||
date: item.DateTimeSent ?? item.DateTimeReceived ?? item.DateTimeCreated ?? "",
|
date: item.DateTimeSent ?? item.DateTimeReceived ?? item.DateTimeCreated
|
||||||
|
?? "",
|
||||||
isRead: item.IsRead === "true" || item.IsRead === true,
|
isRead: item.IsRead === "true" || item.IsRead === true,
|
||||||
hasAttachments: item.HasAttachments === "true" || item.HasAttachments === true,
|
hasAttachments: item.HasAttachments === "true"
|
||||||
|
|| item.HasAttachments === true,
|
||||||
hasLinks: false,
|
hasLinks: false,
|
||||||
itemId: item.ItemId?.["@_Id"] ?? "",
|
itemId: item.ItemId?.["@_Id"] ?? "",
|
||||||
size: item.Size ? Number(item.Size) : 0,
|
size: item.Size ? Number(item.Size) : 0,
|
||||||
@@ -357,15 +370,20 @@ ${restriction}
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (item.DisplayTo) {
|
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) {
|
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) {
|
if (isMeeting) {
|
||||||
email.location = item.Location ?? "";
|
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 ?? "";
|
email.end = item.End ?? item.EndWallClock ?? "";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -416,11 +434,13 @@ ${restriction}
|
|||||||
isInline: a.IsInline === "true" || a.IsInline === true,
|
isInline: a.IsInline === "true" || a.IsInline === true,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const isMeeting = /MeetingRequest|MeetingResponse|MeetingCancellation|CalendarItem/i.test(
|
const isMeeting =
|
||||||
item["@_xsi_type"] ?? "",
|
/MeetingRequest|MeetingResponse|MeetingCancellation|CalendarItem/i.test(
|
||||||
);
|
item["@_xsi_type"] ?? "",
|
||||||
|
);
|
||||||
if (isMeeting) {
|
if (isMeeting) {
|
||||||
email.location = item.Location ?? item.EnhancedLocation?.DisplayName ?? "";
|
email.location = item.Location ?? item.EnhancedLocation?.DisplayName
|
||||||
|
?? "";
|
||||||
email.start = item.Start ?? "";
|
email.start = item.Start ?? "";
|
||||||
email.end = item.End ?? "";
|
email.end = item.End ?? "";
|
||||||
|
|
||||||
@@ -462,7 +482,7 @@ ${restriction}
|
|||||||
text = text.replace(/&/g, "&");
|
text = text.replace(/&/g, "&");
|
||||||
text = text.replace(/</g, "<");
|
text = text.replace(/</g, "<");
|
||||||
text = text.replace(/>/g, ">");
|
text = text.replace(/>/g, ">");
|
||||||
text = text.replace(/"/g, '"');
|
text = text.replace(/"/g, "\"");
|
||||||
text = text.replace(/'/g, "'");
|
text = text.replace(/'/g, "'");
|
||||||
text = text.replace(/\n\s*\n/g, "\n\n");
|
text = text.replace(/\n\s*\n/g, "\n\n");
|
||||||
text = text.replace(/[ \t]+/g, " ");
|
text = text.replace(/[ \t]+/g, " ");
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
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 { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
||||||
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||||
import { Command } from "commander";
|
import { Command } from "commander";
|
||||||
import http from "node:http";
|
|
||||||
import crypto from "node:crypto";
|
import crypto from "node:crypto";
|
||||||
|
import http from "node:http";
|
||||||
import { registerAuthTools } from "./tools/auth.ts";
|
import { registerAuthTools } from "./tools/auth.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";
|
||||||
@@ -12,7 +12,10 @@ const program = new Command()
|
|||||||
.name("exchange-mcp")
|
.name("exchange-mcp")
|
||||||
.description("Exchange MCP Server — EWS integration via MCP")
|
.description("Exchange MCP Server — EWS integration via MCP")
|
||||||
.option("--transport <type>", "Transport: stdio or sse", "stdio")
|
.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("--host <host>", "HTTP host", "127.0.0.1")
|
||||||
.option("--port <port>", "HTTP port", "8000");
|
.option("--port <port>", "HTTP port", "8000");
|
||||||
|
|
||||||
@@ -55,7 +58,10 @@ async function runSSE() {
|
|||||||
|
|
||||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
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") {
|
if (req.method === "OPTIONS") {
|
||||||
res.writeHead(200);
|
res.writeHead(200);
|
||||||
@@ -113,7 +119,9 @@ async function main() {
|
|||||||
await runSSE();
|
await runSSE();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
console.error(`Unsupported transport: "${transportType}". Use "stdio" or "sse".`);
|
console.error(
|
||||||
|
`Unsupported transport: "${transportType}". Use "stdio" or "sse".`,
|
||||||
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+45
-8
@@ -1,6 +1,11 @@
|
|||||||
import { z } from "zod/v4";
|
|
||||||
import { EwsClient, loadConfig, saveConfig, clearConfig } from "../ews_client.ts";
|
|
||||||
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||||
|
import { z } from "zod/v4";
|
||||||
|
import {
|
||||||
|
clearConfig,
|
||||||
|
EwsClient,
|
||||||
|
loadConfig,
|
||||||
|
saveConfig,
|
||||||
|
} from "../ews_client.ts";
|
||||||
|
|
||||||
export function registerAuthTools(server: McpServer): void {
|
export function registerAuthTools(server: McpServer): void {
|
||||||
server.registerTool(
|
server.registerTool(
|
||||||
@@ -8,7 +13,9 @@ export function registerAuthTools(server: McpServer): void {
|
|||||||
{
|
{
|
||||||
description: "Authenticate to Exchange EWS using NTLM credentials",
|
description: "Authenticate to Exchange EWS using NTLM credentials",
|
||||||
inputSchema: z.object({
|
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"),
|
email: z.string().describe("Email address"),
|
||||||
username: z.string().describe("NTLM username"),
|
username: z.string().describe("NTLM username"),
|
||||||
password: z.string().describe("NTLM password"),
|
password: z.string().describe("NTLM password"),
|
||||||
@@ -30,18 +37,36 @@ export function registerAuthTools(server: McpServer): void {
|
|||||||
|
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
return {
|
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);
|
saveConfig(config);
|
||||||
|
|
||||||
return {
|
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) {
|
} catch (error: any) {
|
||||||
return {
|
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),
|
||||||
|
}),
|
||||||
|
}],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -72,7 +97,13 @@ export function registerAuthTools(server: McpServer): void {
|
|||||||
};
|
};
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
return {
|
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 +118,13 @@ export function registerAuthTools(server: McpServer): void {
|
|||||||
async () => {
|
async () => {
|
||||||
clearConfig();
|
clearConfig();
|
||||||
return {
|
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
@@ -1,6 +1,6 @@
|
|||||||
|
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, loadConfig } from "../ews_client.ts";
|
||||||
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
||||||
|
|
||||||
function getClient(): EwsClient {
|
function getClient(): EwsClient {
|
||||||
return new EwsClient(loadConfig());
|
return new EwsClient(loadConfig());
|
||||||
@@ -12,12 +12,24 @@ export function registerEmailTools(server: McpServer): void {
|
|||||||
{
|
{
|
||||||
description: "Get emails from a mailbox folder",
|
description: "Get emails from a mailbox folder",
|
||||||
inputSchema: z.object({
|
inputSchema: z.object({
|
||||||
folder: z.string().default("Inbox").describe("Folder name (Inbox, Sent, Drafts, Deleted, Junk, or custom)"),
|
folder: z.string().default("Inbox").describe(
|
||||||
limit: z.number().default(10).describe("Maximum number of emails to return (default 10, max 50)"),
|
"Folder name (Inbox, Sent, Drafts, Deleted, Junk, or custom)",
|
||||||
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)"),
|
limit: z.number().default(10).describe(
|
||||||
unreadOnly: z.boolean().default(false).describe("If True, only return unread emails"),
|
"Maximum number of emails to return (default 10, max 50)",
|
||||||
idsOnly: z.boolean().default(false).describe("If True, return only item IDs and dates (max limit 500)"),
|
),
|
||||||
|
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 }) => {
|
async ({ folder, limit, offset, includeBody, unreadOnly, idsOnly }) => {
|
||||||
@@ -42,7 +54,12 @@ export function registerEmailTools(server: McpServer): void {
|
|||||||
</m:Restriction>`;
|
</m:Restriction>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const items = await client.findItems(folderId, { limit, offset, baseShape, restriction });
|
const items = await client.findItems(folderId, {
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
baseShape,
|
||||||
|
restriction,
|
||||||
|
});
|
||||||
|
|
||||||
if (idsOnly) {
|
if (idsOnly) {
|
||||||
const result = items.map((item: any) => ({
|
const result = items.map((item: any) => ({
|
||||||
@@ -51,7 +68,10 @@ export function registerEmailTools(server: McpServer): void {
|
|||||||
subject: item.Subject ?? "",
|
subject: item.Subject ?? "",
|
||||||
}));
|
}));
|
||||||
return {
|
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 {
|
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) {
|
} catch (error: any) {
|
||||||
return {
|
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",
|
description: "Get a single email with full body and details",
|
||||||
inputSchema: z.object({
|
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 }) => {
|
async ({ itemId }) => {
|
||||||
@@ -100,7 +128,10 @@ export function registerEmailTools(server: McpServer): void {
|
|||||||
};
|
};
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
return {
|
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",
|
description: "Search emails by text across one or all folders",
|
||||||
inputSchema: z.object({
|
inputSchema: z.object({
|
||||||
query: z.string().describe("The text to search for"),
|
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"),
|
folderId: z.string().optional().describe(
|
||||||
maxResults: z.number().default(20).describe("Maximum number of results (default 20, max 100)"),
|
"Optional folder ID to limit the search. When omitted, searches all mail folders",
|
||||||
searchScope: z.enum(["all", "subject", "body", "from"]).default("all").describe("Where to search"),
|
),
|
||||||
|
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 }) => {
|
async ({ query, folderId, maxResults, searchScope }) => {
|
||||||
@@ -123,7 +159,13 @@ export function registerEmailTools(server: McpServer): void {
|
|||||||
|
|
||||||
if (!query.trim()) {
|
if (!query.trim()) {
|
||||||
return {
|
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 `\
|
return `\
|
||||||
<t:Contains ContainmentMode="Substring" ContainmentComparison="IgnoreCase">
|
<t:Contains ContainmentMode="Substring" ContainmentComparison="IgnoreCase">
|
||||||
<t:FieldURI FieldURI="${fieldUri}"/>
|
<t:FieldURI FieldURI="${fieldUri}"/>
|
||||||
<t:Constant Value="${value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """)}"/>
|
<t:Constant Value="${
|
||||||
|
value.replace(/&/g, "&").replace(/</g, "<").replace(
|
||||||
|
/>/g,
|
||||||
|
">",
|
||||||
|
).replace(/"/g, """)
|
||||||
|
}"/>
|
||||||
</t:Contains>`;
|
</t:Contains>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,7 +203,13 @@ export function registerEmailTools(server: McpServer): void {
|
|||||||
const fieldUri = fieldUriMap[searchScope];
|
const fieldUri = fieldUriMap[searchScope];
|
||||||
if (!fieldUri) {
|
if (!fieldUri) {
|
||||||
return {
|
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 = `\
|
restriction = `\
|
||||||
@@ -168,11 +221,24 @@ export function registerEmailTools(server: McpServer): void {
|
|||||||
const traversal = folderId ? "Shallow" : "Deep";
|
const traversal = folderId ? "Shallow" : "Deep";
|
||||||
|
|
||||||
if (folderId) {
|
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);
|
const results = formatSearchResults(items, client, maxResults);
|
||||||
|
|
||||||
return {
|
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 {
|
} else {
|
||||||
const folders = await client.findFolders("msgfolderroot", true);
|
const folders = await client.findFolders("msgfolderroot", true);
|
||||||
@@ -181,7 +247,11 @@ export function registerEmailTools(server: McpServer): void {
|
|||||||
for (const f of folders) {
|
for (const f of folders) {
|
||||||
if (allResults.length >= maxResults) break;
|
if (allResults.length >= maxResults) break;
|
||||||
const remaining = maxResults - allResults.length;
|
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);
|
const formatted = formatSearchResults(items, client, remaining);
|
||||||
|
|
||||||
for (const r of formatted) {
|
for (const r of formatted) {
|
||||||
@@ -193,19 +263,35 @@ export function registerEmailTools(server: McpServer): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
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) {
|
} catch (error: any) {
|
||||||
return {
|
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[] = [];
|
const results: any[] = [];
|
||||||
for (const item of items) {
|
for (const item of items) {
|
||||||
if (results.length >= maxResults) break;
|
if (results.length >= maxResults) break;
|
||||||
@@ -215,7 +301,8 @@ function formatSearchResults(items: any[], client: EwsClient, maxResults: number
|
|||||||
const bodyType = item.Body?.["@_BodyType"] ?? "HTML";
|
const bodyType = item.Body?.["@_BodyType"] ?? "HTML";
|
||||||
let bodyPreview = "";
|
let bodyPreview = "";
|
||||||
if (bodyType === "HTML" && bodyHtml) {
|
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 {
|
} else {
|
||||||
bodyPreview = bodyHtml.slice(0, 200);
|
bodyPreview = bodyHtml.slice(0, 200);
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-4
@@ -1,6 +1,6 @@
|
|||||||
|
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, loadConfig } from "../ews_client.ts";
|
||||||
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
||||||
|
|
||||||
export function registerFolderTools(server: McpServer): void {
|
export function registerFolderTools(server: McpServer): void {
|
||||||
server.registerTool(
|
server.registerTool(
|
||||||
@@ -8,8 +8,12 @@ export function registerFolderTools(server: McpServer): void {
|
|||||||
{
|
{
|
||||||
description: "List mail folders from the Exchange mailbox",
|
description: "List mail folders from the Exchange mailbox",
|
||||||
inputSchema: z.object({
|
inputSchema: z.object({
|
||||||
parentFolderId: z.string().default("msgfolderroot").describe("Parent folder to list children of (default: msgfolderroot)"),
|
parentFolderId: z.string().default("msgfolderroot").describe(
|
||||||
recursive: z.boolean().default(false).describe("If True, traverse all subfolders recursively"),
|
"Parent folder to list children of (default: msgfolderroot)",
|
||||||
|
),
|
||||||
|
recursive: z.boolean().default(false).describe(
|
||||||
|
"If True, traverse all subfolders recursively",
|
||||||
|
),
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
async ({ parentFolderId, recursive }) => {
|
async ({ parentFolderId, recursive }) => {
|
||||||
@@ -22,7 +26,10 @@ export function registerFolderTools(server: McpServer): void {
|
|||||||
};
|
};
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
return {
|
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) }),
|
||||||
|
}],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user