Scaling Codes Logo
Scaling Codes

API Gateway MCP

Secure and manage AI model access to external APIs with authentication and rate limiting

SecurityAdvancedMCP Protocol

Overview

The API Gateway MCP provides a secure interface for AI models to access external APIs while maintaining strict security controls, rate limiting, and audit trails. This protocol acts as a security layer between AI models and external services.

By implementing this MCP, organizations can safely allow AI models to interact with third-party APIs, internal services, and external data sources while maintaining compliance and security standards.

Architecture Overview

Implementation Guide

1. API Gateway MCP Server

import { Server } from '@modelcontextprotocol/sdk/server'
import { APIGatewayTool } from './tools/APIGatewayTool'

const server = new Server({
  name: 'api-gateway-mcp',
  version: '1.0.0'
})

// Register API gateway tool
server.tool(new APIGatewayTool({
  allowedApis: process.env.ALLOWED_APIS?.split(','),
  rateLimit: parseInt(process.env.RATE_LIMIT || '100'),
  authRequired: process.env.AUTH_REQUIRED === 'true'
}))

server.listen({
  port: 3000,
  host: 'localhost'
})

2. API Gateway Tool Implementation

import { Tool } from '@modelcontextprotocol/sdk/server'
import axios from 'axios'

interface APIGatewayConfig {
  allowedApis: string[]
  rateLimit: number
  authRequired: boolean
}

export class APIGatewayTool extends Tool {
  private config: APIGatewayConfig
  private requestCounts: Map<string, number> = new Map()
  
  constructor(config: APIGatewayConfig) {
    super({
      name: 'api_gateway',
      description: 'Secure access to external APIs with rate limiting and authentication',
      inputSchema: {
        type: 'object',
        properties: {
          api: { type: 'string', enum: config.allowedApis },
          endpoint: { type: 'string' },
          method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'DELETE'] },
          headers: { type: 'object' },
          body: { type: 'object' },
          authToken: { type: 'string' }
        },
        required: ['api', 'endpoint', 'method']
      }
    })
    this.config = config
  }

  async execute(input: any) {
    // Validate API access
    if (!this.config.allowedApis.includes(input.api)) {
      throw new Error(`API ${input.api} not allowed`)
    }

    // Check rate limiting
    if (!this.checkRateLimit(input.api)) {
      throw new Error('Rate limit exceeded')
    }

    // Validate authentication if required
    if (this.config.authRequired && !input.authToken) {
      throw new Error('Authentication token required')
    }

    // Make API request
    try {
      const response = await this.makeRequest(input)
      this.incrementRequestCount(input.api)
      return response
    } catch (error) {
      throw new Error(`API request failed: ${error.message}`)
    }
  }

  private checkRateLimit(api: string): boolean {
    const count = this.requestCounts.get(api) || 0
    return count < this.config.rateLimit
  }

  private incrementRequestCount(api: string) {
    const count = this.requestCounts.get(api) || 0
    this.requestCounts.set(api, count + 1)
  }

  private async makeRequest(input: any) {
    const config = {
      method: input.method,
      url: `${input.api}${input.endpoint}`,
      headers: {
        'Content-Type': 'application/json',
        ...input.headers
      },
      data: input.body
    }

    if (input.authToken) {
      config.headers['Authorization'] = `Bearer ${input.authToken}`
    }

    const response = await axios(config)
    return {
      status: response.status,
      data: response.data,
      headers: response.headers
    }
  }
}

3. Client Integration

import { Client } from '@modelcontextprotocol/sdk/client'

const client = new Client({
  serverUrl: 'ws://localhost:3000'
})

// Example: Call external API through MCP
const result = await client.tools.api_gateway.execute({
  api: 'https://api.openweathermap.org',
  endpoint: '/data/2.5/weather',
  method: 'GET',
  headers: { 'Accept': 'application/json' },
  body: { q: 'London,UK', appid: 'your-api-key' }
})

console.log('Weather data:', result.data)

// Example: Authenticated API call
const authResult = await client.tools.api_gateway.execute({
  api: 'https://api.github.com',
  endpoint: '/user',
  method: 'GET',
  headers: { 'Accept': 'application/vnd.github.v3+json' },
  authToken: 'your-github-token'
})

console.log('GitHub user:', authResult.data)

Security Features

Access Control

  • • API whitelisting and blacklisting
  • • Authentication token validation
  • • Role-based access control
  • • IP address restrictions
  • • Request signature verification

Rate Limiting

  • • Per-API rate limiting
  • • Per-user rate limiting
  • • Sliding window counters
  • • Burst allowance
  • • Rate limit headers

Configuration Example

# api-gateway-mcp-config.yaml
server:
  name: api-gateway-mcp
  version: 1.0.0
  port: 3000
  host: localhost

api_gateway:
  allowed_apis:
    - https://api.openweathermap.org
    - https://api.github.com
    - https://api.stripe.com
    - https://api.twilio.com
  
  rate_limits:
    default: 100  # requests per minute
    per_api:
      https://api.openweathermap.org: 60
      https://api.github.com: 30
      https://api.stripe.com: 1000
      https://api.twilio.com: 50
  
  authentication:
    required: true
    methods:
      - bearer_token
      - api_key
      - oauth2
    
    token_validation:
      jwt_secret: ${JWT_SECRET}
      token_expiry: 3600  # 1 hour
    
    api_keys:
      - name: weather_api
        key: ${WEATHER_API_KEY}
        allowed_apis: [https://api.openweathermap.org]
      - name: github_api
        key: ${GITHUB_API_KEY}
        allowed_apis: [https://api.github.com]

  security:
    ip_whitelist:
      - 192.168.1.0/24
      - 10.0.0.0/8
    
    request_validation:
      max_body_size: 1048576  # 1MB
      allowed_content_types:
        - application/json
        - application/x-www-form-urlencoded
    
    audit_logging:
      enabled: true
      level: info
      storage: database
      retention: 90d

  monitoring:
    metrics:
      enabled: true
      prometheus: true
      custom_metrics:
        - api_calls_total
        - api_response_time
        - api_error_rate
    
    alerts:
      high_error_rate: 0.05  # 5%
      high_latency: 5000     # 5 seconds
      rate_limit_exceeded: true

Monitoring & Metrics

Performance Metrics

  • • API response times
  • • Request throughput
  • • Error rates by API
  • • Rate limit violations
  • • Authentication failures

Security Metrics

  • • Failed authentication attempts
  • • API access violations
  • • IP address blocking
  • • Token expiration events
  • • Suspicious request patterns

Business Metrics

  • • API usage by service
  • • Cost per API call
  • • User activity patterns
  • • API availability
  • • Service dependencies

Common Use Cases

AI-Powered Data Enrichment

AI models can safely access external APIs to enrich data with weather information, geolocation data, or social media insights while maintaining security controls.

Multi-Service Integration

AI models can orchestrate calls to multiple external services (payment, shipping, notification) through a single, secure interface with unified logging and monitoring.

Compliance & Audit

Organizations can maintain compliance by controlling AI model access to sensitive APIs while providing comprehensive audit trails and access logs.