Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 11 additions & 2 deletions analytics_mcp/tools/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down