-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgmail_server.py
402 lines (368 loc) · 14.1 KB
/
gmail_server.py
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import os
import logging
from pathlib import Path
from typing import List, Optional, Dict, Any
from mcp.server.fastmcp import FastMCP, Context
from gmail_api import (
init_gmail_service,
get_email_message_details,
search_emails,
search_email_conversations,
send_email,
get_email_messages,
download_attachments_parent,
download_attachments_all
)
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('gmail_mcp.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger('gmail_mcp')
# Initialize MCP Server
mcp = FastMCP(
"Gmail MCP Server",
dependencies=["google-api-python-client", "google-auth-oauthlib"]
)
# Gmail Service Initialization
CLIENT_FILE = 'client_secret.json'
def get_gmail_service(email_identifier: str):
try:
service = init_gmail_service(CLIENT_FILE, prefix=f'_{email_identifier}')
if not service:
raise ValueError(f"Failed to initialize Gmail service for {email_identifier}")
return service
except Exception as e:
logger.error(f"Error initializing Gmail service: {str(e)}")
raise
# Resources
@mcp.resource("gmail://inbox/{email_identifier}")
async def get_inbox(email_identifier: str) -> Dict[str, Any]:
"""Get latest emails from inbox"""
try:
logger.info(f"Fetching inbox for {email_identifier}")
service = get_gmail_service(email_identifier)
messages, next_page = get_email_messages(service, max_results=10)
emails = []
for msg in messages:
details = get_email_message_details(service, msg['id'])
if details:
emails.append(details)
return {
"success": True,
"emails": emails,
"has_more": bool(next_page)
}
except Exception as e:
logger.error(f"Error fetching inbox: {str(e)}")
return {"success": False, "message": str(e)}
@mcp.resource("gmail://email/{email_identifier}/{msg_id}")
async def get_email_details(email_identifier: str, msg_id: str) -> Dict[str, Any]:
"""Get detailed information about a specific email"""
try:
logger.info(f"Fetching email details for ID {msg_id}")
service = get_gmail_service(email_identifier)
details = get_email_message_details(service, msg_id)
if details:
return {"success": True, "email": details}
return {"success": False, "message": "Email not found"}
except Exception as e:
logger.error(f"Error fetching email details: {str(e)}")
return {"success": False, "message": str(e)}
@mcp.resource("gmail://attachments/{email_identifier}/{msg_id}")
async def list_attachments(email_identifier: str, msg_id: str) -> Dict[str, Any]:
"""List attachments for a specific email"""
try:
logger.info(f"Listing attachments for email {msg_id}")
service = get_gmail_service(email_identifier)
details = get_email_message_details(service, msg_id)
if details and details.get('has_attachments'):
return {
"success": True,
"has_attachments": True,
"message_id": msg_id
}
return {
"success": True,
"has_attachments": False
}
except Exception as e:
logger.error(f"Error listing attachments: {str(e)}")
return {"success": False, "message": str(e)}
# Tools
@mcp.tool()
async def send_gmail(
email_identifier: str,
to: str,
subject: str,
body: str,
attachment_paths: Optional[List[str]] = None
) -> Dict[str, Any]:
"""Send an email with optional attachments"""
try:
logger.info(f"Sending email to {to} from {email_identifier}")
service = get_gmail_service(email_identifier)
# Validate attachment paths
if attachment_paths:
for path in attachment_paths:
if not os.path.exists(path):
return {
"success": False,
"message": f"Attachment not found: {path}"
}
response = send_email(
service=service,
to=to,
subject=subject,
body=body,
body_type='plain',
attachment_paths=attachment_paths
)
if response:
return {
"success": True,
"message": f"Email sent successfully to {to}",
"message_id": response.get('id', 'unknown')
}
return {
"success": False,
"message": "Failed to send email"
}
except Exception as e:
logger.error(f"Error sending email: {str(e)}")
return {"success": False, "message": str(e)}
@mcp.tool()
async def search_email_tool(
email_identifier: str,
query: str = '',
max_results: int = 30,
include_conversations: bool = True
) -> Dict[str, Any]:
"""Search emails with optional conversation inclusion"""
try:
logger.info(f"Searching emails for {email_identifier} with query: {query}")
service = get_gmail_service(email_identifier)
emails = []
# Search regular emails
messages = search_emails(service, query, max_results=max_results)
for msg in messages:
details = get_email_message_details(service, msg['id'])
if details:
emails.append(details)
# Search conversations if requested
if include_conversations:
conversations = search_email_conversations(service, query, max_results=max_results)
for conv in conversations:
details = get_email_message_details(service, conv['id'])
if details:
emails.append(details)
return {
"success": True,
"message": f"Found {len(emails)} emails",
"emails": emails
}
except Exception as e:
logger.error(f"Error searching emails: {str(e)}")
return {"success": False, "message": str(e), "emails": []}
@mcp.tool()
async def read_latest_emails(
email_identifier: str,
max_results: int = 5,
download_attachments: bool = False
) -> Dict[str, Any]:
"""Read latest emails with optional attachment download"""
try:
logger.info(f"Reading latest {max_results} emails for {email_identifier}")
service = get_gmail_service(email_identifier)
messages, _ = get_email_messages(service, max_results=max_results)
emails = []
attachment_dir = Path('./downloaded_attachments')
if download_attachments:
attachment_dir.mkdir(exist_ok=True)
for msg in messages:
details = get_email_message_details(service, msg['id'])
if details:
if download_attachments and details.get('has_attachments'):
download_attachments_parent(
service,
user_id='me',
msg_id=msg['id'],
target_dir=str(attachment_dir)
)
details['attachments_downloaded'] = True
details['attachment_dir'] = str(attachment_dir)
emails.append(details)
return {
"success": True,
"message": f"Retrieved {len(emails)} latest emails",
"emails": emails,
"attachment_downloads": download_attachments
}
except Exception as e:
logger.error(f"Error reading latest emails: {str(e)}")
return {"success": False, "message": str(e), "emails": []}
@mcp.tool()
async def download_email_attachments(
email_identifier: str,
msg_id: str,
download_all_in_thread: bool = False
) -> Dict[str, Any]:
"""Download attachments for a specific email or its entire thread"""
try:
logger.info(f"Downloading attachments for email {msg_id}")
service = get_gmail_service(email_identifier)
attachment_dir = Path('./downloaded_attachments')
attachment_dir.mkdir(exist_ok=True)
if download_all_in_thread:
download_attachments_all(
service,
user_id='me',
msg_id=msg_id,
target_dir=str(attachment_dir)
)
else:
download_attachments_parent(
service,
user_id='me',
msg_id=msg_id,
target_dir=str(attachment_dir)
)
return {
"success": True,
"message": "Attachments downloaded successfully",
"directory": str(attachment_dir),
"thread_downloaded": download_all_in_thread
}
except Exception as e:
logger.error(f"Error downloading attachments: {str(e)}")
return {"success": False, "message": str(e)}
# Prompts
@mcp.prompt()
def compose_email_prompt() -> Dict[str, Any]:
"""Guide for composing and sending an email"""
return {
"description": "Guide for composing and sending an email",
"messages": [
{
"role": "system",
"content": """You're helping the user compose and send an email. Make sure to collect:
1. Email identifier (the account sending the email)
2. Recipient's email address
3. Subject line
4. Email body content
5. Any attachments (optional) - provide full file paths"""
},
{
"role": "user",
"content": "I need to send an email."
},
{
"role": "assistant",
"content": """I'll help you compose and send an email. Please provide:
1. Which email account should send this? (email identifier)
2. Who are you sending it to? (recipient's email)
3. What's the subject of your email?
4. What would you like to say in the email?
5. Do you need to attach any files? If yes, please provide the file paths."""
}
]
}
@mcp.prompt()
def search_email_prompt() -> Dict[str, Any]:
"""Guide for searching emails with various criteria"""
return {
"description": "Guide for searching emails",
"messages": [
{
"role": "system",
"content": """You're helping the user search through their emails. Collect:
1. Email identifier (which account to search)
2. Search criteria (from, to, subject, date range, etc.)
3. Maximum number of results needed
4. Whether to include conversation threads"""
},
{
"role": "user",
"content": "I want to search my emails."
},
{
"role": "assistant",
"content": """I'll help you search your emails. Please specify:
1. Which email account do you want to search? (email identifier)
2. What are you looking for? You can search by:
- Sender (from:[email protected])
- Subject (subject:meeting)
- Date range (after:2024/01/01 before:2024/02/01)
- Has attachment (has:attachment)
Or combine these criteria.
3. How many results would you like to see? (default is 30)
4. Should I include conversation threads in the search? (yes/no)"""
}
]
}
@mcp.prompt()
def read_latest_emails_prompt() -> Dict[str, Any]:
"""Guide for reading recent emails with optional attachment handling"""
return {
"description": "Guide for reading latest emails",
"messages": [
{
"role": "system",
"content": """You're helping the user read their recent emails. Collect:
1. Email identifier (which account to read)
2. Number of emails to retrieve
3. Whether to automatically download attachments"""
},
{
"role": "user",
"content": "I want to check my recent emails."
},
{
"role": "assistant",
"content": """I'll help you check your recent emails. Please specify:
1. Which email account do you want to check? (email identifier)
2. How many recent emails would you like to see? (default is 5)
3. Should I automatically download any attachments found? (yes/no)
Note: Attachments will be saved to a 'downloaded_attachments' folder."""
}
]
}
@mcp.prompt()
def download_attachments_prompt() -> Dict[str, Any]:
"""Guide for downloading email attachments"""
return {
"description": "Guide for downloading email attachments",
"messages": [
{
"role": "system",
"content": """You're helping the user download email attachments. Collect:
1. Email identifier (which account to use)
2. Message ID of the email
3. Whether to download attachments from the entire conversation thread"""
},
{
"role": "user",
"content": "I want to download attachments from an email."
},
{
"role": "assistant",
"content": """I'll help you download email attachments. Please provide:
1. Which email account has the attachments? (email identifier)
2. What's the Message ID of the email? (You can get this from search results)
3. Do you want to download attachments from the entire conversation thread? (yes/no)
Note: Files will be saved to a 'downloaded_attachments' folder."""
}
]
}
if __name__ == "__main__":
try:
logger.info("Starting Gmail MCP server...")
mcp.run()
except KeyboardInterrupt:
logger.info("Server shutting down gracefully...")
except Exception as e:
logger.error(f"Fatal server error: {str(e)}")