@payloadcms/plugin-mcp 4.0.0-internal.e387174 → 4.0.0-internal.e38d3ac
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/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 +90 -38
- package/dist/mcp/builtin/collections/createTool.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/formatCollectionError.d.ts +1 -1
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +24 -2
- 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 +13 -7
- 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/validateEntityData.d.ts.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/schemaConversion/filterFieldsByAccess.d.ts.map +1 -1
- package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.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 +87 -36
- package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
- package/src/mcp/builtin/collections/fileInput.ts +164 -0
- package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +18 -1
- package/src/mcp/builtin/collections/updateTool.ts +7 -5
- package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
- package/src/mcp/builtinTools.ts +9 -2
- package/src/mcp/sanitizeMCPConfig.ts +4 -1
- package/src/stdio.ts +2 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payloadcms/plugin-mcp",
|
|
3
|
-
"version": "4.0.0-internal.
|
|
3
|
+
"version": "4.0.0-internal.e38d3ac",
|
|
4
4
|
"description": "MCP (Model Context Protocol) capabilities with Payload",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"plugin",
|
|
@@ -55,16 +55,16 @@
|
|
|
55
55
|
"bin.js"
|
|
56
56
|
],
|
|
57
57
|
"dependencies": {
|
|
58
|
-
"@modelcontextprotocol/server": "2.0.0
|
|
58
|
+
"@modelcontextprotocol/server": "2.0.0",
|
|
59
59
|
"tsx": "4.22.4",
|
|
60
60
|
"zod": "^4.2.0"
|
|
61
61
|
},
|
|
62
62
|
"devDependencies": {
|
|
63
63
|
"@payloadcms/eslint-config": "3.28.0",
|
|
64
|
-
"payload": "4.0.0-internal.
|
|
64
|
+
"payload": "4.0.0-internal.e38d3ac"
|
|
65
65
|
},
|
|
66
66
|
"peerDependencies": {
|
|
67
|
-
"payload": "4.0.0-internal.
|
|
67
|
+
"payload": "4.0.0-internal.e38d3ac"
|
|
68
68
|
},
|
|
69
69
|
"//deps_notes": {
|
|
70
70
|
"zod": "zod is a hard dependency of @modelcontextprotocol/server, thus we can safely use it without it impacting bundle size. Make extra sure the zod version here matches exactly what's defined in the dependencies of @modelcontextprotocol/server to avoid duplicate versions being installed.",
|
|
@@ -11,12 +11,13 @@ import {
|
|
|
11
11
|
} from '../../../utils/getVirtualFieldNames.js'
|
|
12
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,15 +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
|
|
32
|
-
.record(z.string(), z.unknown())
|
|
33
|
-
.describe(
|
|
34
|
-
'The document fields to create. Only include fields permitted by the schema returned by getCollectionSchema.',
|
|
35
|
-
),
|
|
36
32
|
depth: z
|
|
37
33
|
.number()
|
|
38
34
|
.int()
|
|
@@ -41,6 +37,19 @@ export const createDocumentTool = defineCollectionTool({
|
|
|
41
37
|
.describe('How many levels deep to populate relationships in response')
|
|
42
38
|
.optional()
|
|
43
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'),
|
|
44
53
|
draft: z
|
|
45
54
|
.boolean()
|
|
46
55
|
.describe(
|
|
@@ -55,7 +64,7 @@ export const createDocumentTool = defineCollectionTool({
|
|
|
55
64
|
locale: z
|
|
56
65
|
.string()
|
|
57
66
|
.describe(
|
|
58
|
-
'Optional: locale code to create the
|
|
67
|
+
'Optional: locale code to create the documents in (e.g., "en", "es"). Defaults to the default locale',
|
|
59
68
|
)
|
|
60
69
|
.optional(),
|
|
61
70
|
select: z
|
|
@@ -68,50 +77,92 @@ export const createDocumentTool = defineCollectionTool({
|
|
|
68
77
|
}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {
|
|
69
78
|
const payload = req.payload
|
|
70
79
|
const logger = getLogger({ payload })
|
|
80
|
+
const { depth, documents, draft, fallbackLocale, locale, select } = input
|
|
71
81
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
logger.info(
|
|
75
|
-
`Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,
|
|
76
|
-
)
|
|
82
|
+
logger.info(`Creating ${documents.length} documents in collection: ${collectionSlug}`)
|
|
77
83
|
|
|
78
84
|
try {
|
|
79
85
|
const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)
|
|
80
|
-
const
|
|
81
|
-
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
|
|
82
89
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
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
|
|
86
101
|
|
|
87
|
-
|
|
102
|
+
if (!validationSchema && schema && typeof schema === 'object') {
|
|
103
|
+
validationSchema = schema as Record<string, unknown>
|
|
104
|
+
}
|
|
88
105
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
...(select ? { select: select as SelectType } : {}),
|
|
99
|
-
})
|
|
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
|
+
}
|
|
100
115
|
|
|
101
|
-
|
|
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}`)
|
|
102
150
|
|
|
103
151
|
return {
|
|
104
152
|
content: [
|
|
105
153
|
{
|
|
106
154
|
type: 'text',
|
|
107
|
-
text: `
|
|
155
|
+
text: `Created ${docs.length} of ${documents.length} documents in collection "${collectionSlug}".${retryMessage}\nResults:\n\`\`\`json\n${JSON.stringify(batchResult)}\n\`\`\`${schemaMessage}`,
|
|
108
156
|
},
|
|
109
157
|
],
|
|
110
|
-
doc:
|
|
158
|
+
doc: structuredContent as unknown as Record<string, unknown>,
|
|
159
|
+
isError: docs.length === 0 && errors.length > 0,
|
|
160
|
+
structuredContent,
|
|
111
161
|
}
|
|
112
162
|
} catch (error) {
|
|
113
|
-
const
|
|
114
|
-
|
|
163
|
+
const message = error instanceof Error ? error.message : 'Unknown error'
|
|
164
|
+
|
|
165
|
+
logger.error(`Error creating documents in ${collectionSlug}: ${message}`)
|
|
115
166
|
return formatCollectionError({ action: 'creating', collectionSlug, error, req })
|
|
116
167
|
}
|
|
117
168
|
})
|
|
@@ -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
|
+
}
|
|
@@ -48,16 +48,33 @@ export const getCollectionSchemaTool = defineCollectionTool({
|
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
const uploadConfig = req.payload.collections[collectionSlug]?.config.upload
|
|
52
|
+
const maxFileSize = req.payload.config.upload.limits?.fileSize
|
|
53
|
+
const upload = uploadConfig
|
|
54
|
+
? {
|
|
55
|
+
enabled: true,
|
|
56
|
+
filesRequiredOnCreate: uploadConfig.filesRequiredOnCreate !== false,
|
|
57
|
+
mimeTypes: uploadConfig.mimeTypes ?? ['*/*'],
|
|
58
|
+
sources: [
|
|
59
|
+
...(uploadConfig.pasteURL !== false ? ['externalURL'] : []),
|
|
60
|
+
'base64',
|
|
61
|
+
'uploadReference',
|
|
62
|
+
],
|
|
63
|
+
...(typeof maxFileSize === 'number' && Number.isFinite(maxFileSize) ? { maxFileSize } : {}),
|
|
64
|
+
}
|
|
65
|
+
: { enabled: false }
|
|
66
|
+
|
|
51
67
|
return {
|
|
52
68
|
content: [
|
|
53
69
|
{
|
|
54
70
|
type: 'text',
|
|
55
|
-
text: `Schema for collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(inputSchema)}\n\`\`\``,
|
|
71
|
+
text: `Schema for collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(inputSchema)}\n\`\`\`\nUpload configuration:\n\`\`\`json\n${JSON.stringify(upload)}\n\`\`\``,
|
|
56
72
|
},
|
|
57
73
|
],
|
|
58
74
|
structuredContent: {
|
|
59
75
|
collectionSlug,
|
|
60
76
|
schema: inputSchema,
|
|
77
|
+
upload,
|
|
61
78
|
},
|
|
62
79
|
}
|
|
63
80
|
})
|
|
@@ -13,10 +13,11 @@ import { getCollectionInputSchema } from '../../../utils/schemaConversion/getEnt
|
|
|
13
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) =>
|
|
@@ -52,7 +53,7 @@ export const updateDocumentTool = defineCollectionTool({
|
|
|
52
53
|
.string()
|
|
53
54
|
.describe('Optional: fallback locale code to use when requested locale is not available')
|
|
54
55
|
.optional(),
|
|
55
|
-
|
|
56
|
+
file: fileInputSchema.optional(),
|
|
56
57
|
locale: z
|
|
57
58
|
.string()
|
|
58
59
|
.describe(
|
|
@@ -97,7 +98,7 @@ export const updateDocumentTool = defineCollectionTool({
|
|
|
97
98
|
depth,
|
|
98
99
|
draft,
|
|
99
100
|
fallbackLocale,
|
|
100
|
-
|
|
101
|
+
file: fileInput,
|
|
101
102
|
locale,
|
|
102
103
|
overrideLock,
|
|
103
104
|
overwriteExistingFiles,
|
|
@@ -131,6 +132,7 @@ export const updateDocumentTool = defineCollectionTool({
|
|
|
131
132
|
}
|
|
132
133
|
|
|
133
134
|
const parsedData = transformPointDataToPayload(inputData)
|
|
135
|
+
const file = await resolveFile({ collectionSlug, input: fileInput, req })
|
|
134
136
|
|
|
135
137
|
const whereClause: Where = where ?? {}
|
|
136
138
|
|
|
@@ -144,7 +146,7 @@ export const updateDocumentTool = defineCollectionTool({
|
|
|
144
146
|
overrideAccess: authorizedMCP.overrideAccess,
|
|
145
147
|
overrideLock,
|
|
146
148
|
req,
|
|
147
|
-
...(
|
|
149
|
+
...(file ? { file } : {}),
|
|
148
150
|
...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),
|
|
149
151
|
...(publishAllLocales !== undefined ? { publishAllLocales } : {}),
|
|
150
152
|
...(locale ? { locale } : {}),
|
|
@@ -172,7 +174,7 @@ export const updateDocumentTool = defineCollectionTool({
|
|
|
172
174
|
overrideLock,
|
|
173
175
|
req,
|
|
174
176
|
where: whereClause,
|
|
175
|
-
...(
|
|
177
|
+
...(file ? { file } : {}),
|
|
176
178
|
...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),
|
|
177
179
|
...(publishAllLocales !== undefined ? { publishAllLocales } : {}),
|
|
178
180
|
...(locale ? { locale } : {}),
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { getUploadInstructions as getPayloadUploadInstructions } from 'payload/internal'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
import { defaultAccess } from '../../../defaultAccess.js'
|
|
5
|
+
import { defineCollectionTool } from '../../../defineTool.js'
|
|
6
|
+
|
|
7
|
+
export const getUploadInstructionsTool = defineCollectionTool({
|
|
8
|
+
access: (args) =>
|
|
9
|
+
defaultAccess(args) &&
|
|
10
|
+
Boolean(
|
|
11
|
+
args.permissions?.collections?.[args.collectionSlug]?.create ||
|
|
12
|
+
args.permissions?.collections?.[args.collectionSlug]?.update,
|
|
13
|
+
),
|
|
14
|
+
annotations: {
|
|
15
|
+
destructiveHint: false,
|
|
16
|
+
idempotentHint: false,
|
|
17
|
+
openWorldHint: true,
|
|
18
|
+
readOnlyHint: false,
|
|
19
|
+
title: 'Get Upload Instructions',
|
|
20
|
+
},
|
|
21
|
+
description:
|
|
22
|
+
'Prepare uploads for createDocuments or updateDocument. This does not upload bytes; finish the returned action before use.',
|
|
23
|
+
input: z.object({
|
|
24
|
+
docPrefix: z.string().describe('Optional document folder or prefix').optional(),
|
|
25
|
+
filename: z.string().describe('The original file name'),
|
|
26
|
+
filesize: z.number().int().nonnegative().describe('The file size in bytes'),
|
|
27
|
+
mimeType: z.string().describe('The file MIME type'),
|
|
28
|
+
}),
|
|
29
|
+
}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {
|
|
30
|
+
try {
|
|
31
|
+
const instructions = await getPayloadUploadInstructions({
|
|
32
|
+
...input,
|
|
33
|
+
collectionSlug,
|
|
34
|
+
overrideAccess: authorizedMCP.overrideAccess,
|
|
35
|
+
req,
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
const nextStep =
|
|
39
|
+
instructions.type === 'http'
|
|
40
|
+
? 'Upload bytes with instructions.request. After success, pass { source: "uploadReference", file: instructions.file }.'
|
|
41
|
+
: `Call "${instructions.name}" with file and data. After success, pass { source: "uploadReference", file: instructions.file }.`
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
content: [
|
|
45
|
+
{
|
|
46
|
+
type: 'text',
|
|
47
|
+
text: `Upload instructions for collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(instructions)}\n\`\`\`\n${nextStep}`,
|
|
48
|
+
},
|
|
49
|
+
],
|
|
50
|
+
structuredContent: { instructions },
|
|
51
|
+
}
|
|
52
|
+
} catch (error) {
|
|
53
|
+
const message = error instanceof Error ? error.message : 'Unknown error'
|
|
54
|
+
return {
|
|
55
|
+
content: [
|
|
56
|
+
{
|
|
57
|
+
type: 'text',
|
|
58
|
+
text: `Error getting upload instructions for collection "${collectionSlug}": ${message}`,
|
|
59
|
+
},
|
|
60
|
+
],
|
|
61
|
+
isError: true,
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
})
|
package/src/mcp/builtinTools.ts
CHANGED
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
} from './builtin/collections/authTools.js'
|
|
11
11
|
import { countDocumentsTool } from './builtin/collections/countTool.js'
|
|
12
12
|
import { countVersionsTool } from './builtin/collections/countVersionsTool.js'
|
|
13
|
-
import {
|
|
13
|
+
import { createDocumentsTool } from './builtin/collections/createTool.js'
|
|
14
14
|
import { deleteDocumentsTool } from './builtin/collections/deleteTool.js'
|
|
15
15
|
import { duplicateDocumentTool } from './builtin/collections/duplicateTool.js'
|
|
16
16
|
import { findDistinctTool } from './builtin/collections/findDistinctTool.js'
|
|
@@ -20,6 +20,7 @@ import { findVersionsTool } from './builtin/collections/findVersionsTool.js'
|
|
|
20
20
|
import { getCollectionSchemaTool } from './builtin/collections/getCollectionSchemaTool.js'
|
|
21
21
|
import { restoreVersionTool } from './builtin/collections/restoreVersionTool.js'
|
|
22
22
|
import { updateDocumentTool } from './builtin/collections/updateTool.js'
|
|
23
|
+
import { getUploadInstructionsTool } from './builtin/collections/uploadInstructionsTool.js'
|
|
23
24
|
import { getConfigInfoTool } from './builtin/getConfigInfoTool.js'
|
|
24
25
|
import { countGlobalVersionsTool } from './builtin/globals/countVersionsTool.js'
|
|
25
26
|
import { findGlobalTool } from './builtin/globals/findTool.js'
|
|
@@ -32,6 +33,7 @@ import { updateGlobalTool } from './builtin/globals/updateTool.js'
|
|
|
32
33
|
type CollectionBuiltin = {
|
|
33
34
|
mcpName: string
|
|
34
35
|
requiresDuplicateEnabled?: boolean
|
|
36
|
+
requiresUpload?: boolean
|
|
35
37
|
requiresVersions?: boolean
|
|
36
38
|
tool: CollectionTool
|
|
37
39
|
}
|
|
@@ -54,7 +56,7 @@ export const TOOL_BUILTINS = {
|
|
|
54
56
|
export const COLLECTION_BUILTINS = {
|
|
55
57
|
count: { mcpName: 'countDocuments', tool: countDocumentsTool },
|
|
56
58
|
countVersions: { mcpName: 'countVersions', requiresVersions: true, tool: countVersionsTool },
|
|
57
|
-
create: { mcpName: '
|
|
59
|
+
create: { mcpName: 'createDocuments', tool: createDocumentsTool },
|
|
58
60
|
delete: { mcpName: 'deleteDocuments', tool: deleteDocumentsTool },
|
|
59
61
|
duplicate: {
|
|
60
62
|
mcpName: 'duplicateDocument',
|
|
@@ -70,6 +72,11 @@ export const COLLECTION_BUILTINS = {
|
|
|
70
72
|
},
|
|
71
73
|
findVersions: { mcpName: 'findVersions', requiresVersions: true, tool: findVersionsTool },
|
|
72
74
|
getCollectionSchema: { mcpName: 'getCollectionSchema', tool: getCollectionSchemaTool },
|
|
75
|
+
getUploadInstructions: {
|
|
76
|
+
mcpName: 'getUploadInstructions',
|
|
77
|
+
requiresUpload: true,
|
|
78
|
+
tool: getUploadInstructionsTool,
|
|
79
|
+
},
|
|
73
80
|
restoreVersion: { mcpName: 'restoreVersion', requiresVersions: true, tool: restoreVersionTool },
|
|
74
81
|
update: { mcpName: 'updateDocument', tool: updateDocumentTool },
|
|
75
82
|
} satisfies Record<string, CollectionBuiltin>
|