MCP Brave搜索服务器
通过Brave search进行网络搜索
🚀 特性
- TypeScript:具有现代TypeScript模式的完全类型安全
- JSON API集成:通过Brave search JSON API快速准确的搜索结果
- HTTP传输:带有Express.js服务器的RESTful API
- 会话管理:具有适当会话处理的有状态连接
- 配置管理:基于环境的配置和验证
- 错误处理:全面的错误处理和记录
- 健康检查:内置健康监测端点
- Docker支持:生产就绪的集装箱化
- 开发工具:ESLint、Prettier和测试设置
- 生产就绪:针对可扩展性和安全性进行了优化
📋 先决条件
- Node.js 20+
- npm或纱线
- Docker(可选,用于容器化)
🛠️ 快速开始
选项1:使用项目生成器(推荐)
# Clone the template
git clone
cd mcp-brave-search
# Create a new project using the generator
./create-mcp-project your-project-name --description "Your project description" --author "Your Name"
# Or use the Node.js script directly
node setup-new-project.js your-project-name --description "Your project description" --author "Your Name"发电机选项:
--description:项目描述--author:作者姓名--target-dir:目标目录(默认:mcp-
)
--install-deps:自动安装npm依赖项--no-git:跳过git存储库初始化
选项2:手动设置
# Clone the template
git clone
cd mcp-brave-search
# Install dependencies
npm install
# Copy environment configuration
cp .env.example .env # Create this file with your settings2.API密钥设置
在使用服务器之前,您需要获得Brave Search API密钥:
- 访问 勇敢搜索API仪表板
- 注册帐户或登录
- 创建新的API订阅
- 从仪表板复制API密钥
3.环境配置
创建一个 .env 根目录中的文件:
# Server Configuration
PORT=3000
LOG_LEVEL=info
# Brave Search API Configuration
BRAVE_API_KEY=your_brave_search_api_key_here
# Add your custom environment variables here4.发展
# Start development server with hot reload
npm run dev
# Build for production
npm run build
# Start production server
npm start
# Run tests
npm test
# Lint and format code
npm run lint
npm run lint:fix🏗️ 项目结构
mcp-brave-search/
├── src/
│ ├── config/ # Configuration management
│ │ └── index.ts # Main config file
│ ├── domain/ # Core business logic
│ │ └── brave.ts # Brave Search API integration
│ ├── types.ts # TypeScript type definitions
│ └── index.ts # Main server application
├── tests/ # Test files
│ ├── integration/ # Integration tests
│ └── setup.ts # Test setup utilities
├── create-mcp-project # Bash script for project generation
├── setup-new-project.js # Node.js project generator
├── Dockerfile # Docker configuration
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript configuration
└── README.md # This file🔧 项目生成器
此模板包括强大的项目生成工具,可快速创建新的MCP服务器:
特征:
- 自动名称转换:将烤肉串案例名称转换为所有必需的格式(camelCase、PascalCase等)
- 文件模板:使用新的项目名称和详细信息更新所有文件
- Git集成:可选择初始化新的git存储库
- 依赖管理:可以自动安装npm依赖项
- 智能复制逻辑:排除开发文件并防止无限递归
使用示例:
# Basic usage
./create-mcp-project weather-service
# With full options
./create-mcp-project task-manager \
--description "AI-powered task management MCP server" \
--author "Your Name" \
--install-deps
# Custom target directory
./create-mcp-project file-processor --target-dir ./my-custom-server
# Skip git initialization
./create-mcp-project data-analyzer --no-git🔧 建筑
核心组件
- McpServerApp:编排MCP服务器的主应用程序类
- 勇敢的搜索集成:与Brave Search直接集成JSON API
- 配置:具有类型安全和API密钥管理的基于环境的配置
- 会话管理:具有清理功能的基于HTTP的有状态会话
- 传输层:用于MCP通信的StreamableHTTPServerTransport
- 错误处理:使用正确的HTTP响应进行全面的错误处理
HTTP端点
GET /health-健康检查端点POST /mcp-主MCP通信端点GET /mcp-通过SSE发送服务器到客户端的通知DELETE /mcp-会话终止
🛠️ 定制指南
添加新工具
要添加新的MCP工具,请修改 createServer() 方法in src/index.ts:
// Register your custom tool
server.tool(
'brave_web_search',
'Search the web using Brave Search API',
{
// Define input schema using Zod
query: z.string().describe('Search query'),
count: z
.number()
.optional()
.describe('Number of results to return (default: 10)'),
safesearch: z
.enum(['strict', 'moderate', 'off'])
.optional()
.describe('SafeSearch level'),
},
async ({ query, count, safesearch }) => {
try {
// Your tool implementation here
const result = await performWebSearch({ query, count, safesearch });
return {
content: [
{
type: 'text',
text: result,
} as TextContent,
],
};
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
throw new Error(`Error in brave_web_search: ${errorMessage}`);
}
}
);配置管理
在中添加新的配置选项 src/config/index.ts:
interface Config {
logging: LoggingConfig;
server: ServerConfig;
// Add your custom config sections
brave: {
apiKey: string;
baseUrl: string;
};
database: {
url: string;
timeout: number;
};
}
const config: Config = {
// ... existing config
brave: {
apiKey: process.env.BRAVE_API_KEY || '',
baseUrl: 'https://api.search.brave.com/res/v1/web/search',
},
database: {
url: process.env.DATABASE_URL || 'sqlite://memory',
timeout: parseInt(process.env.DB_TIMEOUT || '5000', 10),
},
};添加中间件
在中添加Express中间件 run() 方法:
async run() {
const app = express();
app.use(express.json());
// Add your custom middleware
app.use(cors()); // CORS support
app.use(helmet()); // Security headers
app.use(morgan('combined')); // Request logging
// ... rest of the setup
}🐳 Docker部署
构建并运行
# Build Docker image
docker build -t mcp-brave-search-server .
# Run container
docker run -p 3000:3000 --env-file .env mcp-brave-search-serverDocker Compose(推荐)
创建一个 docker-compose.yml:
version: '3.8'
services:
mcp-server:
build: .
ports:
- '3000:3000'
environment:
- NODE_ENV=production
- PORT=3000
- LOG_LEVEL=info
- BRAVE_API_KEY=${BRAVE_API_KEY}
restart: unless-stopped
healthcheck:
test: ['CMD', 'curl', '-f', 'http://localhost:3000/health']
interval: 30s
timeout: 10s
retries: 3运行方式:
docker-compose up -d🔒 安全最佳实践
此模板实现了多种安全措施:
- 输入验证:所有工具参数的Zod模式验证
- 错误处理:无信息泄露的安全错误响应
- 会话管理:适当的会话清理和验证
- HTTP安全:已准备好进行安全标头和CORS配置
- 环境变量:安全配置管理
建议的附加安全措施
// Add security middleware
import helmet from 'helmet';
import cors from 'cors';
import rateLimit from 'express-rate-limit';
app.use(helmet());
app.use(
cors({
origin: process.env.ALLOWED_ORIGINS?.split(',') || false,
})
);
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
});
app.use('/mcp', limiter);📊 监控和日志记录
该模板包括基本的日志记录设置。对于生产,考虑添加:
- 结构化日志记录:Winston,JSON格式
- 指标收集:普罗米修斯指标
- 健康检查:综合健康终点
- APM集成:应用程序性能监控
🧪 测试
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage写作测试
在中创建测试文件 src/**/*.test.ts:
import { describe, test, expect } from '@jest/globals';
// Your test imports
describe('YourComponent', () => {
test('should handle valid input', async () => {
// Test implementation
});
});🚀 生产部署
环境变量
NODE_ENV=production
PORT=3000
LOG_LEVEL=warn
# Brave Search API Configuration
BRAVE_API_KEY=your_production_brave_api_key
# Add your production-specific variables
DATABASE_URL=postgresql://...
REDIS_URL=redis://...性能优化
- 启用gzip压缩
- 实现正确的缓存标头
- 对数据库使用连接池
- 监控内存使用情况并实施限制
- 设置日志轮换
缩放注意事项
- 跨多个实例的负载平衡
- 数据库连接池
- 会话存储外部化(Redis)
- Kubernetes中的水平pod自动缩放
📚 参考文献
🤝 贡献
- 分叉存储库
- 创建要素分支
- 进行更改
- 添加新功能的测试
- 运行测试套件
- 提交拉取请求
📝 许可证
此项目根据MIT许可证获得许可-有关详细信息,请参阅许可证文件。
🆘 支持
如有疑问和支持:
- 检查 MCP文件
- 审查现有问题
- 创建包含详细信息的新问题
______________________________________________________________________
编码愉快! 🎉
