@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +353 -2
- package/README.npm.md +34 -0
- package/auth/__init__.py +1 -0
- package/auth/auth_info_middleware.py +419 -0
- package/auth/client_secrets.py +76 -0
- package/auth/credential_store.py +598 -0
- package/auth/external_oauth_provider.py +369 -0
- package/auth/gateway_identity.py +164 -0
- package/auth/google_auth.py +1550 -0
- package/auth/google_oauth_provider.py +20 -0
- package/auth/mcp_session_middleware.py +95 -0
- package/auth/oauth21_session_store.py +1332 -0
- package/auth/oauth_callback_server.py +466 -0
- package/auth/oauth_config.py +693 -0
- package/auth/oauth_proxy_config.py +122 -0
- package/auth/oauth_responses.py +230 -0
- package/auth/oauth_types.py +92 -0
- package/auth/permissions.py +330 -0
- package/auth/port_resolver.py +153 -0
- package/auth/request_identity.py +89 -0
- package/auth/scopes.py +369 -0
- package/auth/service_decorator.py +1109 -0
- package/bin/google-workspace-mcp.cjs +123 -0
- package/core/__init__.py +1 -0
- package/core/api_enablement.py +108 -0
- package/core/attachment_storage.py +496 -0
- package/core/camel_case_middleware.py +98 -0
- package/core/cli.py +161 -0
- package/core/comments.py +609 -0
- package/core/config.py +57 -0
- package/core/context.py +43 -0
- package/core/file_limits.py +632 -0
- package/core/gcs_attachment_storage.py +253 -0
- package/core/http_utils.py +339 -0
- package/core/log_formatter.py +270 -0
- package/core/portable_schema_middleware.py +67 -0
- package/core/server.py +1192 -0
- package/core/startup_ui.py +239 -0
- package/core/storage.py +23 -0
- package/core/telemetry.py +194 -0
- package/core/tool_descriptions.py +19 -0
- package/core/tool_registry.py +311 -0
- package/core/tool_tier_loader.py +197 -0
- package/core/tool_tiers.yaml +179 -0
- package/core/toolset_header_middleware.py +67 -0
- package/core/utils.py +1537 -0
- package/core/valkey_storage.py +271 -0
- package/core/warning_filters.py +19 -0
- package/fastmcp_server.py +198 -0
- package/gappsscript/README.md +512 -0
- package/gappsscript/TESTING.md +254 -0
- package/gappsscript/__init__.py +0 -0
- package/gappsscript/apps_script_tools.py +1940 -0
- package/gcalendar/__init__.py +1 -0
- package/gcalendar/calendar_helpers.py +1323 -0
- package/gcalendar/calendar_tools.py +2252 -0
- package/gchat/__init__.py +7 -0
- package/gchat/chat_helpers.py +410 -0
- package/gchat/chat_tools.py +798 -0
- package/gcontacts/__init__.py +1 -0
- package/gcontacts/contacts_helpers.py +765 -0
- package/gcontacts/contacts_tools.py +1685 -0
- package/gdocs/__init__.py +0 -0
- package/gdocs/docs_anchors.py +163 -0
- package/gdocs/docs_comments.py +89 -0
- package/gdocs/docs_helpers.py +2201 -0
- package/gdocs/docs_links.py +87 -0
- package/gdocs/docs_markdown.py +828 -0
- package/gdocs/docs_markdown_writer.py +592 -0
- package/gdocs/docs_plain_text.py +463 -0
- package/gdocs/docs_structure.py +621 -0
- package/gdocs/docs_tables.py +425 -0
- package/gdocs/docs_tools.py +3300 -0
- package/gdocs/managers/__init__.py +18 -0
- package/gdocs/managers/batch_operation_manager.py +1694 -0
- package/gdocs/managers/header_footer_manager.py +526 -0
- package/gdocs/managers/table_operation_manager.py +488 -0
- package/gdocs/managers/validation_manager.py +1504 -0
- package/gdocs/operation_schemas.py +594 -0
- package/gdrive/__init__.py +0 -0
- package/gdrive/drive_helpers.py +1738 -0
- package/gdrive/drive_tools.py +3085 -0
- package/gforms/__init__.py +3 -0
- package/gforms/forms_tools.py +575 -0
- package/gmail/__init__.py +1 -0
- package/gmail/gmail_helpers.py +2107 -0
- package/gmail/gmail_tools.py +4895 -0
- package/gmail/gmail_web_mime.py +441 -0
- package/gsearch/__init__.py +0 -0
- package/gsearch/search_tools.py +253 -0
- package/gsheets/__init__.py +31 -0
- package/gsheets/sheets_helpers.py +2236 -0
- package/gsheets/sheets_tools.py +3280 -0
- package/gslides/__init__.py +0 -0
- package/gslides/slides_digest.py +390 -0
- package/gslides/slides_helpers.py +392 -0
- package/gslides/slides_markup.py +770 -0
- package/gslides/slides_tools.py +376 -0
- package/gtasks/__init__.py +5 -0
- package/gtasks/tasks_tools.py +936 -0
- package/main.py +1170 -0
- package/package.json +43 -4
- package/pyproject.toml +173 -0
- package/uv.lock +2504 -0
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
"""Pure helpers for building Gmail-web faithful MIME content.
|
|
2
|
+
|
|
3
|
+
These functions are synchronous and side-effect free so they can be unit-tested
|
|
4
|
+
in isolation. Network-bound work (fetching the parent or forwarded message)
|
|
5
|
+
happens in the async Gmail tools, which feed the resulting strings into these
|
|
6
|
+
builders and into ``gmail_helpers._prepare_gmail_message_web``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import html as _html
|
|
13
|
+
import quopri
|
|
14
|
+
import re
|
|
15
|
+
import secrets
|
|
16
|
+
import unicodedata
|
|
17
|
+
from datetime import datetime
|
|
18
|
+
from email.errors import HeaderParseError, InvalidHeaderDefect
|
|
19
|
+
from email.header import Header
|
|
20
|
+
from email.headerregistry import HeaderRegistry
|
|
21
|
+
from email.policy import SMTP
|
|
22
|
+
from email.utils import formataddr, getaddresses
|
|
23
|
+
from typing import List, Literal, Optional, Tuple
|
|
24
|
+
|
|
25
|
+
TextDirection = Literal["auto", "ltr", "rtl"]
|
|
26
|
+
AddressGroup = Tuple[Optional[str], List[Tuple[str, str]]]
|
|
27
|
+
|
|
28
|
+
# Gmail's byte-identical blockquote style string for quoted replies.
|
|
29
|
+
BLOCKQUOTE_STYLE = (
|
|
30
|
+
"margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
# Three-letter day/month names matching Gmail's attribution line.
|
|
34
|
+
_DOW = "Mon Tue Wed Thu Fri Sat Sun".split()
|
|
35
|
+
_MON = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()
|
|
36
|
+
|
|
37
|
+
_ADDRESS_HEADER = HeaderRegistry()
|
|
38
|
+
_PHRASE_SPECIALS = frozenset('()<>[]:;@\\,."')
|
|
39
|
+
_FORWARD_SEPARATOR = "---------- Forwarded message ---------"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def gmail_boundary() -> str:
|
|
43
|
+
"""Return a Gmail-style multipart boundary.
|
|
44
|
+
|
|
45
|
+
Matches ``^0{12}[0-9a-f]{16}$`` -- the literal ``000000000000`` prefix
|
|
46
|
+
followed by exactly 16 random lowercase hex characters (total length 28).
|
|
47
|
+
"""
|
|
48
|
+
# 8 random bytes -> exactly 16 hex chars.
|
|
49
|
+
return "000000000000" + secrets.token_hex(8)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def format_display_address(name: Optional[str], email: str) -> str:
|
|
53
|
+
"""Format ``Display Name <email>`` for a header.
|
|
54
|
+
|
|
55
|
+
- No name -> bare address (so unresolved lookups still send).
|
|
56
|
+
- Non-ASCII or long names are RFC2047 encoded-word wrapped.
|
|
57
|
+
- Names with commas/specials are RFC5322 quoted.
|
|
58
|
+
|
|
59
|
+
``formataddr`` handles quoting; ``Header`` supplies encoded words.
|
|
60
|
+
"""
|
|
61
|
+
# Strip CR/LF/NUL from the address too: formataddr does not sanitize it, so
|
|
62
|
+
# an unvalidated CRLF-bearing address would be RFC5322 header injection.
|
|
63
|
+
safe_email = _strip_header_controls(email)
|
|
64
|
+
if not name or not name.strip():
|
|
65
|
+
return safe_email
|
|
66
|
+
safe_name = _strip_header_controls(name)
|
|
67
|
+
if safe_name.isascii() and len(safe_name) <= 75:
|
|
68
|
+
# ASCII name: formataddr applies RFC5322 quoting when needed.
|
|
69
|
+
return formataddr((safe_name, safe_email))
|
|
70
|
+
# Encoded words also allow long, unbroken display names to fold safely.
|
|
71
|
+
encoded_name = Header(safe_name, "utf-8").encode(maxlinelen=75, linesep="\r\n")
|
|
72
|
+
return f"{encoded_name} <{safe_email}>"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def format_address_list(value: str) -> str:
|
|
76
|
+
"""RFC 2047 encode non-ASCII display names in a To/Cc/Bcc address list.
|
|
77
|
+
|
|
78
|
+
The list is always validated (a malformed entry raises ``ValueError``). A
|
|
79
|
+
Valid ASCII values within the line limit are returned unchanged; otherwise
|
|
80
|
+
each address is reformatted with ``format_display_address``.
|
|
81
|
+
"""
|
|
82
|
+
groups = parse_address_list(value)
|
|
83
|
+
if value.isascii() and len(value) <= 998:
|
|
84
|
+
return value
|
|
85
|
+
out: List[str] = []
|
|
86
|
+
for group_name, members in groups:
|
|
87
|
+
formatted = ", ".join(format_display_address(n, a) for n, a in members)
|
|
88
|
+
if group_name is None:
|
|
89
|
+
out.append(formatted)
|
|
90
|
+
else:
|
|
91
|
+
sep = ": " if formatted else ":"
|
|
92
|
+
out.append(f"{_format_group_name(group_name)}{sep}{formatted};")
|
|
93
|
+
return ", ".join(out)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def parse_address_list(value: str) -> List[AddressGroup]:
|
|
97
|
+
"""Parse an RFC 5322 address list into ``(group_name, [(name, addr), ...])``.
|
|
98
|
+
|
|
99
|
+
Ungrouped mailboxes come back as ``(None, [(name, addr)])``. Empty list
|
|
100
|
+
elements (``a@x.com,,`` or a trailing comma) are skipped; any malformed
|
|
101
|
+
entry (a name with no address, an unclosed ``<``) raises ``ValueError``
|
|
102
|
+
instead of being silently dropped, so a recipient is never lost.
|
|
103
|
+
"""
|
|
104
|
+
try:
|
|
105
|
+
header = _ADDRESS_HEADER("To", value)
|
|
106
|
+
except (IndexError, HeaderParseError) as exc:
|
|
107
|
+
# The stdlib parser raises instead of recording a defect on some
|
|
108
|
+
# truncated input (e.g. "José <" on Python 3.11).
|
|
109
|
+
raise ValueError(f"Invalid address list: could not parse {value!r}.") from exc
|
|
110
|
+
if any(isinstance(d, InvalidHeaderDefect) for d in header.defects):
|
|
111
|
+
raise ValueError(f"Invalid address list: could not parse {value!r}.")
|
|
112
|
+
groups: List[AddressGroup] = []
|
|
113
|
+
for group in header.groups:
|
|
114
|
+
members = [(a.display_name, a.addr_spec) for a in group.addresses]
|
|
115
|
+
if any(not addr for _name, addr in members):
|
|
116
|
+
raise ValueError(f"Invalid address list: empty address in {value!r}.")
|
|
117
|
+
groups.append((group.display_name, members))
|
|
118
|
+
if not groups:
|
|
119
|
+
raise ValueError(f"Invalid address list: no address in {value!r}.")
|
|
120
|
+
return groups
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _format_group_name(name: str) -> str:
|
|
124
|
+
"""Render an RFC 5322 group display name (quoted or RFC 2047 encoded)."""
|
|
125
|
+
safe = _strip_header_controls(name)
|
|
126
|
+
if not safe.isascii() or len(safe) > 75:
|
|
127
|
+
return Header(safe, "utf-8").encode(maxlinelen=75, linesep="\r\n")
|
|
128
|
+
if any(c in _PHRASE_SPECIALS for c in safe):
|
|
129
|
+
return '"' + safe.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
|
130
|
+
return safe
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _escape_body(text: str) -> str:
|
|
134
|
+
"""Escape body text for inclusion in HTML (Gmail entity rules)."""
|
|
135
|
+
# html.escape covers & < > and (quote=True) " and '. Gmail emits ' for
|
|
136
|
+
# the apostrophe; html.escape emits ' -- normalize to match.
|
|
137
|
+
escaped = _html.escape(text, quote=True)
|
|
138
|
+
return escaped.replace("'", "'")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def plain_body_to_html(text: str) -> str:
|
|
142
|
+
"""Convert a plain-text body to Gmail's per-line ``<div>`` HTML.
|
|
143
|
+
|
|
144
|
+
Each line becomes ``<div>line</div>``; blank lines become ``<div><br></div>``.
|
|
145
|
+
Returned value is the inner HTML (caller wraps it in the ltr container).
|
|
146
|
+
"""
|
|
147
|
+
lines = text.replace("\r\n", "\n").replace("\r", "\n").expandtabs().split("\n")
|
|
148
|
+
parts = []
|
|
149
|
+
for line in lines:
|
|
150
|
+
if line == "":
|
|
151
|
+
parts.append("<div><br></div>")
|
|
152
|
+
else:
|
|
153
|
+
# HTML collapses ASCII spaces; preserve indentation and spacing.
|
|
154
|
+
escaped = re.sub(
|
|
155
|
+
r"^ +| +$| {2,}",
|
|
156
|
+
lambda match: " " * len(match.group()),
|
|
157
|
+
_escape_body(line),
|
|
158
|
+
)
|
|
159
|
+
parts.append(f"<div>{escaped}</div>")
|
|
160
|
+
return "".join(parts)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def base_text_direction(text: str) -> str:
|
|
164
|
+
"""Return ``"rtl"`` or ``"ltr"`` for *text*'s base paragraph direction.
|
|
165
|
+
|
|
166
|
+
Follows the Unicode Bidirectional Algorithm's first-strong-character rule:
|
|
167
|
+
the direction is decided by the first character with a strong directional
|
|
168
|
+
type -- ``R``/``AL`` (right-to-left scripts) yield ``"rtl"``, ``L`` yields
|
|
169
|
+
``"ltr"``. Leading bidi-neutral characters (whitespace, digits, punctuation,
|
|
170
|
+
currency signs) are skipped. Text with no strong character defaults to
|
|
171
|
+
``"ltr"`` -- matching Gmail's own compose default and keeping left-to-right
|
|
172
|
+
output byte-identical.
|
|
173
|
+
"""
|
|
174
|
+
for ch in text:
|
|
175
|
+
bidi = unicodedata.bidirectional(ch)
|
|
176
|
+
if bidi == "L":
|
|
177
|
+
return "ltr"
|
|
178
|
+
if bidi in ("R", "AL"):
|
|
179
|
+
return "rtl"
|
|
180
|
+
return "ltr"
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def new_message_html(body_html: str, direction: str = "ltr") -> str:
|
|
184
|
+
"""Wrap body HTML in Gmail's ``<div dir="...">`` container.
|
|
185
|
+
|
|
186
|
+
``direction`` is ``"ltr"`` (default, byte-identical to historical output) or
|
|
187
|
+
``"rtl"``. Callers resolve the value from :func:`base_text_direction` (or an
|
|
188
|
+
explicit user choice) before wrapping. Embedded opposite-direction runs
|
|
189
|
+
(e.g. Latin words or numerals inside a right-to-left body) render correctly
|
|
190
|
+
via the browser's Unicode bidi algorithm regardless of the base.
|
|
191
|
+
"""
|
|
192
|
+
return f'<div dir="{direction}">{body_html}</div>'
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def format_gmail_date(dt: datetime) -> str:
|
|
196
|
+
"""Format ``<Dow>, <D> <Mon> <YYYY> at <H>:<MM>`` as Gmail web renders dates.
|
|
197
|
+
|
|
198
|
+
Day and hour are NOT zero-padded; minute IS zero-padded.
|
|
199
|
+
"""
|
|
200
|
+
dow = _DOW[dt.weekday()]
|
|
201
|
+
mon = _MON[dt.month - 1]
|
|
202
|
+
return f"{dow}, {dt.day} {mon} {dt.year} at {dt.hour}:{dt.minute:02d}"
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _format_attribution_when(dt: datetime) -> str:
|
|
206
|
+
"""Format the ``On <Dow>, <D> <Mon> <YYYY> at <H>:<MM>`` clause."""
|
|
207
|
+
return f"On {format_gmail_date(dt)}"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def format_attribution_plain(name: str, email: str, dt: datetime) -> str:
|
|
211
|
+
"""Plain-text reply attribution line."""
|
|
212
|
+
return f"{_format_attribution_when(dt)}, {name} <{email}> wrote:"
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def format_attribution_html(name: str, email: str, dt: datetime) -> str:
|
|
216
|
+
"""HTML reply attribution div (the ``gmail_attr`` div, trailing ``<br>``)."""
|
|
217
|
+
when = _format_attribution_when(dt)
|
|
218
|
+
safe_name = _escape_body(name)
|
|
219
|
+
safe_email = _html.escape(email)
|
|
220
|
+
return (
|
|
221
|
+
'<div dir="ltr" class="gmail_attr">'
|
|
222
|
+
f"{when}, {safe_name} "
|
|
223
|
+
f'<<a href="mailto:{safe_email}">{safe_email}</a>> wrote:<br></div>'
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def build_quote_plain(parent_text: str) -> str:
|
|
228
|
+
"""Prefix each parent line with Gmail's one-level ``> `` quote marker.
|
|
229
|
+
|
|
230
|
+
Blank lines become a bare ``>`` (no trailing space). Inner quoting in the
|
|
231
|
+
parent body is inherited verbatim (Gmail only adds its own one level).
|
|
232
|
+
"""
|
|
233
|
+
out = []
|
|
234
|
+
for line in parent_text.split("\n"):
|
|
235
|
+
out.append(">" if line == "" else f"> {line}")
|
|
236
|
+
return "\n".join(out)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def build_quote_html(parent_html: str) -> str:
|
|
240
|
+
"""Wrap the parent HTML body in Gmail's blockquote (no attribution div).
|
|
241
|
+
|
|
242
|
+
The attribution div is assembled separately so the container can be built
|
|
243
|
+
as: container-open + attribution + blockquote + container-close.
|
|
244
|
+
"""
|
|
245
|
+
return (
|
|
246
|
+
f'<blockquote class="gmail_quote" style="{BLOCKQUOTE_STYLE}">'
|
|
247
|
+
f"{parent_html}</blockquote>"
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def build_quote_container_html(attribution_html: str, parent_html: str) -> str:
|
|
252
|
+
"""Assemble the full ``gmail_quote gmail_quote_container`` div for a reply."""
|
|
253
|
+
return (
|
|
254
|
+
'<div class="gmail_quote gmail_quote_container">'
|
|
255
|
+
f"{attribution_html}"
|
|
256
|
+
f"{build_quote_html(parent_html)}"
|
|
257
|
+
"</div>"
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _render_recipients_html(raw_header: str) -> str:
|
|
262
|
+
"""Render a raw To/Cc header the way Gmail's forwarded block shows it.
|
|
263
|
+
|
|
264
|
+
Each recipient becomes ``Name <<a href="mailto:addr">addr</a>>``, or
|
|
265
|
+
just the link when it has no display name.
|
|
266
|
+
"""
|
|
267
|
+
parts = []
|
|
268
|
+
for name, email in getaddresses([raw_header]):
|
|
269
|
+
if not email:
|
|
270
|
+
continue
|
|
271
|
+
safe_email = _html.escape(email)
|
|
272
|
+
link = f'<a href="mailto:{safe_email}">{safe_email}</a>'
|
|
273
|
+
parts.append(f"{_escape_body(name)} <{link}>" if name.strip() else link)
|
|
274
|
+
return ", ".join(parts)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def build_forwarded_container_html(
|
|
278
|
+
from_name: str, from_email: str, date: str, subject: str, to: str, orig_html: str
|
|
279
|
+
) -> str:
|
|
280
|
+
"""Assemble Gmail's ``gmail_quote_container`` for a forwarded message.
|
|
281
|
+
|
|
282
|
+
The ``gmail_attr`` header block (separator, From, Date, Subject, To) is
|
|
283
|
+
followed directly by the original HTML; unlike a reply there is no
|
|
284
|
+
blockquote. ``from_name`` or ``from_email`` may be empty; ``to`` is the raw
|
|
285
|
+
header value and ``orig_html`` is inserted verbatim.
|
|
286
|
+
"""
|
|
287
|
+
from_fields = []
|
|
288
|
+
if from_name:
|
|
289
|
+
from_fields.append(
|
|
290
|
+
f'<strong class="gmail_sendername" dir="auto">{_escape_body(from_name)}</strong>'
|
|
291
|
+
)
|
|
292
|
+
if from_email:
|
|
293
|
+
safe_email = _html.escape(from_email)
|
|
294
|
+
from_fields.append(
|
|
295
|
+
f'<span dir="auto"><<a href="mailto:{safe_email}">{safe_email}</a>></span>'
|
|
296
|
+
)
|
|
297
|
+
attr_div = (
|
|
298
|
+
'<div dir="ltr" class="gmail_attr">'
|
|
299
|
+
f"{_FORWARD_SEPARATOR}<br>"
|
|
300
|
+
f"From: {' '.join(from_fields)}<br>"
|
|
301
|
+
f"Date: {_escape_body(date)}<br>"
|
|
302
|
+
f"Subject: {_escape_body(subject)}<br>"
|
|
303
|
+
f"To: {_render_recipients_html(to)}<br>"
|
|
304
|
+
"</div>"
|
|
305
|
+
)
|
|
306
|
+
return f'<div class="gmail_quote gmail_quote_container">{attr_div}{orig_html}</div>'
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def build_forwarded_plain(
|
|
310
|
+
from_name: str, from_email: str, date: str, subject: str, to: str, orig_plain: str
|
|
311
|
+
) -> str:
|
|
312
|
+
"""Assemble Gmail's plain-text forwarded block.
|
|
313
|
+
|
|
314
|
+
The header lines are followed by a blank line and the original body
|
|
315
|
+
verbatim (not ``> ``-quoted).
|
|
316
|
+
"""
|
|
317
|
+
if from_name and from_email:
|
|
318
|
+
from_field = f"{from_name} <{from_email}>"
|
|
319
|
+
else:
|
|
320
|
+
from_field = from_name or from_email
|
|
321
|
+
return (
|
|
322
|
+
f"{_FORWARD_SEPARATOR}\n"
|
|
323
|
+
f"From: {from_field}\n"
|
|
324
|
+
f"Date: {date}\n"
|
|
325
|
+
f"Subject: {subject}\n"
|
|
326
|
+
f"To: {to}\n"
|
|
327
|
+
"\n"
|
|
328
|
+
f"{orig_plain}"
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _qp_encode(text: str) -> str:
|
|
333
|
+
"""Quoted-printable encode text with CRLF line endings (76-col soft wrap)."""
|
|
334
|
+
# Normalize to CRLF so quopri's soft-wrapping operates on canonical lines.
|
|
335
|
+
# quopri passes a bare CR through unencoded, so it becomes a line break too
|
|
336
|
+
# (as EmailMessage does) rather than an RFC 5322-invalid lone CR on the wire.
|
|
337
|
+
lines = text.replace("\r\n", "\n").replace("\r", "\n")
|
|
338
|
+
encoded = quopri.encodestring(lines.replace("\n", "\r\n").encode("utf-8"))
|
|
339
|
+
# binascii.b2a_qp emits bare-LF soft breaks ("=\n") when the input has no
|
|
340
|
+
# CRLF to imitate (a single-line HTML part); canonicalize those to CRLF.
|
|
341
|
+
return encoded.decode("ascii").replace("\r\n", "\n").replace("\n", "\r\n")
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def choose_cte(text: str) -> str:
|
|
345
|
+
"""Choose the smaller Content-Transfer-Encoding for a text body part.
|
|
346
|
+
|
|
347
|
+
Mirrors Gmail's per-part choice: mostly-ASCII/Latin bodies come out
|
|
348
|
+
smaller as ``quoted-printable`` (which wins ties), heavily non-ASCII bodies
|
|
349
|
+
(Hebrew, CJK) as ``base64``.
|
|
350
|
+
"""
|
|
351
|
+
if len(_b64_text(text)) < len(_qp_encode(text)):
|
|
352
|
+
return "base64"
|
|
353
|
+
return "quoted-printable"
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _b64_text(text: str) -> str:
|
|
357
|
+
"""Base64-encode a text string (UTF-8) with CRLF-wrapped 76-col lines."""
|
|
358
|
+
return _b64_crlf(text.encode("utf-8"))
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _alternative_parts(plain_text: str, html_text: str, boundary: str) -> str:
|
|
362
|
+
"""Return the text/plain and text/html parts bounded by ``boundary``.
|
|
363
|
+
|
|
364
|
+
Each part's Content-Transfer-Encoding is chosen by :func:`choose_cte`.
|
|
365
|
+
"""
|
|
366
|
+
crlf = "\r\n"
|
|
367
|
+
|
|
368
|
+
def _part(content_type: str, body: str) -> str:
|
|
369
|
+
cte = choose_cte(body)
|
|
370
|
+
encoded = _qp_encode(body) if cte == "quoted-printable" else _b64_text(body)
|
|
371
|
+
return crlf.join(
|
|
372
|
+
[
|
|
373
|
+
f"--{boundary}",
|
|
374
|
+
f'Content-Type: {content_type}; charset="UTF-8"',
|
|
375
|
+
f"Content-Transfer-Encoding: {cte}",
|
|
376
|
+
"",
|
|
377
|
+
encoded,
|
|
378
|
+
]
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
plain_part = _part("text/plain", plain_text)
|
|
382
|
+
html_part = _part("text/html", html_text)
|
|
383
|
+
closing = f"--{boundary}--"
|
|
384
|
+
return crlf.join([plain_part, html_part, closing, ""])
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def assemble_alternative(
|
|
388
|
+
headers: List[Tuple[str, str]],
|
|
389
|
+
plain_text: str,
|
|
390
|
+
html_text: str,
|
|
391
|
+
boundary: str,
|
|
392
|
+
) -> str:
|
|
393
|
+
"""Assemble a ``multipart/alternative`` message as a raw RFC5322 string.
|
|
394
|
+
|
|
395
|
+
``headers`` is an ordered list of (name, value) pairs authored exactly as the
|
|
396
|
+
spec dictates (the caller controls order and which optional headers appear).
|
|
397
|
+
The ``Content-Type`` header for the top-level multipart is appended here so
|
|
398
|
+
its boundary always matches ``boundary``.
|
|
399
|
+
|
|
400
|
+
Both body parts use ``charset="UTF-8"`` (uppercase, double-quoted). Returns
|
|
401
|
+
the message with CRLF separators, ready for :func:`encode_raw`.
|
|
402
|
+
"""
|
|
403
|
+
crlf = "\r\n"
|
|
404
|
+
policy = SMTP.clone(max_line_length=76)
|
|
405
|
+
lines: List[str] = []
|
|
406
|
+
for name, value in headers:
|
|
407
|
+
if name == "Subject":
|
|
408
|
+
lines.append(policy.fold(name, value).removesuffix(crlf))
|
|
409
|
+
else:
|
|
410
|
+
# Refolding address headers through HeaderRegistry can insert
|
|
411
|
+
# literal spaces between adjacent encoded words on Python 3.12.
|
|
412
|
+
folded = Header(value, header_name=name).encode(maxlinelen=76, linesep=crlf)
|
|
413
|
+
lines.append(f"{name}: {folded}")
|
|
414
|
+
if any(
|
|
415
|
+
len(line.encode("utf-8")) > 998
|
|
416
|
+
for header in lines
|
|
417
|
+
for line in header.split(crlf)
|
|
418
|
+
):
|
|
419
|
+
raise ValueError("Header contains a token too long to fit an RFC 5322 line.")
|
|
420
|
+
lines.append(f'Content-Type: multipart/alternative; boundary="{boundary}"')
|
|
421
|
+
head = crlf.join(lines)
|
|
422
|
+
return crlf.join([head, "", _alternative_parts(plain_text, html_text, boundary)])
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _strip_header_controls(value: str) -> str:
|
|
426
|
+
"""Remove CR/LF/NUL so a value can't inject extra MIME header lines."""
|
|
427
|
+
return value.replace("\r", "").replace("\n", "").replace("\x00", "")
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _b64_crlf(data: bytes) -> str:
|
|
431
|
+
"""Base64-encode *data* with CRLF line breaks and no trailing newline."""
|
|
432
|
+
crlf = "\r\n"
|
|
433
|
+
b64 = base64.encodebytes(data).decode("ascii")
|
|
434
|
+
# encodebytes wraps at 76 cols with a trailing newline; strip it so there
|
|
435
|
+
# is no empty line between the payload and the next boundary delimiter.
|
|
436
|
+
return b64.rstrip("\n").replace("\n", crlf)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def encode_raw(message: str) -> str:
|
|
440
|
+
"""Base64url-encode an assembled message for the Gmail send API."""
|
|
441
|
+
return base64.urlsafe_b64encode(message.encode("utf-8")).decode("ascii")
|
|
File without changes
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Google Custom Search (PSE) MCP Tools
|
|
3
|
+
|
|
4
|
+
This module provides MCP tools for interacting with Google Programmable Search Engine.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
import asyncio
|
|
9
|
+
import os
|
|
10
|
+
from typing import Optional, Literal
|
|
11
|
+
|
|
12
|
+
from mcp.types import ToolAnnotations
|
|
13
|
+
|
|
14
|
+
from auth.service_decorator import require_google_service
|
|
15
|
+
from core.server import server
|
|
16
|
+
from core.utils import handle_http_errors, StringList
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@server.tool(
|
|
22
|
+
title="Search Custom",
|
|
23
|
+
annotations=ToolAnnotations(
|
|
24
|
+
readOnlyHint=True,
|
|
25
|
+
destructiveHint=False,
|
|
26
|
+
idempotentHint=True,
|
|
27
|
+
openWorldHint=True,
|
|
28
|
+
),
|
|
29
|
+
)
|
|
30
|
+
@handle_http_errors("search_custom", is_read_only=True, service_type="customsearch")
|
|
31
|
+
@require_google_service("customsearch", "customsearch")
|
|
32
|
+
async def search_custom(
|
|
33
|
+
service,
|
|
34
|
+
user_google_email: str,
|
|
35
|
+
q: str,
|
|
36
|
+
num: int = 10,
|
|
37
|
+
start: int = 1,
|
|
38
|
+
safe: Literal["active", "moderate", "off"] = "off",
|
|
39
|
+
search_type: Optional[Literal["image"]] = None,
|
|
40
|
+
site_search: Optional[str] = None,
|
|
41
|
+
site_search_filter: Optional[Literal["e", "i"]] = None,
|
|
42
|
+
date_restrict: Optional[str] = None,
|
|
43
|
+
file_type: Optional[str] = None,
|
|
44
|
+
language: Optional[str] = None,
|
|
45
|
+
country: Optional[str] = None,
|
|
46
|
+
sites: Optional[StringList] = None,
|
|
47
|
+
) -> str:
|
|
48
|
+
"""
|
|
49
|
+
Performs a search using Google Custom Search JSON API.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
user_google_email (str): The user's Google email address. Required.
|
|
53
|
+
q (str): The search query. Required.
|
|
54
|
+
num (int): Number of results to return (1-10). Defaults to 10.
|
|
55
|
+
start (int): The index of the first result to return (1-based). Defaults to 1.
|
|
56
|
+
safe (Literal["active", "moderate", "off"]): Safe search level. Defaults to "off".
|
|
57
|
+
search_type (Optional[Literal["image"]]): Search for images if set to "image".
|
|
58
|
+
site_search (Optional[str]): Restrict search to a specific site/domain.
|
|
59
|
+
site_search_filter (Optional[Literal["e", "i"]]): Exclude ("e") or include ("i") site_search results.
|
|
60
|
+
date_restrict (Optional[str]): Restrict results by date (e.g., "d5" for past 5 days, "m3" for past 3 months).
|
|
61
|
+
file_type (Optional[str]): Filter by file type (e.g., "pdf", "doc").
|
|
62
|
+
language (Optional[str]): Language code for results (e.g., "lang_en").
|
|
63
|
+
country (Optional[str]): Country code for results (e.g., "countryUS").
|
|
64
|
+
sites (Optional[List[str]]): List of sites/domains to restrict search to (e.g., ["example.com", "docs.example.com"]). When provided, results are limited to these sites.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
str: Formatted search results including title, link, and snippet for each result.
|
|
68
|
+
"""
|
|
69
|
+
# Get API key and search engine ID from environment
|
|
70
|
+
api_key = os.environ.get("GOOGLE_PSE_API_KEY")
|
|
71
|
+
if not api_key:
|
|
72
|
+
raise ValueError(
|
|
73
|
+
"GOOGLE_PSE_API_KEY environment variable not set. Please set it to your Google Custom Search API key."
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
cx = os.environ.get("GOOGLE_PSE_ENGINE_ID")
|
|
77
|
+
if not cx:
|
|
78
|
+
raise ValueError(
|
|
79
|
+
"GOOGLE_PSE_ENGINE_ID environment variable not set. Please set it to your Programmable Search Engine ID."
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
logger.info(
|
|
83
|
+
f"[search_custom] Invoked. Email: '{user_google_email}', query_len={len(q)}, CX: '{cx}'"
|
|
84
|
+
)
|
|
85
|
+
logger.debug(f"[search_custom] Query: '{q}'")
|
|
86
|
+
|
|
87
|
+
# Apply site restriction if sites are provided
|
|
88
|
+
if sites:
|
|
89
|
+
site_query = " OR ".join([f"site:{site}" for site in sites])
|
|
90
|
+
q = f"{q} ({site_query})"
|
|
91
|
+
logger.debug(f"[search_custom] Applied site restriction: {sites}")
|
|
92
|
+
|
|
93
|
+
# Build the request parameters
|
|
94
|
+
params = {
|
|
95
|
+
"key": api_key,
|
|
96
|
+
"cx": cx,
|
|
97
|
+
"q": q,
|
|
98
|
+
"num": num,
|
|
99
|
+
"start": start,
|
|
100
|
+
"safe": safe,
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
# Add optional parameters
|
|
104
|
+
if search_type:
|
|
105
|
+
params["searchType"] = search_type
|
|
106
|
+
if site_search:
|
|
107
|
+
params["siteSearch"] = site_search
|
|
108
|
+
if site_search_filter:
|
|
109
|
+
params["siteSearchFilter"] = site_search_filter
|
|
110
|
+
if date_restrict:
|
|
111
|
+
params["dateRestrict"] = date_restrict
|
|
112
|
+
if file_type:
|
|
113
|
+
params["fileType"] = file_type
|
|
114
|
+
if language:
|
|
115
|
+
params["lr"] = language
|
|
116
|
+
if country:
|
|
117
|
+
params["cr"] = country
|
|
118
|
+
|
|
119
|
+
# Execute the search request
|
|
120
|
+
result = await asyncio.to_thread(service.cse().list(**params).execute)
|
|
121
|
+
|
|
122
|
+
# Extract search information
|
|
123
|
+
search_info = result.get("searchInformation", {})
|
|
124
|
+
total_results = search_info.get("totalResults", "0")
|
|
125
|
+
search_time = search_info.get("searchTime", 0)
|
|
126
|
+
|
|
127
|
+
# Extract search results
|
|
128
|
+
items = result.get("items", [])
|
|
129
|
+
|
|
130
|
+
# Format the response
|
|
131
|
+
confirmation_message = f"""Search Results for {user_google_email}:
|
|
132
|
+
- Query: "{q}"
|
|
133
|
+
- Search Engine ID: {cx}
|
|
134
|
+
- Total Results: {total_results}
|
|
135
|
+
- Search Time: {search_time:.3f} seconds
|
|
136
|
+
- Results Returned: {len(items)} (showing {start} to {start + len(items) - 1})
|
|
137
|
+
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
if items:
|
|
141
|
+
confirmation_message += "Results:\n"
|
|
142
|
+
for i, item in enumerate(items, start):
|
|
143
|
+
title = item.get("title", "No title")
|
|
144
|
+
link = item.get("link", "No link")
|
|
145
|
+
snippet = item.get("snippet", "No description available").replace("\n", " ")
|
|
146
|
+
|
|
147
|
+
confirmation_message += f"\n{i}. {title}\n"
|
|
148
|
+
confirmation_message += f" URL: {link}\n"
|
|
149
|
+
confirmation_message += f" Snippet: {snippet}\n"
|
|
150
|
+
|
|
151
|
+
# Add additional metadata if available
|
|
152
|
+
if "pagemap" in item:
|
|
153
|
+
pagemap = item["pagemap"]
|
|
154
|
+
if "metatags" in pagemap and pagemap["metatags"]:
|
|
155
|
+
metatag = pagemap["metatags"][0]
|
|
156
|
+
if "og:type" in metatag:
|
|
157
|
+
confirmation_message += f" Type: {metatag['og:type']}\n"
|
|
158
|
+
if "article:published_time" in metatag:
|
|
159
|
+
confirmation_message += (
|
|
160
|
+
f" Published: {metatag['article:published_time'][:10]}\n"
|
|
161
|
+
)
|
|
162
|
+
else:
|
|
163
|
+
confirmation_message += "\nNo results found."
|
|
164
|
+
|
|
165
|
+
# Add information about pagination
|
|
166
|
+
queries = result.get("queries", {})
|
|
167
|
+
if "nextPage" in queries:
|
|
168
|
+
next_start = queries["nextPage"][0].get("startIndex", 0)
|
|
169
|
+
confirmation_message += (
|
|
170
|
+
f"\n\nTo see more results, search again with start={next_start}"
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
logger.info(f"Search completed successfully for {user_google_email}")
|
|
174
|
+
return confirmation_message
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@server.tool(
|
|
178
|
+
title="Get Search Engine Info",
|
|
179
|
+
annotations=ToolAnnotations(
|
|
180
|
+
readOnlyHint=True,
|
|
181
|
+
destructiveHint=False,
|
|
182
|
+
idempotentHint=True,
|
|
183
|
+
openWorldHint=True,
|
|
184
|
+
),
|
|
185
|
+
)
|
|
186
|
+
@handle_http_errors(
|
|
187
|
+
"get_search_engine_info", is_read_only=True, service_type="customsearch"
|
|
188
|
+
)
|
|
189
|
+
@require_google_service("customsearch", "customsearch")
|
|
190
|
+
async def get_search_engine_info(service, user_google_email: str) -> str:
|
|
191
|
+
"""
|
|
192
|
+
Retrieves metadata about a Programmable Search Engine.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
user_google_email (str): The user's Google email address. Required.
|
|
196
|
+
|
|
197
|
+
Returns:
|
|
198
|
+
str: Information about the search engine including its configuration and available refinements.
|
|
199
|
+
"""
|
|
200
|
+
# Get API key and search engine ID from environment
|
|
201
|
+
api_key = os.environ.get("GOOGLE_PSE_API_KEY")
|
|
202
|
+
if not api_key:
|
|
203
|
+
raise ValueError(
|
|
204
|
+
"GOOGLE_PSE_API_KEY environment variable not set. Please set it to your Google Custom Search API key."
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
cx = os.environ.get("GOOGLE_PSE_ENGINE_ID")
|
|
208
|
+
if not cx:
|
|
209
|
+
raise ValueError(
|
|
210
|
+
"GOOGLE_PSE_ENGINE_ID environment variable not set. Please set it to your Programmable Search Engine ID."
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
logger.info(
|
|
214
|
+
f"[get_search_engine_info] Invoked. Email: '{user_google_email}', CX: '{cx}'"
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
# Perform a minimal search to get the search engine context
|
|
218
|
+
params = {
|
|
219
|
+
"key": api_key,
|
|
220
|
+
"cx": cx,
|
|
221
|
+
"q": "test", # Minimal query to get metadata
|
|
222
|
+
"num": 1,
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
result = await asyncio.to_thread(service.cse().list(**params).execute)
|
|
226
|
+
|
|
227
|
+
# Extract context information
|
|
228
|
+
context = result.get("context", {})
|
|
229
|
+
title = context.get("title", "Unknown")
|
|
230
|
+
|
|
231
|
+
confirmation_message = f"""Search Engine Information for {user_google_email}:
|
|
232
|
+
- Search Engine ID: {cx}
|
|
233
|
+
- Title: {title}
|
|
234
|
+
"""
|
|
235
|
+
|
|
236
|
+
# Add facet information if available
|
|
237
|
+
if "facets" in context:
|
|
238
|
+
confirmation_message += "\nAvailable Refinements:\n"
|
|
239
|
+
for facet in context["facets"]:
|
|
240
|
+
for item in facet:
|
|
241
|
+
label = item.get("label", "Unknown")
|
|
242
|
+
anchor = item.get("anchor", "Unknown")
|
|
243
|
+
confirmation_message += f" - {label} (anchor: {anchor})\n"
|
|
244
|
+
|
|
245
|
+
# Add search information
|
|
246
|
+
search_info = result.get("searchInformation", {})
|
|
247
|
+
if search_info:
|
|
248
|
+
total_results = search_info.get("totalResults", "Unknown")
|
|
249
|
+
confirmation_message += "\nSearch Statistics:\n"
|
|
250
|
+
confirmation_message += f" - Total indexed results: {total_results}\n"
|
|
251
|
+
|
|
252
|
+
logger.info(f"Search engine info retrieved successfully for {user_google_email}")
|
|
253
|
+
return confirmation_message
|