DocsAPI ReferenceAuthentication

Authentication

Secure your MCPCodex applications with API keys, OAuth 2.0, and JWT tokens. Learn how to authenticate users and manage access permissions.

Quick Start

Get Your API Key

The fastest way to get started is with an API key. Sign up for a free account and generate your key in the dashboard.

Get API Key
basic-auth.js
import { MCPCodex } from '@mcpcodex/sdk';

// Initialize with API key
const mcp = new MCPCodex({
  apiKey: process.env.MCP_API_KEY,
  environment: 'production' // or 'sandbox'
});

// Authenticate and verify connection
try {
  const auth = await mcp.auth.verify();
  console.log('Authenticated as:', auth.user.email);
  console.log('Organization:', auth.organization.name);
  console.log('Plan:', auth.subscription.plan);
} catch (error) {
  console.error('Authentication failed:', error.message);
}

Authentication Methods

API Keys

Simple and secure for server-to-server communication and personal projects.

  • • Best for backend services
  • • No expiration by default
  • • Easy to implement
  • • Full access control

OAuth 2.0

Industry standard for third-party applications and user delegation.

  • • User consent flow
  • • Scoped permissions
  • • Secure for web apps
  • • Token refresh

JWT Tokens

Stateless tokens with embedded claims, perfect for microservices.

  • • Self-contained
  • • Short-lived
  • • No server state
  • • Claims-based

API Key Authentication

Using cURL

Terminal
# Get your API key from https://app.mcpcodex.com/settings/api
curl -H "Authorization: Bearer YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     https://api.mcpcodex.com/v1/user/profile

# Example response
{
  "id": "usr_1234567890",
  "email": "[email protected]",
  "name": "Jane Developer",
  "organization": {
    "id": "org_0987654321",
    "name": "Acme Corp",
    "plan": "enterprise"
  },
  "permissions": ["read:code", "write:code", "deploy:apps"],
  "rate_limits": {
    "requests_per_hour": 10000,
    "tokens_per_minute": 100000
  }
}

API Key Best Practices

  • Store securely: Never commit API keys to version control. Use environment variables or secure key management systems.
  • Rotate regularly: Generate new API keys periodically and revoke old ones.
  • Use HTTPS: Always use HTTPS when transmitting API keys over the network.
  • Scope permissions: Create API keys with only the permissions your application needs.

OAuth 2.0 Flow

OAuth 2.0 is the recommended approach for applications that need to access MCPCodex on behalf of users. It provides secure, scoped access with user consent.

oauth-flow.js
// OAuth 2.0 Flow
const authUrl = mcp.auth.getAuthorizationUrl({
  clientId: 'your-client-id',
  redirectUri: 'https://your-app.com/callback',
  scopes: ['read:code', 'write:code', 'deploy:apps'],
  state: 'secure-random-state'
});

// Redirect user to authUrl
window.location.href = authUrl;

// Handle callback
const handleCallback = async (code, state) => {
  const tokens = await mcp.auth.exchangeCode({
    code,
    clientId: 'your-client-id',
    clientSecret: process.env.CLIENT_SECRET,
    redirectUri: 'https://your-app.com/callback'
  });
  
  // Store tokens securely
  localStorage.setItem('mcp_access_token', tokens.access_token);
  localStorage.setItem('mcp_refresh_token', tokens.refresh_token);
};

Available Scopes

read:code
Read source code and project files
write:code
Modify and create source code
deploy:apps
Deploy applications to cloud
manage:team
Manage team members and permissions

OAuth Endpoints

Authorization URL
https://app.mcpcodex.com/oauth/authorize
Token URL
https://api.mcpcodex.com/oauth/token
Revoke URL
https://api.mcpcodex.com/oauth/revoke

JWT Token Management

MCPCodex uses JSON Web Tokens (JWT) for stateless authentication. Tokens are short-lived and must be refreshed periodically.

jwt-management.js
// JWT Token Management
const refreshToken = async () => {
  try {
    const response = await fetch('https://api.mcpcodex.com/auth/refresh', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('mcp_refresh_token')}`
      }
    });
    
    const tokens = await response.json();
    
    // Update stored tokens
    localStorage.setItem('mcp_access_token', tokens.access_token);
    localStorage.setItem('mcp_refresh_token', tokens.refresh_token);
    
    return tokens.access_token;
  } catch (error) {
    // Redirect to login
    window.location.href = '/login';
  }
};

// Automatic token refresh
const apiCall = async (endpoint, options = {}) => {
  let token = localStorage.getItem('mcp_access_token');
  
  const response = await fetch(endpoint, {
    ...options,
    headers: {
      ...options.headers,
      'Authorization': `Bearer ${token}`
    }
  });
  
  if (response.status === 401) {
    // Token expired, refresh and retry
    token = await refreshToken();
    return fetch(endpoint, {
      ...options,
      headers: {
        ...options.headers,
        'Authorization': `Bearer ${token}`
      }
    });
  }
  
  return response;
};

Token Lifetimes

Access Tokens
  • • Lifetime: 1 hour
  • • Used for API requests
  • • Contains user claims
  • • Should not be stored long-term
Refresh Tokens
  • • Lifetime: 30 days
  • • Used to get new access tokens
  • • Can be revoked
  • • Store securely

Rate Limits & Permissions

Rate Limits

Free Tier
1,000 requests/hour, 10,000 tokens/minute
Pro Tier
10,000 requests/hour, 100,000 tokens/minute
Enterprise
Custom limits based on agreement

Permission Levels

Viewer
Read-only access
Developer
Code generation and modification
Admin
Full access including deployment

Security Best Practices

Important Security Notes

  • • Never expose API keys or secrets in client-side code
  • • Always use HTTPS for authentication requests
  • • Implement proper error handling to avoid information leakage
  • • Regular audit and rotate your API keys
  • • Use the principle of least privilege for permissions

✅ Do

  • • Use environment variables for secrets
  • • Validate all authentication responses
  • • Implement token refresh logic
  • • Log authentication events
  • • Use secure token storage

❌ Don't

  • • Hard-code API keys in source code
  • • Use HTTP for authentication
  • • Ignore token expiration
  • • Share API keys between applications
  • • Store tokens in localStorage without encryption

Common Issues

401 Unauthorized

Your API key is invalid, expired, or missing. Check that you're passing the correct key in the Authorization header.

Authorization: Bearer YOUR_API_KEY

403 Forbidden

You don't have permission to access this resource. Check your API key permissions or OAuth scopes.

429 Too Many Requests

You've exceeded your rate limit. Implement exponential backoff and check your usage in the dashboard.

Need Help with Authentication?

Our security team can help you implement authentication correctly and securely.