@payloadcms/plugin-mcp 4.0.0-internal.f15737c → 4.0.0-internal.f2a04f7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../../src/endpoint/access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAwB,MAAM,SAAS,CAAA;AAInE,OAAO,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AAIzD,MAAM,MAAM,oBAAoB,GAAG;IACjC,cAAc,EAAE,OAAO,CAAA;IACvB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,gBAAgB,EAAE,CAAC,IAAI,EAAE,oBAAoB,KAAK,OAAO,CAAC,aAAa,CAkCnF,CAAA;AAED,eAAO,MAAM,cAAc,oCAIxB;IACD,KAAK,EAAE,OAAO,EAAE,CAAA;IAChB,cAAc,EAAE,OAAO,CAAA;IACvB,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,OAAO,EAAE,CAkBpB,CAAA"}
1
+ {"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../../src/endpoint/access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAwB,MAAM,SAAS,CAAA;AAInE,OAAO,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AAIzD,MAAM,MAAM,oBAAoB,GAAG;IACjC,cAAc,EAAE,OAAO,CAAA;IACvB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,gBAAgB,EAAE,CAAC,IAAI,EAAE,oBAAoB,KAAK,OAAO,CAAC,aAAa,CA2CnF,CAAA;AAED,eAAO,MAAM,cAAc,oCAIxB;IACD,KAAK,EAAE,OAAO,EAAE,CAAA;IAChB,cAAc,EAAE,OAAO,CAAA;IACvB,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,OAAO,EAAE,CAkBpB,CAAA"}
@@ -1,4 +1,4 @@
1
- import { getAccessResults, UnauthorizedError } from 'payload';
1
+ import { executeAuthStrategies, getAccessResults, UnauthorizedError } from 'payload';
2
2
  import { getPluginConfig } from '../utils/getPluginConfig.js';
3
3
  /**
4
4
  * Authenticates an MCP request and removes items the user cannot access.
@@ -18,11 +18,23 @@ import { getPluginConfig } from '../utils/getPluginConfig.js';
18
18
  const headers = new Headers(req.headers);
19
19
  const hasAuthorization = headers.has('Authorization');
20
20
  headers.set('DisableAutologin', 'true');
21
- req.user = (await req.payload.auth({
21
+ // Not `payload.auth()`, which also computes permissions that filterMCPItems computes anyway
22
+ req.user = (await executeAuthStrategies({
22
23
  headers,
24
+ payload: req.payload,
23
25
  req
24
26
  })).user;
25
- if (hasAuthorization && !req.user) {
27
+ // Only bearer tokens that no auth strategy accepted reach the hook, e.g. an OAuth access token.
28
+ // API keys use the `<collection> API-Key <key>` scheme instead of `Bearer`, so they never do.
29
+ const bearerToken = headers.get('Authorization')?.match(/^Bearer (.+)$/)?.[1];
30
+ if (!req.user && bearerToken && pluginConfig.oauth?.authenticate) {
31
+ req.user = await pluginConfig.oauth.authenticate({
32
+ req,
33
+ token: bearerToken
34
+ });
35
+ }
36
+ // With OAuth, the endpoint answers with a challenge that starts the client's sign-in
37
+ if (hasAuthorization && !req.user && !pluginConfig.oauth) {
26
38
  throw new UnauthorizedError(req.t);
27
39
  }
28
40
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/endpoint/access.ts"],"sourcesContent":["import type { PayloadRequest, SanitizedPermissions } from 'payload'\n\nimport { getAccessResults, UnauthorizedError } from 'payload'\n\nimport type { AuthorizedMCP, MCPItem } from '../types.js'\n\nimport { getPluginConfig } from '../utils/getPluginConfig.js'\n\nexport type GetAuthorizedMCPArgs = {\n overrideAccess: boolean\n req: PayloadRequest\n}\n\n/**\n * Authenticates an MCP request and removes items the user cannot access.\n * `overrideAccess` skips Payload and MCP item access checks.\n */\nexport const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<AuthorizedMCP> = async ({\n overrideAccess,\n req,\n}) => {\n const pluginConfig = getPluginConfig({ config: req.payload.config })\n\n if (pluginConfig.overrideGetAuthorizedMCP) {\n return await pluginConfig.overrideGetAuthorizedMCP({\n overrideAccess,\n pluginConfig,\n req,\n })\n }\n\n if (req.headers) {\n const headers = new Headers(req.headers)\n const hasAuthorization = headers.has('Authorization')\n\n headers.set('DisableAutologin', 'true')\n req.user = (await req.payload.auth({ headers, req })).user\n\n if (hasAuthorization && !req.user) {\n throw new UnauthorizedError(req.t)\n }\n }\n\n return {\n items: await filterMCPItems({\n items: pluginConfig.items,\n overrideAccess,\n req,\n }),\n overrideAccess,\n }\n}\n\nexport const filterMCPItems = async ({\n items,\n overrideAccess,\n req,\n}: {\n items: MCPItem[]\n overrideAccess: boolean\n req: PayloadRequest\n}): Promise<MCPItem[]> => {\n // Match Payload core: overrideAccess bypasses access evaluation\n if (overrideAccess) {\n return items\n }\n\n const authorizedItems: MCPItem[] = []\n\n const permissions = await getAccessResults({ req })\n\n for (const item of items) {\n if (!(await checkItemAccess({ item, permissions, req }))) {\n continue\n }\n authorizedItems.push(item)\n }\n\n return authorizedItems\n}\n\n/**\n * Runs MCP item access callbacks\n */\nconst checkItemAccess = async ({\n item,\n permissions,\n req,\n}: {\n item: MCPItem\n permissions?: SanitizedPermissions\n req: PayloadRequest\n}): Promise<boolean> => {\n switch (item.type) {\n case 'collectionTool':\n return (\n !item.tool.access ||\n (await item.tool.access({ slug: item.collectionSlug, permissions, req }))\n )\n case 'globalTool':\n return (\n !item.tool.access || (await item.tool.access({ slug: item.globalSlug, permissions, req }))\n )\n case 'prompt':\n return !item.prompt.access || (await item.prompt.access({ permissions, req }))\n case 'resource':\n return !item.resource.access || (await item.resource.access({ permissions, req }))\n case 'tool':\n return !item.tool.access || (await item.tool.access({ permissions, req }))\n }\n}\n"],"names":["getAccessResults","UnauthorizedError","getPluginConfig","getAuthorizedMCP","overrideAccess","req","pluginConfig","config","payload","overrideGetAuthorizedMCP","headers","Headers","hasAuthorization","has","set","user","auth","t","items","filterMCPItems","authorizedItems","permissions","item","checkItemAccess","push","type","tool","access","slug","collectionSlug","globalSlug","prompt","resource"],"mappings":"AAEA,SAASA,gBAAgB,EAAEC,iBAAiB,QAAQ,UAAS;AAI7D,SAASC,eAAe,QAAQ,8BAA6B;AAO7D;;;CAGC,GACD,OAAO,MAAMC,mBAA2E,OAAO,EAC7FC,cAAc,EACdC,GAAG,EACJ;IACC,MAAMC,eAAeJ,gBAAgB;QAAEK,QAAQF,IAAIG,OAAO,CAACD,MAAM;IAAC;IAElE,IAAID,aAAaG,wBAAwB,EAAE;QACzC,OAAO,MAAMH,aAAaG,wBAAwB,CAAC;YACjDL;YACAE;YACAD;QACF;IACF;IAEA,IAAIA,IAAIK,OAAO,EAAE;QACf,MAAMA,UAAU,IAAIC,QAAQN,IAAIK,OAAO;QACvC,MAAME,mBAAmBF,QAAQG,GAAG,CAAC;QAErCH,QAAQI,GAAG,CAAC,oBAAoB;QAChCT,IAAIU,IAAI,GAAG,AAAC,CAAA,MAAMV,IAAIG,OAAO,CAACQ,IAAI,CAAC;YAAEN;YAASL;QAAI,EAAC,EAAGU,IAAI;QAE1D,IAAIH,oBAAoB,CAACP,IAAIU,IAAI,EAAE;YACjC,MAAM,IAAId,kBAAkBI,IAAIY,CAAC;QACnC;IACF;IAEA,OAAO;QACLC,OAAO,MAAMC,eAAe;YAC1BD,OAAOZ,aAAaY,KAAK;YACzBd;YACAC;QACF;QACAD;IACF;AACF,EAAC;AAED,OAAO,MAAMe,iBAAiB,OAAO,EACnCD,KAAK,EACLd,cAAc,EACdC,GAAG,EAKJ;IACC,gEAAgE;IAChE,IAAID,gBAAgB;QAClB,OAAOc;IACT;IAEA,MAAME,kBAA6B,EAAE;IAErC,MAAMC,cAAc,MAAMrB,iBAAiB;QAAEK;IAAI;IAEjD,KAAK,MAAMiB,QAAQJ,MAAO;QACxB,IAAI,CAAE,MAAMK,gBAAgB;YAAED;YAAMD;YAAahB;QAAI,IAAK;YACxD;QACF;QACAe,gBAAgBI,IAAI,CAACF;IACvB;IAEA,OAAOF;AACT,EAAC;AAED;;CAEC,GACD,MAAMG,kBAAkB,OAAO,EAC7BD,IAAI,EACJD,WAAW,EACXhB,GAAG,EAKJ;IACC,OAAQiB,KAAKG,IAAI;QACf,KAAK;YACH,OACE,CAACH,KAAKI,IAAI,CAACC,MAAM,IAChB,MAAML,KAAKI,IAAI,CAACC,MAAM,CAAC;gBAAEC,MAAMN,KAAKO,cAAc;gBAAER;gBAAahB;YAAI;QAE1E,KAAK;YACH,OACE,CAACiB,KAAKI,IAAI,CAACC,MAAM,IAAK,MAAML,KAAKI,IAAI,CAACC,MAAM,CAAC;gBAAEC,MAAMN,KAAKQ,UAAU;gBAAET;gBAAahB;YAAI;QAE3F,KAAK;YACH,OAAO,CAACiB,KAAKS,MAAM,CAACJ,MAAM,IAAK,MAAML,KAAKS,MAAM,CAACJ,MAAM,CAAC;gBAAEN;gBAAahB;YAAI;QAC7E,KAAK;YACH,OAAO,CAACiB,KAAKU,QAAQ,CAACL,MAAM,IAAK,MAAML,KAAKU,QAAQ,CAACL,MAAM,CAAC;gBAAEN;gBAAahB;YAAI;QACjF,KAAK;YACH,OAAO,CAACiB,KAAKI,IAAI,CAACC,MAAM,IAAK,MAAML,KAAKI,IAAI,CAACC,MAAM,CAAC;gBAAEN;gBAAahB;YAAI;IAC3E;AACF"}
1
+ {"version":3,"sources":["../../src/endpoint/access.ts"],"sourcesContent":["import type { PayloadRequest, SanitizedPermissions } from 'payload'\n\nimport { executeAuthStrategies, getAccessResults, UnauthorizedError } from 'payload'\n\nimport type { AuthorizedMCP, MCPItem } from '../types.js'\n\nimport { getPluginConfig } from '../utils/getPluginConfig.js'\n\nexport type GetAuthorizedMCPArgs = {\n overrideAccess: boolean\n req: PayloadRequest\n}\n\n/**\n * Authenticates an MCP request and removes items the user cannot access.\n * `overrideAccess` skips Payload and MCP item access checks.\n */\nexport const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<AuthorizedMCP> = async ({\n overrideAccess,\n req,\n}) => {\n const pluginConfig = getPluginConfig({ config: req.payload.config })\n\n if (pluginConfig.overrideGetAuthorizedMCP) {\n return await pluginConfig.overrideGetAuthorizedMCP({\n overrideAccess,\n pluginConfig,\n req,\n })\n }\n\n if (req.headers) {\n const headers = new Headers(req.headers)\n const hasAuthorization = headers.has('Authorization')\n\n headers.set('DisableAutologin', 'true')\n // Not `payload.auth()`, which also computes permissions that filterMCPItems computes anyway\n req.user = (await executeAuthStrategies({ headers, payload: req.payload, req })).user\n\n // Only bearer tokens that no auth strategy accepted reach the hook, e.g. an OAuth access token.\n // API keys use the `<collection> API-Key <key>` scheme instead of `Bearer`, so they never do.\n const bearerToken = headers.get('Authorization')?.match(/^Bearer (.+)$/)?.[1]\n if (!req.user && bearerToken && pluginConfig.oauth?.authenticate) {\n req.user = await pluginConfig.oauth.authenticate({ req, token: bearerToken })\n }\n\n // With OAuth, the endpoint answers with a challenge that starts the client's sign-in\n if (hasAuthorization && !req.user && !pluginConfig.oauth) {\n throw new UnauthorizedError(req.t)\n }\n }\n\n return {\n items: await filterMCPItems({\n items: pluginConfig.items,\n overrideAccess,\n req,\n }),\n overrideAccess,\n }\n}\n\nexport const filterMCPItems = async ({\n items,\n overrideAccess,\n req,\n}: {\n items: MCPItem[]\n overrideAccess: boolean\n req: PayloadRequest\n}): Promise<MCPItem[]> => {\n // Match Payload core: overrideAccess bypasses access evaluation\n if (overrideAccess) {\n return items\n }\n\n const authorizedItems: MCPItem[] = []\n\n const permissions = await getAccessResults({ req })\n\n for (const item of items) {\n if (!(await checkItemAccess({ item, permissions, req }))) {\n continue\n }\n authorizedItems.push(item)\n }\n\n return authorizedItems\n}\n\n/**\n * Runs MCP item access callbacks\n */\nconst checkItemAccess = async ({\n item,\n permissions,\n req,\n}: {\n item: MCPItem\n permissions?: SanitizedPermissions\n req: PayloadRequest\n}): Promise<boolean> => {\n switch (item.type) {\n case 'collectionTool':\n return (\n !item.tool.access ||\n (await item.tool.access({ slug: item.collectionSlug, permissions, req }))\n )\n case 'globalTool':\n return (\n !item.tool.access || (await item.tool.access({ slug: item.globalSlug, permissions, req }))\n )\n case 'prompt':\n return !item.prompt.access || (await item.prompt.access({ permissions, req }))\n case 'resource':\n return !item.resource.access || (await item.resource.access({ permissions, req }))\n case 'tool':\n return !item.tool.access || (await item.tool.access({ permissions, req }))\n }\n}\n"],"names":["executeAuthStrategies","getAccessResults","UnauthorizedError","getPluginConfig","getAuthorizedMCP","overrideAccess","req","pluginConfig","config","payload","overrideGetAuthorizedMCP","headers","Headers","hasAuthorization","has","set","user","bearerToken","get","match","oauth","authenticate","token","t","items","filterMCPItems","authorizedItems","permissions","item","checkItemAccess","push","type","tool","access","slug","collectionSlug","globalSlug","prompt","resource"],"mappings":"AAEA,SAASA,qBAAqB,EAAEC,gBAAgB,EAAEC,iBAAiB,QAAQ,UAAS;AAIpF,SAASC,eAAe,QAAQ,8BAA6B;AAO7D;;;CAGC,GACD,OAAO,MAAMC,mBAA2E,OAAO,EAC7FC,cAAc,EACdC,GAAG,EACJ;IACC,MAAMC,eAAeJ,gBAAgB;QAAEK,QAAQF,IAAIG,OAAO,CAACD,MAAM;IAAC;IAElE,IAAID,aAAaG,wBAAwB,EAAE;QACzC,OAAO,MAAMH,aAAaG,wBAAwB,CAAC;YACjDL;YACAE;YACAD;QACF;IACF;IAEA,IAAIA,IAAIK,OAAO,EAAE;QACf,MAAMA,UAAU,IAAIC,QAAQN,IAAIK,OAAO;QACvC,MAAME,mBAAmBF,QAAQG,GAAG,CAAC;QAErCH,QAAQI,GAAG,CAAC,oBAAoB;QAChC,4FAA4F;QAC5FT,IAAIU,IAAI,GAAG,AAAC,CAAA,MAAMhB,sBAAsB;YAAEW;YAASF,SAASH,IAAIG,O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,CAACsB,KAAKI,IAAI,CAACC,MAAM,IAAK,MAAML,KAAKI,IAAI,CAACC,MAAM,CAAC;gBAAEC,MAAMN,KAAKQ,UAAU;gBAAET;gBAAarB;YAAI;QAE3F,KAAK;YACH,OAAO,CAACsB,KAAKS,MAAM,CAACJ,MAAM,IAAK,MAAML,KAAKS,MAAM,CAACJ,MAAM,CAAC;gBAAEN;gBAAarB;YAAI;QAC7E,KAAK;YACH,OAAO,CAACsB,KAAKU,QAAQ,CAACL,MAAM,IAAK,MAAML,KAAKU,QAAQ,CAACL,MAAM,CAAC;gBAAEN;gBAAarB;YAAI;QACjF,KAAK;YACH,OAAO,CAACsB,KAAKI,IAAI,CAACC,MAAM,IAAK,MAAML,KAAKI,IAAI,CAACC,MAAM,CAAC;gBAAEN;gBAAarB;YAAI;IAC3E;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/endpoint/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAkB,MAAM,SAAS,CAAA;AAc7D,eAAO,MAAM,WAAW,EAAE,cAmEzB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/endpoint/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAkB,MAAM,SAAS,CAAA;AAe7D,eAAO,MAAM,WAAW,EAAE,cA0EzB,CAAA"}
@@ -3,11 +3,19 @@ import { APIError } from 'payload';
3
3
  import { buildMcpServer } from '../mcp/buildMcpServer.js';
4
4
  import { getPluginConfig } from '../utils/getPluginConfig.js';
5
5
  import { getAuthorizedMCP } from './access.js';
6
+ import { getMCPResource, oauthChallenge } from './oauth.js';
6
7
  export const mcpEndpoint = async (req)=>{
7
8
  if (!req.url) {
8
9
  throw new APIError('Missing request URL', 400);
9
10
  }
10
11
  req.payloadAPI = 'MCP';
12
+ // Lets auth strategies check that an OAuth access token was issued for this MCP server
13
+ req.context.mcp = {
14
+ resource: getMCPResource({
15
+ config: req.payload.config,
16
+ url: req.url
17
+ })
18
+ };
11
19
  const pluginConfig = getPluginConfig({
12
20
  config: req.payload.config
13
21
  });
@@ -25,6 +33,11 @@ export const mcpEndpoint = async (req)=>{
25
33
  overrideAccess,
26
34
  req
27
35
  });
36
+ if (pluginConfig.oauth && !req.user) {
37
+ return oauthChallenge({
38
+ req
39
+ });
40
+ }
28
41
  const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize;
29
42
  // Payload augments the original web-standard Request in place.
30
43
  const mcpRequest = req;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/endpoint/index.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\n\nimport {\n createMcpHandler,\n isLegacyRequest,\n readRequestBody,\n WebStandardStreamableHTTPServerTransport,\n} from '@modelcontextprotocol/server'\nimport { APIError } from 'payload'\n\nimport { buildMcpServer } from '../mcp/buildMcpServer.js'\nimport { getPluginConfig } from '../utils/getPluginConfig.js'\nimport { getAuthorizedMCP } from './access.js'\n\nexport const mcpEndpoint: PayloadHandler = async (req) => {\n if (!req.url) {\n throw new APIError('Missing request URL', 400)\n }\n\n req.payloadAPI = 'MCP' as const\n\n const pluginConfig = getPluginConfig({ config: req.payload.config })\n const overrideAccessParam = new URL(req.url).searchParams.get('overrideAccess')\n\n if (overrideAccessParam !== null && process.env.NODE_ENV !== 'development') {\n throw new APIError('MCP overrideAccess is only available in development.', 400)\n }\n\n let overrideAccess = false\n if (overrideAccessParam === 'true') {\n overrideAccess = true\n } else if (overrideAccessParam !== null && overrideAccessParam !== 'false') {\n throw new APIError('MCP overrideAccess must be \"true\" or \"false\".', 400)\n }\n\n const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })\n const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize\n // Payload augments the original web-standard Request in place.\n const mcpRequest = req as PayloadRequest & Request\n const parsedBody = await parseRequestBody({ maxRequestBodySize, request: mcpRequest })\n\n // Keep the old JSON-only, stateless behavior because the SDK's 2025 fallback uses SSE.\n if (await isLegacyRequest(mcpRequest, parsedBody, { maxRequestBodySize })) {\n const server = buildMcpServer({ authorizedMCP, pluginConfig, req })\n const transport = new WebStandardStreamableHTTPServerTransport({\n enableJsonResponse: true,\n maxRequestBodySize,\n sessionIdGenerator: undefined, // stateless mode\n })\n transport.onerror = (err) => {\n req.payload.logger.error({ err, msg: 'Error serving legacy MCP request' })\n }\n\n try {\n await server.connect(transport)\n return await transport.handleRequest(mcpRequest, { parsedBody })\n } finally {\n await server.close().catch((err) => {\n req.payload.logger.error({ err, msg: 'Error closing MCP server' })\n })\n }\n }\n\n const handler = createMcpHandler(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {\n legacy: 'reject',\n maxRequestBodySize,\n // SDK subscriptions always use SSE, so disable them to keep every response JSON-only.\n maxSubscriptions: 0,\n onerror: (err) => {\n req.payload.logger.error({ err, msg: 'Error serving modern MCP request' })\n },\n responseMode: 'json',\n })\n\n try {\n return await handler.fetch(mcpRequest, { parsedBody })\n } finally {\n await handler.close().catch((err) => {\n req.payload.logger.error({ err, msg: 'Error closing modern MCP handler' })\n })\n }\n}\n\n/**\n * Parses a POST body once so the era check and the SDK handler can share it. The SDK\n * skips its size limit for a pre-parsed body, so this reads with the same limit. It reads\n * a clone and returns `undefined` for any body the SDK should reject (too large, unreadable,\n * or not JSON), leaving the original request for the SDK to read and answer.\n */\nconst parseRequestBody = async ({\n maxRequestBodySize,\n request,\n}: {\n maxRequestBodySize?: number\n request: Request\n}): Promise<unknown> => {\n if (request.method.toUpperCase() !== 'POST') {\n return undefined\n }\n\n try {\n const body = await readRequestBody(request.clone(), maxRequestBodySize)\n return body.tooLarge ? undefined : JSON.parse(body.text)\n } catch {\n return undefined\n }\n}\n"],"names":["createMcpHandler","isLegacyRequest","readRequestBody","WebStandardStreamableHTTPServerTransport","APIError","buildMcpServer","getPluginConfig","getAuthorizedMCP","mcpEndpoint","req","url","payloadAPI","pluginConfig","config","payload","overrideAccessParam","URL","searchParams","get","process","env","NODE_ENV","overrideAccess","authorizedMCP","maxRequestBodySize","mcp","mcpRequest","parsedBody","parseRequestBody","request","server","transport","enableJsonResponse","sessionIdGenerator","undefined","onerror","err","logger","error","msg","connect","handleRequest","close","catch","handler","legacy","maxSubscriptions","responseMode","fetch","method","toUpperCase","body","clone","tooLarge","JSON","parse","text"],"mappings":"AAEA,SACEA,gBAAgB,EAChBC,eAAe,EACfC,eAAe,EACfC,wCAAwC,QACnC,+BAA8B;AACrC,SAASC,QAAQ,QAAQ,UAAS;AAElC,SAASC,cAAc,QAAQ,2BAA0B;AACzD,SAASC,eAAe,QAAQ,8BAA6B;AAC7D,SAASC,gBAAgB,QAAQ,cAAa;AAE9C,OAAO,MAAMC,cAA8B,OAAOC;IAChD,IAAI,CAACA,IAAIC,GAAG,EAAE;QACZ,MAAM,IAAIN,SAAS,uBAAuB;IAC5C;IAEAK,IAAIE,UAAU,GAAG;IAEjB,MAAMC,eAAeN,gBAAgB;QAAEO,QAAQJ,IAAIK,OAAO,CAACD,MAAM;IAAC;IAClE,MAAME,sBAAsB,IAAIC,IAAIP,IAAIC,GAAG,EAAEO,YAAY,CAACC,GAAG,CAAC;IAE9D,IAAIH,wBAAwB,QAAQI,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;QAC1E,MAAM,IAAIjB,SAAS,wDAAwD;IAC7E;IAEA,IAAIkB,iBAAiB;IACrB,IAAIP,wBAAwB,QAAQ;QAClCO,iBAAiB;IACnB,OAAO,IAAIP,wBAAwB,QAAQA,wBAAwB,SAAS;QAC1E,MAAM,IAAIX,SAAS,iDAAiD;IACtE;IAEA,MAAMmB,gBAAgB,MAAMhB,iBAAiB;QAAEe;QAAgBb;IAAI;IACnE,MAAMe,qBAAqBZ,aAAaa,GAAG,EAAED;IAC7C,+DAA+D;IAC/D,MAAME,aAAajB;IACnB,MAAMkB,aAAa,MAAMC,iBAAiB;QAAEJ;QAAoBK,SAASH;IAAW;IAEpF,uFAAuF;IACvF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B;IACT;IAEA,IAAI;QACF,MAAMiB,OAAO,MAAMjD,gBAAgB2B,QAAQuB,KAAK,IAAI5B;QACpD,OAAO2B,KAAKE,QAAQ,GAAGnB,YAAYoB,KAAKC,KAAK,CAACJ,KAAKK,IAAI;IACzD,EAAE,OAAM;QACN,OAAOtB;IACT;AACF"}
1
+ {"version":3,"sources":["../../src/endpoint/index.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\n\nimport {\n createMcpHandler,\n isLegacyRequest,\n readRequestBody,\n WebStandardStreamableHTTPServerTransport,\n} from '@modelcontextprotocol/server'\nimport { APIError } from 'payload'\n\nimport { buildMcpServer } from '../mcp/buildMcpServer.js'\nimport { getPluginConfig } from '../utils/getPluginConfig.js'\nimport { getAuthorizedMCP } from './access.js'\nimport { getMCPResource, oauthChallenge } from './oauth.js'\n\nexport const mcpEndpoint: PayloadHandler = async (req) => {\n if (!req.url) {\n throw new APIError('Missing request URL', 400)\n }\n\n req.payloadAPI = 'MCP' as const\n // Lets auth strategies check that an OAuth access token was issued for this MCP server\n req.context.mcp = { resource: getMCPResource({ config: req.payload.config, url: req.url }) }\n\n const pluginConfig = getPluginConfig({ config: req.payload.config })\n const overrideAccessParam = new URL(req.url).searchParams.get('overrideAccess')\n\n if (overrideAccessParam !== null && process.env.NODE_ENV !== 'development') {\n throw new APIError('MCP overrideAccess is only available in development.', 400)\n }\n\n let overrideAccess = false\n if (overrideAccessParam === 'true') {\n overrideAccess = true\n } else if (overrideAccessParam !== null && overrideAccessParam !== 'false') {\n throw new APIError('MCP overrideAccess must be \"true\" or \"false\".', 400)\n }\n\n const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })\n\n if (pluginConfig.oauth && !req.user) {\n return oauthChallenge({ req })\n }\n\n const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize\n // Payload augments the original web-standard Request in place.\n const mcpRequest = req as PayloadRequest & Request\n const parsedBody = await parseRequestBody({ maxRequestBodySize, request: mcpRequest })\n\n // Keep the old JSON-only, stateless behavior because the SDK's 2025 fallback uses SSE.\n if (await isLegacyRequest(mcpRequest, parsedBody, { maxRequestBodySize })) {\n const server = buildMcpServer({ authorizedMCP, pluginConfig, req })\n const transport = new WebStandardStreamableHTTPServerTransport({\n enableJsonResponse: true,\n maxRequestBodySize,\n sessionIdGenerator: undefined, // stateless mode\n })\n transport.onerror = (err) => {\n req.payload.logger.error({ err, msg: 'Error serving legacy MCP request' })\n }\n\n try {\n await server.connect(transport)\n return await transport.handleRequest(mcpRequest, { parsedBody })\n } finally {\n await server.close().catch((err) => {\n req.payload.logger.error({ err, msg: 'Error closing MCP server' })\n })\n }\n }\n\n const handler = createMcpHandler(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {\n legacy: 'reject',\n maxRequestBodySize,\n // SDK subscriptions always use SSE, so disable them to keep every response JSON-only.\n maxSubscriptions: 0,\n onerror: (err) => {\n req.payload.logger.error({ err, msg: 'Error serving modern MCP request' })\n },\n responseMode: 'json',\n })\n\n try {\n return await handler.fetch(mcpRequest, { parsedBody })\n } finally {\n await handler.close().catch((err) => {\n req.payload.logger.error({ err, msg: 'Error closing modern MCP handler' })\n })\n }\n}\n\n/**\n * Parses a POST body once so the era check and the SDK handler can share it. The SDK\n * skips its size limit for a pre-parsed body, so this reads with the same limit. It reads\n * a clone and returns `undefined` for any body the SDK should reject (too large, unreadable,\n * or not JSON), leaving the original request for the SDK to read and answer.\n */\nconst parseRequestBody = async ({\n maxRequestBodySize,\n request,\n}: {\n maxRequestBodySize?: number\n request: Request\n}): Promise<unknown> => {\n if (request.method.toUpperCase() !== 'POST') {\n return undefined\n }\n\n try {\n const body = await readRequestBody(request.clone(), maxRequestBodySize)\n return body.tooLarge ? undefined : JSON.parse(body.text)\n } catch {\n return undefined\n }\n}\n"],"names":["createMcpHandler","isLegacyRequest","readRequestBody","WebStandardStreamableHTTPServerTransport","APIError","buildMcpServer","getPluginConfig","getAuthorizedMCP","getMCPResource","oauthChallenge","mcpEndpoint","req","url","payloadAPI","context","mcp","resource","config","payload","pluginConfig","overrideAccessParam","URL","searchParams","get","process","env","NODE_ENV","overrideAccess","authorizedMCP","oauth","user","maxRequestBodySize","mcpRequest","parsedBody","parseRequestBody","request","server","transport","enableJsonResponse","sessionIdGenerator","undefined","onerror","err","logger","error","msg","connect","handleRequest","close","catch","handler","legacy","maxSubscriptions","responseMode","fetch","method","toUpperCase","body","clone","tooLarge","JSON","parse","text"],"mappings":"AAEA,SACEA,gBAAgB,EAChBC,eAAe,EACfC,eAAe,EACfC,wCAAwC,QACnC,+BAA8B;AACrC,SAASC,QAAQ,QAAQ,UAAS;AAElC,SAASC,cAAc,QAAQ,2BAA0B;AACzD,SAASC,eAAe,QAAQ,8BAA6B;AAC7D,SAASC,gBAAgB,QAAQ,cAAa;AAC9C,SAASC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAE3D,OAAO,MAAMC,cAA8B,OAAOC;IAChD,IAAI,CAACA,IAAIC,GAAG,EAAE;QACZ,MAAM,IAAIR,SAAS,uBAAuB;IAC5C;IAEAO,IAAIE,UAAU,GAAG;IACjB,uFAAuF;IACvFF,IAAIG,OAAO,CAACC,GAAG,GAAG;QAAEC,UAAUR,eAAe;YAAES,QAAQN,IAAIO,OAAO,CAACD,MAAM;YAAEL,KAAKD,IAAIC,GAAG;QAAC;IAAG;IAE3F,MAAMO,eAAeb,gBAAgB;QAAEW,QAAQN,IAAIO,OAAO,CAACD,MAAM;IAAC;IAClE,MAAMG,sBAAsB,IAAIC,IAAIV,IAAIC,GAAG,EAAEU,YAAY,CAACC,GAAG,CAAC;IAE9D,IAAIH,wBAAwB,QAAQI,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;QAC1E,MAAM,IAAItB,SAAS,wDAAwD;IAC7E;IAEA,IAAIuB,iBAAiB;IACrB,IAAIP,wBAAwB,QAAQ;QAClCO,iBAAiB;IACnB,OAAO,IAAIP,wBAAwB,QAAQA,wBAAwB,SAAS;QAC1E,MAAM,IAAIhB,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AMH,QAAQI,KAAK,CAACtB,YAAY;YAAEC;QAAW;IACtD,SAAU;QACR,MAAMiB,QAAQF,KAAK,GAAGC,KAAK,CAAC,CAACP;YAC3B/B,IAAIO,OAAO,CAACyB,MAAM,CAACC,KAAK,CAAC;gBAAEF;gBAAKG,KAAK;YAAmC;QAC1E;IACF;AACF,EAAC;AAED;;;;;CAKC,GACD,MAAMX,mBAAmB,OAAO,EAC9BH,kBAAkB,EAClBI,OAAO,EAIR;IACC,IAAIA,QAAQoB,MAAM,CAACC,WAAW,OAAO,QAAQ;QAC3C,OAAOhB;IACT;IAEA,IAAI;QACF,MAAMiB,OAAO,MAAMvD,gBAAgBiC,QAAQuB,KAAK,IAAI3B;QACpD,OAAO0B,KAAKE,QAAQ,GAAGnB,YAAYoB,KAAKC,KAAK,CAACJ,KAAKK,IAAI;IACzD,EAAE,OAAM;QACN,OAAOtB;IACT;AACF"}
@@ -0,0 +1,35 @@
1
+ import type { PayloadHandler, PayloadRequest, SanitizedConfig } from 'payload';
2
+ /**
3
+ * Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.
4
+ * The OAuth challenge links here, so MCP clients find the authorization server without setup.
5
+ */
6
+ export declare const oauthProtectedResourceEndpoint: PayloadHandler;
7
+ /**
8
+ * Serves the same metadata for clients that ignore the challenge's link and only look at
9
+ * `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at
10
+ * `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:
11
+ *
12
+ * ```ts
13
+ * import config from '@payload-config'
14
+ * import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'
15
+ *
16
+ * export const GET = oauthProtectedResourceHandler(config)
17
+ * ```
18
+ */
19
+ export declare const oauthProtectedResourceHandler: (config: Promise<SanitizedConfig> | SanitizedConfig) => (request: Request) => Promise<Response>;
20
+ /**
21
+ * Answers an unauthenticated MCP request with a challenge linking to the protected resource
22
+ * metadata, which starts the client's OAuth flow.
23
+ */
24
+ export declare const oauthChallenge: ({ req }: {
25
+ req: PayloadRequest;
26
+ }) => Response;
27
+ /**
28
+ * The MCP endpoint's address, as advertised in the metadata's `resource`. Clients send it when
29
+ * they sign in, and authorization servers that support it put it in the access token's audience.
30
+ */
31
+ export declare const getMCPResource: ({ config, url }: {
32
+ config: SanitizedConfig;
33
+ url: string;
34
+ }) => string;
35
+ //# sourceMappingURL=oauth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../../src/endpoint/oauth.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAW9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,EAAE,cAAsD,CAAA;AAEnG;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,6BAA6B,WAC/B,OAAO,CAAC,eAAe,CAAC,GAAG,eAAe,eACnC,OAAO,KAAG,OAAO,CAAC,QAAQ,CAGtC,CAAA;AAEN;;;GAGG;AACH,eAAO,MAAM,cAAc,YAAa;IAAE,GAAG,EAAE,cAAc,CAAA;CAAE,KAAG,QAajE,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,cAAc,oBAAqB;IAAE,MAAM,EAAE,eAAe,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,KAAG,MAChB,CAAA"}
@@ -0,0 +1,87 @@
1
+ import { bearerAuthChallengeResponse, OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server';
2
+ import { createPayloadRequest, getPayload } from 'payload';
3
+ import { getPluginConfig } from '../utils/getPluginConfig.js';
4
+ /**
5
+ * Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.
6
+ * The OAuth challenge links here, so MCP clients find the authorization server without setup.
7
+ */ export const oauthProtectedResourceEndpoint = (req)=>getMetadataResponse({
8
+ req
9
+ });
10
+ /**
11
+ * Serves the same metadata for clients that ignore the challenge's link and only look at
12
+ * `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at
13
+ * `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:
14
+ *
15
+ * ```ts
16
+ * import config from '@payload-config'
17
+ * import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'
18
+ *
19
+ * export const GET = oauthProtectedResourceHandler(config)
20
+ * ```
21
+ */ export const oauthProtectedResourceHandler = (config)=>async (request)=>getMetadataResponse({
22
+ req: await createPayloadRequest({
23
+ payload: await getPayload({
24
+ config
25
+ }),
26
+ req: request
27
+ })
28
+ });
29
+ /**
30
+ * Answers an unauthenticated MCP request with a challenge linking to the protected resource
31
+ * metadata, which starts the client's OAuth flow.
32
+ */ export const oauthChallenge = ({ req })=>{
33
+ const response = bearerAuthChallengeResponse(new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')), {
34
+ requiredScopes: getPluginConfig({
35
+ config: req.payload.config
36
+ }).oauth?.scopes,
37
+ resourceMetadataUrl: `${getMCPURL({
38
+ config: req.payload.config,
39
+ url: req.url
40
+ })}/oauth-protected-resource`
41
+ });
42
+ // Lets browser-based MCP clients read the challenge, when Payload's `cors` setting allows them
43
+ response.headers.set('Access-Control-Expose-Headers', 'WWW-Authenticate');
44
+ return response;
45
+ };
46
+ /**
47
+ * The MCP endpoint's address, as advertised in the metadata's `resource`. Clients send it when
48
+ * they sign in, and authorization servers that support it put it in the access token's audience.
49
+ */ export const getMCPResource = ({ config, url })=>getPluginConfig({
50
+ config
51
+ }).oauth?.resource ?? getMCPURL({
52
+ config,
53
+ url
54
+ });
55
+ const getMCPURL = ({ config, url })=>new URL(`${config.routes.api}/mcp`, config.serverURL || url).href;
56
+ const getMetadataResponse = async ({ req })=>{
57
+ const { config } = req.payload;
58
+ const pluginConfig = getPluginConfig({
59
+ config
60
+ });
61
+ if (!pluginConfig.oauth) {
62
+ return new Response(null, {
63
+ status: 404
64
+ });
65
+ }
66
+ const { authorizationServers, scopes } = pluginConfig.oauth;
67
+ return Response.json({
68
+ authorization_servers: typeof authorizationServers === 'function' ? await authorizationServers({
69
+ req
70
+ }) : authorizationServers,
71
+ bearer_methods_supported: [
72
+ 'header'
73
+ ],
74
+ resource: getMCPResource({
75
+ config,
76
+ url: req.url
77
+ }),
78
+ scopes_supported: scopes
79
+ }, // Public document, readable by browser-based MCP clients on any origin
80
+ {
81
+ headers: {
82
+ 'Access-Control-Allow-Origin': '*'
83
+ }
84
+ });
85
+ };
86
+
87
+ //# sourceMappingURL=oauth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/endpoint/oauth.ts"],"sourcesContent":["import type { OAuthProtectedResourceMetadata } from '@modelcontextprotocol/server'\nimport type { PayloadHandler, PayloadRequest, SanitizedConfig } from 'payload'\n\nimport {\n bearerAuthChallengeResponse,\n OAuthError,\n OAuthErrorCode,\n} from '@modelcontextprotocol/server'\nimport { createPayloadRequest, getPayload } from 'payload'\n\nimport { getPluginConfig } from '../utils/getPluginConfig.js'\n\n/**\n * Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.\n * The OAuth challenge links here, so MCP clients find the authorization server without setup.\n */\nexport const oauthProtectedResourceEndpoint: PayloadHandler = (req) => getMetadataResponse({ req })\n\n/**\n * Serves the same metadata for clients that ignore the challenge's link and only look at\n * `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at\n * `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:\n *\n * ```ts\n * import config from '@payload-config'\n * import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'\n *\n * export const GET = oauthProtectedResourceHandler(config)\n * ```\n */\nexport const oauthProtectedResourceHandler =\n (config: Promise<SanitizedConfig> | SanitizedConfig) =>\n async (request: Request): Promise<Response> =>\n getMetadataResponse({\n req: await createPayloadRequest({ payload: await getPayload({ config }), req: request }),\n })\n\n/**\n * Answers an unauthenticated MCP request with a challenge linking to the protected resource\n * metadata, which starts the client's OAuth flow.\n */\nexport const oauthChallenge = ({ req }: { req: PayloadRequest }): Response => {\n const response = bearerAuthChallengeResponse(\n new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')),\n {\n requiredScopes: getPluginConfig({ config: req.payload.config }).oauth?.scopes,\n resourceMetadataUrl: `${getMCPURL({ config: req.payload.config, url: req.url! })}/oauth-protected-resource`,\n },\n )\n\n // Lets browser-based MCP clients read the challenge, when Payload's `cors` setting allows them\n response.headers.set('Access-Control-Expose-Headers', 'WWW-Authenticate')\n\n return response\n}\n\n/**\n * The MCP endpoint's address, as advertised in the metadata's `resource`. Clients send it when\n * they sign in, and authorization servers that support it put it in the access token's audience.\n */\nexport const getMCPResource = ({ config, url }: { config: SanitizedConfig; url: string }): string =>\n getPluginConfig({ config }).oauth?.resource ?? getMCPURL({ config, url })\n\nconst getMCPURL = ({ config, url }: { config: SanitizedConfig; url: string }): string =>\n new URL(`${config.routes.api}/mcp`, config.serverURL || url).href\n\nconst getMetadataResponse = async ({ req }: { req: PayloadRequest }): Promise<Response> => {\n const { config } = req.payload\n const pluginConfig = getPluginConfig({ config })\n\n if (!pluginConfig.oauth) {\n return new Response(null, { status: 404 })\n }\n\n const { authorizationServers, scopes } = pluginConfig.oauth\n\n return Response.json(\n {\n authorization_servers:\n typeof authorizationServers === 'function'\n ? await authorizationServers({ req })\n : authorizationServers,\n bearer_methods_supported: ['header'],\n resource: getMCPResource({ config, url: req.url! }),\n scopes_supported: scopes,\n } satisfies OAuthProtectedResourceMetadata,\n // Public document, readable by browser-based MCP clients on any origin\n { headers: { 'Access-Control-Allow-Origin': '*' } },\n )\n}\n"],"names":["bearerAuthChallengeResponse","OAuthError","OAuthErrorCode","createPayloadRequest","getPayload","getPluginConfig","oauthProtectedResourceEndpoint","req","getMetadataResponse","oauthProtectedResourceHandler","config","request","payload","oauthChallenge","response","InvalidToken","t","requiredScopes","oauth","scopes","resourceMetadataUrl","getMCPURL","url","headers","set","getMCPResource","resource","URL","routes","api","serverURL","href","pluginConfig","Response","status","authorizationServers","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oB,SAAS,IAAIR,KAAKS,IAAI;AAEnE,MAAMvB,sBAAsB,OAAO,EAAED,GAAG,EAA2B;IACjE,MAAM,EAAEG,MAAM,EAAE,GAAGH,IAAIK,OAAO;IAC9B,MAAMoB,eAAe3B,gBAAgB;QAAEK;IAAO;IAE9C,IAAI,CAACsB,aAAad,KAAK,EAAE;QACvB,OAAO,IAAIe,SAAS,MAAM;YAAEC,QAAQ;QAAI;IAC1C;IAEA,MAAM,EAAEC,oBAAoB,EAAEhB,MAAM,EAAE,GAAGa,aAAad,KAAK;IAE3D,OAAOe,SAASG,IAAI,CAClB;QACEC,uBACE,OAAOF,yBAAyB,aAC5B,MAAMA,qBAAqB;YAAE5B;QAAI,KACjC4B;QACNG,0BAA0B;YAAC;SAAS;QACpCZ,UAAUD,eAAe;YAAEf;YAAQY,KAAKf,IAAIe,GAAG;QAAE;QACjDiB,kBAAkBpB;IACpB,GACA,uEAAuE;IACvE;QAAEI,SAAS;YAAE,+BAA+B;QAAI;IAAE;AAEtD"}
package/dist/index.d.ts CHANGED
@@ -7,8 +7,16 @@ declare module 'payload' {
7
7
  /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */
8
8
  '@payloadcms/plugin-mcp': MCPPluginConfig;
9
9
  }
10
+ interface RequestContext {
11
+ /** Set on MCP requests before they're authenticated. */
12
+ mcp?: {
13
+ /** The MCP endpoint's address, which OAuth access tokens for MCP are issued for. */
14
+ resource: string;
15
+ };
16
+ }
10
17
  }
11
18
  export type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig };
12
19
  export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js';
20
+ export { oauthProtectedResourceHandler } from './endpoint/oauth.js';
13
21
  export declare const mcpPlugin: (options: MCPPluginConfig) => import("payload").Plugin;
14
22
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAK1F,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAiB,iBAAiB;QAChC,GAAG,EAAE,IAAI,CAAA;KACV;IACD,UAAU,iBAAiB;QACzB,uFAAuF;QACvF,wBAAwB,EAAE,eAAe,CAAA;KAC1C;CACF;AAED,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,wBAAwB,EAAE,CAAA;AAExE,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAElG,eAAO,MAAM,SAAS,wDAiCpB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAM1F,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAiB,iBAAiB;QAChC,GAAG,EAAE,IAAI,CAAA;KACV;IACD,UAAU,iBAAiB;QACzB,uFAAuF;QACvF,wBAAwB,EAAE,eAAe,CAAA;KAC1C;IACD,UAAiB,cAAc;QAC7B,wDAAwD;QACxD,GAAG,CAAC,EAAE;YACJ,oFAAoF;YACpF,QAAQ,EAAE,MAAM,CAAA;SACjB,CAAA;KACF;CACF;AAED,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,wBAAwB,EAAE,CAAA;AAExE,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAClG,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAA;AAEnE,eAAO,MAAM,SAAS,wDAyCpB,CAAA"}
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { definePlugin } from 'payload';
2
2
  import { mcpEndpoint } from './endpoint/index.js';
3
+ import { oauthProtectedResourceEndpoint } from './endpoint/oauth.js';
3
4
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js';
4
5
  export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js';
6
+ export { oauthProtectedResourceHandler } from './endpoint/oauth.js';
5
7
  export const mcpPlugin = definePlugin({
6
8
  slug: '@payloadcms/plugin-mcp',
7
9
  order: 10,
@@ -23,8 +25,10 @@ export const mcpPlugin = definePlugin({
23
25
  ...config,
24
26
  endpoints: [
25
27
  ...config.endpoints ?? [],
26
- // Payload prefixes /api, so the full path is /api/mcp.
28
+ // Payload prefixes /api, so the full path is /api/mcp. getAuthorizedMCP authenticates the
29
+ // request with dev auto-login turned off, so Payload doesn't authenticate it first.
27
30
  {
31
+ disableAuth: true,
28
32
  handler: mcpEndpoint,
29
33
  method: 'post',
30
34
  path: '/mcp'
@@ -32,6 +36,7 @@ export const mcpPlugin = definePlugin({
32
36
  // Streamable HTTP's optional server=>client GET stream. We don't offer
33
37
  // one, so answer 405 per spec-— clients then skip it cleanly
34
38
  {
39
+ disableAuth: true,
35
40
  handler: ()=>new Response(null, {
36
41
  headers: {
37
42
  Allow: 'POST'
@@ -40,6 +45,12 @@ export const mcpPlugin = definePlugin({
40
45
  }),
41
46
  method: 'get',
42
47
  path: '/mcp'
48
+ },
49
+ {
50
+ disableAuth: true,
51
+ handler: oauthProtectedResourceEndpoint,
52
+ method: 'get',
53
+ path: '/mcp/oauth-protected-resource'
43
54
  }
44
55
  ]
45
56
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { definePlugin } from 'payload'\n\nimport type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js'\n\nimport { mcpEndpoint } from './endpoint/index.js'\nimport { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'\n\ndeclare module 'payload' {\n export interface PayloadRequestAPI {\n MCP: true\n }\n interface RegisteredPlugins {\n /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */\n '@payloadcms/plugin-mcp': MCPPluginConfig\n }\n}\n\nexport type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig }\n\nexport { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'\n\nexport const mcpPlugin = definePlugin<MCPPluginConfig>({\n slug: '@payloadcms/plugin-mcp',\n order: 10,\n plugin: ({ config, options, plugins }) => {\n const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: options })\n\n // Stash the sanitized config on plugin options so `getPluginConfig()` reads it.\n const registered = plugins['@payloadcms/plugin-mcp']\n if (registered) {\n // @ts-expect-error\n registered.sanitizedOptions = pluginConfig as unknown as typeof registered.options\n }\n\n if (pluginConfig.disabled) {\n return config\n }\n\n return {\n ...config,\n endpoints: [\n ...(config.endpoints ?? []),\n // Payload prefixes /api, so the full path is /api/mcp.\n { handler: mcpEndpoint, method: 'post', path: '/mcp' },\n // Streamable HTTP's optional server=>client GET stream. We don't offer\n // one, so answer 405 per spec-— clients then skip it cleanly\n {\n handler: () => new Response(null, { headers: { Allow: 'POST' }, status: 405 }),\n method: 'get',\n path: '/mcp',\n },\n ],\n }\n },\n})\n"],"names":["definePlugin","mcpEndpoint","sanitizeMCPConfig","defineCollectionTool","defineGlobalTool","definePrompt","defineTool","mcpPlugin","slug","order","plugin","config","options","plugins","pluginConfig","registered","sanitizedOptions","disabled","endpoints","handler","method","path","Response","headers","Allow","status"],"mappings":"AAAA,SAASA,YAAY,QAAQ,UAAS;AAItC,SAASC,WAAW,QAAQ,sBAAqB;AACjD,SAASC,iBAAiB,QAAQ,6BAA4B;AAc9D,SAASC,oBAAoB,EAAEC,gBAAgB,EAAEC,YAAY,EAAEC,UAAU,QAAQ,kBAAiB;AAElG,OAAO,MAAMC,YAAYP,aAA8B;IACrDQ,MAAM;IACNC,OAAO;IACPC,QAAQ,CAAC,EAAEC,MAAM,EAAEC,OAAO,EAAEC,OAAO,EAAE;QACnC,MAAMC,eAAeZ,kBAAkB;YAAES;YAAQG,cAAcF;QAAQ;QAEvE,gFAAgF;QAChF,MAAMG,aAAaF,OAAO,CAAC,yBAAyB;QACpD,IAAIE,YAAY;YACd,mBAAmB;YACnBA,WAAWC,gBAAgB,GAAGF;QAChC;QAEA,IAAIA,aAAaG,QAAQ,EAAE;YACzB,OAAON;QACT;QAEA,OAAO;YACL,GAAGA,MAAM;YACTO,WAAW;mBACLP,OAAOO,SAAS,IAAI,EAAE;gBAC1B,uDAAuD;gBACvD;oBAAEC,SAASlB;oBAAamB,QAAQ;oBAAQC,MAAM;gBAAO;gBACrD,uEAAuE;gBACvE,6DAA6D;gBAC7D;oBACEF,SAAS,IAAM,IAAIG,SAAS,MAAM;4BAAEC,SAAS;gCAAEC,OAAO;4BAAO;4BAAGC,QAAQ;wBAAI;oBAC5EL,QAAQ;oBACRC,MAAM;gBACR;aACD;QACH;IACF;AACF,GAAE"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { definePlugin } from 'payload'\n\nimport type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js'\n\nimport { mcpEndpoint } from './endpoint/index.js'\nimport { oauthProtectedResourceEndpoint } from './endpoint/oauth.js'\nimport { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'\n\ndeclare module 'payload' {\n export interface PayloadRequestAPI {\n MCP: true\n }\n interface RegisteredPlugins {\n /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */\n '@payloadcms/plugin-mcp': MCPPluginConfig\n }\n export interface RequestContext {\n /** Set on MCP requests before they're authenticated. */\n mcp?: {\n /** The MCP endpoint's address, which OAuth access tokens for MCP are issued for. */\n resource: string\n }\n }\n}\n\nexport type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig }\n\nexport { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'\nexport { oauthProtectedResourceHandler } from './endpoint/oauth.js'\n\nexport const mcpPlugin = definePlugin<MCPPluginConfig>({\n slug: '@payloadcms/plugin-mcp',\n order: 10,\n plugin: ({ config, options, plugins }) => {\n const pluginConfig = sanitizeMCPConfig({ config, pluginConfig: options })\n\n // Stash the sanitized config on plugin options so `getPluginConfig()` reads it.\n const registered = plugins['@payloadcms/plugin-mcp']\n if (registered) {\n // @ts-expect-error\n registered.sanitizedOptions = pluginConfig as unknown as typeof registered.options\n }\n\n if (pluginConfig.disabled) {\n return config\n }\n\n return {\n ...config,\n endpoints: [\n ...(config.endpoints ?? []),\n // Payload prefixes /api, so the full path is /api/mcp. getAuthorizedMCP authenticates the\n // request with dev auto-login turned off, so Payload doesn't authenticate it first.\n { disableAuth: true, handler: mcpEndpoint, method: 'post', path: '/mcp' },\n // Streamable HTTP's optional server=>client GET stream. We don't offer\n // one, so answer 405 per spec-— clients then skip it cleanly\n {\n disableAuth: true,\n handler: () => new Response(null, { headers: { Allow: 'POST' }, status: 405 }),\n method: 'get',\n path: '/mcp',\n },\n {\n disableAuth: true,\n handler: oauthProtectedResourceEndpoint,\n method: 'get',\n path: '/mcp/oauth-protected-resource',\n },\n ],\n }\n },\n})\n"],"names":["definePlugin","mcpEndpoint","oauthProtectedResourceEndpoint","sanitizeMCPConfig","defineCollectionTool","defineGlobalTool","definePrompt","defineTool","oauthProtectedResourceHandler","mcpPlugin","slug","order","plugin","config","options","plugins","pluginConfig","registered","sanitizedOptions","disabled","endpoints","disableAuth","handler","method","path","Response","headers","Allow","status"],"mappings":"AAAA,SAASA,YAAY,QAAQ,UAAS;AAItC,SAASC,WAAW,QAAQ,sBAAqB;AACjD,SAASC,8BAA8B,QAAQ,sBAAqB;AACpE,SAASC,iBAAiB,QAAQ,6BAA4B;AAqB9D,SAASC,oBAAoB,EAAEC,gBAAgB,EAAEC,YAAY,EAAEC,UAAU,QAAQ,kBAAiB;AAClG,SAASC,6BAA6B,QAAQ,sBAAqB;AAEnE,OAAO,MAAMC,YAAYT,aAA8B;IACrDU,MAAM;IACNC,OAAO;IACPC,QAAQ,CAAC,EAAEC,MAAM,EAAEC,OAAO,EAAEC,OAAO,EAAE;QACnC,MAAMC,eAAeb,kBAAkB;YAAEU;YAAQG,cAAcF;QAAQ;QAEvE,gFAAgF;QAChF,MAAMG,aAAaF,OAAO,CAAC,yBAAyB;QACpD,IAAIE,YAAY;YACd,mBAAmB;YACnBA,WAAWC,gBAAgB,GAAGF;QAChC;QAEA,IAAIA,aAAaG,QAAQ,EAAE;YACzB,OAAON;QACT;QAEA,OAAO;YACL,GAAGA,MAAM;YACTO,WAAW;mBACLP,OAAOO,SAAS,IAAI,EAAE;gBAC1B,0FAA0F;gBAC1F,oFAAoF;gBACpF;oBAAEC,aAAa;oBAAMC,SAASrB;oBAAasB,QAAQ;oBAAQC,MAAM;gBAAO;gBACxE,uEAAuE;gBACvE,6DAA6D;gBAC7D;oBACEH,aAAa;oBACbC,SAAS,IAAM,IAAIG,SAAS,MAAM;4BAAEC,SAAS;gCAAEC,OAAO;4BAAO;4BAAGC,QAAQ;wBAAI;oBAC5EL,QAAQ;oBACRC,MAAM;gBACR;gBACA;oBACEH,aAAa;oBACbC,SAASpB;oBACTqB,QAAQ;oBACRC,MAAM;gBACR;aACD;QACH;IACF;AACF,GAAE"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/uploadInstructionsTool.ts"],"sourcesContent":["import { strictObject, z } from 'payload'\nimport { getUploadInstructions as getPayloadUploadInstructions } from 'payload/internal'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\n\nexport const getUploadInstructionsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) &&\n Boolean(\n args.permissions?.collections?.[args.slug]?.create ||\n args.permissions?.collections?.[args.slug]?.update,\n ),\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n readOnlyHint: false,\n title: 'Get Upload Instructions',\n },\n description:\n 'Prepare uploads for createDocuments or updateDocument. This does not upload bytes; finish the returned action before use.',\n input: strictObject({\n docPrefix: z.optional(z.string()).check(z.describe('Document folder or prefix.')),\n filename: z.string().check(z.describe('The original file name.')),\n filesize: z.int().check(z.nonnegative(), z.describe('The file size in bytes.')),\n mimeType: z.string().check(z.describe('The file MIME type.')),\n }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n try {\n const instructions = await getPayloadUploadInstructions({\n ...input,\n collectionSlug: slug,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n })\n\n const nextStep =\n instructions.type === 'http'\n ? 'Upload bytes with instructions.request. After success, pass { source: \"uploadReference\", file: instructions.file }.'\n : `Call \"${instructions.name}\" with file and data. After success, pass { source: \"uploadReference\", file: instructions.file }.`\n\n return {\n content: [\n {\n type: 'text',\n text: `Upload instructions for collection \"${slug}\":\\n\\`\\`\\`json\\n${JSON.stringify(instructions)}\\n\\`\\`\\`\\n${nextStep}`,\n },\n ],\n structuredContent: { instructions },\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n return {\n content: [\n {\n type: 'text',\n text: `Error getting upload instructions for collection \"${slug}\": ${message}`,\n },\n ],\n isError: true,\n }\n }\n})\n"],"names":["strictObject","z","getUploadInstructions","getPayloadUploadInstructions","defaultAccess","defineCollectionTool","getUploadInstructionsTool","access","args","Boolean","permissions","collections","slug","create","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","docPrefix","optional","string","check","describe","filename","filesize","int","nonnegative","mimeType","handler","authorizedMCP","req","instructions","collectionSlug","overrideAccess","nextStep","type","name","content","text","JSON","stringify","structuredContent","error","message","Error","isError"],"mappings":"AAAA,SAASA,YAAY,EAAEC,CAAC,QAAQ,UAAS;AACzC,SAASC,yBAAyBC,4BAA4B,QAAQ,mBAAkB;AAExF,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAE7D,OAAO,MAAMC,4BAA4BD,qBAAqB;IAC5DE,QAAQ,CAACC,OACPJ,cAAcI,SACdC,QACED,KAAKE,WAAW,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AC,kDAAkD,EAAE/B,KAAK,GAAG,EAAEoC,SAAS;gBAChF;aACD;YACDE,SAAS;QACX;IACF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/uploadInstructionsTool.ts"],"sourcesContent":["import { strictObject, z } from 'payload'\nimport { getUploadInstructions as getPayloadUploadInstructions } from 'payload/internal'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\n\nexport const getUploadInstructionsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) &&\n Boolean(\n args.permissions?.collections?.[args.slug]?.create ||\n args.permissions?.collections?.[args.slug]?.update,\n ),\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n readOnlyHint: false,\n title: 'Get Upload Instructions',\n },\n description:\n 'Prepare uploads for createDocuments or updateDocument. This does not upload bytes; finish the returned action before use.',\n input: strictObject({\n docPrefix: z.optional(z.string()).check(z.describe('Document folder or prefix.')),\n filename: z.string().check(z.describe('The original file name.')),\n filesize: z.int().check(z.nonnegative(), z.describe('The file size in bytes.')),\n mimeType: z.string().check(z.describe('The file MIME type.')),\n }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n try {\n const instructions = await getPayloadUploadInstructions({\n ...input,\n collectionSlug: slug,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n })\n\n const nextStep =\n instructions.type === 'http'\n ? 'Upload bytes with instructions.request. After success, pass { source: \"uploadReference\", file: instructions.file }.'\n : `Call \"${instructions.name}\" with file and data. After success, pass { source: \"uploadReference\", file: instructions.file }.`\n\n return {\n content: [\n {\n type: 'text',\n text: `Upload instructions for collection \"${slug}\":\\n\\`\\`\\`json\\n${JSON.stringify(instructions)}\\n\\`\\`\\`\\n${nextStep}`,\n },\n ],\n structuredContent: { instructions },\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n return {\n content: [\n {\n type: 'text',\n text: `Error getting upload instructions for collection \"${slug}\": ${message}`,\n },\n ],\n isError: true,\n }\n }\n})\n"],"names":["strictObject","z","getUploadInstructions","getPayloadUploadInstructions","defaultAccess","defineCollectionTool","getUploadInstructionsTool","access","args","Boolean","permissions","collections","slug","create","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","docPrefix","optional","string","check","describe","filename","filesize","int","nonnegative","mimeType","handler","authorizedMCP","req","instructions","collectionSlug","overrideAccess","nextStep","type","name","content","text","JSON","stringify","structuredContent","error","message","Error","isError"],"mappings":"AAAA,SAASA,YAAY,EAAEC,CAAC,QAAQ,UAAS;AACzC,SAASC,yBAAyBC,4BAA4B,QAAQ,mBAAkB;AAExF,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAE7D,OAAO,MAAMC,4BAA4BD,qBAAqB;IAC5DE,QAAQ,CAACC,OACPJ,cAAcI,SACdC,QACED,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,IAAI,CAAC,EAAEC,UAC5CL,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,IAAI,CAAC,EAAEE;IAEhDC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aACE;IACFC,OAAOtB,aAAa;QAClBuB,WAAWtB,EAAEuB,QAAQ,CAACvB,EAAEwB,MAAM,IAAIC,KAAK,CAACzB,EAAE0B,QAAQ,CAAC;QACnDC,UAAU3B,EAAEwB,MAAM,GAAGC,KAAK,CAACzB,EAAE0B,QAAQ,CAAC;QACtCE,UAAU5B,EAAE6B,GAAG,GAAGJ,KAAK,CAACzB,EAAE8B,WAAW,IAAI9B,EAAE0B,QAAQ,CAAC;QACpDK,UAAU/B,EAAEwB,MAAM,GAAGC,KAAK,CAACzB,EAAE0B,QAAQ,CAAC;IACxC;AACF,GAAGM,OAAO,CAAC,OAAO,EAAErB,IAAI,EAAEsB,aAAa,EAAEZ,KAAK,EAAEa,GAAG,EAAE;IACnD,IAAI;QACF,MAAMC,eAAe,MAAMjC,6BAA6B;YACtD,GAAGmB,KAAK;YACRe,gBAAgBzB;YAChB0B,gBAAgBJ,cAAcI,cAAc;YAC5CH;QACF;QAEA,MAAMI,WACJH,aAAaI,IAAI,KAAK,SAClB,wHACA,CAAC,MAAM,EAAEJ,aAAaK,IAAI,CAAC,iGAAiG,CAAC;QAEnI,OAAO;YACLC,SAAS;gBACP;oBACEF,MAAM;oBACNG,MAAM,CAAC,oCAAoC,EAAE/B,KAAK,gBAAgB,EAAEgC,KAAKC,SAAS,CAACT,cAAc,UAAU,EAAEG,UAAU;gBACzH;aACD;YACDO,mBAAmB;gBAAEV;YAAa;QACpC;IACF,EAAE,OAAOW,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAG;QACzD,OAAO;YACLN,SAAS;gBACP;oBACEF,MAAM;oBACNG,MAAM,CAAC,kDAAkD,EAAE/B,KAAK,GAAG,EAAEoC,SAAS;gBAChF;aACD;YACDE,SAAS;QACX;IACF;AACF,GAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"sanitizeMCPConfig.d.ts","sourceRoot":"","sources":["../../src/mcp/sanitizeMCPConfig.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,MAAM,EAGN,eAAe,EAEhB,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,EAMV,eAAe,EACf,wBAAwB,EACzB,MAAM,aAAa,CAAA;AAcpB;;;;;;;;GAQG;AACH,eAAO,MAAM,iBAAiB,8BAG3B;IACD,MAAM,EAAE,MAAM,GAAG,eAAe,CAAA;IAChC,YAAY,EAAE,eAAe,CAAA;CAC9B,KAAG,wBA6DH,CAAA"}
1
+ {"version":3,"file":"sanitizeMCPConfig.d.ts","sourceRoot":"","sources":["../../src/mcp/sanitizeMCPConfig.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,MAAM,EAGN,eAAe,EAEhB,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,EAMV,eAAe,EACf,wBAAwB,EACzB,MAAM,aAAa,CAAA;AAcpB;;;;;;;;GAQG;AACH,eAAO,MAAM,iBAAiB,8BAG3B;IACD,MAAM,EAAE,MAAM,GAAG,eAAe,CAAA;IAChC,YAAY,EAAE,eAAe,CAAA;CAC9B,KAAG,wBA8DH,CAAA"}
@@ -78,6 +78,7 @@ import { COLLECTION_AUTH_BUILTIN_ENTRIES, COLLECTION_AUTH_BUILTINS, COLLECTION_B
78
78
  hooks: pluginConfig.hooks,
79
79
  items,
80
80
  mcp: pluginConfig.mcp,
81
+ oauth: pluginConfig.oauth,
81
82
  overrideGetAuthorizedMCP: pluginConfig.overrideGetAuthorizedMCP
82
83
  };
83
84
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/sanitizeMCPConfig.ts"],"sourcesContent":["import type {\n CollectionConfig,\n Config,\n GlobalConfig,\n SanitizedCollectionConfig,\n SanitizedConfig,\n SanitizedGlobalConfig,\n} from 'payload'\n\nimport type {\n CollectionMCPItem,\n CollectionTool,\n GlobalMCPItem,\n GlobalTool,\n MCPItem,\n MCPPluginConfig,\n SanitizedMCPPluginConfig,\n} from '../types.js'\n\nimport { defaultAccess } from '../defaultAccess.js'\nimport {\n COLLECTION_AUTH_BUILTIN_ENTRIES,\n COLLECTION_AUTH_BUILTINS,\n COLLECTION_BUILTIN_ENTRIES,\n COLLECTION_BUILTINS,\n GLOBAL_BUILTIN_ENTRIES,\n GLOBAL_BUILTINS,\n TOOL_BUILTIN_ENTRIES,\n TOOL_BUILTINS,\n} from './builtinTools.js'\n\n/**\n * Converts the user-configured `MCPPluginConfig` into a `SanitizedMCPPluginConfig`:\n * - Flattens `tools` / `prompts` / `resources` / per-collection / per-global\n * tool maps into a single `items` array.\n * - Applies built-in tools for collections and globals, respecting opt-out user overrides.\n *\n * Called once during plugin init. After that, `plugins['@payloadcms/plugin-mcp']\n * ?.options` holds the sanitized result\n */\nexport const sanitizeMCPConfig = ({\n config,\n pluginConfig,\n}: {\n config: Config | SanitizedConfig\n pluginConfig: MCPPluginConfig\n}): SanitizedMCPPluginConfig => {\n const items: MCPItem[] = []\n\n for (const collection of config.collections ?? []) {\n items.push(...sanitizeCollectionConfig({ collection, pluginConfig }))\n }\n\n for (const global of config.globals ?? []) {\n items.push(...sanitizeGlobalConfig({ global, pluginConfig }))\n }\n\n for (const [configKey, { mcpName, tool }] of TOOL_BUILTIN_ENTRIES) {\n items.push({\n type: 'tool',\n configKey,\n label: tool.annotations?.title ?? configKey,\n mcpName,\n tool: { ...tool, access: tool.access ?? defaultAccess },\n })\n }\n\n for (const [configKey, tool] of Object.entries(pluginConfig.tools ?? {})) {\n if (configKey in TOOL_BUILTINS) {\n continue\n }\n items.push({\n type: 'tool',\n configKey,\n label: tool.annotations?.title ?? configKey,\n mcpName: configKey,\n tool: { ...tool, access: tool.access ?? defaultAccess },\n })\n }\n\n for (const [configKey, prompt] of Object.entries(pluginConfig.prompts ?? {})) {\n items.push({\n type: 'prompt',\n configKey,\n label: prompt.title ?? configKey,\n mcpName: configKey,\n prompt: { ...prompt, access: prompt.access ?? defaultAccess },\n })\n }\n\n for (const [configKey, resource] of Object.entries(pluginConfig.resources ?? {})) {\n items.push({\n type: 'resource',\n configKey,\n label: resource.title ?? configKey,\n mcpName: configKey,\n resource: { ...resource, access: resource.access ?? defaultAccess },\n })\n }\n\n return {\n disabled: pluginConfig.disabled,\n hooks: pluginConfig.hooks,\n items,\n mcp: pluginConfig.mcp,\n overrideGetAuthorizedMCP: pluginConfig.overrideGetAuthorizedMCP,\n }\n}\n\nconst sanitizeCollectionConfig = ({\n collection,\n pluginConfig,\n}: {\n collection: CollectionConfig | SanitizedCollectionConfig\n pluginConfig: MCPPluginConfig\n}): CollectionMCPItem[] => {\n const slug = collection.slug\n const collectionPluginConfig = pluginConfig.collections?.[slug]\n const items: CollectionMCPItem[] = []\n /**\n * Payload disables duplicate for auth collections by default unless the\n * collection explicitly opts back in with `disableDuplicate: false`.\n */\n const isDuplicateDisabled =\n collection.disableDuplicate === true ||\n (Boolean(collection.auth) && collection.disableDuplicate !== false)\n\n for (const [\n toolKey,\n { mcpName, requiresDuplicateEnabled, requiresUpload, requiresVersions, tool },\n ] of COLLECTION_BUILTIN_ENTRIES) {\n if (requiresVersions && !collection.versions) {\n continue\n }\n if (requiresDuplicateEnabled && isDuplicateDisabled) {\n continue\n }\n if (requiresUpload && !collection.upload) {\n continue\n }\n const matchedConfigEntry = collectionPluginConfig?.tools?.[toolKey]\n if (matchedConfigEntry === false) {\n continue\n }\n const override = typeof matchedConfigEntry === 'object' ? matchedConfigEntry : undefined\n const annotations = { ...tool.annotations, ...override?.annotations }\n items.push({\n type: 'collectionTool',\n collectionSlug: slug,\n configKey: toolKey,\n label: annotations.title ?? toolKey,\n mcpName,\n tool: {\n ...tool,\n access: override?.access ?? tool.access ?? defaultAccess,\n annotations,\n description: override?.description ?? tool.description,\n overrideResponse:\n override?.overrideResponse ??\n collectionPluginConfig?.overrideResponse ??\n tool.overrideResponse,\n },\n })\n }\n\n if (collection.auth) {\n for (const [authToolKey, { mcpName, tool }] of COLLECTION_AUTH_BUILTIN_ENTRIES) {\n const matchedConfigEntry = collectionPluginConfig?.tools?.[authToolKey]\n if (!matchedConfigEntry) {\n continue\n }\n // `true` means \"enable, no override\"; only the object form carries fields.\n const override = typeof matchedConfigEntry === 'object' ? matchedConfigEntry : undefined\n const annotations = { ...tool.annotations, ...override?.annotations }\n items.push({\n type: 'collectionTool',\n collectionSlug: slug,\n configKey: authToolKey,\n label: annotations.title ?? authToolKey,\n mcpName,\n tool: {\n ...tool,\n access: override?.access ?? tool.access ?? defaultAccess,\n annotations,\n description: override?.description ?? tool.description,\n overrideResponse:\n override?.overrideResponse ??\n collectionPluginConfig?.overrideResponse ??\n tool.overrideResponse,\n },\n })\n }\n }\n\n // Cast: builtin keys are filtered out below, so the remaining values are\n // always custom tools (`CollectionTool`) or undefined\n const customEntries = Object.entries(collectionPluginConfig?.tools ?? {}) as Array<\n [string, CollectionTool | undefined]\n >\n for (const [configKey, customTool] of customEntries) {\n if (configKey in COLLECTION_BUILTINS || configKey in COLLECTION_AUTH_BUILTINS) {\n continue\n }\n if (!customTool) {\n continue\n }\n items.push({\n type: 'collectionTool',\n collectionSlug: slug,\n configKey,\n label: customTool.annotations?.title ?? configKey,\n mcpName: configKey,\n tool: { ...customTool, access: customTool.access ?? defaultAccess },\n })\n }\n\n return items\n}\n\nconst sanitizeGlobalConfig = ({\n global,\n pluginConfig,\n}: {\n global: GlobalConfig | SanitizedGlobalConfig\n pluginConfig: MCPPluginConfig\n}): GlobalMCPItem[] => {\n const slug = global.slug\n const globalPluginConfig = pluginConfig.globals?.[slug]\n const items: GlobalMCPItem[] = []\n\n for (const [toolKey, { mcpName, requiresVersions, tool }] of GLOBAL_BUILTIN_ENTRIES) {\n if (requiresVersions && !global.versions) {\n continue\n }\n const matchedConfigEntry = globalPluginConfig?.tools?.[toolKey]\n if (matchedConfigEntry === false) {\n continue\n }\n const override = typeof matchedConfigEntry === 'object' ? matchedConfigEntry : undefined\n const annotations = { ...tool.annotations, ...override?.annotations }\n items.push({\n type: 'globalTool',\n configKey: toolKey,\n globalSlug: slug,\n label: annotations.title ?? toolKey,\n mcpName,\n tool: {\n ...tool,\n access: override?.access ?? tool.access ?? defaultAccess,\n annotations,\n description: override?.description ?? tool.description,\n overrideResponse:\n override?.overrideResponse ??\n globalPluginConfig?.overrideResponse ??\n tool.overrideResponse,\n },\n })\n }\n\n const customEntries = Object.entries(globalPluginConfig?.tools ?? {}) as Array<\n [string, GlobalTool | undefined]\n >\n for (const [configKey, customTool] of customEntries) {\n if (configKey in GLOBAL_BUILTINS) {\n continue\n }\n if (!customTool) {\n continue\n }\n items.push({\n type: 'globalTool',\n configKey,\n globalSlug: slug,\n label: customTool.annotations?.title ?? configKey,\n mcpName: configKey,\n tool: { ...customTool, access: customTool.access ?? defaultAccess },\n })\n }\n\n return items\n}\n"],"names":["defaultAccess","COLLECTION_AUTH_BUILTIN_ENTRIES","COLLECTION_AUTH_BUILTINS","COLLECTION_BUILTIN_ENTRIES","COLLECTION_BUILTINS","GLOBAL_BUILTIN_ENTRIES","GLOBAL_BUILTINS","TOOL_BUILTIN_ENTRIES","TOOL_BUILTINS","sanitizeMCPConfig","config","pluginConfig","items","collection","collections","push","sanitizeCollectionConfig","global","globals","sanitizeGlobalConfig","configKey","mcpName","tool","type","label","annotations","title","access","Object","entries","tools","prompt","prompts","resource","resources","disabled","hooks","mcp","overrideGetAuthorizedMCP","slug","collectionPluginConfig","isDuplicateDisabled","disableDuplicate","Boolean","auth","toolKey","requiresDuplicateEnabled","requiresUpload","requiresVersions","versions","upload","matchedConfigEntry","override","undefined","collectionSlug","description","overrideResponse","authToolKey","customEntries","customTool","globalPluginConfig","globalSlug"],"mappings":"AAmBA,SAASA,aAAa,QAAQ,sBAAqB;AACnD,SACEC,+BAA+B,EAC/BC,wBAAwB,EACxBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,sBAAsB,EACtBC,eAAe,EACfC,oBAAoB,EACpBC,aAAa,QACR,oBAAmB;AAE1B;;;;;;;;CAQC,GACD,OAAO,MAAMC,oBAAoB,CAAC,EAChCC,MAAM,EACNC,YAAY,EAIb;IACC,MAAMC,QAAmB,EAAE;IAE3B,KAAK,MAAMC,cAAcH,OAAOI,WAAW,IAAI,EAAE,CAAE;QACjDF,MAAMG,IAAI,IAAIC,yBAAyB;YAAEH;YAAYF;QAAa;IACpE;IAEA,KAAK,MAAMM,UAAUP,OAAOQ,OAAO,IAAI,EAAE,CAAE;QACzCN,MAAMG,IAAI,IAAII,qBAAqB;YAAEF;YAAQN;QAAa;IAC5D;IAEA,KAAK,MAAM,CAACS,WAAW,EAAEC,OAAO,EAAEC,IAAI,EAAE,CAAC,IAAIf,qBAAsB;QACjEK,MAAMG,IAAI,CAAC;YACTQ,MAAM;YACNH;YACAI,OAAOF,KAAKG,WAAW,EAAEC,SAASN;YAClCC;YACAC,MAAM;gB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AExB,OAAO,EAAE2B,gBAAgB,EAAE1B,IAAI,EAAE,CAAC,IAAIjB,uBAAwB;QACnF,IAAI2C,oBAAoB,CAAC/B,OAAOgC,QAAQ,EAAE;YACxC;QACF;QACA,MAAME,qBAAqBS,oBAAoB9B,OAAO,CAACe,QAAQ;QAC/D,IAAIM,uBAAuB,OAAO;YAChC;QACF;QACA,MAAMC,WAAW,OAAOD,uBAAuB,WAAWA,qBAAqBE;QAC/E,MAAM5B,cAAc;YAAE,GAAGH,KAAKG,WAAW;YAAE,GAAG2B,UAAU3B,WAAW;QAAC;QACpEb,MAAMG,IAAI,CAAC;YACTQ,MAAM;YACNH,WAAWyB;YACXgB,YAAYtB;YACZf,OAAOC,YAAYC,KAAK,IAAImB;YAC5BxB;YACAC,MAAM;gBACJ,GAAGA,IAAI;gBACPK,QAAQyB,UAAUzB,UAAUL,KAAKK,MAAM,IAAI3B;gBAC3CyB;gBACA8B,aAAaH,UAAUG,eAAejC,KAAKiC,WAAW;gBACtDC,kBACEJ,UAAUI,oBACVI,oBAAoBJ,oBACpBlC,KAAKkC,gBAAgB;YACzB;QACF;IACF;IAEA,MAAME,gBAAgB9B,OAAOC,OAAO,CAAC+B,oBAAoB9B,SAAS,CAAC;IAGnE,KAAK,MAAM,CAACV,WAAWuC,WAAW,IAAID,cAAe;QACnD,IAAItC,aAAad,iBAAiB;YAChC;QACF;QACA,IAAI,CAACqD,YAAY;YACf;QACF;QACA/C,MAAMG,IAAI,CAAC;YACTQ,MAAM;YACNH;YACAyC,YAAYtB;YACZf,OAAOmC,WAAWlC,WAAW,EAAEC,SAASN;YACxCC,SAASD;YACTE,MAAM;gBAAE,GAAGqC,UAAU;gBAAEhC,QAAQgC,WAAWhC,MAAM,IAAI3B;YAAc;QACpE;IACF;IAEA,OAAOY;AACT"}
1
+ {"version":3,"sources":["../../src/mcp/sanitizeMCPConfig.ts"],"sourcesContent":["import type {\n CollectionConfig,\n Config,\n GlobalConfig,\n SanitizedCollectionConfig,\n SanitizedConfig,\n SanitizedGlobalConfig,\n} from 'payload'\n\nimport type {\n CollectionMCPItem,\n CollectionTool,\n GlobalMCPItem,\n GlobalTool,\n MCPItem,\n MCPPluginConfig,\n SanitizedMCPPluginConfig,\n} from '../types.js'\n\nimport { defaultAccess } from '../defaultAccess.js'\nimport {\n COLLECTION_AUTH_BUILTIN_ENTRIES,\n COLLECTION_AUTH_BUILTINS,\n COLLECTION_BUILTIN_ENTRIES,\n COLLECTION_BUILTINS,\n GLOBAL_BUILTIN_ENTRIES,\n GLOBAL_BUILTINS,\n TOOL_BUILTIN_ENTRIES,\n TOOL_BUILTINS,\n} from './builtinTools.js'\n\n/**\n * Converts the user-configured `MCPPluginConfig` into a `SanitizedMCPPluginConfig`:\n * - Flattens `tools` / `prompts` / `resources` / per-collection / per-global\n * tool maps into a single `items` array.\n * - Applies built-in tools for collections and globals, respecting opt-out user overrides.\n *\n * Called once during plugin init. After that, `plugins['@payloadcms/plugin-mcp']\n * ?.options` holds the sanitized result\n */\nexport const sanitizeMCPConfig = ({\n config,\n pluginConfig,\n}: {\n config: Config | SanitizedConfig\n pluginConfig: MCPPluginConfig\n}): SanitizedMCPPluginConfig => {\n const items: MCPItem[] = []\n\n for (const collection of config.collections ?? []) {\n items.push(...sanitizeCollectionConfig({ collection, pluginConfig }))\n }\n\n for (const global of config.globals ?? []) {\n items.push(...sanitizeGlobalConfig({ global, pluginConfig }))\n }\n\n for (const [configKey, { mcpName, tool }] of TOOL_BUILTIN_ENTRIES) {\n items.push({\n type: 'tool',\n configKey,\n label: tool.annotations?.title ?? configKey,\n mcpName,\n tool: { ...tool, access: tool.access ?? defaultAccess },\n })\n }\n\n for (const [configKey, tool] of Object.entries(pluginConfig.tools ?? {})) {\n if (configKey in TOOL_BUILTINS) {\n continue\n }\n items.push({\n type: 'tool',\n configKey,\n label: tool.annotations?.title ?? configKey,\n mcpName: configKey,\n tool: { ...tool, access: tool.access ?? defaultAccess },\n })\n }\n\n for (const [configKey, prompt] of Object.entries(pluginConfig.prompts ?? {})) {\n items.push({\n type: 'prompt',\n configKey,\n label: prompt.title ?? configKey,\n mcpName: configKey,\n prompt: { ...prompt, access: prompt.access ?? defaultAccess },\n })\n }\n\n for (const [configKey, resource] of Object.entries(pluginConfig.resources ?? {})) {\n items.push({\n type: 'resource',\n configKey,\n label: resource.title ?? configKey,\n mcpName: configKey,\n resource: { ...resource, access: resource.access ?? defaultAccess },\n })\n }\n\n return {\n disabled: pluginConfig.disabled,\n hooks: pluginConfig.hooks,\n items,\n mcp: pluginConfig.mcp,\n oauth: pluginConfig.oauth,\n overrideGetAuthorizedMCP: pluginConfig.overrideGetAuthorizedMCP,\n }\n}\n\nconst sanitizeCollectionConfig = ({\n collection,\n pluginConfig,\n}: {\n collection: CollectionConfig | SanitizedCollectionConfig\n pluginConfig: MCPPluginConfig\n}): CollectionMCPItem[] => {\n const slug = collection.slug\n const collectionPluginConfig = pluginConfig.collections?.[slug]\n const items: CollectionMCPItem[] = []\n /**\n * Payload disables duplicate for auth collections by default unless the\n * collection explicitly opts back in with `disableDuplicate: false`.\n */\n const isDuplicateDisabled =\n collection.disableDuplicate === true ||\n (Boolean(collection.auth) && collection.disableDuplicate !== false)\n\n for (const [\n toolKey,\n { mcpName, requiresDuplicateEnabled, requiresUpload, requiresVersions, tool },\n ] of COLLECTION_BUILTIN_ENTRIES) {\n if (requiresVersions && !collection.versions) {\n continue\n }\n if (requiresDuplicateEnabled && isDuplicateDisabled) {\n continue\n }\n if (requiresUpload && !collection.upload) {\n continue\n }\n const matchedConfigEntry = collectionPluginConfig?.tools?.[toolKey]\n if (matchedConfigEntry === false) {\n continue\n }\n const override = typeof matchedConfigEntry === 'object' ? matchedConfigEntry : undefined\n const annotations = { ...tool.annotations, ...override?.annotations }\n items.push({\n type: 'collectionTool',\n collectionSlug: slug,\n configKey: toolKey,\n label: annotations.title ?? toolKey,\n mcpName,\n tool: {\n ...tool,\n access: override?.access ?? tool.access ?? defaultAccess,\n annotations,\n description: override?.description ?? tool.description,\n overrideResponse:\n override?.overrideResponse ??\n collectionPluginConfig?.overrideResponse ??\n tool.overrideResponse,\n },\n })\n }\n\n if (collection.auth) {\n for (const [authToolKey, { mcpName, tool }] of COLLECTION_AUTH_BUILTIN_ENTRIES) {\n const matchedConfigEntry = collectionPluginConfig?.tools?.[authToolKey]\n if (!matchedConfigEntry) {\n continue\n }\n // `true` means \"enable, no override\"; only the object form carries fields.\n const override = typeof matchedConfigEntry === 'object' ? matchedConfigEntry : undefined\n const annotations = { ...tool.annotations, ...override?.annotations }\n items.push({\n type: 'collectionTool',\n collectionSlug: slug,\n configKey: authToolKey,\n label: annotations.title ?? authToolKey,\n mcpName,\n tool: {\n ...tool,\n access: override?.access ?? tool.access ?? defaultAccess,\n annotations,\n description: override?.description ?? tool.description,\n overrideResponse:\n override?.overrideResponse ??\n collectionPluginConfig?.overrideResponse ??\n tool.overrideResponse,\n },\n })\n }\n }\n\n // Cast: builtin keys are filtered out below, so the remaining values are\n // always custom tools (`CollectionTool`) or undefined\n const customEntries = Object.entries(collectionPluginConfig?.tools ?? {}) as Array<\n [string, CollectionTool | undefined]\n >\n for (const [configKey, customTool] of customEntries) {\n if (configKey in COLLECTION_BUILTINS || configKey in COLLECTION_AUTH_BUILTINS) {\n continue\n }\n if (!customTool) {\n continue\n }\n items.push({\n type: 'collectionTool',\n collectionSlug: slug,\n configKey,\n label: customTool.annotations?.title ?? configKey,\n mcpName: configKey,\n tool: { ...customTool, access: customTool.access ?? defaultAccess },\n })\n }\n\n return items\n}\n\nconst sanitizeGlobalConfig = ({\n global,\n pluginConfig,\n}: {\n global: GlobalConfig | SanitizedGlobalConfig\n pluginConfig: MCPPluginConfig\n}): GlobalMCPItem[] => {\n const slug = global.slug\n const globalPluginConfig = pluginConfig.globals?.[slug]\n const items: GlobalMCPItem[] = []\n\n for (const [toolKey, { mcpName, requiresVersions, tool }] of GLOBAL_BUILTIN_ENTRIES) {\n if (requiresVersions && !global.versions) {\n continue\n }\n const matchedConfigEntry = globalPluginConfig?.tools?.[toolKey]\n if (matchedConfigEntry === false) {\n continue\n }\n const override = typeof matchedConfigEntry === 'object' ? matchedConfigEntry : undefined\n const annotations = { ...tool.annotations, ...override?.annotations }\n items.push({\n type: 'globalTool',\n configKey: toolKey,\n globalSlug: slug,\n label: annotations.title ?? toolKey,\n mcpName,\n tool: {\n ...tool,\n access: override?.access ?? tool.access ?? defaultAccess,\n annotations,\n description: override?.description ?? tool.description,\n overrideResponse:\n override?.overrideResponse ??\n globalPluginConfig?.overrideResponse ??\n tool.overrideResponse,\n },\n })\n }\n\n const customEntries = Object.entries(globalPluginConfig?.tools ?? {}) as Array<\n [string, GlobalTool | undefined]\n >\n for (const [configKey, customTool] of customEntries) {\n if (configKey in GLOBAL_BUILTINS) {\n continue\n }\n if (!customTool) {\n continue\n }\n items.push({\n type: 'globalTool',\n configKey,\n globalSlug: slug,\n label: customTool.annotations?.title ?? configKey,\n mcpName: configKey,\n tool: { ...customTool, access: customTool.access ?? defaultAccess },\n })\n }\n\n return items\n}\n"],"names":["defaultAccess","COLLECTION_AUTH_BUILTIN_ENTRIES","COLLECTION_AUTH_BUILTINS","COLLECTION_BUILTIN_ENTRIES","COLLECTION_BUILTINS","GLOBAL_BUILTIN_ENTRIES","GLOBAL_BUILTINS","TOOL_BUILTIN_ENTRIES","TOOL_BUILTINS","sanitizeMCPConfig","config","pluginConfig","items","collection","collections","push","sanitizeCollectionConfig","global","globals","sanitizeGlobalConfig","configKey","mcpName","tool","type","label","annotations","title","access","Object","entries","tools","prompt","prompts","resource","resources","disabled","hooks","mcp","oauth","overrideGetAuthorizedMCP","slug","collectionPluginConfig","isDuplicateDisabled","disableDuplicate","Boolean","auth","toolKey","requiresDuplicateEnabled","requiresUpload","requiresVersions","versions","upload","matchedConfigEntry","override","undefined","collectionSlug","description","overrideResponse","authToolKey","customEntries","customTool","globalPluginConfig","globalSlug"],"mappings":"AAmBA,SAASA,aAAa,QAAQ,sBAAqB;AACnD,SACEC,+BAA+B,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1B,UAAUL,KAAKK,MAAM,IAAI3B;gBAC3CyB;gBACA+B,aAAaH,UAAUG,eAAelC,KAAKkC,WAAW;gBACtDC,kBACEJ,UAAUI,oBACVI,oBAAoBJ,oBACpBnC,KAAKmC,gBAAgB;YACzB;QACF;IACF;IAEA,MAAME,gBAAgB/B,OAAOC,OAAO,CAACgC,oBAAoB/B,SAAS,CAAC;IAGnE,KAAK,MAAM,CAACV,WAAWwC,WAAW,IAAID,cAAe;QACnD,IAAIvC,aAAad,iBAAiB;YAChC;QACF;QACA,IAAI,CAACsD,YAAY;YACf;QACF;QACAhD,MAAMG,IAAI,CAAC;YACTQ,MAAM;YACNH;YACA0C,YAAYtB;YACZhB,OAAOoC,WAAWnC,WAAW,EAAEC,SAASN;YACxCC,SAASD;YACTE,MAAM;gBAAE,GAAGsC,UAAU;gBAAEjC,QAAQiC,WAAWjC,MAAM,IAAI3B;YAAc;QACpE;IACF;IAEA,OAAOY;AACT"}
package/dist/types.d.ts CHANGED
@@ -233,6 +233,42 @@ export type MCPPluginConfig = {
233
233
  serverOptions?: MCPServerOptions;
234
234
  verboseLogs?: boolean;
235
235
  };
236
+ /**
237
+ * Lets MCP clients sign in through an OAuth authorization server. MCP requests without an
238
+ * authenticated user get a `401` that points to the protected resource metadata (RFC 9728),
239
+ * served by `oauthProtectedResourceHandler`. Payload's auth strategies must accept the
240
+ * issued access tokens.
241
+ */
242
+ oauth?: {
243
+ /**
244
+ * Called on MCP requests with a bearer token that Payload's auth strategies didn't accept.
245
+ * Return the Payload user, including its `collection`, or `null` to answer with the OAuth challenge.
246
+ */
247
+ authenticate?: (args: {
248
+ req: PayloadRequest;
249
+ token: string;
250
+ }) => MaybePromise<PayloadRequest['user']>;
251
+ /**
252
+ * The authorization servers that issue access tokens for MCP clients. Clients require each one
253
+ * to exactly match the `issuer` in that server's metadata, so pass a function when the exact
254
+ * value is only known at runtime, e.g. from the server's OpenID configuration or per host.
255
+ */
256
+ authorizationServers: ((args: {
257
+ req: PayloadRequest;
258
+ }) => MaybePromise<string[]>) | string[];
259
+ /**
260
+ * The URL clients call to reach the MCP endpoint.
261
+ *
262
+ * @default the absolute URL of `/api/mcp`, based on `serverURL` or the request URL
263
+ */
264
+ resource?: string;
265
+ /**
266
+ * Scopes MCP clients should request, e.g. `['openid', 'email', 'profile']`. Without them,
267
+ * clients request none, which some authorization servers reject or answer with a token that
268
+ * doesn't identify the user.
269
+ */
270
+ scopes?: string[];
271
+ };
236
272
  /**
237
273
  * Replace the default MCP authorization resolver.
238
274
  *
@@ -249,7 +285,7 @@ export type MCPPluginConfig = {
249
285
  };
250
286
  export type SanitizedMCPPluginConfig = {
251
287
  items: MCPItem[];
252
- } & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'overrideGetAuthorizedMCP'>;
288
+ } & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'oauth' | 'overrideGetAuthorizedMCP'>;
253
289
  export type MCPServerOptions = {
254
290
  options?: McpServerOptions;
255
291
  serverInfo?: Partial<Implementation>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,YAAY,EACZ,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,aAAa,EACb,sBAAsB,EACtB,eAAe,EAChB,MAAM,8BAA8B,CAAA;AACrC,OAAO,KAAK,EACV,kBAAkB,EAClB,cAAc,EACd,UAAU,EACV,YAAY,EACZ,cAAc,EACd,oBAAoB,EACrB,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAA;AAChE,OAAO,KAAK,EACV,yBAAyB,EACzB,wBAAwB,EACxB,oBAAoB,EACrB,MAAM,uBAAuB,CAAA;AAE9B,YAAY,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,CAAA;AAEzF,gGAAgG;AAChG,YAAY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IACd,IAAI,EAAE,QAAQ,CAAA;CACf,GAAG,WAAW,CAAC,GAChB,CAAC;IACC,QAAQ,EAAE,QAAQ,CAAA;IAClB,IAAI,EAAE,UAAU,CAAA;CACjB,GAAG,WAAW,CAAC,GAChB,CAAC;IACC,IAAI,EAAE,IAAI,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;CACb,GAAG,WAAW,CAAC,GAChB,iBAAiB,GACjB,aAAa,CAAA;AAEjB;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,EAAE,OAAO,EAAE,CAAA;IAChB,cAAc,EAAE,OAAO,CAAA;CACxB,CAAA"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n CallToolResult,\n ContentBlock,\n Implementation,\n JsonSchemaType,\n McpServerOptions,\n ResourceTemplate,\n ServerContext,\n StandardSchemaWithJSON,\n ToolAnnotations,\n} from '@modelcontextprotocol/server'\nimport type {\n AuthCollectionSlug,\n CollectionSlug,\n GlobalSlug,\n MaybePromise,\n PayloadRequest,\n SanitizedPermissions,\n} from 'payload'\n\nimport type { GetAuthorizedMCPArgs } from './endpoint/access.js'\nimport type {\n MCPCollectionAuthToolName,\n MCPCollectionBuiltinName,\n MCPGlobalBuiltinName,\n} from './mcp/builtinTools.js'\n\nexport type { MCPCollectionAuthToolName, MCPCollectionBuiltinName, MCPGlobalBuiltinName }\n\n/** Re-exported from `@modelcontextprotocol/server` — common MCP types used in plugin config. */\nexport type { JsonSchemaType, StandardSchemaWithJSON, ToolAnnotations }\n\n/**\n * What a tool's `input` (or a prompt's `argsSchema`) can be — either a raw\n * JSON Schema 2020-12 literal, or a Standard Schema instance (Zod, Valibot, …).\n * Raw schemas may omit `$schema`; when present it must declare the 2020-12 dialect.\n */\nexport type ToolInputSchema = JsonSchemaType | StandardSchemaWithJSON\n\nexport type MCPToolResponse = {\n content: ContentBlock[]\n /**\n * If available, return the document fetched within the\n * mcp tool. This is threaded as an additional argument to\n * overrideResponse functions and stripped before going on the wire.\n */\n doc?: Record<string, unknown>\n} & Pick<CallToolResult, '_meta' | 'isError' | 'structuredContent'>\n\nexport type MCPResponseOverride = (\n response: MCPToolResponse,\n doc: Record<string, unknown>,\n req: PayloadRequest,\n) => MCPToolResponse\n\nexport type MCPAfterToolCallHook = (args: {\n input: unknown\n req: PayloadRequest\n response: MCPToolResponse\n toolName: string\n}) => MaybePromise<MCPToolResponse>\n\n/**\n * The handler's `input` type. A specific Standard Schema (Zod, Valibot, …) gets\n * its inferred output; anything else falls back to `Record<string, unknown>`.\n */\nexport type TypedInput<TSchema> = TSchema extends StandardSchemaWithJSON\n ? StandardSchemaWithJSON extends TSchema\n ? Record<string, unknown>\n : StandardSchemaWithJSON.InferOutput<TSchema>\n : Record<string, unknown>\n\nexport type MCPAccessArgs = {\n permissions?: SanitizedPermissions\n req: PayloadRequest\n}\n\nexport type CollectionMCPAccessArgs = {\n slug: CollectionSlug\n} & MCPAccessArgs\n\nexport type GlobalMCPAccessArgs = {\n slug: GlobalSlug\n} & MCPAccessArgs\n\nexport type ToolHandlerArgs<TSchema = undefined> = {\n authorizedMCP: AuthorizedMCP\n input: TypedInput<TSchema>\n req: PayloadRequest\n serverContext: ServerContext\n}\n\nexport type CollectionToolHandlerArgs<TSchema = undefined> = {\n slug: CollectionSlug\n} & ToolHandlerArgs<TSchema>\n\nexport type GlobalToolHandlerArgs<TSchema = undefined> = {\n slug: GlobalSlug\n} & ToolHandlerArgs<TSchema>\n\nexport type Tool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> = {\n /**\n * Runs while authorizing each MCP request, before the tool is advertised or called. Return\n * `false` to make the tool unavailable for that request. This is skipped when `overrideAccess`\n * is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description: string\n handler: (args: ToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n /**\n * Override the return value of the tool handler\n */\n overrideResponse?: MCPResponseOverride\n}\n\nexport type CollectionTool<\n TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined,\n> = {\n /**\n * Runs while authorizing each MCP request for this collection. Return `false` to reject calls\n * to this tool for the collection. The shared tool is not advertised when no collections allow\n * it, but can remain advertised when it is available for another collection. This is skipped\n * when `overrideAccess` is enabled.\n */\n access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>\n handler: (args: CollectionToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n} & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>\n\nexport type GlobalTool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> =\n {\n /**\n * Runs while authorizing each MCP request for this global. Return `false` to reject calls to\n * this tool for the global. The shared tool is not advertised when no globals allow it, but\n * can remain advertised when it is available for another global. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>\n handler: (args: GlobalToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n } & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>\n\n/**\n * Configures (or disables) a built-in tool without replacing it.\n * `handler?: never` prevents a full `CollectionTool`/`GlobalTool` (which has a\n * required handler) from being silently accepted at a built-in key slot.\n */\nexport type MCPBuiltInCollectionToolOverride = {\n /**\n * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for\n * this collection. This is skipped when `overrideAccess` is enabled.\n */\n access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description?: string\n handler?: never\n overrideResponse?: MCPResponseOverride\n}\n\nexport type MCPBuiltInGlobalToolOverride = {\n /**\n * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for\n * this global. This is skipped when `overrideAccess` is enabled.\n */\n access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description?: string\n handler?: never\n overrideResponse?: MCPResponseOverride\n}\n\n/**\n * Value at a custom (non-built-in) tool key. Either the tool itself, or `false`\n * to disable it (useful when one plugin defines a custom tool and another\n * wants to opt out per-collection).\n */\nexport type MCPTopLevelToolEntry = Tool\n\nexport type MCPCollectionToolsMap = {\n [customToolName: string]: boolean | CollectionTool | MCPBuiltInCollectionToolOverride | undefined\n} & {\n [K in MCPCollectionBuiltinName]?: false | MCPBuiltInCollectionToolOverride\n}\n\nexport type MCPAuthCollectionToolsMap = {\n [K in MCPCollectionAuthToolName]?: MCPBuiltInCollectionToolOverride | true\n} & MCPCollectionToolsMap\n\n/** Auth-enabled collections get auth-tool name autocomplete; others get CRUD-only. */\nexport type MCPToolsMapForCollection<Slug extends CollectionSlug> = Slug extends AuthCollectionSlug\n ? MCPAuthCollectionToolsMap\n : MCPCollectionToolsMap\n\nexport type MCPGlobalToolsMap = {\n [customToolName: string]: boolean | GlobalTool | MCPBuiltInGlobalToolOverride | undefined\n} & {\n [K in MCPGlobalBuiltinName]?: false | MCPBuiltInGlobalToolOverride\n}\n\nexport type MCPTopLevelToolsMap = Record<string, Tool>\n\nexport type PromptHandlerArgs<TSchema = undefined> = {\n input: TypedInput<TSchema>\n req: PayloadRequest\n serverContext: ServerContext\n}\n\nexport type Prompt<TSchema extends ToolInputSchema = ToolInputSchema> = {\n /**\n * Runs while authorizing each MCP request, before the prompt is advertised or used. Return\n * `false` to make the prompt unavailable for that request. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n argsSchema: TSchema\n description: string\n handler: (args: PromptHandlerArgs<TSchema>) => MaybePromise<{\n messages: Array<{ content: { text: string; type: 'text' }; role: 'assistant' | 'user' }>\n }>\n title: string\n}\n\nexport type ResourceHandlerArgs = {\n /** Variables extracted from a `ResourceTemplate` URI. Empty for static-URI resources. */\n params: Record<string, string>\n req: PayloadRequest\n serverContext: ServerContext\n uri: URL\n}\n\nexport type Resource = {\n /**\n * Runs while authorizing each MCP request, before the resource is advertised or read. Return\n * `false` to make the resource unavailable for that request. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n description: string\n handler: (args: ResourceHandlerArgs) => MaybePromise<{\n contents: Array<{ text: string; uri: string }>\n }>\n mimeType: string\n title: string\n uri: ResourceTemplate | string\n}\n\nexport type MCPPluginCollectionConfig<TSlug extends CollectionSlug> = {\n description?: string\n /** Fallback for built-in tools that don't set their own `overrideResponse`. */\n overrideResponse?: MCPResponseOverride\n tools?: MCPToolsMapForCollection<TSlug>\n}\n\nexport type MCPPluginGlobalConfig = {\n description?: string\n overrideResponse?: MCPResponseOverride\n tools?: MCPGlobalToolsMap\n}\n\n/**\n * The user-facing config shape passed to `mcpPlugin({ ... })`. Tools, prompts,\n * resources, and per-collection/global tool maps live in their own nested\n * fields. `sanitizeMCPConfig` flattens those into `items` and applies defaults\n * to produce a `SanitizedMCPPluginConfig` — the form every internal consumer\n * actually works with.\n */\nexport type MCPPluginConfig = {\n collections?: {\n [Slug in CollectionSlug]?: MCPPluginCollectionConfig<Slug>\n }\n /** Skip MCP endpoint registration. */\n disabled?: boolean\n globals?: {\n [Slug in GlobalSlug]?: MCPPluginGlobalConfig\n }\n hooks?: {\n /** Transform a tool response after its handler returns */\n afterToolCall?: MCPAfterToolCallHook[]\n }\n mcp?: {\n /**\n * Largest HTTP request body, in bytes, that the MCP endpoint accepts. Larger requests\n * are answered with `413`. Base64 file uploads count toward this limit.\n *\n * @default 4194304 (4 MiB, the MCP SDK default)\n */\n maxRequestBodySize?: number\n serverOptions?: MCPServerOptions\n verboseLogs?: boolean\n }\n /**\n * Replace the default MCP authorization resolver.\n *\n * This hook replaces the default authentication flow. It must set `req.user` to the\n * authenticated Payload user, or to `null` for an anonymous caller, before returning.\n */\n overrideGetAuthorizedMCP?: (\n args: {\n pluginConfig: SanitizedMCPPluginConfig\n } & GetAuthorizedMCPArgs,\n ) => MaybePromise<AuthorizedMCP>\n prompts?: Record<string, Prompt>\n resources?: Record<string, Resource>\n /** Cross-cutting tools (not scoped to any collection or global). */\n tools?: MCPTopLevelToolsMap\n}\n\nexport type SanitizedMCPPluginConfig = {\n items: MCPItem[]\n} & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'overrideGetAuthorizedMCP'>\n\nexport type MCPServerOptions = {\n options?: McpServerOptions\n serverInfo?: Partial<Implementation>\n}\n\n/**\n * One MCP primitive plus the metadata needed for config-driven filtering and\n * registration.\n *\n * - `configKey`: the config identifier, e.g. `find` or `echo`.\n * - `mcpName`: the MCP wire name, e.g. `findDocuments` or `echo`.\n * - `label`: human-readable display text.\n */\nexport type MCPItemBase = {\n configKey: string\n label: string\n mcpName: string\n}\n\nexport type CollectionMCPItem = {\n collectionSlug: CollectionSlug\n tool: CollectionTool\n type: 'collectionTool'\n} & MCPItemBase\n\nexport type GlobalMCPItem = {\n globalSlug: GlobalSlug\n tool: GlobalTool\n type: 'globalTool'\n} & MCPItemBase\n\nexport type MCPItem =\n | ({\n prompt: Prompt\n type: 'prompt'\n } & MCPItemBase)\n | ({\n resource: Resource\n type: 'resource'\n } & MCPItemBase)\n | ({\n tool: Tool\n type: 'tool'\n } & MCPItemBase)\n | CollectionMCPItem\n | GlobalMCPItem\n\n/**\n * The MCP items and access mode authorized for this request. The authenticated user is available\n * as `req.user`.\n */\nexport type AuthorizedMCP = {\n items: MCPItem[]\n overrideAccess: boolean\n}\n"],"names":[],"mappings":"AAwWA;;;CAGC,GACD,WAGC"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n CallToolResult,\n ContentBlock,\n Implementation,\n JsonSchemaType,\n McpServerOptions,\n ResourceTemplate,\n ServerContext,\n StandardSchemaWithJSON,\n ToolAnnotations,\n} from '@modelcontextprotocol/server'\nimport type {\n AuthCollectionSlug,\n CollectionSlug,\n GlobalSlug,\n MaybePromise,\n PayloadRequest,\n SanitizedPermissions,\n} from 'payload'\n\nimport type { GetAuthorizedMCPArgs } from './endpoint/access.js'\nimport type {\n MCPCollectionAuthToolName,\n MCPCollectionBuiltinName,\n MCPGlobalBuiltinName,\n} from './mcp/builtinTools.js'\n\nexport type { MCPCollectionAuthToolName, MCPCollectionBuiltinName, MCPGlobalBuiltinName }\n\n/** Re-exported from `@modelcontextprotocol/server` — common MCP types used in plugin config. */\nexport type { JsonSchemaType, StandardSchemaWithJSON, ToolAnnotations }\n\n/**\n * What a tool's `input` (or a prompt's `argsSchema`) can be — either a raw\n * JSON Schema 2020-12 literal, or a Standard Schema instance (Zod, Valibot, …).\n * Raw schemas may omit `$schema`; when present it must declare the 2020-12 dialect.\n */\nexport type ToolInputSchema = JsonSchemaType | StandardSchemaWithJSON\n\nexport type MCPToolResponse = {\n content: ContentBlock[]\n /**\n * If available, return the document fetched within the\n * mcp tool. This is threaded as an additional argument to\n * overrideResponse functions and stripped before going on the wire.\n */\n doc?: Record<string, unknown>\n} & Pick<CallToolResult, '_meta' | 'isError' | 'structuredContent'>\n\nexport type MCPResponseOverride = (\n response: MCPToolResponse,\n doc: Record<string, unknown>,\n req: PayloadRequest,\n) => MCPToolResponse\n\nexport type MCPAfterToolCallHook = (args: {\n input: unknown\n req: PayloadRequest\n response: MCPToolResponse\n toolName: string\n}) => MaybePromise<MCPToolResponse>\n\n/**\n * The handler's `input` type. A specific Standard Schema (Zod, Valibot, …) gets\n * its inferred output; anything else falls back to `Record<string, unknown>`.\n */\nexport type TypedInput<TSchema> = TSchema extends StandardSchemaWithJSON\n ? StandardSchemaWithJSON extends TSchema\n ? Record<string, unknown>\n : StandardSchemaWithJSON.InferOutput<TSchema>\n : Record<string, unknown>\n\nexport type MCPAccessArgs = {\n permissions?: SanitizedPermissions\n req: PayloadRequest\n}\n\nexport type CollectionMCPAccessArgs = {\n slug: CollectionSlug\n} & MCPAccessArgs\n\nexport type GlobalMCPAccessArgs = {\n slug: GlobalSlug\n} & MCPAccessArgs\n\nexport type ToolHandlerArgs<TSchema = undefined> = {\n authorizedMCP: AuthorizedMCP\n input: TypedInput<TSchema>\n req: PayloadRequest\n serverContext: ServerContext\n}\n\nexport type CollectionToolHandlerArgs<TSchema = undefined> = {\n slug: CollectionSlug\n} & ToolHandlerArgs<TSchema>\n\nexport type GlobalToolHandlerArgs<TSchema = undefined> = {\n slug: GlobalSlug\n} & ToolHandlerArgs<TSchema>\n\nexport type Tool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> = {\n /**\n * Runs while authorizing each MCP request, before the tool is advertised or called. Return\n * `false` to make the tool unavailable for that request. This is skipped when `overrideAccess`\n * is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description: string\n handler: (args: ToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n /**\n * Override the return value of the tool handler\n */\n overrideResponse?: MCPResponseOverride\n}\n\nexport type CollectionTool<\n TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined,\n> = {\n /**\n * Runs while authorizing each MCP request for this collection. Return `false` to reject calls\n * to this tool for the collection. The shared tool is not advertised when no collections allow\n * it, but can remain advertised when it is available for another collection. This is skipped\n * when `overrideAccess` is enabled.\n */\n access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>\n handler: (args: CollectionToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n} & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>\n\nexport type GlobalTool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> =\n {\n /**\n * Runs while authorizing each MCP request for this global. Return `false` to reject calls to\n * this tool for the global. The shared tool is not advertised when no globals allow it, but\n * can remain advertised when it is available for another global. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>\n handler: (args: GlobalToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n } & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>\n\n/**\n * Configures (or disables) a built-in tool without replacing it.\n * `handler?: never` prevents a full `CollectionTool`/`GlobalTool` (which has a\n * required handler) from being silently accepted at a built-in key slot.\n */\nexport type MCPBuiltInCollectionToolOverride = {\n /**\n * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for\n * this collection. This is skipped when `overrideAccess` is enabled.\n */\n access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description?: string\n handler?: never\n overrideResponse?: MCPResponseOverride\n}\n\nexport type MCPBuiltInGlobalToolOverride = {\n /**\n * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for\n * this global. This is skipped when `overrideAccess` is enabled.\n */\n access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description?: string\n handler?: never\n overrideResponse?: MCPResponseOverride\n}\n\n/**\n * Value at a custom (non-built-in) tool key. Either the tool itself, or `false`\n * to disable it (useful when one plugin defines a custom tool and another\n * wants to opt out per-collection).\n */\nexport type MCPTopLevelToolEntry = Tool\n\nexport type MCPCollectionToolsMap = {\n [customToolName: string]: boolean | CollectionTool | MCPBuiltInCollectionToolOverride | undefined\n} & {\n [K in MCPCollectionBuiltinName]?: false | MCPBuiltInCollectionToolOverride\n}\n\nexport type MCPAuthCollectionToolsMap = {\n [K in MCPCollectionAuthToolName]?: MCPBuiltInCollectionToolOverride | true\n} & MCPCollectionToolsMap\n\n/** Auth-enabled collections get auth-tool name autocomplete; others get CRUD-only. */\nexport type MCPToolsMapForCollection<Slug extends CollectionSlug> = Slug extends AuthCollectionSlug\n ? MCPAuthCollectionToolsMap\n : MCPCollectionToolsMap\n\nexport type MCPGlobalToolsMap = {\n [customToolName: string]: boolean | GlobalTool | MCPBuiltInGlobalToolOverride | undefined\n} & {\n [K in MCPGlobalBuiltinName]?: false | MCPBuiltInGlobalToolOverride\n}\n\nexport type MCPTopLevelToolsMap = Record<string, Tool>\n\nexport type PromptHandlerArgs<TSchema = undefined> = {\n input: TypedInput<TSchema>\n req: PayloadRequest\n serverContext: ServerContext\n}\n\nexport type Prompt<TSchema extends ToolInputSchema = ToolInputSchema> = {\n /**\n * Runs while authorizing each MCP request, before the prompt is advertised or used. Return\n * `false` to make the prompt unavailable for that request. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n argsSchema: TSchema\n description: string\n handler: (args: PromptHandlerArgs<TSchema>) => MaybePromise<{\n messages: Array<{ content: { text: string; type: 'text' }; role: 'assistant' | 'user' }>\n }>\n title: string\n}\n\nexport type ResourceHandlerArgs = {\n /** Variables extracted from a `ResourceTemplate` URI. Empty for static-URI resources. */\n params: Record<string, string>\n req: PayloadRequest\n serverContext: ServerContext\n uri: URL\n}\n\nexport type Resource = {\n /**\n * Runs while authorizing each MCP request, before the resource is advertised or read. Return\n * `false` to make the resource unavailable for that request. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n description: string\n handler: (args: ResourceHandlerArgs) => MaybePromise<{\n contents: Array<{ text: string; uri: string }>\n }>\n mimeType: string\n title: string\n uri: ResourceTemplate | string\n}\n\nexport type MCPPluginCollectionConfig<TSlug extends CollectionSlug> = {\n description?: string\n /** Fallback for built-in tools that don't set their own `overrideResponse`. */\n overrideResponse?: MCPResponseOverride\n tools?: MCPToolsMapForCollection<TSlug>\n}\n\nexport type MCPPluginGlobalConfig = {\n description?: string\n overrideResponse?: MCPResponseOverride\n tools?: MCPGlobalToolsMap\n}\n\n/**\n * The user-facing config shape passed to `mcpPlugin({ ... })`. Tools, prompts,\n * resources, and per-collection/global tool maps live in their own nested\n * fields. `sanitizeMCPConfig` flattens those into `items` and applies defaults\n * to produce a `SanitizedMCPPluginConfig` — the form every internal consumer\n * actually works with.\n */\nexport type MCPPluginConfig = {\n collections?: {\n [Slug in CollectionSlug]?: MCPPluginCollectionConfig<Slug>\n }\n /** Skip MCP endpoint registration. */\n disabled?: boolean\n globals?: {\n [Slug in GlobalSlug]?: MCPPluginGlobalConfig\n }\n hooks?: {\n /** Transform a tool response after its handler returns */\n afterToolCall?: MCPAfterToolCallHook[]\n }\n mcp?: {\n /**\n * Largest HTTP request body, in bytes, that the MCP endpoint accepts. Larger requests\n * are answered with `413`. Base64 file uploads count toward this limit.\n *\n * @default 4194304 (4 MiB, the MCP SDK default)\n */\n maxRequestBodySize?: number\n serverOptions?: MCPServerOptions\n verboseLogs?: boolean\n }\n /**\n * Lets MCP clients sign in through an OAuth authorization server. MCP requests without an\n * authenticated user get a `401` that points to the protected resource metadata (RFC 9728),\n * served by `oauthProtectedResourceHandler`. Payload's auth strategies must accept the\n * issued access tokens.\n */\n oauth?: {\n /**\n * Called on MCP requests with a bearer token that Payload's auth strategies didn't accept.\n * Return the Payload user, including its `collection`, or `null` to answer with the OAuth challenge.\n */\n authenticate?: (args: {\n req: PayloadRequest\n token: string\n }) => MaybePromise<PayloadRequest['user']>\n /**\n * The authorization servers that issue access tokens for MCP clients. Clients require each one\n * to exactly match the `issuer` in that server's metadata, so pass a function when the exact\n * value is only known at runtime, e.g. from the server's OpenID configuration or per host.\n */\n authorizationServers: ((args: { req: PayloadRequest }) => MaybePromise<string[]>) | string[]\n /**\n * The URL clients call to reach the MCP endpoint.\n *\n * @default the absolute URL of `/api/mcp`, based on `serverURL` or the request URL\n */\n resource?: string\n /**\n * Scopes MCP clients should request, e.g. `['openid', 'email', 'profile']`. Without them,\n * clients request none, which some authorization servers reject or answer with a token that\n * doesn't identify the user.\n */\n scopes?: string[]\n }\n /**\n * Replace the default MCP authorization resolver.\n *\n * This hook replaces the default authentication flow. It must set `req.user` to the\n * authenticated Payload user, or to `null` for an anonymous caller, before returning.\n */\n overrideGetAuthorizedMCP?: (\n args: {\n pluginConfig: SanitizedMCPPluginConfig\n } & GetAuthorizedMCPArgs,\n ) => MaybePromise<AuthorizedMCP>\n prompts?: Record<string, Prompt>\n resources?: Record<string, Resource>\n /** Cross-cutting tools (not scoped to any collection or global). */\n tools?: MCPTopLevelToolsMap\n}\n\nexport type SanitizedMCPPluginConfig = {\n items: MCPItem[]\n} & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'oauth' | 'overrideGetAuthorizedMCP'>\n\nexport type MCPServerOptions = {\n options?: McpServerOptions\n serverInfo?: Partial<Implementation>\n}\n\n/**\n * One MCP primitive plus the metadata needed for config-driven filtering and\n * registration.\n *\n * - `configKey`: the config identifier, e.g. `find` or `echo`.\n * - `mcpName`: the MCP wire name, e.g. `findDocuments` or `echo`.\n * - `label`: human-readable display text.\n */\nexport type MCPItemBase = {\n configKey: string\n label: string\n mcpName: string\n}\n\nexport type CollectionMCPItem = {\n collectionSlug: CollectionSlug\n tool: CollectionTool\n type: 'collectionTool'\n} & MCPItemBase\n\nexport type GlobalMCPItem = {\n globalSlug: GlobalSlug\n tool: GlobalTool\n type: 'globalTool'\n} & MCPItemBase\n\nexport type MCPItem =\n | ({\n prompt: Prompt\n type: 'prompt'\n } & MCPItemBase)\n | ({\n resource: Resource\n type: 'resource'\n } & MCPItemBase)\n | ({\n tool: Tool\n type: 'tool'\n } & MCPItemBase)\n | CollectionMCPItem\n | GlobalMCPItem\n\n/**\n * The MCP items and access mode authorized for this request. The authenticated user is available\n * as `req.user`.\n */\nexport type AuthorizedMCP = {\n items: MCPItem[]\n overrideAccess: boolean\n}\n"],"names":[],"mappings":"AA0YA;;;CAGC,GACD,WAGC"}
package/package.json CHANGED
@@ -1,17 +1,12 @@
1
1
  {
2
2
  "name": "@payloadcms/plugin-mcp",
3
- "version": "4.0.0-internal.f15737c",
3
+ "version": "4.0.0-internal.f2a04f7",
4
4
  "description": "MCP (Model Context Protocol) capabilities with Payload",
5
5
  "keywords": [
6
- "plugin",
7
6
  "mcp",
8
- "model context protocol"
7
+ "model context protocol",
8
+ "plugin"
9
9
  ],
10
- "repository": {
11
- "type": "git",
12
- "url": "https://github.com/payloadcms/payload.git",
13
- "directory": "packages/plugin-mcp"
14
- },
15
10
  "license": "MIT",
16
11
  "author": "Payload <dev@payloadcms.com> (https://payloadcms.com)",
17
12
  "maintainers": [
@@ -21,7 +16,22 @@
21
16
  "url": "https://payloadcms.com"
22
17
  }
23
18
  ],
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "https://github.com/payloadcms/payload.git",
22
+ "directory": "packages/plugin-mcp"
23
+ },
24
+ "bin": {
25
+ "payload-mcp": "./bin.js"
26
+ },
27
+ "files": [
28
+ "src",
29
+ "dist",
30
+ "bin.js"
31
+ ],
24
32
  "type": "module",
33
+ "main": "./dist/index.js",
34
+ "types": "./dist/index.d.ts",
25
35
  "exports": {
26
36
  ".": {
27
37
  "import": "./dist/index.js",
@@ -44,26 +54,16 @@
44
54
  "default": "./dist/exports/internal.js"
45
55
  }
46
56
  },
47
- "main": "./dist/index.js",
48
- "types": "./dist/index.d.ts",
49
- "bin": {
50
- "payload-mcp": "./bin.js"
51
- },
52
- "files": [
53
- "src",
54
- "dist",
55
- "bin.js"
56
- ],
57
57
  "dependencies": {
58
58
  "@modelcontextprotocol/server": "2.3.1",
59
59
  "tsx": "4.23.15"
60
60
  },
61
61
  "devDependencies": {
62
62
  "@payloadcms/eslint-config": "3.28.0",
63
- "payload": "4.0.0-internal.f15737c"
63
+ "payload": "4.0.0-internal.f2a04f7"
64
64
  },
65
65
  "peerDependencies": {
66
- "payload": "4.0.0-internal.f15737c"
66
+ "payload": "4.0.0-internal.f2a04f7"
67
67
  },
68
68
  "//deps_notes": {
69
69
  "tsx": "Required by the `bin.js` stdio mcp. Keep the version pinned to whatever `payload` ships to avoid duplicate installs."
@@ -1,6 +1,6 @@
1
1
  import type { PayloadRequest, SanitizedPermissions } from 'payload'
2
2
 
3
- import { getAccessResults, UnauthorizedError } from 'payload'
3
+ import { executeAuthStrategies, getAccessResults, UnauthorizedError } from 'payload'
4
4
 
5
5
  import type { AuthorizedMCP, MCPItem } from '../types.js'
6
6
 
@@ -34,9 +34,18 @@ export const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<Authorize
34
34
  const hasAuthorization = headers.has('Authorization')
35
35
 
36
36
  headers.set('DisableAutologin', 'true')
37
- req.user = (await req.payload.auth({ headers, req })).user
37
+ // Not `payload.auth()`, which also computes permissions that filterMCPItems computes anyway
38
+ req.user = (await executeAuthStrategies({ headers, payload: req.payload, req })).user
39
+
40
+ // Only bearer tokens that no auth strategy accepted reach the hook, e.g. an OAuth access token.
41
+ // API keys use the `<collection> API-Key <key>` scheme instead of `Bearer`, so they never do.
42
+ const bearerToken = headers.get('Authorization')?.match(/^Bearer (.+)$/)?.[1]
43
+ if (!req.user && bearerToken && pluginConfig.oauth?.authenticate) {
44
+ req.user = await pluginConfig.oauth.authenticate({ req, token: bearerToken })
45
+ }
38
46
 
39
- if (hasAuthorization && !req.user) {
47
+ // With OAuth, the endpoint answers with a challenge that starts the client's sign-in
48
+ if (hasAuthorization && !req.user && !pluginConfig.oauth) {
40
49
  throw new UnauthorizedError(req.t)
41
50
  }
42
51
  }
@@ -11,6 +11,7 @@ import { APIError } from 'payload'
11
11
  import { buildMcpServer } from '../mcp/buildMcpServer.js'
12
12
  import { getPluginConfig } from '../utils/getPluginConfig.js'
13
13
  import { getAuthorizedMCP } from './access.js'
14
+ import { getMCPResource, oauthChallenge } from './oauth.js'
14
15
 
15
16
  export const mcpEndpoint: PayloadHandler = async (req) => {
16
17
  if (!req.url) {
@@ -18,6 +19,8 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
18
19
  }
19
20
 
20
21
  req.payloadAPI = 'MCP' as const
22
+ // Lets auth strategies check that an OAuth access token was issued for this MCP server
23
+ req.context.mcp = { resource: getMCPResource({ config: req.payload.config, url: req.url }) }
21
24
 
22
25
  const pluginConfig = getPluginConfig({ config: req.payload.config })
23
26
  const overrideAccessParam = new URL(req.url).searchParams.get('overrideAccess')
@@ -34,6 +37,11 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
34
37
  }
35
38
 
36
39
  const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
40
+
41
+ if (pluginConfig.oauth && !req.user) {
42
+ return oauthChallenge({ req })
43
+ }
44
+
37
45
  const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize
38
46
  // Payload augments the original web-standard Request in place.
39
47
  const mcpRequest = req as PayloadRequest & Request
@@ -0,0 +1,90 @@
1
+ import type { OAuthProtectedResourceMetadata } from '@modelcontextprotocol/server'
2
+ import type { PayloadHandler, PayloadRequest, SanitizedConfig } from 'payload'
3
+
4
+ import {
5
+ bearerAuthChallengeResponse,
6
+ OAuthError,
7
+ OAuthErrorCode,
8
+ } from '@modelcontextprotocol/server'
9
+ import { createPayloadRequest, getPayload } from 'payload'
10
+
11
+ import { getPluginConfig } from '../utils/getPluginConfig.js'
12
+
13
+ /**
14
+ * Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.
15
+ * The OAuth challenge links here, so MCP clients find the authorization server without setup.
16
+ */
17
+ export const oauthProtectedResourceEndpoint: PayloadHandler = (req) => getMetadataResponse({ req })
18
+
19
+ /**
20
+ * Serves the same metadata for clients that ignore the challenge's link and only look at
21
+ * `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at
22
+ * `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:
23
+ *
24
+ * ```ts
25
+ * import config from '@payload-config'
26
+ * import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'
27
+ *
28
+ * export const GET = oauthProtectedResourceHandler(config)
29
+ * ```
30
+ */
31
+ export const oauthProtectedResourceHandler =
32
+ (config: Promise<SanitizedConfig> | SanitizedConfig) =>
33
+ async (request: Request): Promise<Response> =>
34
+ getMetadataResponse({
35
+ req: await createPayloadRequest({ payload: await getPayload({ config }), req: request }),
36
+ })
37
+
38
+ /**
39
+ * Answers an unauthenticated MCP request with a challenge linking to the protected resource
40
+ * metadata, which starts the client's OAuth flow.
41
+ */
42
+ export const oauthChallenge = ({ req }: { req: PayloadRequest }): Response => {
43
+ const response = bearerAuthChallengeResponse(
44
+ new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')),
45
+ {
46
+ requiredScopes: getPluginConfig({ config: req.payload.config }).oauth?.scopes,
47
+ resourceMetadataUrl: `${getMCPURL({ config: req.payload.config, url: req.url! })}/oauth-protected-resource`,
48
+ },
49
+ )
50
+
51
+ // Lets browser-based MCP clients read the challenge, when Payload's `cors` setting allows them
52
+ response.headers.set('Access-Control-Expose-Headers', 'WWW-Authenticate')
53
+
54
+ return response
55
+ }
56
+
57
+ /**
58
+ * The MCP endpoint's address, as advertised in the metadata's `resource`. Clients send it when
59
+ * they sign in, and authorization servers that support it put it in the access token's audience.
60
+ */
61
+ export const getMCPResource = ({ config, url }: { config: SanitizedConfig; url: string }): string =>
62
+ getPluginConfig({ config }).oauth?.resource ?? getMCPURL({ config, url })
63
+
64
+ const getMCPURL = ({ config, url }: { config: SanitizedConfig; url: string }): string =>
65
+ new URL(`${config.routes.api}/mcp`, config.serverURL || url).href
66
+
67
+ const getMetadataResponse = async ({ req }: { req: PayloadRequest }): Promise<Response> => {
68
+ const { config } = req.payload
69
+ const pluginConfig = getPluginConfig({ config })
70
+
71
+ if (!pluginConfig.oauth) {
72
+ return new Response(null, { status: 404 })
73
+ }
74
+
75
+ const { authorizationServers, scopes } = pluginConfig.oauth
76
+
77
+ return Response.json(
78
+ {
79
+ authorization_servers:
80
+ typeof authorizationServers === 'function'
81
+ ? await authorizationServers({ req })
82
+ : authorizationServers,
83
+ bearer_methods_supported: ['header'],
84
+ resource: getMCPResource({ config, url: req.url! }),
85
+ scopes_supported: scopes,
86
+ } satisfies OAuthProtectedResourceMetadata,
87
+ // Public document, readable by browser-based MCP clients on any origin
88
+ { headers: { 'Access-Control-Allow-Origin': '*' } },
89
+ )
90
+ }
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@ import { definePlugin } from 'payload'
3
3
  import type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js'
4
4
 
5
5
  import { mcpEndpoint } from './endpoint/index.js'
6
+ import { oauthProtectedResourceEndpoint } from './endpoint/oauth.js'
6
7
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'
7
8
 
8
9
  declare module 'payload' {
@@ -13,11 +14,19 @@ declare module 'payload' {
13
14
  /** After the plugin's `plugin` callback runs, `options` holds the sanitized config. */
14
15
  '@payloadcms/plugin-mcp': MCPPluginConfig
15
16
  }
17
+ export interface RequestContext {
18
+ /** Set on MCP requests before they're authenticated. */
19
+ mcp?: {
20
+ /** The MCP endpoint's address, which OAuth access tokens for MCP are issued for. */
21
+ resource: string
22
+ }
23
+ }
16
24
  }
17
25
 
18
26
  export type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig }
19
27
 
20
28
  export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'
29
+ export { oauthProtectedResourceHandler } from './endpoint/oauth.js'
21
30
 
22
31
  export const mcpPlugin = definePlugin<MCPPluginConfig>({
23
32
  slug: '@payloadcms/plugin-mcp',
@@ -40,15 +49,23 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
40
49
  ...config,
41
50
  endpoints: [
42
51
  ...(config.endpoints ?? []),
43
- // Payload prefixes /api, so the full path is /api/mcp.
44
- { handler: mcpEndpoint, method: 'post', path: '/mcp' },
52
+ // Payload prefixes /api, so the full path is /api/mcp. getAuthorizedMCP authenticates the
53
+ // request with dev auto-login turned off, so Payload doesn't authenticate it first.
54
+ { disableAuth: true, handler: mcpEndpoint, method: 'post', path: '/mcp' },
45
55
  // Streamable HTTP's optional server=>client GET stream. We don't offer
46
56
  // one, so answer 405 per spec-— clients then skip it cleanly
47
57
  {
58
+ disableAuth: true,
48
59
  handler: () => new Response(null, { headers: { Allow: 'POST' }, status: 405 }),
49
60
  method: 'get',
50
61
  path: '/mcp',
51
62
  },
63
+ {
64
+ disableAuth: true,
65
+ handler: oauthProtectedResourceEndpoint,
66
+ method: 'get',
67
+ path: '/mcp/oauth-protected-resource',
68
+ },
52
69
  ],
53
70
  }
54
71
  },
@@ -9,7 +9,7 @@ export const getUploadInstructionsTool = defineCollectionTool({
9
9
  defaultAccess(args) &&
10
10
  Boolean(
11
11
  args.permissions?.collections?.[args.slug]?.create ||
12
- args.permissions?.collections?.[args.slug]?.update,
12
+ args.permissions?.collections?.[args.slug]?.update,
13
13
  ),
14
14
  annotations: {
15
15
  destructiveHint: false,
@@ -103,6 +103,7 @@ export const sanitizeMCPConfig = ({
103
103
  hooks: pluginConfig.hooks,
104
104
  items,
105
105
  mcp: pluginConfig.mcp,
106
+ oauth: pluginConfig.oauth,
106
107
  overrideGetAuthorizedMCP: pluginConfig.overrideGetAuthorizedMCP,
107
108
  }
108
109
  }
package/src/types.ts CHANGED
@@ -290,6 +290,40 @@ export type MCPPluginConfig = {
290
290
  serverOptions?: MCPServerOptions
291
291
  verboseLogs?: boolean
292
292
  }
293
+ /**
294
+ * Lets MCP clients sign in through an OAuth authorization server. MCP requests without an
295
+ * authenticated user get a `401` that points to the protected resource metadata (RFC 9728),
296
+ * served by `oauthProtectedResourceHandler`. Payload's auth strategies must accept the
297
+ * issued access tokens.
298
+ */
299
+ oauth?: {
300
+ /**
301
+ * Called on MCP requests with a bearer token that Payload's auth strategies didn't accept.
302
+ * Return the Payload user, including its `collection`, or `null` to answer with the OAuth challenge.
303
+ */
304
+ authenticate?: (args: {
305
+ req: PayloadRequest
306
+ token: string
307
+ }) => MaybePromise<PayloadRequest['user']>
308
+ /**
309
+ * The authorization servers that issue access tokens for MCP clients. Clients require each one
310
+ * to exactly match the `issuer` in that server's metadata, so pass a function when the exact
311
+ * value is only known at runtime, e.g. from the server's OpenID configuration or per host.
312
+ */
313
+ authorizationServers: ((args: { req: PayloadRequest }) => MaybePromise<string[]>) | string[]
314
+ /**
315
+ * The URL clients call to reach the MCP endpoint.
316
+ *
317
+ * @default the absolute URL of `/api/mcp`, based on `serverURL` or the request URL
318
+ */
319
+ resource?: string
320
+ /**
321
+ * Scopes MCP clients should request, e.g. `['openid', 'email', 'profile']`. Without them,
322
+ * clients request none, which some authorization servers reject or answer with a token that
323
+ * doesn't identify the user.
324
+ */
325
+ scopes?: string[]
326
+ }
293
327
  /**
294
328
  * Replace the default MCP authorization resolver.
295
329
  *
@@ -309,7 +343,7 @@ export type MCPPluginConfig = {
309
343
 
310
344
  export type SanitizedMCPPluginConfig = {
311
345
  items: MCPItem[]
312
- } & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'overrideGetAuthorizedMCP'>
346
+ } & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'oauth' | 'overrideGetAuthorizedMCP'>
313
347
 
314
348
  export type MCPServerOptions = {
315
349
  options?: McpServerOptions