Build a Google Search MCP Server for Claude, Cursor and Other MCP Clients
Michael Carter · · 22 min read · Last updated

Key takeaways
- A Google search MCP server is a local program that an AI app starts over stdio; this one exposes two read-only tools, google_search and google_news, in about 140 lines of TypeScript on version 2 of the official MCP SDK.
- Returning compact text instead of raw JSON cut a 9-result Google search from 11,517 to 2,080 characters (82% smaller) and 10 news results from 12,266 to 2,772 in our November 17, 2026 test.
- Keep the API key in the MCP client's env block, or reference an environment variable (${env:NAME} in Cursor, ${NAME} in Claude Code's .mcp.json); the SDK's stdio client does not pass your whole environment to the server.
- Each tool call is one BestSERP search: 1 credit per 10 results, $0.50 per 1,000 after 3,000 free searches, with 502 and 503 failures refunded and a limit of 60 searches per minute.
- Poll on 202, wait Retry-After on 429 and retry 502 and 503, all within a 50-second deadline, because the MCP SDK's client gives up on a request after 60 seconds by default.
A Google search MCP server is a small program that gives AI apps such as Claude Desktop, Claude Code and Cursor a tool for live Google results. The app starts the server, the model calls google_search or google_news, and the server fetches the results from a SERP API and returns short text the model can read and cite.
This tutorial builds one in TypeScript with the official MCP SDK, in about 140 lines. Its two tools call BestSERP, a Google SERP API: google_search (query, country, language, result count) and google_news (with a recency filter). The server polls long searches, retries what is worth retrying and reads the API key from its environment. We tested it on November 17, 2026 with an MCP client built on the same SDK; the outputs below are from that run.
What you will build
The Google search MCP server runs on your machine: the AI app starts it as a child process and sends it tool calls over stdio. For each call, the server makes one HTTPS request to BestSERP and returns a compact list of results instead of a large JSON document.

The server exposes two tools:
| Tool | Inputs | What the model gets | Cost per call |
|---|---|---|---|
google_search |
q, gl (country), hl (language), num (10 to 50) |
Position, title, URL or domain, snippet | 1 credit per 10 results |
google_news |
q, gl, hl, recency (hour, day, week, month, year) |
Headline, publisher, publish time, snippet | 1 credit |
This is the start of what the model received for one real search, 2,080 characters in all (the raw JSON was 11,517):
Google results for "model context protocol typescript sdk" (gl=us, hl=en):
1. Activity · modelcontextprotocol/typescript-sdk | github.com
The official TypeScript SDK for Model Context Protocol servers and clients - Activity · modelcontextprotocol/typescript-sdk.
2. for the - modelcontextprotocol/typescript-sdk | gitmcp.io
Connect your AI assistant · Copy the following JSON configuration: · Go to Msty Studio > Tools > 'Import Tools from JSON Clipboard'.Read more
What is an MCP server?
An MCP server is a program that offers tools, data or prompt templates to AI applications through the Model Context Protocol (MCP), an open standard for connecting AI apps to outside systems. The app (the MCP client) lists the server's tools, describes them to the model, and runs one when the model asks, usually after you approve.
A local server like this one uses the stdio transport: the client starts node build/index.js and exchanges JSON-RPC messages over its standard input and output. As the official guide to building an MCP server stresses, the server must never write to stdout (logs go to stderr). It also gets its settings, the API key included, from the environment the client starts it with.
Several Google search MCP servers that ranked for this topic in November 2026 wrap Google's Custom Search JSON API, which is closed to new customers (existing ones must move by January 1, 2027). Others drive a browser against google.com and fight Google's anti-bot checks themselves. A SERP API leaves the fetching and parsing to a provider (what a SERP API is explains how); for the wider picture, see web search for AI agents.
This tutorial uses version 2 of the official TypeScript SDK: separate @modelcontextprotocol/server and @modelcontextprotocol/client packages (2.4.0 when we tested), built for the 2026-07-28 MCP specification. Version 1, the single @modelcontextprotocol/sdk package in most older tutorials, gets fixes for at least six months after v2's July 27, 2026 release, per the SDK's README, which links the migration guide.
Prerequisites
You need three things:
- Node.js 20 or later. We used Node.js 22.17.1 and npm 10.9.2 on Windows 10.
- A BestSERP API key. Sign in for 3,000 free searches (valid 30 days) and create a key under Dashboard > API keys. The quickstart shows a first request, and the Node.js guide covers the API from Node without MCP.
- An MCP client: Claude Desktop, Claude Code or Cursor. Step 3 tests the server without any of them.
Step 1: Create the Google search MCP server project
Create a folder, install the SDK and zod (the SDK describes tool inputs with zod schemas), and add TypeScript:
mkdir bestserp-mcp && cd bestserp-mcp
npm init -y
npm install @modelcontextprotocol/server zod
npm install -D @modelcontextprotocol/client typescript @types/node@22
mkdir src
Match @types/node to your Node.js major version; the client package is only for the Step 3 test.
In package.json, set the module type and the scripts:
{
"name": "bestserp-mcp-server",
"type": "module",
"scripts": {
"build": "tsc",
"start": "node build/index.js",
"test": "node build/test-client.js"
}
}
Then create tsconfig.json, the configuration from the official tutorial. Keep "types": ["node"]: the SDK's package notes point out that TypeScript 6 and later no longer include @types/* automatically.
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"types": ["node"],
"outDir": "./build",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
We tested with these versions: @modelcontextprotocol/server 2.4.0, @modelcontextprotocol/client 2.4.0, zod 4.6.7 and TypeScript 7.0.2.
Step 2: Add the google_search and google_news tools
The code has two files: src/bestserp.ts calls the API and formats results, and src/index.ts defines the server and its tools.
Call BestSERP with polling and retries
A tool call should return results or a clear error within the time the client will wait. The TypeScript SDK's client gives up on a request after 60 seconds by default, so the server works to a 50-second deadline:
// BestSERP client for the MCP server: one search per call, with polling and retries.
const API = process.env.BESTSERP_API_BASE ?? "https://api.bestserp.com";
const DEADLINE_MS = 50_000; // the MCP SDK client gives up on a request after 60 s by default
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export async function bestserp(path: "/search" | "/news", params: object, apiKey: string) {
const deadline = Date.now() + DEADLINE_MS;
const headers = { "X-API-KEY": apiKey, "Content-Type": "application/json" };
const body = JSON.stringify({ ...params, timeout: 20 }); // answer 202 after 20 s, then we poll
for (let attempt = 1; ; attempt++) {
let res = await fetch(API + path, { method: "POST", headers, body, signal: AbortSignal.timeout(30_000) });
while (res.status === 202) { // still running: polling is free and not rate limited
const { requestId } = await res.json();
if (Date.now() + 2_000 > deadline) throw new Error(`still running (requestId ${requestId}), try again shortly`);
await sleep(2_000);
res = await fetch(`${API}/requests/${requestId}`, { headers, signal: AbortSignal.timeout(30_000) });
}
if (res.ok) return res.json();
// 429 is never charged; 502 and 503 are refunded. Retry them while there is time, nothing else.
const err = (await res.json().catch(() => ({}))).error ?? {};
const retryAfter = res.headers.get("Retry-After");
const waitMs = (res.status === 429 ? Number(retryAfter ?? 5) : Math.min(Number(retryAfter ?? 2), 5)) * 1_000;
const retry = [429, 502, 503].includes(res.status) && attempt < 3 && Date.now() + waitMs < deadline;
console.error(`BestSERP ${res.status} ${err.code ?? res.statusText} (attempt ${attempt}, Retry-After ${retryAfter ?? "-"})` +
(retry ? `, retrying in ${waitMs / 1000} s` : "")); // stderr: the client's log, never stdout
if (!retry) throw new Error(`HTTP ${res.status} ${err.code ?? ""}: ${err.message ?? res.statusText}`);
await sleep(waitMs);
}
}
Each status gets the treatment the error reference recommends:
| Status | Meaning | What the server does | Charged? |
|---|---|---|---|
202 |
Not finished within timeout |
Polls GET /requests/{requestId} every 2 seconds (async requests) |
When it succeeds, even if the tool stopped waiting |
429 |
Over 60 searches a minute | Waits Retry-After if that fits the deadline, otherwise reports it |
No |
502 |
Search failed (blocked or timed out) | Retries, up to 3 attempts | Refunded |
503 |
No capacity right now | Retries after Retry-After (at most 5 seconds) |
Refunded |
400, 401, 402 |
Bad request, bad key, no credits | Reports the error code to the model | No |
BESTSERP_API_BASE exists only for testing: we ran six cases (202 then 200, 503 then 200, 429 then 200, three 502s, a 401, and a 429 asking for 120 seconds) against a local mock before spending any credits. The live API needed the retries too: two of our test searches answered 502 Bad Gateway.
Return compact text, not raw JSON
Every character the model reads costs tokens, and a full response carries fields it does not need, such as favicons and display URLs. The formatter keeps position, title, location and snippet:
// Compact text for the model instead of the full JSON. Long Google links (google.com/goto redirects not yet
// resolved, news.google.com/rss/articles from the RSS fallback) are replaced by the domain: they work, but cost tokens.
const isGoogleRedirect = (url = "") => /^https?:\/\/(www\.|news\.)?google\.[a-z.]+\/(goto|url|rss\/articles)/.test(url);
const where = (r: any): string => (isGoogleRedirect(r.link) ? r.domain ?? "" : r.link ?? "");
const footer = (d: any) => `(${d.credits} credit${d.credits === 1 ? "" : "s"}, ${d.cached ? "cached" : "fresh"}, ${(d.durationMs / 1000).toFixed(1)} s)`;
export function formatSearch(d: any): string {
const p = d.searchParameters;
const lines = [`Google results for "${p.q}" (gl=${p.gl}, hl=${p.hl}):`];
for (const r of d.organic ?? []) {
lines.push(`${r.position}. ${r.title} | ${where(r) || r.source || "?"}`);
if (r.snippet) lines.push(` ${r.snippet}`);
}
if (!d.organic?.length) lines.push("No organic results.");
lines.push(footer(d));
return lines.join("\n");
}
formatNews does the same for news, with the publisher and publish time on each line (see Full code). Google serves many result links as redirects, and in our November 17, 2026 runs all 19 stayed redirects. Since November 18, BestSERP replaces them with final URLs by polling (in 61 searches through the public API, all 401 pending redirects within 54 seconds), but this server returns the first answer to stay inside its 50-second deadline, so many links are still redirects, and news from the RSS fallback always links to news.google.com. They work when clicked but cost up to a few hundred characters each, so the tool shows the domain or publisher instead, and prints the link whenever it is a final URL.
We measured the difference on two real responses (the script is measure.ts in the project):
| Tool | Results | Raw JSON | JSON without favicons | Compact text |
|---|---|---|---|---|
google_search |
9 | 11,517 characters | 5,422 | 2,080 (82% smaller) |
google_news |
10 | 12,266 characters | 6,624 | 2,772 (77% smaller) |

Small results also stay clear of client limits: Claude Code's MCP documentation says it warns when a tool's output passes 10,000 tokens and caps it at 25,000 tokens by default.
Register the two tools
src/index.ts checks the key, describes each tool's inputs with zod, and serves over stdio:
#!/usr/bin/env node
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";
import { bestserp, formatNews, formatSearch } from "./bestserp.js";
const API_KEY = process.env.BESTSERP_API_KEY ?? "";
if (!API_KEY) {
console.error("BESTSERP_API_KEY is not set: add it to the env block of your MCP client config.");
process.exit(1);
}
const q = z.string().min(1).max(256).describe("Search query, as you would type it into Google");
const gl = z.string().length(2).optional().describe("Country code: us, gb, de, vn... Default us");
const hl = z.string().min(2).max(7).optional().describe("Interface language: en, de, vi... Default en");
// Turn a search into a tool result; errors go back to the model as text with isError.
async function run(search: () => Promise<any>, format: (d: any) => string) {
try {
return { content: [{ type: "text" as const, text: format(await search()) }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Search failed: ${(e as Error).message}` }], isError: true };
}
}
function createServer() {
const server = new McpServer({ name: "bestserp-google-search", version: "1.0.0" });
server.registerTool(
"google_search",
{
title: "Google Search",
description:
"Search Google and get the live organic results: position, title, URL (or domain) and snippet. " +
"Use it for current facts, documentation and pages to cite. Costs 1 BestSERP credit per 10 results.",
inputSchema: z.object({
q, gl, hl,
num: z.literal([10, 20, 30, 40, 50]).optional().describe("Number of results. Default 10"),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ q, gl, hl, num }) => run(() => bestserp("/search", { q, gl, hl, num }, API_KEY), formatSearch),
);
// google_news is registered the same way (see Full code)
return server;
}
serveStdio(createServer, { onerror: (error) => console.error("MCP server error:", error) });
Four details matter:
- Descriptions are the model's only documentation. The SDK turns the zod schema into JSON Schema,
.describe()text included. The description also states the cost. - Optional fields stay out of the request. A missing
glorhlisundefined,JSON.stringifydrops it, and BestSERP's defaults apply (us,en). Unknown parameters are refused, so a typo fails loudly. - Errors go back to the model.
runreturnsisError: truewith the message, so the model can tell you what went wrong. serveStdioserves both protocol eras. Per the official tutorial, it answers 2026-07-28 clients and clients that still open with the 2025-erainitializehandshake. Our test checks both.
Build it with npm run build; the output lands in build/index.js.
Step 3: Test the server with an MCP client
Before touching any app's settings, test the server as a client sees it. This script starts the server over stdio with the SDK's client, lists the tools as a 2025-era and as a 2026-07-28 client, and calls both tools:
// Test the server like an MCP client would: start it over stdio, list the tools, call both.
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport, getDefaultEnvironment } from "@modelcontextprotocol/client/stdio";
async function connect(mode: "legacy" | "auto") {
const transport = new StdioClientTransport({
command: process.execPath, // the node binary running this script
args: ["build/index.js"],
// The child gets only a safe default environment, so pass the key explicitly.
env: { ...getDefaultEnvironment(), BESTSERP_API_KEY: process.env.BESTSERP_API_KEY ?? "" },
});
const client = new Client({ name: "bestserp-test-client", version: "1.0.0" }, { versionNegotiation: { mode } });
await client.connect(transport);
return client;
}
// 1. A 2025-era client (initialize handshake): list the tools only, no credits spent.
const legacy = await connect("legacy");
console.log(`legacy client: protocol ${legacy.getNegotiatedProtocolVersion()}, tools: ${(await legacy.listTools()).tools.map((t) => t.name).join(", ")}`);
await legacy.close();
// 2. A 2026-07-28 client (server/discover): list the tools with their inputs, then call both.
const client = await connect("auto");
const { tools } = await client.listTools();
console.log(`modern client: protocol ${client.getNegotiatedProtocolVersion()}, tool definitions: ${JSON.stringify(tools).length} characters`);
for (const tool of tools) {
console.log(`- ${tool.name}(${Object.keys(tool.inputSchema.properties ?? {}).join(", ")})`);
}
const calls = [
{ name: "google_search", arguments: { q: "model context protocol typescript sdk", gl: "us", hl: "en" } },
{ name: "google_news", arguments: { q: "model context protocol", recency: "week" } },
];
for (const call of calls) {
const started = Date.now();
const result = await client.callTool(call, { timeout: 90_000 });
const text = result.content.map((block) => (block.type === "text" ? block.text : `[${block.type}]`)).join("\n");
console.log(`\n> ${call.name} ${JSON.stringify(call.arguments)} (${((Date.now() - started) / 1000).toFixed(1)} s, isError: ${result.isError === true})`);
console.log(text);
}
await client.close();
Note the env line. The SDK's stdio transport does not hand your whole environment to the server, only a short list of variables considered safe (getDefaultEnvironment()). Without the explicit key, the server exits with its "not set" message. The app configurations in Step 4 pass the key the same explicit way.
Set the key in your shell, build, and run (in PowerShell, use $env:BESTSERP_API_KEY = "YOUR_API_KEY"):
export BESTSERP_API_KEY="YOUR_API_KEY"
npm run build
npm test
Our output on November 17, 2026, trimmed where marked:
legacy client: protocol 2025-11-25, tools: google_search, google_news
modern client: protocol 2026-07-28, tool definitions: 1728 characters
- google_search(q, gl, hl, num)
- google_news(q, gl, hl, recency)
> google_search {"q":"model context protocol typescript sdk","gl":"us","hl":"en"} (4.2 s, isError: false)
Google results for "model context protocol typescript sdk" (gl=us, hl=en):
1. Activity · modelcontextprotocol/typescript-sdk | github.com
The official TypeScript SDK for Model Context Protocol servers and clients - Activity · modelcontextprotocol/typescript-sdk.
2. for the - modelcontextprotocol/typescript-sdk | gitmcp.io
Connect your AI assistant · Copy the following JSON configuration: · Go to Msty Studio > Tools > 'Import Tools from JSON Clipboard'.Read more
3. Building a TypeScript MCP Server with Tools, Resources, ... | pub.towardsai.net
Jun 24, 2026 — MCP (Model Context Protocol) is the open standard that gives AI Agents structured access to tools, data, and services. It is the protocol ...Read more
[results 4 to 9 trimmed]
(1 credit, fresh, 3.8 s)
> google_news {"q":"model context protocol","recency":"week"} (0.2 s, isError: false)
Google News for "model context protocol" (gl=us, hl=en, past week):
1. Lab Thread launches Model Context Protocol server | Scientist Live | 2026-11-13T12:05:57+00:00
www.scientistlive.com
2. Build a data foundation for agentic AI on AWS: From lakehouse to MCP | Amazon Web Services (AWS) | 2026-11-11T21:03:43+00:00
aws.amazon.com
[results 3 to 10 trimmed]
Note: from the Google News RSS feed (ranking differs from the News tab).
(1 credit, cached, 0.0 s)
What the runs showed:
- Both protocol eras work. The older client negotiated
2025-11-25, the newer one2026-07-28, and both saw the same two tools. - The tool definitions are small: 1,728 characters for both tools, schemas and descriptions included. A client typically sends them to the model with every request.
- Search took about 4 seconds: 4.2 to 4.8 seconds across three successful
google_searchcalls. - News timing varied: 3.0 and 6.0 seconds from the News tab, 17.1 seconds when BestSERP fell back to the Google News RSS feed (
origin: google_news_rssin the news API reference, flagged by the note in the output). The run above repeated a news search within 5 minutes, so it came from cache in 0.2 seconds and still cost 1 credit.
Step 4: Connect it to Claude Desktop, Claude Code and Cursor
All three apps start the server with node and the absolute path to build/index.js, and pass the key in an env block. The snippets follow each product's official documentation as of November 17, 2026; we tested the server with the SDK client above, not inside these apps, so check the linked page if a menu has moved.
Claude Desktop
Open the Claude menu, then Settings > Developer > Edit Config. The file is claude_desktop_config.json, in ~/Library/Application Support/Claude/ on macOS and %APPDATA%\Claude\ on Windows, per the guide to connecting local MCP servers. Add the server under mcpServers:
{
"mcpServers": {
"bestserp": {
"command": "node",
"args": ["/ABSOLUTE/PATH/TO/bestserp-mcp/build/index.js"],
"env": {
"BESTSERP_API_KEY": "YOUR_API_KEY"
}
}
}
}
On Windows, write the path with doubled backslashes: "C:\\Users\\you\\bestserp-mcp\\build\\index.js". Quit Claude Desktop completely and start it again; the server then appears under Connectors in the "Add files, connectors, and more" menu of the message box. Its stderr, retry lines included, goes to mcp-server-bestserp.log in ~/Library/Logs/Claude (macOS) or %APPDATA%\Claude\logs (Windows).
Claude Code
One command, following the stdio example in Claude Code's MCP documentation:
claude mcp add --env BESTSERP_API_KEY=YOUR_API_KEY --transport stdio bestserp \
-- node /absolute/path/to/bestserp-mcp/build/index.js
Everything after -- starts the server. Keep another option, such as --transport stdio, between --env and the server name, or the CLI reads the name as a second variable. The default local scope stores the entry in ~/.claude.json for the current project only; check it with claude mcp list, or /mcp in a session.
To share the server with a team, put it in .mcp.json at the project root and let each developer's key come from their own environment with the documented ${VAR} expansion:
{
"mcpServers": {
"bestserp": {
"type": "stdio",
"command": "node",
"args": ["/absolute/path/to/bestserp-mcp/build/index.js"],
"env": {
"BESTSERP_API_KEY": "${BESTSERP_API_KEY}"
}
}
}
}
Cursor
Cursor reads .cursor/mcp.json in a project, or ~/.cursor/mcp.json for all projects. Cursor's MCP documentation uses the same mcpServers object, and its ${env:NAME} syntax reads a variable from your environment, keeping the key out of the file:
{
"mcpServers": {
"bestserp": {
"command": "node",
"args": ["/absolute/path/to/bestserp-mcp/build/index.js"],
"env": {
"BESTSERP_API_KEY": "${env:BESTSERP_API_KEY}"
}
}
}
}
By default, Cursor asks for approval before it runs an MCP tool. In any of the three apps, try a prompt that needs fresh information: "Search Google for the current version of the MCP TypeScript SDK and cite your sources."
Common problems and fixes
Most problems show up in the app's MCP log or as the tool's error text, which the model usually repeats to you. The messages below are the server's real output.
| Problem | Cause | Fix |
|---|---|---|
| The server does not appear, or "failed to connect" | Relative path, or build/ missing |
Use the absolute path to build/index.js, run npm run build, restart the app |
| Log says "BESTSERP_API_KEY is not set" and the server exits | No env block, or the referenced variable is unset |
Add the key to env, or set the variable before launching the app |
| Tool answers "HTTP 401 invalid_api_key: Invalid or revoked API key" | Wrong, truncated or revoked key | Create a new key under Dashboard > API keys |
| Tool answers "HTTP 402 insufficient_credits" | Balance too low for the request | Top up on the pricing page, or lower num |
| Tool answers "HTTP 429 rate_limited" | More than 60 searches in a minute, all keys together | Wait a minute; the rate limits page explains how to ask for more |
| The app reports parse errors or the server disconnects | Something writes to stdout | Log with console.error only |
| Tool answers "still running (requestId ...)" | The search took longer than 50 seconds | Ask the model to run the search again |
Full code
The server is two files; with package.json, tsconfig.json and the Step 3 test client, that is the whole project.
src/index.ts:
#!/usr/bin/env node
// Google search MCP server: google_search and google_news tools backed by the BestSERP API.
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";
import { bestserp, formatNews, formatSearch } from "./bestserp.js";
const API_KEY = process.env.BESTSERP_API_KEY ?? "";
if (!API_KEY) {
console.error("BESTSERP_API_KEY is not set: add it to the env block of your MCP client config.");
process.exit(1);
}
const RECENCY = { hour: "qdr:h", day: "qdr:d", week: "qdr:w", month: "qdr:m", year: "qdr:y" } as const;
const q = z.string().min(1).max(256).describe("Search query, as you would type it into Google");
const gl = z.string().length(2).optional().describe("Country code: us, gb, de, vn... Default us");
const hl = z.string().min(2).max(7).optional().describe("Interface language: en, de, vi... Default en");
// Turn a search into a tool result; errors go back to the model as text with isError.
async function run(search: () => Promise<any>, format: (d: any) => string) {
try {
return { content: [{ type: "text" as const, text: format(await search()) }] };
} catch (e) {
return { content: [{ type: "text" as const, text: `Search failed: ${(e as Error).message}` }], isError: true };
}
}
function createServer() {
const server = new McpServer({ name: "bestserp-google-search", version: "1.0.0" });
server.registerTool(
"google_search",
{
title: "Google Search",
description:
"Search Google and get the live organic results: position, title, URL (or domain) and snippet. " +
"Use it for current facts, documentation and pages to cite. Costs 1 BestSERP credit per 10 results.",
inputSchema: z.object({
q,
gl,
hl,
num: z.literal([10, 20, 30, 40, 50]).optional().describe("Number of results. Default 10"),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ q, gl, hl, num }) => run(() => bestserp("/search", { q, gl, hl, num }, API_KEY), formatSearch),
);
server.registerTool(
"google_news",
{
title: "Google News",
description:
"Search the Google News tab: headline, publisher, publish time, snippet and link. " +
"Use it for recent events. Costs 1 BestSERP credit per call.",
inputSchema: z.object({
q,
gl,
hl,
recency: z.enum(["hour", "day", "week", "month", "year"]).optional().describe("Only news from the past hour, day, week, month or year"),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ q, gl, hl, recency }) =>
run(() => bestserp("/news", { q, gl, hl, tbs: recency && RECENCY[recency] }, API_KEY), (d) => formatNews(d, recency)),
);
return server;
}
serveStdio(createServer, { onerror: (error) => console.error("MCP server error:", error) });
console.error("BestSERP Google search MCP server running on stdio"); // stderr: stdout carries the protocol
src/bestserp.ts is the bestserp() function and the formatter from Step 2, plus the news formatter:
export function formatNews(d: any, recency?: string): string {
const p = d.searchParameters;
const lines = [`Google News for "${p.q}" (gl=${p.gl}, hl=${p.hl}${recency ? `, past ${recency}` : ""}):`];
for (const r of d.news ?? []) {
lines.push(`${r.position}. ${r.title} | ${r.source ?? r.domain ?? "?"} | ${r.publishedAt ?? r.date ?? "date unknown"}`);
if (r.snippet) lines.push(` ${r.snippet}`);
if (where(r)) lines.push(` ${where(r)}`);
}
if (!d.news?.length) lines.push("No news results.");
if (d.news?.some((r: any) => r.origin === "google_news_rss")) lines.push("Note: from the Google News RSS feed (ranking differs from the News tab).");
lines.push(footer(d));
return lines.join("\n");
}
The news formatter prints publishedAt, an ISO 8601 time, when it is known, rather than "2 hours ago", because the model does not know when the search ran.
Security and cost
A Google search MCP server holds a key that spends money and feeds third-party text to a model. Both deserve thought before you share it.
Keep the key in the client's environment, not in code. The server reads BESTSERP_API_KEY from its environment and nowhere else. Put the key in the app's env block or, better, reference a variable (${env:BESTSERP_API_KEY} in Cursor, ${BESTSERP_API_KEY} in Claude Code's .mcp.json), so a config file committed to Git holds no secret. The server's logs print status codes, never the key. Create a separate key for the MCP server so you can revoke it without breaking other jobs.
Treat results as untrusted input. Titles and snippets are written by page owners, and a page can contain text aimed at the model ("ignore your instructions and..."). Both tools are read-only and say so in their annotations, so through them a manipulated model can only spend credits. Keep approval prompts on for tools in the same session that write files, send messages or run commands.
Each tool call costs one search. The numbers, from the pricing page as of November 2026:
google_searchcosts 1 credit for 10 results, up to 5 credits fornum: 50.google_newscosts 1 credit.- After the 3,000 free searches, credits cost $0.50 per 1,000, so 1,000 tool calls cost $0.50. Purchased credits never expire.
- Failed searches (
502) and busy answers (503) are refunded. Refused requests (400,401,402,429) are never charged. - Cached answers (an identical search within 1 hour, 5 minutes for news) cost the same as fresh ones.
- The rate limit is 60 searches per minute per account, shared by all keys. An agent firing many parallel searches can reach it; the server then waits for
Retry-Afterwhen the wait fits its deadline.
| Usage | Tool calls per month | Cost at $0.50 per 1,000 |
|---|---|---|
| One developer, about 20 searches a day | 600 | $0.30 |
| A team of 10, about 50 searches each per workday | 11,000 | $5.50 |
| An agent making 2,000 searches a day | 60,000 | $30 |
The footer of every result ("1 credit, fresh, 3.8 s") keeps the spend visible in the conversation, so you notice when a model searches more than the task needs.
Next steps
You now have a Google search MCP server that any MCP client can start, with two read-only tools, sensible retries and a key that never touches the code. Where to go next:
- The bigger picture: web search for AI agents covers grounding, cost per answer and prompt injection in more depth, and the AI agents use case shows what teams build with the API.
- Your own agent loop instead of an MCP app: the Google search tool for LLM agents tutorial builds the same tool for a Python agent.
- When snippets are not enough: search API vs headless browser compares the two ways an agent can get web data.
For news-heavy assistants, see the Google News API page.