@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.
Files changed (49) hide show
  1. package/bin.js +0 -7
  2. package/dist/endpoint/access.d.ts.map +1 -1
  3. package/dist/endpoint/access.js +11 -1
  4. package/dist/endpoint/access.js.map +1 -1
  5. package/dist/endpoint/index.d.ts.map +1 -1
  6. package/dist/endpoint/index.js +39 -4
  7. package/dist/endpoint/index.js.map +1 -1
  8. package/dist/endpoint/oauth.d.ts +27 -0
  9. package/dist/endpoint/oauth.d.ts.map +1 -0
  10. package/dist/endpoint/oauth.js +61 -0
  11. package/dist/endpoint/oauth.js.map +1 -0
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +7 -0
  15. package/dist/index.js.map +1 -1
  16. package/dist/mcp/buildMcpServer.d.ts +1 -1
  17. package/dist/mcp/buildMcpServer.js +1 -1
  18. package/dist/mcp/buildMcpServer.js.map +1 -1
  19. package/dist/mcp/builtin/collections/authTools.d.ts.map +1 -1
  20. package/dist/mcp/builtin/collections/authTools.js +4 -3
  21. package/dist/mcp/builtin/collections/authTools.js.map +1 -1
  22. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  23. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +19 -3
  24. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  25. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  26. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +19 -3
  27. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  28. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  29. package/dist/mcp/sanitizeMCPConfig.js +1 -0
  30. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  31. package/dist/stdio.js +4 -3
  32. package/dist/stdio.js.map +1 -1
  33. package/dist/types.d.ts +34 -4
  34. package/dist/types.d.ts.map +1 -1
  35. package/dist/types.js.map +1 -1
  36. package/package.json +6 -6
  37. package/src/endpoint/access.ts +9 -1
  38. package/src/endpoint/index.ts +39 -3
  39. package/src/endpoint/oauth.ts +72 -0
  40. package/src/index.ts +7 -0
  41. package/src/mcp/buildMcpServer.ts +1 -1
  42. package/src/mcp/builtin/collections/authTools.ts +5 -2
  43. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +12 -1
  44. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +11 -1
  45. package/src/mcp/sanitizeMCPConfig.ts +1 -0
  46. package/src/stdio.ts +2 -2
  47. package/src/types.ts +35 -4
  48. package/dist/mcp/builtin/collections/fileInput.spec.js +0 -86
  49. package/dist/mcp/builtin/collections/fileInput.spec.js.map +0 -1
@@ -3,6 +3,7 @@ import type { PayloadHandler, PayloadRequest } from 'payload'
3
3
  import {
4
4
  createMcpHandler,
5
5
  isLegacyRequest,
6
+ readRequestBody,
6
7
  WebStandardStreamableHTTPServerTransport,
7
8
  } from '@modelcontextprotocol/server'
8
9
  import { APIError } from 'payload'
@@ -10,6 +11,7 @@ import { APIError } from 'payload'
10
11
  import { buildMcpServer } from '../mcp/buildMcpServer.js'
11
12
  import { getPluginConfig } from '../utils/getPluginConfig.js'
12
13
  import { getAuthorizedMCP } from './access.js'
14
+ import { oauthChallenge } from './oauth.js'
13
15
 
14
16
  export const mcpEndpoint: PayloadHandler = async (req) => {
15
17
  if (!req.url) {
@@ -33,14 +35,22 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
33
35
  }
34
36
 
35
37
  const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
38
+
39
+ if (pluginConfig.oauth && !req.user) {
40
+ return oauthChallenge({ req })
41
+ }
42
+
43
+ const maxRequestBodySize = pluginConfig.mcp?.maxRequestBodySize
36
44
  // Payload augments the original web-standard Request in place.
37
45
  const mcpRequest = req as PayloadRequest & Request
46
+ const parsedBody = await parseRequestBody({ maxRequestBodySize, request: mcpRequest })
38
47
 
39
48
  // Keep the old JSON-only, stateless behavior because the SDK's 2025 fallback uses SSE.
40
- if (await isLegacyRequest(mcpRequest)) {
49
+ if (await isLegacyRequest(mcpRequest, parsedBody, { maxRequestBodySize })) {
41
50
  const server = buildMcpServer({ authorizedMCP, pluginConfig, req })
42
51
  const transport = new WebStandardStreamableHTTPServerTransport({
43
52
  enableJsonResponse: true,
53
+ maxRequestBodySize,
44
54
  sessionIdGenerator: undefined, // stateless mode
45
55
  })
46
56
  transport.onerror = (err) => {
@@ -49,7 +59,7 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
49
59
 
50
60
  try {
51
61
  await server.connect(transport)
52
- return await transport.handleRequest(mcpRequest)
62
+ return await transport.handleRequest(mcpRequest, { parsedBody })
53
63
  } finally {
54
64
  await server.close().catch((err) => {
55
65
  req.payload.logger.error({ err, msg: 'Error closing MCP server' })
@@ -59,6 +69,7 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
59
69
 
60
70
  const handler = createMcpHandler(() => buildMcpServer({ authorizedMCP, pluginConfig, req }), {
61
71
  legacy: 'reject',
72
+ maxRequestBodySize,
62
73
  // SDK subscriptions always use SSE, so disable them to keep every response JSON-only.
63
74
  maxSubscriptions: 0,
64
75
  onerror: (err) => {
@@ -68,10 +79,35 @@ export const mcpEndpoint: PayloadHandler = async (req) => {
68
79
  })
69
80
 
70
81
  try {
71
- return await handler.fetch(mcpRequest)
82
+ return await handler.fetch(mcpRequest, { parsedBody })
72
83
  } finally {
73
84
  await handler.close().catch((err) => {
74
85
  req.payload.logger.error({ err, msg: 'Error closing modern MCP handler' })
75
86
  })
76
87
  }
77
88
  }
89
+
90
+ /**
91
+ * Parses a POST body once so the era check and the SDK handler can share it. The SDK
92
+ * skips its size limit for a pre-parsed body, so this reads with the same limit. It reads
93
+ * a clone and returns `undefined` for any body the SDK should reject (too large, unreadable,
94
+ * or not JSON), leaving the original request for the SDK to read and answer.
95
+ */
96
+ const parseRequestBody = async ({
97
+ maxRequestBodySize,
98
+ request,
99
+ }: {
100
+ maxRequestBodySize?: number
101
+ request: Request
102
+ }): Promise<unknown> => {
103
+ if (request.method.toUpperCase() !== 'POST') {
104
+ return undefined
105
+ }
106
+
107
+ try {
108
+ const body = await readRequestBody(request.clone(), maxRequestBodySize)
109
+ return body.tooLarge ? undefined : JSON.parse(body.text)
110
+ } catch {
111
+ return undefined
112
+ }
113
+ }
@@ -0,0 +1,72 @@
1
+ import type { PayloadHandler, PayloadRequest, SanitizedConfig } from 'payload'
2
+
3
+ import {
4
+ bearerAuthChallengeResponse,
5
+ OAuthError,
6
+ OAuthErrorCode,
7
+ } from '@modelcontextprotocol/server'
8
+
9
+ import { getPluginConfig } from '../utils/getPluginConfig.js'
10
+
11
+ /**
12
+ * Serves the OAuth protected resource metadata (RFC 9728) at `/api/mcp/oauth-protected-resource`.
13
+ * The OAuth challenge links here, so MCP clients find the authorization server without setup.
14
+ */
15
+ export const oauthProtectedResourceEndpoint: PayloadHandler = (req) =>
16
+ getMetadataResponse({ config: req.payload.config, url: req.url! })
17
+
18
+ /**
19
+ * Serves the same metadata for clients that ignore the challenge's link and only look at
20
+ * `/.well-known/oauth-protected-resource`. Mount it at the site root, e.g. in Next.js at
21
+ * `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:
22
+ *
23
+ * ```ts
24
+ * import config from '@payload-config'
25
+ * import { oauthProtectedResourceHandler } from '@payloadcms/plugin-mcp'
26
+ *
27
+ * export const GET = oauthProtectedResourceHandler(config)
28
+ * ```
29
+ */
30
+ export const oauthProtectedResourceHandler =
31
+ (config: Promise<SanitizedConfig> | SanitizedConfig) =>
32
+ async (request: Request): Promise<Response> =>
33
+ getMetadataResponse({ config: await config, url: request.url })
34
+
35
+ /**
36
+ * Answers an unauthenticated MCP request with a challenge linking to the protected resource
37
+ * metadata, which starts the client's OAuth flow.
38
+ */
39
+ export const oauthChallenge = ({ req }: { req: PayloadRequest }): Response =>
40
+ bearerAuthChallengeResponse(
41
+ new OAuthError(OAuthErrorCode.InvalidToken, req.t('error:unauthorized')),
42
+ {
43
+ resourceMetadataUrl: `${getMCPURL({ config: req.payload.config, url: req.url! })}/oauth-protected-resource`,
44
+ },
45
+ )
46
+
47
+ const getMCPURL = ({ config, url }: { config: SanitizedConfig; url: string }): string =>
48
+ new URL(`${config.routes.api}/mcp`, config.serverURL || url).href
49
+
50
+ const getMetadataResponse = ({
51
+ config,
52
+ url,
53
+ }: {
54
+ config: SanitizedConfig
55
+ url: string
56
+ }): Response => {
57
+ const pluginConfig = getPluginConfig({ config })
58
+
59
+ if (!pluginConfig.oauth) {
60
+ return new Response(null, { status: 404 })
61
+ }
62
+
63
+ return Response.json(
64
+ {
65
+ authorization_servers: pluginConfig.oauth.authorizationServers,
66
+ bearer_methods_supported: ['header'],
67
+ resource: pluginConfig.oauth.resource ?? getMCPURL({ config, url }),
68
+ },
69
+ // Public document, readable by browser-based MCP clients on any origin
70
+ { headers: { 'Access-Control-Allow-Origin': '*' } },
71
+ )
72
+ }
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@ import { definePlugin } from 'payload'
3
3
  import type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig } from './types.js'
4
4
 
5
5
  import { mcpEndpoint } from './endpoint/index.js'
6
+ import { oauthProtectedResourceEndpoint } from './endpoint/oauth.js'
6
7
  import { sanitizeMCPConfig } from './mcp/sanitizeMCPConfig.js'
7
8
 
8
9
  declare module 'payload' {
@@ -18,6 +19,7 @@ declare module 'payload' {
18
19
  export type { AuthorizedMCP, MCPPluginConfig, SanitizedMCPPluginConfig }
19
20
 
20
21
  export { defineCollectionTool, defineGlobalTool, definePrompt, defineTool } from './defineTool.js'
22
+ export { oauthProtectedResourceHandler } from './endpoint/oauth.js'
21
23
 
22
24
  export const mcpPlugin = definePlugin<MCPPluginConfig>({
23
25
  slug: '@payloadcms/plugin-mcp',
@@ -49,6 +51,11 @@ export const mcpPlugin = definePlugin<MCPPluginConfig>({
49
51
  method: 'get',
50
52
  path: '/mcp',
51
53
  },
54
+ {
55
+ handler: oauthProtectedResourceEndpoint,
56
+ method: 'get',
57
+ path: '/mcp/oauth-protected-resource',
58
+ },
52
59
  ],
53
60
  }
54
61
  },
@@ -25,7 +25,7 @@ import { toStandardSchema } from '../utils/toStandardSchema.js'
25
25
  *
26
26
  * `req` is the request context handlers see. For HTTP it's the live
27
27
  * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a
28
- * synthesized one built via `createLocalReq`.
28
+ * synthesized one built via `createPayloadRequest`.
29
29
  */
30
30
  export const buildMcpServer = ({
31
31
  authorizedMCP,
@@ -1,4 +1,4 @@
1
- import { createLocalReq, strictObject, z } from 'payload'
1
+ import { createPayloadRequest, strictObject, z } from 'payload'
2
2
 
3
3
  import type { MCPToolResponse } from '../../../types.js'
4
4
 
@@ -53,7 +53,10 @@ export const authCollectionTool = defineCollectionTool({
53
53
  if (input.headers) {
54
54
  authHeaders = new Headers(input.headers)
55
55
  }
56
- const authReq = await createLocalReq({ req: { headers: authHeaders } }, req.payload)
56
+ const authReq = await createPayloadRequest({
57
+ payload: req.payload,
58
+ req: { headers: authHeaders },
59
+ })
57
60
  const result = await req.payload.auth({ headers: authHeaders, req: authReq })
58
61
 
59
62
  if (result.user) {
@@ -1,4 +1,5 @@
1
1
  import { getAccessResults, getCollectionInputSchema, getCollectionSchemaInputSchema } from 'payload'
2
+ import { getLLMInstructions } from 'payload/internal'
2
3
 
3
4
  import { defaultAccess } from '../../../defaultAccess.js'
4
5
  import { defineCollectionTool } from '../../../defineTool.js'
@@ -16,7 +17,8 @@ export const getCollectionSchemaTool = defineCollectionTool({
16
17
  readOnlyHint: true,
17
18
  title: 'Get Collection Schema',
18
19
  },
19
- description: 'Get the input schema for creating or updating documents in a collection.',
20
+ description:
21
+ 'Get the input schema and LLM instructions before creating or updating documents in a collection.',
20
22
  input: getCollectionSchemaInputSchema,
21
23
  }).handler(async ({ slug, authorizedMCP, req }) => {
22
24
  const permissions = authorizedMCP.overrideAccess
@@ -64,17 +66,26 @@ export const getCollectionSchemaTool = defineCollectionTool({
64
66
  }
65
67
  : { enabled: false }
66
68
 
69
+ const instructions = await getLLMInstructions({
70
+ slug,
71
+ type: 'collection',
72
+ overrideAccess: authorizedMCP.overrideAccess,
73
+ req,
74
+ })
75
+
67
76
  return {
68
77
  content: [
69
78
  {
70
79
  type: 'text',
71
80
  text: `Schema for collection "${slug}":\n\`\`\`json\n${JSON.stringify(inputSchema)}\n\`\`\`\nUpload configuration:\n\`\`\`json\n${JSON.stringify(upload)}\n\`\`\``,
72
81
  },
82
+ ...(instructions ? [{ type: 'text' as const, text: instructions }] : []),
73
83
  ],
74
84
  structuredContent: {
75
85
  slug,
76
86
  schema: inputSchema,
77
87
  upload,
88
+ ...(instructions ? { instructions } : {}),
78
89
  },
79
90
  }
80
91
  })
@@ -1,4 +1,5 @@
1
1
  import { getAccessResults, getGlobalInputSchema, getGlobalSchemaInputSchema } from 'payload'
2
+ import { getLLMInstructions } from 'payload/internal'
2
3
 
3
4
  import { defaultAccess } from '../../../defaultAccess.js'
4
5
  import { defineGlobalTool } from '../../../defineTool.js'
@@ -16,7 +17,7 @@ export const getGlobalSchemaTool = defineGlobalTool({
16
17
  readOnlyHint: true,
17
18
  title: 'Get Global Schema',
18
19
  },
19
- description: 'Get the input schema for updating a global.',
20
+ description: 'Get the input schema and LLM instructions before updating a global.',
20
21
  input: getGlobalSchemaInputSchema,
21
22
  }).handler(async ({ slug, authorizedMCP, req }) => {
22
23
  const permissions = authorizedMCP.overrideAccess
@@ -48,16 +49,25 @@ export const getGlobalSchemaTool = defineGlobalTool({
48
49
  }
49
50
  }
50
51
 
52
+ const instructions = await getLLMInstructions({
53
+ slug,
54
+ type: 'global',
55
+ overrideAccess: authorizedMCP.overrideAccess,
56
+ req,
57
+ })
58
+
51
59
  return {
52
60
  content: [
53
61
  {
54
62
  type: 'text',
55
63
  text: `Schema for global "${slug}":\n\`\`\`json\n${JSON.stringify(inputSchema)}\n\`\`\``,
56
64
  },
65
+ ...(instructions ? [{ type: 'text' as const, text: instructions }] : []),
57
66
  ],
58
67
  structuredContent: {
59
68
  slug,
60
69
  schema: inputSchema,
70
+ ...(instructions ? { instructions } : {}),
61
71
  },
62
72
  }
63
73
  })
@@ -103,6 +103,7 @@ export const sanitizeMCPConfig = ({
103
103
  hooks: pluginConfig.hooks,
104
104
  items,
105
105
  mcp: pluginConfig.mcp,
106
+ oauth: pluginConfig.oauth,
106
107
  overrideGetAuthorizedMCP: pluginConfig.overrideGetAuthorizedMCP,
107
108
  }
108
109
  }
package/src/stdio.ts CHANGED
@@ -3,7 +3,7 @@ import type { Config, Plugin, SanitizedConfig } from 'payload'
3
3
  /* eslint-disable no-console */
4
4
  import { serveStdio } from '@modelcontextprotocol/server/stdio'
5
5
  import { fileURLToPath, pathToFileURL } from 'node:url'
6
- import { createLocalReq, getPayload } from 'payload'
6
+ import { createPayloadRequest, getPayload } from 'payload'
7
7
  import { findConfig, loadEnv } from 'payload/node'
8
8
 
9
9
  import type { SanitizedMCPPluginConfig } from './types.js'
@@ -91,7 +91,7 @@ export const runMcpStdio = async (): Promise<void> => {
91
91
  headers.set('Authorization', process.env.PAYLOAD_MCP_AUTHORIZATION)
92
92
  }
93
93
 
94
- const req = await createLocalReq({ req: { headers } }, payload)
94
+ const req = await createPayloadRequest({ payload, req: { headers } })
95
95
  req.payloadAPI = 'MCP' as const
96
96
  const authorizedMCP = await getAuthorizedMCP({ overrideAccess, req })
97
97
 
package/src/types.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import type {
2
2
  CallToolResult,
3
3
  ContentBlock,
4
+ Implementation,
4
5
  JsonSchemaType,
5
- McpServer,
6
+ McpServerOptions,
6
7
  ResourceTemplate,
7
8
  ServerContext,
8
9
  StandardSchemaWithJSON,
@@ -279,9 +280,39 @@ export type MCPPluginConfig = {
279
280
  afterToolCall?: MCPAfterToolCallHook[]
280
281
  }
281
282
  mcp?: {
283
+ /**
284
+ * Largest HTTP request body, in bytes, that the MCP endpoint accepts. Larger requests
285
+ * are answered with `413`. Base64 file uploads count toward this limit.
286
+ *
287
+ * @default 4194304 (4 MiB, the MCP SDK default)
288
+ */
289
+ maxRequestBodySize?: number
282
290
  serverOptions?: MCPServerOptions
283
291
  verboseLogs?: boolean
284
292
  }
293
+ /**
294
+ * Lets MCP clients sign in through an OAuth authorization server. MCP requests without an
295
+ * authenticated user get a `401` that points to the protected resource metadata (RFC 9728),
296
+ * served by `oauthProtectedResourceHandler`. Payload's auth strategies must accept the
297
+ * issued access tokens.
298
+ */
299
+ oauth?: {
300
+ /**
301
+ * Called on MCP requests with a bearer token that Payload's auth strategies didn't accept.
302
+ * Return the Payload user, including its `collection`, or `null` to answer with the OAuth challenge.
303
+ */
304
+ authenticate?: (args: {
305
+ req: PayloadRequest
306
+ token: string
307
+ }) => MaybePromise<PayloadRequest['user']>
308
+ authorizationServers: string[]
309
+ /**
310
+ * The URL clients call to reach the MCP endpoint.
311
+ *
312
+ * @default the absolute URL of `/api/mcp`, based on `serverURL` or the request URL
313
+ */
314
+ resource?: string
315
+ }
285
316
  /**
286
317
  * Replace the default MCP authorization resolver.
287
318
  *
@@ -301,11 +332,11 @@ export type MCPPluginConfig = {
301
332
 
302
333
  export type SanitizedMCPPluginConfig = {
303
334
  items: MCPItem[]
304
- } & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'overrideGetAuthorizedMCP'>
335
+ } & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'oauth' | 'overrideGetAuthorizedMCP'>
305
336
 
306
337
  export type MCPServerOptions = {
307
- options?: ConstructorParameters<typeof McpServer>[1]
308
- serverInfo?: Partial<ConstructorParameters<typeof McpServer>[0]>
338
+ options?: McpServerOptions
339
+ serverInfo?: Partial<Implementation>
309
340
  }
310
341
 
311
342
  /**
@@ -1,86 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { fileInputSchema, resolveFile } from './fileInput.js';
3
- describe('MCP file input', ()=>{
4
- it('should reject malformed MIME types', ()=>{
5
- const result = fileInputSchema.safeParse({
6
- data: 'aGVsbG8=',
7
- mimeType: 'text/plain\r\nx-test: value',
8
- name: 'hello.txt',
9
- source: 'base64'
10
- });
11
- expect(result.success).toBe(false);
12
- });
13
- it('should accept a prepared upload', ()=>{
14
- const result = fileInputSchema.safeParse({
15
- file: {
16
- filename: 'image.png',
17
- mimeType: 'image/png',
18
- size: 123,
19
- uploadReference: {
20
- uploadId: 'upload-id'
21
- }
22
- },
23
- source: 'uploadReference'
24
- });
25
- expect(result.success).toBe(true);
26
- });
27
- it('should reject oversized base64 files', async ()=>{
28
- const req = createRequest({
29
- maxFileSize: 4
30
- });
31
- await expect(resolveFile({
32
- slug: 'media',
33
- input: {
34
- data: Buffer.from('hello').toString('base64'),
35
- mimeType: 'text/plain',
36
- name: 'hello.txt',
37
- source: 'base64'
38
- },
39
- req
40
- })).rejects.toThrow('File exceeds the 4 byte upload limit.');
41
- });
42
- it('should reject URLs outside the collection allowlist', async ()=>{
43
- const req = createRequest({
44
- allowList: [
45
- {
46
- hostname: 'assets.example.com',
47
- protocol: 'https'
48
- }
49
- ]
50
- });
51
- await expect(resolveFile({
52
- slug: 'media',
53
- input: {
54
- source: 'externalURL',
55
- url: 'https://example.com/image.png'
56
- },
57
- req
58
- })).rejects.toThrow('The provided file URL is not allowed.');
59
- });
60
- });
61
- function createRequest({ allowList, maxFileSize }) {
62
- return {
63
- payload: {
64
- collections: {
65
- media: {
66
- config: {
67
- upload: allowList ? {
68
- pasteURL: {
69
- allowList
70
- }
71
- } : {}
72
- }
73
- }
74
- },
75
- config: {
76
- upload: {
77
- limits: {
78
- fileSize: maxFileSize
79
- }
80
- }
81
- }
82
- }
83
- };
84
- }
85
-
86
- //# sourceMappingURL=fileInput.spec.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/fileInput.spec.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { describe, expect, it } from 'vitest'\n\nimport { fileInputSchema, resolveFile } from './fileInput.js'\n\ndescribe('MCP file input', () => {\n it('should reject malformed MIME types', () => {\n const result = fileInputSchema.safeParse({\n data: 'aGVsbG8=',\n mimeType: 'text/plain\\r\\nx-test: value',\n name: 'hello.txt',\n source: 'base64',\n })\n\n expect(result.success).toBe(false)\n })\n\n it('should accept a prepared upload', () => {\n const result = fileInputSchema.safeParse({\n file: {\n filename: 'image.png',\n mimeType: 'image/png',\n size: 123,\n uploadReference: { uploadId: 'upload-id' },\n },\n source: 'uploadReference',\n })\n\n expect(result.success).toBe(true)\n })\n\n it('should reject oversized base64 files', async () => {\n const req = createRequest({ maxFileSize: 4 })\n\n await expect(\n resolveFile({\n slug: 'media',\n input: {\n data: Buffer.from('hello').toString('base64'),\n mimeType: 'text/plain',\n name: 'hello.txt',\n source: 'base64',\n },\n req,\n }),\n ).rejects.toThrow('File exceeds the 4 byte upload limit.')\n })\n\n it('should reject URLs outside the collection allowlist', async () => {\n const req = createRequest({\n allowList: [{ hostname: 'assets.example.com', protocol: 'https' }],\n })\n\n await expect(\n resolveFile({\n slug: 'media',\n input: {\n source: 'externalURL',\n url: 'https://example.com/image.png',\n },\n req,\n }),\n ).rejects.toThrow('The provided file URL is not allowed.')\n })\n})\n\nfunction createRequest({\n allowList,\n maxFileSize,\n}: {\n allowList?: Array<{ hostname: string; protocol: 'http' | 'https' }>\n maxFileSize?: number\n}): PayloadRequest {\n return {\n payload: {\n collections: {\n media: {\n config: {\n upload: allowList ? { pasteURL: { allowList } } : {},\n },\n },\n },\n config: {\n upload: {\n limits: {\n fileSize: maxFileSize,\n },\n },\n },\n },\n } as unknown as PayloadRequest\n}\n"],"names":["describe","expect","it","fileInputSchema","resolveFile","result","safeParse","data","mimeType","name","source","success","toBe","file","filename","size","uploadReference","uploadId","req","createRequest","maxFileSize","slug","input","Buffer","from","toString","rejects","toThrow","allowList","hostname","protocol","url","payload","collections","media","config","upload","pasteURL","limits","fileSize"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAE7C,SAASC,eAAe,EAAEC,WAAW,QAAQ,iBAAgB;AAE7DJ,SAAS,kBAAkB;IACzBE,GAAG,sCAAsC;QACvC,MAAMG,SAASF,gBAAgBG,SAAS,CAAC;YACvCC,MAAM;YACNC,UAAU;YACVC,MAAM;YACNC,QAAQ;QACV;QAEAT,OAAOI,OAAOM,OAAO,EAAEC,IAAI,CAAC;IAC9B;IAEAV,GAAG,mCAAmC;QACpC,MAAMG,SAASF,gBAAgBG,SAAS,CAAC;YACvCO,MAAM;gBACJC,UAAU;gBACVN,UAAU;gBACVO,MAAM;gBACNC,iBAAiB;oBAAEC,UAAU;gBAAY;YAC3C;YACAP,QAAQ;QACV;QAEAT,OAAOI,OAAOM,OAAO,EAAEC,IAAI,CAAC;IAC9B;IAEAV,GAAG,wCAAwC;QACzC,MAAMgB,MAAMC,cAAc;YAAEC,aAAa;QAAE;QAE3C,MAAMnB,OACJG,YAAY;YACViB,MAAM;YACNC,OAAO;gBACLf,MAAMgB,OAAOC,IAAI,CAAC,SAASC,QAAQ,CAAC;gBACpCjB,UAAU;gBACVC,MAAM;gBACNC,QAAQ;YACV;YACAQ;QACF,IACAQ,OAAO,CAACC,OAAO,CAAC;IACpB;IAEAzB,GAAG,uDAAuD;QACxD,MAAMgB,MAAMC,cAAc;YACxBS,WAAW;gBAAC;oBAAEC,UAAU;oBAAsBC,UAAU;gBAAQ;aAAE;QACpE;QAEA,MAAM7B,OACJG,YAAY;YACViB,MAAM;YACNC,OAAO;gBACLZ,QAAQ;gBACRqB,KAAK;YACP;YACAb;QACF,IACAQ,OAAO,CAACC,OAAO,CAAC;IACpB;AACF;AAEA,SAASR,cAAc,EACrBS,SAAS,EACTR,WAAW,EAIZ;IACC,OAAO;QACLY,SAAS;YACPC,aAAa;gBACXC,OAAO;oBACLC,QAAQ;wBACNC,QAAQR,YAAY;4BAAES,UAAU;gCAAET;4BAAU;wBAAE,IAAI,CAAC;oBACrD;gBACF;YACF;YACAO,QAAQ;gBACNC,QAAQ;oBACNE,QAAQ;wBACNC,UAAUnB;oBACZ;gBACF;YACF;QACF;IACF;AACF"}