diff --git a/README.md b/README.md index 279da1d..b0a51a1 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,13 @@ Credentials saved to file: [PATH_TO_CREDENTIALS_JSON] Replace `PATH_TO_CREDENTIALS_JSON` with the path you copied in the previous step. + It's also possible to use an + [OAuth 2.0 access token](https://developers.google.com/identity/protocols/oauth2) + to authorize the MCP server, by replacing the `GOOGLE_APPLICATION_CREDENTIALS` + attribute with the `GOOGLE_ACCESS_TOKEN` attribute in the `env` object. + For it's value, use a valid OAuth 2.0 access token with the + `https://www.googleapis.com/auth/analytics.readonly` scope. + We also recommend that you add a `GOOGLE_CLOUD_PROJECT` attribute to the `env` object. Replace `YOUR_PROJECT_ID` in the following example with the [project ID](https://support.google.com/googleapi/answer/7014113) of your diff --git a/analytics_mcp/tools/utils.py b/analytics_mcp/tools/utils.py index 34eec86..c321560 100644 --- a/analytics_mcp/tools/utils.py +++ b/analytics_mcp/tools/utils.py @@ -14,11 +14,13 @@ """Common utilities used by the MCP server.""" +import os from typing import Any, Dict from google.analytics import admin_v1beta, data_v1beta from google.api_core.gapic_v1.client_info import ClientInfo from importlib import metadata +import google.oauth2.credentials import google.auth import proto @@ -44,9 +46,16 @@ def _get_package_version_with_fallback(): "https://www.googleapis.com/auth/analytics.readonly" ) +# Pre-obtained access token to use instead of ADC, if set. +_ACCESS_TOKEN = os.environ.get("GOOGLE_ACCESS_TOKEN") -def _create_credentials() -> google.auth.credentials.Credentials: - """Returns Application Default Credentials with read-only scope.""" + +def _create_credentials() -> ( + google.oauth2.credentials.Credentials | google.auth.credentials.Credentials +): + """Returns credentials from access token, if set, otherwise Application Default Credentials with read-only scope.""" + if _ACCESS_TOKEN: + return google.oauth2.credentials.Credentials(_ACCESS_TOKEN) (credentials, _) = google.auth.default(scopes=[_READ_ONLY_ANALYTICS_SCOPE]) return credentials