Arun Raghav
commited on
Commit
·
6b7ccb5
1
Parent(s):
627b659
removed open ai involvement
Browse files
agentic_implementation/email_mcp_server_oauth.py
CHANGED
@@ -1,3 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import json
|
3 |
import os
|
@@ -7,18 +12,93 @@ from dotenv import load_dotenv
|
|
7 |
|
8 |
# Import OAuth-enabled modules
|
9 |
from tools import extract_query_info, analyze_emails
|
10 |
-
from gmail_api_scraper import
|
11 |
from oauth_manager import oauth_manager
|
12 |
from logger import logger
|
13 |
|
14 |
load_dotenv()
|
15 |
|
|
|
|
|
|
|
16 |
def check_authentication() -> tuple[bool, str]:
|
17 |
-
"""Check if user is authenticated and return status
|
18 |
-
|
19 |
-
|
20 |
-
return True,
|
21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
def authenticate_user() -> str:
|
24 |
"""
|
@@ -203,18 +283,20 @@ def remove_account(email_to_remove: str) -> str:
|
|
203 |
}
|
204 |
return json.dumps(error_result, indent=2)
|
205 |
|
206 |
-
def search_emails(
|
207 |
"""
|
208 |
-
Search for emails
|
209 |
|
210 |
Args:
|
211 |
-
|
|
|
|
|
212 |
|
213 |
Returns:
|
214 |
str: JSON string containing email search results and analysis
|
215 |
"""
|
216 |
try:
|
217 |
-
logger.info("OAuth Email search tool called with
|
218 |
|
219 |
# Check authentication
|
220 |
is_auth, auth_info = check_authentication()
|
@@ -225,11 +307,13 @@ def search_emails(query: str) -> str:
|
|
225 |
"auth_status": auth_info
|
226 |
}, indent=2)
|
227 |
|
228 |
-
#
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
|
|
|
|
233 |
|
234 |
logger.info(f"Searching for emails with keyword '{sender_keyword}' between {start_date} and {end_date}")
|
235 |
|
@@ -238,7 +322,8 @@ def search_emails(query: str) -> str:
|
|
238 |
|
239 |
if not full_emails:
|
240 |
result = {
|
241 |
-
"
|
|
|
242 |
"email_summary": [],
|
243 |
"analysis": {"summary": f"No emails found for '{sender_keyword}' in the specified date range.", "insights": []},
|
244 |
"email_count": 0,
|
@@ -259,12 +344,13 @@ def search_emails(query: str) -> str:
|
|
259 |
}
|
260 |
email_summary.append(summary_email)
|
261 |
|
262 |
-
# Auto-analyze the emails for insights
|
263 |
-
analysis =
|
264 |
|
265 |
# Return summary info with analysis
|
266 |
result = {
|
267 |
-
"
|
|
|
268 |
"email_summary": email_summary,
|
269 |
"analysis": analysis,
|
270 |
"email_count": len(full_emails),
|
@@ -277,8 +363,8 @@ def search_emails(query: str) -> str:
|
|
277 |
logger.error("Error in search_emails: %s", e)
|
278 |
error_result = {
|
279 |
"error": str(e),
|
280 |
-
"
|
281 |
-
"message": "Failed to search emails.
|
282 |
}
|
283 |
return json.dumps(error_result, indent=2)
|
284 |
|
@@ -371,8 +457,8 @@ def analyze_email_patterns(sender_keyword: str, days_back: str = "30") -> str:
|
|
371 |
}
|
372 |
return json.dumps(result, indent=2)
|
373 |
|
374 |
-
# Analyze the emails
|
375 |
-
analysis =
|
376 |
|
377 |
result = {
|
378 |
"sender_keyword": sender_keyword,
|
@@ -436,11 +522,13 @@ def get_authentication_status() -> str:
|
|
436 |
search_interface = gr.Interface(
|
437 |
fn=search_emails,
|
438 |
inputs=[
|
439 |
-
gr.Textbox(label="
|
|
|
|
|
440 |
],
|
441 |
outputs=gr.Textbox(label="Search Results", lines=20),
|
442 |
title="Email Search (OAuth)",
|
443 |
-
description="Search your emails
|
444 |
)
|
445 |
|
446 |
details_interface = gr.Interface(
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
Gmail MCP Server with OAuth Authentication and Multi-Account Support
|
4 |
+
"""
|
5 |
+
|
6 |
import gradio as gr
|
7 |
import json
|
8 |
import os
|
|
|
12 |
|
13 |
# Import OAuth-enabled modules
|
14 |
from tools import extract_query_info, analyze_emails
|
15 |
+
from gmail_api_scraper import GmailAPIScraper
|
16 |
from oauth_manager import oauth_manager
|
17 |
from logger import logger
|
18 |
|
19 |
load_dotenv()
|
20 |
|
21 |
+
# Initialize Gmail API scraper
|
22 |
+
gmail_scraper = GmailAPIScraper()
|
23 |
+
|
24 |
def check_authentication() -> tuple[bool, str]:
|
25 |
+
"""Check if user is authenticated and return status"""
|
26 |
+
current_account = oauth_manager.get_current_account()
|
27 |
+
if current_account and oauth_manager.is_authenticated():
|
28 |
+
return True, current_account
|
29 |
+
else:
|
30 |
+
return False, "Not authenticated"
|
31 |
+
|
32 |
+
def simple_analyze_emails(emails) -> dict:
|
33 |
+
"""
|
34 |
+
Simple email analysis without OpenAI - just basic statistics and patterns
|
35 |
+
"""
|
36 |
+
if not emails:
|
37 |
+
return {"summary": "No emails to analyze.", "insights": []}
|
38 |
+
|
39 |
+
# Basic statistics
|
40 |
+
total_count = len(emails)
|
41 |
+
|
42 |
+
# Group by sender
|
43 |
+
senders = {}
|
44 |
+
subjects = []
|
45 |
+
dates = []
|
46 |
+
|
47 |
+
for email in emails:
|
48 |
+
sender = email.get("from", "Unknown")
|
49 |
+
# Extract just the email domain for grouping
|
50 |
+
if "<" in sender and ">" in sender:
|
51 |
+
email_part = sender.split("<")[1].split(">")[0]
|
52 |
+
else:
|
53 |
+
email_part = sender
|
54 |
+
|
55 |
+
domain = email_part.split("@")[-1] if "@" in email_part else sender
|
56 |
+
|
57 |
+
senders[domain] = senders.get(domain, 0) + 1
|
58 |
+
subjects.append(email.get("subject", ""))
|
59 |
+
dates.append(email.get("date", ""))
|
60 |
+
|
61 |
+
# Create insights
|
62 |
+
insights = []
|
63 |
+
insights.append(f"Found {total_count} emails total")
|
64 |
+
|
65 |
+
if senders:
|
66 |
+
top_sender = max(senders.items(), key=lambda x: x[1])
|
67 |
+
insights.append(f"Most emails from: {top_sender[0]} ({top_sender[1]} emails)")
|
68 |
+
|
69 |
+
if len(senders) > 1:
|
70 |
+
insights.append(f"Emails from {len(senders)} different domains")
|
71 |
+
|
72 |
+
# Date range
|
73 |
+
if dates:
|
74 |
+
unique_dates = list(set(dates))
|
75 |
+
if len(unique_dates) > 1:
|
76 |
+
insights.append(f"Spanning {len(unique_dates)} different days")
|
77 |
+
|
78 |
+
# Subject analysis
|
79 |
+
if subjects:
|
80 |
+
# Count common words in subjects (simple approach)
|
81 |
+
all_words = []
|
82 |
+
for subject in subjects:
|
83 |
+
words = subject.lower().split()
|
84 |
+
all_words.extend([w for w in words if len(w) > 3]) # Only words longer than 3 chars
|
85 |
+
|
86 |
+
if all_words:
|
87 |
+
word_counts = {}
|
88 |
+
for word in all_words:
|
89 |
+
word_counts[word] = word_counts.get(word, 0) + 1
|
90 |
+
|
91 |
+
if word_counts:
|
92 |
+
common_word = max(word_counts.items(), key=lambda x: x[1])
|
93 |
+
if common_word[1] > 1:
|
94 |
+
insights.append(f"Common subject word: '{common_word[0]}' appears {common_word[1]} times")
|
95 |
+
|
96 |
+
summary = f"Analysis of {total_count} emails from {len(senders)} sender(s)"
|
97 |
+
|
98 |
+
return {
|
99 |
+
"summary": summary,
|
100 |
+
"insights": insights
|
101 |
+
}
|
102 |
|
103 |
def authenticate_user() -> str:
|
104 |
"""
|
|
|
283 |
}
|
284 |
return json.dumps(error_result, indent=2)
|
285 |
|
286 |
+
def search_emails(sender_keyword: str, start_date: str = "", end_date: str = "") -> str:
|
287 |
"""
|
288 |
+
Search for emails from a specific sender within a date range using OAuth authentication.
|
289 |
|
290 |
Args:
|
291 |
+
sender_keyword (str): The sender/company keyword to search for (e.g., "apple", "amazon")
|
292 |
+
start_date (str): Start date in DD-MMM-YYYY format (e.g., "01-Jan-2025"). If empty, defaults to 7 days ago.
|
293 |
+
end_date (str): End date in DD-MMM-YYYY format (e.g., "07-Jan-2025"). If empty, defaults to today.
|
294 |
|
295 |
Returns:
|
296 |
str: JSON string containing email search results and analysis
|
297 |
"""
|
298 |
try:
|
299 |
+
logger.info("OAuth Email search tool called with sender: %s, dates: %s to %s", sender_keyword, start_date, end_date)
|
300 |
|
301 |
# Check authentication
|
302 |
is_auth, auth_info = check_authentication()
|
|
|
307 |
"auth_status": auth_info
|
308 |
}, indent=2)
|
309 |
|
310 |
+
# Set default date range if not provided
|
311 |
+
if not start_date or not end_date:
|
312 |
+
today = datetime.today()
|
313 |
+
if not end_date:
|
314 |
+
end_date = today.strftime("%d-%b-%Y")
|
315 |
+
if not start_date:
|
316 |
+
start_date = (today - timedelta(days=7)).strftime("%d-%b-%Y")
|
317 |
|
318 |
logger.info(f"Searching for emails with keyword '{sender_keyword}' between {start_date} and {end_date}")
|
319 |
|
|
|
322 |
|
323 |
if not full_emails:
|
324 |
result = {
|
325 |
+
"sender_keyword": sender_keyword,
|
326 |
+
"date_range": f"{start_date} to {end_date}",
|
327 |
"email_summary": [],
|
328 |
"analysis": {"summary": f"No emails found for '{sender_keyword}' in the specified date range.", "insights": []},
|
329 |
"email_count": 0,
|
|
|
344 |
}
|
345 |
email_summary.append(summary_email)
|
346 |
|
347 |
+
# Auto-analyze the emails for insights (no OpenAI)
|
348 |
+
analysis = simple_analyze_emails(full_emails)
|
349 |
|
350 |
# Return summary info with analysis
|
351 |
result = {
|
352 |
+
"sender_keyword": sender_keyword,
|
353 |
+
"date_range": f"{start_date} to {end_date}",
|
354 |
"email_summary": email_summary,
|
355 |
"analysis": analysis,
|
356 |
"email_count": len(full_emails),
|
|
|
363 |
logger.error("Error in search_emails: %s", e)
|
364 |
error_result = {
|
365 |
"error": str(e),
|
366 |
+
"sender_keyword": sender_keyword,
|
367 |
+
"message": "Failed to search emails."
|
368 |
}
|
369 |
return json.dumps(error_result, indent=2)
|
370 |
|
|
|
457 |
}
|
458 |
return json.dumps(result, indent=2)
|
459 |
|
460 |
+
# Analyze the emails (no OpenAI)
|
461 |
+
analysis = simple_analyze_emails(full_emails)
|
462 |
|
463 |
result = {
|
464 |
"sender_keyword": sender_keyword,
|
|
|
522 |
search_interface = gr.Interface(
|
523 |
fn=search_emails,
|
524 |
inputs=[
|
525 |
+
gr.Textbox(label="Sender Keyword", placeholder="apple, amazon, etc."),
|
526 |
+
gr.Textbox(label="Start Date (Optional)", placeholder="01-Jan-2025 (leave empty for last 7 days)"),
|
527 |
+
gr.Textbox(label="End Date (Optional)", placeholder="07-Jan-2025 (leave empty for today)")
|
528 |
],
|
529 |
outputs=gr.Textbox(label="Search Results", lines=20),
|
530 |
title="Email Search (OAuth)",
|
531 |
+
description="Search your emails by sender keyword and date range with OAuth authentication"
|
532 |
)
|
533 |
|
534 |
details_interface = gr.Interface(
|
agentic_implementation/requirements_oauth.txt
CHANGED
@@ -1,21 +1,22 @@
|
|
1 |
-
# Core
|
2 |
-
gradio
|
3 |
-
|
4 |
-
|
|
|
|
|
|
|
5 |
requests
|
|
|
|
|
6 |
|
7 |
-
#
|
8 |
-
|
9 |
-
google-auth-oauthlib>=1.0.0
|
10 |
-
google-auth-httplib2>=0.2.0
|
11 |
-
google-api-python-client>=2.70.0
|
12 |
|
13 |
-
#
|
14 |
-
|
|
|
|
|
15 |
|
16 |
-
#
|
17 |
-
|
18 |
-
|
19 |
-
numpy
|
20 |
-
matplotlib
|
21 |
-
seaborn
|
|
|
1 |
+
# Core OAuth Gmail MCP Server Dependencies
|
2 |
+
gradio
|
3 |
+
google-auth
|
4 |
+
google-auth-oauthlib
|
5 |
+
google-auth-httplib2
|
6 |
+
google-api-python-client
|
7 |
+
cryptography
|
8 |
requests
|
9 |
+
loguru
|
10 |
+
python-dateutil
|
11 |
|
12 |
+
# MCP server support
|
13 |
+
mcp
|
|
|
|
|
|
|
14 |
|
15 |
+
# Email processing
|
16 |
+
email-validator
|
17 |
+
beautifulsoup4
|
18 |
+
html2text
|
19 |
|
20 |
+
# Development (optional)
|
21 |
+
pytest
|
22 |
+
black
|
|
|
|
|
|