2 Commits

Author SHA1 Message Date
albnnc 33da3cba1a w 2026-07-09 16:40:00 +03:00
albnnc 8fce57800f w 2026-07-09 16:20:46 +03:00
3 changed files with 82 additions and 194 deletions
+4 -12
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,17 +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 |
| `maxResults` | number | `20` | Max results (max 100) |
| `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.
+8 -1
View File
@@ -250,6 +250,13 @@ export class EwsClient {
traversal = "Shallow", traversal = "Shallow",
} = options; } = options;
const isDistinguished =
DISTINGUISHED_FOLDERS[folderId.toLowerCase()] !== undefined;
const folderIdXml = isDistinguished
? `<t:DistinguishedFolderId Id="${folderId}"/>`
: `<t:FolderId Id="${folderId}"/>`;
const soap = buildSoapEnvelope(`\ const soap = buildSoapEnvelope(`\
<m:FindItem Traversal="${traversal}"> <m:FindItem Traversal="${traversal}">
<m:ItemShape> <m:ItemShape>
@@ -257,7 +264,7 @@ export class EwsClient {
</m:ItemShape> </m:ItemShape>
<m:IndexedPageItemView MaxEntriesReturned="${limit}" Offset="${offset}" BasePoint="Beginning"/> <m:IndexedPageItemView MaxEntriesReturned="${limit}" Offset="${offset}" BasePoint="Beginning"/>
<m:ParentFolderIds> <m:ParentFolderIds>
<t:FolderId Id="${folderId}"/> ${folderIdXml}
</m:ParentFolderIds> </m:ParentFolderIds>
<m:SortOrder> <m:SortOrder>
<t:FieldOrder Order="Descending"> <t:FieldOrder Order="Descending">
+70 -181
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,155 +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",
),
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 }) => {
try {
const client = getClient();
if (!query.trim()) {
return {
content: [{
type: "text" as const,
text: JSON.stringify({
error: "query must not be empty",
results: [],
}),
}],
};
}
maxResults = Math.max(1, Math.min(maxResults, 100));
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 traversal = folderId ? "Shallow" : "Deep";
if (folderId) {
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,
}),
}],
};
} 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);
for (const r of formatted) {
r.folderId = f.id;
r.folderName = f.name;
allResults.push(r);
if (allResults.length >= maxResults) break;
}
}
return {
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) }),
}],
};
}
},
);
server.registerTool( server.registerTool(
"mark_email_read", "mark_email_read",
{ {
@@ -444,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;
}