npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@mcp-accelerator/middleware-auth

v1.0.0

Published

Authentication middleware for MCP Accelerator

Readme

@mcp-accelerator/middleware-auth

Authentication middleware for MCP Accelerator. Provides JWT and API Key authentication out of the box.

Installation

npm install @mcp-accelerator/core @mcp-accelerator/middleware-auth

Features

  • ✅ JWT Authentication (jsonwebtoken)
  • ✅ API Key Authentication
  • ✅ Custom verification logic
  • ✅ Async key validation
  • ✅ User info extraction
  • ✅ TypeScript support

Usage

JWT Authentication

import { MCPServer } from '@mcp-accelerator/core';
import { HttpTransport } from '@mcp-accelerator/transport-http';
import { createJWTAuthMiddleware } from '@mcp-accelerator/middleware-auth';

const server = new MCPServer({
  name: 'secure-server',
  version: '1.0.0',
});

server.setTransport(new HttpTransport({ port: 3000 }));

// Add JWT authentication
server.registerMiddleware(createJWTAuthMiddleware({
  secret: process.env.JWT_SECRET!,
  algorithms: ['HS256'],
  // Optional: custom verification
  verify: async (decoded, context) => {
    // Check if user exists, is active, etc.
    const user = await db.users.findById(decoded.userId);
    return user && user.isActive;
  }
}));

server.registerTool({
  name: 'protected-action',
  description: 'Action that requires authentication',
  inputSchema: z.object({}),
  handler: async (input, context) => {
    // Access authenticated user
    const user = context.metadata.user;
    return { message: `Hello, ${user.name}!` };
  },
});

await server.start();

Client request:

curl -X POST http://localhost:3000/mcp \
  -H "Authorization: Bearer eyJhbGc..." \
  -H "Content-Type: application/json" \
  -d '{"type":"request","method":"tools/execute","params":{"name":"protected-action"}}'

API Key Authentication

import { createAPIKeyAuthMiddleware } from '@mcp-accelerator/middleware-auth';

// Simple array of keys
server.registerMiddleware(createAPIKeyAuthMiddleware({
  keys: ['key-123', 'key-456', 'key-789']
}));

// Or async validation with database
server.registerMiddleware(createAPIKeyAuthMiddleware({
  keys: async (key) => {
    const apiKey = await db.apiKeys.findOne({ 
      key, 
      isActive: true 
    });
    return !!apiKey;
  },
  getUserInfo: async (key) => {
    const apiKey = await db.apiKeys.findOne({ key });
    return {
      userId: apiKey.userId,
      permissions: apiKey.permissions,
      rateLimit: apiKey.rateLimit,
    };
  }
}));

Client request:

curl -X POST http://localhost:3000/mcp \
  -H "X-API-Key: key-123" \
  -H "Content-Type: application/json" \
  -d '{"type":"request","method":"tools/execute","params":{"name":"protected-action"}}'

Custom Headers

// Custom header name
server.registerMiddleware(createAPIKeyAuthMiddleware({
  keys: ['key-123'],
  headerName: 'x-custom-api-key' // Default: 'x-api-key'
}));

// Custom JWT header
server.registerMiddleware(createJWTAuthMiddleware({
  secret: 'secret',
  headerName: 'x-auth-token',    // Default: 'authorization'
  tokenPrefix: 'Token '           // Default: 'Bearer '
}));

Accessing User Info in Tools

server.registerTool({
  name: 'get-user-data',
  description: 'Get authenticated user data',
  inputSchema: z.object({}),
  handler: async (input, context) => {
    // User info added by auth middleware
    const user = context.metadata.user;
    const isAuthenticated = context.metadata.authenticated;
    
    return {
      userId: user.userId,
      authenticated: isAuthenticated
    };
  },
});

Optional Authentication

// Make authentication optional for some tools
server.registerMiddleware({
  name: 'optional-auth',
  priority: 90,
  async handler(message, context, next) {
    try {
      // Try JWT auth
      const authMiddleware = createJWTAuthMiddleware({ 
        secret: 'secret' 
      });
      await authMiddleware.handler(message, context, async () => {});
    } catch (error) {
      // No auth - continue anyway
      context.metadata.authenticated = false;
    }
    await next();
  }
});

Configuration

JWTAuthOptions

interface JWTAuthOptions {
  secret: string;                    // JWT secret key
  algorithms?: jwt.Algorithm[];      // Allowed algorithms (default: ['HS256'])
  headerName?: string;               // Header name (default: 'authorization')
  tokenPrefix?: string;              // Token prefix (default: 'Bearer ')
  verify?: (decoded, context) =>     // Custom verification
    Promise<boolean> | boolean;
}

APIKeyAuthOptions

interface APIKeyAuthOptions {
  keys: string[] |                   // Valid keys or validation function
    ((key: string) => Promise<boolean> | boolean);
  headerName?: string;               // Header name (default: 'x-api-key')
  getUserInfo?: (key: string) =>     // Get user info from key
    Promise<any> | any;
}

Error Handling

The middleware throws errors for:

  • Missing authentication (no token/key provided)
  • Invalid token/key
  • Expired JWT
  • Failed custom verification

Handle these in your error handler or let them bubble up to the transport.

Security Best Practices

  1. Use HTTPS in production
  2. Store secrets securely (environment variables, secrets manager)
  3. Rotate API keys regularly
  4. Use short-lived JWTs (15-60 minutes)
  5. Implement refresh tokens for JWT
  6. Rate limit by user/API key
  7. Log authentication failures
  8. Use strong JWT algorithms (RS256 recommended for production)

Examples

See the secure-api example for a complete example.

License

MIT