Home

API Key Authentication

API keys are the primary method for authenticating with your MCP server. This guide explains how to obtain, manage, and securely use API keys for accessing your MCP server's capabilities.

Understanding API Keys

An API key is a secret token that identifies your application or service when making requests to your MCP server. For MCP servers, API keys follow this format:

mcp_sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Each MCP server you deploy through MCP-Cloud.ai comes with a default API key that grants full access to that server's capabilities.

Obtaining API Keys

When you deploy an MCP server through MCP-Cloud.ai, you'll receive your primary API key. You can view this key in your server details page in the MCP-Cloud dashboard.

Creating Additional API Keys

You can create additional API keys with more limited scopes for different use cases:

  1. Log in to the MCP-Cloud dashboard
  2. Navigate to your MCP server details
  3. Select the "API Keys" tab
  4. Click "Create New API Key"
  5. Configure the key settings:
    • Key Name: A descriptive name to identify the key's purpose
    • Expiration: Optionally set an expiration date
    • Scopes: Select the permissions this key will have
  6. Click "Create"
  7. Copy your new API key immediately - it will only be shown once

API Key Scopes

When creating API keys, you can limit their access to specific functionality:

Scope Description
completions:create Generate text completions
chats:create Generate chat completions
models:read List available models
contexts:read Read stored contexts
contexts:write Create and modify contexts
files:read Access stored files
files:write Upload and manage files

For example, a key with only chats:create scope can generate chat completions but cannot create or modify contexts.

Using API Keys in Requests

To authenticate your requests, include your API key in the Authorization header using the Bearer token scheme:

Authorization: Bearer mcp_sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Example Request (cURL)

curl -X POST \
  https://your-mcp-server.mcp-cloud.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer mcp_sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -d '{
    "model": "claude-3-5-sonnet",
    "messages": [
      {"role": "user", "content": "What is the capital of France?"}
    ]
  }'

Example Request (JavaScript)

async function callMCPServer(apiKey, prompt) {
  const response = await fetch('https://your-mcp-server.mcp-cloud.ai/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`
    },
    body: JSON.stringify({
      model: 'claude-3-5-sonnet',
      messages: [{ role: 'user', content: prompt }]
    })
  });
  
  return response.json();
}

// Usage
const apiKey = process.env.MCP_API_KEY; // Store in environment variable
const result = await callMCPServer(apiKey, 'What is the capital of France?');
console.log(result.choices[0].message.content);

Example Request (Python)

import requests

def call_mcp_server(api_key, prompt):
    url = "https://your-mcp-server.mcp-cloud.ai/v1/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    data = {
        "model": "claude-3-5-sonnet",
        "messages": [{"role": "user", "content": prompt}]
    }
    
    response = requests.post(url, headers=headers, json=data)
    response.raise_for_status()  # Raise exception for 4xx/5xx errors
    
    return response.json()

# Usage (store API key in environment variable)
import os
api_key = os.environ.get("MCP_API_KEY")
result = call_mcp_server(api_key, "What is the capital of France?")
print(result["choices"][0]["message"]["content"])

API Key Security Best Practices

Secure Storage

Never hardcode API keys in your source code or include them in client-side JavaScript. Instead:

  1. Environment Variables: Store API keys in environment variables

    # Set environment variable
    export MCP_API_KEY=mcp_sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    
    # Access in application
    api_key = os.environ.get("MCP_API_KEY")
    
  2. Secrets Management Services: For production, use dedicated secrets managers:

    • AWS Secrets Manager
    • Google Secret Manager
    • HashiCorp Vault
    • Azure Key Vault
  3. Configuration Files: If using config files, ensure they're:

    • Not committed to version control (add to .gitignore)
    • Have restricted permissions (e.g., chmod 600)
    • Encrypted when possible

Key Rotation

Regularly rotate your API keys to minimize the impact of potential exposure:

  1. Create a new API key
  2. Update your applications to use the new key
  3. Verify everything works with the new key
  4. Delete or disable the old key

Principle of Least Privilege

Create API keys with only the permissions they need:

IP Restrictions

Restrict API key usage to specific IP addresses or CIDR ranges:

  1. When creating a new API key in the dashboard, click "Advanced Options"
  2. Under "IP Restrictions", add allowed IPs or CIDR ranges
  3. The key will only work when requests come from these IPs

Rate Limits

MCP servers implement rate limiting based on API keys. Default limits vary by plan:

Plan Rate Limit Notes
Free 10 req/min Suitable for development
Standard 60 req/min For small production apps
Professional 300 req/min For medium workloads
Enterprise Custom Contact support for custom limits

If you exceed these limits, you'll receive a 429 Too Many Requests response.

Monitoring API Key Usage

Monitor your API key usage to detect abnormal patterns:

  1. Log in to the MCP-Cloud dashboard
  2. Navigate to your MCP server details
  3. Select the "API Keys" tab
  4. View usage metrics for each key:
    • Requests per day/hour
    • Error rates
    • Endpoint usage patterns

Set up alerts for unusual activity:

Revoking API Keys

If an API key is compromised or no longer needed:

  1. Log in to the MCP-Cloud dashboard
  2. Navigate to your MCP server details
  3. Select the "API Keys" tab
  4. Find the key you want to revoke
  5. Click "Revoke Key"
  6. Confirm the action

Revocation is immediate and permanent. Any requests using the revoked key will receive a 401 Unauthorized response.

Handling API Key Errors

Common API key-related errors and how to handle them:

Status Code Meaning Handling Strategy
401 Unauthorized Invalid or expired API key Check key format, verify it's active
403 Forbidden Valid key but insufficient permissions Check required scopes, request a key with appropriate permissions
429 Too Many Requests Rate limit exceeded Implement exponential backoff, cache responses where appropriate

Example error response:

{
  "error": {
    "code": "invalid_api_key",
    "message": "The API key provided is invalid or has been revoked",
    "type": "authentication_error"
  }
}

Implementing Advanced Features

Request Signing

For additional security, you can implement request signing:

import hmac
import hashlib
import time

def create_signature(api_key, payload, timestamp):
    message = f"{timestamp}.{payload}"
    signature = hmac.new(
        api_key.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()
    return signature

def call_mcp_server_with_signature(api_key, prompt):
    url = "https://your-mcp-server.mcp-cloud.ai/v1/chat/completions"
    payload = json.dumps({
        "model": "claude-3-5-sonnet",
        "messages": [{"role": "user", "content": prompt}]
    })
    timestamp = int(time.time())
    signature = create_signature(api_key, payload, timestamp)
    
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}",
        "X-MCP-Timestamp": str(timestamp),
        "X-MCP-Signature": signature
    }
    
    response = requests.post(url, headers=headers, data=payload)
    return response.json()

Key Scoping with Metadata

Add metadata to your API keys for better organization and tracking:

{
  "metadata": {
    "environment": "production",
    "service": "recommendation-engine",
    "owner": "data-science-team",
    "contact": "[email protected]"
  }
}

This metadata can be added when creating keys in the dashboard and helps with key management.

Migrating Between API Keys

When rotating keys or changing permissions:

  1. Create a new key with the desired scopes and settings
  2. Update one service at a time to use the new key
  3. Monitor for errors during the transition
  4. Set a short expiration on the old key
  5. Revoke the old key after all services have migrated

Conclusion

API keys provide a simple and effective way to authenticate with your MCP server. By following the security best practices in this guide, you can ensure secure access to your AI capabilities while minimizing potential risks.