Skip to main content
Glama
johnoconnor0

Google Ads MCP Server

by johnoconnor0

google_ads_initialize

Set up the Google Ads API connection with OAuth credentials and developer token. Required before using any other Google Ads tools.

Instructions

Initialize the Google Ads API connection with OAuth credentials.

This must be called before using any other Google Ads tools. Provide your developer token, OAuth2 credentials, and optionally an MCC login customer ID if you're accessing client accounts.

Args: developer_token: API developer token client_id: OAuth2 client ID client_secret: OAuth2 client secret refresh_token: OAuth2 refresh token login_customer_id: Optional MCC account ID (without hyphens)

Returns: Confirmation message with initialization status

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
developer_tokenYes
client_idYes
client_secretYes
refresh_tokenYes
login_customer_idNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler for the google_ads_initialize tool. It receives OAuth credentials (developer_token, client_id, client_secret, refresh_token, optional login_customer_id), cleans the login customer ID, delegates to auth.initialize_oauth(), and returns a confirmation or error message.
    @mcp.tool()
    def google_ads_initialize(
        developer_token: str,
        client_id: str,
        client_secret: str,
        refresh_token: str,
        login_customer_id: Optional[str] = None,
    ) -> str:
        """
        Initialize the Google Ads API connection with OAuth credentials.
    
        This must be called before using any other Google Ads tools. Provide your
        developer token, OAuth2 credentials, and optionally an MCC login customer ID
        if you're accessing client accounts.
    
        Args:
            developer_token: API developer token
            client_id: OAuth2 client ID
            client_secret: OAuth2 client secret
            refresh_token: OAuth2 refresh token
            login_customer_id: Optional MCC account ID (without hyphens)
    
        Returns:
            Confirmation message with initialization status
        """
        try:
            clean_login_id = login_customer_id.replace("-", "") if login_customer_id else None
    
            auth = get_auth_manager()
            auth.initialize_oauth(
                developer_token=developer_token,
                client_id=client_id,
                client_secret=client_secret,
                refresh_token=refresh_token,
                login_customer_id=clean_login_id,
            )
    
            msg = "✓ Google Ads API client initialized successfully.\n"
            if clean_login_id:
                msg += f"✓ Using MCC account: {clean_login_id}\n"
            msg += "\nYou can now use other Google Ads tools to access your account data."
            return msg
    
        except Exception as exc:
            return f"❌ Initialization failed: {exc}"
  • The tool is registered using the @mcp.tool() decorator on the google_ads_initialize function, which makes it available via the FastMCP server.
    @mcp.tool()
  • The auto-initialization helper that attempts to load credentials from environment variables (GOOGLE_ADS_DEVELOPER_TOKEN, etc.). If env credentials are incomplete or auto-init fails, it logs a message indicating that manual google_ads_initialize is required.
    def _auto_initialize_from_env():
        """Try to initialise the Google Ads client from .env credentials."""
        dev_token = os.getenv("GOOGLE_ADS_DEVELOPER_TOKEN")
        cid = os.getenv("GOOGLE_ADS_CLIENT_ID")
        csecret = os.getenv("GOOGLE_ADS_CLIENT_SECRET")
        rtoken = os.getenv("GOOGLE_ADS_REFRESH_TOKEN")
        login_id = os.getenv("GOOGLE_ADS_LOGIN_CUSTOMER_ID")
    
        if not all([dev_token, cid, csecret, rtoken]):
            logger.info("Env credentials incomplete – manual google_ads_initialize required")
            return False
    
        try:
            clean_login_id = login_id.replace("-", "") if login_id else None
            auth = get_auth_manager()
            auth.initialize_oauth(
                developer_token=dev_token,
                client_id=cid,
                client_secret=csecret,
                refresh_token=rtoken,
                login_customer_id=clean_login_id,
            )
            logger.info(f"✓ Auto-initialised from .env (MCC: {clean_login_id or 'none'})")
            return True
        except Exception as exc:
            logger.warning(f"Auto-init failed: {exc} – manual google_ads_initialize required")
            return False
  • The initialize_oauth method on GoogleAdsAuthManager, called by the tool handler. It creates a TokenManager, validates the refresh token, builds credentials, creates the GoogleAdsClient, and stores the client session.
    def initialize_oauth(
        self,
        developer_token: str,
        client_id: str,
        client_secret: str,
        refresh_token: str,
        login_customer_id: Optional[str] = None,
        client_key: str = "default"
    ) -> str:
        """
        Initialize Google Ads client with OAuth2.
    
        Args:
            developer_token: Google Ads developer token
            client_id: OAuth2 client ID
            client_secret: OAuth2 client secret
            refresh_token: OAuth2 refresh token
            login_customer_id: Optional MCC account ID
            client_key: Unique identifier for this client session
    
        Returns:
            Client key for this session
    
        Raises:
            AuthenticationError: If initialization fails
        """
        try:
            # Create token manager
            token_manager = TokenManager(
                client_id=client_id,
                client_secret=client_secret,
                refresh_token=refresh_token
            )
    
            # Validate token
            if not token_manager.validate_token():
                raise AuthenticationError("Invalid refresh token")
    
            # Build credentials dict
            credentials = {
                "developer_token": developer_token,
                "client_id": client_id,
                "client_secret": client_secret,
                "refresh_token": refresh_token,
                "use_proto_plus": True
            }
    
            if login_customer_id:
                credentials["login_customer_id"] = login_customer_id
    
            # Create client
            client = GoogleAdsClient.load_from_dict(credentials)
    
            # Store client and token manager
            self._clients[client_key] = client
            self._token_managers[client_key] = token_manager
            self._current_client_key = client_key
    
            logger.info(f"Google Ads client initialized: {client_key}")
    
            return client_key
    
        except Exception as e:
            logger.error(f"Failed to initialize OAuth client: {e}")
            raise AuthenticationError(f"OAuth initialization failed: {e}")
  • The function signature defines the input schema: developer_token (str), client_id (str), client_secret (str), refresh_token (str), and optional login_customer_id (Optional[str]). The return type is str.
    def google_ads_initialize(
        developer_token: str,
        client_id: str,
        client_secret: str,
        refresh_token: str,
        login_customer_id: Optional[str] = None,
    ) -> str:
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Discloses initialization with credentials and optional MCC ID. Could mention idempotency or error handling, but sufficient for a setup tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Concise, well-structured with purpose, prerequisite, args, and returns. No wasted sentences.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Complete for a simple initialization tool with output schema confirming status.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Adds meaning to all 5 parameters beyond schema names, explaining each credential and the optional MCC ID.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Clearly states the tool initializes the API connection and must be called before other tools. Distinguishes from siblings as a setup tool.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly states it must be called before other tools and provides context for optional MCC login customer ID.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/johnoconnor0/google-ads-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server