This commit is contained in:
2026-07-09 16:40:00 +03:00
parent 8fce57800f
commit 33da3cba1a
3 changed files with 75 additions and 166 deletions
+4 -13
View File
@@ -56,7 +56,8 @@ Clear stored credentials. No parameters.
#### `get_emails` #### `get_emails`
Get emails from a folder. Get emails from a folder. Supports optional text search via
`query`/`queryScope`.
| Parameter | Type | Default | Description | | Parameter | Type | Default | Description |
| ------------- | ------- | --------- | ----------------------------------------------------------------------------------- | | ------------- | ------- | --------- | ----------------------------------------------------------------------------------- |
@@ -66,6 +67,8 @@ Get emails from a folder.
| `includeBody` | boolean | `false` | If `true`, fetches full email body | | `includeBody` | boolean | `false` | If `true`, fetches full email body |
| `unreadOnly` | boolean | `false` | Only unread emails | | `unreadOnly` | boolean | `false` | Only unread emails |
| `idsOnly` | boolean | `false` | Return only IDs + dates + subjects (faster, higher limit) | | `idsOnly` | boolean | `false` | Return only IDs + dates + subjects (faster, higher limit) |
| `query` | string | — | Text to search for within the folder |
| `queryScope` | enum | `"all"` | Scope: `all`, `subject`, `body`, `from` (only when `query` is set) |
#### `get_email` #### `get_email`
@@ -75,18 +78,6 @@ Get a single email with full body and details.
| --------- | ------ | -------- | ---------------------------- | | --------- | ------ | -------- | ---------------------------- |
| `itemId` | string | yes | Exchange ItemId of the email | | `itemId` | string | yes | Exchange ItemId of the email |
#### `search_emails`
Search emails by text.
| Parameter | Type | Default | Description |
| ------------- | ------ | -------- | ------------------------------------------- |
| `query` | string | — | Text to search for |
| `folderId` | string | optional | Folder ID to limit search; omitted = all |
| `limit` | number | `10` | Max emails (max 50) |
| `offset` | number | `0` | Pagination offset |
| `searchScope` | enum | `"all"` | Scope: `all`, `subject`, `body`, `from` |
#### `mark_email_read` #### `mark_email_read`
Mark emails as read or unread. Mark emails as read or unread.
+1 -2
View File
@@ -251,8 +251,7 @@ export class EwsClient {
} = options; } = options;
const isDistinguished = const isDistinguished =
DISTINGUISHED_FOLDERS[folderId.toLowerCase()] !== undefined DISTINGUISHED_FOLDERS[folderId.toLowerCase()] !== undefined;
|| ["msgfolderroot"].includes(folderId.toLowerCase());
const folderIdXml = isDistinguished const folderIdXml = isDistinguished
? `<t:DistinguishedFolderId Id="${folderId}"/>` ? `<t:DistinguishedFolderId Id="${folderId}"/>`
+70 -151
View File
@@ -32,27 +32,92 @@ export function registerEmailTools(server: McpServer): void {
idsOnly: z.boolean().default(false).describe( idsOnly: z.boolean().default(false).describe(
"If True, return only item IDs and dates (max limit 500)", "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 { try {
const client = getClient(); const client = getClient();
const maxLimit = idsOnly ? 500 : 50; const maxLimit = idsOnly ? 500 : 50;
if (limit > maxLimit) limit = maxLimit; if (limit > maxLimit) limit = maxLimit;
offset = Math.max(0, offset);
const folderId = await client.getFolderId(folder); const folderId = await client.getFolderId(folder);
const baseShape = idsOnly ? "IdOnly" : "AllProperties"; const baseShape = idsOnly ? "IdOnly" : "AllProperties";
let restriction = ""; if (query && !query.trim()) query = undefined;
const restrictions: string[] = [];
if (unreadOnly) { if (unreadOnly) {
restriction = `\ restrictions.push(`\
<m:Restriction>
<t:IsEqualTo> <t:IsEqualTo>
<t:FieldURI FieldURI="message:IsRead"/> <t:FieldURI FieldURI="message:IsRead"/>
<t:FieldURIOrConstant> <t:FieldURIOrConstant>
<t:Constant Value="false"/> <t:Constant Value="false"/>
</t:FieldURIOrConstant> </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>`; </m:Restriction>`;
} }
@@ -139,127 +204,6 @@ export function registerEmailTools(server: McpServer): void {
}, },
); );
server.registerTool(
"search_emails",
{
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",
),
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",
),
searchScope: z.enum(["all", "subject", "body", "from"]).default("all")
.describe("Where to search"),
}),
},
async ({ query, folderId, limit, offset, searchScope }) => {
try {
const client = getClient();
if (!query.trim()) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({
error: "query must not be empty",
results: [],
}),
}],
};
}
limit = Math.max(1, Math.min(limit, 50));
offset = Math.max(0, offset);
const fieldUriMap: Record<string, string> = {
subject: "item:Subject",
body: "item:Body",
from: "message:From",
};
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>`;
}
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 targetFolder = folderId || "msgfolderroot";
const traversal = folderId ? "Shallow" : "Deep";
const items = await client.findItems(targetFolder, {
limit,
offset,
restriction,
traversal,
});
const results = formatSearchResults(items, client);
return {
content: [{
type: "text" as const,
text: JSON.stringify({
query,
searchScope,
folderId: folderId || "all",
limit,
offset,
totalResults: results.length,
results,
}),
}],
};
} catch (error: any) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({ error: error.message ?? String(error) }),
}],
};
}
},
);
server.registerTool( server.registerTool(
"mark_email_read", "mark_email_read",
{ {
@@ -416,28 +360,3 @@ export function registerEmailTools(server: McpServer): void {
}, },
); );
} }
function formatSearchResults(
items: any[],
client: EwsClient,
): any[] {
const results: any[] = [];
for (const item of items) {
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;
}