Repository: payloadcms/payload
File: packages/plugin-mcp/src/endpoints/mcp.ts (TypeScript)

Code before:
import { createRequestFromPayloadRequest } from '../mcp/createRequest.js'
import { getMCPHandler } from '../mcp/getMcpHandler.js'

export const initializeMCPHandler = (pluginOptions: PluginMCPServerConfig) => {
  const mcpHandler: PayloadHandler = async (req) => {
    const { payload } = req
    const MCPOptions = pluginOptions.mcp || {}
    const MCPHandlerOptions = MCPOptions.handlerOptions || {}
    const useVerboseLogs = MCPHandlerOptions.verboseLogs ?? false

    let mcpAccessSettings: MCPAccessSettings

    if (pluginOptions.overrideAuth) {
      try {
        mcpAccessSettings = await pluginOptions.overrideAuth(req)
        if (useVerboseLogs) {
          payload.logger.info('[payload-mcp] Custom authentication method successful')
        }
      } catch (error) {
        payload.logger.error({
          err: error,
          msg: '[payload-mcp] Custom authentication method failed',
        })
        throw new APIError('Authentication failed', 401)
      }
    } else {
      const apiKey = req.headers.get('Authorization')?.startsWith('Bearer ')
        ? req.headers.get('Authorization')?.replace('Bearer ', '').trim()
        : null

      if (apiKey === null) {
        throw new APIError('API Key is required', 401)
      }

      const sha256APIKeyIndex = crypto
        .createHmac('sha256', payload.secret)
        .update(apiKey || '')
        .digest('hex')

      const apiKeyConstraints = [
        {
          apiKeyIndex: {
            equals: sha256APIKeyIndex,
          },
        },
      ]
      const where: Where = {
        or: apiKeyConstraints,
      }

      const { docs } = await payload.find({

Review comment (security):
FWIW, you could remove the if/else block and instead move the logic from this `else` to a function that gets assigned as a default to `overrideAuth`.

This way we can export it and users could import and call it in their own override as a way to extend existing functionality by adding code before/after calling the default.

Code after:
import { createRequestFromPayloadRequest } from '../mcp/createRequest.js'
import { getMCPHandler } from '../mcp/getMcpHandler.js'

export const initializeMCPHandler = (pluginOptions: PluginMCPServerConfig) => {
  const mcpHandler: PayloadHandler = async (req) => {
    const { payload } = req
    const MCPOptions = pluginOptions.mcp || {}
    const MCPHandlerOptions = MCPOptions.handlerOptions || {}
    const useVerboseLogs = MCPHandlerOptions.verboseLogs ?? false

    const getDefaultMcpAccessSettings = async (overrideApiKey?: null | string) => {
      const apiKey =
        (overrideApiKey ?? req.headers.get('Authorization')?.startsWith('Bearer '))
          ? req.headers.get('Authorization')?.replace('Bearer ', '').trim()
          : null

      if (apiKey === null) {
        throw new UnauthorizedError()
      }

      const sha256APIKeyIndex = crypto
        .createHmac('sha256', payload.secret)
        .update(apiKey || '')
        .digest('hex')

      const apiKeyConstraints = [
        {
          apiKeyIndex: {
            equals: sha256APIKeyIndex,
          },
        },
      ]

      const where: Where = {
        or: apiKeyConstraints,
      }

      const { docs } = await payload.find({
        collection: 'payload-mcp-api-keys',
        limit: 1,
        pagination: false,
        where,
      })

      if (docs.length === 0) {
        throw new UnauthorizedError()
      }

      if (useVerboseLogs) {
        payload.logger.info('[payload-mcp] API Key is valid')
      }