Best Practices
Recommended patterns and anti-patterns for MCP configuration
By Onli Platform2024-01-015 min read
MCP Configuration Best Practices
This guide outlines recommended patterns, anti-patterns, and optimization strategies for MCP configuration.
Configuration Management
Recommended Patterns
Use Environment-Specific Configurations
// config/development.json
{
"onli-mcp": {
"url": "https://stg.onli.app",
"headers": {
"User-Id": "${ONLI_DEV_USER_ID}",
"App-Key": "${ONLI_DEV_APP_KEY}",
"App-Symbol": "ENGMA"
},
"options": {
"debug": true,
"timeout": 30000
}
[object Object][object Object]Implement Configuration Validation
function validateConfig(config) {
const required = ['url', 'headers.User-Id', 'headers.App-Key', 'headers.App-Symbol'];
for (const field of required) {
if (!getNestedValue(config, field)) {
throw new Error(`Missing required field: ${field}`);
}
}
return true;
[object Object]Use Configuration Factories
class MCPConfigFactory {
static createConfig(environment) {
const baseConfig = {
headers: {
'User-Id': process.env.ONLI_USER_ID,
'App-Key': process.env.ONLI_APP_KEY,
'App-Symbol': process.env.ONLI_APP_SYMBOL || 'ENGMA'
}
};
switch (environment) {
case 'development':
return [object Object]
[object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object]Anti-Patterns to Avoid
Hardcoding Credentials
// DON'T DO THIS
const config = {
"onli-mcp": {
"url": "https://api.onli.app",
"headers": {
"User-Id": "user_12345_hardcoded", // Never hardcode
"App-Key": "ak_secret_key_123", // Security risk
"App-Symbol": "ENGMA"
}
}
};
Single Configuration for All Environments
// DON'T DO THIS - Use environment-specific configs
const oneConfigForAll = {
url: "https://api.onli.app", // Should vary by environment
debug: true // Should be false in production
};
Missing Error Handling
// DON'T DO THIS
const client = new MCPClient(config); // No validation or error handling
client.connect(); // No error handling
Security Best Practices
Credential Management
Use Environment Variables
# .env.development
ONLI_USER_ID=dev_user_12345
ONLI_APP_KEY=ak_dev_secret_key
ONLI_APP_SYMBOL=ENGMA
# .env.production
ONLI_USER_ID=prod_user_67890
ONLI_APP_KEY=ak_prod_secret_key
ONLI_APP_SYMBOL=ENGMA
Implement Credential Rotation
class CredentialManager {
constructor() {
this.refreshInterval = 24 * 60 * 60 * 1000; // 24 hours
this.setupRotation();
}
async rotateCredentials() {
const newCredentials = await this.fetchNewCredentials();
this.updateConfig(newCredentials);
this.scheduleNextRotation()[object Object]
[object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object]Monitor API Usage
class APIMonitor {
trackRequest(endpoint, method, timestamp) {
// Log API usage patterns
console.log(`API Call: ${method} ${endpoint} at ${timestamp}`);
// Check for unusual patterns
this.detectAnomalies(endpoint, method);
}
detectAnomalies(endpoint, method) {
[object Object]
[object Object][object Object][object Object][object Object][object Object][object Object][object Object]Network Security
Always Use HTTPS
const config = {
url: "https://api.onli.app", // Always HTTPS
options: {
rejectUnauthorized: true, // Verify SSL certificates
secureProtocol: 'TLSv1_2_method' // Use secure protocols
}
};
Implement Request Signing
class SecureClient {
signRequest(request) {
const timestamp = Date.now();
const signature = this.generateSignature(request, timestamp);
return {
...request,
headers: {
...request.headers,
'X-Timestamp': timestamp,
'X-Signature': signature
}
};
}
[object Object]Performance Optimization
Connection Management
Connection Pooling
const config = {
"onli-mcp": {
"url": "https://api.onli.app",
"headers": {
"User-Id": "${ONLI_USER_ID}",
"App-Key": "${ONLI_APP_KEY}",
"App-Symbol": "ENGMA"
},
"options": {
"pooling": {
"maxConnections": 10,
"keepAlive": true,
"keepAliveMsecs": 30000
}
[object Object]
[object Object][object Object]Appropriate Timeouts
const timeoutConfig = {
development: {
connectionTimeout: 10000,
requestTimeout: 30000,
retryDelay: 2000
},
production: {
connectionTimeout: 5000,
requestTimeout: 15000,
retryDelay: 1000
}
};
Retry Strategies
Exponential Backoff
class RetryManager {
async executeWithRetry(operation, maxRetries = 3) {
let attempt = 0;
while (attempt < maxRetries) {
try {
return await operation();
} catch (error) {
if (!this.isRetryableError(error) || attempt === maxRetries - 1) {
throw error;
[object Object]
[object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object]Error Handling
Comprehensive Error Handling
class MCPErrorHandler {
handleError(error, context) {
switch (error.type) {
case 'AUTHENTICATION_ERROR':
this.handleAuthError(error, context);
break;
case 'NETWORK_ERROR':
this.handleNetworkError(error, context);
break;
case 'TIMEOUT_ERROR':
this.handleTimeoutError(error, context);
[object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object]Circuit Breaker Pattern
class CircuitBreaker {
constructor(threshold = 5, timeout = 60000) {
this.failureThreshold = threshold;
this.timeout = timeout;
this.failureCount = 0;
this.state = 'CLOSED'; // CLOSED, OPEN, HALF_OPEN
this.lastFailureTime = null;
}
async execute(operation) {
if (this.[object Object] [object Object] [object Object][object Object] [object Object]
[object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object]Monitoring and Logging
Structured Logging
const logger = {
logMCPOperation(operation, duration, success, metadata = {}) {
const logEntry = {
timestamp: new Date().toISOString(),
operation,
duration,
success,
environment: process.env.NODE_ENV,
...metadata
};
if (success) {
console.log[object Object][object Object][object Object] [object Object][object Object][object Object][object Object]logEntry[object Object][object Object][object Object]
[object Object][object Object][object Object][object Object][object Object]Health Checks
class HealthChecker {
async performHealthCheck() {
const checks = [
this.checkConnectivity(),
this.checkAuthentication(),
this.checkLatency()
];
const results = await Promise.allSettled(checks);
return {
healthy: results.every(r => r[object Object][object Object] [object Object] [object Object][object Object][object Object]
[object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object]Testing Best Practices
Mock External Dependencies
// test/mcp-client.test.js
describe('MCP Client', () => {
beforeEach(() => {
nock('https://stg.onli.app')
.get('/health')
.reply(200, { status: 'healthy' });
});
it('should connect successfully with valid config', async () => {
const config = createTestConfig()[object Object]
[object Object][object Object][object Object][object Object][object Object][object Object]Test Different Environments
const testConfigs = {
development: createDevConfig(),
staging: createStagingConfig(),
production: createProdConfig()
};
Object.entries(testConfigs).forEach(([env, config]) => {
describe(`${env} environment`, () => {
[object Object][object Object][object Object][object Object] [object Object][object Object] [object Object] [object Object]
[object Object][object Object][object Object][object Object]Next Steps
- Review Setup Instructions for implementation details
- Check Troubleshooting Guide for common issues
- Join our Developer Community for best practice discussions
Support
For questions about best practices:
- Email: support@onli.one
- Documentation: Configuration Guides
- Community: Onli Developer Forum