@payloadcms/plugin-mcp 4.0.0-internal.3aa3d85 → 4.0.0-internal.3ed7230
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/endpoint/access.js +2 -2
- package/dist/endpoint/access.js.map +1 -1
- package/dist/mcp/buildMcpServer.d.ts +1 -1
- package/dist/mcp/buildMcpServer.d.ts.map +1 -1
- package/dist/mcp/buildMcpServer.js +35 -23
- 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 +79 -56
- package/dist/mcp/builtin/collections/authTools.js.map +1 -1
- package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/countTool.js +9 -14
- package/dist/mcp/builtin/collections/countTool.js.map +1 -1
- package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/countVersionsTool.js +9 -13
- package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/collections/createTool.d.ts +1 -1
- package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/createTool.js +104 -53
- package/dist/mcp/builtin/collections/createTool.js.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/deleteTool.js +44 -43
- package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
- package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/duplicateTool.js +31 -37
- package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
- package/dist/mcp/builtin/collections/fileInput.d.ts +28 -0
- package/dist/mcp/builtin/collections/fileInput.d.ts.map +1 -0
- package/dist/mcp/builtin/collections/fileInput.js +88 -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.map +1 -1
- package/dist/mcp/builtin/collections/findDistinctTool.js +11 -26
- package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findTool.js +27 -45
- package/dist/mcp/builtin/collections/findTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findVersionByIDTool.js +17 -26
- package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/findVersionsTool.js +16 -30
- package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +34 -12
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/restoreVersionTool.js +14 -26
- package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.js +65 -84
- 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.map +1 -1
- package/dist/mcp/builtin/getConfigInfoTool.js +3 -2
- package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
- package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/countVersionsTool.js +9 -13
- package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findTool.js +10 -16
- package/dist/mcp/builtin/globals/findTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findVersionByIDTool.js +13 -24
- package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
- package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/findVersionsTool.js +13 -29
- package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +11 -11
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/restoreVersionTool.js +15 -22
- package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
- package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/updateTool.js +27 -36
- package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
- package/dist/mcp/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/types.d.ts +4 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.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 +5 -7
- package/src/endpoint/access.ts +2 -3
- package/src/mcp/buildMcpServer.ts +39 -29
- package/src/mcp/builtin/collections/authTools.ts +77 -69
- package/src/mcp/builtin/collections/countTool.ts +9 -21
- package/src/mcp/builtin/collections/countVersionsTool.ts +9 -18
- package/src/mcp/builtin/collections/createTool.ts +110 -76
- package/src/mcp/builtin/collections/deleteTool.ts +36 -64
- package/src/mcp/builtin/collections/duplicateTool.ts +35 -85
- package/src/mcp/builtin/collections/fileInput.spec.ts +93 -0
- package/src/mcp/builtin/collections/fileInput.ts +127 -0
- package/src/mcp/builtin/collections/findDistinctTool.ts +11 -63
- package/src/mcp/builtin/collections/findTool.ts +23 -105
- package/src/mcp/builtin/collections/findVersionByIDTool.ts +15 -58
- package/src/mcp/builtin/collections/findVersionsTool.ts +14 -85
- package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +27 -10
- package/src/mcp/builtin/collections/restoreVersionTool.ts +14 -56
- package/src/mcp/builtin/collections/updateTool.ts +61 -98
- package/src/mcp/builtin/collections/uploadInstructionsTool.ts +64 -0
- package/src/mcp/builtin/formatEntityError.ts +77 -0
- package/src/mcp/builtin/getConfigInfoTool.ts +2 -1
- package/src/mcp/builtin/globals/countVersionsTool.ts +9 -17
- package/src/mcp/builtin/globals/findTool.ts +12 -51
- package/src/mcp/builtin/globals/findVersionByIDTool.ts +13 -52
- package/src/mcp/builtin/globals/findVersionsTool.ts +14 -92
- package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +10 -10
- package/src/mcp/builtin/globals/restoreVersionTool.ts +14 -45
- package/src/mcp/builtin/globals/updateTool.ts +37 -60
- package/src/mcp/builtinTools.ts +9 -2
- package/src/mcp/sanitizeMCPConfig.ts +4 -1
- package/src/stdio.ts +2 -1
- package/src/types.ts +4 -4
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts +0 -9
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +0 -1
- package/dist/mcp/builtin/collections/formatCollectionError.js +0 -60
- package/dist/mcp/builtin/collections/formatCollectionError.js.map +0 -1
- package/dist/mcp/builtin/validateEntityData.d.ts +0 -14
- package/dist/mcp/builtin/validateEntityData.d.ts.map +0 -1
- package/dist/mcp/builtin/validateEntityData.js +0 -82
- package/dist/mcp/builtin/validateEntityData.js.map +0 -1
- package/dist/utils/getVirtualFieldNames.d.ts +0 -14
- package/dist/utils/getVirtualFieldNames.d.ts.map +0 -1
- package/dist/utils/getVirtualFieldNames.js +0 -35
- package/dist/utils/getVirtualFieldNames.js.map +0 -1
- package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +0 -28
- package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +0 -1
- package/dist/utils/schemaConversion/filterFieldsByAccess.js +0 -71
- package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +0 -1
- package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +0 -13
- package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +0 -1
- package/dist/utils/schemaConversion/getEntityInputSchema.js +0 -66
- package/dist/utils/schemaConversion/getEntityInputSchema.js.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +0 -10
- package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.js +0 -384
- package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +0 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +0 -133
- package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +0 -1
- package/dist/utils/transformPointDataToPayload.d.ts +0 -7
- package/dist/utils/transformPointDataToPayload.d.ts.map +0 -1
- package/dist/utils/transformPointDataToPayload.js +0 -28
- package/dist/utils/transformPointDataToPayload.js.map +0 -1
- package/dist/utils/whereSchema.d.ts +0 -9
- package/dist/utils/whereSchema.d.ts.map +0 -1
- package/dist/utils/whereSchema.js +0 -13
- package/dist/utils/whereSchema.js.map +0 -1
- package/src/mcp/builtin/collections/formatCollectionError.ts +0 -84
- package/src/mcp/builtin/validateEntityData.ts +0 -132
- package/src/utils/getVirtualFieldNames.ts +0 -53
- package/src/utils/schemaConversion/filterFieldsByAccess.ts +0 -123
- package/src/utils/schemaConversion/getEntityInputSchema.ts +0 -96
- package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +0 -96
- package/src/utils/schemaConversion/sanitizeEntitySchema.ts +0 -432
- package/src/utils/transformPointDataToPayload.ts +0 -40
- package/src/utils/whereSchema.ts +0 -24
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { CollectionSlug, File, PayloadRequest } from 'payload';
|
|
2
|
+
import { z } from 'payload';
|
|
3
|
+
export declare const fileInputSchema: z.ZodMiniDiscriminatedUnion<[z.ZodMiniObject<{
|
|
4
|
+
name: z.ZodMiniString<string>;
|
|
5
|
+
data: z.ZodMiniString<string>;
|
|
6
|
+
mimeType: z.ZodMiniString<string>;
|
|
7
|
+
source: z.ZodMiniLiteral<"base64">;
|
|
8
|
+
}, z.core.$strict>, z.ZodMiniObject<{
|
|
9
|
+
name: z.ZodMiniOptional<z.ZodMiniString<string>>;
|
|
10
|
+
source: z.ZodMiniLiteral<"externalURL">;
|
|
11
|
+
url: z.ZodMiniURL;
|
|
12
|
+
}, z.core.$strict>, z.ZodMiniObject<{
|
|
13
|
+
file: z.ZodMiniObject<{
|
|
14
|
+
filename: z.ZodMiniString<string>;
|
|
15
|
+
mimeType: z.ZodMiniString<string>;
|
|
16
|
+
size: z.ZodMiniInt;
|
|
17
|
+
uploadReference: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
|
|
18
|
+
}, z.core.$strict>;
|
|
19
|
+
source: z.ZodMiniLiteral<"uploadReference">;
|
|
20
|
+
}, z.core.$strict>], "source">;
|
|
21
|
+
type FileInput = z.infer<typeof fileInputSchema>;
|
|
22
|
+
export declare function resolveFile({ slug, input, req, }: {
|
|
23
|
+
input?: FileInput;
|
|
24
|
+
req: PayloadRequest;
|
|
25
|
+
slug: CollectionSlug;
|
|
26
|
+
}): Promise<File | undefined>;
|
|
27
|
+
export {};
|
|
28
|
+
//# sourceMappingURL=fileInput.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fileInput.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAEnE,OAAO,EAAY,CAAC,EAAE,MAAM,SAAS,CAAA;AAwBrC,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;8BAoBzB,CAAA;AAEH,KAAK,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAA;AAEhD,wBAAsB,WAAW,CAAC,EAChC,IAAI,EACJ,KAAK,EACL,GAAG,GACJ,EAAE;IACD,KAAK,CAAC,EAAE,SAAS,CAAA;IACjB,GAAG,EAAE,cAAc,CAAA;IACnB,IAAI,EAAE,cAAc,CAAA;CACrB,GAAG,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC,CA2C5B"}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { APIError, z } from 'payload';
|
|
2
|
+
import { externalURLInputSchema, getFileFromUploadInstructions, resolveURLUploadInput } 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
|
+
externalURLInputSchema,
|
|
19
|
+
z.strictObject({
|
|
20
|
+
file: uploadFileSchema.check(z.describe('getUploadInstructions file field post-upload.')),
|
|
21
|
+
source: z.literal('uploadReference')
|
|
22
|
+
})
|
|
23
|
+
]).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.'));
|
|
24
|
+
export async function resolveFile({ slug, input, req }) {
|
|
25
|
+
if (!input) {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
if (input.source === 'uploadReference') {
|
|
29
|
+
try {
|
|
30
|
+
return await getFileFromUploadInstructions({
|
|
31
|
+
collectionSlug: slug,
|
|
32
|
+
file: input.file,
|
|
33
|
+
req
|
|
34
|
+
});
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (error instanceof Error && error.message === 'Staged upload was not found.') {
|
|
37
|
+
throw new APIError('Staged upload not found. Complete the upload action first, or use base64 for small local files.', 400);
|
|
38
|
+
}
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (input.source === 'externalURL') {
|
|
43
|
+
return resolveURLUploadInput({
|
|
44
|
+
slug,
|
|
45
|
+
input,
|
|
46
|
+
req
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
const uploadConfig = req.payload.collections[slug]?.config.upload;
|
|
50
|
+
if (!uploadConfig) {
|
|
51
|
+
throw new APIError(`Collection "${slug}" does not support file uploads.`, 400);
|
|
52
|
+
}
|
|
53
|
+
const maxFileSize = req.payload.config.upload.limits?.fileSize;
|
|
54
|
+
const data = decodeBase64({
|
|
55
|
+
maxFileSize,
|
|
56
|
+
value: input.data
|
|
57
|
+
});
|
|
58
|
+
const file = {
|
|
59
|
+
name: sanitizeFilename(input.name),
|
|
60
|
+
data,
|
|
61
|
+
mimetype: input.mimeType,
|
|
62
|
+
size: data.length
|
|
63
|
+
};
|
|
64
|
+
if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {
|
|
65
|
+
throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400);
|
|
66
|
+
}
|
|
67
|
+
return file;
|
|
68
|
+
}
|
|
69
|
+
function decodeBase64({ maxFileSize, value }) {
|
|
70
|
+
const normalized = value.replace(/\s/g, '');
|
|
71
|
+
if (!/^[a-z0-9+/]*={0,2}$/i.test(normalized) || normalized.length % 4 === 1) {
|
|
72
|
+
throw new APIError('File data must be valid base64.', 400);
|
|
73
|
+
}
|
|
74
|
+
if (maxFileSize !== undefined && Number.isFinite(maxFileSize)) {
|
|
75
|
+
const paddingLength = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0;
|
|
76
|
+
const decodedSize = Math.floor(normalized.length * 3 / 4) - paddingLength;
|
|
77
|
+
if (decodedSize > maxFileSize) {
|
|
78
|
+
throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const data = Buffer.from(normalized, 'base64');
|
|
82
|
+
if (data.toString('base64').replace(/=+$/, '') !== normalized.replace(/=+$/, '')) {
|
|
83
|
+
throw new APIError('File data must be valid base64.', 400);
|
|
84
|
+
}
|
|
85
|
+
return data;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
//# sourceMappingURL=fileInput.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"sourcesContent":["import type { CollectionSlug, File, PayloadRequest } from 'payload'\n\nimport { APIError, z } from 'payload'\nimport {\n externalURLInputSchema,\n getFileFromUploadInstructions,\n resolveURLUploadInput,\n} 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 externalURLInputSchema,\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 if (input.source === 'externalURL') {\n return resolveURLUploadInput({ slug, input, req })\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 const data = decodeBase64({ maxFileSize, value: input.data })\n const file: File = {\n name: sanitizeFilename(input.name),\n data,\n mimetype: input.mimeType,\n size: 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"],"names":["APIError","z","externalURLInputSchema","getFileFromUploadInstructions","resolveURLUploadInput","sanitizeFilename","mimeTypeSchema","string","check","regex","uploadFileSchema","strictObject","filename","mimeType","size","int","nonnegative","uploadReference","record","unknown","fileInputSchema","discriminatedUnion","name","minLength","describe","data","source","literal","file","resolveFile","slug","input","req","undefined","collectionSlug","error","Error","message","uploadConfig","payload","collections","config","upload","maxFileSize","limits","fileSize","decodeBase64","value","mimetype","length","Number","isFinite","normalized","replace","test","paddingLength","endsWith","decodedSize","Math","floor","Buffer","from","toString"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,CAAC,QAAQ,UAAS;AACrC,SACEC,sBAAsB,EACtBC,6BAA6B,EAC7BC,qBAAqB,QAChB,mBAAkB;AACzB,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,EAAEkB,OAAO;AACjD;AAEA,OAAO,MAAMC,kBAAkBnB,EAC5BoB,kBAAkB,CAAC,UAAU;IAC5BpB,EAAEU,YAAY,CAAC;QACbW,MAAMrB,EAAEM,MAAM,GAAGC,KAAK,CAACP,EAAEsB,SAAS,CAAC,IAAItB,EAAEuB,QAAQ,CAAC;QAClDC,MAAMxB,EACHM,MAAM,GACNC,KAAK,CAACP,EAAEuB,QAAQ,CAAC;QACpBX,UAAUP,eAAeE,KAAK,CAACP,EAAEuB,QAAQ,CAAC;QAC1CE,QAAQzB,EAAE0B,OAAO,CAAC;IACpB;IACAzB;IACAD,EAAEU,YAAY,CAAC;QACbiB,MAAMlB,iBAAiBF,KAAK,CAACP,EAAEuB,QAAQ,CAAC;QACxCE,QAAQzB,EAAE0B,OAAO,CAAC;IACpB;CACD,EACAnB,KAAK,CACJP,EAAEuB,QAAQ,CACR,gKAEH;AAIH,OAAO,eAAeK,YAAY,EAChCC,IAAI,EACJC,KAAK,EACLC,GAAG,EAKJ;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GAAG,MAAM,GAAG;QAC3E,MAAM,IAAIjD,SAAS,mCAAmC;IACxD;IAEA,IAAI2C,gBAAgBV,aAAaiB,OAAOC,QAAQ,CAACR,cAAc;QAC7D,MAAMY,gBAAgBH,WAAWI,QAAQ,CAAC,QAAQ,IAAIJ,WAAWI,QAAQ,CAAC,OAAO,IAAI;QACrF,MAAMC,cAAcC,KAAKC,KAAK,CAAC,AAACP,WAAWH,MAAM,GAAG,IAAK,KAAKM;QAE9D,IAAIE,cAAcd,aAAa;YAC7B,MAAM,IAAI3C,SAAS,CAAC,iBAAiB,EAAE2C,YAAY,mBAAmB,CAAC,EAAE;QAC3E;IACF;IAEA,MAAMlB,OAAOmC,OAAOC,IAAI,CAACT,YAAY;IAErC,IAAI3B,KAAKqC,QAAQ,CAAC,UAAUT,OAAO,CAAC,OAAO,QAAQD,WAAWC,OAAO,CAAC,OAAO,KAAK;QAChF,MAAM,IAAIrD,SAAS,mCAAmC;IACxD;IAEA,OAAOyB;AACT"}
|
|
@@ -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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"findDistinctTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/findDistinctTool.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"findDistinctTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/findDistinctTool.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,gBAAgB,4CAyD3B,CAAA"}
|
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { findDistinctInputSchema } from 'payload';
|
|
2
2
|
import { defaultAccess } from '../../../defaultAccess.js';
|
|
3
3
|
import { defineCollectionTool } from '../../../defineTool.js';
|
|
4
4
|
import { getLogger } from '../../../utils/getLogger.js';
|
|
5
|
-
import { whereSchema } from '../../../utils/whereSchema.js';
|
|
6
5
|
const DEFAULT_DESCRIPTION = 'Find distinct values for a field in any collection by passing the collection slug and field path.';
|
|
7
6
|
export const findDistinctTool = defineCollectionTool({
|
|
8
|
-
access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.
|
|
7
|
+
access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.read),
|
|
9
8
|
annotations: {
|
|
10
9
|
destructiveHint: false,
|
|
11
10
|
idempotentHint: true,
|
|
@@ -14,28 +13,17 @@ export const findDistinctTool = defineCollectionTool({
|
|
|
14
13
|
title: 'Find Distinct'
|
|
15
14
|
},
|
|
16
15
|
description: DEFAULT_DESCRIPTION,
|
|
17
|
-
input:
|
|
18
|
-
|
|
19
|
-
field: z.string().describe('The field path to get distinct values for'),
|
|
20
|
-
limit: z.number().int().min(1).max(100).describe('Maximum number of distinct values to return (max: 100)').optional(),
|
|
21
|
-
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(),
|
|
22
|
-
page: z.number().int().min(1).describe('Page number for pagination').optional(),
|
|
23
|
-
populate: z.record(z.string(), z.unknown()).describe('Optional: control which fields to include from populated relationship or upload documents.').optional(),
|
|
24
|
-
showHiddenFields: z.boolean().describe('Optional: include hidden fields in the distinct query').optional(),
|
|
25
|
-
sort: z.string().describe('Field to sort by (e.g., "createdAt", "-updatedAt" for descending)').optional(),
|
|
26
|
-
trash: z.boolean().describe('Optional: include soft-deleted documents when trash is enabled on the collection').optional(),
|
|
27
|
-
where: whereSchema.describe('Optional: where clause for filtering. Use field names with Payload operators, and/or arrays for grouping. Example: {"title":{"contains":"test"}}').optional()
|
|
28
|
-
})
|
|
29
|
-
}).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
|
|
16
|
+
input: findDistinctInputSchema
|
|
17
|
+
}).handler(async ({ slug, authorizedMCP, input, req })=>{
|
|
30
18
|
const payload = req.payload;
|
|
31
19
|
const logger = getLogger({
|
|
32
20
|
payload
|
|
33
21
|
});
|
|
34
|
-
const { depth, field, limit, locale, page, populate,
|
|
35
|
-
logger.info(`Finding distinct values in collection: ${
|
|
22
|
+
const { depth, field, limit, locale, page, populate, sort, trash, where } = input;
|
|
23
|
+
logger.info(`Finding distinct values in collection: ${slug}, field: ${field}`);
|
|
36
24
|
try {
|
|
37
25
|
const result = await payload.findDistinct({
|
|
38
|
-
collection:
|
|
26
|
+
collection: slug,
|
|
39
27
|
depth,
|
|
40
28
|
field,
|
|
41
29
|
overrideAccess: authorizedMCP.overrideAccess,
|
|
@@ -50,10 +38,7 @@ export const findDistinctTool = defineCollectionTool({
|
|
|
50
38
|
page
|
|
51
39
|
} : {},
|
|
52
40
|
...populate ? {
|
|
53
|
-
populate
|
|
54
|
-
} : {},
|
|
55
|
-
...showHiddenFields !== undefined ? {
|
|
56
|
-
showHiddenFields
|
|
41
|
+
populate
|
|
57
42
|
} : {},
|
|
58
43
|
...sort ? {
|
|
59
44
|
sort
|
|
@@ -69,19 +54,19 @@ export const findDistinctTool = defineCollectionTool({
|
|
|
69
54
|
content: [
|
|
70
55
|
{
|
|
71
56
|
type: 'text',
|
|
72
|
-
text: `Distinct values for "${field}" in collection "${
|
|
57
|
+
text: `Distinct values for "${field}" in collection "${slug}":\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\``
|
|
73
58
|
}
|
|
74
59
|
],
|
|
75
60
|
doc: result
|
|
76
61
|
};
|
|
77
62
|
} catch (error) {
|
|
78
63
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
79
|
-
logger.error(`Error finding distinct values in ${
|
|
64
|
+
logger.error(`Error finding distinct values in ${slug}: ${errorMessage}`);
|
|
80
65
|
return {
|
|
81
66
|
content: [
|
|
82
67
|
{
|
|
83
68
|
type: 'text',
|
|
84
|
-
text: `❌ **Error finding distinct values in collection "${
|
|
69
|
+
text: `❌ **Error finding distinct values in collection "${slug}":** ${errorMessage}`
|
|
85
70
|
}
|
|
86
71
|
],
|
|
87
72
|
isError: true
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/collections/findDistinctTool.ts"],"sourcesContent":["import
|
|
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,QAA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,IAAI,CAAC,CAAC;QAC5B;QAEA,OAAO;YACLO,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,qBAAqB,EAAEhB,MAAM,iBAAiB,EAAEhB,KAAK,gBAAgB,EAAEiC,KAAKC,SAAS,CAACT,QAAQ,QAAQ,CAAC;gBAChH;aACD;YACDU,KAAKV;QACP;IACF,EAAE,OAAOW,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,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 +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,11 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { findDocumentsInputSchema, parseDocumentID } from 'payload';
|
|
2
2
|
import { defaultAccess } from '../../../defaultAccess.js';
|
|
3
3
|
import { defineCollectionTool } from '../../../defineTool.js';
|
|
4
4
|
import { getLogger } from '../../../utils/getLogger.js';
|
|
5
|
-
import { whereSchema } from '../../../utils/whereSchema.js';
|
|
6
5
|
const DEFAULT_DESCRIPTION = 'Find documents in any collection by passing the collection slug and optional ID or where clause.';
|
|
7
6
|
export const findDocumentsTool = defineCollectionTool({
|
|
8
|
-
access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.
|
|
7
|
+
access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.slug]?.read),
|
|
9
8
|
annotations: {
|
|
10
9
|
destructiveHint: false,
|
|
11
10
|
idempotentHint: true,
|
|
@@ -14,57 +13,40 @@ export const findDocumentsTool = defineCollectionTool({
|
|
|
14
13
|
title: 'Find Documents'
|
|
15
14
|
},
|
|
16
15
|
description: DEFAULT_DESCRIPTION,
|
|
17
|
-
input:
|
|
18
|
-
|
|
19
|
-
z.string(),
|
|
20
|
-
z.number()
|
|
21
|
-
]).describe('Optional: specific document ID to retrieve. If not provided, returns all documents').optional(),
|
|
22
|
-
depth: z.number().int().min(0).max(10).describe('How many levels deep to populate relationships (default: 0)').optional().default(0),
|
|
23
|
-
draft: z.boolean().describe('Optional: whether the document should be queried from the versions table/collection or not.').optional(),
|
|
24
|
-
fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
|
|
25
|
-
joins: z.union([
|
|
26
|
-
z.record(z.string(), z.unknown()),
|
|
27
|
-
z.literal(false)
|
|
28
|
-
]).describe('Optional: configure join field queries, or pass false to disable all join fields.').optional(),
|
|
29
|
-
limit: z.number().int().min(1).max(100).describe('Maximum number of documents to return (default: 10, max: 100)').optional().default(10),
|
|
30
|
-
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(),
|
|
31
|
-
page: z.number().int().min(1).describe('Page number for pagination (default: 1)').optional().default(1),
|
|
32
|
-
pagination: z.boolean().describe('Optional: set to false to skip the count query overhead').optional(),
|
|
33
|
-
populate: z.record(z.string(), z.unknown()).describe('Optional: control which fields to include from populated relationship or upload documents.').optional(),
|
|
34
|
-
select: z.record(z.string(), z.unknown()).describe('Optional: define exactly which fields you\'d like to return in the response, e.g., {"title": true}').optional(),
|
|
35
|
-
sort: z.string().describe('Field to sort by (e.g., "createdAt", "-updatedAt" for descending)').optional(),
|
|
36
|
-
trash: z.boolean().describe('Optional: include soft-deleted documents when trash is enabled on the collection').optional(),
|
|
37
|
-
where: whereSchema.describe('Optional: where clause for filtering. Use field names with Payload operators, and/or arrays for grouping. Example: {"title":{"contains":"test"}}').optional()
|
|
38
|
-
})
|
|
39
|
-
}).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
|
|
16
|
+
input: findDocumentsInputSchema
|
|
17
|
+
}).handler(async ({ slug, authorizedMCP, input, req })=>{
|
|
40
18
|
const payload = req.payload;
|
|
41
19
|
const logger = getLogger({
|
|
42
20
|
payload
|
|
43
21
|
});
|
|
44
22
|
const { id, depth, draft, fallbackLocale, joins, limit, locale, page, pagination, populate, select, sort, trash, where } = input;
|
|
45
|
-
logger.info(`Reading document from collection: ${
|
|
23
|
+
logger.info(`Reading document from collection: ${slug}${id ? ` with ID: ${id}` : ''}, limit: ${limit}, page: ${page}${locale ? `, locale: ${locale}` : ''}`);
|
|
46
24
|
try {
|
|
47
|
-
if (id) {
|
|
25
|
+
if (id !== undefined) {
|
|
48
26
|
try {
|
|
49
27
|
const doc = await payload.findByID({
|
|
50
|
-
id
|
|
51
|
-
|
|
28
|
+
id: parseDocumentID({
|
|
29
|
+
id,
|
|
30
|
+
collectionSlug: slug,
|
|
31
|
+
payload
|
|
32
|
+
}),
|
|
33
|
+
collection: slug,
|
|
52
34
|
depth,
|
|
53
35
|
overrideAccess: authorizedMCP.overrideAccess,
|
|
54
36
|
req,
|
|
55
37
|
...select && {
|
|
56
|
-
select
|
|
38
|
+
select
|
|
57
39
|
},
|
|
58
40
|
...populate && {
|
|
59
|
-
populate
|
|
41
|
+
populate
|
|
60
42
|
},
|
|
61
43
|
...joins !== undefined && {
|
|
62
|
-
joins
|
|
44
|
+
joins
|
|
63
45
|
},
|
|
64
46
|
...locale && {
|
|
65
47
|
locale
|
|
66
48
|
},
|
|
67
|
-
...fallbackLocale && {
|
|
49
|
+
...fallbackLocale !== undefined && {
|
|
68
50
|
fallbackLocale
|
|
69
51
|
},
|
|
70
52
|
...draft !== undefined && {
|
|
@@ -78,43 +60,43 @@ export const findDocumentsTool = defineCollectionTool({
|
|
|
78
60
|
content: [
|
|
79
61
|
{
|
|
80
62
|
type: 'text',
|
|
81
|
-
text: `Document from collection "${
|
|
63
|
+
text: `Document from collection "${slug}":\n${JSON.stringify(doc)}`
|
|
82
64
|
}
|
|
83
65
|
],
|
|
84
66
|
doc: doc
|
|
85
67
|
};
|
|
86
68
|
} catch {
|
|
87
|
-
logger.warn(`Document not found with ID: ${id} in collection: ${
|
|
69
|
+
logger.warn(`Document not found with ID: ${id} in collection: ${slug}`);
|
|
88
70
|
return {
|
|
89
71
|
content: [
|
|
90
72
|
{
|
|
91
73
|
type: 'text',
|
|
92
|
-
text: `Error: Document with ID "${id}" not found in collection "${
|
|
74
|
+
text: `Error: Document with ID "${id}" not found in collection "${slug}"`
|
|
93
75
|
}
|
|
94
76
|
]
|
|
95
77
|
};
|
|
96
78
|
}
|
|
97
79
|
}
|
|
98
80
|
const findOptions = {
|
|
99
|
-
collection:
|
|
81
|
+
collection: slug,
|
|
100
82
|
depth,
|
|
101
83
|
limit,
|
|
102
84
|
overrideAccess: authorizedMCP.overrideAccess,
|
|
103
85
|
page,
|
|
104
86
|
req,
|
|
105
87
|
...select && {
|
|
106
|
-
select
|
|
88
|
+
select
|
|
107
89
|
},
|
|
108
90
|
...populate && {
|
|
109
|
-
populate
|
|
91
|
+
populate
|
|
110
92
|
},
|
|
111
93
|
...joins !== undefined && {
|
|
112
|
-
joins
|
|
94
|
+
joins
|
|
113
95
|
},
|
|
114
96
|
...locale && {
|
|
115
97
|
locale
|
|
116
98
|
},
|
|
117
|
-
...fallbackLocale && {
|
|
99
|
+
...fallbackLocale !== undefined && {
|
|
118
100
|
fallbackLocale
|
|
119
101
|
},
|
|
120
102
|
...draft !== undefined && {
|
|
@@ -134,7 +116,7 @@ export const findDocumentsTool = defineCollectionTool({
|
|
|
134
116
|
findOptions.where = where;
|
|
135
117
|
}
|
|
136
118
|
const result = await payload.find(findOptions);
|
|
137
|
-
let responseText = `Collection: "${
|
|
119
|
+
let responseText = `Collection: "${slug}"\nTotal: ${result.totalDocs} documents\nPage: ${result.page} of ${result.totalPages}\n`;
|
|
138
120
|
for (const doc of result.docs){
|
|
139
121
|
responseText += `\n\`\`\`json\n${JSON.stringify(doc)}\n\`\`\``;
|
|
140
122
|
}
|
|
@@ -149,12 +131,12 @@ export const findDocumentsTool = defineCollectionTool({
|
|
|
149
131
|
};
|
|
150
132
|
} catch (error) {
|
|
151
133
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
152
|
-
logger.error(`Error reading documents from collection ${
|
|
134
|
+
logger.error(`Error reading documents from collection ${slug}: ${errorMessage}`);
|
|
153
135
|
return {
|
|
154
136
|
content: [
|
|
155
137
|
{
|
|
156
138
|
type: 'text',
|
|
157
|
-
text: `❌ **Error reading documents from collection "${
|
|
139
|
+
text: `❌ **Error reading documents from collection "${slug}":** ${errorMessage}`
|
|
158
140
|
}
|
|
159
141
|
]
|
|
160
142
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/collections/findTool.ts"],"sourcesContent":["import type { JoinQuery, PopulateType, SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { whereSchema } from '../../../utils/whereSchema.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.collectionSlug]?.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: 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 joins: z\n .union([z.record(z.string(), z.unknown()), z.literal(false)])\n .describe('Optional: configure join field queries, or pass false to disable all join fields.')\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 pagination: z\n .boolean()\n .describe('Optional: set to false to skip the count query overhead')\n .optional(),\n populate: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: control which fields to include from populated relationship or upload documents.',\n )\n .optional(),\n select: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response, 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 trash: z\n .boolean()\n .describe('Optional: include soft-deleted documents when trash is enabled on the collection')\n .optional(),\n where: whereSchema\n .describe(\n 'Optional: where clause for filtering. Use field names with Payload operators, and/or arrays for grouping. Example: {\"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 {\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: ${collectionSlug}${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: collectionSlug,\n depth,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(select && { select: select as SelectType }),\n ...(populate && { populate: populate as PopulateType }),\n ...(joins !== undefined && { joins: joins as JoinQuery }),\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(draft !== undefined && { draft }),\n ...(trash !== undefined && { trash }),\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 overrideAccess: authorizedMCP.overrideAccess,\n page,\n req,\n ...(select && { select: select as SelectType }),\n ...(populate && { populate: populate as PopulateType }),\n ...(joins !== undefined && { joins: joins as JoinQuery }),\n ...(locale && { locale }),\n ...(fallbackLocale && { 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: \"${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","defaultAccess","defineCollectionTool","getLogger","whereSchema","DEFAULT_DESCRIPTION","findDocumentsTool","access","args","Boolean","permissions","collections","collectionSlug","read","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","id","union","string","number","describe","optional","depth","int","min","max","default","draft","boolean","fallbackLocale","joins","record","unknown","literal","limit","locale","page","pagination","populate","select","sort","trash","where","handler","authorizedMCP","req","payload","logger","info","doc","findByID","collection","overrideAccess","undefined","content","type","text","JSON","stringify","warn","findOptions","result","find","responseText","totalDocs","totalPages","docs","error","errorMessage","Error","message"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,WAAW,QAAQ,gCAA+B;AAE3D,MAAMC,sBACJ;AAEF,OAAO,MAAMC,oBAAoBJ,qBAAqB;IACpDK,QAAQ,CAACC,OACPP,cAAcO,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IACvFC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOrB,EAAEsB,MAAM,CAAC;QACdC,IAAIvB,EACDwB,KAAK,CAAC;YAACxB,EAAEyB,MAAM;YAAIzB,EAAE0B,MAAM;SAAG,EAC9BC,QAAQ,CACP,sFAEDC,QAAQ;QACXC,OAAO7B,EACJ0B,MAAM,GACNI,GAAG,GACHC,GAAG,CAAC,GACJC,GAAG,CAAC,IACJL,QAAQ,CAAC,+DACTC,QAAQ,GACRK,OAAO,CAAC;QACXC,OAAOlC,EACJmC,OAAO,GACPR,QAAQ,CACP,+FAE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YACLd,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,6CAA6C,EAAEnD,eAAe,KAAK,EAAE+D,cAAc;gBAC5F;aACD;QACH;IACF;AACF,GAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/collections/findTool.ts"],"sourcesContent":["import { findDocumentsInputSchema, parseDocumentID } 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 !== undefined) {\n try {\n const doc = await payload.findByID({\n id: parseDocumentID({ id, collectionSlug: slug, payload }),\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","parseDocumentID","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","undefined","doc","findByID","collectionSlug","collection","overrideAccess","content","type","text","JSON","stringify","warn","findOptions","result","find","responseText","totalDocs","totalPages","docs","error","errorMessage","Error","message"],"mappings":"AAAA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AGA;QACrB;QACA,IAAIE,OAAO;YACTc,YAAYd,KAAK,GAAGA;QACtB;QAEA,MAAMe,SAAS,MAAM9B,QAAQ+B,IAAI,CAACF;QAElC,IAAIG,eAAe,CAAC,aAAa,EAAE7C,KAAK,UAAU,EAAE2C,OAAOG,SAAS,CAAC,kBAAkB,EAAEH,OAAOrB,IAAI,CAAC,IAAI,EAAEqB,OAAOI,UAAU,CAAC,EAAE,CAAC;QAChI,KAAK,MAAMhB,OAAOY,OAAOK,IAAI,CAAE;YAC7BH,gBAAgB,CAAC,cAAc,EAAEN,KAAKC,SAAS,CAACT,KAAK,QAAQ,CAAC;QAChE;QAEA,OAAO;YACLK,SAAS;gBAAC;oBAAEC,MAAM;oBAAQC,MAAMO;gBAAa;aAAE;YAC/Cd,KAAKY;QACP;IACF,EAAE,OAAOM,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DtC,OAAOmC,KAAK,CAAC,CAAC,wCAAwC,EAAEjD,KAAK,EAAE,EAAEkD,cAAc;QAC/E,OAAO;YACLd,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,6CAA6C,EAAEtC,KAAK,KAAK,EAAEkD,cAAc;gBAClF;aACD;QACH;IACF;AACF,GAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"findVersionByIDTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/findVersionByIDTool.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"findVersionByIDTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/findVersionByIDTool.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,mBAAmB,4CAwD9B,CAAA"}
|