@payloadcms/plugin-mcp 3.75.0-internal.e61a4d7 → 3.75.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mcp/tools/resource/create.d.ts.map +1 -1
- package/dist/mcp/tools/resource/create.js +3 -0
- package/dist/mcp/tools/resource/create.js.map +1 -1
- package/dist/mcp/tools/resource/update.d.ts.map +1 -1
- package/dist/mcp/tools/resource/update.js +3 -0
- package/dist/mcp/tools/resource/update.js.map +1 -1
- package/dist/utils/convertCollectionSchemaToZod.d.ts.map +1 -1
- package/dist/utils/convertCollectionSchemaToZod.js +3 -1
- package/dist/utils/convertCollectionSchemaToZod.js.map +1 -1
- package/dist/utils/transformPointDataToPayload.d.ts +7 -0
- package/dist/utils/transformPointDataToPayload.d.ts.map +1 -0
- package/dist/utils/transformPointDataToPayload.js +28 -0
- package/dist/utils/transformPointDataToPayload.js.map +1 -0
- package/dist/utils/transformPointFields.d.ts +3 -0
- package/dist/utils/transformPointFields.d.ts.map +1 -0
- package/dist/utils/transformPointFields.js +51 -0
- package/dist/utils/transformPointFields.js.map +1 -0
- package/package.json +3 -3
- package/src/mcp/tools/resource/create.ts +5 -0
- package/src/mcp/tools/resource/update.ts +5 -0
- package/src/utils/convertCollectionSchemaToZod.ts +4 -1
- package/src/utils/transformPointDataToPayload.ts +40 -0
- package/src/utils/transformPointFields.ts +55 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/resource/create.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAc,SAAS,EAAE,MAAM,SAAS,CAAA;AAIpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;
|
|
1
|
+
{"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/resource/create.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAc,SAAS,EAAE,MAAM,SAAS,CAAA;AAIpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAM9D,eAAO,MAAM,kBAAkB,WACrB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,UACzC,WAAW,SAsLpB,CAAA"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { toCamelCase } from '../../../utils/camelCase.js';
|
|
3
3
|
import { convertCollectionSchemaToZod } from '../../../utils/convertCollectionSchemaToZod.js';
|
|
4
|
+
import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
|
|
4
5
|
import { toolSchemas } from '../schemas.js';
|
|
5
6
|
export const createResourceTool = (server, req, user, verboseLogs, collectionSlug, collections, schema)=>{
|
|
6
7
|
const tool = async (data, depth = 0, draft, locale, fallbackLocale, select)=>{
|
|
@@ -13,6 +14,8 @@ export const createResourceTool = (server, req, user, verboseLogs, collectionSlu
|
|
|
13
14
|
let parsedData;
|
|
14
15
|
try {
|
|
15
16
|
parsedData = JSON.parse(data);
|
|
17
|
+
// Transform point fields from object format to tuple array
|
|
18
|
+
parsedData = transformPointDataToPayload(parsedData);
|
|
16
19
|
if (verboseLogs) {
|
|
17
20
|
payload.logger.info(`[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`);
|
|
18
21
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/tools/resource/create.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { JSONSchema4 } from 'json-schema'\nimport type { PayloadRequest, SelectType, TypedUser } from 'payload'\n\nimport { z } from 'zod'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { convertCollectionSchemaToZod } from '../../../utils/convertCollectionSchemaToZod.js'\nimport { toolSchemas } from '../schemas.js'\nexport const createResourceTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n collectionSlug: string,\n collections: PluginMCPServerConfig['collections'],\n schema: JSONSchema4,\n) => {\n const tool = async (\n data: string,\n depth: number = 0,\n draft: boolean,\n locale?: string,\n fallbackLocale?: string,\n select?: string,\n ): Promise<{\n content: Array<{\n text: string\n type: 'text'\n }>\n }> => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Creating resource in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Parse the data JSON\n let parsedData: Record<string, unknown>\n try {\n parsedData = JSON.parse(data)\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`,\n )\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid JSON data provided: ${data}`)\n return {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON data provided' }],\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid select clause JSON: ${select}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in select clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Create the resource\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: false,\n req,\n user,\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(selectClause && { select: selectClause }),\n })\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Successfully created resource in ${collectionSlug} with ID: ${result.id}`,\n )\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Resource created successfully in collection \"${collectionSlug}\"!\nCreated resource:\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, result, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n payload.logger.error(\n `[payload-mcp] Error creating resource in ${collectionSlug}: ${errorMessage}`,\n )\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error creating resource in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n if (collections?.[collectionSlug]?.enabled) {\n const convertedFields = convertCollectionSchemaToZod(schema)\n\n // Create a new schema that combines the converted fields with create-specific parameters\n const createResourceSchema = z.object({\n ...convertedFields.shape,\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .optional()\n .default(0)\n .describe('How many levels deep to populate relationships in response'),\n draft: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to create the document as a draft'),\n fallbackLocale: z\n .string()\n .optional()\n .describe('Optional: fallback locale code to use when requested locale is not available'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Optional: locale code to create the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n ),\n select: z\n .string()\n .optional()\n .describe(\n 'Optional: define exactly which fields you\\'d like to create (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n ),\n })\n\n server.tool(\n `create${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n `${collections?.[collectionSlug]?.description || toolSchemas.createResource.description.trim()}`,\n createResourceSchema.shape,\n async (params: Record<string, unknown>) => {\n const { depth, draft, fallbackLocale, locale, select, ...fieldData } = params\n const data = JSON.stringify(fieldData)\n return await tool(\n data,\n depth as number,\n draft as boolean,\n locale as string | undefined,\n fallbackLocale as string | undefined,\n select as string | undefined,\n )\n },\n )\n }\n}\n"],"names":["z","toCamelCase","convertCollectionSchemaToZod","toolSchemas","createResourceTool","server","req","user","verboseLogs","collectionSlug","collections","schema","tool","data","depth","draft","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","stringify","_parseError","error","content","type","text","selectClause","warn","response","overrideResponse","result","create","collection","overrideAccess","id","errorMessage","Error","message","enabled","convertedFields","createResourceSchema","object","shape","number","int","min","max","optional","default","describe","boolean","string","charAt","toUpperCase","slice","description","createResource","trim","params","fieldData"],"mappings":"AAIA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,4BAA4B,QAAQ,iDAAgD;AAC7F,SAASC,WAAW,QAAQ,gBAAe;AAC3C,OAAO,MAAMC,qBAAqB,CAChCC,QACAC,KACAC,MACAC,aACAC,gBACAC,aACAC;IAEA,MAAMC,OAAO,OACXC,MACAC,QAAgB,CAAC,EACjBC,OACAC,QACAC,gBACAC;QAOA,MAAMC,UAAUb,IAAIa,OAAO;QAE3B,IAAIX,aAAa;YACfW,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,+CAA+C,EAAEZ,iBAAiBO,SAAS,CAAC,cAAc,EAAEA,QAAQ,GAAG,IAAI;QAEhH;QAEA,IAAI;YACF,sBAAsB;YACtB,IAAIM;YACJ,IAAI;gBACFA,aAAaC,KAAKC,KAAK,CAACX;gBACxB,IAAIL,aAAa;oBACfW,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,8BAA8B,EAAEZ,eAAe,EAAE,EAAEc,KAAKE,SAAS,CAACH,aAAa;gBAEpF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,EAAEC,KAAK,EAAEE,cAAc,EAAED,MAAM,EAAEE,MAAM,EAAE,GAAG8C,WAAW,GAAGD;YACvE,MAAMlD,OAAOU,KAAKE,SAAS,CAACuC;YAC5B,OAAO,MAAMpD,KACXC,MACAC,OACAC,OACAC,QACAC,gBACAC;QAEJ;IAEJ;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/tools/resource/create.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { JSONSchema4 } from 'json-schema'\nimport type { PayloadRequest, SelectType, TypedUser } from 'payload'\n\nimport { z } from 'zod'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { convertCollectionSchemaToZod } from '../../../utils/convertCollectionSchemaToZod.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { toolSchemas } from '../schemas.js'\nexport const createResourceTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n collectionSlug: string,\n collections: PluginMCPServerConfig['collections'],\n schema: JSONSchema4,\n) => {\n const tool = async (\n data: string,\n depth: number = 0,\n draft: boolean,\n locale?: string,\n fallbackLocale?: string,\n select?: string,\n ): Promise<{\n content: Array<{\n text: string\n type: 'text'\n }>\n }> => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Creating resource in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Parse the data JSON\n let parsedData: Record<string, unknown>\n try {\n parsedData = JSON.parse(data)\n\n // Transform point fields from object format to tuple array\n parsedData = transformPointDataToPayload(parsedData)\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`,\n )\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid JSON data provided: ${data}`)\n return {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON data provided' }],\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid select clause JSON: ${select}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in select clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Create the resource\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: false,\n req,\n user,\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(selectClause && { select: selectClause }),\n })\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Successfully created resource in ${collectionSlug} with ID: ${result.id}`,\n )\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Resource created successfully in collection \"${collectionSlug}\"!\nCreated resource:\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, result, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n payload.logger.error(\n `[payload-mcp] Error creating resource in ${collectionSlug}: ${errorMessage}`,\n )\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error creating resource in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n if (collections?.[collectionSlug]?.enabled) {\n const convertedFields = convertCollectionSchemaToZod(schema)\n\n // Create a new schema that combines the converted fields with create-specific parameters\n const createResourceSchema = z.object({\n ...convertedFields.shape,\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .optional()\n .default(0)\n .describe('How many levels deep to populate relationships in response'),\n draft: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to create the document as a draft'),\n fallbackLocale: z\n .string()\n .optional()\n .describe('Optional: fallback locale code to use when requested locale is not available'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Optional: locale code to create the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n ),\n select: z\n .string()\n .optional()\n .describe(\n 'Optional: define exactly which fields you\\'d like to create (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n ),\n })\n\n server.tool(\n `create${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n `${collections?.[collectionSlug]?.description || toolSchemas.createResource.description.trim()}`,\n createResourceSchema.shape,\n async (params: Record<string, unknown>) => {\n const { depth, draft, fallbackLocale, locale, select, ...fieldData } = params\n const data = JSON.stringify(fieldData)\n return await tool(\n data,\n depth as number,\n draft as boolean,\n locale as string | undefined,\n fallbackLocale as string | undefined,\n select as string | undefined,\n )\n },\n )\n }\n}\n"],"names":["z","toCamelCase","convertCollectionSchemaToZod","transformPointDataToPayload","toolSchemas","createResourceTool","server","req","user","verboseLogs","collectionSlug","collections","schema","tool","data","depth","draft","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","stringify","_parseError","error","content","type","text","selectClause","warn","response","overrideResponse","result","create","collection","overrideAccess","id","errorMessage","Error","message","enabled","convertedFields","createResourceSchema","object","shape","number","int","min","max","optional","default","describe","boolean","string","charAt","toUpperCase","slice","description","createResource","trim","params","fieldData"],"mappings":"AAIA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,4BAA4B,QAAQ,iDAAgD;AAC7F,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,WAAW,QAAQ,gBAAe;AAC3C,OAAO,MAAMC,qBAAqB,CAChCC,QACAC,KACAC,MACAC,aACAC,gBACAC,aACAC;IAEA,MAAMC,OAAO,OACXC,MACAC,QA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YACZrC,gBAAgBlB,EACbyD,MAAM,GACNJ,QAAQ,GACRE,QAAQ,CAAC;YACZtC,QAAQjB,EACLyD,MAAM,GACNJ,QAAQ,GACRE,QAAQ,CACP;YAEJpC,QAAQnB,EACLyD,MAAM,GACNJ,QAAQ,GACRE,QAAQ,CACP;QAEN;QAEAjD,OAAOO,IAAI,CACT,CAAC,MAAM,EAAEH,eAAegD,MAAM,CAAC,GAAGC,WAAW,KAAK1D,YAAYS,gBAAgBkD,KAAK,CAAC,IAAI,EACxF,GAAGjD,aAAa,CAACD,eAAe,EAAEmD,eAAezD,YAAY0D,cAAc,CAACD,WAAW,CAACE,IAAI,IAAI,EAChGjB,qBAAqBE,KAAK,EAC1B,OAAOgB;YACL,MAAM,EAAEjD,KAAK,EAAEC,KAAK,EAAEE,cAAc,EAAED,MAAM,EAAEE,MAAM,EAAE,GAAG8C,WAAW,GAAGD;YACvE,MAAMlD,OAAOU,KAAKE,SAAS,CAACuC;YAC5B,OAAO,MAAMpD,KACXC,MACAC,OACAC,OACAC,QACAC,gBACAC;QAEJ;IAEJ;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/resource/update.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAc,SAAS,EAAE,MAAM,SAAS,CAAA;AAIpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;
|
|
1
|
+
{"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/resource/update.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAc,SAAS,EAAE,MAAM,SAAS,CAAA;AAIpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAM9D,eAAO,MAAM,kBAAkB,WACrB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,UACzC,WAAW,SAkWpB,CAAA"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { toCamelCase } from '../../../utils/camelCase.js';
|
|
3
3
|
import { convertCollectionSchemaToZod } from '../../../utils/convertCollectionSchemaToZod.js';
|
|
4
|
+
import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
|
|
4
5
|
import { toolSchemas } from '../schemas.js';
|
|
5
6
|
export const updateResourceTool = (server, req, user, verboseLogs, collectionSlug, collections, schema)=>{
|
|
6
7
|
const tool = async (data, id, where, draft = false, depth = 0, overrideLock = true, filePath, overwriteExistingFiles = false, locale, fallbackLocale, select)=>{
|
|
@@ -13,6 +14,8 @@ export const updateResourceTool = (server, req, user, verboseLogs, collectionSlu
|
|
|
13
14
|
let parsedData;
|
|
14
15
|
try {
|
|
15
16
|
parsedData = JSON.parse(data);
|
|
17
|
+
// Transform point fields from object format to tuple array
|
|
18
|
+
parsedData = transformPointDataToPayload(parsedData);
|
|
16
19
|
if (verboseLogs) {
|
|
17
20
|
payload.logger.info(`[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`);
|
|
18
21
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/tools/resource/update.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { JSONSchema4 } from 'json-schema'\nimport type { PayloadRequest, SelectType, TypedUser } from 'payload'\n\nimport { z } from 'zod'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { convertCollectionSchemaToZod } from '../../../utils/convertCollectionSchemaToZod.js'\nimport { toolSchemas } from '../schemas.js'\nexport const updateResourceTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n collectionSlug: string,\n collections: PluginMCPServerConfig['collections'],\n schema: JSONSchema4,\n) => {\n const tool = async (\n data: string,\n id?: number | string,\n where?: string,\n draft: boolean = false,\n depth: number = 0,\n overrideLock: boolean = true,\n filePath?: string,\n overwriteExistingFiles: boolean = false,\n locale?: string,\n fallbackLocale?: string,\n select?: string,\n ): Promise<{\n content: Array<{\n text: string\n type: 'text'\n }>\n }> => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Updating resource in collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Parse the data JSON\n let parsedData: Record<string, unknown>\n try {\n parsedData = JSON.parse(data)\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`,\n )\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid JSON data provided: ${data}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON data provided' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n\n // Validate that either id or where is provided\n if (!id && !where) {\n payload.logger.error('[payload-mcp] Either id or where clause must be provided')\n const response = {\n content: [\n { type: 'text' as const, text: 'Error: Either id or where clause must be provided' },\n ],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n\n // Parse where clause if provided\n let whereClause = {}\n if (where) {\n try {\n whereClause = JSON.parse(where)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Using where clause: ${where}`)\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid where clause JSON: ${where}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in where clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid select clause JSON: ${select}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in select clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Update by ID or where clause\n if (id) {\n // Single document update\n const updateOptions = {\n id,\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: false,\n overrideLock,\n req,\n user,\n ...(filePath && { filePath }),\n ...(overwriteExistingFiles && { overwriteExistingFiles }),\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(selectClause && { select: selectClause }),\n }\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Updating single document with ID: ${id}`)\n }\n const result = await payload.update({\n ...updateOptions,\n data: parsedData,\n } as any)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully updated document with ID: ${id}`)\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Document updated successfully in collection \"${collectionSlug}\"!\nUpdated document:\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, result, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } else {\n // Multiple documents update\n const updateOptions = {\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: false,\n overrideLock,\n req,\n user,\n where: whereClause,\n ...(filePath && { filePath }),\n ...(overwriteExistingFiles && { overwriteExistingFiles }),\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(selectClause && { select: selectClause }),\n }\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Updating multiple documents with where clause`)\n }\n const result = await payload.update({\n ...updateOptions,\n data: parsedData,\n } as any)\n\n const bulkResult = result as { docs?: unknown[]; errors?: unknown[] }\n const docs = bulkResult.docs || []\n const errors = bulkResult.errors || []\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Successfully updated ${docs.length} documents, ${errors.length} errors`,\n )\n }\n\n let responseText = `Multiple documents updated in collection \"${collectionSlug}\"!\nUpdated: ${docs.length} documents\nErrors: ${errors.length}\n---`\n\n if (docs.length > 0) {\n responseText += `\\n\\nUpdated documents:\n\\`\\`\\`json\n${JSON.stringify(docs, null, 2)}\n\\`\\`\\``\n }\n\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\n\\`\\`\\`json\n${JSON.stringify(errors, null, 2)}\n\\`\\`\\``\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: responseText,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(\n response,\n { docs, errors },\n req,\n ) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n payload.logger.error(\n `[payload-mcp] Error updating resource in ${collectionSlug}: ${errorMessage}`,\n )\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error updating resource in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n if (collections?.[collectionSlug]?.enabled) {\n const convertedFields = convertCollectionSchemaToZod(schema)\n\n // Create a new schema that combines the converted fields with update-specific parameters\n // Use .partial() to make all fields optional for partial updates\n const updateResourceSchema = z.object({\n ...convertedFields.partial().shape,\n id: z.union([z.string(), z.number()]).optional().describe('The ID of the document to update'),\n depth: z\n .number()\n .optional()\n .default(0)\n .describe('How many levels deep to populate relationships'),\n draft: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to update the document as a draft'),\n fallbackLocale: z\n .string()\n .optional()\n .describe('Optional: fallback locale code to use when requested locale is not available'),\n filePath: z.string().optional().describe('File path for file uploads'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Optional: locale code to update the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n ),\n overrideLock: z\n .boolean()\n .optional()\n .default(true)\n .describe('Whether to override document locks'),\n overwriteExistingFiles: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to overwrite existing files'),\n select: z\n .string()\n .optional()\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n ),\n where: z\n .string()\n .optional()\n .describe('JSON string for where clause to update multiple documents'),\n })\n\n server.tool(\n `update${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n `${collections?.[collectionSlug]?.description || toolSchemas.updateResource.description.trim()}`,\n updateResourceSchema.shape,\n async (params: Record<string, unknown>) => {\n const {\n id,\n depth,\n draft,\n fallbackLocale,\n filePath,\n locale,\n overrideLock,\n overwriteExistingFiles,\n select,\n where,\n ...fieldData\n } = params\n // Convert field data back to JSON string format expected by the tool\n const data = JSON.stringify(fieldData)\n return await tool(\n data,\n id as number | string | undefined,\n where as string | undefined,\n draft as boolean,\n depth as number,\n overrideLock as boolean,\n filePath as string | undefined,\n overwriteExistingFiles as boolean,\n locale as string | undefined,\n fallbackLocale as string | undefined,\n select as string | undefined,\n )\n },\n )\n }\n}\n"],"names":["z","toCamelCase","convertCollectionSchemaToZod","toolSchemas","updateResourceTool","server","req","user","verboseLogs","collectionSlug","collections","schema","tool","data","id","where","draft","depth","overrideLock","filePath","overwriteExistingFiles","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","stringify","_parseError","error","response","content","type","text","overrideResponse","whereClause","selectClause","warn","updateOptions","collection","overrideAccess","result","update","bulkResult","docs","errors","length","responseText","errorMessage","Error","message","enabled","convertedFields","updateResourceSchema","object","partial","shape","union","string","number","optional","describe","default","boolean","charAt","toUpperCase","slice","description","updateResource","trim","params","fieldData"],"mappings":"AAIA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,4BAA4B,QAAQ,iDAAgD;AAC7F,SAASC,WAAW,QAAQ,gBAAe;AAC3C,OAAO,MAAMC,qBAAqB,CAChCC,QACAC,KACAC,MACAC,aACAC,gBACAC,aACAC;IAEA,MAAMC,OAAO,OACXC,MACAC,IACAC,OACAC,QAAiB,KAAK,EACtBC,QAAgB,CAAC,EACjBC,eAAwB,IAAI,EAC5BC,UACAC,yBAAkC,KAAK,EACvCC,QACAC,gBACAC;QAOA,MAAMC,UAAUlB,IAAIkB,OAAO;QAE3B,IAAIhB,aAAa;YACfgB,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,+CAA+C,EAAEjB,iBAAiBK,KAAK,CAAC,UAAU,EAAEA,IAAI,GAAG,qBAAqB,SAAS,EAAEE,QAAQK,SAAS,CAAC,UAAU,EAAEA,QAAQ,GAAG,IAAI;QAE7K;QAEA,IAAI;YACF,sBAAsB;YACtB,IAAIM;YACJ,IAAI;gBACFA,aAAaC,KAAKC,KAAK,CAAChB;gBACxB,IAAIL,aAAa;oBACfgB,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,8BAA8B,EAAEjB,eAAe,EAAE,EAAEmB,KAAKE,SAAS,CAACH,aAAa;gBAEpF;YACF,EAAE,OAAOI,aAAa;gBACpBP,QAAQC,MAAM,CAACO,KAAK,CAAC,CAAC,0CAA0C,EAAEnB,MAAM;gBACxE,MAAMoB,WAAW;oBACfC,SAAS;wBAAC;4BAAEC,MAAM;4BAAiBC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QAAQ,GACRC,QAAQ,CACP;YAEJjD,OAAOf,EACJ6D,MAAM,GACNE,QAAQ,GACRC,QAAQ,CAAC;QACd;QAEA3D,OAAOO,IAAI,CACT,CAAC,MAAM,EAAEH,eAAe0D,MAAM,CAAC,GAAGC,WAAW,KAAKnE,YAAYQ,gBAAgB4D,KAAK,CAAC,IAAI,EACxF,GAAG3D,aAAa,CAACD,eAAe,EAAE6D,eAAenE,YAAYoE,cAAc,CAACD,WAAW,CAACE,IAAI,IAAI,EAChGhB,qBAAqBG,KAAK,EAC1B,OAAOc;YACL,MAAM,EACJ3D,EAAE,EACFG,KAAK,EACLD,KAAK,EACLM,cAAc,EACdH,QAAQ,EACRE,MAAM,EACNH,YAAY,EACZE,sBAAsB,EACtBG,MAAM,EACNR,KAAK,EACL,GAAG2D,WACJ,GAAGD;YACJ,qEAAqE;YACrE,MAAM5D,OAAOe,KAAKE,SAAS,CAAC4C;YAC5B,OAAO,MAAM9D,KACXC,MACAC,IACAC,OACAC,OACAC,OACAC,cACAC,UACAC,wBACAC,QACAC,gBACAC;QAEJ;IAEJ;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/tools/resource/update.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { JSONSchema4 } from 'json-schema'\nimport type { PayloadRequest, SelectType, TypedUser } from 'payload'\n\nimport { z } from 'zod'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { convertCollectionSchemaToZod } from '../../../utils/convertCollectionSchemaToZod.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { toolSchemas } from '../schemas.js'\nexport const updateResourceTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n collectionSlug: string,\n collections: PluginMCPServerConfig['collections'],\n schema: JSONSchema4,\n) => {\n const tool = async (\n data: string,\n id?: number | string,\n where?: string,\n draft: boolean = false,\n depth: number = 0,\n overrideLock: boolean = true,\n filePath?: string,\n overwriteExistingFiles: boolean = false,\n locale?: string,\n fallbackLocale?: string,\n select?: string,\n ): Promise<{\n content: Array<{\n text: string\n type: 'text'\n }>\n }> => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Updating resource in collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Parse the data JSON\n let parsedData: Record<string, unknown>\n try {\n parsedData = JSON.parse(data)\n\n // Transform point fields from object format to tuple array\n parsedData = transformPointDataToPayload(parsedData)\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`,\n )\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid JSON data provided: ${data}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON data provided' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n\n // Validate that either id or where is provided\n if (!id && !where) {\n payload.logger.error('[payload-mcp] Either id or where clause must be provided')\n const response = {\n content: [\n { type: 'text' as const, text: 'Error: Either id or where clause must be provided' },\n ],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n\n // Parse where clause if provided\n let whereClause = {}\n if (where) {\n try {\n whereClause = JSON.parse(where)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Using where clause: ${where}`)\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid where clause JSON: ${where}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in where clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid select clause JSON: ${select}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in select clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Update by ID or where clause\n if (id) {\n // Single document update\n const updateOptions = {\n id,\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: false,\n overrideLock,\n req,\n user,\n ...(filePath && { filePath }),\n ...(overwriteExistingFiles && { overwriteExistingFiles }),\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(selectClause && { select: selectClause }),\n }\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Updating single document with ID: ${id}`)\n }\n const result = await payload.update({\n ...updateOptions,\n data: parsedData,\n } as any)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully updated document with ID: ${id}`)\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Document updated successfully in collection \"${collectionSlug}\"!\nUpdated document:\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, result, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } else {\n // Multiple documents update\n const updateOptions = {\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: false,\n overrideLock,\n req,\n user,\n where: whereClause,\n ...(filePath && { filePath }),\n ...(overwriteExistingFiles && { overwriteExistingFiles }),\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(selectClause && { select: selectClause }),\n }\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Updating multiple documents with where clause`)\n }\n const result = await payload.update({\n ...updateOptions,\n data: parsedData,\n } as any)\n\n const bulkResult = result as { docs?: unknown[]; errors?: unknown[] }\n const docs = bulkResult.docs || []\n const errors = bulkResult.errors || []\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Successfully updated ${docs.length} documents, ${errors.length} errors`,\n )\n }\n\n let responseText = `Multiple documents updated in collection \"${collectionSlug}\"!\nUpdated: ${docs.length} documents\nErrors: ${errors.length}\n---`\n\n if (docs.length > 0) {\n responseText += `\\n\\nUpdated documents:\n\\`\\`\\`json\n${JSON.stringify(docs, null, 2)}\n\\`\\`\\``\n }\n\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\n\\`\\`\\`json\n${JSON.stringify(errors, null, 2)}\n\\`\\`\\``\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: responseText,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(\n response,\n { docs, errors },\n req,\n ) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n payload.logger.error(\n `[payload-mcp] Error updating resource in ${collectionSlug}: ${errorMessage}`,\n )\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error updating resource in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n if (collections?.[collectionSlug]?.enabled) {\n const convertedFields = convertCollectionSchemaToZod(schema)\n\n // Create a new schema that combines the converted fields with update-specific parameters\n // Use .partial() to make all fields optional for partial updates\n const updateResourceSchema = z.object({\n ...convertedFields.partial().shape,\n id: z.union([z.string(), z.number()]).optional().describe('The ID of the document to update'),\n depth: z\n .number()\n .optional()\n .default(0)\n .describe('How many levels deep to populate relationships'),\n draft: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to update the document as a draft'),\n fallbackLocale: z\n .string()\n .optional()\n .describe('Optional: fallback locale code to use when requested locale is not available'),\n filePath: z.string().optional().describe('File path for file uploads'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Optional: locale code to update the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n ),\n overrideLock: z\n .boolean()\n .optional()\n .default(true)\n .describe('Whether to override document locks'),\n overwriteExistingFiles: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to overwrite existing files'),\n select: z\n .string()\n .optional()\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n ),\n where: z\n .string()\n .optional()\n .describe('JSON string for where clause to update multiple documents'),\n })\n\n server.tool(\n `update${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n `${collections?.[collectionSlug]?.description || toolSchemas.updateResource.description.trim()}`,\n updateResourceSchema.shape,\n async (params: Record<string, unknown>) => {\n const {\n id,\n depth,\n draft,\n fallbackLocale,\n filePath,\n locale,\n overrideLock,\n overwriteExistingFiles,\n select,\n where,\n ...fieldData\n } = params\n // Convert field data back to JSON string format expected by the tool\n const data = JSON.stringify(fieldData)\n return await tool(\n data,\n id as number | string | undefined,\n where as string | undefined,\n draft as boolean,\n depth as number,\n overrideLock as boolean,\n filePath as string | undefined,\n overwriteExistingFiles as boolean,\n locale as string | undefined,\n fallbackLocale as string | undefined,\n select as string | undefined,\n )\n },\n )\n }\n}\n"],"names":["z","toCamelCase","convertCollectionSchemaToZod","transformPointDataToPayload","toolSchemas","updateResourceTool","server","req","user","verboseLogs","collectionSlug","collections","schema","tool","data","id","where","draft","depth","overrideLock","filePath","overwriteExistingFiles","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","stringify","_parseError","error","response","content","type","text","overrideResponse","whereClause","selectClause","warn","updateOptions","collection","overrideAccess","result","update","bulkResult","docs","errors","length","responseText","errorMessage","Error","message","enabled","convertedFields","updateResourceSchema","object","partial","shape","union","string","number","optional","describe","default","boolean","char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,CAAC,MAAM,EAAEH,eAAe0D,MAAM,CAAC,GAAGC,WAAW,KAAKpE,YAAYS,gBAAgB4D,KAAK,CAAC,IAAI,EACxF,GAAG3D,aAAa,CAACD,eAAe,EAAE6D,eAAenE,YAAYoE,cAAc,CAACD,WAAW,CAACE,IAAI,IAAI,EAChGhB,qBAAqBG,KAAK,EAC1B,OAAOc;YACL,MAAM,EACJ3D,EAAE,EACFG,KAAK,EACLD,KAAK,EACLM,cAAc,EACdH,QAAQ,EACRE,MAAM,EACNH,YAAY,EACZE,sBAAsB,EACtBG,MAAM,EACNR,KAAK,EACL,GAAG2D,WACJ,GAAGD;YACJ,qEAAqE;YACrE,MAAM5D,OAAOe,KAAKE,SAAS,CAAC4C;YAC5B,OAAO,MAAM9D,KACXC,MACAC,IACAC,OACAC,OACAC,OACAC,cACAC,UACAC,wBACAC,QACAC,gBACAC;QAEJ;IAEJ;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"convertCollectionSchemaToZod.d.ts","sourceRoot":"","sources":["../../src/utils/convertCollectionSchemaToZod.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"convertCollectionSchemaToZod.d.ts","sourceRoot":"","sources":["../../src/utils/convertCollectionSchemaToZod.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAsD9C,eAAO,MAAM,4BAA4B,WAAY,WAAW,QAwC/D,CAAA"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { jsonSchemaToZod } from 'json-schema-to-zod';
|
|
2
2
|
import * as ts from 'typescript';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
+
import { transformPointFieldsForMCP } from './transformPointFields.js';
|
|
4
5
|
/**
|
|
5
6
|
* Recursively processes JSON schema properties to simplify relationship fields.
|
|
6
7
|
* For create/update validation we only need to accept IDs (string/number),
|
|
@@ -53,7 +54,8 @@ export const convertCollectionSchemaToZod = (schema)=>{
|
|
|
53
54
|
delete schemaClone.required;
|
|
54
55
|
}
|
|
55
56
|
}
|
|
56
|
-
const
|
|
57
|
+
const pointTransformed = transformPointFieldsForMCP(schemaClone);
|
|
58
|
+
const simplifiedSchema = simplifyRelationshipFields(pointTransformed);
|
|
57
59
|
const zodSchemaAsString = jsonSchemaToZod(simplifiedSchema);
|
|
58
60
|
// Transpile TypeScript to JavaScript
|
|
59
61
|
const transpileResult = ts.transpileModule(zodSchemaAsString, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/convertCollectionSchemaToZod.ts"],"sourcesContent":["import type { JSONSchema4 } from 'json-schema'\n\nimport { jsonSchemaToZod } from 'json-schema-to-zod'\nimport * as ts from 'typescript'\nimport { z } from 'zod'\n\n/**\n * Recursively processes JSON schema properties to simplify relationship fields.\n * For create/update validation we only need to accept IDs (string/number),\n * not populated objects. This removes the $ref option from oneOf unions\n * that represent relationship fields, leaving only the ID shape.\n *\n * NOTE: This function must operate on a cloned schema to avoid mutating\n * the original JSON schema used for tool listing.\n */\nfunction simplifyRelationshipFields(schema: JSONSchema4): JSONSchema4 {\n if (!schema || typeof schema !== 'object') {\n return schema\n }\n\n const processed = { ...schema }\n\n if (Array.isArray(processed.oneOf)) {\n const hasRef = processed.oneOf.some(\n (option) => option && typeof option === 'object' && '$ref' in option,\n )\n\n processed.oneOf = processed.oneOf.map((option) => {\n if (option && typeof option === 'object' && '$ref' in option) {\n // Replace unresolved $ref with a permissive object schema to keep the union shape\n return { type: 'object', additionalProperties: true }\n }\n return simplifyRelationshipFields(option)\n })\n }\n\n if (processed.properties && typeof processed.properties === 'object') {\n processed.properties = Object.fromEntries(\n Object.entries(processed.properties).map(([key, value]) => [\n key,\n simplifyRelationshipFields(value),\n ]),\n )\n }\n\n if (processed.items && typeof processed.items === 'object' && !Array.isArray(processed.items)) {\n processed.items = simplifyRelationshipFields(processed.items)\n }\n\n return processed\n}\n\nexport const convertCollectionSchemaToZod = (schema: JSONSchema4) => {\n // Clone to avoid mutating the original schema (used elsewhere for tool listing)\n const schemaClone = JSON.parse(JSON.stringify(schema)) as JSONSchema4\n\n // Remove properties that should not be included in the Zod schema\n delete schemaClone?.properties?.id\n delete schemaClone?.properties?.createdAt\n delete schemaClone?.properties?.updatedAt\n if (Array.isArray(schemaClone.required)) {\n schemaClone.required = schemaClone.required.filter((field) => field !== 'id')\n if (schemaClone.required.length === 0) {\n delete schemaClone.required\n }\n }\n\n const simplifiedSchema = simplifyRelationshipFields(
|
|
1
|
+
{"version":3,"sources":["../../src/utils/convertCollectionSchemaToZod.ts"],"sourcesContent":["import type { JSONSchema4 } from 'json-schema'\n\nimport { jsonSchemaToZod } from 'json-schema-to-zod'\nimport * as ts from 'typescript'\nimport { z } from 'zod'\n\nimport { transformPointFieldsForMCP } from './transformPointFields.js'\n\n/**\n * Recursively processes JSON schema properties to simplify relationship fields.\n * For create/update validation we only need to accept IDs (string/number),\n * not populated objects. This removes the $ref option from oneOf unions\n * that represent relationship fields, leaving only the ID shape.\n *\n * NOTE: This function must operate on a cloned schema to avoid mutating\n * the original JSON schema used for tool listing.\n */\nfunction simplifyRelationshipFields(schema: JSONSchema4): JSONSchema4 {\n if (!schema || typeof schema !== 'object') {\n return schema\n }\n\n const processed = { ...schema }\n\n if (Array.isArray(processed.oneOf)) {\n const hasRef = processed.oneOf.some(\n (option) => option && typeof option === 'object' && '$ref' in option,\n )\n\n processed.oneOf = processed.oneOf.map((option) => {\n if (option && typeof option === 'object' && '$ref' in option) {\n // Replace unresolved $ref with a permissive object schema to keep the union shape\n return { type: 'object', additionalProperties: true }\n }\n return simplifyRelationshipFields(option)\n })\n }\n\n if (processed.properties && typeof processed.properties === 'object') {\n processed.properties = Object.fromEntries(\n Object.entries(processed.properties).map(([key, value]) => [\n key,\n simplifyRelationshipFields(value),\n ]),\n )\n }\n\n if (processed.items && typeof processed.items === 'object' && !Array.isArray(processed.items)) {\n processed.items = simplifyRelationshipFields(processed.items)\n }\n\n return processed\n}\n\nexport const convertCollectionSchemaToZod = (schema: JSONSchema4) => {\n // Clone to avoid mutating the original schema (used elsewhere for tool listing)\n const schemaClone = JSON.parse(JSON.stringify(schema)) as JSONSchema4\n\n // Remove properties that should not be included in the Zod schema\n delete schemaClone?.properties?.id\n delete schemaClone?.properties?.createdAt\n delete schemaClone?.properties?.updatedAt\n if (Array.isArray(schemaClone.required)) {\n schemaClone.required = schemaClone.required.filter((field) => field !== 'id')\n if (schemaClone.required.length === 0) {\n delete schemaClone.required\n }\n }\n\n const pointTransformed = transformPointFieldsForMCP(schemaClone)\n const simplifiedSchema = simplifyRelationshipFields(pointTransformed)\n\n const zodSchemaAsString = jsonSchemaToZod(simplifiedSchema)\n\n // Transpile TypeScript to JavaScript\n const transpileResult = ts.transpileModule(zodSchemaAsString, {\n compilerOptions: {\n module: ts.ModuleKind.CommonJS,\n removeComments: true,\n strict: false,\n target: ts.ScriptTarget.ES2018,\n },\n })\n\n /**\n * This Function evaluation is safe because:\n * 1. The input schema comes from Payload's collection configuration, which is controlled by the application developer\n * 2. The jsonSchemaToZod library converts JSON Schema to Zod schema definitions, producing only type validation code\n * 3. The transpiled output contains only Zod schema definitions (z.string(), z.number(), etc.) - no executable logic\n * 4. The resulting Zod schema is used only for parameter validation in MCP tools, not for data processing\n * 5. No user input or external data is involved in the schema generation process\n */\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n return new Function('z', `return ${transpileResult.outputText}`)(z)\n}\n"],"names":["jsonSchemaToZod","ts","z","transformPointFieldsForMCP","simplifyRelationshipFields","schema","processed","Array","isArray","oneOf","hasRef","some","option","map","type","additionalProperties","properties","Object","fromEntries","entries","key","value","items","convertCollectionSchemaToZod","schemaClone","JSON","parse","stringify","id","createdAt","updatedAt","required","filter","field","length","pointTransformed","simplifiedSchema","zodSchemaAsString","transpileResult","transpileModule","compilerOptions","module","ModuleKind","CommonJS","removeComments","strict","target","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S,CAACtB;IAE9C,kEAAkE;IAClE,OAAOmB,aAAaR,YAAYY;IAChC,OAAOJ,aAAaR,YAAYa;IAChC,OAAOL,aAAaR,YAAYc;IAChC,IAAIvB,MAAMC,OAAO,CAACgB,YAAYO,QAAQ,GAAG;QACvCP,YAAYO,QAAQ,GAAGP,YAAYO,QAAQ,CAACC,MAAM,CAAC,CAACC,QAAUA,UAAU;QACxE,IAAIT,YAAYO,QAAQ,CAACG,MAAM,KAAK,GAAG;YACrC,OAAOV,YAAYO,QAAQ;QAC7B;IACF;IAEA,MAAMI,mBAAmBhC,2BAA2BqB;IACpD,MAAMY,mBAAmBhC,2BAA2B+B;IAEpD,MAAME,oBAAoBrC,gBAAgBoC;IAE1C,qCAAqC;IACrC,MAAME,kBAAkBrC,GAAGsC,eAAe,CAACF,mBAAmB;QAC5DG,iBAAiB;YACfC,QAAQxC,GAAGyC,UAAU,CAACC,QAAQ;YAC9BC,gBAAgB;YAChBC,QAAQ;YACRC,QAAQ7C,GAAG8C,YAAY,CAACC,MAAM;QAChC;IACF;IAEA;;;;;;;GAOC,GACD,8DAA8D;IAC9D,OAAO,IAAIC,SAAS,KAAK,CAAC,OAAO,EAAEX,gBAAgBY,UAAU,EAAE,EAAEhD;AACnE,EAAC"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transforms incoming MCP tool data from object format to tuple array format.
|
|
3
|
+
* Converts { longitude: number, latitude: number } back to [longitude, latitude]
|
|
4
|
+
* for Payload's internal point field representation.
|
|
5
|
+
*/
|
|
6
|
+
export declare function transformPointDataToPayload(data: Record<string, unknown>): Record<string, unknown>;
|
|
7
|
+
//# sourceMappingURL=transformPointDataToPayload.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transformPointDataToPayload.d.ts","sourceRoot":"","sources":["../../src/utils/transformPointDataToPayload.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,2BAA2B,CACzC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC5B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAgCzB"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transforms incoming MCP tool data from object format to tuple array format.
|
|
3
|
+
* Converts { longitude: number, latitude: number } back to [longitude, latitude]
|
|
4
|
+
* for Payload's internal point field representation.
|
|
5
|
+
*/ export function transformPointDataToPayload(data) {
|
|
6
|
+
if (!data || typeof data !== 'object') {
|
|
7
|
+
return data;
|
|
8
|
+
}
|
|
9
|
+
const transformed = {};
|
|
10
|
+
for (const [key, value] of Object.entries(data)){
|
|
11
|
+
if (value && typeof value === 'object' && 'longitude' in value && 'latitude' in value && typeof value.longitude === 'number' && typeof value.latitude === 'number') {
|
|
12
|
+
// Transform to tuple array [longitude, latitude]
|
|
13
|
+
transformed[key] = [
|
|
14
|
+
value.longitude,
|
|
15
|
+
value.latitude
|
|
16
|
+
];
|
|
17
|
+
} else if (Array.isArray(value)) {
|
|
18
|
+
transformed[key] = value.map((item)=>typeof item === 'object' ? transformPointDataToPayload(item) : item);
|
|
19
|
+
} else if (value && typeof value === 'object') {
|
|
20
|
+
transformed[key] = transformPointDataToPayload(value);
|
|
21
|
+
} else {
|
|
22
|
+
transformed[key] = value;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return transformed;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
//# sourceMappingURL=transformPointDataToPayload.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/transformPointDataToPayload.ts"],"sourcesContent":["/**\n * Transforms incoming MCP tool data from object format to tuple array format.\n * Converts { longitude: number, latitude: number } back to [longitude, latitude]\n * for Payload's internal point field representation.\n */\nexport function transformPointDataToPayload(\n data: Record<string, unknown>,\n): Record<string, unknown> {\n if (!data || typeof data !== 'object') {\n return data\n }\n\n const transformed: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(data)) {\n if (\n value &&\n typeof value === 'object' &&\n 'longitude' in value &&\n 'latitude' in value &&\n typeof value.longitude === 'number' &&\n typeof value.latitude === 'number'\n ) {\n // Transform to tuple array [longitude, latitude]\n transformed[key] = [value.longitude, value.latitude]\n } else if (Array.isArray(value)) {\n transformed[key] = value.map((item) =>\n typeof item === 'object'\n ? transformPointDataToPayload(item as Record<string, unknown>)\n : item,\n )\n } else if (value && typeof value === 'object') {\n transformed[key] = transformPointDataToPayload(value as Record<string, unknown>)\n } else {\n transformed[key] = value\n }\n }\n\n return transformed\n}\n"],"names":["transformPointDataToPayload","data","transformed","key","value","Object","entries","longitude","latitude","Array","isArray","map","item"],"mappings":"AAAA;;;;CAIC,GACD,OAAO,SAASA,4BACdC,IAA6B;IAE7B,IAAI,CAACA,QAAQ,OAAOA,SAAS,UAAU;QACrC,OAAOA;IACT;IAEA,MAAMC,cAAuC,CAAC;IAE9C,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACL,MAAO;QAC/C,IACEG,SACA,OAAOA,UAAU,YACjB,eAAeA,SACf,cAAcA,SACd,OAAOA,MAAMG,SAAS,KAAK,YAC3B,OAAOH,MAAMI,QAAQ,KAAK,UAC1B;YACA,iDAAiD;YACjDN,WAAW,CAACC,IAAI,GAAG;gBAACC,MAAMG,SAAS;gBAAEH,MAAMI,QAAQ;aAAC;QACtD,OAAO,IAAIC,MAAMC,OAAO,CAACN,QAAQ;YAC/BF,WAAW,CAACC,IAAI,GAAGC,MAAMO,GAAG,CAAC,CAACC,OAC5B,OAAOA,SAAS,WACZZ,4BAA4BY,QAC5BA;QAER,OAAO,IAAIR,SAAS,OAAOA,UAAU,UAAU;YAC7CF,WAAW,CAACC,IAAI,GAAGH,4BAA4BI;QACjD,OAAO;YACLF,WAAW,CAACC,IAAI,GAAGC;QACrB;IACF;IAEA,OAAOF;AACT"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transformPointFields.d.ts","sourceRoot":"","sources":["../../src/utils/transformPointFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAE9C,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,WAAW,GAAG,WAAW,CAoD3E"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export function transformPointFieldsForMCP(schema) {
|
|
2
|
+
if (!schema || typeof schema !== 'object') {
|
|
3
|
+
return schema;
|
|
4
|
+
}
|
|
5
|
+
const transformed = {
|
|
6
|
+
...schema
|
|
7
|
+
};
|
|
8
|
+
if (transformed.properties && typeof transformed.properties === 'object') {
|
|
9
|
+
transformed.properties = Object.fromEntries(Object.entries(transformed.properties).map(([key, value])=>{
|
|
10
|
+
const isArrayType = value.type === 'array' || Array.isArray(value.type) && value.type.includes('array');
|
|
11
|
+
if (value && typeof value === 'object' && isArrayType && Array.isArray(value.items) && value.items.length === 2 && value.items.every((item)=>item?.type === 'number')) {
|
|
12
|
+
// Transform to object format
|
|
13
|
+
const isNullable = Array.isArray(value.type) && value.type.includes('null');
|
|
14
|
+
return [
|
|
15
|
+
key,
|
|
16
|
+
{
|
|
17
|
+
type: isNullable ? [
|
|
18
|
+
'object',
|
|
19
|
+
'null'
|
|
20
|
+
] : 'object',
|
|
21
|
+
description: value.description || 'Geographic coordinates (longitude, latitude)',
|
|
22
|
+
properties: {
|
|
23
|
+
latitude: {
|
|
24
|
+
type: 'number',
|
|
25
|
+
description: 'Latitude coordinate'
|
|
26
|
+
},
|
|
27
|
+
longitude: {
|
|
28
|
+
type: 'number',
|
|
29
|
+
description: 'Longitude coordinate'
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
required: [
|
|
33
|
+
'longitude',
|
|
34
|
+
'latitude'
|
|
35
|
+
]
|
|
36
|
+
}
|
|
37
|
+
];
|
|
38
|
+
}
|
|
39
|
+
return [
|
|
40
|
+
key,
|
|
41
|
+
transformPointFieldsForMCP(value)
|
|
42
|
+
];
|
|
43
|
+
}));
|
|
44
|
+
}
|
|
45
|
+
if (transformed.items && typeof transformed.items === 'object' && !Array.isArray(transformed.items)) {
|
|
46
|
+
transformed.items = transformPointFieldsForMCP(transformed.items);
|
|
47
|
+
}
|
|
48
|
+
return transformed;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
//# sourceMappingURL=transformPointFields.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/transformPointFields.ts"],"sourcesContent":["import type { JSONSchema4 } from 'json-schema'\n\nexport function transformPointFieldsForMCP(schema: JSONSchema4): JSONSchema4 {\n if (!schema || typeof schema !== 'object') {\n return schema\n }\n\n const transformed = { ...schema }\n\n if (transformed.properties && typeof transformed.properties === 'object') {\n transformed.properties = Object.fromEntries(\n Object.entries(transformed.properties).map(([key, value]) => {\n const isArrayType =\n value.type === 'array' || (Array.isArray(value.type) && value.type.includes('array'))\n\n if (\n value &&\n typeof value === 'object' &&\n isArrayType &&\n Array.isArray(value.items) &&\n value.items.length === 2 &&\n value.items.every((item: JSONSchema4) => item?.type === 'number')\n ) {\n // Transform to object format\n const isNullable = Array.isArray(value.type) && value.type.includes('null')\n\n return [\n key,\n {\n type: isNullable ? ['object', 'null'] : 'object',\n description: value.description || 'Geographic coordinates (longitude, latitude)',\n properties: {\n latitude: { type: 'number', description: 'Latitude coordinate' },\n longitude: { type: 'number', description: 'Longitude coordinate' },\n },\n required: ['longitude', 'latitude'],\n },\n ]\n }\n\n return [key, transformPointFieldsForMCP(value)]\n }),\n )\n }\n\n if (\n transformed.items &&\n typeof transformed.items === 'object' &&\n !Array.isArray(transformed.items)\n ) {\n transformed.items = transformPointFieldsForMCP(transformed.items)\n }\n\n return transformed\n}\n"],"names":["transformPointFieldsForMCP","schema","transformed","properties","Object","fromEntries","entries","map","key","value","isArrayType","type","Array","isArray","includes","items","length","every","item","isNullable","description","latitude","longitude","required"],"mappings":"AAEA,OAAO,SAASA,2BAA2BC,MAA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EA,OAAOb;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payloadcms/plugin-mcp",
|
|
3
|
-
"version": "3.75.0
|
|
3
|
+
"version": "3.75.0",
|
|
4
4
|
"description": "MCP (Model Context Protocol) capabilities with Payload",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"plugin",
|
|
@@ -45,10 +45,10 @@
|
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@payloadcms/eslint-config": "3.28.0",
|
|
48
|
-
"payload": "3.75.0
|
|
48
|
+
"payload": "3.75.0"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
|
-
"payload": "3.75.0
|
|
51
|
+
"payload": "3.75.0"
|
|
52
52
|
},
|
|
53
53
|
"homepage:": "https://payloadcms.com",
|
|
54
54
|
"scripts": {
|
|
@@ -8,6 +8,7 @@ import type { PluginMCPServerConfig } from '../../../types.js'
|
|
|
8
8
|
|
|
9
9
|
import { toCamelCase } from '../../../utils/camelCase.js'
|
|
10
10
|
import { convertCollectionSchemaToZod } from '../../../utils/convertCollectionSchemaToZod.js'
|
|
11
|
+
import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
|
|
11
12
|
import { toolSchemas } from '../schemas.js'
|
|
12
13
|
export const createResourceTool = (
|
|
13
14
|
server: McpServer,
|
|
@@ -44,6 +45,10 @@ export const createResourceTool = (
|
|
|
44
45
|
let parsedData: Record<string, unknown>
|
|
45
46
|
try {
|
|
46
47
|
parsedData = JSON.parse(data)
|
|
48
|
+
|
|
49
|
+
// Transform point fields from object format to tuple array
|
|
50
|
+
parsedData = transformPointDataToPayload(parsedData)
|
|
51
|
+
|
|
47
52
|
if (verboseLogs) {
|
|
48
53
|
payload.logger.info(
|
|
49
54
|
`[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`,
|
|
@@ -8,6 +8,7 @@ import type { PluginMCPServerConfig } from '../../../types.js'
|
|
|
8
8
|
|
|
9
9
|
import { toCamelCase } from '../../../utils/camelCase.js'
|
|
10
10
|
import { convertCollectionSchemaToZod } from '../../../utils/convertCollectionSchemaToZod.js'
|
|
11
|
+
import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
|
|
11
12
|
import { toolSchemas } from '../schemas.js'
|
|
12
13
|
export const updateResourceTool = (
|
|
13
14
|
server: McpServer,
|
|
@@ -49,6 +50,10 @@ export const updateResourceTool = (
|
|
|
49
50
|
let parsedData: Record<string, unknown>
|
|
50
51
|
try {
|
|
51
52
|
parsedData = JSON.parse(data)
|
|
53
|
+
|
|
54
|
+
// Transform point fields from object format to tuple array
|
|
55
|
+
parsedData = transformPointDataToPayload(parsedData)
|
|
56
|
+
|
|
52
57
|
if (verboseLogs) {
|
|
53
58
|
payload.logger.info(
|
|
54
59
|
`[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`,
|
|
@@ -4,6 +4,8 @@ import { jsonSchemaToZod } from 'json-schema-to-zod'
|
|
|
4
4
|
import * as ts from 'typescript'
|
|
5
5
|
import { z } from 'zod'
|
|
6
6
|
|
|
7
|
+
import { transformPointFieldsForMCP } from './transformPointFields.js'
|
|
8
|
+
|
|
7
9
|
/**
|
|
8
10
|
* Recursively processes JSON schema properties to simplify relationship fields.
|
|
9
11
|
* For create/update validation we only need to accept IDs (string/number),
|
|
@@ -65,7 +67,8 @@ export const convertCollectionSchemaToZod = (schema: JSONSchema4) => {
|
|
|
65
67
|
}
|
|
66
68
|
}
|
|
67
69
|
|
|
68
|
-
const
|
|
70
|
+
const pointTransformed = transformPointFieldsForMCP(schemaClone)
|
|
71
|
+
const simplifiedSchema = simplifyRelationshipFields(pointTransformed)
|
|
69
72
|
|
|
70
73
|
const zodSchemaAsString = jsonSchemaToZod(simplifiedSchema)
|
|
71
74
|
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transforms incoming MCP tool data from object format to tuple array format.
|
|
3
|
+
* Converts { longitude: number, latitude: number } back to [longitude, latitude]
|
|
4
|
+
* for Payload's internal point field representation.
|
|
5
|
+
*/
|
|
6
|
+
export function transformPointDataToPayload(
|
|
7
|
+
data: Record<string, unknown>,
|
|
8
|
+
): Record<string, unknown> {
|
|
9
|
+
if (!data || typeof data !== 'object') {
|
|
10
|
+
return data
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const transformed: Record<string, unknown> = {}
|
|
14
|
+
|
|
15
|
+
for (const [key, value] of Object.entries(data)) {
|
|
16
|
+
if (
|
|
17
|
+
value &&
|
|
18
|
+
typeof value === 'object' &&
|
|
19
|
+
'longitude' in value &&
|
|
20
|
+
'latitude' in value &&
|
|
21
|
+
typeof value.longitude === 'number' &&
|
|
22
|
+
typeof value.latitude === 'number'
|
|
23
|
+
) {
|
|
24
|
+
// Transform to tuple array [longitude, latitude]
|
|
25
|
+
transformed[key] = [value.longitude, value.latitude]
|
|
26
|
+
} else if (Array.isArray(value)) {
|
|
27
|
+
transformed[key] = value.map((item) =>
|
|
28
|
+
typeof item === 'object'
|
|
29
|
+
? transformPointDataToPayload(item as Record<string, unknown>)
|
|
30
|
+
: item,
|
|
31
|
+
)
|
|
32
|
+
} else if (value && typeof value === 'object') {
|
|
33
|
+
transformed[key] = transformPointDataToPayload(value as Record<string, unknown>)
|
|
34
|
+
} else {
|
|
35
|
+
transformed[key] = value
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return transformed
|
|
40
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { JSONSchema4 } from 'json-schema'
|
|
2
|
+
|
|
3
|
+
export function transformPointFieldsForMCP(schema: JSONSchema4): JSONSchema4 {
|
|
4
|
+
if (!schema || typeof schema !== 'object') {
|
|
5
|
+
return schema
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const transformed = { ...schema }
|
|
9
|
+
|
|
10
|
+
if (transformed.properties && typeof transformed.properties === 'object') {
|
|
11
|
+
transformed.properties = Object.fromEntries(
|
|
12
|
+
Object.entries(transformed.properties).map(([key, value]) => {
|
|
13
|
+
const isArrayType =
|
|
14
|
+
value.type === 'array' || (Array.isArray(value.type) && value.type.includes('array'))
|
|
15
|
+
|
|
16
|
+
if (
|
|
17
|
+
value &&
|
|
18
|
+
typeof value === 'object' &&
|
|
19
|
+
isArrayType &&
|
|
20
|
+
Array.isArray(value.items) &&
|
|
21
|
+
value.items.length === 2 &&
|
|
22
|
+
value.items.every((item: JSONSchema4) => item?.type === 'number')
|
|
23
|
+
) {
|
|
24
|
+
// Transform to object format
|
|
25
|
+
const isNullable = Array.isArray(value.type) && value.type.includes('null')
|
|
26
|
+
|
|
27
|
+
return [
|
|
28
|
+
key,
|
|
29
|
+
{
|
|
30
|
+
type: isNullable ? ['object', 'null'] : 'object',
|
|
31
|
+
description: value.description || 'Geographic coordinates (longitude, latitude)',
|
|
32
|
+
properties: {
|
|
33
|
+
latitude: { type: 'number', description: 'Latitude coordinate' },
|
|
34
|
+
longitude: { type: 'number', description: 'Longitude coordinate' },
|
|
35
|
+
},
|
|
36
|
+
required: ['longitude', 'latitude'],
|
|
37
|
+
},
|
|
38
|
+
]
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return [key, transformPointFieldsForMCP(value)]
|
|
42
|
+
}),
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (
|
|
47
|
+
transformed.items &&
|
|
48
|
+
typeof transformed.items === 'object' &&
|
|
49
|
+
!Array.isArray(transformed.items)
|
|
50
|
+
) {
|
|
51
|
+
transformed.items = transformPointFieldsForMCP(transformed.items)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return transformed
|
|
55
|
+
}
|