@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.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +28 -0
  4. package/auth/__init__.py +1 -0
  5. package/auth/auth_info_middleware.py +419 -0
  6. package/auth/client_secrets.py +76 -0
  7. package/auth/credential_store.py +598 -0
  8. package/auth/external_oauth_provider.py +369 -0
  9. package/auth/gateway_identity.py +164 -0
  10. package/auth/google_auth.py +1550 -0
  11. package/auth/google_oauth_provider.py +20 -0
  12. package/auth/mcp_session_middleware.py +95 -0
  13. package/auth/oauth21_session_store.py +1332 -0
  14. package/auth/oauth_callback_server.py +466 -0
  15. package/auth/oauth_config.py +693 -0
  16. package/auth/oauth_proxy_config.py +122 -0
  17. package/auth/oauth_responses.py +230 -0
  18. package/auth/oauth_types.py +92 -0
  19. package/auth/permissions.py +330 -0
  20. package/auth/port_resolver.py +153 -0
  21. package/auth/request_identity.py +89 -0
  22. package/auth/scopes.py +369 -0
  23. package/auth/service_decorator.py +1109 -0
  24. package/bin/google-workspace-mcp.cjs +123 -0
  25. package/core/__init__.py +1 -0
  26. package/core/api_enablement.py +108 -0
  27. package/core/attachment_storage.py +496 -0
  28. package/core/camel_case_middleware.py +98 -0
  29. package/core/cli.py +161 -0
  30. package/core/comments.py +609 -0
  31. package/core/config.py +57 -0
  32. package/core/context.py +43 -0
  33. package/core/file_limits.py +632 -0
  34. package/core/gcs_attachment_storage.py +253 -0
  35. package/core/http_utils.py +339 -0
  36. package/core/log_formatter.py +270 -0
  37. package/core/portable_schema_middleware.py +67 -0
  38. package/core/server.py +1192 -0
  39. package/core/startup_ui.py +239 -0
  40. package/core/storage.py +23 -0
  41. package/core/telemetry.py +194 -0
  42. package/core/tool_descriptions.py +19 -0
  43. package/core/tool_registry.py +311 -0
  44. package/core/tool_tier_loader.py +197 -0
  45. package/core/tool_tiers.yaml +179 -0
  46. package/core/toolset_header_middleware.py +67 -0
  47. package/core/utils.py +1537 -0
  48. package/core/valkey_storage.py +271 -0
  49. package/core/warning_filters.py +19 -0
  50. package/fastmcp_server.py +198 -0
  51. package/gappsscript/README.md +512 -0
  52. package/gappsscript/TESTING.md +254 -0
  53. package/gappsscript/__init__.py +0 -0
  54. package/gappsscript/apps_script_tools.py +1940 -0
  55. package/gcalendar/__init__.py +1 -0
  56. package/gcalendar/calendar_helpers.py +1323 -0
  57. package/gcalendar/calendar_tools.py +2252 -0
  58. package/gchat/__init__.py +7 -0
  59. package/gchat/chat_helpers.py +410 -0
  60. package/gchat/chat_tools.py +798 -0
  61. package/gcontacts/__init__.py +1 -0
  62. package/gcontacts/contacts_helpers.py +765 -0
  63. package/gcontacts/contacts_tools.py +1685 -0
  64. package/gdocs/__init__.py +0 -0
  65. package/gdocs/docs_anchors.py +163 -0
  66. package/gdocs/docs_comments.py +89 -0
  67. package/gdocs/docs_helpers.py +2201 -0
  68. package/gdocs/docs_links.py +87 -0
  69. package/gdocs/docs_markdown.py +828 -0
  70. package/gdocs/docs_markdown_writer.py +592 -0
  71. package/gdocs/docs_plain_text.py +463 -0
  72. package/gdocs/docs_structure.py +621 -0
  73. package/gdocs/docs_tables.py +425 -0
  74. package/gdocs/docs_tools.py +3300 -0
  75. package/gdocs/managers/__init__.py +18 -0
  76. package/gdocs/managers/batch_operation_manager.py +1694 -0
  77. package/gdocs/managers/header_footer_manager.py +526 -0
  78. package/gdocs/managers/table_operation_manager.py +488 -0
  79. package/gdocs/managers/validation_manager.py +1504 -0
  80. package/gdocs/operation_schemas.py +594 -0
  81. package/gdrive/__init__.py +0 -0
  82. package/gdrive/drive_helpers.py +1738 -0
  83. package/gdrive/drive_tools.py +3085 -0
  84. package/gforms/__init__.py +3 -0
  85. package/gforms/forms_tools.py +575 -0
  86. package/gmail/__init__.py +1 -0
  87. package/gmail/gmail_helpers.py +2107 -0
  88. package/gmail/gmail_tools.py +4895 -0
  89. package/gmail/gmail_web_mime.py +441 -0
  90. package/gsearch/__init__.py +0 -0
  91. package/gsearch/search_tools.py +253 -0
  92. package/gsheets/__init__.py +31 -0
  93. package/gsheets/sheets_helpers.py +2236 -0
  94. package/gsheets/sheets_tools.py +3280 -0
  95. package/gslides/__init__.py +0 -0
  96. package/gslides/slides_digest.py +390 -0
  97. package/gslides/slides_helpers.py +392 -0
  98. package/gslides/slides_markup.py +770 -0
  99. package/gslides/slides_tools.py +376 -0
  100. package/gtasks/__init__.py +5 -0
  101. package/gtasks/tasks_tools.py +936 -0
  102. package/main.py +1170 -0
  103. package/package.json +43 -4
  104. package/pyproject.toml +173 -0
  105. package/uv.lock +2504 -0
File without changes
@@ -0,0 +1,163 @@
1
+ """
2
+ Resolution of semantic anchors to Google Docs indices.
3
+
4
+ Docs write requests address raw indices, and every write shifts the indices that
5
+ follow it. Resolving a human-meaningful target ("after the Results heading") at
6
+ execution time rather than at generation time removes the stale-index class of
7
+ error, where an edit lands on unrelated content without failing.
8
+ """
9
+
10
+ import logging
11
+ from typing import Any, Iterator, Optional
12
+
13
+ from gdocs.docs_helpers import _paragraph_element_text, utf16_length
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # Named styles that count as a heading for after_heading / before_heading.
18
+ HEADING_STYLES = ("TITLE", "SUBTITLE")
19
+
20
+
21
+ class AnchorResolutionError(Exception):
22
+ """Raised when an anchor matches zero or more than one location."""
23
+
24
+
25
+ def _is_heading(style: dict[str, Any]) -> bool:
26
+ named_style = style.get("namedStyleType", "")
27
+ return named_style.startswith("HEADING_") or named_style in HEADING_STYLES
28
+
29
+
30
+ def _aligned_paragraph_text(paragraph: dict[str, Any]) -> str:
31
+ """Paragraph text whose character offsets match the document's indices."""
32
+ return "".join(
33
+ _paragraph_element_text(element) for element in paragraph.get("elements", [])
34
+ )
35
+
36
+
37
+ def iter_paragraphs(
38
+ body: dict[str, Any], include_tables: bool = False
39
+ ) -> Iterator[tuple[int, int, str, dict[str, Any]]]:
40
+ """Yield (start_index, end_index, text, paragraph_style) for each paragraph.
41
+
42
+ include_tables also yields the paragraphs inside table cells, in document order.
43
+ """
44
+ for element in body.get("content", []):
45
+ paragraph = element.get("paragraph")
46
+ if paragraph is not None:
47
+ yield (
48
+ element.get("startIndex", 0),
49
+ element.get("endIndex", 0),
50
+ _aligned_paragraph_text(paragraph),
51
+ paragraph.get("paragraphStyle", {}),
52
+ )
53
+ continue
54
+ table = element.get("table")
55
+ if include_tables and table is not None:
56
+ for row in table.get("tableRows", []):
57
+ for cell in row.get("tableCells", []):
58
+ yield from iter_paragraphs(cell, include_tables=True)
59
+
60
+
61
+ def _only_match(matches: list[int], anchor_kind: str, needle: str) -> int:
62
+ if not matches:
63
+ raise AnchorResolutionError(
64
+ f"{anchor_kind} '{needle}' was not found in the document."
65
+ )
66
+ if len(matches) > 1:
67
+ raise AnchorResolutionError(
68
+ f"{anchor_kind} '{needle}' matches {len(matches)} locations "
69
+ f"(at indices {', '.join(str(m) for m in matches)}). "
70
+ "Use a longer, unique anchor or target an index directly."
71
+ )
72
+ return matches[0]
73
+
74
+
75
+ def resolve_heading(body: dict[str, Any], heading: str, position: str) -> int:
76
+ """
77
+ Resolve a heading's text to an insertion index.
78
+
79
+ position "after" returns the index just past the heading paragraph, which is
80
+ the start of its following paragraph. position "before" returns the heading's
81
+ own start index.
82
+ """
83
+ wanted = heading.strip().casefold()
84
+ matches = []
85
+ for start_index, end_index, text, style in iter_paragraphs(body):
86
+ if not _is_heading(style):
87
+ continue
88
+ if text.strip().casefold() == wanted:
89
+ matches.append(end_index if position == "after" else start_index)
90
+ kind = "after_heading" if position == "after" else "before_heading"
91
+ return _only_match(matches, kind, heading)
92
+
93
+
94
+ def resolve_anchor_text(body: dict[str, Any], anchor: str, position: str) -> int:
95
+ """
96
+ Resolve literal text to an index at its start ("before") or end ("after").
97
+
98
+ The search runs per paragraph, so an anchor spanning a paragraph break will
99
+ not match; that is deliberate, since such an anchor is ambiguous to place.
100
+ """
101
+ matches = []
102
+ for start_index, _end_index, text, _style in iter_paragraphs(body):
103
+ offset = text.find(anchor)
104
+ while offset != -1:
105
+ matches.append(
106
+ start_index
107
+ + utf16_length(text[:offset])
108
+ + (utf16_length(anchor) if position == "after" else 0)
109
+ )
110
+ offset = text.find(anchor, offset + 1)
111
+ return _only_match(matches, "anchor_text", anchor)
112
+
113
+
114
+ def resolve_anchor_range(body: dict[str, Any], anchor: str) -> tuple[int, int]:
115
+ """Resolve literal text within one paragraph to its (start_index, end_index).
116
+
117
+ Table cells are searched too; the anchor must occur exactly once.
118
+ """
119
+ if not anchor or not anchor.strip():
120
+ raise AnchorResolutionError("anchor_text must not be empty.")
121
+ anchor_units = utf16_length(anchor)
122
+ matches: list[tuple[int, int]] = []
123
+ for start_index, _end_index, text, _style in iter_paragraphs(
124
+ body, include_tables=True
125
+ ):
126
+ position, units = 0, 0
127
+ offset = text.find(anchor)
128
+ while offset != -1:
129
+ units += utf16_length(text[position:offset])
130
+ position = offset
131
+ start = start_index + units
132
+ matches.append((start, start + anchor_units))
133
+ offset = text.find(anchor, offset + 1)
134
+ if not matches:
135
+ raise AnchorResolutionError(f"anchor_text '{anchor}' was not found in the tab.")
136
+ if len(matches) > 1:
137
+ raise AnchorResolutionError(
138
+ f"anchor_text '{anchor}' matches {len(matches)} locations "
139
+ f"(at indices {', '.join(str(start) for start, _ in matches)}). "
140
+ "Use a longer, unique anchor."
141
+ )
142
+ return matches[0]
143
+
144
+
145
+ def resolve_operation_anchor(
146
+ body: dict[str, Any],
147
+ after_heading: Optional[str] = None,
148
+ before_heading: Optional[str] = None,
149
+ anchor_text: Optional[str] = None,
150
+ anchor_position: str = "after",
151
+ ) -> int:
152
+ """Resolve whichever anchor an operation carries into a document index."""
153
+ if after_heading is not None:
154
+ return resolve_heading(body, after_heading, "after")
155
+ if before_heading is not None:
156
+ return resolve_heading(body, before_heading, "before")
157
+ if anchor_text is not None:
158
+ if anchor_position not in ("before", "after"):
159
+ raise AnchorResolutionError(
160
+ f"anchor_position must be 'before' or 'after', got '{anchor_position}'."
161
+ )
162
+ return resolve_anchor_text(body, anchor_text, anchor_position)
163
+ raise AnchorResolutionError("No anchor provided.")
@@ -0,0 +1,89 @@
1
+ """Comments anchored to text in a Google Doc, created through the Docs API."""
2
+
3
+ import asyncio
4
+ from typing import Any, Optional
5
+
6
+ from core.utils import UserInputError
7
+ from gdocs.docs_anchors import AnchorResolutionError, resolve_anchor_range
8
+ from gdocs.managers.batch_operation_manager import BatchOperationManager
9
+
10
+ # InsertCommentRequest.content is capped by the Docs API.
11
+ MAX_COMMENT_UTF8_UNITS = 2048
12
+
13
+ # BatchUpdateDocumentResponse.commentUpdateState when no comment was saved.
14
+ COMMENT_UPDATE_FAILED = "ALL_FAILED_UNKNOWN_REASON"
15
+
16
+
17
+ def build_insert_comment_request(
18
+ start_index: int,
19
+ end_index: int,
20
+ comment_content: str,
21
+ tab_id: Optional[str] = None,
22
+ ) -> dict[str, Any]:
23
+ """Build the batchUpdate request that creates a comment thread on a range."""
24
+ comment_range: dict[str, Any] = {"startIndex": start_index, "endIndex": end_index}
25
+ if tab_id:
26
+ comment_range["tabId"] = tab_id
27
+ return {"insertComment": {"range": comment_range, "content": comment_content}}
28
+
29
+
30
+ async def insert_anchored_comment(
31
+ docs_service,
32
+ document_id: str,
33
+ anchor_text: str,
34
+ comment_content: str,
35
+ tab_id: Optional[str] = None,
36
+ ) -> dict[str, Any]:
37
+ """Create a comment anchored to anchor_text in a tab (the first by default).
38
+
39
+ Returns the thread's comment_id, quoted_text, start_index and end_index.
40
+ """
41
+ if len(comment_content.encode("utf-8")) > MAX_COMMENT_UTF8_UNITS:
42
+ raise UserInputError(
43
+ f"comment_content exceeds the Docs API limit of {MAX_COMMENT_UTF8_UNITS} "
44
+ "UTF-8 code units for an anchored comment; shorten it or split it."
45
+ )
46
+
47
+ doc = await asyncio.to_thread(
48
+ docs_service.documents()
49
+ .get(documentId=document_id, includeTabsContent=True)
50
+ .execute
51
+ )
52
+ tab_body = BatchOperationManager._target_segment(doc, tab_id)
53
+ if tab_body is None and tab_id:
54
+ raise UserInputError(f"Tab '{tab_id}' not found in the document.")
55
+ try:
56
+ start_index, end_index = resolve_anchor_range(tab_body or {}, anchor_text)
57
+ except AnchorResolutionError as e:
58
+ raise UserInputError(str(e)) from e
59
+
60
+ request = build_insert_comment_request(
61
+ start_index, end_index, comment_content, tab_id
62
+ )
63
+ body: dict[str, Any] = {"requests": [request]}
64
+ # Absent for users without edit access; their write goes unguarded.
65
+ if doc.get("revisionId"):
66
+ body["writeControl"] = {"requiredRevisionId": doc["revisionId"]}
67
+ response = await asyncio.to_thread(
68
+ docs_service.documents().batchUpdate(documentId=document_id, body=body).execute
69
+ )
70
+
71
+ if response.get("commentUpdateState") == COMMENT_UPDATE_FAILED:
72
+ raise RuntimeError(
73
+ "Docs API reported that the comment was not saved "
74
+ f"({COMMENT_UPDATE_FAILED}); check list_document_comments before retrying."
75
+ )
76
+ replies = response.get("replies") or [{}]
77
+ thread = replies[0].get("insertComment", {}).get("commentThread", {})
78
+ comment_id = thread.get("commentId")
79
+ if not comment_id:
80
+ raise RuntimeError(
81
+ "Docs API did not return a comment ID; check list_document_comments "
82
+ "before retrying."
83
+ )
84
+ return {
85
+ "comment_id": comment_id,
86
+ "quoted_text": thread.get("plainTextQuote") or anchor_text,
87
+ "start_index": start_index,
88
+ "end_index": end_index,
89
+ }