feat: more tools
This commit was merged in pull request #2.
This commit is contained in:
+185
-138
@@ -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";
|
||||
|
||||
@@ -30,27 +32,92 @@ export function registerEmailTools(server: McpServer): void {
|
||||
idsOnly: z.boolean().default(false).describe(
|
||||
"If True, return only item IDs and dates (max limit 500)",
|
||||
),
|
||||
query: z.string().optional().describe(
|
||||
"Optional text to search for within the folder",
|
||||
),
|
||||
queryScope: z.enum(["all", "subject", "body", "from"]).default("all")
|
||||
.describe("Where to search (only used when query is set)"),
|
||||
}),
|
||||
},
|
||||
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, "&").replace(/</g, "<").replace(
|
||||
/>/g,
|
||||
">",
|
||||
).replace(/"/g, """)
|
||||
}"/>
|
||||
</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>`;
|
||||
}
|
||||
|
||||
@@ -138,143 +205,150 @@ 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",
|
||||
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",
|
||||
),
|
||||
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, "&").replace(/</g, "<").replace(
|
||||
/>/g,
|
||||
">",
|
||||
).replace(/"/g, """)
|
||||
}"/>
|
||||
</t:Contains>`;
|
||||
}
|
||||
server.registerTool(
|
||||
"download_attachments",
|
||||
{
|
||||
description: "Download all file attachments from an email to disk",
|
||||
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 +360,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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user