Google Search MCP Server
Google 搜索 MCP 服务器
一个模型上下文协议 (MCP) 服务器,通过 Google 的自定义搜索 API 提供网页和图片搜索功能。该服务器遵循 MCP 规范,可与 Claude 和其他 AI 助手集成。
我们正在构建什么
许多 AI 助手缺乏最新信息或搜索网络的能力。MCP 服务器通过提供以下两个工具解决了这个问题:
google_web_search:在网络上搜索当前信息google_image_search:查找与查询相关的图片
一旦连接到与 MCP 兼容的客户端(如 Cursor、VSCode 或 Claude Desktop 中的 Claude),您的 AI 助手就可以执行搜索并访问当前信息。
Related MCP server: Google Search MCP Server
核心 MCP 概念
MCP 服务器为 AI 助手提供功能。该服务器实现:
工具:AI 可以调用的功能(需经用户批准)
结构化通信:通过 MCP 协议标准化消息格式
传输层:通过标准输入/输出进行通信
先决条件
Node.js(v18 或更高版本)和 npm
Google 云端平台帐户
Google 自定义搜索 API 密钥和搜索引擎 ID
与 MCP 兼容的客户端(Claude for Desktop、Cursor、VSCode with Claude 等)
快速启动(克隆此存储库)
如果您不想从头开始构建此服务器,请按照以下步骤操作:
# Clone the repository
git clone https://github.com/yourusername/google-search-mcp-server.git
cd google-search-mcp-server
# Install dependencies
npm install
# Set up your environment variables
# Setup .env file in the root folder of the project
# On macOS/Linux
touch .env
# On Windows
new-item .env
# Edit .env file to add your Google API credentials
# Use any text editor you prefer (VS Code, Notepad, nano, vim, etc.)
# Add these to your newly created .env
GOOGLE_API_KEY=your_api_key_here
GOOGLE_CSE_ID=your_search_engine_id_here
# Build the server
npm run build
# Test the server (optional)
# On macOS/Linux
echo '{"jsonrpc":"2.0","method":"listTools","id":1}' | node dist/index.js
# On Windows PowerShell
echo '{"jsonrpc":"2.0","method":"listTools","id":1}' | node dist/index.js
# On Windows CMD
echo {"jsonrpc":"2.0","method":"listTools","id":1} | node dist/index.js构建后,按照连接到 MCP 客户端部分将服务器连接到您首选的客户端。
设置您的环境(从头开始构建)
如果您希望自己从头开始构建服务器,请按照以下说明操作:
创建项目结构
macOS/Linux
# Create a new directory for our project
mkdir google-search-mcp
cd google-search-mcp
# Initialize a new npm project
npm init -y
# Install dependencies
npm install @modelcontextprotocol/sdk dotenv zod
npm install -D @types/node typescript
# Create our files
mkdir src
touch src/index.ts视窗
# Create a new directory for our project
md google-search-mcp
cd google-search-mcp
# Initialize a new npm project
npm init -y
# Install dependencies
npm install @modelcontextprotocol/sdk dotenv zod
npm install -D @types/node typescript
# Create our files
md src
new-item src\index.ts配置 TypeScript
在根目录下创建tsconfig.json :
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}更新 package.json
确保您的package.json包含:
{
"name": "google_search_mcp",
"version": "0.1.0",
"description": "MCP server for Google Custom Search API integration",
"license": "MIT",
"type": "module",
"bin": {
"google_search": "./dist/index.js"
},
"files": [
"dist"
],
"scripts": {
"build": "tsc",
"build:unix": "tsc && chmod 755 dist/index.js",
"prepare": "npm run build",
"watch": "tsc --watch",
"start": "node dist/index.js"
}
}Google API 设置
您需要设置 Google Cloud Platform 并获取 API 凭据:
Google 云平台设置
创建新项目
启用自定义搜索 API:
Navigate to "APIs & Services" → "Library" Search for "Custom Search API" Click on "Custom Search API" → "Enable"创建 API 凭证:
Navigate to "APIs & Services" → "Credentials" Click "Create Credentials" → "API key" Copy your API key
自定义搜索引擎设置
前往可编程搜索引擎
点击“添加”创建新的搜索引擎
选择“搜索整个网络”并命名您的搜索引擎
从控制面板获取您的搜索引擎 ID(cx 值)
环境配置
在根目录中创建一个.env文件:
GOOGLE_API_KEY=your_api_key_here
GOOGLE_CSE_ID=your_search_engine_id_here将.env添加到您的.gitignore文件以保护您的凭据:
echo ".env" >> .gitignore构建您的服务器
创建服务器实现
在src/index.ts中创建服务器实现:
import dotenv from "dotenv"
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
Tool,
} from "@modelcontextprotocol/sdk/types.js";
dotenv.config();
// Define your tools
const WEB_SEARCH_TOOL: Tool = {
name: "google_web_search",
description: "Performs a web search using Google's Custom Search API...",
inputSchema: {
// Schema details here
},
};
const IMAGE_SEARCH_TOOL: Tool = {
name: "google_image_search",
description: "Searches for images using Google's Custom Search API...",
inputSchema: {
// Schema details here
}
};
// Server implementation
const server = new Server(
{
name: "google-search",
version: "0.1.0",
},
{
capabilities: {
tools: {},
},
},
);
// Check for API key and Search Engine ID
const GOOGLE_API_KEY = process.env.GOOGLE_API_KEY!;
const GOOGLE_CSE_ID = process.env.GOOGLE_CSE_ID!;
if (!GOOGLE_API_KEY || !GOOGLE_CSE_ID) {
console.error("Error: Missing environment variables");
process.exit(1);
}
// Tool handlers
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [WEB_SEARCH_TOOL, IMAGE_SEARCH_TOOL],
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
// Implement tool handlers
});
// Run the server
async function runServer() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Google Search MCP Server running on stdio");
}
runServer().catch((error) => {
console.error("Fatal error running server:", error);
process.exit(1);
});有关完整的实施细节,请参阅存储库文件。
构建服务器
完成实施后,构建服务器:
npm run build这会将dist目录中的 TypeScript 代码编译为 JavaScript。
连接到 MCP 客户端
MCP 服务器可以连接到各种客户端。以下是一些常用客户端的设置说明:
克劳德桌面版
macOS/Linux
打开您的配置文件:
code ~/Library/Application\ Support/Claude/claude_desktop_config.json添加服务器配置:
{
"mcpServers": {
"google_search": {
"command": "node",
"args": [
"/absolute/path/to/google-search-mcp/dist/index.js"
],
"env": {
"GOOGLE_API_KEY": "your_api_key_here",
"GOOGLE_CSE_ID": "your_search_engine_id_here"
}
}
}
}视窗
打开您的配置文件:
code $env:AppData\Claude\claude_desktop_config.json添加服务器配置:
{
"mcpServers": {
"google_search": {
"command": "node",
"args": [
"C:\\absolute\\path\\to\\google-search-mcp\\dist\\index.js"
],
"env": {
"GOOGLE_API_KEY": "your_api_key_here",
"GOOGLE_CSE_ID": "your_search_engine_id_here"
}
}
}
}重启 Claude 桌面版
通过单击界面中的工具图标来验证工具是否出现
与 Claude 一起编写 VSCode
macOS/Linux 和 Windows
在您的工作区中创建或编辑
.vscode/settings.json:
对于 macOS/Linux:
{
"mcp.servers": {
"google_search": {
"command": "node",
"args": [
"/absolute/path/to/google-search-mcp/dist/index.js"
],
"env": {
"GOOGLE_API_KEY": "your_api_key_here",
"GOOGLE_CSE_ID": "your_search_engine_id_here"
}
}
}
}对于 Windows:
{
"mcp.servers": {
"google_search": {
"command": "node",
"args": [
"C:\\absolute\\path\\to\\google-search-mcp\\dist\\index.js"
],
"env": {
"GOOGLE_API_KEY": "your_api_key_here",
"GOOGLE_CSE_ID": "your_search_engine_id_here"
}
}
}
}重启 VSCode
这些工具将在 VSCode 中提供给 Claude
光标
打开光标设置(齿轮图标)
搜索“MCP”并打开 MCP 设置
点击“添加新的 MCP 服务器”
使用与上述类似的设置进行配置:
对于 macOS/Linux:
{
"mcpServers": {
"google_search": {
"command": "node",
"args": [
"/absolute/path/to/google-search-mcp/dist/index.js"
],
"env": {
"GOOGLE_API_KEY": "your_api_key_here",
"GOOGLE_CSE_ID": "your_search_engine_id_here"
}
}
}
}对于 Windows:
{
"mcpServers": {
"google_search": {
"command": "node",
"args": [
"C:\\absolute\\path\\to\\google-search-mcp\\dist\\index.js"
],
"env": {
"GOOGLE_API_KEY": "your_api_key_here",
"GOOGLE_CSE_ID": "your_search_engine_id_here"
}
}
}
}重启光标
测试您的服务器
与 Claude 一起使用
连接后,您可以通过向 Claude 询问以下问题来测试该工具:
“搜索有关可再生能源的最新消息”
“查找电动汽车的图像”
“日本最热门的旅游目的地有哪些?”
当需要时,Claude 会自动使用适当的搜索工具。
手动测试
您也可以直接测试您的服务器:
# Test web search
echo '{
"jsonrpc": "2.0",
"method": "callTool",
"params": {
"name": "google_web_search",
"arguments": {
"query": "test query",
"count": 2
}
},
"id": 1
}' | node dist/index.js幕后发生了什么
当你问一个问题时:
客户将您的问题发送给 Claude
Claude 分析可用的工具并决定使用哪一个
客户端通过您的 MCP 服务器执行所选工具
结果被发回给克劳德
Claude 根据搜索结果制定自然语言响应
响应将显示给您
故障排除
常见问题
环境变量
如果您看到Error: GOOGLE_API_KEY environment variable is required :
# Check your .env file
cat .env
# Try setting environment variables directly:
export GOOGLE_API_KEY=your_key_here
export GOOGLE_CSE_ID=your_id_hereAPI 错误
如果遇到 API 错误:
# Test your API credentials directly
curl "https://www.googleapis.com/customsearch/v1?key=YOUR_API_KEY&cx=YOUR_CX_ID&q=test"连接问题
如果您的客户端无法连接到服务器:
# Verify the server runs correctly on its own
node dist/index.js
# Check file permissions
chmod 755 dist/index.js
# Ensure you're using absolute paths in your configurationAPI 参考
google_web_search
使用 Google 的自定义搜索 API 执行网络搜索。
参数:
query(字符串,必需):搜索查询count(数字,可选):结果数量(1-10,默认5)start(数字,可选):分页起始索引(默认为 1)site(字符串,可选):将搜索限制在特定站点(例如“example.com”)
google_image_search
使用 Google 的自定义搜索 API 搜索图像。
参数:
query(字符串,必需):图像搜索查询count(数字,可选):结果数量(1-10,默认5)start(数字,可选):分页起始索引(默认为 1)
限制
Google 自定义搜索 API 免费套餐:每天 100 次查询
服务器强制速率限制:每秒 5 个请求
每个查询最多 10 个结果(Google API 限制)
执照
该项目根据 MIT 许可证获得许可 - 有关详细信息,请参阅 LICENSE 文件。
Available Tools
2 toolsgoogle_image_searchB
Searches for images using Google's Custom Search API. Best for finding images related to specific terms, concepts, or objects. Returns image URLs, titles, and thumbnails. Use this when needing to find relevant images or visual references.
| Name | Required | Description | Default |
|---|---|---|---|
| count | No | Number of results (1-10, default 5) | |
| query | Yes | Image search query | |
| start | No | Pagination start index (default 1) |
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 mentions the API source and return values (image URLs, titles, thumbnails) but lacks details on rate limits, authentication needs, error handling, or whether this is a read-only operation. For a search tool with external API dependencies, this leaves significant behavioral gaps.
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 appropriately sized and front-loaded: it starts with the core purpose, adds context about best use cases, specifies return values, and ends with usage guidance. Every sentence adds value without redundancy, making it efficient and well-structured.
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 moderate complexity (external API search with 3 parameters) and no annotations or output schema, the description is partially complete. It covers purpose, usage, and returns but lacks behavioral details like rate limits or error handling. It's adequate for basic use but insufficient for robust agent operation without additional context.
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?
The schema description coverage is 100%, so the schema already documents all three parameters (count, query, start) with their types, defaults, and constraints. The description adds no additional parameter semantics beyond what's in the schema, meeting the baseline for high schema coverage.
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 the tool's purpose: 'Searches for images using Google's Custom Search API' with specific resources (image URLs, titles, thumbnails) and distinguishes it from the sibling google_web_search by focusing on images rather than general web content. However, it doesn't explicitly name the sibling for comparison.
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 implied usage guidance: 'Best for finding images related to specific terms, concepts, or objects' and 'Use this when needing to find relevant images or visual references.' It suggests when to use it but doesn't explicitly mention when not to use it or directly compare it to the sibling google_web_search.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
google_web_searchA
Performs a web search using the Google Custom Search API, ideal for general queries, news, articles, and online content. Use this for broad information gathering, recent events, or when you need diverse web sources. Supports pagination and filtering by site or type. Maximum 10 results per request, with start index for pagination.
| Name | Required | Description | Default |
|---|---|---|---|
| count | No | Number of results (1-10, default 5) | |
| query | Yes | Search query | |
| site | No | Optional: Limit search to specific site (e.g., 'site:example.com') | |
| start | No | Pagination start index (default 1) |
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 mentions key behavioral traits: 'maximum 10 results per request', 'supports pagination and filtering by site or type', and 'start index for pagination'. However, it doesn't cover important aspects like rate limits, authentication requirements, error conditions, or what the response format looks like.
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 efficiently structured in three sentences that each serve distinct purposes: stating the core functionality, providing usage guidance, and disclosing behavioral constraints. Every sentence earns its place with no redundant information, making it appropriately sized and front-loaded.
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?
For a search tool with 4 parameters, 100% schema coverage, but no annotations and no output schema, the description provides adequate context about what the tool does and when to use it. However, it lacks information about the response format, error handling, and operational constraints like rate limits, which would be important for an API-based search tool.
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 100% schema description coverage, the input schema already documents all 4 parameters thoroughly. The description adds minimal value beyond what's in the schema - it mentions 'filtering by site or type' and 'pagination' which map to the 'site' and 'start' parameters, but doesn't provide additional semantic context beyond what the schema descriptions already offer.
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 the tool 'performs a web search using the Google Custom Search API' with specific examples of use cases (general queries, news, articles, online content). It distinguishes from the sibling tool 'google_image_search' by specifying this is for web content rather than images. However, it doesn't explicitly contrast with the sibling beyond the domain difference.
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 clear context for when to use this tool ('broad information gathering, recent events, or when you need diverse web sources'), which implicitly distinguishes it from the image search sibling. It doesn't explicitly state when NOT to use it or name alternatives beyond the implied contrast with image search.
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.
2 tool updates
v1.0.0- First observed
google_image_search - First observed
google_web_search
TDQS
Scored across 2 tools
The two tools have clearly distinct purposes: google_image_search is for finding images, while google_web_search is for general web content like articles and news. There is no overlap in functionality, making it easy for an agent to choose the correct tool based on the need for visual vs. textual information.
Both tools follow a consistent verb_noun pattern with 'google_' prefix and descriptive suffixes (_image_search, _web_search). The naming is uniform and predictable, adhering to snake_case throughout without any deviations or mixed conventions.
With only 2 tools, the server is minimal but reasonable for a search-focused domain, covering image and web searches. It might feel slightly thin if broader search capabilities (e.g., video, news-specific) were expected, but it's well-scoped for basic search needs without being overloaded.
For a Google Search server, the tools cover the core search operations: image and web searches. Minor gaps exist, such as lack of specialized search types (e.g., video, scholarly articles) or advanced filtering options, but agents can work around this with the provided tools for most common queries.
Maintenance
Related MCP Connectors
MCP server for Google search results via SERP API
Live AI-native web search with citations. One tool for every MCP client. Flat per-request pricing.
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
The Remote MCP server acts as a standardized bridge between LLM applications (like Claude, ChatGPT, and Cursor) and external services, enabling AI agents to access external tools and resources. Its primary capability is providing a centralized search tool to discover other MCP servers and their respective tools. Unlike local implementations, it runs remotely with OAuth authentication and permission controls for security.
Related MCP Servers
- 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
- AlicenseBqualityDmaintenanceA Model Context Protocol server that enables Claude to perform web research by integrating Google search, extracting webpage content, and capturing screenshots.31,175 npm20MIT
- AlicenseAqualityCmaintenanceA Model Context Protocol server that enables Claude to perform web research by integrating Google search, extracting webpage content, and capturing screenshots in real-time.41,175 npm9MIT