Skip to content

Chanlinnn/google-ads-agent-skills / skills/setup-google-ads

setup-google-ads

Verified

配置和排查 Google Ads API 到 AI Agent 的本地只读 MCP 接入。用于新电脑部署、Google Cloud 与 Ads 权限区分、服务账号或 ADC 配置、Codex MCP 注册、可访问账户验证,以及认证、网络、版本和权限错误排查。Set up or troubleshoot a local read-only Google Ads MCP connection. 不负责广告表现分析或广告修改。

scripts/manage.py

View on GitHub
#!/usr/bin/env python3
"""Local configuration and STDIO launcher. Never prints credential contents."""

from __future__ import annotations

import argparse
from importlib.metadata import PackageNotFoundError, version
import json
import os
from pathlib import Path
import re
import sys
import tempfile
from urllib.parse import urlsplit

SKILL = Path(__file__).resolve().parents[1]
DEFAULT_CONFIG = Path.home() / '.config' / 'google-ads-agent' / 'local.json'
TOOLS_CONFIG = SKILL / 'assets' / 'tools-readonly.json'
EXPECTED_NAMESPACES = {
    category: {'enabled': True, 'prefix': category, 'enabled_tools': [tool]}
    for category, tool in [('customers', 'list_accessible_customers'),
                           ('metadata', 'get_resource_metadata'), ('search', 'search')]
}
EXPECTED_NAMESPACES.update({'assets': False, 'labels': False})
PROXY_NAMES = ('http_proxy', 'https_proxy', 'all_proxy', 'grpc_proxy')


def private_location(path: Path) -> Path:
    """Reject locations in this skill or a Git checkout, including symlinks."""
    path = path.expanduser().resolve()
    if path == SKILL or SKILL in path.parents:
        raise ValueError('Keep credentials and local configuration outside the skill.')
    if any((parent / '.git').exists() or (parent / 'SKILL.md').is_file()
           or (parent / 'skills' / 'setup-google-ads' / 'SKILL.md').is_file()
           for parent in path.parents):
        raise ValueError('Keep credentials and local configuration outside repositories and skills.')
    return path


def read_private_json(path: Path) -> dict:
    path = private_location(path)
    try:
        if os.name == 'posix' and path.stat().st_mode & 0o077:
            raise ValueError('Private file permissions are too broad; restrict to 0600.')
        value = json.loads(path.read_text(encoding='utf-8'))
    except (OSError, json.JSONDecodeError) as from_error:
        raise ValueError('Cannot read a required private JSON file.') from from_error
    if not isinstance(value, dict):
        raise ValueError('Private JSON must contain an object.')
    return value


def normalize_customer_id(value: str) -> str:
    cleaned = re.sub(r'[\s-]', '', value)
    if cleaned and not re.fullmatch(r'[0-9]{10}', cleaned):
        raise ValueError('Manager customer ID must be blank or contain 10 digits.')
    return cleaned


def validate_proxy(value: str) -> str:
    if not value:
        return ''
    try:
        parsed = urlsplit(value)
        valid = (parsed.scheme == 'http' and parsed.hostname and parsed.port
                 and not parsed.username and not parsed.password
                 and parsed.path in ('', '/') and not parsed.query and not parsed.fragment)
    except ValueError:
        valid = False
    if not valid:
        raise ValueError('Use an HTTP proxy URL with a port and without credentials.')
    return value.rstrip('/')


def validate_config(config: dict) -> dict[str, str]:
    allowed = {'project_id', 'credentials_path', 'login_customer_id', 'proxy_url'}
    if not isinstance(config, dict) or set(config) - allowed:
        raise ValueError('Unexpected local configuration fields.')
    if any(not isinstance(value, str) for value in config.values()):
        raise ValueError('Configuration values must be strings.')
    project = config.get('project_id', '').strip()
    if not re.fullmatch(r'[a-z][a-z0-9-]{4,28}[a-z0-9]', project):
        raise ValueError('Provide a valid Google Cloud project ID.')
    raw_path = config.get('credentials_path', '')
    if not raw_path or not Path(raw_path).expanduser().is_absolute():
        raise ValueError('Provide an absolute path to the private ADC JSON file.')
    credentials_path = private_location(Path(raw_path))
    credentials = read_private_json(credentials_path)
    if credentials.get('type') not in ('service_account', 'authorized_user'):
        raise ValueError('This launcher supports service_account or authorized_user ADC.')
    if credentials.get('type') == 'service_account' and credentials.get('project_id') != project:
        raise ValueError('The configured project must own the service account.')
    return {
        'project_id': project,
        'credentials_path': str(credentials_path),
        'login_customer_id': normalize_customer_id(config.get('login_customer_id', '')),
        'proxy_url': validate_proxy(config.get('proxy_url', '').strip()),
    }


def write_private_config(path: Path, config: dict) -> None:
    path = private_location(path)
    if path.exists():
        raise ValueError('Configuration already exists; review and edit it locally.')
    path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    descriptor, name = tempfile.mkstemp(prefix='.ads-config-', dir=path.parent)
    try:
        os.fchmod(descriptor, 0o600)
        with os.fdopen(descriptor, 'w', encoding='utf-8') as handle:
            json.dump(config, handle, indent=2)
            handle.write('\n')
        # Linking fails if another process created the destination meanwhile.
        os.link(name, path)
    finally:
        Path(name).unlink(missing_ok=True)


def verify_tools_config() -> None:
    try:
        value = json.loads(TOOLS_CONFIG.read_text(encoding='utf-8'))
    except (OSError, json.JSONDecodeError) as exc:
        raise ValueError('Read-only tool configuration is missing or invalid.') from exc
    if value != {'namespaces': EXPECTED_NAMESPACES}:
        raise ValueError('Read-only tool configuration differs from the supported allowlist.')


def build_environment(config: dict[str, str], parent: dict[str, str]) -> dict[str, str]:
    environment = {key: value for key, value in parent.items()
                   if not key.startswith('GOOGLE_ADS_')}
    for key in PROXY_NAMES:
        environment.pop(key, None)
        environment.pop(key.upper(), None)
    environment.update({
        'GOOGLE_APPLICATION_CREDENTIALS': config['credentials_path'],
        'GOOGLE_CLOUD_PROJECT': config['project_id'],
        'GOOGLE_PROJECT_ID': config['project_id'],
        'GOOGLE_ADS_MCP_TOOLS_CONFIG': str(TOOLS_CONFIG),
    })
    if config['login_customer_id']:
        environment['GOOGLE_ADS_LOGIN_CUSTOMER_ID'] = config['login_customer_id']
    if config['proxy_url']:
        for key in ('http_proxy', 'https_proxy', 'grpc_proxy'):
            environment[key] = config['proxy_url']
            environment[key.upper()] = config['proxy_url']
    return environment


def verify_runtime() -> Path:
    expected = {'google-ads-mcp': '0.0.6', 'google-ads': '35.1.0',
                'fastmcp': '4.2.0', 'mcp': '2.3.0'}
    for package, required in expected.items():
        try:
            installed = version(package)
        except PackageNotFoundError as exc:
            raise ValueError('Install the bundled requirements in a dedicated virtual environment.') from exc
        if installed != required:
            raise ValueError('Runtime version mismatch; use the bundled requirements.')
    executable = Path(sys.executable).parent / 'google-ads-mcp'
    if not executable.is_file() or not os.access(executable, os.X_OK):
        raise ValueError('MCP executable is missing in the current Python environment.')
    return executable


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('action', choices=['configure', 'check', 'launch'])
    parser.add_argument('--config', type=Path, default=DEFAULT_CONFIG)
    args = parser.parse_args()
    try:
        if args.action == 'configure':
            config = validate_config({
                'project_id': input('Google Cloud project ID: ').strip(),
                'credentials_path': input('Private ADC JSON absolute path (not its contents): ').strip(),
                'login_customer_id': input('Manager customer ID (blank for direct access): ').strip(),
                'proxy_url': input('HTTP proxy URL (blank for direct network): ').strip(),
            })
            write_private_config(args.config, config)
            print('Local configuration saved with restricted permissions. No live call was made.')
            return 0
        config = validate_config(read_private_json(args.config))
        verify_tools_config()
        executable = verify_runtime()
        environment = build_environment(config, dict(os.environ))
        if args.action == 'check':
            print('Offline configuration checks passed. Authentication and account access are not tested.')
            return 0
        os.execve(executable, [str(executable)], environment)
    except (ValueError, OSError, EOFError):
        # Error details can contain user paths; expose only known, controlled errors.
        error = sys.exc_info()[1]
        message = str(error) if isinstance(error, ValueError) else 'Local setup could not complete.'
        print(message, file=sys.stderr)
        return 1
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall