mcp-cross-ai-secure

doritoman90000/mcp-cross-ai-secure

3.2

If you are the rightful owner of mcp-cross-ai-secure and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

The Secure MCP Cross-AI Tool is a robust server implementation designed to securely interface with external AI services like ChatGPT and Google Gemini, focusing on security, performance, and comprehensive management features.

Tools
  1. query_external_ai

    Allows querying of ChatGPT or Gemini AI models with specified prompts.

  2. test_connection

    Tests server status and provides diagnostics.

๐Ÿ”’ Secure MCP Cross-AI Tool

A production-ready, security-hardened MCP (Model Context Protocol) server that provides secure access to external AI services including ChatGPT and Gemini. This implementation addresses critical security vulnerabilities and implements comprehensive rate limiting, authentication, and authorization systems.

๐Ÿš€ Features

Security Features

  • โœ… Multiple Authentication Modes: Development, API Key, JWT, and Session-based
  • โœ… Comprehensive Rate Limiting: Service-specific, client-specific, and global limits
  • โœ… Input Validation & Sanitization: Prevents injection attacks and malicious prompts
  • โœ… Request Logging & Monitoring: Detailed audit trails and security monitoring
  • โœ… Automatic Cleanup: Memory management and expired session cleanup

Supported AI Services

  • OpenAI ChatGPT: GPT-3.5-turbo with configurable parameters
  • Google Gemini: Gemini-pro with smart content handling

Production Features

  • Health Checks: Automated monitoring and maintenance
  • Graceful Shutdown: Proper cleanup and data persistence
  • Comprehensive Logging: Winston-based structured logging
  • Error Handling: Robust error categorization and recovery
  • Performance Monitoring: Request statistics and performance metrics

๐Ÿ“‹ Security Issues Resolved

โœ… MEDIUM SEVERITY - Issue #3: Missing Rate Limiting

  • Status: โœ… RESOLVED
  • Implementation:
    • Service-specific limits: ChatGPT (20/min), Gemini (60/min)
    • Global server limit: 100 requests/minute
    • Per-client limits: 10 requests/minute
    • Automatic cleanup and statistics tracking
  • Files: rate-limiter.js, integrated in secure-mcp-server.js
  • Testing: Comprehensive test suite in tests/security.test.js

โœ… MEDIUM SEVERITY - Issue #4: No Authentication/Authorization

  • Status: โœ… RESOLVED
  • Implementation:
    • 4 authentication modes: Development, API Key, JWT, Session
    • Granular permission system with role-based access
    • Secure token generation and management
    • Session management with automatic expiration
  • Files: auth-manager.js, integrated in secure-mcp-server.js
  • Testing: Full authentication test coverage

๐Ÿš€ Quick Start

Prerequisites

  • Node.js 18.0.0 or higher
  • npm or yarn package manager
  • Environment variables configured

Installation

  1. Clone and install dependencies:
npm install
  1. Configure environment:
cp .env.example .env
# Edit .env with your API keys and configuration
  1. Create logs directory:
mkdir logs
  1. Start the server:
# Development mode
npm run dev

# Production mode
npm start

๐Ÿ”ง Configuration

Environment Variables

VariableDescriptionDefaultRequired
AUTH_MODEAuthentication mode: development, api-key, jwt, sessiondevelopmentYes
JWT_SECRETSecret key for JWT tokens (32+ chars)-Production
OPENAI_API_KEYOpenAI API key-Yes
GEMINI_API_KEYGoogle Gemini API key-Yes
RATE_LIMIT_CHATGPT_PER_MINUTEChatGPT rate limit20No
RATE_LIMIT_GEMINI_PER_MINUTEGemini rate limit60No
RATE_LIMIT_GLOBAL_PER_MINUTEGlobal rate limit100No
RATE_LIMIT_CLIENT_PER_MINUTEPer-client rate limit10No
LOG_LEVELLogging levelinfoNo

Authentication Modes

Development Mode (AUTH_MODE=development)
  • Use case: Testing and development
  • Security: Minimal - allows all requests
  • Setup: No additional configuration needed
API Key Mode (AUTH_MODE=api-key)
  • Use case: Simple authentication for known clients
  • Setup: Set MCP_API_KEYS=client1:key1,client2:key2
  • Usage: Send Authorization: Bearer <api-key> header
JWT Mode (AUTH_MODE=jwt)
  • Use case: Stateless authentication with expiration
  • Setup: Set JWT_SECRET to a secure 64-character string
  • Usage: Send Authorization: Bearer <jwt-token> header
Session Mode (AUTH_MODE=session)
  • Use case: Traditional session-based authentication
  • Setup: Configure session duration with SESSION_DURATION_HOURS
  • Usage: Send X-Session-Token: <session-token> header

๐Ÿงช Testing

Run Test Suite

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run with coverage
npm test -- --coverage

Manual Testing

Rate Limiting Tests
# Test ChatGPT rate limit (should fail on 21st request)
for i in {1..21}; do
  echo "Request $i"
  # Make request to ChatGPT endpoint
done

# Test client rate limit
for i in {1..11}; do
  echo "Client request $i"
  # Make request with same client ID
done
Authentication Tests
# Test with valid API key
curl -H "Authorization: Bearer valid-key" http://localhost:3000/test

# Test with invalid API key
curl -H "Authorization: Bearer invalid-key" http://localhost:3000/test

# Test without authentication (should fail in non-dev mode)
curl http://localhost:3000/test

๐Ÿ“Š Monitoring

Health Checks

The server provides built-in health monitoring:

  • Automatic health checks every 5 minutes
  • Memory usage monitoring
  • Request statistics tracking
  • Error categorization and counting

Log Files

  • logs/mcp-server.log - General server logs
  • logs/error.log - Error-specific logs
  • logs/auth-manager.log - Authentication logs
  • logs/rate-limiter.log - Rate limiting logs

Statistics Endpoints

Use the test_connection tool to get current server statistics:

{
  "tool": "test_connection",
  "arguments": {
    "message": "status check"
  }
}

๐Ÿ” Security Best Practices

Production Deployment

  1. Use strong JWT secrets: Generate with openssl rand -hex 64
  2. Rotate API keys regularly: Implement key rotation schedule
  3. Monitor logs: Set up log aggregation and alerting
  4. Use HTTPS: Always encrypt traffic in production
  5. Secure environment variables: Use secure secret management

Rate Limiting Strategy

  • ChatGPT: 20 requests/minute (within OpenAI free tier)
  • Gemini: 60 requests/minute (generous limit for Gemini API)
  • Global: 100 requests/minute (server capacity limit)
  • Client: 10 requests/minute (prevents individual abuse)

Authentication Security

  • Development: Only for testing - never in production
  • API Key: Use for service-to-service communication
  • JWT: Best for stateless applications
  • Session: Good for traditional web applications

๐Ÿ› ๏ธ API Reference

Available Tools

query_external_ai

Query ChatGPT or Gemini AI models.

Parameters:

  • prompt (string, required): The prompt to send
  • target_ai (enum, required): Either "chatgpt" or "gemini"

Example:

{
  "tool": "query_external_ai",
  "arguments": {
    "prompt": "What is the capital of France?",
    "target_ai": "chatgpt"
  }
}
test_connection

Test server status and get diagnostics.

Parameters:

  • message (string, required): Test message to echo

Example:

{
  "tool": "test_connection",
  "arguments": {
    "message": "Hello, server!"
  }
}

๐Ÿšจ Troubleshooting

Common Issues

Rate Limit Exceeded

Error: "Rate limit exceeded. Please try again later." Solution:

  • Wait for the rate limit window to reset
  • Check rate limit configuration
  • Verify client identification
Authentication Failed

Error: "Authentication failed" or "Invalid API key" Solution:

  • Verify correct authentication mode
  • Check API key format and validity
  • Ensure proper headers are sent
API Key Not Configured

Error: "OpenAI API key not configured" Solution:

  • Set OPENAI_API_KEY in environment
  • Verify API key is valid and has credits
  • Check API key permissions

Debug Mode

Enable debug logging:

LOG_LEVEL=debug npm start

๐Ÿ“ Project Structure

mcp-cross-ai-secure/
โ”œโ”€โ”€ rate-limiter.js          # Rate limiting implementation
โ”œโ”€โ”€ auth-manager.js          # Authentication/authorization
โ”œโ”€โ”€ secure-mcp-server.js     # Main server with security integration
โ”œโ”€โ”€ config/
โ”‚   โ””โ”€โ”€ config-manager.js    # Configuration management
โ”œโ”€โ”€ tests/
โ”‚   โ””โ”€โ”€ security.test.js     # Comprehensive test suite
โ”œโ”€โ”€ logs/                    # Log files (created at runtime)
โ”œโ”€โ”€ package.json             # Dependencies and scripts
โ”œโ”€โ”€ .env.example             # Environment template
โ””โ”€โ”€ README.md               # This file

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Run the test suite
  6. Submit a pull request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ”— Related Documentation

๐Ÿ“ž Support

For issues and questions:

  1. Check the troubleshooting section above
  2. Review the test suite for examples
  3. Check server logs for detailed error information
  4. Open an issue on the project repository

Security Notice: This implementation has been designed to address medium-severity security issues including rate limiting and authentication/authorization. Regular security audits and updates are recommended for production deployments.