@payloadcms/plugin-mcp 4.0.0-canary.20 → 4.0.0-canary.20261117
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 +20 -4
- package/dist/endpoint/access.d.ts.map +1 -1
- package/dist/endpoint/access.js +73 -11
- package/dist/endpoint/access.js.map +1 -1
- package/dist/endpoint/index.d.ts.map +1 -1
- package/dist/endpoint/index.js +58 -4
- package/dist/endpoint/index.js.map +1 -1
- package/dist/endpoint/oauth.d.ts +37 -0
- package/dist/endpoint/oauth.d.ts.map +1 -0
- package/dist/endpoint/oauth.js +105 -0
- package/dist/endpoint/oauth.js.map +1 -0
- package/dist/endpoint/oauthLoginToken.d.ts +27 -0
- package/dist/endpoint/oauthLoginToken.d.ts.map +1 -0
- package/dist/endpoint/oauthLoginToken.js +86 -0
- package/dist/endpoint/oauthLoginToken.js.map +1 -0
- package/dist/endpoint/oauthServer.d.ts +28 -0
- package/dist/endpoint/oauthServer.d.ts.map +1 -0
- package/dist/endpoint/oauthServer.js +455 -0
- package/dist/endpoint/oauthServer.js.map +1 -0
- package/dist/exports/client.d.ts +1 -1
- package/dist/exports/client.d.ts.map +1 -1
- package/dist/exports/client.js +1 -1
- package/dist/exports/client.js.map +1 -1
- package/dist/exports/rsc.d.ts +2 -0
- package/dist/exports/rsc.d.ts.map +1 -0
- package/dist/exports/rsc.js +3 -0
- package/dist/exports/rsc.js.map +1 -0
- package/dist/index.d.ts +10 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +34 -10
- package/dist/index.js.map +1 -1
- package/dist/mcp/buildMcpServer.d.ts +2 -2
- package/dist/mcp/buildMcpServer.d.ts.map +1 -1
- package/dist/mcp/buildMcpServer.js +36 -24
- 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 +80 -56
- package/dist/mcp/builtin/collections/authTools.js.map +1 -1
- package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/countTool.js +9 -14
- package/dist/mcp/builtin/collections/countTool.js.map +1 -1
- package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/countVersionsTool.js +9 -13
- package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/createTool.js +48 -49
- package/dist/mcp/builtin/collections/createTool.js.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.js +47 -44
- package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
- package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/duplicateTool.js +31 -37
- package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
- package/dist/mcp/builtin/collections/fileInput.d.ts +21 -21
- package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/fileInput.js +34 -70
- package/dist/mcp/builtin/collections/fileInput.js.map +1 -1
- package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findDistinctTool.js +11 -26
- package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findTool.js +28 -46
- package/dist/mcp/builtin/collections/findTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findVersionByIDTool.js +17 -26
- package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findVersionsTool.js +16 -30
- package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +30 -14
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/restoreVersionTool.js +14 -26
- package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.js +55 -87
- package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
- package/dist/mcp/builtin/collections/uploadInstructionsTool.js +11 -11
- package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -1
- package/dist/mcp/builtin/formatEntityError.d.ts +16 -0
- package/dist/mcp/builtin/formatEntityError.d.ts.map +1 -0
- package/dist/mcp/builtin/formatEntityError.js +55 -0
- package/dist/mcp/builtin/formatEntityError.js.map +1 -0
- package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
- package/dist/mcp/builtin/getConfigInfoTool.js +3 -2
- package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
- package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/countVersionsTool.js +9 -13
- package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findTool.js +10 -16
- package/dist/mcp/builtin/globals/findTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findVersionByIDTool.js +13 -24
- package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findVersionsTool.js +13 -29
- package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +29 -13
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/restoreVersionTool.js +15 -22
- package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
- package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/updateTool.js +27 -36
- package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.js +4 -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 +131 -10
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/seal.d.ts +17 -0
- package/dist/utils/seal.d.ts.map +1 -0
- package/dist/utils/seal.js +24 -0
- package/dist/utils/seal.js.map +1 -0
- package/dist/utils/toStandardSchema.js.map +1 -1
- package/dist/views/Authorize/AllowButtons/index.d.ts +18 -0
- package/dist/views/Authorize/AllowButtons/index.d.ts.map +1 -0
- package/dist/views/Authorize/AllowButtons/index.js +88 -0
- package/dist/views/Authorize/AllowButtons/index.js.map +1 -0
- package/dist/views/Authorize/index.css +19 -0
- package/dist/views/Authorize/index.d.ts +9 -0
- package/dist/views/Authorize/index.d.ts.map +1 -0
- package/dist/views/Authorize/index.js +98 -0
- package/dist/views/Authorize/index.js.map +1 -0
- package/package.json +30 -28
- package/src/endpoint/access.ts +81 -9
- package/src/endpoint/index.ts +50 -4
- package/src/endpoint/oauth.ts +108 -0
- package/src/endpoint/oauthLoginToken.ts +100 -0
- package/src/endpoint/oauthServer.ts +472 -0
- package/src/exports/client.ts +1 -1
- package/src/exports/rsc.ts +1 -0
- package/src/index.ts +53 -9
- package/src/mcp/buildMcpServer.ts +40 -30
- package/src/mcp/builtin/collections/authTools.ts +82 -71
- package/src/mcp/builtin/collections/countTool.ts +9 -21
- package/src/mcp/builtin/collections/countVersionsTool.ts +9 -18
- package/src/mcp/builtin/collections/createTool.ts +71 -96
- package/src/mcp/builtin/collections/deleteTool.ts +40 -66
- package/src/mcp/builtin/collections/duplicateTool.ts +36 -86
- package/src/mcp/builtin/collections/fileInput.spec.ts +2 -2
- package/src/mcp/builtin/collections/fileInput.ts +44 -81
- package/src/mcp/builtin/collections/findDistinctTool.ts +11 -63
- package/src/mcp/builtin/collections/findTool.ts +24 -106
- package/src/mcp/builtin/collections/findVersionByIDTool.ts +15 -58
- package/src/mcp/builtin/collections/findVersionsTool.ts +14 -85
- package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +23 -12
- package/src/mcp/builtin/collections/restoreVersionTool.ts +15 -57
- package/src/mcp/builtin/collections/updateTool.ts +55 -109
- package/src/mcp/builtin/collections/uploadInstructionsTool.ts +12 -12
- package/src/mcp/builtin/formatEntityError.ts +77 -0
- package/src/mcp/builtin/getConfigInfoTool.ts +2 -1
- package/src/mcp/builtin/globals/countVersionsTool.ts +9 -17
- package/src/mcp/builtin/globals/findTool.ts +13 -52
- package/src/mcp/builtin/globals/findVersionByIDTool.ts +13 -52
- package/src/mcp/builtin/globals/findVersionsTool.ts +14 -92
- package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +21 -11
- package/src/mcp/builtin/globals/restoreVersionTool.ts +14 -45
- package/src/mcp/builtin/globals/updateTool.ts +38 -61
- package/src/mcp/sanitizeMCPConfig.ts +2 -0
- package/src/stdio.ts +2 -2
- package/src/types.ts +130 -10
- package/src/utils/seal.ts +46 -0
- package/src/utils/toStandardSchema.ts +1 -1
- package/src/views/Authorize/AllowButtons/index.tsx +97 -0
- package/src/views/Authorize/index.css +19 -0
- package/src/views/Authorize/index.tsx +100 -0
- package/dist/mcp/builtin/collections/fileInput.spec.js +0 -86
- package/dist/mcp/builtin/collections/fileInput.spec.js.map +0 -1
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
- package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
- package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
- package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
- package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
- package/dist/mcp/builtin/validateEntityData.js +0 -82
- package/dist/mcp/builtin/validateEntityData.js.map +0 -1
- package/dist/utils/getVirtualFieldNames.d.ts +0 -14
- package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
- package/dist/utils/getVirtualFieldNames.js +0 -35
- package/dist/utils/getVirtualFieldNames.js.map +0 -1
- package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +0 -28
- package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +0 -1
- package/dist/utils/schemaConversion/filterFieldsByAccess.js +0 -71
- package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +0 -1
- package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -13
- package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
- package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -66
- package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -10
- package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -384
- package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -133
- package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
- package/dist/utils/transformPointDataToPayload.d.ts +0 -7
- package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
- package/dist/utils/transformPointDataToPayload.js +0 -28
- package/dist/utils/transformPointDataToPayload.js.map +0 -1
- package/dist/utils/whereSchema.d.ts +0 -9
- package/dist/utils/whereSchema.d.ts.map +0 -1
- package/dist/utils/whereSchema.js +0 -13
- package/dist/utils/whereSchema.js.map +0 -1
- package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
- package/src/mcp/builtin/validateEntityData.ts +0 -132
- package/src/utils/getVirtualFieldNames.ts +0 -53
- package/src/utils/schemaConversion/filterFieldsByAccess.ts +0 -123
- package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -96
- package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -96
- package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -432
- package/src/utils/transformPointDataToPayload.ts +0 -40
- package/src/utils/whereSchema.ts +0 -24
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,17 +1,33 @@
|
|
|
1
|
-
import type { PayloadRequest } from 'payload';
|
|
1
|
+
import type { PayloadRequest, SanitizedPermissions } from 'payload';
|
|
2
2
|
import type { AuthorizedMCP, MCPItem } from '../types.js';
|
|
3
3
|
export type GetAuthorizedMCPArgs = {
|
|
4
|
+
/**
|
|
5
|
+
* Whether the request came through the HTTP endpoint, whose response can carry the OAuth
|
|
6
|
+
* challenge and headers from auth strategies. stdio has no response to carry them.
|
|
7
|
+
*/
|
|
8
|
+
isHTTP?: boolean;
|
|
4
9
|
overrideAccess: boolean;
|
|
5
10
|
req: PayloadRequest;
|
|
6
11
|
};
|
|
7
12
|
/**
|
|
8
|
-
* Authenticates an MCP request and removes items the
|
|
9
|
-
* `overrideAccess` skips Payload and MCP
|
|
13
|
+
* Authenticates an MCP request, rejects users the plugin's `access` denies, and removes items the
|
|
14
|
+
* user cannot access. `overrideAccess` skips Payload and MCP access checks.
|
|
10
15
|
*/
|
|
11
16
|
export declare const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<AuthorizedMCP>;
|
|
12
|
-
|
|
17
|
+
/**
|
|
18
|
+
* Runs the plugin's top-level `access`, which decides whether the user can use MCP at all. Doesn't
|
|
19
|
+
* check `overrideAccess`, so callers skip it themselves.
|
|
20
|
+
*/
|
|
21
|
+
export declare const canUseMCP: ({ permissions, req, }: {
|
|
22
|
+
/** Computed when missing and `access` is set. */
|
|
23
|
+
permissions?: SanitizedPermissions;
|
|
24
|
+
req: PayloadRequest;
|
|
25
|
+
}) => Promise<boolean>;
|
|
26
|
+
export declare const filterMCPItems: ({ items, overrideAccess, permissions: providedPermissions, req, }: {
|
|
13
27
|
items: MCPItem[];
|
|
14
28
|
overrideAccess: boolean;
|
|
29
|
+
/** Computed when missing. */
|
|
30
|
+
permissions?: SanitizedPermissions;
|
|
15
31
|
req: PayloadRequest;
|
|
16
32
|
}) => Promise<MCPItem[]>;
|
|
17
33
|
//# sourceMappingURL=access.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../../src/endpoint/access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,
|
|
1
|
+
{"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../../src/endpoint/access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAKnE,OAAO,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AAKzD,MAAM,MAAM,oBAAoB,GAAG;IACjC;;;OAGG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,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,CA6EnF,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,SAAS,0BAGnB;IACD,iDAAiD;IACjD,WAAW,CAAC,EAAE,oBAAoB,CAAA;IAClC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,OAAO,CAOlB,CAAA;AAED,eAAO,MAAM,cAAc,sEAKxB;IACD,KAAK,EAAE,OAAO,EAAE,CAAA;IAChB,cAAc,EAAE,OAAO,CAAA;IACvB,6BAA6B;IAC7B,WAAW,CAAC,EAAE,oBAAoB,CAAA;IAClC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,OAAO,EAAE,CAkBpB,CAAA"}
|
package/dist/endpoint/access.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
|
-
import { getAccessResults, UnauthorizedError } from 'payload';
|
|
1
|
+
import { executeAuthStrategies, Forbidden, getAccessResults, UnauthorizedError } from 'payload';
|
|
2
|
+
import { extractBearerToken } from 'payload/shared';
|
|
2
3
|
import { getPluginConfig } from '../utils/getPluginConfig.js';
|
|
4
|
+
import { authenticateLoginToken } from './oauthLoginToken.js';
|
|
3
5
|
/**
|
|
4
|
-
* Authenticates an MCP request and removes items the
|
|
5
|
-
* `overrideAccess` skips Payload and MCP
|
|
6
|
-
*/ export const getAuthorizedMCP = async ({ overrideAccess, req })=>{
|
|
6
|
+
* Authenticates an MCP request, rejects users the plugin's `access` denies, and removes items the
|
|
7
|
+
* user cannot access. `overrideAccess` skips Payload and MCP access checks.
|
|
8
|
+
*/ export const getAuthorizedMCP = async ({ isHTTP = false, overrideAccess, req })=>{
|
|
7
9
|
const pluginConfig = getPluginConfig({
|
|
8
10
|
config: req.payload.config
|
|
9
11
|
});
|
|
12
|
+
const isChallengedWhenSignedOut = isHTTP && Boolean(pluginConfig.oauth);
|
|
10
13
|
if (pluginConfig.overrideGetAuthorizedMCP) {
|
|
11
14
|
return await pluginConfig.overrideGetAuthorizedMCP({
|
|
12
15
|
overrideAccess,
|
|
@@ -18,30 +21,89 @@ import { getPluginConfig } from '../utils/getPluginConfig.js';
|
|
|
18
21
|
const headers = new Headers(req.headers);
|
|
19
22
|
const hasAuthorization = headers.has('Authorization');
|
|
20
23
|
headers.set('DisableAutologin', 'true');
|
|
21
|
-
|
|
24
|
+
// Not `payload.auth()`, which also computes permissions that filterMCPItems computes anyway
|
|
25
|
+
const { responseHeaders, user } = await executeAuthStrategies({
|
|
26
|
+
canSetHeaders: isHTTP,
|
|
22
27
|
headers,
|
|
28
|
+
payload: req.payload,
|
|
23
29
|
req
|
|
24
|
-
})
|
|
25
|
-
|
|
30
|
+
});
|
|
31
|
+
req.user = user;
|
|
32
|
+
if (responseHeaders) {
|
|
33
|
+
req.responseHeaders = responseHeaders;
|
|
34
|
+
}
|
|
35
|
+
// Only bearer tokens that no auth strategy accepted get here, e.g. an OAuth access token.
|
|
36
|
+
// API keys use the `<collection> API-Key <key>` scheme instead of `Bearer`, so they never do.
|
|
37
|
+
const bearerToken = extractBearerToken({
|
|
38
|
+
headers
|
|
39
|
+
});
|
|
40
|
+
// Sealed Payload login tokens from the built-in OAuth server
|
|
41
|
+
if (!req.user && bearerToken && pluginConfig.oauth?.type === 'builtin' && !pluginConfig.oauth.issueToken) {
|
|
42
|
+
req.user = await authenticateLoginToken({
|
|
43
|
+
req,
|
|
44
|
+
token: bearerToken
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
if (!req.user && bearerToken && pluginConfig.oauth?.authenticate) {
|
|
48
|
+
req.user = await pluginConfig.oauth.authenticate({
|
|
49
|
+
req,
|
|
50
|
+
token: bearerToken
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
// With OAuth, the endpoint answers with a challenge that starts the client's sign-in
|
|
54
|
+
if (hasAuthorization && !req.user && !isChallengedWhenSignedOut) {
|
|
26
55
|
throw new UnauthorizedError(req.t);
|
|
27
56
|
}
|
|
28
57
|
}
|
|
58
|
+
// Signed-out users only get the challenge, so they can't use any MCP items. Skipping the access
|
|
59
|
+
// checks saves work, and access callbacks only see signed-in users.
|
|
60
|
+
if (isChallengedWhenSignedOut && !req.user) {
|
|
61
|
+
return {
|
|
62
|
+
items: [],
|
|
63
|
+
overrideAccess
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
// Computed once for the plugin's `access` and every item's
|
|
67
|
+
const permissions = overrideAccess ? undefined : await getAccessResults({
|
|
68
|
+
req
|
|
69
|
+
});
|
|
70
|
+
if (!overrideAccess && !await canUseMCP({
|
|
71
|
+
permissions,
|
|
72
|
+
req
|
|
73
|
+
})) {
|
|
74
|
+
throw new Forbidden(req.t);
|
|
75
|
+
}
|
|
29
76
|
return {
|
|
30
77
|
items: await filterMCPItems({
|
|
31
78
|
items: pluginConfig.items,
|
|
32
79
|
overrideAccess,
|
|
80
|
+
permissions,
|
|
33
81
|
req
|
|
34
82
|
}),
|
|
35
83
|
overrideAccess
|
|
36
84
|
};
|
|
37
85
|
};
|
|
38
|
-
|
|
86
|
+
/**
|
|
87
|
+
* Runs the plugin's top-level `access`, which decides whether the user can use MCP at all. Doesn't
|
|
88
|
+
* check `overrideAccess`, so callers skip it themselves.
|
|
89
|
+
*/ export const canUseMCP = async ({ permissions, req })=>{
|
|
90
|
+
const { access } = getPluginConfig({
|
|
91
|
+
config: req.payload.config
|
|
92
|
+
});
|
|
93
|
+
return !access || await access({
|
|
94
|
+
permissions: permissions ?? await getAccessResults({
|
|
95
|
+
req
|
|
96
|
+
}),
|
|
97
|
+
req
|
|
98
|
+
});
|
|
99
|
+
};
|
|
100
|
+
export const filterMCPItems = async ({ items, overrideAccess, permissions: providedPermissions, req })=>{
|
|
39
101
|
// Match Payload core: overrideAccess bypasses access evaluation
|
|
40
102
|
if (overrideAccess) {
|
|
41
103
|
return items;
|
|
42
104
|
}
|
|
43
105
|
const authorizedItems = [];
|
|
44
|
-
const permissions = await getAccessResults({
|
|
106
|
+
const permissions = providedPermissions ?? await getAccessResults({
|
|
45
107
|
req
|
|
46
108
|
});
|
|
47
109
|
for (const item of items){
|
|
@@ -62,13 +124,13 @@ export const filterMCPItems = async ({ items, overrideAccess, req })=>{
|
|
|
62
124
|
switch(item.type){
|
|
63
125
|
case 'collectionTool':
|
|
64
126
|
return !item.tool.access || await item.tool.access({
|
|
65
|
-
|
|
127
|
+
slug: item.collectionSlug,
|
|
66
128
|
permissions,
|
|
67
129
|
req
|
|
68
130
|
});
|
|
69
131
|
case 'globalTool':
|
|
70
132
|
return !item.tool.access || await item.tool.access({
|
|
71
|
-
|
|
133
|
+
slug: item.globalSlug,
|
|
72
134
|
permissions,
|
|
73
135
|
req
|
|
74
136
|
});
|
|
@@ -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
|
|
1
|
+
{"version":3,"sources":["../../src/endpoint/access.ts"],"sourcesContent":["import type { PayloadRequest, SanitizedPermissions } from 'payload'\n\nimport { executeAuthStrategies, Forbidden, getAccessResults, UnauthorizedError } from 'payload'\nimport { extractBearerToken } from 'payload/shared'\n\nimport type { AuthorizedMCP, MCPItem } from '../types.js'\n\nimport { getPluginConfig } from '../utils/getPluginConfig.js'\nimport { authenticateLoginToken } from './oauthLoginToken.js'\n\nexport type GetAuthorizedMCPArgs = {\n /**\n * Whether the request came through the HTTP endpoint, whose response can carry the OAuth\n * challenge and headers from auth strategies. stdio has no response to carry them.\n */\n isHTTP?: boolean\n overrideAccess: boolean\n req: PayloadRequest\n}\n\n/**\n * Authenticates an MCP request, rejects users the plugin's `access` denies, and removes items the\n * user cannot access. `overrideAccess` skips Payload and MCP access checks.\n */\nexport const getAuthorizedMCP: (args: GetAuthorizedMCPArgs) => Promise<AuthorizedMCP> = async ({\n isHTTP = false,\n overrideAccess,\n req,\n}) => {\n const pluginConfig = getPluginConfig({ config: req.payload.config })\n const isChallengedWhenSignedOut = isHTTP && Boolean(pluginConfig.oauth)\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 const { responseHeaders, user } = await executeAuthStrategies({\n canSetHeaders: isHTTP,\n headers,\n payload: req.payload,\n req,\n })\n req.user = user\n if (responseHeaders) {\n req.responseHeaders = responseHeaders\n }\n\n // Only bearer tokens that no auth strategy accepted get here, 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 = extractBearerToken({ headers })\n // Sealed Payload login tokens from the built-in OAuth server\n if (\n !req.user &&\n bearerToken &&\n pluginConfig.oauth?.type === 'builtin' &&\n !pluginConfig.oauth.issueToken\n ) {\n req.user = await authenticateLoginToken({ req, token: bearerToken })\n }\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 && !isChallengedWhenSignedOut) {\n throw new UnauthorizedError(req.t)\n }\n }\n\n // Signed-out users only get the challenge, so they can't use any MCP items. Skipping the access\n // checks saves work, and access callbacks only see signed-in users.\n if (isChallengedWhenSignedOut && !req.user) {\n return { items: [], overrideAccess }\n }\n\n // Computed once for the plugin's `access` and every item's\n const permissions = overrideAccess ? undefined : await getAccessResults({ req })\n\n if (!overrideAccess && !(await canUseMCP({ permissions, req }))) {\n throw new Forbidden(req.t)\n }\n\n return {\n items: await filterMCPItems({\n items: pluginConfig.items,\n overrideAccess,\n permissions,\n req,\n }),\n overrideAccess,\n }\n}\n\n/**\n * Runs the plugin's top-level `access`, which decides whether the user can use MCP at all. Doesn't\n * check `overrideAccess`, so callers skip it themselves.\n */\nexport const canUseMCP = async ({\n permissions,\n req,\n}: {\n /** Computed when missing and `access` is set. */\n permissions?: SanitizedPermissions\n req: PayloadRequest\n}): Promise<boolean> => {\n const { access } = getPluginConfig({ config: req.payload.config })\n\n return (\n !access ||\n (await access({ permissions: permissions ?? (await getAccessResults({ req })), req }))\n )\n}\n\nexport const filterMCPItems = async ({\n items,\n overrideAccess,\n permissions: providedPermissions,\n req,\n}: {\n items: MCPItem[]\n overrideAccess: boolean\n /** Computed when missing. */\n permissions?: SanitizedPermissions\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 = providedPermissions ?? (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","Forbidden","getAccessResults","UnauthorizedError","extractBearerToken","getPluginConfig","authenticateLoginToken","getAuthorizedMCP","isHTTP","overrideAccess","req","pluginConfig","config","payload","isChallengedWhenSignedOut","Boolean","oauth","overrideGetAuthorizedMCP","headers","Headers","hasAuthorization","has","set","responseHeaders","user","canSetHeaders","bearerToken","type","issueToken","token","authenticate","t","items","permissions","undefined","canUseMCP","filterMCPItems","access","providedPermissions","authorizedItems","item","checkItemAccess","push","tool","slug","collectionSlug","globalSlug","prompt","resource"],"mappings":"AAEA,SAASA,qBAAqB,EAAEC,SAAS,EAAEC,gBAAgB,EAAEC,iBAAiB,QAAQ,UAAS;AAC/F,SAASC,kBAAkB,QAAQ,iBAAgB;AAInD,SAASC,eAAe,QAAQ,8BAA6B;AAC7D,SAASC,sBAAsB,QAAQ,uBAAsB;AAY7D;;;CAGC,GACD,OAAO,MAAMC,mBAA2E,OAAO,EAC7FC,SAAS,KAAK,EACdC,cAAc,EACdC,GAAG,EACJ;IACC,MAAMC,eAAeN,gBAAgB;QAAEO,QAAQF,IAAIG,OAAO,CAACD,MAAM;IAAC;IAClE,MAAME,4BAA4BN,UAAUO,QAAQJ,aAAaK,KAAK;IAEtE,IAAIL,aAAaM,wBAAwB,EAAE;QACzC,OAAO,MAAMN,aAAaM,wBAAwB,CAAC;YACjDR;YACAE;YACAD;QACF;IACF;IAEA,IAAIA,IAAIQ,OAAO,EAAE;QACf,MAAMA,UAAU,IAAIC,QAAQT,IAAIQ,OAAO;QACvC,MAAME,mBAAmBF,QAAQG,GAAG,CAAC;QAErCH,QAAQI,GAAG,CAAC,oBAAoB;QAChC,4FAA4F;QAC5F,MAAM,EAA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M,CAAC;gBAAEJ;gBAAavB;YAAI;QAC7E,KAAK;YACH,OAAO,CAAC8B,KAAKQ,QAAQ,CAACX,MAAM,IAAK,MAAMG,KAAKQ,QAAQ,CAACX,MAAM,CAAC;gBAAEJ;gBAAavB;YAAI;QACjF,KAAK;YACH,OAAO,CAAC8B,KAAKG,IAAI,CAACN,MAAM,IAAK,MAAMG,KAAKG,IAAI,CAACN,MAAM,CAAC;gBAAEJ;gBAAavB;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,cAkFzB,CAAA"}
|
package/dist/endpoint/index.js
CHANGED
|
@@ -1,13 +1,20 @@
|
|
|
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 { 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
|
+
req
|
|
16
|
+
})
|
|
17
|
+
};
|
|
11
18
|
const pluginConfig = getPluginConfig({
|
|
12
19
|
config: req.payload.config
|
|
13
20
|
});
|
|
@@ -22,13 +29,38 @@ export const mcpEndpoint = async (req)=>{
|
|
|
22
29
|
throw new APIError('MCP overrideAccess must be "true" or "false".', 400);
|
|
23
30
|
}
|
|
24
31
|
const authorizedMCP = await getAuthorizedMCP({
|
|
32
|
+
isHTTP: true,
|
|
25
33
|
overrideAccess,
|
|
26
34
|
req
|
|
27
35
|
});
|
|
36
|
+
// Clients like Codex send a GET first to find out where to sign in, so this comes before the
|
|
37
|
+
// GET check
|
|
38
|
+
if (pluginConfig.oauth && !req.user) {
|
|
39
|
+
return oauthChallenge({
|
|
40
|
+
req
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
// Streamable HTTP's optional server-to-client stream. We don't offer one, so answer 405 per
|
|
44
|
+
// spec, and clients skip it
|
|
45
|
+
if (req.method === 'GET') {
|
|
46
|
+
return new Response(null, {
|
|
47
|
+
headers: {
|
|
48
|
+
Allow: 'POST'
|
|
49
|
+
},
|
|
50
|
+
status: 405
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize;
|
|
28
54
|
// Payload augments the original web-standard Request in place.
|
|
29
55
|
const mcpRequest = req;
|
|
56
|
+
const parsedBody = await parseRequestBody({
|
|
57
|
+
maxRequestBodySize,
|
|
58
|
+
request: mcpRequest
|
|
59
|
+
});
|
|
30
60
|
// Keep the old JSON-only, stateless behavior because the SDK's 2025 fallback uses SSE.
|
|
31
|
-
if (await isLegacyRequest(mcpRequest
|
|
61
|
+
if (await isLegacyRequest(mcpRequest, parsedBody, {
|
|
62
|
+
maxRequestBodySize
|
|
63
|
+
})) {
|
|
32
64
|
const server = buildMcpServer({
|
|
33
65
|
authorizedMCP,
|
|
34
66
|
pluginConfig,
|
|
@@ -36,6 +68,7 @@ export const mcpEndpoint = async (req)=>{
|
|
|
36
68
|
});
|
|
37
69
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
38
70
|
enableJsonResponse: true,
|
|
71
|
+
maxRequestBodySize,
|
|
39
72
|
sessionIdGenerator: undefined
|
|
40
73
|
});
|
|
41
74
|
transport.onerror = (err)=>{
|
|
@@ -46,7 +79,9 @@ export const mcpEndpoint = async (req)=>{
|
|
|
46
79
|
};
|
|
47
80
|
try {
|
|
48
81
|
await server.connect(transport);
|
|
49
|
-
return await transport.handleRequest(mcpRequest
|
|
82
|
+
return await transport.handleRequest(mcpRequest, {
|
|
83
|
+
parsedBody
|
|
84
|
+
});
|
|
50
85
|
} finally{
|
|
51
86
|
await server.close().catch((err)=>{
|
|
52
87
|
req.payload.logger.error({
|
|
@@ -62,6 +97,7 @@ export const mcpEndpoint = async (req)=>{
|
|
|
62
97
|
req
|
|
63
98
|
}), {
|
|
64
99
|
legacy: 'reject',
|
|
100
|
+
maxRequestBodySize,
|
|
65
101
|
// SDK subscriptions always use SSE, so disable them to keep every response JSON-only.
|
|
66
102
|
maxSubscriptions: 0,
|
|
67
103
|
onerror: (err)=>{
|
|
@@ -73,7 +109,9 @@ export const mcpEndpoint = async (req)=>{
|
|
|
73
109
|
responseMode: 'json'
|
|
74
110
|
});
|
|
75
111
|
try {
|
|
76
|
-
return await handler.fetch(mcpRequest
|
|
112
|
+
return await handler.fetch(mcpRequest, {
|
|
113
|
+
parsedBody
|
|
114
|
+
});
|
|
77
115
|
} finally{
|
|
78
116
|
await handler.close().catch((err)=>{
|
|
79
117
|
req.payload.logger.error({
|
|
@@ -83,5 +121,21 @@ export const mcpEndpoint = async (req)=>{
|
|
|
83
121
|
});
|
|
84
122
|
}
|
|
85
123
|
};
|
|
124
|
+
/**
|
|
125
|
+
* Parses a POST body once so the era check and the SDK handler can share it. The SDK
|
|
126
|
+
* skips its size limit for a pre-parsed body, so this reads with the same limit. It reads
|
|
127
|
+
* a clone and returns `undefined` for any body the SDK should reject (too large, unreadable,
|
|
128
|
+
* or not JSON), leaving the original request for the SDK to read and answer.
|
|
129
|
+
*/ const parseRequestBody = async ({ maxRequestBodySize, request })=>{
|
|
130
|
+
if (request.method.toUpperCase() !== 'POST') {
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
try {
|
|
134
|
+
const body = await readRequestBody(request.clone(), maxRequestBodySize);
|
|
135
|
+
return body.tooLarge ? undefined : JSON.parse(body.text);
|
|
136
|
+
} catch {
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
};
|
|
86
140
|
|
|
87
141
|
//# 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 { 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({ req }) }\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({ isHTTP: true, overrideAccess, req })\n\n // Clients like Codex send a GET first to find out where to sign in, so this comes before the\n // GET check\n if (pluginConfig.oauth && !req.user) {\n return oauthChallenge({ req })\n }\n\n // Streamable HTTP's optional server-to-client stream. We don't offer one, so answer 405 per\n // spec, and clients skip it\n if (req.method === 'GET') {\n return new Response(null, { headers: { Allow: 'POST' }, status: 405 })\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","pluginConfig","config","payload","overrideAccessParam","URL","searchParams","get","process","env","NODE_ENV","overrideAccess","authorizedMCP","isHTTP","oauth","user","method","Response","headers","Allow","status","maxRequestBodySize","mcpRequest","parsedBody","parseRequestBody","request","server","transport","enableJsonResponse","sessionIdGenerator","undefined","onerror","err","logger","error","msg","connect","handleRequest","close","catch","handler","legacy","maxSubscriptions","responseMode","fetch","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;YAAEG;QAAI;IAAG;IAEtD,MAAMM,eAAeX,gBAAgB;QAAEY,QAAQP,IAAIQ,OAAO,CAACD,MAAM;IAAC;IAClE,MAAME,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,SAAS,iDAAiD;IACtE;IAEA,MAAMwB,gBAAgB,MAAMrB,iBAAiB;QAAEsB,QAAQ;QAAMF;QAAgBhB;IAAI;IAEjF,6FAA6F;IAC7F,YAAY;IACZ,IAAIM,aAAaa,KAAK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AmC;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;YAC3BrC,IAAIQ,OAAO,CAAC8B,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,QAAQT,MAAM,CAAC6B,WAAW,OAAO,QAAQ;QAC3C,OAAOf;IACT;IAEA,IAAI;QACF,MAAMgB,OAAO,MAAM5D,gBAAgBuC,QAAQsB,KAAK,IAAI1B;QACpD,OAAOyB,KAAKE,QAAQ,GAAGlB,YAAYmB,KAAKC,KAAK,CAACJ,KAAKK,IAAI;IACzD,EAAE,OAAM;QACN,OAAOrB;IACT;AACF"}
|
|
@@ -0,0 +1,37 @@
|
|
|
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 }: {
|
|
20
|
+
config: Promise<SanitizedConfig> | SanitizedConfig;
|
|
21
|
+
}) => (request: Request) => Promise<Response>;
|
|
22
|
+
/**
|
|
23
|
+
* Answers an unauthenticated MCP request with a challenge linking to the protected resource
|
|
24
|
+
* metadata, which starts the client's OAuth flow.
|
|
25
|
+
*/
|
|
26
|
+
export declare const oauthChallenge: ({ req }: {
|
|
27
|
+
req: PayloadRequest;
|
|
28
|
+
}) => Response;
|
|
29
|
+
/**
|
|
30
|
+
* The MCP endpoint's address, as advertised in the metadata's `resource`. The metadata link and
|
|
31
|
+
* the built-in authorization server's issuer are based on it. Clients send it when they sign in,
|
|
32
|
+
* and authorization servers that support it put it in the access token's audience.
|
|
33
|
+
*/
|
|
34
|
+
export declare const getMCPResource: ({ req }: {
|
|
35
|
+
req: PayloadRequest;
|
|
36
|
+
}) => string;
|
|
37
|
+
//# 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;AAY9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,EAAE,cAAsD,CAAA;AAEnG;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,6BAA6B,eAC3B;IAAE,MAAM,EAAE,OAAO,CAAC,eAAe,CAAC,GAAG,eAAe,CAAA;CAAE,eACnD,OAAO,KAAG,OAAO,CAAC,QAAQ,CAGtC,CAAA;AAEN;;;GAGG;AACH,eAAO,MAAM,cAAc,YAAa;IAAE,GAAG,EAAE,cAAc,CAAA;CAAE,KAAG,QAcjE,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,cAAc,YAAa;IAAE,GAAG,EAAE,cAAc,CAAA;CAAE,KAAG,MAgBjE,CAAA"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { bearerAuthChallengeResponse, OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server';
|
|
2
|
+
import { createPayloadRequest, getPayload } from 'payload';
|
|
3
|
+
import { formatAdminURL, stripTrailingSlash } from 'payload/shared';
|
|
4
|
+
import { getPluginConfig } from '../utils/getPluginConfig.js';
|
|
5
|
+
/**
|
|
6
|
+
* Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.
|
|
7
|
+
* The OAuth challenge links here, so MCP clients find the authorization server without setup.
|
|
8
|
+
*/ export const oauthProtectedResourceEndpoint = (req)=>getMetadataResponse({
|
|
9
|
+
req
|
|
10
|
+
});
|
|
11
|
+
/**
|
|
12
|
+
* Serves the same metadata for clients that ignore the challenge's link and only look at
|
|
13
|
+
* `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at
|
|
14
|
+
* `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* import config from '@payload-config'
|
|
18
|
+
* import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'
|
|
19
|
+
*
|
|
20
|
+
* export const GET = oauthProtectedResourceHandler({ config })
|
|
21
|
+
* ```
|
|
22
|
+
*/ export const oauthProtectedResourceHandler = ({ config })=>async (request)=>getMetadataResponse({
|
|
23
|
+
req: await createPayloadRequest({
|
|
24
|
+
payload: await getPayload({
|
|
25
|
+
config
|
|
26
|
+
}),
|
|
27
|
+
req: request
|
|
28
|
+
})
|
|
29
|
+
});
|
|
30
|
+
/**
|
|
31
|
+
* Answers an unauthenticated MCP request with a challenge linking to the protected resource
|
|
32
|
+
* metadata, which starts the client's OAuth flow.
|
|
33
|
+
*/ export const oauthChallenge = ({ req })=>{
|
|
34
|
+
const { oauth } = getPluginConfig({
|
|
35
|
+
config: req.payload.config
|
|
36
|
+
});
|
|
37
|
+
const response = bearerAuthChallengeResponse(new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')), {
|
|
38
|
+
requiredScopes: oauth?.type === 'external' ? oauth.scopes : undefined,
|
|
39
|
+
resourceMetadataUrl: `${getMCPResource({
|
|
40
|
+
req
|
|
41
|
+
})}/oauth-protected-resource`
|
|
42
|
+
});
|
|
43
|
+
// Lets browser-based MCP clients read the challenge, when Payload's `cors` setting allows them
|
|
44
|
+
response.headers.set('Access-Control-Expose-Headers', 'WWW-Authenticate');
|
|
45
|
+
return response;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* The MCP endpoint's address, as advertised in the metadata's `resource`. The metadata link and
|
|
49
|
+
* the built-in authorization server's issuer are based on it. Clients send it when they sign in,
|
|
50
|
+
* and authorization servers that support it put it in the access token's audience.
|
|
51
|
+
*/ export const getMCPResource = ({ req })=>{
|
|
52
|
+
const { config } = req.payload;
|
|
53
|
+
const resource = getPluginConfig({
|
|
54
|
+
config
|
|
55
|
+
}).oauth?.resource;
|
|
56
|
+
if (typeof resource === 'function') {
|
|
57
|
+
return resource({
|
|
58
|
+
req
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
if (resource) {
|
|
62
|
+
return resource;
|
|
63
|
+
}
|
|
64
|
+
// Without the slash Next.js's `trailingSlash` would add, since the metadata link appends to it
|
|
65
|
+
const path = stripTrailingSlash(formatAdminURL({
|
|
66
|
+
apiRoute: config.routes.api,
|
|
67
|
+
path: '/mcp'
|
|
68
|
+
}));
|
|
69
|
+
return new URL(path, config.serverURL || req.url).href;
|
|
70
|
+
};
|
|
71
|
+
const getMetadataResponse = async ({ req })=>{
|
|
72
|
+
const { config } = req.payload;
|
|
73
|
+
const { oauth } = getPluginConfig({
|
|
74
|
+
config
|
|
75
|
+
});
|
|
76
|
+
if (!oauth) {
|
|
77
|
+
return new Response(null, {
|
|
78
|
+
status: 404
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
const resource = getMCPResource({
|
|
82
|
+
req
|
|
83
|
+
});
|
|
84
|
+
return Response.json({
|
|
85
|
+
authorization_servers: oauth.type === 'builtin' ? [
|
|
86
|
+
`${resource}/oauth`
|
|
87
|
+
] : typeof oauth.authorizationServers === 'function' ? await oauth.authorizationServers({
|
|
88
|
+
req
|
|
89
|
+
}) : oauth.authorizationServers,
|
|
90
|
+
bearer_methods_supported: [
|
|
91
|
+
'header'
|
|
92
|
+
],
|
|
93
|
+
resource,
|
|
94
|
+
scopes_supported: oauth.type === 'external' ? oauth.scopes : undefined
|
|
95
|
+
}, // Public document, readable by browser-based MCP clients on any origin. Not cached, since its
|
|
96
|
+
// URLs can depend on the request.
|
|
97
|
+
{
|
|
98
|
+
headers: {
|
|
99
|
+
'Access-Control-Allow-Origin': '*',
|
|
100
|
+
'Cache-Control': 'no-store'
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
//# 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'\nimport { formatAdminURL, stripTrailingSlash } from 'payload/shared'\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 }: { 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 { oauth } = getPluginConfig({ config: req.payload.config })\n const response = bearerAuthChallengeResponse(\n new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')),\n {\n requiredScopes: oauth?.type === 'external' ? oauth.scopes : undefined,\n resourceMetadataUrl: `${getMCPResource({ req })}/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`. The metadata link and\n * the built-in authorization server's issuer are based on it. Clients send it when they sign in,\n * and authorization servers that support it put it in the access token's audience.\n */\nexport const getMCPResource = ({ req }: { req: PayloadRequest }): string => {\n const { config } = req.payload\n const resource = getPluginConfig({ config }).oauth?.resource\n\n if (typeof resource === 'function') {\n return resource({ req })\n }\n\n if (resource) {\n return resource\n }\n\n // Without the slash Next.js's `trailingSlash` would add, since the metadata link appends to it\n const path = stripTrailingSlash(formatAdminURL({ apiRoute: config.routes.api, path: '/mcp' }))\n\n return new URL(path, config.serverURL || req.url).href\n}\n\nconst getMetadataResponse = async ({ req }: { req: PayloadRequest }): Promise<Response> => {\n const { config } = req.payload\n const { oauth } = getPluginConfig({ config })\n\n if (!oauth) {\n return new Response(null, { status: 404 })\n }\n\n const resource = getMCPResource({ req })\n\n return Response.json(\n {\n authorization_servers:\n oauth.type === 'builtin'\n ? [`${resource}/oauth`]\n : typeof oauth.authorizationServers === 'function'\n ? await oauth.authorizationServers({ req })\n : oauth.authorizationServers,\n bearer_methods_supported: ['header'],\n resource,\n scopes_supported: oauth.type === 'external' ? oauth.scopes : undefined,\n } satisfies OAuthProtectedResourceMetadata,\n // Public document, readable by browser-based MCP clients on any origin. Not cached, since its\n // URLs can depend on the request.\n { headers: { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' } },\n )\n}\n"],"names":["bearerAuthChallengeResponse","OAuthError","OAuthErrorCode","createPayloadRequest","getPayload","formatAdminURL","stripTrailingSlash","getPluginConfig","oauthProtectedResourceEndpoint","req","getMetadataResponse","oauthProtectedResourceHandler","config","request","payload","oauthChallenge","oauth","response","InvalidToken","t","requiredScopes","type","scopes","undefined","resourceMetadataUrl","getMCPResource","headers","set","resource","path","apiRoute","routes","api","URL","serverURL","url","href","Response","status","json","authorization_servers","authorizationServers","bearer_methods_supported","scopes_supported"],"mappings":"AAGA,SACEA,2BAA2B,EAC3BC,UAAU,EACVC,cAAc,QACT,+BAA8B;AACrC,SAASC,oBAAoB,EAAEC,UAAU,QAAQ,UAAS;AAC1D,SAASC,cAAc,EAAEC,kBAAkB,QAAQ,iBAAgB;AAEnE,SAASC,eAAe,QAAQ,8BAA6B;AAE7D;;;CAGC,GACD,OAAO,MAAMC,iCAAiD,CAACC,MAAQC,oBAAoB;QAAED;IAAI,GAAE;AAEnG;;;;;;;;;;;CAWC,GACD,OAAO,MAAME,gCACX,CAAC,EAAEC,MAAM,EAA0D,GACnE,OAAOC,UACLH,oBAAoB;YAClBD,KAAK,MAAMN,qBAAqB;gBAAEW,SAAS,MAAMV,WAAW;oBAAEQ;gBAAO;gBAAIH,KAAKI;YAAQ;QACxF,GAAE;AAEN;;;CAGC,GACD,OAAO,MAAME,iBAAiB,CAAC,EAAEN,GAAG,EAA2B;IAC7D,MAAM,EAAEO,KAAK,EAAE,GAAGT,gBAAgB;QAAEK,QAAQH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CAAC;SAAC,GACrB,OAAOZ,MAAMyB,oBAAoB,KAAK,aACpC,MAAMzB,MAAMyB,oBAAoB,CAAC;YAAEhC;QAAI,KACvCO,MAAMyB,oBAAoB;QAClCC,0BAA0B;YAAC;SAAS;QACpCd;QACAe,kBAAkB3B,MAAMK,IAAI,KAAK,aAAaL,MAAMM,MAAM,GAAGC;IAC/D,GACA,8FAA8F;IAC9F,kCAAkC;IAClC;QAAEG,SAAS;YAAE,+BAA+B;YAAK,iBAAiB;QAAW;IAAE;AAEnF"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload';
|
|
2
|
+
import type { MCPOAuthTokens } from '../types.js';
|
|
3
|
+
/**
|
|
4
|
+
* The default `issueToken`: a Payload login token, sealed so it only works for MCP, where
|
|
5
|
+
* `authenticateLoginToken` unseals it. Otherwise an MCP client could use it as the user's admin
|
|
6
|
+
* panel login. When the collection uses sessions, the client also gets a refresh token.
|
|
7
|
+
*/
|
|
8
|
+
export declare const issueLoginToken: ({ client, req, }: {
|
|
9
|
+
client: {
|
|
10
|
+
name: string;
|
|
11
|
+
redirectURI: string;
|
|
12
|
+
};
|
|
13
|
+
req: PayloadRequest;
|
|
14
|
+
}) => Promise<MCPOAuthTokens>;
|
|
15
|
+
/** The default `refreshToken`. Payload logs out the session when a refresh token is reused. */
|
|
16
|
+
export declare const refreshLoginToken: ({ refreshToken, req, reuseInterval, }: {
|
|
17
|
+
refreshToken: string;
|
|
18
|
+
req: PayloadRequest;
|
|
19
|
+
/** See `redeemRefreshToken`. */
|
|
20
|
+
reuseInterval?: number;
|
|
21
|
+
}) => Promise<MCPOAuthTokens | null>;
|
|
22
|
+
/** Finds the user of an MCP request's access token from `issueLoginToken`. */
|
|
23
|
+
export declare const authenticateLoginToken: ({ req, token, }: {
|
|
24
|
+
req: PayloadRequest;
|
|
25
|
+
token: string;
|
|
26
|
+
}) => Promise<PayloadRequest['user']>;
|
|
27
|
+
//# sourceMappingURL=oauthLoginToken.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauthLoginToken.d.ts","sourceRoot":"","sources":["../../src/endpoint/oauthLoginToken.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAI7C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAIjD;;;;GAIG;AACH,eAAO,MAAM,eAAe,qBAGzB;IACD,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAA;IAC7C,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,cAAc,CAiCzB,CAAA;AAED,+FAA+F;AAC/F,eAAO,MAAM,iBAAiB,0CAI3B;IACD,YAAY,EAAE,MAAM,CAAA;IACpB,GAAG,EAAE,cAAc,CAAA;IACnB,gCAAgC;IAChC,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB,KAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAUhC,CAAA;AAED,8EAA8E;AAC9E,eAAO,MAAM,sBAAsB,oBAGhC;IACD,GAAG,EAAE,cAAc,CAAA;IACnB,KAAK,EAAE,MAAM,CAAA;CACd,KAAG,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,CAajC,CAAA"}
|