Workspace diagnostic API
Generate an expiring read-only key for selected connections and sources.
# Workspace diagnostic API
Open MCP → Workspace API keys in the dashboard. A workspace owner or admin can generate their own key, select up to 100 connections for metadata diagnostics and up to 100 usable sources for statistics, set expiry (1, 7 or 30 days) and optionally allow read-only assistant tests. Copy the secret once. Revoke the key when finished; rotation and scope changes require a new key. Impersonated sessions cannot issue keys. Select at least one connection or source. A connection-only key works with zero discovered or usable sources and grants no tool access. No selection ever means access to all connections or sources.
Keys permit reads only. They cannot change campaigns, preview or apply changes, read private chat history, link accounts, start discovery jobs or run BigQuery queries. Connection metadata follows dashboard visibility; owners and admins may inspect private metadata. Private credentials remain usable only by their linker. Existing plan, seat, source and own-use restrictions still apply.
Use the Authorization: Bearer header. Cookies, URL keys and actor/workspace/grant IDs are refused. Keep the key out of URLs, browser storage and analytics. The public specification is OpenAPI.
Delivery and acceptance
Customer access requires Google verification. Our team uses this API in the sandbox. Metadata visibility, a registered tool or a paid plan does not open an own-use platform gate.
Confirm the deployed sandbox revision with the test coordinator. Open /api/v1/openapi.json on that sandbox’s origin. Delivery or metadata HTTP200 does not prove a fresh provider read. Saved Google discovery is not current Google access-tier proof; use an explicitly authorized selected resource and its returned registered schema for a bounded read. Future production testing needs its own setup, target/key and explicit session authorization.
Endpoints
GET /api/v1/whoami: scope, workspace plan, expiry and permissions.GET /api/v1/connections: selected connection health, saved discovery outcomes and selected source snapshots. One combined page contains at most 25 entries, connections first, then sources. Followdata.cursoruntildata.completeis true. This performs no discovery or provider call.GET /api/v1/tools?server=ga4: registered read tools and strict argument and output schemas. Available servers:ga4,gtm,google-ads,meta-ads,openai-ads,tiktok-ads, subject to the workspace's current access and own-use gates.POST /api/v1/tools/call: exact registered statistics through the normal tool pipeline. Dates, currency, micros, timezone, nulls, pagination and attribution follow that tool's schema and answer. Follow its continuation fields.GET /api/v1/assistant: assistant permission, rollout and seat status.POST /api/v1/assistant/test: optional stateless read-only assistant test. The assistant retains its GA4, GTM and OpenAI Ads policy and only sees selected sources.
Saved connection diagnostics
data.connections[].savedDiscovery is null if no saved result exists. Otherwise it contains saved timestamps and each product's complete, incomplete or error outcome, count when known, closed error code and optional finite diagnostic.kind, diagnostic.stage and diagnostic.httpStatus. A complete count of zero means that run found no accounts; an error never establishes a count of zero. The saved outcome does not identify a current live cause.
Each connection's sourceSnapshot counts up to 100 stored rows and how many are enabled. When its complete is false these are lower bounds, not totals or usable source counts. Tool use, available servers and new source selection require active credential and connection health. A selected source may be disabled or unusable while its saved metadata remains available: nonactive status (needs_reauth, suspended or revoked) does not grant tool access. With active health but a scope/custody refusal, status is unavailable. Inspect toolUsable, savedDiscoveryAt and stale. Stale means the row predates the last saved connection discovery run, not a live freshness check. Removed or rebound pins are projected as unavailable. If visibility or identity changes after detailed metadata was prepared, the final fence withholds that page. Issue a newly scoped key after checking access.
Safe sandbox client
Generate a short-lived key for the smallest selected scope. Save it in a private file outside the repository, owned by your Unix user with mode 600. Run this client under that same UID. A different user cannot read the file just by knowing its path; give an authorized reviewer only sanitized evidence from your agreed check, not the key or its file. Keep the permission checks intact. Read that file into memory; do not export the bearer to a shell variable or pass it as a process argument. Do not use curl verbose/trace output, shell tracing or HTTP debug logging. Deployment smoke secrets are not diagnostic keys.
This Python 3 example requires macOS or Linux (including WSL) and makes one sandbox identity request. On Windows, run it inside WSL with the private key file in the Linux home directory, not a mounted Windows drive. Do not remove the ownership/permission checks to run it under native Windows Python. It never prints the bearer or response payload and refuses redirects. It is a client example, not proof of authenticated acceptance. It sends an explicit diagnostic User-Agent; a default Python client can be refused by the edge before API authorization.
import json, os, re, stat
from http.client import HTTPException
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, build_opener, HTTPRedirectHandler, ProxyHandler
# Enter only the owner-supplied private file path, never the bearer.
key_path = Path(input("Private key file path: ").strip()).expanduser()
try:
fd = os.open(key_path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(fd, encoding="utf-8") as file:
info = os.fstat(file.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
raise SystemExit("Use a private file owned by your user (chmod 600).")
key = file.read(512).strip()
except (OSError, UnicodeError):
raise SystemExit("Cannot read diagnostic key file.") from None
if not re.fullmatch(r"adt_diag_[0-9a-f]{32}\.[0-9a-f]{64}", key):
raise SystemExit("Invalid diagnostic key file.")
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
# No redirects or environment proxy settings carrying the Authorization header.
opener = build_opener(ProxyHandler({}), NoRedirect())
base = "https://sandbox.adtool.ai"
def request(path, body=None):
data = None if body is None else json.dumps(body).encode("utf-8")
if data is not None and len(data) > 20 * 1024:
raise SystemExit("Request exceeds 20 KiB.")
req = Request(base + path, data=data, headers={
"Authorization": "Bearer " + key, "Content-Type": "application/json",
"User-Agent": "adtool-diagnostic/1.0"
})
try:
response = opener.open(req, timeout=180)
except HTTPError as error:
response = error
except (URLError, OSError, HTTPException):
raise SystemExit("Transport failed; no response cause established.")
with response:
try:
raw = response.read(1024 * 1024 + 1)
except (OSError, HTTPException):
raise SystemExit("Transport failed; no response cause established.")
if len(raw) > 1024 * 1024:
raise SystemExit("Response exceeds 1 MiB.")
try:
result = json.loads(raw)
except (ValueError, UnicodeError):
raise SystemExit("Expected a JSON API response.")
if not isinstance(result, dict):
raise SystemExit("Expected a JSON object.")
# Keep payloads in memory; do not print headers, key, arguments or result rows.
print({"http": response.code, "requestId": result.get("requestId")})
return response.code, result
status, identity = request("/api/v1/whoami")
# Inspect identity["data"] privately; proceed only when status == 200 and scope matches.After confirming identity and scope, use the same request function sequentially:
- Read
/api/v1/connections. Follow the returneddata.cursoras?cursor=<value>untildata.completeis true; keep each page in memory. Check both connection and source lists, saved discovery status, lower-bound counts andtoolUsable. - Read
/api/v1/tools?server=ga4for a selected usable server. Choose only a read returned by this response and follow its exact argument schema. For example,request("/api/v1/tools/call", {"server": "ga4", "name": "ga4_list_accounts", "args": {}})works only with current permitted GA4 scope. This checks saved authorized grant metadata: it makes no Google request and does not consume metered tool usage. Diagnostic request limits still apply. For genuine provider-read acceptance, select a currently usable authorized resource and a returned registered provider-read tool. Follow its exact argument schema, use a small result limit where supported, follow its separate continuation fields and stop within your agreed test budget. - Read
/api/v1/assistant. Only if key permission, workspace policy, seat, server scope and runtime allow it, and you accept message/tool charges and model data transfer, make one optional call:request("/api/v1/assistant/test", {"message": "Read my selected sources only. Do not change anything."}). HTTP200 can contain a refused or unavailable assistant status; inspect the data status and settlement before calling it successful.
Stop on a refusal; retain only request ID and finite diagnostic fields for support. Do not make broad sweeps, probe limits at volume or retry an unavailable call in a loop. Revoke the key when finished. Use a production target only after its setup and separate owner authorization, with its own read-only key; never reuse a sandbox key or infer production permission from these examples.
Limits, privacy and charges
Before authorization or request-body processing, the edge admits up to 120 requests per minute per trusted client IP. Rotating keys does not bypass this limit. HTTP429 with stage=ingress and Retry-After: 60 means admission was denied; HTTP503 with that stage means admission is unavailable. These responses make no signed authorization call or body read. This protective edge limit supplements the authenticated budgets below.
Requests are limited to 60 per key, 120 per creator and 240 per workspace per minute. Assistant tests are limited to 3 per key, 6 per creator and 10 per workspace per minute. Existing workspace tool, message and provider quotas also apply. JSON request bodies are bounded to 20 KiB of UTF-8; serialized tool arguments have a separate maximum of 16,384 UTF-16 code units. Responses are bounded to 1 MiB. Assistant tests return a bounded JSON answer. Model work aborts after 120 seconds; settlement follows.
Tool calls consume normal workspace usage. Assistant tests additionally consume assistant message usage and send selected source context and requested tool data to the model provider, as disclosed for the web assistant. They create no chat history. Audit records keep IDs, operation and outcome, without the key secret, prompt, full arguments or results.
Every response is no-store and includes version and requestId. Errors have a closed code, stage and operation; retryable refusals include retryAfterSeconds. Direct tool failures may also include error.diagnostic: failure_stage is local_validation or upstream_response, operation is an allowlisted OpenAI provider method or unknown, and http_status is an integer 400..499 when present. This provider operation is separate from the REST error.operation (call). REST uses HTTP422 for a tool failure. An optional rejected_parameter names only an allowlisted public request field; never infer it from provider prose. Saved Google Ads discovery snapshots may have an optional finite adsReason; absence or a generic access refusal does not prove the Cloud project access tier. These fields are source-built in merged PR #274; #276 preserves the legacy connections projection during rolling updates through signed server-owned negotiation. Clients must not add an internal capability parameter to public requests. Both changes are delivered in sandbox; consult the deployed OpenAPI for the target revision and use only its returned registered tool schema. Delivery does not establish provider access or resolve a reported provider error. For example, a fixture rejection at the account read returns:
{"error":{"code":"invalid_request","stage":"tool","operation":"call","diagnostic":{"failure_stage":"upstream_response","operation":"adaccount.get","http_status":400}}}Report the response's request ID and these finite fields when diagnosing a failure. This example is not evidence about a real account's cause. No raw provider error body or credential is returned. Revocation, expiry, removal, disabled sources and credential/scope drift refuse further authorization. A completed provider read cannot be undone; disclosure is checked again before the response is returned.
A selected connection or source that is no longer visible returns only its ID and unavailable status. Detailed metadata is freshly checked before disclosure. Direct tool results are fenced against the source actually admitted for the call; an unrelated unusable selection does not hide that result.
The stateless diagnostic assistant uses English and UTC for the existing loop locale/time-zone context; relative tool date presets retain their registered semantics.