@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.0
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 +28 -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,798 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Google Chat MCP Tools
|
|
3
|
+
|
|
4
|
+
This module provides MCP tools for interacting with Google Chat API.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import base64
|
|
8
|
+
import logging
|
|
9
|
+
import asyncio
|
|
10
|
+
import ssl
|
|
11
|
+
from typing import List, Optional
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
from googleapiclient.errors import HttpError
|
|
15
|
+
|
|
16
|
+
from mcp.types import ToolAnnotations
|
|
17
|
+
|
|
18
|
+
# Auth & server utilities
|
|
19
|
+
from auth.service_decorator import require_google_service, require_multiple_services
|
|
20
|
+
from core.file_limits import FileTooLargeError, download_http_url_bytes
|
|
21
|
+
from core.gcs_attachment_storage import gcs_files_enabled
|
|
22
|
+
from core.server import server
|
|
23
|
+
from core.utils import TransientNetworkError, UserInputError, handle_http_errors
|
|
24
|
+
from gchat.chat_helpers import (
|
|
25
|
+
_execute_chat_request,
|
|
26
|
+
_extract_rich_links,
|
|
27
|
+
_format_search_message_ids,
|
|
28
|
+
_format_space_members,
|
|
29
|
+
_name_spaces,
|
|
30
|
+
_none_if_blank,
|
|
31
|
+
_none_if_null_sentinel,
|
|
32
|
+
_normalize_message_resource_name,
|
|
33
|
+
_normalize_space_resource_name,
|
|
34
|
+
_resolve_sender,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
_SEARCH_MESSAGES_MAX_CONCURRENT_SPACE_FETCHES = 1
|
|
41
|
+
_SEARCH_MESSAGES_SSL_RETRIES = 3
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@server.tool(
|
|
45
|
+
title="List Spaces",
|
|
46
|
+
annotations=ToolAnnotations(
|
|
47
|
+
readOnlyHint=True,
|
|
48
|
+
destructiveHint=False,
|
|
49
|
+
idempotentHint=True,
|
|
50
|
+
openWorldHint=True,
|
|
51
|
+
),
|
|
52
|
+
)
|
|
53
|
+
@require_multiple_services(
|
|
54
|
+
[
|
|
55
|
+
{
|
|
56
|
+
"service_type": "chat",
|
|
57
|
+
"scopes": "chat_spaces_readonly",
|
|
58
|
+
"param_name": "chat_service",
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
"service_type": "people",
|
|
62
|
+
"scopes": "contacts_read",
|
|
63
|
+
"param_name": "people_service",
|
|
64
|
+
},
|
|
65
|
+
]
|
|
66
|
+
)
|
|
67
|
+
@handle_http_errors("list_spaces", service_type="chat")
|
|
68
|
+
async def list_spaces(
|
|
69
|
+
chat_service,
|
|
70
|
+
people_service,
|
|
71
|
+
user_google_email: str,
|
|
72
|
+
page_size: int = 100,
|
|
73
|
+
space_type: str = "all", # "all", "room", "dm"
|
|
74
|
+
space_id: Optional[str] = None,
|
|
75
|
+
) -> str:
|
|
76
|
+
"""
|
|
77
|
+
Lists Google Chat spaces (rooms and direct messages) accessible to the user,
|
|
78
|
+
or the members of one space.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
space_id: Space (spaces/X or a bare ID X) whose members to list instead
|
|
82
|
+
of spaces, up to page_size: people, apps and groups with role and
|
|
83
|
+
invite state.
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
str: A formatted list of Google Chat spaces, or of the members of space_id.
|
|
87
|
+
"""
|
|
88
|
+
space_id = _none_if_blank(space_id)
|
|
89
|
+
if space_id is not None:
|
|
90
|
+
space_id = _normalize_space_resource_name(space_id)
|
|
91
|
+
logger.info(f"[list_spaces] Members of {space_id}")
|
|
92
|
+
return await _format_space_members(
|
|
93
|
+
chat_service, people_service, space_id, max(page_size, 1)
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
logger.info(f"[list_spaces] Email={user_google_email}, Type={space_type}")
|
|
97
|
+
|
|
98
|
+
# Build filter based on space_type
|
|
99
|
+
filter_param = None
|
|
100
|
+
if space_type == "room":
|
|
101
|
+
filter_param = 'spaceType = "SPACE"'
|
|
102
|
+
elif space_type == "dm":
|
|
103
|
+
filter_param = 'spaceType = "DIRECT_MESSAGE"'
|
|
104
|
+
|
|
105
|
+
request_params = {"pageSize": page_size}
|
|
106
|
+
if filter_param:
|
|
107
|
+
request_params["filter"] = filter_param
|
|
108
|
+
|
|
109
|
+
response = await asyncio.to_thread(
|
|
110
|
+
chat_service.spaces().list(**request_params).execute
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
spaces = response.get("spaces", [])
|
|
114
|
+
if not spaces:
|
|
115
|
+
return f"No Chat spaces found for type '{space_type}'."
|
|
116
|
+
|
|
117
|
+
space_labels = await _name_spaces(
|
|
118
|
+
chat_service, people_service, spaces, user_google_email
|
|
119
|
+
)
|
|
120
|
+
output = [f"Found {len(spaces)} Chat spaces (type: {space_type}):"]
|
|
121
|
+
for space in spaces:
|
|
122
|
+
space_id = space.get("name", "")
|
|
123
|
+
space_name = space_labels[space.get("name")]
|
|
124
|
+
space_type_actual = space.get("spaceType", "UNKNOWN")
|
|
125
|
+
output.append(f"- {space_name} (ID: {space_id}, Type: {space_type_actual})")
|
|
126
|
+
|
|
127
|
+
return "\n".join(output)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@server.tool(
|
|
131
|
+
title="Get Messages",
|
|
132
|
+
annotations=ToolAnnotations(
|
|
133
|
+
readOnlyHint=True,
|
|
134
|
+
destructiveHint=False,
|
|
135
|
+
idempotentHint=True,
|
|
136
|
+
openWorldHint=True,
|
|
137
|
+
),
|
|
138
|
+
)
|
|
139
|
+
@require_multiple_services(
|
|
140
|
+
[
|
|
141
|
+
{"service_type": "chat", "scopes": "chat_read", "param_name": "chat_service"},
|
|
142
|
+
{
|
|
143
|
+
"service_type": "people",
|
|
144
|
+
"scopes": "contacts_read",
|
|
145
|
+
"param_name": "people_service",
|
|
146
|
+
},
|
|
147
|
+
]
|
|
148
|
+
)
|
|
149
|
+
@handle_http_errors("get_messages", service_type="chat")
|
|
150
|
+
async def get_messages(
|
|
151
|
+
chat_service,
|
|
152
|
+
people_service,
|
|
153
|
+
user_google_email: str,
|
|
154
|
+
space_id: str,
|
|
155
|
+
page_size: int = 50,
|
|
156
|
+
order_by: str = "createTime desc",
|
|
157
|
+
message_filter: Optional[str] = None,
|
|
158
|
+
page_token: Optional[str] = None,
|
|
159
|
+
) -> str:
|
|
160
|
+
"""
|
|
161
|
+
Retrieves messages from a Google Chat space.
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
message_filter: Optional filter string using the Chat API filter syntax.
|
|
165
|
+
Supports createTime and thread.name.
|
|
166
|
+
Examples:
|
|
167
|
+
'createTime > "2026-03-18T00:00:00-03:00"'
|
|
168
|
+
'createTime > "2026-03-18T00:00:00-03:00" AND createTime < "2026-03-19T00:00:00-03:00"'
|
|
169
|
+
'thread.name = spaces/X/threads/Y'
|
|
170
|
+
page_token: Token for the next page, taken from a previous response. Keep all other arguments unchanged.
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
str: Formatted messages from the specified space. When more messages
|
|
174
|
+
remain, a "Next page token" line is appended.
|
|
175
|
+
"""
|
|
176
|
+
space_id = _normalize_space_resource_name(space_id)
|
|
177
|
+
logger.info(f"[get_messages] Space ID: '{space_id}' for user '{user_google_email}'")
|
|
178
|
+
|
|
179
|
+
# Get space info first
|
|
180
|
+
space_info = await asyncio.to_thread(
|
|
181
|
+
chat_service.spaces().get(name=space_id).execute
|
|
182
|
+
)
|
|
183
|
+
space_labels = await _name_spaces(
|
|
184
|
+
chat_service, people_service, [space_info], user_google_email
|
|
185
|
+
)
|
|
186
|
+
space_name = space_labels[space_info.get("name")]
|
|
187
|
+
|
|
188
|
+
# Get messages
|
|
189
|
+
list_params = {"parent": space_id, "pageSize": page_size, "orderBy": order_by}
|
|
190
|
+
if message_filter is not None:
|
|
191
|
+
list_params["filter"] = message_filter
|
|
192
|
+
if page_token:
|
|
193
|
+
list_params["pageToken"] = page_token
|
|
194
|
+
response = await asyncio.to_thread(
|
|
195
|
+
chat_service.spaces().messages().list(**list_params).execute
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
messages = response.get("messages", [])
|
|
199
|
+
next_page_token = response.get("nextPageToken")
|
|
200
|
+
if not messages:
|
|
201
|
+
if next_page_token:
|
|
202
|
+
return (
|
|
203
|
+
f"No messages on this page in space '{space_name}' (ID: {space_id}), "
|
|
204
|
+
f"and more pages remain.\nNext page token: {next_page_token}"
|
|
205
|
+
)
|
|
206
|
+
matching = " matching the filter" if message_filter else ""
|
|
207
|
+
if page_token:
|
|
208
|
+
return (
|
|
209
|
+
f"No more messages{matching} in space '{space_name}' (ID: {space_id})."
|
|
210
|
+
)
|
|
211
|
+
return f"No messages{matching} found in space '{space_name}' (ID: {space_id})."
|
|
212
|
+
|
|
213
|
+
# Pre-resolve unique senders sequentially. The underlying googleapiclient/httplib2
|
|
214
|
+
# service objects are not safe to fan out across worker threads.
|
|
215
|
+
sender_lookup = {}
|
|
216
|
+
for msg in messages:
|
|
217
|
+
s = msg.get("sender", {})
|
|
218
|
+
key = s.get("name", "")
|
|
219
|
+
if key and key not in sender_lookup:
|
|
220
|
+
sender_lookup[key] = s
|
|
221
|
+
sender_map = {}
|
|
222
|
+
for key, sender_obj in sender_lookup.items():
|
|
223
|
+
sender_map[key] = await _resolve_sender(
|
|
224
|
+
people_service, sender_obj, user_google_email
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
output = [f"Messages from '{space_name}' (ID: {space_id}):\n"]
|
|
228
|
+
for msg in messages:
|
|
229
|
+
sender_obj = msg.get("sender", {})
|
|
230
|
+
sender_key = sender_obj.get("name", "")
|
|
231
|
+
sender = sender_map.get(sender_key) or await _resolve_sender(
|
|
232
|
+
people_service, sender_obj, user_google_email
|
|
233
|
+
)
|
|
234
|
+
create_time = msg.get("createTime", "Unknown Time")
|
|
235
|
+
text_content = msg.get("text", "No text content")
|
|
236
|
+
msg_name = msg.get("name", "")
|
|
237
|
+
|
|
238
|
+
output.append(f"[{create_time}] {sender}:")
|
|
239
|
+
output.append(f" {text_content}")
|
|
240
|
+
rich_links = _extract_rich_links(msg)
|
|
241
|
+
for url in rich_links:
|
|
242
|
+
output.append(f" [linked: {url}]")
|
|
243
|
+
# Show attachments
|
|
244
|
+
attachments = msg.get("attachment", [])
|
|
245
|
+
for idx, att in enumerate(attachments):
|
|
246
|
+
att_name = att.get("contentName", "unnamed")
|
|
247
|
+
att_type = att.get("contentType", "unknown type")
|
|
248
|
+
att_resource = att.get("name", "")
|
|
249
|
+
output.append(f" [attachment {idx}: {att_name} ({att_type})]")
|
|
250
|
+
if att_resource:
|
|
251
|
+
output.append(
|
|
252
|
+
f" Use download_chat_attachment(message_id='{msg_name}', attachment_index={idx}) to download"
|
|
253
|
+
)
|
|
254
|
+
# Show thread info if this is a threaded reply
|
|
255
|
+
thread = msg.get("thread", {})
|
|
256
|
+
if msg.get("threadReply") and thread.get("name"):
|
|
257
|
+
output.append(f" [thread: {thread['name']}]")
|
|
258
|
+
# Show emoji reactions
|
|
259
|
+
reactions = msg.get("emojiReactionSummaries", [])
|
|
260
|
+
if reactions:
|
|
261
|
+
parts = []
|
|
262
|
+
for r in reactions:
|
|
263
|
+
emoji = r.get("emoji", {})
|
|
264
|
+
symbol = emoji.get("unicode", "")
|
|
265
|
+
if not symbol:
|
|
266
|
+
ce = emoji.get("customEmoji", {})
|
|
267
|
+
symbol = f":{ce.get('uid', '?')}:"
|
|
268
|
+
count = r.get("reactionCount", 0)
|
|
269
|
+
parts.append(f"{symbol}x{count}")
|
|
270
|
+
output.append(f" [reactions: {', '.join(parts)}]")
|
|
271
|
+
output.append(f" (Message ID: {msg_name})\n")
|
|
272
|
+
|
|
273
|
+
if next_page_token:
|
|
274
|
+
output.append(f"Next page token: {next_page_token}")
|
|
275
|
+
return "\n".join(output)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
@server.tool(
|
|
279
|
+
title="Send Message",
|
|
280
|
+
annotations=ToolAnnotations(
|
|
281
|
+
readOnlyHint=False,
|
|
282
|
+
destructiveHint=True,
|
|
283
|
+
idempotentHint=False,
|
|
284
|
+
openWorldHint=True,
|
|
285
|
+
),
|
|
286
|
+
)
|
|
287
|
+
@require_google_service("chat", "chat_write")
|
|
288
|
+
@handle_http_errors("send_message", service_type="chat")
|
|
289
|
+
async def send_message(
|
|
290
|
+
service,
|
|
291
|
+
user_google_email: str,
|
|
292
|
+
space_id: str,
|
|
293
|
+
message_text: str,
|
|
294
|
+
thread_key: Optional[str] = None,
|
|
295
|
+
thread_name: Optional[str] = None,
|
|
296
|
+
message_name: Optional[str] = None,
|
|
297
|
+
) -> str:
|
|
298
|
+
"""
|
|
299
|
+
Sends a message to a Google Chat space, or edits a message already sent there.
|
|
300
|
+
|
|
301
|
+
Args:
|
|
302
|
+
thread_name: Reply in an existing thread by its resource name (e.g. spaces/X/threads/Y).
|
|
303
|
+
thread_key: Reply in a thread by app-defined key (creates thread if not found).
|
|
304
|
+
message_name: Edit this message in place instead of sending a new one
|
|
305
|
+
(e.g. spaces/X/messages/Y, as returned by send_message or get_messages).
|
|
306
|
+
Must be a message of space_id. Only the text is replaced, and only the
|
|
307
|
+
author can edit their own message.
|
|
308
|
+
|
|
309
|
+
Returns:
|
|
310
|
+
str: Confirmation message with the sent or updated message details.
|
|
311
|
+
"""
|
|
312
|
+
space_id = _normalize_space_resource_name(space_id)
|
|
313
|
+
logger.info(f"[send_message] Email: '{user_google_email}', Space: '{space_id}'")
|
|
314
|
+
|
|
315
|
+
thread_key = _none_if_blank(thread_key)
|
|
316
|
+
thread_name = _none_if_blank(thread_name)
|
|
317
|
+
message_name = _none_if_null_sentinel(message_name)
|
|
318
|
+
|
|
319
|
+
if message_name is not None:
|
|
320
|
+
if thread_name or thread_key:
|
|
321
|
+
raise UserInputError(
|
|
322
|
+
"message_name cannot be combined with thread_name or thread_key: "
|
|
323
|
+
"editing a message cannot move it to another thread."
|
|
324
|
+
)
|
|
325
|
+
message_name = _normalize_message_resource_name(message_name, "message_name")
|
|
326
|
+
if message_name.split("/messages/", 1)[0] != space_id:
|
|
327
|
+
raise UserInputError(
|
|
328
|
+
f"message_name '{message_name}' does not belong to space '{space_id}'. "
|
|
329
|
+
"Expected the full resource name, e.g. spaces/X/messages/Y."
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
message = await asyncio.to_thread(
|
|
333
|
+
service.spaces()
|
|
334
|
+
.messages()
|
|
335
|
+
.patch(
|
|
336
|
+
name=message_name,
|
|
337
|
+
updateMask="text",
|
|
338
|
+
body={"text": message_text},
|
|
339
|
+
)
|
|
340
|
+
.execute
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
update_time = message.get("lastUpdateTime") or message.get("createTime", "")
|
|
344
|
+
msg = (
|
|
345
|
+
f"Message updated in space '{space_id}' by {user_google_email}. "
|
|
346
|
+
f"Message ID: {message.get('name', message_name)}, Time: {update_time}"
|
|
347
|
+
)
|
|
348
|
+
logger.info(
|
|
349
|
+
f"Successfully updated message '{message_name}' by {user_google_email}"
|
|
350
|
+
)
|
|
351
|
+
return msg
|
|
352
|
+
|
|
353
|
+
message_body = {"text": message_text}
|
|
354
|
+
|
|
355
|
+
request_params = {"parent": space_id, "body": message_body}
|
|
356
|
+
|
|
357
|
+
# Thread reply support
|
|
358
|
+
if thread_name:
|
|
359
|
+
message_body["thread"] = {"name": thread_name}
|
|
360
|
+
request_params["messageReplyOption"] = "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
|
|
361
|
+
elif thread_key:
|
|
362
|
+
message_body["thread"] = {"threadKey": thread_key}
|
|
363
|
+
request_params["messageReplyOption"] = "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
|
|
364
|
+
|
|
365
|
+
message = await asyncio.to_thread(
|
|
366
|
+
service.spaces().messages().create(**request_params).execute
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
sent_message_name = message.get("name", "")
|
|
370
|
+
create_time = message.get("createTime", "")
|
|
371
|
+
|
|
372
|
+
msg = f"Message sent to space '{space_id}' by {user_google_email}. Message ID: {sent_message_name}, Time: {create_time}"
|
|
373
|
+
logger.info(
|
|
374
|
+
f"Successfully sent message to space '{space_id}' by {user_google_email}"
|
|
375
|
+
)
|
|
376
|
+
return msg
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
@server.tool(
|
|
380
|
+
title="Search Messages",
|
|
381
|
+
annotations=ToolAnnotations(
|
|
382
|
+
readOnlyHint=True,
|
|
383
|
+
destructiveHint=False,
|
|
384
|
+
idempotentHint=True,
|
|
385
|
+
openWorldHint=True,
|
|
386
|
+
),
|
|
387
|
+
)
|
|
388
|
+
@require_multiple_services(
|
|
389
|
+
[
|
|
390
|
+
{"service_type": "chat", "scopes": "chat_read", "param_name": "chat_service"},
|
|
391
|
+
{
|
|
392
|
+
"service_type": "people",
|
|
393
|
+
"scopes": "contacts_read",
|
|
394
|
+
"param_name": "people_service",
|
|
395
|
+
},
|
|
396
|
+
]
|
|
397
|
+
)
|
|
398
|
+
@handle_http_errors("search_messages", is_read_only=True, service_type="chat")
|
|
399
|
+
async def search_messages(
|
|
400
|
+
chat_service,
|
|
401
|
+
people_service,
|
|
402
|
+
user_google_email: str,
|
|
403
|
+
query: Optional[str] = None,
|
|
404
|
+
space_id: Optional[str] = None,
|
|
405
|
+
page_size: int = 25,
|
|
406
|
+
time_filter: Optional[str] = None,
|
|
407
|
+
max_spaces: int = 10,
|
|
408
|
+
) -> str:
|
|
409
|
+
"""
|
|
410
|
+
Searches for messages in Google Chat spaces by text content and/or time range.
|
|
411
|
+
|
|
412
|
+
Args:
|
|
413
|
+
query: Optional text to search for. If omitted, only time_filter is applied.
|
|
414
|
+
space_id: Optional space to restrict the search to.
|
|
415
|
+
page_size: Maximum number of messages to return per space.
|
|
416
|
+
time_filter: Optional filter using Chat API createTime syntax.
|
|
417
|
+
Examples:
|
|
418
|
+
'createTime > "2026-03-18T00:00:00-03:00"'
|
|
419
|
+
'createTime > "2026-03-18T00:00:00-03:00" AND createTime < "2026-03-19T00:00:00-03:00"'
|
|
420
|
+
max_spaces: Maximum number of spaces to search when space_id is not provided (default 10).
|
|
421
|
+
|
|
422
|
+
Returns:
|
|
423
|
+
str: A formatted list of messages matching the search criteria.
|
|
424
|
+
"""
|
|
425
|
+
logger.info(
|
|
426
|
+
f"[search_messages] Email={user_google_email}, query_len={len(query) if query else 0}, has_time_filter={bool(time_filter)}"
|
|
427
|
+
)
|
|
428
|
+
if query:
|
|
429
|
+
logger.debug(f"[search_messages] Query='{query}'")
|
|
430
|
+
if time_filter:
|
|
431
|
+
logger.debug(f"[search_messages] TimeFilter='{time_filter}'")
|
|
432
|
+
|
|
433
|
+
# Google Chat messages.list supports time/thread filters, but not full-text
|
|
434
|
+
# search. Apply only supported API filters, then filter message text below.
|
|
435
|
+
filter_parts = []
|
|
436
|
+
if time_filter:
|
|
437
|
+
filter_parts.append(time_filter)
|
|
438
|
+
filter_str = " AND ".join(filter_parts) if filter_parts else None
|
|
439
|
+
|
|
440
|
+
search_terms = []
|
|
441
|
+
if query:
|
|
442
|
+
search_terms.append(f'text "{query}"')
|
|
443
|
+
if time_filter:
|
|
444
|
+
search_terms.append(time_filter)
|
|
445
|
+
search_desc = " and ".join(search_terms) if search_terms else "all messages"
|
|
446
|
+
|
|
447
|
+
# If specific space provided, search within that space
|
|
448
|
+
if space_id:
|
|
449
|
+
space_id = _normalize_space_resource_name(space_id)
|
|
450
|
+
list_params = {
|
|
451
|
+
"parent": space_id,
|
|
452
|
+
"pageSize": page_size,
|
|
453
|
+
"orderBy": "createTime desc",
|
|
454
|
+
}
|
|
455
|
+
if filter_str:
|
|
456
|
+
list_params["filter"] = filter_str
|
|
457
|
+
response = await _execute_chat_request(
|
|
458
|
+
lambda: chat_service.spaces().messages().list(**list_params),
|
|
459
|
+
request_label=f"fetching messages for {space_id}",
|
|
460
|
+
retries=_SEARCH_MESSAGES_SSL_RETRIES,
|
|
461
|
+
)
|
|
462
|
+
space = await _execute_chat_request(
|
|
463
|
+
lambda: chat_service.spaces().get(name=space_id),
|
|
464
|
+
request_label=f"fetching space {space_id}",
|
|
465
|
+
retries=_SEARCH_MESSAGES_SSL_RETRIES,
|
|
466
|
+
)
|
|
467
|
+
messages = response.get("messages", [])
|
|
468
|
+
for msg in messages:
|
|
469
|
+
msg["_space"] = space
|
|
470
|
+
context = f"space '{space_id}'"
|
|
471
|
+
else:
|
|
472
|
+
# Search across accessible spaces, paging until max_spaces are listed
|
|
473
|
+
spaces = []
|
|
474
|
+
list_params = {"pageSize": 100}
|
|
475
|
+
while True:
|
|
476
|
+
spaces_response = await _execute_chat_request(
|
|
477
|
+
lambda: chat_service.spaces().list(**list_params),
|
|
478
|
+
request_label="listing accessible spaces",
|
|
479
|
+
retries=_SEARCH_MESSAGES_SSL_RETRIES,
|
|
480
|
+
)
|
|
481
|
+
spaces.extend(spaces_response.get("spaces", []))
|
|
482
|
+
next_page_token = spaces_response.get("nextPageToken")
|
|
483
|
+
if len(spaces) >= max_spaces or not next_page_token:
|
|
484
|
+
break
|
|
485
|
+
list_params["pageToken"] = next_page_token
|
|
486
|
+
spaces_to_search = spaces[:max_spaces]
|
|
487
|
+
fetch_semaphore = asyncio.Semaphore(
|
|
488
|
+
_SEARCH_MESSAGES_MAX_CONCURRENT_SPACE_FETCHES
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
async def fetch_space_messages(space: dict) -> tuple[List[dict], bool]:
|
|
492
|
+
try:
|
|
493
|
+
list_params = {
|
|
494
|
+
"parent": space.get("name"),
|
|
495
|
+
"pageSize": page_size,
|
|
496
|
+
"orderBy": "createTime desc",
|
|
497
|
+
}
|
|
498
|
+
if filter_str:
|
|
499
|
+
list_params["filter"] = filter_str
|
|
500
|
+
response = await _execute_chat_request(
|
|
501
|
+
lambda: chat_service.spaces().messages().list(**list_params),
|
|
502
|
+
request_label=f"fetching messages for {space.get('name')}",
|
|
503
|
+
retries=_SEARCH_MESSAGES_SSL_RETRIES,
|
|
504
|
+
semaphore=fetch_semaphore,
|
|
505
|
+
)
|
|
506
|
+
msgs = response.get("messages", [])
|
|
507
|
+
for msg in msgs:
|
|
508
|
+
msg["_space"] = space
|
|
509
|
+
return msgs, False
|
|
510
|
+
except HttpError as e:
|
|
511
|
+
logger.debug(
|
|
512
|
+
"Skipping space %s during search: %s", space.get("name"), e
|
|
513
|
+
)
|
|
514
|
+
return [], False
|
|
515
|
+
except ssl.SSLError as e:
|
|
516
|
+
logger.warning(
|
|
517
|
+
"Skipping space %s during search after repeated SSL failures: %s",
|
|
518
|
+
space.get("name"),
|
|
519
|
+
e,
|
|
520
|
+
)
|
|
521
|
+
return [], True
|
|
522
|
+
|
|
523
|
+
results = await asyncio.gather(
|
|
524
|
+
*(fetch_space_messages(space) for space in spaces_to_search)
|
|
525
|
+
)
|
|
526
|
+
transient_failures = 0
|
|
527
|
+
messages = []
|
|
528
|
+
for batch, had_transient_failure in results:
|
|
529
|
+
messages.extend(batch)
|
|
530
|
+
transient_failures += int(had_transient_failure)
|
|
531
|
+
if spaces_to_search and transient_failures == len(spaces_to_search):
|
|
532
|
+
raise TransientNetworkError(
|
|
533
|
+
"A transient SSL error occurred in 'search_messages' while searching Chat spaces. "
|
|
534
|
+
"Please try again shortly."
|
|
535
|
+
)
|
|
536
|
+
if len(spaces) > len(spaces_to_search) or spaces_response.get("nextPageToken"):
|
|
537
|
+
context = f"the first {len(spaces_to_search)} accessible spaces"
|
|
538
|
+
else:
|
|
539
|
+
context = "all accessible spaces"
|
|
540
|
+
|
|
541
|
+
# Client-side text filtering (text: operator is not supported by the API)
|
|
542
|
+
if query:
|
|
543
|
+
query_lower = query.lower()
|
|
544
|
+
messages = [m for m in messages if query_lower in (m.get("text") or "").lower()]
|
|
545
|
+
|
|
546
|
+
if not messages:
|
|
547
|
+
suffix = (
|
|
548
|
+
f" Skipped {transient_failures} spaces due to repeated SSL failures."
|
|
549
|
+
if "transient_failures" in locals() and transient_failures
|
|
550
|
+
else ""
|
|
551
|
+
)
|
|
552
|
+
return f"No messages found matching '{search_desc}' in {context}.{suffix}"
|
|
553
|
+
|
|
554
|
+
# Resolve senders sequentially. The underlying googleapiclient/httplib2
|
|
555
|
+
# service objects are not safe to fan out heavily and can trigger SSL churn.
|
|
556
|
+
sender_lookup = {}
|
|
557
|
+
for msg in messages:
|
|
558
|
+
s = msg.get("sender", {})
|
|
559
|
+
key = s.get("name", "")
|
|
560
|
+
if key and key not in sender_lookup:
|
|
561
|
+
sender_lookup[key] = s
|
|
562
|
+
sender_map = {}
|
|
563
|
+
for key, sender_obj in sender_lookup.items():
|
|
564
|
+
sender_map[key] = await _resolve_sender(
|
|
565
|
+
people_service, sender_obj, user_google_email
|
|
566
|
+
)
|
|
567
|
+
|
|
568
|
+
space_names = await _name_spaces(
|
|
569
|
+
chat_service,
|
|
570
|
+
people_service,
|
|
571
|
+
[msg["_space"] for msg in messages if msg.get("_space")],
|
|
572
|
+
user_google_email,
|
|
573
|
+
)
|
|
574
|
+
|
|
575
|
+
output = [f"Found {len(messages)} messages matching '{search_desc}' in {context}:"]
|
|
576
|
+
for msg in messages:
|
|
577
|
+
sender_obj = msg.get("sender", {})
|
|
578
|
+
sender_key = sender_obj.get("name", "")
|
|
579
|
+
sender = sender_map.get(sender_key) or await _resolve_sender(
|
|
580
|
+
people_service, sender_obj, user_google_email
|
|
581
|
+
)
|
|
582
|
+
create_time = msg.get("createTime", "Unknown Time")
|
|
583
|
+
text_content = msg.get("text", "No text content")
|
|
584
|
+
space_name = space_names.get(msg.get("_space", {}).get("name"), "Unknown Space")
|
|
585
|
+
|
|
586
|
+
# Truncate long messages
|
|
587
|
+
if len(text_content) > 100:
|
|
588
|
+
text_content = text_content[:100] + "..."
|
|
589
|
+
|
|
590
|
+
rich_links = _extract_rich_links(msg)
|
|
591
|
+
links_suffix = "".join(f" [linked: {url}]" for url in rich_links)
|
|
592
|
+
attachments = msg.get("attachment", [])
|
|
593
|
+
att_suffix = "".join(
|
|
594
|
+
f" [attachment: {a.get('contentName', 'unnamed')} ({a.get('contentType', 'unknown type')})]"
|
|
595
|
+
for a in attachments
|
|
596
|
+
)
|
|
597
|
+
summary = f"[{create_time}] {sender} in '{space_name}': {text_content}{links_suffix}{att_suffix}"
|
|
598
|
+
output.append(
|
|
599
|
+
f"- {' '.join(summary.split())}\n {_format_search_message_ids(msg)}"
|
|
600
|
+
)
|
|
601
|
+
|
|
602
|
+
return "\n".join(output)
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
@server.tool(
|
|
606
|
+
title="Create Reaction",
|
|
607
|
+
annotations=ToolAnnotations(
|
|
608
|
+
readOnlyHint=False,
|
|
609
|
+
destructiveHint=False,
|
|
610
|
+
idempotentHint=False,
|
|
611
|
+
openWorldHint=True,
|
|
612
|
+
),
|
|
613
|
+
)
|
|
614
|
+
@require_google_service("chat", "chat_write")
|
|
615
|
+
@handle_http_errors("create_reaction", service_type="chat")
|
|
616
|
+
async def create_reaction(
|
|
617
|
+
service,
|
|
618
|
+
user_google_email: str,
|
|
619
|
+
message_id: str,
|
|
620
|
+
emoji_unicode: str,
|
|
621
|
+
) -> str:
|
|
622
|
+
"""
|
|
623
|
+
Adds an emoji reaction to a Google Chat message.
|
|
624
|
+
|
|
625
|
+
Args:
|
|
626
|
+
message_id: The message resource name (e.g. spaces/X/messages/Y).
|
|
627
|
+
emoji_unicode: The emoji character to react with (e.g. 👍).
|
|
628
|
+
|
|
629
|
+
Returns:
|
|
630
|
+
str: Confirmation message.
|
|
631
|
+
"""
|
|
632
|
+
message_id = _normalize_message_resource_name(message_id)
|
|
633
|
+
logger.info(f"[create_reaction] Message: '{message_id}', Emoji: '{emoji_unicode}'")
|
|
634
|
+
|
|
635
|
+
reaction = await asyncio.to_thread(
|
|
636
|
+
service.spaces()
|
|
637
|
+
.messages()
|
|
638
|
+
.reactions()
|
|
639
|
+
.create(
|
|
640
|
+
parent=message_id,
|
|
641
|
+
body={"emoji": {"unicode": emoji_unicode}},
|
|
642
|
+
)
|
|
643
|
+
.execute
|
|
644
|
+
)
|
|
645
|
+
|
|
646
|
+
reaction_name = reaction.get("name", "")
|
|
647
|
+
return f"Reacted with {emoji_unicode} on message {message_id}. Reaction ID: {reaction_name}"
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
@server.tool(
|
|
651
|
+
title="Download Chat Attachment",
|
|
652
|
+
annotations=ToolAnnotations(
|
|
653
|
+
readOnlyHint=False,
|
|
654
|
+
destructiveHint=False,
|
|
655
|
+
idempotentHint=False,
|
|
656
|
+
openWorldHint=True,
|
|
657
|
+
),
|
|
658
|
+
)
|
|
659
|
+
@handle_http_errors("download_chat_attachment", is_read_only=True, service_type="chat")
|
|
660
|
+
@require_google_service("chat", "chat_read")
|
|
661
|
+
async def download_chat_attachment(
|
|
662
|
+
service,
|
|
663
|
+
user_google_email: str,
|
|
664
|
+
message_id: str,
|
|
665
|
+
attachment_index: int = 0,
|
|
666
|
+
) -> str:
|
|
667
|
+
"""
|
|
668
|
+
Downloads an attachment from a Google Chat message and saves it to local disk.
|
|
669
|
+
|
|
670
|
+
In stdio mode, returns the local file path for direct access.
|
|
671
|
+
In HTTP mode, returns a temporary download URL (valid for 1 hour).
|
|
672
|
+
|
|
673
|
+
Args:
|
|
674
|
+
message_id: The message resource name (e.g. spaces/X/messages/Y).
|
|
675
|
+
attachment_index: Zero-based index of the attachment to download (default 0).
|
|
676
|
+
|
|
677
|
+
Returns:
|
|
678
|
+
str: Attachment metadata with either a local file path or download URL.
|
|
679
|
+
"""
|
|
680
|
+
message_id = _normalize_message_resource_name(message_id)
|
|
681
|
+
logger.info(
|
|
682
|
+
f"[download_chat_attachment] Message: '{message_id}', Index: {attachment_index}"
|
|
683
|
+
)
|
|
684
|
+
|
|
685
|
+
# Fetch the message to get attachment metadata
|
|
686
|
+
msg = await asyncio.to_thread(
|
|
687
|
+
service.spaces().messages().get(name=message_id).execute
|
|
688
|
+
)
|
|
689
|
+
|
|
690
|
+
attachments = msg.get("attachment", [])
|
|
691
|
+
if not attachments:
|
|
692
|
+
return f"No attachments found on message {message_id}."
|
|
693
|
+
|
|
694
|
+
if attachment_index < 0 or attachment_index >= len(attachments):
|
|
695
|
+
return (
|
|
696
|
+
f"Invalid attachment_index {attachment_index}. "
|
|
697
|
+
f"Message has {len(attachments)} attachment(s) (0-{len(attachments) - 1})."
|
|
698
|
+
)
|
|
699
|
+
|
|
700
|
+
att = attachments[attachment_index]
|
|
701
|
+
filename = att.get("contentName", "attachment")
|
|
702
|
+
content_type = att.get("contentType", "application/octet-stream")
|
|
703
|
+
source = att.get("source", "")
|
|
704
|
+
|
|
705
|
+
# The media endpoint needs attachmentDataRef.resourceName (e.g.
|
|
706
|
+
# "spaces/S/attachments/A"), NOT the attachment name which includes
|
|
707
|
+
# the /messages/ segment and causes 400 errors.
|
|
708
|
+
media_resource = att.get("attachmentDataRef", {}).get("resourceName", "")
|
|
709
|
+
att_name = att.get("name", "")
|
|
710
|
+
|
|
711
|
+
logger.info(
|
|
712
|
+
f"[download_chat_attachment] Downloading '{filename}' ({content_type}), "
|
|
713
|
+
f"source={source}, mediaResource={media_resource}, name={att_name}"
|
|
714
|
+
)
|
|
715
|
+
|
|
716
|
+
# Download the attachment binary data via the Chat API media endpoint.
|
|
717
|
+
# Prefer httpx + Bearer token: MediaIoBaseDownload / AuthorizedHttp fail in
|
|
718
|
+
# OAuth 2.1 (no refresh_token). The attachment's downloadUri points to
|
|
719
|
+
# chat.google.com which requires browser cookies.
|
|
720
|
+
if not media_resource and not att_name:
|
|
721
|
+
return f"No resource name available for attachment '{filename}'."
|
|
722
|
+
|
|
723
|
+
# Prefer attachmentDataRef.resourceName for the media endpoint
|
|
724
|
+
resource_name = media_resource or att_name
|
|
725
|
+
download_url = f"https://chat.googleapis.com/v1/media/{resource_name}?alt=media"
|
|
726
|
+
|
|
727
|
+
try:
|
|
728
|
+
access_token = service._http.credentials.token
|
|
729
|
+
file_bytes = await download_http_url_bytes(
|
|
730
|
+
download_url,
|
|
731
|
+
headers={"Authorization": f"Bearer {access_token}"},
|
|
732
|
+
file_name=filename,
|
|
733
|
+
kind="attachment",
|
|
734
|
+
)
|
|
735
|
+
except FileTooLargeError as e:
|
|
736
|
+
return str(e)
|
|
737
|
+
except httpx.HTTPStatusError as e:
|
|
738
|
+
body = (e.response.text or "")[:500]
|
|
739
|
+
return (
|
|
740
|
+
f"Failed to download attachment '{filename}': "
|
|
741
|
+
f"HTTP {e.response.status_code} from {download_url}\n{body}"
|
|
742
|
+
)
|
|
743
|
+
except Exception as e:
|
|
744
|
+
return f"Failed to download attachment '{filename}': {e}"
|
|
745
|
+
|
|
746
|
+
size_bytes = len(file_bytes)
|
|
747
|
+
size_kb = size_bytes / 1024
|
|
748
|
+
|
|
749
|
+
# Stateless mode has no file storage unless GCS staging is configured.
|
|
750
|
+
from auth.oauth_config import is_stateless_mode
|
|
751
|
+
|
|
752
|
+
if is_stateless_mode() and not gcs_files_enabled():
|
|
753
|
+
# 75 input bytes encode to at most 100 base64 characters; do not encode
|
|
754
|
+
# the entire attachment merely to return a short preview.
|
|
755
|
+
b64_preview = base64.urlsafe_b64encode(file_bytes[:75]).decode("utf-8")[:100]
|
|
756
|
+
return "\n".join(
|
|
757
|
+
[
|
|
758
|
+
f"Attachment downloaded: {filename} ({content_type})",
|
|
759
|
+
f"Size: {size_kb:.1f} KB ({size_bytes} bytes)",
|
|
760
|
+
"",
|
|
761
|
+
"Stateless mode: File storage disabled.",
|
|
762
|
+
f"Base64 preview: {b64_preview}...",
|
|
763
|
+
]
|
|
764
|
+
)
|
|
765
|
+
|
|
766
|
+
# Save to local disk
|
|
767
|
+
from core.attachment_storage import get_attachment_storage, get_attachment_url
|
|
768
|
+
from core.config import get_transport_mode
|
|
769
|
+
|
|
770
|
+
storage = get_attachment_storage()
|
|
771
|
+
# The GCS backend uploads over the network, so keep it off the event loop.
|
|
772
|
+
result = await asyncio.to_thread(
|
|
773
|
+
storage.save_attachment_bytes,
|
|
774
|
+
file_bytes=file_bytes,
|
|
775
|
+
filename=filename,
|
|
776
|
+
mime_type=content_type,
|
|
777
|
+
)
|
|
778
|
+
|
|
779
|
+
result_lines = [
|
|
780
|
+
f"Attachment downloaded: {filename}",
|
|
781
|
+
f"Type: {content_type}",
|
|
782
|
+
f"Size: {size_kb:.1f} KB ({size_bytes} bytes)",
|
|
783
|
+
]
|
|
784
|
+
|
|
785
|
+
if get_transport_mode() == "stdio":
|
|
786
|
+
result_lines.append(f"\nSaved to: {result.path}")
|
|
787
|
+
result_lines.append(
|
|
788
|
+
"\nThe file has been saved to disk and can be accessed directly via the file path."
|
|
789
|
+
)
|
|
790
|
+
else:
|
|
791
|
+
download_url = await asyncio.to_thread(get_attachment_url, result.file_id)
|
|
792
|
+
result_lines.append(f"\nDownload URL: {download_url}")
|
|
793
|
+
result_lines.append("\nThe file will expire after 1 hour.")
|
|
794
|
+
|
|
795
|
+
logger.info(
|
|
796
|
+
f"[download_chat_attachment] Saved {size_kb:.1f} KB attachment to {result.path}"
|
|
797
|
+
)
|
|
798
|
+
return "\n".join(result_lines)
|