Aller au contenu principal

MCP Server Authentication

Overview

The MCP server is now secured with API key authentication. Each MCP client must provide a valid API key stored in the Credential model to access the server.

Security Benefits

  • Access Control: Only users with valid API keys can access MCP tools
  • Audit Trail: All MCP operations are logged with the authenticated user
  • Role-Based Access: Tools can check user roles and permissions
  • Key Revocation: API keys can be revoked at any time
  • User Tracking: Know which user performed which operations

Generating an API Key

Run the interactive script:

npm run mcp:generate-key

This will:

  1. List all active credentials
  2. Let you select which user to generate a key for
  3. Generate and display the API key
  4. Show you how to configure it

Method 2: Programmatically

import mcpAuthService from "./services/core/mcpAuth.service";

const apiKey = await mcpAuthService.generateMCPApiKey("USER_CREDENTIAL_ID");
console.log("API Key:", apiKey);

Method 3: Via MCP Tools (Admin Only)

Once authenticated with an admin account:

generate a new MCP API key for credential ID: 60a7b5c4d5e6f7g8h9i0j1k2

Configuring VS Code

  1. Generate an API key using one of the methods above

  2. Update .vscode/mcp.json:

{
"servers": {
"BaldrApi": {
"type": "stdio",
"command": "/path/to/node",
"args": ["/path/to/dist/mcp-server.js"],
"env": {
"NODE_ENV": "development",
"MCP_API_KEY": "mcp_your_generated_api_key_here"
}
}
}
}
  1. Reload VS Code window

API Key Format

API keys follow this format:

mcp_[64 hexadecimal characters]

Example: mcp_a1b2c3d4e5f6... (shortened for display)

Managing API Keys

List All API Keys (Admin Only)

list all MCP API keys

Returns:

  • User name
  • Email
  • Role
  • Active status
  • API key creation date

Get Your Own API Key

get my MCP API key

Returns a masked version of your API key.

Revoke an API Key (Admin Only)

revoke MCP API key for credential ID: 60a7b5c4d5e6f7g8h9i0j1k2

Or programmatically:

await mcpAuthService.revokeApiKey("USER_CREDENTIAL_ID");

Database Schema

API keys are stored in the Credential model:

{
mcpApiKey: string; // Unique API key
mcpApiKeyCreatedAt: Date; // Creation timestamp
}

Role-Based Access Control

Tools can check user roles:

mcpService.registerTool(
"admin_only_tool",
"This tool is admin only",
schema,
async (args, user) => {
if (user?.role !== "inleedMaster") {
throw new Error("Unauthorized: Admin only");
}
// ... tool implementation
}
);

Security Best Practices

  1. Never commit API keys to version control

    • Add .vscode/mcp.json to .gitignore
    • Use environment variables in production
  2. Rotate keys regularly

    • Regenerate keys periodically
    • Revoke old keys after rotation
  3. Use principle of least privilege

    • Only grant MCP access to users who need it
    • Use role checks in sensitive tools
  4. Monitor usage

    • Check MCP logs for suspicious activity
    • Review which users have active API keys
  5. Secure storage

    • Store the API key securely
    • Don't share API keys between users

Troubleshooting

"Authentication required" Error

Cause: No API key provided or invalid API key

Solutions:

  1. Generate an API key: npm run mcp:generate-key
  2. Add it to .vscode/mcp.json in the env.MCP_API_KEY field
  3. Reload VS Code window

"Invalid or inactive API key" Error

Causes:

  • API key was revoked
  • Credential is inactive
  • Wrong API key format

Solutions:

  1. Generate a new API key
  2. Ensure the credential is active
  3. Check the API key starts with mcp_

"Unauthorized: Only admins..." Error

Cause: Trying to use an admin-only tool without admin role

Solution: Use an API key from a credential with inleedMaster or admin role

Environment Variables

# Required for MCP server
MCP_API_KEY=mcp_your_api_key_here

# Optional: MCP log level
MCP_LOG_LEVEL=info # or "silent" to disable logs

Migration Guide

If you had an MCP server running without authentication:

  1. Generate API keys for users who need MCP access:

    npm run mcp:generate-key
  2. Update configuration with the generated API key

  3. Rebuild and restart:

    npm run build
    # Reload VS Code window
  4. Test authentication:

    @BaldrApi check API health

API Key Lifecycle

┌─────────────────┐
│ Generate Key │ ← npm run mcp:generate-key
└────────┬────────┘


┌─────────────────┐
│ Store in Model │ ← Credential.mcpApiKey
└────────┬────────┘


┌─────────────────┐
│ Configure MCP │ ← .vscode/mcp.json
└────────┬────────┘


┌─────────────────┐
│ MCP Server │ ← Validates on each request
│ Authenticates │
└────────┬────────┘


┌─────────────────┐
│ Tools Execute │ ← With user context
│ (with logging) │
└────────┬────────┘


┌─────────────────┐
│ Revoke (opt.) │ ← When needed
└─────────────────┘

Examples

Generate key and configure

# Step 1: Generate
npm run mcp:generate-key
# Select user, copy the generated key

# Step 2: Configure .vscode/mcp.json
{
"servers": {
"BaldrApi": {
...
"env": {
"MCP_API_KEY": "mcp_abc123..."
}
}
}
}

# Step 3: Reload VS Code
# Ctrl+Shift+P → "Developer: Reload Window"

Check who you're authenticated as

@BaldrApi get API health

The logs will show: Authenticated as: username


Your MCP server is now secured! 🔐