MCP Secure Server
A secure MCP server with authentication, rate limiting, and tools for querying records and managing integrations.
README
MCP Secure Server
A secure Model Context Protocol (MCP) server implementation with HMAC-signed token authentication, rate limiting, and comprehensive audit logging.
Features
🔒 Security
- HMAC-signed API tokens with expiration and scope-based access control
- Rate limiting (configurable, default: 60 requests/minute)
- Timestamp validation to prevent replay attacks (5-minute window)
- Comprehensive audit logging for all operations
- Secrets management via environment variables
🛠️ Tools
- ping - Returns server status and timestamp
- search_records - Query a local dataset with filtering options
- create_integration - Persist integration configurations locally
📊 Monitoring & Observability
- Structured logging with Winston
- Audit trail for security events
- Rate limiting headers
- Health check endpoint
Quick Start
1. Installation
git clone <repository-url>
cd mcp-secure-server
npm install
2. Environment Setup
cp .env.example .env
# Edit .env with your configuration
Important: Change the default secrets in production!
3. Initialize Data Directories
npm run setup
4. Development
# Start in development mode
npm run dev
# Or build and start
npm run build
npm start
The server will start on http://localhost:3000 (configurable via PORT environment variable).
Environment Variables
| Variable | Description | Default |
|---|---|---|
PORT |
Server port | 3000 |
NODE_ENV |
Environment | development |
JWT_SECRET |
JWT signing secret | ⚠️ Change in production |
HMAC_SECRET |
HMAC signing secret | ⚠️ Change in production |
TOKEN_EXPIRY |
Token expiration (seconds) | 3600 |
MAX_TOKEN_AGE_MINUTES |
Max token age for replay protection | 5 |
RATE_LIMIT_WINDOW_MS |
Rate limit window | 60000 |
RATE_LIMIT_MAX_REQUESTS |
Max requests per window | 60 |
RECORDS_PATH |
Path to records dataset | ./data/records.json |
INTEGRATIONS_PATH |
Path to integrations storage | ./data/integrations.json |
LOG_LEVEL |
Logging level | info |
AUDIT_LOG_FILE |
Audit log file path | ./logs/audit.log |
API Documentation
Authentication
All MCP endpoints require a Bearer token in the Authorization header:
Authorization: Bearer <your-token>
Generate Token
Generate a new API token:
POST /auth/token
Content-Type: application/json
{
"userId": "your-user-id",
"scope": "read" // or "write"
}
Response:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"userId": "your-user-id",
"scope": "read",
"expiresIn": 3600
}
Health Check
Check server status (no authentication required):
GET /health
Response:
{
"status": "ok",
"timestamp": "2024-03-07T10:30:00.000Z",
"version": "1.0.0"
}
List Tools
Get available tools:
POST /mcp/tools/list
Content-Type: application/json
Authorization: Bearer <token>
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list"
}
Response:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"tools": [
{
"name": "ping",
"description": "Returns server status and current timestamp",
"inputSchema": {
"type": "object",
"properties": {},
"required": []
}
},
// ... other tools
]
}
}
Tool Execution
Execute a tool:
POST /mcp/tools/call
Content-Type: application/json
Authorization: Bearer <token>
{
"jsonrpc": "2.0",
"id": 1,
"method": "<tool-name>",
"params": { /* tool-specific parameters */ }
}
Tools Reference
1. ping
Returns server status and timestamp.
Scope Required: Any (read/write)
Parameters: None
Example:
curl -X POST http://localhost:3000/mcp/tools/call \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <token>" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "ping",
"params": {}
}'
Response:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"status": "ok",
"timestamp": "2024-03-07T10:30:00.000Z",
"serverTime": 1709810200000,
"uptime": 3600.5,
"version": "1.0.0"
}
}
2. search_records
Search through local dataset records.
Scope Required: read or write
Parameters:
query(optional): Text search querycategory(optional): Filter by categorytags(optional): Array of tags to filter by (AND operation)limit(optional): Maximum results (1-100, default: 10)
Example:
curl -X POST http://localhost:3000/mcp/tools/call \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <token>" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "search_records",
"params": {
"query": "API",
"category": "Security",
"tags": ["auth", "jwt"],
"limit": 5
}
}'
Response:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"records": [
{
"id": "rec_002",
"name": "User Authentication Service",
"description": "OAuth2 and JWT-based authentication service",
"category": "Security",
"tags": ["auth", "oauth2", "jwt", "security"],
"data": { /* ... */ },
"createdAt": "2024-01-10T09:15:00.000Z",
"updatedAt": "2024-02-10T16:45:00.000Z"
}
],
"total": 1,
"query": "API",
"filters": {
"category": "Security",
"tags": ["auth", "jwt"]
}
}
}
3. create_integration
Create and persist a new integration configuration.
Scope Required: write
Parameters:
name(required): Integration name (1-100 chars)type(required): One of:webhook,api,database,file,customconfig(required): Configuration object (type-specific validation)
Type-specific config requirements:
webhook:config.url(string)api:config.endpoint(string)database:config.connectionString(string)file:config.path(string)custom: any object
Example:
curl -X POST http://localhost:3000/mcp/tools/call \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <write-token>" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "create_integration",
"params": {
"name": "Payment Webhook",
"type": "webhook",
"config": {
"url": "https://api.example.com/webhooks/payments",
"method": "POST",
"headers": {
"Authorization": "Bearer secret",
"Content-Type": "application/json"
},
"retries": 3
}
}
}'
Response:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"integration": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Payment Webhook",
"type": "webhook",
"config": {
"url": "https://api.example.com/webhooks/payments",
"method": "POST",
"headers": { /* ... */ },
"retries": 3
},
"createdAt": "2024-03-07T10:30:00.000Z",
"updatedAt": "2024-03-07T10:30:00.000Z",
"userId": "your-user-id"
},
"message": "Integration created successfully"
}
}
Security Features
HMAC Token Authentication
Tokens are JWT-signed with an additional HMAC signature for enhanced security:
- JWT Layer: Standard JWT with RSA/HMAC signing
- HMAC Layer: Additional HMAC-SHA256 signature of the payload
- Double Verification: Both signatures must be valid
Scope-based Access Control
- read: Can access
pingandsearch_records - write: Can access all tools including
create_integration
Replay Attack Protection
- Tokens include creation timestamp
- Requests are rejected if token is older than
MAX_TOKEN_AGE_MINUTES(default: 5 minutes) - Use fresh tokens for each session
Rate Limiting
- Per-token rate limiting using token hash
- Configurable limits via environment variables
- Rate limit headers included in responses:
X-RateLimit-LimitX-RateLimit-RemainingX-RateLimit-Reset
Audit Logging
All operations are logged with:
- Timestamp
- User ID
- Tool/method called
- Success/failure status
- Response latency
- Error details (if any)
- Client IP (if available)
Audit logs are stored separately from application logs for security compliance.
Testing
Automated Test Suite
Run the comprehensive test suite:
# Run all tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watch
Postman Collection
A complete Postman collection is available for API testing:
📁 postman/ directory contains:
MCP-Secure-Server.postman_collection.json- 25+ API requestsMCP-Server-Environment.postman_environment.json- Environment setupREADME.md- Detailed usage instructions
Quick Setup:
- Import both files into Postman
- Start the server:
npm start - Run the collection for automated testing
Features:
- ✅ 60+ automated test assertions
- ✅ Complete security testing scenarios
- ✅ Authentication & authorization tests
- ✅ Rate limiting validation
- ✅ Error handling verification
- ✅ JSON-RPC 2.0 compliance checks
Test Coverage
The test suite covers:
- ✅ Token generation and validation
- ✅ HMAC signature verification
- ✅ Expired token rejection
- ✅ Replay attack protection
- ✅ Scope validation
- ✅ Rate limiting
- ✅ All tool functionality
- ✅ Error handling
- ✅ Integration tests
Sample Requests
Complete Workflow Example
# 1. Generate a read token
READ_TOKEN=$(curl -s -X POST http://localhost:3000/auth/token \
-H "Content-Type: application/json" \
-d '{"userId": "demo-user", "scope": "read"}' | \
jq -r '.token')
# 2. Generate a write token
WRITE_TOKEN=$(curl -s -X POST http://localhost:3000/auth/token \
-H "Content-Type: application/json" \
-d '{"userId": "demo-user", "scope": "write"}' | \
jq -r '.token')
# 3. List available tools
curl -X POST http://localhost:3000/mcp/tools/list \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $READ_TOKEN" \
-d '{"jsonrpc": "2.0", "id": 1}'
# 4. Ping the server
curl -X POST http://localhost:3000/mcp/tools/call \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $READ_TOKEN" \
-d '{"jsonrpc": "2.0", "id": 1, "method": "ping", "params": {}}'
# 5. Search for API-related records
curl -X POST http://localhost:3000/mcp/tools/call \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $READ_TOKEN" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "search_records",
"params": {"query": "API", "limit": 3}
}'
# 6. Create an integration (requires write token)
curl -X POST http://localhost:3000/mcp/tools/call \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $WRITE_TOKEN" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "create_integration",
"params": {
"name": "Demo API Integration",
"type": "api",
"config": {
"endpoint": "https://jsonplaceholder.typicode.com/posts",
"method": "GET",
"timeout": 5000
}
}
}'
Development
Project Structure
mcp-secure-server/
├── src/
│ ├── auth/ # Authentication logic
│ ├── middleware/ # Express middleware
│ ├── tools/ # MCP tools implementation
│ ├── types/ # TypeScript type definitions
│ ├── utils/ # Utilities (config, logging)
│ ├── __tests__/ # Test files
│ └── index.ts # Main server file
├── data/ # JSON data files
├── logs/ # Log files
├── .env.example # Environment variables template
└── package.json
Adding New Tools
- Create tool implementation in
src/tools/ - Export tool schema and handler
- Register in
src/index.ts - Add tests in
src/__tests__/
Scripts
npm run dev- Start development server with hot reloadnpm run build- Build TypeScript to JavaScriptnpm start- Start production servernpm test- Run test suitenpm run lint- Type check with TypeScriptnpm run setup- Initialize data directories and environment
Security Best Practices
- Change default secrets in production environments
- Use HTTPS in production
- Set strong environment variables for JWT and HMAC secrets
- Monitor audit logs regularly
- Implement additional rate limiting at reverse proxy level
- Regularly rotate secrets
- Use scoped tokens - generate read tokens for read-only operations
Production Deployment
- Set
NODE_ENV=production - Configure strong secrets in environment variables
- Set up proper log rotation
- Configure reverse proxy (nginx/Apache) with HTTPS
- Set up monitoring and alerting
- Implement backup strategies for data files
License
MIT
Contributing
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
Support
For issues and questions, please use the GitHub issue tracker.
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。