Advanced Integration Patterns

class ResilientMCPClient {
  constructor(maxRetries = 3, retryDelay = 1000) {
    this.maxRetries = maxRetries;
    this.retryDelay = retryDelay;
    this.client = new Client(
      { name: 'resilient-client', version: '1.0.0' },
      { capabilities: {} }
    );
  }

  async callToolWithRetry(toolName, arguments) {
    let lastError;
    for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
      try {
        const response = await this.client.request(
          { method: 'tools/call' },
          { name: toolName, arguments }
        );
        this.retryDelay = 1000;
        return response;
      } catch (error) {
        lastError = error;
        if (attempt < this.maxRetries) {
          console.log(`Attempt ${attempt} failed, retrying in ${this.retryDelay}ms...`);
          await this.sleep(this.retryDelay);
          this.retryDelay *= 2;
        }
      }
    }
    throw new Error(`Tool call failed after ${this.maxRetries} attempts: ${lastError.message}`);
  }

  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}
from dataclasses import dataclass
from typing import Dict, List, Optional
import json
import os

@dataclass
class MCPServerConfig:
    name: str
    command: List[str]
    args: List[str] = None
    env: Dict[str, str] = None
    working_directory: Optional[str] = None

@dataclass
class MCPConfig:
    servers: Dict[str, MCPServerConfig]
    global_timeout: int = 30
    max_retries: int = 3
    @classmethod
    def from_file(cls, config_path: str) -> 'MCPConfig':
        with open(config_path, 'r') as f:
            config_data = json.load(f)
        servers = {}
        for name, server_config in config_data.get('servers', {}).items():
            servers[name] = MCPServerConfig(
                name=name,
                command=server_config['command'],
                args=server_config.get('args', []),
                env=server_config.get('env', {}),
                working_directory=server_config.get('working_directory')
            )
        return cls(
            servers=servers,
            global_timeout=config_data.get('global_timeout', 30),
            max_retries=config_data.get('max_retries', 3)
        )

# Example configuration file (config.json)
example_config = {
    "servers": {
        "filesystem": {
            "command": ["python", "filesystem_server.py"],
            "args": ["--root", "/allowed/path"],
            "env": {"LOG_LEVEL": "INFO"}
        },
        "database": {
            "command": ["node", "database_server.js"],
            "args": ["--db", "production.db"],
            "working_directory": "/app/servers"
        }
    },
    "global_timeout": 45,
    "max_retries": 5
}