@payloadcms/plugin-mcp 4.0.0-internal.b8e7c89 → 4.0.0-internal.bf4bcce
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.
- package/bin.js +0 -7
- package/dist/endpoint/access.d.ts.map +1 -1
- package/dist/endpoint/access.js +11 -1
- package/dist/endpoint/access.js.map +1 -1
- package/dist/endpoint/index.d.ts.map +1 -1
- package/dist/endpoint/index.js +39 -4
- package/dist/endpoint/index.js.map +1 -1
- package/dist/endpoint/oauth.d.ts +27 -0
- package/dist/endpoint/oauth.d.ts.map +1 -0
- package/dist/endpoint/oauth.js +61 -0
- package/dist/endpoint/oauth.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/dist/mcp/buildMcpServer.d.ts +1 -1
- package/dist/mcp/buildMcpServer.js +1 -1
- package/dist/mcp/buildMcpServer.js.map +1 -1
- package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/authTools.js +4 -3
- package/dist/mcp/builtin/collections/authTools.js.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +19 -3
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +19 -3
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.js +1 -0
- package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
- package/dist/stdio.js +4 -3
- package/dist/stdio.js.map +1 -1
- package/dist/types.d.ts +34 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -6
- package/src/endpoint/access.ts +9 -1
- package/src/endpoint/index.ts +39 -3
- package/src/endpoint/oauth.ts +72 -0
- package/src/index.ts +7 -0
- package/src/mcp/buildMcpServer.ts +1 -1
- package/src/mcp/builtin/collections/authTools.ts +5 -2
- package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +12 -1
- package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +11 -1
- package/src/mcp/sanitizeMCPConfig.ts +1 -0
- package/src/stdio.ts +2 -2
- package/src/types.ts +35 -4
- package/dist/mcp/builtin/collections/fileInput.spec.js +0 -86
- package/dist/mcp/builtin/collections/fileInput.spec.js.map +0 -1
package/bin.js
CHANGED
|
@@ -27,13 +27,6 @@ const start = async () => {
|
|
|
27
27
|
return
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
// tsx 4.22.4's synchronous loader leaks its namespace query onto Node built-ins on Node 23.5+.
|
|
31
|
-
// Force the stable asynchronous loader path, matching payload/bin.js.
|
|
32
|
-
const nodeModule = await import('node:module')
|
|
33
|
-
if (typeof nodeModule.default.registerHooks === 'function') {
|
|
34
|
-
nodeModule.default.registerHooks = undefined
|
|
35
|
-
}
|
|
36
|
-
|
|
37
30
|
const { tsImport } = await import('tsx/esm/api')
|
|
38
31
|
const { runMcpStdio } = await tsImport('./dist/stdio.js', baseURL)
|
|
39
32
|
await runMcpStdio()
|
|
@@ -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,
|
|
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,CA0CnF,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"}
|
package/dist/endpoint/access.js
CHANGED
|
@@ -22,7 +22,17 @@ import { getPluginConfig } from '../utils/getPluginConfig.js';
|
|
|
22
22
|
headers,
|
|
23
23
|
req
|
|
24
24
|
})).user;
|
|
25
|
-
|
|
25
|
+
// Only bearer tokens that no auth strategy accepted reach the hook, e.g. an OAuth access token.
|
|
26
|
+
// API keys use the `<collection> API-Key <key>` scheme instead of `Bearer`, so they never do.
|
|
27
|
+
const bearerToken = headers.get('Authorization')?.match(/^Bearer (.+)$/)?.[1];
|
|
28
|
+
if (!req.user && bearerToken && pluginConfig.oauth?.authenticate) {
|
|
29
|
+
req.user = await pluginConfig.oauth.authenticate({
|
|
30
|
+
req,
|
|
31
|
+
token: bearerToken
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
// With OAuth, the endpoint answers with a challenge that starts the client's sign-in
|
|
35
|
+
if (hasAuthorization && !req.user && !pluginConfig.oauth) {
|
|
26
36
|
throw new UnauthorizedError(req.t);
|
|
27
37
|
}
|
|
28
38
|
}
|
|
@@ -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,
|
|
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 // 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":["getAccessResults","UnauthorizedError","getPluginConfig","getAuthorizedMCP","overrideAccess","req","pluginConfig","config","payload","overrideGetAuthorizedMCP","headers","Headers","hasAuthorization","has","set","user","auth","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,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,oBAAo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CAAC;gBAAEC,MAAMN,KAAKO,cAAc;gBAAER;gBAAatB;YAAI;QAE1E,KAAK;YACH,OACE,CAACuB,KAAKI,IAAI,CAACC,MAAM,IAAK,MAAML,KAAKI,IAAI,CAACC,MAAM,CAAC;gBAAEC,MAAMN,KAAKQ,UAAU;gBAAET;gBAAatB;YAAI;QAE3F,KAAK;YACH,OAAO,CAACuB,KAAKS,MAAM,CAACJ,MAAM,IAAK,MAAML,KAAKS,MAAM,CAACJ,MAAM,CAAC;gBAAEN;gBAAatB;YAAI;QAC7E,KAAK;YACH,OAAO,CAACuB,KAAKU,QAAQ,CAACL,MAAM,IAAK,MAAML,KAAKU,QAAQ,CAACL,MAAM,CAAC;gBAAEN;gBAAatB;YAAI;QACjF,KAAK;YACH,OAAO,CAACuB,KAAKI,IAAI,CAACC,MAAM,IAAK,MAAML,KAAKI,IAAI,CAACC,MAAM,CAAC;gBAAEN;gBAAatB;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;
|
|
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,cAwEzB,CAAA"}
|
package/dist/endpoint/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { createMcpHandler, isLegacyRequest, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server';
|
|
1
|
+
import { createMcpHandler, isLegacyRequest, readRequestBody, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server';
|
|
2
2
|
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 { 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);
|
|
@@ -25,10 +26,22 @@ export const mcpEndpoint = async (req)=>{
|
|
|
25
26
|
overrideAccess,
|
|
26
27
|
req
|
|
27
28
|
});
|
|
29
|
+
if (pluginConfig.oauth && !req.user) {
|
|
30
|
+
return oauthChallenge({
|
|
31
|
+
req
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize;
|
|
28
35
|
// Payload augments the original web-standard Request in place.
|
|
29
36
|
const mcpRequest = req;
|
|
37
|
+
const parsedBody = await parseRequestBody({
|
|
38
|
+
maxRequestBodySize,
|
|
39
|
+
request: mcpRequest
|
|
40
|
+
});
|
|
30
41
|
// Keep the old JSON-only, stateless behavior because the SDK's 2025 fallback uses SSE.
|
|
31
|
-
if (await isLegacyRequest(mcpRequest
|
|
42
|
+
if (await isLegacyRequest(mcpRequest, parsedBody, {
|
|
43
|
+
maxRequestBodySize
|
|
44
|
+
})) {
|
|
32
45
|
const server = buildMcpServer({
|
|
33
46
|
authorizedMCP,
|
|
34
47
|
pluginConfig,
|
|
@@ -36,6 +49,7 @@ export const mcpEndpoint = async (req)=>{
|
|
|
36
49
|
});
|
|
37
50
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
38
51
|
enableJsonResponse: true,
|
|
52
|
+
maxRequestBodySize,
|
|
39
53
|
sessionIdGenerator: undefined
|
|
40
54
|
});
|
|
41
55
|
transport.onerror = (err)=>{
|
|
@@ -46,7 +60,9 @@ export const mcpEndpoint = async (req)=>{
|
|
|
46
60
|
};
|
|
47
61
|
try {
|
|
48
62
|
await server.connect(transport);
|
|
49
|
-
return await transport.handleRequest(mcpRequest
|
|
63
|
+
return await transport.handleRequest(mcpRequest, {
|
|
64
|
+
parsedBody
|
|
65
|
+
});
|
|
50
66
|
} finally{
|
|
51
67
|
await server.close().catch((err)=>{
|
|
52
68
|
req.payload.logger.error({
|
|
@@ -62,6 +78,7 @@ export const mcpEndpoint = async (req)=>{
|
|
|
62
78
|
req
|
|
63
79
|
}), {
|
|
64
80
|
legacy: 'reject',
|
|
81
|
+
maxRequestBodySize,
|
|
65
82
|
// SDK subscriptions always use SSE, so disable them to keep every response JSON-only.
|
|
66
83
|
maxSubscriptions: 0,
|
|
67
84
|
onerror: (err)=>{
|
|
@@ -73,7 +90,9 @@ export const mcpEndpoint = async (req)=>{
|
|
|
73
90
|
responseMode: 'json'
|
|
74
91
|
});
|
|
75
92
|
try {
|
|
76
|
-
return await handler.fetch(mcpRequest
|
|
93
|
+
return await handler.fetch(mcpRequest, {
|
|
94
|
+
parsedBody
|
|
95
|
+
});
|
|
77
96
|
} finally{
|
|
78
97
|
await handler.close().catch((err)=>{
|
|
79
98
|
req.payload.logger.error({
|
|
@@ -83,5 +102,21 @@ export const mcpEndpoint = async (req)=>{
|
|
|
83
102
|
});
|
|
84
103
|
}
|
|
85
104
|
};
|
|
105
|
+
/**
|
|
106
|
+
* Parses a POST body once so the era check and the SDK handler can share it. The SDK
|
|
107
|
+
* skips its size limit for a pre-parsed body, so this reads with the same limit. It reads
|
|
108
|
+
* a clone and returns `undefined` for any body the SDK should reject (too large, unreadable,
|
|
109
|
+
* or not JSON), leaving the original request for the SDK to read and answer.
|
|
110
|
+
*/ const parseRequestBody = async ({ maxRequestBodySize, request })=>{
|
|
111
|
+
if (request.method.toUpperCase() !== 'POST') {
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
const body = await readRequestBody(request.clone(), maxRequestBodySize);
|
|
116
|
+
return body.tooLarge ? undefined : JSON.parse(body.text);
|
|
117
|
+
} catch {
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
86
121
|
|
|
87
122
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/endpoint/index.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\n\nimport {\n createMcpHandler,\n isLegacyRequest,\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 // Payload augments the original web-standard Request in place.\n const mcpRequest = req as PayloadRequest & Request\n\n // Keep the old JSON-only, stateless behavior because the SDK's 2025 fallback uses SSE.\n if (await isLegacyRequest(mcpRequest)) {\n const server = buildMcpServer({ authorizedMCP, pluginConfig, req })\n const transport = new WebStandardStreamableHTTPServerTransport({\n enableJsonResponse: true,\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)\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 // 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)\n } finally {\n await handler.close().catch((err) => {\n req.payload.logger.error({ err, msg: 'Error closing modern MCP handler' })\n })\n }\n}\n"],"names":["createMcpHandler","isLegacyRequest","WebStandardStreamableHTTPServerTransport","APIError","buildMcpServer","getPluginConfig","getAuthorizedMCP","mcpEndpoint","req","url","payloadAPI","pluginConfig","config","payload","overrideAccessParam","URL","searchParams","get","process","env","NODE_ENV","overrideAccess","authorizedMCP","mcpRequest","server","transport","enableJsonResponse","sessionIdGenerator","undefined","onerror","err","logger","error","msg","connect","handleRequest","close","catch","handler","legacy","maxSubscriptions","responseMode","fetch"],"mappings":"AAEA,SACEA,gBAAgB,EAChBC,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;
|
|
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 { 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\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","oauthChallenge","mcpEndpoint","req","url","payloadAPI","pluginConfig","config","payload","overrideAccessParam","URL","searchParams","get","process","env","NODE_ENV","overrideAccess","authorizedMCP","oauth","user","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;AAC9C,SAASC,cAAc,QAAQ,aAAY;AAE3C,OAAO,MAAMC,cAA8B,OAAOC;IAChD,IAAI,CAACA,IAAIC,GAAG,EAAE;QACZ,MAAM,IAAIP,SAAS,uBAAuB;IAC5C;IAEAM,IAAIE,UAAU,GAAG;IAEjB,MAAMC,eAAeP,gBAAgB;QAAEQ,QAAQJ,IAAIK,OAAO,CAACD,MAAM;IAAC;IAClE,MAAME,sBAAsB,IAAIC,IA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ACF;IAEA,MAAMK,UAAU/C,iBAAiB,IAAMK,eAAe;YAAEmB;YAAeX;YAAcH;QAAI,IAAI;QAC3FsC,QAAQ;QACRrB;QACA,sFAAsF;QACtFsB,kBAAkB;QAClBX,SAAS,CAACC;YACR7B,IAAIK,OAAO,CAACyB,MAAM,CAACC,KAAK,CAAC;gBAAEF;gBAAKG,KAAK;YAAmC;QAC1E;QACAQ,cAAc;IAChB;IAEA,IAAI;QACF,OAAO,MAAMH,QAAQI,KAAK,CAACtB,YAAY;YAAEC;QAAW;IACtD,SAAU;QACR,MAAMiB,QAAQF,KAAK,GAAGC,KAAK,CAAC,CAACP;YAC3B7B,IAAIK,OAAO,CAACyB,MAAM,CAACC,KAAK,CAAC;gBAAEF;gBAAKG,KAAK;YAAmC;QAC1E;IACF;AACF,EAAC;AAED;;;;;CAKC,GACD,MAAMX,mBAAmB,OAAO,EAC9BJ,kBAAkB,EAClBK,OAAO,EAIR;IACC,IAAIA,QAAQoB,MAAM,CAACC,WAAW,OAAO,QAAQ;QAC3C,OAAOhB;IACT;IAEA,IAAI;QACF,MAAMiB,OAAO,MAAMpD,gBAAgB8B,QAAQuB,KAAK,IAAI5B;QACpD,OAAO2B,KAAKE,QAAQ,GAAGnB,YAAYoB,KAAKC,KAAK,CAACJ,KAAKK,IAAI;IACzD,EAAE,OAAM;QACN,OAAOtB;IACT;AACF"}
|
|
@@ -0,0 +1,27 @@
|
|
|
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
|
+
//# sourceMappingURL=oauth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../../src/endpoint/oauth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAU9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,EAAE,cACuB,CAAA;AAEpE;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,6BAA6B,WAC/B,OAAO,CAAC,eAAe,CAAC,GAAG,eAAe,eACnC,OAAO,KAAG,OAAO,CAAC,QAAQ,CACuB,CAAA;AAEnE;;;GAGG;AACH,eAAO,MAAM,cAAc,YAAa;IAAE,GAAG,EAAE,cAAc,CAAA;CAAE,KAAG,QAM/D,CAAA"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { bearerAuthChallengeResponse, OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server';
|
|
2
|
+
import { getPluginConfig } from '../utils/getPluginConfig.js';
|
|
3
|
+
/**
|
|
4
|
+
* Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.
|
|
5
|
+
* The OAuth challenge links here, so MCP clients find the authorization server without setup.
|
|
6
|
+
*/ export const oauthProtectedResourceEndpoint = (req)=>getMetadataResponse({
|
|
7
|
+
config: req.payload.config,
|
|
8
|
+
url: req.url
|
|
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
|
+
config: await config,
|
|
23
|
+
url: request.url
|
|
24
|
+
});
|
|
25
|
+
/**
|
|
26
|
+
* Answers an unauthenticated MCP request with a challenge linking to the protected resource
|
|
27
|
+
* metadata, which starts the client's OAuth flow.
|
|
28
|
+
*/ export const oauthChallenge = ({ req })=>bearerAuthChallengeResponse(new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')), {
|
|
29
|
+
resourceMetadataUrl: `${getMCPURL({
|
|
30
|
+
config: req.payload.config,
|
|
31
|
+
url: req.url
|
|
32
|
+
})}/oauth-protected-resource`
|
|
33
|
+
});
|
|
34
|
+
const getMCPURL = ({ config, url })=>new URL(`${config.routes.api}/mcp`, config.serverURL || url).href;
|
|
35
|
+
const getMetadataResponse = ({ config, url })=>{
|
|
36
|
+
const pluginConfig = getPluginConfig({
|
|
37
|
+
config
|
|
38
|
+
});
|
|
39
|
+
if (!pluginConfig.oauth) {
|
|
40
|
+
return new Response(null, {
|
|
41
|
+
status: 404
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return Response.json({
|
|
45
|
+
authorization_servers: pluginConfig.oauth.authorizationServers,
|
|
46
|
+
bearer_methods_supported: [
|
|
47
|
+
'header'
|
|
48
|
+
],
|
|
49
|
+
resource: pluginConfig.oauth.resource ?? getMCPURL({
|
|
50
|
+
config,
|
|
51
|
+
url
|
|
52
|
+
})
|
|
53
|
+
}, // Public document, readable by browser-based MCP clients on any origin
|
|
54
|
+
{
|
|
55
|
+
headers: {
|
|
56
|
+
'Access-Control-Allow-Origin': '*'
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=oauth.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/endpoint/oauth.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest, SanitizedConfig } from 'payload'\n\nimport {\n bearerAuthChallengeResponse,\n OAuthError,\n OAuthErrorCode,\n} from '@modelcontextprotocol/server'\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) =>\n getMetadataResponse({ config: req.payload.config, url: req.url! })\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({ config: await config, url: request.url })\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 bearerAuthChallengeResponse(\n new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')),\n {\n resourceMetadataUrl: `${getMCPURL({ config: req.payload.config, url: req.url! })}/oauth-protected-resource`,\n },\n )\n\nconst getMCPURL = ({ config, url }: { config: SanitizedConfig; url: string }): string =>\n new URL(`${config.routes.api}/mcp`, config.serverURL || url).href\n\nconst getMetadataResponse = ({\n config,\n url,\n}: {\n config: SanitizedConfig\n url: string\n}): Response => {\n const pluginConfig = getPluginConfig({ config })\n\n if (!pluginConfig.oauth) {\n return new Response(null, { status: 404 })\n }\n\n return Response.json(\n {\n authorization_servers: pluginConfig.oauth.authorizationServers,\n bearer_methods_supported: ['header'],\n resource: pluginConfig.oauth.resource ?? getMCPURL({ config, url }),\n },\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","getPluginConfig","oauthProtectedResourceEndpoint","req","getMetadataResponse","config","payload","url","oauthProtectedResourceHandler","request","oauthChallenge","InvalidToken","t","resourceMetadataUrl","getMCPURL","URL","routes","api","serverURL","href","pluginConfig","oauth","Response","status","json","authorization_servers","authorizationServers","bearer_methods_supported","resource","headers"],"mappings":"AAEA,SACEA,2BAA2B,EAC3BC,UAAU,EACVC,cAAc,QACT,+BAA8B;AAErC,SAASC,eAAe,QAAQ,8BAA6B;AAE7D;;;CAGC,GACD,OAAO,MAAMC,iCAAiD,CAACC,MAC7DC,oBAAoB;QAAEC,QAAQF,IAAIG,OAAO,CAACD,MAAM;QAAEE,KAAKJ,IAAII,GAAG;IAAE,GAAE;AAEpE;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,gCACX,CAACH,SACD,OAAOI,UACLL,oBAAoB;YAAEC,QAAQ,MAAMA;YAAQE,KAAKE,QAAQF,GAAG;QAAC,GAAE;AAEnE;;;CAGC,GACD,OAAO,MAAMG,iBAAiB,CAAC,EAAEP,GAAG,EAA2B,GAC7DL,4BACE,IAAIC,WAAWC,eAAeW,YAAY,EAAER,IAAIS,CAAC,CAAC,wBAClD;QACEC,qBAAqB,GAAGC,UAAU;YAAET,QAAQF,IAAIG,OAAO,CAACD,MAAM;YAAEE,KAAKJ,IAAII,GAAG;QAAE,GAAG,yBAAyB,CAAC;IAC7G,GACD;AAEH,MAAMO,YAAY,CAAC,EAAET,MAAM,EAAEE,GAAG,EAA4C,GAC1E,IAAIQ,IAAI,GAAGV,OAAOW,MAAM,CAACC,GAAG,CAAC,IAAI,CAAC,EAAEZ,OAAOa,SAAS,IAAIX,KAAKY,IAAI;AAEnE,MAAMf,sBAAsB,CAAC,EAC3BC,MAAM,EACNE,GAAG,EAIJ;IACC,MAAMa,eAAenB,gBAAgB;QAAEI;IAAO;IAE9C,IAAI,CAACe,aAAaC,KAAK,EAAE;QACvB,OAAO,IAAIC,SAAS,MAAM;YAAEC,QAAQ;QAAI;IAC1C;IAEA,OAAOD,SAASE,IAAI,CAClB;QACEC,uBAAuBL,aAAaC,KAAK,CAACK,oBAAoB;QAC9DC,0BAA0B;YAAC;SAAS;QACpCC,UAAUR,aAAaC,KAAK,CAACO,QAAQ,IAAId,UAAU;YAAET;YAAQE;QAAI;IACnE,GACA,uEAAuE;IACvE;QAAEsB,SAAS;YAAE,+BAA+B;QAAI;IAAE;AAEtD"}
|
package/dist/index.d.ts
CHANGED
|
@@ -10,5 +10,6 @@ declare module 'payload' {
|
|
|
10
10
|
}
|
|
11
11
|
export type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig };
|
|
12
12
|
export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js';
|
|
13
|
+
export { oauthProtectedResourceHandler } from './endpoint/oauth.js';
|
|
13
14
|
export declare const mcpPlugin: (options: MCPPluginConfig) => import("payload").Plugin;
|
|
14
15
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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;
|
|
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;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,wDAsCpB,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,
|
|
@@ -40,6 +42,11 @@ export const mcpPlugin = definePlugin({
|
|
|
40
42
|
}),
|
|
41
43
|
method: 'get',
|
|
42
44
|
path: '/mcp'
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
handler: oauthProtectedResourceEndpoint,
|
|
48
|
+
method: 'get',
|
|
49
|
+
path: '/mcp/oauth-protected-resource'
|
|
43
50
|
}
|
|
44
51
|
]
|
|
45
52
|
};
|
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;
|
|
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}\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.\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 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","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;AAc9D,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,uDAAuD;gBACvD;oBAAEC,SAASpB;oBAAaqB,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;gBACA;oBACEF,SAASnB;oBACToB,QAAQ;oBACRC,MAAM;gBACR;aACD;QACH;IACF;AACF,GAAE"}
|
|
@@ -9,7 +9,7 @@ import type { AuthorizedMCP, SanitizedMCPPluginConfig } from '../types.js';
|
|
|
9
9
|
*
|
|
10
10
|
* `req` is the request context handlers see. For HTTP it's the live
|
|
11
11
|
* `PayloadRequest` derived from the incoming HTTP request; for stdio it's a
|
|
12
|
-
* synthesized one built via `
|
|
12
|
+
* synthesized one built via `createPayloadRequest`.
|
|
13
13
|
*/
|
|
14
14
|
export declare const buildMcpServer: ({ authorizedMCP, pluginConfig, req, }: {
|
|
15
15
|
authorizedMCP: AuthorizedMCP;
|
|
@@ -10,7 +10,7 @@ import { toStandardSchema } from '../utils/toStandardSchema.js';
|
|
|
10
10
|
*
|
|
11
11
|
* `req` is the request context handlers see. For HTTP it's the live
|
|
12
12
|
* `PayloadRequest` derived from the incoming HTTP request; for stdio it's a
|
|
13
|
-
* synthesized one built via `
|
|
13
|
+
* synthesized one built via `createPayloadRequest`.
|
|
14
14
|
*/ export const buildMcpServer = ({ authorizedMCP, pluginConfig, req })=>{
|
|
15
15
|
z.config(z.locales.en());
|
|
16
16
|
const serverOptions = pluginConfig.mcp?.serverOptions || {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/mcp/buildMcpServer.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { McpServer, type ServerContext } from '@modelcontextprotocol/server'\nimport { APIError, strictObject, z } from 'payload'\n\nimport type {\n AuthorizedMCP,\n CollectionMCPItem,\n GlobalMCPItem,\n JsonSchemaType,\n MCPResponseOverride,\n MCPToolResponse,\n SanitizedMCPPluginConfig,\n ToolInputSchema,\n} from '../types.js'\n\nimport { getLogger } from '../utils/getLogger.js'\nimport { toStandardSchema } from '../utils/toStandardSchema.js'\n\n/**\n * Serving-entry-agnostic core: registers every authorized MCP item onto a fresh\n * `McpServer` and returns it. The HTTP and stdio entry point callers provide fresh\n * instances from this builder while they own the transport and protocol-era\n * decision.\n *\n * `req` is the request context handlers see. For HTTP it's the live\n * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a\n * synthesized one built via `createLocalReq`.\n */\nexport const buildMcpServer = ({\n authorizedMCP,\n pluginConfig,\n req,\n}: {\n authorizedMCP: AuthorizedMCP\n pluginConfig: SanitizedMCPPluginConfig\n req: PayloadRequest\n}): McpServer => {\n z.config(z.locales.en())\n\n const serverOptions = pluginConfig.mcp?.serverOptions || {}\n const server = new McpServer(\n { name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },\n serverOptions.options,\n )\n\n const logger = getLogger({ payload: req.payload })\n\n /**\n * Wrap a tool handler's response with the tool's `overrideResponse`, then\n * strip the internal `doc` field so it doesn't leak onto the wire.\n */\n const finalizeToolResponse = async ({\n input,\n overrideResponse,\n response,\n toolName,\n }: {\n input: unknown\n overrideResponse?: MCPResponseOverride\n response: MCPToolResponse\n toolName: string\n }): Promise<MCPToolResponse> => {\n let overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response\n for (const hook of pluginConfig.hooks?.afterToolCall ?? []) {\n overridden = await hook({ input, req, response: overridden, toolName })\n }\n const { doc: _doc, ...rest } = overridden\n return rest\n }\n\n /**\n * Runs a collection/global tool call:\n * - reads `slug` from the input\n * - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug\n * - runs the tool handler and finalizes its response\n */\n const callEntityTool = async ({\n input,\n item,\n serverContext,\n }: {\n input: unknown\n item: CollectionMCPItem | GlobalMCPItem\n serverContext: ServerContext\n }): Promise<MCPToolResponse> => {\n const entity = item.type === 'collectionTool' ? 'collection' : 'global'\n const toolInput = (input ?? {}) as Record<string, unknown>\n const slug = toolInput.slug as string | undefined\n\n if (!slug) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: \"${item.mcpName}\" requires slug. Use getConfigInfo to inspect ${entity} slugs.`,\n },\n ],\n isError: true,\n }\n }\n\n const match = authorizedMCP.items.find(\n (candidate): candidate is CollectionMCPItem | GlobalMCPItem =>\n candidate.type === item.type &&\n candidate.mcpName === item.mcpName &&\n (candidate.type === 'collectionTool'\n ? candidate.collectionSlug === slug\n : candidate.type === 'globalTool' && candidate.globalSlug === slug),\n )\n\n if (!match) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: MCP access to \"${item.mcpName}\" is not enabled for ${entity} \"${slug}\"`,\n },\n ],\n isError: true,\n }\n }\n\n const handlerArgs = {\n authorizedMCP,\n input: toolInput,\n req,\n serverContext,\n }\n const response = await (match.type === 'collectionTool'\n ? match.tool.handler({ ...handlerArgs, slug })\n : match.tool.handler({ ...handlerArgs, slug }))\n\n return finalizeToolResponse({\n input: toolInput,\n overrideResponse: match.tool.overrideResponse,\n response,\n toolName: match.mcpName,\n })\n }\n\n try {\n const registeredEntityTools = new Set<string>()\n\n for (const item of authorizedMCP.items) {\n switch (item.type) {\n case 'collectionTool':\n case 'globalTool': {\n if (registeredEntityTools.has(item.mcpName)) {\n break\n }\n registeredEntityTools.add(item.mcpName)\n\n const inputSchema = withSlugInput({ input: item.tool.input })\n\n server.registerTool(\n item.mcpName,\n {\n annotations: item.tool.annotations,\n description: item.tool.description,\n inputSchema: toStandardSchema(inputSchema),\n },\n async (input: unknown, ctx: ServerContext) =>\n callEntityTool({ input, item, serverContext: ctx }),\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n case 'prompt': {\n const prompt = item.prompt\n server.registerPrompt(\n item.mcpName,\n {\n argsSchema: prompt.argsSchema ? toStandardSchema(prompt.argsSchema) : undefined,\n description: prompt.description,\n title: prompt.title,\n },\n async (input: unknown, ctx: ServerContext) =>\n prompt.handler({\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n )\n logger.info(`✅ Prompt: ${prompt.title} Registered.`)\n break\n }\n case 'resource': {\n const resource = item.resource\n server.registerResource(\n item.mcpName,\n // @ts-expect-error - Overload type ambiguity (string OR ResourceTemplate is valid)\n resource.uri,\n {\n description: resource.description,\n mimeType: resource.mimeType,\n title: resource.title,\n },\n // Static URIs call (uri, ctx); ResourceTemplates call (uri, params, ctx).\n // The rest-params shape lets us collect either signature uniformly.\n async (...sdkArgs: unknown[]) => {\n const ctx = sdkArgs[sdkArgs.length - 1] as ServerContext\n const uri = sdkArgs[0] as URL\n const params = (sdkArgs.length > 2 ? sdkArgs[1] : {}) as Record<string, string>\n return resource.handler({ params, req, serverContext: ctx, uri })\n },\n )\n logger.info(`✅ Resource: ${resource.title} Registered.`)\n break\n }\n case 'tool': {\n const tool = item.tool\n server.registerTool(\n item.mcpName,\n {\n annotations: tool.annotations,\n description: tool.description,\n inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,\n },\n async (input: unknown, ctx: ServerContext) => {\n const toolInput = (input ?? {}) as Record<string, unknown>\n const response = await tool.handler({\n authorizedMCP,\n input: toolInput,\n req,\n serverContext: ctx,\n })\n return finalizeToolResponse({\n input: toolInput,\n overrideResponse: tool.overrideResponse,\n response,\n toolName: item.mcpName,\n })\n },\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n }\n }\n } catch (error) {\n throw new APIError(`Error initializing MCP handler: ${String(error)}`, 500)\n }\n\n return server\n}\n\nconst withSlugInput = ({ input }: { input?: ToolInputSchema }): ToolInputSchema => {\n const description = 'The target slug.'\n const slugSchema = z.string().check(z.describe(description))\n\n if (!input) {\n return strictObject({ slug: slugSchema }) as unknown as ToolInputSchema\n }\n\n if (typeof input === 'object' && input !== null && '~standard' in input) {\n const schema = input['~standard'].jsonSchema.input({ target: 'draft-2020-12' })\n const properties = schema.properties as Record<string, unknown> | undefined\n\n if (properties?.slug) {\n return input\n }\n\n return addSlugToJSONSchema({ description, schema: schema as JsonSchemaType })\n }\n\n return addSlugToJSONSchema({ description, schema: input })\n}\n\nconst addSlugToJSONSchema = ({\n description,\n schema,\n}: {\n description: string\n schema: JsonSchemaType\n}): JsonSchemaType => {\n const objectSchema = schema as {\n properties?: Record<string, JsonSchemaType>\n required?: string[]\n } & JsonSchemaType\n\n return {\n ...objectSchema,\n type: 'object',\n properties: {\n ...objectSchema.properties,\n slug: {\n type: 'string',\n description,\n },\n },\n required: Array.from(new Set(['slug', ...(objectSchema.required ?? [])])),\n }\n}\n"],"names":["McpServer","APIError","strictObject","z","getLogger","toStandardSchema","buildMcpServer","authorizedMCP","pluginConfig","req","config","locales","en","serverOptions","mcp","server","name","version","serverInfo","options","logger","payload","finalizeToolResponse","input","overrideResponse","response","toolName","overridden","doc","hook","hooks","afterToolCall","_doc","rest","callEntityTool","item","serverContext","entity","type","toolInput","slug","content","text","mcpName","isError","match","items","find","candidate","collectionSlug","globalSlug","handlerArgs","tool","handler","registeredEntityTools","Set","has","add","inputSchema","withSlugInput","registerTool","annotations","description","ctx","info","prompt","registerPrompt","argsSchema","undefined","title","resource","registerResource","uri","mimeType","sdkArgs","length","params","error","String","slugSchema","string","check","describe","schema","jsonSchema","target","properties","addSlugToJSONSchema","objectSchema","required","Array","from"],"mappings":"AAEA,SAASA,SAAS,QAA4B,+BAA8B;AAC5E,SAASC,QAAQ,EAAEC,YAAY,EAAEC,CAAC,QAAQ,UAAS;AAanD,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,gBAAgB,QAAQ,+BAA8B;AAE/D;;;;;;;;;CASC,GACD,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,aAAa,EACbC,YAAY,EACZC,GAAG,EAKJ;IACCN,EAAEO,MAAM,CAACP,EAAEQ,OAAO,CAACC,EAAE;IAErB,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QAEpC,IAAIA,YAAY9C,MAAM;YACpB,OAAOjB;QACT;QAEA,OAAOgE,oBAAoB;YAAEzB;YAAaqB,QAAQA;QAAyB;IAC7E;IAEA,OAAOI,oBAAoB;QAAEzB;QAAaqB,QAAQ5D;IAAM;AAC1D;AAEA,MAAMgE,sBAAsB,CAAC,EAC3BzB,WAAW,EACXqB,MAAM,EAIP;IACC,MAAMK,eAAeL;IAKrB,OAAO;QACL,GAAGK,YAAY;QACflD,MAAM;QACNgD,YAAY;YACV,GAAGE,aAAaF,UAAU;YAC1B9C,MAAM;gBACJF,MAAM;gBACNwB;YACF;QACF;QACA2B,UAAUC,MAAMC,IAAI,CAAC,IAAIpC,IAAI;YAAC;eAAYiC,aAAaC,QAAQ,IAAI,EAAE;SAAE;IACzE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/mcp/buildMcpServer.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { McpServer, type ServerContext } from '@modelcontextprotocol/server'\nimport { APIError, strictObject, z } from 'payload'\n\nimport type {\n AuthorizedMCP,\n CollectionMCPItem,\n GlobalMCPItem,\n JsonSchemaType,\n MCPResponseOverride,\n MCPToolResponse,\n SanitizedMCPPluginConfig,\n ToolInputSchema,\n} from '../types.js'\n\nimport { getLogger } from '../utils/getLogger.js'\nimport { toStandardSchema } from '../utils/toStandardSchema.js'\n\n/**\n * Serving-entry-agnostic core: registers every authorized MCP item onto a fresh\n * `McpServer` and returns it. The HTTP and stdio entry point callers provide fresh\n * instances from this builder while they own the transport and protocol-era\n * decision.\n *\n * `req` is the request context handlers see. For HTTP it's the live\n * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a\n * synthesized one built via `createPayloadRequest`.\n */\nexport const buildMcpServer = ({\n authorizedMCP,\n pluginConfig,\n req,\n}: {\n authorizedMCP: AuthorizedMCP\n pluginConfig: SanitizedMCPPluginConfig\n req: PayloadRequest\n}): McpServer => {\n z.config(z.locales.en())\n\n const serverOptions = pluginConfig.mcp?.serverOptions || {}\n const server = new McpServer(\n { name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },\n serverOptions.options,\n )\n\n const logger = getLogger({ payload: req.payload })\n\n /**\n * Wrap a tool handler's response with the tool's `overrideResponse`, then\n * strip the internal `doc` field so it doesn't leak onto the wire.\n */\n const finalizeToolResponse = async ({\n input,\n overrideResponse,\n response,\n toolName,\n }: {\n input: unknown\n overrideResponse?: MCPResponseOverride\n response: MCPToolResponse\n toolName: string\n }): Promise<MCPToolResponse> => {\n let overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response\n for (const hook of pluginConfig.hooks?.afterToolCall ?? []) {\n overridden = await hook({ input, req, response: overridden, toolName })\n }\n const { doc: _doc, ...rest } = overridden\n return rest\n }\n\n /**\n * Runs a collection/global tool call:\n * - reads `slug` from the input\n * - runs access control: errors if `authorizedMCP.items` has no entry for this tool + slug\n * - runs the tool handler and finalizes its response\n */\n const callEntityTool = async ({\n input,\n item,\n serverContext,\n }: {\n input: unknown\n item: CollectionMCPItem | GlobalMCPItem\n serverContext: ServerContext\n }): Promise<MCPToolResponse> => {\n const entity = item.type === 'collectionTool' ? 'collection' : 'global'\n const toolInput = (input ?? {}) as Record<string, unknown>\n const slug = toolInput.slug as string | undefined\n\n if (!slug) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: \"${item.mcpName}\" requires slug. Use getConfigInfo to inspect ${entity} slugs.`,\n },\n ],\n isError: true,\n }\n }\n\n const match = authorizedMCP.items.find(\n (candidate): candidate is CollectionMCPItem | GlobalMCPItem =>\n candidate.type === item.type &&\n candidate.mcpName === item.mcpName &&\n (candidate.type === 'collectionTool'\n ? candidate.collectionSlug === slug\n : candidate.type === 'globalTool' && candidate.globalSlug === slug),\n )\n\n if (!match) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: MCP access to \"${item.mcpName}\" is not enabled for ${entity} \"${slug}\"`,\n },\n ],\n isError: true,\n }\n }\n\n const handlerArgs = {\n authorizedMCP,\n input: toolInput,\n req,\n serverContext,\n }\n const response = await (match.type === 'collectionTool'\n ? match.tool.handler({ ...handlerArgs, slug })\n : match.tool.handler({ ...handlerArgs, slug }))\n\n return finalizeToolResponse({\n input: toolInput,\n overrideResponse: match.tool.overrideResponse,\n response,\n toolName: match.mcpName,\n })\n }\n\n try {\n const registeredEntityTools = new Set<string>()\n\n for (const item of authorizedMCP.items) {\n switch (item.type) {\n case 'collectionTool':\n case 'globalTool': {\n if (registeredEntityTools.has(item.mcpName)) {\n break\n }\n registeredEntityTools.add(item.mcpName)\n\n const inputSchema = withSlugInput({ input: item.tool.input })\n\n server.registerTool(\n item.mcpName,\n {\n annotations: item.tool.annotations,\n description: item.tool.description,\n inputSchema: toStandardSchema(inputSchema),\n },\n async (input: unknown, ctx: ServerContext) =>\n callEntityTool({ input, item, serverContext: ctx }),\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n case 'prompt': {\n const prompt = item.prompt\n server.registerPrompt(\n item.mcpName,\n {\n argsSchema: prompt.argsSchema ? toStandardSchema(prompt.argsSchema) : undefined,\n description: prompt.description,\n title: prompt.title,\n },\n async (input: unknown, ctx: ServerContext) =>\n prompt.handler({\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n )\n logger.info(`✅ Prompt: ${prompt.title} Registered.`)\n break\n }\n case 'resource': {\n const resource = item.resource\n server.registerResource(\n item.mcpName,\n // @ts-expect-error - Overload type ambiguity (string OR ResourceTemplate is valid)\n resource.uri,\n {\n description: resource.description,\n mimeType: resource.mimeType,\n title: resource.title,\n },\n // Static URIs call (uri, ctx); ResourceTemplates call (uri, params, ctx).\n // The rest-params shape lets us collect either signature uniformly.\n async (...sdkArgs: unknown[]) => {\n const ctx = sdkArgs[sdkArgs.length - 1] as ServerContext\n const uri = sdkArgs[0] as URL\n const params = (sdkArgs.length > 2 ? sdkArgs[1] : {}) as Record<string, string>\n return resource.handler({ params, req, serverContext: ctx, uri })\n },\n )\n logger.info(`✅ Resource: ${resource.title} Registered.`)\n break\n }\n case 'tool': {\n const tool = item.tool\n server.registerTool(\n item.mcpName,\n {\n annotations: tool.annotations,\n description: tool.description,\n inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,\n },\n async (input: unknown, ctx: ServerContext) => {\n const toolInput = (input ?? {}) as Record<string, unknown>\n const response = await tool.handler({\n authorizedMCP,\n input: toolInput,\n req,\n serverContext: ctx,\n })\n return finalizeToolResponse({\n input: toolInput,\n overrideResponse: tool.overrideResponse,\n response,\n toolName: item.mcpName,\n })\n },\n )\n logger.info(`✅ Tool: ${item.mcpName} Registered.`)\n break\n }\n }\n }\n } catch (error) {\n throw new APIError(`Error initializing MCP handler: ${String(error)}`, 500)\n }\n\n return server\n}\n\nconst withSlugInput = ({ input }: { input?: ToolInputSchema }): ToolInputSchema => {\n const description = 'The target slug.'\n const slugSchema = z.string().check(z.describe(description))\n\n if (!input) {\n return strictObject({ slug: slugSchema }) as unknown as ToolInputSchema\n }\n\n if (typeof input === 'object' && input !== null && '~standard' in input) {\n const schema = input['~standard'].jsonSchema.input({ target: 'draft-2020-12' })\n const properties = schema.properties as Record<string, unknown> | undefined\n\n if (properties?.slug) {\n return input\n }\n\n return addSlugToJSONSchema({ description, schema: schema as JsonSchemaType })\n }\n\n return addSlugToJSONSchema({ description, schema: input })\n}\n\nconst addSlugToJSONSchema = ({\n description,\n schema,\n}: {\n description: string\n schema: JsonSchemaType\n}): JsonSchemaType => {\n const objectSchema = schema as {\n properties?: Record<string, JsonSchemaType>\n required?: string[]\n } & JsonSchemaType\n\n return {\n ...objectSchema,\n type: 'object',\n properties: {\n ...objectSchema.properties,\n slug: {\n type: 'string',\n description,\n },\n },\n required: Array.from(new Set(['slug', ...(objectSchema.required ?? [])])),\n }\n}\n"],"names":["McpServer","APIError","strictObject","z","getLogger","toStandardSchema","buildMcpServer","authorizedMCP","pluginConfig","req","config","locales","en","serverOptions","mcp","server","name","version","serverInfo","options","logger","payload","finalizeToolResponse","input","overrideResponse","response","toolName","overridden","doc","hook","hooks","afterToolCall","_doc","rest","callEntityTool","item","serverContext","entity","type","toolInput","slug","content","text","mcpName","isError","match","items","find","candidate","collectionSlug","globalSlug","handlerArgs","tool","handler","registeredEntityTools","Set","has","add","inputSchema","withSlugInput","registerTool","annotations","description","ctx","info","prompt","registerPrompt","argsSchema","undefined","title","resource","registerResource","uri","mimeType","sdkArgs","length","params","error","String","slugSchema","string","check","describe","schema","jsonSchema","target","properties","addSlugToJSONSchema","objectSchema","required","Array","from"],"mappings":"AAEA,SAASA,SAAS,QAA4B,+BAA8B;AAC5E,SAASC,QAAQ,EAAEC,YAAY,EAAEC,CAAC,QAAQ,UAAS;AAanD,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,gBAAgB,QAAQ,+BAA8B;AAE/D;;;;;;;;;CASC,GACD,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,aAAa,EACbC,YAAY,EACZC,GAAG,EAKJ;IACCN,EAAEO,MAAM,CAACP,EAAEQ,OAAO,CAACC,EAAE;IAErB,MAAMC,gBAAgBL,aAAaM,GAAG,EAAED,iBAAiB,CAAC;IAC1D,MAAME,SAAS,IAAIf,UACjB;QAAEgB,MAAM;QAAsBC,SAAS;QAAS,GAAGJ,cAAcK,UAAU;IAAC,GAC5EL,cAAcM,OAAO;IAGvB,MAAMC,SAAShB,UAAU;QAAEiB,SAASZ,IAAIY,OAAO;IAAC;IAEhD;;;GAGC,GACD,MAAMC,uBAAuB,OAAO,EAClCC,KAAK,EACLC,gBAAgB,EAChBC,QAAQ,EACRC,QAAQ,EAMT;QACC,IAAIC,aAAaH,mBAAmBC,UAAUA,SAASG,GAAG,IAAI,CAAC,GAAGnB,QAAQgB;QAC1E,KAAK,MAAMI,QAAQrB,aAAasB,KAAK,EAAEC,iBAAiB,EAAE,CAAE;YAC1DJ,aAAa,MAAME,KAAK;gBAAEN;gBAAOd;gBAAKgB,UAAUE;gBAAYD;YAAS;QACvE;QACA,MAAM,EAAEE,KAAKI,IA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ts"],"names":[],"mappings":"AAkCA,eAAO,MAAM,kBAAkB,
|
|
1
|
+
{"version":3,"file":"authTools.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"names":[],"mappings":"AAkCA,eAAO,MAAM,kBAAkB,4CA0D7B,CAAA;AAEF,eAAO,MAAM,4BAA4B,4CAmCvC,CAAA;AAEF,eAAO,MAAM,mBAAmB,4CAuC9B,CAAA;AAEF,eAAO,MAAM,2BAA2B,4CAmCtC,CAAA;AAEF,eAAO,MAAM,oBAAoB,4CAmC/B,CAAA;AAEF,eAAO,MAAM,oBAAoB,4CAiC/B,CAAA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createPayloadRequest, strictObject, z } from 'payload';
|
|
2
2
|
import { defaultAccess } from '../../../defaultAccess.js';
|
|
3
3
|
import { defineCollectionTool } from '../../../defineTool.js';
|
|
4
4
|
import { getLogger } from '../../../utils/getLogger.js';
|
|
@@ -43,11 +43,12 @@ export const authCollectionTool = defineCollectionTool({
|
|
|
43
43
|
if (input.headers) {
|
|
44
44
|
authHeaders = new Headers(input.headers);
|
|
45
45
|
}
|
|
46
|
-
const authReq = await
|
|
46
|
+
const authReq = await createPayloadRequest({
|
|
47
|
+
payload: req.payload,
|
|
47
48
|
req: {
|
|
48
49
|
headers: authHeaders
|
|
49
50
|
}
|
|
50
|
-
}
|
|
51
|
+
});
|
|
51
52
|
const result = await req.payload.auth({
|
|
52
53
|
headers: authHeaders,
|
|
53
54
|
req: authReq
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"sourcesContent":["import { createLocalReq, strictObject, z } from 'payload'\n\nimport type { MCPToolResponse } from '../../../types.js'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\n/**\n * Auth tools surfaced under `collections.<auth-collection>.tools`. Opt-in: they\n * default off (an LLM with `login` access can probe passwords; not something\n * to expose by default). Enable in plugin config via `tools: { login: true }`\n * (or `{ description: '...' }`).\n *\n * `auth` (check current token) doesn't actually depend on the collection at\n * runtime — `payload.auth({ headers })` is global — but it's grouped under the\n * users collection so all auth-shaped tools live in one place.\n */\n\nconst emailSchema = z.email().check(z.describe('The user email address.'))\n\nconst wrapError =\n (name: string) =>\n ({ slug, message }: { message: string; slug: string }): MCPToolResponse => {\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error in ${name}** on ${slug}: ${message}`,\n },\n ],\n }\n }\n\nexport const authCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Check Auth Status',\n },\n description: 'Checks authentication status for the current user.',\n input: strictObject({\n headers: z\n .optional(z.record(z.string(), z.string()))\n .check(z.describe('Custom headers to send with the authentication request.')),\n }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n let authHeaders = new Headers()\n if (input.headers) {\n authHeaders = new Headers(input.headers)\n }\n const authReq = await createLocalReq({ req: { headers: authHeaders } }, req.payload)\n const result = await req.payload.auth({ headers: authHeaders, req: authReq })\n\n if (result.user) {\n const authenticatedUser = result.user\n // Auth strategies read users with trusted Local API access. Re-read the user with the MCP\n // caller's access level before returning it to the client.\n const user = await req.payload.findByID({\n id: authenticatedUser.id,\n collection: authenticatedUser.collection,\n overrideAccess: authorizedMCP.overrideAccess,\n req: authReq,\n })\n result.user = {\n ...user,\n _sid: authenticatedUser._sid,\n _strategy: authenticatedUser._strategy,\n collection: authenticatedUser.collection,\n }\n }\n return {\n content: [\n {\n type: 'text',\n text: `# Authentication Status\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in auth tool on ${slug}: ${errorMessage}`)\n return wrapError('auth')({ slug, message: errorMessage })\n }\n})\n\nexport const forgotPasswordCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n readOnlyHint: false,\n title: 'Forgot Password',\n },\n description: 'Sends a password reset email to a user.',\n input: strictObject({\n email: emailSchema,\n }),\n}).handler(async ({ slug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n await req.payload.forgotPassword({\n collection: slug,\n data: { email: input.email },\n disableEmail: false,\n overrideAccess: false,\n req,\n })\n return {\n content: [\n {\n type: 'text',\n text: 'If an account matches that email, password reset instructions have been sent.',\n },\n ],\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in forgotPassword tool on ${slug}: ${errorMessage}`)\n return wrapError('forgotPassword')({ slug, message: errorMessage })\n }\n})\n\nexport const loginCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'User Login',\n },\n description: 'Authenticates a user with email and password.',\n input: strictObject({\n depth: z\n ._default(z.int().check(z.minimum(0), z.maximum(10)), 0)\n .check(z.describe('Depth of population for relationships.')),\n email: emailSchema,\n password: z.string().check(z.describe('The user password.')),\n }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.login({\n collection: slug,\n data: { email: input.email, password: input.password },\n depth: input.depth,\n overrideAccess: authorizedMCP.overrideAccess,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Login Successful\\n\\n**User:** ${input.email}\\n**Collection:** ${slug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in login tool on ${slug}: ${errorMessage}`)\n return wrapError('login')({ slug, message: errorMessage })\n }\n})\n\nexport const resetPasswordCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Reset Password',\n },\n description: 'Resets a user password with a reset token.',\n input: strictObject({\n password: z.string().check(z.describe('The new password for the user.')),\n token: z.string().check(z.describe('The password reset token sent to the user email.')),\n }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.resetPassword({\n collection: slug,\n data: { password: input.password, token: input.token },\n overrideAccess: authorizedMCP.overrideAccess,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Password Reset Successful\\n\\n**Collection:** ${slug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in resetPassword tool on ${slug}: ${errorMessage}`)\n return wrapError('resetPassword')({ slug, message: errorMessage })\n }\n})\n\nexport const unlockCollectionTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.unlock),\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Unlock Account',\n },\n description: 'Unlocks a user account that has been locked due to failed login attempts.',\n input: strictObject({ email: emailSchema }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.unlock({\n collection: slug,\n data: { email: input.email },\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Account Unlocked\\n\\n**Collection:** ${slug}\\n**Email:** ${input.email}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in unlock tool on ${slug}: ${errorMessage}`)\n return wrapError('unlock')({ slug, message: errorMessage })\n }\n})\n\nexport const verifyCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Email Verification',\n },\n description: 'Verifies a user email with a verification token.',\n input: strictObject({\n token: z.string().check(z.describe('The verification token sent to the user email.')),\n }),\n}).handler(async ({ slug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.verifyEmail({\n collection: slug,\n token: input.token,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Email Verification Successful\\n\\n**Collection:** ${slug}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in verify tool on ${slug}: ${errorMessage}`)\n return wrapError('verify')({ slug, message: errorMessage })\n }\n})\n"],"names":["createLocalReq","strictObject","z","defaultAccess","defineCollectionTool","getLogger","emailSchema","email","check","describe","wrapError","name","slug","message","content","type","text","authCollectionTool","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","headers","optional","record","string","handler","authorizedMCP","req","logger","payload","authHeaders","Headers","authReq","result","auth","user","authenticatedUser","findByID","id","collection","overrideAccess","_sid","_strategy","JSON","stringify","doc","error","errorMessage","Error","forgotPasswordCollectionTool","forgotPassword","data","disableEmail","loginCollectionTool","depth","_default","int","minimum","maximum","password","login","resetPasswordCollectionTool","token","resetPassword","unlockCollectionTool","access","args","Boolean","permissions","collections","unlock","verifyCollectionTool","verifyEmail"],"mappings":"AAAA,SAASA,cAAc,EAAEC,YAAY,EAAEC,CAAC,QAAQ,UAAS;AAIzD,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD;;;;;;;;;CASC,GAED,MAA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IACAC,aAAa;IACbC,OAAOxB,aAAa;QAClBkE,OAAOjE,EAAE2B,MAAM,GAAGrB,KAAK,CAACN,EAAEO,QAAQ,CAAC;IACrC;AACF,GAAGqB,OAAO,CAAC,OAAO,EAAElB,IAAI,EAAEa,KAAK,EAAEO,GAAG,EAAE;IACpC,MAAMC,SAAS5B,UAAU;QAAE6B,SAASF,IAAIE,OAAO;IAAC;IAChD,IAAI;QACF,MAAMI,SAAS,MAAMN,IAAIE,OAAO,CAAC2C,WAAW,CAAC;YAC3CjC,YAAYhC;YACZuD,OAAO1C,MAAM0C,KAAK;QACpB;QACA,OAAO;YACLrD,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,mDAAmD,EAAEJ,KAAK,cAAc,EAAE0B,SAAS,YAAY,UAAU;gBAClH;aACD;YACDY,KAAK;gBAAEZ;YAAO;QAChB;IACF,EAAE,OAAOa,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMtC,OAAO,GAAG;QAC9DoB,OAAOkB,KAAK,CAAC,CAAC,wBAAwB,EAAEvC,KAAK,EAAE,EAAEwC,cAAc;QAC/D,OAAO1C,UAAU,UAAU;YAAEE;YAAMC,SAASuC;QAAa;IAC3D;AACF,GAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/collections/authTools.ts"],"sourcesContent":["import { createPayloadRequest, strictObject, z } from 'payload'\n\nimport type { MCPToolResponse } from '../../../types.js'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\n/**\n * Auth tools surfaced under `collections.<auth-collection>.tools`. Opt-in: they\n * default off (an LLM with `login` access can probe passwords; not something\n * to expose by default). Enable in plugin config via `tools: { login: true }`\n * (or `{ description: '...' }`).\n *\n * `auth` (check current token) doesn't actually depend on the collection at\n * runtime — `payload.auth({ headers })` is global — but it's grouped under the\n * users collection so all auth-shaped tools live in one place.\n */\n\nconst emailSchema = z.email().check(z.describe('The user email address.'))\n\nconst wrapError =\n (name: string) =>\n ({ slug, message }: { message: string; slug: string }): MCPToolResponse => {\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error in ${name}** on ${slug}: ${message}`,\n },\n ],\n }\n }\n\nexport const authCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Check Auth Status',\n },\n description: 'Checks authentication status for the current user.',\n input: strictObject({\n headers: z\n .optional(z.record(z.string(), z.string()))\n .check(z.describe('Custom headers to send with the authentication request.')),\n }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n let authHeaders = new Headers()\n if (input.headers) {\n authHeaders = new Headers(input.headers)\n }\n const authReq = await createPayloadRequest({\n payload: req.payload,\n req: { headers: authHeaders },\n })\n const result = await req.payload.auth({ headers: authHeaders, req: authReq })\n\n if (result.user) {\n const authenticatedUser = result.user\n // Auth strategies read users with trusted Local API access. Re-read the user with the MCP\n // caller's access level before returning it to the client.\n const user = await req.payload.findByID({\n id: authenticatedUser.id,\n collection: authenticatedUser.collection,\n overrideAccess: authorizedMCP.overrideAccess,\n req: authReq,\n })\n result.user = {\n ...user,\n _sid: authenticatedUser._sid,\n _strategy: authenticatedUser._strategy,\n collection: authenticatedUser.collection,\n }\n }\n return {\n content: [\n {\n type: 'text',\n text: `# Authentication Status\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in auth tool on ${slug}: ${errorMessage}`)\n return wrapError('auth')({ slug, message: errorMessage })\n }\n})\n\nexport const forgotPasswordCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n readOnlyHint: false,\n title: 'Forgot Password',\n },\n description: 'Sends a password reset email to a user.',\n input: strictObject({\n email: emailSchema,\n }),\n}).handler(async ({ slug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n await req.payload.forgotPassword({\n collection: slug,\n data: { email: input.email },\n disableEmail: false,\n overrideAccess: false,\n req,\n })\n return {\n content: [\n {\n type: 'text',\n text: 'If an account matches that email, password reset instructions have been sent.',\n },\n ],\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in forgotPassword tool on ${slug}: ${errorMessage}`)\n return wrapError('forgotPassword')({ slug, message: errorMessage })\n }\n})\n\nexport const loginCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'User Login',\n },\n description: 'Authenticates a user with email and password.',\n input: strictObject({\n depth: z\n ._default(z.int().check(z.minimum(0), z.maximum(10)), 0)\n .check(z.describe('Depth of population for relationships.')),\n email: emailSchema,\n password: z.string().check(z.describe('The user password.')),\n }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.login({\n collection: slug,\n data: { email: input.email, password: input.password },\n depth: input.depth,\n overrideAccess: authorizedMCP.overrideAccess,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Login Successful\\n\\n**User:** ${input.email}\\n**Collection:** ${slug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in login tool on ${slug}: ${errorMessage}`)\n return wrapError('login')({ slug, message: errorMessage })\n }\n})\n\nexport const resetPasswordCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Reset Password',\n },\n description: 'Resets a user password with a reset token.',\n input: strictObject({\n password: z.string().check(z.describe('The new password for the user.')),\n token: z.string().check(z.describe('The password reset token sent to the user email.')),\n }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.resetPassword({\n collection: slug,\n data: { password: input.password, token: input.token },\n overrideAccess: authorizedMCP.overrideAccess,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Password Reset Successful\\n\\n**Collection:** ${slug}\\n\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in resetPassword tool on ${slug}: ${errorMessage}`)\n return wrapError('resetPassword')({ slug, message: errorMessage })\n }\n})\n\nexport const unlockCollectionTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.unlock),\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Unlock Account',\n },\n description: 'Unlocks a user account that has been locked due to failed login attempts.',\n input: strictObject({ email: emailSchema }),\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.unlock({\n collection: slug,\n data: { email: input.email },\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Account Unlocked\\n\\n**Collection:** ${slug}\\n**Email:** ${input.email}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in unlock tool on ${slug}: ${errorMessage}`)\n return wrapError('unlock')({ slug, message: errorMessage })\n }\n})\n\nexport const verifyCollectionTool = defineCollectionTool({\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Email Verification',\n },\n description: 'Verifies a user email with a verification token.',\n input: strictObject({\n token: z.string().check(z.describe('The verification token sent to the user email.')),\n }),\n}).handler(async ({ slug, input, req }) => {\n const logger = getLogger({ payload: req.payload })\n try {\n const result = await req.payload.verifyEmail({\n collection: slug,\n token: input.token,\n })\n return {\n content: [\n {\n type: 'text',\n text: `# Email Verification Successful\\n\\n**Collection:** ${slug}\\n**Result:** ${result ? 'Success' : 'Failed'}`,\n },\n ],\n doc: { result } as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error in verify tool on ${slug}: ${errorMessage}`)\n return wrapError('verify')({ slug, message: errorMessage })\n }\n})\n"],"names":["createPayloadRequest","strictObject","z","defaultAccess","defineCollectionTool","getLogger","emailSchema","email","check","describe","wrapError","name","slug","message","content","type","text","authCollectionTool","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","headers","optional","record","string","handler","authorizedMCP","req","logger","payload","authHeaders","Headers","authReq","result","auth","user","authenticatedUser","findByID","id","collection","overrideAccess","_sid","_strategy","JSON","stringify","doc","error","errorMessage","Error","forgotPasswordCollectionTool","forgotPassword","data","disableEmail","loginCollectionTool","depth","_default","int","minimum","maximum","password","login","resetPasswordCollectionTool","token","resetPassword","unlockCollectionTool","access","args","Boolean","permissions","collections","unlock","verifyCollectionTool","verifyEmail"],"mappings":"AAAA,SAASA,oBAAoB,EAAEC,YAAY,EAAEC,CAAC,QAAQ,UAAS;AAI/D,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD;;;;;;;;;CASC,GAED,MAAMC,cAAcJ,EAAEK,KAAK,GAAGC,KAAK,CAACN,EAAEO,QAAQ,CAAC;AAE/C,MAAMC,YACJ,CAACC,OACD,CAAC,EAAEC,IAAI,EAAEC,OAAO,EAAqC;QACnD,OAAO;YACLC,SAAS;gBACP;oBACEC,MAAM;o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EO,GAAG,EAAE;IACpC,MAAMC,SAAS5B,UAAU;QAAE6B,SAASF,IAAIE,OAAO;IAAC;IAChD,IAAI;QACF,MAAMI,SAAS,MAAMN,IAAIE,OAAO,CAAC2C,WAAW,CAAC;YAC3CjC,YAAYhC;YACZuD,OAAO1C,MAAM0C,KAAK;QACpB;QACA,OAAO;YACLrD,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,mDAAmD,EAAEJ,KAAK,cAAc,EAAE0B,SAAS,YAAY,UAAU;gBAClH;aACD;YACDY,KAAK;gBAAEZ;YAAO;QAChB;IACF,EAAE,OAAOa,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMtC,OAAO,GAAG;QAC9DoB,OAAOkB,KAAK,CAAC,CAAC,wBAAwB,EAAEvC,KAAK,EAAE,EAAEwC,cAAc;QAC/D,OAAO1C,UAAU,UAAU;YAAEE;YAAMC,SAASuC;QAAa;IAC3D;AACF,GAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getCollectionSchemaTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/getCollectionSchemaTool.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"getCollectionSchemaTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/getCollectionSchemaTool.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,uBAAuB,4CAoFlC,CAAA"}
|