Skip to main content
Glama
ZLeventer

Google Analytics MCP Server

ga4_paid_search_performance

Retrieve paid search traffic metrics including sessions, conversions, cost, and CPC. Break down results by campaign, landing page, keyword, or source to analyze Google Ads performance.

Instructions

Paid: sessions/conversions/cost/CPC for Paid Search traffic, broken down by campaign (default), landing page, keyword, or source.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
start_dateNoStart date: YYYY-MM-DD, NdaysAgo, yesterday, or today28daysAgo
end_dateNoEnd date: YYYY-MM-DD, NdaysAgo, yesterday, or todayyesterday
property_idNoOverride GA4_PROPERTY_ID env var for this call
limitNoMax rows to return
breakdownNoDimension to break paid search traffic down bysessionCampaignName

Implementation Reference

  • src/index.ts:64-71 (registration)
    Registration of the ga4_paid_search_performance tool, mapping the tool name to the paidSearchPerformance handler and paidSearchSchema.
    server.tool(
      "ga4_paid_search_performance",
      "Paid: sessions/conversions/cost/CPC for Paid Search traffic, broken down by campaign (default), landing page, keyword, or source.",
      paidSearchSchema,
      async (args) => {
        try { return ok(await paidSearchPerformance(args)); } catch (e) { return err(e); }
      }
    );
  • Zod schema for paid search performance, defining input params: start_date, end_date, property_id, limit, and breakdown (campaign/page/keyword/source).
    export const paidSearchSchema = {
      ...common,
      breakdown: z
        .enum(["sessionCampaignName", "landingPage", "sessionGoogleAdsKeyword", "sessionSource"])
        .default("sessionCampaignName")
        .describe("Dimension to break paid search traffic down by"),
    };
  • Actual handler for ga4_paid_search_performance. Calls GA4 runReport API filtered to Paid Search channel, fetching sessions, users, engagement, conversions, revenue, clicks, cost, and CPC, broken down by campaign/page/keyword/source.
    export async function paidSearchPerformance(args: z.infer<z.ZodObject<typeof paidSearchSchema>>) {
      const [res] = await getClient().runReport({
        property: getProperty(args.property_id),
        dateRanges: [{ startDate: args.start_date, endDate: args.end_date }],
        dimensions: [{ name: args.breakdown }],
        metrics: [
          { name: "sessions" },
          { name: "totalUsers" },
          { name: "engagementRate" },
          { name: "conversions" },
          { name: "keyEvents" },
          { name: "totalRevenue" },
          { name: "advertiserAdClicks" },
          { name: "advertiserAdCost" },
          { name: "advertiserAdCostPerClick" },
        ],
        dimensionFilter: {
          filter: {
            fieldName: "sessionDefaultChannelGroup",
            stringFilter: { value: "Paid Search" },
          },
        },
        orderBys: [{ metric: { metricName: "sessions" }, desc: true }],
        limit: args.limit as unknown as number,
      });
      return formatReport(res);
    }
  • Helper function that formats the GA4 API response into a clean JSON structure with rowCount and rows arrays. Used by the paidSearchPerformance handler.
    function formatReport(res: any) {
      const rows = (res.rows ?? []).map((r: any) => {
        const out: Record<string, string | number> = {};
        (res.dimensionHeaders ?? []).forEach((h: any, i: number) => {
          out[h.name] = r.dimensionValues?.[i]?.value ?? "";
        });
        (res.metricHeaders ?? []).forEach((h: any, i: number) => {
          const v = r.metricValues?.[i]?.value ?? "0";
          const n = Number(v);
          out[h.name] = Number.isFinite(n) ? n : v;
        });
        return out;
      });
      return { rowCount: res.rowCount ?? rows.length, rows };
    }
  • Helper functions getClient (returns a singleton GA4 BetaAnalyticsDataClient) and getProperty (resolves property ID string), used by the handler to initialize the API client.
    export function getClient(): BetaAnalyticsDataClient {
      if (cachedClient) return cachedClient;
      if (!process.env.GOOGLE_APPLICATION_CREDENTIALS) {
        throw new GA4Error("GOOGLE_APPLICATION_CREDENTIALS is not set");
      }
      cachedClient = new BetaAnalyticsDataClient();
      return cachedClient;
    }
    
    export function getProperty(override?: string): string {
      const id = override ?? process.env.GA4_PROPERTY_ID;
      if (!id) throw new GA4Error("GA4_PROPERTY_ID is not set and no property_id was passed");
      return id.startsWith("properties/") ? id : `properties/${id}`;
    }
    
    export const DEFAULT_START = "28daysAgo";
    export const DEFAULT_END = "yesterday";
Behavior2/5

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

No annotations provided, and description does not mention behavioral traits like read-only nature, rate limits, or side effects. The tool is likely read-only but this is not stated, leaving the agent uninformed about safety.

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?

Single, front-loaded sentence with no extra words. All key information (subject, metrics, breakdown options) is included efficiently.

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

Completeness4/5

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

Description covers the essential return values (sessions, conversions, cost, CPC) and breakdown dimension, but does not specify row structure or pagination. Given no output schema, this is reasonably complete for a simple report tool.

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

Parameters3/5

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

Schema description coverage is 100%, so baseline is 3. The description mentions breakdown dimensions but these are already fully documented in the schema's enum and parameter descriptions, adding minimal extra meaning.

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?

The description clearly specifies the tool returns metrics (sessions, conversions, cost, CPC) for Paid Search traffic, with breakdown options. It distinguishes itself by explicitly targeting Paid Search, differentiating from sibling tools like ga4_organic_search_performance.

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

Usage Guidelines2/5

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

No guidance on when to use this tool vs alternatives such as ga4_all_paid_performance or ga4_google_ads_performance. Description lacks any usage conditions or exclusions.

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/ZLeventer/google-analytics-mcp-server'

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