Skip to content

Commit f7fb60c

Browse files
feat: add support for using access token instead of ADC
1 parent 7a569b5 commit f7fb60c

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,13 @@ Credentials saved to file: [PATH_TO_CREDENTIALS_JSON]
121121
Replace `PATH_TO_CREDENTIALS_JSON` with the path you copied in the previous
122122
step.
123123

124+
It's also possible to use an
125+
[OAuth 2.0 access token](https://developers.google.com/identity/protocols/oauth2)
126+
to authorize the MCP server, by replacing the `GOOGLE_APPLICATION_CREDENTIALS`
127+
attribute with the `GOOGLE_ACCESS_TOKEN` attribute in the `env` object.
128+
For it's value, use a valid OAuth 2.0 access token with the
129+
`https://www.googleapis.com/auth/analytics.readonly` scope.
130+
124131
We also recommend that you add a `GOOGLE_CLOUD_PROJECT` attribute to the
125132
`env` object. Replace `YOUR_PROJECT_ID` in the following example with the
126133
[project ID](https://support.google.com/googleapi/answer/7014113) of your

analytics_mcp/tools/utils.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,13 @@
1414

1515
"""Common utilities used by the MCP server."""
1616

17+
import os
1718
from typing import Any, Dict
1819

1920
from google.analytics import admin_v1beta, data_v1beta
2021
from google.api_core.gapic_v1.client_info import ClientInfo
2122
from importlib import metadata
23+
import google.oauth2.credentials
2224
import google.auth
2325
import proto
2426

@@ -44,9 +46,16 @@ def _get_package_version_with_fallback():
4446
"https://www.googleapis.com/auth/analytics.readonly"
4547
)
4648

49+
# Pre-obtained access token to use instead of ADC, if set.
50+
_ACCESS_TOKEN = os.environ.get("GOOGLE_ACCESS_TOKEN")
4751

48-
def _create_credentials() -> google.auth.credentials.Credentials:
49-
"""Returns Application Default Credentials with read-only scope."""
52+
53+
def _create_credentials() -> (
54+
google.oauth2.credentials.Credentials | google.auth.credentials.Credentials
55+
):
56+
"""Returns credentials from access token, if set, otherwise Application Default Credentials with read-only scope."""
57+
if _ACCESS_TOKEN:
58+
return google.oauth2.credentials.Credentials(_ACCESS_TOKEN)
5059
(credentials, _) = google.auth.default(scopes=[_READ_ONLY_ANALYTICS_SCOPE])
5160
return credentials
5261

0 commit comments

Comments
 (0)