Skip to main content
Glama
mrgoonie

SearchAPI MCP Server

by mrgoonie

SearchAPI.site - MCP 服务器

该项目提供了一个模型上下文协议(MCP)服务器,通过SearchAPI.site将 AI 助手连接到外部数据源(Google、Bing 等)。

可用平台

  • [x] Google - 网页搜索

  • [x] Google - 图片搜索

  • [x] Google - YouTube 搜索

  • [ ] Google - 地图搜索

  • [x] Bing - 网页搜索

  • [ ] Bing - 图片搜索

  • [ ] 红迪网

  • [ ] X/推特

  • [ ] Facebook 搜索

  • [ ] Facebook 群组搜索

  • Instagram

  • [ ] 抖音

SearchAPI.site

Related MCP server: WebSearch-MCP

支持的传输

如何使用

命令行界面

# Google search via CLI
npm run dev:cli -- search-google --query "your search query" --api-key "your-api-key"

# Google image search via CLI
npm run dev:cli -- search-google-images --query "your search query" --api-key "your-api-key"

# YouTube search via CLI
npm run dev:cli -- search-youtube --query "your search query" --api-key "your-api-key" --max-results 5

MCP 设置

对于使用 stdio 传输的本地配置:

{
  "mcpServers": {
    "searchapi": {
      "command": "node",
      "args": ["/path/to/searchapi-mcp-server/dist/index.js"],
      "transportType": "stdio"
    }
  }
}

对于远程 HTTP 配置:

{
  "mcpServers": {
    "searchapi": {
      "type": "http",
      "url": "http://mcp.searchapi.site/mcp"
    }
  }
}

HTTP 传输的环境变量:

您可以使用以下环境变量配置 HTTP 服务器:

  • MCP_HTTP_HOST :绑定到的主机(默认值: 127.0.0.1

  • MCP_HTTP_PORT :监听的端口(默认值: 8080

  • MCP_HTTP_PATH :端点路径(默认值: /mcp


源代码概述

什么是 MCP?

模型上下文协议 (MCP) 是一种开放标准,允许 AI 系统安全且上下文地与外部工具和数据源连接。

该样板通过清晰的分层架构实现了 MCP 规范,可以扩展以构建任何 API 或数据源的自定义 MCP 服务器。

为什么要使用这个样板?

  • 生产就绪架构:遵循已发布的 MCP 服务器中使用的相同模式,CLI、工具、控制器和服务之间有明确的分离。

  • 类型安全:使用 TypeScript 构建,以改善开发人员体验、代码质量和可维护性。

  • 工作示例:包括一个完全实现的 IP 查找工具,演示从 CLI 到 API 集成的完整模式。

  • 测试框架:配备单元和 CLI 集成测试的测试基础设施,包括覆盖率报告。

  • 开发工具:包括 ESLint、Prettier、TypeScript 和其他为 MCP 服务器开发预先配置的质量工具。


入门

先决条件

  • Node.js (>=18.x):下载

  • Git :用于版本控制


步骤 1:克隆并安装

# Clone the repository
git clone https://github.com/mrgoonie/searchapi-mcp-server.git
cd searchapi-mcp-server

# Install dependencies
npm install

第 2 步:运行开发服务器

使用 stdio 传输(默认)以开发模式启动服务器:

npm run dev:server

或者使用 Streamable HTTP 传输:

npm run dev:server:http

这将以热重载方式启动 MCP 服务器,并在http://localhost:5173启用 MCP 检查器。

⚙️ 代理服务器正在监听 6277 端口 🔍 MCP Inspector 已启动并运行于http://127.0.0.1:6274

当使用 HTTP 传输时,服务器默认在http://127.0.0.1:8080/mcp上可用。


步骤 3:测试示例工具

从 CLI 运行示例 IP 查找工具:

# Using CLI in development mode
npm run dev:cli -- search-google --query "your search query" --api-key "your-api-key"

# Or with a specific IP
npm run dev:cli -- search-google --query "your search query" --api-key "your-api-key" --limit 10 --offset 0 --sort "date:d" --from_date "2023-01-01" --to_date "2023-12-31"

建筑学

该样板遵循清晰的分层架构模式,可分离关注点并提高可维护性。

项目结构

src/
├── cli/              # Command-line interfaces
├── controllers/      # Business logic
├── resources/        # MCP resources: expose data and content from your servers to LLMs
├── services/         # External API interactions
├── tools/            # MCP tool definitions
├── types/            # Type definitions
├── utils/            # Shared utilities
└── index.ts          # Entry point

层次和职责

CLI 层( src/cli/*.cli.ts

  • 目的:定义解析参数和调用控制器的命令行接口

  • 命名:文件应命名为<feature>.cli.ts

  • 测试<feature>.cli.test.ts中的 CLI 集成测试

工具层( src/tools/*.tool.ts

  • 目的:为人工智能助手定义带有模式和描述的 MCP 工具

  • 命名:文件应命名为<feature>.tool.ts ,类型为<feature>.types.ts

  • 模式:每个工具都应该使用 zod 进行参数验证

控制器层( src/controllers/*.controller.ts

  • 目的:实现业务逻辑、处理错误和格式化响应

  • 命名:文件应命名为<feature>.controller.ts

  • 模式:应返回标准化的ControllerResponse对象

服务层( src/services/*.service.ts

  • 目的:与外部 API 或数据源交互

  • 命名:文件应命名为<feature>.service.ts

  • 模式:纯 API 交互,逻辑最少

实用程序层 ( src/utils/*.util.ts )

  • 目的:提供跨应用程序的共享功能

  • 主要用途

    • logger.util.ts :结构化日志记录

    • error.util.ts :错误处理和标准化

    • formatter.util.ts :Markdown 格式化助手


开发指南

开发脚本

# Start server in development mode (hot-reload & inspector)
npm run dev:server

# Run CLI in development mode
npm run dev:cli -- [command] [args]

# Build the project
npm run build

# Start server in production mode
npm run start:server

# Run CLI in production mode
npm run start:cli -- [command] [args]

测试

# Run all tests
npm test

# Run specific tests
npm test -- src/path/to/test.ts

# Generate test coverage report
npm run test:coverage

评估

evals 包会加载一个 mcp 客户端,然后运行 index.ts 文件,因此测试之间无需重新构建。您可以通过在 npx 命令前添加前缀来加载环境变量。完整文档可在此处找到。

OPENAI_API_KEY=your-key  npx mcp-eval src/evals/evals.ts src/tools/searchapi.tool.ts

代码质量

# Lint code
npm run lint

# Format code with Prettier
npm run format

# Check types
npm run typecheck

构建自定义工具

按照以下步骤将您自己的工具添加到服务器:

1.定义服务层

src/services/中创建一个新服务来与您的外部 API 交互:

// src/services/example.service.ts
import { Logger } from '../utils/logger.util.js';

const logger = Logger.forContext('services/example.service.ts');

export async function getData(param: string): Promise<any> {
	logger.debug('Getting data', { param });
	// API interaction code here
	return { result: 'example data' };
}

2.创建控制器

src/controllers/中添加一个控制器来处理业务逻辑:

// src/controllers/example.controller.ts
import { Logger } from '../utils/logger.util.js';
import * as exampleService from '../services/example.service.js';
import { formatMarkdown } from '../utils/formatter.util.js';
import { handleControllerError } from '../utils/error-handler.util.js';
import { ControllerResponse } from '../types/common.types.js';

const logger = Logger.forContext('controllers/example.controller.ts');

export interface GetDataOptions {
	param?: string;
}

export async function getData(
	options: GetDataOptions = {},
): Promise<ControllerResponse> {
	try {
		logger.debug('Getting data with options', options);

		const data = await exampleService.getData(options.param || 'default');

		const content = formatMarkdown(data);

		return { content };
	} catch (error) {
		throw handleControllerError(error, {
			entityType: 'ExampleData',
			operation: 'getData',
			source: 'controllers/example.controller.ts',
		});
	}
}

3. 实现MCP工具

src/tools/中创建工具定义:

// src/tools/example.tool.ts
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { Logger } from '../utils/logger.util.js';
import { formatErrorForMcpTool } from '../utils/error.util.js';
import * as exampleController from '../controllers/example.controller.js';

const logger = Logger.forContext('tools/example.tool.ts');

const GetDataArgs = z.object({
	param: z.string().optional().describe('Optional parameter'),
});

type GetDataArgsType = z.infer<typeof GetDataArgs>;

async function handleGetData(args: GetDataArgsType) {
	try {
		logger.debug('Tool get_data called', args);

		const result = await exampleController.getData({
			param: args.param,
		});

		return {
			content: [{ type: 'text' as const, text: result.content }],
		};
	} catch (error) {
		logger.error('Tool get_data failed', error);
		return formatErrorForMcpTool(error);
	}
}

export function register(server: McpServer) {
	server.tool(
		'get_data',
		`Gets data from the example API, optionally using \`param\`.
Use this to fetch example data. Returns formatted data as Markdown.`,
		GetDataArgs.shape,
		handleGetData,
	);
}

4.添加CLI支持

src/cli/中创建 CLI 命令:

// src/cli/example.cli.ts
import { program } from 'commander';
import { Logger } from '../utils/logger.util.js';
import * as exampleController from '../controllers/example.controller.js';
import { handleCliError } from '../utils/error-handler.util.js';

const logger = Logger.forContext('cli/example.cli.ts');

program
	.command('get-data')
	.description('Get example data')
	.option('--param <value>', 'Optional parameter')
	.action(async (options) => {
		try {
			logger.debug('CLI get-data called', options);

			const result = await exampleController.getData({
				param: options.param,
			});

			console.log(result.content);
		} catch (error) {
			handleCliError(error);
		}
	});

5. 注册组件

更新入口点以注册新组件:

// In src/cli/index.ts
import '../cli/example.cli.js';

// In src/index.ts (for the tool)
import exampleTool from './tools/example.tool.js';
// Then in registerTools function:
exampleTool.register(server);

调试工具

MCP 检查器

访问可视化 MCP 检查器来测试您的工具并查看请求/响应详细信息:

  1. 运行npm run dev:server

  2. 在浏览器中打开http://localhost:5173

  3. 测试您的工具并直接在 UI 中查看日志

服务器日志

启用开发调试日志:

# Set environment variable
DEBUG=true npm run dev:server

# Or configure in ~/.mcp/configs.json

发布您的 MCP 服务器

准备发布您的自定义 MCP 服务器时:

  1. 使用您的详细信息更新 package.json

  2. 使用您的工具文档更新 README.md

  3. 构建项目: npm run build

  4. 测试生产版本: npm run start:server

  5. 发布到 npm: npm publish


执照

ISC 许可证

{
	"searchapi": {
		"environments": {
			"DEBUG": "true",
			"SEARCHAPI_API_KEY": "value"
		}
	}
}

**注意:**为了向后兼容,如果未找到searchapi键,服务器也会识别完整软件包名称 ( searchapi-mcp-server ) 或未指定范围的软件包名称 ( searchapi-mcp-server ) 下的配置。不过,建议对新配置使用短searchapi键。

Available Tools

3 tools
search_googleC

Performs a Google search using SearchAPI.site. Requires a search "query" string, can be able to search multiple keywords that separated by commas. Returns formatted search results including titles, snippets, and links.

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYesThe search query to perform
limitNoMaximum number of results to return (1-100)
offsetNoOffset for pagination
sortNoSort order (e.g., "date:d" for newest first)
from_dateNoStart date for filtering results (format: YYYY-MM-DD)
to_dateNoEnd date for filtering results (format: YYYY-MM-DD)

TDQS

C2.8/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It states the tool 'Returns formatted search results including titles, snippets, and links,' which gives some output context, but lacks critical behavioral details like rate limits, authentication requirements, error handling, pagination behavior (beyond the offset parameter), or whether this is a read-only operation. The mention of 'SearchAPI.site' hints at a third-party service but doesn't explain implications.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness3/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is reasonably concise with three sentences, but it's not optimally front-loaded. The first sentence states the purpose, but the second sentence awkwardly mixes parameter guidance ('Requires a search "query" string') with feature description ('can be able to search multiple keywords'). The third sentence covers return values. Some redundancy exists (e.g., 'query' is mentioned twice), and the structure could be tighter for better clarity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations, no output schema, and 6 parameters (though well-documented in schema), the description is incomplete. It lacks behavioral context (e.g., rate limits, auth), doesn't explain the relationship with sibling tools, and provides minimal guidance on usage. For a search tool with multiple parameters and no structured output definition, more contextual information would be helpful for an AI agent to use it effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all 6 parameters thoroughly. The description adds minimal value beyond the schema: it mentions the query parameter and that it 'can be able to search multiple keywords that separated by commas' (though awkwardly phrased), but doesn't explain other parameters like limit, offset, sort, from_date, or to_date. Baseline 3 is appropriate when schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool 'Performs a Google search using SearchAPI.site' with a specific verb ('Performs') and resource ('Google search'), distinguishing it from sibling tools like search_google_images and search_youtube by focusing on general web search. However, it doesn't explicitly contrast with siblings beyond the different search types.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

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 like search_google_images or search_youtube. It mentions the tool can search multiple keywords separated by commas, but this is more about parameter usage than contextual guidance. No explicit when/when-not instructions or alternative recommendations are included.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

search_google_imagesB

Performs a Google image search using SearchAPI.site. Requires a search query and your SearchAPI.site API key. Returns formatted image search results including titles, thumbnails, and source links.

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYesThe image search query to perform
limitNoMaximum number of results to return (1-100)
offsetNoOffset for pagination
sortNoSort order (e.g., "date:d" for newest first)
from_dateNoStart date for filtering results (format: YYYY-MM-DD)
to_dateNoEnd date for filtering results (format: YYYY-MM-DD)

TDQS

B3.2/5.0
Behavior3/5

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 key requirement (authentication need) and describes the return format ('formatted image search results including titles, thumbnails, and source links'), which adds value beyond the input schema. However, it doesn't mention rate limits, error conditions, or other behavioral traits like whether results are cached or real-time.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized with three concise sentences that each add value: what it does, what it requires, and what it returns. It's front-loaded with the core purpose. There's minimal waste, though it could be slightly more structured with bullet points for the three key pieces of information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 6 parameters, 100% schema coverage, but no annotations and no output schema, the description provides adequate but incomplete context. It covers the purpose, authentication requirement, and return format, but doesn't address error handling, rate limits, or provide examples. The absence of an output schema means the description's mention of return format is helpful but could be more detailed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all 6 parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema - it mentions 'search query' and 'API key' but doesn't explain parameter interactions, defaults, or usage examples. Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool 'performs a Google image search using SearchAPI.site' which is a specific verb+resource combination. It distinguishes itself from sibling tools like 'search_google' and 'search_youtube' by specifying it's for images, though it doesn't explicitly contrast with them in the description text itself.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description mentions the requirement for a SearchAPI.site API key, which provides some usage context. However, it offers no guidance on when to use this tool versus the sibling tools (search_google, search_youtube) or any alternatives. There's no explicit 'when' or 'when not' guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

search_youtubeB

Performs a YouTube search using SearchAPI.site. Requires a search query and your SearchAPI.site API key. Returns formatted YouTube search results including video titles, thumbnails, descriptions, and links. Supports optional parameters for pagination, sorting, filtering by date and duration.

ParametersJSON Schema
NameRequiredDescriptionDefault
queryYesThe YouTube search query to perform
maxResultsNoMaximum number of results to return (1-50)
pageTokenNoToken for pagination to get next/previous page of results
orderNoSort order for results
publishedAfterNoNumber of days to filter videos from
videoDurationNoFilter by video duration

TDQS

B3.4/5.0
Behavior3/5

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 key requirement (auth needs) and describes the return format (video titles, thumbnails, descriptions, links), which adds value beyond the input schema. However, it doesn't cover rate limits, error handling, or other operational constraints.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized with four sentences that each add value: purpose, requirements, returns, and optional features. It's front-loaded with core functionality. Minor improvement could come from tighter phrasing, but there's no wasted content.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a search tool with 6 parameters, 100% schema coverage, and no output schema, the description provides adequate context on what the tool does and returns. However, without annotations or output schema, it lacks details on response structure, error cases, or performance characteristics that would help an agent use it effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all 6 parameters thoroughly. The description adds minimal value by listing optional parameters (pagination, sorting, filtering by date and duration) but doesn't provide additional syntax, format, or usage details beyond what's in the schema. This meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Performs a YouTube search') and resource ('using SearchAPI.site'), distinguishing it from sibling tools like search_google and search_google_images by specifying YouTube as the search target. It provides a complete verb+resource+scope combination.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description mentions when to use this tool (for YouTube searches) but provides no guidance on when to choose it versus the sibling tools search_google or search_google_images. There's no explicit comparison or exclusion criteria, leaving the agent to infer usage context.

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. Dates show when Glama detected each change.

  1. 3 tool updates
    • First observedsearch_google
    • First observedsearch_google_images
    • First observedsearch_youtube

TDQS

B3.4/5.0
Disambiguation5/5

Each tool has a clearly distinct purpose targeting a specific search type: Google web search, Google image search, and YouTube search. The descriptions explicitly differentiate them by platform and result format, with no overlap in functionality that could cause confusion.

Naming Consistency5/5

All tools follow a consistent verb_noun pattern with 'search_' prefix followed by the target platform (google, google_images, youtube). This predictable naming scheme makes it easy for agents to understand and select the appropriate tool.

Tool Count4/5

Three tools is reasonable for a search API server, covering major search platforms. However, it feels slightly thin—adding tools for other platforms (like news or shopping search) could make it more comprehensive, but the current count is appropriate for the core functionality.

Completeness4/5

The toolset covers the essential search operations for Google web, images, and YouTube, which aligns well with the server's purpose. A minor gap is the lack of a general search tool that could handle other platforms or unified search, but agents can work effectively with the provided tools.

Maintenance

ActivityInactive
ResponsivenessUnresponsive

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • F
    license
    B
    quality
    D
    maintenance
    Implements the Model Context Protocol (MCP) to provide AI models with a standardized interface for connecting to external data sources and tools like file systems, databases, or APIs.
    1
    153
    -
  • A
    license
    B
    quality
    C
    maintenance
    A Model Context Protocol server that enables AI assistants to perform real-time web searches, retrieving up-to-date information from the internet via a Crawler API.
    1
    62
    40
    ISC

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/mrgoonie/searchapi-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server