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

@pavindulakshan/mcp-express

v0.1.0

Published

Express middleware for enforcing Model Context Protocol (MCP) authorization using Asgardeo.

Readme

@asgardeo/mcp-express

npm version npm downloads

Express middleware for enforcing Model Context Protocol (MCP) authorization using Asgardeo.

Overview

This package provides Express middleware that implements Model Context Protocol (MCP) based authorization for Express.js applications. It integrates with Asgardeo for authentication and authorization services.

This package is part of the Asgardeo MCP Node.js SDKs monorepo. For overall project information, contribution guidelines, and details on other related packages, please refer to the main repository.

Installation

npm install @asgardeo/mcp-express
# or
yarn add @asgardeo/mcp-express
# or
pnpm add @asgardeo/mcp-express

Features

  • Easy-to-use Express middleware
  • Protected route handling
  • Automatic metadata endpoint setup
  • Built-in CORS support
  • Seamless integration with Asgardeo

Usage

Basic Setup

import express from 'express';
import {McpAuthServer} from '@asgardeo/mcp-express';

const app = express();

// Initialize McpAuthServer with baseUrl
const mcpAuthServer = new McpAuthServer({
  baseUrl: process.env.BASE_URL as string,
});

app.use(express.json());
app.use(mcpAuthServer.router());

// Protect your MCP endpoint
app.post('/mcp', mcpAuthServer.protect(), async (req, res) => {
  // Your MCP handling logic here
});

API Reference

McpAuthServer(options)

Creates a new instance of the MCP authentication server with the given configuration.

import {McpAuthServer} from '@asgardeo/mcp-express';

const mcpAuthServer = new McpAuthServer({baseUrl: 'https://auth.example.com'});

mcpAuthServer.router()

Returns an Express router that sets up the necessary endpoints for MCP authentication.

app.use(mcpAuthServer.router());

mcpAuthServer.protect()

Returns middleware that protects routes requiring authentication. This middleware should be applied before your route handler.

app.post('/api/protected', mcpAuthServer.protect(), async (req, res) => {
  // Your protected route logic here
});

Configuration

The server can be configured with the following option:

interface McpAuthServerOptions {
  /** Base URL of the authorization server */
  baseUrl: string;
}

Example

Here's a complete example of setting up an Express server with MCP authentication:

import {randomUUID} from 'node:crypto';
import {McpAuthServer} from '@asgardeo/mcp-express';
import {McpServer} from '@modelcontextprotocol/sdk/server/mcp';
import {StreamableHTTPServerTransport} from '@modelcontextprotocol/sdk/server/streamableHttp';
import {isInitializeRequest} from '@modelcontextprotocol/sdk/types';
import {config} from 'dotenv';
import express, {Express, Request, Response} from 'express';
import {z} from 'zod';

config();

const app: Express = express();

// Initialize McpAuthServer
const mcpAuthServer = new McpAuthServer({
  baseUrl: process.env.BASE_URL as string,
});

app.use(express.json());
app.use(mcpAuthServer.router());

// Session management
interface TransportMap {
  [sessionId: string]: {
    lastAccess: number;
    transport: StreamableHTTPServerTransport;
  };
}

const transports: TransportMap = {};
const SESSION_TIMEOUT_MS: number = 30 * 60 * 1000;

const isSessionExpired = (lastAccessTime: number): boolean => Date.now() - lastAccessTime > SESSION_TIMEOUT_MS;

// MCP endpoint with authentication
app.post(
  '/mcp',
  mcpAuthServer.protect(),
  async (req: Request, res: Response): Promise<void> => {
    try {
      const sessionId: string | undefined = req.headers['mcp-session-id'] as string | undefined;
      let transport: StreamableHTTPServerTransport;

      // Handle existing session or create new one
      if (sessionId && transports[sessionId]) {
        // Session management code...
        transport = transports[sessionId].transport;
        transports[sessionId].lastAccess = Date.now();
      } else if (!sessionId && isInitializeRequest(req.body)) {
        // Extract bearer token if present
        let bearerToken: string | undefined;
        const authHeader: string | undefined = req.headers.authorization as string | undefined;
        if (authHeader && authHeader.toLowerCase().startsWith('bearer ')) {
          bearerToken = authHeader.substring(7);
          console.log(`Bearer token captured for new session.`);
        }

        // Create MCP server and configure tools
        transport = new StreamableHTTPServerTransport({
          // Transport configuration...
        });

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

        // Define MCP tools
        server.tool(
          'get_pet_vaccination_info',
          'Retrieves the vaccination history for a specific pet.',
          {
            petId: z.string().describe('The unique identifier for the pet.'),
          },
          async ({petId}) => {
            // Tool implementation using bearer token
            return {
              content: [
                {
                  text: `Retrieved vaccination info for pet ID: ${petId}. Token was ${
                    bearerToken ? 'present' : 'absent'
                  }.`,
                  type: 'text',
                },
              ],
            };
          },
        );

        await server.connect(transport);
      } else {
        // Handle invalid requests
        res.status(400).json({
          error: {
            code: -32000,
            message: 'Bad Request',
          },
          id: req.body?.id || null,
          jsonrpc: '2.0',
        });
        return;
      }

      await transport.handleRequest(req, res, req.body);
    } catch (error) {
      // Error handling
    }
  }),
);

const PORT: string | number = process.env.PORT || 3000;
app.listen(PORT, (): void => {
  console.log(`MCP server running on port ${PORT}`);
});

Prerequisites

  • Node.js 16.x or later
  • pnpm 8.x or later

Setup

  1. Clone the repository
  2. Install dependencies:
pnpm install

Build

pnpm build

Lint

pnpm lint

License

Apache-2.0 - see the LICENSE file for details.