Gathering detailed insights and metrics for @asgardeo/mcp-express
Gathering detailed insights and metrics for @asgardeo/mcp-express
Gathering detailed insights and metrics for @asgardeo/mcp-express
Gathering detailed insights and metrics for @asgardeo/mcp-express
npm install @asgardeo/mcp-express
Typescript
Module System
Min. Node Version
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
4
1
Express middleware for enforcing Model Context Protocol (MCP) authorization using Asgardeo.
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.
1npm install @asgardeo/mcp-express 2# or 3yarn add @asgardeo/mcp-express 4# or 5pnpm add @asgardeo/mcp-express
1import express from 'express'; 2import {McpAuthServer} from '@asgardeo/mcp-express'; 3 4const app = express(); 5 6// Initialize McpAuthServer with baseUrl 7const mcpAuthServer = new McpAuthServer({ 8 baseUrl: process.env.BASE_URL as string, 9}); 10 11app.use(express.json()); 12app.use(mcpAuthServer.router()); 13 14// Protect your MCP endpoint 15app.post('/mcp', mcpAuthServer.protect(), async (req, res) => { 16 // Your MCP handling logic here 17});
Creates a new instance of the MCP authentication server with the given configuration.
1import {McpAuthServer} from '@asgardeo/mcp-express'; 2 3const mcpAuthServer = new McpAuthServer({baseUrl: 'https://auth.example.com'});
Returns an Express router that sets up the necessary endpoints for MCP authentication.
1app.use(mcpAuthServer.router());
Returns middleware that protects routes requiring authentication. This middleware should be applied before your route handler.
1app.post('/api/protected', mcpAuthServer.protect(), async (req, res) => { 2 // Your protected route logic here 3});
The server can be configured with the following option:
1interface McpAuthServerOptions { 2 /** Base URL of the authorization server */ 3 baseUrl: string; 4}
Here's a complete example of setting up an Express server with MCP authentication:
1import {randomUUID} from 'node:crypto'; 2import {McpAuthServer} from '@asgardeo/mcp-express'; 3import {McpServer} from '@modelcontextprotocol/sdk/server/mcp'; 4import {StreamableHTTPServerTransport} from '@modelcontextprotocol/sdk/server/streamableHttp'; 5import {isInitializeRequest} from '@modelcontextprotocol/sdk/types'; 6import {config} from 'dotenv'; 7import express, {Express, Request, Response} from 'express'; 8import {z} from 'zod'; 9 10config(); 11 12const app: Express = express(); 13 14// Initialize McpAuthServer 15const mcpAuthServer = new McpAuthServer({ 16 baseUrl: process.env.BASE_URL as string, 17}); 18 19app.use(express.json()); 20app.use(mcpAuthServer.router()); 21 22// Session management 23interface TransportMap { 24 [sessionId: string]: { 25 lastAccess: number; 26 transport: StreamableHTTPServerTransport; 27 }; 28} 29 30const transports: TransportMap = {}; 31const SESSION_TIMEOUT_MS: number = 30 * 60 * 1000; 32 33const isSessionExpired = (lastAccessTime: number): boolean => Date.now() - lastAccessTime > SESSION_TIMEOUT_MS; 34 35// MCP endpoint with authentication 36app.post( 37 '/mcp', 38 mcpAuthServer.protect(), 39 async (req: Request, res: Response): Promise<void> => { 40 try { 41 const sessionId: string | undefined = req.headers['mcp-session-id'] as string | undefined; 42 let transport: StreamableHTTPServerTransport; 43 44 // Handle existing session or create new one 45 if (sessionId && transports[sessionId]) { 46 // Session management code... 47 transport = transports[sessionId].transport; 48 transports[sessionId].lastAccess = Date.now(); 49 } else if (!sessionId && isInitializeRequest(req.body)) { 50 // Extract bearer token if present 51 let bearerToken: string | undefined; 52 const authHeader: string | undefined = req.headers.authorization as string | undefined; 53 if (authHeader && authHeader.toLowerCase().startsWith('bearer ')) { 54 bearerToken = authHeader.substring(7); 55 console.log(`Bearer token captured for new session.`); 56 } 57 58 // Create MCP server and configure tools 59 transport = new StreamableHTTPServerTransport({ 60 // Transport configuration... 61 }); 62 63 const server: McpServer = new McpServer({ 64 name: 'example-server', 65 version: '1.0.0', 66 }); 67 68 // Define MCP tools 69 server.tool( 70 'get_pet_vaccination_info', 71 'Retrieves the vaccination history for a specific pet.', 72 { 73 petId: z.string().describe('The unique identifier for the pet.'), 74 }, 75 async ({petId}) => { 76 // Tool implementation using bearer token 77 return { 78 content: [ 79 { 80 text: `Retrieved vaccination info for pet ID: ${petId}. Token was ${ 81 bearerToken ? 'present' : 'absent' 82 }.`, 83 type: 'text', 84 }, 85 ], 86 }; 87 }, 88 ); 89 90 await server.connect(transport); 91 } else { 92 // Handle invalid requests 93 res.status(400).json({ 94 error: { 95 code: -32000, 96 message: 'Bad Request', 97 }, 98 id: req.body?.id || null, 99 jsonrpc: '2.0', 100 }); 101 return; 102 } 103 104 await transport.handleRequest(req, res, req.body); 105 } catch (error) { 106 // Error handling 107 } 108 }), 109); 110 111const PORT: string | number = process.env.PORT || 3000; 112app.listen(PORT, (): void => { 113 console.log(`MCP server running on port ${PORT}`); 114});
1pnpm install
1pnpm build
1pnpm lint
Apache-2.0 - see the LICENSE file for details.
No vulnerabilities found.
No security vulnerabilities found.