@payloadcms/plugin-mcp 4.0.0-internal.8867dba → 4.0.0-internal.8ba6b5b
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 +0 -7
- package/dist/defaultAccess.d.ts.map +1 -1
- package/dist/defineTool.d.ts +8 -8
- package/dist/defineTool.d.ts.map +1 -1
- package/dist/endpoint/access.d.ts.map +1 -1
- package/dist/mcp/buildMcpServer.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/createTool.js +4 -14
- package/dist/mcp/builtin/collections/createTool.js.map +1 -1
- package/dist/mcp/builtin/collections/findTool.js +1 -1
- package/dist/mcp/builtin/collections/findTool.js.map +1 -1
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts +1 -1
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +2 -24
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.js +9 -22
- package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
- package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -1
- package/dist/mcp/builtinTools.d.ts +0 -6
- package/dist/mcp/builtinTools.d.ts.map +1 -1
- package/dist/mcp/builtinTools.js +0 -6
- package/dist/mcp/builtinTools.js.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
- package/dist/mcp/sanitizeMCPConfig.js +1 -4
- package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
- package/dist/utils/camelCase.d.ts.map +1 -1
- package/dist/utils/resolveProjectRoot.d.ts.map +1 -1
- package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +1 -1
- package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -1
- package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +2 -2
- package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -1
- package/dist/utils/toStandardSchema.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/mcp/builtin/collections/createTool.ts +4 -14
- package/src/mcp/builtin/collections/findTool.ts +1 -1
- package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +1 -18
- package/src/mcp/builtin/collections/updateTool.ts +7 -24
- package/src/mcp/builtinTools.ts +0 -7
- package/src/mcp/sanitizeMCPConfig.ts +1 -4
- package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +2 -2
- package/dist/mcp/builtin/collections/fileInput.d.ts +0 -28
- package/dist/mcp/builtin/collections/fileInput.d.ts.map +0 -1
- package/dist/mcp/builtin/collections/fileInput.js +0 -117
- package/dist/mcp/builtin/collections/fileInput.js.map +0 -1
- package/dist/mcp/builtin/collections/fileInput.spec.js +0 -86
- package/dist/mcp/builtin/collections/fileInput.spec.js.map +0 -1
- package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts +0 -2
- package/dist/mcp/builtin/collections/uploadInstructionsTool.d.ts.map +0 -1
- package/dist/mcp/builtin/collections/uploadInstructionsTool.js +0 -55
- package/dist/mcp/builtin/collections/uploadInstructionsTool.js.map +0 -1
- package/src/mcp/builtin/collections/fileInput.spec.ts +0 -93
- package/src/mcp/builtin/collections/fileInput.ts +0 -154
- package/src/mcp/builtin/collections/uploadInstructionsTool.ts +0 -64
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
import { APIError } from 'payload';
|
|
2
|
-
import { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal';
|
|
3
|
-
import { sanitizeFilename } from 'payload/shared';
|
|
4
|
-
import { z } from 'zod';
|
|
5
|
-
const mimeTypeSchema = z.string().regex(/^[!#$%&'*+.^`|~\w-]+\/[!#$%&'*+.^`|~\w-]+$/, 'MIME type must use the type/subtype format');
|
|
6
|
-
const uploadFileSchema = z.object({
|
|
7
|
-
filename: z.string(),
|
|
8
|
-
mimeType: z.string(),
|
|
9
|
-
size: z.number().int().nonnegative(),
|
|
10
|
-
uploadReference: z.record(z.string(), z.unknown())
|
|
11
|
-
});
|
|
12
|
-
export const fileInputSchema = z.discriminatedUnion('source', [
|
|
13
|
-
z.object({
|
|
14
|
-
name: z.string().min(1).describe('The file name, including its extension'),
|
|
15
|
-
data: z.string().describe('The base64-encoded file bytes, without a data URL prefix'),
|
|
16
|
-
mimeType: mimeTypeSchema.describe('The file MIME type, for example image/png'),
|
|
17
|
-
source: z.literal('base64')
|
|
18
|
-
}),
|
|
19
|
-
z.object({
|
|
20
|
-
name: z.string().min(1).describe('Optional file name override').optional(),
|
|
21
|
-
source: z.literal('externalURL'),
|
|
22
|
-
url: z.url().describe('The http or https URL to download')
|
|
23
|
-
}),
|
|
24
|
-
z.object({
|
|
25
|
-
file: uploadFileSchema.describe('The file value returned by getUploadInstructions'),
|
|
26
|
-
source: z.literal('uploadReference')
|
|
27
|
-
})
|
|
28
|
-
]).describe('A file for an upload collection. Use externalURL for an online file, base64 for local file bytes, or uploadReference after following getUploadInstructions. Usage of getUploadInstructions and uploadReference is recommended.');
|
|
29
|
-
export async function resolveFile({ collectionSlug, input, req }) {
|
|
30
|
-
if (!input) {
|
|
31
|
-
return undefined;
|
|
32
|
-
}
|
|
33
|
-
if (input.source === 'uploadReference') {
|
|
34
|
-
return getFileFromUploadInstructions({
|
|
35
|
-
collectionSlug,
|
|
36
|
-
file: input.file,
|
|
37
|
-
req
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
const uploadConfig = req.payload.collections[collectionSlug]?.config.upload;
|
|
41
|
-
if (!uploadConfig) {
|
|
42
|
-
throw new APIError(`Collection "${collectionSlug}" does not support file uploads.`, 400);
|
|
43
|
-
}
|
|
44
|
-
const maxFileSize = req.payload.config.upload.limits?.fileSize;
|
|
45
|
-
let file;
|
|
46
|
-
if (input.source === 'base64') {
|
|
47
|
-
const data = decodeBase64({
|
|
48
|
-
maxFileSize,
|
|
49
|
-
value: input.data
|
|
50
|
-
});
|
|
51
|
-
file = {
|
|
52
|
-
name: sanitizeFilename(input.name),
|
|
53
|
-
data,
|
|
54
|
-
mimetype: input.mimeType,
|
|
55
|
-
size: data.length
|
|
56
|
-
};
|
|
57
|
-
} else {
|
|
58
|
-
if (uploadConfig.pasteURL === false) {
|
|
59
|
-
throw new APIError(`Uploading files from URLs is disabled for collection "${collectionSlug}".`, 400);
|
|
60
|
-
}
|
|
61
|
-
const url = new URL(input.url);
|
|
62
|
-
if (![
|
|
63
|
-
'http:',
|
|
64
|
-
'https:'
|
|
65
|
-
].includes(url.protocol)) {
|
|
66
|
-
throw new APIError('File URLs must use http or https.', 400);
|
|
67
|
-
}
|
|
68
|
-
if (typeof uploadConfig.pasteURL === 'object' && !isURLAllowed(input.url, uploadConfig.pasteURL.allowList)) {
|
|
69
|
-
throw new APIError('The provided file URL is not allowed.', 400);
|
|
70
|
-
}
|
|
71
|
-
file = await getExternalFile({
|
|
72
|
-
data: {
|
|
73
|
-
filename: sanitizeFilename(input.name || getURLFilename(url)),
|
|
74
|
-
url: input.url
|
|
75
|
-
},
|
|
76
|
-
req,
|
|
77
|
-
uploadConfig: {
|
|
78
|
-
...uploadConfig,
|
|
79
|
-
externalFileHeaderFilter: uploadConfig.externalFileHeaderFilter ?? (()=>({}))
|
|
80
|
-
}
|
|
81
|
-
});
|
|
82
|
-
file.mimetype = file.mimetype?.split(';')[0] || 'application/octet-stream';
|
|
83
|
-
file.size = file.data.length;
|
|
84
|
-
}
|
|
85
|
-
if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {
|
|
86
|
-
throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400);
|
|
87
|
-
}
|
|
88
|
-
return file;
|
|
89
|
-
}
|
|
90
|
-
function decodeBase64({ maxFileSize, value }) {
|
|
91
|
-
const normalized = value.replace(/\s/g, '');
|
|
92
|
-
if (!/^[a-z0-9+/]*={0,2}$/i.test(normalized) || normalized.length % 4 === 1) {
|
|
93
|
-
throw new APIError('File data must be valid base64.', 400);
|
|
94
|
-
}
|
|
95
|
-
if (maxFileSize !== undefined && Number.isFinite(maxFileSize)) {
|
|
96
|
-
const paddingLength = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0;
|
|
97
|
-
const decodedSize = Math.floor(normalized.length * 3 / 4) - paddingLength;
|
|
98
|
-
if (decodedSize > maxFileSize) {
|
|
99
|
-
throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400);
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
const data = Buffer.from(normalized, 'base64');
|
|
103
|
-
if (data.toString('base64').replace(/=+$/, '') !== normalized.replace(/=+$/, '')) {
|
|
104
|
-
throw new APIError('File data must be valid base64.', 400);
|
|
105
|
-
}
|
|
106
|
-
return data;
|
|
107
|
-
}
|
|
108
|
-
function getURLFilename(url) {
|
|
109
|
-
const pathSegment = url.pathname.split('/').pop() || 'upload';
|
|
110
|
-
try {
|
|
111
|
-
return decodeURIComponent(pathSegment);
|
|
112
|
-
} catch {
|
|
113
|
-
return pathSegment;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
//# sourceMappingURL=fileInput.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/collections/fileInput.ts"],"sourcesContent":["import type { CollectionSlug, File, FileData, PayloadRequest } from 'payload'\n\nimport { APIError } from 'payload'\nimport { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal'\nimport { sanitizeFilename } from 'payload/shared'\nimport { z } from 'zod'\n\nconst mimeTypeSchema = z\n .string()\n .regex(/^[!#$%&'*+.^`|~\\w-]+\\/[!#$%&'*+.^`|~\\w-]+$/, 'MIME type must use the type/subtype format')\n\nconst uploadFileSchema = z.object({\n filename: z.string(),\n mimeType: z.string(),\n size: z.number().int().nonnegative(),\n uploadReference: z.record(z.string(), z.unknown()),\n})\n\nexport const fileInputSchema = z\n .discriminatedUnion('source', [\n z.object({\n name: z.string().min(1).describe('The file name, including its extension'),\n data: z.string().describe('The base64-encoded file bytes, without a data URL prefix'),\n mimeType: mimeTypeSchema.describe('The file MIME type, for example image/png'),\n source: z.literal('base64'),\n }),\n z.object({\n name: z.string().min(1).describe('Optional file name override').optional(),\n source: z.literal('externalURL'),\n url: z.url().describe('The http or https URL to download'),\n }),\n z.object({\n file: uploadFileSchema.describe('The file value returned by getUploadInstructions'),\n source: z.literal('uploadReference'),\n }),\n ])\n .describe(\n 'A file for an upload collection. Use externalURL for an online file, base64 for local file bytes, or uploadReference after following getUploadInstructions. Usage of getUploadInstructions and uploadReference is recommended.',\n )\n\ntype FileInput = z.infer<typeof fileInputSchema>\n\nexport async function resolveFile({\n collectionSlug,\n input,\n req,\n}: {\n collectionSlug: CollectionSlug\n input?: FileInput\n req: PayloadRequest\n}): Promise<File | undefined> {\n if (!input) {\n return undefined\n }\n\n if (input.source === 'uploadReference') {\n return getFileFromUploadInstructions({ collectionSlug, file: input.file, req })\n }\n\n const uploadConfig = req.payload.collections[collectionSlug]?.config.upload\n\n if (!uploadConfig) {\n throw new APIError(`Collection \"${collectionSlug}\" 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(\n `Uploading files from URLs is disabled for collection \"${collectionSlug}\".`,\n 400,\n )\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","getExternalFile","getFileFromUploadInstructions","isURLAllowed","sanitizeFilename","z","mimeTypeSchema","string","regex","uploadFileSchema","object","filename","mimeType","size","number","int","nonnegative","uploadReference","record","unknown","fileInputSchema","discriminatedUnion","name","min","describe","data","source","literal","optional","url","file","resolveFile","collectionSlug","input","req","undefined","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,QAAQ,UAAS;AAClC,SAASC,eAAe,EAAEC,6BAA6B,EAAEC,YAAY,QAAQ,mBAAkB;AAC/F,SAASC,gBAAgB,QAAQ,iBAAgB;AACjD,SAASC,CAAC,QAAQ,MAAK;AAEvB,MAAMC,iBAAiBD,EACpBE,MAAM,GACNC,KAAK,CAAC,8CAA8C;AAEvD,MAAMC,mBAAmBJ,EAAEK,MAAM,CAAC;IAChCC,UAAUN,EAAEE,MAAM;IAClBK,UAAUP,EAAEE,MAAM;IAClBM,MAAMR,EAAES,MAAM,GAAGC,GAAG,GAAGC,WAAW;IAClCC,iBAAiBZ,EAAEa,MAAM,CAACb,EAAEE,MAAM,IAAIF,EAAEc,OAAO;AACjD;AAEA,OAAO,MAAMC,kBAAkBf,EAC5BgB,kBAAkB,CAAC,UAAU;IAC5BhB,EAAEK,MAAM,CAAC;QACPY,MAAMjB,EAAEE,MAAM,GAAGgB,GAAG,CAAC,GAAGC,QAAQ,CAAC;QACjCC,MAAMpB,EAAEE,MAAM,GAAGiB,QAAQ,CAAC;QAC1BZ,UAAUN,eAAekB,QAAQ,CAAC;QAClCE,QAAQrB,EAAEsB,OAAO,CAAC;IACpB;IACAtB,EAAEK,MAAM,CAAC;QACPY,MAAMjB,EAAEE,MAAM,GAAGgB,GAAG,CAAC,GAAGC,QAAQ,CAAC,+BAA+BI,QAAQ;QACxEF,QAAQrB,EAAEsB,OAAO,CAAC;QAClBE,KAAKxB,EAAEwB,GAAG,GAAGL,QAAQ,CAAC;IACxB;IACAnB,EAAEK,MAAM,CAAC;QACPoB,MAAMrB,iBAAiBe,QAAQ,CAAC;QAChCE,Q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ACT,YAAY;IAErC,IAAIjC,KAAK2C,QAAQ,CAAC,UAAUT,OAAO,CAAC,OAAO,QAAQD,WAAWC,OAAO,CAAC,OAAO,KAAK;QAChF,MAAM,IAAI3D,SAAS,mCAAmC;IACxD;IAEA,OAAOyB;AACT;AAEA,SAAS4B,eAAexB,GAAQ;IAC9B,MAAMwC,cAAcxC,IAAIyC,QAAQ,CAACf,KAAK,CAAC,KAAKgB,GAAG,MAAM;IAErD,IAAI;QACF,OAAOC,mBAAmBH;IAC5B,EAAE,OAAM;QACN,OAAOA;IACT;AACF"}
|
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import { fileInputSchema, resolveFile } from './fileInput.js';
|
|
3
|
-
describe('MCP file input', ()=>{
|
|
4
|
-
it('should reject malformed MIME types', ()=>{
|
|
5
|
-
const result = fileInputSchema.safeParse({
|
|
6
|
-
data: 'aGVsbG8=',
|
|
7
|
-
mimeType: 'text/plain\r\nx-test: value',
|
|
8
|
-
name: 'hello.txt',
|
|
9
|
-
source: 'base64'
|
|
10
|
-
});
|
|
11
|
-
expect(result.success).toBe(false);
|
|
12
|
-
});
|
|
13
|
-
it('should accept a prepared upload', ()=>{
|
|
14
|
-
const result = fileInputSchema.safeParse({
|
|
15
|
-
file: {
|
|
16
|
-
filename: 'image.png',
|
|
17
|
-
mimeType: 'image/png',
|
|
18
|
-
size: 123,
|
|
19
|
-
uploadReference: {
|
|
20
|
-
uploadId: 'upload-id'
|
|
21
|
-
}
|
|
22
|
-
},
|
|
23
|
-
source: 'uploadReference'
|
|
24
|
-
});
|
|
25
|
-
expect(result.success).toBe(true);
|
|
26
|
-
});
|
|
27
|
-
it('should reject oversized base64 files', async ()=>{
|
|
28
|
-
const req = createRequest({
|
|
29
|
-
maxFileSize: 4
|
|
30
|
-
});
|
|
31
|
-
await expect(resolveFile({
|
|
32
|
-
collectionSlug: '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
|
-
collectionSlug: 'media',
|
|
53
|
-
input: {
|
|
54
|
-
source: 'externalURL',
|
|
55
|
-
url: 'https://example.com/image.png'
|
|
56
|
-
},
|
|
57
|
-
req
|
|
58
|
-
})).rejects.toThrow('The provided file URL is not allowed.');
|
|
59
|
-
});
|
|
60
|
-
});
|
|
61
|
-
function createRequest({ allowList, maxFileSize }) {
|
|
62
|
-
return {
|
|
63
|
-
payload: {
|
|
64
|
-
collections: {
|
|
65
|
-
media: {
|
|
66
|
-
config: {
|
|
67
|
-
upload: allowList ? {
|
|
68
|
-
pasteURL: {
|
|
69
|
-
allowList
|
|
70
|
-
}
|
|
71
|
-
} : {}
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
},
|
|
75
|
-
config: {
|
|
76
|
-
upload: {
|
|
77
|
-
limits: {
|
|
78
|
-
fileSize: maxFileSize
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
//# sourceMappingURL=fileInput.spec.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/collections/fileInput.spec.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { describe, expect, it } from 'vitest'\n\nimport { fileInputSchema, resolveFile } from './fileInput.js'\n\ndescribe('MCP file input', () => {\n it('should reject malformed MIME types', () => {\n const result = fileInputSchema.safeParse({\n data: 'aGVsbG8=',\n mimeType: 'text/plain\\r\\nx-test: value',\n name: 'hello.txt',\n source: 'base64',\n })\n\n expect(result.success).toBe(false)\n })\n\n it('should accept a prepared upload', () => {\n const result = fileInputSchema.safeParse({\n file: {\n filename: 'image.png',\n mimeType: 'image/png',\n size: 123,\n uploadReference: { uploadId: 'upload-id' },\n },\n source: 'uploadReference',\n })\n\n expect(result.success).toBe(true)\n })\n\n it('should reject oversized base64 files', async () => {\n const req = createRequest({ maxFileSize: 4 })\n\n await expect(\n resolveFile({\n collectionSlug: '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 collectionSlug: '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","collectionSlug","input","Buffer","from","toString","rejects","toThrow","allowList","hostname","protocol","url","payload","collections","media","config","upload","pasteURL","limits","fileSize"],"mappings":"AAEA,SAASA,QAAQ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CAAC;oBACrD;gBACF;YACF;YACAO,QAAQ;gBACNC,QAAQ;oBACNE,QAAQ;wBACNC,UAAUnB;oBACZ;gBACF;YACF;QACF;IACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"uploadInstructionsTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/uploadInstructionsTool.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,yBAAyB,4CAyDpC,CAAA"}
|
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import { getUploadInstructions as getPayloadUploadInstructions } from 'payload/internal';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import { defaultAccess } from '../../../defaultAccess.js';
|
|
4
|
-
import { defineCollectionTool } from '../../../defineTool.js';
|
|
5
|
-
export const getUploadInstructionsTool = defineCollectionTool({
|
|
6
|
-
access: (args)=>defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create || args.permissions?.collections?.[args.collectionSlug]?.update),
|
|
7
|
-
annotations: {
|
|
8
|
-
destructiveHint: false,
|
|
9
|
-
idempotentHint: false,
|
|
10
|
-
openWorldHint: true,
|
|
11
|
-
readOnlyHint: false,
|
|
12
|
-
title: 'Get Upload Instructions'
|
|
13
|
-
},
|
|
14
|
-
description: 'Prepare a file upload before createDocument or updateDocument. Pass file metadata only, without base64 or file contents.',
|
|
15
|
-
input: z.object({
|
|
16
|
-
docPrefix: z.string().describe('Optional document folder or prefix').optional(),
|
|
17
|
-
filename: z.string().describe('The original file name'),
|
|
18
|
-
filesize: z.number().int().nonnegative().describe('The file size in bytes'),
|
|
19
|
-
mimeType: z.string().describe('The file MIME type')
|
|
20
|
-
})
|
|
21
|
-
}).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
|
|
22
|
-
try {
|
|
23
|
-
const instructions = await getPayloadUploadInstructions({
|
|
24
|
-
...input,
|
|
25
|
-
collectionSlug,
|
|
26
|
-
overrideAccess: authorizedMCP.overrideAccess,
|
|
27
|
-
req
|
|
28
|
-
});
|
|
29
|
-
const nextStep = instructions.type === 'http' ? 'Send the exact file bytes using request, then pass { source: "uploadReference", file } to createDocument or updateDocument.' : `Call the local MCP tool named "${instructions.name}" with the file and data, then pass { source: "uploadReference", file } to createDocument or updateDocument.`;
|
|
30
|
-
return {
|
|
31
|
-
content: [
|
|
32
|
-
{
|
|
33
|
-
type: 'text',
|
|
34
|
-
text: `Upload instructions for collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(instructions)}\n\`\`\`\n${nextStep}`
|
|
35
|
-
}
|
|
36
|
-
],
|
|
37
|
-
structuredContent: {
|
|
38
|
-
instructions
|
|
39
|
-
}
|
|
40
|
-
};
|
|
41
|
-
} catch (error) {
|
|
42
|
-
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
43
|
-
return {
|
|
44
|
-
content: [
|
|
45
|
-
{
|
|
46
|
-
type: 'text',
|
|
47
|
-
text: `Error getting upload instructions for collection "${collectionSlug}": ${message}`
|
|
48
|
-
}
|
|
49
|
-
],
|
|
50
|
-
isError: true
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
});
|
|
54
|
-
|
|
55
|
-
//# sourceMappingURL=uploadInstructionsTool.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/collections/uploadInstructionsTool.ts"],"sourcesContent":["import { getUploadInstructions as getPayloadUploadInstructions } from 'payload/internal'\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\n\nexport const getUploadInstructionsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) &&\n Boolean(\n args.permissions?.collections?.[args.collectionSlug]?.create ||\n args.permissions?.collections?.[args.collectionSlug]?.update,\n ),\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n readOnlyHint: false,\n title: 'Get Upload Instructions',\n },\n description:\n 'Prepare a file upload before createDocument or updateDocument. Pass file metadata only, without base64 or file contents.',\n input: z.object({\n docPrefix: z.string().describe('Optional document folder or prefix').optional(),\n filename: z.string().describe('The original file name'),\n filesize: z.number().int().nonnegative().describe('The file size in bytes'),\n mimeType: z.string().describe('The file MIME type'),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n try {\n const instructions = await getPayloadUploadInstructions({\n ...input,\n collectionSlug,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n })\n\n const nextStep =\n instructions.type === 'http'\n ? 'Send the exact file bytes using request, then pass { source: \"uploadReference\", file } to createDocument or updateDocument.'\n : `Call the local MCP tool named \"${instructions.name}\" with the file and data, then pass { source: \"uploadReference\", file } to createDocument or updateDocument.`\n\n return {\n content: [\n {\n type: 'text',\n text: `Upload instructions for collection \"${collectionSlug}\":\\n\\`\\`\\`json\\n${JSON.stringify(instructions)}\\n\\`\\`\\`\\n${nextStep}`,\n },\n ],\n structuredContent: { instructions },\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n return {\n content: [\n {\n type: 'text',\n text: `Error getting upload instructions for collection \"${collectionSlug}\": ${message}`,\n },\n ],\n isError: true,\n }\n }\n})\n"],"names":["getUploadInstructions","getPayloadUploadInstructions","z","defaultAccess","defineCollectionTool","getUploadInstructionsTool","access","args","Boolean","permissions","collections","collectionSlug","create","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","docPrefix","string","describe","optional","filename","filesize","number","int","nonnegative","mimeType","handler","authorizedMCP","req","instructions","overrideAccess","nextStep","type","name","content","text","JSON","stringify","structuredContent","error","message","Error","isError"],"mappings":"AAAA,SAASA,yBAAyBC,4BAA4B,QAAQ,mBAAkB;AACxF,SAASC,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAE7D,OAAO,MAAMC,4BAA4BD,qBAAqB;IAC5DE,QAAQ,CAACC,OACPJ,cAAcI,SAC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SAAS;QACX;IACF;AACF,GAAE"}
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
import type { PayloadRequest } from 'payload'
|
|
2
|
-
|
|
3
|
-
import { describe, expect, it } from 'vitest'
|
|
4
|
-
|
|
5
|
-
import { fileInputSchema, resolveFile } from './fileInput.js'
|
|
6
|
-
|
|
7
|
-
describe('MCP file input', () => {
|
|
8
|
-
it('should reject malformed MIME types', () => {
|
|
9
|
-
const result = fileInputSchema.safeParse({
|
|
10
|
-
data: 'aGVsbG8=',
|
|
11
|
-
mimeType: 'text/plain\r\nx-test: value',
|
|
12
|
-
name: 'hello.txt',
|
|
13
|
-
source: 'base64',
|
|
14
|
-
})
|
|
15
|
-
|
|
16
|
-
expect(result.success).toBe(false)
|
|
17
|
-
})
|
|
18
|
-
|
|
19
|
-
it('should accept a prepared upload', () => {
|
|
20
|
-
const result = fileInputSchema.safeParse({
|
|
21
|
-
file: {
|
|
22
|
-
filename: 'image.png',
|
|
23
|
-
mimeType: 'image/png',
|
|
24
|
-
size: 123,
|
|
25
|
-
uploadReference: { uploadId: 'upload-id' },
|
|
26
|
-
},
|
|
27
|
-
source: 'uploadReference',
|
|
28
|
-
})
|
|
29
|
-
|
|
30
|
-
expect(result.success).toBe(true)
|
|
31
|
-
})
|
|
32
|
-
|
|
33
|
-
it('should reject oversized base64 files', async () => {
|
|
34
|
-
const req = createRequest({ maxFileSize: 4 })
|
|
35
|
-
|
|
36
|
-
await expect(
|
|
37
|
-
resolveFile({
|
|
38
|
-
collectionSlug: 'media',
|
|
39
|
-
input: {
|
|
40
|
-
data: Buffer.from('hello').toString('base64'),
|
|
41
|
-
mimeType: 'text/plain',
|
|
42
|
-
name: 'hello.txt',
|
|
43
|
-
source: 'base64',
|
|
44
|
-
},
|
|
45
|
-
req,
|
|
46
|
-
}),
|
|
47
|
-
).rejects.toThrow('File exceeds the 4 byte upload limit.')
|
|
48
|
-
})
|
|
49
|
-
|
|
50
|
-
it('should reject URLs outside the collection allowlist', async () => {
|
|
51
|
-
const req = createRequest({
|
|
52
|
-
allowList: [{ hostname: 'assets.example.com', protocol: 'https' }],
|
|
53
|
-
})
|
|
54
|
-
|
|
55
|
-
await expect(
|
|
56
|
-
resolveFile({
|
|
57
|
-
collectionSlug: 'media',
|
|
58
|
-
input: {
|
|
59
|
-
source: 'externalURL',
|
|
60
|
-
url: 'https://example.com/image.png',
|
|
61
|
-
},
|
|
62
|
-
req,
|
|
63
|
-
}),
|
|
64
|
-
).rejects.toThrow('The provided file URL is not allowed.')
|
|
65
|
-
})
|
|
66
|
-
})
|
|
67
|
-
|
|
68
|
-
function createRequest({
|
|
69
|
-
allowList,
|
|
70
|
-
maxFileSize,
|
|
71
|
-
}: {
|
|
72
|
-
allowList?: Array<{ hostname: string; protocol: 'http' | 'https' }>
|
|
73
|
-
maxFileSize?: number
|
|
74
|
-
}): PayloadRequest {
|
|
75
|
-
return {
|
|
76
|
-
payload: {
|
|
77
|
-
collections: {
|
|
78
|
-
media: {
|
|
79
|
-
config: {
|
|
80
|
-
upload: allowList ? { pasteURL: { allowList } } : {},
|
|
81
|
-
},
|
|
82
|
-
},
|
|
83
|
-
},
|
|
84
|
-
config: {
|
|
85
|
-
upload: {
|
|
86
|
-
limits: {
|
|
87
|
-
fileSize: maxFileSize,
|
|
88
|
-
},
|
|
89
|
-
},
|
|
90
|
-
},
|
|
91
|
-
},
|
|
92
|
-
} as unknown as PayloadRequest
|
|
93
|
-
}
|
|
@@ -1,154 +0,0 @@
|
|
|
1
|
-
import type { CollectionSlug, File, FileData, PayloadRequest } from 'payload'
|
|
2
|
-
|
|
3
|
-
import { APIError } from 'payload'
|
|
4
|
-
import { getExternalFile, getFileFromUploadInstructions, isURLAllowed } from 'payload/internal'
|
|
5
|
-
import { sanitizeFilename } from 'payload/shared'
|
|
6
|
-
import { z } from 'zod'
|
|
7
|
-
|
|
8
|
-
const mimeTypeSchema = z
|
|
9
|
-
.string()
|
|
10
|
-
.regex(/^[!#$%&'*+.^`|~\w-]+\/[!#$%&'*+.^`|~\w-]+$/, 'MIME type must use the type/subtype format')
|
|
11
|
-
|
|
12
|
-
const uploadFileSchema = z.object({
|
|
13
|
-
filename: z.string(),
|
|
14
|
-
mimeType: z.string(),
|
|
15
|
-
size: z.number().int().nonnegative(),
|
|
16
|
-
uploadReference: z.record(z.string(), z.unknown()),
|
|
17
|
-
})
|
|
18
|
-
|
|
19
|
-
export const fileInputSchema = z
|
|
20
|
-
.discriminatedUnion('source', [
|
|
21
|
-
z.object({
|
|
22
|
-
name: z.string().min(1).describe('The file name, including its extension'),
|
|
23
|
-
data: z.string().describe('The base64-encoded file bytes, without a data URL prefix'),
|
|
24
|
-
mimeType: mimeTypeSchema.describe('The file MIME type, for example image/png'),
|
|
25
|
-
source: z.literal('base64'),
|
|
26
|
-
}),
|
|
27
|
-
z.object({
|
|
28
|
-
name: z.string().min(1).describe('Optional file name override').optional(),
|
|
29
|
-
source: z.literal('externalURL'),
|
|
30
|
-
url: z.url().describe('The http or https URL to download'),
|
|
31
|
-
}),
|
|
32
|
-
z.object({
|
|
33
|
-
file: uploadFileSchema.describe('The file value returned by getUploadInstructions'),
|
|
34
|
-
source: z.literal('uploadReference'),
|
|
35
|
-
}),
|
|
36
|
-
])
|
|
37
|
-
.describe(
|
|
38
|
-
'A file for an upload collection. Use externalURL for an online file, base64 for local file bytes, or uploadReference after following getUploadInstructions. Usage of getUploadInstructions and uploadReference is recommended.',
|
|
39
|
-
)
|
|
40
|
-
|
|
41
|
-
type FileInput = z.infer<typeof fileInputSchema>
|
|
42
|
-
|
|
43
|
-
export async function resolveFile({
|
|
44
|
-
collectionSlug,
|
|
45
|
-
input,
|
|
46
|
-
req,
|
|
47
|
-
}: {
|
|
48
|
-
collectionSlug: CollectionSlug
|
|
49
|
-
input?: FileInput
|
|
50
|
-
req: PayloadRequest
|
|
51
|
-
}): Promise<File | undefined> {
|
|
52
|
-
if (!input) {
|
|
53
|
-
return undefined
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
if (input.source === 'uploadReference') {
|
|
57
|
-
return getFileFromUploadInstructions({ collectionSlug, file: input.file, req })
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const uploadConfig = req.payload.collections[collectionSlug]?.config.upload
|
|
61
|
-
|
|
62
|
-
if (!uploadConfig) {
|
|
63
|
-
throw new APIError(`Collection "${collectionSlug}" does not support file uploads.`, 400)
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
const maxFileSize = req.payload.config.upload.limits?.fileSize
|
|
67
|
-
let file: File
|
|
68
|
-
|
|
69
|
-
if (input.source === 'base64') {
|
|
70
|
-
const data = decodeBase64({ maxFileSize, value: input.data })
|
|
71
|
-
|
|
72
|
-
file = {
|
|
73
|
-
name: sanitizeFilename(input.name),
|
|
74
|
-
data,
|
|
75
|
-
mimetype: input.mimeType,
|
|
76
|
-
size: data.length,
|
|
77
|
-
}
|
|
78
|
-
} else {
|
|
79
|
-
if (uploadConfig.pasteURL === false) {
|
|
80
|
-
throw new APIError(
|
|
81
|
-
`Uploading files from URLs is disabled for collection "${collectionSlug}".`,
|
|
82
|
-
400,
|
|
83
|
-
)
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
const url = new URL(input.url)
|
|
87
|
-
|
|
88
|
-
if (!['http:', 'https:'].includes(url.protocol)) {
|
|
89
|
-
throw new APIError('File URLs must use http or https.', 400)
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
if (
|
|
93
|
-
typeof uploadConfig.pasteURL === 'object' &&
|
|
94
|
-
!isURLAllowed(input.url, uploadConfig.pasteURL.allowList)
|
|
95
|
-
) {
|
|
96
|
-
throw new APIError('The provided file URL is not allowed.', 400)
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
file = await getExternalFile({
|
|
100
|
-
data: {
|
|
101
|
-
filename: sanitizeFilename(input.name || getURLFilename(url)),
|
|
102
|
-
url: input.url,
|
|
103
|
-
} as FileData,
|
|
104
|
-
req,
|
|
105
|
-
uploadConfig: {
|
|
106
|
-
...uploadConfig,
|
|
107
|
-
externalFileHeaderFilter: uploadConfig.externalFileHeaderFilter ?? (() => ({})),
|
|
108
|
-
},
|
|
109
|
-
})
|
|
110
|
-
file.mimetype = file.mimetype?.split(';')[0] || 'application/octet-stream'
|
|
111
|
-
file.size = file.data.length
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
if (maxFileSize !== undefined && Number.isFinite(maxFileSize) && file.size > maxFileSize) {
|
|
115
|
-
throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
return file
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
function decodeBase64({ maxFileSize, value }: { maxFileSize?: number; value: string }): Buffer {
|
|
122
|
-
const normalized = value.replace(/\s/g, '')
|
|
123
|
-
|
|
124
|
-
if (!/^[a-z0-9+/]*={0,2}$/i.test(normalized) || normalized.length % 4 === 1) {
|
|
125
|
-
throw new APIError('File data must be valid base64.', 400)
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
if (maxFileSize !== undefined && Number.isFinite(maxFileSize)) {
|
|
129
|
-
const paddingLength = normalized.endsWith('==') ? 2 : normalized.endsWith('=') ? 1 : 0
|
|
130
|
-
const decodedSize = Math.floor((normalized.length * 3) / 4) - paddingLength
|
|
131
|
-
|
|
132
|
-
if (decodedSize > maxFileSize) {
|
|
133
|
-
throw new APIError(`File exceeds the ${maxFileSize} byte upload limit.`, 400)
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
const data = Buffer.from(normalized, 'base64')
|
|
138
|
-
|
|
139
|
-
if (data.toString('base64').replace(/=+$/, '') !== normalized.replace(/=+$/, '')) {
|
|
140
|
-
throw new APIError('File data must be valid base64.', 400)
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
return data
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
function getURLFilename(url: URL): string {
|
|
147
|
-
const pathSegment = url.pathname.split('/').pop() || 'upload'
|
|
148
|
-
|
|
149
|
-
try {
|
|
150
|
-
return decodeURIComponent(pathSegment)
|
|
151
|
-
} catch {
|
|
152
|
-
return pathSegment
|
|
153
|
-
}
|
|
154
|
-
}
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { getUploadInstructions as getPayloadUploadInstructions } from 'payload/internal'
|
|
2
|
-
import { z } from 'zod'
|
|
3
|
-
|
|
4
|
-
import { defaultAccess } from '../../../defaultAccess.js'
|
|
5
|
-
import { defineCollectionTool } from '../../../defineTool.js'
|
|
6
|
-
|
|
7
|
-
export const getUploadInstructionsTool = defineCollectionTool({
|
|
8
|
-
access: (args) =>
|
|
9
|
-
defaultAccess(args) &&
|
|
10
|
-
Boolean(
|
|
11
|
-
args.permissions?.collections?.[args.collectionSlug]?.create ||
|
|
12
|
-
args.permissions?.collections?.[args.collectionSlug]?.update,
|
|
13
|
-
),
|
|
14
|
-
annotations: {
|
|
15
|
-
destructiveHint: false,
|
|
16
|
-
idempotentHint: false,
|
|
17
|
-
openWorldHint: true,
|
|
18
|
-
readOnlyHint: false,
|
|
19
|
-
title: 'Get Upload Instructions',
|
|
20
|
-
},
|
|
21
|
-
description:
|
|
22
|
-
'Prepare a file upload before createDocument or updateDocument. Pass file metadata only, without base64 or file contents.',
|
|
23
|
-
input: z.object({
|
|
24
|
-
docPrefix: z.string().describe('Optional document folder or prefix').optional(),
|
|
25
|
-
filename: z.string().describe('The original file name'),
|
|
26
|
-
filesize: z.number().int().nonnegative().describe('The file size in bytes'),
|
|
27
|
-
mimeType: z.string().describe('The file MIME type'),
|
|
28
|
-
}),
|
|
29
|
-
}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {
|
|
30
|
-
try {
|
|
31
|
-
const instructions = await getPayloadUploadInstructions({
|
|
32
|
-
...input,
|
|
33
|
-
collectionSlug,
|
|
34
|
-
overrideAccess: authorizedMCP.overrideAccess,
|
|
35
|
-
req,
|
|
36
|
-
})
|
|
37
|
-
|
|
38
|
-
const nextStep =
|
|
39
|
-
instructions.type === 'http'
|
|
40
|
-
? 'Send the exact file bytes using request, then pass { source: "uploadReference", file } to createDocument or updateDocument.'
|
|
41
|
-
: `Call the local MCP tool named "${instructions.name}" with the file and data, then pass { source: "uploadReference", file } to createDocument or updateDocument.`
|
|
42
|
-
|
|
43
|
-
return {
|
|
44
|
-
content: [
|
|
45
|
-
{
|
|
46
|
-
type: 'text',
|
|
47
|
-
text: `Upload instructions for collection "${collectionSlug}":\n\`\`\`json\n${JSON.stringify(instructions)}\n\`\`\`\n${nextStep}`,
|
|
48
|
-
},
|
|
49
|
-
],
|
|
50
|
-
structuredContent: { instructions },
|
|
51
|
-
}
|
|
52
|
-
} catch (error) {
|
|
53
|
-
const message = error instanceof Error ? error.message : 'Unknown error'
|
|
54
|
-
return {
|
|
55
|
-
content: [
|
|
56
|
-
{
|
|
57
|
-
type: 'text',
|
|
58
|
-
text: `Error getting upload instructions for collection "${collectionSlug}": ${message}`,
|
|
59
|
-
},
|
|
60
|
-
],
|
|
61
|
-
isError: true,
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
})
|