Google Ads MCP Server
A Model Context Protocol (MCP) server for Google Ads integration with OAuth 2.0 authentication.
Features
- OAuth 2.0 Authentication: Secure Google OAuth flow with automatic token refresh
- MCP Protocol Support: Full implementation of the Model Context Protocol
- Google Ads Operations:
- List campaigns with filtering
- Get campaign performance metrics
- Get account summary and statistics
- Session Management: Persistent sessions with automatic token refresh
- TypeScript: Fully typed with TypeScript for better development experience
- Google Ads API v18: Latest version of the Google Ads API
Prerequisites
- Node.js 18+
- Google Cloud Project with Google Ads API enabled
- OAuth 2.0 credentials (Client ID and Client Secret)
- Google Ads Developer Token
Setup
1. Google Cloud & Google Ads Configuration
Google Cloud Console Setup
- Go to Google Cloud Console
- Create a new project or select an existing one
- Enable the Google Ads API
- Create OAuth 2.0 credentials:
- Application type: Web application
- Authorized redirect URIs:http://localhost:3003/oauth/callback - Copy your Client ID and Client Secret
Google Ads API Setup
- Go to Google Ads API Center
- Apply for a Developer Token (required for API access)
- Wait for approval (can take 24-48 hours)
- Once approved, copy your Developer Token
2. Installation```bash
Clone or navigate to the project directory
cd google-ads-mcp-server
Install dependencies
npm install
### 3. Configuration
Create a `.env` file in the root directory:```bash
cp env.example .env
Edit .env with your configuration:```env
Server Configuration
PORT=3003
NODE_ENV=development
Google OAuth Configuration
GOOGLE_CLIENT_ID=your_google_client_id_here
GOOGLE_CLIENT_SECRET=your_google_client_secret_here
GOOGLE_REDIRECT_URI=http://localhost:3003/oauth/callback
Google Ads API Configuration
GOOGLE_ADS_DEVELOPER_TOKEN=your_developer_token_here
Frontend URL (where to redirect after OAuth)
FRONTEND_URL=http://localhost:5173
MCP Server Configuration
MCP_SERVER_NAME=google-ads-mcp-server
MCP_SERVER_VERSION=1.0.0
## Usage
### Development Mode```bash
npm run dev
Production Mode```bash
Build
npm run build
Start
npm start
## API Endpoints
### Health Check```
GET /health
OAuth Flow
1. Initiate Authorization```
GET /oauth/authorize?userId={userId}&state={state}
Response:```json
{
"authorizationUrl": "https://accounts.google.com/o/oauth2/v2/auth?...",
"state": "your-state-value"
}
2. OAuth Callback (handled automatically)```
GET /oauth/callback?code={code}&state={state}
#### 3. Refresh Token```
POST /oauth/refresh
Content-Type: application/json
{
"userId": "user123",
"refreshToken": "refresh_token_here"
}
4. Disconnect```
POST /oauth/disconnect
Content-Type: application/json
{
"userId": "user123"
}
### MCP Endpoint```
POST /mcp
GET /mcp
DELETE /mcp
The MCP endpoint follows the Model Context Protocol specification for tool execution.
MCP Tools
1. google_ads_list_campaigns
List Google Ads campaigns with optional filtering.
Input:```json
{
"userId": "user123",
"customerId": "1234567890",
"status": "ALL",
"limit": 50
}
**Parameters:**
- `userId` (string, required): User ID for authentication
- `customerId` (string, required): Google Ads customer ID without hyphens
- `status` (enum, optional): Filter by campaign status - 'ALL', 'ENABLED', or 'PAUSED' (default: 'ALL')
- `limit` (number, optional): Maximum campaigns to return, 1-10000 (default: 50)
**Output:**```json
{
"campaigns": [
{
"id": "123456789",
"name": "Summer Campaign",
"status": "ENABLED",
"advertisingChannelType": "SEARCH",
"startDate": "2024-01-01",
"endDate": "2024-12-31",
"budgetAmountMicros": "10000000"
}
],
"count": 1,
"customerId": "1234567890"
}
2. google_ads_campaign_metrics
Get performance metrics for Google Ads campaigns.
Input:```json
{
"userId": "user123",
"customerId": "1234567890",
"campaignIds": ["123456789", "987654321"],
"startDate": "2024-01-01",
"endDate": "2024-01-31",
"metrics": ["impressions", "clicks", "conversions", "cost_micros"]
}
**Parameters:**
- `userId` (string, required): User ID for authentication
- `customerId` (string, required): Google Ads customer ID without hyphens
- `campaignIds` (array, optional): List of campaign IDs to get metrics for (empty for all campaigns)
- `startDate` (string, optional): Start date in YYYY-MM-DD format (default: 30 days ago)
- `endDate` (string, optional): End date in YYYY-MM-DD format (default: today)
- `metrics` (array, optional): Metrics to retrieve (default: impressions, clicks, conversions, cost_micros)
**Available Metrics:**
- `impressions` - Number of times ads were shown
- `clicks` - Number of clicks on ads
- `conversions` - Number of conversions
- `cost_micros` - Cost in micros (divide by 1,000,000 for actual cost)
- `average_cpc` - Average cost per click
- `ctr` - Click-through rate
**Output:**```json
{
"campaignMetrics": [
{
"campaignId": "123456789",
"campaignName": "Summer Campaign",
"impressions": 10000,
"clicks": 500,
"conversions": 50,
"cost_micros": 5000000
}
],
"customerId": "1234567890",
"dateRange": {
"startDate": "20240101",
"endDate": "20240131"
}
}
3. google_ads_account_summary
Get overall account summary and performance metrics.
Input:```json
{
"userId": "user123",
"customerId": "1234567890",
"startDate": "2024-01-01",
"endDate": "2024-01-31"
}
**Parameters:**
- `userId` (string, required): User ID for authentication
- `customerId` (string, required): Google Ads customer ID without hyphens
- `startDate` (string, optional): Start date in YYYY-MM-DD format (default: 30 days ago)
- `endDate` (string, optional): End date in YYYY-MM-DD format (default: today)
**Output:**```json
{
"summary": {
"customerId": "1234567890",
"accountName": "My Business Account",
"totalCampaigns": 10,
"activeCampaigns": 7,
"pausedCampaigns": 3,
"metrics": {
"impressions": 50000,
"clicks": 2500,
"conversions": 250,
"costMicros": 25000000,
"averageCpc": 10000,
"ctr": 0.05
},
"dateRange": {
"startDate": "20240101",
"endDate": "20240131"
}
}
}
Integration with ZeroTwoApi
To integrate this Google Ads MCP server with your ZeroTwoApi backend:
1. Update Frontend OAuth Configuration
In ZeroTwo/src/services/oauthProviders.js, add the Google Ads configuration:```javascript
google_ads: {
provider: "google_ads",
clientId: import.meta.env.VITE_GOOGLE_CLIENT_ID,
flowType: OAuthFlowType.REDIRECT,
scopes: [
"https://www.googleapis.com/auth/adwords",
],
authEndpoint: "http://localhost:3003/oauth/authorize",
backendExchangeEndpoint: "/api/auth/google-ads/callback",
backendRefreshEndpoint: "/api/auth/google-ads/refresh",
mcpEnabled: true,
mcpEndpoint: "http://localhost:3003/mcp",
},
### 2. Update Backend Auth Routes
The existing Google Ads auth routes in `ZeroTwoApi/routes/auth/google-ads.js` are already compatible. Just ensure the endpoints match:
- `/api/auth/google-ads/callback` - Exchange authorization code
- `/api/auth/google-ads/refresh` - Refresh access token
### 3. Update MCP Client Configuration
In `ZeroTwoApi/lib/mcp-client.js`, add Google Ads MCP support:```javascript
// For Google Ads MCP
if (integration.provider === "google_ads") {
endpointUrl = "http://localhost:3003/mcp";
// Use OAuth token from profile
if (integration.oauth_token) {
transportOptions.headers = {
Authorization: `Bearer ${integration.oauth_token}`,
...integration.headers,
};
}
}
4. Create MCP Integration
After OAuth authentication, create an MCP integration in the database:```sql
INSERT INTO mcp_integrations (
user_id,
name,
provider,
endpoint,
mcp_type,
connection_status,
auth_type,
description
) VALUES (
'user_id_here',
'Google Ads',
'google_ads',
'http://localhost:3003/mcp',
'remote_mcp',
'connected',
'oauth',
'Google Ads integration via MCP'
);
### 5. Update Tool Definitions
In `ZeroTwoApi/lib/agents/tools/`, create or update the Google Ads tool definitions to call the MCP server:```javascript
// Example tool definition
{
name: "google_ads_list_campaigns",
description: "List Google Ads campaigns",
inputSchema: {
type: "object",
properties: {
customerId: {
type: "string",
description: "Google Ads customer ID (without hyphens)",
},
status: {
type: "string",
enum: ["ALL", "ENABLED", "PAUSED"],
default: "ALL",
},
},
required: ["customerId"],
},
handler: async (args) => {
// Call MCP server
const result = await mcpClient.callTool({
provider: "google_ads",
toolName: "google_ads_list_campaigns",
arguments: {
userId: args.userId,
...args,
},
});
return result;
},
}
Architecture```
┌─────────────────┐
│ Frontend │
│ (ZeroTwo) │
└────────┬────────┘
│
│ OAuth Flow
▼
┌─────────────────┐ ┌──────────────────┐
│ Google Ads │◄────►│ Google OAuth │
│ MCP Server │ │ & Ads API │
└────────┬────────┘ └──────────────────┘
│
│ MCP Protocol
▼
┌─────────────────┐
│ Backend │
│ (ZeroTwoApi) │
└─────────────────┘
## Development
### Project Structure```
google-ads-mcp-server/
├── src/
│ ├── auth/
│ │ └── oauth-manager.ts # OAuth token management
│ ├── config/
│ │ └── index.ts # Configuration management
│ ├── google-ads/
│ │ └── client.ts # Google Ads API wrapper
│ ├── mcp/
│ │ ├── server.ts # MCP server implementation
│ │ └── tools.ts # MCP tool definitions
│ ├── types/
│ │ └── index.ts # TypeScript type definitions
│ ├── utils/
│ │ └── logger.ts # Logging utility
│ └── index.ts # Entry point
├── package.json
├── tsconfig.json
├── env.example
└── README.md
Scripts
npm run dev- Start development server with hot reloadnpm run build- Build TypeScript to JavaScriptnpm start- Start production servernpm run lint- Run ESLintnpm run format- Format code with Prettier
Google Ads Customer ID
To find your Google Ads Customer ID:
- Sign in to your Google Ads account
- Click on the help icon (?) in the top right
- Look for your customer ID (10 digits)
- Use it without hyphens in API calls
Example: If your customer ID displays as 123-456-7890, use 1234567890
Security Considerations
- OAuth Tokens: Tokens are stored in memory. For production, use a secure database or encrypted storage.
- Developer Token: Keep your Google Ads Developer Token secure. Never commit it to version control.
- CORS: Configure CORS origins appropriately for production.
- HTTPS: Use HTTPS in production for secure communication.
- Environment Variables: Never commit
.envfiles. Use secure secret management in production. - Rate Limiting: Implement rate limiting for production deployments.
Troubleshooting
OAuth Errors
- "Missing required environment variables": Check your
.envfile has all required variables - "Failed to exchange authorization code": Verify your redirect URI matches exactly in Google Cloud Console
- "Token expired": The server automatically refreshes tokens if a refresh token is available
Google Ads API Errors
- "Developer token is invalid": Verify your developer token is correct and approved
- "Customer not found": Check that your customer ID is correct (10 digits, no hyphens)
- "Authentication failed": Ensure the user has granted the
adwordsscope during OAuth
MCP Connection Issues
- "No valid session ID": Ensure the MCP client sends proper session headers
- "Authentication required": User needs to complete OAuth flow first
Cost Considerations
- Google Ads API calls are free and don't count against your advertising budget
- No additional costs beyond your normal Google Ads spend
- API has rate limits: follow Google Ads API rate limits
Useful Links
- Google Ads API Documentation
- Google Ads Query Language (GAQL)
- Google Ads API Metrics
- Model Context Protocol
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Powered by ZeroTwo
This Google Ads MCP connector is part of the ZeroTwo AI platform — the all-in-one AI workspace that lets you manage Google Ads campaigns, analyze performance, and optimize your ad spend through GPT-5, Claude, and Gemini.
🌐 ZeroTwo — All AI Models in One App · Manage Google Ads campaigns with GPT-5, Claude, and Gemini — all in one workspace.
✨ ZeroTwo Features · AI ad copywriting, campaign analysis, web search, and MCP-powered Google Ads tools.
🤖 AI Models — GPT-5, Claude & Gemini · Use the world's most capable AI to write ads, analyze metrics, and optimize campaigns.
🔌 ZeroTwo Connectors & Integrations · Connect Google Ads, Gmail, Google Analytics, and more to your AI marketing workflow.
💰 ZeroTwo Pricing · One subscription that replaces ChatGPT Plus, Claude Pro, and Gemini Advanced.
📝 ZeroTwo Blog · AI marketing strategies, Google Ads tips, and ZeroTwo product updates.
🚀 Try ZeroTwo Free · Supercharge your Google Ads with AI — get started free today.
> Built for ZeroTwo — Use this Google Ads MCP server with ZeroTwo's AI connector system to manage campaigns, analyze ad performance, and optimize your advertising through natural language conversations.
