-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathapp.py
More file actions
294 lines (262 loc) · 11.8 KB
/
app.py
File metadata and controls
294 lines (262 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
from datetime import datetime
from typing import Annotated, Literal
from mcp.server.fastmcp import FastMCP
from pydantic import Field
from mcp_email_server.config import (
AccountAttributes,
EmailSettings,
ProviderSettings,
get_settings,
)
from mcp_email_server.emails.dispatcher import dispatch_handler
from mcp_email_server.emails.models import (
AttachmentDownloadResponse,
EmailContentBatchResponse,
EmailMetadataPageResponse,
)
mcp = FastMCP("email")
@mcp.resource("email://{account_name}")
async def get_account(account_name: str) -> EmailSettings | ProviderSettings | None:
settings = get_settings()
return settings.get_account(account_name, masked=True)
@mcp.tool(description="List all configured email accounts with masked credentials.")
async def list_available_accounts() -> list[AccountAttributes]:
settings = get_settings()
return [account.masked() for account in settings.get_accounts()]
@mcp.tool(
description="List all mailboxes (folders) in an email account. Use this to discover available folders like Archive, Sent, Trash, etc."
)
async def list_mailboxes(
account_name: Annotated[str, Field(description="The name of the email account.")],
) -> list[dict]:
handler = dispatch_handler(account_name)
return await handler.list_mailboxes()
@mcp.tool(
description="Search emails using server-side IMAP search. Fast even with thousands of emails. "
"Searches in subject, body, and headers by default."
)
async def search_emails(
account_name: Annotated[str, Field(description="The name of the email account.")],
query: Annotated[str, Field(description="Text to search for in emails.")],
mailbox: Annotated[str, Field(default="INBOX", description="Mailbox to search in.")] = "INBOX",
search_in: Annotated[
Literal["all", "subject", "body", "from"],
Field(default="all", description="Where to search: 'all' (headers+body), 'subject', 'body', or 'from'."),
] = "all",
page: Annotated[int, Field(default=1, description="Page number (starting from 1).")] = 1,
page_size: Annotated[int, Field(default=20, description="Number of results per page.")] = 20,
) -> dict:
handler = dispatch_handler(account_name)
return await handler.search_emails(query, mailbox, search_in, page, page_size)
@mcp.tool(description="Add a new email account configuration to the settings.")
async def add_email_account(email: EmailSettings) -> str:
settings = get_settings()
settings.add_email(email)
settings.store()
return f"Successfully added email account '{email.account_name}'"
@mcp.tool(
description="List email metadata (email_id, subject, sender, recipients, date) without body content. Returns email_id for use with get_emails_content."
)
async def list_emails_metadata(
account_name: Annotated[str, Field(description="The name of the email account.")],
page: Annotated[
int,
Field(default=1, description="The page number to retrieve (starting from 1)."),
] = 1,
page_size: Annotated[int, Field(default=10, description="The number of emails to retrieve per page.")] = 10,
before: Annotated[
datetime | None,
Field(default=None, description="Retrieve emails before this datetime (UTC)."),
] = None,
since: Annotated[
datetime | None,
Field(default=None, description="Retrieve emails since this datetime (UTC)."),
] = None,
subject: Annotated[str | None, Field(default=None, description="Filter emails by subject.")] = None,
from_address: Annotated[str | None, Field(default=None, description="Filter emails by sender address.")] = None,
to_address: Annotated[
str | None,
Field(default=None, description="Filter emails by recipient address."),
] = None,
order: Annotated[
Literal["asc", "desc"],
Field(default=None, description="Order emails by field. `asc` or `desc`."),
] = "desc",
mailbox: Annotated[str, Field(default="INBOX", description="The mailbox to search.")] = "INBOX",
seen: Annotated[
bool | None,
Field(default=None, description="Filter by read status: True=read, False=unread, None=all."),
] = None,
flagged: Annotated[
bool | None,
Field(default=None, description="Filter by flagged/starred status: True=flagged, False=unflagged, None=all."),
] = None,
answered: Annotated[
bool | None,
Field(default=None, description="Filter by replied status: True=replied, False=not replied, None=all."),
] = None,
) -> EmailMetadataPageResponse:
handler = dispatch_handler(account_name)
return await handler.get_emails_metadata(
page=page,
page_size=page_size,
before=before,
since=since,
subject=subject,
from_address=from_address,
to_address=to_address,
order=order,
mailbox=mailbox,
seen=seen,
flagged=flagged,
answered=answered,
)
@mcp.tool(
description="Get the full content (including body) of one or more emails by their email_id. Use list_emails_metadata first to get the email_id."
)
async def get_emails_content(
account_name: Annotated[str, Field(description="The name of the email account.")],
email_ids: Annotated[
list[str],
Field(
description="List of email_id to retrieve (obtained from list_emails_metadata). Can be a single email_id or multiple email_ids."
),
],
mailbox: Annotated[str, Field(default="INBOX", description="The mailbox to retrieve emails from.")] = "INBOX",
) -> EmailContentBatchResponse:
handler = dispatch_handler(account_name)
return await handler.get_emails_content(email_ids, mailbox)
@mcp.tool(
description="Send an email using the specified account. Supports replying to emails with proper threading when in_reply_to is provided.",
)
async def send_email(
account_name: Annotated[str, Field(description="The name of the email account to send from.")],
recipients: Annotated[list[str], Field(description="A list of recipient email addresses.")],
subject: Annotated[str, Field(description="The subject of the email.")],
body: Annotated[str, Field(description="The body of the email.")],
cc: Annotated[
list[str] | None,
Field(default=None, description="A list of CC email addresses."),
] = None,
bcc: Annotated[
list[str] | None,
Field(default=None, description="A list of BCC email addresses."),
] = None,
html: Annotated[
bool,
Field(default=False, description="Whether to send the email as HTML (True) or plain text (False)."),
] = False,
attachments: Annotated[
list[str] | None,
Field(
default=None,
description="A list of absolute file paths to attach to the email. Supports common file types (documents, images, archives, etc.).",
),
] = None,
in_reply_to: Annotated[
str | None,
Field(
default=None,
description="Message-ID of the email being replied to. Enables proper threading in email clients.",
),
] = None,
references: Annotated[
str | None,
Field(
default=None,
description="Space-separated Message-IDs for the thread chain. Usually includes in_reply_to plus ancestors.",
),
] = None,
) -> str:
handler = dispatch_handler(account_name)
await handler.send_email(
recipients,
subject,
body,
cc,
bcc,
html,
attachments,
in_reply_to,
references,
)
recipient_str = ", ".join(recipients)
attachment_info = f" with {len(attachments)} attachment(s)" if attachments else ""
return f"Email sent successfully to {recipient_str}{attachment_info}"
@mcp.tool(
description="Delete one or more emails by their email_id. Use list_emails_metadata first to get the email_id."
)
async def delete_emails(
account_name: Annotated[str, Field(description="The name of the email account.")],
email_ids: Annotated[
list[str],
Field(description="List of email_id to delete (obtained from list_emails_metadata)."),
],
mailbox: Annotated[str, Field(default="INBOX", description="The mailbox to delete emails from.")] = "INBOX",
) -> str:
handler = dispatch_handler(account_name)
deleted_ids, failed_ids = await handler.delete_emails(email_ids, mailbox)
result = f"Successfully deleted {len(deleted_ids)} email(s)"
if failed_ids:
result += f", failed to delete {len(failed_ids)} email(s): {', '.join(failed_ids)}"
return result
@mcp.tool(description="Mark one or more emails as read or unread. Use list_emails_metadata first to get the email_id.")
async def mark_emails_as_read(
account_name: Annotated[str, Field(description="The name of the email account.")],
email_ids: Annotated[
list[str],
Field(description="List of email_id to mark (obtained from list_emails_metadata)."),
],
mailbox: Annotated[str, Field(default="INBOX", description="The mailbox containing the emails.")] = "INBOX",
read: Annotated[bool, Field(default=True, description="True to mark as read, False to mark as unread.")] = True,
) -> str:
handler = dispatch_handler(account_name)
success_ids, failed_ids = await handler.mark_emails_as_read(email_ids, mailbox, read)
status = "read" if read else "unread"
result = f"Successfully marked {len(success_ids)} email(s) as {status}"
if failed_ids:
result += f", failed to mark {len(failed_ids)} email(s): {', '.join(failed_ids)}"
return result
@mcp.tool(
description="Move one or more emails to a different mailbox/folder. Common destinations: 'Archive', 'Trash', 'Spam'. Use list_emails_metadata first to get the email_id."
)
async def move_emails(
account_name: Annotated[str, Field(description="The name of the email account.")],
email_ids: Annotated[
list[str],
Field(description="List of email_id to move (obtained from list_emails_metadata)."),
],
destination_mailbox: Annotated[
str,
Field(description="Target mailbox name (e.g., 'Archive', 'Trash', 'Spam', '[Gmail]/All Mail')."),
],
source_mailbox: Annotated[str, Field(default="INBOX", description="Source mailbox.")] = "INBOX",
) -> str:
handler = dispatch_handler(account_name)
moved_ids, failed_ids = await handler.move_emails(email_ids, destination_mailbox, source_mailbox)
result = f"Successfully moved {len(moved_ids)} email(s) to '{destination_mailbox}'"
if failed_ids:
result += f", failed to move {len(failed_ids)} email(s): {', '.join(failed_ids)}"
return result
@mcp.tool(
description="Download an email attachment and save it to the specified path. This feature must be explicitly enabled in settings (enable_attachment_download=true) due to security considerations.",
)
async def download_attachment(
account_name: Annotated[str, Field(description="The name of the email account.")],
email_id: Annotated[
str, Field(description="The email ID (obtained from list_emails_metadata or get_emails_content).")
],
attachment_name: Annotated[
str, Field(description="The name of the attachment to download (as shown in the attachments list).")
],
save_path: Annotated[str, Field(description="The absolute path where the attachment should be saved.")],
mailbox: Annotated[str, Field(description="The mailbox to search in (default: INBOX).")] = "INBOX",
) -> AttachmentDownloadResponse:
settings = get_settings()
if not settings.enable_attachment_download:
msg = (
"Attachment download is disabled. Set 'enable_attachment_download=true' in settings to enable this feature."
)
raise PermissionError(msg)
handler = dispatch_handler(account_name)
return await handler.download_attachment(email_id, attachment_name, save_path, mailbox)