googlemcp 0.1.0__py3-none-any.whl
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.
- googlemcp/__init__.py +17 -0
- googlemcp/__main__.py +8 -0
- googlemcp/auth/__init__.py +33 -0
- googlemcp/auth/credentials.py +195 -0
- googlemcp/auth/flow.py +323 -0
- googlemcp/catalog.py +49 -0
- googlemcp/cli.py +497 -0
- googlemcp/config.py +241 -0
- googlemcp/context.py +207 -0
- googlemcp/policy.py +89 -0
- googlemcp/probes.py +444 -0
- googlemcp/py.typed +0 -0
- googlemcp/redaction.py +90 -0
- googlemcp/secretstore/__init__.py +48 -0
- googlemcp/secretstore/backends.py +201 -0
- googlemcp/secretstore/base.py +69 -0
- googlemcp/secretstore/secretmanager.py +124 -0
- googlemcp/server.py +140 -0
- googlemcp/services/__init__.py +32 -0
- googlemcp/services/_reporting.py +72 -0
- googlemcp/services/analytics.py +179 -0
- googlemcp/services/appsscript.py +224 -0
- googlemcp/services/base.py +166 -0
- googlemcp/services/calendar.py +339 -0
- googlemcp/services/chat.py +163 -0
- googlemcp/services/docs.py +192 -0
- googlemcp/services/drive.py +350 -0
- googlemcp/services/driveactivity.py +138 -0
- googlemcp/services/forms.py +252 -0
- googlemcp/services/gmail.py +481 -0
- googlemcp/services/meet.py +194 -0
- googlemcp/services/people.py +355 -0
- googlemcp/services/photos.py +349 -0
- googlemcp/services/searchconsole.py +157 -0
- googlemcp/services/sheets.py +347 -0
- googlemcp/services/slides.py +189 -0
- googlemcp/services/tasks.py +186 -0
- googlemcp/services/youtube.py +303 -0
- googlemcp/services/youtube_analytics.py +85 -0
- googlemcp/services/youtube_reporting.py +108 -0
- googlemcp/services.json +167 -0
- googlemcp/testing.py +86 -0
- googlemcp-0.1.0.dist-info/METADATA +221 -0
- googlemcp-0.1.0.dist-info/RECORD +47 -0
- googlemcp-0.1.0.dist-info/WHEEL +4 -0
- googlemcp-0.1.0.dist-info/entry_points.txt +2 -0
- googlemcp-0.1.0.dist-info/licenses/LICENSE +21 -0
googlemcp/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""GoogleMCP: scoped Google API access over the Model Context Protocol."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
# Reported by a source tree that was never installed (no package metadata).
|
|
6
|
+
UNKNOWN_VERSION = "0.0.0+unknown"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _resolve_version(distribution: str = "googlemcp") -> str:
|
|
10
|
+
"""Installed package version, so ``pyproject.toml`` is the only place to bump it."""
|
|
11
|
+
try:
|
|
12
|
+
return version(distribution)
|
|
13
|
+
except PackageNotFoundError:
|
|
14
|
+
return UNKNOWN_VERSION
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
__version__ = _resolve_version()
|
googlemcp/__main__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Google account authorization (installed-app OAuth flow)."""
|
|
2
|
+
|
|
3
|
+
from googlemcp.auth.credentials import (
|
|
4
|
+
AuthError,
|
|
5
|
+
CredentialProvider,
|
|
6
|
+
credentials_from_store,
|
|
7
|
+
invalid_grant_message,
|
|
8
|
+
map_refresh_error,
|
|
9
|
+
)
|
|
10
|
+
from googlemcp.auth.flow import (
|
|
11
|
+
AuthStatus,
|
|
12
|
+
ClientVerificationResult,
|
|
13
|
+
LoginResult,
|
|
14
|
+
login,
|
|
15
|
+
revoke,
|
|
16
|
+
status,
|
|
17
|
+
verify_stored_client,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"AuthError",
|
|
22
|
+
"AuthStatus",
|
|
23
|
+
"ClientVerificationResult",
|
|
24
|
+
"CredentialProvider",
|
|
25
|
+
"LoginResult",
|
|
26
|
+
"credentials_from_store",
|
|
27
|
+
"invalid_grant_message",
|
|
28
|
+
"login",
|
|
29
|
+
"map_refresh_error",
|
|
30
|
+
"revoke",
|
|
31
|
+
"status",
|
|
32
|
+
"verify_stored_client",
|
|
33
|
+
]
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Credentials for Google API calls.
|
|
2
|
+
|
|
3
|
+
The server acts as one Google account, the one authorized with a refresh token
|
|
4
|
+
obtained by ``googlemcp auth login`` and kept in the secret store. Access
|
|
5
|
+
tokens live only in memory.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
import threading
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from google.auth.exceptions import RefreshError, TransportError
|
|
16
|
+
from google.auth.transport.requests import Request
|
|
17
|
+
from google.oauth2.credentials import Credentials
|
|
18
|
+
|
|
19
|
+
from googlemcp.redaction import redact
|
|
20
|
+
from googlemcp.secretstore import SecretKey, SecretStore, SecretStoreError
|
|
21
|
+
from googlemcp.services.base import UpstreamError
|
|
22
|
+
|
|
23
|
+
log = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
TOKEN_URI = "https://oauth2.googleapis.com/token" # noqa: S105 (endpoint, not a secret)
|
|
26
|
+
# Repo-relative, not URLs: tool errors pass through redact(), which replaces URLs.
|
|
27
|
+
LONGEVITY_DOC = "docs/access-longevity.md in the googlemcp repository"
|
|
28
|
+
SETUP_DOC = "docs/manual-steps.md in the googlemcp repository"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class AuthError(UpstreamError):
|
|
32
|
+
"""Google credentials are missing or rejected. Message says how to recover.
|
|
33
|
+
|
|
34
|
+
Subclasses ``UpstreamError`` so adapters and probes that catch upstream
|
|
35
|
+
failures classify it as an auth problem. ``status`` is 401 unless Google
|
|
36
|
+
could not be reached; ``reason`` is a stable code such as
|
|
37
|
+
``invalid_grant``, ``invalid_client``, ``missing_credentials``,
|
|
38
|
+
``refresh_failed``, or ``network``.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, message: str, *, reason: str = "auth_error", status: int | None = 401):
|
|
42
|
+
super().__init__(message, status=status, reason=reason)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def invalid_grant_message() -> str:
|
|
46
|
+
return (
|
|
47
|
+
"Google rejected the stored refresh token (invalid_grant): it was revoked, expired, "
|
|
48
|
+
"or replaced. Run `googlemcp auth login` again. If the OAuth consent screen "
|
|
49
|
+
"publishing status is Testing, Google expires refresh tokens after 7 days; "
|
|
50
|
+
f"see {LONGEVITY_DOC} for the In production fix."
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def map_refresh_error(exc: RefreshError) -> AuthError:
|
|
55
|
+
"""Translate a google-auth refresh failure into an actionable, secret-free error."""
|
|
56
|
+
error_code = None
|
|
57
|
+
if len(exc.args) > 1 and isinstance(exc.args[1], dict):
|
|
58
|
+
error_code = exc.args[1].get("error")
|
|
59
|
+
text = str(exc.args[0]) if exc.args else ""
|
|
60
|
+
if error_code == "invalid_grant" or "invalid_grant" in text:
|
|
61
|
+
return AuthError(invalid_grant_message(), reason="invalid_grant")
|
|
62
|
+
if error_code == "invalid_client" or "invalid_client" in text:
|
|
63
|
+
return AuthError(
|
|
64
|
+
"Google rejected the OAuth client (invalid_client). The client was deleted or its "
|
|
65
|
+
"secret rotated. Store the current Desktop client with `googlemcp auth login "
|
|
66
|
+
"--client-secrets <path>`.",
|
|
67
|
+
reason="invalid_client",
|
|
68
|
+
)
|
|
69
|
+
if error_code:
|
|
70
|
+
code = redact(str(error_code))
|
|
71
|
+
return AuthError(
|
|
72
|
+
f"token refresh failed ({code}). Run `googlemcp auth login`.",
|
|
73
|
+
reason=code,
|
|
74
|
+
)
|
|
75
|
+
return AuthError(
|
|
76
|
+
"token refresh failed. Run `googlemcp doctor` for details.", reason="refresh_failed"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def credentials_from_store(store: SecretStore) -> Credentials:
|
|
81
|
+
try:
|
|
82
|
+
client_id = store.get(SecretKey.OAUTH_CLIENT_ID)
|
|
83
|
+
client_secret = store.get(SecretKey.OAUTH_CLIENT_SECRET)
|
|
84
|
+
refresh_token = store.get(SecretKey.REFRESH_TOKEN)
|
|
85
|
+
except SecretStoreError as exc:
|
|
86
|
+
raise AuthError(str(exc), reason="secret_store") from None
|
|
87
|
+
missing = [
|
|
88
|
+
key.value
|
|
89
|
+
for key, value in (
|
|
90
|
+
(SecretKey.OAUTH_CLIENT_ID, client_id),
|
|
91
|
+
(SecretKey.OAUTH_CLIENT_SECRET, client_secret),
|
|
92
|
+
(SecretKey.REFRESH_TOKEN, refresh_token),
|
|
93
|
+
)
|
|
94
|
+
if not value
|
|
95
|
+
]
|
|
96
|
+
if missing:
|
|
97
|
+
if client_id and client_secret:
|
|
98
|
+
hint = "Run `googlemcp auth login` to authorize your Google account."
|
|
99
|
+
else:
|
|
100
|
+
hint = (
|
|
101
|
+
"Not logged in yet: run `googlemcp auth login --client-secrets "
|
|
102
|
+
"<path-to-Desktop-OAuth-client.json>` once to store the OAuth client and "
|
|
103
|
+
f"authorize your Google account. See {SETUP_DOC}."
|
|
104
|
+
)
|
|
105
|
+
raise AuthError(
|
|
106
|
+
f"missing secrets in the {store.name} store: {', '.join(missing)}. {hint}",
|
|
107
|
+
reason="missing_credentials",
|
|
108
|
+
)
|
|
109
|
+
# No scopes on refresh: Google returns a token for whatever the user
|
|
110
|
+
# granted. Missing scopes surface per call (403) and in `auth status`.
|
|
111
|
+
return Credentials( # type: ignore[no-untyped-call]
|
|
112
|
+
token=None,
|
|
113
|
+
refresh_token=refresh_token,
|
|
114
|
+
client_id=client_id,
|
|
115
|
+
client_secret=client_secret,
|
|
116
|
+
token_uri=TOKEN_URI,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class CredentialProvider:
|
|
121
|
+
"""Thread-safe holder that refreshes on demand and persists rotated tokens."""
|
|
122
|
+
|
|
123
|
+
def __init__(
|
|
124
|
+
self,
|
|
125
|
+
store: SecretStore,
|
|
126
|
+
*,
|
|
127
|
+
request_factory: Callable[[], Any] = Request,
|
|
128
|
+
credentials: Credentials | None = None,
|
|
129
|
+
):
|
|
130
|
+
self._store = store
|
|
131
|
+
self._request_factory = request_factory
|
|
132
|
+
self._credentials = credentials
|
|
133
|
+
self._lock = threading.Lock()
|
|
134
|
+
|
|
135
|
+
def _load(self) -> Credentials:
|
|
136
|
+
if self._credentials is None:
|
|
137
|
+
self._credentials = credentials_from_store(self._store)
|
|
138
|
+
return self._credentials
|
|
139
|
+
|
|
140
|
+
def get(self) -> Credentials:
|
|
141
|
+
"""Return valid credentials, refreshing first when needed."""
|
|
142
|
+
with self._lock:
|
|
143
|
+
creds = self._load()
|
|
144
|
+
if not creds.valid:
|
|
145
|
+
self._refresh(creds)
|
|
146
|
+
return self._load()
|
|
147
|
+
|
|
148
|
+
def force_refresh(self) -> Credentials:
|
|
149
|
+
with self._lock:
|
|
150
|
+
self._refresh(self._load())
|
|
151
|
+
return self._load()
|
|
152
|
+
|
|
153
|
+
def _refresh(self, creds: Credentials, *, reloaded: bool = False) -> None:
|
|
154
|
+
previous = creds.refresh_token
|
|
155
|
+
try:
|
|
156
|
+
creds.refresh(self._request_factory()) # type: ignore[no-untyped-call]
|
|
157
|
+
except RefreshError as exc:
|
|
158
|
+
error = map_refresh_error(exc)
|
|
159
|
+
if not reloaded and self._store_has_newer_token(previous):
|
|
160
|
+
# Someone re-ran `auth login` (or a mounted secret moved to a
|
|
161
|
+
# new version) since this process loaded the token. Retry once.
|
|
162
|
+
log.info("stored refresh token changed; retrying with the new one")
|
|
163
|
+
self._credentials = credentials_from_store(self._store)
|
|
164
|
+
self._refresh(self._credentials, reloaded=True)
|
|
165
|
+
return
|
|
166
|
+
raise error from None
|
|
167
|
+
except TransportError:
|
|
168
|
+
raise AuthError(
|
|
169
|
+
"could not reach Google to refresh the access token (network error)",
|
|
170
|
+
reason="network",
|
|
171
|
+
status=None,
|
|
172
|
+
) from None
|
|
173
|
+
if creds.refresh_token and creds.refresh_token != previous:
|
|
174
|
+
self._persist_rotated(creds.refresh_token)
|
|
175
|
+
|
|
176
|
+
def _store_has_newer_token(self, current: str | None) -> bool:
|
|
177
|
+
try:
|
|
178
|
+
stored = self._store.get(SecretKey.REFRESH_TOKEN)
|
|
179
|
+
except SecretStoreError:
|
|
180
|
+
return False
|
|
181
|
+
return bool(stored) and stored != current
|
|
182
|
+
|
|
183
|
+
def _persist_rotated(self, token: str) -> None:
|
|
184
|
+
if self._store.read_only:
|
|
185
|
+
log.warning(
|
|
186
|
+
"Google rotated the refresh token but the %s store is read-only; "
|
|
187
|
+
"the new token lives only in memory until restart",
|
|
188
|
+
self._store.name,
|
|
189
|
+
)
|
|
190
|
+
return
|
|
191
|
+
try:
|
|
192
|
+
self._store.set(SecretKey.REFRESH_TOKEN, token)
|
|
193
|
+
log.info("persisted rotated refresh token to the %s store", self._store.name)
|
|
194
|
+
except SecretStoreError as exc:
|
|
195
|
+
log.warning("could not persist rotated refresh token: %s", exc)
|
googlemcp/auth/flow.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"""Interactive Google account authorization, status, and revocation.
|
|
2
|
+
|
|
3
|
+
``login`` runs Google's installed-app flow: a loopback redirect on 127.0.0.1
|
|
4
|
+
with PKCE (S256), ``access_type=offline`` and ``prompt=consent`` so Google
|
|
5
|
+
always returns a refresh token. The Desktop OAuth client comes from the
|
|
6
|
+
secret store, or from a downloaded client JSON that is read once, copied into
|
|
7
|
+
the secret store, and never written anywhere else.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hmac
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
from collections.abc import Callable, Sequence
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
import requests
|
|
21
|
+
|
|
22
|
+
from googlemcp.auth.credentials import AuthError, CredentialProvider
|
|
23
|
+
from googlemcp.secretstore import SecretKey, SecretStore, SecretStoreError, ensure_writable
|
|
24
|
+
|
|
25
|
+
AUTH_URI = "https://accounts.google.com/o/oauth2/auth"
|
|
26
|
+
TOKEN_URI = "https://oauth2.googleapis.com/token" # noqa: S105 (endpoint, not a secret)
|
|
27
|
+
REVOKE_URI = "https://oauth2.googleapis.com/revoke"
|
|
28
|
+
TOKENINFO_URI = "https://oauth2.googleapis.com/tokeninfo"
|
|
29
|
+
HTTP_TIMEOUT = 15
|
|
30
|
+
|
|
31
|
+
CLIENTS_CONSOLE_URL = "https://console.cloud.google.com/auth/clients"
|
|
32
|
+
SETUP_DOC = "https://github.com/1solomonwakhungu/googlemcp/blob/main/docs/manual-steps.md"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def client_setup_hint() -> str:
|
|
36
|
+
"""Where a new user gets the Desktop OAuth client JSON and what to run next."""
|
|
37
|
+
return (
|
|
38
|
+
f"Create an OAuth client of type 'Desktop app' at {CLIENTS_CONSOLE_URL} "
|
|
39
|
+
"(Google Auth Platform > Clients), download its JSON, then run "
|
|
40
|
+
"`googlemcp auth login --client-secrets <path-to-downloaded.json>`. "
|
|
41
|
+
f"See {SETUP_DOC} for the full Google Cloud setup."
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class ClientConfig:
|
|
47
|
+
client_id: str
|
|
48
|
+
client_secret: str
|
|
49
|
+
|
|
50
|
+
def as_installed(self) -> dict[str, Any]:
|
|
51
|
+
return {
|
|
52
|
+
"installed": {
|
|
53
|
+
"client_id": self.client_id,
|
|
54
|
+
"client_secret": self.client_secret,
|
|
55
|
+
"auth_uri": AUTH_URI,
|
|
56
|
+
"token_uri": TOKEN_URI,
|
|
57
|
+
"redirect_uris": ["http://127.0.0.1", "http://localhost"],
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def read_client_secrets(path: Path) -> ClientConfig:
|
|
63
|
+
"""Parse a downloaded Desktop OAuth client JSON without keeping a copy."""
|
|
64
|
+
try:
|
|
65
|
+
raw = json.loads(path.expanduser().read_text(encoding="utf-8"))
|
|
66
|
+
except FileNotFoundError:
|
|
67
|
+
raise AuthError(f"OAuth client file {path} does not exist. {client_setup_hint()}") from None
|
|
68
|
+
except ValueError:
|
|
69
|
+
raise AuthError(
|
|
70
|
+
f"OAuth client file {path} is not valid JSON. Download the client JSON again "
|
|
71
|
+
f"from {CLIENTS_CONSOLE_URL}."
|
|
72
|
+
) from None
|
|
73
|
+
except OSError as exc:
|
|
74
|
+
raise AuthError(f"cannot read OAuth client file {path} ({type(exc).__name__})") from None
|
|
75
|
+
if not isinstance(raw, dict) or "installed" not in raw:
|
|
76
|
+
kind = next(iter(raw), "unknown") if isinstance(raw, dict) and raw else "unknown"
|
|
77
|
+
raise AuthError(
|
|
78
|
+
f"{path} is a {kind!r} OAuth client. GoogleMCP needs a Desktop app client "
|
|
79
|
+
f"(JSON top-level key 'installed'). {client_setup_hint()}"
|
|
80
|
+
)
|
|
81
|
+
section = raw["installed"]
|
|
82
|
+
if not isinstance(section, dict):
|
|
83
|
+
raise AuthError(f"{path} is missing client_id or client_secret")
|
|
84
|
+
client_id, client_secret = section.get("client_id"), section.get("client_secret")
|
|
85
|
+
if (
|
|
86
|
+
not isinstance(client_id, str)
|
|
87
|
+
or not isinstance(client_secret, str)
|
|
88
|
+
or not client_id
|
|
89
|
+
or not client_secret
|
|
90
|
+
):
|
|
91
|
+
raise AuthError(f"{path} is missing client_id or client_secret")
|
|
92
|
+
return ClientConfig(client_id=client_id, client_secret=client_secret)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass(frozen=True)
|
|
96
|
+
class ClientVerificationResult:
|
|
97
|
+
"""Outcome of comparing stored OAuth client credentials with a JSON file.
|
|
98
|
+
|
|
99
|
+
Never contains the client_id or client_secret values.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
backend: str
|
|
103
|
+
matches: bool
|
|
104
|
+
problems: list[str] = field(default_factory=list)
|
|
105
|
+
|
|
106
|
+
def as_dict(self) -> dict[str, Any]:
|
|
107
|
+
return {
|
|
108
|
+
"backend": self.backend,
|
|
109
|
+
"matches": self.matches,
|
|
110
|
+
"problems": list(self.problems),
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _constant_time_equal(stored: str | None, wanted: str) -> bool:
|
|
115
|
+
return stored is not None and hmac.compare_digest(
|
|
116
|
+
stored.encode("utf-8"), wanted.encode("utf-8")
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def verify_stored_client(store: SecretStore, client_secrets: Path) -> ClientVerificationResult:
|
|
121
|
+
"""Confirm the secret store holds the exact Desktop OAuth client in ``client_secrets``.
|
|
122
|
+
|
|
123
|
+
Raises AuthError if ``client_secrets`` is missing, unreadable, invalid JSON, or
|
|
124
|
+
not a Desktop app client (top-level key ``installed``). Never returns or logs
|
|
125
|
+
the client ID or client secret values.
|
|
126
|
+
"""
|
|
127
|
+
client = read_client_secrets(client_secrets)
|
|
128
|
+
keys = (SecretKey.OAUTH_CLIENT_ID, SecretKey.OAUTH_CLIENT_SECRET)
|
|
129
|
+
wanted_values = (client.client_id, client.client_secret)
|
|
130
|
+
labels = ("client ID", "client secret")
|
|
131
|
+
problems: list[str] = []
|
|
132
|
+
for key, wanted, what in zip(keys, wanted_values, labels, strict=True):
|
|
133
|
+
stored = store.get(key)
|
|
134
|
+
if not stored:
|
|
135
|
+
problems.append(f"{key.value} is missing from the {store.name} store")
|
|
136
|
+
elif not _constant_time_equal(stored, wanted):
|
|
137
|
+
problems.append(f"stored {key.value} does not match the {what} in the file")
|
|
138
|
+
return ClientVerificationResult(
|
|
139
|
+
backend=store.name,
|
|
140
|
+
matches=not problems,
|
|
141
|
+
problems=problems,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def resolve_client(store: SecretStore, client_secrets: Path | None) -> ClientConfig:
|
|
146
|
+
if client_secrets is not None:
|
|
147
|
+
config = read_client_secrets(client_secrets)
|
|
148
|
+
ensure_writable(store, SecretKey.OAUTH_CLIENT_ID)
|
|
149
|
+
store.set(SecretKey.OAUTH_CLIENT_ID, config.client_id)
|
|
150
|
+
store.set(SecretKey.OAUTH_CLIENT_SECRET, config.client_secret)
|
|
151
|
+
return config
|
|
152
|
+
client_id = store.get(SecretKey.OAUTH_CLIENT_ID)
|
|
153
|
+
client_secret = store.get(SecretKey.OAUTH_CLIENT_SECRET)
|
|
154
|
+
if not client_id or not client_secret:
|
|
155
|
+
raise AuthError(
|
|
156
|
+
f"no Desktop OAuth client in the {store.name} store. {client_setup_hint()} "
|
|
157
|
+
"The JSON is read once and copied into the store; delete the file afterwards."
|
|
158
|
+
)
|
|
159
|
+
return ClientConfig(client_id=client_id, client_secret=client_secret)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass
|
|
163
|
+
class LoginResult:
|
|
164
|
+
"""``granted_scopes`` and ``missing_scopes`` are None when Google did not
|
|
165
|
+
report the grant, so nothing can be claimed about it."""
|
|
166
|
+
|
|
167
|
+
granted_scopes: list[str] | None
|
|
168
|
+
missing_scopes: list[str] | None = None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
FlowFactory = Callable[[dict[str, Any], Sequence[str]], Any]
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _default_flow_factory(client_config: dict[str, Any], scopes: Sequence[str]) -> Any:
|
|
175
|
+
from google_auth_oauthlib.flow import InstalledAppFlow
|
|
176
|
+
|
|
177
|
+
return InstalledAppFlow.from_client_config(
|
|
178
|
+
client_config, scopes=list(scopes), autogenerate_code_verifier=True
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def login(
|
|
183
|
+
store: SecretStore,
|
|
184
|
+
scopes: Sequence[str],
|
|
185
|
+
*,
|
|
186
|
+
client_secrets: Path | None = None,
|
|
187
|
+
open_browser: bool = True,
|
|
188
|
+
port: int = 0,
|
|
189
|
+
login_hint: str | None = None,
|
|
190
|
+
flow_factory: FlowFactory = _default_flow_factory,
|
|
191
|
+
) -> LoginResult:
|
|
192
|
+
"""Run the consent flow and store the resulting refresh token."""
|
|
193
|
+
if not scopes:
|
|
194
|
+
raise AuthError(
|
|
195
|
+
"no scopes to request: enable at least one product with GOOGLEMCP_PRODUCTS or "
|
|
196
|
+
"`products` in the config file. `googlemcp products` lists them."
|
|
197
|
+
)
|
|
198
|
+
ensure_writable(store, SecretKey.REFRESH_TOKEN)
|
|
199
|
+
client = resolve_client(store, client_secrets)
|
|
200
|
+
# Google's granular consent lets the user untick scopes. oauthlib would
|
|
201
|
+
# raise on the narrower grant; accept it and report the gap instead.
|
|
202
|
+
os.environ.setdefault("OAUTHLIB_RELAX_TOKEN_SCOPE", "1")
|
|
203
|
+
flow = flow_factory(client.as_installed(), scopes)
|
|
204
|
+
extra: dict[str, str] = {
|
|
205
|
+
"access_type": "offline",
|
|
206
|
+
"prompt": "consent",
|
|
207
|
+
"include_granted_scopes": "true",
|
|
208
|
+
}
|
|
209
|
+
if login_hint:
|
|
210
|
+
extra["login_hint"] = login_hint
|
|
211
|
+
creds = flow.run_local_server(
|
|
212
|
+
host="127.0.0.1",
|
|
213
|
+
port=port,
|
|
214
|
+
open_browser=open_browser,
|
|
215
|
+
authorization_prompt_message="Open this URL to authorize GoogleMCP:\n{url}\n",
|
|
216
|
+
success_message="GoogleMCP authorization complete. You can close this tab.",
|
|
217
|
+
**extra,
|
|
218
|
+
)
|
|
219
|
+
if not getattr(creds, "refresh_token", None):
|
|
220
|
+
raise AuthError(
|
|
221
|
+
"Google returned no refresh token. Remove GoogleMCP from "
|
|
222
|
+
"https://myaccount.google.com/connections and run login again."
|
|
223
|
+
)
|
|
224
|
+
store.set(SecretKey.REFRESH_TOKEN, creds.refresh_token)
|
|
225
|
+
reported = getattr(creds, "granted_scopes", None)
|
|
226
|
+
if not reported:
|
|
227
|
+
return LoginResult(granted_scopes=None, missing_scopes=None)
|
|
228
|
+
granted = sorted(reported)
|
|
229
|
+
return LoginResult(granted_scopes=granted, missing_scopes=sorted(set(scopes) - set(granted)))
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@dataclass
|
|
233
|
+
class AuthStatus:
|
|
234
|
+
backend: str
|
|
235
|
+
client_configured: bool
|
|
236
|
+
refresh_token_present: bool
|
|
237
|
+
refresh_ok: bool | None = None
|
|
238
|
+
access_token_expiry: str | None = None
|
|
239
|
+
granted_scopes: list[str] = field(default_factory=list)
|
|
240
|
+
# None means unknown: scopes were not checked, or Google tokeninfo failed.
|
|
241
|
+
missing_scopes: list[str] | None = None
|
|
242
|
+
scopes_verified: bool = False
|
|
243
|
+
error: str | None = None
|
|
244
|
+
|
|
245
|
+
def as_dict(self) -> dict[str, Any]:
|
|
246
|
+
return dict(self.__dict__)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def status(
|
|
250
|
+
store: SecretStore,
|
|
251
|
+
required_scopes: Sequence[str],
|
|
252
|
+
*,
|
|
253
|
+
check: bool = True,
|
|
254
|
+
session: Any | None = None,
|
|
255
|
+
provider: CredentialProvider | None = None,
|
|
256
|
+
) -> AuthStatus:
|
|
257
|
+
"""Report credential health without printing any secret."""
|
|
258
|
+
try:
|
|
259
|
+
client_ok = bool(store.get(SecretKey.OAUTH_CLIENT_ID)) and bool(
|
|
260
|
+
store.get(SecretKey.OAUTH_CLIENT_SECRET)
|
|
261
|
+
)
|
|
262
|
+
token_ok = bool(store.get(SecretKey.REFRESH_TOKEN))
|
|
263
|
+
except SecretStoreError as exc:
|
|
264
|
+
return AuthStatus(store.name, False, False, error=str(exc))
|
|
265
|
+
result = AuthStatus(store.name, client_ok, token_ok)
|
|
266
|
+
if not (check and client_ok and token_ok):
|
|
267
|
+
return result
|
|
268
|
+
try:
|
|
269
|
+
creds = (provider or CredentialProvider(store)).force_refresh()
|
|
270
|
+
except AuthError as exc:
|
|
271
|
+
result.refresh_ok = False
|
|
272
|
+
result.error = str(exc)
|
|
273
|
+
return result
|
|
274
|
+
result.refresh_ok = True
|
|
275
|
+
result.access_token_expiry = creds.expiry.isoformat() + "Z" if creds.expiry else None
|
|
276
|
+
http = session or requests.Session()
|
|
277
|
+
try:
|
|
278
|
+
# POST keeps the access token out of URLs and proxy logs.
|
|
279
|
+
resp = http.post(TOKENINFO_URI, data={"access_token": creds.token}, timeout=HTTP_TIMEOUT)
|
|
280
|
+
info = resp.json() if resp.status_code == 200 else {}
|
|
281
|
+
except (requests.RequestException, ValueError):
|
|
282
|
+
info = {}
|
|
283
|
+
granted = sorted(str(info.get("scope", "")).split())
|
|
284
|
+
if not granted:
|
|
285
|
+
result.error = (
|
|
286
|
+
"token refresh worked, but granted scopes could not be verified "
|
|
287
|
+
"(Google tokeninfo unavailable); retry `googlemcp auth status`"
|
|
288
|
+
)
|
|
289
|
+
return result
|
|
290
|
+
result.granted_scopes = granted
|
|
291
|
+
result.missing_scopes = sorted(set(required_scopes) - set(granted))
|
|
292
|
+
result.scopes_verified = True
|
|
293
|
+
return result
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def revoke(store: SecretStore, *, session: Any | None = None) -> bool:
|
|
297
|
+
"""Revoke the refresh token at Google, then delete it locally.
|
|
298
|
+
|
|
299
|
+
Returns True when Google confirmed revocation. A token Google already
|
|
300
|
+
considers invalid is still removed locally.
|
|
301
|
+
"""
|
|
302
|
+
ensure_writable(store, SecretKey.REFRESH_TOKEN)
|
|
303
|
+
token = store.get(SecretKey.REFRESH_TOKEN)
|
|
304
|
+
if not token:
|
|
305
|
+
return False
|
|
306
|
+
http = session or requests.Session()
|
|
307
|
+
try:
|
|
308
|
+
resp = http.post(
|
|
309
|
+
REVOKE_URI,
|
|
310
|
+
data={"token": token},
|
|
311
|
+
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
|
312
|
+
timeout=HTTP_TIMEOUT,
|
|
313
|
+
)
|
|
314
|
+
except requests.RequestException:
|
|
315
|
+
raise AuthError(
|
|
316
|
+
"could not reach Google to revoke the token; nothing was deleted. Retry, or revoke "
|
|
317
|
+
"at https://myaccount.google.com/connections"
|
|
318
|
+
) from None
|
|
319
|
+
confirmed = resp.status_code == 200
|
|
320
|
+
if not confirmed and resp.status_code != 400:
|
|
321
|
+
raise AuthError(f"Google revoke endpoint returned HTTP {resp.status_code}; token kept")
|
|
322
|
+
store.delete(SecretKey.REFRESH_TOKEN)
|
|
323
|
+
return confirmed
|
googlemcp/catalog.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Loader for catalog/services.json, the shared product catalog.
|
|
2
|
+
|
|
3
|
+
Terraform and the MCP adapters both read this file so API enablement and
|
|
4
|
+
tool registration cannot drift apart silently.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from functools import lru_cache
|
|
12
|
+
from importlib import resources
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
_REPO_CATALOG = Path(__file__).resolve().parents[2] / "catalog" / "services.json"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Product:
|
|
21
|
+
key: str
|
|
22
|
+
title: str
|
|
23
|
+
api_services: tuple[str, ...]
|
|
24
|
+
default_enabled: bool
|
|
25
|
+
risk: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _read_raw() -> dict[str, Any]:
|
|
29
|
+
if _REPO_CATALOG.is_file():
|
|
30
|
+
data: dict[str, Any] = json.loads(_REPO_CATALOG.read_text(encoding="utf-8"))
|
|
31
|
+
return data
|
|
32
|
+
packaged = resources.files("googlemcp").joinpath("services.json")
|
|
33
|
+
data = json.loads(packaged.read_text(encoding="utf-8"))
|
|
34
|
+
return data
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@lru_cache(maxsize=1)
|
|
38
|
+
def load_catalog() -> dict[str, Product]:
|
|
39
|
+
raw = _read_raw()
|
|
40
|
+
return {
|
|
41
|
+
key: Product(
|
|
42
|
+
key=key,
|
|
43
|
+
title=entry["title"],
|
|
44
|
+
api_services=tuple(entry["api_services"]),
|
|
45
|
+
default_enabled=bool(entry["default_enabled"]),
|
|
46
|
+
risk=str(entry["risk"]),
|
|
47
|
+
)
|
|
48
|
+
for key, entry in raw["products"].items()
|
|
49
|
+
}
|