Google Ads MCP服务器

一个支持OAuth 2.0认证的Google Ads集成模型上下文协议服务器,提供广告系列管理、性能指标获取和账户统计功能。

  • by EmilyThaHuman
  • 本地部署
  • 更新于
在 GitHub 查看 EmilyThaHuman/google-ads-mcp-server

使用说明

谷歌广告MCP服务器

用于Google广告与OAuth 2.0身份验证集成的模型上下文协议(MCP)服务器。

特性

  • OAuth 2.0身份验证:通过自动令牌刷新保护Google OAuth流
  • MCP协议支持:全面实施模型上下文协议
  • 谷歌广告运营:
    • 使用筛选功能列出活动
    • 获取活动绩效指标
    • 获取帐户摘要和统计信息
  • 会话管理:具有自动令牌刷新功能的持久会话
  • TypeScript:完全使用TypeScript类型,以获得更好的开发体验
  • 谷歌广告API v18:最新版本的谷歌广告API

先决条件

  • Node.js 18+
  • 启用Google Ads API的Google云项目
  • OAuth 2.0凭据(客户端ID和客户端密钥)
  • 谷歌广告开发者代币

设置

1.谷歌云和谷歌广告配置

谷歌云控制台设置

  1. 首选 谷歌云控制台
  2. 创建新项目或选择现有项目
  3. 启用Google Ads API
  4. 创建OAuth 2.0凭据:
    • 应用程序类型:Web应用程序
    • 授权重定向URI: http://localhost:3003/oauth/callback
  5. 复制您的客户端ID和客户端密码

Google Ads API设置

  1. 首选 谷歌广告API中心
  2. 申请开发者代币(API访问需要)
  3. 等待批准(可能需要24-48小时)
  4. 一旦获得批准,复制您的开发者令牌

2.安装

# Clone or navigate to the project directory
cd google-ads-mcp-server

# Install dependencies
npm install

3.配置

创建一个 .env 根目录中的文件:

cp env.example .env

编辑 .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

用法

发展模式

npm run dev

生产模式

# Build
npm run build

# Start
npm start

API终点

健康检查

GET /health

OAuth流

1.启动授权

GET /oauth/authorize?userId={userId}&state={state}

答复:

{
  "authorizationUrl": "https://accounts.google.com/o/oauth2/v2/auth?...",
  "state": "your-state-value"
}

2.OAuth回调(自动处理)

GET /oauth/callback?code={code}&state={state}

3.刷新令牌

POST /oauth/refresh
Content-Type: application/json

{
  "userId": "user123",
  "refreshToken": "refresh_token_here"
}

4.断开连接

POST /oauth/disconnect
Content-Type: application/json

{
  "userId": "user123"
}

MCP端点

POST /mcp
GET /mcp
DELETE /mcp

MCP端点遵循工具执行的模型上下文协议规范。

MCP工具

1.google_ads_list_campaigns

列出带有可选过滤功能的Google广告活动。

输入:

{
  "userId": "user123",
  "customerId": "1234567890",
  "status": "ALL",
  "limit": 50
}

参数:

  • userId (string,必填):用于身份验证的用户ID
  • customerId (字符串,必填):不带连字符的Google Ads客户ID
  • status (枚举,可选):按活动状态筛选-“全部”、“已启用”或“已暂停”(默认值:“全部”)
  • limit (数字,可选):要返回的最大活动数,1-10000(默认值:50)

输出:

{
  "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

获取Google广告活动的性能指标。

输入:

{
  "userId": "user123",
  "customerId": "1234567890",
  "campaignIds": ["123456789", "987654321"],
  "startDate": "2024-01-01",
  "endDate": "2024-01-31",
  "metrics": ["impressions", "clicks", "conversions", "cost_micros"]
}

参数:

  • userId (string,必填):用于身份验证的用户ID
  • customerId (字符串,必填):不带连字符的Google Ads客户ID
  • campaignIds (数组,可选):要获取指标的活动ID列表(所有活动为空)
  • startDate (字符串,可选):YYYY-MM-DD格式的开始日期(默认值:30天前)
  • endDate (字符串,可选):YYYY-MM-DD格式的结束日期(默认值:今天)
  • metrics (数组,可选):要检索的指标(默认值:展示次数、点击次数、转化率、成本_微米)

可用指标:

  • impressions -广告显示次数
  • clicks -广告点击次数
  • conversions -转换次数
  • cost_micros -微观成本(实际成本除以1000000)
  • average_cpc -每次点击的平均成本
  • ctr -点击率

输出:

{
  "campaignMetrics": [
    {
      "campaignId": "123456789",
      "campaignName": "Summer Campaign",
      "impressions": 10000,
      "clicks": 500,
      "conversions": 50,
      "cost_micros": 5000000
    }
  ],
  "customerId": "1234567890",
  "dateRange": {
    "startDate": "20240101",
    "endDate": "20240131"
  }
}

3.谷歌统计摘要

获取总体客户摘要和绩效指标。

输入:

{
  "userId": "user123",
  "customerId": "1234567890",
  "startDate": "2024-01-01",
  "endDate": "2024-01-31"
}

参数:

  • userId (string,必填):用于身份验证的用户ID
  • customerId (字符串,必填):不带连字符的Google Ads客户ID
  • startDate (字符串,可选):YYYY-MM-DD格式的开始日期(默认值:30天前)
  • endDate (字符串,可选):YYYY-MM-DD格式的结束日期(默认值:今天)

输出:

{
  "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"
    }
  }
}

与ZeroTwoApi集成

要将此Google Ads MCP服务器与您的ZeroTwoApi后端集成:

1.更新前端OAuth配置

在 ZeroTwo/src/services/oauthProviders.js,添加Google Ads配置:

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.更新后端认证路由

现有的Google Ads身份验证路由 ZeroTwoApi/routes/auth/google-ads.js 已经兼容了。只需确保端点匹配:

  • /api/auth/google-ads/callback -交易所授权码
  • /api/auth/google-ads/refresh -刷新访问令牌

3.更新MCP客户端配置

在 ZeroTwoApi/lib/mcp-client.js,添加谷歌广告MCP支持:

// 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.创建MCP集成

OAuth身份验证后,在数据库中创建MCP集成:

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.更新工具定义

在 ZeroTwoApi/lib/agents/tools/,创建或更新Google Ads工具定义以调用MCP服务器:

// 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;
  },
}

建筑

┌─────────────────┐
│   Frontend      │
│   (ZeroTwo)     │
└────────┬────────┘
         │
         │ OAuth Flow
         ▼
┌─────────────────┐      ┌──────────────────┐
│  Google Ads     │◄────►│  Google OAuth    │
│  MCP Server     │      │  & Ads API       │
└────────┬────────┘      └──────────────────┘
         │
         │ MCP Protocol
         ▼
┌─────────────────┐
│   Backend       │
│   (ZeroTwoApi)  │
└─────────────────┘

发展

项目结构

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

脚本

  • npm run dev -使用热重新加载启动开发服务器
  • npm run build -将TypeScript构建为JavaScript
  • npm start -启动生产服务器
  • npm run lint -运行ESLint
  • npm run format -使用Prettier格式化代码

谷歌广告客户ID

要查找您的Google Ads客户ID:

  1. 登录您的Google Ads帐户
  2. 点击右上角的帮助图标(?)
  3. 查找您的客户ID(10位数字)
  4. 用它 没有连字符 在API调用中

示例:如果您的客户ID显示为 123-456-7890,使用 1234567890

安全考虑

  1. OAuth令牌:令牌存储在内存中。对于生产,请使用安全的数据库或加密存储。
  2. 开发者令牌:确保您的Google Ads开发者令牌安全。永远不要将其提交给版本控制。
  3. 跨域资源共享:为生产适当配置CORS源。
  4. 超文本传输安全协议:在生产环境中使用HTTPS进行安全通信。
  5. 环境变量:从不承诺 .env 文件夹。在生产中使用安全的秘密管理。
  6. 速率限制:对生产部署实施速率限制。

故障排除

OAuth错误

  • “缺少必需的环境变量”:检查您的 .env 文件包含所有必需的变量
  • “交换授权码失败”:在Google Cloud控制台中验证您的重定向URI是否完全匹配
  • “令牌已过期”:如果刷新令牌可用,服务器会自动刷新令牌

Google Ads API错误

  • “开发人员令牌无效”:验证您的开发人员令牌是否正确并获得批准
  • “未找到客户”:检查您的客户ID是否正确(10位数字,无连字符)
  • “身份验证失败”:确保用户已授予 adwords OAuth期间的作用域

MCP连接问题

  • “没有有效的会话ID”:确保MCP客户端发送正确的会话标头
  • “需要身份验证”:用户需要先完成OAuth流程

成本考虑

  • Google Ads API调用 自由 不要计入你的广告预算
  • 除了正常的谷歌广告支出外,没有其他额外费用
  • API有费率限制:遵循 Google Ads API费率限制

实用链接

许可证

麻省理工学院

贡献

欢迎投稿!请随时提交拉取请求。


由ZeroTwo提供技术支持

此Google Ads MCP连接器是 ZeroTwo人工智能平台 --通过GPT-5、Claude和Gemini,您可以管理谷歌广告活动、分析性能并优化广告支出。

🌐 ZeroTwo——一个应用程序中的所有AI模型 使用GPT-5、Claude和Gemini管理谷歌广告活动——所有这些都在一个工作区中。
✨ 零两个功能 人工智能广告文案、活动分析、网络搜索和MCP驱动的谷歌广告工具。
🤖 人工智能模型——GPT-5、克劳德和双子座 使用世界上最强大的人工智能来撰写广告、分析指标和优化活动。
🔌 ZeroTwo连接器和集成 将谷歌广告、Gmail、谷歌分析等连接到您的人工智能营销工作流程。
💰 零二定价 一个替代ChatGPT Plus、Claude Pro和Gemini Advanced的订阅。
📝 ZeroTwo博客 人工智能营销策略、谷歌广告提示和ZeroTwo产品更新。
🚀 免费试用ZeroTwo 用人工智能增强你的谷歌广告——今天就免费开始吧。

专为ZeroTwo打造 --使用此Google Ads MCP服务器 ZeroTwo的AI连接器系统 通过自然语言对话管理广告系列、分析广告效果并优化广告。