Skip to main content
Glama
serper-search-mcp-server

serper-search-mcp-server

README.md
<div align="center">

# πŸ” Serper Search MCP Server v4.1

**The First Universal Search Gateway for AI Agents β€” Google (Serper), Tavily, Brave, Exa, and Firecrawl with auto-failover, 15 tools, and token-smart verbosity.**

[![npm version](https://img.shields.io/npm/v/serper-search-mcp?color=blue&logo=npm)](https://www.npmjs.com/package/serper-search-mcp)
[![npm downloads](https://img.shields.io/npm/dt/serper-search-mcp?color=brightgreen&label=npm%20downloads)](https://www.npmjs.com/package/serper-search-mcp)
[![Docker Pulls](https://img.shields.io/docker/pulls/smjahid/server-serper-search?logo=docker)](https://hub.docker.com/r/smjahid/server-serper-search)
[![Tools](https://img.shields.io/badge/Tools:%2015-blue)](#tool-reference)
[![Node](https://img.shields.io/node/v/serper-search-mcp)](https://www.npmjs.com/package/serper-search-mcp)
[![AI agents: Ready(Claude,Codex..)](https://img.shields.io/badge/AI%20agents:%20Ready(Claude,Codex..)-7B61FF?logo=bot&logoColor=white)](https://modelcontextprotocol.io)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
[![MCP](https://img.shields.io/badge/Protocol-MCP-purple)](https://modelcontextprotocol.io)

</div>

---

## What this does

This MCP server wraps the [Serper API](https://serper.dev) (Google Search results) and exposes **15 tools** that any MCP-compatible AI client (Claude, Cursor, Windsurf, KiloCode, n8n, etc.) can call in real time β€” including web, image, video, news, shopping, places, scholar, patents, autocomplete, full-page scraping, and batch search.

| Tool | What you get |
|---|---|
| `search` ⭐ | Unified search `{type, provider, verbosity}` β€” 1 schema (~700 tokens vs ~7k for all) |
| `search_web` | Organic results + **Knowledge Graph** + **Answer Box** + "People Also Ask" + Related Searches |
| `search_images` | Image URLs, thumbnails, dimensions, source pages + `gallery` layout + `size/orientation/site` (size/orientation filter client-side via WΓ—H) |
| `search_videos` | Titles, channels, durations, links |
| `search_news` | Headlines, sources, dates β€” freshness-filtered |
| `search_shopping` | Products, prices, ratings, delivery info (always rich) |
| `search_places` | Local businesses & POIs with address, phone, **full 7-day hours**, GPS + Directions (always rich) |
| `search_scholar` πŸ†• | Academic papers with authors, journal, year, and citation counts |
| `search_patents` πŸ†• | Patents with publication number, assignee, inventor, dates |
| `autocomplete` πŸ†• | Query completions β€” cheap, no LLM needed |
| `scrape` πŸ†• | Full page content as markdown β€” read articles found via search |
| `search_many` πŸ†• | 1–10 parallel web searches with automatic cross-query dedupe |
| `deep_research` | Multi-step research: auto sub-queries β†’ parallel searches β†’ LLM-synthesized cited report |
| `search_rag_context` | Clean chunked text with metadata for embedding pipelines & vector DBs β€” no LLM needed |
| `resolve_links` πŸ†• | Turn `google.com/goto` redirect links from a search into real URLs (free, 0 credits) |

### Verbosity (token-smart, auto by default)

| Mode | Who | What | Tokens |
|---|---|---|---|
| `auto` (default) | server picks | dev→compact, chat→standard, scholar/research→full, places/shopping/images→always rich | varies |
| `compact` | dev coding | title+URL+1-line snippet, no KG/PAA/Related | ~800 |
| `standard` | normal chat | KG + Answer Box + 10 organic | ~4k |
| `full` | researcher | everything + citations | ~5k |

> Credit rule: `compact` fetches `num=5` (never fetch-10-show-3). 1 search = 1 credit (1–10 results; >10 = 2), cache hit = 0, scrape = 2 **per page** (verified live β€” same with or without `include_images`; scrape chains multiply). `deep_research`: basic 3cr / standard 5cr / deep 8cr.

### Providers (universal gateway β€” auto-failover)

| Provider | Cost per 1k | When to use |
|---|---|---|
| **Serper** (default) | $3-5, 2500 free/mo | Cheapest Google truth β€” keep first |
| **Tavily** fallback | $8-16 | AI-reranked, finance/news topics |
| **Brave** fallback | $5 | Independent index, private, 669ms |
| **Exa** fallback | $4-7 | Neural semantic when keywords fail |
| **Firecrawl** fallback | ~$3-4 eff | JS-rendered scraping & search upgrade |

```bash
SEARCH_PROVIDER_ORDER=serper,tavily,brave,exa  # failover chain
SEARCH_FALLBACK=true                           # on 402/429/5xx/empty
```

### CLI (dev power-tool β€” 4-32x cheaper than MCP schemas)

```bash
npx serper-search-mcp search "react server components" --compact --limit 5
npx serper-search-mcp scrape https://example.com --max-chars 8000
npx serper-search-mcp research "RAG limits" --depth basic
npx serper-search-mcp rag "transformer" --format json
npx serper-search-mcp providers --status
```

> **Free to start:** Serper gives you 2,500 free queries/month. No credit card required.

---

## Quick start

### πŸ”‘ Provider Keys & Universal Gateway Configuration

This server functions as a **Universal Search Gateway**. Only `SERPER_API_KEY` is required. You can add any combination of the other 4 search providers and LLM keys to enable automatic multi-provider failover, semantic search, and scraping upgrades:

| Variable | Provider / Purpose | Default / Priority |
|---|---|---|
| `SERPER_API_KEY` | **Serper** (Google Search baseline) | **Required** ([serper.dev](https://serper.dev)) |
| `TAVILY_API_KEY` | **Tavily** (AI-reranked fallback) | Optional ([tavily.com](https://tavily.com)) |
| `BRAVE_API_KEY` | **Brave** (Independent web index fallback) | Optional ([brave.com/search/api](https://brave.com/search/api)) |
| `EXA_API_KEY` | **Exa** (Neural semantic search fallback) | Optional ([exa.ai](https://exa.ai)) |
| `FIRECRAWL_API_KEY` | **Firecrawl** (JS-rendered scraping & search upgrade) | Optional ([firecrawl.dev](https://firecrawl.dev)) |
| `OPENROUTER_API_KEY` | LLM for `deep_research` | Optional (takes priority over Gemini) |
| `GEMINI_API_KEY` | LLM for `deep_research` | Optional (used when OpenRouter is absent) |

#### Failover Control:
```bash
SEARCH_PROVIDER_ORDER=serper,tavily,brave,exa  # custom failover priority chain
SEARCH_FALLBACK=true                           # auto-failover on 402/429/5xx/empty (default: true)
```

---

### Option 1 β€” npx (MCP Client Configuration)

Add this to your MCP client config file (Claude Desktop, Cursor, Windsurf, KiloCode).

#### 🌟 Full Universal Gateway Config (All 5 Providers + Failover):
```json
{
  "mcpServers": {
    "serper-search": {
      "command": "npx",
      "args": ["-y", "serper-search-mcp"],
      "env": {
        "SERPER_API_KEY": "${SERPER_API_KEY}",
        "TAVILY_API_KEY": "${TAVILY_API_KEY}",
        "BRAVE_API_KEY": "${BRAVE_API_KEY}",
        "EXA_API_KEY": "${EXA_API_KEY}",
        "FIRECRAWL_API_KEY": "${FIRECRAWL_API_KEY}",
        "OPENROUTER_API_KEY": "${OPENROUTER_API_KEY}",
        "SEARCH_PROVIDER_ORDER": "serper,tavily,brave,exa",
        "SEARCH_FALLBACK": "true"
      }
    }
  }
}
```

*(You can omit any provider keys you don't use; the server automatically detects configured providers and skips unconfigured ones).*

#### Minimal Config (Serper Only):
```json
{
  "mcpServers": {
    "serper-search": {
      "command": "npx",
      "args": ["-y", "serper-search-mcp"],
      "env": {
        "SERPER_API_KEY": "your_serper_key_here"
      }
    }
  }
}
```

---

### Option 2 β€” Docker

```bash
docker run -i --rm \
  -e SERPER_API_KEY \
  -e TAVILY_API_KEY \
  -e BRAVE_API_KEY \
  -e EXA_API_KEY \
  -e FIRECRAWL_API_KEY \
  -e OPENROUTER_API_KEY \
  smjahid/server-serper-search:4
```

For HTTP mode (remote server or cloud):
```bash
docker run --rm -p 8080:8080 \
  -e SERPER_API_KEY \
  -e SERPER_MCP_TRANSPORT=http \
  -e SERPER_MCP_HOST=0.0.0.0 \
  -e SERPER_MCP_AUTH_TOKEN="your_secure_bearer_token" \
  smjahid/server-serper-search:4
```

---

### Option 3 β€” Shell & CLI (PowerShell / Bash / CMD)

**PowerShell (Windows):**
```powershell
$env:SERPER_API_KEY = "your_key"
$env:TAVILY_API_KEY = "your_key"      # optional
$env:OPENROUTER_API_KEY = "your_key"  # optional
node index.js
```

**Bash / macOS / Linux:**
```bash
export SERPER_API_KEY="your_key"
export TAVILY_API_KEY="your_key"      # optional
export OPENROUTER_API_KEY="your_key"  # optional
node index.js
```

**Windows Command Prompt:**
```bat
set SERPER_API_KEY=your_key
node index.js
```

> **AI-powered research runs on your own LLM key.** `deep_research` uses Gemini's free tier when `GEMINI_API_KEY` is set (OpenRouter takes priority if both are set β€” see the env table above).

---

## Config file locations

| Client | Config path |
|---|---|
| **Claude Desktop (Mac)** | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| **Claude Desktop (Win)** | `%APPDATA%\Claude\claude_desktop_config.json` |
| **Cursor** | `~/.cursor/mcp.json` |
| **Windsurf** | `~/.codeium/windsurf/mcp_config.json` |
| **KiloCode** | `~/.config/kilo/kilo.json` (global) or `<project>/kilo.json` (project) |
| **n8n** | MCP Client node β†’ Server URL |

---

## Tool reference

### `search_web`

Google web search with the full SERP breakdown.

```jsonc
{
  "query":       "best mechanical keyboards 2025",   // required
  "num_results": 10,        // 1–20, default 10
  "country":     "US",      // ISO 3166-1 alpha-2
  "search_lang": "en",      // language code
  "freshness":   "pw",      // "pd" day Β· "pw" week Β· "pm" month Β· "py" year Β· "any" no filter
  "safesearch":  "moderate",// "off" Β· "moderate" Β· "strict"
  "autocorrect": true,
  "page":        1,         // pagination
  "link_resolution": "auto" // "auto" Β· "all" Β· "none" β€” see Google redirect links below
}
```

**Response includes:**
- 🎯 **Answer Box** β€” direct answer when available
- 🧠 **Knowledge Graph** β€” entity info (type, description, rating, website, attributes)
- 🌐 **Organic results** β€” title, URL, snippet, sitelinks, date
- πŸ’¬ **People Also Ask** β€” up to 4 follow-up questions with answers
- πŸ”— **Related Searches** β€” up to 6 suggestions
- ⏱️ **Time filter** β€” footer echoes the applied `freshness` (or `none (all time)`) so agents know why results look thin

> **No AI summary on this tool.** For a synthesized answer in ONE call use `deep_research` (full report, 3–8 credits + LLM) or `search_rag_context` (chunked evidence, 1 credit, no LLM). For **latest/current** results pass `freshness` (`py`, `pw`, …) β€” the footer confirms it was applied. Avoid `search β†’ scrape β†’ scrape` chains: every scrape costs 2 credits.

---

### `search_images`

```jsonc
{
  "query":       "minimalist desk setup",
  "num_results": 10,
  "country":     "US",
  "safesearch":  "moderate"
}
```

Returns: image URL, thumbnail, dimensions (width Γ— height), source domain, source page URL.

---

### `search_videos`

```jsonc
{
  "query":       "react server components tutorial",
  "num_results": 5,
  "freshness":   "pm"
}
```

Returns: title, channel, duration, publish date, video URL.

---

### `search_news`

```jsonc
{
  "query":       "OpenAI GPT-5 release",
  "num_results": 10,
  "freshness":   "pd",   // default is past day for news; pass "any" for historical news (or use after:/before: operators in the query)
  "country":     "US"
}
```

Returns: headline, source publication, date, snippet, URL.

---

### `search_shopping`

```jsonc
{
  "query":       "Sony WH-1000XM5 headphones",
  "num_results": 8,
  "country":     "US"
}
```

Returns: product name, price, seller, star rating + review count, delivery info, product URL.

---

### `search_places` ⭐ unique to this server

```jsonc
{
  "query":       "ramen restaurants in Shibuya Tokyo",
  "num_results": 5,
  "country":     "JP"
}
```

Returns: business name, category, address, phone, website, star rating + review count, opening hours, GPS coordinates + Google Maps link.

**Example use cases:**
- "Find the top-rated coffee shops near Times Square"
- "What dentists are open on Sundays in Austin TX?"
- "List coworking spaces in Dhaka"

---

### `search_scholar` πŸ†• v4.0.0

Google Scholar search for academic literature.

```jsonc
{
  "query":       "attention is all you need",
  "num_results": 10,
  "freshness":   "py",   // optional year filter β€” useful for recent literature
  "country":     "US"
}
```

Returns: title, link, authors/journal/year (`publicationInfo`), snippet, and citation count.

---

### `scrape` πŸ†• v4.0.0

Fetch the full contents of a single URL (Serper Scrape API β€” `scrape.serper.dev`).

```jsonc
{
  "url":              "https://example.com/article",  // required
  "include_markdown": true,       // default true β€” markdown rendering
  "include_images":   false,
  "include_links":    false,
  "include_videos":   false,
  "max_chars":        50000       // 1000–200000, default 50000
}
```

Returns the page as markdown (falls back to plain text), truncated for context safety. **Costs 2 credits per page** (verified live β€” `include_images` does not change the price). Before scraping: prefer `search_rag_context` (1 credit, no LLM) or `deep_research` for synthesized answers; if you do scrape, chain only 1–3 pages β€” each page is 2 credits.

---

### `search_many` πŸ†• v4.0.0

Run 1–10 web searches in one call, in parallel.

```jsonc
{
  "queries":     ["react server components", "vue server components", "sveltekit ssr"],
  "num_results": 5,
  "country":     "US"
}
```

Duplicate URLs across queries are removed automatically; per-query failures are reported inline without failing the batch. One credit per query.

---

### Google redirect links & `resolve_links` πŸ†•

Since 2026-10-30, Serper may return Google result links beyond the top 3 as `https://www.google.com/goto?url=…` redirects. Opening one right after the search lands on Google's "Verifying your request" page instead of the site. Serper's free `/resolve` endpoint turns them back into real URLs ([serper.dev/google-links](https://serper.dev/google-links)).

`search`, `search_web`, `search_images`, `search_videos`, `search_news`, `search_shopping` and `search_rag_context` take a `link_resolution` parameter:

| Mode | Behaviour |
|---|---|
| `auto` (default) | Serper's default: top 3 resolved. If the shown results still contain redirect links, the output says how many and gives a `search_id`. |
| `all` | Also calls `/resolve` before returning. Free, but adds ~20–30 s when redirect links are present. |
| `none` | Sends `resolveLinks: false`: fastest, links exactly as Google returns them. |

`resolve_links` resolves a search later by `search_id` (the last 50 searches with redirect links are kept in memory) or from a list of goto links:

```jsonc
{ "search_id": "Xq3v…" }                                 // re-renders that search with real URLs
{ "links": ["https://www.google.com/goto?url=…"], "max_wait_seconds": 60 }
```

Links that are not ready yet stay goto links and Serper suggests a wait (often 90 s); it is honoured only if it fits in `max_wait_seconds`. `/resolve` failures never fail a search: the original results are kept and the error is shown. `deep_research` resolves its sources before building the prompt and lists any citation that is still a redirect.

---

## Environment variables

### Search Providers & Universal Gateway

| Variable | Required | Default | Description |
|---|---|---|---|
| `SERPER_API_KEY` | βœ… | β€” | Primary search provider key ([serper.dev](https://serper.dev) β€” 2,500 free queries/mo) |
| `TAVILY_API_KEY` | ❌ | β€” | Tavily fallback provider key ([tavily.com](https://tavily.com) β€” AI-reranked search) |
| `BRAVE_API_KEY` | ❌ | β€” | Brave Search fallback provider key ([brave.com/search/api](https://brave.com/search/api) β€” independent index) |
| `EXA_API_KEY` | ❌ | β€” | Exa neural search fallback key ([exa.ai](https://exa.ai) β€” semantic search & highlights) |
| `FIRECRAWL_API_KEY` | ❌ | β€” | Firecrawl JS-rendered scraping & search upgrade key ([firecrawl.dev](https://firecrawl.dev)) |
| `SEARCH_PROVIDER_ORDER` | ❌ | `serper,tavily,brave` | Comma-separated failover priority chain (`serper,tavily,brave,exa,firecrawl`) |
| `SEARCH_FALLBACK` | ❌ | `true` | Auto-failover on 402/429/5xx/empty response (`true` or `false`) |

### Server & Transport

| Variable | Required | Default | Description |
|---|---|---|---|
| `SERPER_MCP_TRANSPORT` | ❌ | `stdio` | MCP transport mode: `stdio` (local AI clients) or `http` (stateless Streamable HTTP) |
| `SERPER_MCP_PORT` | ❌ | `8080` | Port for HTTP transport mode (1–65535) |
| `SERPER_MCP_HOST` | ❌ | `127.0.0.1` | Host interface to bind for HTTP mode (non-loopback requires `SERPER_MCP_AUTH_TOKEN`) |
| `SERPER_MCP_AUTH_TOKEN` | ❌ | β€” | Bearer token for HTTP `/mcp` (`Authorization: Bearer <token>`); required off-loopback |
| `SERPER_MCP_INSECURE_NO_AUTH` | ❌ | `false` | `true` allows binding a non-loopback host without a token (use only behind an authenticating reverse proxy) |
| `SERPER_MCP_ALLOWED_HOSTS` | ❌ | β€” | Comma-separated extra `Host` values accepted on `/mcp` when bound to loopback (DNS-rebinding protection allows `127.0.0.1`/`localhost`/`::1` by default; add your reverse-proxy domain here) |
| `SERPER_MCP_LOG_LEVEL` | ❌ | `info` | Logging verbosity: `error` · `warn` · `info` · `debug` · `silent` |

### Cache & Resilience Tuning

| Variable | Required | Default | Description |
|---|---|---|---|
| `SERPER_CACHE_TTL_MS` | ❌ | `600000` | Search-result cache TTL in ms (`0` disables the cache) |
| `SERPER_CACHE_MAX` | ❌ | `200` | Maximum cached responses (LRU eviction) |
| `SERPER_TIMEOUT_MS` | ❌ | `30000` | Per-request timeout for Serper calls in ms |
| `SERPER_RETRIES` | ❌ | `2` | Retries on 429 / 5xx / network errors (honors `Retry-After`) |
| `SERPER_RETRY_BASE_MS` | ❌ | `500` | Base backoff delay in ms (exponential backoff + jitter) |
| `SERPER_CACHE_PERSIST` | ❌ | `false` | `true` persists the search/scrape cache to disk (0600 files, 0700 dir, scoped per API key) |
| `SERPER_CACHE_DIR` | ❌ | `~/.serper-cache` | Directory for the persisted cache files |
| `SERPER_LINK_RESOLUTION` | ❌ | `auto` | Default `link_resolution` mode: `auto` · `all` · `none` |
| `SERPER_RESOLVE_MAX_WAIT` | ❌ | `60` | Seconds `/resolve` may keep retrying when Serper says to wait |

### Deep Research LLM Synthesis

| Variable | Required | Default | Description |
|---|---|---|---|
| `OPENROUTER_API_KEY` | ❌ | β€” | LLM key for `deep_research` synthesis (free tier at [openrouter.ai](https://openrouter.ai)) |
| `OPENROUTER_MODEL` | ❌ | `google/gemini-3.1-flash-lite:free` | OpenRouter model override |
| `GEMINI_API_KEY` | ❌ | β€” | LLM key for `deep_research` synthesis (free tier at [ai.google.dev](https://ai.google.dev)) |
| `GEMINI_MODEL` | ❌ | `gemini-3.1-flash-lite` | Gemini model override |
| `SERPER_LLM_TIMEOUT_MS` | ❌ | `120000` | Per-request timeout for LLM synthesis calls in ms |
| `SERPER_LLM_RETRIES` | ❌ | `2` | Retries for LLM calls on rate-limit or network errors |

---

## HTTP transport (remote / Docker)

Run as a stateless Streamable HTTP server (this is also how the Docker image runs):

```bash
npx serper-search-mcp --transport http --port 8080
# or via env: SERPER_MCP_TRANSPORT=http SERPER_MCP_PORT=8080 npx serper-search-mcp
```

- MCP endpoint: `POST http://localhost:8080/mcp`
- Health probe: `GET http://localhost:8080/health`

Point any Streamable HTTP capable MCP client at `http://<host>:8080/mcp`.

### Optional bearer auth

Set `SERPER_MCP_AUTH_TOKEN` (or `--auth-token`) to require authentication on `/mcp`:

```bash
SERPER_MCP_AUTH_TOKEN=secret npx serper-search-mcp --transport http --port 8080
```

```bash
curl -X POST http://localhost:8080/mcp \
  -H "Authorization: Bearer secret" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```

Requests without the token get `401`. `/health` stays unauthenticated for load balancers and reports `auth_required`.

---

## Example prompts

Once connected to any MCP client:

```
Search for the latest news about Claude 4 and summarize the key points.

Find me 5 Italian restaurants in Warsaw with their ratings and phone numbers.

What is the current price of the MacBook Pro M4 on Google Shopping?

Search for YouTube tutorials on building agentic AI systems published this month.

Find images of brutalist architecture in Eastern Europe.
```

---

---

## `deep_research`

Runs multi-step AI research using your own LLM key. No LLM data leaves your environment.

**Requires:** `OPENROUTER_API_KEY` (free models at [openrouter.ai](https://openrouter.ai)) or `GEMINI_API_KEY` (free at [aistudio.google.com](https://aistudio.google.com))

```jsonc
{
  "query": "What are the real-world limitations of RAG systems in production?",
  "depth": "standard",  // "basic" | "standard" | "deep"
  "country": "US"
}
```

| Depth | Sub-queries | Results each | Best for |
|---|---|---|---|
| `basic` | 3 | 3 | Quick overviews |
| `standard` | 5 | 5 | Most use cases |
| `deep` | 8 | 5 | Exhaustive research |

**Output:** Structured markdown report with inline citations + Sources section.

**Supported LLMs via env (all vars documented in the [table above](#environment-variables)):**

| Provider | Variable | Default |
|---|---|---|
| OpenRouter | `OPENROUTER_API_KEY` | β€” |
| | `OPENROUTER_MODEL` | `google/gemini-3.1-flash-lite:free` |
| Google Gemini | `GEMINI_API_KEY` | β€” |
| | `GEMINI_MODEL` | `gemini-3.1-flash-lite` |

---

## `search_rag_context`

Turns Google search results into embedding-ready chunks. No LLM needed β€” pure text processing.

```jsonc
{
  "query":           "transformer architecture explained",
  "num_results":     10,
  "freshness":       "py",     // optional: pd/pw/pm/py/any β€” omitted = all time
  "max_chunk_words": 200,
  "include_paa":     true,
  "output_format":   "json"   // "json" or "text"
}
```

**JSON output** (for vector DB ingestion):
```json
{
  "query": "transformer architecture explained",
  "total_sources": 10,
  "total_chunks": 24,
  "total_words": 4231,
  "chunks": [
    {
      "chunk_index": 0,
      "source_index": 1,
      "title": "Attention Is All You Need",
      "url": "https://arxiv.org/abs/1706.03762",
      "domain": "arxiv.org",
      "date": "2024-01-15",
      "text": "The transformer architecture uses self-attention mechanisms...",
      "word_count": 198,
      "char_count": 1124
    }
  ]
}
```

**Text output** (for direct prompt injection):
```
--- Chunk 1 | Source 1 | arxiv.org | 2024-01-15 ---
Title: Attention Is All You Need
URL: https://arxiv.org/abs/1706.03762
The transformer architecture uses self-attention...
```

**Use cases:**
- Feed into Chroma, Pinecone, Qdrant, pgvector
- Ground prompts with fresh web data
- Build search-augmented RAG pipelines

---

## Architecture

```
serper-search-mcp-server/
β”œβ”€β”€ index.js                    ← Zero-build JS entry (npx / Docker) β€” generated from src/ via `npm run bundle`; never edit by hand
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ index.ts                ← TypeScript CLI entry
β”‚   β”œβ”€β”€ api/
β”‚   β”‚   β”œβ”€β”€ SerperAPI.ts        ← HTTP client (per-type endpoints, retry, timeout, TTL cache, scrape)
β”‚   β”‚   β”œβ”€β”€ LLMClient.ts        ← OpenRouter + Gemini client
β”‚   β”‚   └── providers/          ← Universal gateway: Router (failover + RRF fusion) Β· Serper Β· Tavily Β· Brave Β· Exa Β· Firecrawl
β”‚   β”œβ”€β”€ server/
β”‚   β”‚   └── SerperMCPServer.ts  ← MCP server, stdio + HTTP transport, bearer auth
β”‚   β”œβ”€β”€ tools/
β”‚   β”‚   β”œβ”€β”€ SearchTools.ts      ← All 15 tool definitions + validation
β”‚   β”‚   β”œβ”€β”€ BatchSearch.ts      ← search_many (parallel + dedupe)
β”‚   β”‚   β”œβ”€β”€ DeepResearch.ts     ← Multi-step research orchestration
β”‚   β”‚   β”œβ”€β”€ RAGContext.ts       ← Chunk + metadata formatter
β”‚   β”‚   └── ResolveLinks.ts     ← link_resolution modes + resolve_links (Serper /resolve)
β”‚   β”œβ”€β”€ types/
β”‚   β”‚   └── index.ts            ← Full TypeScript types
β”‚   └── utils/
β”‚       β”œβ”€β”€ ResultFormatter.ts  ← Markdown formatting
β”‚       β”œβ”€β”€ LinkResolution.ts   ← google.com/goto handling (link_resolution modes + /resolve)
β”‚       β”œβ”€β”€ HttpRetry.ts        ← Timeout + retry/backoff
β”‚       β”œβ”€β”€ TtlCache.ts         ← TTL + LRU cache
β”‚       β”œβ”€β”€ Logger.ts           ← Leveled stderr logger (+ request-id)
β”‚       β”œβ”€β”€ errors.ts           ← Typed error hierarchy
β”‚       β”œβ”€β”€ Metrics.ts          ← /health counters
β”‚       └── EnvCheck.ts         ← Boot-time env validation
β”œβ”€β”€ scripts/
β”‚   └── bundle.mjs              ← Builds index.js from src/ (`--check` mode for CI)
β”œβ”€β”€ tests/                      ← node:test suite (102 tests)
└── .github/workflows/ci.yml    ← Node 22/24: build + bundle check + tests
```

**Dual-file design:** `index.js` runs without any build step (ideal for `npx` and Docker) and is generated from `src/` β€” the TS tree is the only source of truth. `npm run check:bundle` fails CI if they drift.

---

## Get a Serper API key

1. Go to [serper.dev](https://serper.dev)
2. Sign up (free β€” no credit card)
3. Copy your API key from the dashboard
4. You get **2,500 free queries/month**

---

## Version evolution

| Feature | v1.0.0 | v2.0.1 | v3.0.0 | v4.0.0 |
|---|---|---|---|---|
| **Total tools** | 5 | 5 | 8 | 14 |
| `search` (unified) | ❌ | ❌ | ❌ | βœ… auto-verbosity + provider failover |
| `search_web` | βœ… organic only | βœ… organic only | βœ… + Answer Box, Knowledge Graph, PAA, Related | βœ… |
| `search_images` | βœ… | βœ… | βœ… + dimensions, domain | βœ… + gallery layout |
| `search_videos` | βœ… | βœ… | βœ… + date field | βœ… |
| `search_news` | βœ… | βœ… | βœ… cleaner formatting | βœ… + past-day default |
| `search_shopping` | βœ… | βœ… | βœ… + delivery, offers | βœ… (always rich) |
| `search_places` | ❌ | ❌ | βœ… address, phone, hours, GPS, Maps link | βœ… + full 7-day hours, directions |
| `search_scholar` | ❌ | ❌ | ❌ | βœ… papers + citation counts |
| `search_patents` | ❌ | ❌ | ❌ | βœ… publication, assignee, dates |
| `autocomplete` | ❌ | ❌ | ❌ | βœ… fast query completions |
| `scrape` | ❌ | ❌ | ❌ | βœ… full page β†’ markdown |
| `search_many` | ❌ | ❌ | ❌ | βœ… batch + cross-query dedupe |
| `deep_research` | ❌ | ❌ | βœ… sub-queries β†’ parallel search β†’ LLM report | βœ… |
| `search_rag_context` | ❌ | ❌ | βœ… chunked text + metadata, JSON/text output | βœ… |
| `resolve_links` + `link_resolution` modes | ❌ | ❌ | ❌ | ❌ β†’ βœ… in **v4.1.0** (14 β†’ 15 tools) |
| **API endpoints** | all hitting `/search` with `tbm` param | all hitting `/search` with `tbm` param | βœ… correct per-type endpoints | βœ… + scholar + scrape host |
| **Answer Box / KG / PAA** | ❌ | ❌ | βœ… full SERP extraction | βœ… |
| **Pagination** | ❌ | ❌ | βœ… `page` param | βœ… |
| **Autocorrect param** | ❌ | ❌ | βœ… | βœ… |
| **LLM support** | ❌ | ❌ | βœ… OpenRouter + Gemini (user's own key) | βœ… |
| **LLM-free RAG output** | ❌ | ❌ | βœ… JSON + plain text | βœ… |
| **TypeScript types** | partial (heavy `any`) | partial (heavy `any`) | βœ… full types for every result shape | βœ… + scholar/scrape |
| **MCP SDK version** | ^0.5.0 | ^0.5.0 or ^1.0.0 | ^1.0.0 | ^1.0.0 |
| **Node requirement** | >=16 | >=16 | >=18 (native `fetch`, no axios) | >=18 |
| **HTTP transport** | ❌ | βœ… | βœ… | βœ… stateless Streamable HTTP |
| **HTTP bearer auth** | ❌ | ❌ | ❌ | βœ… optional |
| **Retry + timeout** | ❌ | ❌ | ❌ | βœ… 429/5xx/network |
| **Response cache** | ❌ | ❌ | ❌ | βœ… TTL + LRU |
| **Log levels** | ❌ | ❌ | ❌ | βœ… error/warn/info/debug/silent |
| **Tests + CI** | ❌ | ❌ | ❌ | βœ… node:test + GitHub Actions |
| **Docker** | ❌ | βœ… | βœ… | βœ… |
| **npx** | ❌ | βœ… | βœ… | βœ… |
| **Client configs** | Claude Desktop only | Claude Desktop + a few | Claude Desktop + Cursor + Windsurf + KiloCode + n8n | βœ… |
| **Telemetry** | ❌ none | ❌ none | ❌ none (intentional β€” privacy win) | ❌ none |

> **v4.1.0** (see Changelog): security hardening + correctness sweep β€” tool count 14 β†’ **15** (added `resolve_links`), no new search types.

---

## Changelog

### v4.1.0 β€” Security hardening + correctness sweep (36 fixes)

- πŸ”§ **`freshness` was silently broken** β€” the server sent invalid Google `tbs` values (`qdr:pd/pw/pm/py` instead of `qdr:d/w/m/y`), so Google ignored the filter and returned all-time results (the "16 years ago" problem from the incident log). One mapping fix healed 7 tools: `search`, `search_web`, `search_videos`, `search_news`, `search_scholar`, `search_many`, `search_rag_context`. Verified live: `freshness: py` β†’ Dec 2025–Jun 2026 results at 1 credit.
- βž• **`freshness: "any"`** β€” explicit no-filter opt-out; `search_news` (defaults to past day) can now reach historical news (`before:2015-01-01` verified β†’ 2004–2013 articles). `after:`/`before:` operators documented in the tool description.
- ⏱️ **Footer `Time filter` echo** β€” every web/news response states the applied filter (`none (all time)` / `past day` / `past year` / `none (opt-out)`) so agents correct in one retry instead of looping.
- πŸ”§ **People Also Ask guards** β€” question-only PAA entries no longer render `undefined` / `[Read more](undefined)`; `search_rag_context` no longer crashes on them (`cleanText(undefined)` TypeError).
- 🧹 **Dead `summary` param removed from `search_web`** β€” Serper never implemented it and it was never rendered; schema/server/type cleaned (stale clients still passing `summary` are silently accepted β€” non-breaking). Tool description now steers to `search_rag_context` (fast) or `deep_research` (thorough) instead of searchβ†’scrape chains.
- πŸ’° **Credit transparency** β€” `scrape` pricing verified live: 2 credits/page, identical with or without `include_images` (incident's "6 credits" = 3 scrapes Γ— 2). README credit rules corrected; the misleading *"typical flow: search_web β†’ scrape"* guidance replaced with rag/deep-first advice + chain warnings.
- πŸ§ͺ **Tests** β€” **102/102** : regression tests for all four freshness mappings + the `any` opt-out; the old assertion that enshrined the bug (`tbs === 'qdr:pw'`) corrected to Google's real syntax.
- πŸ”’ **HTTP is safe by default** β€” binds `127.0.0.1`, refuses a non-loopback bind without `SERPER_MCP_AUTH_TOKEN` (`SERPER_MCP_INSECURE_NO_AUTH=true` opts out), `docker-compose.yml` requires the token, chunked bodies are rejected (`411`), error messages are sanitized before leaving the process, the Gemini key moved to the `x-goog-api-key` header, bearer comparison is case-insensitive and constant-time (digest compare).
- 🧠 **Wrong-results fixes** β€” failover now judges emptiness per search type (videos/shopping/patents/autocomplete are no longer discarded), `provider=all` fuses the right result field, non-Serper providers are rejected for non-web searches instead of returning empty output.
- πŸ§ͺ **Tests are hermetic** β€” cache persistence is opt-in (`SERPER_CACHE_PERSIST=true`), files are `0600` in a `0700` dir, scoped per API key; the suite passes on immediate re-runs (82/82 Γ—2).
- βœ… **Validation** β€” schema-driven `validateArgs` (types, enums, ranges), `layout` gallery wired, `size`/`orientation` filter client-side, dead `color`/`open_now_only` params removed.
- βš™οΈ **Reliability** β€” body reads are covered by the request timeout, `/resolve` wall-time is budgeted, per-request log IDs via `AsyncLocalStorage`, cache writes are debounced + atomic, deep-research counts only sources actually sent, empty LLM reports fail loudly, stdio shutdown can't hang.

### v4.0.0 β€” Universal Search Gateway (Multi-Provider, 14 Tools, CLI, Resilience, Tests)
- βž• **Universal Multi-Provider Gateway** β€” failover chain: Serper β†’ Tavily β†’ Brave (+ Exa/Firecrawl) with `provider=all` reciprocal-rank fusion
- βž• **14 MCP Tools** β€” including unified `search` (token-smart auto-verbosity), `search_scholar`, `search_patents`, `autocomplete`, `scrape`, `search_many`
- βž• **Developer CLI** β€” `search`, `scrape`, `research`, `rag`, `providers`, `status` subcommands
- βž• **`search_scholar` tool** β€” Google Scholar with authors, journal, year, citation counts
- βž• **`scrape` tool** β€” full page content as markdown via `scrape.serper.dev` (truncation-safe)
- βž• **`search_many` tool** β€” 1–10 parallel web searches, cross-query URL dedupe, per-query failure isolation
- βž• **Retry + timeout** β€” 429/5xx/network retries with exponential backoff + jitter (Retry-After honored)
- βž• **Response cache** β€” in-memory TTL + LRU (`SERPER_CACHE_TTL_MS=0` disables); opt-in disk persistence (`SERPER_CACHE_PERSIST=true`, dir `SERPER_CACHE_DIR`, written 0600 and scoped per API key)
- βž• **Optional HTTP bearer auth** β€” `SERPER_MCP_AUTH_TOKEN` guards `/mcp`; `/health` stays open
- βž• **Real log levels** β€” `SERPER_MCP_LOG_LEVEL` now controls error/warn/info/debug/silent
- βž• **Test suite + CI** β€” 58 `node:test` tests (no extra deps, incl. real-HTTP e2e) + GitHub Actions matrix (Node 18/20/22)
- πŸ”§ HTTP transport now works on Node 18 β€” WebCrypto shim for the MCP SDK (`crypto.randomUUID`); Docker base image bumped to `node:20-alpine`
- πŸ”§ `search_lang` is now correctly mapped to Serper's `hl` (was previously ignored)
- πŸ”§ News results default to past-day freshness as documented
- πŸ”§ `max_chunk_words` clamped 50–1000 (fixes a hang on zero/negative values)
- πŸ”§ Unknown `depth` falls back to `standard` in `deep_research`
- πŸ”§ Unknown tools return `MethodNotFound` instead of `InternalError`
- πŸ”§ `--api-key` without a value no longer breaks startup
- πŸ”§ `index.js` is generated from `src/` via esbuild; `npm run check:bundle` guards drift
- πŸ”§ Windows-compatible npm scripts; `npm audit` reports 0 vulnerabilities

### v3.0.0 β€” Places + Deep Research + RAG
- βž• **`search_places` tool** β€” local businesses with address, phone, hours, GPS
- βž• **Knowledge Graph** extraction in web search
- βž• **Answer Box** extraction in web search
- βž• **People Also Ask** + Related Searches in web results
- βž• **Pagination** support (`page` param)
- βž• **`autocorrect`** param on web search
- πŸ”§ Corrected per-type Serper endpoints (images/videos/news/shopping now use dedicated endpoints)
- πŸ”§ Full TypeScript types for all result shapes
- βž• **`deep_research` tool** β€” multi-step research with LLM synthesis (OpenRouter / Gemini)
- βž• **`search_rag_context` tool** β€” embedding-ready chunks with metadata (no LLM needed)
- πŸ”§ Node β‰₯ 18 requirement (native `fetch`)

### v2.0.1
- HTTP/SSE transport mode
- Docker Compose support
- CLI flags

### v1.0.0
- Initial release: web, images, videos, news, shopping

---

## Contributing

PRs and issues are welcome. Please open an issue before large changes β€” and if something looks wrong (stale results, unexpected credits, a parameter that seems ignored), start an issue or Discussion with the exact tool call, the response footer line (`Provider Β· Cache Β· Time filter Β· credits`), and your server version (`vX.Y.Z` startup banner or `npm view serper-search-mcp version`); security vulnerabilities go to GitHub Security Advisories, not public issues.

```bash
git clone https://github.com/smjahid012/serper-search-mcp-server.git
cd serper-search-mcp-server
npm install
export SERPER_API_KEY="your_key"
node index.js   # test immediately, no build required
```

---

## License

Apache 2.0 β€” see [LICENSE](LICENSE)

---

<div align="center">

**Built by [SMLabs AI](https://smlabsai.com) Β· [smjahid012](https://github.com/smjahid012)**  
If this saved you time, a ⭐ on GitHub helps others find it.

</div>

TDQS

A3.5/5.0

Scored across 15 tools

Disambiguation3/5

The vertical search tools (search_web, search_images, search_news, search_scholar, etc.) are clearly distinct from each other, but the unified `search` tool explicitly subsumes nine of them, so an agent must guess between `search(type=web)` and `search_web`. The web-retrieval family is also crowded β€” search, search_web, search_many, search_rag_context, and deep_research all return web results with only subtle intent differences (raw vs chunked vs synthesized vs parallel).

Naming Consistency4/5

Most tools follow a predictable `search_<vertical>` or verb_noun pattern (search_web, search_news, search_rag_context, resolve_links, deep_research). The lone outlier is `autocomplete` (no verb) and the bare `search`, which breaks the prefix family while sitting in the middle of it.

Tool Count3/5

Fifteen tools is within a reasonable band, but roughly nine of them are redundant duplicates of the unified `search` tool, so the set is effectively two overlapping surfaces shipped together rather than 15 distinct capabilities. The redundancy inflates the count without adding reachable functionality.

Completeness4/5

Coverage of the search domain is strong: all major Google verticals, scraping, link resolution, RAG-ready chunking, and synthesized research are present. Minor gaps remain around pagination/result-set continuation, batch scraping, and any cache or credit-budget inspection tool, but agents can work around these.

Maintenance

ActivityNo data
ResponsivenessOutdated data