@payloadcms/plugin-mcp 4.0.0-internal.5214550 → 4.0.0-internal.532221d
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 +7 -0
- package/dist/defaultAccess.d.ts.map +1 -1
- package/dist/defineTool.d.ts +8 -8
- package/dist/defineTool.d.ts.map +1 -1
- package/dist/endpoint/access.d.ts.map +1 -1
- package/dist/mcp/buildMcpServer.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
- package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/createTool.js +92 -41
- package/dist/mcp/builtin/collections/createTool.js.map +1 -1
- package/dist/mcp/builtin/collections/duplicateTool.js +1 -2
- package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
- package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
- package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
- package/dist/mcp/builtin/collections/fileInput.js +124 -0
- package/dist/mcp/builtin/collections/fileInput.js.map +1 -0
- package/dist/mcp/builtin/collections/fileInput.spec.js +86 -0
- package/dist/mcp/builtin/collections/fileInput.spec.js.map +1 -0
- package/dist/mcp/builtin/collections/findTool.js +1 -1
- package/dist/mcp/builtin/collections/findTool.js.map +1 -1
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts +1 -1
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/formatCollectionError.js +1 -1
- package/dist/mcp/builtin/collections/formatCollectionError.js.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +25 -4
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.js +23 -12
- package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
- package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +2 -0
- package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +1 -0
- package/dist/mcp/builtin/collections/uploadInstructionsTool.js +55 -0
- package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +1 -0
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +1 -2
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/globals/updateTool.js +1 -2
- package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
- package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -1
- package/dist/mcp/builtin/validateEntityData.js +1 -1
- package/dist/mcp/builtin/validateEntityData.js.map +1 -1
- package/dist/mcp/builtinTools.d.ts +6 -0
- package/dist/mcp/builtinTools.d.ts.map +1 -1
- package/dist/mcp/builtinTools.js +9 -3
- package/dist/mcp/builtinTools.js.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.js +4 -1
- package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
- package/dist/stdio.d.ts.map +1 -1
- package/dist/stdio.js +2 -1
- package/dist/stdio.js.map +1 -1
- package/dist/utils/camelCase.d.ts.map +1 -1
- package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
- package/dist/utils/toStandardSchema.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/mcp/builtin/collections/createTool.ts +95 -38
- package/src/mcp/builtin/collections/duplicateTool.ts +5 -5
- package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
- package/src/mcp/builtin/collections/fileInput.ts +164 -0
- package/src/mcp/builtin/collections/findTool.ts +1 -1
- package/src/mcp/builtin/collections/formatCollectionError.ts +2 -2
- package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +19 -3
- package/src/mcp/builtin/collections/updateTool.ts +30 -13
- package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
- package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +1 -2
- package/src/mcp/builtin/globals/updateTool.ts +5 -5
- package/src/mcp/builtin/validateEntityData.ts +3 -7
- package/src/mcp/builtinTools.ts +9 -2
- package/src/mcp/sanitizeMCPConfig.ts +4 -1
- package/src/stdio.ts +2 -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/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
|
@@ -1,22 +1,23 @@
|
|
|
1
1
|
import type { SelectType } from 'payload'
|
|
2
2
|
|
|
3
|
+
import {
|
|
4
|
+
getCollectionVirtualFieldNames,
|
|
5
|
+
stripVirtualFields,
|
|
6
|
+
transformPointDataToPayload,
|
|
7
|
+
} from 'payload'
|
|
3
8
|
import { z } from 'zod'
|
|
4
9
|
|
|
5
10
|
import { defaultAccess } from '../../../defaultAccess.js'
|
|
6
11
|
import { defineCollectionTool } from '../../../defineTool.js'
|
|
7
12
|
import { getLogger } from '../../../utils/getLogger.js'
|
|
8
|
-
import {
|
|
9
|
-
getCollectionVirtualFieldNames,
|
|
10
|
-
stripVirtualFields,
|
|
11
|
-
} from '../../../utils/getVirtualFieldNames.js'
|
|
12
|
-
import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
|
|
13
13
|
import { validateCollectionData } from '../validateEntityData.js'
|
|
14
|
+
import { fileInputSchema, resolveFile } from './fileInput.js'
|
|
14
15
|
import { formatCollectionError } from './formatCollectionError.js'
|
|
15
16
|
|
|
16
17
|
const DEFAULT_DESCRIPTION =
|
|
17
|
-
'Create a
|
|
18
|
+
'Create one or more documents. Each can have different data or a file. Prefer uploadReference after upload, externalURL for URLs, or base64 for small local files.'
|
|
18
19
|
|
|
19
|
-
export const
|
|
20
|
+
export const createDocumentsTool = defineCollectionTool({
|
|
20
21
|
access: (args) =>
|
|
21
22
|
defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),
|
|
22
23
|
annotations: {
|
|
@@ -24,11 +25,10 @@ export const createDocumentTool = defineCollectionTool({
|
|
|
24
25
|
idempotentHint: false,
|
|
25
26
|
openWorldHint: false,
|
|
26
27
|
readOnlyHint: false,
|
|
27
|
-
title: 'Create
|
|
28
|
+
title: 'Create Documents',
|
|
28
29
|
},
|
|
29
30
|
description: DEFAULT_DESCRIPTION,
|
|
30
31
|
input: z.object({
|
|
31
|
-
data: z.record(z.string(), z.unknown()).describe('The document fields to create'),
|
|
32
32
|
depth: z
|
|
33
33
|
.number()
|
|
34
34
|
.int()
|
|
@@ -37,9 +37,24 @@ export const createDocumentTool = defineCollectionTool({
|
|
|
37
37
|
.describe('How many levels deep to populate relationships in response')
|
|
38
38
|
.optional()
|
|
39
39
|
.default(0),
|
|
40
|
+
documents: z
|
|
41
|
+
.array(
|
|
42
|
+
z.object({
|
|
43
|
+
data: z
|
|
44
|
+
.record(z.string(), z.unknown())
|
|
45
|
+
.describe(
|
|
46
|
+
'The document fields to create. Only include fields permitted by the schema returned by getCollectionSchema.',
|
|
47
|
+
),
|
|
48
|
+
file: fileInputSchema.optional(),
|
|
49
|
+
}),
|
|
50
|
+
)
|
|
51
|
+
.min(1)
|
|
52
|
+
.describe('The documents to create, in order'),
|
|
40
53
|
draft: z
|
|
41
54
|
.boolean()
|
|
42
|
-
.describe(
|
|
55
|
+
.describe(
|
|
56
|
+
'Only if getCollectionSchema includes _status; otherwise _status does not exist. true forces data._status to "draft"; with false, data._status controls draft or published.',
|
|
57
|
+
)
|
|
43
58
|
.optional()
|
|
44
59
|
.default(false),
|
|
45
60
|
fallbackLocale: z
|
|
@@ -49,7 +64,7 @@ export const createDocumentTool = defineCollectionTool({
|
|
|
49
64
|
locale: z
|
|
50
65
|
.string()
|
|
51
66
|
.describe(
|
|
52
|
-
'Optional: locale code to create the
|
|
67
|
+
'Optional: locale code to create the documents in (e.g., "en", "es"). Defaults to the default locale',
|
|
53
68
|
)
|
|
54
69
|
.optional(),
|
|
55
70
|
select: z
|
|
@@ -62,50 +77,92 @@ export const createDocumentTool = defineCollectionTool({
|
|
|
62
77
|
}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {
|
|
63
78
|
const payload = req.payload
|
|
64
79
|
const logger = getLogger({ payload })
|
|
80
|
+
const { depth, documents, draft, fallbackLocale, locale, select } = input
|
|
65
81
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
logger.info(
|
|
69
|
-
`Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,
|
|
70
|
-
)
|
|
82
|
+
logger.info(`Creating ${documents.length} documents in collection: ${collectionSlug}`)
|
|
71
83
|
|
|
72
84
|
try {
|
|
73
85
|
const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)
|
|
74
|
-
const
|
|
75
|
-
const
|
|
86
|
+
const docs: Array<{ doc: Record<string, unknown>; index: number }> = []
|
|
87
|
+
const errors: Array<{ index: number; message: string }> = []
|
|
88
|
+
let validationSchema: Record<string, unknown> | undefined
|
|
76
89
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
90
|
+
for (const [index, document] of documents.entries()) {
|
|
91
|
+
try {
|
|
92
|
+
const inputData = stripVirtualFields(document.data, virtualFieldNames)
|
|
93
|
+
const validationError = validateCollectionData({ collectionSlug, data: inputData, req })
|
|
94
|
+
|
|
95
|
+
if (validationError) {
|
|
96
|
+
const firstContent = validationError.content[0]
|
|
97
|
+
const validationContent = validationError.structuredContent as
|
|
98
|
+
| Record<string, unknown>
|
|
99
|
+
| undefined
|
|
100
|
+
const schema = validationContent?.schema
|
|
80
101
|
|
|
81
|
-
|
|
102
|
+
if (!validationSchema && schema && typeof schema === 'object') {
|
|
103
|
+
validationSchema = schema as Record<string, unknown>
|
|
104
|
+
}
|
|
82
105
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
...(select ? { select: select as SelectType } : {}),
|
|
93
|
-
})
|
|
106
|
+
errors.push({
|
|
107
|
+
index,
|
|
108
|
+
message:
|
|
109
|
+
firstContent?.type === 'text'
|
|
110
|
+
? (firstContent.text.split('\n\nUse this schema')[0] ?? 'Invalid document data')
|
|
111
|
+
: 'Invalid document data',
|
|
112
|
+
})
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
94
115
|
|
|
95
|
-
|
|
116
|
+
const parsedData = transformPointDataToPayload(inputData)
|
|
117
|
+
const file = await resolveFile({ collectionSlug, input: document.file, req })
|
|
118
|
+
const result = await payload.create({
|
|
119
|
+
collection: collectionSlug,
|
|
120
|
+
data: parsedData,
|
|
121
|
+
depth,
|
|
122
|
+
draft,
|
|
123
|
+
overrideAccess: authorizedMCP.overrideAccess,
|
|
124
|
+
req,
|
|
125
|
+
...(file ? { file } : {}),
|
|
126
|
+
...(locale ? { locale } : {}),
|
|
127
|
+
...(fallbackLocale ? { fallbackLocale } : {}),
|
|
128
|
+
...(select ? { select: select as SelectType } : {}),
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
docs.push({ doc: result as Record<string, unknown>, index })
|
|
132
|
+
} catch (error) {
|
|
133
|
+
const message = error instanceof Error ? error.message : 'Unknown error'
|
|
134
|
+
|
|
135
|
+
logger.error(`Error creating document at index ${index} in ${collectionSlug}: ${message}`)
|
|
136
|
+
errors.push({ index, message })
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const batchResult = { docs, errors }
|
|
141
|
+
const retryMessage = errors.length > 0 ? '\nRetry failed indexes only.' : ''
|
|
142
|
+
const schemaMessage = validationSchema
|
|
143
|
+
? `\n\nUse this schema for data:\n\`\`\`json\n${JSON.stringify(validationSchema)}\n\`\`\``
|
|
144
|
+
: ''
|
|
145
|
+
const structuredContent = validationSchema
|
|
146
|
+
? { ...batchResult, schema: validationSchema }
|
|
147
|
+
: batchResult
|
|
148
|
+
|
|
149
|
+
logger.info(`Created ${docs.length} of ${documents.length} documents in ${collectionSlug}`)
|
|
96
150
|
|
|
97
151
|
return {
|
|
98
152
|
content: [
|
|
99
153
|
{
|
|
100
154
|
type: 'text',
|
|
101
|
-
text: `
|
|
155
|
+
text: `Created ${docs.length} of ${documents.length} documents in collection "${collectionSlug}".${retryMessage}\nResults:\n\`\`\`json\n${JSON.stringify(batchResult)}\n\`\`\`${schemaMessage}`,
|
|
102
156
|
},
|
|
103
157
|
],
|
|
104
|
-
doc:
|
|
158
|
+
doc: structuredContent as unknown as Record<string, unknown>,
|
|
159
|
+
isError: docs.length === 0 && errors.length > 0,
|
|
160
|
+
structuredContent,
|
|
105
161
|
}
|
|
106
162
|
} catch (error) {
|
|
107
|
-
const
|
|
108
|
-
|
|
163
|
+
const message = error instanceof Error ? error.message : 'Unknown error'
|
|
164
|
+
|
|
165
|
+
logger.error(`Error creating documents in ${collectionSlug}: ${message}`)
|
|
109
166
|
return formatCollectionError({ action: 'creating', collectionSlug, error, req })
|
|
110
167
|
}
|
|
111
168
|
})
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import type { PopulateType, SelectType } from 'payload'
|
|
2
2
|
|
|
3
|
+
import {
|
|
4
|
+
getCollectionVirtualFieldNames,
|
|
5
|
+
stripVirtualFields,
|
|
6
|
+
transformPointDataToPayload,
|
|
7
|
+
} from 'payload'
|
|
3
8
|
import { z } from 'zod'
|
|
4
9
|
|
|
5
10
|
import { defaultAccess } from '../../../defaultAccess.js'
|
|
6
11
|
import { defineCollectionTool } from '../../../defineTool.js'
|
|
7
12
|
import { getLogger } from '../../../utils/getLogger.js'
|
|
8
|
-
import {
|
|
9
|
-
getCollectionVirtualFieldNames,
|
|
10
|
-
stripVirtualFields,
|
|
11
|
-
} from '../../../utils/getVirtualFieldNames.js'
|
|
12
|
-
import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
|
|
13
13
|
import { formatCollectionError } from './formatCollectionError.js'
|
|
14
14
|
|
|
15
15
|
const DEFAULT_DESCRIPTION =
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload'
|
|
2
|
+
|
|
3
|
+
import { describe, expect, it } from 'vitest'
|
|
4
|
+
|
|
5
|
+
import { fileInputSchema, resolveFile } from './fileInput.js'
|
|
6
|
+
|
|
7
|
+
describe('MCP file input', () => {
|
|
8
|
+
it('should reject malformed MIME types', () => {
|
|
9
|
+
const result = fileInputSchema.safeParse({
|
|
10
|
+
data: 'aGVsbG8=',
|
|
11
|
+
mimeType: 'text/plain\r\nx-test: value',
|
|
12
|
+
name: 'hello.txt',
|
|
13
|
+
source: 'base64',
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
expect(result.success).toBe(false)
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
it('should accept a prepared upload', () => {
|
|
20
|
+
const result = fileInputSchema.safeParse({
|
|
21
|
+
file: {
|
|
22
|
+
filename: 'image.png',
|
|
23
|
+
mimeType: 'image/png',
|
|
24
|
+
size: 123,
|
|
25
|
+
uploadReference: { uploadId: 'upload-id' },
|
|
26
|
+
},
|
|
27
|
+
source: 'uploadReference',
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
expect(result.success).toBe(true)
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('should reject oversized base64 files', async () => {
|
|
34
|
+
const req = createRequest({ maxFileSize: 4 })
|
|
35
|
+
|
|
36
|
+
await expect(
|
|
37
|
+
resolveFile({
|
|
38
|
+
collectionSlug: 'media',
|
|
39
|
+
input: {
|
|
40
|
+
data: Buffer.from('hello').toString('base64'),
|
|
41
|
+
mimeType: 'text/plain',
|
|
42
|
+
name: 'hello.txt',
|
|
43
|
+
source: 'base64',
|
|
44
|
+
},
|
|
45
|
+
req,
|
|
46
|
+
}),
|
|
47
|
+
).rejects.toThrow('File exceeds the 4 byte upload limit.')
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it('should reject URLs outside the collection allowlist', async () => {
|
|
51
|
+
const req = createRequest({
|
|
52
|
+
allowList: [{ hostname: 'assets.example.com', protocol: 'https' }],
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
await expect(
|
|
56
|
+
resolveFile({
|
|
57
|
+
collectionSlug: 'media',
|
|
58
|
+
input: {
|
|
59
|
+
source: 'externalURL',
|
|
60
|
+
url: 'https://example.com/image.png',
|
|
61
|
+
},
|
|
62
|
+
req,
|
|
63
|
+
}),
|
|
64
|
+
).rejects.toThrow('The provided file URL is not allowed.')
|
|
65
|
+
})
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
function createRequest({
|
|
69
|
+
allowList,
|
|
70
|
+
maxFileSize,
|
|
71
|
+
}: {
|
|
72
|
+
allowList?: Array<{ hostname: string; protocol: 'http' | 'https' }>
|
|
73
|
+
maxFileSize?: number
|
|
74
|
+
}): PayloadRequest {
|
|
75
|
+
return {
|
|
76
|
+
payload: {
|
|
77
|
+
collections: {
|
|
78
|
+
media: {
|
|
79
|
+
config: {
|
|
80
|
+
upload: allowList ? { pasteURL: { allowList } } : {},
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
config: {
|
|
85
|
+
upload: {
|
|
86
|
+
limits: {
|
|
87
|
+
fileSize: maxFileSize,
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
} as unknown as PayloadRequest
|
|
93
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import type { CollectionSlug, File, FileData, PayloadRequest } from 'payload'
|
|
2
|
+
|
|
3
|
+
import { APIError } from 'payload'
|
|
4
|
+
import { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal'
|
|
5
|
+
import { sanitizeFilename } from 'payload/shared'
|
|
6
|
+
import { z } from 'zod'
|
|
7
|
+
|
|
8
|
+
const mimeTypeSchema = z
|
|
9
|
+
.string()
|
|
10
|
+
.regex(/^[!#$%&'*+.^`|~\w-]+\/[!#$%&'*+.^`|~\w-]+$/, 'MIME type must use the type/subtype format')
|
|
11
|
+
|
|
12
|
+
const uploadFileSchema = z.object({
|
|
13
|
+
filename: z.string(),
|
|
14
|
+
mimeType: z.string(),
|
|
15
|
+
size: z.number().int().nonnegative(),
|
|
16
|
+
uploadReference: z.record(z.string(), z.unknown()),
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
export const fileInputSchema = z
|
|
20
|
+
.discriminatedUnion('source', [
|
|
21
|
+
z.object({
|
|
22
|
+
name: z.string().min(1).describe('The file name, including its extension'),
|
|
23
|
+
data: z.string().describe('The base64-encoded file bytes, without a data URL prefix'),
|
|
24
|
+
mimeType: mimeTypeSchema.describe('The file MIME type, for example image/png'),
|
|
25
|
+
source: z.literal('base64'),
|
|
26
|
+
}),
|
|
27
|
+
z.object({
|
|
28
|
+
name: z.string().min(1).describe('Optional file name override').optional(),
|
|
29
|
+
source: z.literal('externalURL'),
|
|
30
|
+
url: z.url().describe('The http or https URL to download'),
|
|
31
|
+
}),
|
|
32
|
+
z.object({
|
|
33
|
+
file: uploadFileSchema.describe('getUploadInstructions file field post-upload'),
|
|
34
|
+
source: z.literal('uploadReference'),
|
|
35
|
+
}),
|
|
36
|
+
])
|
|
37
|
+
.describe(
|
|
38
|
+
'A file for an upload collection. Prefer uploadReference after its upload succeeds; use base64 only for small local files or externalURL for an online file.',
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
type FileInput = z.infer<typeof fileInputSchema>
|
|
42
|
+
|
|
43
|
+
export async function resolveFile({
|
|
44
|
+
collectionSlug,
|
|
45
|
+
input,
|
|
46
|
+
req,
|
|
47
|
+
}: {
|
|
48
|
+
collectionSlug: CollectionSlug
|
|
49
|
+
input?: FileInput
|
|
50
|
+
req: PayloadRequest
|
|
51
|
+
}): Promise<File | undefined> {
|
|
52
|
+
if (!input) {
|
|
53
|
+
return undefined
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (input.source === 'uploadReference') {
|
|
57
|
+
try {
|
|
58
|
+
return await getFileFromUploadInstructions({ collectionSlug, file: input.file, req })
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error instanceof Error && error.message === 'Staged upload was not found.') {
|
|
61
|
+
throw new APIError(
|
|
62
|
+
'Staged upload not found. Complete the upload action first, or use base64 for small local files.',
|
|
63
|
+
400,
|
|
64
|
+
)
|
|
65
|
+
}
|
|
66
|
+
throw error
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const uploadConfig = req.payload.collections[collectionSlug]?.config.upload
|
|
71
|
+
|
|
72
|
+
if (!uploadConfig) {
|
|
73
|
+
throw new APIError(`Collection "${collectionSlug}" does not support file uploads.`, 400)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const maxFileSize = req.payload.config.upload.limits?.fileSize
|
|
77
|
+
let file: File
|
|
78
|
+
|
|
79
|
+
if (input.source === 'base64') {
|
|
80
|
+
const data = decodeBase64({ maxFileSize, value: input.data })
|
|
81
|
+
|
|
82
|
+
file = {
|
|
83
|
+
name: sanitizeFilename(input.name),
|
|
84
|
+
data,
|
|
85
|
+
mimetype: input.mimeType,
|
|
86
|
+
size: data.length,
|
|
87
|
+
}
|
|
88
|
+
} else {
|
|
89
|
+
if (uploadConfig.pasteURL === false) {
|
|
90
|
+
throw new APIError(
|
|
91
|
+
`Uploading files from URLs is disabled for collection "${collectionSlug}".`,
|
|
92
|
+
400,
|
|
93
|
+
)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const url = new URL(input.url)
|
|
97
|
+
|
|
98
|
+
if (!['http:', 'https:'].includes(url.protocol)) {
|
|
99
|
+
throw new APIError('File URLs must use http or https.', 400)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (
|
|
103
|
+
typeof uploadConfig.pasteURL === 'object' &&
|
|
104
|
+
!isURLAllowed(input.url, uploadConfig.pasteURL.allowList)
|
|
105
|
+
) {
|
|
106
|
+
throw new APIError('The provided file URL is not allowed.', 400)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
file = await getExternalFile({
|
|
110
|
+
data: {
|
|
111
|
+
filename: sanitizeFilename(input.name || getURLFilename(url)),
|
|
112
|
+
url: input.url,
|
|
113
|
+
} as FileData,
|
|
114
|
+
req,
|
|
115
|
+
uploadConfig: {
|
|
116
|
+
...uploadConfig,
|
|
117
|
+
externalFileHeaderFilter: uploadConfig.externalFileHeaderFilter ?? (() => ({})),
|
|
118
|
+
},
|
|
119
|
+
})
|
|
120
|
+
file.mimetype = file.mimetype?.split(';')[0] || 'application/octet-stream'
|
|
121
|
+
file.size = file.data.length
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {
|
|
125
|
+
throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return file
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function decodeBase64({ maxFileSize, value }: { maxFileSize?: number; value: string }): Buffer {
|
|
132
|
+
const normalized = value.replace(/\s/g, '')
|
|
133
|
+
|
|
134
|
+
if (!/^[a-z0-9+/]*={0,2}$/i.test(normalized) || normalized.length % 4 === 1) {
|
|
135
|
+
throw new APIError('File data must be valid base64.', 400)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (maxFileSize !== undefined && Number.isFinite(maxFileSize)) {
|
|
139
|
+
const paddingLength = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0
|
|
140
|
+
const decodedSize = Math.floor((normalized.length * 3) / 4) - paddingLength
|
|
141
|
+
|
|
142
|
+
if (decodedSize > maxFileSize) {
|
|
143
|
+
throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const data = Buffer.from(normalized, 'base64')
|
|
148
|
+
|
|
149
|
+
if (data.toString('base64').replace(/=+$/, '') !== normalized.replace(/=+$/, '')) {
|
|
150
|
+
throw new APIError('File data must be valid base64.', 400)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return data
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function getURLFilename(url: URL): string {
|
|
157
|
+
const pathSegment = url.pathname.split('/').pop() || 'upload'
|
|
158
|
+
|
|
159
|
+
try {
|
|
160
|
+
return decodeURIComponent(pathSegment)
|
|
161
|
+
} catch {
|
|
162
|
+
return pathSegment
|
|
163
|
+
}
|
|
164
|
+
}
|
|
@@ -39,7 +39,7 @@ export const findDocumentsTool = defineCollectionTool({
|
|
|
39
39
|
draft: z
|
|
40
40
|
.boolean()
|
|
41
41
|
.describe(
|
|
42
|
-
'
|
|
42
|
+
'For versioned collections, true returns the latest draft version when available. False reads the main document.',
|
|
43
43
|
)
|
|
44
44
|
.optional(),
|
|
45
45
|
fallbackLocale: z
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { CollectionSlug, PayloadRequest } from 'payload'
|
|
2
2
|
|
|
3
|
-
import
|
|
3
|
+
import { getCollectionInputSchema } from 'payload'
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import type { MCPToolResponse } from '../../../types.js'
|
|
6
6
|
|
|
7
7
|
const getValidationErrors = (error: unknown): undefined | unknown[] => {
|
|
8
8
|
if (!error || typeof error !== 'object') {
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { getAccessResults } from 'payload'
|
|
1
|
+
import { getAccessResults, getCollectionInputSchema } from 'payload'
|
|
2
2
|
|
|
3
3
|
import { defaultAccess } from '../../../defaultAccess.js'
|
|
4
4
|
import { defineCollectionTool } from '../../../defineTool.js'
|
|
5
|
-
import { getCollectionInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js'
|
|
6
5
|
|
|
7
6
|
export const getCollectionSchemaTool = defineCollectionTool({
|
|
8
7
|
access: (args) => {
|
|
@@ -48,16 +47,33 @@ export const getCollectionSchemaTool = defineCollectionTool({
|
|
|
48
47
|
}
|
|
49
48
|
}
|
|
50
49
|
|
|
50
|
+
const uploadConfig = req.payload.collections[collectionSlug]?.config.upload
|
|
51
|
+
const maxFileSize = req.payload.config.upload.limits?.fileSize
|
|
52
|
+
const upload = uploadConfig
|
|
53
|
+
? {
|
|
54
|
+
enabled: true,
|
|
55
|
+
filesRequiredOnCreate: uploadConfig.filesRequiredOnCreate !== false,
|
|
56
|
+
mimeTypes: uploadConfig.mimeTypes ?? ['*/*'],
|
|
57
|
+
sources: [
|
|
58
|
+
...(uploadConfig.pasteURL !== false ? ['externalURL'] : []),
|
|
59
|
+
'base64',
|
|
60
|
+
'uploadReference',
|
|
61
|
+
],
|
|
62
|
+
...(typeof maxFileSize === 'number' && Number.isFinite(maxFileSize) ? { maxFileSize } : {}),
|
|
63
|
+
}
|
|
64
|
+
: { enabled: false }
|
|
65
|
+
|
|
51
66
|
return {
|
|
52
67
|
content: [
|
|
53
68
|
{
|
|
54
69
|
type: 'text',
|
|
55
|
-
text: `Schema for collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(inputSchema)}\n\`\`\``,
|
|
70
|
+
text: `Schema for collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(inputSchema)}\n\`\`\`\nUpload configuration:\n\`\`\`json\n${JSON.stringify(upload)}\n\`\`\``,
|
|
56
71
|
},
|
|
57
72
|
],
|
|
58
73
|
structuredContent: {
|
|
59
74
|
collectionSlug,
|
|
60
75
|
schema: inputSchema,
|
|
76
|
+
upload,
|
|
61
77
|
},
|
|
62
78
|
}
|
|
63
79
|
})
|
|
@@ -1,22 +1,23 @@
|
|
|
1
1
|
import type { SelectType, Where } from 'payload'
|
|
2
2
|
|
|
3
|
+
import {
|
|
4
|
+
getCollectionInputSchema,
|
|
5
|
+
getCollectionVirtualFieldNames,
|
|
6
|
+
stripVirtualFields,
|
|
7
|
+
transformPointDataToPayload,
|
|
8
|
+
} from 'payload'
|
|
3
9
|
import { z } from 'zod'
|
|
4
10
|
|
|
5
11
|
import { defaultAccess } from '../../../defaultAccess.js'
|
|
6
12
|
import { defineCollectionTool } from '../../../defineTool.js'
|
|
7
13
|
import { getLogger } from '../../../utils/getLogger.js'
|
|
8
|
-
import {
|
|
9
|
-
getCollectionVirtualFieldNames,
|
|
10
|
-
stripVirtualFields,
|
|
11
|
-
} from '../../../utils/getVirtualFieldNames.js'
|
|
12
|
-
import { getCollectionInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js'
|
|
13
|
-
import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
|
|
14
14
|
import { whereSchema } from '../../../utils/whereSchema.js'
|
|
15
15
|
import { validateCollectionData } from '../validateEntityData.js'
|
|
16
|
+
import { fileInputSchema, resolveFile } from './fileInput.js'
|
|
16
17
|
import { formatCollectionError } from './formatCollectionError.js'
|
|
17
18
|
|
|
18
19
|
const DEFAULT_DESCRIPTION =
|
|
19
|
-
'Update documents
|
|
20
|
+
'Update documents. Prefer uploadReference after upload, externalURL for URLs, or base64 for small local files.'
|
|
20
21
|
|
|
21
22
|
export const updateDocumentTool = defineCollectionTool({
|
|
22
23
|
access: (args) =>
|
|
@@ -31,7 +32,11 @@ export const updateDocumentTool = defineCollectionTool({
|
|
|
31
32
|
description: DEFAULT_DESCRIPTION,
|
|
32
33
|
input: z.object({
|
|
33
34
|
id: z.union([z.string(), z.number()]).describe('The ID of the document to update').optional(),
|
|
34
|
-
data: z
|
|
35
|
+
data: z
|
|
36
|
+
.record(z.string(), z.unknown())
|
|
37
|
+
.describe(
|
|
38
|
+
'The fields to update. Only include fields permitted by the schema returned by getCollectionSchema.',
|
|
39
|
+
),
|
|
35
40
|
depth: z
|
|
36
41
|
.number()
|
|
37
42
|
.describe('How many levels deep to populate relationships')
|
|
@@ -39,14 +44,16 @@ export const updateDocumentTool = defineCollectionTool({
|
|
|
39
44
|
.default(0),
|
|
40
45
|
draft: z
|
|
41
46
|
.boolean()
|
|
42
|
-
.describe(
|
|
47
|
+
.describe(
|
|
48
|
+
'Only if getCollectionSchema includes _status; otherwise _status does not exist. true saves only a draft version; false updates main and versions. data._status: "published" overrides true.',
|
|
49
|
+
)
|
|
43
50
|
.optional()
|
|
44
51
|
.default(false),
|
|
45
52
|
fallbackLocale: z
|
|
46
53
|
.string()
|
|
47
54
|
.describe('Optional: fallback locale code to use when requested locale is not available')
|
|
48
55
|
.optional(),
|
|
49
|
-
|
|
56
|
+
file: fileInputSchema.optional(),
|
|
50
57
|
locale: z
|
|
51
58
|
.string()
|
|
52
59
|
.describe(
|
|
@@ -63,6 +70,12 @@ export const updateDocumentTool = defineCollectionTool({
|
|
|
63
70
|
.describe('Whether to overwrite existing files')
|
|
64
71
|
.optional()
|
|
65
72
|
.default(false),
|
|
73
|
+
publishAllLocales: z
|
|
74
|
+
.boolean()
|
|
75
|
+
.describe(
|
|
76
|
+
'For collections with localized publishing status, whether publishing should affect every locale. Set false with locale to publish only that locale.',
|
|
77
|
+
)
|
|
78
|
+
.optional(),
|
|
66
79
|
select: z
|
|
67
80
|
.record(z.string(), z.unknown())
|
|
68
81
|
.describe(
|
|
@@ -85,10 +98,11 @@ export const updateDocumentTool = defineCollectionTool({
|
|
|
85
98
|
depth,
|
|
86
99
|
draft,
|
|
87
100
|
fallbackLocale,
|
|
88
|
-
|
|
101
|
+
file: fileInput,
|
|
89
102
|
locale,
|
|
90
103
|
overrideLock,
|
|
91
104
|
overwriteExistingFiles,
|
|
105
|
+
publishAllLocales,
|
|
92
106
|
select,
|
|
93
107
|
where,
|
|
94
108
|
} = input
|
|
@@ -118,6 +132,7 @@ export const updateDocumentTool = defineCollectionTool({
|
|
|
118
132
|
}
|
|
119
133
|
|
|
120
134
|
const parsedData = transformPointDataToPayload(inputData)
|
|
135
|
+
const file = await resolveFile({ collectionSlug, input: fileInput, req })
|
|
121
136
|
|
|
122
137
|
const whereClause: Where = where ?? {}
|
|
123
138
|
|
|
@@ -131,8 +146,9 @@ export const updateDocumentTool = defineCollectionTool({
|
|
|
131
146
|
overrideAccess: authorizedMCP.overrideAccess,
|
|
132
147
|
overrideLock,
|
|
133
148
|
req,
|
|
134
|
-
...(
|
|
149
|
+
...(file ? { file } : {}),
|
|
135
150
|
...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),
|
|
151
|
+
...(publishAllLocales !== undefined ? { publishAllLocales } : {}),
|
|
136
152
|
...(locale ? { locale } : {}),
|
|
137
153
|
...(fallbackLocale ? { fallbackLocale } : {}),
|
|
138
154
|
...(select ? { select: select as SelectType } : {}),
|
|
@@ -158,8 +174,9 @@ export const updateDocumentTool = defineCollectionTool({
|
|
|
158
174
|
overrideLock,
|
|
159
175
|
req,
|
|
160
176
|
where: whereClause,
|
|
161
|
-
...(
|
|
177
|
+
...(file ? { file } : {}),
|
|
162
178
|
...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),
|
|
179
|
+
...(publishAllLocales !== undefined ? { publishAllLocales } : {}),
|
|
163
180
|
...(locale ? { locale } : {}),
|
|
164
181
|
...(fallbackLocale ? { fallbackLocale } : {}),
|
|
165
182
|
...(select ? { select: select as SelectType } : {}),
|