@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.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +34 -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
@@ -0,0 +1,239 @@
1
+ """
2
+ Terminal presentation for the Google Workspace MCP startup sequence.
3
+
4
+ Centralises the ANSI palette, section rules and column alignment used by
5
+ ``main.py`` so the startup screen reads as one coherent block instead of a
6
+ stream of ad-hoc prints. Every method renders through a caller-supplied
7
+ ``emit`` callable, which keeps the transport-safety rules (stdout must stay
8
+ clean for JSON-RPC) in one place in ``main.py``.
9
+ """
10
+
11
+ import os
12
+ import shutil
13
+ import sys
14
+ import textwrap
15
+ from typing import Callable, Iterable, Sequence
16
+
17
+ # Rule width bounds. Narrow enough to survive a split pane, wide enough that
18
+ # credential paths do not wrap.
19
+ MIN_WIDTH = 60
20
+ MAX_WIDTH = 76
21
+
22
+ # Hues, used only where the color itself carries meaning.
23
+ BLUE = "\033[1;34m"
24
+ RED = "\033[1;31m"
25
+ YELLOW = "\033[1;33m"
26
+ GREEN = "\033[1;32m"
27
+ CYAN = "\033[0;36m"
28
+
29
+ # Emphasis is expressed with attributes rather than hardcoded neutrals: SGR 1
30
+ # and SGR 2 compose with whatever foreground the terminal already uses, so the
31
+ # screen stays legible on black, white and tinted backgrounds alike. A fixed
32
+ # grey such as SGR 90 would assume a near-black background. Terminals that
33
+ # ignore SGR 2 simply render the text at full strength, which is still legible.
34
+ BOLD = "\033[1m"
35
+ FAINT = "\033[2m"
36
+ RESET = "\033[0m"
37
+
38
+ # state -> (glyph, glyph color, value color)
39
+ _FIELD_STATES = {
40
+ "on": ("●", GREEN, ""),
41
+ "off": ("○", FAINT, FAINT),
42
+ "warn": ("●", YELLOW, YELLOW),
43
+ }
44
+
45
+ # state -> (glyph, color)
46
+ _STEP_STATES = {
47
+ "ok": ("✓", GREEN),
48
+ "skip": ("·", FAINT),
49
+ "warn": ("!", YELLOW),
50
+ "fail": ("✗", RED),
51
+ }
52
+
53
+ # (plain, colored) pairs. The plain form drives column alignment; the block
54
+ # characters below are all single-width so ``len`` is an accurate measure.
55
+ _LOGO_ROWS = (
56
+ ("██████╗", (BLUE, "██████", RED, "╗")),
57
+ ("██╔════╝", (BLUE, "██", "", "╔════╝")),
58
+ ("██║ ███╗", (BLUE, "██", "", "║ ", YELLOW, "███", "", "╗")),
59
+ ("██║ ██║", (BLUE, "██", "", "║ ", YELLOW, "██", "", "║")),
60
+ ("╚██████╔╝", (BLUE, "╚█████", GREEN, "█╔╝")),
61
+ (" ╚═════╝", ("", " ", BLUE, "╚════", GREEN, "═╝")),
62
+ )
63
+ _LOGO_INDENT = 5
64
+ _LOGO_GUTTER = 5
65
+ _LOGO_WIDTH = max(len(plain) for plain, _ in _LOGO_ROWS)
66
+
67
+ # Floor for the value column so a very wide label cannot squeeze it to nothing.
68
+ _MIN_VALUE = 24
69
+
70
+
71
+ def supports_color() -> bool:
72
+ """Report whether stderr can render ANSI color."""
73
+ return (
74
+ sys.stderr.isatty()
75
+ and os.getenv("NO_COLOR") is None
76
+ and os.getenv("TERM") != "dumb"
77
+ )
78
+
79
+
80
+ def elide(value: str, limit: int) -> str:
81
+ """Shorten ``value`` from the middle so both ends stay recognisable."""
82
+ if len(value) <= limit:
83
+ return value
84
+ head = (limit - 1) // 2
85
+ tail = limit - 1 - head
86
+ return f"{value[:head]}…{value[-tail:]}"
87
+
88
+
89
+ def collapse_home(path: str) -> str:
90
+ """Render ``path`` with the user's home directory as ``~``."""
91
+ home = os.path.expanduser("~")
92
+ if path == home:
93
+ return "~"
94
+ if path.startswith(home + os.sep):
95
+ return "~" + path[len(home) :]
96
+ return path
97
+
98
+
99
+ class StartupDisplay:
100
+ """Renders the startup screen through a caller-supplied emit function."""
101
+
102
+ def __init__(
103
+ self,
104
+ emit: Callable[[str], None],
105
+ *,
106
+ color: bool | None = None,
107
+ width: int | None = None,
108
+ ):
109
+ self.emit = emit
110
+ self.color = supports_color() if color is None else color
111
+ self.width = width or self._terminal_width()
112
+
113
+ @staticmethod
114
+ def _terminal_width() -> int:
115
+ columns = shutil.get_terminal_size((80, 24)).columns
116
+ return max(MIN_WIDTH, min(MAX_WIDTH, columns - 2))
117
+
118
+ def paint(self, code: str, text: str) -> str:
119
+ """Wrap ``text`` in an ANSI ``code`` when color is enabled."""
120
+ if not self.color or not code:
121
+ return text
122
+ return f"{code}{text}{RESET}"
123
+
124
+ def blank(self) -> None:
125
+ self.emit("")
126
+
127
+ def rule(self, title: str | None = None) -> None:
128
+ """Draw a full-width rule, optionally labelled with a section title."""
129
+ if not title:
130
+ self.emit(self.paint(FAINT, "━" * self.width))
131
+ return
132
+ trailing = max(3, self.width - len(title) - 4)
133
+ self.emit(
134
+ f"{self.paint(FAINT, '━━')} {self.paint(BOLD, title)} "
135
+ f"{self.paint(FAINT, '━' * trailing)}"
136
+ )
137
+
138
+ def banner(self, info: Sequence[str | None]) -> None:
139
+ """Print the wordmark with ``info`` aligned in a fixed right column."""
140
+ for index, (plain, segments) in enumerate(_LOGO_ROWS):
141
+ logo = "".join(
142
+ self.paint(segments[i], segments[i + 1])
143
+ for i in range(0, len(segments), 2)
144
+ )
145
+ line = f"{' ' * _LOGO_INDENT}{logo}"
146
+ detail = info[index] if index < len(info) else None
147
+ if detail:
148
+ pad = _LOGO_WIDTH - len(plain) + _LOGO_GUTTER
149
+ line += f"{' ' * pad}{detail}"
150
+ self.emit(line.rstrip())
151
+
152
+ def heading(self, text: str) -> None:
153
+ """Dim sub-heading that groups related rows inside a section."""
154
+ self.emit(f" {self.paint(BOLD, text)}")
155
+
156
+ def fields(
157
+ self, groups: Sequence[tuple[str | None, Sequence[tuple[str, str, str]]]]
158
+ ) -> None:
159
+ """Render labelled groups of ``(label, value, state)`` rows in one column."""
160
+ labels = [label for _, rows in groups for label, _, _ in rows]
161
+ if not labels:
162
+ return
163
+ pad = max(len(label) for label in labels)
164
+ # Rows are indented 4, then glyph + space, then the label column and a
165
+ # two-space gutter. Whatever is left of the rule belongs to the value.
166
+ limit = max(_MIN_VALUE, self.width - pad - 8)
167
+ for index, (title, rows) in enumerate(groups):
168
+ if index:
169
+ self.blank()
170
+ if title:
171
+ self.heading(title)
172
+ for label, value, state in rows:
173
+ glyph, glyph_color, value_color = _FIELD_STATES[state]
174
+ self.emit(
175
+ f" {self.paint(glyph_color, glyph)} "
176
+ f"{label.ljust(pad)} "
177
+ f"{self.paint(value_color, elide(value, limit))}"
178
+ )
179
+
180
+ def grid(self, cells: Sequence[tuple[str, str]], columns: int = 4) -> None:
181
+ """Lay ``(icon, label)`` cells out in aligned columns."""
182
+ if not cells:
183
+ return
184
+ pad = max(len(label) for _, label in cells)
185
+ for start in range(0, len(cells), columns):
186
+ row = cells[start : start + columns]
187
+ rendered = [
188
+ f"{icon} {self.paint(BOLD, label)}{' ' * (pad - len(label))}"
189
+ for icon, label in row
190
+ ]
191
+ self.emit(f" {' '.join(rendered).rstrip()}")
192
+
193
+ def step(self, text: str, detail: str | None = None, state: str = "ok") -> None:
194
+ """Report a completed startup step, optionally with a trailing detail."""
195
+ glyph, color = _STEP_STATES[state]
196
+ line = f" {self.paint(color, glyph)} {text}"
197
+ if detail:
198
+ line += f" {self.paint(CYAN, detail)}"
199
+ self.emit(line)
200
+
201
+ def detail(self, text: str) -> None:
202
+ """Continuation line beneath a step."""
203
+ self.emit(f" {self.paint(FAINT, text)}")
204
+
205
+ def notice(self, text: str, state: str = "warn") -> None:
206
+ """Wrap and print an advisory paragraph."""
207
+ glyph, color = _STEP_STATES[state]
208
+ body = textwrap.wrap(" ".join(text.split()), width=self.width - 4) or [""]
209
+ self.emit(f" {self.paint(color, glyph)} {body[0]}")
210
+ for line in body[1:]:
211
+ self.emit(f" {line}")
212
+
213
+ def section(self, title: str) -> None:
214
+ """Open a titled section with the surrounding whitespace it needs."""
215
+ self.blank()
216
+ self.rule(title)
217
+ self.blank()
218
+
219
+
220
+ def wordmark_lines(
221
+ display: StartupDisplay,
222
+ *,
223
+ version: str,
224
+ transport: str,
225
+ mode: str,
226
+ python_version: str,
227
+ url: str | None,
228
+ flags: Iterable[str] = (),
229
+ ) -> list[str | None]:
230
+ """Build the six-line info column that sits beside the wordmark."""
231
+ descriptor = " · ".join([transport, mode, *flags])
232
+ return [
233
+ display.paint(BOLD, "Google Workspace"),
234
+ f"{display.paint(BOLD, 'MCP Server')} {display.paint(CYAN, 'v' + version)}",
235
+ None,
236
+ display.paint(CYAN, descriptor),
237
+ display.paint(CYAN, f"Python {python_version}"),
238
+ display.paint(CYAN, url) if url else None,
239
+ ]
@@ -0,0 +1,23 @@
1
+ """Shared helpers for creating disk-backed key-value stores."""
2
+
3
+ import string
4
+
5
+ from key_value.aio._utils.sanitization import HybridSanitizationStrategy
6
+ from key_value.aio.stores.filetree import FileTreeStore
7
+
8
+ SAFE_FILENAME_CHARS = string.ascii_letters + string.digits + "-_."
9
+ """Characters allowed in on-disk file names for key-value stores."""
10
+
11
+
12
+ def make_sanitized_file_store(data_directory: str) -> FileTreeStore:
13
+ """Return a ``FileTreeStore`` using the project-wide sanitization rules.
14
+
15
+ Both the OAuth-proxy server storage and the CLI token storage need
16
+ identical sanitization; this factory keeps them in sync.
17
+ """
18
+ return FileTreeStore(
19
+ data_directory=data_directory,
20
+ key_sanitization_strategy=HybridSanitizationStrategy(
21
+ allowed_characters=SAFE_FILENAME_CHARS,
22
+ ),
23
+ )
@@ -0,0 +1,194 @@
1
+ """Optional OpenTelemetry tracing bootstrap.
2
+
3
+ FastMCP is already instrumented with OpenTelemetry (see ``fastmcp.telemetry``),
4
+ but it links only ``opentelemetry-api``, so every span is a no-op until a
5
+ ``TracerProvider`` with an exporter is configured. This module wires that
6
+ provider from the standard ``OTEL_*`` environment variables so FastMCP's
7
+ tool-call spans are exported to an OTLP collector.
8
+
9
+ It is entirely opt-in: if no OTLP endpoint is configured the function is a
10
+ no-op, and if the SDK extra is not installed it logs a hint and returns. Enable
11
+ it by installing the ``otel`` extra and setting ``OTEL_EXPORTER_OTLP_ENDPOINT``.
12
+ """
13
+
14
+ import logging
15
+ import os
16
+ from typing import Any, Optional
17
+
18
+ from opentelemetry import trace
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ DEFAULT_SERVICE_NAME = "google-workspace-mcp"
23
+ _OTLP_PROTOCOL_GRPC = "grpc"
24
+ _OTLP_PROTOCOL_HTTP = "http/protobuf"
25
+
26
+ # Recording the authenticated user's email on spans is personally identifying,
27
+ # so it is strictly opt-in and off by default. FastMCP's own spans already
28
+ # carry the opaque ``enduser.id`` derived from the OAuth token; this adds a
29
+ # human-readable ``user.email`` only when the operator sets this env var.
30
+ USER_EMAIL_ATTRIBUTE_ENV = "WORKSPACE_MCP_OTEL_USER_EMAIL"
31
+ _TRUTHY = {"1", "true", "yes", "on"}
32
+
33
+
34
+ def _user_email_attribute_enabled() -> bool:
35
+ """True if the operator opted in to recording the user email on spans."""
36
+ return os.getenv(USER_EMAIL_ATTRIBUTE_ENV, "").strip().lower() in _TRUTHY
37
+
38
+
39
+ def record_authenticated_user(email: Optional[str]) -> None:
40
+ """Attach the authenticated Google user's email to the active span.
41
+
42
+ Sets the OpenTelemetry ``user.email`` attribute so tool-call traces can be
43
+ attributed to a person rather than only the opaque ``enduser.id`` FastMCP
44
+ derives from the OAuth token. This is PII, so it is a no-op unless the
45
+ operator opts in via ``WORKSPACE_MCP_OTEL_USER_EMAIL``. Safe to call
46
+ unconditionally: it no-ops when disabled, when there is no email, or when
47
+ no span is recording.
48
+ """
49
+ if email and _user_email_attribute_enabled():
50
+ _set_span_attribute("user.email", email)
51
+
52
+
53
+ def record_google_principal(auth_mode: str, email: Optional[str]) -> None:
54
+ """Attach the Google identity a tool call acts as to the active span.
55
+
56
+ ``workspace_mcp.auth.mode`` names the credential path (``service-account``,
57
+ ``oauth2.1`` or ``oauth2.0``) and is always recorded. Under domain-wide
58
+ delegation the impersonated subject can differ from the MCP caller in
59
+ ``user.email``, so ``workspace_mcp.google.principal`` records the account
60
+ the Google API calls actually run as. That email is PII and follows the
61
+ same ``WORKSPACE_MCP_OTEL_USER_EMAIL`` opt-in as ``user.email``.
62
+ """
63
+ _set_span_attribute("workspace_mcp.auth.mode", auth_mode)
64
+ if email and _user_email_attribute_enabled():
65
+ _set_span_attribute("workspace_mcp.google.principal", email)
66
+
67
+
68
+ def record_degraded_failure(error: BaseException) -> None:
69
+ """Mark the active span as failed for an error a tool caught and recovered from.
70
+
71
+ Records only the exception type and errno, since the message can carry file
72
+ paths derived from email subjects and attachment names.
73
+ """
74
+ span = trace.get_current_span()
75
+ if not span.is_recording():
76
+ return
77
+ error_type = type(error).__name__
78
+ attributes = {"exception.type": error_type}
79
+ if isinstance(getattr(error, "errno", None), int):
80
+ attributes["exception.errno"] = error.errno
81
+ span.add_event("exception", attributes)
82
+ span.set_status(trace.Status(trace.StatusCode.ERROR, error_type))
83
+
84
+
85
+ def _set_span_attribute(key: str, value: str) -> None:
86
+ """Set an attribute on the active span if one is recording."""
87
+ span = trace.get_current_span()
88
+ if span.is_recording():
89
+ span.set_attribute(key, value)
90
+
91
+
92
+ def _otlp_endpoint_configured() -> bool:
93
+ """True if the user pointed us at an OTLP collector via standard env vars."""
94
+ return bool(
95
+ os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT")
96
+ or os.getenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")
97
+ )
98
+
99
+
100
+ def _build_span_exporter() -> tuple[Any, str]:
101
+ """Build an OTLP span exporter honoring OTEL_EXPORTER_OTLP[_TRACES]_PROTOCOL.
102
+
103
+ Defaults to gRPC per the OpenTelemetry specification. Endpoint, headers and
104
+ TLS are read from the standard env vars by the exporter itself.
105
+ """
106
+ protocol = (
107
+ (
108
+ os.getenv("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL")
109
+ or os.getenv("OTEL_EXPORTER_OTLP_PROTOCOL")
110
+ or _OTLP_PROTOCOL_GRPC
111
+ )
112
+ .strip()
113
+ .lower()
114
+ )
115
+
116
+ if protocol == _OTLP_PROTOCOL_HTTP:
117
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
118
+ OTLPSpanExporter,
119
+ )
120
+ elif protocol == _OTLP_PROTOCOL_GRPC:
121
+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
122
+ OTLPSpanExporter,
123
+ )
124
+ else:
125
+ raise ValueError("OTLP protocol must be 'grpc' or 'http/protobuf'")
126
+ return OTLPSpanExporter(), protocol
127
+
128
+
129
+ def _build_resource():
130
+ """Build an OTEL resource while supplying a useful fallback service name."""
131
+ from opentelemetry.sdk.resources import Resource
132
+
133
+ resource = Resource.create()
134
+ service_name = str(resource.attributes.get("service.name", ""))
135
+ if not service_name or service_name.startswith("unknown_service"):
136
+ resource = resource.merge(Resource({"service.name": DEFAULT_SERVICE_NAME}))
137
+ return resource
138
+
139
+
140
+ def configure_telemetry() -> bool:
141
+ """Configure OpenTelemetry tracing if an OTLP endpoint is set.
142
+
143
+ Returns True if a real ``TracerProvider`` was installed, False otherwise
144
+ (no endpoint configured, SDK not installed, provider already configured, or
145
+ setup failed). Safe to call unconditionally at startup.
146
+ """
147
+ if not _otlp_endpoint_configured():
148
+ return False
149
+
150
+ try:
151
+ from opentelemetry.sdk.trace import TracerProvider
152
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
153
+ except ImportError:
154
+ logger.warning(
155
+ "An OTLP endpoint is set, but the OpenTelemetry SDK is not installed; "
156
+ "reinstall with the 'otel' extra to enable tracing."
157
+ )
158
+ return False
159
+
160
+ # OpenTelemetry permits only one global provider. Leave a provider installed
161
+ # by auto-instrumentation or an embedding application untouched.
162
+ if not isinstance(trace.get_tracer_provider(), trace.ProxyTracerProvider):
163
+ logger.info(
164
+ "OpenTelemetry tracing provider is already configured; leaving it unchanged."
165
+ )
166
+ return False
167
+
168
+ try:
169
+ exporter, protocol = _build_span_exporter()
170
+ except ImportError:
171
+ logger.warning(
172
+ "OpenTelemetry OTLP exporter not available; reinstall with the "
173
+ "'otel' extra to enable tracing."
174
+ )
175
+ return False
176
+ except Exception as exc:
177
+ logger.warning("OpenTelemetry tracing configuration is invalid: %s", exc)
178
+ return False
179
+
180
+ try:
181
+ resource = _build_resource()
182
+ provider = TracerProvider(resource=resource)
183
+ provider.add_span_processor(BatchSpanProcessor(exporter))
184
+ trace.set_tracer_provider(provider)
185
+ except Exception as exc:
186
+ logger.warning("Failed to configure OpenTelemetry tracing: %s", exc)
187
+ return False
188
+
189
+ logger.info(
190
+ "OpenTelemetry tracing enabled (service=%s, protocol=%s)",
191
+ resource.attributes.get("service.name"),
192
+ protocol,
193
+ )
194
+ return True
@@ -0,0 +1,19 @@
1
+ """Tool descriptions taken from everything above a docstring's first standard section."""
2
+
3
+ import inspect
4
+ import re
5
+ from collections.abc import Callable
6
+ from itertools import takewhile
7
+ from typing import Any
8
+
9
+ _END_OF_DESCRIPTION = re.compile(
10
+ r"^(Args|Arguments|Parameters|Params|Returns|Return|Yields|Raises"
11
+ r"|Examples|Example):\s*$"
12
+ )
13
+
14
+
15
+ def docstring_description(fn: Callable[..., Any]) -> str | None:
16
+ """Return the docstring up to its first Args/Returns/Examples section, or None."""
17
+ lines = (inspect.getdoc(fn) or "").splitlines()
18
+ kept = takewhile(lambda line: not _END_OF_DESCRIPTION.match(line), lines)
19
+ return "\n".join(kept).strip() or None