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:
- Log in to the MCP-Cloud dashboard
- Navigate to your MCP server details
- Select the "API Keys" tab
- Click "Create New API Key"
- 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
- Click "Create"
- 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:
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")
Secrets Management Services: For production, use dedicated secrets managers:
- AWS Secrets Manager
- Google Secret Manager
- HashiCorp Vault
- Azure Key Vault
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
- Not committed to version control (add to
Key Rotation
Regularly rotate your API keys to minimize the impact of potential exposure:
- Create a new API key
- Update your applications to use the new key
- Verify everything works with the new key
- Delete or disable the old key
Principle of Least Privilege
Create API keys with only the permissions they need:
- For a read-only dashboard, use keys with only
models:read
andcontexts:read
scopes - For a chatbot, use keys with only
chats:create
scope - For a file processing service, use keys with only
files:read
andfiles:write
scopes
IP Restrictions
Restrict API key usage to specific IP addresses or CIDR ranges:
- When creating a new API key in the dashboard, click "Advanced Options"
- Under "IP Restrictions", add allowed IPs or CIDR ranges
- 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:
- Log in to the MCP-Cloud dashboard
- Navigate to your MCP server details
- Select the "API Keys" tab
- View usage metrics for each key:
- Requests per day/hour
- Error rates
- Endpoint usage patterns
Set up alerts for unusual activity:
- Sudden spikes in usage
- Requests from new geographic regions
- High rates of authentication failures
Revoking API Keys
If an API key is compromised or no longer needed:
- Log in to the MCP-Cloud dashboard
- Navigate to your MCP server details
- Select the "API Keys" tab
- Find the key you want to revoke
- Click "Revoke Key"
- 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:
- Create a new key with the desired scopes and settings
- Update one service at a time to use the new key
- Monitor for errors during the transition
- Set a short expiration on the old key
- 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.