@payloadcms/plugin-mcp 3.77.0-canary.7 → 3.77.0-internal-debug.98d2e4d

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.
Files changed (119) hide show
  1. package/dist/mcp/getMcpHandler.d.ts.map +1 -1
  2. package/dist/mcp/getMcpHandler.js +8 -4
  3. package/dist/mcp/getMcpHandler.js.map +1 -1
  4. package/dist/mcp/tools/auth/auth.d.ts.map +1 -1
  5. package/dist/mcp/tools/auth/auth.js +4 -1
  6. package/dist/mcp/tools/auth/auth.js.map +1 -1
  7. package/dist/mcp/tools/auth/forgotPassword.d.ts.map +1 -1
  8. package/dist/mcp/tools/auth/forgotPassword.js +4 -1
  9. package/dist/mcp/tools/auth/forgotPassword.js.map +1 -1
  10. package/dist/mcp/tools/auth/login.d.ts.map +1 -1
  11. package/dist/mcp/tools/auth/login.js +4 -1
  12. package/dist/mcp/tools/auth/login.js.map +1 -1
  13. package/dist/mcp/tools/auth/resetPassword.d.ts.map +1 -1
  14. package/dist/mcp/tools/auth/resetPassword.js +4 -1
  15. package/dist/mcp/tools/auth/resetPassword.js.map +1 -1
  16. package/dist/mcp/tools/auth/unlock.d.ts.map +1 -1
  17. package/dist/mcp/tools/auth/unlock.js +4 -1
  18. package/dist/mcp/tools/auth/unlock.js.map +1 -1
  19. package/dist/mcp/tools/auth/verify.d.ts.map +1 -1
  20. package/dist/mcp/tools/auth/verify.js +4 -1
  21. package/dist/mcp/tools/auth/verify.js.map +1 -1
  22. package/dist/mcp/tools/collection/create.d.ts.map +1 -1
  23. package/dist/mcp/tools/collection/create.js +4 -1
  24. package/dist/mcp/tools/collection/create.js.map +1 -1
  25. package/dist/mcp/tools/collection/delete.d.ts.map +1 -1
  26. package/dist/mcp/tools/collection/delete.js +4 -1
  27. package/dist/mcp/tools/collection/delete.js.map +1 -1
  28. package/dist/mcp/tools/collection/find.d.ts.map +1 -1
  29. package/dist/mcp/tools/collection/find.js +4 -1
  30. package/dist/mcp/tools/collection/find.js.map +1 -1
  31. package/dist/mcp/tools/collection/update.d.ts.map +1 -1
  32. package/dist/mcp/tools/collection/update.js +4 -1
  33. package/dist/mcp/tools/collection/update.js.map +1 -1
  34. package/dist/mcp/tools/config/find.d.ts.map +1 -1
  35. package/dist/mcp/tools/config/find.js +4 -1
  36. package/dist/mcp/tools/config/find.js.map +1 -1
  37. package/dist/mcp/tools/config/update.d.ts.map +1 -1
  38. package/dist/mcp/tools/config/update.js +4 -1
  39. package/dist/mcp/tools/config/update.js.map +1 -1
  40. package/dist/mcp/tools/global/find.d.ts.map +1 -1
  41. package/dist/mcp/tools/global/find.js +4 -1
  42. package/dist/mcp/tools/global/find.js.map +1 -1
  43. package/dist/mcp/tools/global/update.d.ts.map +1 -1
  44. package/dist/mcp/tools/global/update.js +5 -2
  45. package/dist/mcp/tools/global/update.js.map +1 -1
  46. package/dist/mcp/tools/job/create.d.ts.map +1 -1
  47. package/dist/mcp/tools/job/create.js +4 -1
  48. package/dist/mcp/tools/job/create.js.map +1 -1
  49. package/dist/mcp/tools/job/run.d.ts.map +1 -1
  50. package/dist/mcp/tools/job/run.js +4 -1
  51. package/dist/mcp/tools/job/run.js.map +1 -1
  52. package/dist/mcp/tools/job/update.d.ts.map +1 -1
  53. package/dist/mcp/tools/job/update.js +4 -1
  54. package/dist/mcp/tools/job/update.js.map +1 -1
  55. package/dist/mcp/tools/resource/create.d.ts.map +1 -1
  56. package/dist/mcp/tools/resource/create.js +5 -2
  57. package/dist/mcp/tools/resource/create.js.map +1 -1
  58. package/dist/mcp/tools/resource/delete.d.ts.map +1 -1
  59. package/dist/mcp/tools/resource/delete.js +4 -1
  60. package/dist/mcp/tools/resource/delete.js.map +1 -1
  61. package/dist/mcp/tools/resource/find.d.ts.map +1 -1
  62. package/dist/mcp/tools/resource/find.js +4 -1
  63. package/dist/mcp/tools/resource/find.js.map +1 -1
  64. package/dist/mcp/tools/resource/update.d.ts.map +1 -1
  65. package/dist/mcp/tools/resource/update.js +5 -2
  66. package/dist/mcp/tools/resource/update.js.map +1 -1
  67. package/dist/types.d.ts +11 -1
  68. package/dist/types.d.ts.map +1 -1
  69. package/dist/types.js.map +1 -1
  70. package/dist/utils/schemaConversion/convertCollectionSchemaToZod.d.ts.map +1 -0
  71. package/dist/utils/schemaConversion/convertCollectionSchemaToZod.js +34 -0
  72. package/dist/utils/schemaConversion/convertCollectionSchemaToZod.js.map +1 -0
  73. package/dist/utils/schemaConversion/sanitizeJsonSchema.d.ts +8 -0
  74. package/dist/utils/schemaConversion/sanitizeJsonSchema.d.ts.map +1 -0
  75. package/dist/utils/schemaConversion/sanitizeJsonSchema.js +18 -0
  76. package/dist/utils/schemaConversion/sanitizeJsonSchema.js.map +1 -0
  77. package/dist/utils/schemaConversion/simplifyRelationshipFields.d.ts +20 -0
  78. package/dist/utils/schemaConversion/simplifyRelationshipFields.d.ts.map +1 -0
  79. package/dist/utils/schemaConversion/simplifyRelationshipFields.js +53 -0
  80. package/dist/utils/schemaConversion/simplifyRelationshipFields.js.map +1 -0
  81. package/dist/utils/schemaConversion/transformPointFields.d.ts.map +1 -0
  82. package/dist/utils/schemaConversion/transformPointFields.js.map +1 -0
  83. package/package.json +5 -5
  84. package/src/mcp/getMcpHandler.ts +9 -6
  85. package/src/mcp/tools/auth/auth.ts +5 -3
  86. package/src/mcp/tools/auth/forgotPassword.ts +5 -3
  87. package/src/mcp/tools/auth/login.ts +5 -3
  88. package/src/mcp/tools/auth/resetPassword.ts +5 -3
  89. package/src/mcp/tools/auth/unlock.ts +5 -3
  90. package/src/mcp/tools/auth/verify.ts +5 -3
  91. package/src/mcp/tools/collection/create.ts +5 -3
  92. package/src/mcp/tools/collection/delete.ts +5 -3
  93. package/src/mcp/tools/collection/find.ts +5 -3
  94. package/src/mcp/tools/collection/update.ts +5 -3
  95. package/src/mcp/tools/config/find.ts +5 -3
  96. package/src/mcp/tools/config/update.ts +5 -3
  97. package/src/mcp/tools/global/find.ts +5 -3
  98. package/src/mcp/tools/global/update.ts +6 -4
  99. package/src/mcp/tools/job/create.ts +5 -3
  100. package/src/mcp/tools/job/run.ts +5 -3
  101. package/src/mcp/tools/job/update.ts +6 -3
  102. package/src/mcp/tools/resource/create.ts +6 -4
  103. package/src/mcp/tools/resource/delete.ts +5 -3
  104. package/src/mcp/tools/resource/find.ts +5 -3
  105. package/src/mcp/tools/resource/update.ts +6 -4
  106. package/src/types.ts +11 -2
  107. package/src/utils/schemaConversion/convertCollectionSchemaToZod.ts +41 -0
  108. package/src/utils/schemaConversion/sanitizeJsonSchema.ts +21 -0
  109. package/src/utils/schemaConversion/simplifyRelationshipFields.ts +65 -0
  110. package/dist/utils/convertCollectionSchemaToZod.d.ts.map +0 -1
  111. package/dist/utils/convertCollectionSchemaToZod.js +0 -80
  112. package/dist/utils/convertCollectionSchemaToZod.js.map +0 -1
  113. package/dist/utils/transformPointFields.d.ts.map +0 -1
  114. package/dist/utils/transformPointFields.js.map +0 -1
  115. package/src/utils/convertCollectionSchemaToZod.ts +0 -95
  116. /package/dist/utils/{convertCollectionSchemaToZod.d.ts → schemaConversion/convertCollectionSchemaToZod.d.ts} +0 -0
  117. /package/dist/utils/{transformPointFields.d.ts → schemaConversion/transformPointFields.d.ts} +0 -0
  118. /package/dist/utils/{transformPointFields.js → schemaConversion/transformPointFields.js} +0 -0
  119. /package/src/utils/{transformPointFields.ts → schemaConversion/transformPointFields.ts} +0 -0
@@ -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.tool(\n 'createJob',\n 'Creates a new Payload job (task or workflow) with specified configuration',\n toolSchemas.createJob.parameters.shape,\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","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,CAACG,QAAQE,QAAQ,CAACD,kBAAkB;YACtC,IAAIb,aAAa;gBACfM,QAAQI,MAAM,CAACC,IAAI,CAAC,CAAC,6BAA6B,EAAEE,iBAAiB;YACvE;YAEA,kDAAkD;YAClD,MAAME,cAAc;YACpB,IAAIC;YACJ,IAAIC;YACJ,MAAO,AAACA,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7C,SAAS;oBACP;wBACEuC,MAAM;wBACNC,MAAM,CAAC,gCAAgC,EAAEK,cAAc;oBACzD;iBACD;YACH;QACF;IACF;IAEAU,OAAOC,IAAI,CACT,aACA,6EACAvE,YAAYyC,SAAS,CAACiC,UAAU,CAACC,KAAK,EACtC,OAAOC;QACL,OAAOL,KACLK,KAAKvE,OAAO,EACZuE,KAAKtE,OAAO,EACZsE,KAAKrE,OAAO,EACZqE,KAAKlC,WAAW,EAChBkC,KAAKjC,WAAW,EAChBiC,KAAKhC,YAAY,EACjBgC,KAAK/B,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 { 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,SA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AQA,IAAIE,WAAW;AAChD;AAEA,OAAO,MAAMC,gBAAgB,CAC3BC,QACApE,KACAC,aACAC;IAEA,MAAMmE,OAAO,OACXlE,SACAC,SACAC,SACAmC,aACAC,cAAmB,CAAC,CAAC,EACrBC,eAAoB,CAAC,CAAC,EACtBC,UAA+B,CAAC,CAAC;QAEjC,IAAI1C,aAAa;YACfD,IAAIO,OAAO,CAACI,MAAM,CAACC,IAAI,CACrB,CAAC,2CAA2C,EAAET,QAAQ,EAAE,EAAEC,QAAQ,EAAE,EAAEC,SAAS;QAEnF;QAEA,IAAI;YACF,MAAMiE,SAAS,MAAM/B,UACnBvC,KACAC,aACAC,SACAC,SACAC,SACAC,SACAmC,aACAC,aACAC,cACAC;YAGF,IAAI1C,aAAa;gBACfD,IAAIO,OAAO,CAACI,MAAM,CAACC,IAAI,CAAC,CAAC,oDAAoD,CAAC;YAChF;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 +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,GAAG,CAAC,UAClB,MAAM,aACH,MAAM,UACT,MAAM;;;;;EAiIf,CAAA;AAED,eAAO,MAAM,UAAU,WAAY,SAAS,OAAO,cAAc,eAAe,OAAO,SA4CtF,CAAA"}
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,GAAG,CAAC,UAClB,MAAM,aACH,MAAM,UACT,MAAM;;;;;EAiIf,CAAA;AAED,eAAO,MAAM,UAAU,WAAY,SAAS,OAAO,cAAc,eAAe,OAAO,SA8CtF,CAAA"}
@@ -138,7 +138,10 @@ export const runJobTool = (server, req, verboseLogs)=>{
138
138
  };
139
139
  }
140
140
  };
141
- server.tool('runJob', 'Runs a Payload job with specified input data and queue options', toolSchemas.runJob.parameters.shape, async (args)=>{
141
+ server.registerTool('runJob', {
142
+ description: 'Runs a Payload job with specified input data and queue options',
143
+ inputSchema: toolSchemas.runJob.parameters.shape
144
+ }, async (args)=>{
142
145
  const { delay, input, jobSlug, priority, queue } = args;
143
146
  return await tool(jobSlug, input, queue, priority, delay);
144
147
  });
@@ -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, any>,\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 const tool = async (\n jobSlug: string,\n input: Record<string, any>,\n queue?: string,\n priority?: number,\n delay?: number,\n ) => {\n if (verboseLogs) {\n req.payload.logger.info(`[payload-mcp] Run Job Tool called with: ${jobSlug}`)\n }\n\n try {\n const result = await runJob(req, verboseLogs, jobSlug, input, queue, priority, delay)\n\n if (verboseLogs) {\n req.payload.logger.info(`[payload-mcp] Run 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 Run Job Tool: ${errorMessage}`)\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error in Run Job Tool**: ${errorMessage}`,\n },\n ],\n }\n }\n }\n\n server.tool(\n 'runJob',\n 'Runs a Payload job with specified input data and queue options',\n toolSchemas.runJob.parameters.shape,\n async (args) => {\n const { delay, input, jobSlug, priority, queue } = args\n return await tool(jobSlug, input, queue, priority, delay)\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","tool","result","errorMessage","Error","parameters","shape","args"],"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,K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C;gBAC3D;aACD;QACH;IACF;AACF,EAAC;AAED,OAAO,MAAMyB,aAAa,CAACC,QAAmB5B,KAAqBC;IACjE,MAAM4B,OAAO,OACX3B,SACAC,OACAC,OACAC,UACAC;QAEA,IAAIL,aAAa;YACfD,IAAIO,OAAO,CAACC,MAAM,CAACC,IAAI,CAAC,CAAC,wCAAwC,EAAEP,SAAS;QAC9E;QAEA,IAAI;YACF,MAAM4B,SAAS,MAAM/B,OAAOC,KAAKC,aAAaC,SAASC,OAAOC,OAAOC,UAAUC;YAE/E,IAAIL,aAAa;gBACfD,IAAIO,OAAO,CAACC,MAAM,CAACC,IAAI,CAAC,CAAC,iDAAiD,CAAC;YAC7E;YAEA,OAAOqB;QACT,EAAE,OAAON,OAAO;YACd,MAAMO,eAAeP,iBAAiBQ,QAAQR,MAAME,OAAO,GAAG;YAC9D1B,IAAIO,OAAO,CAACC,MAAM,CAACgB,KAAK,CAAC,CAAC,qCAAqC,EAAEO,cAAc;YAE/E,OAAO;gBACLV,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAM,CAAC,6BAA6B,EAAEQ,cAAc;oBACtD;iBACD;YACH;QACF;IACF;IAEAH,OAAOC,IAAI,CACT,UACA,kEACA/B,YAAYC,MAAM,CAACkC,UAAU,CAACC,KAAK,EACnC,OAAOC;QACL,MAAM,EAAE7B,KAAK,EAAEH,KAAK,EAAED,OAAO,EAAEG,QAAQ,EAAED,KAAK,EAAE,GAAG+B;QACnD,OAAO,MAAMN,KAAK3B,SAASC,OAAOC,OAAOC,UAAUC;IACrD;AAEJ,EAAC"}
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, any>,\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 const tool = async (\n jobSlug: string,\n input: Record<string, any>,\n queue?: string,\n priority?: number,\n delay?: number,\n ) => {\n if (verboseLogs) {\n req.payload.logger.info(`[payload-mcp] Run Job Tool called with: ${jobSlug}`)\n }\n\n try {\n const result = await runJob(req, verboseLogs, jobSlug, input, queue, priority, delay)\n\n if (verboseLogs) {\n req.payload.logger.info(`[payload-mcp] Run 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 Run Job Tool: ${errorMessage}`)\n\n return {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error in Run Job Tool**: ${errorMessage}`,\n },\n ],\n }\n }\n }\n\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 (args) => {\n const { delay, input, jobSlug, priority, queue } = args\n return await tool(jobSlug, input, queue, priority, delay)\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","tool","result","errorMessage","Error","registerTool","description","inputSchema","parameters","shape","args"],"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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,MAAM4B,OAAO,OACX3B,SACAC,OACAC,OACAC,UACAC;QAEA,IAAIL,aAAa;YACfD,IAAIO,OAAO,CAACC,MAAM,CAACC,IAAI,CAAC,CAAC,wCAAwC,EAAEP,SAAS;QAC9E;QAEA,IAAI;YACF,MAAM4B,SAAS,MAAM/B,OAAOC,KAAKC,aAAaC,SAASC,OAAOC,OAAOC,UAAUC;YAE/E,IAAIL,aAAa;gBACfD,IAAIO,OAAO,CAACC,MAAM,CAACC,IAAI,CAAC,CAAC,iDAAiD,CAAC;YAC7E;YAEA,OAAOqB;QACT,EAAE,OAAON,OAAO;YACd,MAAMO,eAAeP,iBAAiBQ,QAAQR,MAAME,OAAO,GAAG;YAC9D1B,IAAIO,OAAO,CAACC,MAAM,CAACgB,KAAK,CAAC,CAAC,qCAAqC,EAAEO,cAAc;YAE/E,OAAO;gBACLV,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAM,CAAC,6BAA6B,EAAEQ,cAAc;oBACtD;iBACD;YACH;QACF;IACF;IAEAH,OAAOK,YAAY,CACjB,UACA;QACEC,aAAa;QACbC,aAAarC,YAAYC,MAAM,CAACqC,UAAU,CAACC,KAAK;IAClD,GACA,OAAOC;QACL,MAAM,EAAEhC,KAAK,EAAEH,KAAK,EAAED,OAAO,EAAEG,QAAQ,EAAED,KAAK,EAAE,GAAGkC;QACnD,OAAO,MAAMT,KAAK3B,SAASC,OAAOC,OAAOC,UAAUC;IACrD;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;AAMvF,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;AAuCD,eAAO,MAAM,aAAa,WAChB,SAAS,OACZ,cAAc,eACN,OAAO,WACX,MAAM,SA4EhB,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;AAMvF,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;AAuCD,eAAO,MAAM,aAAa,WAChB,SAAS,OACZ,cAAc,eACN,OAAO,WACX,MAAM,SA+EhB,CAAA"}
@@ -202,7 +202,10 @@ export const updateJobTool = (server, req, verboseLogs, jobsDir)=>{
202
202
  };
203
203
  }
204
204
  };
205
- server.tool('updateJob', 'Updates an existing Payload job with new configuration, schema, or handler code', toolSchemas.updateJob.parameters.shape, async (args)=>{
205
+ server.registerTool('updateJob', {
206
+ description: 'Updates an existing Payload job with new configuration, schema, or handler code',
207
+ inputSchema: toolSchemas.updateJob.parameters.shape
208
+ }, async (args)=>{
206
209
  const { configUpdate, handlerCode, inputSchema, jobSlug, outputSchema, taskSequence, updateType } = args;
207
210
  return await tool(jobSlug, updateType, inputSchema, outputSchema, taskSequence, configUpdate, handlerCode);
208
211
  });
@@ -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.tool(\n 'updateJob',\n 'Updates an existing Payload job with new configuration, schema, or handler code',\n toolSchemas.updateJob.parameters.shape,\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","parameters","shape","args"],"mappings":"AAGA,SAASA,UAAU,EAAEC,YAAY,EAAEC,aAAa,QAAQ,KAAI;AAC5D,SAASC,IAAI,QAAQ,OAAM;AAI3B,SAASC,mBAAmB,QAAQ,kCAAiC;AACrE,SAASC,WAAW,QAAQ,gBAAe;AAE3C,sCAAsC;AACtC,OAAO,MAAMC,YAAY,OACvBC,KACAC,aACAC,SACAC,SACAC,YACAC,aACAC,cACAC,cACAC,cACAC;IAEA,MAAMC,UAAUV,IAAIU,OAAO;IAE3B,IAAIT,aAAa;QACfS,QAAQC,MAAM,CAACC,IAAI,CAAC,CAAC,4BAA4B,EAAET,QAAQ,EAAE,EAAEC,WAAW,CAAC,CAAC;IAC9E;IAEA,IAAI;QACF,MAAMS,mBAAmBC,YAAYX;QAErC,qDAAqD;QACrD,IAAIY,WAA0B;QAC9B,IAAIC,UAAsC;QAE1C,MAAMC,WAAWrB,KAAKM,SAAS,SAAS,GAAGW,iBAAiB,GAAG,CAAC;QAChE,MAAMK,eAAetB,KAAKM,SAAS,aAAa,GAAGW,iBAAiB,GAAG,CAAC;QAExE,IAAIpB,WAAWwB,WAAW;YACxBF,WAAWE;YACXD,UAAU;YACV,IAAIf,aAAa;gBACfS,QAAQC,MAAM,CAACC,IAAI,CAAC,CAAC,+BAA+B,EAAEK,UAAU;YAClE;QACF,OAAO,IAAIxB,WAAWyB,eAAe;YACnCH,WAAWG;YACXF,UAAU;YACV,IAAIf,aAAa;gBACfS,QAAQC,MAAM,CAACC,IAAI,CAAC,CAAC,mCAAmC,EAAEM,cAAc;YAC1E;QACF,OAAO;YACL,MAAM,IAAIC,MAAM,CAAC,6CAA6C,EAAEhB,SAAS;QAC3E;QAEA,gCAAgC;QAChC,IAAIiB,UAAU1B,aAAaqB,UAAU;QACrC,MAAMM,kBAAkBD;QAExB,IAAInB,aAAa;YACfS,QAAQC,MAAM,CAACC,IAAI,CAAC,CAAC,oCAAoC,EAAER,Y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OAAOf,OAAO;YACd,MAAMI,eAAeJ,iBAAiBZ,QAAQY,MAAMK,OAAO,GAAG;YAC9DpC,IAAIU,OAAO,CAACC,MAAM,CAACoB,KAAK,CAAC,CAAC,wCAAwC,EAAEI,cAAc;YAElF,OAAO;gBACLf,SAAS;oBACP;wBACEY,MAAM;wBACNC,MAAM,CAAC,gCAAgC,EAAEE,cAAc;oBACzD;iBACD;YACH;QACF;IACF;IAEAS,OAAOC,IAAI,CACT,aACA,mFACA/C,YAAYC,SAAS,CAACgD,UAAU,CAACC,KAAK,EACtC,OAAOC;QACL,MAAM,EACJzC,YAAY,EACZC,WAAW,EACXJ,WAAW,EACXF,OAAO,EACPG,YAAY,EACZC,YAAY,EACZH,UAAU,EACX,GAAG6C;QACJ,OAAO,MAAMJ,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 { 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,mBAAmB,QAAQ,kCAAiC;AACrE,SAASC,WAAW,QAAQ,gBAAe;AAE3C,sCAAsC;AACtC,OAAO,MAAMC,YAAY,OACvBC,KACAC,aACAC,SACAC,SACAC,YACAC,aACAC,cACAC,cACAC,cACAC;IAEA,MAAMC,UAAUV,IAAIU,OAAO;IAE3B,IAAIT,aAAa;QACfS,QAAQC,MAAM,CAACC,IAAI,CAAC,CAAC,4BAA4B,EAAET,QAAQ,EAAE,EAAEC,WAAW,CAAC,CAAC;IAC9E;IAEA,IAAI;QACF,MAAMS,mBAAmBC,YAAYX;QAErC,qDAAqD;QACrD,IAAIY,WAA0B;QAC9B,IAAIC,UAAsC;QAE1C,MAAMC,WAAWrB,KAAKM,SAAS,SAAS,GA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Root":"","sources":["../../../../src/mcp/tools/resource/create.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAc,SAAS,EAAE,MAAM,SAAS,CAAA;AAIpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAM9D,eAAO,MAAM,kBAAkB,WACrB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,UACzC,WAAW,SAsLpB,CAAA"}
1
+ {"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/resource/create.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAc,SAAS,EAAE,MAAM,SAAS,CAAA;AAIpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAM9D,eAAO,MAAM,kBAAkB,WACrB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,UACzC,WAAW,SAwLpB,CAAA"}
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { toCamelCase } from '../../../utils/camelCase.js';
3
- import { convertCollectionSchemaToZod } from '../../../utils/convertCollectionSchemaToZod.js';
3
+ import { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js';
4
4
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
5
5
  import { toolSchemas } from '../schemas.js';
6
6
  export const createResourceTool = (server, req, user, verboseLogs, collectionSlug, collections, schema)=>{
@@ -107,7 +107,10 @@ ${JSON.stringify(result, null, 2)}
107
107
  locale: z.string().optional().describe('Optional: locale code to create the document in (e.g., "en", "es"). Defaults to the default locale'),
108
108
  select: z.string().optional().describe('Optional: define exactly which fields you\'d like to create (JSON), e.g., \'{"title": "My Post"}\'')
109
109
  });
110
- server.tool(`create${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`, `${collections?.[collectionSlug]?.description || toolSchemas.createResource.description.trim()}`, createResourceSchema.shape, async (params)=>{
110
+ server.registerTool(`create${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`, {
111
+ description: `${collections?.[collectionSlug]?.description || toolSchemas.createResource.description.trim()}`,
112
+ inputSchema: createResourceSchema.shape
113
+ }, async (params)=>{
111
114
  const { depth, draft, fallbackLocale, locale, select, ...fieldData } = params;
112
115
  const data = JSON.stringify(fieldData);
113
116
  return await tool(data, depth, draft, locale, fallbackLocale, select);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/tools/resource/create.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { JSONSchema4 } from 'json-schema'\nimport type { PayloadRequest, SelectType, TypedUser } from 'payload'\n\nimport { z } from 'zod'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { convertCollectionSchemaToZod } from '../../../utils/convertCollectionSchemaToZod.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { toolSchemas } from '../schemas.js'\nexport const createResourceTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n collectionSlug: string,\n collections: PluginMCPServerConfig['collections'],\n schema: JSONSchema4,\n) => {\n const tool = async (\n data: string,\n depth: number = 0,\n draft: boolean,\n locale?: string,\n fallbackLocale?: string,\n select?: string,\n ): Promise<{\n content: Array<{\n text: string\n type: 'text'\n }>\n }> => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Creating resource in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Parse the data JSON\n let parsedData: Record<string, unknown>\n try {\n parsedData = JSON.parse(data)\n\n // Transform point fields from object format to tuple array\n parsedData = transformPointDataToPayload(parsedData)\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`,\n )\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid JSON data provided: ${data}`)\n return {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON data provided' }],\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid select clause JSON: ${select}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in select clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Create the resource\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: false,\n req,\n user,\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(selectClause && { select: selectClause }),\n })\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Successfully created resource in ${collectionSlug} with ID: ${result.id}`,\n )\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Resource created successfully in collection \"${collectionSlug}\"!\nCreated resource:\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, result, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n payload.logger.error(\n `[payload-mcp] Error creating resource in ${collectionSlug}: ${errorMessage}`,\n )\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error creating resource in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n if (collections?.[collectionSlug]?.enabled) {\n const convertedFields = convertCollectionSchemaToZod(schema)\n\n // Create a new schema that combines the converted fields with create-specific parameters\n const createResourceSchema = z.object({\n ...convertedFields.shape,\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .optional()\n .default(0)\n .describe('How many levels deep to populate relationships in response'),\n draft: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to create the document as a draft'),\n fallbackLocale: z\n .string()\n .optional()\n .describe('Optional: fallback locale code to use when requested locale is not available'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Optional: locale code to create the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n ),\n select: z\n .string()\n .optional()\n .describe(\n 'Optional: define exactly which fields you\\'d like to create (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n ),\n })\n\n server.tool(\n `create${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n `${collections?.[collectionSlug]?.description || toolSchemas.createResource.description.trim()}`,\n createResourceSchema.shape,\n async (params: Record<string, unknown>) => {\n const { depth, draft, fallbackLocale, locale, select, ...fieldData } = params\n const data = JSON.stringify(fieldData)\n return await tool(\n data,\n depth as number,\n draft as boolean,\n locale as string | undefined,\n fallbackLocale as string | undefined,\n select as string | undefined,\n )\n },\n )\n }\n}\n"],"names":["z","toCamelCase","convertCollectionSchemaToZod","transformPointDataToPayload","toolSchemas","createResourceTool","server","req","user","verboseLogs","collectionSlug","collections","schema","tool","data","depth","draft","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","stringify","_parseError","error","content","type","text","selectClause","warn","response","overrideResponse","result","create","collection","overrideAccess","id","errorMessage","Error","message","enabled","convertedFields","createResourceSchema","object","shape","number","int","min","max","optional","default","describe","boolean","string","charAt","toUpperCase","slice","description","createResource","trim","params","fieldData"],"mappings":"AAIA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,4BAA4B,QAAQ,iDAAgD;AAC7F,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,WAAW,QAAQ,gBAAe;AAC3C,OAAO,MAAMC,qBAAqB,CAChCC,QACAC,KACAC,MACAC,aACAC,gBACAC,aACAC;IAEA,MAAMC,OAAO,OACXC,MACAC,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,IAAId,aAAa;oBACfW,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,8BAA8B,EAAEZ,eAAe,EAAE,EAAEc,KAAKE,SAAS,CAACH,aAAa;gBAEpF;YACF,EAAE,OAAOI,aAAa;gBACpBP,QAAQC,MAAM,CAACO,KAAK,CAAC,CAAC,0CAA0C,EAAEd,MAAM;gBACxE,OAAO;oBACLe,SAAS;wBAAC;4BAAEC,MAAM;4BAAiBC,MAAM;wBAAoC;qBAAE;gBACjF;YACF;YAEA,IAAIC;YACJ,IAAIb,QAAQ;gBACV,IAAI;oBACFa,eAAeR,KAAKC,KAAK,CAACN;gBAC5B,EAAE,OAAOQ,aAAa;oBACpBP,QAAQC,MAAM,CAACY,IAAI,CAAC,CAAC,0CAA0C,EAAEd,QAAQ;oBACzE,MAAMe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;IACF;IAEA,IAAIvB,aAAa,CAACD,eAAe,EAAEkC,SAAS;QAC1C,MAAMC,kBAAkB3C,6BAA6BU;QAErD,yFAAyF;QACzF,MAAMkC,uBAAuB9C,EAAE+C,MAAM,CAAC;YACpC,GAAGF,gBAAgBG,KAAK;YACxBjC,OAAOf,EACJiD,MAAM,GACNC,GAAG,GACHC,GAAG,CAAC,GACJC,GAAG,CAAC,IACJC,QAAQ,GACRC,OAAO,CAAC,GACRC,QAAQ,CAAC;YACZvC,OAAOhB,EACJwD,OAAO,GACPH,QAAQ,GACRC,OAAO,CAAC,OACRC,QAAQ,CAAC;YACZrC,gBAAgBlB,EACbyD,MAAM,GACNJ,QAAQ,GACRE,QAAQ,CAAC;YACZtC,QAAQjB,EACLyD,MAAM,GACNJ,QAAQ,GACRE,QAAQ,CACP;YAEJpC,QAAQnB,EACLyD,MAAM,GACNJ,QAAQ,GACRE,QAAQ,CACP;QAEN;QAEAjD,OAAOO,IAAI,CACT,CAAC,MAAM,EAAEH,eAAegD,MAAM,CAAC,GAAGC,WAAW,KAAK1D,YAAYS,gBAAgBkD,KAAK,CAAC,IAAI,EACxF,GAAGjD,aAAa,CAACD,eAAe,EAAEmD,eAAezD,YAAY0D,cAAc,CAACD,WAAW,CAACE,IAAI,IAAI,EAChGjB,qBAAqBE,KAAK,EAC1B,OAAOgB;YACL,MAAM,EAAEjD,KAAK,EAAEC,KAAK,EAAEE,cAAc,EAAED,MAAM,EAAEE,MAAM,EAAE,GAAG8C,WAAW,GAAGD;YACvE,MAAMlD,OAAOU,KAAKE,SAAS,CAACuC;YAC5B,OAAO,MAAMpD,KACXC,MACAC,OACAC,OACAC,QACAC,gBACAC;QAEJ;IAEJ;AACF,EAAC"}
1
+ {"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;QAEhH;QAEA,IAAI;YACF,sBAAsB;YACtB,IAAIM;YACJ,IAAI;gBACFA,aAAaC,KAAKC,KAAK,CAACX;gBAExB,2DAA2D;gBAC3DS,aAAapB,4BAA4BoB;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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 +1 @@
1
- {"version":3,"file":"delete.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/resource/delete.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AAExD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAK9D,eAAO,MAAM,kBAAkB,WACrB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,SAyMlD,CAAA"}
1
+ {"version":3,"file":"delete.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/resource/delete.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AAExD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAK9D,eAAO,MAAM,kBAAkB,WACrB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,SA2MlD,CAAA"}
@@ -139,7 +139,10 @@ ${JSON.stringify(errors, null, 2)}
139
139
  }
140
140
  };
141
141
  if (collections?.[collectionSlug]?.enabled) {
142
- server.tool(`delete${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`, `${collections?.[collectionSlug]?.description || toolSchemas.deleteResource.description.trim()}`, toolSchemas.deleteResource.parameters.shape, async ({ id, depth, fallbackLocale, locale, where })=>{
142
+ server.registerTool(`delete${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`, {
143
+ description: `${collections?.[collectionSlug]?.description || toolSchemas.deleteResource.description.trim()}`,
144
+ inputSchema: toolSchemas.deleteResource.parameters.shape
145
+ }, async ({ id, depth, fallbackLocale, locale, where })=>{
143
146
  return await tool(id, where, depth, locale, fallbackLocale);
144
147
  });
145
148
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/tools/resource/delete.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { PayloadRequest, TypedUser } from 'payload'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { toolSchemas } from '../schemas.js'\n\nexport const deleteResourceTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n collectionSlug: string,\n collections: PluginMCPServerConfig['collections'],\n) => {\n const tool = async (\n id?: number | string,\n where?: string,\n depth: number = 0,\n locale?: string,\n fallbackLocale?: 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] Deleting resource from collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}${locale ? `, locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Validate that either id or where is provided\n if (!id && !where) {\n payload.logger.error('[payload-mcp] Either id or where clause must be provided')\n const response = {\n content: [\n { type: 'text' as const, text: 'Error: Either id or where clause must be provided' },\n ],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n\n // Parse where clause if provided\n let whereClause = {}\n if (where) {\n try {\n whereClause = JSON.parse(where)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Using where clause: ${where}`)\n }\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid where clause JSON: ${where}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in where clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Build delete options\n const deleteOptions: Record<string, unknown> = {\n collection: collectionSlug,\n depth,\n overrideAccess: false,\n req,\n user,\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n }\n\n // Delete by ID or where clause\n if (id) {\n deleteOptions.id = id\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Deleting single document with ID: ${id}`)\n }\n } else {\n deleteOptions.where = whereClause\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Deleting multiple documents with where clause`)\n }\n }\n\n const result = await payload.delete(deleteOptions as Parameters<typeof payload.delete>[0])\n\n // Handle different result types\n if (id) {\n // Single document deletion\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully deleted document with ID: ${id}`)\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Document deleted successfully from collection \"${collectionSlug}\"!\nDeleted document:\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, result, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } else {\n // Multiple documents deletion\n const bulkResult = result as { docs?: unknown[]; errors?: unknown[] }\n const docs = bulkResult.docs || []\n const errors = bulkResult.errors || []\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Successfully deleted ${docs.length} documents, ${errors.length} errors`,\n )\n }\n\n let responseText = `Document deleted successfully from collection \"${collectionSlug}\"!\nDeleted: ${docs.length} documents\nErrors: ${errors.length}\n---`\n\n if (docs.length > 0) {\n responseText += `\\n\\nDeleted documents:\n\\`\\`\\`json\n${JSON.stringify(docs, null, 2)}\n\\`\\`\\``\n }\n\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\n\\`\\`\\`json\n${JSON.stringify(errors, null, 2)}\n\\`\\`\\``\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: responseText,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(\n response,\n { docs, errors },\n req,\n ) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n payload.logger.error(\n `[payload-mcp] Error deleting resource from ${collectionSlug}: ${errorMessage}`,\n )\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error deleting resource from 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 server.tool(\n `delete${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n `${collections?.[collectionSlug]?.description || toolSchemas.deleteResource.description.trim()}`,\n toolSchemas.deleteResource.parameters.shape,\n async ({ id, depth, fallbackLocale, locale, where }) => {\n return await tool(id, where, depth, locale, fallbackLocale)\n },\n )\n }\n}\n"],"names":["toCamelCase","toolSchemas","deleteResourceTool","server","req","user","verboseLogs","collectionSlug","collections","tool","id","where","depth","locale","fallbackLocale","payload","logger","info","error","response","content","type","text","overrideResponse","whereClause","JSON","parse","_parseError","warn","deleteOptions","collection","overrideAccess","result","delete","stringify","bulkResult","docs","errors","length","responseText","errorMessage","Error","message","enabled","charAt","toUpperCase","slice","description","deleteResource","trim","par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cAAc,CAACE,UAAU,CAACC,KAAK,EAC3C,OAAO,EAAEzC,EAAE,EAAEE,KAAK,EAAEE,cAAc,EAAED,MAAM,EAAEF,KAAK,EAAE;YACjD,OAAO,MAAMF,KAAKC,IAAIC,OAAOC,OAAOC,QAAQC;QAC9C;IAEJ;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../src/mcp/tools/resource/delete.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { PayloadRequest, TypedUser } from 'payload'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { toolSchemas } from '../schemas.js'\n\nexport const deleteResourceTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n collectionSlug: string,\n collections: PluginMCPServerConfig['collections'],\n) => {\n const tool = async (\n id?: number | string,\n where?: string,\n depth: number = 0,\n locale?: string,\n fallbackLocale?: 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] Deleting resource from collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}${locale ? `, locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Validate that either id or where is provided\n if (!id && !where) {\n payload.logger.error('[payload-mcp] Either id or where clause must be provided')\n const response = {\n content: [\n { type: 'text' as const, text: 'Error: Either id or where clause must be provided' },\n ],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n\n // Parse where clause if provided\n let whereClause = {}\n if (where) {\n try {\n whereClause = JSON.parse(where)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Using where clause: ${where}`)\n }\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid where clause JSON: ${where}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in where clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Build delete options\n const deleteOptions: Record<string, unknown> = {\n collection: collectionSlug,\n depth,\n overrideAccess: false,\n req,\n user,\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n }\n\n // Delete by ID or where clause\n if (id) {\n deleteOptions.id = id\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Deleting single document with ID: ${id}`)\n }\n } else {\n deleteOptions.where = whereClause\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Deleting multiple documents with where clause`)\n }\n }\n\n const result = await payload.delete(deleteOptions as Parameters<typeof payload.delete>[0])\n\n // Handle different result types\n if (id) {\n // Single document deletion\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully deleted document with ID: ${id}`)\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Document deleted successfully from collection \"${collectionSlug}\"!\nDeleted document:\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, result, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } else {\n // Multiple documents deletion\n const bulkResult = result as { docs?: unknown[]; errors?: unknown[] }\n const docs = bulkResult.docs || []\n const errors = bulkResult.errors || []\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Successfully deleted ${docs.length} documents, ${errors.length} errors`,\n )\n }\n\n let responseText = `Document deleted successfully from collection \"${collectionSlug}\"!\nDeleted: ${docs.length} documents\nErrors: ${errors.length}\n---`\n\n if (docs.length > 0) {\n responseText += `\\n\\nDeleted documents:\n\\`\\`\\`json\n${JSON.stringify(docs, null, 2)}\n\\`\\`\\``\n }\n\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\n\\`\\`\\`json\n${JSON.stringify(errors, null, 2)}\n\\`\\`\\``\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: responseText,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(\n response,\n { docs, errors },\n req,\n ) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n payload.logger.error(\n `[payload-mcp] Error deleting resource from ${collectionSlug}: ${errorMessage}`,\n )\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error deleting resource from 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 server.registerTool(\n `delete${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n {\n description: `${collections?.[collectionSlug]?.description || toolSchemas.deleteResource.description.trim()}`,\n inputSchema: toolSchemas.deleteResource.parameters.shape,\n },\n async ({ id, depth, fallbackLocale, locale, where }) => {\n return await tool(id, where, depth, locale, fallbackLocale)\n },\n )\n }\n}\n"],"names":["toCamelCase","toolSchemas","deleteResourceTool","server","req","user","verboseLogs","collectionSlug","collections","tool","id","where","depth","locale","fallbackLocale","payload","logger","info","error","response","content","type","text","overrideResponse","whereClause","JSON","parse","_parseError","warn","deleteOptions","collection","overrideAccess","result","delete","stringify","bulkResult","docs","errors","length","responseText","errorMessage","Error","message","enabled","registerTool","charAt","toUpperCase","slice","description","deleteResource","trim","inputSchema","parameters","shape"],"mappings":"AAKA,SAASA,WAAW,QAAQ,8BAA6B;AACzD,SAASC,WAAW,QAAQ,gBAAe;AAE3C,OAAO,MAAMC,qBAAqB,CAChCC,QACAC,KACAC,MACAC,aACAC,gBACAC;IAEA,MAAMC,OAAO,OACXC,IACAC,OACAC,QAAgB,CAAC,EACjBC,QACAC;QAOA,MAAMC,UAAUX,IAAIW,OAAO;QA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"file":"find.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/resource/find.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,cAAc,EAAc,SAAS,EAAE,MAAM,SAAS,CAAA;AAEpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAK9D,eAAO,MAAM,gBAAgB,WACnB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,SAqOlD,CAAA"}
1
+ {"version":3,"file":"find.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/resource/find.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,cAAc,EAAc,SAAS,EAAE,MAAM,SAAS,CAAA;AAEpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAK9D,eAAO,MAAM,gBAAgB,WACnB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,SAuOlD,CAAA"}
@@ -158,7 +158,10 @@ Page: ${result.page} of ${result.totalPages}
158
158
  }
159
159
  };
160
160
  if (collections?.[collectionSlug]?.enabled) {
161
- server.tool(`find${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`, `${collections?.[collectionSlug]?.description || toolSchemas.findResources.description.trim()}`, toolSchemas.findResources.parameters.shape, async ({ id, depth, draft, fallbackLocale, limit, locale, page, select, sort, where })=>{
161
+ server.registerTool(`find${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`, {
162
+ description: `${collections?.[collectionSlug]?.description || toolSchemas.findResources.description.trim()}`,
163
+ inputSchema: toolSchemas.findResources.parameters.shape
164
+ }, async ({ id, depth, draft, fallbackLocale, limit, locale, page, select, sort, where })=>{
162
165
  return await tool(id, limit, page, sort, where, select, depth, locale, fallbackLocale, draft);
163
166
  });
164
167
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/tools/resource/find.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { PayloadRequest, SelectType, TypedUser } from 'payload'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { toolSchemas } from '../schemas.js'\n\nexport const findResourceTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n collectionSlug: string,\n collections: PluginMCPServerConfig['collections'],\n) => {\n const tool = async (\n id?: number | string,\n limit: number = 10,\n page: number = 1,\n sort?: string,\n where?: string,\n select?: string,\n depth: number = 0,\n locale?: string,\n fallbackLocale?: string,\n draft?: boolean,\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] Reading resource from collection: ${collectionSlug}${id ? ` with ID: ${id}` : ''}, limit: ${limit}, page: ${page}${locale ? `, locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Parse where clause if provided\n let whereClause = {}\n if (where) {\n try {\n whereClause = JSON.parse(where)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Using where clause: ${where}`)\n }\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid where clause JSON: ${where}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in where clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Parse select clause if provided\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 // If ID is provided, use findByID\n if (id) {\n try {\n const doc = await payload.findByID({\n id,\n collection: collectionSlug,\n depth,\n ...(selectClause && { select: selectClause }),\n overrideAccess: false,\n req,\n user,\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(draft !== undefined && { draft }),\n })\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Found document with ID: ${id}`)\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Resource from collection \"${collectionSlug}\":\n${JSON.stringify(doc, null, 2)}`,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, doc, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } catch (_findError) {\n payload.logger.warn(\n `[payload-mcp] Document not found with ID: ${id} in collection: ${collectionSlug}`,\n )\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error: Document with ID \"${id}\" not found in collection \"${collectionSlug}\"`,\n },\n ],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Otherwise, use find to get multiple documents\n const findOptions: Parameters<typeof payload.find>[0] = {\n collection: collectionSlug,\n depth,\n limit,\n overrideAccess: false,\n page,\n req,\n user,\n ...(selectClause && { select: selectClause }),\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(draft !== undefined && { draft }),\n }\n\n if (sort) {\n findOptions.sort = sort\n }\n\n if (Object.keys(whereClause).length > 0) {\n findOptions.where = whereClause\n }\n\n const result = await payload.find(findOptions)\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Found ${result.docs.length} documents in collection: ${collectionSlug}`,\n )\n }\n\n let responseText = `Collection: \"${collectionSlug}\"\nTotal: ${result.totalDocs} documents\nPage: ${result.page} of ${result.totalPages}\n`\n\n for (const doc of result.docs) {\n responseText += `\\n\\`\\`\\`json\\n${JSON.stringify(doc, null, 2)}\\n\\`\\`\\``\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: responseText,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(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 reading resources from collection ${collectionSlug}: ${errorMessage}`,\n )\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error reading resources from collection \"${collectionSlug}\":** ${errorMessage}`,\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 server.tool(\n `find${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n `${collections?.[collectionSlug]?.description || toolSchemas.findResources.description.trim()}`,\n toolSchemas.findResources.parameters.shape,\n async ({ id, depth, draft, fallbackLocale, limit, locale, page, select, sort, where }) => {\n return await tool(\n id,\n limit,\n page,\n sort,\n where,\n select,\n depth,\n locale,\n fallbackLocale,\n draft,\n )\n },\n )\n }\n}\n"],"names":["toCamelCase","toolSchemas","findResourceTool","server","req","user","verboseLogs","collectionSlug","collections","tool","id","limit","page","sort","where","select","depth","locale","fallbackLocale","draft","payload","logger","info","whereClause","JSON","parse","_parseError","warn","response","content","type","text","overrideResponse","selectClause","doc","findByID","collection","overrideAccess","undefined","stringify","_findError","findOptions","Object","keys","length","result","find","docs","responseText","totalDocs","totalPages","error","errorMessage","Error","message","enabled","charAt","toUpperCase","slice","description","findResources","trim","parameters","shape"],"mappings":"AAKA,SAASA,WAAW,QAAQ,8BAA6B;A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EAAE6C,cAAc;YAE5F,MAAMxB,WAAW;gBACfC,SAAS;oBACP;wBACEC,MAAM;wBACNC,MAAM,CAAC,6CAA6C,EAAExB,eAAe,KAAK,EAAE6C,cAAc;oBAC5F;iBACD;YACH;YACA,OAAQ5C,aAAa,CAACD,eAAe,EAAEyB,mBAAmBJ,UAAU,CAAC,GAAGxB,QAAQwB;QAMlF;IACF;IAEA,IAAIpB,aAAa,CAACD,eAAe,EAAEgD,SAAS;QAC1CpD,OAAOM,IAAI,CACT,CAAC,IAAI,EAAEF,eAAeiD,MAAM,CAAC,GAAGC,WAAW,KAAKzD,YAAYO,gBAAgBmD,KAAK,CAAC,IAAI,EACtF,GAAGlD,aAAa,CAACD,eAAe,EAAEoD,eAAe1D,YAAY2D,aAAa,CAACD,WAAW,CAACE,IAAI,IAAI,EAC/F5D,YAAY2D,aAAa,CAACE,UAAU,CAACC,KAAK,EAC1C,OAAO,EAAErD,EAAE,EAAEM,KAAK,EAAEG,KAAK,EAAED,cAAc,EAAEP,KAAK,EAAEM,MAAM,EAAEL,IAAI,EAAEG,MAAM,EAAEF,IAAI,EAAEC,KAAK,EAAE;YACnF,OAAO,MAAML,KACXC,IACAC,OACAC,MACAC,MACAC,OACAC,QACAC,OACAC,QACAC,gBACAC;QAEJ;IAEJ;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../src/mcp/tools/resource/find.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { PayloadRequest, SelectType, TypedUser } from 'payload'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { toolSchemas } from '../schemas.js'\n\nexport const findResourceTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n collectionSlug: string,\n collections: PluginMCPServerConfig['collections'],\n) => {\n const tool = async (\n id?: number | string,\n limit: number = 10,\n page: number = 1,\n sort?: string,\n where?: string,\n select?: string,\n depth: number = 0,\n locale?: string,\n fallbackLocale?: string,\n draft?: boolean,\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] Reading resource from collection: ${collectionSlug}${id ? ` with ID: ${id}` : ''}, limit: ${limit}, page: ${page}${locale ? `, locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Parse where clause if provided\n let whereClause = {}\n if (where) {\n try {\n whereClause = JSON.parse(where)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Using where clause: ${where}`)\n }\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid where clause JSON: ${where}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in where clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Parse select clause if provided\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 // If ID is provided, use findByID\n if (id) {\n try {\n const doc = await payload.findByID({\n id,\n collection: collectionSlug,\n depth,\n ...(selectClause && { select: selectClause }),\n overrideAccess: false,\n req,\n user,\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(draft !== undefined && { draft }),\n })\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Found document with ID: ${id}`)\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Resource from collection \"${collectionSlug}\":\n${JSON.stringify(doc, null, 2)}`,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, doc, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } catch (_findError) {\n payload.logger.warn(\n `[payload-mcp] Document not found with ID: ${id} in collection: ${collectionSlug}`,\n )\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error: Document with ID \"${id}\" not found in collection \"${collectionSlug}\"`,\n },\n ],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Otherwise, use find to get multiple documents\n const findOptions: Parameters<typeof payload.find>[0] = {\n collection: collectionSlug,\n depth,\n limit,\n overrideAccess: false,\n page,\n req,\n user,\n ...(selectClause && { select: selectClause }),\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(draft !== undefined && { draft }),\n }\n\n if (sort) {\n findOptions.sort = sort\n }\n\n if (Object.keys(whereClause).length > 0) {\n findOptions.where = whereClause\n }\n\n const result = await payload.find(findOptions)\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Found ${result.docs.length} documents in collection: ${collectionSlug}`,\n )\n }\n\n let responseText = `Collection: \"${collectionSlug}\"\nTotal: ${result.totalDocs} documents\nPage: ${result.page} of ${result.totalPages}\n`\n\n for (const doc of result.docs) {\n responseText += `\\n\\`\\`\\`json\\n${JSON.stringify(doc, null, 2)}\\n\\`\\`\\``\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: responseText,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(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 reading resources from collection ${collectionSlug}: ${errorMessage}`,\n )\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `❌ **Error reading resources from collection \"${collectionSlug}\":** ${errorMessage}`,\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 server.registerTool(\n `find${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n {\n description: `${collections?.[collectionSlug]?.description || toolSchemas.findResources.description.trim()}`,\n inputSchema: toolSchemas.findResources.parameters.shape,\n },\n async ({ id, depth, draft, fallbackLocale, limit, locale, page, select, sort, where }) => {\n return await tool(\n id,\n limit,\n page,\n sort,\n where,\n select,\n depth,\n locale,\n fallbackLocale,\n draft,\n )\n },\n )\n }\n}\n"],"names":["toCamelCase","toolSchemas","findResourceTool","server","req","user","verboseLogs","collectionSlug","collections","tool","id","limit","page","sort","where","select","depth","locale","fallbackLocale","draft","payload","logger","info","whereClause","JSON","parse","_parseError","warn","response","content","type","text","overrideResponse","selectClause","doc","findByID","collection","overrideAccess","undefined","stringify","_findError","findOptions","Object","keys","length","result","find","docs","responseText","totalDocs","totalPages","error","errorMessage","Error","message","enabled","registerTool","charAt","toUpperCase","slice","description","findResources","trim","inputSchema","parameters","shape"],"mappings":"AAKA,SAASA,WAAW,QAAQ,8BAA6B;AACzD,SAASC,WAAW,QAAQ,gBAAe;AAE3C,OAAO,MAAMC,mBAAmB,CAC9BC,QACAC,KACAC,MACAC,aACAC,gBACAC;IAEA,MAAMC,OAAO,OACXC,IACAC,QAAgB,EAAE,EAClBC,OAAe,CAAC,EAChBC,MACAC,OACAC,QACAC,QAAgB,CAAC,EACjBC,QACAC,gBACAC;QAOA,MAAMC,UAAUhB,IAAIgB,OAAO;QAE3B,IAAId,aAAa;YACfc,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,gDAAgD,EAAEf,iBAAiBG,KAAK,CAAC,UAAU,EAAEA,IAAI,GAAG,GAAG,SAAS,EAAEC,MAAM,QAAQ,EAAEC,OAAOK,SAAS,CAAC,UAAU,EAAEA,QAAQ,GAAG,IAAI;QAE3K;QAEA,IAAI;YACF,iC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W,CAACE,IAAI,IAAI;YAC5GC,aAAa9D,YAAY4D,aAAa,CAACG,UAAU,CAACC,KAAK;QACzD,GACA,OAAO,EAAEvD,EAAE,EAAEM,KAAK,EAAEG,KAAK,EAAED,cAAc,EAAEP,KAAK,EAAEM,MAAM,EAAEL,IAAI,EAAEG,MAAM,EAAEF,IAAI,EAAEC,KAAK,EAAE;YACnF,OAAO,MAAML,KACXC,IACAC,OACAC,MACAC,MACAC,OACAC,QACAC,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;AAM9D,eAAO,MAAM,kBAAkB,WACrB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,UACzC,WAAW,SAkWpB,CAAA"}
1
+ {"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/resource/update.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAc,SAAS,EAAE,MAAM,SAAS,CAAA;AAIpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAM9D,eAAO,MAAM,kBAAkB,WACrB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,UACzC,WAAW,SAoWpB,CAAA"}
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { toCamelCase } from '../../../utils/camelCase.js';
3
- import { convertCollectionSchemaToZod } from '../../../utils/convertCollectionSchemaToZod.js';
3
+ import { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js';
4
4
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
5
5
  import { toolSchemas } from '../schemas.js';
6
6
  export const updateResourceTool = (server, req, user, verboseLogs, collectionSlug, collections, schema)=>{
@@ -238,7 +238,10 @@ ${JSON.stringify(errors, null, 2)}
238
238
  select: z.string().optional().describe('Optional: define exactly which fields you\'d like to return in the response (JSON), e.g., \'{"title": "My Post"}\''),
239
239
  where: z.string().optional().describe('JSON string for where clause to update multiple documents')
240
240
  });
241
- server.tool(`update${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`, `${collections?.[collectionSlug]?.description || toolSchemas.updateResource.description.trim()}`, updateResourceSchema.shape, async (params)=>{
241
+ server.registerTool(`update${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`, {
242
+ description: `${collections?.[collectionSlug]?.description || toolSchemas.updateResource.description.trim()}`,
243
+ inputSchema: updateResourceSchema.shape
244
+ }, async (params)=>{
242
245
  const { id, depth, draft, fallbackLocale, filePath, locale, overrideLock, overwriteExistingFiles, select, where, ...fieldData } = params;
243
246
  // Convert field data back to JSON string format expected by the tool
244
247
  const data = JSON.stringify(fieldData);