@payloadcms/plugin-mcp 4.0.0-internal.a0ef1b8 → 4.0.0-internal.a1317b2
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/LICENSE.md +1 -1
- package/bin.js +7 -0
- package/dist/defaultAccess.d.ts +3 -0
- package/dist/defaultAccess.d.ts.map +1 -0
- package/dist/defaultAccess.js +3 -0
- package/dist/defaultAccess.js.map +1 -0
- package/dist/defineTool.d.ts +8 -8
- package/dist/defineTool.d.ts.map +1 -1
- package/dist/endpoint/access.d.ts +12 -5
- package/dist/endpoint/access.d.ts.map +1 -1
- package/dist/endpoint/access.js +75 -88
- package/dist/endpoint/access.js.map +1 -1
- package/dist/endpoint/index.d.ts +1 -1
- package/dist/endpoint/index.d.ts.map +1 -1
- package/dist/endpoint/index.js +68 -17
- package/dist/endpoint/index.js.map +1 -1
- 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/internal.d.ts +2 -0
- package/dist/exports/internal.d.ts.map +1 -0
- package/dist/exports/internal.js +3 -0
- package/dist/exports/internal.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +15 -20
- package/dist/index.js.map +1 -1
- package/dist/mcp/buildMcpServer.d.ts +5 -5
- package/dist/mcp/buildMcpServer.d.ts.map +1 -1
- package/dist/mcp/buildMcpServer.js +145 -80
- 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 +122 -61
- package/dist/mcp/builtin/collections/authTools.js.map +1 -1
- package/dist/mcp/builtin/collections/countTool.d.ts +2 -0
- package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -0
- package/dist/mcp/builtin/collections/countTool.js +63 -0
- package/dist/mcp/builtin/collections/countTool.js.map +1 -0
- package/dist/mcp/builtin/collections/countVersionsTool.d.ts +2 -0
- package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -0
- package/dist/mcp/builtin/collections/countVersionsTool.js +60 -0
- package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -0
- 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 +111 -68
- package/dist/mcp/builtin/collections/createTool.js.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.d.ts +1 -1
- package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.js +51 -61
- package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
- package/dist/mcp/builtin/collections/duplicateTool.d.ts +2 -0
- package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -0
- package/dist/mcp/builtin/collections/duplicateTool.js +86 -0
- package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -0
- 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 +123 -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/findDistinctTool.d.ts +2 -0
- package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -0
- package/dist/mcp/builtin/collections/findDistinctTool.js +77 -0
- package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -0
- package/dist/mcp/builtin/collections/findTool.d.ts +1 -1
- package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findTool.js +55 -72
- package/dist/mcp/builtin/collections/findTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts +2 -0
- package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -0
- package/dist/mcp/builtin/collections/findVersionByIDTool.js +74 -0
- package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -0
- package/dist/mcp/builtin/collections/findVersionsTool.d.ts +2 -0
- package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -0
- package/dist/mcp/builtin/collections/findVersionsTool.js +84 -0
- package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -0
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts +2 -0
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -0
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +87 -0
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -0
- package/dist/mcp/builtin/collections/restoreVersionTool.d.ts +2 -0
- package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -0
- package/dist/mcp/builtin/collections/restoreVersionTool.js +69 -0
- package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -0
- package/dist/mcp/builtin/collections/updateTool.d.ts +1 -1
- package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.js +104 -136
- 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/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 +2 -0
- package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -0
- package/dist/mcp/builtin/getConfigInfoTool.js +69 -0
- package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -0
- package/dist/mcp/builtin/globals/countVersionsTool.d.ts +2 -0
- package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -0
- package/dist/mcp/builtin/globals/countVersionsTool.js +60 -0
- package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -0
- package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findTool.js +27 -36
- package/dist/mcp/builtin/globals/findTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts +2 -0
- package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -0
- package/dist/mcp/builtin/globals/findVersionByIDTool.js +68 -0
- package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -0
- package/dist/mcp/builtin/globals/findVersionsTool.d.ts +2 -0
- package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -0
- package/dist/mcp/builtin/globals/findVersionsTool.js +78 -0
- package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -0
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts +2 -0
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -0
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +65 -0
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -0
- package/dist/mcp/builtin/globals/restoreVersionTool.d.ts +2 -0
- package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -0
- package/dist/mcp/builtin/globals/restoreVersionTool.js +70 -0
- package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -0
- package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/updateTool.js +44 -62
- package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
- package/dist/mcp/builtinTools.d.ts +150 -19
- package/dist/mcp/builtinTools.d.ts.map +1 -1
- package/dist/mcp/builtinTools.js +125 -20
- package/dist/mcp/builtinTools.js.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.d.ts +0 -1
- package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.js +124 -58
- package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
- package/dist/stdio.d.ts +3 -3
- package/dist/stdio.d.ts.map +1 -1
- package/dist/stdio.js +84 -46
- package/dist/stdio.js.map +1 -1
- package/dist/types.d.ts +114 -112
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +2 -4
- package/dist/types.js.map +1 -1
- package/dist/utils/camelCase.d.ts.map +1 -1
- package/dist/utils/getPluginConfig.d.ts +1 -1
- package/dist/utils/getPluginConfig.js +1 -1
- package/dist/utils/getPluginConfig.js.map +1 -1
- package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
- package/dist/utils/toStandardSchema.d.ts.map +1 -1
- package/package.json +11 -18
- package/src/defaultAccess.ts +3 -0
- package/src/endpoint/access.ts +80 -101
- package/src/endpoint/index.ts +58 -16
- package/src/exports/client.ts +2 -1
- package/src/exports/internal.ts +1 -0
- package/src/index.ts +12 -20
- package/src/mcp/buildMcpServer.ts +179 -114
- package/src/mcp/builtin/collections/authTools.ts +119 -75
- package/src/mcp/builtin/collections/countTool.ts +61 -0
- package/src/mcp/builtin/collections/countVersionsTool.ts +60 -0
- package/src/mcp/builtin/collections/createTool.ts +104 -88
- package/src/mcp/builtin/collections/deleteTool.ts +48 -74
- package/src/mcp/builtin/collections/duplicateTool.ts +83 -0
- package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
- package/src/mcp/builtin/collections/fileInput.ts +169 -0
- package/src/mcp/builtin/collections/findDistinctTool.ts +67 -0
- package/src/mcp/builtin/collections/findTool.ts +55 -108
- package/src/mcp/builtin/collections/findVersionByIDTool.ts +66 -0
- package/src/mcp/builtin/collections/findVersionsTool.ts +83 -0
- package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +80 -0
- package/src/mcp/builtin/collections/restoreVersionTool.ts +65 -0
- package/src/mcp/builtin/collections/updateTool.ts +101 -142
- package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
- package/src/mcp/builtin/formatEntityError.ts +77 -0
- package/src/mcp/builtin/getConfigInfoTool.ts +68 -0
- package/src/mcp/builtin/globals/countVersionsTool.ts +60 -0
- package/src/mcp/builtin/globals/findTool.ts +27 -57
- package/src/mcp/builtin/globals/findVersionByIDTool.ts +64 -0
- package/src/mcp/builtin/globals/findVersionsTool.ts +69 -0
- package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +63 -0
- package/src/mcp/builtin/globals/restoreVersionTool.ts +68 -0
- package/src/mcp/builtin/globals/updateTool.ts +51 -79
- package/src/mcp/builtinTools.ts +118 -41
- package/src/mcp/sanitizeMCPConfig.ts +120 -78
- package/src/stdio.ts +79 -46
- package/src/types.ts +130 -117
- package/src/utils/getPluginConfig.ts +1 -1
- package/dist/@types/assets.d.js +0 -2
- package/dist/@types/assets.d.js.map +0 -1
- package/dist/collection/getAccessField.d.ts +0 -12
- package/dist/collection/getAccessField.d.ts.map +0 -1
- package/dist/collection/getAccessField.js +0 -57
- package/dist/collection/getAccessField.js.map +0 -1
- package/dist/collection/index.d.ts +0 -6
- package/dist/collection/index.d.ts.map +0 -1
- package/dist/collection/index.js +0 -60
- package/dist/collection/index.js.map +0 -1
- package/dist/components/AccessField/index.client.d.ts +0 -10
- package/dist/components/AccessField/index.client.d.ts.map +0 -1
- package/dist/components/AccessField/index.client.js +0 -305
- package/dist/components/AccessField/index.client.js.map +0 -1
- package/dist/components/AccessField/index.css +0 -93
- 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/localAPIDefaults.d.ts +0 -20
- package/dist/utils/localAPIDefaults.d.ts.map +0 -1
- package/dist/utils/localAPIDefaults.js +0 -19
- package/dist/utils/localAPIDefaults.js.map +0 -1
- package/dist/utils/schemaConversion/buildToolInput.d.ts +0 -29
- package/dist/utils/schemaConversion/buildToolInput.d.ts.map +0 -1
- package/dist/utils/schemaConversion/buildToolInput.js +0 -51
- package/dist/utils/schemaConversion/buildToolInput.js.map +0 -1
- package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
- package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
- package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
- package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -15
- package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -464
- package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -158
- 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/@types/assets.d.ts +0 -3
- package/src/collection/getAccessField.ts +0 -64
- package/src/collection/index.ts +0 -64
- package/src/components/AccessField/index.client.tsx +0 -344
- package/src/components/AccessField/index.css +0 -93
- package/src/utils/getVirtualFieldNames.ts +0 -53
- package/src/utils/localAPIDefaults.ts +0 -22
- package/src/utils/schemaConversion/buildToolInput.ts +0 -68
- package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
- package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -103
- package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -529
- package/src/utils/transformPointDataToPayload.ts +0 -40
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { APIError, z } from 'payload';
|
|
2
|
+
import { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal';
|
|
3
|
+
import { sanitizeFilename } from 'payload/shared';
|
|
4
|
+
const mimeTypeSchema = z.string().check(z.regex(/^[!#$%&'*+.^`|~\w-]+\/[!#$%&'*+.^`|~\w-]+$/, 'MIME type must use the type/subtype format'));
|
|
5
|
+
const uploadFileSchema = z.strictObject({
|
|
6
|
+
filename: z.string(),
|
|
7
|
+
mimeType: z.string(),
|
|
8
|
+
size: z.int().check(z.nonnegative()),
|
|
9
|
+
uploadReference: z.record(z.string(), z.unknown())
|
|
10
|
+
});
|
|
11
|
+
export const fileInputSchema = z.discriminatedUnion('source', [
|
|
12
|
+
z.strictObject({
|
|
13
|
+
name: z.string().check(z.minLength(1), z.describe('The file name, including its extension.')),
|
|
14
|
+
data: z.string().check(z.describe('The base64-encoded file bytes, without a data URL prefix.')),
|
|
15
|
+
mimeType: mimeTypeSchema.check(z.describe('The file MIME type, for example image/png.')),
|
|
16
|
+
source: z.literal('base64')
|
|
17
|
+
}),
|
|
18
|
+
z.strictObject({
|
|
19
|
+
name: z.optional(z.string().check(z.minLength(1))).check(z.describe('File name override.')),
|
|
20
|
+
source: z.literal('externalURL'),
|
|
21
|
+
url: z.url().check(z.describe('The http or https URL to download.'))
|
|
22
|
+
}),
|
|
23
|
+
z.strictObject({
|
|
24
|
+
file: uploadFileSchema.check(z.describe('getUploadInstructions file field post-upload.')),
|
|
25
|
+
source: z.literal('uploadReference')
|
|
26
|
+
})
|
|
27
|
+
]).check(z.describe('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.'));
|
|
28
|
+
export async function resolveFile({ slug, input, req }) {
|
|
29
|
+
if (!input) {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
if (input.source === 'uploadReference') {
|
|
33
|
+
try {
|
|
34
|
+
return await getFileFromUploadInstructions({
|
|
35
|
+
collectionSlug: slug,
|
|
36
|
+
file: input.file,
|
|
37
|
+
req
|
|
38
|
+
});
|
|
39
|
+
} catch (error) {
|
|
40
|
+
if (error instanceof Error && error.message === 'Staged upload was not found.') {
|
|
41
|
+
throw new APIError('Staged upload not found. Complete the upload action first, or use base64 for small local files.', 400);
|
|
42
|
+
}
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const uploadConfig = req.payload.collections[slug]?.config.upload;
|
|
47
|
+
if (!uploadConfig) {
|
|
48
|
+
throw new APIError(`Collection "${slug}" does not support file uploads.`, 400);
|
|
49
|
+
}
|
|
50
|
+
const maxFileSize = req.payload.config.upload.limits?.fileSize;
|
|
51
|
+
let file;
|
|
52
|
+
if (input.source === 'base64') {
|
|
53
|
+
const data = decodeBase64({
|
|
54
|
+
maxFileSize,
|
|
55
|
+
value: input.data
|
|
56
|
+
});
|
|
57
|
+
file = {
|
|
58
|
+
name: sanitizeFilename(input.name),
|
|
59
|
+
data,
|
|
60
|
+
mimetype: input.mimeType,
|
|
61
|
+
size: data.length
|
|
62
|
+
};
|
|
63
|
+
} else {
|
|
64
|
+
if (uploadConfig.pasteURL === false) {
|
|
65
|
+
throw new APIError(`Uploading files from URLs is disabled for collection "${slug}".`, 400);
|
|
66
|
+
}
|
|
67
|
+
const url = new URL(input.url);
|
|
68
|
+
if (![
|
|
69
|
+
'http:',
|
|
70
|
+
'https:'
|
|
71
|
+
].includes(url.protocol)) {
|
|
72
|
+
throw new APIError('File URLs must use http or https.', 400);
|
|
73
|
+
}
|
|
74
|
+
if (typeof uploadConfig.pasteURL === 'object' && !isURLAllowed(input.url, uploadConfig.pasteURL.allowList)) {
|
|
75
|
+
throw new APIError('The provided file URL is not allowed.', 400);
|
|
76
|
+
}
|
|
77
|
+
file = await getExternalFile({
|
|
78
|
+
data: {
|
|
79
|
+
filename: sanitizeFilename(input.name || getURLFilename(url)),
|
|
80
|
+
url: input.url
|
|
81
|
+
},
|
|
82
|
+
req,
|
|
83
|
+
uploadConfig: {
|
|
84
|
+
...uploadConfig,
|
|
85
|
+
externalFileHeaderFilter: uploadConfig.externalFileHeaderFilter ?? (()=>({}))
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
file.mimetype = file.mimetype?.split(';')[0] || 'application/octet-stream';
|
|
89
|
+
file.size = file.data.length;
|
|
90
|
+
}
|
|
91
|
+
if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {
|
|
92
|
+
throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400);
|
|
93
|
+
}
|
|
94
|
+
return file;
|
|
95
|
+
}
|
|
96
|
+
function decodeBase64({ maxFileSize, value }) {
|
|
97
|
+
const normalized = value.replace(/\s/g, '');
|
|
98
|
+
if (!/^[a-z0-9+/]*={0,2}$/i.test(normalized) || normalized.length % 4 === 1) {
|
|
99
|
+
throw new APIError('File data must be valid base64.', 400);
|
|
100
|
+
}
|
|
101
|
+
if (maxFileSize !== undefined && Number.isFinite(maxFileSize)) {
|
|
102
|
+
const paddingLength = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0;
|
|
103
|
+
const decodedSize = Math.floor(normalized.length * 3 / 4) - paddingLength;
|
|
104
|
+
if (decodedSize > maxFileSize) {
|
|
105
|
+
throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const data = Buffer.from(normalized, 'base64');
|
|
109
|
+
if (data.toString('base64').replace(/=+$/, '') !== normalized.replace(/=+$/, '')) {
|
|
110
|
+
throw new APIError('File data must be valid base64.', 400);
|
|
111
|
+
}
|
|
112
|
+
return data;
|
|
113
|
+
}
|
|
114
|
+
function getURLFilename(url) {
|
|
115
|
+
const pathSegment = url.pathname.split('/').pop() || 'upload';
|
|
116
|
+
try {
|
|
117
|
+
return decodeURIComponent(pathSegment);
|
|
118
|
+
} catch {
|
|
119
|
+
return pathSegment;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
//# sourceMappingURL=fileInput.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"sourcesContent":["import type { CollectionSlug, File, FileData, PayloadRequest } from 'payload'\n\nimport { APIError, z } from 'payload'\nimport { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal'\nimport { sanitizeFilename } from 'payload/shared'\n\nconst mimeTypeSchema = z\n .string()\n .check(\n z.regex(\n /^[!#$%&'*+.^`|~\\w-]+\\/[!#$%&'*+.^`|~\\w-]+$/,\n 'MIME type must use the type/subtype format',\n ),\n )\n\nconst uploadFileSchema = z.strictObject({\n filename: z.string(),\n mimeType: z.string(),\n size: z.int().check(z.nonnegative()),\n uploadReference: z.record(z.string(), z.unknown()),\n})\n\nexport const fileInputSchema = z\n .discriminatedUnion('source', [\n z.strictObject({\n name: z.string().check(z.minLength(1), z.describe('The file name, including its extension.')),\n data: z\n .string()\n .check(z.describe('The base64-encoded file bytes, without a data URL prefix.')),\n mimeType: mimeTypeSchema.check(z.describe('The file MIME type, for example image/png.')),\n source: z.literal('base64'),\n }),\n z.strictObject({\n name: z.optional(z.string().check(z.minLength(1))).check(z.describe('File name override.')),\n source: z.literal('externalURL'),\n url: z.url().check(z.describe('The http or https URL to download.')),\n }),\n z.strictObject({\n file: uploadFileSchema.check(z.describe('getUploadInstructions file field post-upload.')),\n source: z.literal('uploadReference'),\n }),\n ])\n .check(\n z.describe(\n '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.',\n ),\n )\n\ntype FileInput = z.infer<typeof fileInputSchema>\n\nexport async function resolveFile({\n slug,\n input,\n req,\n}: {\n input?: FileInput\n req: PayloadRequest\n slug: CollectionSlug\n}): Promise<File | undefined> {\n if (!input) {\n return undefined\n }\n\n if (input.source === 'uploadReference') {\n try {\n return await getFileFromUploadInstructions({ collectionSlug: slug, file: input.file, req })\n } catch (error) {\n if (error instanceof Error && error.message === 'Staged upload was not found.') {\n throw new APIError(\n 'Staged upload not found. Complete the upload action first, or use base64 for small local files.',\n 400,\n )\n }\n throw error\n }\n }\n\n const uploadConfig = req.payload.collections[slug]?.config.upload\n\n if (!uploadConfig) {\n throw new APIError(`Collection \"${slug}\" does not support file uploads.`, 400)\n }\n\n const maxFileSize = req.payload.config.upload.limits?.fileSize\n let file: File\n\n if (input.source === 'base64') {\n const data = decodeBase64({ maxFileSize, value: input.data })\n\n file = {\n name: sanitizeFilename(input.name),\n data,\n mimetype: input.mimeType,\n size: data.length,\n }\n } else {\n if (uploadConfig.pasteURL === false) {\n throw new APIError(`Uploading files from URLs is disabled for collection \"${slug}\".`, 400)\n }\n\n const url = new URL(input.url)\n\n if (!['http:', 'https:'].includes(url.protocol)) {\n throw new APIError('File URLs must use http or https.', 400)\n }\n\n if (\n typeof uploadConfig.pasteURL === 'object' &&\n !isURLAllowed(input.url, uploadConfig.pasteURL.allowList)\n ) {\n throw new APIError('The provided file URL is not allowed.', 400)\n }\n\n file = await getExternalFile({\n data: {\n filename: sanitizeFilename(input.name || getURLFilename(url)),\n url: input.url,\n } as FileData,\n req,\n uploadConfig: {\n ...uploadConfig,\n externalFileHeaderFilter: uploadConfig.externalFileHeaderFilter ?? (() => ({})),\n },\n })\n file.mimetype = file.mimetype?.split(';')[0] || 'application/octet-stream'\n file.size = file.data.length\n }\n\n if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {\n throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)\n }\n\n return file\n}\n\nfunction decodeBase64({ maxFileSize, value }: { maxFileSize?: number; value: string }): Buffer {\n const normalized = value.replace(/\\s/g, '')\n\n if (!/^[a-z0-9+/]*={0,2}$/i.test(normalized) || normalized.length % 4 === 1) {\n throw new APIError('File data must be valid base64.', 400)\n }\n\n if (maxFileSize !== undefined && Number.isFinite(maxFileSize)) {\n const paddingLength = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0\n const decodedSize = Math.floor((normalized.length * 3) / 4) - paddingLength\n\n if (decodedSize > maxFileSize) {\n throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)\n }\n }\n\n const data = Buffer.from(normalized, 'base64')\n\n if (data.toString('base64').replace(/=+$/, '') !== normalized.replace(/=+$/, '')) {\n throw new APIError('File data must be valid base64.', 400)\n }\n\n return data\n}\n\nfunction getURLFilename(url: URL): string {\n const pathSegment = url.pathname.split('/').pop() || 'upload'\n\n try {\n return decodeURIComponent(pathSegment)\n } catch {\n return pathSegment\n }\n}\n"],"names":["APIError","z","getExternalFile","getFileFromUploadInstructions","isURLAllowed","sanitizeFilename","mimeTypeSchema","string","check","regex","uploadFileSchema","strictObject","filename","mimeType","size","int","nonnegative","uploadReference","record","unknown","fileInputSchema","discriminatedUnion","name","minLength","describe","data","source","literal","optional","url","file","resolveFile","slug","input","req","undefined","collectionSlug","error","Error","message","uploadConfig","payload","collections","config","upload","maxFileSize","limits","fileSize","decodeBase64","value","mimetype","length","pasteURL","URL","includes","protocol","allowList","getURLFilename","externalFileHeaderFilter","split","Number","isFinite","normalized","replace","test","paddingLength","endsWith","decodedSize","Math","floor","Buffer","from","toString","pathSegment","pathname","pop","decodeURIComponent"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,CAAC,QAAQ,UAAS;AACrC,SAASC,eAAe,EAAEC,6BAA6B,EAAEC,YAAY,QAAQ,mBAAkB;AAC/F,SAASC,gBAAgB,QAAQ,iBAAgB;AAEjD,MAAMC,iBAAiBL,EACpBM,MAAM,GACNC,KAAK,CACJP,EAAEQ,KAAK,CACL,8CACA;AAIN,MAAMC,mBAAmBT,EAAEU,YAAY,CAAC;IACtCC,UAAUX,EAAEM,MAAM;IAClBM,UAAUZ,EAAEM,MAAM;IAClBO,MAAMb,EAAEc,GAAG,GAAGP,KAAK,CAACP,EAAEe,WAAW;IACjCC,iBAAiBhB,EAAEiB,MAAM,CAACjB,EAAEM,MAAM,IAAIN,EA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BAAmBH;IAC5B,EAAE,OAAM;QACN,OAAOA;IACT;AACF"}
|
|
@@ -0,0 +1,86 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"findDistinctTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/findDistinctTool.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,gBAAgB,4CAyD3B,CAAA"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { findDistinctInputSchema } from 'payload';
|
|
2
|
+
import { defaultAccess } from '../../../defaultAccess.js';
|
|
3
|
+
import { defineCollectionTool } from '../../../defineTool.js';
|
|
4
|
+
import { getLogger } from '../../../utils/getLogger.js';
|
|
5
|
+
const DEFAULT_DESCRIPTION = 'Find distinct values for a field in any collection by passing the collection slug and field path.';
|
|
6
|
+
export const findDistinctTool = defineCollectionTool({
|
|
7
|
+
access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.read),
|
|
8
|
+
annotations: {
|
|
9
|
+
destructiveHint: false,
|
|
10
|
+
idempotentHint: true,
|
|
11
|
+
openWorldHint: false,
|
|
12
|
+
readOnlyHint: true,
|
|
13
|
+
title: 'Find Distinct'
|
|
14
|
+
},
|
|
15
|
+
description: DEFAULT_DESCRIPTION,
|
|
16
|
+
input: findDistinctInputSchema
|
|
17
|
+
}).handler(async ({ slug, authorizedMCP, input, req })=>{
|
|
18
|
+
const payload = req.payload;
|
|
19
|
+
const logger = getLogger({
|
|
20
|
+
payload
|
|
21
|
+
});
|
|
22
|
+
const { depth, field, limit, locale, page, populate, sort, trash, where } = input;
|
|
23
|
+
logger.info(`Finding distinct values in collection: ${slug}, field: ${field}`);
|
|
24
|
+
try {
|
|
25
|
+
const result = await payload.findDistinct({
|
|
26
|
+
collection: slug,
|
|
27
|
+
depth,
|
|
28
|
+
field,
|
|
29
|
+
overrideAccess: authorizedMCP.overrideAccess,
|
|
30
|
+
req,
|
|
31
|
+
...limit ? {
|
|
32
|
+
limit
|
|
33
|
+
} : {},
|
|
34
|
+
...locale ? {
|
|
35
|
+
locale
|
|
36
|
+
} : {},
|
|
37
|
+
...page ? {
|
|
38
|
+
page
|
|
39
|
+
} : {},
|
|
40
|
+
...populate ? {
|
|
41
|
+
populate
|
|
42
|
+
} : {},
|
|
43
|
+
...sort ? {
|
|
44
|
+
sort
|
|
45
|
+
} : {},
|
|
46
|
+
...trash !== undefined ? {
|
|
47
|
+
trash
|
|
48
|
+
} : {},
|
|
49
|
+
...where ? {
|
|
50
|
+
where
|
|
51
|
+
} : {}
|
|
52
|
+
});
|
|
53
|
+
return {
|
|
54
|
+
content: [
|
|
55
|
+
{
|
|
56
|
+
type: 'text',
|
|
57
|
+
text: `Distinct values for "${field}" in collection "${slug}":\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
|
|
58
|
+
}
|
|
59
|
+
],
|
|
60
|
+
doc: result
|
|
61
|
+
};
|
|
62
|
+
} catch (error) {
|
|
63
|
+
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
64
|
+
logger.error(`Error finding distinct values in ${slug}: ${errorMessage}`);
|
|
65
|
+
return {
|
|
66
|
+
content: [
|
|
67
|
+
{
|
|
68
|
+
type: 'text',
|
|
69
|
+
text: `❌ **Error finding distinct values in collection "${slug}":** ${errorMessage}`
|
|
70
|
+
}
|
|
71
|
+
],
|
|
72
|
+
isError: true
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
//# sourceMappingURL=findDistinctTool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/collections/findDistinctTool.ts"],"sourcesContent":["import { findDistinctInputSchema } from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Find distinct values for a field in any collection by passing the collection slug and field path.'\n\nexport const findDistinctTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.read),\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Find Distinct',\n },\n description: DEFAULT_DESCRIPTION,\n input: findDistinctInputSchema,\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n const { depth, field, limit, locale, page, populate, sort, trash, where } = input\n\n logger.info(`Finding distinct values in collection: ${slug}, field: ${field}`)\n\n try {\n const result = await payload.findDistinct({\n collection: slug,\n depth,\n field,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(limit ? { limit } : {}),\n ...(locale ? { locale } : {}),\n ...(page ? { page } : {}),\n ...(populate ? { populate } : {}),\n ...(sort ? { sort } : {}),\n ...(trash !== undefined ? { trash } : {}),\n ...(where ? { where } : {}),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Distinct values for \"${field}\" in collection \"${slug}\":\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error finding distinct values in ${slug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error finding distinct values in collection \"${slug}\":** ${errorMessage}`,\n },\n ],\n isError: true,\n }\n }\n})\n"],"names":["findDistinctInputSchema","defaultAccess","defineCollectionTool","getLogger","DEFAULT_DESCRIPTION","findDistinctTool","access","args","Boolean","permissions","collections","slug","read","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","handler","authorizedMCP","req","payload","logger","depth","field","limit","locale","page","populate","sort","trash","where","info","result","findDistinct","collection","overrideAccess","undefined","content","type","text","JSON","stringify","doc","error","errorMessage","Error","message","isError"],"mappings":"AAAA,SAASA,uBAAuB,QAAQ,UAAS;AAEjD,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD,MAAMC,sBACJ;AAEF,OAAO,MAAMC,mBAAmBH,qBAAqB;IACnDI,QAAQ,CAACC,OACPN,cAAcM,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,IAAI,CAAC,EAAEC;IAC7EC,aAAa;QACXC,iBAAiB;QACjBC,gB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G,OAAO,GAAG;QAC9DzB,OAAOsB,KAAK,CAAC,CAAC,iCAAiC,EAAEpC,KAAK,EAAE,EAAEqC,cAAc;QACxE,OAAO;YACLP,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,iDAAiD,EAAEhC,KAAK,KAAK,EAAEqC,cAAc;gBACtF;aACD;YACDG,SAAS;QACX;IACF;AACF,GAAE"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const
|
|
1
|
+
export declare const findDocumentsTool: import("../../../types.js").CollectionTool;
|
|
2
2
|
//# sourceMappingURL=findTool.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"findTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/findTool.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"findTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/findTool.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,iBAAiB,4CA4H5B,CAAA"}
|
|
@@ -1,135 +1,118 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { findDocumentsInputSchema } from 'payload';
|
|
2
|
+
import { defaultAccess } from '../../../defaultAccess.js';
|
|
2
3
|
import { defineCollectionTool } from '../../../defineTool.js';
|
|
3
4
|
import { getLogger } from '../../../utils/getLogger.js';
|
|
4
|
-
|
|
5
|
-
const
|
|
6
|
-
|
|
5
|
+
const DEFAULT_DESCRIPTION = 'Find documents in any collection by passing the collection slug and optional ID or where clause.';
|
|
6
|
+
export const findDocumentsTool = defineCollectionTool({
|
|
7
|
+
access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.read),
|
|
8
|
+
annotations: {
|
|
9
|
+
destructiveHint: false,
|
|
10
|
+
idempotentHint: true,
|
|
11
|
+
openWorldHint: false,
|
|
12
|
+
readOnlyHint: true,
|
|
13
|
+
title: 'Find Documents'
|
|
14
|
+
},
|
|
7
15
|
description: DEFAULT_DESCRIPTION,
|
|
8
|
-
input:
|
|
9
|
-
|
|
10
|
-
z.string(),
|
|
11
|
-
z.number()
|
|
12
|
-
]).describe('Optional: specific document ID to retrieve. If not provided, returns all documents').optional(),
|
|
13
|
-
depth: z.number().int().min(0).max(10).describe('How many levels deep to populate relationships (default: 0)').optional().default(0),
|
|
14
|
-
draft: z.boolean().describe('Optional: whether the document should be queried from the versions table/collection or not.').optional(),
|
|
15
|
-
fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
|
|
16
|
-
limit: z.number().int().min(1).max(100).describe('Maximum number of documents to return (default: 10, max: 100)').optional().default(10),
|
|
17
|
-
locale: z.string().describe('Optional: locale code to retrieve data in (e.g., "en", "es"). Use "all" to retrieve all locales for localized fields').optional(),
|
|
18
|
-
page: z.number().int().min(1).describe('Page number for pagination (default: 1)').optional().default(1),
|
|
19
|
-
select: z.string().describe("Optional: define exactly which fields you'd like to return in the response (JSON), e.g., '{\"title\": true}'").optional(),
|
|
20
|
-
sort: z.string().describe('Field to sort by (e.g., "createdAt", "-updatedAt" for descending)').optional(),
|
|
21
|
-
where: z.string().describe('Optional JSON string for where clause filtering (e.g., \'{"title": {"contains": "test"}}\')').optional()
|
|
22
|
-
})
|
|
23
|
-
}).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
|
|
16
|
+
input: findDocumentsInputSchema
|
|
17
|
+
}).handler(async ({ slug, authorizedMCP, input, req })=>{
|
|
24
18
|
const payload = req.payload;
|
|
25
19
|
const logger = getLogger({
|
|
26
20
|
payload
|
|
27
21
|
});
|
|
28
|
-
const { id, depth, draft, fallbackLocale, limit, locale, page, select, sort, where } = input;
|
|
29
|
-
logger.info(`Reading document from collection: ${
|
|
22
|
+
const { id, depth, draft, fallbackLocale, joins, limit, locale, page, pagination, populate, select, sort, trash, where } = input;
|
|
23
|
+
logger.info(`Reading document from collection: ${slug}${id ? ` with ID: ${id}` : ''}, limit: ${limit}, page: ${page}${locale ? `, locale: ${locale}` : ''}`);
|
|
30
24
|
try {
|
|
31
|
-
let whereClause = {};
|
|
32
|
-
if (where) {
|
|
33
|
-
try {
|
|
34
|
-
whereClause = JSON.parse(where);
|
|
35
|
-
} catch {
|
|
36
|
-
logger.warn(`Invalid where clause JSON: ${where}`);
|
|
37
|
-
return {
|
|
38
|
-
content: [
|
|
39
|
-
{
|
|
40
|
-
type: 'text',
|
|
41
|
-
text: 'Error: Invalid JSON in where clause'
|
|
42
|
-
}
|
|
43
|
-
]
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
let selectClause;
|
|
48
|
-
if (select) {
|
|
49
|
-
try {
|
|
50
|
-
selectClause = JSON.parse(select);
|
|
51
|
-
} catch {
|
|
52
|
-
logger.warn(`Invalid select clause JSON: ${select}`);
|
|
53
|
-
return {
|
|
54
|
-
content: [
|
|
55
|
-
{
|
|
56
|
-
type: 'text',
|
|
57
|
-
text: 'Error: Invalid JSON in select clause'
|
|
58
|
-
}
|
|
59
|
-
]
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
25
|
if (id) {
|
|
64
26
|
try {
|
|
65
27
|
const doc = await payload.findByID({
|
|
66
28
|
id,
|
|
67
|
-
collection:
|
|
29
|
+
collection: slug,
|
|
68
30
|
depth,
|
|
31
|
+
overrideAccess: authorizedMCP.overrideAccess,
|
|
69
32
|
req,
|
|
70
|
-
...
|
|
71
|
-
|
|
72
|
-
|
|
33
|
+
...select && {
|
|
34
|
+
select
|
|
35
|
+
},
|
|
36
|
+
...populate && {
|
|
37
|
+
populate
|
|
38
|
+
},
|
|
39
|
+
...joins !== undefined && {
|
|
40
|
+
joins
|
|
73
41
|
},
|
|
74
42
|
...locale && {
|
|
75
43
|
locale
|
|
76
44
|
},
|
|
77
|
-
...fallbackLocale && {
|
|
45
|
+
...fallbackLocale !== undefined && {
|
|
78
46
|
fallbackLocale
|
|
79
47
|
},
|
|
80
48
|
...draft !== undefined && {
|
|
81
49
|
draft
|
|
50
|
+
},
|
|
51
|
+
...trash !== undefined && {
|
|
52
|
+
trash
|
|
82
53
|
}
|
|
83
54
|
});
|
|
84
55
|
return {
|
|
85
56
|
content: [
|
|
86
57
|
{
|
|
87
58
|
type: 'text',
|
|
88
|
-
text: `Document from collection "${
|
|
59
|
+
text: `Document from collection "${slug}":\n${JSON.stringify(doc)}`
|
|
89
60
|
}
|
|
90
61
|
],
|
|
91
62
|
doc: doc
|
|
92
63
|
};
|
|
93
64
|
} catch {
|
|
94
|
-
logger.warn(`Document not found with ID: ${id} in collection: ${
|
|
65
|
+
logger.warn(`Document not found with ID: ${id} in collection: ${slug}`);
|
|
95
66
|
return {
|
|
96
67
|
content: [
|
|
97
68
|
{
|
|
98
69
|
type: 'text',
|
|
99
|
-
text: `Error: Document with ID "${id}" not found in collection "${
|
|
70
|
+
text: `Error: Document with ID "${id}" not found in collection "${slug}"`
|
|
100
71
|
}
|
|
101
72
|
]
|
|
102
73
|
};
|
|
103
74
|
}
|
|
104
75
|
}
|
|
105
76
|
const findOptions = {
|
|
106
|
-
collection:
|
|
77
|
+
collection: slug,
|
|
107
78
|
depth,
|
|
108
79
|
limit,
|
|
80
|
+
overrideAccess: authorizedMCP.overrideAccess,
|
|
109
81
|
page,
|
|
110
82
|
req,
|
|
111
|
-
...
|
|
112
|
-
|
|
113
|
-
|
|
83
|
+
...select && {
|
|
84
|
+
select
|
|
85
|
+
},
|
|
86
|
+
...populate && {
|
|
87
|
+
populate
|
|
88
|
+
},
|
|
89
|
+
...joins !== undefined && {
|
|
90
|
+
joins
|
|
114
91
|
},
|
|
115
92
|
...locale && {
|
|
116
93
|
locale
|
|
117
94
|
},
|
|
118
|
-
...fallbackLocale && {
|
|
95
|
+
...fallbackLocale !== undefined && {
|
|
119
96
|
fallbackLocale
|
|
120
97
|
},
|
|
121
98
|
...draft !== undefined && {
|
|
122
99
|
draft
|
|
100
|
+
},
|
|
101
|
+
...pagination !== undefined && {
|
|
102
|
+
pagination
|
|
103
|
+
},
|
|
104
|
+
...trash !== undefined && {
|
|
105
|
+
trash
|
|
123
106
|
}
|
|
124
107
|
};
|
|
125
108
|
if (sort) {
|
|
126
109
|
findOptions.sort = sort;
|
|
127
110
|
}
|
|
128
|
-
if (
|
|
129
|
-
findOptions.where =
|
|
111
|
+
if (where) {
|
|
112
|
+
findOptions.where = where;
|
|
130
113
|
}
|
|
131
114
|
const result = await payload.find(findOptions);
|
|
132
|
-
let responseText = `Collection: "${
|
|
115
|
+
let responseText = `Collection: "${slug}"\nTotal: ${result.totalDocs} documents\nPage: ${result.page} of ${result.totalPages}\n`;
|
|
133
116
|
for (const doc of result.docs){
|
|
134
117
|
responseText += `\n\`\`\`json\n${JSON.stringify(doc)}\n\`\`\``;
|
|
135
118
|
}
|
|
@@ -144,12 +127,12 @@ export const findCollectionTool = defineCollectionTool({
|
|
|
144
127
|
};
|
|
145
128
|
} catch (error) {
|
|
146
129
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
147
|
-
logger.error(`Error reading documents from collection ${
|
|
130
|
+
logger.error(`Error reading documents from collection ${slug}: ${errorMessage}`);
|
|
148
131
|
return {
|
|
149
132
|
content: [
|
|
150
133
|
{
|
|
151
134
|
type: 'text',
|
|
152
|
-
text: `❌ **Error reading documents from collection "${
|
|
135
|
+
text: `❌ **Error reading documents from collection "${slug}":** ${errorMessage}`
|
|
153
136
|
}
|
|
154
137
|
]
|
|
155
138
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/collections/findTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { localAPIDefaults } from '../../../utils/localAPIDefaults.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Find documents in a collection by ID or where clause using Find or FindByID.'\n\nexport const findCollectionTool = defineCollectionTool({\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n id: z\n .union([z.string(), z.number()])\n .describe(\n 'Optional: specific document ID to retrieve. If not provided, returns all documents',\n )\n .optional(),\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('How many levels deep to populate relationships (default: 0)')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe(\n 'Optional: whether the document should be queried from the versions table/collection or not.',\n )\n .optional(),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .describe('Maximum number of documents to return (default: 10, max: 100)')\n .optional()\n .default(10),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to retrieve data in (e.g., \"en\", \"es\"). Use \"all\" to retrieve all locales for localized fields',\n )\n .optional(),\n page: z\n .number()\n .int()\n .min(1)\n .describe('Page number for pagination (default: 1)')\n .optional()\n .default(1),\n select: z\n .string()\n .describe(\n \"Optional: define exactly which fields you'd like to return in the response (JSON), e.g., '{\\\"title\\\": true}'\",\n )\n .optional(),\n sort: z\n .string()\n .describe('Field to sort by (e.g., \"createdAt\", \"-updatedAt\" for descending)')\n .optional(),\n where: z\n .string()\n .describe(\n 'Optional JSON string for where clause filtering (e.g., \\'{\"title\": {\"contains\": \"test\"}}\\')',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const { id, depth, draft, fallbackLocale, limit, locale, page, select, sort, where } = input\n\n logger.info(\n `Reading document from collection: ${collectionSlug}${id ? ` with ID: ${id}` : ''}, limit: ${limit}, page: ${page}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n let whereClause: Record<string, unknown> = {}\n if (where) {\n try {\n whereClause = JSON.parse(where) as Record<string, unknown>\n } catch {\n logger.warn(`Invalid where clause JSON: ${where}`)\n return { content: [{ type: 'text', text: 'Error: Invalid JSON in where clause' }] }\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch {\n logger.warn(`Invalid select clause JSON: ${select}`)\n return { content: [{ type: 'text', text: 'Error: Invalid JSON in select clause' }] }\n }\n }\n\n if (id) {\n try {\n const doc = await payload.findByID({\n id,\n collection: collectionSlug,\n depth,\n req,\n ...localAPIDefaults(authorizedMCP),\n ...(selectClause && { select: selectClause }),\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(draft !== undefined && { draft }),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Document from collection \"${collectionSlug}\":\\n${JSON.stringify(doc)}`,\n },\n ],\n doc: doc as Record<string, unknown>,\n }\n } catch {\n logger.warn(`Document not found with ID: ${id} in collection: ${collectionSlug}`)\n return {\n content: [\n {\n type: 'text',\n text: `Error: Document with ID \"${id}\" not found in collection \"${collectionSlug}\"`,\n },\n ],\n }\n }\n }\n\n const findOptions: Parameters<typeof payload.find>[0] = {\n collection: collectionSlug,\n depth,\n limit,\n page,\n req,\n ...localAPIDefaults(authorizedMCP),\n ...(selectClause && { select: selectClause }),\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(draft !== undefined && { draft }),\n }\n\n if (sort) {\n findOptions.sort = sort\n }\n if (Object.keys(whereClause).length > 0) {\n findOptions.where = whereClause as Parameters<typeof payload.find>[0]['where']\n }\n\n const result = await payload.find(findOptions)\n\n let responseText = `Collection: \"${collectionSlug}\"\\nTotal: ${result.totalDocs} documents\\nPage: ${result.page} of ${result.totalPages}\\n`\n for (const doc of result.docs) {\n responseText += `\\n\\`\\`\\`json\\n${JSON.stringify(doc)}\\n\\`\\`\\``\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error reading documents from collection ${collectionSlug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error reading documents from collection \"${collectionSlug}\":** ${errorMessage}`,\n },\n ],\n }\n }\n})\n"],"names":["z","defineCollectionTool","getLogger","localAPIDefaults","DEFAULT_DESCRIPTION","findCollectionTool","description","input","object","id","union","string","number","describe","optional","depth","int","min","max","default","draft","boolean","fallbackLocale","limit","locale","page","select","sort","where","handler","authorizedMCP","collectionSlug","req","payload","logger","info","whereClause","JSON","parse","warn","content","type","text","selectClause","doc","findByID","collection","undefined","stringify","findOptions","Object","keys","length","result","find","responseText","totalDocs","totalPages","docs","error","errorMessage","Error","message"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,gBAAgB,QAAQ,qCAAoC;AAErE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,qBAAqBJ,qBAAqB;IACrDK,aAAaF;IACbG,OAAOP,EAAEQ,MAAM,CAAC;QACdC,IAAIT,EACDU,KAAK,CAAC;YAACV,EAAEW,MAAM;YAAIX,EAAEY,MAAM;SAAG,EAC9BC,QAAQ,CACP,sFAEDC,QAAQ;QACXC,OAAOf,EACJY,MAAM,GACNI,GAAG,GACHC,GAAG,CAAC,GACJC,GAAG,CAAC,IACJL,QAAQ,CAAC,+DACTC,QAAQ,GACRK,OAAO,CAAC;QACXC,OAAOpB,EACJqB,OAAO,GACPR,QAAQ,CACP,+FAEDC,QAAQ;QACXQ,gBAAgBtB,EACbW,MAAM,GACNE,QAAQ,CAAC,gFACTC,QAAQ;QACXS,OAAOvB,EACJY,MAAM,GACNI,GAAG,GACHC,GAAG,CAAC,GACJC,GAAG,CAAC,KACJL,QAAQ,CAAC,iEACTC,QAAQ,GACRK,OAAO,CAAC;QACXK,QAAQxB,EACLW,MAAM,GACNE,QAAQ,CACP,wHAEDC,QAAQ;QACXW,MAAMzB,EACHY,MAAM,GACNI,GAAG,GACHC,GAAG,CAAC,GACJJ,QAAQ,CAAC,2CACTC,QAAQ,GACRK,OAAO,CAAC;QACXO,QAAQ1B,EACLW,MAAM,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M,eAAe,CAAC,aAAa,EAAExB,eAAe,UAAU,EAAEsB,OAAOG,SAAS,CAAC,kBAAkB,EAAEH,OAAO5B,IAAI,CAAC,IAAI,EAAE4B,OAAOI,UAAU,CAAC,EAAE,CAAC;QAC1I,KAAK,MAAMb,OAAOS,OAAOK,IAAI,CAAE;YAC7BH,gBAAgB,CAAC,cAAc,EAAElB,KAAKW,SAAS,CAACJ,KAAK,QAAQ,CAAC;QAChE;QAEA,OAAO;YACLJ,SAAS;gBAAC;oBAAEC,MAAM;oBAAQC,MAAMa;gBAAa;aAAE;YAC/CX,KAAKS;QACP;IACF,EAAE,OAAOM,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9D5B,OAAOyB,KAAK,CAAC,CAAC,wCAAwC,EAAE5B,eAAe,EAAE,EAAE6B,cAAc;QACzF,OAAO;YACLpB,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,6CAA6C,EAAEX,eAAe,KAAK,EAAE6B,cAAc;gBAC5F;aACD;QACH;IACF;AACF,GAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/collections/findTool.ts"],"sourcesContent":["import { findDocumentsInputSchema } from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Find documents in any collection by passing the collection slug and optional ID or where clause.'\n\nexport const findDocumentsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.read),\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Find Documents',\n },\n description: DEFAULT_DESCRIPTION,\n input: findDocumentsInputSchema,\n}).handler(async ({ slug, authorizedMCP, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const {\n id,\n depth,\n draft,\n fallbackLocale,\n joins,\n limit,\n locale,\n page,\n pagination,\n populate,\n select,\n sort,\n trash,\n where,\n } = input\n\n logger.info(\n `Reading document from collection: ${slug}${id ? ` with ID: ${id}` : ''}, limit: ${limit}, page: ${page}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n if (id) {\n try {\n const doc = await payload.findByID({\n id,\n collection: slug,\n depth,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(select && { select }),\n ...(populate && { populate }),\n ...(joins !== undefined && { joins }),\n ...(locale && { locale }),\n ...(fallbackLocale !== undefined && { fallbackLocale }),\n ...(draft !== undefined && { draft }),\n ...(trash !== undefined && { trash }),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Document from collection \"${slug}\":\\n${JSON.stringify(doc)}`,\n },\n ],\n doc: doc as Record<string, unknown>,\n }\n } catch {\n logger.warn(`Document not found with ID: ${id} in collection: ${slug}`)\n return {\n content: [\n {\n type: 'text',\n text: `Error: Document with ID \"${id}\" not found in collection \"${slug}\"`,\n },\n ],\n }\n }\n }\n\n const findOptions: Parameters<typeof payload.find>[0] = {\n collection: slug,\n depth,\n limit,\n overrideAccess: authorizedMCP.overrideAccess,\n page,\n req,\n ...(select && { select }),\n ...(populate && { populate }),\n ...(joins !== undefined && { joins }),\n ...(locale && { locale }),\n ...(fallbackLocale !== undefined && { fallbackLocale }),\n ...(draft !== undefined && { draft }),\n ...(pagination !== undefined && { pagination }),\n ...(trash !== undefined && { trash }),\n }\n\n if (sort) {\n findOptions.sort = sort\n }\n if (where) {\n findOptions.where = where\n }\n\n const result = await payload.find(findOptions)\n\n let responseText = `Collection: \"${slug}\"\\nTotal: ${result.totalDocs} documents\\nPage: ${result.page} of ${result.totalPages}\\n`\n for (const doc of result.docs) {\n responseText += `\\n\\`\\`\\`json\\n${JSON.stringify(doc)}\\n\\`\\`\\``\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: result as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error reading documents from collection ${slug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error reading documents from collection \"${slug}\":** ${errorMessage}`,\n },\n ],\n }\n }\n})\n"],"names":["findDocumentsInputSchema","defaultAccess","defineCollectionTool","getLogger","DEFAULT_DESCRIPTION","findDocumentsTool","access","args","Boolean","permissions","collections","slug","read","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","handler","authorizedMCP","req","payload","logger","id","depth","draft","fallbackLocale","joins","limit","locale","page","pagination","populate","select","sort","trash","where","info","doc","findByID","collection","overrideAccess","undefined","content","type","text","JSON","stringify","warn","findOptions","result","find","responseText","totalDocs","totalPages","docs","error","errorMessage","Error","message"],"mappings":"AAAA,SAASA,wBAAwB,QAAQ,UAAS;AAElD,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AAEvD,MAAMC,sBACJ;AAEF,OAAO,MAAMC,oBAAoBH,qBAAqB;IACpDI,QAAQ,CAACC,OACPN,cAAcM,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,IAAI,CAAC,EAAEC;IAC7EC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOpB;AACT,GAAGqB,OAAO,CAAC,OAAO,EAAEV,IAAI,EAAEW,aAAa,EAAEF,KAAK,EAAEG,GAAG,EAAE;IACnD,MAAMC,UAAUD,IAAIC,OAAO;IAC3B,MAAMC,SAAStB,UAAU;QAAEqB;IAAQ;IAEnC,MAAM,EACJE,EAAE,EACFC,KAAK,EACLC,KAAK,EACLC,cAAc,EACdC,KAAK,EACLC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,UAAU,EACVC,QAAQ,EACRC,MAAM,EACNC,IAAI,EACJC,KAAK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3,"file":"findVersionByIDTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/findVersionByIDTool.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,mBAAmB,4CAwD9B,CAAA"}
|