|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# [START cloudrun_mcpserver_setup_otel] |
| 16 | +import logging |
| 17 | +import google.auth |
| 18 | +import google.auth.transport.requests |
| 19 | +import grpc |
| 20 | +from google.auth.transport.grpc import AuthMetadataPlugin |
| 21 | +from opentelemetry import trace |
| 22 | +from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import ( |
| 23 | + OTLPSpanExporter, |
| 24 | +) |
| 25 | +from opentelemetry.sdk.resources import SERVICE_NAME, Resource |
| 26 | +from opentelemetry.sdk.trace import TracerProvider |
| 27 | +from opentelemetry.sdk.trace.export import BatchSpanProcessor |
| 28 | + |
| 29 | +logger = logging.getLogger(__name__) |
| 30 | + |
| 31 | + |
| 32 | +def setup_opentelemetry(service_name: str) -> None: |
| 33 | + """Sets up OpenTelemetry to send traces to Google Cloud Observability.""" |
| 34 | + credentials, project_id = google.auth.default() |
| 35 | + if not project_id: |
| 36 | + raise Exception("Could not determine Google Cloud project ID.") |
| 37 | + |
| 38 | + resource = Resource.create( |
| 39 | + attributes={ |
| 40 | + SERVICE_NAME: service_name, |
| 41 | + "gcp.project_id": project_id, |
| 42 | + } |
| 43 | + ) |
| 44 | + |
| 45 | + # Set up OTLP auth |
| 46 | + request = google.auth.transport.requests.Request() |
| 47 | + auth_metadata_plugin = AuthMetadataPlugin(credentials=credentials, request=request) |
| 48 | + channel_creds = grpc.composite_channel_credentials( |
| 49 | + grpc.ssl_channel_credentials(), |
| 50 | + grpc.metadata_call_credentials(auth_metadata_plugin), |
| 51 | + ) |
| 52 | + |
| 53 | + # Set up OpenTelemetry Python SDK |
| 54 | + tracer_provider = TracerProvider(resource=resource) |
| 55 | + tracer_provider.add_span_processor( |
| 56 | + BatchSpanProcessor( |
| 57 | + OTLPSpanExporter( |
| 58 | + credentials=channel_creds, |
| 59 | + endpoint="https://telemetry.googleapis.com:443/v1/traces", |
| 60 | + ) |
| 61 | + ) |
| 62 | + ) |
| 63 | + trace.set_tracer_provider(tracer_provider) |
| 64 | + logger.info("OpenTelemetry successfully initialized.") |
| 65 | + |
| 66 | + |
| 67 | +# [END cloudrun_mcpserver_setup_otel] |
0 commit comments