/** * OAuth Middleware for MCP Server * * Implements OAuth 2.0 Protected Resource support per RFC 9728 for MCP servers. * This allows MCP servers to require OAuth authentication from clients. * * @see https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization * @see https://www.rfc-editor.org/rfc/rfc9728.html */ import type * as http from 'node:http'; import type { MCPServerOAuthConfig, TokenValidationResult } from '../shared/oauth-types.js'; /** * Simple logger interface for OAuth middleware. */ interface OAuthMiddlewareLogger { debug?: (message: string, ...args: unknown[]) => void; } /** * Options for the OAuth middleware. */ export interface OAuthMiddlewareOptions { /** * OAuth configuration for the MCP server. */ oauth: MCPServerOAuthConfig; /** * Path where the MCP endpoint is served. * @default '/mcp' */ mcpPath?: string; /** * Logger instance for debugging. */ logger?: OAuthMiddlewareLogger; } /** * Result of the middleware check. */ export interface OAuthMiddlewareResult { /** * Whether the request should proceed. */ proceed: boolean; /** * If false, the response has already been sent. */ handled: boolean; /** * Token validation result if authentication was attempted. */ tokenValidation?: TokenValidationResult; } /** * Creates an OAuth middleware function for protecting MCP server endpoints. * * This middleware: * 1. Serves Protected Resource Metadata at `/.well-known/oauth-protected-resource` * 2. Validates bearer tokens on protected endpoints * 3. Returns proper 401 responses with WWW-Authenticate headers * * @param options - Middleware configuration * @returns Middleware function that returns whether request should proceed * * @example * ```typescript * import http from 'node:http'; * import { MCPServer, createOAuthMiddleware } from '@mastra/mcp'; * * const server = new MCPServer({ name: 'Protected Server', version: '1.0.0', tools: {} }); * * const oauthMiddleware = createOAuthMiddleware({ * oauth: { * resource: 'https://mcp.example.com/mcp', * authorizationServers: ['https://auth.example.com'], * validateToken: async (token, resource) => { * // Your token validation logic here * return { valid: true, scopes: ['mcp:read', 'mcp:write'] }; * }, * }, * }); * * const httpServer = http.createServer(async (req, res) => { * const url = new URL(req.url || '', 'http://localhost:3000'); * * // Apply OAuth middleware first * const result = await oauthMiddleware(req, res, url); * if (!result.proceed) return; // Middleware handled the response * * // Continue to MCP handler * await server.startHTTP({ url, httpPath: '/mcp', req, res }); * }); * * httpServer.listen(3000); * ``` */ export declare function createOAuthMiddleware(options: OAuthMiddlewareOptions): (req: http.IncomingMessage, res: http.ServerResponse, url: URL) => Promise; /** * Helper to create a simple token validator that checks against a list of valid tokens. * * Useful for testing and development. For production, use a proper JWT validator * or call your authorization server's introspection endpoint. * * @param validTokens - Array of valid token strings * @returns Token validation function * * @example * ```typescript * const validateToken = createStaticTokenValidator(['secret-token-1', 'secret-token-2']); * * const middleware = createOAuthMiddleware({ * oauth: { * resource: 'https://mcp.example.com/mcp', * authorizationServers: ['https://auth.example.com'], * validateToken, * }, * }); * ``` */ export declare function createStaticTokenValidator(validTokens: string[]): MCPServerOAuthConfig['validateToken']; /** * Creates a token validator that calls an introspection endpoint. * * Per RFC 7662, the introspection endpoint returns token metadata. * * @param introspectionEndpoint - URL of the token introspection endpoint * @param clientCredentials - Optional client credentials for authenticated introspection * @returns Token validation function * * @example * ```typescript * const validateToken = createIntrospectionValidator( * 'https://auth.example.com/oauth/introspect', * { clientId: 'mcp-server', clientSecret: 'secret' } * ); * ``` */ export declare function createIntrospectionValidator(introspectionEndpoint: string, clientCredentials?: { clientId: string; clientSecret: string; }): MCPServerOAuthConfig['validateToken']; export {}; //# sourceMappingURL=oauth-middleware.d.ts.map