This commit is contained in:
2026-07-09 09:08:39 +03:00
parent d09b6145d2
commit d517162081
7 changed files with 228 additions and 69 deletions
+114 -27
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);
}
@@ -225,4 +312,4 @@ function formatSearchResults(items: any[], client: EwsClient, maxResults: number
results.push(summary);
}
return results;
}
}