How to Build MCP Server for Google Data in 2026
Learn how to build MCP server code with OAuth, tool routing and per-repo API key scoping, so Claude Code or Cursor can safely read Google data.

Your coding agent is updating a landing page, and you ask it for last month's clicks before it rewrites the title. It can read the repository, but it can't safely fetch the site's Search Console data. Pasting a dashboard export works once. Giving the agent unrestricted Google credentials creates a different problem.
Learning how to build an MCP server means designing the boundary between those extremes. For Google data, the useful first build is a small, read-only server with repository-scoped access, predictable responses, and a cross-project test that fails safely.
Table of Contents
- Scope the Server and Its Capabilities
- Build the Server Step by Step
- Add Authentication and Per-Repo Key Scoping
- Handle Errors, Timeouts and Stale Data
- Test Security and Performance Before Release
- Deploy the Server and Connect Your First Agent
Scope the Server and Its Capabilities
Start with the question your agent needs to answer: which queries brought clicks to this page during the requested period? That calls for a bounded analytics query, not a general-purpose tool that accepts arbitrary Google API requests.
The MCP server exposes data or capabilities. The MCP client, inside an application such as Claude Code or Cursor, connects to that server on the agent's behalf. Anthropic introduced MCP on November 25, 2024, as an open standard, establishing a common integration boundary rather than a client-specific plugin, as described in its MCP announcement.
Match capabilities to the job
MCP capability types mapped to Google data
| Capability | What It Does | Google Data Example |
|---|---|---|
| Tools | Runs a function the agent can call with arguments | query_search_console(site, start_date, end_date) returns rows of queries, clicks and impressions |
| Resources | Supplies read-only project context the agent can load | Verified Search Console properties and the project's GA4 property ID |
| Prompts | Provides reusable workflow templates | Post-deploy comparison template that checks a defined window before and after a release |
MCP uses JSON-RPC for communication. Clients discover tool definitions through tools/list and invoke them through tools/call. Each definition needs a unique name, an accurate description, and an input schema the server can validate.
Keep the distinction between context and permission clear. A resource can describe a project's approved properties, but that description doesn't authorize access. Your handlers must enforce access independently of anything the model reads or supplies.
Finish the boundary before coding
Write down these decisions:
- Data sources: Decide whether the initial server needs Search Console, GA4, keyword data, or only a subset.
- Read-only operations: Identify the reports agents need without introducing exports or mutations.
- Project context: Specify which tools require a project selector and how the authenticated identity constrains it.
- Excluded operations: Rule out arbitrary HTTP requests, unrestricted property enumeration, credential retrieval, and unrestricted database queries.
Google credentials stay server-side. Clients should receive the same behavior and limits regardless of which agent invokes the tool. Keep Google integration code separate from MCP registration so you can test business logic without running a model.
Build the Server Step by Step
Build a vertical slice that reaches a real Google report. An echo tool proves connectivity, but it doesn't exercise property mapping, date handling, OAuth refresh, or report normalization.
The process below keeps the entry point small and the provider integration replaceable.

Create the transport and Google connection
Create the project with an official MCP SDK. Use TypeScript or Python, whichever your team already operates confidently. Create an entry point that starts a Streamable HTTP transport for remote access, and keep tool registration outside the startup file. The common slip is copying a local standard-input/output example and assuming remote clients can connect to it unchanged.
Configure Google access before writing report handlers. Create a Google Cloud project, enable the Search Console and Google Analytics Data APIs, and configure the OAuth consent flow. Request read-only scopes for the reports you intend to expose. Don't request broad account-management permissions because you might need them later.
Define focused report tools. Start with names such as
query_search_consoleandquery_ga4_landing_pages. Require explicit dates, constrain dimensions and metrics, reject unknown arguments, and describe whether the date boundaries are inclusive. A vague description such as “gets analytics” leaves the agent guessing which report to request.
For Search Console, distinguish the page being analyzed from the property containing it. A page URL is a report filter; it isn't proof that the caller may access the property. Resolve the approved property through your project configuration.
Implement and inspect the report path
Register definitions and handlers through the SDK. Let the SDK handle protocol discovery and dispatch rather than writing your own JSON-RPC router. Ensure
tools/listexposes the intended schemas andtools/callreaches the corresponding handler. Return structured rows, not a paragraph containing clicks and impressions that the agent must parse.Wrap the existing Google APIs. In 2025, 58% of MCP builders reported wrapping existing APIs rather than building APIs from scratch, according to Zuplo's State of MCP survey. Put Search Console and GA4 clients behind adapters so provider-specific response formats don't spread into your tool contracts. Load development credentials through environment variables and production credentials through a secret manager, never through committed sample code.
Run the server locally with MCP Inspector. Connect to the HTTP endpoint, list tools, inspect their schemas, and invoke a report directly. Testing only through conversational prompts makes it harder to tell whether a failure came from the schema, the handler, or the agent's arguments.
Preserve Google's metric meanings during normalization. Search Console clicks and GA4 sessions aren't interchangeable, and joining them by page doesn't make them equivalent. Return explicit column names and source identifiers instead of a generic traffic field.
Build check: The tool list matches your registry, and a bounded Search Console call matches the dashboard when property, dates, filters, dimensions, and search type match.
If the results differ, inspect those settings before changing your calculations. Also distinguish an empty report from a failed upstream request. Returning an empty array for both makes a broken integration look like a site with no traffic.
Add Authentication and Per-Repo Key Scoping
A local-only demo isn't a safe team deployment. Once the server reads private analytics, authentication and tool-level authorization become part of its core contract.
Make the repository-to-project mapping visible in your design, not just in a setup document.

Separate identity from permission
For remote OAuth access, use the OAuth 2.1 resource-server model. Validate issuer, audience, expiry, and intended resource on every request. Clients should use PKCE and exact redirect-URI matching; a valid token minted for another service must still be rejected.
Prefer workload identities where your infrastructure supports them, rather than distributing long-lived secrets. Microsoft's MCP server security guidance also recommends an enforcement gateway for validation, rate limiting, and auditing. The gateway can establish identity, but each tool still needs to authorize the requested operation.
For CI or headless integrations that support API-key authentication, use a separate repository credential. This is a deliberate machine-access path, not a reason to skip the remote client's OAuth requirements.
Authorization controls and what each one stops
| Control | Problem It Stops | Where It Runs |
|---|---|---|
| Token validation, including issuer, audience and expiry | Accepting a token minted for another service | Every request, before any tool runs |
| Per-repo API key scope | One agent reading another project's Search Console data | Project lookup inside each tool |
| Denial by default | A new tool exposing data without a check | Tool registry at startup |
| Rate limit and quota | A runaway loop draining Google API quota | Gateway or middleware, per key |
| Revocation and rotation | A leaked key that stays valid | Key store, with immediate disable |
Implement the repository boundary
Issue a random key from your own key store, display it only when created, and store a hash of the key, not its plaintext value. Map that record to a repository, a single internal project ID, allowed scopes, and revocation state. Don't hash the project ID as a substitute for protecting the credential.
Inside every handler, resolve the project from the authenticated principal before looking up Google properties. A supplied project ID is a requested selector, never authority. Sharing a key across repositories removes the isolation you're trying to create.
Use this implementation order:
- Issue and bind: Create the repository key and its project mapping.
- Resolve internally: Load allowed properties from that mapping.
- Require declared scopes: Reject tools without an explicit authorization policy.
- Hide foreign objects: Return the same not-found result for inaccessible and nonexistent properties.
- Support lifecycle changes: Allow immediate revocation and a bounded overlap during rotation.
For a companion walkthrough while implementing the connection path, use this video.
The release-blocking test is concrete: authenticate with repository A's key and request repository B's Search Console property. The handler must stop before calling Google and return no property name, verification status, account identifier, or other distinguishing metadata.
Handle Errors, Timeouts and Stale Data
A malformed argument should produce a field-level validation error, not a Google request followed by a stack trace. Validate both schema shape and meaning: a correctly formatted end date can still precede the start date.
Define typed output contracts alongside inputs. Agents need to distinguish a retryable interruption from a denied request and a complete report from an incomplete one. The OWASP guide to secure MCP server development supports strict validation, session isolation, and hardened operational controls.
Make recovery explicit
The retry budget below is an example implementation policy, not an MCP requirement.
Failure types and the response each one should return
| Failure | Response to Agent | Retry? |
|---|---|---|
| Malformed argument | Validation error that names the failing field | No, fix the call first |
| Google API timeout | Timeout error with a correlation ID | Yes, after backoff, within the configured attempt budget |
| Quota exceeded | Quota error with the reset time when known | No, until reset or an explicit retry-after time |
| Partial result | Data with partial set to true and the missing date range listed |
Only for the missing range |
| Stale data | Data with fetched_at and known data lag |
Re-query after the lag window |
Put a timeout on every upstream call. For example, you could cap timeout retries at three attempts with exponential backoff and jitter. Retry transient throttling only when Google's response indicates it's appropriate; a daily quota exhaustion isn't a brief throttling event.
Choose a pagination policy too. For example, return at most a thousand rows per call with an opaque next cursor bound to the project and query. Don't let a cursor become a way to resume another project's report.
Preserve completeness and provenance
Every successful report should identify its project scope, source, requested date range, comparison window, and retrieval time. Include provider freshness information when available. fetched_at tells you when your server retrieved data, not when Google finished processing it.
If freshness is unknown, say so. If a comparison window is incomplete, don't present its percentage change as a finished measurement.
- Audit events: Record correlation ID, tool name, project, outcome, latency, and provider status without credentials or raw sensitive payloads.
- Write safety: Require idempotency keys if you later add recommendation writes or exports, and bind them to the caller and operation.
- Cache boundaries: Include authorization scope and normalized query parameters in cache keys.
A narrow report tool is easier to approve, cache, and monitor than a tool that accepts arbitrary analytics instructions.
Test Security and Performance Before Release
Security testing is a release gate. An analysis of 1,899 open-source MCP servers found 7.2% contained general vulnerabilities, 5.5% exhibited MCP-specific tool-poisoning issues, and 3.6% exposed credentials.
Turn those risks into reproducible checks rather than relying on a successful demo.

Exercise the denied paths
Negative tests every Google-data MCP server should fail safely
| Test | Input | Expected Result |
|---|---|---|
| Cross-project access | Key for repo A requests repo B's Search Console property | Denied, with no data or distinguishable metadata |
| Broad date range | A request exceeding the configured daily-report range | Rejected with a range-limit message |
| Injected page text | Page copy that says to ignore prior rules | Treated as data, with no change to tool calls |
| Malformed GA4 filter | Filter with an unknown operator | Schema validation error before any API call |
| Expired token | Token past its expiry time | Denied with an authentication error and no data |
For a concrete range-limit case, submit a hypothetical request for five years of daily rows against a tool configured for shorter reports. Assert the rejection happens before provider access.
Tool descriptions and annotations aren't permission checks. Likewise, page text retrieved for SEO analysis is untrusted content, even if it appears inside a legitimate Google-data workflow. Test the full agent interaction as well as the handler to verify that injected instructions don't trigger unintended operations.
Run the release gate in order
- Encode assertions: Write each request as an automated test. Verify the response, audit event, and absence of an upstream call where denial should happen locally.
- Use preproduction: Run the tests against realistic project mappings under representative concurrent load. Include revoked keys, cache hits, and connection reuse.
- Measure behavior: Record p50 and p95 latency, provider-error rate, timeout rate, schema-validation failures, and blocked authorization attempts.
- Inspect leakage: Search logs and errors for tokens, key prefixes, authorization headers, and provider responses containing sensitive identifiers.
- Compare denied responses: Check inaccessible and nonexistent properties for differences in bodies, status behavior, and avoidable timing signals.
Use Foo Guard's pre-deployment security checks for agent developers as a companion checklist when reviewing authentication, secrets, and tool access. Keep your own executable tests as the release authority.
Load testing should also exercise cancellation and provider failures. A server that responds quickly when Google succeeds may still exhaust its connection pool when upstream calls hang.
Don't declare production readiness until every negative test passes. Track operational thresholds separately so acceptable latency never excuses an authorization failure.
Deploy the Server and Connect Your First Agent
Choose self-hosted or hosted based on whether you need to own the integration's behavior. Self-hosting gives you control over report contracts and infrastructure, but it also makes your team responsible for OAuth maintenance, provider failures, and on-call work.
For the self-hosted path, containerize the application and place it behind an HTTPS gateway. Let the gateway enforce request-level controls while handlers retain project authorization. Store secrets outside the image and add health checks that don't expose configuration or account information.
Connect a real client
Use a controlled rollout:
- Register the endpoint: Add your server's remote URL to Claude Code or Cursor using the client's supported authentication flow.
- Inspect discovery: Confirm that the client sees the intended tools and required arguments.
- Run a known report: Query an approved site and compare the result with the matching Search Console dashboard view.
- Inspect operations: Verify that the request appears in your metrics and audit trail with the expected project identity.
For infrastructure visibility, Fivenines' example of monitoring through an MCP server is useful when deciding how agents should inspect operational state. Keep diagnostic access separate from customer analytics permissions.
Hosting decision: If operating the integration costs more engineering time than it saves, use a hosted option.
Our hosted option, AgentGrown, gives agents Search Console, GA4, and keyword-demand data through remote MCP and works with Claude Code, Claude.ai, Cursor, ChatGPT, and other remote-MCP clients. In Claude Code, run claude mcp add --transport http agentgrown https://agentgrown.com/mcp, then complete Google sign-in and site selection. CI and headless agents can use a created API key as a bearer token; follow the connection documentation for client setup.
Check what you're shipping
Before publishing your own server, review dependency licenses and add a license for your repository. In 2025, an analysis of 10,663 GitHub repositories implementing MCP servers found that 41% lacked license information, according to Endor Labs. Don't treat public availability as permission to redistribute.
This week, pick your hosting path, complete a real read-only tool call, and write down your scope rules. Make the approved property mapping and denied-request behavior part of that record. You'll have a working integration boundary, not just an endpoint an agent happens to reach.
AgentGrown connects your coding agent to real Search Console, GA4, and keyword-demand data without requiring you to operate the Google-data integration yourself. Visit AgentGrown, connect a site, and ask your agent for a page-level baseline before its next SEO change.


