@payloadcms/plugin-mcp 3.78.0-internal-debug.f663370 → 3.78.0-internal.ab11ffa
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/index.d.ts +0 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -1
- package/dist/index.js.map +1 -1
- package/dist/mcp/getMcpHandler.d.ts.map +1 -1
- package/dist/mcp/getMcpHandler.js +8 -2
- package/dist/mcp/getMcpHandler.js.map +1 -1
- package/dist/mcp/helpers/config.d.ts +1 -9
- package/dist/mcp/helpers/config.d.ts.map +1 -1
- package/dist/mcp/helpers/config.js +0 -62
- package/dist/mcp/helpers/config.js.map +1 -1
- package/dist/mcp/helpers/fields.d.ts +6 -25
- package/dist/mcp/helpers/fields.d.ts.map +1 -1
- package/dist/mcp/helpers/fields.js +35 -29
- package/dist/mcp/helpers/fields.js.map +1 -1
- package/dist/mcp/helpers/fileValidation.d.ts +0 -2
- package/dist/mcp/helpers/fileValidation.d.ts.map +1 -1
- package/dist/mcp/helpers/fileValidation.js +44 -82
- package/dist/mcp/helpers/fileValidation.js.map +1 -1
- package/dist/mcp/tools/collection/create.d.ts.map +1 -1
- package/dist/mcp/tools/collection/create.js +2 -25
- package/dist/mcp/tools/collection/create.js.map +1 -1
- package/dist/mcp/tools/collection/delete.d.ts.map +1 -1
- package/dist/mcp/tools/collection/delete.js +1 -12
- package/dist/mcp/tools/collection/delete.js.map +1 -1
- package/dist/mcp/tools/config/update.d.ts +1 -1
- package/dist/mcp/tools/config/update.d.ts.map +1 -1
- package/dist/mcp/tools/config/update.js +3 -3
- package/dist/mcp/tools/config/update.js.map +1 -1
- package/dist/mcp/tools/global/update.d.ts.map +1 -1
- package/dist/mcp/tools/global/update.js +3 -0
- package/dist/mcp/tools/global/update.js.map +1 -1
- package/dist/mcp/tools/job/create.d.ts.map +1 -1
- package/dist/mcp/tools/job/create.js +3 -6
- package/dist/mcp/tools/job/create.js.map +1 -1
- package/dist/mcp/tools/job/run.d.ts +1 -1
- package/dist/mcp/tools/job/run.d.ts.map +1 -1
- package/dist/mcp/tools/job/run.js +5 -26
- package/dist/mcp/tools/job/run.js.map +1 -1
- package/dist/mcp/tools/job/update.d.ts.map +1 -1
- package/dist/mcp/tools/job/update.js +10 -38
- package/dist/mcp/tools/job/update.js.map +1 -1
- 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/mcp/tools/schemas.d.ts +2 -5
- package/dist/mcp/tools/schemas.d.ts.map +1 -1
- package/dist/mcp/tools/schemas.js +0 -1
- package/dist/mcp/tools/schemas.js.map +1 -1
- package/dist/utils/getVirtualFieldNames.d.ts +14 -0
- package/dist/utils/getVirtualFieldNames.d.ts.map +1 -0
- package/dist/utils/getVirtualFieldNames.js +35 -0
- package/dist/utils/getVirtualFieldNames.js.map +1 -0
- package/dist/utils/schemaConversion/convertCollectionSchemaToZod.d.ts.map +1 -1
- package/dist/utils/schemaConversion/convertCollectionSchemaToZod.js +1 -2
- package/dist/utils/schemaConversion/convertCollectionSchemaToZod.js.map +1 -1
- package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +7 -0
- package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +1 -0
- package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +20 -0
- package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +1 -0
- package/dist/utils/schemaConversion/sanitizeJsonSchema.d.ts +5 -0
- package/dist/utils/schemaConversion/sanitizeJsonSchema.d.ts.map +1 -1
- package/dist/utils/schemaConversion/sanitizeJsonSchema.js +38 -0
- package/dist/utils/schemaConversion/sanitizeJsonSchema.js.map +1 -1
- package/package.json +4 -4
- package/src/index.ts +0 -1
- package/src/mcp/getMcpHandler.ts +22 -2
- package/src/mcp/helpers/config.ts +1 -114
- package/src/mcp/helpers/fields.ts +46 -50
- package/src/mcp/helpers/fileValidation.ts +38 -93
- package/src/mcp/tools/collection/create.ts +2 -30
- package/src/mcp/tools/collection/delete.ts +1 -19
- package/src/mcp/tools/config/update.ts +0 -4
- package/src/mcp/tools/global/update.ts +8 -0
- package/src/mcp/tools/job/create.ts +5 -11
- package/src/mcp/tools/job/run.ts +14 -38
- package/src/mcp/tools/job/update.ts +29 -77
- package/src/mcp/tools/resource/create.ts +7 -0
- package/src/mcp/tools/resource/update.ts +7 -0
- package/src/mcp/tools/schemas.ts +0 -1
- package/src/utils/getVirtualFieldNames.ts +53 -0
- package/src/utils/schemaConversion/convertCollectionSchemaToZod.ts +1 -3
- package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +27 -0
- package/src/utils/schemaConversion/sanitizeJsonSchema.ts +41 -0
- package/dist/mcp/helpers/conversion.d.ts +0 -2
- package/dist/mcp/helpers/conversion.d.ts.map +0 -1
- package/dist/mcp/helpers/conversion.js +0 -5
- package/dist/mcp/helpers/conversion.js.map +0 -1
- package/dist/mcp/helpers/validation.d.ts +0 -9
- package/dist/mcp/helpers/validation.d.ts.map +0 -1
- package/dist/mcp/helpers/validation.js +0 -22
- package/dist/mcp/helpers/validation.js.map +0 -1
- package/src/mcp/helpers/conversion.ts +0 -3
- package/src/mcp/helpers/validation.ts +0 -32
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/tools/global/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/schemaConversion/convertCollectionSchemaToZod.js'\nimport { toolSchemas } from '../schemas.js'\n\nexport const updateGlobalTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n globalSlug: string,\n globals: PluginMCPServerConfig['globals'],\n schema: JSONSchema4,\n) => {\n const tool = async (\n data: string,\n draft: boolean = false,\n depth: number = 0,\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 global: ${globalSlug}, 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 ${globalSlug}: ${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 (globals?.[globalSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\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 for global: ${select}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in select clause' }],\n }\n return (globals?.[globalSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n const updateOptions: Parameters<typeof payload.updateGlobal>[0] = {\n slug: globalSlug,\n data: parsedData,\n depth,\n draft,\n user,\n }\n\n // Add locale parameters if provided\n if (locale) {\n updateOptions.locale = locale\n }\n if (fallbackLocale) {\n updateOptions.fallbackLocale = fallbackLocale\n }\n if (selectClause) {\n updateOptions.select = selectClause\n }\n\n const result = await payload.updateGlobal(updateOptions)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully updated global: ${globalSlug}`)\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Global \"${globalSlug}\" updated successfully!\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (globals?.[globalSlug]?.overrideResponse?.(response, result, req) || 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(`[payload-mcp] Error updating global ${globalSlug}: ${errorMessage}`)\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error updating global \"${globalSlug}\": ${errorMessage}`,\n },\n ],\n }\n\n return (globals?.[globalSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n if (globals?.[globalSlug]?.enabled) {\n const convertedFields = convertCollectionSchemaToZod(schema)\n\n // Make all fields optional for partial updates (PATCH-style)\n const optionalFields = Object.fromEntries(\n Object.entries(convertedFields.shape).map(([key, value]) => [key, (value as any).optional()]),\n )\n\n const updateGlobalSchema = z.object({\n ...optionalFields,\n depth: z.number().optional().describe('Optional: Depth of relationships to populate'),\n draft: z.boolean().optional().describe('Optional: Whether to save as draft (default: false)'),\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 update data in (e.g., \"en\", \"es\"). Use \"all\" to update all locales for localized fields',\n ),\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., \\'{\"siteName\": \"My Site\"}\\'',\n ),\n })\n\n server.registerTool(\n `update${globalSlug.charAt(0).toUpperCase() + toCamelCase(globalSlug).slice(1)}`,\n {\n description: `${toolSchemas.updateGlobal.description.trim()}\\n\\n${globals?.[globalSlug]?.description || ''}`,\n inputSchema: updateGlobalSchema.shape,\n },\n async (params: Record<string, unknown>) => {\n const { depth, draft, fallbackLocale, locale, select, ...rest } = params\n const data = JSON.stringify(rest)\n return await tool(\n data,\n draft as boolean,\n depth as number,\n locale as string,\n fallbackLocale as string,\n select as string | undefined,\n )\n },\n )\n }\n}\n"],"names":["z","toCamelCase","convertCollectionSchemaToZod","toolSchemas","updateGlobalTool","server","req","user","verboseLogs","globalSlug","globals","schema","tool","data","draft","depth","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","stringify","_parseError","error","response","content","type","text","overrideResponse","selectClause","warn","updateOptions","slug","result","updateGlobal","errorMessage","Error","message","enabled","convertedFields","optionalFields","Object","fromEntries","entries","shape","map","key","value","optional","updateGlobalSchema","object","number","describe","boolean","string","registerTool","charAt","toUpperCase","slice","description","trim","inputSchema","params","rest"],"mappings":"AAIA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,4BAA4B,QAAQ,kEAAiE;AAC9G,SAASC,WAAW,QAAQ,gBAAe;AAE3C,OAAO,MAAMC,mBAAmB,CAC9BC,QACAC,KACAC,MACAC,aACAC,YACAC,SACAC;IAEA,MAAMC,OAAO,OACXC,MACAC,QAAiB,KAAK,EACtBC,QAAgB,CAAC,EACjBC,QACAC,gBACAC;QAOA,MAAMC,UAAUb,IAAIa,OAAO;QAE3B,IAAIX,aAAa;YACfW,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,+BAA+B,EAAEZ,WAAW,SAAS,EAAEK,QAAQE,SAAS,CAAC,UAAU,EAAEA,QAAQ,GAAG,IAAI;QAEzG;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,WAAW,EAAE,EAAEc,KAAKE,SAAS,CAACH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YAAYqD,KAAK,CAAC,IAAI,EAChF;YACEC,aAAa,GAAG5D,YAAYmC,YAAY,CAACyB,WAAW,CAACC,IAAI,GAAG,IAAI,EAAEtD,SAAS,CAACD,WAAW,EAAEsD,eAAe,IAAI;YAC5GE,aAAaZ,mBAAmBL,KAAK;QACvC,GACA,OAAOkB;YACL,MAAM,EAAEnD,KAAK,EAAED,KAAK,EAAEG,cAAc,EAAED,MAAM,EAAEE,MAAM,EAAE,GAAGiD,MAAM,GAAGD;YAClE,MAAMrD,OAAOU,KAAKE,SAAS,CAAC0C;YAC5B,OAAO,MAAMvD,KACXC,MACAC,OACAC,OACAC,QACAC,gBACAC;QAEJ;IAEJ;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/tools/global/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 {\n getGlobalVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js'\nimport { toolSchemas } from '../schemas.js'\n\nexport const updateGlobalTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n globalSlug: string,\n globals: PluginMCPServerConfig['globals'],\n schema: JSONSchema4,\n) => {\n const tool = async (\n data: string,\n draft: boolean = false,\n depth: number = 0,\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 global: ${globalSlug}, 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 const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, globalSlug)\n parsedData = stripVirtualFields(parsedData, virtualFieldNames)\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Parsed data for ${globalSlug}: ${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 (globals?.[globalSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\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 for global: ${select}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in select clause' }],\n }\n return (globals?.[globalSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n const updateOptions: Parameters<typeof payload.updateGlobal>[0] = {\n slug: globalSlug,\n data: parsedData,\n depth,\n draft,\n user,\n }\n\n // Add locale parameters if provided\n if (locale) {\n updateOptions.locale = locale\n }\n if (fallbackLocale) {\n updateOptions.fallbackLocale = fallbackLocale\n }\n if (selectClause) {\n updateOptions.select = selectClause\n }\n\n const result = await payload.updateGlobal(updateOptions)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully updated global: ${globalSlug}`)\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Global \"${globalSlug}\" updated successfully!\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (globals?.[globalSlug]?.overrideResponse?.(response, result, req) || 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(`[payload-mcp] Error updating global ${globalSlug}: ${errorMessage}`)\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error updating global \"${globalSlug}\": ${errorMessage}`,\n },\n ],\n }\n\n return (globals?.[globalSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n if (globals?.[globalSlug]?.enabled) {\n const convertedFields = convertCollectionSchemaToZod(schema)\n\n // Make all fields optional for partial updates (PATCH-style)\n const optionalFields = Object.fromEntries(\n Object.entries(convertedFields.shape).map(([key, value]) => [key, (value as any).optional()]),\n )\n\n const updateGlobalSchema = z.object({\n ...optionalFields,\n depth: z.number().optional().describe('Optional: Depth of relationships to populate'),\n draft: z.boolean().optional().describe('Optional: Whether to save as draft (default: false)'),\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 update data in (e.g., \"en\", \"es\"). Use \"all\" to update all locales for localized fields',\n ),\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., \\'{\"siteName\": \"My Site\"}\\'',\n ),\n })\n\n server.registerTool(\n `update${globalSlug.charAt(0).toUpperCase() + toCamelCase(globalSlug).slice(1)}`,\n {\n description: `${toolSchemas.updateGlobal.description.trim()}\\n\\n${globals?.[globalSlug]?.description || ''}`,\n inputSchema: updateGlobalSchema.shape,\n },\n async (params: Record<string, unknown>) => {\n const { depth, draft, fallbackLocale, locale, select, ...rest } = params\n const data = JSON.stringify(rest)\n return await tool(\n data,\n draft as boolean,\n depth as number,\n locale as string,\n fallbackLocale as string,\n select as string | undefined,\n )\n },\n )\n }\n}\n"],"names":["z","toCamelCase","getGlobalVirtualFieldNames","stripVirtualFields","convertCollectionSchemaToZod","toolSchemas","updateGlobalTool","server","req","user","verboseLogs","globalSlug","globals","schema","tool","data","draft","depth","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","virtualFieldNames","config","stringify","_parseError","error","response","content","type","text","overrideResponse","selectClause","warn","updateOptions","slug","result","updateGlobal","errorMessage","Error","message","enabled","convertedFields","optionalFields","Object","fromEntries","entries","shape","map","key","value","optional","updateGlobalSchema","object","number","describe","boolean","string","registerTool","charAt","toUpperCase","slice","description","trim","inputSchema","params","rest"],"mappings":"AAIA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,0BAA0B,EAC1BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,4BAA4B,QAAQ,kEAAiE;AAC9G,SAASC,WAAW,QAAQ,gBAAe;AAE3C,OAAO,MAAMC,mBAAmB,CAC9BC,QACAC,KACAC,MACAC,aACAC,YACAC,SACAC;IAEA,MAAMC,OAAO,OACXC,MACAC,QAAiB,KAAK,EACtBC,QAAgB,CAAC,EACjBC,QACAC,gBACAC;QAOA,MAAMC,UAAUb,IAAIa,OAAO;QAE3B,IAAIX,aAAa;YACfW,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,+BAA+B,EAAEZ,WAAW,SAAS,EAAEK,QAAQE,SAAS,CAAC,UAAU,EAAEA,QAAQ,GAAG,IAAI;QAEzG;QAEA,IAAI;YACF,sBAAsB;YACtB,IAAIM;YACJ,IAAI;gBACFA,aAAaC,KAAKC,KAAK,CAACX;gBAExB,MAAMY,oBAAoBzB,2BAA2BmB,QAAQO,MAAM,EAAEjB;gBACrEa,aAAarB,mBAAmBqB,YAAYG;gBAE5C,IAAIjB,aAAa;oBACfW,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,8BAA8B,EAAEZ,WAAW,EAAE,EAAEc,KAAKI,SAAS,CAACL,aAAa;gBAEhF;YACF,EAAE,OAAOM,aAAa;gBACpBT,QAAQC,MAAM,CAACS,KAAK,CAAC,CAAC,0CAA0C,EAAEhB,MAAM;gBACxE,MAAMiB,WAAW;oBACfC,SAAS;wBAAC;4BA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AI;YAC5GE,aAAaZ,mBAAmBL,KAAK;QACvC,GACA,OAAOkB;YACL,MAAM,EAAErD,KAAK,EAAED,KAAK,EAAEG,cAAc,EAAED,MAAM,EAAEE,MAAM,EAAE,GAAGmD,MAAM,GAAGD;YAClE,MAAMvD,OAAOU,KAAKI,SAAS,CAAC0C;YAC5B,OAAO,MAAMzD,KACXC,MACAC,OACAC,OACAC,QACAC,gBACAC;QAEJ;IAEJ;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/job/create.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/job/create.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAuH7C,eAAO,MAAM,SAAS,QACf,cAAc,eACN,OAAO,WACX,MAAM,WACN,MAAM,WACN,MAAM,GAAG,UAAU,WACnB,MAAM,eACF,MAAM,eACN,GAAG,gBACF,GAAG,WACR,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;;;;;EA4I7B,CAAA;AAwED,eAAO,MAAM,aAAa,WAChB,SAAS,OACZ,cAAc,eACN,OAAO,WACX,MAAM,SAqEhB,CAAA"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
|
2
2
|
import { join } from 'path';
|
|
3
|
+
import { toCamelCase } from '../../../utils/camelCase.js';
|
|
3
4
|
import { validatePayloadFile } from '../../helpers/fileValidation.js';
|
|
4
5
|
import { toolSchemas } from '../schemas.js';
|
|
5
6
|
const createOrUpdateJobFile = (req, verboseLogs, jobsDir, jobName, jobType, jobSlug, camelCaseJobSlug)=>{
|
|
@@ -206,7 +207,7 @@ ${jobContent}
|
|
|
206
207
|
}
|
|
207
208
|
};
|
|
208
209
|
// Helper function to generate task content
|
|
209
|
-
function generateTaskContent(
|
|
210
|
+
function generateTaskContent(_jobName, jobSlug, description, inputSchema, outputSchema, _jobData) {
|
|
210
211
|
const camelCaseJobSlug = toCamelCase(jobSlug);
|
|
211
212
|
return `import type { Task } from 'payload'
|
|
212
213
|
|
|
@@ -233,7 +234,7 @@ export const ${camelCaseJobSlug}Task: Task = {
|
|
|
233
234
|
`;
|
|
234
235
|
}
|
|
235
236
|
// Helper function to generate workflow content
|
|
236
|
-
function generateWorkflowContent(
|
|
237
|
+
function generateWorkflowContent(_jobName, jobSlug, description, inputSchema, outputSchema, _jobData) {
|
|
237
238
|
const camelCaseJobSlug = toCamelCase(jobSlug);
|
|
238
239
|
return `import type { Workflow } from 'payload'
|
|
239
240
|
|
|
@@ -257,10 +258,6 @@ export const ${camelCaseJobSlug}Workflow: Workflow = {
|
|
|
257
258
|
}
|
|
258
259
|
`;
|
|
259
260
|
}
|
|
260
|
-
// Helper function to convert to camel case
|
|
261
|
-
function toCamelCase(str) {
|
|
262
|
-
return str.replace(/[-_\s]+(.)?/g, (_, chr)=>chr ? chr.toUpperCase() : '').replace(/^(.)/, (_, chr)=>chr.toLowerCase());
|
|
263
|
-
}
|
|
264
261
|
export const createJobTool = (server, req, verboseLogs, jobsDir)=>{
|
|
265
262
|
const tool = async (jobName, jobType, jobSlug, description, inputSchema = {}, outputSchema = {}, jobData = {})=>{
|
|
266
263
|
if (verboseLogs) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/tools/job/create.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { PayloadRequest } from 'payload'\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'\nimport { join } from 'path'\n\nimport { validatePayloadFile } from '../../helpers/fileValidation.js'\nimport { toolSchemas } from '../schemas.js'\n\nconst createOrUpdateJobFile = (\n req: PayloadRequest,\n verboseLogs: boolean,\n jobsDir: string,\n jobName: string,\n jobType: 'task' | 'workflow',\n jobSlug: string,\n camelCaseJobSlug: string,\n) => {\n const payload = req.payload\n const jobFilePath = join(jobsDir, `${jobName}.ts`)\n const importName = `${camelCaseJobSlug}${jobType === 'task' ? 'Task' : 'Workflow'}`\n const importPath = `./${jobType === 'task' ? 'tasks' : 'workflows'}/${camelCaseJobSlug}`\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Processing job file: ${jobFilePath}`)\n }\n\n if (existsSync(jobFilePath)) {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Updating existing job file: ${jobFilePath}`)\n }\n\n // Update existing job file\n let content = readFileSync(jobFilePath, 'utf8')\n\n // Add import if not already present\n const importStatement = `import { ${importName} } from '${importPath}'`\n if (!content.includes(importStatement)) {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Adding import: ${importStatement}`)\n }\n\n // Find the last import statement and add after it\n const importRegex = /import\\s+(?:\\S.*)?from\\s+['\"].*['\"];?\\s*\\n/g\n let lastImportMatch\n let match\n while ((match = importRegex.exec(content)) !== null) {\n lastImportMatch = match\n }\n\n if (lastImportMatch) {\n const insertIndex = lastImportMatch.index + lastImportMatch[0].length\n content =\n content.slice(0, insertIndex) + importStatement + '\\n' + content.slice(insertIndex)\n } else {\n // No imports found, add at the beginning\n content = importStatement + '\\n\\n' + content\n }\n }\n\n // Add to the appropriate array\n const arrayName = jobType === 'task' ? 'tasks' : 'workflows'\n const arrayRegex = new RegExp(`(${arrayName}:\\\\s*\\\\[)([^\\\\]]*)(\\\\])`, 's')\n const arrayMatch = content.match(arrayRegex)\n\n if (arrayMatch && arrayMatch[2]) {\n const existingItems = arrayMatch[2].trim()\n const newItem = existingItems ? `${existingItems},\\n ${importName}` : `\\n ${importName}`\n content = content.replace(arrayRegex, `$1${newItem}\\n $3`)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Added ${importName} to ${arrayName} array`)\n }\n } else {\n // Array doesn't exist, add it\n const jobsConfigRegex = /(export\\s+const\\s.*JobsConfig\\s*=\\s*\\{)([^}]*)(\\})/s\n const jobsConfigMatch = content.match(jobsConfigRegex)\n\n if (jobsConfigMatch && jobsConfigMatch[2]) {\n const existingConfig = jobsConfigMatch[2].trim()\n const newConfig = existingConfig\n ? `${existingConfig},\\n ${arrayName}: [\\n ${importName}\\n ]`\n : `\\n ${arrayName}: [\\n ${importName}\\n ]`\n content = content.replace(jobsConfigRegex, `$1${newConfig}\\n$3`)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Created new ${arrayName} array with ${importName}`)\n }\n }\n }\n\n writeFileSync(jobFilePath, content)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully updated job file: ${jobFilePath}`)\n }\n } else {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Creating new job file: ${jobFilePath}`)\n }\n\n // Create new job file\n const camelCaseJobName = toCamelCase(jobName)\n const jobFileContent = `import type { JobsConfig } from 'payload'\nimport { ${importName} } from '${importPath}'\n\nexport const ${camelCaseJobName}JobsConfig: JobsConfig = {\n ${jobType === 'task' ? 'tasks' : 'workflows'}: [\n ${importName}\n ]\n}\n`\n writeFileSync(jobFilePath, jobFileContent)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully created new job file: ${jobFilePath}`)\n }\n }\n}\n\n// Reusable function for creating jobs\nexport const createJob = async (\n req: PayloadRequest,\n verboseLogs: boolean,\n jobsDir: string,\n jobName: string,\n jobType: 'task' | 'workflow',\n jobSlug: string,\n description: string,\n inputSchema: any,\n outputSchema: any,\n jobData: Record<string, any>,\n) => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Creating ${jobType}: ${jobName}`)\n }\n\n try {\n // Ensure jobs directory exists\n if (!existsSync(jobsDir)) {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Creating jobs directory: ${jobsDir}`)\n }\n mkdirSync(jobsDir, { recursive: true })\n }\n\n // Ensure subdirectories exist\n const tasksDir = join(jobsDir, 'tasks')\n const workflowsDir = join(jobsDir, 'workflows')\n\n if (!existsSync(tasksDir)) {\n mkdirSync(tasksDir, { recursive: true })\n }\n if (!existsSync(workflowsDir)) {\n mkdirSync(workflowsDir, { recursive: true })\n }\n\n const camelCaseJobSlug = toCamelCase(jobSlug)\n const targetDir = jobType === 'task' ? tasksDir : workflowsDir\n const fileName = `${camelCaseJobSlug}.ts`\n const filePath = join(targetDir, fileName)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Target file path: ${filePath}`)\n }\n\n // Security check: ensure we're working with the jobs directory\n if (!filePath.startsWith(jobsDir)) {\n payload.logger.error(`[payload-mcp] Invalid job path attempted: ${filePath}`)\n return {\n content: [\n {\n type: 'text' as const,\n text: '❌ **Error**: Invalid job path',\n },\n ],\n }\n }\n\n // Check if file already exists\n if (existsSync(filePath)) {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Job file already exists: ${fileName}`)\n }\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error**: Job file already exists: ${fileName}`,\n },\n ],\n }\n }\n\n // Generate job content based on type\n let jobContent: string\n if (jobType === 'task') {\n jobContent = generateTaskContent(\n jobName,\n jobSlug,\n description,\n inputSchema,\n outputSchema,\n jobData,\n )\n } else {\n jobContent = generateWorkflowContent(\n jobName,\n jobSlug,\n description,\n inputSchema,\n outputSchema,\n jobData,\n )\n }\n\n // Write the job file\n writeFileSync(filePath, jobContent, 'utf8')\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully created job file: ${filePath}`)\n }\n\n // Update the main job file\n createOrUpdateJobFile(req, verboseLogs, jobsDir, jobName, jobType, jobSlug, camelCaseJobSlug)\n\n // Validate the generated file\n const validationResult = await validatePayloadFile(fileName, jobType)\n if (validationResult.error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error**: Generated job has validation issues:\\n\\n${validationResult.error}`,\n },\n ],\n }\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `✅ **Job created successfully!**\n\n**File**: \\`${fileName}\\`\n**Type**: \\`${jobType}\\`\n**Slug**: \\`${jobSlug}\\`\n**Description**: ${description}\n\n**Generated Job Code:**\n\\`\\`\\`typescript\n${jobContent}\n\\`\\`\\``,\n },\n ],\n }\n } catch (error) {\n const errorMessage = (error as Error).message\n payload.logger.error(`[payload-mcp] Error creating job: ${errorMessage}`)\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error creating job**: ${errorMessage}`,\n },\n ],\n }\n }\n}\n\n// Helper function to generate task content\nfunction generateTaskContent(\n jobName: string,\n jobSlug: string,\n description: string,\n inputSchema: any,\n outputSchema: any,\n jobData: Record<string, any>,\n): string {\n const camelCaseJobSlug = toCamelCase(jobSlug)\n\n return `import type { Task } from 'payload'\n\nexport const ${camelCaseJobSlug}Task: Task = {\n slug: '${jobSlug}',\n description: '${description}',\n inputSchema: ${JSON.stringify(inputSchema, null, 2)},\n outputSchema: ${JSON.stringify(outputSchema, null, 2)},\n handler: async (input, context) => {\n // TODO: Implement your task logic here\n // Access input data: input.fieldName\n // Access context: context.payload, context.req, etc.\n\n // Example implementation:\n const result = {\n message: 'Task executed successfully',\n input,\n timestamp: new Date().toISOString(),\n }\n\n return result\n },\n}\n`\n}\n\n// Helper function to generate workflow content\nfunction generateWorkflowContent(\n jobName: string,\n jobSlug: string,\n description: string,\n inputSchema: any,\n outputSchema: any,\n jobData: Record<string, any>,\n): string {\n const camelCaseJobSlug = toCamelCase(jobSlug)\n\n return `import type { Workflow } from 'payload'\n\nexport const ${camelCaseJobSlug}Workflow: Workflow = {\n slug: '${jobSlug}',\n description: '${description}',\n inputSchema: ${JSON.stringify(inputSchema, null, 2)},\n outputSchema: ${JSON.stringify(outputSchema, null, 2)},\n steps: [\n // TODO: Define your workflow steps here\n // Each step should be a function that returns a result\n // Example:\n // {\n // name: 'step1',\n // handler: async (input, context) => {\n // // Step logic here\n // return { result: 'step1 completed' }\n // }\n // }\n ],\n}\n`\n}\n\n// Helper function to convert to camel case\nfunction toCamelCase(str: string): string {\n return str\n .replace(/[-_\\s]+(.)?/g, (_, chr) => (chr ? chr.toUpperCase() : ''))\n .replace(/^(.)/, (_, chr) => chr.toLowerCase())\n}\n\nexport const createJobTool = (\n server: McpServer,\n req: PayloadRequest,\n verboseLogs: boolean,\n jobsDir: string,\n) => {\n const tool = async (\n jobName: string,\n jobType: 'task' | 'workflow',\n jobSlug: string,\n description: string,\n inputSchema: any = {},\n outputSchema: any = {},\n jobData: Record<string, any> = {},\n ) => {\n if (verboseLogs) {\n req.payload.logger.info(\n `[payload-mcp] Create Job Tool called with: ${jobName}, ${jobType}, ${jobSlug}`,\n )\n }\n\n try {\n const result = await createJob(\n req,\n verboseLogs,\n jobsDir,\n jobName,\n jobType,\n jobSlug,\n description,\n inputSchema,\n outputSchema,\n jobData,\n )\n\n if (verboseLogs) {\n req.payload.logger.info(`[payload-mcp] Create Job Tool completed successfully`)\n }\n\n return result\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n req.payload.logger.error(`[payload-mcp] Error in Create Job Tool: ${errorMessage}`)\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error in Create Job Tool**: ${errorMessage}`,\n },\n ],\n }\n }\n }\n\n server.registerTool(\n 'createJob',\n {\n description: 'Creates a new Payload job (task or workflow) with specified configuration',\n inputSchema: toolSchemas.createJob.parameters.shape,\n },\n async (args) => {\n return tool(\n args.jobName,\n args.jobType,\n args.jobSlug,\n args.description,\n args.inputSchema,\n args.outputSchema,\n args.jobData,\n )\n },\n )\n}\n"],"names":["existsSync","mkdirSync","readFileSync","writeFileSync","join","validatePayloadFile","toolSchemas","createOrUpdateJobFile","req","verboseLogs","jobsDir","jobName","jobType","jobSlug","camelCaseJobSlug","payload","jobFilePath","importName","importPath","logger","info","content","importStatement","includes","importRegex","lastImportMatch","match","exec","insertIndex","index","length","slice","arrayName","arrayRegex","RegExp","arrayMatch","existingItems","trim","newItem","replace","jobsConfigRegex","jobsConfigMatch","existingConfig","newConfig","camelCaseJobName","toCamelCase","jobFileContent","createJob","description","inputSchema","outputSchema","jobData","recursive","tasksDir","workflowsDir","targetDir","fileName","filePath","startsWith","error","type","text","jobContent","generateTaskContent","generateWorkflowContent","validationResult","errorMessage","message","JSON","stringify","str","_","chr","toUpperCase","toLowerCase","createJobTool","server","tool","result","Error","registerTool","parameters","shape","args"],"mappings":"AAGA,SAASA,UAAU,EAAEC,SAAS,EAAEC,YAAY,EAAEC,aAAa,QAAQ,KAAI;AACvE,SAASC,IAAI,QAAQ,OAAM;AAE3B,SAASC,mBAAmB,QAAQ,kCAAiC;AACrE,SAASC,WAAW,QAAQ,gBAAe;AAE3C,MAAMC,wBAAwB,CAC5BC,KACAC,aACAC,SACAC,SACAC,SACAC,SACAC;IAEA,MAAMC,UAAUP,IAAIO,OAAO;IAC3B,MAAMC,cAAcZ,KAAKM,SAAS,GAAGC,QAAQ,GAAG,CAAC;IACjD,MAAMM,aAAa,GAAGH,mBAAmBF,YAAY,SAAS,SAAS,YAAY;IACnF,MAAMM,aAAa,CAAC,EAAE,EAAEN,YAAY,SAAS,UAAU,YAAY,CAAC,EAAEE,kBAAkB;IAExF,IAAIL,aAAa;QACfM,QAAQI,MAAM,CAACC,IAAI,CAAC,CAAC,mCAAmC,EAAEJ,aAAa;IACzE;IAEA,IAAIhB,WAAWgB,cAAc;QAC3B,IAAIP,aAAa;YACfM,QAAQI,MAAM,CAACC,IAAI,CAAC,CAAC,0CAA0C,EAAEJ,aAAa;QAChF;QAEA,2BAA2B;QAC3B,IAAIK,UAAUnB,aAAac,aAAa;QAExC,oCAAoC;QACpC,MAAMM,kBAAkB,CAAC,SAAS,EAAEL,WAAW,SAAS,EAAEC,WAAW,CAAC,CAAC;QACvE,IAAI,CAAC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AChF;YAEA,OAAO0D;QACT,EAAE,OAAOnB,OAAO;YACd,MAAMO,eAAeP,iBAAiBoB,QAAQpB,MAAMQ,OAAO,GAAG;YAC9D3D,IAAIO,OAAO,CAACI,MAAM,CAACwC,KAAK,CAAC,CAAC,wCAAwC,EAAEO,cAAc;YAElF,OAAO;gBACL7C,SAAS;oBACP;wBACEuC,MAAM;wBACNC,MAAM,CAAC,gCAAgC,EAAEK,cAAc;oBACzD;iBACD;YACH;QACF;IACF;IAEAU,OAAOI,YAAY,CACjB,aACA;QACEhC,aAAa;QACbC,aAAa3C,YAAYyC,SAAS,CAACkC,UAAU,CAACC,KAAK;IACrD,GACA,OAAOC;QACL,OAAON,KACLM,KAAKxE,OAAO,EACZwE,KAAKvE,OAAO,EACZuE,KAAKtE,OAAO,EACZsE,KAAKnC,WAAW,EAChBmC,KAAKlC,WAAW,EAChBkC,KAAKjC,YAAY,EACjBiC,KAAKhC,OAAO;IAEhB;AAEJ,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/tools/job/create.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { PayloadRequest } from 'payload'\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'\nimport { join } from 'path'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { validatePayloadFile } from '../../helpers/fileValidation.js'\nimport { toolSchemas } from '../schemas.js'\n\nconst createOrUpdateJobFile = (\n req: PayloadRequest,\n verboseLogs: boolean,\n jobsDir: string,\n jobName: string,\n jobType: 'task' | 'workflow',\n jobSlug: string,\n camelCaseJobSlug: string,\n) => {\n const payload = req.payload\n const jobFilePath = join(jobsDir, `${jobName}.ts`)\n const importName = `${camelCaseJobSlug}${jobType === 'task' ? 'Task' : 'Workflow'}`\n const importPath = `./${jobType === 'task' ? 'tasks' : 'workflows'}/${camelCaseJobSlug}`\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Processing job file: ${jobFilePath}`)\n }\n\n if (existsSync(jobFilePath)) {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Updating existing job file: ${jobFilePath}`)\n }\n\n // Update existing job file\n let content = readFileSync(jobFilePath, 'utf8')\n\n // Add import if not already present\n const importStatement = `import { ${importName} } from '${importPath}'`\n if (!content.includes(importStatement)) {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Adding import: ${importStatement}`)\n }\n\n // Find the last import statement and add after it\n const importRegex = /import\\s+(?:\\S.*)?from\\s+['\"].*['\"];?\\s*\\n/g\n let lastImportMatch\n let match\n while ((match = importRegex.exec(content)) !== null) {\n lastImportMatch = match\n }\n\n if (lastImportMatch) {\n const insertIndex = lastImportMatch.index + lastImportMatch[0].length\n content =\n content.slice(0, insertIndex) + importStatement + '\\n' + content.slice(insertIndex)\n } else {\n // No imports found, add at the beginning\n content = importStatement + '\\n\\n' + content\n }\n }\n\n // Add to the appropriate array\n const arrayName = jobType === 'task' ? 'tasks' : 'workflows'\n const arrayRegex = new RegExp(`(${arrayName}:\\\\s*\\\\[)([^\\\\]]*)(\\\\])`, 's')\n const arrayMatch = content.match(arrayRegex)\n\n if (arrayMatch && arrayMatch[2]) {\n const existingItems = arrayMatch[2].trim()\n const newItem = existingItems ? `${existingItems},\\n ${importName}` : `\\n ${importName}`\n content = content.replace(arrayRegex, `$1${newItem}\\n $3`)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Added ${importName} to ${arrayName} array`)\n }\n } else {\n // Array doesn't exist, add it\n const jobsConfigRegex = /(export\\s+const\\s.*JobsConfig\\s*=\\s*\\{)([^}]*)(\\})/s\n const jobsConfigMatch = content.match(jobsConfigRegex)\n\n if (jobsConfigMatch && jobsConfigMatch[2]) {\n const existingConfig = jobsConfigMatch[2].trim()\n const newConfig = existingConfig\n ? `${existingConfig},\\n ${arrayName}: [\\n ${importName}\\n ]`\n : `\\n ${arrayName}: [\\n ${importName}\\n ]`\n content = content.replace(jobsConfigRegex, `$1${newConfig}\\n$3`)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Created new ${arrayName} array with ${importName}`)\n }\n }\n }\n\n writeFileSync(jobFilePath, content)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully updated job file: ${jobFilePath}`)\n }\n } else {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Creating new job file: ${jobFilePath}`)\n }\n\n // Create new job file\n const camelCaseJobName = toCamelCase(jobName)\n const jobFileContent = `import type { JobsConfig } from 'payload'\nimport { ${importName} } from '${importPath}'\n\nexport const ${camelCaseJobName}JobsConfig: JobsConfig = {\n ${jobType === 'task' ? 'tasks' : 'workflows'}: [\n ${importName}\n ]\n}\n`\n writeFileSync(jobFilePath, jobFileContent)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully created new job file: ${jobFilePath}`)\n }\n }\n}\n\n// Reusable function for creating jobs\nexport const createJob = async (\n req: PayloadRequest,\n verboseLogs: boolean,\n jobsDir: string,\n jobName: string,\n jobType: 'task' | 'workflow',\n jobSlug: string,\n description: string,\n inputSchema: any,\n outputSchema: any,\n jobData: Record<string, any>,\n) => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Creating ${jobType}: ${jobName}`)\n }\n\n try {\n // Ensure jobs directory exists\n if (!existsSync(jobsDir)) {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Creating jobs directory: ${jobsDir}`)\n }\n mkdirSync(jobsDir, { recursive: true })\n }\n\n // Ensure subdirectories exist\n const tasksDir = join(jobsDir, 'tasks')\n const workflowsDir = join(jobsDir, 'workflows')\n\n if (!existsSync(tasksDir)) {\n mkdirSync(tasksDir, { recursive: true })\n }\n if (!existsSync(workflowsDir)) {\n mkdirSync(workflowsDir, { recursive: true })\n }\n\n const camelCaseJobSlug = toCamelCase(jobSlug)\n const targetDir = jobType === 'task' ? tasksDir : workflowsDir\n const fileName = `${camelCaseJobSlug}.ts`\n const filePath = join(targetDir, fileName)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Target file path: ${filePath}`)\n }\n\n // Security check: ensure we're working with the jobs directory\n if (!filePath.startsWith(jobsDir)) {\n payload.logger.error(`[payload-mcp] Invalid job path attempted: ${filePath}`)\n return {\n content: [\n {\n type: 'text' as const,\n text: '❌ **Error**: Invalid job path',\n },\n ],\n }\n }\n\n // Check if file already exists\n if (existsSync(filePath)) {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Job file already exists: ${fileName}`)\n }\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error**: Job file already exists: ${fileName}`,\n },\n ],\n }\n }\n\n // Generate job content based on type\n let jobContent: string\n if (jobType === 'task') {\n jobContent = generateTaskContent(\n jobName,\n jobSlug,\n description,\n inputSchema,\n outputSchema,\n jobData,\n )\n } else {\n jobContent = generateWorkflowContent(\n jobName,\n jobSlug,\n description,\n inputSchema,\n outputSchema,\n jobData,\n )\n }\n\n // Write the job file\n writeFileSync(filePath, jobContent, 'utf8')\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully created job file: ${filePath}`)\n }\n\n // Update the main job file\n createOrUpdateJobFile(req, verboseLogs, jobsDir, jobName, jobType, jobSlug, camelCaseJobSlug)\n\n // Validate the generated file\n const validationResult = await validatePayloadFile(fileName, jobType)\n if (validationResult.error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error**: Generated job has validation issues:\\n\\n${validationResult.error}`,\n },\n ],\n }\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `✅ **Job created successfully!**\n\n**File**: \\`${fileName}\\`\n**Type**: \\`${jobType}\\`\n**Slug**: \\`${jobSlug}\\`\n**Description**: ${description}\n\n**Generated Job Code:**\n\\`\\`\\`typescript\n${jobContent}\n\\`\\`\\``,\n },\n ],\n }\n } catch (error) {\n const errorMessage = (error as Error).message\n payload.logger.error(`[payload-mcp] Error creating job: ${errorMessage}`)\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error creating job**: ${errorMessage}`,\n },\n ],\n }\n }\n}\n\n// Helper function to generate task content\nfunction generateTaskContent(\n _jobName: string,\n jobSlug: string,\n description: string,\n inputSchema: any,\n outputSchema: any,\n _jobData: Record<string, any>,\n): string {\n const camelCaseJobSlug = toCamelCase(jobSlug)\n\n return `import type { Task } from 'payload'\n\nexport const ${camelCaseJobSlug}Task: Task = {\n slug: '${jobSlug}',\n description: '${description}',\n inputSchema: ${JSON.stringify(inputSchema, null, 2)},\n outputSchema: ${JSON.stringify(outputSchema, null, 2)},\n handler: async (input, context) => {\n // TODO: Implement your task logic here\n // Access input data: input.fieldName\n // Access context: context.payload, context.req, etc.\n\n // Example implementation:\n const result = {\n message: 'Task executed successfully',\n input,\n timestamp: new Date().toISOString(),\n }\n\n return result\n },\n}\n`\n}\n\n// Helper function to generate workflow content\nfunction generateWorkflowContent(\n _jobName: string,\n jobSlug: string,\n description: string,\n inputSchema: any,\n outputSchema: any,\n _jobData: Record<string, any>,\n): string {\n const camelCaseJobSlug = toCamelCase(jobSlug)\n\n return `import type { Workflow } from 'payload'\n\nexport const ${camelCaseJobSlug}Workflow: Workflow = {\n slug: '${jobSlug}',\n description: '${description}',\n inputSchema: ${JSON.stringify(inputSchema, null, 2)},\n outputSchema: ${JSON.stringify(outputSchema, null, 2)},\n steps: [\n // TODO: Define your workflow steps here\n // Each step should be a function that returns a result\n // Example:\n // {\n // name: 'step1',\n // handler: async (input, context) => {\n // // Step logic here\n // return { result: 'step1 completed' }\n // }\n // }\n ],\n}\n`\n}\n\nexport const createJobTool = (\n server: McpServer,\n req: PayloadRequest,\n verboseLogs: boolean,\n jobsDir: string,\n) => {\n const tool = async (\n jobName: string,\n jobType: 'task' | 'workflow',\n jobSlug: string,\n description: string,\n inputSchema: any = {},\n outputSchema: any = {},\n jobData: Record<string, any> = {},\n ) => {\n if (verboseLogs) {\n req.payload.logger.info(\n `[payload-mcp] Create Job Tool called with: ${jobName}, ${jobType}, ${jobSlug}`,\n )\n }\n\n try {\n const result = await createJob(\n req,\n verboseLogs,\n jobsDir,\n jobName,\n jobType,\n jobSlug,\n description,\n inputSchema,\n outputSchema,\n jobData,\n )\n\n if (verboseLogs) {\n req.payload.logger.info(`[payload-mcp] Create Job Tool completed successfully`)\n }\n\n return result\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n req.payload.logger.error(`[payload-mcp] Error in Create Job Tool: ${errorMessage}`)\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error in Create Job Tool**: ${errorMessage}`,\n },\n ],\n }\n }\n }\n\n server.registerTool(\n 'createJob',\n {\n description: 'Creates a new Payload job (task or workflow) with specified configuration',\n inputSchema: toolSchemas.createJob.parameters.shape,\n },\n async (args) => {\n return tool(\n args.jobName,\n args.jobType,\n args.jobSlug,\n args.description,\n args.inputSchema,\n args.outputSchema,\n args.jobData,\n )\n },\n )\n}\n"],"names":["existsSync","mkdirSync","readFileSync","writeFileSync","join","toCamelCase","validatePayloadFile","toolSchemas","createOrUpdateJobFile","req","verboseLogs","jobsDir","jobName","jobType","jobSlug","camelCaseJobSlug","payload","jobFilePath","importName","importPath","logger","info","content","importStatement","includes","importRegex","lastImportMatch","match","exec","insertIndex","index","length","slice","arrayName","arrayRegex","RegExp","arrayMatch","existingItems","trim","newItem","replace","jobsConfigRegex","jobsConfigMatch","existingConfig","newConfig","camelCaseJobName","jobFileContent","createJob","description","inputSchema","outputSchema","jobData","recursive","tasksDir","workflowsDir","targetDir","fileName","filePath","startsWith","error","type","text","jobContent","generateTaskContent","generateWorkflowContent","validationResult","errorMessage","message","_jobName","_jobData","JSON","stringify","createJobTool","server","tool","result","Error","registerTool","parameters","shape","args"],"mappings":"AAGA,SAASA,UAAU,EAAEC,SAAS,EAAEC,YAAY,EAAEC,aAAa,QAAQ,KAAI;AACvE,SAASC,IAAI,QAAQ,OAAM;AAE3B,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,mBAAmB,QAAQ,kCAAiC;AACrE,SAASC,WAAW,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B,CAC3BC,QACAhE,KACAC,aACAC;IAEA,MAAM+D,OAAO,OACX9D,SACAC,SACAC,SACAkC,aACAC,cAAmB,CAAC,CAAC,EACrBC,eAAoB,CAAC,CAAC,EACtBC,UAA+B,CAAC,CAAC;QAEjC,IAAIzC,aAAa;YACfD,IAAIO,OAAO,CAACI,MAAM,CAACC,IAAI,CACrB,CAAC,2CAA2C,EAAET,QAAQ,EAAE,EAAEC,QAAQ,EAAE,EAAEC,SAAS;QAEnF;QAEA,IAAI;YACF,MAAM6D,SAAS,MAAM5B,UACnBtC,KACAC,aACAC,SACAC,SACAC,SACAC,SACAkC,aACAC,aACAC,cACAC;YAGF,IAAIzC,aAAa;gBACfD,IAAIO,OAAO,CAACI,MAAM,CAACC,IAAI,CAAC,CAAC,oDAAoD,CAAC;YAChF;YAEA,OAAOsD;QACT,EAAE,OAAOhB,OAAO;YACd,MAAMO,eAAeP,iBAAiBiB,QAAQjB,MAAMQ,OAAO,GAAG;YAC9D1D,IAAIO,OAAO,CAACI,MAAM,CAACuC,KAAK,CAAC,CAAC,wCAAwC,EAAEO,cAAc;YAElF,OAAO;gBACL5C,SAAS;oBACP;wBACEsC,MAAM;wBACNC,MAAM,CAAC,gCAAgC,EAAEK,cAAc;oBACzD;iBACD;YACH;QACF;IACF;IAEAO,OAAOI,YAAY,CACjB,aACA;QACE7B,aAAa;QACbC,aAAa1C,YAAYwC,SAAS,CAAC+B,UAAU,CAACC,KAAK;IACrD,GACA,OAAOC;QACL,OAAON,KACLM,KAAKpE,OAAO,EACZoE,KAAKnE,OAAO,EACZmE,KAAKlE,OAAO,EACZkE,KAAKhC,WAAW,EAChBgC,KAAK/B,WAAW,EAChB+B,KAAK9B,YAAY,EACjB8B,KAAK7B,OAAO;IAEhB;AAEJ,EAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
2
|
import type { PayloadRequest } from 'payload';
|
|
3
|
-
export declare const runJob: (req: PayloadRequest, verboseLogs: boolean, jobSlug: string, input: Record<string,
|
|
3
|
+
export declare const runJob: (req: PayloadRequest, verboseLogs: boolean, jobSlug: string, input: Record<string, unknown>, queue?: string, priority?: number, delay?: number) => Promise<{
|
|
4
4
|
content: {
|
|
5
5
|
type: "text";
|
|
6
6
|
text: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/job/run.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAK7C,eAAO,MAAM,MAAM,QACZ,cAAc,eACN,OAAO,WACX,MAAM,SACR,MAAM,CAAC,MAAM,EAAE,
|
|
1
|
+
{"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/job/run.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAK7C,eAAO,MAAM,MAAM,QACZ,cAAc,eACN,OAAO,WACX,MAAM,SACR,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,UACtB,MAAM,aACH,MAAM,UACT,MAAM;;;;;EAiIf,CAAA;AAED,eAAO,MAAM,UAAU,WAAY,SAAS,OAAO,cAAc,eAAe,OAAO,SAsBtF,CAAA"}
|
|
@@ -115,35 +115,14 @@ ${JSON.stringify(input, null, 2)}
|
|
|
115
115
|
}
|
|
116
116
|
};
|
|
117
117
|
export const runJobTool = (server, req, verboseLogs)=>{
|
|
118
|
-
const tool = async (jobSlug, input, queue, priority, delay)=>{
|
|
119
|
-
if (verboseLogs) {
|
|
120
|
-
req.payload.logger.info(`[payload-mcp] Run Job Tool called with: ${jobSlug}`);
|
|
121
|
-
}
|
|
122
|
-
try {
|
|
123
|
-
const result = await runJob(req, verboseLogs, jobSlug, input, queue, priority, delay);
|
|
124
|
-
if (verboseLogs) {
|
|
125
|
-
req.payload.logger.info(`[payload-mcp] Run Job Tool completed successfully`);
|
|
126
|
-
}
|
|
127
|
-
return result;
|
|
128
|
-
} catch (error) {
|
|
129
|
-
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
130
|
-
req.payload.logger.error(`[payload-mcp] Error in Run Job Tool: ${errorMessage}`);
|
|
131
|
-
return {
|
|
132
|
-
content: [
|
|
133
|
-
{
|
|
134
|
-
type: 'text',
|
|
135
|
-
text: `❌ **Error in Run Job Tool**: ${errorMessage}`
|
|
136
|
-
}
|
|
137
|
-
]
|
|
138
|
-
};
|
|
139
|
-
}
|
|
140
|
-
};
|
|
141
118
|
server.registerTool('runJob', {
|
|
142
119
|
description: 'Runs a Payload job with specified input data and queue options',
|
|
143
120
|
inputSchema: toolSchemas.runJob.parameters.shape
|
|
144
|
-
}, async (
|
|
145
|
-
|
|
146
|
-
|
|
121
|
+
}, async ({ delay, input, jobSlug, priority, queue })=>{
|
|
122
|
+
if (verboseLogs) {
|
|
123
|
+
req.payload.logger.info(`[payload-mcp] Run Job Tool called with: ${jobSlug}`);
|
|
124
|
+
}
|
|
125
|
+
return runJob(req, verboseLogs, jobSlug, input, queue, priority, delay);
|
|
147
126
|
});
|
|
148
127
|
};
|
|
149
128
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/tools/job/run.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { PayloadRequest } from 'payload'\n\nimport { toolSchemas } from '../schemas.js'\n\n// Reusable function for running jobs\nexport const runJob = async (\n req: PayloadRequest,\n verboseLogs: boolean,\n jobSlug: string,\n input: Record<string,
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/tools/job/run.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { PayloadRequest } from 'payload'\n\nimport { toolSchemas } from '../schemas.js'\n\n// Reusable function for running jobs\nexport const runJob = async (\n req: PayloadRequest,\n verboseLogs: boolean,\n jobSlug: string,\n input: Record<string, unknown>,\n queue?: string,\n priority?: number,\n delay?: number,\n) => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Running job: ${jobSlug}`)\n }\n\n try {\n // Actually run the job using Payload's job queue\n const jobQueueOptions: Record<string, unknown> = {\n input,\n task: jobSlug,\n }\n\n if (queue && queue !== 'default') {\n jobQueueOptions.queue = queue\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Using custom queue: ${queue}`)\n }\n }\n\n if (priority && priority > 0) {\n jobQueueOptions.priority = priority\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Setting job priority: ${priority}`)\n }\n }\n\n if (delay && delay > 0) {\n jobQueueOptions.waitUntil = new Date(Date.now() + delay)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Setting job delay: ${delay}ms`)\n }\n }\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Queuing job with options: ${JSON.stringify(jobQueueOptions)}`,\n )\n }\n\n const job = await payload.jobs.queue(\n jobQueueOptions as Parameters<typeof payload.jobs.queue>[0],\n )\n\n const jobId = (job as { id?: string })?.id || 'unknown'\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Job created successfully: ${jobId}`)\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `# Job Queued Successfully: ${jobSlug}\n\n## Job Details\n- **Job ID**: ${jobId}\n- **Job Slug**: ${jobSlug}\n- **Queue**: ${queue || 'default'}\n- **Priority**: ${priority || 'default'}\n- **Delay**: ${delay ? `${delay}ms` : 'none'}\n- **Status**: Queued and Running\n\n## Input Data\n\\`\\`\\`json\n${JSON.stringify(input, null, 2)}\n\\`\\`\\`\n\n## Job Status\nThe job has been successfully queued and will be processed according to the queue settings.\n\n## Monitoring the Job\nYou can monitor the job status using:\n\n\\`\\`\\`typescript\n// Check job status\nconst jobStatus = await payload.jobs.status('${jobId}')\nconsole.log('Job status:', jobStatus)\n\n// Wait for completion\nconst result = await payload.jobs.wait('${jobId}')\nconsole.log('Job result:', result)\n\\`\\`\\`\n\n✅ Job successfully queued with ID: ${jobId}`,\n },\n ],\n }\n } catch (error) {\n const errorMsg = (error as Error).message\n payload.logger.error(`[payload-mcp] Error running job \"${jobSlug}\": ${errorMsg}`)\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ Error running job \"${jobSlug}\": ${errorMsg}\n\n## Common Issues:\n1. **Job not found**: The job \"${jobSlug}\" may not be registered in your Payload configuration\n2. **Invalid input format**: Ensure the input matches the job's input schema\n3. **Queue not configured**: The queue \"${queue || 'default'}\" may not be properly set up\n4. **Permission issues**: Ensure proper access rights for job execution\n5. **Job handler error**: The job implementation may have errors\n\n## Input Data Provided:\n\\`\\`\\`json\n${JSON.stringify(input, null, 2)}\n\\`\\`\\`\n\n## Next Steps:\n1. **Verify job exists**: Check that the job \"${jobSlug}\" is properly registered\n2. **Check input format**: Ensure the input data matches the expected schema\n3. **Review job configuration**: Verify the job is properly configured in your Payload setup\n4. **Check permissions**: Ensure you have the necessary permissions to run jobs\n5. **Review error logs**: Check the server logs for more detailed error information\n\n## Troubleshooting:\n- **Job not found**: Verify the job slug and check your jobs configuration\n- **Schema mismatch**: Ensure input data matches the job's input schema\n- **Queue issues**: Check that the specified queue is properly configured\n- **Permission errors**: Verify user permissions for job execution`,\n },\n ],\n }\n }\n}\n\nexport const runJobTool = (server: McpServer, req: PayloadRequest, verboseLogs: boolean) => {\n server.registerTool(\n 'runJob',\n {\n description: 'Runs a Payload job with specified input data and queue options',\n inputSchema: toolSchemas.runJob.parameters.shape,\n },\n async ({ delay, input, jobSlug, priority, queue }) => {\n if (verboseLogs) {\n req.payload.logger.info(`[payload-mcp] Run Job Tool called with: ${jobSlug}`)\n }\n return runJob(\n req,\n verboseLogs,\n jobSlug,\n input as Record<string, unknown>,\n queue,\n priority,\n delay,\n )\n },\n )\n}\n"],"names":["toolSchemas","runJob","req","verboseLogs","jobSlug","input","queue","priority","delay","payload","logger","info","jobQueueOptions","task","waitUntil","Date","now","JSON","stringify","job","jobs","jobId","id","content","type","text","error","errorMsg","message","runJobTool","server","registerTool","description","inputSchema","parameters","shape"],"mappings":"AAGA,SAASA,WAAW,QAAQ,gBAAe;AAE3C,qCAAqC;AACrC,OAAO,MAAMC,SAAS,OACpBC,KACAC,aACAC,SACAC,OACAC,OACAC,UACAC;IAEA,MAAMC,UAAUP,IAAIO,OAAO;IAE3B,IAAIN,aAAa;QACfM,QAAQC,MAAM,CAACC,IAAI,CAAC,CAAC,2BAA2B,EAAEP,SAAS;IAC7D;IAEA,IAAI;QACF,iDAAiD;QACjD,MAAMQ,kBAA2C;YAC/CP;YACAQ,MAAMT;QACR;QAEA,IAAIE,SAASA,UAAU,WAAW;YAChCM,gBAAgBN,KAAK,GAAGA;YACxB,IAAIH,aAAa;gBACfM,QAAQC,MAAM,CAACC,IAAI,CAAC,CAAC,kCAAkC,EAAEL,OAAO;YAClE;QACF;QAEA,IAAIC,YAAYA,WAAW,GAAG;YAC5BK,gBAAgBL,QAAQ,GAAGA;YAC3B,IAAIJ,aAAa;gBACfM,QAAQC,MAAM,CAACC,IAAI,CAAC,CAAC,oCAAoC,EAAEJ,UAAU;YACvE;QACF;QAEA,IAAIC,SAASA,QAAQ,GAAG;YACtBI,gBAAgBE,SAAS,GAAG,IAAIC,KAAKA,KAAKC,GAAG,KAAKR;YAClD,IAAIL,aAAa;gBACfM,QAAQC,MAAM,CAACC,IAAI,CAAC,CAAC,iCAAiC,EAAEH,MAAM,EAAE,CAAC;YACnE;QACF;QAEA,IAAIL,aAAa;YACfM,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,wCAAwC,EAAEM,KAAKC,SAAS,CAACN,kBAAkB;QAEhF;QAEA,MAAMO,MAAM,MAAMV,QAAQW,IAAI,CAACd,KAAK,CAClCM;QAGF,MAAMS,QAAQ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OAAO,CAACC,MAAM,CAACC,IAAI,CAAC,CAAC,wCAAwC,EAAEP,SAAS;QAC9E;QACA,OAAOH,OACLC,KACAC,aACAC,SACAC,OACAC,OACAC,UACAC;IAEJ;AAEJ,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/job/update.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAK7C,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAA;
|
|
1
|
+
{"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/job/update.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAK7C,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAA;AAOvF,eAAO,MAAM,SAAS,QACf,cAAc,eACN,OAAO,WACX,MAAM,WACN,MAAM,cACH,MAAM,gBACJ,WAAW,EAAE,iBACZ,WAAW,EAAE,iBACb,gBAAgB,EAAE,iBAClB,eAAe,gBAChB,MAAM;;;;;EAiLrB,CAAA;AAgCD,eAAO,MAAM,aAAa,WAChB,SAAS,OACZ,cAAc,eACN,OAAO,WACX,MAAM,SAqChB,CAAA"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
|
2
2
|
import { join } from 'path';
|
|
3
|
+
import { toCamelCase } from '../../../utils/camelCase.js';
|
|
3
4
|
import { validatePayloadFile } from '../../helpers/fileValidation.js';
|
|
4
5
|
import { toolSchemas } from '../schemas.js';
|
|
5
6
|
// Reusable function for updating jobs
|
|
@@ -153,61 +154,32 @@ export const updateJob = async (req, verboseLogs, jobsDir, jobSlug, updateType,
|
|
|
153
154
|
};
|
|
154
155
|
}
|
|
155
156
|
};
|
|
156
|
-
// Helper function to convert to camel case
|
|
157
|
-
function toCamelCase(str) {
|
|
158
|
-
return str.replace(/[-_\s]+(.)?/g, (_, chr)=>chr ? chr.toUpperCase() : '').replace(/^(.)/, (_, chr)=>chr.toLowerCase());
|
|
159
|
-
}
|
|
160
157
|
// Helper functions for different update types
|
|
161
|
-
function updateSchema(content,
|
|
158
|
+
function updateSchema(content, _camelCaseJobSlug, _inputSchema, _outputSchema) {
|
|
162
159
|
// TODO: Implementation for schema updates
|
|
163
|
-
// This would modify the inputSchema and outputSchema in the job file
|
|
164
160
|
return content;
|
|
165
161
|
}
|
|
166
|
-
function updateWorkflowTasks(content,
|
|
162
|
+
function updateWorkflowTasks(content, _taskSequence) {
|
|
167
163
|
// TODO: Implementation for updating workflow tasks
|
|
168
|
-
// This would modify the steps array in the workflow
|
|
169
164
|
return content;
|
|
170
165
|
}
|
|
171
|
-
function updateConfig(content,
|
|
166
|
+
function updateConfig(content, _jobSlug, _configUpdate) {
|
|
172
167
|
// TODO: Implementation for updating job configuration
|
|
173
|
-
// This would modify various config properties
|
|
174
168
|
return content;
|
|
175
169
|
}
|
|
176
|
-
function updateHandler(content,
|
|
170
|
+
function updateHandler(content, _handlerCode, _jobType) {
|
|
177
171
|
// TODO: Implementation for replacing handler code
|
|
178
|
-
// This would replace the handler function in the job file
|
|
179
172
|
return content;
|
|
180
173
|
}
|
|
181
174
|
export const updateJobTool = (server, req, verboseLogs, jobsDir)=>{
|
|
182
|
-
const tool = async (jobSlug, updateType, inputSchema, outputSchema, taskSequence, configUpdate, handlerCode)=>{
|
|
183
|
-
if (verboseLogs) {
|
|
184
|
-
req.payload.logger.info(`[payload-mcp] Update Job Tool called with: ${jobSlug}, ${updateType}`);
|
|
185
|
-
}
|
|
186
|
-
try {
|
|
187
|
-
const result = await updateJob(req, verboseLogs, jobsDir, jobSlug, updateType, inputSchema, outputSchema, taskSequence, configUpdate, handlerCode);
|
|
188
|
-
if (verboseLogs) {
|
|
189
|
-
req.payload.logger.info(`[payload-mcp] Update Job Tool completed successfully`);
|
|
190
|
-
}
|
|
191
|
-
return result;
|
|
192
|
-
} catch (error) {
|
|
193
|
-
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
194
|
-
req.payload.logger.error(`[payload-mcp] Error in Update Job Tool: ${errorMessage}`);
|
|
195
|
-
return {
|
|
196
|
-
content: [
|
|
197
|
-
{
|
|
198
|
-
type: 'text',
|
|
199
|
-
text: `❌ **Error in Update Job Tool**: ${errorMessage}`
|
|
200
|
-
}
|
|
201
|
-
]
|
|
202
|
-
};
|
|
203
|
-
}
|
|
204
|
-
};
|
|
205
175
|
server.registerTool('updateJob', {
|
|
206
176
|
description: 'Updates an existing Payload job with new configuration, schema, or handler code',
|
|
207
177
|
inputSchema: toolSchemas.updateJob.parameters.shape
|
|
208
|
-
}, async (
|
|
209
|
-
|
|
210
|
-
|
|
178
|
+
}, async ({ configUpdate, handlerCode, inputSchema, jobSlug, outputSchema, taskSequence, updateType })=>{
|
|
179
|
+
if (verboseLogs) {
|
|
180
|
+
req.payload.logger.info(`[payload-mcp] Update Job Tool called with: ${jobSlug}, ${updateType}`);
|
|
181
|
+
}
|
|
182
|
+
return updateJob(req, verboseLogs, jobsDir, jobSlug, updateType, inputSchema, outputSchema, taskSequence, configUpdate, handlerCode);
|
|
211
183
|
});
|
|
212
184
|
};
|
|
213
185
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/tools/job/update.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { PayloadRequest } from 'payload'\n\nimport { existsSync, readFileSync, writeFileSync } from 'fs'\nimport { join } from 'path'\n\nimport type { JobConfigUpdate, SchemaField, TaskSequenceItem } from '../../../types.js'\n\nimport { validatePayloadFile } from '../../helpers/fileValidation.js'\nimport { toolSchemas } from '../schemas.js'\n\n// Reusable function for updating jobs\nexport const updateJob = async (\n req: PayloadRequest,\n verboseLogs: boolean,\n jobsDir: string,\n jobSlug: string,\n updateType: string,\n inputSchema?: SchemaField[],\n outputSchema?: SchemaField[],\n taskSequence?: TaskSequenceItem[],\n configUpdate?: JobConfigUpdate,\n handlerCode?: string,\n) => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Updating job: ${jobSlug} (${updateType})`)\n }\n\n try {\n const camelCaseJobSlug = toCamelCase(jobSlug)\n\n // Find the job file - check both tasks and workflows\n let filePath: null | string = null\n let jobType: 'task' | 'workflow' | null = null\n\n const taskPath = join(jobsDir, 'tasks', `${camelCaseJobSlug}.ts`)\n const workflowPath = join(jobsDir, 'workflows', `${camelCaseJobSlug}.ts`)\n\n if (existsSync(taskPath)) {\n filePath = taskPath\n jobType = 'task'\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Found task file: ${taskPath}`)\n }\n } else if (existsSync(workflowPath)) {\n filePath = workflowPath\n jobType = 'workflow'\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Found workflow file: ${workflowPath}`)\n }\n } else {\n throw new Error(`No task or workflow file found for job slug: ${jobSlug}`)\n }\n\n // Read the current file content\n let content = readFileSync(filePath, 'utf8')\n const originalContent = content\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Applying update type: ${updateType}`)\n }\n\n // Apply updates based on type\n switch (updateType) {\n case 'change_config':\n if (!configUpdate) {\n throw new Error('config must be provided for change_config')\n }\n\n content = updateConfig(content, jobSlug, configUpdate)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Configuration updated successfully`)\n }\n break\n\n case 'modify_schema':\n if (!inputSchema && !outputSchema) {\n throw new Error('Either inputSchema or outputSchema must be provided for modify_schema')\n }\n\n content = updateSchema(content, camelCaseJobSlug, inputSchema, outputSchema)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Schema updated successfully`)\n }\n break\n\n case 'replace_handler':\n if (!handlerCode) {\n throw new Error('handlerCode must be provided for replace_handler')\n }\n\n content = updateHandler(content, handlerCode, jobType)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Handler code replaced successfully`)\n }\n break\n\n case 'update_tasks':\n if (!taskSequence) {\n throw new Error('taskSequence must be provided for update_tasks')\n }\n\n if (jobType !== 'workflow') {\n throw new Error('update_tasks is only supported for workflow jobs')\n }\n\n content = updateWorkflowTasks(content, taskSequence)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Workflow tasks updated successfully`)\n }\n break\n }\n\n // Only write if content changed\n if (content !== originalContent) {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Writing updated content to file`)\n }\n\n // Write the updated content\n writeFileSync(filePath, content)\n\n // Validate the updated file\n const fileName = `${camelCaseJobSlug}.ts`\n const validationType = jobType === 'task' ? 'task' : 'workflow'\n\n try {\n const validationResult = await validatePayloadFile(fileName, validationType)\n\n if (!validationResult.success) {\n if (verboseLogs) {\n payload.logger.warn(`[payload-mcp] Validation warning: ${validationResult.error}`)\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `⚠️ **Warning**: Job updated but validation failed:\\n\\n${validationResult.error}\\n\\nPlease review the generated code for any syntax errors.`,\n },\n ],\n }\n }\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] File validation successful`)\n }\n } catch (validationError) {\n if (verboseLogs) {\n payload.logger.warn(`[payload-mcp] Validation error: ${validationError}`)\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `⚠️ **Warning**: Job updated but validation could not be completed:\\n\\n${validationError}\\n\\nPlease review the generated code manually.`,\n },\n ],\n }\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `✅ **Job updated successfully!**\\n\\n**Job**: \\`${jobSlug}\\`\\n**Type**: \\`${jobType}\\`\\n**Update**: \\`${updateType}\\`\\n**File**: \\`${fileName}\\`\\n\\n**Next steps**:\\n1. Restart your development server to load the updated job\\n2. Test the updated functionality\\n3. Verify the changes meet your requirements`,\n },\n ],\n }\n } else {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] No changes detected, file not modified`)\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `ℹ️ **No changes made**: The job file was not modified as no changes were detected.\\n\\n**Job**: \\`${jobSlug}\\`\\n**Type**: \\`${jobType}\\`\\n**Update**: \\`${updateType}\\``,\n },\n ],\n }\n }\n } catch (error) {\n const errorMessage = (error as Error).message\n payload.logger.error(`[payload-mcp] Error updating job: ${errorMessage}`)\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error updating job**: ${errorMessage}`,\n },\n ],\n }\n }\n}\n\n// Helper function to convert to camel case\nfunction toCamelCase(str: string): string {\n return str\n .replace(/[-_\\s]+(.)?/g, (_, chr) => (chr ? chr.toUpperCase() : ''))\n .replace(/^(.)/, (_, chr) => chr.toLowerCase())\n}\n\n// Helper functions for different update types\nfunction updateSchema(\n content: string,\n camelCaseJobSlug: string,\n inputSchema?: SchemaField[],\n outputSchema?: SchemaField[],\n): string {\n // TODO: Implementation for schema updates\n // This would modify the inputSchema and outputSchema in the job file\n return content\n}\n\nfunction updateWorkflowTasks(content: string, taskSequence: TaskSequenceItem[]): string {\n // TODO: Implementation for updating workflow tasks\n // This would modify the steps array in the workflow\n return content\n}\n\nfunction updateConfig(content: string, jobSlug: string, configUpdate: JobConfigUpdate): string {\n // TODO: Implementation for updating job configuration\n // This would modify various config properties\n return content\n}\n\nfunction updateHandler(content: string, handlerCode: string, jobType: 'task' | 'workflow'): string {\n // TODO: Implementation for replacing handler code\n // This would replace the handler function in the job file\n return content\n}\n\nexport const updateJobTool = (\n server: McpServer,\n req: PayloadRequest,\n verboseLogs: boolean,\n jobsDir: string,\n) => {\n const tool = async (\n jobSlug: string,\n updateType: string,\n inputSchema?: SchemaField[],\n outputSchema?: SchemaField[],\n taskSequence?: TaskSequenceItem[],\n configUpdate?: JobConfigUpdate,\n handlerCode?: string,\n ) => {\n if (verboseLogs) {\n req.payload.logger.info(\n `[payload-mcp] Update Job Tool called with: ${jobSlug}, ${updateType}`,\n )\n }\n\n try {\n const result = await updateJob(\n req,\n verboseLogs,\n jobsDir,\n jobSlug,\n updateType,\n inputSchema,\n outputSchema,\n taskSequence,\n configUpdate,\n handlerCode,\n )\n\n if (verboseLogs) {\n req.payload.logger.info(`[payload-mcp] Update Job Tool completed successfully`)\n }\n\n return result\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n req.payload.logger.error(`[payload-mcp] Error in Update Job Tool: ${errorMessage}`)\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error in Update Job Tool**: ${errorMessage}`,\n },\n ],\n }\n }\n }\n\n server.registerTool(\n 'updateJob',\n {\n description:\n 'Updates an existing Payload job with new configuration, schema, or handler code',\n inputSchema: toolSchemas.updateJob.parameters.shape,\n },\n async (args) => {\n const {\n configUpdate,\n handlerCode,\n inputSchema,\n jobSlug,\n outputSchema,\n taskSequence,\n updateType,\n } = args\n return await tool(\n jobSlug,\n updateType,\n inputSchema as unknown as SchemaField[],\n outputSchema as unknown as SchemaField[],\n taskSequence,\n configUpdate,\n handlerCode,\n )\n },\n )\n}\n"],"names":["existsSync","readFileSync","writeFileSync","join","validatePayloadFile","toolSchemas","updateJob","req","verboseLogs","jobsDir","jobSlug","updateType","inputSchema","outputSchema","taskSequence","configUpdate","handlerCode","payload","logger","info","camelCaseJobSlug","toCamelCase","filePath","jobType","taskPath","workflowPath","Error","content","originalContent","updateConfig","updateSchema","updateHandler","updateWorkflowTasks","fileName","validationType","validationResult","success","warn","error","type","text","validationError","errorMessage","message","str","replace","_","chr","toUpperCase","toLowerCase","updateJobTool","server","tool","result","registerTool","description","parameters","shape","args"],"mappings":"AAGA,SAASA,UAAU,EAAEC,YAAY,EAAEC,aAAa,QAAQ,KAAI;AAC5D,SAASC,IAAI,QAAQ,OAAM;AAI3B,SAASC,mB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O;gBACLf,SAAS;oBACP;wBACEY,MAAM;wBACNC,MAAM,CAAC,gCAAgC,EAAEE,cAAc;oBACzD;iBACD;YACH;QACF;IACF;IAEAS,OAAOG,YAAY,CACjB,aACA;QACEC,aACE;QACF3C,aAAaP,YAAYC,SAAS,CAACkD,UAAU,CAACC,KAAK;IACrD,GACA,OAAOC;QACL,MAAM,EACJ3C,YAAY,EACZC,WAAW,EACXJ,WAAW,EACXF,OAAO,EACPG,YAAY,EACZC,YAAY,EACZH,UAAU,EACX,GAAG+C;QACJ,OAAO,MAAMN,KACX1C,SACAC,YACAC,aACAC,cACAC,cACAC,cACAC;IAEJ;AAEJ,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/tools/job/update.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { PayloadRequest } from 'payload'\n\nimport { existsSync, readFileSync, writeFileSync } from 'fs'\nimport { join } from 'path'\n\nimport type { JobConfigUpdate, SchemaField, TaskSequenceItem } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { validatePayloadFile } from '../../helpers/fileValidation.js'\nimport { toolSchemas } from '../schemas.js'\n\n// Reusable function for updating jobs\nexport const updateJob = async (\n req: PayloadRequest,\n verboseLogs: boolean,\n jobsDir: string,\n jobSlug: string,\n updateType: string,\n inputSchema?: SchemaField[],\n outputSchema?: SchemaField[],\n taskSequence?: TaskSequenceItem[],\n configUpdate?: JobConfigUpdate,\n handlerCode?: string,\n) => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Updating job: ${jobSlug} (${updateType})`)\n }\n\n try {\n const camelCaseJobSlug = toCamelCase(jobSlug)\n\n // Find the job file - check both tasks and workflows\n let filePath: null | string = null\n let jobType: 'task' | 'workflow' | null = null\n\n const taskPath = join(jobsDir, 'tasks', `${camelCaseJobSlug}.ts`)\n const workflowPath = join(jobsDir, 'workflows', `${camelCaseJobSlug}.ts`)\n\n if (existsSync(taskPath)) {\n filePath = taskPath\n jobType = 'task'\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Found task file: ${taskPath}`)\n }\n } else if (existsSync(workflowPath)) {\n filePath = workflowPath\n jobType = 'workflow'\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Found workflow file: ${workflowPath}`)\n }\n } else {\n throw new Error(`No task or workflow file found for job slug: ${jobSlug}`)\n }\n\n // Read the current file content\n let content = readFileSync(filePath, 'utf8')\n const originalContent = content\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Applying update type: ${updateType}`)\n }\n\n // Apply updates based on type\n switch (updateType) {\n case 'change_config':\n if (!configUpdate) {\n throw new Error('config must be provided for change_config')\n }\n\n content = updateConfig(content, jobSlug, configUpdate)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Configuration updated successfully`)\n }\n break\n\n case 'modify_schema':\n if (!inputSchema && !outputSchema) {\n throw new Error('Either inputSchema or outputSchema must be provided for modify_schema')\n }\n\n content = updateSchema(content, camelCaseJobSlug, inputSchema, outputSchema)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Schema updated successfully`)\n }\n break\n\n case 'replace_handler':\n if (!handlerCode) {\n throw new Error('handlerCode must be provided for replace_handler')\n }\n\n content = updateHandler(content, handlerCode, jobType)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Handler code replaced successfully`)\n }\n break\n\n case 'update_tasks':\n if (!taskSequence) {\n throw new Error('taskSequence must be provided for update_tasks')\n }\n\n if (jobType !== 'workflow') {\n throw new Error('update_tasks is only supported for workflow jobs')\n }\n\n content = updateWorkflowTasks(content, taskSequence)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Workflow tasks updated successfully`)\n }\n break\n }\n\n // Only write if content changed\n if (content !== originalContent) {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Writing updated content to file`)\n }\n\n // Write the updated content\n writeFileSync(filePath, content)\n\n // Validate the updated file\n const fileName = `${camelCaseJobSlug}.ts`\n const validationType = jobType === 'task' ? 'task' : 'workflow'\n\n try {\n const validationResult = await validatePayloadFile(fileName, validationType)\n\n if (!validationResult.success) {\n if (verboseLogs) {\n payload.logger.warn(`[payload-mcp] Validation warning: ${validationResult.error}`)\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `⚠️ **Warning**: Job updated but validation failed:\\n\\n${validationResult.error}\\n\\nPlease review the generated code for any syntax errors.`,\n },\n ],\n }\n }\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] File validation successful`)\n }\n } catch (validationError) {\n if (verboseLogs) {\n payload.logger.warn(`[payload-mcp] Validation error: ${validationError}`)\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `⚠️ **Warning**: Job updated but validation could not be completed:\\n\\n${validationError}\\n\\nPlease review the generated code manually.`,\n },\n ],\n }\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `✅ **Job updated successfully!**\\n\\n**Job**: \\`${jobSlug}\\`\\n**Type**: \\`${jobType}\\`\\n**Update**: \\`${updateType}\\`\\n**File**: \\`${fileName}\\`\\n\\n**Next steps**:\\n1. Restart your development server to load the updated job\\n2. Test the updated functionality\\n3. Verify the changes meet your requirements`,\n },\n ],\n }\n } else {\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] No changes detected, file not modified`)\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `ℹ️ **No changes made**: The job file was not modified as no changes were detected.\\n\\n**Job**: \\`${jobSlug}\\`\\n**Type**: \\`${jobType}\\`\\n**Update**: \\`${updateType}\\``,\n },\n ],\n }\n }\n } catch (error) {\n const errorMessage = (error as Error).message\n payload.logger.error(`[payload-mcp] Error updating job: ${errorMessage}`)\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error updating job**: ${errorMessage}`,\n },\n ],\n }\n }\n}\n\n// Helper functions for different update types\nfunction updateSchema(\n content: string,\n _camelCaseJobSlug: string,\n _inputSchema?: SchemaField[],\n _outputSchema?: SchemaField[],\n): string {\n // TODO: Implementation for schema updates\n return content\n}\n\nfunction updateWorkflowTasks(content: string, _taskSequence: TaskSequenceItem[]): string {\n // TODO: Implementation for updating workflow tasks\n return content\n}\n\nfunction updateConfig(content: string, _jobSlug: string, _configUpdate: JobConfigUpdate): string {\n // TODO: Implementation for updating job configuration\n return content\n}\n\nfunction updateHandler(\n content: string,\n _handlerCode: string,\n _jobType: 'task' | 'workflow',\n): string {\n // TODO: Implementation for replacing handler code\n return content\n}\n\nexport const updateJobTool = (\n server: McpServer,\n req: PayloadRequest,\n verboseLogs: boolean,\n jobsDir: string,\n) => {\n server.registerTool(\n 'updateJob',\n {\n description:\n 'Updates an existing Payload job with new configuration, schema, or handler code',\n inputSchema: toolSchemas.updateJob.parameters.shape,\n },\n async ({\n configUpdate,\n handlerCode,\n inputSchema,\n jobSlug,\n outputSchema,\n taskSequence,\n updateType,\n }) => {\n if (verboseLogs) {\n req.payload.logger.info(\n `[payload-mcp] Update Job Tool called with: ${jobSlug}, ${updateType}`,\n )\n }\n return updateJob(\n req,\n verboseLogs,\n jobsDir,\n jobSlug,\n updateType,\n inputSchema as unknown as SchemaField[],\n outputSchema as unknown as SchemaField[],\n taskSequence,\n configUpdate,\n handlerCode,\n )\n },\n )\n}\n"],"names":["existsSync","readFileSync","writeFileSync","join","toCamelCase","validatePayloadFile","toolSchemas","updateJob","req","verboseLogs","jobsDir","jobSlug","updateType","inputSchema","outputSchema","taskSequence","configUpdate","handlerCode","payload","logger","info","camelCaseJobSlug","filePath","jobType","taskPath","workflowPath","Error","content","originalContent","updateConfig","updateSchema","updateHandler","updateWorkflowTasks","fileName","validationType","validationResult","success","warn","error","type","text","validationError","errorMessage","message","_camelCaseJobSlug","_inputSchema","_outputSchema","_taskSequence","_jobSlug","_configUpdate","_handlerCode","_jobType","updateJobTool","server","registerTool","description","parameters","shape"],"mappings":"AAGA,SAASA,UAAU,EAAEC,YAAY,EAAEC,aAAa,QAAQ,KAAI;AAC5D,SAASC,IAAI,QAAQ,OA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ACD;QACH;IACF;AACF,EAAC;AAED,8CAA8C;AAC9C,SAASZ,aACPH,OAAe,EACfiB,iBAAyB,EACzBC,YAA4B,EAC5BC,aAA6B;IAE7B,0CAA0C;IAC1C,OAAOnB;AACT;AAEA,SAASK,oBAAoBL,OAAe,EAAEoB,aAAiC;IAC7E,mDAAmD;IACnD,OAAOpB;AACT;AAEA,SAASE,aAAaF,OAAe,EAAEqB,QAAgB,EAAEC,aAA8B;IACrF,sDAAsD;IACtD,OAAOtB;AACT;AAEA,SAASI,cACPJ,OAAe,EACfuB,YAAoB,EACpBC,QAA6B;IAE7B,kDAAkD;IAClD,OAAOxB;AACT;AAEA,OAAO,MAAMyB,gBAAgB,CAC3BC,QACA7C,KACAC,aACAC;IAEA2C,OAAOC,YAAY,CACjB,aACA;QACEC,aACE;QACF1C,aAAaP,YAAYC,SAAS,CAACiD,UAAU,CAACC,KAAK;IACrD,GACA,OAAO,EACLzC,YAAY,EACZC,WAAW,EACXJ,WAAW,EACXF,OAAO,EACPG,YAAY,EACZC,YAAY,EACZH,UAAU,EACX;QACC,IAAIH,aAAa;YACfD,IAAIU,OAAO,CAACC,MAAM,CAACC,IAAI,CACrB,CAAC,2CAA2C,EAAET,QAAQ,EAAE,EAAEC,YAAY;QAE1E;QACA,OAAOL,UACLC,KACAC,aACAC,SACAC,SACAC,YACAC,aACAC,cACAC,cACAC,cACAC;IAEJ;AAEJ,EAAC"}
|
|
@@ -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;AAU9D,eAAO,MAAM,kBAAkB,WACrB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,UACzC,WAAW,SA2LpB,CAAA"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { toCamelCase } from '../../../utils/camelCase.js';
|
|
3
|
+
import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
|
|
3
4
|
import { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js';
|
|
4
5
|
import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
|
|
5
6
|
import { toolSchemas } from '../schemas.js';
|
|
@@ -16,6 +17,8 @@ export const createResourceTool = (server, req, user, verboseLogs, collectionSlu
|
|
|
16
17
|
parsedData = JSON.parse(data);
|
|
17
18
|
// Transform point fields from object format to tuple array
|
|
18
19
|
parsedData = transformPointDataToPayload(parsedData);
|
|
20
|
+
const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug);
|
|
21
|
+
parsedData = stripVirtualFields(parsedData, virtualFieldNames);
|
|
19
22
|
if (verboseLogs) {
|
|
20
23
|
payload.logger.info(`[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`);
|
|
21
24
|
}
|
|
@@ -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/schemaConversion/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.registerTool(\n `create${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n {\n description: `${collections?.[collectionSlug]?.description || toolSchemas.createResource.description.trim()}`,\n inputSchema: createResourceSchema.shape,\n },\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","registerTool","charAt","toUpperCase","slice","description","createResource","trim","inputSchema","params","fieldData"],"mappings":"AAIA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,4BAA4B,QAAQ,kEAAiE;AAC9G,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,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;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AOoD,YAAY,CACjB,CAAC,MAAM,EAAEhD,eAAeiD,MAAM,CAAC,GAAGC,WAAW,KAAK3D,YAAYS,gBAAgBmD,KAAK,CAAC,IAAI,EACxF;YACEC,aAAa,GAAGnD,aAAa,CAACD,eAAe,EAAEoD,eAAe1D,YAAY2D,cAAc,CAACD,WAAW,CAACE,IAAI,IAAI;YAC7GC,aAAanB,qBAAqBE,KAAK;QACzC,GACA,OAAOkB;YACL,MAAM,EAAEnD,KAAK,EAAEC,KAAK,EAAEE,cAAc,EAAED,MAAM,EAAEE,MAAM,EAAE,GAAGgD,WAAW,GAAGD;YACvE,MAAMpD,OAAOU,KAAKE,SAAS,CAACyC;YAC5B,OAAO,MAAMtD,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 {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/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 const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n parsedData = stripVirtualFields(parsedData, virtualFieldNames)\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.registerTool(\n `create${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n {\n description: `${collections?.[collectionSlug]?.description || toolSchemas.createResource.description.trim()}`,\n inputSchema: createResourceSchema.shape,\n },\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","getCollectionVirtualFieldNames","stripVirtualFields","convertCollectionSchemaToZod","transformPointDataToPayload","toolSchemas","createResourceTool","server","req","user","verboseLogs","collectionSlug","collections","schema","tool","data","depth","draft","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","virtualFieldNames","config","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","registerTool","charAt","toUpperCase","slice","description","createResource","trim","inputSchema","params","fieldData"],"mappings":"AAIA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,4BAA4B,QAAQ,kEAAiE;AAC9G,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,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;gBAExB,2DAA2D;gBAC3DS,aAAapB,4BAA4BoB;gBAEzC,MAAMG,oBAAoB1B,+BAA+BoB,QAAQO,MAAM,EAAEjB;gBACzEa,aAAatB,mBAAmBsB,YAAYG;gBAE5C,IAAIjB,aAAa;oBACfW,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,8BAA8B,EAAEZ,eAAe,EAAE,EAAEc,KAAKI,SAAS,CAACL,aAAa;gBAEpF;YACF,EAAE,OAAOM,aAAa;gBACpBT,QAAQC,MAAM,CAACS,KAAK,CAAC,CAAC,0CAA0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AAEE,MAAM,EAAE,GAAGkD,WAAW,GAAGD;YACvE,MAAMtD,OAAOU,KAAKI,SAAS,CAACyC;YAC5B,OAAO,MAAMxD,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;AAU9D,eAAO,MAAM,kBAAkB,WACrB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,UACzC,WAAW,SAuWpB,CAAA"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { toCamelCase } from '../../../utils/camelCase.js';
|
|
3
|
+
import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
|
|
3
4
|
import { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js';
|
|
4
5
|
import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
|
|
5
6
|
import { toolSchemas } from '../schemas.js';
|
|
@@ -16,6 +17,8 @@ export const updateResourceTool = (server, req, user, verboseLogs, collectionSlu
|
|
|
16
17
|
parsedData = JSON.parse(data);
|
|
17
18
|
// Transform point fields from object format to tuple array
|
|
18
19
|
parsedData = transformPointDataToPayload(parsedData);
|
|
20
|
+
const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug);
|
|
21
|
+
parsedData = stripVirtualFields(parsedData, virtualFieldNames);
|
|
19
22
|
if (verboseLogs) {
|
|
20
23
|
payload.logger.info(`[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`);
|
|
21
24
|
}
|