October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Google API

How to Build a Google Custom Search MCP Server (And What to Check First)

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can expose Google Custom Search through an MCP tool by registering a validated search function that calls Google’s Custom Search JSON API with a query (q), Programmable Search Engine ID (cx) and API key (key). But first check eligibility: Google says the JSON API is closed to new customers and will be discontinued on January 1, 2027. This walkthrough is therefore for existing eligible API users; new projects should evaluate Google’s stated alternatives rather than plan on getting a new API key.

Check whether the Google API is available to you

Google’s current Custom Search JSON API overview says the API is not available to new customers and is scheduled for discontinuation on January 1, 2027. Existing customers may continue for a limited period, subject to Google’s published terms. Confirm your project’s eligibility and access before building around it; a working MCP wrapper cannot create API access that Google does not grant.

Google points new projects toward Vertex AI Search for searches across up to 50 domains, or asks developers to contact Google about its full web search solution. Those are alternatives to investigate, not documented drop-in replacements for the JSON API. Compare their scope, features, access requirements, pricing and migration effort against your use case before choosing one.

Understand the request and MCP flow

A Programmable Search Engine defines the sites or collection of sites to search and supplies the engine identifier, cx. The JSON API accepts an HTTP GET request at https://www.googleapis.com/customsearch/v1; its required query parameters include key, cx and q. Google describes its Programmable Search Engine options, including site-focused search and optional image search, in its Programmable Search Engine overview.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The MCP server sits between the AI host and Google. It registers a tool with a name, description and validated input schema. When the host invokes that tool, the handler calls Google, checks the HTTP response and returns results in MCP content format. The server does not replace Google’s engine configuration, API credentials, quota or lifecycle restrictions.

Prepare a TypeScript v2 project

The example below uses the official TypeScript SDK v2 package, @modelcontextprotocol/server, and the local stdio transport. The SDK’s first-server guide lists Node.js 20 or later and installs the SDK, Zod and tsx. Use the v2 package and API consistently; the older v1 documentation has a different package and interface.

  1. Verify that the Google project already has eligible Custom Search JSON API access.
  2. Configure a Programmable Search Engine and note its cx identifier.
  3. Create or identify an API key for that application. Keep the key outside source code and avoid printing it in logs.
  4. Install Node.js 20 or later. Create a project directory and initialize it with npm init -y.
  5. Install the documented dependencies: npm install @modelcontextprotocol/server zod and npm install --save-dev tsx.
  6. Set GOOGLE_API_KEY and GOOGLE_CSE_ID in the server process environment, using your platform’s secret-management method rather than committing them to the repository.

The following is an illustrative implementation based on the documented SDK and Google request shape. It has not been validated against a live Google API account or run in MCP Inspector.

Register a validated search tool

Save as src/index.ts. The example bounds query length, handles missing configuration, non-success HTTP responses and malformed result data, and returns a concise list of titles, links and snippets. It requests ten results by setting num; remove or change that parameter only after checking the API’s current supported options and your intended result format.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { McpServer } from "@modelcontextprotocol/server";
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio.js";
import { z } from "zod";

const apiKey = process.env.GOOGLE_API_KEY;
const engineId = process.env.GOOGLE_CSE_ID;

const server = new McpServer({
  name: "google-custom-search",
  version: "1.0.0",
});

server.registerTool(
  "google_custom_search",
  {
    title: "Google Custom Search",
    description: "Search the configured Google Programmable Search Engine.",
    inputSchema: {
      query: z.string().trim().min(1).max(300)
        .describe("The terms to search for"),
    },
  },
  async ({ query }) => {
    if (!apiKey || !engineId) {
      return {
        isError: true,
        content: [{ type: "text", text: "Missing GOOGLE_API_KEY or GOOGLE_CSE_ID configuration." }],
      };
    }

    const url = new URL("https://www.googleapis.com/customsearch/v1");
    url.search = new URLSearchParams({
      key: apiKey,
      cx: engineId,
      q: query,
      num: "10",
    }).toString();

    let response: Response;
    try {
      response = await fetch(url, { signal: AbortSignal.timeout(15000) });
    } catch {
      return {
        isError: true,
        content: [{ type: "text", text: "Google Custom Search request failed or timed out." }],
      };
    }

    if (!response.ok) {
      const detail = await response.text();
      return {
        isError: true,
        content: [{
          type: "text",
          text: `Google Custom Search returned HTTP ${response.status}: ${detail.slice(0, 1000)}`,
        }],
      };
    }

    const data: unknown = await response.json();
    if (typeof data !== "object" || data === null || !("items" in data)) {
      return {
        content: [{ type: "text", text: "Google returned no results in the expected response shape." }],
      };
    }

    const items = (data as { items?: Array<{ title?: string; link?: string; snippet?: string }> }).items ?? [];
    const results = items.map((item, index) =>
      `${index + 1}. ${item.title ?? "Untitled"}n${item.link ?? ""}n${item.snippet ?? ""}`
    );

    return {
      content: [{
        type: "text",
        text: results.length ? results.join("nn") : "No results returned.",
      }],
    };
  },
);

const transport = new StdioServerTransport();
await server.connect(transport);

Run it from the project directory with npx tsx src/index.ts. The server waits for its MCP host to launch it and communicate over stdin/stdout; it is not a command-line search interface. Do not add ordinary status messages to stdout, because stdout carries protocol messages. Send any diagnostics to stderr instead.

Connect and validate the local server

The SDK’s first-server guide recommends MCP Inspector for exercising a local stdio server. Configure the Inspector to launch the command npx with arguments tsx and src/index.ts, from the project directory, and provide the two environment variables to that process. The exact Inspector controls can vary by release.

  1. Start the server through Inspector. Confirm that the process starts and the server exposes google_custom_search.
  2. Invoke the tool with a non-empty query, such as site:example.com documentation.
  3. Check that the result content contains numbered titles, links and snippets, or the explicit no-results message.
  4. Try an empty query to confirm input validation rejects it before a Google request is made.
  5. Temporarily omit a credential in a safe local environment to confirm the configuration error is returned without exposing a secret.

This validation sequence checks the MCP tool path and error handling; a live result still depends on eligible API access, a valid engine and Google’s service response.

Choose stdio or Streamable HTTP

Transport Best fit Operational consideration
stdio A local MCP host launches the server as a process. Keep stdout dedicated to the protocol and route logs to stderr. The host and server share a process-launch configuration.
Streamable HTTP A remote server must be reachable by clients over a network. Deployment and access security become part of the design. The SDK overview recommends Streamable HTTP for remote servers; the local stdio example above is not a remote deployment.

See the SDK’s transport documentation before adapting the example. A remote server needs appropriate network and authentication controls; the cited guidance does not establish a particular hosting architecture or provider.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cost, quota and lifecycle implications

For existing customers, Google’s API overview lists 100 free queries per day, then $5 per 1,000 additional queries, with a maximum of 10,000 queries per day. These are Google’s published figures for existing customers, not an offer to new signups, and the API is scheduled to end January 1, 2027. Check the current API overview for the terms that apply to your account.

An MCP invocation that makes one Google request consumes the underlying API quota; wrapping it in MCP does not change Google’s pricing or daily ceiling. Avoid automatic retries without a reason and a retry limit: transient network failure is different from an API rejection, and repeated calls can use quota. For larger workflows, decide how to handle empty results, Google errors, timeout budgets and any caching policy explicitly. The cited API and SDK sources do not establish performance benchmarks or a recommended cache duration.

Troubleshooting common failures

The server will not start

Confirm Node.js 20 or later, installed dependencies, the correct working directory and the exact entry path. Keep the example’s v2 imports aligned with the installed @modelcontextprotocol/server package; do not mix v1 setup instructions into a v2 project.

The host cannot see the tool or protocol messages fail

Check that the host launches the intended command and arguments and that it can access the environment variables. Remove ordinary console output from stdout; use stderr for diagnostic logs. Ensure the process remains running for the host’s stdio session rather than exiting after startup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Google returns an unsuccessful HTTP response

Inspect the status and response detail locally without logging the API key. Verify API eligibility, that the key is valid for the application, that the cx value identifies the configured engine, and that the request contains q. A wrapper cannot remedy an account that is not eligible for the API.

The tool returns no results

Check that the engine is configured to search the intended sites or collection, then try a query known to match that scope. The sample treats a missing or empty items array as no results rather than assuming that every successful response contains matches.

The request times out

The sample aborts a request after 15 seconds and returns an MCP error. If that budget is unsuitable for your host, adjust it deliberately and make sure the host’s own timeout allows for the same operation. Do not turn a timeout into an unbounded retry loop.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to capture a webpage for a search workflow rather than build a Google-backed search tool, ScreenshotNeo is a separate website screenshot API and MCP server. A single GET request can return an image or PDF; it does not replace Google Custom Search or return search results. Its documented options include full-page capture, selected-element capture, device presets, PDF settings, custom headers and cookies, and asynchronous or bulk capture.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

One-call cURL example (see the ScreenshotNeo API documentation):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo removes cookie and consent banners, newsletter popups and chat widgets before capture; bot checks, blank pages and failed loads are not billed. Its MCP server lets AI agents use screenshot tools. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for the free plan.

Frequently Asked Questions

Can a new Google project obtain Custom Search JSON API access?

Google’s current API overview says the JSON API is closed to new customers. New projects should assess Google’s stated alternatives rather than assume they can obtain access.

Does this MCP server search the entire web?

It queries the Programmable Search Engine identified by its cx value. The sites and scope depend on that engine’s configuration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can the server use another search provider?

The MCP tool pattern can be adapted to another backend, but this example and its request parameters are specific to Google’s Custom Search JSON API.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.