Google Search MCP Server
This Google Search MCP Server provides programmatic access to Google Custom Search Engine (CSE) functionality through the Model Context Protocol.
Core Capabilities:
Configurable Search: Execute Google searches with comprehensive parameter control including query string, result count (1-10), pagination, exact/OR/excluded terms, and advanced query modifiers
Filtering & Localization: Filter by site/domain (include/exclude), SafeSearch levels, allowed domains, geolocation (gl), UI language (hl), and language restrictions (lr)
Time-based & Performance Controls: Date range filtering (e.g., last 7 days, 3 months, 1 year) and lean field mode to reduce response size
Query Logging: Optional logging with non-reversible query hash, timing metrics, parameters, and full query text for auditing
Deployment Patterns:
stdio Mode: Standard MCP for local development and client integration
HTTP over SSE: Browser-friendly deployment using Server-Sent Events
HTTP Streamable: Non-SSE HTTP transport for compatible clients
AWS Lambda + AgentCore Gateway: Serverless deployment with OAuth authentication and JSON-RPC 2.0
Containerized (ECS Fargate): Scalable Docker-based cloud deployment
Configuration:
Requires GOOGLE_API_KEY and GOOGLE_CX credentials with Dynaconf for flexible environment variable overrides. Returns structured results with provider info, sanitized query, search metadata, pagination info, latency metrics, and normalized results.
Provides Google Custom Search functionality, allowing AI agents to perform web searches using Google's search engine API
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Google Search MCP Serverfind recent articles about AI advancements in healthcare"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Google Search MCP Server
A Model Context Protocol (MCP) server that provides Google Custom Search functionality.
🎯 This repository demonstrates 5 different deployment patterns for the same MCP functionality:
stdio Mode - Standard MCP over stdin/stdout for local development and MCP client integration
HTTP over SSE - MCP HTTP transport using Server‑Sent Events (browser-friendly)
HTTP Streamable - MCP Streamable HTTP transport (non‑SSE)
AWS Lambda + AgentCore Gateway - Serverless deployment with OAuth authentication
Containerized MCP Service - Docker containers deployed to ECS Fargate for scalable cloud deployment
Installation
Clone the repository and install dependencies:
git clone https://github.com/jspv/google-search-mcp.git
cd google-search-mcp
uv syncRelated MCP server: MCP Google Custom Search Server
Project structure
server.py/server_http.py/server_http_stream.py— MCP servers (stdio, HTTP, streaming)lambda_handler.py— AWS Lambda adapter for MCP stdio serverDockerfile.mcp— Container image for HTTP/streaming MCP servicedeploy/— legacy deployment assets (usedeploy_aws_agentcore_auth0/)deploy_aws_agentcore_auth0/— canonical Auth0 + AgentCore Gateway deploy scripts and templatesbuild_zip.sh— build Lambda ZIPdeploy_lambda.sh— deploy Lambda via CloudFormationAGENTCORE_GATEWAY_CHECKLIST.md— complete Gateway (Lambda + Cognito) integration checklistdeploy_gateway.sh— attempt AgentCore setup via CLIgen_tool_schema.sh— generate MCP tool schema (uses Python stdio client)cloudformation-*.yaml— infrastructure templatesREADME-*.md— deployment-specific docs
scripts/— developer/CI utilitiesdump_tool_schema.py— dump schema from an MCP server over stdio
dist/— build artifacts and generated outputsschema/tool-schema.json— generated tool schema for AgentCoregoogle_search_mcp_lambda.zip— built Lambda package
tests/— unit and integration tests
Optional Dependencies
Install additional dependencies based on your deployment needs:
# For HTTP/streaming modes
uv sync --extra http
# For AWS Lambda deployment
uv sync --extra lambda
# For containerized deployments (ECS/Fargate)
uv sync --extra container
# For AWS (both Lambda and container)
uv sync --extra aws
# For development
uv sync --extra dev
# Install multiple extras
uv sync --extra http --extra aws --extra devConfiguration
This server uses Dynaconf for configuration management, supporting both .env files and environment variables.
Setup
Copy the example environment file:
cp .env.example .envEdit
.envand add your Google API credentials:GOOGLE_API_KEY=your_actual_api_key_here GOOGLE_CX=your_custom_search_engine_id_here
Environment Variable Override
Environment variables will override .env file values when both are present. This allows for flexible deployment scenarios:
Development: Use
.envfile for local developmentProduction: Use environment variables for production deployment
CI/CD: Environment variables can override defaults for testing
Example:
If your .env file contains:
GOOGLE_API_KEY=dev_key_from_fileAnd you set an environment variable:
export GOOGLE_API_KEY=prod_key_from_envThe server will use prod_key_from_env (environment variable takes precedence).
Required Configuration
GOOGLE_API_KEY: Your Google Custom Search API keyGOOGLE_CX: Your Custom Search Engine ID
Get these from:
API Key: Google Cloud Console
Search Engine ID: Google Custom Search
Optional Configuration
ALLOW_DOMAINS(GOOGLE_ALLOW_DOMAINSenv var): Comma-separated list of allowed domains (e.g.,example.com, docs.python.org). When set, results outside these domains are filtered out.Logging:
LOG_QUERIES(GOOGLE_LOG_QUERIES): Enable logging of query hash, timing, and key params.LOG_QUERY_TEXT(GOOGLE_LOG_QUERY_TEXT): Also log full query text (off by default).LOG_LEVEL(GOOGLE_LOG_LEVEL): Set logging level (e.g.,INFO,DEBUG).LOG_FILE(GOOGLE_LOG_FILE): Optional path to also write logs to a file (stderr remains enabled).
Usage
This project provides 5 different deployment patterns for the same Google Search MCP functionality:
1. stdio Mode (Default MCP)
Standard MCP server for local development and integration with MCP clients:
# Run via uv (recommended)
uv run python -m server
# Or direct execution
python server.py
# Run via uvx (no activation, from any folder)
uvx --from /Users/justin/src/google_search_mcp google-search-mcp
# Run via pipx (isolated, globally available)
pipx install /Users/justin/src/google_search_mcp
google-search-mcpCommunicates over stdin/stdout using the standard MCP protocol.
2. HTTP over SSE (MCP transport)
MCP over HTTP using Server‑Sent Events (SSE). This exposes the standard MCP HTTP endpoints used by browser clients.
# Install HTTP extras and run
uv sync --extra http
uv run python -m server_http
# Or via console script (if installed)
uv run google-search-mcp-http
# With custom host/port
HOST=0.0.0.0 PORT=8000 uv run python -m server_httpAvailable MCP endpoints (not a custom REST API):
GET /sse— SSE connection for eventsPOST /messages— MCP message handling
Notes:
CORS enabled by default (customize with
CORS_ORIGINS).Same configuration as stdio mode (
GOOGLE_API_KEY,GOOGLE_CX, etc.).
3. HTTP Streamable (non‑SSE)
MCP Streamable HTTP transport for clients that don’t use SSE.
# Start the Streamable HTTP MCP server
uv sync --extra http
uv run python -m server_http_stream
# Or via console script (if installed)
uv run google-search-mcp-stream
# Custom host/port
HOST=0.0.0.0 PORT=8000 uv run python -m server_http_streamNotes:
Not a REST interface. Use an MCP client that supports the Streamable HTTP transport.
CORS behavior matches the SSE app and is configurable via
CORS_ORIGINS.
4. AWS Lambda + AgentCore Gateway
Prerequisites:
# Install Lambda dependencies
uv sync --extra lambda
# Configure AWS credentials
aws configureDeploy to AWS Lambda with Bedrock AgentCore Gateway integration:
# Build and deploy
./deploy_aws_agentcore_auth0/build_zip.sh # Cross-platform build
./deploy_aws_agentcore_auth0/deploy_lambda.sh # Deploy via CloudFormation
./deploy_aws_agentcore_auth0/deploy_gateway.sh # Setup AgentCore Gateway
# Test the deployment
python3 deploy_aws_agentcore_auth0/test_gateway_auth0.py https://your-gateway-url.amazonaws.com client-id client_secret https://your-domain.auth0.com [audience]Features:
JSON-RPC 2.0 protocol with OAuth authentication
Serverless execution with environment variable inheritance
Integrated with AWS Bedrock AgentCore ecosystem
5. Containerized MCP Service
Prerequisites:
# Install container dependencies (for ECR/ECS deployment)
uv sync --extra container
# Configure Docker and AWS
docker --version
aws configureLocal Testing:
# Build container
docker build -f Dockerfile.mcp -t google-search-mcp .
# Run locally
docker run -p 8000:8000 --env-file .env -e MCP_MODE=http-stream google-search-mcpDeploy to AWS ECS Fargate:
# Deploy to ECS Fargate
./deploy/deploy_mcp_container.sh google-search-mcp us-east-1 ecs-fargateFeatures:
Multi-mode container supporting stdio, HTTP, and streaming
Scalable deployment via ECS Fargate
Environment variable configuration
Health checks and monitoring
Note: AgentCore Runtime uses preview SDK and requires manual configuration as APIs are not publicly available.
Configuration Notes
All deployment patterns use the same configuration:
Set
DYNACONF_DOTENV_PATHfor .env loading when neededEnvironment variables override settings.toml values
Logging configuration applies across all modes
Quick Start
This project uses httpx with HTTP/2 support enabled. The dependency is declared as httpx[http2] and will install the h2 package automatically.
Using uv (recommended)
# Install dependencies
uv sync
# Create and configure environment
cp .env.example .env
$EDITOR .env
# Run tests (optional sanity check)
uv run pytest -q
# Start the MCP server (stdio mode)
uv run python server.pyQuick Test (no MCP client required)
Test the search function directly:
uv run python -c 'import asyncio, server; print(asyncio.run(server.search("site:python.org httpx", num=2, safe="off")))'Note: safe must be off or active, and num is clamped to maximum of 10 per Google CSE limits.
Logging behavior
If LOG_QUERIES is enabled, the server will write a single line per request to stdout containing:
q_hash (short, non-reversible hash of the query), dt_ms (latency), num, start, safe, and endpoint (cse/siterestrict)
If
LOG_QUERY_TEXTis true, it also includes the fullqtext.
Example log line:
2025-09-27T12:34:56+0000 INFO google_search_mcp: search q_hash=1a2b3c4d dt_ms=123 num=5 start=1 safe=off endpoint=cse q="site:python.org httpx"When a client spawns the server via uvx, logs go to the server process’s stderr by default (safe for MCP stdio). To persist logs regardless of the client’s stderr handling:
Set a file path (absolute recommended):
GOOGLE_LOG_QUERIES=true GOOGLE_LOG_FILE=/var/log/google_search_mcp.logOr redirect stderr in the launch command:
uvx --from /path/to/repo google-search-mcp 2>> /tmp/google_search_mcp.log
Testing
Unit Tests
Run the test suite to validate functionality:
# Run all tests
uv run pytest
# Run with quiet output
uv run pytest -q
# Run specific test files
uv run pytest tests/test_server.py
uv run pytest tests/test_server_http.pyTesting
Testing
The project includes a comprehensive test suite located in the tests/ directory. All tests use pytest and mock external dependencies for reliable, fast execution.
Unit Tests
Run the comprehensive test suite to validate functionality:
# Run all tests
uv run pytest
# Run with quiet output
uv run pytest -q
# Run specific test modules
uv run pytest tests/test_server.py # Core MCP server functionality
uv run pytest tests/test_server_http.py # HTTP endpoint testing
uv run pytest tests/test_server_http_stream.py # HTTP streaming testing
uv run pytest tests/test_client.py # Client integration
uv run pytest tests/test_logging.py # Logging configurationLocal Testing
Use an MCP client (e.g., Inspector or your app) that supports SSE or Streamable HTTP transports. There is no custom REST list_tools/call_tool in this server.
AWS Gateway Testing
For AWS AgentCore Gateway deployments, use the dedicated test script:
# Test gateway with authentication
python3 deploy_aws_agentcore_auth0/test_gateway_auth0.py \
"https://your-gateway.amazonaws.com/mcp" \
"client-id" \
"client-secret" \
"https://your-domain.auth0.com" \
"https://your-gateway.amazonaws.com/mcp" # audience (optional depending on IdP)This validates authentication, tool listing, and tool execution through the gateway.
Deployment Details
AWS Lambda + AgentCore Gateway
Uses JSON-RPC 2.0 protocol with OAuth authentication
Cognito client credentials flow required
Manual console configuration for compute targets and MCP providers (APIs not publicly available)
See
deploy/README-lambda-zip.mdfor detailed instructions (use scripts underdeploy_aws_agentcore_auth0/)
AWS AgentCore Runtime
Uses preview AgentCore SDK (placeholder implementation)
Requires manual configuration as APIs are not publicly available
Container-based deployment via ECR integration
Provides persistent sessions with microVM isolation
Available Tools
1 toolsearchA
Google Programmable Search (CSE) via MCP.
Parameters:
q: Query string. Trimmed; required.
num: Number of results to return (1..10; clamped).
start: 1-based index for pagination start (clamped to >=1).
siteSearch: Limit results to a site (or domain) per CSE rules.
siteSearchFilter: "i" to include or "e" to exclude `siteSearch`.
safe: SafeSearch level: "off" or "active".
gl: Geolocation/country code.
hl: UI language.
lr: Language restrict (e.g., "lang_en").
useSiteRestrict: Use the siterestrict endpoint variant.
dateRestrict: Time filter (e.g., "d7", "m3", "y1").
exactTerms, orTerms, excludeTerms: Query modifiers.
cxOverride: Override the configured CSE ID (avoid echoing to clients).
lean_fields: If True, request a smaller response via fields projection.
Returns:
A dict with keys: provider, query (sanitized), searchInfo, nextPage,
latency_ms, results (normalized), raw (subset), trace (q hash).
Raises:
ValueError: For invalid parameter values (e.g., unsupported safe).
RuntimeError: For Google API errors or network failures.
| Name | Required | Description | Default |
|---|---|---|---|
| q | Yes | ||
| num | No | ||
| start | No | ||
| siteSearch | No | ||
| siteSearchFilter | No | ||
| safe | No | ||
| gl | No | ||
| hl | No | ||
| lr | No | ||
| useSiteRestrict | No | ||
| dateRestrict | No | ||
| exactTerms | No | ||
| orTerms | No | ||
| excludeTerms | No | ||
| cxOverride | No | ||
| lean_fields | No |
Output Schema
| Name | Required | Description |
|---|---|---|
No output parameters | ||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure. It does well by describing the return structure ('Returns: A dict with keys...'), error conditions ('Raises: ValueError...'), and implementation details like 'clamped' ranges and 'sanitized' queries. However, it doesn't mention rate limits, authentication requirements, or cost implications.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is well-structured with clear sections (Parameters, Returns, Raises) and uses bullet-like formatting. While comprehensive, some sentences could be more concise (e.g., 'Google Programmable Search (CSE) via MCP' could be simplified). Overall, it's efficiently organized with minimal wasted space.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's complexity (16 parameters, no annotations), the description provides substantial context. It covers parameters thoroughly, describes the return structure (though an output schema exists), and documents error conditions. The main gap is lack of usage guidance and some behavioral aspects like rate limits. For a search tool with many parameters, this is quite complete.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
With 0% schema description coverage for 16 parameters, the description provides excellent compensation. It explains every parameter's purpose, constraints (e.g., '1..10; clamped'), and special behaviors (e.g., 'Trimmed; required', 'avoid echoing to clients'). The parameter explanations add substantial meaning beyond what the bare schema provides.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states this tool performs 'Google Programmable Search (CSE) via MCP,' which is a specific verb+resource combination. However, without sibling tools to differentiate from, it cannot achieve the highest score of 5. The purpose is unambiguous: it executes search queries through Google's Custom Search Engine.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides no guidance on when to use this tool versus alternatives. There are no sibling tools mentioned, but it doesn't discuss typical use cases, prerequisites, or limitations. The agent receives no help in determining appropriate contexts for invoking this search tool.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
1 tool update
v1.0.0- Changed
search1 field changed- added
Input schema / titleAdded value: +"searchArguments"
1 tool update
- First observed
search
TDQS
Scored across 1 tool
With only one tool, there is no possibility of confusion or overlap between tools. The single 'search' tool has a clearly defined and distinct purpose that cannot be mistaken for any other tool in this server.
The naming is trivially consistent as there is only one tool named 'search'. This follows a simple verb pattern and there are no other tools to create inconsistency or mixed conventions.
A single tool is too few for a server named 'Google Search MCP Server', which suggests broader search functionality. While the tool is feature-rich, the server lacks complementary tools like image_search, news_search, or advanced filtering tools that would make the set more complete and appropriate for the domain.
The server is severely incomplete for a Google Search domain. It only provides a general web search tool, missing obvious gaps such as image search, video search, news search, or specialized search types that agents would expect from a comprehensive search interface. This will likely cause agent failures when trying to perform common search-related tasks beyond basic web queries.
Maintenance
Related MCP Connectors
Search Google straight from your AI agent. Web results, images, videos, news, products, scholarly ar
1 Google Search endpoints. Pay per call in USDC via x402.
Web search, scraping, Google Trends and data lookups. Paid per call in USDC on Base via x402.
Google Web Search: Google Web Search API. Search the world’s information, including webpages.
Related MCP Servers
- AlicenseBqualityDmaintenanceProvides web search capabilities using Google Custom Search API, enabling users to perform searches through a Model Context Protocol server.2179 npm68MIT
- AlicenseBqualityDmaintenanceA Model Context Protocol server that enables LLMs to perform web searches using Google's Custom Search API through a standardized interface.147MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that enables Claude to perform Google Custom Search operations by connecting to Google's search API.2MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that enables AI assistants to perform web searches using Google Search API, returning up to 20 search results in JSON format.2Apache 2.0