Content
# MCP Server Wrapper
A powerful MCP (Model Context Protocol) client server wrapper for intercepting, mapping, and wrapping MCP client requests, enabling them to use features that some MCP clients do not natively support.
## Features
### Core Features
- **Request Interception**: Intercept and modify requests sent to the upstream server
- **Response Interception**: Intercept and modify responses from the upstream server
- **Request Mapping**: Map old API methods to new methods
- **Response Mapping**: Transform and enhance response data
### Enhanced Features
- **Cache**: Automatically cache responses for specified methods, reducing duplicate requests
- **Retry**: Automatically retry failed requests, supporting exponential backoff
- **Rate Limiting**: Limit request frequency to prevent overload
- **Logging**: Detailed request/response logs
- **Middleware System**: Flexible middleware chain supporting custom processing logic
## Installation
```bash
npm install
```
## Quick Start
### Basic Usage
```typescript
import { createMCPWrapper } from './src';
import { WrapperConfig } from './src/types/wrapper';
// Create configuration
const config: WrapperConfig = {
upstream: {
type: 'stdio',
command: 'node',
args: ['mcp-server.js'],
},
listen: {
type: 'stdio',
},
features: {
logging: {
enabled: true,
level: 'info',
},
cache: {
enabled: true,
ttl: 300,
methods: ['tools/list', 'resources/list'],
},
},
};
// Create wrapper
const wrapper = createMCPWrapper(config);
// Add request interceptor
wrapper.addRequestInterceptor(async (request) => {
console.log('Intercepted request:', request.method);
return request;
});
// Start wrapper
await wrapper.start();
// Handle request
const response = await wrapper.handleRequest({
jsonrpc: '2.0',
id: 1,
method: 'tools/list',
});
console.log('Response:', response);
```
### Add Request Mapping
```typescript
// Map old method to new method
wrapper.addRequestMappingRule({
match: {
method: 'tools/execute', // Old method name
},
transform: async (request) => {
return {
...request,
method: 'tools/call', // New method name
};
},
priority: 10,
});
```
### Add Custom Middleware
```typescript
// Authentication middleware
wrapper.addMiddleware(async (request, next) => {
const token = request.params?._auth?.token;
if (!token) {
return {
jsonrpc: '2.0',
id: request.id,
error: {
code: 401,
message: 'Unauthorized',
},
};
}
return next(request);
});
```
## Configuration Options
### WrapperConfig
```typescript
interface WrapperConfig {
// Upstream server configuration
upstream: {
type: 'stdio' | 'websocket' | 'http';
command?: string; // Command for stdio mode
args?: string[]; // Arguments for stdio mode
url?: string; // URL for websocket/http mode
};
// Listen configuration
listen: {
type: 'stdio' | 'websocket' | 'http';
port?: number; // Port for websocket/http mode
host?: string; // Host for websocket/http mode
};
// Feature configuration
features?: {
// Cache configuration
cache?: {
enabled: boolean;
ttl?: number; // Cache time (seconds)
methods?: string[]; // Methods to cache
};
// Retry configuration
retry?: {
enabled: boolean;
maxRetries?: number; // Maximum number of retries
retryDelay?: number; // Retry delay (milliseconds)
retryMethods?: string[]; // Methods to retry
};
// Rate limit configuration
rateLimit?: {
enabled: boolean;
maxRequests?: number; // Maximum number of requests in the time window
windowMs?: number; // Time window (milliseconds)
};
// Logging configuration
logging?: {
enabled: boolean;
level?: 'debug' | 'info' | 'warn' | 'error';
logRequests?: boolean;
logResponses?: boolean;
};
};
}
```
## Examples
### Run Basic Example
```bash
npm run build
npm run example
```
### Run Advanced Example
```bash
npm run build
node dist/examples/advanced-usage.js
```
## API Documentation
### MCPWrapper
The main wrapper class.
#### Methods
- `start()`: Start the wrapper
- `stop()`: Stop the wrapper
- `handleRequest(request)`: Handle an MCP request
- `handleNotification(notification)`: Handle an MCP notification
- `addRequestInterceptor(interceptor)`: Add a request interceptor
- `addResponseInterceptor(interceptor)`: Add a response interceptor
- `addNotificationInterceptor(interceptor)`: Add a notification interceptor
- `addRequestMappingRule(rule)`: Add a request mapping rule
- `addResponseMappingRule(rule)`: Add a response mapping rule
- `addMiddleware(middleware)`: Add custom middleware
#### Events
- `connected`: Triggered when a connection is established
- `disconnected`: Triggered when a connection is disconnected
- `request`: Triggered when a request is received
- `response`: Triggered when a response is sent
- `error`: Triggered when an error occurs
## Usage Scenarios
### 1. API Version Compatibility
Map old version API calls to new versions:
```typescript
wrapper.addRequestMappingRule({
match: { method: /^v1\// },
transform: async (request) => ({
...request,
method: request.method.replace(/^v1\//, 'v2/'),
}),
});
```
### 2. Parameter Format Conversion
Convert parameter formats to adapt to different servers:
```typescript
wrapper.addRequestInterceptor(async (request) => {
if (request.params) {
request.params = convertCamelToSnake(request.params);
}
return request;
});
```
### 3. Response Enhancement
Add extra metadata to the response:
```typescript
wrapper.addResponseInterceptor(async (response, request) => {
if (response.result) {
response.result._metadata = {
timestamp: new Date().toISOString(),
processedBy: 'wrapper',
};
}
return response;
});
```
### 4. Authentication and Authorization
Add an authentication layer:
```typescript
wrapper.addMiddleware(async (request, next) => {
if (!validateToken(request.params?.token)) {
return {
jsonrpc: '2.0',
id: request.id,
error: { code: 401, message: 'Unauthorized' },
};
}
return next(request);
});
```
### 5. Performance Monitoring
Monitor request performance:
```typescript
wrapper.addMiddleware(async (request, next) => {
const start = Date.now();
const response = await next(request);
const duration = Date.now() - start;
console.log(`${request.method}: ${duration}ms`);
return response;
});
```
## Architecture
```
┌─────────────┐
│ Client │
└──────┬──────┘
│
▼
┌─────────────────────────────────────┐
│ MCP Wrapper │
│ │
│ ┌──────────────────────────────┐ │
│ │ Request Interceptors │ │
│ └──────────────────────────────┘ │
│ ▼ │
│ ┌──────────────────────────────┐ │
│ │ Request Mapping Rules │ │
│ └──────────────────────────────┘ │
│ ▼ │
│ ┌──────────────────────────────┐ │
│ │ Middleware Chain │ │
│ │ - Logging │ │
│ │ - Rate Limiting │ │
│ │ - Caching │ │
│ │ - Retry │ │
│ │ - Custom Middlewares │ │
│ └──────────────────────────────┘ │
│ ▼ │
│ ┌──────────────────────────────┐ │
│ │ Response Mapping Rules │ │
│ └──────────────────────────────┘ │
│ ▼ │
│ ┌──────────────────────────────┐ │
│ │ Response Interceptors │ │
│ └──────────────────────────────┘ │
└─────────────┬───────────────────────┘
│
▼
┌──────────────┐
│ Upstream │
│ Server │
└──────────────┘
```
## Development
### Build
```bash
npm run build
```
### Development Mode
```bash
npm run dev
```
## License
MIT
## Contribution
Welcome to submit Issues and Pull Requests!
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
firecrawl
Firecrawl MCP Server enables web scraping, crawling, and content extraction.
servers
Model Context Protocol Servers
Time
A Model Context Protocol server for time and timezone conversions.
Filesystem
Node.js MCP Server for filesystem operations with dynamic access control.
Sequential Thinking
A structured MCP server for dynamic problem-solving and reflective thinking.