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 助手就可以执行搜索并访问当前信息。

核心 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 云平台设置

  1. 前往Google Cloud Console
  2. 创建新项目
  3. 启用自定义搜索 API:
    Navigate to "APIs & Services" → "Library" Search for "Custom Search API" Click on "Custom Search API" → "Enable"
  4. 创建 API 凭证:
    Navigate to "APIs & Services" → "Credentials" Click "Create Credentials" → "API key" Copy your API key

自定义搜索引擎设置

  1. 前往可编程搜索引擎
  2. 点击“添加”创建新的搜索引擎
  3. 选择“搜索整个网络”并命名您的搜索引擎
  4. 从控制面板获取您的搜索引擎 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

  1. 打开您的配置文件:
code ~/Library/Application\ Support/Claude/claude_desktop_config.json
  1. 添加服务器配置:
{ "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" } } } }

视窗

  1. 打开您的配置文件:
code $env:AppData\Claude\claude_desktop_config.json
  1. 添加服务器配置:
{ "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" } } } }
  1. 重启 Claude 桌面版
  2. 通过单击界面中的工具图标来验证工具是否出现

与 Claude 一起编写 VSCode

macOS/Linux 和 Windows

  1. 安装VSCode 的 MCP 扩展
  2. 在您的工作区中创建或编辑.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" } } } }
  1. 重启 VSCode
  2. 这些工具将在 VSCode 中提供给 Claude

光标

  1. 打开光标设置(齿轮图标)
  2. 搜索“MCP”并打开 MCP 设置
  3. 点击“添加新的 MCP 服务器”
  4. 使用与上述类似的设置进行配置:

对于 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" } } } }
  1. 重启光标

测试您的服务器

与 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

幕后发生了什么

当你问一个问题时:

  1. 客户将您的问题发送给 Claude
  2. Claude 分析可用的工具并决定使用哪一个
  3. 客户端通过您的 MCP 服务器执行所选工具
  4. 结果被发回给克劳德
  5. Claude 根据搜索结果制定自然语言响应
  6. 响应将显示给您

故障排除

常见问题

环境变量

如果您看到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_here

API 错误

如果遇到 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 configuration

API 参考

使用 Google 的自定义搜索 API 执行网络搜索。

参数:

  • query (字符串,必需):搜索查询
  • count (数字,可选):结果数量(1-10,默认5)
  • start (数字,可选):分页起始索引(默认为 1)
  • site (字符串,可选):将搜索限制在特定站点(例如“example.com”)

使用 Google 的自定义搜索 API 搜索图像。

参数:

  • query (字符串,必需):图像搜索查询
  • count (数字,可选):结果数量(1-10,默认5)
  • start (数字,可选):分页起始索引(默认为 1)

限制

  • Google 自定义搜索 API 免费套餐:每天 100 次查询
  • 服务器强制速率限制:每秒 5 个请求
  • 每个查询最多 10 个结果(Google API 限制)

执照

该项目根据 MIT 许可证获得许可 - 有关详细信息,请参阅 LICENSE 文件。

ID: 5pgk82sfi7